From 75f16e724410274ff5872fb385c0725fa96287fa Mon Sep 17 00:00:00 2001 From: Matas Ubarevicius Date: Tue, 26 Nov 2024 21:18:20 +0200 Subject: [PATCH] update --- runner/bitbybit-runner.js | 2 +- workers/167.bitbybit-manifold-webworker.js | 1 - workers/167.bitbybit-occt-webworker.js | 1 - workers/903.bitbybit-occt-webworker.js | 1 - workers/bitbybit-manifold-webworker.js | 2 +- 5 files changed, 2 insertions(+), 5 deletions(-) delete mode 100644 workers/167.bitbybit-manifold-webworker.js delete mode 100644 workers/167.bitbybit-occt-webworker.js delete mode 100644 workers/903.bitbybit-occt-webworker.js diff --git a/runner/bitbybit-runner.js b/runner/bitbybit-runner.js index 098c31b..003582b 100644 --- a/runner/bitbybit-runner.js +++ b/runner/bitbybit-runner.js @@ -1 +1 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.bitbybitRunner=t():e.bitbybitRunner=t()}(this,(()=>(()=>{var e={96772:(e,t,i)=>{"use strict";i.d(t,{G:()=>r});class r{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1,this.disposeWhenUnowned=!0}static get HasTriggers(){for(const e in r.Triggers)if(Object.prototype.hasOwnProperty.call(r.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in r.Triggers)if(Object.prototype.hasOwnProperty.call(r.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in r.Triggers)if(Object.prototype.hasOwnProperty.call(r.Triggers,t)&&parseInt(t)===e)return!0;return!1}}r.Triggers={}},89357:(e,t,i)=>{"use strict";i.d(t,{X:()=>r});class r{constructor(e,t,i,r,s,n){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=r,this.sourceEvent=s,this.additionalData=n}static CreateNew(e,t,i){const s=e.getScene();return new r(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new r(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new r(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new r(e,t.x,t.y,null,i,s)}}},66418:(e,t,i)=>{"use strict";i.d(t,{SM:()=>f,rT:()=>h,BT:()=>d});var r=i(87665),s=i(43279),n=i(34493),o=i(54065),a=i(64736),l=i(94212);class h{get syncRoot(){return this._syncRoot}get masterFrame(){return 0===this._runtimeAnimations.length?0:this._runtimeAnimations[0].currentFrame}get weight(){return this._weight}set weight(e){this._weight=-1!==e?Math.min(Math.max(e,0),1):-1}get speedRatio(){return this._speedRatio}set speedRatio(e){for(let t=0;t-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(s)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i-1){const n=this._runtimeAnimations;for(let i=n.length-1;i>=0;i--){const r=n[i];e&&r.animation.name!=e||t&&!t(r.target)||(r.dispose(),n.splice(i,1))}0==n.length&&(i||this._scene._activeAnimatables.splice(s,1),r||this._raiseOnAnimationEnd())}}else{const e=this._scene._activeAnimatables.indexOf(this);if(e>-1){i||this._scene._activeAnimatables.splice(e,1);const t=this._runtimeAnimations;for(let e=0;e{this.onAnimationEndObservable.add((()=>{e(this)}),void 0,void 0,this,!0)}))}_animate(e){if(this._paused)return this.animationStarted=!1,null===this._pausedDelay&&(this._pausedDelay=e),!0;if(null===this._localDelayOffset?(this._localDelayOffset=e,this._pausedDelay=null):null!==this._pausedDelay&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),null!==this._manualJumpDelay&&(this._localDelayOffset+=this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,0===this._weight)return!0;let t=!1;const i=this._runtimeAnimations;let r;for(r=0;r0?h:-h,s),a.scaleAndAddToRef(h,i)}s.normalize()}for(let t=0;t0)s.copyFrom(r);else if(1===e.animations.length){if(l.PT.SlerpToRef(r,i.currentValue,Math.min(1,e.totalWeight),s),0===e.totalAdditiveWeight)return s}else if(e.animations.length>1){let i,n,o=1;if(e.totalWeight<1){const t=1-e.totalWeight;i=[],n=[],i.push(r),n.push(t)}else{if(2===e.animations.length&&(l.PT.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],n=[],o=e.totalWeight}for(let t=0;t=a&&g.frame<=l&&(r?(x=g.value.clone(),f?(v=x.getTranslation(),x.setTranslation(v.scaleInPlace(p))):_&&s?(v=x.getTranslation(),x.setTranslation(v.multiplyInPlace(s))):x=g.value):x=g.value,m.push({frame:g.frame+i,value:x}));return this.animations[0].createRange(t,a+i,l+i),!0}),e&&(e.prototype._animate=function(e){if(!this.animationsEnabled)return;const t=a.j.Now;if(!this._animationTimeLast){if(this._pendingData.length>0)return;this._animationTimeLast=t}this.deltaTime=void 0!==e?e:this.useConstantAnimationDeltaTime?16:(t-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=t;const i=this._activeAnimatables;if(0===i.length)return;this._animationTime+=this.deltaTime;const r=this._animationTime;for(let e=0;ee.playOrder-t.playOrder))},e.prototype.beginWeightedAnimation=function(e,t,i,r=1,s,n=1,o,a,l,h,c=!1){const u=this.beginAnimation(e,t,i,s,n,o,a,!1,l,h,c);return u.weight=r,u},e.prototype.beginAnimation=function(e,t,i,r,s=1,n,o,a=!0,l,c,u=!1){if(s<0){const e=t;t=i,i=e,s=-s}t>i&&(s=-s),a&&this.stopAnimation(e,void 0,l),o||(o=new h(this,e,t,i,r,s,n,void 0,c,u));const d=!l||l(e);if(e.animations&&d&&o.appendAnimations(e,e.animations),e.getAnimatables){const h=e.getAnimatables();for(let e=0;er&&(n=-n),new h(this,e,i,r,s,n,o,t,a,l)},e.prototype.beginDirectHierarchyAnimation=function(e,t,i,r,s,n,o,a,l,h=!1){const c=e.getDescendants(t),u=[];u.push(this.beginDirectAnimation(e,i,r,s,n,o,a,l,h));for(const e of c)u.push(this.beginDirectAnimation(e,i,r,s,n,o,a,l,h));return u},e.prototype.getAnimatableByTarget=function(e){for(let t=0;t{"use strict";i.d(t,{X5:()=>x,eA:()=>m,nl:()=>g,rq:()=>p,s$:()=>d,vF:()=>_,y4:()=>f});var r=i(94212),s=i(11084),n=i(56984),o=i(56225),a=i(888),l=i(14747),h=i(29962),c=i(67313),u=i(89518);const d=Object.freeze(new r.PT(0,0,0,0)),f=Object.freeze(r.Pq.Zero()),p=Object.freeze(r.I9.Zero()),_=Object.freeze(h.o.Zero()),m=Object.freeze(s.v9.Black()),g=Object.freeze(new s.ov(0,0,0,0)),v={key:0,repeatCount:0,loopMode:2};class x{static _PrepareAnimation(e,t,i,n,o,a,l,c){let u;if(!isNaN(parseFloat(o))&&isFinite(o)?u=x.ANIMATIONTYPE_FLOAT:o instanceof r.PT?u=x.ANIMATIONTYPE_QUATERNION:o instanceof r.Pq?u=x.ANIMATIONTYPE_VECTOR3:o instanceof r.I9?u=x.ANIMATIONTYPE_VECTOR2:o instanceof s.v9?u=x.ANIMATIONTYPE_COLOR3:o instanceof s.ov?u=x.ANIMATIONTYPE_COLOR4:o instanceof h.o&&(u=x.ANIMATIONTYPE_SIZE),null==u)return null;const d=new x(e,t,i,u,l),f=[{frame:0,value:o},{frame:n,value:a}];return d.setKeys(f),void 0!==c&&d.setEasingFunction(c),d}static CreateAnimation(e,t,i,r){const s=new x(e+"Animation",e,i,t,x.ANIMATIONLOOPMODE_CONSTANT);return s.setEasingFunction(r),s}static CreateAndStartAnimation(e,t,i,r,s,n,o,a,l,h,c){const u=x._PrepareAnimation(e,i,r,s,n,o,a,l);return u?(t.getScene&&(c=t.getScene()),c?c.beginDirectAnimation(t,[u],0,s,1===u.loopMode,1,h):null):null}static CreateAndStartHierarchyAnimation(e,t,i,r,s,n,o,a,l,h,c){const u=x._PrepareAnimation(e,r,s,n,o,a,l,h);return u?t.getScene().beginDirectHierarchyAnimation(t,i,[u],0,n,1===u.loopMode,1,c):null}static CreateMergeAndStartAnimation(e,t,i,r,s,n,o,a,l,h){const c=x._PrepareAnimation(e,i,r,s,n,o,a,l);return c?(t.animations.push(c),t.getScene().beginAnimation(t,0,s,1===c.loopMode,1,h)):null}static MakeAnimationAdditive(e,t,i,s=!1,n){let o;o="object"==typeof t?t:{referenceFrame:t??0,range:i,cloneOriginalAnimation:s,clonedAnimationName:n};let a=e;if(o.cloneOriginalAnimation&&(a=e.clone(),a.name=o.clonedAnimationName||a.name),!a._keys.length)return a;const l=o.referenceFrame&&o.referenceFrame>=0?o.referenceFrame:0;let h=0;const c=a._keys[0];let u=a._keys.length-1;const d=a._keys[u],f={referenceValue:c.value,referencePosition:r.AA.Vector3[0],referenceQuaternion:r.AA.Quaternion[0],referenceScaling:r.AA.Vector3[1],keyPosition:r.AA.Vector3[2],keyQuaternion:r.AA.Quaternion[1],keyScaling:r.AA.Vector3[3]};let p=c.frame,_=d.frame;if(o.range){const e=a.getRange(o.range);e&&(p=e.from,_=e.to)}else p=o.fromFrame??p,_=o.toFrame??_;if(p!==c.frame&&(h=a.createKeyForFrame(p)),_!==d.frame&&(u=a.createKeyForFrame(_)),1===a._keys.length){const e=a._getKeyValue(a._keys[0]);f.referenceValue=e.clone?e.clone():e}else if(l<=c.frame){const e=a._getKeyValue(c.value);f.referenceValue=e.clone?e.clone():e}else if(l>=d.frame){const e=a._getKeyValue(d.value);f.referenceValue=e.clone?e.clone():e}else{v.key=0;const e=a._interpolate(l,v);f.referenceValue=e.clone?e.clone():e}a.dataType===x.ANIMATIONTYPE_QUATERNION?f.referenceValue.normalize().conjugateInPlace():a.dataType===x.ANIMATIONTYPE_MATRIX&&(f.referenceValue.decompose(f.referenceScaling,f.referenceQuaternion,f.referencePosition),f.referenceQuaternion.normalize().conjugateInPlace());let m=Number.MAX_VALUE;const g=o.clipKeys?[]:null;for(let e=h;e<=u;e++){let t=a._keys[e];if((g||o.cloneOriginalAnimation)&&(t={frame:t.frame,value:t.value.clone?t.value.clone():t.value,inTangent:t.inTangent,outTangent:t.outTangent,interpolation:t.interpolation,lockedTangent:t.lockedTangent},g&&(m===Number.MAX_VALUE&&(m=t.frame),t.frame-=m,g.push(t))),!e||a.dataType===x.ANIMATIONTYPE_FLOAT||t.value!==c.value)switch(a.dataType){case x.ANIMATIONTYPE_MATRIX:t.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),r.uq.ComposeToRef(f.keyScaling,f.keyQuaternion,f.keyPosition,t.value);break;case x.ANIMATIONTYPE_QUATERNION:f.referenceValue.multiplyToRef(t.value,t.value);break;case x.ANIMATIONTYPE_VECTOR2:case x.ANIMATIONTYPE_VECTOR3:case x.ANIMATIONTYPE_COLOR3:case x.ANIMATIONTYPE_COLOR4:t.value.subtractToRef(f.referenceValue,t.value);break;case x.ANIMATIONTYPE_SIZE:t.value.width-=f.referenceValue.width,t.value.height-=f.referenceValue.height;break;default:t.value-=f.referenceValue}}return g&&a.setKeys(g,!0),a}static TransitionTo(e,t,i,r,s,n,o,a=null){if(o<=0)return i[e]=t,a&&a(),null;const l=s*(o/1e3);n.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(n);const h=r.beginAnimation(i,0,l,!1);return h.onAnimationEnd=a,h}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,r,s,n){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=r,this.loopMode=s,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=r,this.loopMode=void 0===s?x.ANIMATIONLOOPMODE_CYCLE:s,this.uniqueId=x._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 e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort(((e,t)=>e.frame-t.frame))}removeEvents(e){for(let t=0;t=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const r=this._keys,s=r.length;let n=t.key;for(;n>=0&&e=r[n+1].frame;)++n;if(t.key=n,n<0)return i?void 0:this._getKeyValue(r[0].value);if(n+1>s-1)return i?void 0:this._getKeyValue(r[s-1].value);const o=r[n],a=r[n+1];if(i&&(e===o.frame||e===a.frame))return;const l=this._getKeyValue(o.value),h=this._getKeyValue(a.value);if(1===o.interpolation)return a.frame>e?l:h;const c=void 0!==o.outTangent&&void 0!==a.inTangent,u=a.frame-o.frame;let v=(e-o.frame)/u;const b=o.easingFunction||this.getEasingFunction();switch(null!==b&&(v=b.ease(v)),this.dataType){case x.ANIMATIONTYPE_FLOAT:{const e=c?this.floatInterpolateFunctionWithTangents(l,o.outTangent*u,h,a.inTangent*u,v):this.floatInterpolateFunction(l,h,v);switch(t.loopMode){case x.ANIMATIONLOOPMODE_CYCLE:case x.ANIMATIONLOOPMODE_CONSTANT:case x.ANIMATIONLOOPMODE_YOYO:return e;case x.ANIMATIONLOOPMODE_RELATIVE:case x.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(t.offsetValue??0)*t.repeatCount+e}break}case x.ANIMATIONTYPE_QUATERNION:{const e=c?this.quaternionInterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),v):this.quaternionInterpolateFunction(l,h,v);switch(t.loopMode){case x.ANIMATIONLOOPMODE_CYCLE:case x.ANIMATIONLOOPMODE_CONSTANT:case x.ANIMATIONLOOPMODE_YOYO:return e;case x.ANIMATIONLOOPMODE_RELATIVE:case x.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.addInPlace((t.offsetValue||d).scale(t.repeatCount))}return e}case x.ANIMATIONTYPE_VECTOR3:{const e=c?this.vector3InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),v):this.vector3InterpolateFunction(l,h,v);switch(t.loopMode){case x.ANIMATIONLOOPMODE_CYCLE:case x.ANIMATIONLOOPMODE_CONSTANT:case x.ANIMATIONLOOPMODE_YOYO:return e;case x.ANIMATIONLOOPMODE_RELATIVE:case x.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||f).scale(t.repeatCount))}break}case x.ANIMATIONTYPE_VECTOR2:{const e=c?this.vector2InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),v):this.vector2InterpolateFunction(l,h,v);switch(t.loopMode){case x.ANIMATIONLOOPMODE_CYCLE:case x.ANIMATIONLOOPMODE_CONSTANT:case x.ANIMATIONLOOPMODE_YOYO:return e;case x.ANIMATIONLOOPMODE_RELATIVE:case x.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||p).scale(t.repeatCount))}break}case x.ANIMATIONTYPE_SIZE:switch(t.loopMode){case x.ANIMATIONLOOPMODE_CYCLE:case x.ANIMATIONLOOPMODE_CONSTANT:case x.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(l,h,v);case x.ANIMATIONLOOPMODE_RELATIVE:case x.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(l,h,v).add((t.offsetValue||_).scale(t.repeatCount))}break;case x.ANIMATIONTYPE_COLOR3:{const e=c?this.color3InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),v):this.color3InterpolateFunction(l,h,v);switch(t.loopMode){case x.ANIMATIONLOOPMODE_CYCLE:case x.ANIMATIONLOOPMODE_CONSTANT:case x.ANIMATIONLOOPMODE_YOYO:return e;case x.ANIMATIONLOOPMODE_RELATIVE:case x.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||m).scale(t.repeatCount))}break}case x.ANIMATIONTYPE_COLOR4:{const e=c?this.color4InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),v):this.color4InterpolateFunction(l,h,v);switch(t.loopMode){case x.ANIMATIONLOOPMODE_CYCLE:case x.ANIMATIONLOOPMODE_CONSTANT:case x.ANIMATIONLOOPMODE_YOYO:return e;case x.ANIMATIONLOOPMODE_RELATIVE:case x.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||g).scale(t.repeatCount))}break}case x.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case x.ANIMATIONLOOPMODE_CYCLE:case x.ANIMATIONLOOPMODE_CONSTANT:case x.ANIMATIONLOOPMODE_YOYO:return x.AllowMatricesInterpolation?this.matrixInterpolateFunction(l,h,v,t.workValue):l;case x.ANIMATIONLOOPMODE_RELATIVE:case x.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return l}}return 0}matrixInterpolateFunction(e,t,i,s){return x.AllowMatrixDecomposeForInterpolation?s?(r.uq.DecomposeLerpToRef(e,t,i,s),s):r.uq.DecomposeLerp(e,t,i):s?(r.uq.LerpToRef(e,t,i,s),s):r.uq.Lerp(e,t,i)}clone(){const e=new x(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){v.key=0;const t=this._interpolate(e,v,!0);if(!t)return this._keys[v.key].frame===e?v.key:v.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(v.key+1,0,i),v.key+1}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const i=this.getKeys();for(let r=0;r=2&&(l=t.values[1]),t.values.length>=3&&(h=t.values[2]),t.values.length>=4&&(c=t.values[3]);break;case x.ANIMATIONTYPE_QUATERNION:if(o=r.PT.FromArray(t.values),t.values.length>=8){const e=r.PT.FromArray(t.values.slice(4,8));e.equals(r.PT.Zero())||(l=e)}if(t.values.length>=12){const e=r.PT.FromArray(t.values.slice(8,12));e.equals(r.PT.Zero())||(h=e)}t.values.length>=13&&(c=t.values[12]);break;case x.ANIMATIONTYPE_MATRIX:o=r.uq.FromArray(t.values),t.values.length>=17&&(c=t.values[16]);break;case x.ANIMATIONTYPE_COLOR3:o=s.v9.FromArray(t.values),t.values[3]&&(l=s.v9.FromArray(t.values[3])),t.values[4]&&(h=s.v9.FromArray(t.values[4])),t.values[5]&&(c=t.values[5]);break;case x.ANIMATIONTYPE_COLOR4:o=s.ov.FromArray(t.values),t.values[4]&&(l=s.ov.FromArray(t.values[4])),t.values[5]&&(h=s.ov.FromArray(t.values[5])),t.values[6]&&(c=s.ov.FromArray(t.values[6]));break;case x.ANIMATIONTYPE_VECTOR3:default:o=r.Pq.FromArray(t.values),t.values[3]&&(l=r.Pq.FromArray(t.values[3])),t.values[4]&&(h=r.Pq.FromArray(t.values[4])),t.values[5]&&(c=t.values[5])}const u={};u.frame=t.frame,u.value=o,null!=l&&(u.inTangent=l),null!=h&&(u.outTangent=h),null!=c&&(u.interpolation=c),n.push(u)}if(t.setKeys(n),e.ranges)for(a=0;a{const s=new c.u;s.addEventListener("readystatechange",(()=>{if(4==s.readyState)if(200==s.status){let t=JSON.parse(s.responseText);if(t.animations&&(t=t.animations),t.length){const e=[];for(const i of t)e.push(this.Parse(i));i(e)}else{const r=this.Parse(t);e&&(r.name=e),i(r)}}else r("Unable to load the animation")})),s.open("GET",t),s.send()}))}static ParseFromSnippetAsync(e){return new Promise(((t,i)=>{const r=new c.u;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){const i=JSON.parse(JSON.parse(r.responseText).jsonPayload);if(i.animations){const r=JSON.parse(i.animations),s=[];for(const t of r.animations){const i=this.Parse(t);i.snippetId=e,s.push(i)}t(s)}else{const r=JSON.parse(i.animation),s=this.Parse(r);s.snippetId=e,t(s)}}else i("Unable to load the snippet "+e)})),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()}))}}x._UniqueIdGenerator=0,x.AllowMatricesInterpolation=!1,x.AllowMatrixDecomposeForInterpolation=!0,x.SnippetUrl="https://snippet.babylonjs.com",x.ANIMATIONTYPE_FLOAT=0,x.ANIMATIONTYPE_VECTOR3=1,x.ANIMATIONTYPE_QUATERNION=2,x.ANIMATIONTYPE_MATRIX=3,x.ANIMATIONTYPE_COLOR3=4,x.ANIMATIONTYPE_COLOR4=7,x.ANIMATIONTYPE_VECTOR2=5,x.ANIMATIONTYPE_SIZE=6,x.ANIMATIONLOOPMODE_RELATIVE=0,x.ANIMATIONLOOPMODE_CYCLE=1,x.ANIMATIONLOOPMODE_CONSTANT=2,x.ANIMATIONLOOPMODE_YOYO=4,x.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5,x.CreateFromSnippetAsync=x.ParseFromSnippetAsync,(0,o.Y5)("BABYLON.Animation",x),l.b._AnimationRangeFactory=(e,t,i)=>new a.K(e,t,i)},7042:(e,t,i)=>{"use strict";i.r(t),i.d(t,{AnimationGroup:()=>l,TargetedAnimation:()=>a});var r=i(54065),s=i(43279),n=i(34268),o=i(84015);i(66418);class a{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class l{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=0;for(let e=0;e0)){for(let e=0;en&&(n=t.to);const o=new l(e[0].name+"_merged",e[0]._scene,r);for(const r of e){i&&r.normalize(s,n);for(const e of r.targetedAnimations)o.addTargetedAnimation(e.animation,e.target);t&&r.dispose()}return o}constructor(e,t=null,i=-1,r=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._shouldStart=!0,this._parentContainer=null,this.onAnimationEndObservable=new s.cP,this.onAnimationLoopObservable=new s.cP,this.onAnimationGroupLoopObservable=new s.cP,this.onAnimationGroupEndObservable=new s.cP,this.onAnimationGroupPauseObservable=new s.cP,this.onAnimationGroupPlayObservable=new s.cP,this.metadata=null,this._mask=null,this._animationLoopFlags=[],this._scene=t||n.q.LastCreatedScene,this._weight=i,this._playOrder=r,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new a;i.animation=e,i.target=t;const r=e.getKeys();return this._from>r[0].frame&&(this._from=r[0].frame),this._to-1;t--)this._targetedAnimations[t].animation===e&&this._targetedAnimations.splice(t,1)}normalize(e=null,t=null){null==e&&(e=this._from),null==t&&(t=this._to);for(let i=0;ie){const t={frame:e,value:s.value,inTangent:s.inTangent,outTangent:s.outTangent,interpolation:s.interpolation};r.splice(0,0,t)}if(n.frame{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._numActiveAnimatables&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,r,s){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._shouldStart=!1,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let n=0;n{this.onAnimationEndObservable.notifyObservers(o),this._checkAnimationGroupEnded(a)},this._processLoop(a,o,n),this._animatables.push(a)}return this.syncWithMask(),this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e0?this._scene._activeAnimatables[i++]=r:e&&this._checkAnimationGroupEnded(r,e)}return this._scene._activeAnimatables.length=i,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){const e=this._parentContainer.animationGroups.indexOf(this);e>-1&&this._parentContainer.animationGroups.splice(e,1),this._parentContainer=null}this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()}_checkAnimationGroupEnded(e,t=!1){const i=this._animatables.indexOf(e);i>-1&&this._animatables.splice(i,1),this._animatables.length===this._targetedAnimations.length-this._numActiveAnimatables&&(this._isStarted=!1,t||this.onAnimationGroupEndObservable.notifyObservers(this),this._animatables.length=0)}clone(e,t,i=!1){const r=new l(e||this.name,this._scene,this._weight,this._playOrder);r._from=this.from,r._to=this.to,r._speedRatio=this.speedRatio,r._loopAnimation=this.loopAnimation,r._isAdditive=this.isAdditive,r._enableBlending=this.enableBlending,r._blendingSpeed=this.blendingSpeed,r.metadata=this.metadata,r.mask=this.mask;for(const e of this._targetedAnimations)r.addTargetedAnimation(i?e.animation.clone():e.animation,t?t(e.target):e.target);return r}serialize(){const e={};e.name=this.name,e.from=this.from,e.to=this.to,e.speedRatio=this.speedRatio,e.loopAnimation=this.loopAnimation,e.isAdditive=this.isAdditive,e.weight=this.weight,e.playOrder=this.playOrder,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,e.targetedAnimations=[];for(let t=0;ts[0].frame&&(e=s[0].frame),t=t&&e<=i||s&&r.frame>=t&&r.frame<=i){const e={frame:r.frame,value:r.value.clone?r.value.clone():r.value,inTangent:r.inTangent,outTangent:r.outTangent,interpolation:r.interpolation,lockedTangent:r.lockedTangent};d===Number.MAX_VALUE&&(d=e.frame),e.frame-=d,u.push(e)}}0!==u.length?(n>u[0].frame&&(n=u[0].frame),o{"use strict";i.d(t,{K:()=>r});class r{constructor(e,t,i){this.name=e,this.from=t,this.to=i}clone(){return new r(this.name,this.from,this.to)}}},34493:(e,t,i)=>{"use strict";i.d(t,{x:()=>n});var r=i(94212),s=i(54065);class n{get currentFrame(){return this._currentFrame}get weight(){return this._weight}get currentValue(){return this._currentValue}get targetPath(){return this._targetPath}get target(){return this._currentActiveTarget}get isAdditive(){return this._host&&this._host.isAdditive}constructor(e,t,i,n){if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._absoluteFrameOffset=0,this._previousElapsedTime=0,this._yoyoDirection=1,this._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=n,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===s.X5.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=r.uq.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,0!==this._minFrame){const e={frame:0,value:this._minValue};this._keys.splice(0,0,e)}if(this._target instanceof Array){let e=0;for(const t of this._target)this._preparePath(t,e),this._getOriginalValues(e),e++;this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];const o=t.getEvents();o&&o.length>0&&o.forEach((e=>{this._events.push(e._clone())})),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}_preparePath(e,t=0){const i=this._animation.targetPropertyPath;if(i.length>1){let r=e;for(let e=0;e-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray)for(let i=0;ii[i.length-1].frame&&(e=i[i.length-1].frame);const r=this._events;if(r.length)for(let t=0;tthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);const c=i-t;let u,d=e*(a.framePerSecond*n)/1e3+this._absoluteFrameOffset,f=0,p=!1;const _=r&&this._animationState.loopMode===s.X5.ANIMATIONLOOPMODE_YOYO;if(_){const e=(d-t)/c,i=Math.sin(e*Math.PI);d=Math.abs(i)*c+t;const r=i>=0?1:-1;this._yoyoDirection!==r&&(p=!0),this._yoyoDirection=r}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=d,!r&&i>=t&&(d>=c&&n>0||d<=0&&n<0))h=!1,f=a._getKeyValue(this._maxValue);else if(!r&&t>=i&&(d<=c&&n<0||d>=0&&n>0))h=!1,f=a._getKeyValue(this._minValue);else if(this._animationState.loopMode!==s.X5.ANIMATIONLOOPMODE_CYCLE){const e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=s.X5.ANIMATIONLOOPMODE_CYCLE;const r=a._interpolate(t,this._animationState),n=a._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),a.dataType){case s.X5.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=n-r;break;case s.X5.ANIMATIONTYPE_QUATERNION:case s.X5.ANIMATIONTYPE_VECTOR3:case s.X5.ANIMATIONTYPE_VECTOR2:case s.X5.ANIMATIONTYPE_SIZE:case s.X5.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=n.subtract(r)}this._highLimitsCache[e]=n}f=this._highLimitsCache[e],u=this._offsetsCache[e]}if(void 0===u)switch(a.dataType){case s.X5.ANIMATIONTYPE_FLOAT:u=0;break;case s.X5.ANIMATIONTYPE_QUATERNION:u=s.s$;break;case s.X5.ANIMATIONTYPE_VECTOR3:u=s.y4;break;case s.X5.ANIMATIONTYPE_VECTOR2:u=s.rq;break;case s.X5.ANIMATIONTYPE_SIZE:u=s.vF;break;case s.X5.ANIMATIONTYPE_COLOR3:u=s.eA;break;case s.X5.ANIMATIONTYPE_COLOR4:u=s.nl}let m;if(this._host&&this._host.syncRoot){const e=this._host.syncRoot;m=t+c*((e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame))}else m=d>0&&t>i||d<0&&t0&&this.currentFrame>m||n<0&&this.currentFrame0?0:a.getKeys().length-1}this._currentFrame=m,this._animationState.repeatCount=0===c?0:d/c|0,this._animationState.highLimitValue=f,this._animationState.offsetValue=u;const v=a._interpolate(m,this._animationState);if(this.setValue(v,o),g.length)for(let e=0;e=0&&m>=g[e].frame&&g[e].frame>=t||c<0&&m<=g[e].frame&&g[e].frame<=t){const t=g[e];t.isDone||(t.onlyOnce&&(g.splice(e,1),e--),t.isDone=!0,t.action(m))}return h||(this._stopped=!0),h}}},87665:(e,t,i)=>{"use strict";i.d(t,{$:()=>o});var r=i(94212),s=i(34130),n=i(14747);class o extends n.b{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,n=null,o=null,a=null){super(e,t.getScene(),!1),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=s?.clone()??r.uq.Identity(),this._restMatrix=n??this._localMatrix.clone(),this._bindMatrix=o??this._localMatrix.clone(),this._index=a,this._absoluteMatrix=new r.uq,this._absoluteBindMatrix=new r.uq,this._absoluteInverseBindMatrix=new r.uq,this._finalMatrix=new r.uq,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 null===this._index?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 e=this.parent.children.indexOf(this);-1!==e&&this.parent.children.splice(e,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=r.AA.Vector3[0],t=r.AA.Quaternion[0],i=r.AA.Vector3[1];this.getRestMatrix().decompose(e,t,i),this._linkedTransformNode.position.copyFrom(i),this._linkedTransformNode.rotationQuaternion=this._linkedTransformNode.rotationQuaternion??r.PT.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=r.Pq.Zero(),this._localRotation=r.PT.Zero(),this._localPosition=r.Pq.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,r.uq.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)):this._needToCompose=!1)}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 e=0;e{"use strict";i.d(t,{R:()=>o,h:()=>n});var r=i(75801),s=i(60590);class n{get isDisposed(){return this._isDisposed}constructor(e,t,i,s=0,n=!1,o=!1,a=!1,l,h){this._isAlreadyOwned=!1,this._isDisposed=!1,e&&e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=o,this._divisor=l||1,this._label=h,t instanceof r.n?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=a?s:s*Float32Array.BYTES_PER_ELEMENT,n||this.create()}createVertexBuffer(e,t,i,r,s,n=!1,a){const l=n?t:t*Float32Array.BYTES_PER_ELEMENT,h=r?n?r:r*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new o(this._engine,this,e,this._updatable,!0,h,void 0===s?this._instanced:s,l,i,void 0,void 0,!0,this._divisor||a)}isUpdatable(){return this._updatable}getData(){return this._data}getBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT}create(e=null){!e&&this._buffer||(e=e||this._data)&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e,this._label),this._data=e):this._buffer=this._engine.createVertexBuffer(e,void 0,this._label))}_rebuild(){if(this._data)this._buffer=null,this.create(this._data);else{if(!this._buffer)return;if(this._buffer.capacity>0)return void(this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label));s.V.Warn(`Missing data for buffer "${this._label}" ${this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":""}. Buffer reconstruction failed.`),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,i,r=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,r?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),this._data=0===t&&void 0===i?e:null)}_increaseReferences(){this._buffer&&(this._isAlreadyOwned?this._buffer.references++:this._isAlreadyOwned=!0)}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}}class o{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=0!=e;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get _maxVerticesCount(){const e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,i,r,s,a,l,h,c,u,d=!1,f=!1,p=1,_=!1){this._isDisposed=!1;let m=!1;if(this.engine=e,"object"==typeof r&&null!==r?(m=r.updatable??!1,s=r.postponeInternalCreation,a=r.stride,l=r.instanced,h=r.offset,c=r.size,u=r.type,d=r.normalized??!1,f=r.useBytes??!1,p=r.divisor??1,_=r.takeBufferOwnership??!1,this._label=r.label):m=!!r,t instanceof n?(this._buffer=t,this._ownsBuffer=_):(this._buffer=new n(e,t,m,a,s,l,f,p,this._label),this._ownsBuffer=!0),this.uniqueId=o._Counter++,this._kind=i,void 0===u){const e=this.getData();this.type=e?o.GetDataType(e):o.FLOAT}else this.type=u;const g=o.GetTypeByteLength(this.type);f?(this._size=c||(a?a/g:o.DeduceStride(i)),this.byteStride=a||this._buffer.byteStride||this._size*g,this.byteOffset=h||0):(this._size=c||a||o.DeduceStride(i),this.byteStride=a?a*g:this._buffer.byteStride||this._size*g,this.byteOffset=(h||0)*g),this.normalized=d,this._instanced=void 0!==l&&l,this._instanceDivisor=l?p: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(){this._buffer?._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();return i?o.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/o.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/o.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*o.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){o.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case o.UVKind:case o.UV2Kind:case o.UV3Kind:case o.UV4Kind:case o.UV5Kind:case o.UV6Kind:return 2;case o.NormalKind:case o.PositionKind:return 3;case o.ColorKind:case o.ColorInstanceKind:case o.MatricesIndicesKind:case o.MatricesIndicesExtraKind:case o.MatricesWeightsKind:case o.MatricesWeightsExtraKind:case o.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?o.BYTE:e instanceof Uint8Array?o.UNSIGNED_BYTE:e instanceof Int16Array?o.SHORT:e instanceof Uint16Array?o.UNSIGNED_SHORT:e instanceof Int32Array?o.INT:e instanceof Uint32Array?o.UNSIGNED_INT:o.FLOAT}static GetTypeByteLength(e){switch(e){case o.BYTE:case o.UNSIGNED_BYTE:return 1;case o.SHORT:case o.UNSIGNED_SHORT:return 2;case o.INT:case o.UNSIGNED_INT:case o.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,r,s,n,a,l){if(e instanceof Array){let s=t/4;const o=i/4;for(let t=0;ts[t]=e)),s}if(!(e instanceof Array||e instanceof Float32Array)||0!==r||e.length!==u){if(e instanceof Array){const t=r/4;return e.slice(t,t+u)}if(e instanceof ArrayBuffer)return new Float32Array(e,r,u);{const t=e.byteOffset+r;if(3&t&&(s.V.Warn("Float array must be aligned to 4-bytes border"),h=!0),h){const i=new Uint8Array(u*Float32Array.BYTES_PER_ELEMENT),r=new Uint8Array(e.buffer,t,i.length);return i.set(r),new Float32Array(i.buffer)}return new Float32Array(e.buffer,t,u)}}return h?e.slice():e}}o._Counter=0,o.BYTE=5120,o.UNSIGNED_BYTE=5121,o.SHORT=5122,o.UNSIGNED_SHORT=5123,o.INT=5124,o.UNSIGNED_INT=5125,o.FLOAT=5126,o.PositionKind="position",o.NormalKind="normal",o.TangentKind="tangent",o.UVKind="uv",o.UV2Kind="uv2",o.UV3Kind="uv3",o.UV4Kind="uv4",o.UV5Kind="uv5",o.UV6Kind="uv6",o.ColorKind="color",o.ColorInstanceKind="instanceColor",o.MatricesIndicesKind="matricesIndices",o.MatricesWeightsKind="matricesWeights",o.MatricesIndicesExtraKind="matricesIndicesExtra",o.MatricesWeightsExtraKind="matricesWeightsExtra"},75801:(e,t,i)=>{"use strict";i.d(t,{n:()=>r});class r{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=r._Counter++}}r._Counter=0},91112:(e,t,i)=>{"use strict";i.d(t,{K:()=>r});class r{constructor(e,t,i=3,r){this._engine=e,this._label=r,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,r){return this._engine.readFromStorageBuffer(this._buffer,e,t,i,r)}dispose(){const e=this._engine._storageBuffers,t=e.indexOf(this);-1!==t&&(e[t]=e[e.length-1],e.pop()),this._engine._releaseBuffer(this._buffer),this._buffer=null}}},81310:(e,t,i)=>{"use strict";i.d(t,{G:()=>n});var r=i(94212),s=i(12721);class n{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(s.R.NormalKind))return null;let i,n=this.pickedMesh.getIndices();0===n?.length&&(n=null);const o=r.AA.Vector3[0],a=r.AA.Vector3[1],l=r.AA.Vector3[2];if(t){const e=this.pickedMesh.getVerticesData(s.R.NormalKind);let t=n?r.Pq.FromArrayToRef(e,3*n[3*this.faceId],o):o.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),h=n?r.Pq.FromArrayToRef(e,3*n[3*this.faceId+1],a):a.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),c=n?r.Pq.FromArrayToRef(e,3*n[3*this.faceId+2],l):l.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]);t=t.scale(this.bu),h=h.scale(this.bv),c=c.scale(1-this.bu-this.bv),i=new r.Pq(t.x+h.x+c.x,t.y+h.y+c.y,t.z+h.z+c.z)}else{const e=this.pickedMesh.getVerticesData(s.R.PositionKind),t=n?r.Pq.FromArrayToRef(e,3*n[3*this.faceId],o):o.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),h=n?r.Pq.FromArrayToRef(e,3*n[3*this.faceId+1],a):a.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),c=n?r.Pq.FromArrayToRef(e,3*n[3*this.faceId+2],l):l.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]),u=t.subtract(h),d=c.subtract(h);i=r.Pq.Cross(u,d)}const h=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(r.AA.Matrix[0].copyFrom(i),i=r.AA.Matrix[0],i.setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(r.AA.Matrix[1]),i=r.AA.Matrix[1]),r.Pq.TransformNormalToRef(t,i,t)};if(e&&h(this.pickedMesh,i),this.ray){const t=r.AA.Vector3[0].copyFrom(i);e||h(this.pickedMesh,t),r.Pq.Dot(t,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i}getTextureCoordinates(e=s.R.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;const t=this.pickedMesh.getIndices();if(!t)return null;const i=this.pickedMesh.getVerticesData(e);if(!i)return null;let n=r.I9.FromArray(i,2*t[3*this.faceId]),o=r.I9.FromArray(i,2*t[3*this.faceId+1]),a=r.I9.FromArray(i,2*t[3*this.faceId+2]);return n=n.scale(this.bu),o=o.scale(this.bv),a=a.scale(1-this.bu-this.bv),new r.I9(n.x+o.x+a.x,n.y+o.y+a.y)}}},75174:(e,t,i)=>{"use strict";i.d(t,{ge:()=>s,p9:()=>n,rX:()=>r});let r=!1;function s(e){r=e}const n={get UseOpenGLOrientationForUV(){return r},set UseOpenGLOrientationForUV(e){r=e}}},62061:(e,t,i)=>{"use strict";i.d(t,{H:()=>d});var r=i(15287),s=i(40220),n=i(89518),o=i(56225),a=i(4756),l=i(83839),h=i(60590),c=i(18310),u=i(89237);class d{get options(){return this._options}get shaderPath(){return this._shaderPath}constructor(e,t,i,r={}){this._bindings={},this._samplers={},this._contextIsDirty=!1,this.fastMode=!1,this.onCompiled=null,this.onError=null,this.name=e,this._engine=t,this.uniqueId=l.K.UniqueId,t.enableGPUTimingMeasurements&&(this.gpuTimeInFrame=new u.e),this._engine.getCaps().supportComputeShaders?r.bindingsMapping?(this._context=t.createComputeContext(),this._shaderPath=i,this._options={bindingsMapping:{},defines:[],...r}):h.V.Error("You must provide the binding mappings as browsers don't support reflection for wgsl shaders yet!"):h.V.Error("This engine does not support compute shaders!")}getClassName(){return"ComputeShader"}setTexture(e,t,i=!0){const r=this._bindings[e];this._bindings[e]={type:i?0:4,object:t,indexInGroupEntries:r?.indexInGroupEntries},this._contextIsDirty||(this._contextIsDirty=!r||r.object!==t||r.type!==this._bindings[e].type)}setStorageTexture(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:1,object:t,indexInGroupEntries:i?.indexInGroupEntries}}setExternalTexture(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:6,object:t,indexInGroupEntries:i?.indexInGroupEntries}}setVideoTexture(e,t){return!!t.externalTexture&&(this.setExternalTexture(e,t.externalTexture),!0)}setUniformBuffer(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:d._BufferIsDataBuffer(t)?7:2,object:t,indexInGroupEntries:i?.indexInGroupEntries}}setStorageBuffer(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:d._BufferIsDataBuffer(t)?7:3,object:t,indexInGroupEntries:i?.indexInGroupEntries}}setTextureSampler(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||!t.compareSampler(i.object)),this._bindings[e]={type:5,object:t,indexInGroupEntries:i?.indexInGroupEntries}}isReady(){let e=this._effect;for(const e in this._bindings){const t=this._bindings[e],i=t.type,r=t.object;switch(i){case 0:case 4:case 1:case 6:if(!r.isReady())return!1}}const t=[],i=this._shaderPath;if(this._options.defines)for(let e=0;e{const n=()=>{this.dispatch(e,t,i)?s():setTimeout(n,r)};n()}))}serialize(){const e=n.p.Serialize(this);e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={};for(const t in this._bindings){const i=this._bindings[t],r=i.object;switch(i.type){case 0:case 4:case 1:{const s=r.serialize();s&&(e.textures[t]=s,e.bindings[t]={type:i.type});break}}}return e}static Parse(e,t,i){const r=n.p.Parse((()=>new d(e.name,t.getEngine(),e.shaderPath,e.options)),e,t,i);for(const s in e.textures){const n=e.bindings[s],o=a.g.Parse(e.textures[s],t,i);0===n.type?r.setTexture(s,o):4===n.type?r.setTexture(s,o,!1):r.setStorageTexture(s,o)}return r}static _BufferIsDataBuffer(e){return void 0!==e.underlyingResource}}(0,r.Cg)([(0,s.lK)()],d.prototype,"name",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"fastMode",void 0),(0,o.Y5)("BABYLON.ComputeShader",d)},19164:(e,t,i)=>{"use strict";i.r(t),i.d(t,{ComputeShaderBoundingHelper:()=>l});var r=i(62061),s=i(91112),n=i(12721),o=i(94212),a=i(4216);i(69841).l.ShadersStoreWGSL.boundingInfoComputeShader="struct Results {minX : atomic,\nminY : atomic,\nminZ : atomic,\nmaxX : atomic,\nmaxY : atomic,\nmaxZ : atomic,\ndummy1 : i32,\ndummy2 : i32,};fn floatToBits(value: f32)->i32 {return bitcast(value);}\nfn bitsToFloat(value: i32)->f32 {return bitcast(value);}\nfn atomicMinFloat(atomicVar: ptr,read_write>,value: f32) {let intValue=floatToBits(value);loop {let oldIntValue=atomicLoad(atomicVar);let oldValue=bitsToFloat(oldIntValue);if (value>=oldValue) {break;}\nif (atomicCompareExchangeWeak(atomicVar,oldIntValue,intValue).old_value==oldIntValue) {break;}}}\nfn atomicMaxFloat(atomicVar: ptr,read_write>,value: f32) {let intValue=floatToBits(value);loop {let oldIntValue=atomicLoad(atomicVar);let oldValue=bitsToFloat(oldIntValue);if (value<=oldValue) {break;}\nif (atomicCompareExchangeWeak(atomicVar,oldIntValue,intValue).old_value==oldIntValue) {break;}}}\nfn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4\n{let offset=i32(index) *4; \nlet 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);}\nconst identity=mat4x4f(\nvec4f(1.0,0.0,0.0,0.0),\nvec4f(0.0,1.0,0.0,0.0),\nvec4f(0.0,0.0,1.0,0.0),\nvec4f(0.0,0.0,0.0,1.0)\n);struct Settings {morphTargetTextureInfo: vec3f,\nmorphTargetCount: i32,\nindexResult : u32,};@group(0) @binding(0) var positionBuffer : array;@group(0) @binding(1) var resultBuffer : array;@group(0) @binding(7) var settings : Settings;\n#if NUM_BONE_INFLUENCERS>0\n@group(0) @binding(2) var boneSampler : texture_2d;@group(0) @binding(3) var indexBuffer : array;@group(0) @binding(4) var weightBuffer : array;\n#if NUM_BONE_INFLUENCERS>4\n@group(0) @binding(5) var indexExtraBuffer : array;@group(0) @binding(6) var weightExtraBuffer : array;\n#endif\n#endif\n#ifdef MORPHTARGETS\n@group(0) @binding(8) var morphTargets : texture_2d_array;@group(0) @binding(9) var morphTargetInfluences : array;@group(0) @binding(10) var morphTargetTextureIndices : array;\n#endif\n#ifdef MORPHTARGETS\nfn readVector3FromRawSampler(targetIndex : i32,vertexIndex : u32)->vec3f\n{ \nlet vertexID=f32(vertexIndex)*settings.morphTargetTextureInfo.x;let y=floor(vertexID/settings.morphTargetTextureInfo.y);let x=vertexID-y*settings.morphTargetTextureInfo.y;let textureUV=vec2(i32(x),i32(y));return textureLoad(morphTargets,textureUV,i32(morphTargetTextureIndices[targetIndex]),0).xyz;}\n#endif\n@compute @workgroup_size(256,1,1)\nfn main(@builtin(global_invocation_id) global_id : vec3) {let index=global_id.x;if (index>=arrayLength(&positionBuffer)/3) {return;}\nlet position=vec3f(positionBuffer[index*3],positionBuffer[index*3+1],positionBuffer[index*3+2]);var finalWorld=identity;var positionUpdated=position;\n#if NUM_BONE_INFLUENCERS>0\nvar influence : mat4x4;let matricesIndices=indexBuffer[index];let matricesWeights=weightBuffer[index];influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\nlet matricesIndicesExtra=indexExtraBuffer[index];let matricesWeightsExtra=weightExtraBuffer[index];influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra.x)*matricesWeightsExtra.x;\n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra.y)*matricesWeightsExtra.y;\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra.z)*matricesWeightsExtra.z;\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra.w)*matricesWeightsExtra.w;\n#endif \n#endif \nfinalWorld=finalWorld*influence;\n#endif\n#ifdef MORPHTARGETS\nfor (var i=0; i=settings.morphTargetCount) {break;}\npositionUpdated=positionUpdated+(readVector3FromRawSampler(i,index)-position)*morphTargetInfluences[i];}\n#endif\nvar worldPos=finalWorld*vec4f(positionUpdated.x,positionUpdated.y,positionUpdated.z,1.0);atomicMinFloat(&resultBuffer[settings.indexResult].minX,worldPos.x);atomicMinFloat(&resultBuffer[settings.indexResult].minY,worldPos.y);atomicMinFloat(&resultBuffer[settings.indexResult].minZ,worldPos.z);atomicMaxFloat(&resultBuffer[settings.indexResult].maxX,worldPos.x);atomicMaxFloat(&resultBuffer[settings.indexResult].maxY,worldPos.y);atomicMaxFloat(&resultBuffer[settings.indexResult].maxZ,worldPos.z);}\n";class l{constructor(e){this._computeShadersCache={},this._positionBuffers={},this._indexBuffers={},this._weightBuffers={},this._indexExtraBuffers={},this._weightExtraBuffers={},this._morphTargetInfluenceBuffers={},this._morphTargetTextureIndexBuffers={},this._ubos=[],this._uboIndex=0,this._processedMeshes=[],this._computeShaders=[],this._uniqueComputeShaders=new Set,this._resultBuffers=[],this._engine=e}_getComputeShader(e,t,i){let s;const n=e.join("\n");if(this._computeShadersCache[n])s=this._computeShadersCache[n];else{const o={positionBuffer:{group:0,binding:0},resultBuffer:{group:0,binding:1},settings:{group:0,binding:7}};t&&(o.boneSampler={group:0,binding:2},o.indexBuffer={group:0,binding:3},o.weightBuffer={group:0,binding:4},o.indexExtraBuffer={group:0,binding:5},o.weightExtraBuffer={group:0,binding:6}),i&&(o.morphTargets={group:0,binding:8},o.morphTargetInfluences={group:0,binding:9},o.morphTargetTextureIndices={group:0,binding:10}),s=new r.H(`boundingInfoCompute${t?"_bones":""}${i?"_morphs":""}`,this._engine,"boundingInfo",{bindingsMapping:o,defines:e}),this._computeShadersCache[n]=s}return s}_getUBO(){if(this._uboIndex>=this._ubos.length){const e=new a.D(this._engine);e.addFloat3("morphTargetTextureInfo",0,0,0),e.addUniform("morphTargetCount",1),e.addUniform("indexResult",1),this._ubos.push(e)}return this._ubos[this._uboIndex++]}_extractDataAndLink(e,t,i,r,n,o){let a;const l=t.getTotalVertices();if(o[t.uniqueId])a=o[t.uniqueId];else{const e=t.getVertexBuffer(i)?.getFloatData(l);a=new s.K(this._engine,Float32Array.BYTES_PER_ELEMENT*l*r),a.update(e),o[t.uniqueId]=a}e.setStorageBuffer(n,a)}_prepareStorage(e,t,i,r,n,o){let a;r[i]?a=r[i]:(a=new s.K(this._engine,Float32Array.BYTES_PER_ELEMENT*n),r[i]=a),a.update(o),e.setStorageBuffer(t,a)}async processAsync(e){await this.registerMeshListAsync(e),this.processMeshList(),await this.fetchResultsForMeshListAsync()}registerMeshListAsync(e){this._disposeForMeshList(),Array.isArray(e)||(e=[e]);let t=0;for(let i=0;i{const t=()=>{const i=this._uniqueComputeShaders.keys();for(let e=i.next();!0!==e.done;e=i.next())if(!e.value.isReady())return void setTimeout(t,10);e()};t()}))}processMeshList(){if(0===this._processedMeshes.length)return;this._uboIndex=0;const e=8*this._processedMeshes.length,t=new Float32Array(e),i=new s.K(this._engine,Float32Array.BYTES_PER_ELEMENT*e);this._resultBuffers.push(i);for(let e=0;e0,h=l?o:s;if(this._extractDataAndLink(h,t,n.R.PositionKind,3,"positionBuffer",this._positionBuffers),t&&t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&t.skeleton.useTextureToStoreBoneMatrices){this._extractDataAndLink(h,t,n.R.MatricesIndicesKind,4,"indexBuffer",this._indexBuffers),this._extractDataAndLink(h,t,n.R.MatricesWeightsKind,4,"weightBuffer",this._weightBuffers);const e=t.skeleton.getTransformMatrixTexture(t);h.setTexture("boneSampler",e,!1),t.numBoneInfluencers>4&&(this._extractDataAndLink(h,t,n.R.MatricesIndicesExtraKind,4,"indexExtraBuffer",this._indexExtraBuffers),this._extractDataAndLink(h,t,n.R.MatricesWeightsExtraKind,4,"weightExtraBuffer",this._weightExtraBuffers))}const c=this._getUBO();if(l){const e=a._targetStoreTexture;h.setTexture("morphTargets",e,!1),this._prepareStorage(h,"morphTargetInfluences",t.uniqueId,this._morphTargetInfluenceBuffers,a.numInfluencers,a.influences),this._prepareStorage(h,"morphTargetTextureIndices",t.uniqueId,this._morphTargetTextureIndexBuffers,a.numInfluencers,a._morphTargetTextureIndices),c.updateFloat3("morphTargetTextureInfo",a._textureVertexStride,a._textureWidth,a._textureHeight),c.updateInt("morphTargetCount",a.numInfluencers),c.update()}h.setStorageBuffer("resultBuffer",i),h.setUniformBuffer("settings",c),h.dispatch(Math.ceil(r/256)),this._engine.flushFramebuffer()}}fetchResultsForMeshListAsync(){return new Promise((e=>{const t=[];let i=0;for(let e=0;e{let t=0;for(let e=0;e0&&(s.minimizeInPlace(l.getBoundingInfo().minimum),n.maximizeInPlace(l.getBoundingInfo().maximum)),l._refreshBoundingInfoDirect(a)}t+=8*this._processedMeshes.length}for(const e of this._resultBuffers)e.dispose();this._resultBuffers=[],this._uboIndex=0,e()}))}))}_disposeCache(e){for(const t in e)e[t].dispose()}_disposeForMeshList(){for(const e of this._resultBuffers)e.dispose();this._resultBuffers=[],this._processedMeshes=[],this._computeShaders=[],this._uniqueComputeShaders=new Set}dispose(){this._disposeCache(this._positionBuffers),this._positionBuffers={},this._disposeCache(this._indexBuffers),this._indexBuffers={},this._disposeCache(this._weightBuffers),this._weightBuffers={},this._disposeCache(this._morphTargetInfluenceBuffers),this._morphTargetInfluenceBuffers={},this._disposeCache(this._morphTargetTextureIndexBuffers),this._morphTargetTextureIndexBuffers={};for(const e of this._ubos)e.dispose();this._ubos=[],this._computeShadersCache={},this._engine=void 0,this._disposeForMeshList()}}},43306:(e,t,i)=>{"use strict";i.r(t),i.d(t,{TransformFeedbackBoundingHelper:()=>l});var r=i(12721),s=i(85770),n=i(890),o=i(94212),a=i(69841);i(39948),i(66682),i(9158),i(11783),i(99216),i(44219),i(78792),i(95532);a.l.ShadersStore.gpuTransformVertexShader="attribute vec3 position;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\nout vec3 outPosition;const mat4 identity=mat4(\nvec4(1.0,0.0,0.0,0.0),\nvec4(0.0,1.0,0.0,0.0),\nvec4(0.0,0.0,1.0,0.0),\nvec4(0.0,0.0,0.0,1.0)\n);void main(void) {vec3 positionUpdated=position;\n#include\n#include[0..maxSimultaneousMorphTargets]\nmat4 finalWorld=identity;\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);outPosition=worldPos.xyz;}";a.l.ShadersStore.gpuTransformPixelShader="#version 300 es\nvoid main() {discard;}\n";class l{constructor(e){this._buffers={},this._effects={},this._meshListCounter=0,this._engine=e}processAsync(e){return Array.isArray(e)||(e=[e]),this._meshListCounter=0,this._processMeshList(e),Promise.resolve()}_processMeshList(e){const t=this._engine.getCaps().parallelShaderCompile;this._engine.getCaps().parallelShaderCompile=void 0;for(let t=0;t4&&(h.push(r.R.MatricesIndicesExtraKind),h.push(r.R.MatricesWeightsExtraKind));const e=i.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+i.numBoneInfluencers),e.isUsingTextureForMatrices?(a.push("#define BONETEXTURE"),-1===l.indexOf("boneTextureWidth")&&l.push("boneTextureWidth"),-1===c.indexOf("boneSampler")&&c.push("boneSampler")):(a.push("#define BonesPerMesh "+(e.bones.length+1)),-1===l.indexOf("mBones")&&l.push("mBones"))}else a.push("#define NUM_BONE_INFLUENCERS 0");const u=i?i.morphTargetManager:null;if(u){o=u.numMaxInfluencers||u.numInfluencers,o>0&&a.push("#define MORPHTARGETS"),u.isUsingTextureForTargets&&(a.push("#define MORPHTARGETS_TEXTURE"),-1===l.indexOf("morphTargetTextureIndices")&&l.push("morphTargetTextureIndices"),-1===c.indexOf("morphTargets")&&c.push("morphTargets")),a.push("#define NUM_MORPH_INFLUENCERS "+o);for(let e=0;e0&&(l=l.slice(),l.push("morphTargetInfluences"),l.push("morphTargetCount"),l.push("morphTargetTextureInfo"),l.push("morphTargetTextureIndices"))}const d=i.bakedVertexAnimationManager;d&&d.isEnabled&&(a.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===l.indexOf("bakedVertexAnimationSettings")&&l.push("bakedVertexAnimationSettings"),-1===l.indexOf("bakedVertexAnimationTextureSizeInverted")&&l.push("bakedVertexAnimationTextureSizeInverted"),-1===l.indexOf("bakedVertexAnimationTime")&&l.push("bakedVertexAnimationTime"),-1===c.indexOf("bakedVertexAnimationTexture")&&c.push("bakedVertexAnimationTexture"),(0,s.J2)(h,i,a));const f=a.join("\n");if(this._effects[f])n=this._effects[f];else{const e={attributes:h,uniformsNames:l,uniformBuffersNames:[],samplers:c,defines:f,fallbacks:null,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:o},maxSimultaneousLights:0,transformFeedbackVaryings:["outPosition"]};n=this._engine.createEffect("gpuTransform",e,this._engine),this._effects[f]=n}this._compute(i,n)}this._engine.getCaps().parallelShaderCompile=t}_compute(e,t){const i=this._engine;let o;const a=e.getTotalVertices();if(this._buffers[e.uniqueId])o=this._buffers[e.uniqueId];else{const t=new Float32Array(3*a);o=new r.h(e.getEngine(),t,!0,3),this._buffers[e.uniqueId]=o}t.getEngine().enableEffect(t),e._bindDirect(t,null,!0),(0,s.f$)(e,t);const h=e.morphTargetManager;h&&h.numInfluencers>0&&(0,s.nR)(e,t);const c=e.bakedVertexAnimationManager;c&&c.isEnabled&&e.bakedVertexAnimationManager?.bind(t,!1);const u=o.getData();if(i.bindTransformFeedbackBuffer(o.getBuffer()),i.setRasterizerState(!1),i.beginTransformFeedback(!0),i.drawArraysType(2,0,a),i.endTransformFeedback(),i.setRasterizerState(!0),i.readTransformFeedbackBuffer(u),i.bindTransformFeedbackBuffer(null),0===this._meshListCounter)e._refreshBoundingInfo(u,null);else{const t=e.getBoundingInfo().boundingBox,i=(0,n.b8)(u,0,a);l._Min.copyFrom(t.minimum).minimizeInPlace(i.minimum),l._Max.copyFrom(t.maximum).maximizeInPlace(i.maximum),e._refreshBoundingInfoDirect({minimum:l._Min,maximum:l._Max})}}registerMeshListAsync(e){return Array.isArray(e)||(e=[e]),this._meshList=e,this._meshListCounter=0,Promise.resolve()}processMeshList(){0!==this._meshList.length&&(this._processMeshList(this._meshList),this._meshListCounter++)}fetchResultsForMeshListAsync(){return this._meshListCounter=0,Promise.resolve()}dispose(){for(const e in this._buffers)this._buffers[e].dispose();this._buffers={},this._effects={},this._engine=null}}l._Min=new o.Pq,l._Max=new o.Pq},58292:(e,t,i)=>{"use strict";var r,s,n,o,a,l,h;i.d(t,{ST:()=>s,Ze:()=>n,bq:()=>r,dR:()=>h,h8:()=>o,pI:()=>a,sZ:()=>l}),function(e){e[e.Generic=0]="Generic",e[e.Keyboard=1]="Keyboard",e[e.Mouse=2]="Mouse",e[e.Touch=3]="Touch",e[e.DualShock=4]="DualShock",e[e.Xbox=5]="Xbox",e[e.Switch=6]="Switch",e[e.DualSense=7]="DualSense"}(r||(r={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical",e[e.LeftClick=2]="LeftClick",e[e.MiddleClick=3]="MiddleClick",e[e.RightClick=4]="RightClick",e[e.BrowserBack=5]="BrowserBack",e[e.BrowserForward=6]="BrowserForward",e[e.MouseWheelX=7]="MouseWheelX",e[e.MouseWheelY=8]="MouseWheelY",e[e.MouseWheelZ=9]="MouseWheelZ",e[e.Move=12]="Move"}(s||(s={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical",e[e.LeftClick=2]="LeftClick",e[e.MiddleClick=3]="MiddleClick",e[e.RightClick=4]="RightClick",e[e.BrowserBack=5]="BrowserBack",e[e.BrowserForward=6]="BrowserForward",e[e.MouseWheelX=7]="MouseWheelX",e[e.MouseWheelY=8]="MouseWheelY",e[e.MouseWheelZ=9]="MouseWheelZ",e[e.DeltaHorizontal=10]="DeltaHorizontal",e[e.DeltaVertical=11]="DeltaVertical"}(n||(n={})),function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.L2=6]="L2",e[e.R2=7]="R2",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.L3=10]="L3",e[e.R3=11]="R3",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.TouchPad=17]="TouchPad",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(o||(o={})),function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.L2=6]="L2",e[e.R2=7]="R2",e[e.Create=8]="Create",e[e.Options=9]="Options",e[e.L3=10]="L3",e[e.R3=11]="R3",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.TouchPad=17]="TouchPad",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(a||(a={})),function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.LT=6]="LT",e[e.RT=7]="RT",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LS=10]="LS",e[e.RS=11]="RS",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.LStickXAxis=17]="LStickXAxis",e[e.LStickYAxis=18]="LStickYAxis",e[e.RStickXAxis=19]="RStickXAxis",e[e.RStickYAxis=20]="RStickYAxis"}(l||(l={})),function(e){e[e.B=0]="B",e[e.A=1]="A",e[e.Y=2]="Y",e[e.X=3]="X",e[e.L=4]="L",e[e.R=5]="R",e[e.ZL=6]="ZL",e[e.ZR=7]="ZR",e[e.Minus=8]="Minus",e[e.Plus=9]="Plus",e[e.LS=10]="LS",e[e.RS=11]="RS",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.Capture=17]="Capture",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(h||(h={}))},77333:(e,t,i)=>{"use strict";i.d(t,{c:()=>s});var r=i(43279);class s{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new r.cP,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}},78035:(e,t,i)=>{"use strict";i.d(t,{Z:()=>p});var r=i(58292),s=i(43279),n=i(7474);class o{static CreateDeviceEvent(e,t,i,s,n,o,a){switch(e){case r.bq.Keyboard:return this._CreateKeyboardEvent(i,s,n,o);case r.bq.Mouse:if(i===r.ST.MouseWheelX||i===r.ST.MouseWheelY||i===r.ST.MouseWheelZ)return this._CreateWheelEvent(e,t,i,s,n,o);case r.bq.Touch:return this._CreatePointerEvent(e,t,i,s,n,o,a);default:throw`Unable to generate event for device ${r.bq[e]}`}}static _CreatePointerEvent(e,t,i,s,n,o,a){const l=this._CreateMouseEvent(e,t,i,s,n,o);e===r.bq.Mouse?(l.deviceType=r.bq.Mouse,l.pointerId=1,l.pointerType="mouse"):(l.deviceType=r.bq.Touch,l.pointerId=a??t,l.pointerType="touch");let h=0;return h+=n.pollInput(e,t,r.ST.LeftClick),h+=2*n.pollInput(e,t,r.ST.RightClick),h+=4*n.pollInput(e,t,r.ST.MiddleClick),l.buttons=h,i===r.ST.Move?l.type="pointermove":i>=r.ST.LeftClick&&i<=r.ST.RightClick&&(l.type=1===s?"pointerdown":"pointerup",l.button=i-2),l}static _CreateWheelEvent(e,t,i,s,o,a){const l=this._CreateMouseEvent(e,t,i,s,o,a);switch(l.pointerId=1,l.type="wheel",l.deltaMode=n.s.DOM_DELTA_PIXEL,l.deltaX=0,l.deltaY=0,l.deltaZ=0,i){case r.ST.MouseWheelX:l.deltaX=s;break;case r.ST.MouseWheelY:l.deltaY=s;break;case r.ST.MouseWheelZ:l.deltaZ=s}return l}static _CreateMouseEvent(e,t,i,s,n,o){const a=this._CreateEvent(o),l=n.pollInput(e,t,r.ST.Horizontal),h=n.pollInput(e,t,r.ST.Vertical);return o?(a.movementX=0,a.movementY=0,a.offsetX=a.movementX-o.getBoundingClientRect().x,a.offsetY=a.movementY-o.getBoundingClientRect().y):(a.movementX=n.pollInput(e,t,10),a.movementY=n.pollInput(e,t,11),a.offsetX=0,a.offsetY=0),this._CheckNonCharacterKeys(a,n),a.clientX=l,a.clientY=h,a.x=l,a.y=h,a.deviceType=e,a.deviceSlot=t,a.inputIndex=i,a}static _CreateKeyboardEvent(e,t,i,s){const n=this._CreateEvent(s);return this._CheckNonCharacterKeys(n,i),n.deviceType=r.bq.Keyboard,n.deviceSlot=0,n.inputIndex=e,n.type=1===t?"keydown":"keyup",n.key=String.fromCharCode(e),n.keyCode=e,n}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(r.bq.Keyboard),s=i&&1===t.pollInput(r.bq.Keyboard,0,18),n=i&&1===t.pollInput(r.bq.Keyboard,0,17),o=i&&(1===t.pollInput(r.bq.Keyboard,0,91)||1===t.pollInput(r.bq.Keyboard,0,92)||1===t.pollInput(r.bq.Keyboard,0,93)),a=i&&1===t.pollInput(r.bq.Keyboard,0,16);e.altKey=s,e.ctrlKey=n,e.metaKey=o,e.shiftKey=a}static _CreateEvent(e){const t={preventDefault:()=>{}};return t.target=e,t}}class a{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,((e,t,r,s)=>{const n=o.CreateDeviceEvent(e,t,r,s,this);i(e,t,n)})):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===r.bq.Mouse||e===r.bq.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}var l=i(68191),h=i(9723);const c=Object.keys(r.ST).length/2;class u{constructor(e,t,i,r){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=h.S0.IsSafari(),this._usingMacOS=(0,l.XD)()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=e=>{},this._keyboardUpEvent=e=>{},this._keyboardBlurEvent=e=>{},this._pointerMoveEvent=e=>{},this._pointerDownEvent=e=>{},this._pointerUpEvent=e=>{},this._pointerCancelEvent=e=>{},this._pointerWheelEvent=e=>{},this._pointerBlurEvent=e=>{},this._pointerMacOSChromeOutEvent=e=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=(0,l.XD)()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=(0,l.XD)()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=h.S0.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=r,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){const s=this._inputs[e][t];if(!s)throw`Unable to find device ${r.bq[e]}`;e>=r.bq.DualShock&&e<=r.bq.DualSense&&this._updateDevice(e,t,i);const n=s[i];if(void 0===n)throw`Unable to find input ${i} for device ${r.bq[e]} in slot ${t}`;return i===r.ST.Move&&h.S0.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),n}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){const e=this?._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs)for(const e of this._inputs)if(e)for(const t in e){const i=e[+t];if(i)for(let e=0;e{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(r.bq.Keyboard,0,255));const t=this._inputs[r.bq.Keyboard][0];if(t){t[e.keyCode]=1;const i=e;i.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&"Meta"!==e.key&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(r.bq.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(r.bq.Keyboard,0,255));const t=this._inputs[r.bq.Keyboard][0];if(t){t[e.keyCode]=0;const i=e;if(i.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(const e of this._metaKeys){const i=o.CreateDeviceEvent(r.bq.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(r.bq.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(r.bq.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[r.bq.Keyboard][0];for(let t=0;t{const t=this._getPointerType(e);let i=t===r.bq.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===r.bq.Touch&&-1===i){const r=this._activeTouchIds.indexOf(-1);if(!(r>=0))return void h.S0.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=r,this._activeTouchIds[r]=e.pointerId,this._onDeviceConnected(t,i)}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const n=e;n.inputIndex=r.ST.Move,s[r.ST.Horizontal]=e.clientX,s[r.ST.Vertical]=e.clientY,t===r.bq.Touch&&0===s[r.ST.LeftClick]&&(s[r.ST.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,n),this._usingSafari||-1===e.button||(n.inputIndex=e.button+2,s[e.button+2]=s[e.button+2]?0:1,this._onInputChanged(t,i,n))}},this._pointerDownEvent=e=>{const t=this._getPointerType(e);let i=t===r.bq.Mouse?0:e.pointerId;if(t===r.bq.Touch){let t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t&&(t=this._activeTouchIds.indexOf(-1)),!(t>=0))return void h.S0.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=t,this._activeTouchIds[t]=e.pointerId}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]?t===r.bq.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const n=s[r.ST.Horizontal],o=s[r.ST.Vertical];if(t===r.bq.Mouse){if(void 0===e.pointerId&&(e.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(e){}}else if(e.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(e.pointerId)}catch(e){}s[r.ST.Horizontal]=e.clientX,s[r.ST.Vertical]=e.clientY,s[e.button+2]=1;const a=e;a.inputIndex=e.button+2,this._onInputChanged(t,i,a),n===e.clientX&&o===e.clientY||(a.inputIndex=r.ST.Move,this._onInputChanged(t,i,a))}},this._pointerUpEvent=e=>{const t=this._getPointerType(e),i=t===r.bq.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===r.bq.Touch){if(-1===i)return;this._activeTouchIds[i]=-1}const s=this._inputs[t]?.[i];if(s&&0!==s[e.button+2]){const n=s[r.ST.Horizontal],o=s[r.ST.Vertical];s[r.ST.Horizontal]=e.clientX,s[r.ST.Vertical]=e.clientY,s[e.button+2]=0;const a=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),n===e.clientX&&o===e.clientY||(a.inputIndex=r.ST.Move,this._onInputChanged(t,i,a)),a.inputIndex=e.button+2,t===r.bq.Mouse&&this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(t,i,a),t===r.bq.Touch&&this._onDeviceDisconnected(t,i)}},this._pointerCancelEvent=e=>{if("mouse"===e.pointerType){const e=this._inputs[r.bq.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=r.ST.LeftClick;t<=r.ST.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=o.CreateDeviceEvent(r.bq.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(r.bq.Mouse,0,i)}}else{const t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t)return;this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[r.bq.Touch][t][r.ST.LeftClick]=0;const i=o.CreateDeviceEvent(r.bq.Touch,t,r.ST.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(r.bq.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(r.bq.Touch,t)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"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(e){}this._pointerBlurEvent=()=>{if(this.isDeviceAvailable(r.bq.Mouse)){const e=this._inputs[r.bq.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=r.ST.LeftClick;t<=r.ST.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=o.CreateDeviceEvent(r.bq.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(r.bq.Mouse,0,i)}}if(this.isDeviceAvailable(r.bq.Touch)){const e=this._inputs[r.bq.Touch];for(let t=0;t{const t=r.bq.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,c));const i=this._inputs[t][0];if(i){i[r.ST.MouseWheelX]=e.deltaX||0,i[r.ST.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[r.ST.MouseWheelZ]=e.deltaZ||0;const s=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[r.ST.MouseWheelX]&&(s.inputIndex=r.ST.MouseWheelX,this._onInputChanged(t,0,s)),0!==i[r.ST.MouseWheelY]&&(s.inputIndex=r.ST.MouseWheelY,this._onInputChanged(t,0,s)),0!==i[r.ST.MouseWheelZ]&&(s.inputIndex=r.ST.MouseWheelZ,this._onInputChanged(t,0,s))}},this._usingMacOS&&this._isUsingChromium&&(this._pointerMacOSChromeOutEvent=e=>{e.buttons>1&&this._pointerCancelEvent(e)},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}),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add((()=>{if(this.isDeviceAvailable(r.bq.Mouse)){const e=this._inputs[r.bq.Mouse][0];e[r.ST.MouseWheelX]=0,e[r.ST.MouseWheelY]=0,e[r.ST.MouseWheelZ]=0}}))}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){const r=navigator.getGamepads()[t];if(r&&e===this._gamepads[t]){const s=this._inputs[e][t];i>=r.buttons.length?s[i]=r.axes[i-r.buttons.length].valueOf():s[i]=r.buttons[i].value}}_getGamepadDeviceType(e){return-1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?r.bq.DualSense:r.bq.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?r.bq.Xbox:-1!==e.indexOf("057e")?r.bq.Switch:r.bq.Generic}_getPointerType(e){let t=r.bq.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=r.bq.Touch),t}}var d=i(77333);class f{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=e=>{for(let t=0;t{const t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};const t=Object.keys(r.bq).length/2;this._devices=new Array(t);const i=(e,t)=>{this._devices[e]||(this._devices[e]=new Array),this._devices[e][t]||(this._devices[e][t]=t);for(const i of this._registeredManagers){const r=new d.c(this._deviceInputSystem,e,t);i._addDevice(r)}},s=(e,t)=>{this._devices[e]?.[t]&&delete this._devices[e][t];for(const i of this._registeredManagers)i._removeDevice(e,t)},n=(e,t,i)=>{if(i)for(const r of this._registeredManagers)r._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new a(i,s,n):this._deviceInputSystem=new u(e,i,s,n)}dispose(){this._deviceInputSystem.dispose()}}class p{getDeviceSource(e,t){if(void 0===t){if(void 0===this._firstDevice[e])return null;t=this._firstDevice[e]}return this._devices[e]&&void 0!==this._devices[e][t]?this._devices[e][t]:null}getDeviceSources(e){return this._devices[e]?this._devices[e].filter((e=>!!e)):[]}constructor(e){const t=Object.keys(r.bq).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new f(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new s.cP((e=>{for(const t of this._devices)if(t)for(const i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)})),this.onDeviceDisconnectedObservable=new s.cP,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){const i=this._devices[e]?.[t];this.onDeviceDisconnectedObservable.notifyObservers(i),this._devices[e]?.[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){this._devices[e]?.[t]?.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case r.bq.Keyboard:case r.bq.Mouse:this._firstDevice[e]=0;break;case r.bq.Touch:case r.bq.DualSense:case r.bq.DualShock:case r.bq.Xbox:case r.bq.Switch:case r.bq.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t)for(let i=0;i{"use strict";var r=i(7107),s=i(60590),n=i(28909),o=i(71627),a=i(55935),l=i(47221);a.$.prototype._partialLoadFile=function(e,t,i,r,s=null){this._loadFile(e,(e=>{i[t]=e,i._internalCount++,6===i._internalCount&&r(i)}),void 0,void 0,!0,((e,t)=>{s&&e&&s(e.status+" "+e.statusText,t)}))},a.$.prototype._cascadeLoadFiles=function(e,t,i,r=null){const s=[];s._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(i[e],e,s,t,r)},a.$.prototype._cascadeLoadImgs=function(e,t,i,r,s=null,n){const o=[];o._internalCount=0;for(let a=0;a<6;a++)this._partialLoadImg(r[a],a,o,e,t,i,s,n)},a.$.prototype._partialLoadImg=function(e,t,i,r,s,a,l=null,h){const c=(0,o.z)();(0,n.W$)(e,(e=>{i[t]=e,i._internalCount++,r&&r.removePendingData(c),6===i._internalCount&&a&&a(s,i)}),((e,t)=>{r&&r.removePendingData(c),l&&l(e,t)}),r?r.offlineProvider:null,h),r&&r.addPendingData(c)},a.$.prototype.createCubeTextureBase=function(e,t,i,n,o=null,a=null,h,c=null,u=!1,d=0,f=0,p=null,_=null,m=null,g=!1,v=null){const x=p||new r.h(this,7);x.isCube=!0,x.url=e,x.generateMipMaps=!n,x._lodGenerationScale=d,x._lodGenerationOffset=f,x._useSRGBBuffer=!!g&&this._caps.supportSRGBBuffers&&(this.version>1||this.isWebGPU||!!n),x!==p&&(x.label=e.substring(0,60)),this._doNotHandleContextLost||(x._extension=c,x._files=i,x._buffer=v);const b=e;this._transformTextureUrl&&!p&&(e=this._transformTextureUrl(e));const S=e.split("?")[0],T=S.lastIndexOf("."),C=c||(T>-1?S.substring(T).toLowerCase():""),y=(0,l.gT)(C),E=(r,l)=>{e===b?a&&r&&a(r.status+" "+r.statusText,l):(s.V.Warn(`Failed to load ${e}, falling back to the ${b}`),this.createCubeTextureBase(b,t,i,!!n,o,a,h,c,u,d,f,x,_,m,g,v))};if(y)y.then((r=>{const n=e=>{_&&_(x,e),r.loadCubeData(e,x,u,o,a)};v?n(v):i&&6===i.length?r.supportCascades?this._cascadeLoadFiles(t,(e=>n(e.map((e=>new Uint8Array(e))))),i,a):a?a("Textures type does not support cascades."):s.V.Warn("Texture loader does not support cascades."):this._loadFile(e,(e=>n(new Uint8Array(e))),void 0,void 0,!0,E)}));else{if(!i||0===i.length)throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");this._cascadeLoadImgs(t,x,((e,t)=>{m&&m(e,t)}),i,a)}return this._internalTexturesCache.push(x),x}},88217:(e,t,i)=>{"use strict";i.d(t,{nO:()=>E,pB:()=>T,jC:()=>y,M0:()=>C,Iq:()=>D,J:()=>w});class r{constructor(){this.children=[]}isValid(e){return!0}process(e,t){let i="";if(this.line){let r=this.line;const s=t.processor;if(s){s.lineProcessor&&(r=s.lineProcessor(r,t.isFragment,t.processingContext));const i=t.processor?.attributeKeywordName??"attribute",n=t.isFragment&&t.processor?.varyingFragmentKeywordName?t.processor?.varyingFragmentKeywordName:!t.isFragment&&t.processor?.varyingVertexKeywordName?t.processor?.varyingVertexKeywordName:"varying";!t.isFragment&&s.attributeProcessor&&this.line.startsWith(i)?r=s.attributeProcessor(this.line,e,t.processingContext):s.varyingProcessor&&(s.varyingCheck?.(this.line,t.isFragment)||!s.varyingCheck&&this.line.startsWith(n))?r=s.varyingProcessor(this.line,t.isFragment,e,t.processingContext):s.uniformProcessor&&s.uniformRegexp&&s.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(r=s.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):s.uniformBufferProcessor&&s.uniformBufferRegexp&&s.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(r=s.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):s.textureProcessor&&s.textureRegexp&&s.textureRegexp.test(this.line)?r=s.textureProcessor(this.line,t.isFragment,e,t.processingContext):(s.uniformProcessor||s.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?s.uniformProcessor&&(r=s.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):s.uniformBufferProcessor&&(r=s.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,s.endOfUniformBufferProcessor&&(r=s.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}i+=r+"\n"}return this.children.forEach((r=>{i+=r.process(e,t)})),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),i}}class s{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(e);else{const e=t.split(";");for(let t=0;t{c=c.trim(),""!==c&&(i.push(c),c="")},n=e=>{ra._Stack[r],l=()=>-1===r?"!!INVALID EXPRESSION!!":a._Stack[r--];let h=0,c="";for(;h1){for(s();-1!==r&&a._OperatorPriority[o()]>=a._OperatorPriority[u];)i.push(l());n(u),h++}else c+=t;h++}for(s();-1!==r;)"("===o()?l():i.push(l());return a._InfixToPostfixCache.size>=a.InfixToPostfixCacheLimitSize&&a.ClearCache(),a._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(a._InfixToPostfixCache.entries()).sort(((e,t)=>e[1].accessTime-t[1].accessTime));for(let t=0;t":i=r>s;break;case"<":i=r=":i=r>=s;break;case"==":i=r===s;break;case"!=":i=r!==s}return i}}var d=i(75108),f=i(2636);const p=/defined\s*?\((.+?)\)/g,_=/defined\s*?\[(.+?)\]/g,m=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,g=/__decl__/,v=/light\{X\}.(\w*)/g,x=/\{X\}/g,b=[],S=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;function T(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}function C(e,t,i,r){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),D(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e,t.defines));const s=function(e,t,i){let r=function(e,t){if(t.processor?.noPrecision)return e;const i=t.shouldUseHighPrecisionShader;return-1===e.indexOf("precision highp float")?e=i?"precision highp float;\n"+e:"precision mediump float;\n"+e:i||(e=e.replace("precision highp float","precision mediump float")),e}(e,t);if(!t.processor)return r;if(0===t.processor.shaderLanguage&&-1!==r.indexOf("#version 3")&&(r=r.replace("#version 300 es",""),!t.processor.parseGLES3))return r;const s=t.defines,n=O(t,i);return t.processor.preProcessor&&(r=t.processor.preProcessor(r,s,n,t.isFragment,t.processingContext)),r=M(r,n,t),t.processor.postProcessor&&(r=t.processor.postProcessor(r,s,t.isFragment,t.processingContext,i?{drawBuffersExtensionDisabled:!i.getCaps().drawBuffersExtension}:{})),i?._features.needShaderCodeInlining&&(r=i.inlineShaderCode(r)),r}(e,t,r);i(s,e)}))}function y(e,t,i,r){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),D(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e,t.defines));const s=function(e,t,i){let r=e;const s=t.defines,n=O(t,i);return t.processor?.preProcessor&&(r=t.processor.preProcessor(r,s,n,t.isFragment,t.processingContext)),r=M(r,n,t),t.processor?.postProcessor&&(r=t.processor.postProcessor(r,s,t.isFragment,t.processingContext,i?{drawBuffersExtensionDisabled:!i.getCaps().drawBuffersExtension}:{})),i._features.needShaderCodeInlining&&(r=i.inlineShaderCode(r)),r}(e,t,r);i(s,e)}))}function E(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}function P(e){const t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new l(t[1].trim(),"!"===e[0]);const i=["==","!=",">=","<=","<",">"];let r="",s=0;for(r of i)if(s=e.indexOf(r),s>-1)break;if(-1===s)return new l(e);const n=e.substring(0,s).trim(),o=e.substring(s+r.length).trim();return new u(n,r,o)}function A(e,t){const i=new o,r=e.substring(0,t);let s=e.substring(t);return s=s.substring(0,(s.indexOf("//")+1||s.length+1)-1).trim(),i.testExpression="#ifdef"===r?new l(s):"#ifndef"===r?new l(s,!0):function(e){e=e.replace(p,"defined[$1]");const t=a.infixToPostfix(e),i=[];for(const e of t)if("||"!==e&&"&&"!==e)i.push(e);else if(i.length>=2){let t=i[i.length-1],r=i[i.length-2];i.length-=2;const s="&&"==e?new c:new h;"string"==typeof t&&(t=t.replace(_,"defined($1)")),"string"==typeof r&&(r=r.replace(_,"defined($1)")),s.leftOperand="string"==typeof r?P(r):r,s.rightOperand="string"==typeof t?P(t):t,i.push(s)}let r=i[i.length-1];return"string"==typeof r&&(r=r.replace(_,"defined($1)")),"string"==typeof r?P(r):r}(s),i}function R(e,t,i){let s=e.currentLine;for(;I(e,i);){s=e.currentLine;const n=s.substring(0,5).toLowerCase();if("#else"===n){const i=new r;return t.children.push(i),void I(e,i)}if("#elif"===n){const e=A(s,5);t.children.push(e),i=e}}}function I(e,t){for(;e.canRead;){e.lineIndex++;const i=e.currentLine;if(i.indexOf("#")>=0){const r=S.exec(i);if(r&&r.length){switch(r[0]){case"#ifdef":{const r=new n;t.children.push(r);const s=A(i,6);r.children.push(s),R(e,r,s);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const r=new n;t.children.push(r);const s=A(i,7);r.children.push(s),R(e,r,s);break}case"#if":{const r=new n,s=A(i,3);t.children.push(r),r.children.push(s),R(e,r,s);break}}continue}}const s=new r;if(s.line=i,t.children.push(s),"#"===i[0]&&"d"===i[1]){const e=i.replace(";","").split(" ");s.additionalDefineKey=e[1],3===e.length&&(s.additionalDefineValue=e[2])}}return!1}function M(e,t,i){const n=new r,o=new s;return o.lineIndex=-1,o.lines=e.split("\n"),I(o,n),n.process(t,i)}function O(e,t){const i=e.defines,r={};for(const e of i){const t=e.replace("#define","").replace(";","").trim().split(" ");r[t[0]]=t.length>1?t[1]:""}return 0===e.processor?.shaderLanguage&&(r.GL_ES="true"),r.__VERSION__=e.version,r[e.platformName]="true",(0,f.xt)(r,t?.isNDCHalfZRange,t?.useReverseDepthBuffer,t?.useExactSrgbConversions),r}function D(e,t,i){let r;for(b.length=0;null!==(r=m.exec(e));)b.push(r);let s=String(e),n=[e],o=!1;for(const e of b){let r=e[1];if(-1!==r.indexOf("__decl__")&&(r=r.replace(g,""),t.supportsUniformBuffers&&(r=r.replace("Vertex","Ubo").replace("Fragment","Ubo")),r+="Declaration"),!t.includesShadersStore[r]){const e=t.shadersRepository+"ShadersInclude/"+r+".fx";return void w.loadFile(e,(e=>{t.includesShadersStore[r]=e,D(n.join(""),t,i)}))}{let i=t.includesShadersStore[r];if(e[2]){const t=e[3].split(",");for(let e=0;et+"{X}"))),i+=o.replace(x,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(v,((e,t)=>t+"{X}"))),i=i.replace(x,r)}const s=[];for(const t of n){const r=t.split(e[0]);for(let e=0;e=0||i.indexOf("#include <")>=0}}b.length=0,s=n.join(""),o?D(s.toString(),t,i):i(s)}const w={loadFile:(e,t,i,r,s,n)=>{throw(0,d.n)("FileTools")}}},16964:(e,t,i)=>{"use strict";i.d(t,{B:()=>s});const r=/(flat\s)?\s*varying\s*.*/;class s{constructor(){this.shaderLanguage=0}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return r.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const r=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){const t=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(r||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else if(-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e}}},96281:(e,t,i)=>{"use strict";i.d(t,{d:()=>r});class r{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))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){return this._MSAARenderBuffers?.[e]??null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}},42167:(e,t,i)=>{"use strict";i.d(t,{x:()=>r});class r{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))}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}setEngine(e){this.engine=e}_fillEffectInformation(e,t,i,r,s,n,o,a){const l=this.engine;if(l.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let h;for(this.engine.getUniforms(this,i).forEach(((e,t)=>{r[i[t]]=e})),this._uniforms=r,h=0;h{n[e]=t}));for(const e of l.getAttributes(this,o))a.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r||2!==r.length)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s||3!==s.length)return s=[t,i,r],this._valueCache[e]=s,!0;let n=!1;return s[0]!==t&&(s[0]=t,n=!0),s[1]!==i&&(s[1]=i,n=!0),s[2]!==r&&(s[2]=r,n=!0),n}_cacheFloat4(e,t,i,r,s){let n=this._valueCache[e];if(!n||4!==n.length)return n=[t,i,r,s],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]!==r&&(n[2]=r,o=!0),n[3]!==s&&(n[3]=s,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this.engine.setInt4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setUInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this.engine.setUInt4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setFloat3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this.engine.setFloat4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}},89237:(e,t,i)=>{"use strict";i.d(t,{e:()=>s});var r=i(78641);class s{constructor(){this._gpuTimeInFrameId=-1,this.counter=new r.A}_addDuration(e,t){e{"use strict";i.d(t,{W0:()=>o,iL:()=>n,kZ:()=>l,sg:()=>s,xt:()=>a});var r=i(75108);i(68191);const s={};function n(e,t,i=""){return i+(t?t+"\n":"")+e}function o(e,t,i,n,o,a,l){const h=l||s.loadFile;if(h)return h(e,t,i,n,o,a);throw(0,r.n)("FileTools")}function a(e,t,i,r){if(e)return t?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,i?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(r?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return t&&(e+="#define IS_NDC_HALF_ZRANGE"),i&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),r&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}function l(e,t,i=!1,r){switch(e){case 3:{const e=(ArrayBuffer,new Int8Array(t));return r&&e.set(new Int8Array(r)),e}case 0:{const e=(ArrayBuffer,new Uint8Array(t));return r&&e.set(new Uint8Array(r)),e}case 4:{const e=t instanceof ArrayBuffer?new Int16Array(t):new Int16Array(i?t/2:t);return r&&e.set(new Int16Array(r)),e}case 5:case 8:case 9:case 10:case 2:{const e=t instanceof ArrayBuffer?new Uint16Array(t):new Uint16Array(i?t/2:t);return r&&e.set(new Uint16Array(r)),e}case 6:{const e=t instanceof ArrayBuffer?new Int32Array(t):new Int32Array(i?t/4:t);return r&&e.set(new Int32Array(r)),e}case 7:case 11:case 12:case 13:case 14:case 15:{const e=t instanceof ArrayBuffer?new Uint32Array(t):new Uint32Array(i?t/4:t);return r&&e.set(new Uint32Array(r)),e}case 1:{const e=t instanceof ArrayBuffer?new Float32Array(t):new Float32Array(i?t/4:t);return r&&e.set(new Float32Array(r)),e}}const s=(ArrayBuffer,new Uint8Array(t));return r&&s.set(new Uint8Array(r)),s}},55935:(e,t,i)=>{"use strict";i.d(t,{$:()=>x,r:()=>v});var r=i(34268),s=i(60590),n=i(36217),o=i(82352),a=i(64736),l=i(14506),h=i(67715),c=i(69905),u=i(94895),d=i(75108),f=i(7107),p=i(68191),_=i(43279),m=i(2636),g=i(47221);function v(e,t){if((0,p.BA)()){const{requestAnimationFrame:i}=t||window;if("function"==typeof i)return i(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}class x{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,this._depthCullingState.depthFunc=e?518: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)return this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return this.isNDCHalfZRange&&(e+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}_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()}n.M.ResetCache()}_rebuildGraphicsResources(){this.wipeCaches(!0),this._rebuildEffects(),this._rebuildComputeEffects?.(),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){s.V.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}_restoreEngineAfterContextLost(e){setTimeout((async()=>{this._clearEmptyResources();const t=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,r=this._depthCullingState.depthMask,s=this._stencilState.stencilTest;await e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=r,this._stencilState.stencilTest=s,this._flagContextRestored()}),0)}get isDisposed(){return this._isDisposed}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return 0}set snapshotRenderingMode(e){}getClassName(){return"AbstractEngine"}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){const e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get activeRenderLoops(){return this._activeRenderLoops}stopRenderLoop(e){if(!e)return this._activeRenderLoops.length=0,void this._cancelFrame();const t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),0==this._activeRenderLoops.length&&this._cancelFrame())}_cancelFrame(){if(0!==this._frameHandler){const e=this._frameHandler;if(this._frameHandler=0,(0,p.BA)()){const{cancelAnimationFrame:t}=this.getHostWindow()||window;if("function"==typeof t)return t(e)}else if("function"==typeof cancelAnimationFrame)return cancelAnimationFrame(e);return clearTimeout(e)}}beginFrame(){this.onBeginFrameObservable.notifyObservers(this)}endFrame(){this._frameId++,this.onEndFrameObservable.notifyObservers(this)}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&0===this._frameHandler&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}_renderFrame(){for(let e=0;e-1?e.substring(P).toLowerCase():"");A.indexOf("?")>-1&&(A=A.split("?")[0]);const R=(0,g.gT)(A,m);n&&n.addPendingData(y),y.url=e,y.generateMipMaps=!t,y.samplingMode=o,y.invertY=i,y._useSRGBBuffer=this._getUseSRGBBuffer(!!b,t),this._doNotHandleContextLost||(y._buffer=u);let I=null;a&&!d&&(I=y.onLoadedObservable.add(a)),d||this._internalTexturesCache.push(y);const M=(i,d)=>{n&&n.removePendingData(y),e===E?(I&&y.onLoadedObservable.remove(I),r.q.UseFallbackTexture&&e!==r.q.FallbackTexture&&this._createTextureBase(r.q.FallbackTexture,t,y.invertY,n,o,null,l,h,c,u,y),i=(i||"Unknown error")+(r.q.UseFallbackTexture?" - Fallback texture was used":""),y.onErrorObservable.notifyObservers({message:i,exception:d}),l&&l(i,d)):(s.V.Warn(`Failed to load ${e}, falling back to ${E}`),this._createTextureBase(E,t,y.invertY,n,o,a,l,h,c,u,y,p,_,m,v,b))};if(R){const t=async e=>{(await R).loadData(e,y,((e,t,i,r,s,a)=>{a?M("TextureLoader failed to load data"):h(y,A,n,{width:e,height:t},y.invertY,!i,r,(()=>(s(),!1)),o)}),v)};u?u instanceof ArrayBuffer?t(new Uint8Array(u)):ArrayBuffer.isView(u)?t(u):l&&l("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,(e=>t(new Uint8Array(e))),void 0,n?n.offlineProvider:void 0,!0,((e,t)=>{M("Unable to load "+(e&&e.responseURL,t))}))}else{const i=e=>{T&&!this._doNotHandleContextLost&&(y._buffer=e),h(y,A,n,e,y.invertY,t,!1,c,o)};!S||C?u&&("string"==typeof u.decoding||u.close)?i(u):x._FileToolsLoadImage(e||"",i,M,n?n.offlineProvider:null,m,y.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof u||u instanceof ArrayBuffer||ArrayBuffer.isView(u)||u instanceof Blob?x._FileToolsLoadImage(u,i,M,n?n.offlineProvider:null,m,y.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):u&&i(u)}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:(0,p.Nf)()?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.35.2"}static get Version(){return"7.35.2"}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){this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new l.N,this._stencilStateComposer=new h.u,this._stencilState=new c.K,this._alphaState=new u.i,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 _.cP,this.onCanvasFocusObservable=new _.cP,this.onNewSceneAddedObservable=new _.cP,this.onResizeObservable=new _.cP,this.onCanvasPointerOutObservable=new _.cP,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 _.cP,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=()=>this._renderLoop(),this.onBeforeShaderCompilationObservable=new _.cP,this.onAfterShaderCompilationObservable=new _.cP,this.onBeginFrameObservable=new _.cP,this.onEndFrameObservable=new _.cP,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new _.cP,this.onContextRestoredObservable=new _.cP,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 _.cP,r.q.Instances.push(this),this.startTime=a.j.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,o.I.SetMatrixPrecision(!!t.useHighPrecisionMatrix),(0,p.XD)()&&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=t.audioEngineOptions?.audioContext??null,this._audioDestination=t.audioEngineOptions?.audioDestination??null,this.premultipliedAlpha=t.premultipliedAlpha??!0,this._doNotHandleContextLost=!!t.doNotHandleContextLost,this._isStencilEnable=!!t.stencil,this.useExactSrgbConversions=t.useExactSrgbConversions??!1;const s=(0,p.BA)()&&window.devicePixelRatio||1,n=t.limitDeviceRatio||s;i=i||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=i?1/Math.min(n,s):1,this._lastDevicePixelRatio=s,this._creationOptions=t}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const e=(0,p.BA)()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}if((0,p.BA)()&&(0,p.Nf)())if(this._renderingCanvas){const e=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||e.width||this._renderingCanvas.width||100,i=this._renderingCanvas.clientHeight||e.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)return!1;if(e|=0,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 e=0;e{const e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&(0,p.Nf)()&&"ontouchend"in document},this._checkForMobile(),(0,p.BA)()&&window.addEventListener("resize",this._checkForMobile))}createVideoElement(e){return document.createElement("video")}_reportDrawCall(e=1){this._drawCalls?.addCount(e,!1)}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return 1e3*this._timeStep}_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("undefined"==typeof document)return new OffscreenCanvas(e,t);const i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return x._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,i,r,s,n){throw(0,d.n)("FileTools")}_loadFile(e,t,i,r,s,n){const o=(0,m.W0)(e,t,i,r,s,n);return this._activeRequests.push(o),o.onCompleteObservable.add((()=>{const e=this._activeRequests.indexOf(o);-1!==e&&this._activeRequests.splice(e,1)})),o}static _FileToolsLoadFile(e,t,i,r,s,n){if(m.sg.loadFile)return m.sg.loadFile(e,t,i,r,s,n);throw(0,d.n)("FileTools")}dispose(){for(this.releaseEffects(),this._isDisposed=!0,this.stopRenderLoop(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._renderingCanvas=null,this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(;this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();this.releaseComputeEffects?.(),n.M.ResetCache();for(const e of this._activeRequests)e.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(),(0,p.BA)()&&window.removeEventListener("resize",this._checkForMobile);const e=r.q.Instances.indexOf(this);e>=0&&r.q.Instances.splice(e,1),r.q.Instances.length||(r.q.OnEnginesDisposedObservable.notifyObservers(this),r.q.OnEnginesDisposedObservable.clear()),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw(0,d.n)("LoadingScreen")}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{"use strict";i.d(t,{q:()=>s});var r=i(43279);class s{static get LastCreatedEngine(){return 0===this.Instances.length?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}}s.Instances=[],s.OnEnginesDisposedObservable=new r.cP,s._LastCreatedScene=null,s.UseFallbackTexture=!0,s.FallbackTexture=""},82352:(e,t,i)=>{"use strict";i.d(t,{I:()=>r});class r{static SetMatrixPrecision(e){if(r.MatrixTrackPrecisionChange=!1,e&&!r.MatrixUse64Bits&&r.MatrixTrackedMatrices)for(let e=0;e{"use strict";i.d(t,{l:()=>r});class r{static GetShadersRepository(e=0){return 0===e?r.ShadersRepository:r.ShadersRepositoryWGSL}static GetShadersStore(e=0){return 0===e?r.ShadersStore:r.ShadersStoreWGSL}static GetIncludesShadersStore(e=0){return 0===e?r.IncludesShadersStore:r.IncludesShadersStoreWGSL}}r.ShadersRepository="src/Shaders/",r.ShadersStore={},r.IncludesShadersStore={},r.ShadersRepositoryWGSL="src/ShadersWGSL/",r.ShadersStoreWGSL={},r.IncludesShadersStoreWGSL={}},66593:(e,t,i)=>{"use strict";i.d(t,{C5:()=>g,Cm:()=>l,EX:()=>c,GX:()=>u,N5:()=>a,YM:()=>p,bS:()=>v,kf:()=>h,tI:()=>d,tg:()=>f});var r=i(42167),s=i(2636);const n=new WeakMap,o={_webGLVersion:2,cachedPipelines:{}};function a(e){let t=n.get(e);if(!t){if(!e)return o;t={_webGLVersion:e.TEXTURE_BINDING_3D?2:1,_context:e,cachedPipelines:{}},n.set(e,t)}return t}function l(e){n.delete(e)}function h(e,t,i,r,s,n){const o=a(r);return n||(n=o._createShaderProgramInjection??d),n(e,m(t,"vertex",r,o._contextWasLost),m(i,"fragment",r,o._contextWasLost),r,s,o.validateShaderPrograms)}function c(e,t,i,r,s,n=null,o){const l=a(s);o||(o=l._createShaderProgramInjection??d);const h=l._webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"";return o(e,_(t,"vertex",r,h,s,l._contextWasLost),_(i,"fragment",r,h,s,l._contextWasLost),s,n,l.validateShaderPrograms)}function u(e,t){const i=new r.x,s=a(e);return s.parallelShaderCompile&&(i.isParallelCompiled=!0),i.context=s._context,i}function d(e,t,i,r,s=null,n){const o=r.createProgram();if(e.program=o,!o)throw new Error("Unable to create program");return r.attachShader(o,t),r.attachShader(o,i),r.linkProgram(o),e.context=r,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||f(e,r,n),o}function f(e,t,i){const r=e.context,s=e.vertexShader,n=e.fragmentShader,o=e.program;if(!r.getProgramParameter(o,r.LINK_STATUS)){if(!t.getShaderParameter(s,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(s);if(i)throw e.vertexCompilationError=i,new Error("VERTEX SHADER "+i)}if(!t.getShaderParameter(n,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(n);if(i)throw e.fragmentCompilationError=i,new Error("FRAGMENT SHADER "+i)}const i=r.getProgramInfoLog(o);if(i)throw e.programLinkError=i,new Error(i)}if(i&&(r.validateProgram(o),!r.getProgramParameter(o,r.VALIDATE_STATUS))){const t=r.getProgramInfoLog(o);if(t)throw e.programValidationError=t,new Error(t)}r.deleteShader(s),r.deleteShader(n),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}function p(e,t,i,r,s,n,o,l,u,d="",f,p,_){const m=a(e.context);p||(p=m.createRawShaderProgramInjection??h),_||(_=m.createShaderProgramInjection??c);const g=e;g.program=r?p(g,t,i,g.context,u):_(g,t,i,l,g.context,u),g.program.__SPECTOR_rebuildProgram=o,f()}function _(e,t,i,r,n,o){return m((0,s.iL)(e,i,r),t,n,o)}function m(e,t,i,r){const s=i.createShader("vertex"===t?i.VERTEX_SHADER:i.FRAGMENT_SHADER);if(!s){let e=i.NO_ERROR,s=i.NO_ERROR;for(;(s=i.getError())!==i.NO_ERROR;)e=s;throw new Error(`Something went wrong while creating a gl ${t} shader object. gl error=${e}, gl isContextLost=${i.isContextLost()}, _contextWasLost=${r}`)}return i.shaderSource(s,e),i.compileShader(s),s}function g(e,t){t.useProgram(e)}function v(e,t){const i=e;if(!i.isParallelCompiled)return void t(e);const r=i.onCompiled;i.onCompiled=()=>{r?.(),t(e)}}},722:(e,t,i)=>{"use strict";i.r(t),i.d(t,{ThinEngine:()=>v});var r=i(66593),s=i(61340),n=i(60590),o=i(68191);class a{constructor(){this.shaderLanguage=0}postProcessor(e,t,i,r,s){if(s.drawBuffersExtensionDisabled){const t=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(t,"")}return e}}var l=i(16964),h=i(7240),c=i(44512),u=i(55935),d=i(96281),f=i(7107),p=i(36217),_=i(2636),m=i(73010);class g{}class v extends u.${get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return p.M.ShadersRepository}static set ShadersRepository(e){p.M.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 o=null;if(e.getContext){if(o=e,this._renderingCanvas=o,void 0===i.preserveDrawingBuffer&&(i.preserveDrawingBuffer=!1),void 0===i.xrCompatible&&(i.xrCompatible=!1),navigator&&navigator.userAgent){this._setupMobileChecks();const e=navigator.userAgent;for(const t of v.ExceptionList){const r=t.key,s=t.targets;if(new RegExp(r).test(e)){if(t.capture&&t.captureConstraint){const i=t.capture,r=t.captureConstraint,s=new RegExp(i).exec(e);if(s&&s.length>0&&parseInt(s[s.length-1])>=r)continue}for(const e of s)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost||(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,n.V.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost((()=>this._initGLContext()))},o.addEventListener("webglcontextlost",this._onContextLost,!1),o.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=o.getContext("webgl2",i)||o.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!o)throw new Error("The provided canvas is null or undefined.");try{this._gl=o.getContext("webgl",i)||o.getContext("experimental-webgl",i)}catch(e){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 t=this._gl.getContextAttributes();t&&(i.stencil=t.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==i.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e1?new l.B:new a;const h=`Babylon.js v${v.Version}`;n.V.Log(h+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",h);const c=(0,r.N5)(this._gl);c.validateShaderPrograms=this.validateShaderPrograms,c.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||null!==this._gl.getExtension("OES_standard_derivatives"),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||null!==this._gl.getExtension("OES_element_index_uint"),fragmentDepthSupported:this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),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:1!==this._webGLVersion,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(null!=e&&(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"),36193!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=36193),34842!==this._gl.RGBA16F&&(this._gl.RGBA16F=34842),34836!==this._gl.RGBA32F&&(this._gl.RGBA32F=34836),35056!==this._gl.DEPTH24_STENCIL8&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(1===this._webGLVersion&&(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&&5131!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=null!==this._maxMSAASamplesOverride?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES),this._caps.maxDrawBuffers=this._gl.getParameter(this._gl.MAX_DRAW_BUFFERS);else{const e=this._gl.getExtension("WEBGL_draw_buffers");if(null!==e){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=e.drawBuffersWEBGL.bind(e),this._caps.maxDrawBuffers=this._gl.getParameter(e.MAX_DRAW_BUFFERS_WEBGL),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let t=0;t<16;t++)this._gl["COLOR_ATTACHMENT"+t+"_WEBGL"]=e["COLOR_ATTACHMENT"+t+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const e=this._gl.getExtension("WEBGL_depth_texture");null!=e&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=e.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const e=this._gl.getExtension("OES_vertex_array_object");null!=e&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=e.createVertexArrayOES.bind(e),this._gl.bindVertexArray=e.bindVertexArrayOES.bind(e),this._gl.deleteVertexArray=e.deleteVertexArrayOES.bind(e))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const e=this._gl.getExtension("ANGLE_instanced_arrays");null!=e?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=e.drawArraysInstancedANGLE.bind(e),this._gl.drawElementsInstanced=e.drawElementsInstancedANGLE.bind(e),this._gl.vertexAttribDivisor=e.vertexAttribDivisorANGLE.bind(e)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const e=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),t=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);e&&t&&(this._caps.highPrecisionShaderSupported=0!==e.precision&&0!==t.precision)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const e=this._gl.getExtension("EXT_blend_minmax");null!=e&&(this._caps.blendMinMax=!0,this._gl.MAX=e.MAX_EXT,this._gl.MIN=e.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 e=this._gl.getExtension("EXT_sRGB");null!=e&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:e.SRGB_EXT,SRGB8:e.SRGB_ALPHA_EXT,SRGB8_ALPHA8:e.SRGB_ALPHA_EXT})}if(this._creationOptions){const e=this._creationOptions.forceSRGBBufferSupportState;void 0!==e&&(this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&e)}}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let e=0;e=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){const r=e.program,s=this._gl.getUniformBlockIndex(r,t);this._gl.uniformBlockBinding(r,s,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,r,s,n,o){const a=this._currentBufferPointers[t];if(!a)return;let l=!1;a.active?(a.buffer!==e&&(a.buffer=e,l=!0),a.size!==i&&(a.size=i,l=!0),a.type!==r&&(a.type=r,l=!0),a.normalized!==s&&(a.normalized=s,l=!0),a.stride!==n&&(a.stride=n,l=!0),a.offset!==o&&(a.offset=o,l=!0)):(l=!0,a.active=!0,a.index=t,a.size=i,a.type=r,a.normalized=s,a.stride=n,a.offset=o,a.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),r===this._gl.UNSIGNED_INT||r===this._gl.INT?this._gl.vertexAttribIPointer(t,i,r,n,o):this._gl.vertexAttribPointer(t,i,r,s,n,o))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const r=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let s=0;s=0){const t=r[s];let o=null;if(i&&(o=i[t]),o||(o=e[t]),!o)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);const a=o.getBuffer();a&&(this._vertexAttribPointer(a,n,o.getSize(),o.type,o.normalized,o.byteStride,o.byteOffset),o.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,o.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(a))))}}}recordVertexArrayObject(e,t,i,r){const s=this._gl.createVertexArray();if(!s)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(s),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,r),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),s}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,r,s){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==s){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=s;const t=s.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let n=0;for(let o=0;o=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,i[o],this._gl.FLOAT,!1,r,n)),n+=4*i[o]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,r){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===i||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,r)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t1||this.isWebGPU)),(1!==a||this._caps.textureFloatLinearFiltering)&&(2!==a||this._caps.textureHalfFloatLinearFiltering)||(l=1),1!==a||this._caps.textureFloat||(a=0,n.V.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const d=this._gl,p=new f.h(this,r),_=e.width||e,m=e.height||e,g=e.depth||0,v=e.layers||0,x=this._getSamplingParameters(l,o),b=0!==v?d.TEXTURE_2D_ARRAY:0!==g?d.TEXTURE_3D:d.TEXTURE_2D,S=this._getRGBABufferInternalSizedFormat(a,h,c),T=this._getInternalFormat(h),C=this._getWebGLTextureType(a);return this._bindTextureDirectly(b,p),0!==v?(p.is2DArray=!0,d.texImage3D(b,0,S,_,m,v,0,T,C,null)):0!==g?(p.is3D=!0,d.texImage3D(b,0,S,_,m,g,0,T,C,null)):d.texImage2D(b,0,S,_,m,0,T,C,null),d.texParameteri(b,d.TEXTURE_MAG_FILTER,x.mag),d.texParameteri(b,d.TEXTURE_MIN_FILTER,x.min),d.texParameteri(b,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(b,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),o&&this._gl.generateMipmap(b),this._bindTextureDirectly(b,null),p._useSRGBBuffer=c,p.baseWidth=_,p.baseHeight=m,p.width=_,p.height=m,p.depth=v,p.isReady=!0,p.samples=u,p.generateMipMaps=o,p.samplingMode=l,p.type=a,p.format=h,p.label=s,this._internalTexturesCache.push(p),p}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)}createTexture(e,t,i,r,s=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,p,_){return this._createTextureBase(e,t,i,r,s,n,o,((...e)=>this._prepareWebGLTexture(...e,h)),((e,t,i,s,n,o)=>{const a=this._gl,l=i.width===e&&i.height===t;n._creationFlags=p??0;const h=this._getTexImageParametersForCreateTexture(n.format,n._useSRGBBuffer);if(l)return a.texImage2D(a.TEXTURE_2D,0,h.internalFormat,h.format,h.type,i),!1;const c=this._caps.maxTextureSize;if(i.width>c||i.height>c||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!(!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(i,0,0,i.width,i.height,0,0,e,t),a.texImage2D(a.TEXTURE_2D,0,h.internalFormat,h.format,h.type,this._workingCanvas),n.width=e,n.height=t,1));{const e=new f.h(this,2);this._bindTextureDirectly(a.TEXTURE_2D,e,!0),a.texImage2D(a.TEXTURE_2D,0,h.internalFormat,h.format,h.type,i),this._rescaleTexture(e,n,r,h.format,(()=>{this._releaseTexture(e),this._bindTextureDirectly(a.TEXTURE_2D,n,!0),o()}))}return!0}),a,l,h,c,u,d,_)}_getTexImageParametersForCreateTexture(e,t){let i,r;return 1===this.webGLVersion?(i=this._getInternalFormat(e,t),r=i):(i=this._getInternalFormat(e,!1),r=this._getRGBABufferInternalSizedFormat(0,e,t)),{internalFormat:r,format:i,type:this._gl.UNSIGNED_BYTE}}_rescaleTexture(e,t,i,r,s){}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){const r=this._getTextureTarget(t),s=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(r,this._gl.TEXTURE_MAG_FILTER,s.mag,t),this._setTextureParameterInteger(r,this._gl.TEXTURE_MIN_FILTER,s.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(r)),this._bindTextureDirectly(r,null),t.samplingMode=e}updateTextureDimensions(e,t,i,r=1){}updateTextureWrappingMode(e,t,i=null,r=null){const s=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==i&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==r&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(r),e),e._cachedWrapR=r),this._bindTextureDirectly(s,null)}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,n=0,o=0){const a=this._gl;let l=a.TEXTURE_2D;if(e.isCube&&(l=a.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=a.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(l,o,t,i,r,0,s)}_uploadDataToTextureDirectly(e,t,i=0,r=0,s,n=!1){const o=this._gl,a=this._getWebGLTextureType(e.type),l=this._getInternalFormat(e.format),h=void 0===s?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(s,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let c=o.TEXTURE_2D;e.isCube&&(c=o.TEXTURE_CUBE_MAP_POSITIVE_X+i);const u=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),f=n?e.width:Math.pow(2,Math.max(u-r,0)),p=n?e.height:Math.pow(2,Math.max(d-r,0));o.texImage2D(c,r,h,f,p,0,l,a,t)}updateTextureData(e,t,i,r,s,n,o=0,a=0,l=!1){const h=this._gl,c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=h.TEXTURE_2D,f=h.TEXTURE_2D;e.isCube&&(f=h.TEXTURE_CUBE_MAP_POSITIVE_X+o,d=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),h.texSubImage2D(f,a,i,r,s,n,u,c,t),l&&this._gl.generateMipmap(f),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){const s=this._gl,n=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,i,r),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,i,r,s){const n=this._gl;if(!n)return;const o=this._getSamplingParameters(s,!i);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,o.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,o.min),i||r||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,r,s,n,o,a,l,h){const u=this.getCaps().maxTextureSize,d=Math.min(u,this.needPOTTextures?(0,c.R)(r.width,u):r.width),f=Math.min(u,this.needPOTTextures?(0,c.R)(r.height,u):r.height),p=this._gl;p&&(e._hardwareTexture?(this._bindTextureDirectly(p.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===s||!!s),e.baseWidth=r.width,e.baseHeight=r.height,e.width=d,e.height=f,e.isReady=!0,e.type=-1!==e.type?e.type:0,e.format=-1!==e.format?e.format:h??(".jpg"!==t||e._useSRGBBuffer?5:4),a(d,f,r,t,e,(()=>{this._prepareWebGLTextureContinuation(e,i,n,o,l)}))||this._prepareWebGLTextureContinuation(e,i,n,o,l)):i&&i.removePendingData(e))}_getInternalFormatFromDepthTextureFormat(e,t,i){const r=this._gl;if(!t)return r.STENCIL_INDEX8;let s=i?r.DEPTH_STENCIL:r.DEPTH_COMPONENT;return this.webGLVersion>1?15===e?s=r.DEPTH_COMPONENT16:16===e?s=r.DEPTH_COMPONENT24:17===e||13===e?s=i?r.DEPTH24_STENCIL8:r.DEPTH_COMPONENT24:14===e?s=r.DEPTH_COMPONENT32F:18===e&&(s=i?r.DEPTH32F_STENCIL8:r.DEPTH_COMPONENT32F):s=r.DEPTH_COMPONENT16,s}_setupFramebufferDepthAttachments(e,t,i,r,s=1,n){const o=this._gl;n=n??(e?13:14);const a=this._getInternalFormatFromDepthTextureFormat(n,t,e);return e&&t?this._createRenderBuffer(i,r,s,o.DEPTH_STENCIL,a,o.DEPTH_STENCIL_ATTACHMENT):t?this._createRenderBuffer(i,r,s,a,a,o.DEPTH_ATTACHMENT):e?this._createRenderBuffer(i,r,s,a,a,o.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,r,s,n,o=!0){const a=this._gl.createRenderbuffer();return this._updateRenderBuffer(a,e,t,i,r,s,n,o)}_updateRenderBuffer(e,t,i,r,s,n,o,a=!0){const l=this._gl;return l.bindRenderbuffer(l.RENDERBUFFER,e),r>1&&l.renderbufferStorageMultisample?l.renderbufferStorageMultisample(l.RENDERBUFFER,r,n,t,i):l.renderbufferStorage(l.RENDERBUFFER,s,t,i),l.framebufferRenderbuffer(l.FRAMEBUFFER,o,l.RENDERBUFFER,e),a&&l.bindRenderbuffer(l.RENDERBUFFER,null),e}_releaseTexture(e){this._deleteTexture(e._hardwareTexture),this.unbindAllTextures();const t=this._internalTexturesCache.indexOf(e);-1!==t&&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?.release()}_setProgram(e){this._currentProgram!==e&&((0,r.C5)(e,this._gl),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let t=0;t-1;if(i&&o&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||r){if(this._activateCurrentTexture(),t&&t.isMultiview)throw n.V.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,t?._hardwareTexture?.underlyingResource??null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(s=!0,this._activateCurrentTexture());return o&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),s}_bindTexture(e,t,i){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;const r=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(r,t)}unbindAllTextures(){for(let e=0;e1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,r){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){const i=this._boundUniforms[e];i&&i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,r=!1,s=""){if(!t)return null!=this._boundTexturesCache[e]&&(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 i=t.getInternalTexture();i&&(i._associatedChannel=e),t.update()}else if(4===t.delayLoadState)return t.delayLoad(),!1;let n;n=r?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray: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 a=this._getTextureTarget(n);if(o&&this._bindTextureDirectly(a,n,i),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;const e=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=e,t.wrapV=e}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(a,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,r){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(let t=0;t=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){const e=Object.keys(this._compiledEffects);for(const t of e)this._compiledEffects[t].dispose();this._compiledEffects={}}dispose(){(0,o.BA)()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored))),super.dispose(),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.unbindAllAttributes(),this._boundUniforms={},this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._currentProgram=null,this._creationOptions.loseContextOnDispose&&this._gl.getExtension("WEBGL_lose_context")?.loseContext(),(0,r.Cm)(this._gl)}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){const t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0;const r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);const s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,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 e=t.RGBA,r=t.UNSIGNED_BYTE,s=new Uint8Array(4);t.readPixels(0,0,1,1,e,r,s),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(r),t.deleteFramebuffer(s),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(1===this._webGLVersion){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}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}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(1===this._webGLVersion){if(void 0!==t)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;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;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;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;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;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;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:default:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}readPixels(e,t,i,r,s=!0,n=!0){const o=s?4:3,a=s?this._gl.RGBA:this._gl.RGB,l=new Uint8Array(r*i*o);return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,r,a,this._gl.UNSIGNED_BYTE,l),Promise.resolve(l)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(null!==this._HasMajorPerformanceCaveat)return!this._HasMajorPerformanceCaveat;if(null===this._IsSupported)try{const e=u.$._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=null!=t&&!!window.WebGLRenderingContext}catch(e){this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(null===this._HasMajorPerformanceCaveat)try{const e=u.$._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch(e){this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}}v._TempClearColorUint32=new Uint32Array(4),v._TempClearColorInt32=new Int32Array(4),v.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"]}],v._ConcatenateShader=_.iL,v._IsSupported=null,v._HasMajorPerformanceCaveat=null},7474:(e,t,i)=>{"use strict";var r;i.d(t,{b:()=>r,s:()=>s}),function(e){e[e.PointerMove=0]="PointerMove",e[e.PointerDown=1]="PointerDown",e[e.PointerUp=2]="PointerUp"}(r||(r={}));class s{}s.DOM_DELTA_PIXEL=0,s.DOM_DELTA_LINE=1,s.DOM_DELTA_PAGE=2},80109:(e,t,i)=>{"use strict";i.d(t,{Bu:()=>n,TB:()=>r,W0:()=>s});class r{}r.KEYDOWN=1,r.KEYUP=2;class s{constructor(e,t){this.type=e,this.event=t}}class n extends s{get skipOnPointerObservable(){return this.skipOnKeyboardObservable}set skipOnPointerObservable(e){this.skipOnKeyboardObservable=e}constructor(e,t){super(e,t),this.type=e,this.event=t,this.skipOnKeyboardObservable=!1}}},1241:(e,t,i)=>{"use strict";i.d(t,{Vn:()=>n,Zp:()=>s,mx:()=>a,tT:()=>o});var r=i(94212);class s{}s.POINTERDOWN=1,s.POINTERUP=2,s.POINTERMOVE=4,s.POINTERWHEEL=8,s.POINTERPICK=16,s.POINTERTAP=32,s.POINTERDOUBLETAP=64;class n{constructor(e,t){this.type=e,this.event=t}}class o extends n{constructor(e,t,i,s){super(e,t),this.ray=null,this.originalPickingInfo=null,this.skipOnPointerObservable=!1,this.localPosition=new r.I9(i,s)}}class a extends n{get pickInfo(){return this._pickInfo||this._generatePickInfo(),this._pickInfo}constructor(e,t,i,r=null){super(e,t),this._pickInfo=i,this._inputManager=r}_generatePickInfo(){this._inputManager&&(this._pickInfo=this._inputManager._pickMove(this.event),this._inputManager._setRayOnPointerInfo(this._pickInfo,this.event),this._inputManager=null)}}},14952:(e,t,i)=>{"use strict";i.d(t,{c:()=>r});class r{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}r.FALLOFF_DEFAULT=0,r.FALLOFF_PHYSICAL=1,r.FALLOFF_GLTF=2,r.FALLOFF_STANDARD=3,r.LIGHTMAP_DEFAULT=0,r.LIGHTMAP_SPECULAR=1,r.LIGHTMAP_SHADOWSONLY=2,r.INTENSITYMODE_AUTOMATIC=0,r.INTENSITYMODE_LUMINOUSPOWER=1,r.INTENSITYMODE_LUMINOUSINTENSITY=2,r.INTENSITYMODE_ILLUMINANCE=3,r.INTENSITYMODE_LUMINANCE=4,r.LIGHTTYPEID_POINTLIGHT=0,r.LIGHTTYPEID_DIRECTIONALLIGHT=1,r.LIGHTTYPEID_SPOTLIGHT=2,r.LIGHTTYPEID_HEMISPHERICLIGHT=3},1649:(e,t,i)=>{"use strict";i.d(t,{FG:()=>a,Kq:()=>b,ZR:()=>p,tb:()=>x});var r=i(68907),s=i(85260);const n=32768,o=65535;function a(e,t){let i=0;for(let r=0;r>3]&1<<(7&r))&&(t[i++]=r);const r=i-1;for(;i>(i-=e)&(1<>(r-=8);if(e=new Uint8Array([e])[0],a.value+e>l)return null;const t=o[a.value-1];for(;e-- >0;)o[a.value++]=t}else{if(!(a.value>6}function p(e,t,i,n,o,a){const p=i.value,_=(0,r.PX)(t,i),m=(0,r.PX)(t,i);i.value+=4;const g=(0,r.PX)(t,i);if(i.value+=4,_<0||_>=s.U0||m<0||m>=s.U0)throw new Error("Wrong HUF_ENCSIZE");const v=new Array(s.U0),x=new Array(s.A_);if(function(e){for(let t=0;ti)return;let u=l(6,h,c,e,a);const d=u.l;if(h=u.c,c=u.lc,o[r]=d,d==s.Hh){if(a.value-t.value>i)throw new Error("Error in HufUnpackEncTable");u=l(8,h,c,e,a);let d=u.l+s.gn;if(h=u.c,c=u.lc,r+d>n+1)throw new Error("Error in HufUnpackEncTable");for(;d--;)o[r++]=0;r--}else if(d>=s.LU){let e=d-s.LU+2;if(r+e>n+1)throw new Error("Error in HufUnpackEncTable");for(;e--;)o[r++]=0;r--}}!function(e){for(let e=0;e<=58;++e)u[e]=0;for(let t=0;t0;--e){const i=t+u[e]>>1;u[e]=t,t=i}for(let t=0;t0&&(e[t]=i|u[i]++<<6)}}(o)}(e,i,n-(i.value-p),_,m,v),g>8*(n-(i.value-p)))throw new Error("Wrong hufUncompress");!function(e,t,i,r){for(;t<=i;t++){const i=f(e[t]),n=d(e[t]);if(i>>n)throw new Error("Invalid table entry");if(n>s.LK){const e=r[i>>n-s.LK];if(e.len)throw new Error("Invalid table entry");if(e.lit++,e.p){const t=e.p;e.p=new Array(e.lit);for(let i=0;i0;o--){const o=r[(i<=s.LK;){const a=t[p>>_-s.LK&s.lR];if(a.len){_-=a.len;const e=c(a.lit,o,p,_,i,r,l,u,m);e&&(p=e.c,_=e.lc)}else{if(!a.p)throw new Error("hufDecode issues");let t;for(t=0;t=s&&f(e[a.p[t]])==(p>>_-s&(1<>=v,_-=v;_>0;){const e=t[p<32767?t-65536:t}function g(e,t){const i=m(e),r=m(t),s=i+(1&r)+(r>>1);return{a:s,b:s-r}}function v(e,t){const i=_(e),r=_(t),s=i-(r>>1)&o;return{a:r+s-n&o,b:s}}function x(e,t,i,r,s,n,o){const a=o<16384,l=i>s?s:i;let h,c,u=1;for(;u<=l;)u<<=1;for(u>>=1,h=u,u>>=1;u>=1;){c=0;const o=c+n*(s-h),l=n*u,d=n*h,f=r*u,p=r*h;let _,m,x,b;for(;c<=o;c+=d){let s=c;const n=c+r*(i-h);for(;s<=n;s+=p){const i=s+f,r=s+l,n=r+f;if(a){let o=g(e[s+t],e[r+t]);_=o.a,x=o.b,o=g(e[i+t],e[n+t]),m=o.a,b=o.b,o=g(_,m),e[s+t]=o.a,e[i+t]=o.b,o=g(x,b),e[r+t]=o.a,e[n+t]=o.b}else{let o=v(e[s+t],e[r+t]);_=o.a,x=o.b,o=v(e[i+t],e[n+t]),m=o.a,b=o.b,o=v(_,m),e[s+t]=o.a,e[i+t]=o.b,o=v(x,b),e[r+t]=o.a,e[n+t]=o.b}}if(i&u){const i=s+l;let r;r=a?g(e[s+t],e[i+t]):v(e[s+t],e[i+t]),_=r.a,e[i+t]=r.b,e[s+t]=_}}if(s&u){let s=c;const n=c+r*(i-h);for(;s<=n;s+=p){const i=s+f;let r;r=a?g(e[s+t],e[i+t]):v(e[s+t],e[i+t]),_=r.a,e[i+t]=r.b,e[s+t]=_}}h=u,u>>=1}return c}function b(e,t,i){for(let r=0;r{"use strict";i.d(t,{S4:()=>a,VE:()=>h,_k:()=>c,r:()=>l,tg:()=>u});var r=i(1649),s=i(91727),n=i(68907),o=i(85260);function a(e){return new DataView(e.array.buffer,e.offset.value,e.size)}function l(e){const t=e.viewer.buffer.slice(e.offset.value,e.offset.value+e.size),i=new Uint8Array((0,s._)(t)),r=new Uint8Array(i.length);return(0,n.XE)(i),(0,n.KA)(i,r),new DataView(r.buffer)}function h(e){const t=e.array.slice(e.offset.value,e.offset.value+e.size),i=fflate.unzlibSync(t),r=new Uint8Array(i.length);return(0,n.XE)(i),(0,n.KA)(i,r),new DataView(r.buffer)}function c(e){const t=e.array.slice(e.offset.value,e.offset.value+e.size),i=fflate.unzlibSync(t),r=e.lines*e.channels*e.width,s=1==e.type?new Uint16Array(r):new Uint32Array(r);let n=0,o=0;const a=new Array(4);for(let t=0;t=o.cQ)throw new Error("Wrong PIZ_COMPRESSION BITMAP_SIZE");if(c<=u)for(let e=0;e{"use strict";function r(e){let t=e.byteLength;const i=new Array;let r=0;const s=new DataView(e);for(;t>0;){const e=s.getInt8(r++);if(e<0){const n=-e;t-=n+1;for(let e=0;er})},9668:(e,t,i)=>{"use strict";var r;i.d(t,{V:()=>r,u:()=>s}),function(e){e[e.Float=0]="Float",e[e.HalfFloat=1]="HalfFloat"}(r||(r={}));class s{}s.DefaultOutputType=r.HalfFloat,s.FFLATEUrl="https://unpkg.com/fflate@0.8.2"},68907:(e,t,i)=>{"use strict";i.d(t,{Ff:()=>_,Jn:()=>d,KA:()=>b,LD:()=>m,PX:()=>c,Sn:()=>g,T$:()=>l,XE:()=>x,_S:()=>u,cL:()=>h,fz:()=>f,he:()=>r,tB:()=>p,zX:()=>v});var r,s,n=i(56984),o=i(85260);!function(e){e[e.NO_COMPRESSION=0]="NO_COMPRESSION",e[e.RLE_COMPRESSION=1]="RLE_COMPRESSION",e[e.ZIPS_COMPRESSION=2]="ZIPS_COMPRESSION",e[e.ZIP_COMPRESSION=3]="ZIP_COMPRESSION",e[e.PIZ_COMPRESSION=4]="PIZ_COMPRESSION",e[e.PXR24_COMPRESSION=5]="PXR24_COMPRESSION"}(r||(r={})),function(e){e[e.INCREASING_Y=0]="INCREASING_Y",e[e.DECREASING_Y=1]="DECREASING_Y"}(s||(s={}));const a=function(){const e=new ArrayBuffer(4),t=new Float32Array(e),i=new Uint32Array(e),r=new Uint32Array(512),s=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-27?(r[e]=0,r[256|e]=32768,s[e]=24,s[256|e]=24):t<-14?(r[e]=1024>>-t-14,r[256|e]=1024>>-t-14|32768,s[e]=-t-1,s[256|e]=-t-1):t<=15?(r[e]=t+15<<10,r[256|e]=t+15<<10|32768,s[e]=13,s[256|e]=13):t<128?(r[e]=31744,r[256|e]=64512,s[e]=24,s[256|e]=24):(r[e]=31744,r[256|e]=64512,s[e]=13,s[256|e]=13)}const n=new Uint32Array(2048),o=new Uint32Array(64),a=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,i=0;for(;!(8388608&t);)t<<=1,i-=8388608;t&=-8388609,i+=947912704,n[e]=t|i}for(let e=1024;e<2048;++e)n[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)o[e]=e<<23;o[31]=1199570944,o[32]=2147483648;for(let e=33;e<63;++e)o[e]=2147483648+(e-32<<23);o[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(a[e]=1024);return{floatView:t,uint32View:i,baseTable:r,shiftTable:s,mantissaTable:n,exponentTable:o,offsetTable:a}}();function l(e,t){const i=new Uint8Array(e);let r=0;for(;0!=i[t.value+r];)r+=1;const s=(new TextDecoder).decode(i.slice(t.value,t.value+r));return t.value=t.value+r+1,s}function h(e,t){const i=e.getInt32(t.value,!0);return t.value+=o.b7,i}function c(e,t){const i=e.getUint32(t.value,!0);return t.value+=o.b7,i}function u(e,t){const i=e.getUint8(t.value);return t.value+=o.aN,i}function d(e,t){const i=e.getUint16(t.value,!0);return t.value+=o.JH,i}function f(e,t){const i=e[t.value];return t.value+=o.aN,i}function p(e,t){let i;return i="getBigInt64"in DataView.prototype?Number(e.getBigInt64(t.value,!0)):e.getUint32(t.value+4,!0)+Number(e.getUint32(t.value,!0)<<32),t.value+=o.Kl,i}function _(e,t){const i=e.getFloat32(t.value,!0);return t.value+=o.Y3,i}function m(e,t){return function(e){const t=(31744&e)>>10,i=1023&e;return(e>>15?-1:1)*(t?31===t?i?NaN:1/0:Math.pow(2,t-15)*(1+i/1024):i/1024*6103515625e-14)}(d(e,t))}function g(e,t){return function(e){if(Math.abs(e)>65504)throw new Error("Value out of range.Consider using float instead of half-float.");e=(0,n.Clamp)(e,-65504,65504),a.floatView[0]=e;const t=a.uint32View[0],i=t>>23&511;return a.baseTable[i]+((8388607&t)>>a.shiftTable[i])}(_(e,t))}function v(e,t,i,r){switch(i){case"string":case"stringvector":case"iccProfile":return function(e,t,i){const r=(new TextDecoder).decode(new Uint8Array(e).slice(t.value,t.value+i));return t.value=t.value+i,r}(e.buffer,t,r);case"chlist":return function(e,t,i){const r=t.value,s=[];for(;t.valuen||(t[s++]=e[i++],s>n));)t[s++]=e[r++]}},37642:(e,t,i)=>{"use strict";i.d(t,{d:()=>l,u:()=>h});var r=i(68907),s=i(12540),n=i(85260),o=i(9723),a=i(9668);async function l(e,t,i,l){const h={size:0,viewer:t,array:new Uint8Array(t.buffer),offset:i,width:e.dataWindow.xMax-e.dataWindow.xMin+1,height:e.dataWindow.yMax-e.dataWindow.yMin+1,channels:e.channels.length,channelLineOffsets:{},scanOrder:()=>0,bytesPerLine:0,outLineWidth:0,lines:0,scanlineBlockSize:0,inputSize:null,type:0,uncompress:null,getter:()=>0,format:5,outputChannels:0,decodeChannels:{},blockCount:null,byteArray:null,linearSpace:!1,textureType:0};switch(e.compression){case r.he.NO_COMPRESSION:h.lines=1,h.uncompress=s.S4;break;case r.he.RLE_COMPRESSION:h.lines=1,h.uncompress=s.r;break;case r.he.ZIPS_COMPRESSION:h.lines=1,h.uncompress=s.VE,await o.S0.LoadScriptAsync(a.u.FFLATEUrl);break;case r.he.ZIP_COMPRESSION:h.lines=16,h.uncompress=s.VE,await o.S0.LoadScriptAsync(a.u.FFLATEUrl);break;case r.he.PIZ_COMPRESSION:h.lines=32,h.uncompress=s.tg;break;case r.he.PXR24_COMPRESSION:h.lines=16,h.uncompress=s._k,await o.S0.LoadScriptAsync(a.u.FFLATEUrl);break;default:throw new Error(r.he[e.compression]+" is unsupported")}h.scanlineBlockSize=h.lines;const c={};for(const t of e.channels)switch(t.name){case"Y":case"R":case"G":case"B":case"A":c[t.name]=!0,h.type=t.pixelType}let u=!1;if(c.R&&c.G&&c.B)u=!c.A,h.outputChannels=4,h.decodeChannels={R:0,G:1,B:2,A:3};else{if(!c.Y)throw new Error("EXRLoader.parse: file contains unsupported data channels.");h.outputChannels=1,h.decodeChannels={Y:0}}if(1===h.type)switch(l){case a.V.Float:h.getter=r.LD,h.inputSize=n.JH;break;case a.V.HalfFloat:h.getter=r.Jn,h.inputSize=n.JH}else{if(2!==h.type)throw new Error("Unsupported pixelType "+h.type+" for "+e.compression);switch(l){case a.V.Float:h.getter=r.Ff,h.inputSize=n.Y3;break;case a.V.HalfFloat:h.getter=r.Sn,h.inputSize=n.Y3}}h.blockCount=h.height/h.scanlineBlockSize;for(let e=0;ee:h.scanOrder=e=>h.height-1-e,4==h.outputChannels?(h.format=5,h.linearSpace=!0):(h.format=6,h.linearSpace=!1),h}function h(e,t,i,n){const o={value:0};for(let a=0;ae.height?e.height-l:e.scanlineBlockSize;const h=e.size=e.height)continue;const n=i*e.bytesPerLine,l=(e.height-1-s)*e.outLineWidth;for(let i=0;i{"use strict";i.d(t,{V:()=>o});var r=i(60590),s=i(68907);const n=20000630;function o(e,t){if(e.getUint32(0,!0)!=n)throw new Error("Incorrect OpenEXR format");const i=e.getUint8(4),o=e.getUint8(5),a={singleTile:!!(2&o),longName:!!(4&o),deepFormat:!!(8&o),multiPart:!!(16&o)};t.value=8;const l={};let h=!0;for(;h;){const i=(0,s.T$)(e.buffer,t);if(i){const n=(0,s.T$)(e.buffer,t),o=(0,s.PX)(e,t),a=(0,s.zX)(e,t,n,o);void 0===a?r.V.Warn(`Unknown header attribute type ${n}'.`):l[i]=a}else h=!1}if(-5&o)throw new Error("Unsupported file format");return{version:i,spec:a,...l}}},85260:(e,t,i)=>{"use strict";i.d(t,{A_:()=>d,Ez:()=>l,Hh:()=>_,JH:()=>o,Kl:()=>a,LK:()=>c,LU:()=>p,U0:()=>u,Y3:()=>s,aN:()=>n,b7:()=>r,cQ:()=>h,gn:()=>m,lR:()=>f});const r=4,s=4,n=1,o=2,a=8,l=65536,h=l>>3,c=14,u=65537,d=1<{"use strict";i.r(t),i.d(t,{_BasisTextureLoader:()=>n});var r=i(68622),s=i(9723);class n{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,n,o){if(Array.isArray(e))return;const a=t.getEngine().getCaps(),l={supportedCompressionFormats:{etc1:!!a.etc1,s3tc:!!a.s3tc,pvrtc:!!a.pvrtc,etc2:!!a.etc2,astc:!!a.astc,bc7:!!a.bptc}};(0,r.yk)(e,l).then((e=>{const i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;(0,r.aB)(t,e),t.getEngine()._setCubeMapTextureParams(t,i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()})).catch((e=>{s.S0.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,o&&o(e)}))}loadData(e,t,i){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}};(0,r.yk)(e,o).then((e=>{const s=e.fileInfo.images[0].levels[0],n=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(s.width,s.height,n,-1!==e.format,(()=>{(0,r.aB)(t,e)}))})).catch((e=>{s.S0.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),s.S0.Warn(`Failed to transcode Basis file: ${e}`),i(0,0,!1,!1,(()=>{}),!0)}))}}},50153:(e,t,i)=>{"use strict";i.r(t),i.d(t,{_DDSTextureLoader:()=>n});var r=i(13798),s=i(26589);class n{constructor(){this.supportCascades=!0}loadCubeData(e,t,i,n){const o=t.getEngine();let a,l=!1,h=1e3;if(Array.isArray(e))for(let i=0;i1)&&t.generateMipMaps,o._unpackFlipY(a.isCompressed),s.DDSTools.UploadDDSLevels(o,t,r,a,l,6,-1,i),a.isFourCC||1!==a.mipmapCount?h=a.mipmapCount-1:o.generateMipMapsForCubemap(t)}else{const n=e;a=s.DDSTools.GetDDSInfo(n),t.width=a.width,t.height=a.height,i&&(a.sphericalPolynomial=new r.Q),l=(a.isRGB||a.isLuminance||a.mipmapCount>1)&&t.generateMipMaps,o._unpackFlipY(a.isCompressed),s.DDSTools.UploadDDSLevels(o,t,n,a,l,6),a.isFourCC||1!==a.mipmapCount?h=a.mipmapCount-1:o.generateMipMapsForCubemap(t,!1)}o._setCubeMapTextureParams(t,l,h),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n({isDDS:!0,width:t.width,info:a,data:e,texture:t})}loadData(e,t,i){const r=s.DDSTools.GetDDSInfo(e),n=(r.isRGB||r.isLuminance||r.mipmapCount>1)&&t.generateMipMaps&&Math.max(r.width,r.height)>>r.mipmapCount-1==1;i(r.width,r.height,n,r.isFourCC,(()=>{s.DDSTools.UploadDDSLevels(t.getEngine(),t,e,r,n,1)}))}}},33815:(e,t,i)=>{"use strict";i.r(t),i.d(t,{_ENVTextureLoader:()=>s});var r=i(48195);class s{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,s,n){if(Array.isArray(e))return;const o=(0,r.cU)(e);if(o){t.width=o.width,t.height=o.width;try{(0,r.ow)(t,o),(0,r.o5)(t,e,o).then((()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}),(e=>{n?.("Can not upload environment levels",e)}))}catch(e){n?.("Can not upload environment file",e)}}else n&&n("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}},3197:(e,t,i)=>{"use strict";i.r(t),i.d(t,{_ExrTextureLoader:()=>o});var r=i(44969),s=i(37642),n=i(9668);class o{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,r,s){throw".exr not supported in Cube."}async loadData(e,t,i){const o=new DataView(e.buffer),a={value:0},l=(0,r.V)(o,a),h=await(0,s.d)(l,o,a,n.u.DefaultOutputType);(0,s.u)(h,l,o,a),i(l.dataWindow.xMax-l.dataWindow.xMin+1,l.dataWindow.yMax-l.dataWindow.yMin+1,t.generateMipMaps,!1,(()=>{const e=t.getEngine();t.format=l.format,t.type=h.textureType,t.invertY=!1,t._gammaSpace=!l.linearSpace,h.byteArray&&e._uploadDataToTextureDirectly(t,h.byteArray,0,0,void 0,!0)}))}}},46628:(e,t,i)=>{"use strict";i.r(t),i.d(t,{_HDRTextureLoader:()=>s});var r=i(22377);class s{constructor(){this.supportCascades=!1}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=(0,r.NK)(s),o=(0,r.LT)(s,n),a=n.width*n.height,l=new Float32Array(4*a);for(let e=0;e{const e=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,e._uploadDataToTextureDirectly(t,l)}))}}},53797:(e,t,i)=>{"use strict";i.r(t),i.d(t,{_KTXTextureLoader:()=>o});var r=i(52710),s=i(27606),n=i(60590);class o{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,s){if(Array.isArray(e))return;t._invertVScale=!t.invertY;const n=t.getEngine(),o=new r.H(e,6),a=o.numberOfMipmapLevels>1&&t.generateMipMaps;n._unpackFlipY(!0),o.uploadLevels(t,t.generateMipMaps),t.width=o.pixelWidth,t.height=o.pixelHeight,n._setCubeMapTextureParams(t,a,o.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}loadData(e,t,i,o){if(r.H.IsValid(e)){t._invertVScale=!t.invertY;const s=new r.H(e,1),n=function(e){switch(e){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}(s.glInternalFormat);n?(t.format=n,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=s.glInternalFormat,i(s.pixelWidth,s.pixelHeight,t.generateMipMaps,!0,(()=>{s.uploadLevels(t,t.generateMipMaps)}),s.isInvalid)}else s.Z.IsValid(e)?new s.Z(t.getEngine())._uploadAsync(e,t,o).then((()=>{i(t.width,t.height,t.generateMipMaps,!0,(()=>{}),!1)}),(e=>{n.V.Warn(`Failed to load KTX2 texture data: ${e.message}`),i(0,0,!1,!1,(()=>{}),!0)})):(n.V.Error("texture missing KTX identifier"),i(0,0,!1,!1,(()=>{}),!0))}}},47221:(e,t,i)=>{"use strict";i.d(t,{gT:()=>a,hy:()=>o,kf:()=>n});var r=i(60590);const s=new Map;function n(e,t){o(e)&&r.V.Warn(`Extension with the name '${name}' already exists`),s.set(e,t)}function o(e){return s.delete(e)}function a(e,t){"image/ktx"!==t&&"image/ktx2"!==t||(e=".ktx"),s.has(e)||(e.endsWith(".dds")&&n(".dds",(()=>Promise.resolve().then(i.bind(i,50153)).then((e=>new e._DDSTextureLoader)))),e.endsWith(".basis")&&n(".basis",(()=>Promise.resolve().then(i.bind(i,60232)).then((e=>new e._BasisTextureLoader)))),e.endsWith(".env")&&n(".env",(()=>Promise.resolve().then(i.bind(i,33815)).then((e=>new e._ENVTextureLoader)))),e.endsWith(".hdr")&&n(".hdr",(()=>Promise.resolve().then(i.bind(i,46628)).then((e=>new e._HDRTextureLoader)))),(e.endsWith(".ktx")||e.endsWith(".ktx2"))&&(n(".ktx",(()=>Promise.resolve().then(i.bind(i,53797)).then((e=>new e._KTXTextureLoader)))),n(".ktx2",(()=>Promise.resolve().then(i.bind(i,53797)).then((e=>new e._KTXTextureLoader))))),e.endsWith(".tga")&&n(".tga",(()=>Promise.resolve().then(i.bind(i,60254)).then((e=>new e._TGATextureLoader)))),e.endsWith(".exr")&&n(".exr",(()=>Promise.resolve().then(i.bind(i,3197)).then((e=>new e._ExrTextureLoader)))));const r=s.get(e);return r?Promise.resolve(r(t)):null}},60254:(e,t,i)=>{"use strict";i.r(t),i.d(t,{_TGATextureLoader:()=>s});var r=i(96172);class s{constructor(){this.supportCascades=!1}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=(0,r.O_)(s);i(n.width,n.height,t.generateMipMaps,!1,(()=>{(0,r.FA)(t,s)}))}}},23199:(e,t,i)=>{"use strict";i.d(t,{t:()=>u});var r=i(15287),s=i(40220),n=i(43279),o=i(94212),a=i(34268),l=i(71627),h=(i(28909),i(29305)),c=i(89518);class u extends h.D{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.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}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){return this._texture?(null===this._texture._gammaSpace&&(this._texture._gammaSpace=this._gammaSpace),this._texture._gammaSpace&&!this._texture._useSRGBBuffer):this._gammaSpace}set gammaSpace(e){if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}this.getScene()?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this)))}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),this.getScene()?.markAllMaterialsAsDirty(1,(e=>e.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}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=(0,l.z)()),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=u.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 n.cP,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?u._IsScene(e)?this._scene=e:this._engine=e:this._scene=a.q.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 o.uq.IdentityReadOnly}getReflectionTextureMatrix(){return o.uq.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,r,s,n){const o=this._getEngine();if(!o)return null;const a=o._getUseSRGBBuffer(!!s,t),l=o.getLoadedTexturesCache();for(let o=0;o=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){const e=this._parentContainer.textures.indexOf(this);e>-1&&this._parentContainer.textures.splice(e,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=c.p.Serialize(this);return c.p.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0!==i)for(let r=0;r{0==--i&&t()})):0==--i&&t()}}else t()}static _IsScene(e){return"Scene"===e.getClassName()}}u.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,(0,r.Cg)([(0,s.lK)()],u.prototype,"uniqueId",void 0),(0,r.Cg)([(0,s.lK)()],u.prototype,"name",void 0),(0,r.Cg)([(0,s.lK)()],u.prototype,"displayName",void 0),(0,r.Cg)([(0,s.lK)()],u.prototype,"metadata",void 0),(0,r.Cg)([(0,s.lK)("hasAlpha")],u.prototype,"_hasAlpha",void 0),(0,r.Cg)([(0,s.lK)("getAlphaFromRGB")],u.prototype,"_getAlphaFromRGB",void 0),(0,r.Cg)([(0,s.lK)()],u.prototype,"level",void 0),(0,r.Cg)([(0,s.lK)("coordinatesIndex")],u.prototype,"_coordinatesIndex",void 0),(0,r.Cg)([(0,s.lK)()],u.prototype,"optimizeUVAllocation",void 0),(0,r.Cg)([(0,s.lK)("coordinatesMode")],u.prototype,"_coordinatesMode",void 0),(0,r.Cg)([(0,s.lK)()],u.prototype,"wrapU",null),(0,r.Cg)([(0,s.lK)()],u.prototype,"wrapV",null),(0,r.Cg)([(0,s.lK)()],u.prototype,"wrapR",void 0),(0,r.Cg)([(0,s.lK)()],u.prototype,"anisotropicFilteringLevel",void 0),(0,r.Cg)([(0,s.lK)()],u.prototype,"isCube",null),(0,r.Cg)([(0,s.lK)()],u.prototype,"is3D",null),(0,r.Cg)([(0,s.lK)()],u.prototype,"is2DArray",null),(0,r.Cg)([(0,s.lK)()],u.prototype,"gammaSpace",null),(0,r.Cg)([(0,s.lK)()],u.prototype,"invertZ",void 0),(0,r.Cg)([(0,s.lK)()],u.prototype,"lodLevelInAlpha",void 0),(0,r.Cg)([(0,s.lK)()],u.prototype,"lodGenerationOffset",null),(0,r.Cg)([(0,s.lK)()],u.prototype,"lodGenerationScale",null),(0,r.Cg)([(0,s.lK)()],u.prototype,"linearSpecularLOD",null),(0,r.Cg)([(0,s.uM)()],u.prototype,"irradianceTexture",null),(0,r.Cg)([(0,s.lK)()],u.prototype,"isRenderTarget",void 0)},54699:(e,t,i)=>{"use strict";var r=i(82266),s=i(23199);s.t.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(s.t.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=r.d.ConvertCubeMapTextureToSphericalPolynomial(this),null===this._texture._sphericalPolynomialPromise?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then((e=>{this._texture._sphericalPolynomial=e,this._texture._sphericalPolynomialComputed=!0}))),null}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0})},7107:(e,t,i)=>{"use strict";i.d(t,{G:()=>r,h:()=>o});var r,s=i(43279),n=i(18310);!function(e){e[e.Unknown=0]="Unknown",e[e.Url=1]="Url",e[e.Temp=2]="Temp",e[e.Raw=3]="Raw",e[e.Dynamic=4]="Dynamic",e[e.RenderTarget=5]="RenderTarget",e[e.MultiRenderTarget=6]="MultiRenderTarget",e[e.Cube=7]="Cube",e[e.CubeRaw=8]="CubeRaw",e[e.CubePrefiltered=9]="CubePrefiltered",e[e.Raw3D=10]="Raw3D",e[e.Raw2DArray=11]="Raw2DArray",e[e.DepthStencil=12]="DepthStencil",e[e.CubeRawRGBD=13]="CubeRawRGBD",e[e.Depth=14]="Depth"}(r||(r={}));class o extends n.u{get useMipMaps(){return this.generateMipMaps}set useMipMaps(e){this.generateMipMaps=e}get uniqueId(){return this._uniqueId}_setUniqueId(e){this._uniqueId=e}getEngine(){return this._engine}get source(){return this._source}constructor(e,t,i=!1){super(),this.isReady=!1,this.isCube=!1,this.is3D=!1,this.is2DArray=!1,this.isMultiview=!1,this.url="",this.generateMipMaps=!1,this.samples=0,this.type=-1,this.format=-1,this.onLoadedObservable=new s.cP,this.onErrorObservable=new s.cP,this.onRebuildCallback=null,this.width=0,this.height=0,this.depth=0,this.baseWidth=0,this.baseHeight=0,this.baseDepth=0,this.invertY=!1,this._invertVScale=!1,this._associatedChannel=-1,this._source=0,this._buffer=null,this._bufferView=null,this._bufferViewArray=null,this._bufferViewArrayArray=null,this._size=0,this._extension="",this._files=null,this._workingCanvas=null,this._workingContext=null,this._cachedCoordinatesMode=null,this._isDisabled=!1,this._compression=null,this._sphericalPolynomial=null,this._sphericalPolynomialPromise=null,this._sphericalPolynomialComputed=!1,this._lodGenerationScale=0,this._lodGenerationOffset=0,this._useSRGBBuffer=!1,this._creationFlags=0,this._lodTextureHigh=null,this._lodTextureMid=null,this._lodTextureLow=null,this._isRGBD=!1,this._linearSpecularLOD=!1,this._irradianceTexture=null,this._hardwareTexture=null,this._maxLodLevel=null,this._references=1,this._gammaSpace=null,this._premulAlpha=!1,this._dynamicTextureSource=null,this._engine=e,this._source=t,this._uniqueId=o._Counter++,i||(this._hardwareTexture=e._createHardwareTexture())}incrementReferences(){this._references++}updateSize(e,t,i=1){this._engine.updateTextureDimensions(this,e,t,i),this.width=e,this.height=t,this.depth=i,this.baseWidth=e,this.baseHeight=t,this.baseDepth=i,this._size=e*t*i}_rebuild(){if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){const e=this.onRebuildCallback(this),t=t=>{t._swapAndDie(this,!1),this.isReady=e.isReady};return void(e.isAsync?e.proxy.then(t):t(e.proxy))}let e;switch(this.source){case 2:case 12:case 14:break;case 1:return void(e=this._engine.createTexture(this._originalUrl??this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,(e=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer));case 3:e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer),e._swapAndDie(this,!1),this.isReady=!0;break;case 10:e=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case 11:e=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case 4:e=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),e._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case 7:return void(e=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,(()=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer,ArrayBuffer.isView(this._buffer)?this._buffer:null));case 8:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this._originalFormat??this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case 13:return;case 9:return e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,(e=>{e&&e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension),void(e._sphericalPolynomial=this._sphericalPolynomial)}}_swapAndDie(e,t=!0){this._hardwareTexture?.setUsage(e._source,this.generateMipMaps,this.is2DArray,this.isCube,this.is3D,this.width,this.height,this.depth),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);const i=this._engine.getLoadedTexturesCache();let r=i.indexOf(this);-1!==r&&i.splice(r,1),r=i.indexOf(e),-1===r&&i.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}o._Counter=0},63199:(e,t,i)=>{"use strict";var r,s,n;i.d(t,{GQ:()=>n,Ok:()=>r,Xl:()=>s}),function(e){e[e.ETC1S=0]="ETC1S",e[e.UASTC4x4=1]="UASTC4x4"}(r||(r={})),function(e){e[e.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",e[e.BC7_RGBA=1]="BC7_RGBA",e[e.BC3_RGBA=2]="BC3_RGBA",e[e.BC1_RGB=3]="BC1_RGB",e[e.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",e[e.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",e[e.ETC2_RGBA=6]="ETC2_RGBA",e[e.ETC1_RGB=7]="ETC1_RGB",e[e.RGBA32=8]="RGBA32",e[e.R8=9]="R8",e[e.RG8=10]="RG8"}(s||(s={})),function(e){e[e.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",e[e.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",e[e.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",e[e.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",e[e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",e[e.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",e[e.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",e[e.RGBA8Format=32856]="RGBA8Format",e[e.R8Format=33321]="R8Format",e[e.RG8Format=33323]="RG8Format"}(n||(n={}))},58059:(e,t,i)=>{"use strict";i.d(t,{$:()=>u});var r=i(43279),s=i(94212),n=i(4756),o=i(2449),a=i(44512),l=i(36217),h=i(60590),c=i(25266);l.M.prototype.setDepthStencilTexture=function(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)};class u extends n.g{get renderListPredicate(){return this._objectRenderer.renderListPredicate}set renderListPredicate(e){this._objectRenderer.renderListPredicate=e}get renderList(){return this._objectRenderer.renderList}set renderList(e){this._objectRenderer.renderList=e}get particleSystemList(){return this._objectRenderer.particleSystemList}set particleSystemList(e){this._objectRenderer.particleSystemList=e}get getCustomRenderList(){return this._objectRenderer.getCustomRenderList}set getCustomRenderList(e){this._objectRenderer.getCustomRenderList=e}get renderParticles(){return this._objectRenderer.renderParticles}set renderParticles(e){this._objectRenderer.renderParticles=e}get renderSprites(){return this._objectRenderer.renderSprites}set renderSprites(e){this._objectRenderer.renderSprites=e}get forceLayerMaskCheck(){return this._objectRenderer.forceLayerMaskCheck}set forceLayerMaskCheck(e){this._objectRenderer.forceLayerMaskCheck=e}get activeCamera(){return this._objectRenderer.activeCamera}set activeCamera(e){this._objectRenderer.activeCamera=e}get customIsReadyFunction(){return this._objectRenderer.customIsReadyFunction}set customIsReadyFunction(e){this._objectRenderer.customIsReadyFunction=e}get customRenderFunction(){return this._objectRenderer.customRenderFunction}set customRenderFunction(e){this._objectRenderer.customRenderFunction=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)}get onBeforeRenderObservable(){return this._objectRenderer.onBeforeRenderObservable}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}get onAfterRenderObservable(){return this._objectRenderer.onAfterRenderObservable}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 _waitingRenderList(){return this._objectRenderer._waitingRenderList}set _waitingRenderList(e){this._objectRenderer._waitingRenderList=e}get renderPassId(){return this._objectRenderer.renderPassId}get renderPassIds(){return this._objectRenderer.renderPassIds}get currentRefreshId(){return this._objectRenderer.currentRefreshId}setMaterialForRendering(e,t){this._objectRenderer.setMaterialForRendering(e,t)}get isMulti(){return this._renderTarget?.isMulti??!1}get renderTargetOptions(){return this._renderTargetOptions}get renderTarget(){return this._renderTarget}_onRatioRescale(){this._sizeRatio&&this.resize(this._initialSizeParameter)}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}get depthStencilTexture(){return this._renderTarget?._depthStencilTexture??null}constructor(e,t,i,o=!1,a=!0,l=0,u=!1,d=n.g.TRILINEAR_SAMPLINGMODE,f=!0,p=!1,_=!1,m=5,g=!1,v,x,b=!1,S=!1){let T,C=!0;if("object"==typeof o){const e=o;o=!!e.generateMipMaps,a=e.doNotChangeAspectRatio??!0,l=e.type??0,u=!!e.isCube,d=e.samplingMode??n.g.TRILINEAR_SAMPLINGMODE,f=e.generateDepthBuffer??!0,p=!!e.generateStencilBuffer,_=!!e.isMulti,m=e.format??5,g=!!e.delayAllocation,v=e.samples,x=e.creationFlags,b=!!e.noColorAttachment,S=!!e.useSRGBBuffer,T=e.colorAttachment,C=e.gammaSpace??C}if(super(null,i,!o,void 0,d,void 0,void 0,void 0,void 0,m),this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new r.cP,this.onAfterUnbindObservable=new r.cP,this.onClearObservable=new r.cP,this.onResizeObservable=new r.cP,this._cleared=!1,this.skipInitialClear=!1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=s.Pq.Zero(),this._dumpToolsLoading=!1,!(i=this.getScene()))return;const y=this.getScene().getEngine();this._gammaSpace=C,this._coordinatesMode=n.g.PROJECTION_MODE,this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._processSizeParameter(t),this._objectRenderer=new c.P(e,i,{numPasses:u?6:this.getRenderLayers()||1,doNotChangeAspectRatio:a}),this._objectRenderer.onBeforeRenderingManagerRenderObservable.add((()=>{for(const e of this._scene._beforeRenderTargetClearStage)e.action(this,this._currentFaceIndex,this._currentLayer);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(y):this.skipInitialClear||y.clear(this.clearColor||this._scene.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||this._scene.updateTransformMatrix(!0);for(const e of this._scene._beforeRenderTargetDrawStage)e.action(this,this._currentFaceIndex,this._currentLayer)})),this._objectRenderer.onAfterRenderingManagerRenderObservable.add((()=>{for(const e of this._scene._afterRenderTargetDrawStage)e.action(this,this._currentFaceIndex,this._currentLayer);const e=this._texture?.generateMipMaps??!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,this._currentFaceIndex,this._postProcesses,this.ignoreCameraViewport):this._currentUseCameraPostProcess&&this._scene.postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,this._currentFaceIndex);for(const e of this._scene._afterRenderTargetPostProcessStage)e.action(this,this._currentFaceIndex,this._currentLayer);this._texture&&(this._texture.generateMipMaps=e),this._doNotChangeAspectRatio||this._scene.updateTransformMatrix(!0),this._currentDumpForDebug&&(this._dumpTools?this._dumpTools.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),y):h.V.Error("dumpTools module is still being loaded. To speed up the process import dump tools directly in your project"))})),this._objectRenderer.onFastPathRenderObservable.add((()=>{this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(y):this.skipInitialClear||y.clear(this.clearColor||this._scene.clearColor,!0,!0,!0)})),this._resizeObserver=y.onResizeObservable.add((()=>{})),this._generateMipMaps=!!o,this._doNotChangeAspectRatio=a,_||(this._renderTargetOptions={generateMipMaps:o,type:l,format:this._format??void 0,samplingMode:this.samplingMode,generateDepthBuffer:f,generateStencilBuffer:p,samples:v,creationFlags:x,noColorAttachment:b,useSRGBBuffer:S,colorAttachment:T,label:this.name},this.samplingMode===n.g.NEAREST_SAMPLINGMODE&&(this.wrapU=n.g.CLAMP_ADDRESSMODE,this.wrapV=n.g.CLAMP_ADDRESSMODE),g||(u?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=n.g.INVCUBIC_MODE,this._textureMatrix=s.uq.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==v&&(this.samples=v)))}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,n){this._renderTarget?.createDepthStencilTexture(e,t,i,r,s,n)}_processSizeParameter(e){if(e.ratio){this._sizeRatio=e.ratio;const t=this._getEngine();this._size={width:this._bestReflectionRenderTargetDimension(t.getRenderWidth(),this._sizeRatio),height:this._bestReflectionRenderTargetDimension(t.getRenderHeight(),this._sizeRatio)}}else this._size=e}get samples(){return this._renderTarget?.samples??this._samples}set samples(e){this._renderTarget&&(this._samples=this._renderTarget.setSamples(e))}addPostProcess(e){if(!this._postProcessManager){const e=this.getScene();if(!e)return;this._postProcessManager=new o.X(e),this._postProcesses=new Array}this._postProcesses.push(e),this._postProcesses[0].autoClear=!1}clearPostProcesses(e=!1){if(this._postProcesses){if(e)for(const e of this._postProcesses)e.dispose();this._postProcesses=[]}}removePostProcess(e){if(!this._postProcesses)return;const t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses.splice(t,1),this._postProcesses.length>0&&(this._postProcesses[0].autoClear=!1))}resetRefreshCounter(){this._objectRenderer.resetRefreshCounter()}get refreshRate(){return this._objectRenderer.refreshRate}set refreshRate(e){this._objectRenderer.refreshRate=e}_shouldRender(){return this._objectRenderer.shouldRender()}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;return this._size.depth||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){const t=this.isCube;this._renderTarget?.dispose(),this._renderTarget=null;const i=this.getScene();i&&(this._processSizeParameter(e),this._renderTarget=t?i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==this._renderTargetOptions.samples&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){this._dumpToolsLoading||(this._dumpToolsLoading=!0,Promise.resolve().then(i.bind(i,465)).then((e=>this._dumpTools=e))),this._objectRenderer.prepareRenderList(),this.onBeforeBindObservable.notifyObservers(this),this._objectRenderer.initRender(this.getRenderWidth(),this.getRenderHeight());const e=this._objectRenderer._checkReadiness();return this.onAfterUnbindObservable.notifyObservers(this),this._objectRenderer.finishRender(),e}_render(e=!1,t=!1){const i=this.getScene();if(i){if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._objectRenderer.prepareRenderList(),this.onBeforeBindObservable.notifyObservers(this),this._objectRenderer.initRender(this.getRenderWidth(),this.getRenderHeight()),!this.is2DArray&&!this.is3D||this.isMulti)if(this.isCube&&!this.isMulti)for(let r=0;r<6;r++)this._renderToTarget(r,e,t),i.incrementRenderId(),i.resetCachedMaterial();else this._renderToTarget(0,e,t);else for(let r=0;r{this.onAfterRenderObservable.notifyObservers(t)}))}_prepareFrame(e,t,i,r){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):r&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,r=0){const s=this.getScene();if(!s)return;const n=s.getEngine();this._currentFaceIndex=e,this._currentLayer=r,this._currentUseCameraPostProcess=t,this._currentDumpForDebug=i,this._prepareFrame(s,e,r,t),n._debugPushGroup?.(`render to face #${e} layer #${r}`,2),this._objectRenderer.render(e+r,!0),n._debugPopGroup?.(2),this._unbindFrameBuffer(n,e),this._texture&&this.isCube&&5===e&&n.generateMipMapsForCubemap(this._texture,!0)}setRenderingOrder(e,t=null,i=null,r=null){this._objectRenderer.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t){this._objectRenderer.setRenderingAutoClearDepthStencil(e,t)}clone(){const e=this.getSize(),t=new u(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 i of e.cameras)t=i.customRenderTargets.indexOf(this),t>=0&&i.customRenderTargets.splice(t,1);this._renderTarget?.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this._objectRenderer._rebuild(),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._objectRenderer.freeRenderingGroups()}getViewCount(){return 1}}u.REFRESHRATE_RENDER_ONCE=c.P.REFRESHRATE_RENDER_ONCE,u.REFRESHRATE_RENDER_ONEVERYFRAME=c.P.REFRESHRATE_RENDER_ONEVERYFRAME,u.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=c.P.REFRESHRATE_RENDER_ONEVERYTWOFRAMES,n.g._CreateRenderTargetTexture=(e,t,i,r,s)=>new u(e,t,i,r)},4756:(e,t,i)=>{"use strict";i.d(t,{g:()=>g});var r=i(15287),s=i(40220),n=i(43279),o=i(94212),a=i(23199),l=i(56225),h=i(75108),c=i(72649),u=i(14798),d=i(30573),f=i(5800),p=i(61572),_=i(75174),m=i(89518);class g extends a.t{static _CreateVideoTexture(e,t,i,r=!1,s=!1,n=g.TRILINEAR_SAMPLINGMODE,o={},a,l=5){throw(0,h.n)("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,r,s=g.TRILINEAR_SAMPLINGMODE,o=null,a=null,l=null,h=!1,u,d,f,p,m){let v;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 n.cP,this._isBlocking=!0,this.name=e||"",this.url=e;let x=!1,b=null,S=!0;"object"==typeof i&&null!==i?(v=i.noMipmap??!1,r=i.invertY??!_.rX,s=i.samplingMode??g.TRILINEAR_SAMPLINGMODE,o=i.onLoad??null,a=i.onError??null,l=i.buffer??null,h=i.deleteBuffer??!1,u=i.format,d=i.mimeType,f=i.loaderOptions,p=i.creationFlags,x=i.useSRGBBuffer??!1,b=i.internalTexture??null,S=i.gammaSpace??S,m=i.forcedExtension??m):v=!!i,this._gammaSpace=S,this._noMipmap=v,this._invertY=void 0===r?!_.rX:r,this._initialSamplingMode=s,this._buffer=l,this._deleteBuffer=h,this._mimeType=d,this._loaderOptions=f,this._creationFlags=p,this._useSRGBBuffer=x,this._forcedExtension=m,u&&(this._format=u);const T=this.getScene(),C=this._getEngine();if(!C)return;C.onBeforeTextureInitObservable.notifyObservers(this);const y=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),null!==this._texture._cachedWrapU&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),null!==this._texture._cachedWrapV&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),null!==this._texture._cachedWrapR&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),o&&o(),!this.isBlocking&&T&&T.resetCachedMaterial()},E=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},a&&a(e,t),g.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!b)return this._delayedOnLoad=y,void(this._delayedOnError=E);if(this._texture=b??this._getFromCache(this.url,v,s,this._invertY,x,this.isCube),this._texture)if(this._texture.isReady)c._.SetImmediate((()=>y()));else{const e=this._texture.onLoadedObservable.add(y);this._texture.onErrorObservable.add((t=>{E(t.message,t.exception),this._texture?.onLoadedObservable.remove(e)}))}else if(T&&T.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=y,this._delayedOnError=E;else{try{this._texture=C.createTexture(this.url,v,this._invertY,T,s,y,E,this._buffer,void 0,this._format,this._forcedExtension,d,f,p,x)}catch(e){throw E("error loading",e),e}h&&(this._buffer=null)}}updateURL(e,t=null,i,r){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,(e=>e.hasTexture(this)))),this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=r,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(4!==this.delayLoadState)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?c._.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null)}_prepareRowForTextureGeneration(e,t,i,r){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,o.Pq.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,r),r.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,r.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,r.z+=this.wRotationCenter}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,this._cachedTextureMatrix&&this._rowGenerationMatrix||(this._cachedTextureMatrix=o.uq.Zero(),this._rowGenerationMatrix=new o.uq,this._t0=o.Pq.Zero(),this._t1=o.Pq.Zero(),this._t2=o.Pq.Zero()),o.uq.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(o.uq.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,o.AA.Matrix[0]),o.uq.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,o.AA.Matrix[1]),o.uq.ScalingToRef(this._cachedUScale,this._cachedVScale,0,o.AA.Matrix[2]),o.uq.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,o.AA.Matrix[3]),o.AA.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(o.AA.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(o.AA.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(o.AA.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),o.uq.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,(e=>e.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!==g.PROJECTION_MODE)return this._cachedReflectionTextureMatrix;if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=o.uq.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=o.uq.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 g.PLANAR_MODE:o.uq.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 g.PROJECTION_MODE:{o.uq.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:o.uq.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,(e=>e.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 m.p.Clone((()=>new g(this._texture?this._texture.url:null,this.getScene(),e)),this)}serialize(){const e=this.name;g.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(g._SerializeInternalTextureUniqueId);return t?((g.SerializeBuffers||g.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substring(0,5)?(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,"+(0,f.EL)(this._buffer):(g.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?(0,p.lP)(this):(0,p.nh)(this))),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,g._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=this._texture?.uniqueId),t.internalTextureLabel=this._texture?.label,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 r=u.n.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&r.updateSamplingMode&&r._samplingMode&&r._samplingMode!==e.samplingMode&&r.updateSamplingMode(e.samplingMode),r}if(e.isCube&&!e.isRenderTarget)return g._CubeTextureParser(e,t,i);const r=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!r)return null;let s;if(r){const i=t.getEngine().getLoadedTexturesCache();for(const t of i)if(t.uniqueId===e.internalTextureUniqueId){s=t;break}}const n=t=>{if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){const i=e.samplingMode;t&&t.samplingMode!==i&&t.updateSamplingMode(i)}if(t&&e.animations)for(let i=0;i{let r=!0;if(e.noMipmap&&(r=!1),e.mirrorPlane){const i=g._CreateMirror(e.name,e.renderTargetSize,t,r);return i._waitingRenderList=e.renderList,i.mirrorPlane=d.Z.FromArray(e.mirrorPlane),n(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i{n(o)}),e._creationFlags??0,e._useSRGBBuffer??!1),o.name=e.name;else{let a;a=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||g.UseSerializedUrlIfAny)&&(a=e.url);const l={noMipmap:!r,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{n(o)},internalTexture:s};o=new g(a,t,l)}return o}}),e,t)}static CreateFromBase64String(e,t,i,r,s,n=g.TRILINEAR_SAMPLINGMODE,o=null,a=null,l=5,h,c){return new g("data:"+t,i,r,s,n,o,a,e,!1,l,void 0,void 0,h,c)}static LoadFromDataString(e,t,i,r=!1,s,n=!0,o=g.TRILINEAR_SAMPLINGMODE,a=null,l=null,h=5,c,u){return"data:"!==e.substring(0,5)&&(e="data:"+e),new g(e,i,s,n,o,a,l,t,r,h,void 0,void 0,c,u)}}g.SerializeBuffers=!0,g.ForceSerializeBuffers=!1,g.OnTextureLoadErrorObservable=new n.cP,g._SerializeInternalTextureUniqueId=!1,g._CubeTextureParser=(e,t,i)=>{throw(0,h.n)("CubeTexture")},g._CreateMirror=(e,t,i,r)=>{throw(0,h.n)("MirrorTexture")},g._CreateRenderTargetTexture=(e,t,i,r,s)=>{throw(0,h.n)("RenderTargetTexture")},g.NEAREST_SAMPLINGMODE=1,g.NEAREST_NEAREST_MIPLINEAR=8,g.BILINEAR_SAMPLINGMODE=2,g.LINEAR_LINEAR_MIPNEAREST=11,g.TRILINEAR_SAMPLINGMODE=3,g.LINEAR_LINEAR_MIPLINEAR=3,g.NEAREST_NEAREST_MIPNEAREST=4,g.NEAREST_LINEAR_MIPNEAREST=5,g.NEAREST_LINEAR_MIPLINEAR=6,g.NEAREST_LINEAR=7,g.NEAREST_NEAREST=1,g.LINEAR_NEAREST_MIPNEAREST=9,g.LINEAR_NEAREST_MIPLINEAR=10,g.LINEAR_LINEAR=2,g.LINEAR_NEAREST=12,g.EXPLICIT_MODE=0,g.SPHERICAL_MODE=1,g.PLANAR_MODE=2,g.CUBIC_MODE=3,g.PROJECTION_MODE=4,g.SKYBOX_MODE=5,g.INVCUBIC_MODE=6,g.EQUIRECTANGULAR_MODE=7,g.FIXED_EQUIRECTANGULAR_MODE=8,g.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,g.CLAMP_ADDRESSMODE=0,g.WRAP_ADDRESSMODE=1,g.MIRROR_ADDRESSMODE=2,g.UseSerializedUrlIfAny=!1,(0,r.Cg)([(0,s.lK)()],g.prototype,"url",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"uOffset",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"vOffset",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"uScale",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"vScale",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"uAng",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"vAng",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"wAng",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"uRotationCenter",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"vRotationCenter",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"wRotationCenter",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"homogeneousRotationInUVTransform",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"isBlocking",null),(0,l.Y5)("BABYLON.Texture",g),m.p._TextureParser=g.Parse},18310:(e,t,i)=>{"use strict";i.d(t,{u:()=>r});class r{get wrapU(){return this._cachedWrapU}set wrapU(e){this._cachedWrapU=e}get wrapV(){return this._cachedWrapV}set wrapV(e){this._cachedWrapV=e}get wrapR(){return this._cachedWrapR}set wrapR(e){this._cachedWrapR=e}get anisotropicFilteringLevel(){return this._cachedAnisotropicFilteringLevel}set anisotropicFilteringLevel(e){this._cachedAnisotropicFilteringLevel=e}get comparisonFunction(){return this._comparisonFunction}set comparisonFunction(e){this._comparisonFunction=e}get useMipMaps(){return this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}constructor(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}setParameters(e=1,t=1,i=1,r=1,s=2,n=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=r,this.samplingMode=s,this._comparisonFunction=n,this}compareSampler(e){return this._cachedWrapU===e._cachedWrapU&&this._cachedWrapV===e._cachedWrapV&&this._cachedWrapR===e._cachedWrapR&&this._cachedAnisotropicFilteringLevel===e._cachedAnisotropicFilteringLevel&&this.samplingMode===e.samplingMode&&this._comparisonFunction===e._comparisonFunction&&this._useMipMaps===e._useMipMaps}}},29305:(e,t,i)=>{"use strict";i.d(t,{D:()=>s});var r=i(29962);class s{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}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return void 0!==e?.shareDepth}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=r.o.Zero(),this._cachedBaseSize=r.o.Zero(),this._initialSamplingMode=2,this._texture=s._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return 4===this.delayLoadState?(this.delayLoad(),!1):!!this._texture&&this._texture.isReady}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._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):(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,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)}}},57551:(e,t,i)=>{"use strict";function r(e){-1===e.indexOf("vClipPlane")&&e.push("vClipPlane"),-1===e.indexOf("vClipPlane2")&&e.push("vClipPlane2"),-1===e.indexOf("vClipPlane3")&&e.push("vClipPlane3"),-1===e.indexOf("vClipPlane4")&&e.push("vClipPlane4"),-1===e.indexOf("vClipPlane5")&&e.push("vClipPlane5"),-1===e.indexOf("vClipPlane6")&&e.push("vClipPlane6")}function s(e,t,i){const r=!!(e.clipPlane??t.clipPlane),s=!!(e.clipPlane2??t.clipPlane2),n=!!(e.clipPlane3??t.clipPlane3),o=!!(e.clipPlane4??t.clipPlane4),a=!!(e.clipPlane5??t.clipPlane5),l=!!(e.clipPlane6??t.clipPlane6);r&&i.push("#define CLIPPLANE"),s&&i.push("#define CLIPPLANE2"),n&&i.push("#define CLIPPLANE3"),o&&i.push("#define CLIPPLANE4"),a&&i.push("#define CLIPPLANE5"),l&&i.push("#define CLIPPLANE6")}function n(e,t,i){let r=!1;const s=!!(e.clipPlane??t.clipPlane),n=!!(e.clipPlane2??t.clipPlane2),o=!!(e.clipPlane3??t.clipPlane3),a=!!(e.clipPlane4??t.clipPlane4),l=!!(e.clipPlane5??t.clipPlane5),h=!!(e.clipPlane6??t.clipPlane6);return i.CLIPPLANE!==s&&(i.CLIPPLANE=s,r=!0),i.CLIPPLANE2!==n&&(i.CLIPPLANE2=n,r=!0),i.CLIPPLANE3!==o&&(i.CLIPPLANE3=o,r=!0),i.CLIPPLANE4!==a&&(i.CLIPPLANE4=a,r=!0),i.CLIPPLANE5!==l&&(i.CLIPPLANE5=l,r=!0),i.CLIPPLANE6!==h&&(i.CLIPPLANE6=h,r=!0),r}function o(e,t,i){let r=t.clipPlane??i.clipPlane;a(e,"vClipPlane",r),r=t.clipPlane2??i.clipPlane2,a(e,"vClipPlane2",r),r=t.clipPlane3??i.clipPlane3,a(e,"vClipPlane3",r),r=t.clipPlane4??i.clipPlane4,a(e,"vClipPlane4",r),r=t.clipPlane5??i.clipPlane5,a(e,"vClipPlane5",r),r=t.clipPlane6??i.clipPlane6,a(e,"vClipPlane6",r)}function a(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}i.d(t,{Eq:()=>n,TV:()=>r,gS:()=>o,tv:()=>s})},90446:(e,t,i)=>{"use strict";function r(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}i.d(t,{B:()=>r})},87741:(e,t,i)=>{"use strict";i.d(t,{Q:()=>l});var r=i(15287),s=i(40220),n=i(11084),o=i(89518),a=i(90446);class l{constructor(){this._dirty=!0,this._tempColor=new n.ov(0,0,0,0),this._globalCurve=new n.ov(0,0,0,0),this._highlightsCurve=new n.ov(0,0,0,0),this._midtonesCurve=new n.ov(0,0,0,0),this._shadowsCurve=new n.ov(0,0,0,0),this._positiveCurve=new n.ov(0,0,0,0),this._negativeCurve=new n.ov(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",r="vCameraColorCurveNeutral",s="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(r,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(s,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,r,s){null!=e&&(e=l._Clamp(e,0,360),t=l._Clamp(t,-100,100),i=l._Clamp(i,-100,100),r=l._Clamp(r,-100,100),t=l._ApplyColorGradingSliderNonlinear(t),t*=.5,r=l._ApplyColorGradingSliderNonlinear(r),t<0&&(t*=-1,e=(e+180)%360),l._FromHSBToRef(e,t,50+.25*r,s),s.scaleToRef(2,s),s.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(e,t,i,r){let s=l._Clamp(e,0,360);const n=l._Clamp(t/100,0,1),o=l._Clamp(i/100,0,1);if(0===n)r.r=o,r.g=o,r.b=o;else{s/=60;const e=Math.floor(s),t=s-e,i=o*(1-n),a=o*(1-n*t),l=o*(1-n*(1-t));switch(e){case 0:r.r=o,r.g=l,r.b=i;break;case 1:r.r=a,r.g=o,r.b=i;break;case 2:r.r=i,r.g=o,r.b=l;break;case 3:r.r=i,r.g=a,r.b=o;break;case 4:r.r=l,r.g=i,r.b=o;break;default:r.r=o,r.g=i,r.b=a}}r.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return o.p.Clone((()=>new l),this)}serialize(){return o.p.Serialize(this)}static Parse(e){return o.p.Parse((()=>new l),e,null,null)}}l.PrepareUniforms=a.B,(0,r.Cg)([(0,s.lK)()],l.prototype,"_globalHue",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_globalDensity",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_globalSaturation",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_globalExposure",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_highlightsHue",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_highlightsDensity",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_highlightsSaturation",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_highlightsExposure",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_midtonesHue",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_midtonesDensity",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_midtonesSaturation",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_midtonesExposure",void 0),o.p._ColorCurvesParser=l.Parse},61340:(e,t,i)=>{"use strict";function r(e){return void 0===e.getPipelineContext}i.d(t,{E:()=>r})},15311:(e,t,i)=>{"use strict";i.d(t,{E:()=>r});class r{static GetEffect(e){return void 0===e.getPipelineContext?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){this.effect=e,void 0!==t&&(this.defines=t),i&&this.drawContext?.reset()}dispose(){this.effect&&(this.effect.dispose(),this.effect=null),this.drawContext?.dispose()}}},73010:(e,t,i)=>{"use strict";i.d(t,{b4:()=>h,bu:()=>u,mO:()=>c,uR:()=>f});var r=i(68191),s=i(66593),n=i(69841),o=i(60590),a=i(88217),l=i(2636);function h(e,t){return(0,s.N5)(t).cachedPipelines[e]}function c(e){const t=e._name,i=e.context;if(t&&i){const e=(0,s.N5)(i),r=e.cachedPipelines[t];r?.dispose(),delete e.cachedPipelines[t]}}function u(e,t,i,s,n,o,l){let h,c;const u=(0,r.BA)()?o?.getHostDocument():null;h="string"==typeof t?t:t.vertexSource?"source:"+t.vertexSource:t.vertexElement?u?.getElementById(t.vertexElement)||t.vertexElement:t.vertex||t,c="string"==typeof t?t:t.fragmentSource?"source:"+t.fragmentSource:t.fragmentElement?u?.getElementById(t.fragmentElement)||t.fragmentElement:t.fragment||t;const f=[void 0,void 0],p=()=>{if(f[0]&&f[1]){e.isFragment=!0;const[r,h]=f;(0,a.M0)(h,e,((o,h)=>{l&&(l._fragmentSourceCodeBeforeMigration=h),i&&(o=i("fragment",o));const c=(0,a.nO)(r,o,e);e=null;const u=function(e,t,i,r){return i?{vertexSourceCode:(1===r?"//":"")+"#define SHADER_NAME vertex:"+(i.vertexElement||i.vertex||i.spectorName||i)+"\n"+e,fragmentSourceCode:(1===r?"//":"")+"#define SHADER_NAME fragment:"+(i.fragmentElement||i.fragment||i.spectorName||i)+"\n"+t}:{vertexSourceCode:e,fragmentSourceCode:t}}(c.vertexCode,c.fragmentCode,t,n);s?.(u.vertexSourceCode,u.fragmentSourceCode)}),o)}};d(h,"Vertex","",(t=>{(0,a.pB)(e),(0,a.M0)(t,e,((e,r)=>{l&&(l._rawVertexSourceCode=t,l._vertexSourceCodeBeforeMigration=r),i&&(e=i("vertex",e)),f[0]=e,p()}),o)}),n),d(c,"Fragment","Pixel",(e=>{l&&(l._rawFragmentSourceCode=e),f[1]=e,p()}),n)}function d(e,t,i,s,o,a){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void s((0,r.Zl)(e));if("source:"===e.substring(0,7))return void s(e.substring(7));if("base64:"===e.substring(0,7))return void s(window.atob(e.substring(7)));const h=n.l.GetShadersStore(o);if(h[e+t+"Shader"])return void s(h[e+t+"Shader"]);if(i&&h[e+i+"Shader"])return void s(h[e+i+"Shader"]);let c;if(c="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:n.l.GetShadersRepository(o)+e,!(a=a||l.W0))throw new Error("loadFileInjection is not defined");a(c+"."+t.toLowerCase()+".fx",s)}const f=(e,t,i,r)=>{try{const n=e.existingPipelineContext||t(e.shaderProcessingContext);return n._name=e.name,e.name&&e.context&&((0,s.N5)(e.context).cachedPipelines[e.name]=n),i(n,e.vertex,e.fragment,!!e.createAsRaw,"","",e.rebuildRebind,e.defines,e.transformFeedbackVaryings,"",(()=>{r(n,(()=>{e.onRenderingStateCompiled?.(n)}))})),n}catch(e){throw o.V.Error("Error compiling effect"),e}}},36217:(e,t,i)=>{"use strict";i.d(t,{M:()=>a});var r=i(43279),s=i(60590),n=i(69841),o=i(73010);class a{static get ShadersRepository(){return n.l.ShadersRepository}static set ShadersRepository(e){n.l.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new r.cP),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,s=null,n,l=null,h=null,c=null,u=null,d,f="",p=0,_){this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new r.cP,this.onErrorObservable=new r.cP,this._onBindObservable=null,this._isDisposed=!1,this._refCount=1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=f;const m=this._key.replace(/\r/g,"").replace(/\n/g,"|");let g;if(t.attributes){const e=t;if(this._engine=i,this._attributesNames=e.attributes,this._uniformsNames=e.uniformsNames.concat(e.samplers),this._samplerList=e.samplers.slice(),this.defines=e.defines,this.onError=e.onError,this.onCompiled=e.onCompiled,this._fallbacks=e.fallbacks,this._indexParameters=e.indexParameters,this._transformFeedbackVaryings=e.transformFeedbackVaryings||null,this._multiTarget=!!e.multiTarget,this._shaderLanguage=e.shaderLanguage??0,e.uniformBuffersNames){this._uniformBuffersNamesList=e.uniformBuffersNames.slice();for(let t=0;t{this._vertexSourceCode=e,this._fragmentSourceCode=i,this._prepareEffect(t)}),this._shaderLanguage,this._engine,this)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!this._engine.isDisposed||!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}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){this.isReady()?e(this):(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){return void this._processCompilationErrors(t,e)}this._isDisposed||setTimeout((()=>{this._checkIsReady(e)}),16)}get vertexSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:this._pipelineContext?._getVertexShaderCode()??this._vertexSourceCode}get fragmentSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:this._pipelineContext?._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("\n"),addGlobalDefines:!1,extendedProcessingOptions:{indexParameters:this._indexParameters,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,supportsUniformBuffers:this._engine.supportsUniformBuffers},extendedCreatePipelineOptions:{transformFeedbackVaryings:this._transformFeedbackVaryings,createAsRaw:!(!this._vertexSourceCodeOverride||!this._fragmentSourceCodeOverride)}}}_rebuildProgram(e,t,i,r){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{r&&r(t)},this.onCompiled=()=>{const e=this.getEngine().scenes;if(e)for(let t=0;tthis._rebuildProgram(e,t,i,r),defines:r,transformFeedbackVaryings:this._transformFeedbackVaryings,name:this._key.replace(/\r/g,"").replace(/\n/g,"|"),createAsRaw:i,parallelShaderCompile:a._caps.parallelShaderCompile,shaderProcessingContext:this._processingContext,onRenderingStateCompiled:i=>{t&&!e&&this._engine._deletePipelineContext(t),i&&this._onRenderingStateCompiled(i)}},this._engine.createPipelineContext.bind(this._engine),this._engine._preparePipelineContext.bind(this._engine),this._engine._executeWhenRenderingStateIsCompiled.bind(this._engine)),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(e){this._processCompilationErrors(e,t)}}_getShaderCodeAndErrorLine(e,t,i){const r=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/;let s=null;if(t&&e){const n=t.match(r);if(n&&2===n.length){const t=parseInt(n[1]),r=e.split("\n",-1);r.length>=t&&(s=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${r[t-1]}`)}}return[e,s]}_processCompilationErrors(e,t=null){this._compilationError=e.message;const i=this._attributesNames,r=this._fallbacks;if(s.V.Error("Unable to compile effect:"),s.V.Error("Uniforms: "+this._uniformsNames.map((function(e){return" "+e}))),s.V.Error("Attributes: "+i.map((function(e){return" "+e}))),s.V.Error("Defines:\n"+this.defines),a.LogShaderCodeOnCompilationError){let e=null,t=null,i=null;this._pipelineContext?._getVertexShaderCode()&&([i,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),i&&(s.V.Error("Vertex code:"),s.V.Error(i))),this._pipelineContext?._getFragmentShaderCode()&&([i,t]=this._getShaderCodeAndErrorLine(this._pipelineContext?._getFragmentShaderCode(),this._compilationError,!0),i&&(s.V.Error("Fragment code:"),s.V.Error(i))),e&&s.V.Error(e),t&&s.V.Error(t)}s.V.Error("Error: "+this._compilationError);const n=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,n()),r?(this._pipelineContext=null,r.hasMoreFallbacks?(this._allFallbacksProcessed=!1,s.V.Error("Trying next fallback."),this.defines=r.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,n(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||n())}get isSupported(){return""===this._compilationError}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){const r=this._samplerList.indexOf(e);for(let e=1;e0||this._isDisposed||(this._pipelineContext&&(0,o.mO)(this._pipelineContext),this._engine._releaseEffect(this),this.clearCodeCache(),this._isDisposed=!0)}static RegisterShader(e,t,i,r=0){t&&(n.l.GetShadersStore(r)[`${e}PixelShader`]=t),i&&(n.l.GetShadersStore(r)[`${e}VertexShader`]=i)}static ResetCache(){a._BaseCache={}}}a.LogShaderCodeOnCompilationError=!0,a.AutomaticallyClearCodeCache=!1,a._UniqueIdSeed=0,a._BaseCache={},a.ShadersStore=n.l.ShadersStore,a.IncludesShadersStore=n.l.IncludesShadersStore},50606:(e,t,i)=>{"use strict";i.d(t,{$:()=>c,J:()=>h});var r=i(12721),s=i(13093),n=i(43279),o=i(36217),a=i(15311);i(18013);const l={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class h{constructor(e,t=l){this._fullscreenViewport=new s.L(0,0,1,1);const i=t.positions??l.positions,n=t.indices??l.indices;this.engine=e,this._vertexBuffers={[r.R.PositionKind]:new r.R(e,i,r.R.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(n),this._onContextRestoredObserver=e.onContextRestoredObservable.add((()=>{this._indexBuffer=e.createIndexBuffer(n);for(const e in this._vertexBuffers)this._vertexBuffers[e]._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 void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();const i=null===t?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[r.R.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[r.R.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class c{static RegisterShaderCodeProcessing(e,t){t?c._CustomShaderCodeProcessing[e??""]=t:delete c._CustomShaderCodeProcessing[e??""]}static _GetShaderCodeProcessing(e){return c._CustomShaderCodeProcessing[e]??c._CustomShaderCodeProcessing[""]}get name(){return this.options.name}set name(e){this.options.name=e}isReady(){return this._drawWrapper.effect?.isReady()??!1}get drawWrapper(){return this._drawWrapper}get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){this.alphaMode=0,this.onEffectCreatedObservable=new n.cP(void 0,!0),this.onApplyObservable=new n.cP,this._shadersLoaded=!1,this._webGPUReady=!1,this._importPromises=[],this.options={...e,name:e.name||"effectWrapper",engine:e.engine,uniforms:e.uniforms||e.uniformNames||[],uniformNames:void 0,samplers:e.samplers||e.samplerNames||[],samplerNames:void 0,attributeNames:e.attributeNames||["position"],uniformBuffers:e.uniformBuffers||[],defines:e.defines||"",useShaderStore:e.useShaderStore||!1,vertexUrl:e.vertexUrl||e.vertexShader||"postprocess",vertexShader:void 0,fragmentShader:e.fragmentShader||"pass",indexParameters:e.indexParameters,blockCompilation:e.blockCompilation||!1,shaderLanguage:e.shaderLanguage||0,onCompiled:e.onCompiled||void 0,extraInitializations:e.extraInitializations||void 0,extraInitializationsAsync:e.extraInitializationsAsync||void 0,useAsPostProcess:e.useAsPostProcess??!1},this.options.uniformNames=this.options.uniforms,this.options.samplerNames=this.options.samplers,this.options.vertexShader=this.options.vertexUrl,this.options.useAsPostProcess&&(-1===this.options.samplers.indexOf("textureSampler")&&this.options.samplers.push("textureSampler"),-1===this.options.uniforms.indexOf("scale")&&this.options.uniforms.push("scale")),e.vertexUrl||e.vertexShader?this._shaderPath={vertexSource:this.options.vertexShader}:(this.options.useAsPostProcess||(this.options.uniforms.push("scale"),this.onApplyObservable.add((()=>{this.effect.setFloat2("scale",1,1)}))),this._shaderPath={vertex:this.options.vertexShader}),this._shaderPath.fragmentSource=this.options.fragmentShader,this._shaderPath.spectorName=this.options.name,this.options.useShaderStore&&(this._shaderPath.fragment=this._shaderPath.fragmentSource,this._shaderPath.vertex||(this._shaderPath.vertex=this._shaderPath.vertexSource),delete this._shaderPath.fragmentSource,delete this._shaderPath.vertexSource),this.onApplyObservable.add((()=>{this.bind()})),this.options.useShaderStore||(this._onContextRestoredObserver=this.options.engine.onContextRestoredObservable.add((()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()}))),this._drawWrapper=new a.E(this.options.engine),this._webGPUReady=1===this.options.shaderLanguage;const t=Array.isArray(this.options.defines)?this.options.defines.join("\n"):this.options.defines;this._postConstructor(this.options.blockCompilation,t,this.options.extraInitializations)}_gatherImports(e=!1,t){this.options.useAsPostProcess&&(e&&this._webGPUReady?t.push(Promise.all([Promise.resolve().then(i.bind(i,45010))])):t.push(Promise.all([Promise.resolve().then(i.bind(i,18013))])))}_postConstructor(e,t=null,i,r){this._importPromises.length=0,r&&this._importPromises.push(...r);const s=this.options.engine.isWebGPU&&!c.ForceGLSL;this._gatherImports(s,this._importPromises),void 0!==i&&i(s,this._importPromises),s&&this._webGPUReady&&(this.options.shaderLanguage=1),e||this.updateEffect(t)}updateEffect(e=null,t=null,i=null,r,s,n,a,l){const h=c._GetShaderCodeProcessing(this.name);if(h?.defineCustomBindings){const r=t?.slice()??[];r.push(...this.options.uniforms);const s=i?.slice()??[];s.push(...this.options.samplers),e=h.defineCustomBindings(this.name,e,r,s),t=r,i=s}this.options.defines=e||"";const u=this._shadersLoaded||0===this._importPromises.length?void 0:async()=>{await Promise.all(this._importPromises),this._shadersLoaded=!0};let d;d=this.options.extraInitializationsAsync?async()=>{u?.(),await this.options.extraInitializationsAsync}:u,this.options.useShaderStore?this._drawWrapper.effect=this.options.engine.createEffect({vertex:a??this._shaderPath.vertex,fragment:l??this._shaderPath.fragment},{attributes:this.options.attributeNames,uniformsNames:t||this.options.uniforms,uniformBuffersNames:this.options.uniformBuffers,samplers:i||this.options.samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:s??this.options.onCompiled,onError:n??null,indexParameters:r||this.options.indexParameters,processCodeAfterIncludes:h?.processCodeAfterIncludes?(e,t)=>h.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:h?.processFinalCode?(e,t)=>h.processFinalCode(this.name,e,t):null,shaderLanguage:this.options.shaderLanguage,extraInitializationsAsync:d},this.options.engine):this._drawWrapper.effect=new o.M(this._shaderPath,this.options.attributeNames,t||this.options.uniforms,i||this.options.samplerNames,this.options.engine,e,void 0,s||this.options.onCompiled,void 0,void 0,void 0,this.options.shaderLanguage,d),this.onEffectCreatedObservable.notifyObservers(this._drawWrapper.effect)}bind(){this.options.useAsPostProcess&&(this.options.engine.setAlphaMode(this.alphaMode),this.drawWrapper.effect.setFloat2("scale",1,1)),c._GetShaderCodeProcessing(this.name)?.bindCustomBindings?.(this.name,this._drawWrapper.effect)}dispose(e=!1){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.onEffectCreatedObservable.clear(),this.effect.dispose()}}c.ForceGLSL=!1,c._CustomShaderCodeProcessing={}},61923:(e,t,i)=>{"use strict";i.d(t,{C:()=>n,_:()=>s});var r=i(90446);function s(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),(t.VIGNETTE||t.DITHER)&&e.push("vInverseScreenSize"),t.VIGNETTE&&(e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&(0,r.B)(e),t.DITHER&&e.push("ditherIntensity")}function n(e,t){t.COLORGRADING&&e.push("txColorTransform")}},69648:(e,t,i)=>{"use strict";i.d(t,{p:()=>d});var r=i(15287),s=i(40220),n=i(43279),o=i(11084),a=i(87741),l=i(44512),h=i(89518),c=i(61923),u=i(56225);class d{constructor(){this.colorCurves=new a.Q,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=d.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new o.ov(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=d.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new n.cP}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)return 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,void(e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled);if(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===d._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,this._toneMappingEnabled)switch(this._toneMappingType){case d.TONEMAPPING_KHR_PBR_NEUTRAL:e.TONEMAPPING=3;break;case d.TONEMAPPING_ACES:e.TONEMAPPING=2;break;default:e.TONEMAPPING=1}else e.TONEMAPPING=0;e.CONTRAST=1!==this.contrast,e.EXPOSURE=1!==this.exposure,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&&a.Q.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),r=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,r),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const s=null!=t?t:r/i;let n=Math.tan(.5*this.vignetteCameraFov),o=n*s;const a=Math.sqrt(o*n);o=(0,l.zF)(o,a,this.vignetteStretch),n=(0,l.zF)(n,a,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 t=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(t-1)/t,.5/t,t,this.colorGradingTexture.level)}}clone(){return h.p.Clone((()=>new d),this)}serialize(){return h.p.Serialize(this)}static Parse(e){const t=h.p.Parse((()=>new d),e,null,null);return void 0!==e.vignetteCentreX&&(t.vignetteCenterX=e.vignetteCentreX),void 0!==e.vignetteCentreY&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}}d.TONEMAPPING_STANDARD=0,d.TONEMAPPING_ACES=1,d.TONEMAPPING_KHR_PBR_NEUTRAL=2,d.PrepareUniforms=c._,d.PrepareSamplers=c.C,d._VIGNETTEMODE_MULTIPLY=0,d._VIGNETTEMODE_OPAQUE=1,(0,r.Cg)([(0,s.wL)()],d.prototype,"colorCurves",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_colorCurvesEnabled",void 0),(0,r.Cg)([(0,s.uM)("colorGradingTexture")],d.prototype,"_colorGradingTexture",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_colorGradingEnabled",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_colorGradingWithGreenDepth",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_colorGradingBGR",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_exposure",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_toneMappingEnabled",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_toneMappingType",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_contrast",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"vignetteStretch",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"vignetteCenterX",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"vignetteCenterY",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"vignetteWeight",void 0),(0,r.Cg)([(0,s.qK)()],d.prototype,"vignetteColor",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"vignetteCameraFov",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_vignetteBlendMode",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_vignetteEnabled",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_ditheringEnabled",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_ditheringIntensity",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_skipFinalColorClamp",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_applyByPostProcess",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_isEnabled",void 0),h.p._ImageProcessingConfigurationParser=d.Parse,(0,u.Y5)("BABYLON.ImageProcessingConfiguration",d)},85770:(e,t,i)=>{"use strict";i.d(t,{Bb:()=>G,DL:()=>c,ER:()=>E,GD:()=>U,IC:()=>D,IF:()=>f,J2:()=>x,Jz:()=>w,Kd:()=>T,L0:()=>S,MF:()=>d,N4:()=>V,Nc:()=>B,OR:()=>O,RL:()=>C,VO:()=>L,Y7:()=>k,YT:()=>g,Yy:()=>u,_8:()=>m,az:()=>I,c4:()=>P,f$:()=>b,fm:()=>R,lo:()=>M,mA:()=>v,nR:()=>_,ni:()=>y,qB:()=>F,qL:()=>A,te:()=>p,wu:()=>N});var r=i(60590),s=i(11084),n=i(34268),o=i(14952),a=i(57551);const l=s.v9.Black(),h={NUM_MORPH_INFLUENCERS:0};function c(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){const e=i.activeCamera;1===e.mode&&r.V.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}function u(e,t,i,r=!1){i&&e.fogEnabled&&(!t||t.applyFog)&&0!==e.fogMode&&(i.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),r?(e.fogColor.toLinearSpaceToRef(l,e.getEngine().useExactSrgbConversions),i.setColor3("vFogColor",l)):i.setColor3("vFogColor",e.fogColor))}function d(e,t,i){h.NUM_MORPH_INFLUENCERS=i,f(e,t,h)}function f(e,t,i){const s=i.NUM_MORPH_INFLUENCERS;if(s>0&&n.q.LastCreatedEngine){const o=n.q.LastCreatedEngine.getCaps().maxVertexAttribs,a=t.morphTargetManager;if(a?.isUsingTextureForTargets)return;const l=a&&a.supportsNormals&&i.NORMAL,h=a&&a.supportsTangents&&i.TANGENT,c=a&&a.supportsUVs&&i.UV1;for(let i=0;io&&r.V.Error("Cannot add more vertex attributes for mesh "+t.name)}}function p(e,t=!1){e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"),t&&(e.push("previousWorld0"),e.push("previousWorld1"),e.push("previousWorld2"),e.push("previousWorld3"))}function _(e,t){const i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}function m(e,t){t.bindToEffect(e,"Scene")}function g(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}function v(e,t,i){const r=e.getTextureMatrix();t.updateMatrix(i+"Matrix",r)}function x(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}function b(e,t,i){var r;if(t&&e&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){const s=e.skeleton;if(s.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureWidth")>-1){const i=s.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(s.bones.length+1))}else{const n=s.getTransformMatrices(e);n&&(t.setMatrices("mBones",n),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=n.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),r=n,i.previousBones[e.uniqueId].set(r)))}}}function S(e,t,i){e.transferToEffect(t,i+"")}function T(e,t,i,r,s,n=!0){e._bindLight(t,i,r,s,n)}function C(e,t,i,r,s=4){const n=Math.min(t.lightSources.length,s);for(let s=0;s0&&(r.addCPUSkinningFallback(0,t),e.push("matricesIndices"),e.push("matricesWeights"),i.NUM_BONE_INFLUENCERS>4&&(e.push("matricesIndicesExtra"),e.push("matricesWeightsExtra")))}function E(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&p(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push("instanceColor")}function P(e,t,i=4,r=0){let s=0;for(let n=0;n0&&(s=r+n,t.addFallback(s,"LIGHT"+n)),e.SHADOWS||(e["SHADOW"+n]&&t.addFallback(r,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(r,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(r,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(r,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(r,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(r,"SHADOWCLOSEESM"+n));return s++}function A(e,t){return t.fogEnabled&&e.applyFog&&0!==t.fogMode}function R(e,t,i,r,s,n,o,a=!1){o._areMiscDirty&&(o.LOGARITHMICDEPTH=i,o.POINTSIZE=r,o.FOG=s&&A(e,t),o.NONUNIFORMSCALING=e.nonUniformScaling,o.ALPHATEST=n,o.DECAL_AFTER_DETAIL=a)}function I(e,t,i,r,s=4,n=!1){if(!i._areLightsDirty)return i._needNormals;let o=0;const a={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n)for(const n of t.lightSources)if(M(e,t,n,o,i,r,a),o++,o===s)break;i.SPECULARTERM=a.specularEnabled,i.SHADOWS=a.shadowEnabled;for(let e=o;e0&&(a.shadowEnabled=!0,t.prepareDefines(s,r))}}i.lightmapMode!=o.c.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,s["LIGHTMAPEXCLUDED"+r]=!0,s["LIGHTMAPNOSPECULAR"+r]=i.lightmapMode==o.c.LIGHTMAP_SHADOWSONLY):(s["LIGHTMAPEXCLUDED"+r]=!1,s["LIGHTMAPNOSPECULAR"+r]=!1)}function O(e,t,i,r,s,n=null,o=!1){let l=k(e,r);!1!==n&&(l=(0,a.Eq)(i,e,r)),r.DEPTHPREPASS!==!t.getColorWrite()&&(r.DEPTHPREPASS=!r.DEPTHPREPASS,l=!0),r.INSTANCES!==s&&(r.INSTANCES=s,l=!0),r.THIN_INSTANCES!==o&&(r.THIN_INSTANCES=o,l=!0),l&&r.markAsUnprocessed()}function D(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;const i=void 0!==t.BONETEXTURE;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!i&&void 0;const r=e.getScene().prePassRenderer;if(r&&r.enabled){const i=-1===r.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=i}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}function w(e,t){const i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.NUM_MORPH_INFLUENCERS=i.numMaxInfluencers||i.numInfluencers,t.MORPHTARGETS=t.NUM_MORPH_INFLUENCERS>0,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}function N(e,t){const i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!(!i||!i.isEnabled)}function F(e,t,i,r,s=!1,n=!0,o=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent("normal"),t._needNormals&&e.isVerticesDataPresent("tangent")&&(t.TANGENT=!0);for(let i=1;i<=6;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);if(i){const i=e.useVertexColors&&e.isVerticesDataPresent("color");t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&n}return e.isVerticesDataPresent("instanceColor")&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),r&&D(e,t),s&&w(e,t),o&&N(e,t),!0}function L(e,t){if(e.activeCamera){const i=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}function B(e,t,i){const r=t.ORDER_INDEPENDENT_TRANSPARENCY,s=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,r===t.ORDER_INDEPENDENT_TRANSPARENCY&&s===t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS||t.markAsUnprocessed()}function V(e,t,i){const r=t.PREPASS;if(!t._arePrePassDirty)return;const s=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:9,define:"PREPASS_LOCAL_POSITION",index:"PREPASS_LOCAL_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:11,define:"PREPASS_VELOCITY_LINEAR",index:"PREPASS_VELOCITY_LINEAR_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:10,define:"PREPASS_SCREENSPACE_DEPTH",index:"PREPASS_SCREENSPACE_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"},{type:8,define:"PREPASS_WORLD_NORMAL",index:"PREPASS_WORLD_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace,t.PREPASS_COLOR=!0,t.PREPASS_COLOR_INDEX=0;for(let i=0;i{"use strict";i.d(t,{D:()=>n});var r=i(60590),s=i(9723);class n{constructor(e,t,i,r,s=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||s,this._dynamic=i,this._name=r??"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return void 0!==this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}_fillAlignment(e){let t;if(t=e<=2?e:4,this._uniformLocationPointer%t!=0){const e=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;const i=this._uniformLocationPointer-e;for(let e=0;e0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},16==t?t*=i:t=t*i+(4-t)*i,r=[];for(let e=0;e1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1]))return this._needSync=!1,void(this._createBufferOnWrite=this._engine._features.trackUbosInFrame);this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(n._UpdatedUbosInFrame[this._name]||(n._UpdatedUbosInFrame[this._name]=0),n._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}else this._createBufferOnWrite=this._engine._features.trackUbosInFrame;else this.create()}_createNewBuffer(){this._bufferIndex+10?(this._needSync=0!==this._bufferIndex,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(void 0===s){if(this._buffer)return void r.V.Error("Cannot add an uniform after UBO has been created. uniformName="+e);this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;e{"use strict";i.d(t,{$x:()=>r,_0:()=>o,xp:()=>s});var r,s,n=i(94212);!function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(r||(r={}));class o{}o.X=new n.Pq(1,0,0),o.Y=new n.Pq(0,1,0),o.Z=new n.Pq(0,0,1),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(s||(s={}))},11084:(e,t,i)=>{"use strict";i.d(t,{IG:()=>f,ov:()=>d,v9:()=>u});var r=i(34130),s=i(56225),n=i(34910),o=i(56984);function a(e){return Math.pow(e,n.tk)}function l(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function h(e){return Math.pow(e,n.rv)}function c(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}class u{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=255*this.r|0;return e=397*e^255*this.g,e=397*e^255*this.b,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 u.FromArrayToRef(e,t,this),this}toColor4(e=1){return new d(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return.3*this.r+.59*this.g+.11*this.b}multiply(e){return new u(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 u(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=n.bH){return(0,o.WithinEpsilon)(this.r,e.r,t)&&(0,o.WithinEpsilon)(this.g,e.g,t)&&(0,o.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 u(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=(0,o.Clamp)(this.r,e,t),i.g=(0,o.Clamp)(this.g,e,t),i.b=(0,o.Clamp)(this.b,e,t),i}add(e){return new u(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 u(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 u(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-i,r}clone(){return new u(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(255*this.r),t=Math.round(255*this.g),i=Math.round(255*this.b);return"#"+(0,o.ToHex)(e)+(0,o.ToHex)(t)+(0,o.ToHex)(i)}fromHexString(e){return"#"!==e.substring(0,1)||7!==e.length||(this.r=parseInt(e.substring(1,3),16)/255,this.g=parseInt(e.substring(3,5),16)/255,this.b=parseInt(e.substring(5,7),16)/255),this}toHSV(){return this.toHSVToRef(new u)}toHSVToRef(e){const t=this.r,i=this.g,r=this.b,s=Math.max(t,i,r),n=Math.min(t,i,r);let o=0,a=0;const l=s,h=s-n;return 0!==s&&(a=h/s),s!=n&&(s==t?(o=(i-r)/h,i=0&&n<=1?(a=s,l=o):n>=1&&n<=2?(a=o,l=s):n>=2&&n<=3?(l=s,h=o):n>=3&&n<=4?(l=o,h=s):n>=4&&n<=5?(a=o,h=s):n>=5&&n<=6&&(a=s,h=o);const c=i-s;return r.r=a+c,r.g=l+c,r.b=h+c,r}static FromHSV(e,t,i){const r=new u(0,0,0);return u.HSVtoRGBToRef(e,t,i,r),r}static FromHexString(e){return new u(0,0,0).fromHexString(e)}static FromArray(e,t=0){return new u(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 u(e/255,t/255,i/255)}static Lerp(e,t,i){const r=new u(0,0,0);return u.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,r,s){const n=s*s,o=s*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+s,c=o-n,d=e.r*a+i.r*l+t.r*h+r.r*c,f=e.g*a+i.g*l+t.g*h+r.g*c,p=e.b*a+i.b*l+t.b*h+r.b*c;return new u(d,f,p)}static Hermite1stDerivative(e,t,i,r,s){const n=u.Black();return this.Hermite1stDerivativeToRef(e,t,i,r,s,n),n}static Hermite1stDerivativeToRef(e,t,i,r,s,n){const o=s*s;n.r=6*(o-s)*e.r+(3*o-4*s+1)*t.r+6*(-o+s)*i.r+(3*o-2*s)*r.r,n.g=6*(o-s)*e.g+(3*o-4*s+1)*t.g+6*(-o+s)*i.g+(3*o-2*s)*r.g,n.b=6*(o-s)*e.b+(3*o-4*s+1)*t.b+6*(-o+s)*i.b+(3*o-2*s)*r.b}static Red(){return new u(1,0,0)}static Green(){return new u(0,1,0)}static Blue(){return new u(0,0,1)}static Black(){return new u(0,0,0)}static get BlackReadOnly(){return u._BlackReadOnly}static White(){return new u(1,1,1)}static Purple(){return new u(.5,0,.5)}static Magenta(){return new u(1,0,1)}static Yellow(){return new u(1,1,0)}static Gray(){return new u(.5,.5,.5)}static Teal(){return new u(0,1,1)}static Random(){return new u(Math.random(),Math.random(),Math.random())}}u._BlackReadOnly=u.Black(),Object.defineProperties(u.prototype,{dimension:{value:[3]},rank:{value:1}});class d{constructor(e=0,t=0,i=0,r=1){this.r=e,this.g=t,this.b=i,this.a=r}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new d(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}addInPlaceFromFloats(e,t,i,r){return this.r+=e,this.g+=t,this.b+=i,this.a+=r,this}subtract(e){return new d(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this}subtractFromFloats(e,t,i,r){return new d(this.r-e,this.g-t,this.b-i,this.a-r)}subtractFromFloatsToRef(e,t,i,r,s){return s.r=this.r-e,s.g=this.g-t,s.b=this.b-i,s.a=this.a-r,s}scale(e){return new d(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=(0,o.Clamp)(this.r,e,t),i.g=(0,o.Clamp)(this.g,e,t),i.b=(0,o.Clamp)(this.b,e,t),i.a=(0,o.Clamp)(this.a,e,t),i}multiply(e){return new d(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this}multiplyByFloats(e,t,i,r){return new d(this.r*e,this.g*t,this.b*i,this.a*r)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this}maximizeInPlace(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this}minimizeInPlaceFromFloats(e,t,i,r){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this.a=Math.min(r,this.a),this}maximizeInPlaceFromFloats(e,t,i,r){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this.a=Math.max(r,this.a),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}equalsWithEpsilon(e,t=n.bH){return(0,o.WithinEpsilon)(this.r,e.r,t)&&(0,o.WithinEpsilon)(this.g,e.g,t)&&(0,o.WithinEpsilon)(this.b,e.b,t)&&(0,o.WithinEpsilon)(this.a,e.a,t)}equalsToFloats(e,t,i,r){return this.r===e&&this.g===t&&this.b===i&&this.a===r}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=255*this.r|0;return e=397*e^255*this.g,e=397*e^255*this.b,e=397*e^255*this.a,e}clone(){return(new d).copyFrom(this)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,r){return this.r=e,this.g=t,this.b=i,this.a=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){const t=Math.round(255*this.r),i=Math.round(255*this.g),r=Math.round(255*this.b);if(e)return"#"+(0,o.ToHex)(t)+(0,o.ToHex)(i)+(0,o.ToHex)(r);const s=Math.round(255*this.a);return"#"+(0,o.ToHex)(t)+(0,o.ToHex)(i)+(0,o.ToHex)(r)+(0,o.ToHex)(s)}fromHexString(e){return"#"!==e.substring(0,1)||9!==e.length&&7!==e.length||(this.r=parseInt(e.substring(1,3),16)/255,this.g=parseInt(e.substring(3,5),16)/255,this.b=parseInt(e.substring(5,7),16)/255,9===e.length&&(this.a=parseInt(e.substring(7,9),16)/255)),this}toLinearSpace(e=!1){const t=new d;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=l(this.r),e.g=l(this.g),e.b=l(this.b)):(e.r=a(this.r),e.g=a(this.g),e.b=a(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new d;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=c(this.r),e.g=c(this.g),e.b=c(this.b)):(e.r=h(this.r),e.g=h(this.g),e.b=h(this.b)),e.a=this.a,this}static FromHexString(e){return"#"!==e.substring(0,1)||9!==e.length&&7!==e.length?new d(0,0,0,0):new d(0,0,0,1).fromHexString(e)}static Lerp(e,t,i){return d.LerpToRef(e,t,i,new d)}static LerpToRef(e,t,i,r){return r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i,r.a=e.a+(t.a-e.a)*i,r}static Hermite(e,t,i,r,s){const n=s*s,o=s*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+s,c=o-n,u=e.r*a+i.r*l+t.r*h+r.r*c,f=e.g*a+i.g*l+t.g*h+r.g*c,p=e.b*a+i.b*l+t.b*h+r.b*c,_=e.a*a+i.a*l+t.a*h+r.a*c;return new d(u,f,p,_)}static Hermite1stDerivative(e,t,i,r,s){const n=new d;return this.Hermite1stDerivativeToRef(e,t,i,r,s,n),n}static Hermite1stDerivativeToRef(e,t,i,r,s,n){const o=s*s;n.r=6*(o-s)*e.r+(3*o-4*s+1)*t.r+6*(-o+s)*i.r+(3*o-2*s)*r.r,n.g=6*(o-s)*e.g+(3*o-4*s+1)*t.g+6*(-o+s)*i.g+(3*o-2*s)*r.g,n.b=6*(o-s)*e.b+(3*o-4*s+1)*t.b+6*(-o+s)*i.b+(3*o-2*s)*r.b,n.a=6*(o-s)*e.a+(3*o-4*s+1)*t.a+6*(-o+s)*i.a+(3*o-2*s)*r.a}static FromColor3(e,t=1){return new d(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new d(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,r){return new d(e/255,t/255,i/255,r/255)}static CheckColors4(e,t){if(e.length===3*t){const t=[];for(let i=0;inew d(0,0,0,0))),(0,s.Y5)("BABYLON.Color3",u),(0,s.Y5)("BABYLON.Color4",d)},34910:(e,t,i)=>{"use strict";i.d(t,{a6:()=>n,bH:()=>o,rv:()=>r,tk:()=>s});const r=1/2.2,s=2.2,n=(1+Math.sqrt(5))/2,o=.001},59881:(e,t,i)=>{"use strict";i.d(t,{P:()=>s});var r=i(30573);class s{static GetPlanes(e){const t=[];for(let e=0;e<6;e++)t.push(new r.Z(0,0,0,0));return s.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){s.GetNearPlaneToRef(e,t[0]),s.GetFarPlaneToRef(e,t[1]),s.GetLeftPlaneToRef(e,t[2]),s.GetRightPlaneToRef(e,t[3]),s.GetTopPlaneToRef(e,t[4]),s.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}}},890:(e,t,i)=>{"use strict";i.d(t,{Y4:()=>h,b8:()=>l,cD:()=>a});var r=i(15287),s=i(94212),n=i(40220);class o{static extractMinAndMaxIndexed(e,t,i,r,s,n){for(let o=i;o=0&&(t[i]=p,t[i+2]=l)}}(0,r.Cg)([n.Cx.filter(((...[e,t])=>!Array.isArray(e)&&!Array.isArray(t)))],o,"extractMinAndMaxIndexed",null),(0,r.Cg)([n.Cx.filter(((...[e])=>!Array.isArray(e)))],o,"extractMinAndMax",null)},73864:(e,t,i)=>{"use strict";i.d(t,{uM:()=>a.uM,Xy:()=>a.Xy,_0:()=>r._0,vr:()=>a.vr,v9:()=>s.v9,ov:()=>s.ov,xp:()=>r.xp,jj:()=>a.jj,bH:()=>n.bH,PP:()=>o.P,uq:()=>c.uq,t4:()=>a.t4,a6:()=>n.a6,Cu:()=>a.Cu,tO:()=>a.tO,Zc:()=>l.Z,k0:()=>d,B5:()=>u,PT:()=>c.PT,or:()=>h.o,$x:()=>r.$x,IG:()=>s.IG,AA:()=>c.AA,rv:()=>n.rv,tk:()=>n.tk,I9:()=>c.I9,Pq:()=>c.Pq,IU:()=>c.IU,LM:()=>f.L});var r=i(4514),s=i(11084),n=i(34910),o=i(59881),a=i(50324),l=i(30573),h=i(29962),c=i(94212);class u{constructor(e=c.Pq.Zero(),t=c.Pq.Up()){this.position=e,this.normal=t}clone(){return new u(this.position.clone(),this.normal.clone())}}class d{constructor(e=c.Pq.Zero(),t=c.Pq.Up(),i=c.I9.Zero()){this.position=e,this.normal=t,this.uv=i}clone(){return new d(this.position.clone(),this.normal.clone(),this.uv.clone())}}var f=i(13093)},50324:(e,t,i)=>{"use strict";i.d(t,{Cu:()=>c,Xy:()=>h,jj:()=>d,t4:()=>r,tO:()=>u,uM:()=>l,vr:()=>a});var r,s=i(56984),n=i(94212),o=i(34910);!function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(r||(r={}));class a{static Interpolate(e,t,i,r,s){const n=1-3*r+3*t,o=3*r-6*t,a=3*t;let l=e;for(let t=0;t<5;t++){const t=l*l;l-=1/(3*n*t+2*o*l+a)*(n*(t*l)+o*t+a*l-e),l=Math.min(1,Math.max(0,l))}return 3*Math.pow(1-l,2)*l*i+3*(1-l)*Math.pow(l,2)*s+Math.pow(l,3)}}class l{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return 180*this._radians/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){const i=t.subtract(e),r=Math.atan2(i.y,i.x);return new l(r)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(0===i)return new l(Math.PI/2);i=Math.sqrt(i);let r=e.dot(t)/i;r=(0,s.Clamp)(r,-1,1);const n=Math.acos(r);return new l(n)}static FromRadians(e){return new l(e)}static FromDegrees(e){return new l(e*Math.PI/180)}}class h{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;const r=Math.pow(t.x,2)+Math.pow(t.y,2),s=(Math.pow(e.x,2)+Math.pow(e.y,2)-r)/2,o=(r-Math.pow(i.x,2)-Math.pow(i.y,2))/2,a=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new n.I9((s*(t.y-i.y)-o*(e.y-t.y))/a,((e.x-t.x)*o-(t.x-i.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);const h=this.startAngle.degrees();let c=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();c-h>180&&(c-=360),c-h<-180&&(c+=360),u-c>180&&(u-=360),u-c<-180&&(u+=360),this.orientation=c-h<0?0:1,this.angle=l.FromDegrees(0===this.orientation?h-u:u-h)}}class c{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new n.I9(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new n.I9(e,t),r=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(r).length(),this}addArcTo(e,t,i,r,s=36){if(this.closed)return this;const o=this._points[this._points.length-1],a=new n.I9(e,t),l=new n.I9(i,r),c=new h(o,a,l);let u=c.angle.radians()/s;0===c.orientation&&(u*=-1);let d=c.startAngle.radians()+u;for(let e=0;e(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r,o=this._points[this._points.length-1];for(let a=0;a<=s;a++){const l=a/s,h=n(l,o.x,e,i),c=n(l,o.y,t,r);this.addLineTo(h,c)}return this}addBezierCurveTo(e,t,i,r,s,n,o=36){if(this.closed)return this;const a=(e,t,i,r,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*s,l=this._points[this._points.length-1];for(let h=0;h<=o;h++){const c=h/o,u=a(c,l.x,e,i,s),d=a(c,l.y,t,r,n);this.addLineTo(u,d)}return this}isPointInside(e){let t=!1;const i=this._points.length;for(let r=i-1,s=0;sNumber.EPSILON){if(a<0&&(i=this._points[s],o=-o,n=this._points[r],a=-a),e.yn.y)continue;if(e.y===i.y&&e.x===i.x)return!0;{const r=a*(e.x-i.x)-o*(e.y-i.y);if(0===r)return!0;if(r<0)continue;t=!t}}else{if(e.y!==i.y)continue;if(n.x<=e.x&&e.x<=i.x||i.x<=e.x&&e.x<=n.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];e+=this._points[0].subtract(t).length()}return e}area(){const e=this._points.length;let t=0;for(let i=e-1,r=0;r1)return n.I9.Zero();const t=e*this.length();let i=0;for(let e=0;e=i&&t<=a){const e=o.normalize(),r=t-i;return new n.I9(s.x+e.x*r,s.y+e.y*r)}i=a}return n.I9.Zero()}static StartingAt(e,t){return new c(e,t)}}class u{constructor(e,t=null,i,r=!1){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:n.Pq.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:n.uq.Identity()};for(let t=0;tt){const i=e;e=t,t=i}const i=this.getCurve(),r=this.getPointAt(e);let s=this.getPreviousPointIndexAt(e);const n=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,a=[];return 0!==e&&(s++,a.push(r)),a.push(...i.slice(s,o)),1===t&&1!==e||a.push(n),new u(a,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let t=0;tt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,r=e.length();if(0===r&&(r=1),null==t){let t;t=(0,s.WithinEpsilon)(Math.abs(e.y)/r,1,o.bH)?(0,s.WithinEpsilon)(Math.abs(e.x)/r,1,o.bH)?(0,s.WithinEpsilon)(Math.abs(e.z)/r,1,o.bH)?n.Pq.Zero():new n.Pq(0,0,1):new n.Pq(1,0,0):new n.Pq(0,-1,0),i=n.Pq.Cross(e,t)}else i=n.Pq.Cross(e,t),n.Pq.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;const i=this.getPoints();if(e<=0)return this._setPointAtData(0,0,i[0],0,t);if(e>=1)return this._setPointAtData(1,1,i[i.length-1],i.length-1,t);let r,s=i[0],o=0;const a=e*this.length();for(let l=1;la){const i=(o-a)/h,n=s.subtract(r),c=r.add(n.scaleInPlace(i));return this._setPointAtData(e,1-i,c,l-1,t)}s=r}return this._pointAtData}_setPointAtData(e,t,i,r,s){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=r,this._pointAtData.interpolateReady=s,s&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=n.uq.Identity();const e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){const t=e+1,i=this._tangents[e].clone(),r=this._normals[e].clone(),s=this._binormals[e].clone(),o=this._tangents[t].clone(),a=this._normals[t].clone(),l=this._binormals[t].clone(),h=n.PT.RotationQuaternionFromAxis(r,s,i),c=n.PT.RotationQuaternionFromAxis(a,l,o);n.PT.Slerp(h,c,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class d{static CreateQuadraticBezier(e,t,i,r){r=r>2?r:3;const s=[],o=(e,t,i,r)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r;for(let a=0;a<=r;a++)s.push(new n.Pq(o(a/r,e.x,t.x,i.x),o(a/r,e.y,t.y,i.y),o(a/r,e.z,t.z,i.z)));return new d(s)}static CreateCubicBezier(e,t,i,r,s){s=s>3?s:4;const o=[],a=(e,t,i,r,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*s;for(let l=0;l<=s;l++)o.push(new n.Pq(a(l/s,e.x,t.x,i.x,r.x),a(l/s,e.y,t.y,i.y,r.y),a(l/s,e.z,t.z,i.z,r.z)));return new d(o)}static CreateHermiteSpline(e,t,i,r,s){const o=[],a=1/s;for(let l=0;l<=s;l++)o.push(n.Pq.Hermite(e,t,i,r,l*a));return new d(o)}static CreateCatmullRomSpline(e,t,i){const r=[],s=1/t;let o=0;if(i){const i=e.length;for(let a=0;a{"use strict";i.d(t,{Z:()=>s});var r=i(94212);class s{constructor(e,t,i,s){this.normal=new r.Pq(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new s(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=397*e^this.d,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 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){const t=s._TmpMatrix;e.invertToRef(t);const i=t.m,r=this.normal.x,n=this.normal.y,o=this.normal.z,a=this.d,l=r*i[0]+n*i[1]+o*i[2]+a*i[3],h=r*i[4]+n*i[5]+o*i[6]+a*i[7],c=r*i[8]+n*i[9]+o*i[10]+a*i[11],u=r*i[12]+n*i[13]+o*i[14]+a*i[15];return new s(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 r=t.x-e.x,s=t.y-e.y,n=t.z-e.z,o=i.x-e.x,a=i.y-e.y,l=i.z-e.z,h=s*l-n*a,c=n*o-r*l,u=r*a-s*o,d=Math.sqrt(h*h+c*c+u*u);let f;return f=0!==d?1/d:0,this.normal.x=h*f,this.normal.y=c*f,this.normal.z=u*f,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return r.Pq.Dot(this.normal,e)<=t}signedDistanceTo(e){return r.Pq.Dot(e,this.normal)+this.d}static FromArray(e){return new s(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const r=new s(0,0,0,0);return r.copyFromPoints(e,t,i),r}static FromPositionAndNormal(e,t){const i=new s(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 r.Pq.Dot(i,t)+s}}s._TmpMatrix=r.uq.Identity()},56984:(e,t,i)=>{"use strict";function r(e){return parseInt(e.toString().replace(/\W/g,""))}function s(e,t,i=1401298e-51){return Math.abs(e-t)<=i}function n(e,t){return e===t?e:Math.random()*(t-e)+e}function o(e,t,i){return e+(t-e)*i}function a(e,t,i){let r=_(t-e,360);return r>180&&(r-=360),e+r*u(i)}function l(e,t,i){let r=0;return r=e!=t?u((i-e)/(t-e)):0,r}function h(e,t,i,r,s){const n=s*s,o=s*n;return e*(2*o-3*n+1)+i*(-2*o+3*n)+t*(o-2*n+s)+r*(o-n)}function c(e,t,i,r,s){const n=s*s;return 6*(n-s)*e+(3*n-4*s+1)*t+6*(-n+s)*i+(3*n-2*s)*r}function u(e,t=0,i=1){return Math.min(i,Math.max(t,e))}function d(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function f(e){const t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()}function p(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(0===e)return-1/0;let t=0;if(e<1){for(;e<1;)t++,e*=2;t=-t}else if(e>1)for(;e>1;)t++,e=Math.floor(e/2);return t}function _(e,t){return e-Math.floor(e/t)*t}function m(e,t,i){return(e-t)/(i-t)}function g(e,t,i){return e*(i-t)+t}function v(e,t){let i=_(t-e,360);return i>180&&(i-=360),i}function x(e,t){const i=_(e,2*t);return t-Math.abs(i-t)}function b(e,t,i){let r=u(i);return r=-2*r*r*r+3*r*r,t*r+e*(1-r)}function S(e,t,i){let r=0;return r=Math.abs(t-e)<=i?t:e+Math.sign(t-e)*i,r}function T(e,t,i){const r=v(e,t);let s=0;return s=-iu,DeltaAngle:()=>v,Denormalize:()=>g,ExtractAsInt:()=>r,Hermite:()=>h,Hermite1stDerivative:()=>c,HighestCommonFactor:()=>E,ILog2:()=>p,InverseLerp:()=>l,Lerp:()=>o,LerpAngle:()=>a,MoveTowards:()=>S,MoveTowardsAngle:()=>T,Normalize:()=>m,NormalizeRadians:()=>d,PercentToRange:()=>y,PingPong:()=>x,RandomRange:()=>n,RangeToPercent:()=>C,Repeat:()=>_,SmoothStep:()=>b,ToHex:()=>f,WithinEpsilon:()=>s})},29962:(e,t,i)=>{"use strict";i.d(t,{o:()=>r});class r{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){let e=0|this.width;return e=397*e^this.height,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 r(this.width*e,this.height*t)}clone(){return new r(this.width,this.height)}equals(e){return!!e&&this.width===e.width&&this.height===e.height}get surface(){return this.width*this.height}static Zero(){return new r(0,0)}add(e){return new r(this.width+e.width,this.height+e.height)}subtract(e){return new r(this.width-e.width,this.height-e.height)}scale(e){return new r(this.width*e,this.height*e)}static Lerp(e,t,i){const s=e.width+(t.width-e.width)*i,n=e.height+(t.height-e.height)*i;return new r(s,n)}}},94212:(e,t,i)=>{"use strict";i.d(t,{AA:()=>m,I9:()=>c,IU:()=>d,PT:()=>f,Pq:()=>u,uq:()=>p});var r=i(34910),s=i(34130),n=i(56225),o=i(82352),a=i(34268),l=i(56984);const h=e=>parseInt(e.toString().replace(/\W/g,""));class c{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let e=h(this.x);return e=397*e^h(this.y),e}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return c.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 c(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 c(this.x+e.x,this.y+e.y)}subtract(e){return new c(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 c(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 c(this.x*e,this.y*t)}divide(e){return new c(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 c(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,i){return i.x=this.x-e,i.y=this.y-t,i}negate(){return new c(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.x=-this.x,e.y=-this.y,e}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){return new c(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=r.bH){return e&&(0,l.WithinEpsilon)(this.x,e.x,t)&&(0,l.WithinEpsilon)(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new c(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 c(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e}rotateToRef(e,t){const i=Math.cos(e),r=Math.sin(e),s=i*this.x-r*this.y,n=r*this.x+i*this.y;return t.x=s,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 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new c;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t&&(e.x=this.x,e.y=this.y),this.scaleToRef(1/t,e)}clone(){return new c(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new c(0,0)}static One(){return new c(1,1)}static Random(e=0,t=1){return new c((0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats((0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t))}static get ZeroReadOnly(){return c._ZeroReadOnly}static FromArray(e,t=0){return new c(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static FromFloatsToRef(e,t,i){return i.copyFromFloats(e,t),i}static CatmullRom(e,t,i,r,s){const n=s*s,o=s*n,a=.5*(2*t.x+(-e.x+i.x)*s+(2*e.x-5*t.x+4*i.x-r.x)*n+(-e.x+3*t.x-3*i.x+r.x)*o),l=.5*(2*t.y+(-e.y+i.y)*s+(2*e.y-5*t.y+4*i.y-r.y)*n+(-e.y+3*t.y-3*i.y+r.y)*o);return new c(a,l)}static ClampToRef(e,t,i,r){return r.x=(0,l.Clamp)(e.x,t.x,i.x),r.y=(0,l.Clamp)(e.y,t.y,i.y),r}static Clamp(e,t,i){const r=(0,l.Clamp)(e.x,t.x,i.x),s=(0,l.Clamp)(e.y,t.y,i.y);return new c(r,s)}static Hermite(e,t,i,r,s){const n=s*s,o=s*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+s,u=o-n,d=e.x*a+i.x*l+t.x*h+r.x*u,f=e.y*a+i.y*l+t.y*h+r.y*u;return new c(d,f)}static Hermite1stDerivative(e,t,i,r,s){return this.Hermite1stDerivativeToRef(e,t,i,r,s,new c)}static Hermite1stDerivativeToRef(e,t,i,r,s,n){const o=s*s;return n.x=6*(o-s)*e.x+(3*o-4*s+1)*t.x+6*(-o+s)*i.x+(3*o-2*s)*r.x,n.y=6*(o-s)*e.y+(3*o-4*s+1)*t.y+6*(-o+s)*i.y+(3*o-2*s)*r.y,n}static Lerp(e,t,i){return c.LerpToRef(e,t,i,new c)}static LerpToRef(e,t,i,r){return r.x=e.x+(t.x-e.x)*i,r.y=e.y+(t.y-e.y)*i,r}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){return c.NormalizeToRef(e,new c)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=e.xt.x?e.x:t.x,r=e.y>t.y?e.y:t.y;return new c(i,r)}static Transform(e,t){return c.TransformToRef(e,t,new c)}static TransformToRef(e,t,i){const r=t.m,s=e.x*r[0]+e.y*r[4]+r[12],n=e.x*r[1]+e.y*r[5]+r[13];return i.x=s,i.y=n,i}static PointInTriangle(e,t,i,r){const s=.5*(-i.y*r.x+t.y*(-i.x+r.x)+t.x*(i.y-r.y)+i.x*r.y),n=s<0?-1:1,o=(t.y*r.x-t.x*r.y+(r.y-t.y)*e.x+(t.x-r.x)*e.y)*n,a=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*n;return o>0&&a>0&&o+a<2*s*n}static Distance(e,t){return Math.sqrt(c.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,r=e.y-t.y;return i*i+r*r}static Center(e,t){return c.CenterToRef(e,t,new c)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){const r=c.DistanceSquared(t,i);if(0===r)return c.Distance(e,t);const s=i.subtract(t),n=Math.max(0,Math.min(1,c.Dot(e.subtract(t),s)/r)),o=t.add(s.multiplyByFloats(n,n));return c.Distance(e,o)}}c._ZeroReadOnly=c.Zero(),Object.defineProperties(c.prototype,{dimension:{value:[2]},rank:{value:1}});class u{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(){let e=h(this._x);return e=397*e^h(this._y),e=397*e^h(this._z),e}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 u.FromArrayToRef(e,t,this),this}toQuaternion(){return f.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 u(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._isDirty=!0,t}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new u(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 u(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,r){return r._x=this._x-e,r._y=this._y-t,r._z=this._z-i,r._isDirty=!0,r}negate(){return new u(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e._x=-1*this._x,e._y=-1*this._y,e._z=-1*this._z,e._isDirty=!0,e}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new u(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._isDirty=!0,t}getNormalToRef(e){const t=this.length();let i=Math.acos(this.y/t);const r=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const s=t*Math.sin(i)*Math.cos(r),n=t*Math.cos(i),o=t*Math.sin(i)*Math.sin(r);return e.set(s,n,o),e}applyRotationQuaternionToRef(e,t){const i=this._x,r=this._y,s=this._z,n=e._x,o=e._y,a=e._z,l=e._w,h=2*(o*s-a*r),c=2*(a*i-n*s),u=2*(n*r-o*i);return t._x=i+l*h+o*u-a*c,t._y=r+l*c+a*h-n*u,t._z=s+l*u+n*c-o*h,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new u)}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._isDirty=!0,t}projectOnPlane(e,t){return this.projectOnPlaneToRef(e,t,new u)}projectOnPlaneToRef(e,t,i){const r=e.normal,s=e.d,n=_.Vector3[0];this.subtractToRef(t,n),n.normalize();const o=u.Dot(n,r);if(Math.abs(o)<1e-10)i.setAll(1/0);else{const e=-(u.Dot(t,r)+s)/o,a=n.scaleInPlace(e);t.addToRef(a,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=r.bH){return e&&(0,l.WithinEpsilon)(this._x,e._x,t)&&(0,l.WithinEpsilon)(this._y,e._y,t)&&(0,l.WithinEpsilon)(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t._x=this._x*e._x,t._y=this._y*e._y,t._z=this._z*e._z,t._isDirty=!0,t}multiplyByFloats(e,t,i){return new u(this._x*e,this._y*t,this._z*i)}divide(e){return new u(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t._x=this._x/e._x,t._y=this._y/e._y,t._z=this._z/e._z,t._isDirty=!0,t}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return ethis._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),i=Math.abs(this._y);if(!(0,l.WithinEpsilon)(t,i,e))return!0;const r=Math.abs(this._z);return!(0,l.WithinEpsilon)(t,r,e)||!(0,l.WithinEpsilon)(i,r,e)}get isNonUniform(){const e=Math.abs(this._x);return e!==Math.abs(this._y)||e!==Math.abs(this._z)}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 u(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 u(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("xyz"===(e=e.toLowerCase()))return this;const t=_.Vector3[0].copyFrom(this);return this.x=t[e[0]],this.y=t[e[1]],this.z=t[e[2]],this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(_.Matrix[0]),u.TransformCoordinatesToRef(this,_.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,_.Vector3[0]),_.Vector3[0].rotateByQuaternionToRef(e,_.Vector3[0]),t.addToRef(_.Vector3[0],i),i}cross(e){return u.CrossToRef(this,e,new u)}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new u)}normalizeToRef(e){const t=this.length();return 0===t||1===t?(e._x=this._x,e._y=this._y,e._z=this._z,e._isDirty=!0,e):this.scaleToRef(1/t,e)}clone(){return new u(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,r){const s=u.Dot(e,i);return(s-r)/(s-u.Dot(t,i))}static GetAngleBetweenVectors(e,t,i){const r=e.normalizeToRef(_.Vector3[1]),s=t.normalizeToRef(_.Vector3[2]);let n=u.Dot(r,s);n=(0,l.Clamp)(n,-1,1);const o=Math.acos(n),a=_.Vector3[3];return u.CrossToRef(r,s,a),u.Dot(a,i)>0?isNaN(o)?0:o:isNaN(o)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(e,t,i){_.Vector3[0].copyFrom(e);const r=_.Vector3[0];_.Vector3[1].copyFrom(t);const s=_.Vector3[1];_.Vector3[2].copyFrom(i);const n=_.Vector3[2],o=_.Vector3[3],a=_.Vector3[4];r.normalize(),s.normalize(),n.normalize(),u.CrossToRef(n,r,o),u.CrossToRef(o,n,a);const h=Math.atan2(u.Dot(s,o),u.Dot(s,a));return(0,l.NormalizeRadians)(h)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const r=m.Vector3[0];return t.subtractToRef(e,r),i._y=Math.atan2(r.x,r.z)||0,i._x=Math.atan2(Math.sqrt(r.x**2+r.z**2),r.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){const i=u.Zero();return u.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,s){i=(0,l.Clamp)(i,0,1);const n=_.Vector3[0],o=_.Vector3[1];n.copyFrom(e);const a=n.length();n.normalizeFromLength(a),o.copyFrom(t);const h=o.length();o.normalizeFromLength(h);const c=u.Dot(n,o);let d,f;if(c<1-r.bH){const e=Math.acos(c),t=1/Math.sin(e);d=Math.sin((1-i)*e)*t,f=Math.sin(i*e)*t}else d=1-i,f=i;return n.scaleInPlace(d),o.scaleInPlace(f),s.copyFrom(n).addInPlace(o),s.scaleInPlace((0,l.Lerp)(a,h,i)),s}static SmoothToRef(e,t,i,r,s){return u.SlerpToRef(e,t,0===r?1:i/r,s),s}static FromArray(e,t=0){return new u(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return u.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 u.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,r){return r.copyFromFloats(e,t,i),r}static Zero(){return new u(0,0,0)}static One(){return new u(1,1,1)}static Up(){return new u(0,1,0)}static get UpReadOnly(){return u._UpReadOnly}static get DownReadOnly(){return u._DownReadOnly}static get RightReadOnly(){return u._RightReadOnly}static get LeftReadOnly(){return u._LeftReadOnly}static get LeftHandedForwardReadOnly(){return u._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return u._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return u._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return u._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return u._ZeroReadOnly}static get OneReadOnly(){return u._OneReadOnly}static Down(){return new u(0,-1,0)}static Forward(e=!1){return new u(0,0,e?-1:1)}static Backward(e=!1){return new u(0,0,e?1:-1)}static Right(){return new u(1,0,0)}static Left(){return new u(-1,0,0)}static Random(e=0,t=1){return new u((0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats((0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t))}static TransformCoordinates(e,t){const i=u.Zero();return u.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return u.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,r,s){const n=r.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],a=e*n[1]+t*n[5]+i*n[9]+n[13],l=e*n[2]+t*n[6]+i*n[10]+n[14],h=1/(e*n[3]+t*n[7]+i*n[11]+n[15]);return s._x=o*h,s._y=a*h,s._z=l*h,s._isDirty=!0,s}static TransformNormal(e,t){const i=u.Zero();return u.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,r,s){const n=r.m;return s._x=e*n[0]+t*n[4]+i*n[8],s._y=e*n[1]+t*n[5]+i*n[9],s._z=e*n[2]+t*n[6]+i*n[10],s._isDirty=!0,s}static CatmullRom(e,t,i,r,s){const n=s*s,o=s*n,a=.5*(2*t._x+(-e._x+i._x)*s+(2*e._x-5*t._x+4*i._x-r._x)*n+(-e._x+3*t._x-3*i._x+r._x)*o),l=.5*(2*t._y+(-e._y+i._y)*s+(2*e._y-5*t._y+4*i._y-r._y)*n+(-e._y+3*t._y-3*i._y+r._y)*o),h=.5*(2*t._z+(-e._z+i._z)*s+(2*e._z-5*t._z+4*i._z-r._z)*n+(-e._z+3*t._z-3*i._z+r._z)*o);return new u(a,l,h)}static Clamp(e,t,i){const r=new u;return u.ClampToRef(e,t,i,r),r}static ClampToRef(e,t,i,r){let s=e._x;s=s>i._x?i._x:s,s=si._y?i._y:n,n=ni._z?i._z:o,o=o0&&I<0?(O.copyFrom(o),D=t,w=i):I>0&&M<0?(O.copyFrom(h),D=i,w=s):(O.copyFrom(a).scaleInPlace(-1),D=s,w=t);const N=_.Vector3[9],F=_.Vector3[4];if(D.subtractToRef(S,E),w.subtractToRef(S,N),u.CrossToRef(E,N,F),!(u.Dot(F,c)<0))return n.copyFrom(S),Math.abs(v*x);const L=_.Vector3[5];u.CrossToRef(O,F,L),L.normalize();const B=_.Vector3[9];B.copyFrom(D).subtractInPlace(S);const V=B.length();if(Vthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this}minimizeInPlaceFromFloats(e,t,i,r){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this.z=Math.min(i,this.z),this.w=Math.min(r,this.w),this}maximizeInPlaceFromFloats(e,t,i,r){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this.z=Math.max(i,this.z),this.w=Math.max(r,this.w),this}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e.z=Math.floor(this.z),e.w=Math.floor(this.w),e}floor(){return new d(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 d(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 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new d)}normalizeToRef(e){const t=this.length();return 0===t||1===t?(e.x=this.x,e.y=this.y,e.z=this.z,e.w=this.w,e):this.scaleToRef(1/t,e)}toVector3(){return new u(this.x,this.y,this.z)}clone(){return new d(this.x,this.y,this.z,this.w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.x=this.y=this.z=this.w=e,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}static FromArray(e,t){return t||(t=0),new d(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 d.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,r,s){return s.x=e,s.y=t,s.z=i,s.w=r,s}static Zero(){return new d(0,0,0,0)}static One(){return new d(1,1,1,1)}static Random(e=0,t=1){return new d((0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t))}static RandomToRef(e=0,t=1,i){return i.x=(0,l.RandomRange)(e,t),i.y=(0,l.RandomRange)(e,t),i.z=(0,l.RandomRange)(e,t),i.w=(0,l.RandomRange)(e,t),i}static Clamp(e,t,i){return d.ClampToRef(e,t,i,new d)}static ClampToRef(e,t,i,r){return r.x=(0,l.Clamp)(e.x,t.x,i.x),r.y=(0,l.Clamp)(e.y,t.y,i.y),r.z=(0,l.Clamp)(e.z,t.z,i.z),r.w=(0,l.Clamp)(e.w,t.w,i.w),r}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return d._ZeroReadOnly}static Normalize(e){return d.NormalizeToRef(e,new d)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=new d;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new d;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(d.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,r=e.y-t.y,s=e.z-t.z,n=e.w-t.w;return i*i+r*r+s*s+n*n}static Center(e,t){return d.CenterToRef(e,t,new d)}static CenterToRef(e,t,i){return i.x=(e.x+t.x)/2,i.y=(e.y+t.y)/2,i.z=(e.z+t.z)/2,i.w=(e.w+t.w)/2,i}static TransformCoordinates(e,t){return d.TransformCoordinatesToRef(e,t,new d)}static TransformCoordinatesToRef(e,t,i){return d.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,r,s){const n=r.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],a=e*n[1]+t*n[5]+i*n[9]+n[13],l=e*n[2]+t*n[6]+i*n[10]+n[14],h=e*n[3]+t*n[7]+i*n[11]+n[15];return s.x=o,s.y=a,s.z=l,s.w=h,s}static TransformNormal(e,t){return d.TransformNormalToRef(e,t,new d)}static TransformNormalToRef(e,t,i){const r=t.m,s=e.x*r[0]+e.y*r[4]+e.z*r[8],n=e.x*r[1]+e.y*r[5]+e.z*r[9],o=e.x*r[2]+e.y*r[6]+e.z*r[10];return i.x=s,i.y=n,i.z=o,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,r,s,n){const o=s.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=r,n}static FromVector3(e,t=0){return new d(e._x,e._y,e._z,t)}static Dot(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w}}d._ZeroReadOnly=d.Zero(),Object.defineProperties(d.prototype,{dimension:{value:[4]},rank:{value:1}});class f{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,r=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=r}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=h(this._x);return e=397*e^h(this._y),e=397*e^h(this._z),e=397*e^h(this._w),e}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 f.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=r.bH){return e&&(0,l.WithinEpsilon)(this._x,e._x,t)&&(0,l.WithinEpsilon)(this._y,e._y,t)&&(0,l.WithinEpsilon)(this._z,e._z,t)&&(0,l.WithinEpsilon)(this._w,e._w,t)}clone(){return new f(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,i,r){return this._x=e,this._y=t,this._z=i,this._w=r,this._isDirty=!0,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new f(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t}addInPlaceFromFloats(e,t,i,r){return this._x+=e,this._y+=t,this._z+=i,this._w+=r,this._isDirty=!0,this}subtractToRef(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t}subtractFromFloats(e,t,i,r){return this.subtractFromFloatsToRef(e,t,i,r,new f)}subtractFromFloatsToRef(e,t,i,r,s){return s._x=this._x-e,s._y=this._y-t,s._z=this._z-i,s._w=this._w-r,s._isDirty=!0,s}subtract(e){return new f(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 f(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 f(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,r=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,s=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,r,s,n),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,i,r){return this._x*=e,this._y*=t,this._z*=i,this._w*=r,this._isDirty=!0,this}divide(e){throw new ReferenceError("Can not divide a quaternion")}divideToRef(e,t){throw new ReferenceError("Can not divide a quaternion")}divideInPlace(e){throw new ReferenceError("Can not divide a quaternion")}minimizeInPlace(){throw new ReferenceError("Can not minimize a quaternion")}minimizeInPlaceFromFloats(){throw new ReferenceError("Can not minimize a quaternion")}maximizeInPlace(){throw new ReferenceError("Can not maximize a quaternion")}maximizeInPlaceFromFloats(){throw new ReferenceError("Can not maximize a quaternion")}negate(){return this.negateToRef(new f)}negateInPlace(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this}negateToRef(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e}equalsToFloats(e,t,i,r){return this._x===e&&this._y===t&&this._z===i&&this._w===r}floorToRef(e){throw new ReferenceError("Can not floor a quaternion")}floor(){throw new ReferenceError("Can not floor a quaternion")}fractToRef(e){throw new ReferenceError("Can not fract a quaternion")}fract(){throw new ReferenceError("Can not fract a quaternion")}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new f(-this._x,-this._y,-this._z,this._w)}invert(){const e=this.conjugate(),t=this.lengthSquared();return 0==t||1==t||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();const e=this.lengthSquared();return 0==e||1==e||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 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new f(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){const e=u.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,r=this._y,s=this._w,n=r*t-i*s,o=.4999999;if(n<-o)e._y=2*Math.atan2(r,s),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(n>o)e._y=2*Math.atan2(r,s),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const o=s*s,a=t*t,l=i*i,h=r*r;e._z=Math.atan2(2*(i*r+t*s),-a-l+h+o),e._x=Math.asin(-2*n),e._y=Math.atan2(2*(t*i+r*s),a-l-h+o),e._isDirty=!0}return e}toAlphaBetaGammaToRef(e){const t=this._z,i=this._x,r=this._y,s=this._w,n=Math.sqrt(i*i+r*r),o=Math.sqrt(t*t+s*s),a=2*Math.atan2(n,o),l=2*Math.atan2(t,s),h=2*Math.atan2(r,i),c=(l+h)/2,u=(l-h)/2;return e.set(u,a,c),e}toRotationMatrix(e){return p.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return f.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 f;return f.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,r=i[0],s=i[4],n=i[8],o=i[1],a=i[5],l=i[9],h=i[2],c=i[6],u=i[10],d=r+a+u;let f;return d>0?(f=.5/Math.sqrt(d+1),t._w=.25/f,t._x=(c-l)*f,t._y=(n-h)*f,t._z=(o-s)*f,t._isDirty=!0):r>a&&r>u?(f=2*Math.sqrt(1+r-a-u),t._w=(c-l)/f,t._x=.25*f,t._y=(s+o)/f,t._z=(n+h)/f,t._isDirty=!0):a>u?(f=2*Math.sqrt(1+a-r-u),t._w=(n-h)/f,t._x=(s+o)/f,t._y=.25*f,t._z=(l+c)/f,t._isDirty=!0):(f=2*Math.sqrt(1+u-r-a),t._w=(o-s)/f,t._x=(n+h)/f,t._y=(l+c)/f,t._z=.25*f,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){const r=f.Dot(e,t);return 1-r*r<=i}static SmoothToRef(e,t,i,r,s){let n=0===r?1:i/r;return n=(0,l.Clamp)(n,0,1),f.SlerpToRef(e,t,n,s),s}static Zero(){return new f(0,0,0,0)}static Inverse(e){return new f(-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 f(0,0,0,1)}static IsIdentity(e){return e&&0===e._x&&0===e._y&&0===e._z&&1===e._w}static RotationAxis(e,t){return f.RotationAxisToRef(e,t,new f)}static RotationAxisToRef(e,t,i){i._w=Math.cos(t/2);const r=Math.sin(t/2)/e.length();return i._x=e._x*r,i._y=e._y*r,i._z=e._z*r,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new f(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromFloatsToRef(e,t,i,r,s){return s.copyFromFloats(e,t,i,r),s}static FromEulerAngles(e,t,i){const r=new f;return f.RotationYawPitchRollToRef(t,e,i,r),r}static FromEulerAnglesToRef(e,t,i,r){return f.RotationYawPitchRollToRef(t,e,i,r),r}static FromEulerVector(e){const t=new f;return f.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return f.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,s=r.bH){const n=u.Dot(e,t)+1;return nMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(u.CrossToRef(e,t,m.Vector3[0]),i.set(m.Vector3[0].x,m.Vector3[0].y,m.Vector3[0].z,n)),i.normalize()}static RotationYawPitchRoll(e,t,i){const r=new f;return f.RotationYawPitchRollToRef(e,t,i,r),r}static RotationYawPitchRollToRef(e,t,i,r){const s=.5*i,n=.5*t,o=.5*e,a=Math.sin(s),l=Math.cos(s),h=Math.sin(n),c=Math.cos(n),u=Math.sin(o),d=Math.cos(o);return r._x=d*h*l+u*c*a,r._y=u*c*l-d*h*a,r._z=d*c*a-u*h*l,r._w=d*c*l+u*h*a,r._isDirty=!0,r}static RotationAlphaBetaGamma(e,t,i){const r=new f;return f.RotationAlphaBetaGammaToRef(e,t,i,r),r}static RotationAlphaBetaGammaToRef(e,t,i,r){const s=.5*(i+e),n=.5*(i-e),o=.5*t;return r._x=Math.cos(n)*Math.sin(o),r._y=Math.sin(n)*Math.sin(o),r._z=Math.sin(s)*Math.cos(o),r._w=Math.cos(s)*Math.cos(o),r._isDirty=!0,r}static RotationQuaternionFromAxis(e,t,i){const r=new f(0,0,0,0);return f.RotationQuaternionFromAxisToRef(e,t,i,r),r}static RotationQuaternionFromAxisToRef(e,t,i,r){const s=_.Matrix[0];return e=e.normalizeToRef(_.Vector3[0]),t=t.normalizeToRef(_.Vector3[1]),i=i.normalizeToRef(_.Vector3[2]),p.FromXYZAxesToRef(e,t,i,s),f.FromRotationMatrixToRef(s,r),r}static FromLookDirectionLH(e,t){const i=new f;return f.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const r=_.Matrix[0];return p.LookDirectionLHToRef(e,t,r),f.FromRotationMatrixToRef(r,i),i}static FromLookDirectionRH(e,t){const i=new f;return f.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const r=_.Matrix[0];return p.LookDirectionRHToRef(e,t,r),f.FromRotationMatrixToRef(r,i)}static Slerp(e,t,i){const r=f.Identity();return f.SlerpToRef(e,t,i,r),r}static SlerpToRef(e,t,i,r){let s,n,o=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,a=!1;if(o<0&&(a=!0,o=-o),o>.999999)n=1-i,s=a?-i:i;else{const e=Math.acos(o),t=1/Math.sin(e);n=Math.sin((1-i)*e)*t,s=a?-Math.sin(i*e)*t:Math.sin(i*e)*t}return r._x=n*e._x+s*t._x,r._y=n*e._y+s*t._y,r._z=n*e._z+s*t._z,r._w=n*e._w+s*t._w,r._isDirty=!0,r}static Hermite(e,t,i,r,s){const n=s*s,o=s*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+s,c=o-n,u=e._x*a+i._x*l+t._x*h+r._x*c,d=e._y*a+i._y*l+t._y*h+r._y*c,p=e._z*a+i._z*l+t._z*h+r._z*c,_=e._w*a+i._w*l+t._w*h+r._w*c;return new f(u,d,p,_)}static Hermite1stDerivative(e,t,i,r,s){const n=new f;return this.Hermite1stDerivativeToRef(e,t,i,r,s,n),n}static Hermite1stDerivativeToRef(e,t,i,r,s,n){const o=s*s;return n._x=6*(o-s)*e._x+(3*o-4*s+1)*t._x+6*(-o+s)*i._x+(3*o-2*s)*r._x,n._y=6*(o-s)*e._y+(3*o-4*s+1)*t._y+6*(-o+s)*i._y+(3*o-2*s)*r._y,n._z=6*(o-s)*e._z+(3*o-4*s+1)*t._z+6*(-o+s)*i._z+(3*o-2*s)*r._z,n._w=6*(o-s)*e._w+(3*o-4*s+1)*t._w+6*(-o+s)*i._w+(3*o-2*s)*r._w,n._isDirty=!0,n}static Normalize(e){const t=f.Zero();return f.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){const r=new f;return f.ClampToRef(e,t,i,r),r}static ClampToRef(e,t,i,r){return r.copyFromFloats((0,l.Clamp)(e.x,t.x,i.x),(0,l.Clamp)(e.y,t.y,i.y),(0,l.Clamp)(e.z,t.z,i.z),(0,l.Clamp)(e.w,t.w,i.w))}static Random(e=0,t=1){return new f((0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats((0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t),(0,l.RandomRange)(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(f.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,r=e.y-t.y,s=e.z-t.z,n=e.w-t.w;return i*i+r*r+s*s+n*n}static Center(e,t){return f.CenterToRef(e,t,f.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(f.prototype,{dimension:{value:[4]},rank:{value:1}});class p{static get Use64Bits(){return o.I.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=p._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,r=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=!this._isIdentity&&t,this._isIdentity3x2Dirty=!this._isIdentity3x2&&r}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,o.I.MatrixTrackPrecisionChange&&o.I.MatrixTrackedMatrices.push(this),this._m=new o.I.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;const e=this._m;this._isIdentity=1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]||0!==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]?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(!0===this._isIdentity)return 1;const e=this._m,t=e[0],i=e[1],r=e[2],s=e[3],n=e[4],o=e[5],a=e[6],l=e[7],h=e[8],c=e[9],u=e[10],d=e[11],f=e[12],p=e[13],_=e[14],m=e[15],g=u*m-_*d,v=c*m-p*d,x=c*_-p*u,b=h*m-f*d,S=h*_-u*f,T=h*p-f*c;return t*+(o*g-a*v+l*x)+i*-(n*g-a*b+l*S)+r*+(n*v-o*b+l*T)+s*-(n*x-o*S+a*T)}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]}\n${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]}\n${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]}\n${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(e=null,t=0){if(!e)return this._m;const i=this._m;for(let r=0;r<16;r++)e[t+r]=i[r];return this}asArray(){return this._m}fromArray(e,t=0){return p.FromArrayToRef(e,t,this)}copyFromFloats(...e){return p.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 p.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 p;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,r=t._m,s=e.m;for(let e=0;e<16;e++)r[e]=i[e]+s[e];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,i=e.m;return t[0]+=i[0],t[1]+=i[1],t[2]+=i[2],t[3]+=i[3],t[4]+=i[4],t[5]+=i[5],t[6]+=i[6],t[7]+=i[7],t[8]+=i[8],t[9]+=i[9],t[10]+=i[10],t[11]+=i[11],t[12]+=i[12],t[13]+=i[13],t[14]+=i[14],t[15]+=i[15],this.markAsUpdated(),this}addInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];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 e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractToRef(e,t){const i=this._m,r=e.m,s=t._m;for(let e=0;e<16;e++)s[e]=i[e]-r[e];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new p)}subtractFromFloatsToRef(...e){const t=e.pop(),i=this._m,r=t._m,s=e;for(let e=0;e<16;e++)r[e]=i[e]-s[e];return t.markAsUpdated(),t}invertToRef(e){if(!0===this._isIdentity)return p.IdentityToRef(e),e;const t=this._m,i=t[0],r=t[1],s=t[2],n=t[3],o=t[4],a=t[5],l=t[6],h=t[7],c=t[8],u=t[9],d=t[10],f=t[11],_=t[12],m=t[13],g=t[14],v=t[15],x=d*v-g*f,b=u*v-m*f,S=u*g-m*d,T=c*v-_*f,C=c*g-d*_,y=c*m-_*u,E=+(a*x-l*b+h*S),P=-(o*x-l*T+h*C),A=+(o*b-a*T+h*y),R=-(o*S-a*C+l*y),I=i*E+r*P+s*A+n*R;if(0===I)return e.copyFrom(this),e;const M=1/I,O=l*v-g*h,D=a*v-m*h,w=a*g-m*l,N=o*v-_*h,F=o*g-_*l,L=o*m-_*a,B=l*f-d*h,V=a*f-u*h,k=a*d-u*l,U=o*f-c*h,G=o*d-c*l,z=o*u-c*a,W=-(r*x-s*b+n*S),H=+(i*x-s*T+n*C),X=-(i*b-r*T+n*y),q=+(i*S-r*C+s*y),Y=+(r*O-s*D+n*w),K=-(i*O-s*N+n*F),j=+(i*D-r*N+n*L),$=-(i*w-r*F+s*L),Q=-(r*B-s*V+n*k),Z=+(i*B-s*U+n*G),J=-(i*V-r*U+n*z),ee=+(i*k-r*G+s*z);return p.FromValuesToRef(E*M,W*M,Y*M,Q*M,P*M,H*M,K*M,Z*M,A*M,X*M,j*M,J*M,R*M,q*M,$*M,ee*M,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 u(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 p.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]),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 p;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]*=i[e];return this.markAsUpdated(),this}multiplyByFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e[i];return this.markAsUpdated(),this}multiplyByFloatsToRef(...e){const t=e.pop(),i=this._m,r=t._m,s=e;for(let e=0;e<16;e++)r[e]=i[e]*s[e];return t.markAsUpdated(),t}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,i){const r=this._m,s=e.m,n=r[0],o=r[1],a=r[2],l=r[3],h=r[4],c=r[5],u=r[6],d=r[7],f=r[8],p=r[9],_=r[10],m=r[11],g=r[12],v=r[13],x=r[14],b=r[15],S=s[0],T=s[1],C=s[2],y=s[3],E=s[4],P=s[5],A=s[6],R=s[7],I=s[8],M=s[9],O=s[10],D=s[11],w=s[12],N=s[13],F=s[14],L=s[15];return t[i]=n*S+o*E+a*I+l*w,t[i+1]=n*T+o*P+a*M+l*N,t[i+2]=n*C+o*A+a*O+l*F,t[i+3]=n*y+o*R+a*D+l*L,t[i+4]=h*S+c*E+u*I+d*w,t[i+5]=h*T+c*P+u*M+d*N,t[i+6]=h*C+c*A+u*O+d*F,t[i+7]=h*y+c*R+u*D+d*L,t[i+8]=f*S+p*E+_*I+m*w,t[i+9]=f*T+p*P+_*M+m*N,t[i+10]=f*C+p*A+_*O+m*F,t[i+11]=f*y+p*R+_*D+m*L,t[i+12]=g*S+v*E+x*I+b*w,t[i+13]=g*T+v*P+x*M+b*N,t[i+14]=g*C+v*A+x*O+b*F,t[i+15]=g*y+v*R+x*D+b*L,this}divide(e){return this.divideToRef(e,new p)}divideToRef(e,t){const i=this._m,r=e.m,s=t._m;for(let e=0;e<16;e++)s[e]=i[e]/r[e];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]/=i[e];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);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 e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);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 p)}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 e=0;e<16;e++)i[e]=-t[e];return e.markAsUpdated(),e}equals(e){const t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;const i=this.m,r=t.m;return i[0]===r[0]&&i[1]===r[1]&&i[2]===r[2]&&i[3]===r[3]&&i[4]===r[4]&&i[5]===r[5]&&i[6]===r[6]&&i[7]===r[7]&&i[8]===r[8]&&i[9]===r[9]&&i[10]===r[10]&&i[11]===r[11]&&i[12]===r[12]&&i[13]===r[13]&&i[14]===r[14]&&i[15]===r[15]}equalsWithEpsilon(e,t=0){const i=this._m,r=e.m;for(let e=0;e<16;e++)if(!(0,l.WithinEpsilon)(i[e],r[e],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 p)}floorToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=Math.floor(t[e]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new p)}fractToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=t[e]-Math.floor(t[e]);return e.markAsUpdated(),e}clone(){const e=new p;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=h(this._m[0]);for(let t=1;t<16;t++)e=397*e^h(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new f,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,r,s=!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||_.Vector3[0]).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]),r){const t=(s?r.absoluteScaling.x:r.scaling.x)<0?-1:1,i=(s?r.absoluteScaling.y:r.scaling.y)<0?-1:1,n=(s?r.absoluteScaling.z:r.scaling.z)<0?-1:1;e.x*=t,e.y*=i,e.z*=n}else this.determinant()<=0&&(e.y*=-1);if(0===e._x||0===e._y||0===e._z)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){const i=1/e._x,r=1/e._y,s=1/e._z;p.FromValuesToRef(n[0]*i,n[1]*i,n[2]*i,0,n[4]*r,n[5]*r,n[6]*r,0,n[8]*s,n[9]*s,n[10]*s,0,0,0,0,1,_.Matrix[0]),f.FromRotationMatrixToRef(_.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=4*e;return new d(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=4*e;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 p;return p.TransposeToRef(this,e),e}transposeToRef(e){return p.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,r,s){if(e<0||e>3)return this;const n=4*e;return this._m[n+0]=t,this._m[n+1]=i,this._m[n+2]=r,this._m[n+3]=s,this.markAsUpdated(),this}scale(e){const t=new p;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=_.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return p.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 p;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=_.Vector3[0];if(!this.decompose(t))return p.IdentityToRef(e),e;const i=this._m,r=1/t._x,s=1/t._y,n=1/t._z;return p.FromValuesToRef(i[0]*r,i[1]*r,i[2]*r,0,i[4]*s,i[5]*s,i[6]*s,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 p;return p.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let r=0;r<16;r++)i._m[r]=e[r+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,r){return r._m[0]=e[0+t]*i,r._m[1]=e[1+t]*i,r._m[2]=e[2+t]*i,r._m[3]=e[3+t]*i,r._m[4]=e[4+t]*i,r._m[5]=e[5+t]*i,r._m[6]=e[6+t]*i,r._m[7]=e[7+t]*i,r._m[8]=e[8+t]*i,r._m[9]=e[9+t]*i,r._m[10]=e[10+t]*i,r._m[11]=e[11+t]*i,r._m[12]=e[12+t]*i,r._m[13]=e[13+t]*i,r._m[14]=e[14+t]*i,r._m[15]=e[15+t]*i,r.markAsUpdated(),r}static get IdentityReadOnly(){return p._IdentityReadOnly}static FromValuesToRef(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m){const g=m._m;g[0]=e,g[1]=t,g[2]=i,g[3]=r,g[4]=s,g[5]=n,g[6]=o,g[7]=a,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=f,g[14]=p,g[15]=_,m.markAsUpdated()}static FromValues(e,t,i,r,s,n,o,a,l,h,c,u,d,f,_,m){const g=new p,v=g._m;return v[0]=e,v[1]=t,v[2]=i,v[3]=r,v[4]=s,v[5]=n,v[6]=o,v[7]=a,v[8]=l,v[9]=h,v[10]=c,v[11]=u,v[12]=d,v[13]=f,v[14]=_,v[15]=m,g.markAsUpdated(),g}static Compose(e,t,i){const r=new p;return p.ComposeToRef(e,t,i,r),r}static ComposeToRef(e,t,i,r){const s=r._m,n=t._x,o=t._y,a=t._z,l=t._w,h=n+n,c=o+o,u=a+a,d=n*h,f=n*c,p=n*u,_=o*c,m=o*u,g=a*u,v=l*h,x=l*c,b=l*u,S=e._x,T=e._y,C=e._z;return s[0]=(1-(_+g))*S,s[1]=(f+b)*S,s[2]=(p-x)*S,s[3]=0,s[4]=(f-b)*T,s[5]=(1-(d+g))*T,s[6]=(m+v)*T,s[7]=0,s[8]=(p+x)*C,s[9]=(m-v)*C,s[10]=(1-(d+_))*C,s[11]=0,s[12]=i._x,s[13]=i._y,s[14]=i._z,s[15]=1,r.markAsUpdated(),r}static Identity(){const e=p.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 p.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=p.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 p;return p.RotationXToRef(e,t),t}static Invert(e){const t=new p;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),r=Math.cos(e);return p.FromValuesToRef(1,0,0,0,0,r,i,0,0,-i,r,0,0,0,0,1,t),t._updateIdentityStatus(1===r&&0===i),t}static RotationY(e){const t=new p;return p.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),r=Math.cos(e);return p.FromValuesToRef(r,0,-i,0,0,1,0,0,i,0,r,0,0,0,0,1,t),t._updateIdentityStatus(1===r&&0===i),t}static RotationZ(e){const t=new p;return p.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),r=Math.cos(e);return p.FromValuesToRef(r,i,0,0,-i,r,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(1===r&&0===i),t}static RotationAxis(e,t){const i=new p;return p.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const r=Math.sin(-t),s=Math.cos(-t),n=1-s;e=e.normalizeToRef(_.Vector3[0]);const o=i._m;return o[0]=e._x*e._x*n+s,o[1]=e._x*e._y*n-e._z*r,o[2]=e._x*e._z*n+e._y*r,o[3]=0,o[4]=e._y*e._x*n+e._z*r,o[5]=e._y*e._y*n+s,o[6]=e._y*e._z*n-e._x*r,o[7]=0,o[8]=e._z*e._x*n-e._y*r,o[9]=e._z*e._y*n+e._x*r,o[10]=e._z*e._z*n+s,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 n=u.Dot(t,e),o=i._m;if(n<-1+r.bH)o[0]=-1,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=s?1:-1,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=s?-1:1,o[11]=0;else{const i=u.Cross(t,e),r=1/(1+n);o[0]=i._x*i._x*r+n,o[1]=i._y*i._x*r-i._z,o[2]=i._z*i._x*r+i._y,o[3]=0,o[4]=i._x*i._y*r+i._z,o[5]=i._y*i._y*r+n,o[6]=i._z*i._y*r-i._x,o[7]=0,o[8]=i._x*i._z*r-i._y,o[9]=i._y*i._z*r+i._x,o[10]=i._z*i._z*r+n,o[11]=0}return o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const r=new p;return p.RotationYawPitchRollToRef(e,t,i,r),r}static RotationYawPitchRollToRef(e,t,i,r){return f.RotationYawPitchRollToRef(e,t,i,_.Quaternion[0]),_.Quaternion[0].toRotationMatrix(r),r}static Scaling(e,t,i){const r=new p;return p.ScalingToRef(e,t,i,r),r}static ScalingToRef(e,t,i,r){return p.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,r),r._updateIdentityStatus(1===e&&1===t&&1===i),r}static Translation(e,t,i){const r=new p;return p.TranslationToRef(e,t,i,r),r}static TranslationToRef(e,t,i,r){return p.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,r),r._updateIdentityStatus(0===e&&0===t&&0===i),r}static Lerp(e,t,i){const r=new p;return p.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){const s=r._m,n=e.m,o=t.m;for(let e=0;e<16;e++)s[e]=n[e]*(1-i)+o[e]*i;return r.markAsUpdated(),r}static DecomposeLerp(e,t,i){const r=new p;return p.DecomposeLerpToRef(e,t,i,r),r}static DecomposeLerpToRef(e,t,i,r){const s=_.Vector3[0],n=_.Quaternion[0],o=_.Vector3[1];e.decompose(s,n,o);const a=_.Vector3[2],l=_.Quaternion[1],h=_.Vector3[3];t.decompose(a,l,h);const c=_.Vector3[4];u.LerpToRef(s,a,i,c);const d=_.Quaternion[2];f.SlerpToRef(n,l,i,d);const m=_.Vector3[5];return u.LerpToRef(o,h,i,m),p.ComposeToRef(c,d,m,r),r}static LookAtLH(e,t,i){const r=new p;return p.LookAtLHToRef(e,t,i,r),r}static LookAtLHToRef(e,t,i,r){const s=_.Vector3[0],n=_.Vector3[1],o=_.Vector3[2];t.subtractToRef(e,o),o.normalize(),u.CrossToRef(i,o,s);const a=s.lengthSquared();0===a?s.x=1:s.normalizeFromLength(Math.sqrt(a)),u.CrossToRef(o,s,n),n.normalize();const l=-u.Dot(s,e),h=-u.Dot(n,e),c=-u.Dot(o,e);return p.FromValuesToRef(s._x,n._x,o._x,0,s._y,n._y,o._y,0,s._z,n._z,o._z,0,l,h,c,1,r),r}static LookAtRH(e,t,i){const r=new p;return p.LookAtRHToRef(e,t,i,r),r}static LookAtRHToRef(e,t,i,r){const s=_.Vector3[0],n=_.Vector3[1],o=_.Vector3[2];e.subtractToRef(t,o),o.normalize(),u.CrossToRef(i,o,s);const a=s.lengthSquared();0===a?s.x=1:s.normalizeFromLength(Math.sqrt(a)),u.CrossToRef(o,s,n),n.normalize();const l=-u.Dot(s,e),h=-u.Dot(n,e),c=-u.Dot(o,e);return p.FromValuesToRef(s._x,n._x,o._x,0,s._y,n._y,o._y,0,s._z,n._z,o._z,0,l,h,c,1,r),r}static LookDirectionLH(e,t){const i=new p;return p.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const r=_.Vector3[0];r.copyFrom(e),r.scaleInPlace(-1);const s=_.Vector3[1];return u.CrossToRef(t,r,s),p.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,r._x,r._y,r._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new p;return p.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const r=_.Vector3[2];return u.CrossToRef(t,e,r),p.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,r,s){const n=new p;return p.OrthoLHToRef(e,t,i,r,n,s),n}static OrthoLHToRef(e,t,i,r,s,n){const o=2/e,a=2/t,l=2/(r-i),h=-(r+i)/(r-i);return p.FromValuesToRef(o,0,0,0,0,a,0,0,0,0,l,0,0,0,h,1,s),n&&s.multiplyToRef(g,s),s._updateIdentityStatus(1===o&&1===a&&1===l&&0===h),s}static OrthoOffCenterLH(e,t,i,r,s,n,o){const a=new p;return p.OrthoOffCenterLHToRef(e,t,i,r,s,n,a,o),a}static OrthoOffCenterLHToRef(e,t,i,r,s,n,o,a){const l=2/(t-e),h=2/(r-i),c=2/(n-s),u=-(n+s)/(n-s),d=(e+t)/(e-t),f=(r+i)/(i-r);return p.FromValuesToRef(l,0,0,0,0,h,0,0,0,0,c,0,d,f,u,1,o),a&&o.multiplyToRef(g,o),o.markAsUpdated(),o}static ObliqueOffCenterLHToRef(e,t,i,r,s,n,o,a,l,h,c){const u=-o*Math.cos(a),d=-o*Math.sin(a);return p.TranslationToRef(0,0,-l,_.Matrix[1]),p.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,_.Matrix[0]),_.Matrix[1].multiplyToRef(_.Matrix[0],_.Matrix[0]),p.TranslationToRef(0,0,l,_.Matrix[1]),_.Matrix[0].multiplyToRef(_.Matrix[1],_.Matrix[0]),p.OrthoOffCenterLHToRef(e,t,i,r,s,n,h,c),_.Matrix[0].multiplyToRef(h,h),h}static OrthoOffCenterRH(e,t,i,r,s,n,o){const a=new p;return p.OrthoOffCenterRHToRef(e,t,i,r,s,n,a,o),a}static OrthoOffCenterRHToRef(e,t,i,r,s,n,o,a){return p.OrthoOffCenterLHToRef(e,t,i,r,s,n,o,a),o._m[10]*=-1,o}static ObliqueOffCenterRHToRef(e,t,i,r,s,n,o,a,l,h,c){const u=o*Math.cos(a),d=o*Math.sin(a);return p.TranslationToRef(0,0,l,_.Matrix[1]),p.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,_.Matrix[0]),_.Matrix[1].multiplyToRef(_.Matrix[0],_.Matrix[0]),p.TranslationToRef(0,0,-l,_.Matrix[1]),_.Matrix[0].multiplyToRef(_.Matrix[1],_.Matrix[0]),p.OrthoOffCenterRHToRef(e,t,i,r,s,n,h,c),_.Matrix[0].multiplyToRef(h,h),h}static PerspectiveLH(e,t,i,r,s,n=0){const o=new p,a=2*i/e,l=2*i/t,h=(r+i)/(r-i),c=-2*r*i/(r-i),u=Math.tan(n);return p.FromValuesToRef(a,0,0,0,0,l,0,u,0,0,h,1,0,0,c,0,o),s&&o.multiplyToRef(g,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,r,s,n=0,o=!1){const a=new p;return p.PerspectiveFovLHToRef(e,t,i,r,a,!0,s,n,o),a}static PerspectiveFovLHToRef(e,t,i,r,s,n=!0,o,a=0,l=!1){const h=i,c=r,u=1/Math.tan(.5*e),d=n?u/t:u,f=n?u:u*t,_=l&&0===h?-1:0!==c?(c+h)/(c-h):1,m=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,v=Math.tan(a);return p.FromValuesToRef(d,0,0,0,0,f,0,v,0,0,_,1,0,0,m,0,s),o&&s.multiplyToRef(g,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseLHToRef(e,t,i,r,s,n=!0,o,a=0){const l=1/Math.tan(.5*e),h=n?l/t:l,c=n?l:l*t,u=Math.tan(a);return p.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,1,0,0,1,0,s),o&&s.multiplyToRef(g,s),s._updateIdentityStatus(!1),s}static PerspectiveFovRH(e,t,i,r,s,n=0,o=!1){const a=new p;return p.PerspectiveFovRHToRef(e,t,i,r,a,!0,s,n,o),a}static PerspectiveFovRHToRef(e,t,i,r,s,n=!0,o,a=0,l=!1){const h=i,c=r,u=1/Math.tan(.5*e),d=n?u/t:u,f=n?u:u*t,_=l&&0===h?1:0!==c?-(c+h)/(c-h):-1,m=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,v=Math.tan(a);return p.FromValuesToRef(d,0,0,0,0,f,0,v,0,0,_,-1,0,0,m,0,s),o&&s.multiplyToRef(g,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseRHToRef(e,t,i,r,s,n=!0,o,a=0){const l=1/Math.tan(.5*e),h=n?l/t:l,c=n?l:l*t,u=Math.tan(a);return p.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,-1,0,0,-1,0,s),o&&s.multiplyToRef(g,s),s._updateIdentityStatus(!1),s}static GetFinalMatrix(e,t,i,r,s,n){const o=e.width,a=e.height,l=e.x,h=e.y,c=p.FromValues(o/2,0,0,0,0,-a/2,0,0,0,0,n-s,0,l+o/2,a/2+h,s,1),u=new p;return t.multiplyToRef(i,u),u.multiplyToRef(r,u),u.multiplyToRef(c,u)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return o.I.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 o.I.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new p;return p.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,r=i[0],s=i[4],n=i[8],o=i[12],a=i[1],l=i[5],h=i[9],c=i[13],u=i[2],d=i[6],f=i[10],p=i[14],_=i[3],m=i[7],g=i[11],v=i[15],x=t._m;return x[0]=r,x[1]=s,x[2]=n,x[3]=o,x[4]=a,x[5]=l,x[6]=h,x[7]=c,x[8]=u,x[9]=d,x[10]=f,x[11]=p,x[12]=_,x[13]=m,x[14]=g,x[15]=v,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new p;return p.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,r=e.normal.y,s=e.normal.z,n=-2*i,o=-2*r,a=-2*s;return p.FromValuesToRef(n*i+1,o*i,a*i,0,n*r,o*r+1,a*r,0,n*s,o*s,a*s+1,0,n*e.d,o*e.d,a*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,r){return p.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,r),r}static FromQuaternionToRef(e,t){const i=e._x*e._x,r=e._y*e._y,s=e._z*e._z,n=e._x*e._y,o=e._z*e._w,a=e._z*e._x,l=e._y*e._w,h=e._y*e._z,c=e._x*e._w;return t._m[0]=1-2*(r+s),t._m[1]=2*(n+o),t._m[2]=2*(a-l),t._m[3]=0,t._m[4]=2*(n-o),t._m[5]=1-2*(s+i),t._m[6]=2*(h+c),t._m[7]=0,t._m[8]=2*(a+l),t._m[9]=2*(h-c),t._m[10]=1-2*(r+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}p._UpdateFlagSeed=0,p._IdentityReadOnly=p.Identity(),Object.defineProperties(p.prototype,{dimension:{value:[4,4]},rank:{value:2}});class _{}_.Vector3=(0,s.ln)(11,u.Zero),_.Matrix=(0,s.ln)(2,p.Identity),_.Quaternion=(0,s.ln)(3,f.Zero);class m{}m.Vector2=(0,s.ln)(3,c.Zero),m.Vector3=(0,s.ln)(13,u.Zero),m.Vector4=(0,s.ln)(3,d.Zero),m.Quaternion=(0,s.ln)(3,f.Zero),m.Matrix=(0,s.ln)(8,p.Identity),(0,n.Y5)("BABYLON.Vector2",c),(0,n.Y5)("BABYLON.Vector3",u),(0,n.Y5)("BABYLON.Vector4",d),(0,n.Y5)("BABYLON.Matrix",p);const g=p.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1)},13093:(e,t,i)=>{"use strict";i.d(t,{L:()=>r});class r{constructor(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}toGlobal(e,t){return new r(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 r(this.x,this.y,this.width,this.height)}}},13798:(e,t,i)=>{"use strict";i.d(t,{O:()=>h,Q:()=>c});var r=i(94212),s=i(73864);const n=[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))],o=[()=>1,e=>e.y,e=>e.z,e=>e.x,e=>e.x*e.y,e=>e.y*e.z,e=>3*e.z*e.z-1,e=>e.x*e.z,e=>e.x*e.x-e.y*e.y],a=(e,t)=>n[e]*o[e](t),l=[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 h{constructor(){this.preScaled=!1,this.l00=r.Pq.Zero(),this.l1_1=r.Pq.Zero(),this.l10=r.Pq.Zero(),this.l11=r.Pq.Zero(),this.l2_2=r.Pq.Zero(),this.l2_1=r.Pq.Zero(),this.l20=r.Pq.Zero(),this.l21=r.Pq.Zero(),this.l22=r.Pq.Zero()}addLight(e,t,i){s.AA.Vector3[0].set(t.r,t.g,t.b);const r=s.AA.Vector3[0],n=s.AA.Vector3[1];r.scaleToRef(i,n),n.scaleToRef(a(0,e),s.AA.Vector3[2]),this.l00.addInPlace(s.AA.Vector3[2]),n.scaleToRef(a(1,e),s.AA.Vector3[2]),this.l1_1.addInPlace(s.AA.Vector3[2]),n.scaleToRef(a(2,e),s.AA.Vector3[2]),this.l10.addInPlace(s.AA.Vector3[2]),n.scaleToRef(a(3,e),s.AA.Vector3[2]),this.l11.addInPlace(s.AA.Vector3[2]),n.scaleToRef(a(4,e),s.AA.Vector3[2]),this.l2_2.addInPlace(s.AA.Vector3[2]),n.scaleToRef(a(5,e),s.AA.Vector3[2]),this.l2_1.addInPlace(s.AA.Vector3[2]),n.scaleToRef(a(6,e),s.AA.Vector3[2]),this.l20.addInPlace(s.AA.Vector3[2]),n.scaleToRef(a(7,e),s.AA.Vector3[2]),this.l21.addInPlace(s.AA.Vector3[2]),n.scaleToRef(a(8,e),s.AA.Vector3[2]),this.l22.addInPlace(s.AA.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(l[0]),this.l1_1.scaleInPlace(l[1]),this.l10.scaleInPlace(l[2]),this.l11.scaleInPlace(l[3]),this.l2_2.scaleInPlace(l[4]),this.l2_1.scaleInPlace(l[5]),this.l20.scaleInPlace(l[6]),this.l21.scaleInPlace(l[7]),this.l22.scaleInPlace(l[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(n[0]),this.l1_1.scaleInPlace(n[1]),this.l10.scaleInPlace(n[2]),this.l11.scaleInPlace(n[3]),this.l2_2.scaleInPlace(n[4]),this.l2_1.scaleInPlace(n[5]),this.l20.scaleInPlace(n[6]),this.l21.scaleInPlace(n[7]),this.l22.scaleInPlace(n[8])}updateFromArray(e){return r.Pq.FromArrayToRef(e[0],0,this.l00),r.Pq.FromArrayToRef(e[1],0,this.l1_1),r.Pq.FromArrayToRef(e[2],0,this.l10),r.Pq.FromArrayToRef(e[3],0,this.l11),r.Pq.FromArrayToRef(e[4],0,this.l2_2),r.Pq.FromArrayToRef(e[5],0,this.l2_1),r.Pq.FromArrayToRef(e[6],0,this.l20),r.Pq.FromArrayToRef(e[7],0,this.l21),r.Pq.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return r.Pq.FromFloatsToRef(e[0],e[1],e[2],this.l00),r.Pq.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),r.Pq.FromFloatsToRef(e[6],e[7],e[8],this.l10),r.Pq.FromFloatsToRef(e[9],e[10],e[11],this.l11),r.Pq.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),r.Pq.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),r.Pq.FromFloatsToRef(e[18],e[19],e[20],this.l20),r.Pq.FromFloatsToRef(e[21],e[22],e[23],this.l21),r.Pq.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return(new h).updateFromArray(e)}static FromPolynomial(e){const t=new h;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 c{constructor(){this.x=r.Pq.Zero(),this.y=r.Pq.Zero(),this.z=r.Pq.Zero(),this.xx=r.Pq.Zero(),this.yy=r.Pq.Zero(),this.zz=r.Pq.Zero(),this.xy=r.Pq.Zero(),this.yz=r.Pq.Zero(),this.zx=r.Pq.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=h.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){s.AA.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=s.AA.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),s.AA.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),s.AA.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(s.AA.Vector3[0]).addInPlace(s.AA.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(s.AA.Vector3[0]).subtractInPlace(s.AA.Vector3[1]),this.zz.copyFrom(e.l00),s.AA.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(s.AA.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 c).updateFromHarmonics(e)}static FromArray(e){const t=new c;return r.Pq.FromArrayToRef(e[0],0,t.x),r.Pq.FromArrayToRef(e[1],0,t.y),r.Pq.FromArrayToRef(e[2],0,t.z),r.Pq.FromArrayToRef(e[3],0,t.xx),r.Pq.FromArrayToRef(e[4],0,t.yy),r.Pq.FromArrayToRef(e[5],0,t.zz),r.Pq.FromArrayToRef(e[6],0,t.yz),r.Pq.FromArrayToRef(e[7],0,t.zx),r.Pq.FromArrayToRef(e[8],0,t.xy),t}}},7240:(e,t,i)=>{"use strict";i.d(t,{A:()=>s});var r=i(75801);class s extends r.n{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}},82266:(e,t,i)=>{"use strict";i.d(t,{d:()=>h});var r=i(94212),s=i(56984),n=i(13798),o=i(34910),a=i(11084);class l{constructor(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r}}class h{static ConvertCubeMapTextureToSphericalPolynomial(e){if(!e.isCube)return null;e.getScene()?.getEngine().flushFramebuffer();const t=e.getSize().width,i=e.readPixels(0,void 0,void 0,!1),r=e.readPixels(1,void 0,void 0,!1);let s,n;e.isRenderTarget?(s=e.readPixels(3,void 0,void 0,!1),n=e.readPixels(2,void 0,void 0,!1)):(s=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),a=e.readPixels(5,void 0,void 0,!1),l=e.gammaSpace;let h=0;return 1!=e.textureType&&2!=e.textureType||(h=1),new Promise((e=>{Promise.all([r,i,s,n,o,a]).then((([i,r,s,n,o,a])=>{const c={size:t,right:r,left:i,up:s,down:n,front:o,back:a,format:5,type:h,gammaSpace:l};e(this.ConvertCubeMapToSphericalPolynomial(c))}))}))}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new n.O;let i=0;const r=2/e.size,l=r,h=.5*r,c=h-1;for(let n=0;n<6;n++){const u=this._FileFaces[n],d=e[u.name];let f=c;const p=5===e.format?4:3;for(let n=0;nb){const t=b/e;g*=t,v*=t,x*=t}}else g=(0,s.Clamp)(g,0,b),v=(0,s.Clamp)(v,0,b),x=(0,s.Clamp)(x,0,b);const S=new a.v9(g,v,x);t.addLight(c,S,m),i+=m,_+=r}f+=l}}const u=4*Math.PI*6/6/i;return t.scaleInPlace(u),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),n.Q.FromHarmonics(t)}}h._FileFaces=[new l("right",new r.Pq(1,0,0),new r.Pq(0,0,-1),new r.Pq(0,-1,0)),new l("left",new r.Pq(-1,0,0),new r.Pq(0,0,1),new r.Pq(0,-1,0)),new l("up",new r.Pq(0,1,0),new r.Pq(1,0,0),new r.Pq(0,0,1)),new l("down",new r.Pq(0,-1,0),new r.Pq(1,0,0),new r.Pq(0,0,-1)),new l("front",new r.Pq(0,0,1),new r.Pq(1,0,0),new r.Pq(0,-1,0)),new l("back",new r.Pq(0,0,-1),new r.Pq(-1,0,0),new r.Pq(0,-1,0))],h.MAX_HDRI_VALUE=4096,h.PRESERVE_CLAMPED_COLORS=!1},22377:(e,t,i)=>{"use strict";i.d(t,{I9:()=>c,LT:()=>l,NK:()=>o,VH:()=>a});var r=i(5060);function s(e,t,i,r,s,n){s>0?(s=function(e,t){return t>1023?1*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?1*Math.pow(2,-1074)*Math.pow(2,t+1074):1*Math.pow(2,t)}(0,s-136),e[n+0]=t*s,e[n+1]=i*s,e[n+2]=r*s):(e[n+0]=0,e[n+1]=0,e[n+2]=0)}function n(e,t){let i="",r="";for(let s=t;s32767)throw"HDR Bad header format, unsupported size";return a+=r.length+1,{height:t,width:i,dataPosition:a}}function a(e,t,i=!1){const s=new Uint8Array(e),n=o(s),a=l(s,n);return r.D.ConvertPanoramaToCubemap(a,n.width,n.height,t,i)}function l(e,t){return function(e,t){let i=t.height;const r=t.width;let n,o,a,l,c,u=t.dataPosition,d=0,f=0,p=0;const _=new ArrayBuffer(4*r),m=new Uint8Array(_),g=new ArrayBuffer(t.width*t.height*4*3),v=new Float32Array(g);for(;i>0;){if(n=e[u++],o=e[u++],a=e[u++],l=e[u++],2!=n||2!=o||128&a||t.width<8||t.width>32767)return h(e,t);if((a<<8|l)!=r)throw"HDR Bad header format, wrong scan line width";for(d=0,p=0;p<4;p++)for(f=(p+1)*r;d128){if(c=n-128,0==c||c>f-d)throw"HDR Bad Format, bad scanline data (run)";for(;c-- >0;)m[d++]=o}else{if(c=n,0==c||c>f-d)throw"HDR Bad Format, bad scanline data (non-run)";if(m[d++]=o,--c>0)for(let t=0;t0;){for(h=0;h{"use strict";i.d(t,{D:()=>s});var r=i(94212);class s{static ConvertPanoramaToCubemap(e,t,i,r,s=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";return{front:this.CreateCubemapTexture(r,this.FACE_FRONT,e,t,i,s),back:this.CreateCubemapTexture(r,this.FACE_BACK,e,t,i,s),left:this.CreateCubemapTexture(r,this.FACE_LEFT,e,t,i,s),right:this.CreateCubemapTexture(r,this.FACE_RIGHT,e,t,i,s),up:this.CreateCubemapTexture(r,this.FACE_UP,e,t,i,s),down:this.CreateCubemapTexture(r,this.FACE_DOWN,e,t,i,s),size:r,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,r,s,n=!1){const o=new ArrayBuffer(e*e*4*3),a=new Float32Array(o),l=n?Math.max(1,Math.round(r/4/e)):1,h=1/l,c=h*h,u=t[1].subtract(t[0]).scale(h/e),d=t[3].subtract(t[2]).scale(h/e),f=1/e;let p=0;for(let n=0;nMath.PI;)s-=2*Math.PI;let o=s/Math.PI;const a=n/Math.PI;o=.5*o+.5;let l=Math.round(o*i);l<0?l=0:l>=i&&(l=i-1);let h=Math.round(a*r);h<0?h=0:h>=r&&(h=r-1);const c=r-h-1;return{r:t[c*i*3+3*l+0],g:t[c*i*3+3*l+1],b:t[c*i*3+3*l+2]}}}s.FACE_LEFT=[new r.Pq(-1,-1,-1),new r.Pq(1,-1,-1),new r.Pq(-1,1,-1),new r.Pq(1,1,-1)],s.FACE_RIGHT=[new r.Pq(1,-1,1),new r.Pq(-1,-1,1),new r.Pq(1,1,1),new r.Pq(-1,1,1)],s.FACE_FRONT=[new r.Pq(1,-1,-1),new r.Pq(1,-1,1),new r.Pq(1,1,-1),new r.Pq(1,1,1)],s.FACE_BACK=[new r.Pq(-1,-1,1),new r.Pq(-1,-1,-1),new r.Pq(-1,1,1),new r.Pq(-1,1,-1)],s.FACE_DOWN=[new r.Pq(1,1,-1),new r.Pq(1,1,1),new r.Pq(-1,1,-1),new r.Pq(-1,1,1)],s.FACE_UP=[new r.Pq(-1,-1,-1),new r.Pq(-1,-1,1),new r.Pq(1,-1,-1),new r.Pq(1,-1,1)]},76486:(e,t,i)=>{"use strict";i.d(t,{Z:()=>r});class r{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,(e=>(e=e.slice(1,e.length-1),r._HandleParenthesisContent(e,t)))):r._HandleParenthesisContent(e,t))||"false"!==e&&r.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);const s=e.split("||");for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)){let n=r._SimplifyNegation(s[e].trim());const o=n.split("&&");if(o.length>1)for(let e=0;e(e=e.replace(/[\s]/g,(()=>""))).length%2?"!":""))).trim())?e="false":"!false"===e&&(e="true"),e}}},34130:(e,t,i)=>{"use strict";function r(e,t){const i=[];for(let r=0;ro,ln:()=>s,mI:()=>r});const n=["push","splice","pop","shift","unshift"];function o(e,t){const i=n.map((i=>function(e,t,i){const r=e[t];if("function"!=typeof r)return null;const s=function(){const r=e.length,n=s.previous.apply(e,arguments);return i(t,r),n};return r.next=s,s.previous=r,e[t]=s,()=>{const i=s.previous;if(!i)return;const r=s.next;r?(i.next=r,r.previous=i):(i.next=void 0,e[t]=i),s.next=void 0,s.previous=void 0}}(e,i,t)));return()=>{i.forEach((e=>{e?.()}))}}},68622:(e,t,i)=>{"use strict";i.d(t,{$e:()=>l,ED:()=>x,Sl:()=>c,SV:()=>h,yT:()=>u,aB:()=>v,af:()=>_,yk:()=>m});var r,s=i(9723),n=i(4756),o=i(7107);function a(){let e=null;function t(e,t,i,r,s){const n=e.getImageTranscodedSizeInBytes(t,i,r);let o=new Uint8Array(n);return e.transcodeImage(o,t,i,r,1,0)?(s&&(o=function(e,t,i,r){const s=new Uint16Array(4),n=new Uint16Array(i*r),o=i/4,a=r/4;for(let t=0;t>2&3],n[h++]=s[l>>4&3],n[h++]=s[l>>6&3]}}return n}(o,0,e.getImageWidth(t,i)+3&-4,e.getImageHeight(t,i)+3&-4)),o):null}onmessage=i=>{if("init"===i.data.action){if(i.data.url)try{importScripts(i.data.url)}catch(e){postMessage({action:"error",error:e})}e||(e=BASIS({wasmBinary:i.data.wasmBinary})),null!==e&&e.then((e=>{BASIS=e,e.initializeBasis(),postMessage({action:"init"})}))}else if("transcode"===i.data.action){const e=i.data.config,r=i.data.imageData,s=new BASIS.BasisFile(r),n=function(e){const t=e.getHasAlpha(),i=e.getNumImages(),r=[];for(let t=0;t{let i;switch(e){case r.cTFETC1:i=36196;break;case r.cTFBC1:i=33776;break;case r.cTFBC4:i=33779;break;case r.cTFASTC_4x4:i=37808;break;case r.cTFETC2:i=37496;break;case r.cTFBC7:i=36492}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i};let d=null,f=null,p=0;const _=e=>{f=e},m=(e,t)=>{const i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise(((e,r)=>{(d||(d=new Promise(((e,t)=>{f?e(f):s.S0.LoadFileAsync(s.S0.GetBabylonScriptURL(c.WasmModuleURL)).then((i=>{if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");const r=URL.createObjectURL(new Blob([`(${a})()`],{type:"application/javascript"}));f=new Worker(r),function(e,t,i){return new Promise(((r,n)=>{const o=t=>{"init"===t.data.action?(e.removeEventListener("message",o),r(e)):"error"===t.data.action&&n(t.data.error||"error initializing worker")};e.addEventListener("message",o),e.postMessage({action:"init",url:i?s.S0.GetBabylonScriptURL(i):void 0,wasmBinary:t},[t])}))}(f,i,c.JSModuleURL).then(e,t)})).catch(t)}))),d).then((()=>{const s=p++,n=t=>{"transcode"===t.data.action&&t.data.id===s&&(f.removeEventListener("message",n),t.data.success?e(t.data):r("Transcode is not supported on this device"))};f.addEventListener("message",n);const o=new Uint8Array(i.byteLength);o.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),f.postMessage({action:"transcode",id:s,imageData:o,config:t,ignoreSupportedFormats:!1},[o.buffer])}),(e=>{r(e)}))}))},g=(e,t)=>{let i=t._gl?.TEXTURE_2D;e.isCube&&(i=t._gl?.TEXTURE_CUBE_MAP),t._bindTextureDirectly(i,e,!0)},v=(e,t)=>{const i=e.getEngine();for(let a=0;a{i._releaseTexture(t),g(e,i)}))}else{e.width=l.width,e.height=l.height,e.generateMipMaps=t.fileInfo.images[a].levels.length>1;const r=x.GetInternalFormatFromBasisFormat(t.format,i);e.format=r,g(e,i),t.fileInfo.images[a].levels.forEach(((t,s)=>{i._uploadCompressedDataToTextureDirectly(e,r,t.width,t.height,t.transcodedPixels,a,s)})),!i._features.basisNeedsPOT||Math.log2(e.width)%1==0&&Math.log2(e.height)%1==0||(s.S0.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."),e._cachedWrapU=n.g.CLAMP_ADDRESSMODE,e._cachedWrapV=n.g.CLAMP_ADDRESSMODE)}}},x={JSModuleURL:c.JSModuleURL,WasmModuleURL:c.WasmModuleURL,GetInternalFormatFromBasisFormat:u,TranscodeAsync:m,LoadTextureFromTranscodeResult:v};Object.defineProperty(x,"JSModuleURL",{get:function(){return c.JSModuleURL},set:function(e){c.JSModuleURL=e}}),Object.defineProperty(x,"WasmModuleURL",{get:function(){return c.WasmModuleURL},set:function(e){c.WasmModuleURL=e}})},61572:(e,t,i)=>{"use strict";function r(e,t,i=!1){const r=t.width,s=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT;const i=new Uint8Array(t);for(;--t>=0;){let r=e[t];r<0?r=0:r>1&&(r=1),i[t]=255*r}e=i}const n=document.createElement("canvas");n.width=r,n.height=s;const o=n.getContext("2d");if(!o)return null;const a=o.createImageData(r,s);if(a.data.set(e),o.putImageData(a,0,0),i){const e=document.createElement("canvas");e.width=r,e.height=s;const t=e.getContext("2d");return t?(t.translate(0,s),t.scale(1,-1),t.drawImage(n,0,0),e.toDataURL("image/png")):null}return n.toDataURL("image/png")}function s(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const n=e._readPixelsSync(t,i);return n?r(n,e.getSize(),s.invertY):null}async function n(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const n=await e.readPixels(t,i);return n?r(n,e.getSize(),s.invertY):null}i.d(t,{D8:()=>o,c9:()=>r,lP:()=>s,nh:()=>n});const o={GenerateBase64StringFromPixelData:r,GenerateBase64StringFromTexture:s,GenerateBase64StringFromTextureAsync:n}},26589:(e,t,i)=>{"use strict";i.d(t,{DDSTools:()=>p});var r=i(56984),s=i(60590),n=i(82266),o=i(28876);i(7244);const a=131072,l=131072;function h(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}const c=h("DXT1"),u=h("DXT3"),d=h("DXT5"),f=h("DX10");class p{static GetDDSInfo(e){const t=new Int32Array(e.buffer,e.byteOffset,31),i=new Int32Array(e.buffer,e.byteOffset,35);let r=1;t[2]&a&&(r=Math.max(1,t[7]));const s=t[21],n=s===f?i[32]:0;let o=0;switch(s){case 113:o=2;break;case 116:o=1;break;case f:if(10===n){o=2;break}if(2===n){o=1;break}}return{width:t[4],height:t[3],mipmapCount:r,isFourCC:!(4&~t[20]),isRGB:!(64&~t[20]),isLuminance:(t[20]&l)===l,isCube:!(512&~t[28]),isCompressed:s===c||s===u||s===d,dxgiFormat:n,textureType:o}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,r,s,n){const a=new Float32Array(r),l=new Uint16Array(s,i);let h=0;for(let i=0;i>8)}static _GetRGBArrayBuffer(e,t,i,r,s,n,o,a){const l=new Uint8Array(r),h=new Uint8Array(s,i);let c=0;for(let i=0;i>8&255,D>>16&255,D>>24&255))])}var D;const w=p._ExtractLongWordOrder(x[23]),N=p._ExtractLongWordOrder(x[24]),F=p._ExtractLongWordOrder(x[25]),L=p._ExtractLongWordOrder(x[26]);O&&(R=e._getRGBABufferInternalSizedFormat(r.textureType)),E=1,x[2]&a&&!1!==o&&(E=Math.max(1,x[7]));const B=_||0,V=e.getCaps();for(let s=B;s0?r.sphericalPolynomial=n.d.ConvertCubeMapToSphericalPolynomial({size:x[4],right:g[0],left:g[1],up:g[2],down:g[3],front:g[4],back:g[5],format:5,type:1,gammaSpace:!1}):r.sphericalPolynomial=void 0}}p.StoreLODInAlphaChannel=!1},23559:(e,t,i)=>{"use strict";i.d(t,{B:()=>n,K:()=>o});const r={},s={};function n(e){const t=e.getClassName();return s[t]||(s[t]={}),s[t]}function o(e){const t=e.getClassName();if(r[t])return r[t];r[t]={};const i=r[t];let n=e,o=t;for(;o;){const e=s[o];for(const t in e)i[t]=e[t];let t,r=!1;do{if(t=Object.getPrototypeOf(n),!t.getClassName){r=!0;break}if(t.getClassName()!==o)break;n=t}while(t);if(r)break;o=t.getClassName(),n=t}return i}},40220:(e,t,i)=>{"use strict";i.d(t,{$z:()=>n,Cx:()=>x,GG:()=>g,P_:()=>u,WM:()=>c,Y9:()=>h,bR:()=>m,fW:()=>v,jT:()=>l,lK:()=>o,n1:()=>_,qK:()=>p,uM:()=>a,wL:()=>f,xG:()=>d});var r=i(23559);function s(e,t){return(i,s)=>{const n=(0,r.B)(i);n[s]||(n[s]={type:e,sourceName:t})}}function n(e,t=null){return function(e,t=null){return(i,r)=>{const s=t||"_"+r;Object.defineProperty(i,r,{get:function(){return this[s]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[s]!==t&&(this[s]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function o(e){return s(0,e)}function a(e){return s(1,e)}function l(e){return s(2,e)}function h(e){return s(3,e)}function c(e){return s(4,e)}function u(e){return s(5,e)}function d(e){return s(6,e)}function f(e){return s(7,e)}function p(e){return s(8,e)}function _(e){return s(9,e)}function m(e){return s(10,e)}function g(e){return s(12,e)}function v(e){return s(11,e)}function x(e,t,i,r){const s=i.value;i.value=(...i)=>{let n=s;if("undefined"!=typeof _native&&_native[t]){const e=_native[t];n=r?(...t)=>r(...t)?e(...t):s(...t):e}return e[t]=n,n(...i)}}x.filter=function(e){return(t,i,r)=>x(t,i,r,e)}},89518:(e,t,i)=>{"use strict";i.d(t,{p:()=>h});var r=i(75108),s=i(84015),n=i(11084),o=i(94212),a=i(23559);const l=function(e,t,i,r={}){const n=e();s.Y&&s.Y.HasTags(t)&&s.Y.AddTagsTo(n,s.Y.GetTags(t,!0));const o=(0,a.K)(n),l={};for(const e in o){const s=o[e],a=t[e],c=s.type;if(null!=a&&("uniqueId"!==e||h.AllowLoadingUniqueId))switch(c){case 0:case 6:case 11:n[e]=a;break;case 1:r.cloneTexturesOnlyOnce&&l[a.uniqueId]?n[e]=l[a.uniqueId]:(n[e]=i||a.isRenderTarget?a:a.clone(),l[a.uniqueId]=n[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:n[e]=i?a:a.clone()}}return n};class h{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw(0,r.n)("ImageProcessingConfiguration")},h._FresnelParametersParser=e=>{throw(0,r.n)("FresnelParameters")},h._ColorCurvesParser=e=>{throw(0,r.n)("ColorCurves")},h._TextureParser=(e,t,i)=>{throw(0,r.n)("Texture")}},35290:(e,t,i)=>{"use strict";i.d(t,{r:()=>n});var r=i(60590);const s=(e,t,i)=>e?e.getClassName&&"Mesh"===e.getClassName()?null:!e.getClassName||"SubMesh"!==e.getClassName()&&"PhysicsBody"!==e.getClassName()?e.clone?e.clone():Array.isArray(e)?e.slice():i&&"object"==typeof e?{...e}:null:e.clone(t):null;class n{static DeepCopy(e,t,i,n,o=!1){const a=function(e){const t=[];do{Object.getOwnPropertyNames(e).forEach((function(e){-1===t.indexOf(e)&&t.push(e)}))}while(e=Object.getPrototypeOf(e));return t}(e);for(const l of a){if("_"===l[0]&&(!n||-1===n.indexOf(l)))continue;if(l.endsWith("Observable"))continue;if(i&&-1!==i.indexOf(l))continue;const a=e[l],h=typeof a;if("function"!==h)try{if("object"===h)if(a instanceof Uint8Array)t[l]=Uint8Array.from(a);else if(a instanceof Array){if(t[l]=[],a.length>0)if("object"==typeof a[0])for(let e=0;e{"use strict";i.d(t,{n:()=>s});const r={};function s(e,t=!1){if(!t||!r[e])return r[e]=!0,`${e} needs to be imported before as it contains a side-effect required by your code.`}},68191:(e,t,i)=>{"use strict";function r(){return"undefined"!=typeof window}function s(){return"undefined"!=typeof navigator}function n(){return"undefined"!=typeof document}function o(e){let t="",i=e.firstChild;for(;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}i.d(t,{Az:()=>a,BA:()=>r,Nf:()=>n,XD:()=>s,Zl:()=>o});const a={IsWindowObjectExist:r,IsNavigatorAvailable:s,IsDocumentAvailable:n,GetDOMTextContent:o}},465:(e,t,i)=>{"use strict";i.r(t),i.d(t,{Dispose:()=>d,DumpData:()=>u,DumpDataAsync:()=>c,DumpFramebuffer:()=>h,DumpTools:()=>f});var r=i(50606),s=i(9723),n=i(56984),o=i(34268);let a,l=null;async function h(e,t,i,r,s="image/png",n,o){const a=await i.readPixels(0,0,e,t);u(e,t,new Uint8Array(a.buffer),r,s,n,!0,void 0,o)}function c(e,t,i,r="image/png",s,n=!1,o=!1,a){return new Promise((l=>{u(e,t,i,(e=>l(e)),r,s,n,o,a)}))}function u(e,t,h,c,u="image/png",f,p=!1,_=!1,m){(async function(){return l||(l=new Promise(((e,t)=>{let s,n=null;const l={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};Promise.resolve().then(i.bind(i,722)).then((({ThinEngine:h})=>{try{s=new OffscreenCanvas(100,100),n=new h(s,!1,l)}catch(e){s=document.createElement("canvas"),n=new h(s,!1,l)}o.q.Instances.pop(),o.q.OnEnginesDisposedObservable.add((e=>{n&&e!==n&&!n.isDisposed&&0===o.q.Instances.length&&d()})),n.getCaps().parallelShaderCompile=void 0;const c=new r.J(n);Promise.resolve().then(i.bind(i,30927)).then((({passPixelShader:i})=>{if(!n)return void t("Engine is not defined");const o=new r.$({engine:n,name:i.name,fragmentShader:i.shader,samplerNames:["textureSampler"]});a={canvas:s,engine:n,renderer:c,wrapper:o},e(a)}))})).catch(t)}))),await l})().then((i=>{if(i.engine.setSize(e,t,!0),h instanceof Float32Array){const e=new Uint8Array(h.length);let t=h.length;for(;t--;){const i=h[t];e[t]=Math.round(255*(0,n.Clamp)(i))}h=e}const r=i.engine.createRawTexture(h,e,t,5,!1,!p,1);i.renderer.setViewport(),i.renderer.applyEffectWrapper(i.wrapper),i.wrapper.effect._bindTexture("textureSampler",r),i.renderer.draw(),_?s.S0.ToBlob(i.canvas,(e=>{const t=new FileReader;t.onload=e=>{const t=e.target.result;c&&c(t)},t.readAsArrayBuffer(e)}),u,m):s.S0.EncodeScreenshotCanvasData(i.canvas,c,u,f,m),r.dispose()}))}function d(){a?(a.wrapper.dispose(),a.renderer.dispose(),a.engine.dispose()):l?.then((e=>{e.wrapper.dispose(),e.renderer.dispose(),e.engine.dispose()})),l=null,a=null}const f={DumpData:u,DumpDataAsync:c,DumpFramebuffer:h,Dispose:d};s.S0.DumpData=u,s.S0.DumpDataAsync=c,s.S0.DumpFramebuffer=h},48195:(e,t,i)=>{"use strict";i.d(t,{$h:()=>S,Hx:()=>x,RZ:()=>v,bv:()=>y,cU:()=>g,gW:()=>P,o5:()=>T,ow:()=>E,qY:()=>A});var r=i(9723),s=i(94212),n=i(56984),o=i(13798),a=i(7107),l=i(23199),h=i(88193),c=i(52660),u=i(60590),d=i(2069),f=(i(54699),i(465));const p="image/png",_=2,m=[134,22,135,150,246,214,150,54];function g(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let i=0;for(let e=0;e_)throw new Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "${_}".`);return 2===e.version?e:e={...e,version:2,imageType:p}}async function x(e,t={}){const i=e.getInternalTexture();if(!i)return Promise.reject("The cube texture is invalid.");const r=t.imageType??p,s=i.getEngine();if(2!==e.textureType&&1!==e.textureType&&0!==e.textureType&&0!==e.textureType&&7!==e.textureType&&-1!==e.textureType)return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");let o=1;if(!s.getCaps().textureFloatRender&&(o=2,!s.getCaps().textureHalfFloatRender))return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");e.sphericalPolynomial;const a=e.getInternalTexture()?._sphericalPolynomialPromise,l=i.width,c=new h.Z(s),u={};s.flushFramebuffer();const g=(0,n.ILog2)(i.width);for(let i=0;i<=g;i++){const n=Math.pow(2,g-i);for(let a=0;a<6;a++){let l=await e.readPixels(a,i,void 0,!1);if(l&&l.byteLength===l.length){const e=new Float32Array(4*l.byteLength);for(let t=0;t{if(i){const i=t.createTexture(null,!0,!0,null,1,null,(e=>{d(e)}),e);r?.onEffectCreatedObservable.addOnce((a=>{a.executeWhenCompiled((()=>{r.externalTextureSamplerBinding=!0,r.onApply=r=>{r._bindTexture("textureSampler",i),r.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([r],h,!0,n,o),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(s),u())}))}))}else{if(t._uploadImageToTexture(c,e,n,o),a){const i=l[o];i&&t._uploadImageToTexture(i._texture,e,n,0)}u()}}))}async function y(e,t,s=p){if(!r.S0.IsExponentOfTwo(e.width))throw new Error("Texture size must be a power of two");const o=(0,n.ILog2)(e.width)+1,h=e.getEngine();let u=!1,d=!1,f=null,_=null,m=null;const g=h.getCaps();e.format=5,e.type=0,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,h.updateTextureSamplingMode(3,e),g.textureLOD?h._features.supportRenderAndCopyToLodForFloatTextures?g.textureHalfFloatRender&&g.textureHalfFloatLinearFiltering?(u=!0,e.type=2):g.textureFloatRender&&g.textureFloatLinearFiltering&&(u=!0,e.type=1):u=!1:(u=!1,d=!0,m={});let v=0;if(u)h.isWebGPU?(v=1,await Promise.resolve().then(i.bind(i,79388))):await Promise.resolve().then(i.bind(i,64849)),f=new c.w("rgbdDecode","rgbdDecode",null,null,1,null,3,h,!1,void 0,e.type,void 0,null,!1,void 0,v),e._isRGBD=!1,e.invertY=!1,_=h.createRenderTargetCubeTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:e.type,format:5});else if(e._isRGBD=!0,e.invertY=!0,d){const t=3,i=e._lodGenerationScale,r=e._lodGenerationOffset;for(let s=0;sC(t,h,u,f,a,r,i,d,m,_,e)));else{const t=new Image;t.src=a,l=new Promise(((s,n)=>{t.onload=()=>{C(t,h,u,f,a,r,i,d,m,_,e).then((()=>s())).catch((e=>{n(e)}))},t.onerror=e=>{n(e)}}))}x.push(l)}if(t.length{_&&(h._releaseTexture(e),_._swapAndDie(e)),f&&f.dispose(),d&&(e._lodTextureHigh&&e._lodTextureHigh._texture&&(e._lodTextureHigh._texture.isReady=!0),e._lodTextureMid&&e._lodTextureMid._texture&&(e._lodTextureMid._texture.isReady=!0),e._lodTextureLow&&e._lodTextureLow._texture&&(e._lodTextureLow._texture.isReady=!0))}))}function E(e,t){const i=(t=v(t)).irradiance;if(!i)return;const r=new o.Q;s.Pq.FromArrayToRef(i.x,0,r.x),s.Pq.FromArrayToRef(i.y,0,r.y),s.Pq.FromArrayToRef(i.z,0,r.z),s.Pq.FromArrayToRef(i.xx,0,r.xx),s.Pq.FromArrayToRef(i.yy,0,r.yy),s.Pq.FromArrayToRef(i.zz,0,r.zz),s.Pq.FromArrayToRef(i.yz,0,r.yz),s.Pq.FromArrayToRef(i.zx,0,r.zx),s.Pq.FromArrayToRef(i.xy,0,r.xy),e._sphericalPolynomial=r}function P(e,t,i,r,s){const n=y(e.getEngine().createRawCubeTexture(null,e.width,e.format,e.type,e.generateMipMaps,e.invertY,e.samplingMode,e._compression),t).then((()=>e));return e.onRebuildCallback=e=>({proxy:n,isReady:!0,isAsync:!0}),e._source=13,e._bufferViewArrayArray=t,e._lodGenerationScale=r,e._lodGenerationOffset=s,e._sphericalPolynomial=i,y(e,t).then((()=>(e.isReady=!0,e)))}const A={GetEnvInfo:g,CreateEnvTextureAsync:x,CreateImageDataArrayBufferViews:S,UploadEnvLevelsAsync:T,UploadLevelsAsync:y,UploadEnvSpherical:E}},14914:(e,t,i)=>{"use strict";i.d(t,{Cf:()=>r,bu:()=>n,tG:()=>s});class r extends Error{}r._setPrototypeOf=Object.setPrototypeOf||((e,t)=>(e.__proto__=t,e));const s={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class n extends r{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",r._setPrototypeOf(this,n.prototype)}}},28909:(e,t,i)=>{"use strict";i.d(t,{M1:()=>S,Mi:()=>v,NJ:()=>y,VB:()=>x,W$:()=>C,ZP:()=>I,dy:()=>O,eC:()=>b,f2:()=>R,hX:()=>g,my:()=>A,qc:()=>T,rh:()=>w,rz:()=>M,sh:()=>P,wS:()=>D,zU:()=>E});var r=i(67313),s=i(68191),n=i(43279),o=i(20934),a=i(56703),l=i(14914),h=i(5800),c=i(88217),u=i(34268),d=i(60590),f=i(72649),p=i(2636),_=i(55935);const m=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class g extends l.bu{constructor(e,t){super(e,l.tG.LoadFileError),this.name="LoadFileError",l.Cf._setPrototypeOf(this,g.prototype),t instanceof r.u?this.request=t:this.file=t}}class v extends l.bu{constructor(e,t){super(e,l.tG.RequestFileError),this.request=t,this.name="RequestFileError",l.Cf._setPrototypeOf(this,v.prototype)}}class x extends l.bu{constructor(e,t){super(e,l.tG.ReadFileError),this.file=t,this.name="ReadFileError",l.Cf._setPrototypeOf(this,x.prototype)}}const b={DefaultRetryStrategy:a.a.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e,ScriptBaseUrl:"",ScriptPreprocessUrl:e=>e,CleanUrl:e=>e.replace(/#/gm,"%23")},S=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&b.CorsBehavior)if("string"==typeof b.CorsBehavior||b.CorsBehavior instanceof String)t.crossOrigin=b.CorsBehavior;else{const i=b.CorsBehavior(e);i&&(t.crossOrigin=i)}},T={getRequiredSize:null},C=(e,t,i,s,n="",a)=>{const l=u.q.LastCreatedEngine;if("undefined"==typeof HTMLImageElement&&!l?._features.forceBitmapOverHTMLImageElement)return i("LoadImage is only supported in web or BabylonNative environments."),null;let c,d=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(c=URL.createObjectURL(new Blob([e],{type:n})),d=!0):c=`data:${n};base64,`+(0,h.EL)(e):e instanceof Blob?(c=URL.createObjectURL(e),d=!0):(c=b.CleanUrl(e),c=b.PreprocessUrl(c));const f=t=>{if(i){const r=c||e.toString();i(`Error while trying to load image: ${0===r.indexOf("http")||r.length<=128?r:r.slice(0,128)+"..."}`,t)}};if(l?._features.forceBitmapOverHTMLImageElement)return E(c,(r=>{l.createImageBitmap(new Blob([r],{type:n}),{premultiplyAlpha:"none",...a}).then((e=>{t(e),d&&URL.revokeObjectURL(c)})).catch((t=>{i&&i("Error while trying to load image: "+e,t)}))}),void 0,s||void 0,!0,((e,t)=>{f(t)})),null;const p=new Image;if(T.getRequiredSize){const t=T.getRequiredSize(e);t.width&&(p.width=t.width),t.height&&(p.height=t.height)}S(c,p);const _=[],m=()=>{_.forEach((e=>{e.target.removeEventListener(e.name,e.handler)})),_.length=0};_.push({target:p,name:"load",handler:()=>{m(),t(p),d&&p.src&&URL.revokeObjectURL(p.src)}}),_.push({target:p,name:"error",handler:e=>{m(),f(e),d&&p.src&&URL.revokeObjectURL(p.src)}}),_.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==p.src||"report"===e.disposition)return;m();const t=new Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);u.q.UseFallbackTexture=!1,f(t),d&&p.src&&URL.revokeObjectURL(p.src),p.src=""}}),_.forEach((e=>{e.target.addEventListener(e.name,e.handler)}));const g="blob:"===c.substring(0,5),v="data:"===c.substring(0,5),x=()=>{g||v||!r.u.IsCustomRequestAvailable?p.src=c:E(c,((e,t,i)=>{const r=new Blob([e],{type:!n&&i?i:n}),s=URL.createObjectURL(r);d=!0,p.src=s}),void 0,s||void 0,!0,((e,t)=>{f(t)}))};if(!g&&!v&&s&&s.enableTexturesOffline)s.open((()=>{s&&s.loadImage(c,p)}),x);else{if(-1!==c.indexOf("file:")){const e=decodeURIComponent(c.substring(5).toLowerCase());if(o.T.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(o.T.FilesToLoad[e])}catch(i){t=URL.createObjectURL(o.T.FilesToLoad[e])}p.src=t,d=!0}catch(e){p.src=""}return p}}x()}return p},y=(e,t,i,r,s)=>{const o=new FileReader,a={onCompleteObservable:new n.cP,abort:()=>o.abort()};return o.onloadend=()=>a.onCompleteObservable.notifyObservers(a),s&&(o.onerror=()=>{s(new x(`Unable to read ${e.name}`,e))}),o.onload=e=>{t(e.target.result)},i&&(o.onprogress=i),r?o.readAsArrayBuffer(e):o.readAsText(e),a},E=(e,t,i,r,s,a,l)=>{if(e.name)return y(e,t,i,s,a?e=>{a(void 0,e)}:void 0);const h=e;if(-1!==h.indexOf("file:")){let e=decodeURIComponent(h.substring(5).toLowerCase());0===e.indexOf("./")&&(e=e.substring(2));const r=o.T.FilesToLoad[e];if(r)return y(r,t,i,s,a?e=>a(void 0,new g(e.message,e.file)):void 0)}const{match:c,type:u}=I(h);if(c){const e={onCompleteObservable:new n.cP,abort:()=>()=>{}};try{const e=s?M(h):O(h);t(e,void 0,u)}catch(e){a?a(void 0,e):d.V.Error(e.message||"Failed to parse the Data URL")}return f._.SetImmediate((()=>{e.onCompleteObservable.notifyObservers(e)})),e}return P(h,((e,i)=>{t(e,i?.responseURL,i?.getResponseHeader("content-type"))}),i,r,s,a?e=>{a(e.request,new g(e.message,e.request))}:void 0,l)},P=(e,t,i,o,a,l,h)=>{e=b.CleanUrl(e),e=b.PreprocessUrl(e);const c=b.BaseUrl+e;let u=!1;const f={onCompleteObservable:new n.cP,abort:()=>u=!0},p=()=>{let e,n=new r.u,o=null;const p=()=>{n&&(i&&n.removeEventListener("progress",i),e&&n.removeEventListener("readystatechange",e),n.removeEventListener("loadend",_))};let _=()=>{p(),f.onCompleteObservable.notifyObservers(f),f.onCompleteObservable.clear(),i=void 0,e=null,_=null,l=void 0,h=void 0,t=void 0};f.abort=()=>{u=!0,_&&_(),n&&n.readyState!==(XMLHttpRequest.DONE||4)&&n.abort(),null!==o&&(clearTimeout(o),o=null),n=null};const m=e=>{const t=e.message||"Unknown error";l&&n?l(new v(t,n)):d.V.Error(t)},g=d=>{if(n){if(n.open("GET",c),h)try{h(n)}catch(e){return void m(e)}a&&(n.responseType="arraybuffer"),i&&n.addEventListener("progress",i),_&&n.addEventListener("loadend",_),e=()=>{if(!u&&n&&n.readyState===(XMLHttpRequest.DONE||4)){if(e&&n.removeEventListener("readystatechange",e),n.status>=200&&n.status<300||0===n.status&&(!(0,s.BA)()||A())){try{t&&t(a?n.response:n.responseText,n)}catch(e){m(e)}return}const i=b.DefaultRetryStrategy;if(i){const e=i(c,n,d);if(-1!==e)return p(),n=new r.u,void(o=setTimeout((()=>g(d+1)),e))}const h=new v("Error status: "+n.status+" "+n.statusText+" - Unable to load "+c,n);l&&l(h)}},n.addEventListener("readystatechange",e),n.send()}};g(0)};if(o&&o.enableSceneOffline){const r=e=>{e&&e.status>400?l&&l(e):p()},s=()=>{o&&o.loadFile(b.BaseUrl+e,(e=>{!u&&t&&t(e),f.onCompleteObservable.notifyObservers(f)}),i?e=>{!u&&i&&i(e)}:void 0,r,a)};o.open(s,r)}else p();return f},A=()=>"undefined"!=typeof location&&"file:"===location.protocol,R=e=>m.test(e),I=e=>{const t=m.exec(e);return null===t||0===t.length?{match:!1,type:""}:{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function M(e){return(0,h.yS)(e.split(",")[1])}const O=e=>(0,h.AV)(e.split(",")[1]);let D;_.$._FileToolsLoadImage=C,p.sg.loadFile=E,c.J.loadFile=E;const w=(e,t,i,r,s,n,o,a,l,h)=>{D={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:r,IsFileURL:s,LoadFile:n,LoadImage:o,ReadFile:a,RequestFile:l,SetCorsBehavior:h},Object.defineProperty(D,"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(D,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(D,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(D,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})};w(M,O,b,R,A,E,C,y,P,S)},20934:(e,t,i)=>{"use strict";i.d(t,{T:()=>r});class r{}r.FilesToLoad={}},71627:(e,t,i)=>{"use strict";function r(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}i.d(t,{S:()=>s,z:()=>r});const s={RandomId:r}},14798:(e,t,i)=>{"use strict";i.d(t,{n:()=>n});var r=i(60590),s=i(56225);class n{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=(0,s.n9)(e);if(t)return t;r.V.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let n=window||this;for(let e=0,t=i.length;e{"use strict";i.d(t,{H:()=>s});var r=i(60590);class s{constructor(e,t){if(this.data=e,this.isInvalid=!1,!s.IsValid(e))return this.isInvalid=!0,void r.V.Error("texture missing KTX identifier");const i=Uint32Array.BYTES_PER_ELEMENT,n=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),o=67305985===n.getUint32(0,!0);return this.glType=n.getUint32(1*i,o),this.glTypeSize=n.getUint32(2*i,o),this.glFormat=n.getUint32(3*i,o),this.glInternalFormat=n.getUint32(4*i,o),this.glBaseInternalFormat=n.getUint32(5*i,o),this.pixelWidth=n.getUint32(6*i,o),this.pixelHeight=n.getUint32(7*i,o),this.pixelDepth=n.getUint32(8*i,o),this.numberOfArrayElements=n.getUint32(9*i,o),this.numberOfFaces=n.getUint32(10*i,o),this.numberOfMipmapLevels=n.getUint32(11*i,o),this.bytesOfKeyValueData=n.getUint32(12*i,o),0!==this.glType?(r.V.Error("only compressed formats currently supported"),void(this.isInvalid=!0)):(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth?(r.V.Error("only 2D textures currently supported"),void(this.isInvalid=!0)):0!==this.numberOfArrayElements?(r.V.Error("texture arrays not currently supported"),void(this.isInvalid=!0)):this.numberOfFaces!==t?(r.V.Error("number of faces expected"+t+", but found "+this.numberOfFaces),void(this.isInvalid=!0)):void(this.loadType=s.COMPRESSED_2D))}uploadLevels(e,t){switch(this.loadType){case s.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);case s.TEX_2D:case s.COMPRESSED_3D:case s.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=s.HEADER_LEN+this.bytesOfKeyValueData,r=this.pixelWidth,n=this.pixelHeight;const o=t?this.numberOfMipmapLevels:1;for(let t=0;t=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&49===t[5]&&49===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}s.HEADER_LEN=64,s.COMPRESSED_2D=0,s.COMPRESSED_3D=1,s.TEX_2D=2,s.TEX_3D=3},27606:(e,t,i)=>{"use strict";i.d(t,{$:()=>l,Z:()=>h});var r=i(28382),s=i(9723),n=i(63199);function o(e,t){const i=t?.jsDecoderModule||KTX2DECODER;e&&(e.wasmUASTCToASTC&&(i.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(i.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(i.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(i.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(i.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(i.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(i.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(i.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(i.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder)),t&&(t.wasmUASTCToASTC&&(i.LiteTranscoder_UASTC_ASTC.WasmBinary=t.wasmUASTCToASTC),t.wasmUASTCToBC7&&(i.LiteTranscoder_UASTC_BC7.WasmBinary=t.wasmUASTCToBC7),t.wasmUASTCToRGBA_UNORM&&(i.LiteTranscoder_UASTC_RGBA_UNORM.WasmBinary=t.wasmUASTCToRGBA_UNORM),t.wasmUASTCToRGBA_SRGB&&(i.LiteTranscoder_UASTC_RGBA_SRGB.WasmBinary=t.wasmUASTCToRGBA_SRGB),t.wasmUASTCToR8_UNORM&&(i.LiteTranscoder_UASTC_R8_UNORM.WasmBinary=t.wasmUASTCToR8_UNORM),t.wasmUASTCToRG8_UNORM&&(i.LiteTranscoder_UASTC_RG8_UNORM.WasmBinary=t.wasmUASTCToRG8_UNORM),t.jsMSCTranscoder&&(i.MSCTranscoder.JSModule=t.jsMSCTranscoder),t.wasmMSCTranscoder&&(i.MSCTranscoder.WasmBinary=t.wasmMSCTranscoder),t.wasmZSTDDecoder&&(i.ZSTDDecoder.WasmBinary=t.wasmZSTDDecoder))}function a(e){let t;void 0===e&&"undefined"!=typeof KTX2DECODER&&(e=KTX2DECODER),onmessage=i=>{if(i.data)switch(i.data.action){case"init":{const r=i.data.urls;r&&(r.jsDecoderModule&&void 0===e&&(importScripts(r.jsDecoderModule),e=KTX2DECODER),o(r)),i.data.wasmBinaries&&o(void 0,{...i.data.wasmBinaries,jsDecoderModule:e}),t=new e.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":e.KTX2Decoder.DefaultDecoderOptions=i.data.options;break;case"decode":t.decode(i.data.data,i.data.caps,i.data.options).then((e=>{const t=[];for(let i=0;i{postMessage({action:"decoded",success:!1,msg:e})}))}}}class l{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:[n.Xl.BC1_RGB,n.Xl.BC3_RGBA],yes:{transcodeFormat:n.Xl.RGBA32,engineFormat:32856,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}}class h{static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if(h._WorkerPoolPromise||h._DecoderModulePromise)return;const t={jsDecoderModule:s.S0.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:s.S0.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:s.S0.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:s.S0.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:s.S0.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:s.S0.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:s.S0.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:s.S0.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:s.S0.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:s.S0.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?h._WorkerPoolPromise=new Promise((i=>{const s=`${o}(${a})()`,n=URL.createObjectURL(new Blob([s],{type:"application/javascript"}));i(new r.h(e,(()=>function(e,t,i){return new Promise(((t,r)=>{const s=t=>{e.removeEventListener("error",s),e.removeEventListener("message",n),r(t)},n=i=>{"init"===i.data.action&&(e.removeEventListener("error",s),e.removeEventListener("message",n),t(e))};e.addEventListener("error",s),e.addEventListener("message",n),e.postMessage({action:"init",urls:i,wasmBinaries:undefined})}))}(new Worker(n),0,t))))})):void 0===h._KTX2DecoderModule?h._DecoderModulePromise=s.S0.LoadBabylonScriptAsync(t.jsDecoderModule).then((()=>(h._KTX2DecoderModule=KTX2DECODER,h._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,h._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,o(t,h._KTX2DecoderModule),new h._KTX2DecoderModule.KTX2Decoder))):(h._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,h._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,h._DecoderModulePromise=Promise.resolve(new h._KTX2DecoderModule.KTX2Decoder))}constructor(e,t=h.DefaultNumWorkers){this._engine=e;const i="object"==typeof t&&t.workerPool||h.WorkerPool;if(i)h._WorkerPoolPromise=Promise.resolve(i);else{"object"==typeof t?h._KTX2DecoderModule=t?.binariesAndModulesContainer?.jsDecoderModule:"undefined"!=typeof KTX2DECODER&&(h._KTX2DecoderModule=KTX2DECODER);const e="number"==typeof t?t:t.numWorkers??h.DefaultNumWorkers;h._Initialize(e)}}_uploadAsync(e,t,i){const r=this._engine.getCaps(),s={astc:!!r.astc,bptc:!!r.bptc,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,etc1:!!r.etc1};if(h._WorkerPoolPromise)return h._WorkerPoolPromise.then((r=>new Promise(((n,o)=>{r.push(((r,a)=>{const l=e=>{r.removeEventListener("error",l),r.removeEventListener("message",c),o(e),a()},c=e=>{if("decoded"===e.data.action){if(r.removeEventListener("error",l),r.removeEventListener("message",c),e.data.success)try{this._createTexture(e.data.decodedData,t,i),n()}catch(e){o({message:e})}else o({message:e.data.msg});a()}};r.addEventListener("error",l),r.addEventListener("message",c),r.postMessage({action:"setDefaultDecoderOptions",options:h.DefaultDecoderOptions._getKTX2DecoderOptions()});const u=new Uint8Array(e.byteLength);u.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),r.postMessage({action:"decode",data:u,caps:s,options:i},[u.buffer])}))}))));if(h._DecoderModulePromise)return h._DecoderModulePromise.then((i=>(h.DefaultDecoderOptions.isDirty&&(h._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions=h.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise(((s,n)=>{i.decode(e,r).then((e=>{this._createTexture(e,t),s()})).catch((e=>{n({message:e})}))})))));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}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 i=0;i=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&50===t[5]&&48===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}h.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},h.DefaultNumWorkers=h.GetDefaultNumWorkers(),h.DefaultDecoderOptions=new l},60590:(e,t,i)=>{"use strict";i.d(t,{V:()=>r});class r{static _CheckLimit(e,t){let i=r._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},r._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){const i=r._LogLimitOutputs[e];if(!i||!r.MessageLimitReached)return;const s=this._Levels[t];i.current===i.limit&&r[s.name](r.MessageLimitReached.replace(/%LIMIT%/g,""+i.limit).replace(/%TYPE%/g,s.name??""))}static _AddLogEntry(e){r._LogCache=e+r._LogCache,r.OnNewCacheEntry&&r.OnNewCacheEntry(e)}static _FormatMessage(e){const t=e=>e<10?"0"+e:""+e,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(void 0!==i&&!r._CheckLimit(s,i))return;const n=r._FormatMessage(s),o=this._Levels[e],a=Array.isArray(t)?t.slice(1):[];o.logFunc&&o.logFunc("BJS - "+n,...a);const l=`
${n}

`;r._AddLogEntry(l),r._GenerateLimitMessage(s,e)}static get LogCache(){return r._LogCache}static ClearLogCache(){r._LogCache="",r._LogLimitOutputs={},r.errorsCount=0}static set LogLevels(e){r.Log=r._LogDisabled,r.Warn=r._LogDisabled,r.Error=r._LogDisabled,[r.MessageLogLevel,r.WarningLogLevel,r.ErrorLogLevel].forEach((t=>{if((e&t)===t){const e=this._Levels[t];r[e.name]=r._LogEnabled.bind(r,t)}}))}}r.NoneLogLevel=0,r.MessageLogLevel=1,r.WarningLogLevel=2,r.ErrorLogLevel=4,r.AllLogLevel=7,r.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",r._LogCache="",r._LogLimitOutputs={},r._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],r.errorsCount=0,r.Log=r._LogEnabled.bind(r,r.MessageLogLevel),r.Warn=r._LogEnabled.bind(r,r.WarningLogLevel),r.Error=r._LogEnabled.bind(r,r.ErrorLogLevel)},43279:(e,t,i)=>{"use strict";i.d(t,{cP:()=>n,nu:()=>s,qO:()=>r});class r{constructor(e,t=!1,i,r){this.initialize(e,t,i,r)}initialize(e,t=!1,i,r){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=r,this}}class s{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){if(this._remove){const e=this._remove.deref();e&&e()}}}class n{static FromPromise(e,t){const i=new n;return e.then((e=>{i.notifyObservers(e)})).catch((e=>{if(!t)throw e;t.notifyObservers(e)})),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 r(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,r=null,n=!1){if(!e)return null;const o=new s(e,t,r);return o.unregisterOnNextCall=n,i?this._observers.unshift(o):this._observers.push(o),this._onObserverAdded&&this._onObserverAdded(o),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(o,this._lastNotifiedValue),o._remove=new WeakRef((()=>{this.remove(o)})),o}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return!!e&&(e._remove=null,-1!==this._observers.indexOf(e)&&(this._deferUnregister(e),!0))}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-1!==i&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0)}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,r,s){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=r,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=s;for(const i of this._observers)if(!i._willBeUnregistered&&(i.mask&t&&(i.unregisterOnNextCall&&this._deferUnregister(i),i.scope?n.lastReturnValue=i.callback.apply(i.scope,[e,n]):n.lastReturnValue=i.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 r=this._eventState;r.mask=i,r.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,r)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){const e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new n;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}}},78641:(e,t,i)=>{"use strict";i.d(t,{A:()=>s});var r=i(64736);class s{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){s.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){s.Enabled&&(this._startMonitoringTime=r.j.Now)}endMonitoring(e=!0){if(!s.Enabled)return;e&&this.fetchNewFrame();const t=r.j.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=r.j.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}s.Enabled=!0},64736:(e,t,i)=>{"use strict";i.d(t,{j:()=>s});var r=i(68191);class s{static get Now(){return(0,r.BA)()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}},56703:(e,t,i)=>{"use strict";i.d(t,{a:()=>r});class r{static ExponentialBackoff(e=3,t=500){return(i,r,s)=>0!==r.status||s>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,s)*t}}},2069:(e,t,i)=>{"use strict";i.d(t,{G:()=>n});var r=i(52660),s=i(28876);class n{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const s=t.getEngine(),n=s.getCaps(),o=t.isReady;let a=!1;n.textureHalfFloatRender&&n.textureHalfFloatLinearFiltering?(a=!0,t.type=2):n.textureFloatRender&&n.textureFloatLinearFiltering&&(a=!0,t.type=1),a&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const l=async()=>{const n=s.isWebGPU,o=n?1:0;t.isReady=!1,n?await Promise.all([Promise.resolve().then(i.bind(i,79388)),Promise.resolve().then(i.bind(i,41572))]):await Promise.all([Promise.resolve().then(i.bind(i,64849)),Promise.resolve().then(i.bind(i,32957))]);const a=new r.w("rgbdDecode","rgbdDecode",null,null,1,null,3,s,!1,void 0,t.type,void 0,null,!1,void 0,o);a.externalTextureSamplerBinding=!0;const l=s.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});a.onEffectCreatedObservable.addOnce((i=>{i.executeWhenCompiled((()=>{a.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([a],l,!0),s.restoreDefaultFramebuffer(),s._releaseTexture(t),a&&a.dispose(),l._swapAndDie(t),t.isReady=!0}))}))};a&&(o?l():e.onLoadObservable.addOnce(l))}static EncodeTextureToRGBD(e,t,i=0){return(0,s.Qs)("rgbdEncode",e,t,i,1,5)}}},39464:(e,t,i)=>{"use strict";i.d(t,{L:()=>r,b:()=>s});class r{constructor(e){this.length=0,this.data=new Array(e),this._id=r._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=2*(this.length+e.length));for(let t=0;t=this.length?-1:t}contains(e){return-1!==this.indexOf(e)}}r._GlobalId=0;class s extends r{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||(this.push(e),0))}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;t{"use strict";i.d(t,{w:()=>r});class r{constructor(){this._count=0,this._data={}}copyFrom(e){this.clear(),e.forEach(((e,t)=>this.add(e,t)))}get(e){const t=this._data[e];if(void 0!==t)return t}getOrAddWithFactory(e,t){let i=this.get(e);return void 0!==i||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){const i=this.get(e);return void 0!==i?i:(this.add(e,t),t)}contains(e){return void 0!==this._data[e]}add(e,t){return void 0===this._data[e]&&(this._data[e]=t,++this._count,!0)}set(e,t){return void 0!==this._data[e]&&(this._data[e]=t,!0)}getAndRemove(e){const t=this.get(e);return void 0!==t?(delete this._data[e],--this._count,t):null}remove(e){return!!this.contains(e)&&(delete this._data[e],--this._count,!0)}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(const t in this._data)e(t,this._data[t])}first(e){for(const t in this._data){const i=e(t,this._data[t]);if(i)return i}return null}}},5800:(e,t,i)=>{"use strict";i.d(t,{AV:()=>a,EL:()=>o,LW:()=>h,Tq:()=>n,UH:()=>s,jq:()=>r,nQ:()=>c,yS:()=>l});const r=(e,t)=>e.endsWith(t),s=(e,t)=>!!e&&e.startsWith(t),n=e=>{if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let i=0;i{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let i,r,s,n,o,a,l,h="",c=0;const u=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;c>2,o=(3&i)<<4|r>>4,a=(15&r)<<2|s>>6,l=63&s,isNaN(r)?a=l=64:isNaN(s)&&(l=64),h+=t.charAt(n)+t.charAt(o)+t.charAt(a)+t.charAt(l);return h},a=e=>atob(e),l=e=>{const t=a(e),i=t.length,r=new Uint8Array(new ArrayBuffer(i));for(let e=0;e{let i=String(e);for(;i.length{"use strict";i.d(t,{Y:()=>s});var r=i(76486);class s{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>s.HasTags(e),e.addTags=t=>s.AddTagsTo(e,t),e.removeTags=t=>s.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>s.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 e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){const t=[];for(const i in e._tags)Object.prototype.hasOwnProperty.call(e._tags,i)&&!0===e._tags[i]&&t.push(i);return t.join(" ")}return e._tags}static AddTagsTo(e,t){t&&"string"==typeof t&&t.split(" ").forEach((function(t){s._AddTagTo(e,t)}))}static _AddTagTo(e,t){""!==(t=t.trim())&&"true"!==t&&"false"!==t&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(s.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!s.HasTags(e))return;const i=t.split(" ");for(const t in i)s._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?s.HasTags(e):r.Z.Eval(t,(t=>s.HasTags(e)&&e._tags[t])))}}},28876:(e,t,i)=>{"use strict";i.d(t,{EE:()=>a,LO:()=>_,LZ:()=>u,Oz:()=>p,Qs:()=>l,SX:()=>d});var r=i(4756),s=i(58059),n=i(78239),o=i(52660);function a(e,t,i,o=!0){const a=e.getScene(),l=a.getEngine(),h=new s.$("resized"+e.name,{width:t,height:i},a,!e.noMipmap,!0,e._texture.type,!1,e.samplingMode,!1);h.wrapU=e.wrapU,h.wrapV=e.wrapV,h.uOffset=e.uOffset,h.vOffset=e.vOffset,h.uScale=e.uScale,h.vScale=e.vScale,h.uAng=e.uAng,h.vAng=e.vAng,h.wAng=e.wAng,h.coordinatesIndex=e.coordinatesIndex,h.level=e.level,h.anisotropicFilteringLevel=e.anisotropicFilteringLevel,h._texture.isReady=!1,e.wrapU=r.g.CLAMP_ADDRESSMODE,e.wrapV=r.g.CLAMP_ADDRESSMODE;const c=new n.v("pass",1,null,o?r.g.BILINEAR_SAMPLINGMODE:r.g.NEAREST_SAMPLINGMODE,l,!1,0);return c.externalTextureSamplerBinding=!0,c.onEffectCreatedObservable.addOnce((t=>{t.executeWhenCompiled((()=>{c.onApply=function(t){t.setTexture("textureSampler",e)};const t=h.renderTarget;t&&(a.postProcessManager.directRender([c],t),l.unBindFramebuffer(t),h.disposeFramebufferObjects(),c.dispose(),h.getInternalTexture().isReady=!0)}))})),h}function l(e,t,i,r,s,n,a,l){const h=t.getEngine();return t.isReady=!1,s=s??t.samplingMode,r=r??t.type,n=n??t.format,a=a??t.width,l=l??t.height,-1===r&&(r=0),new Promise((c=>{const u=new o.w("postprocess",e,null,null,1,null,s,h,!1,void 0,r,void 0,null,!1,n);u.externalTextureSamplerBinding=!0;const d=h.createRenderTargetTexture({width:a,height:l},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:r,format:n});u.onEffectCreatedObservable.addOnce((e=>{e.executeWhenCompiled((()=>{u.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([u],d,!0),h.restoreDefaultFramebuffer(),h._releaseTexture(t),u&&u.dispose(),d._swapAndDie(t),t.type=r,t.format=5,t.isReady=!0,c(t)}))}))}))}let h,c;function u(e){h||(h=new Float32Array(1),c=new Int32Array(h.buffer)),h[0]=e;const t=c[0];let i=t>>16&32768,r=t>>12&2047;const s=t>>23&255;return s<103?i:s>142?(i|=31744,i|=(255==s?0:1)&&8388607&t,i):s<113?(r|=2048,i|=(r>>114-s)+(r>>113-s&1),i):(i|=s-112<<10|r>>1,i+=1&r,i)}function d(e){const t=(32768&e)>>15,i=(31744&e)>>10,r=1023&e;return 0===i?(t?-1:1)*Math.pow(2,-14)*(r/Math.pow(2,10)):31==i?r?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+r/Math.pow(2,10))}const f=async(e,t,n,a,l)=>{const h=e.getScene(),c=h.getEngine();let u;if(c.isWebGPU?e.isCube?await Promise.resolve().then(i.bind(i,61951)):await Promise.resolve().then(i.bind(i,58316)):e.isCube?await Promise.resolve().then(i.bind(i,47084)):await Promise.resolve().then(i.bind(i,46143)),e.isCube){const e=["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"];u=new o.w("lodCube","lodCube",{uniforms:["lod","gamma"],samplingMode:r.g.NEAREST_NEAREST_MIPNEAREST,engine:c,defines:e[a],shaderLanguage:c.isWebGPU?1:0})}else u=new o.w("lod","lod",{uniforms:["lod","gamma"],samplingMode:r.g.NEAREST_NEAREST_MIPNEAREST,engine:c,shaderLanguage:c.isWebGPU?1:0});await new Promise((e=>{u.onEffectCreatedObservable.addOnce((t=>{t.executeWhenCompiled((()=>{e(0)}))}))}));const d=new s.$("temp",{width:t,height:n},h,!1);u.onApply=function(t){t.setTexture("textureSampler",e),t.setFloat("lod",l),t.setInt("gamma",e.gammaSpace?1:0)};const f=e.getInternalTexture();try{if(d.renderTarget&&f){const i=f.samplingMode;0!==l?e.updateSamplingMode(r.g.NEAREST_NEAREST_MIPNEAREST):e.updateSamplingMode(r.g.NEAREST_NEAREST),h.postProcessManager.directRender([u],d.renderTarget,!0),e.updateSamplingMode(i);const s=await c.readPixels(0,0,t,n),o=new Uint8Array(s.buffer,0,s.byteLength);return c.unBindFramebuffer(d.renderTarget),o}throw Error("Render to texture failed.")}finally{d.dispose(),u.dispose()}};async function p(e,t,i,r=0,s=0){return!e.isReady()&&e._texture&&await new Promise(((t,i)=>{null!==e._texture?e._texture.onLoadedObservable.addOnce((()=>{t(0)})):i(0)})),await f(e,t,i,r,s)}const _={CreateResizedCopy:a,ApplyPostProcess:l,ToHalfFloat:u,FromHalfFloat:d,GetTextureDataAsync:p}},96172:(e,t,i)=>{"use strict";i.d(t,{FA:()=>g,O_:()=>m,uT:()=>v});var r=i(60590);const s=1,n=2,o=3,a=9,l=10,h=11,c=48,u=4,d=0,f=1,p=2,_=3;function m(e){let t=0;return{id_length:e[t++],colormap_type:e[t++],image_type:e[t++],colormap_index:e[t++]|e[t++]<<8,colormap_length:e[t++]|e[t++]<<8,colormap_size:e[t++],origin:[e[t++]|e[t++]<<8,e[t++]|e[t++]<<8],width:e[t++]|e[t++]<<8,height:e[t++]|e[t++]<<8,pixel_size:e[t++],flags:e[t++]}}function g(e,t){if(t.length<19)return void r.V.Error("Unable to load TGA file - Not enough data to contain header");let i=18;const g=m(t);if(g.id_length+i>t.length)return void r.V.Error("Unable to load TGA file - Not enough data");i+=g.id_length;let x,b=!1,S=!1,T=!1;switch(g.image_type){case a:b=!0;case s:S=!0;break;case l:b=!0;case n:break;case h:b=!0;case o:T=!0}const C=g.pixel_size>>3,y=g.width*g.height*C;let E,P,A,R,I,M,O;if(S&&(E=t.subarray(i,i+=g.colormap_length*(g.colormap_size>>3))),b){let e,r,s;x=new Uint8Array(y);let n=0;const o=new Uint8Array(C);for(;i>u){default:case p:P=0,R=1,O=g.width,A=0,I=1,M=g.height;break;case d:P=0,R=1,O=g.width,A=g.height-1,I=-1,M=-1;break;case _:P=g.width-1,R=-1,O=-1,A=0,I=1,M=g.height;break;case f:P=g.width-1,R=-1,O=-1,A=g.height-1,I=-1,M=-1}const D="_getImageData"+(T?"Grey":"")+g.pixel_size+"bits",w=v[D](g,E,x,A,I,M,P,R,O);e.getEngine()._uploadDataToTextureDirectly(e,w)}const v={GetTGAHeader:m,UploadContent:g,_getImageData8bits:function(e,t,i,r,s,n,o,a,l){const h=i,c=t,u=e.width,d=e.height;let f,p,_,m=0;const g=new Uint8Array(u*d*4);for(_=r;_!==n;_+=s)for(p=o;p!==l;p+=a,m++)f=h[m],g[4*(p+u*_)+3]=255,g[4*(p+u*_)+2]=c[3*f+0],g[4*(p+u*_)+1]=c[3*f+1],g[4*(p+u*_)+0]=c[3*f+2];return g},_getImageData16bits:function(e,t,i,r,s,n,o,a,l){const h=i,c=e.width,u=e.height;let d,f,p,_=0;const m=new Uint8Array(c*u*4);for(p=r;p!==n;p+=s)for(f=o;f!==l;f+=a,_+=2){d=h[_+0]+(h[_+1]<<8);const e=255*((31744&d)>>10)/31|0,t=255*((992&d)>>5)/31|0,i=255*(31&d)/31|0;m[4*(f+c*p)+0]=e,m[4*(f+c*p)+1]=t,m[4*(f+c*p)+2]=i,m[4*(f+c*p)+3]=32768&d?0:255}return m},_getImageData24bits:function(e,t,i,r,s,n,o,a,l){const h=i,c=e.width,u=e.height;let d,f,p=0;const _=new Uint8Array(c*u*4);for(f=r;f!==n;f+=s)for(d=o;d!==l;d+=a,p+=3)_[4*(d+c*f)+3]=255,_[4*(d+c*f)+2]=h[p+0],_[4*(d+c*f)+1]=h[p+1],_[4*(d+c*f)+0]=h[p+2];return _},_getImageData32bits:function(e,t,i,r,s,n,o,a,l){const h=i,c=e.width,u=e.height;let d,f,p=0;const _=new Uint8Array(c*u*4);for(f=r;f!==n;f+=s)for(d=o;d!==l;d+=a,p+=4)_[4*(d+c*f)+2]=h[p+0],_[4*(d+c*f)+1]=h[p+1],_[4*(d+c*f)+0]=h[p+2],_[4*(d+c*f)+3]=h[p+3];return _},_getImageDataGrey8bits:function(e,t,i,r,s,n,o,a,l){const h=i,c=e.width,u=e.height;let d,f,p,_=0;const m=new Uint8Array(c*u*4);for(p=r;p!==n;p+=s)for(f=o;f!==l;f+=a,_++)d=h[_],m[4*(f+c*p)+0]=d,m[4*(f+c*p)+1]=d,m[4*(f+c*p)+2]=d,m[4*(f+c*p)+3]=255;return m},_getImageDataGrey16bits:function(e,t,i,r,s,n,o,a,l){const h=i,c=e.width,u=e.height;let d,f,p=0;const _=new Uint8Array(c*u*4);for(f=r;f!==n;f+=s)for(d=o;d!==l;d+=a,p+=2)_[4*(d+c*f)+0]=h[p+0],_[4*(d+c*f)+1]=h[p+0],_[4*(d+c*f)+2]=h[p+0],_[4*(d+c*f)+3]=h[p+1];return _}}},72649:(e,t,i)=>{"use strict";i.d(t,{_:()=>s});var r=i(68191);class s{static SetImmediate(e){(0,r.BA)()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}},44512:(e,t,i)=>{"use strict";function r(e){let t=1;do{t*=2}while(te-i?i:t}function o(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}function a(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}function l(e,t,i=2){let r;switch(i){case 1:r=a(e);break;case 2:r=n(e);break;default:r=o(e)}return Math.min(r,t)}i.d(t,{C4:()=>a,L8:()=>r,OG:()=>n,R:()=>l,zF:()=>s})},9723:(e,t,i)=>{"use strict";i.d(t,{LV:()=>v,S0:()=>m,s7:()=>g});var r=i(43279),s=i(68191),n=i(60590),o=i(35290),a=i(64736),l=i(75108),h=i(67313),c=i(34268),u=i(28909),d=i(72649),f=i(14798),p=i(71627),_=i(44512);class m{static get BaseUrl(){return u.eC.BaseUrl}static set BaseUrl(e){u.eC.BaseUrl=e}static get CleanUrl(){return u.eC.CleanUrl}static set CleanUrl(e){u.eC.CleanUrl=e}static IsAbsoluteUrl(e){return 0===e.indexOf("//")||-1!==e.indexOf("://")&&-1!==e.indexOf(".")&&-1!==e.indexOf("/")&&!(e.indexOf(":")>e.indexOf("/"))&&(e.indexOf("://"){(0,u.zU)(e,(e=>{i(e)}),void 0,void 0,t,((e,t)=>{r(t)}))}))}static GetBabylonScriptURL(e,t){if(!e)return"";if(m.ScriptBaseUrl&&e.startsWith(m._DefaultCdnUrl)){const t="/"===m.ScriptBaseUrl[m.ScriptBaseUrl.length-1]?m.ScriptBaseUrl.substring(0,m.ScriptBaseUrl.length-1):m.ScriptBaseUrl;e=e.replace(m._DefaultCdnUrl,t)}return e=m.ScriptPreprocessUrl(e),t&&(e=m.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,r){e=m.GetBabylonScriptURL(e),m.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=m.GetBabylonScriptURL(e),m.LoadScriptAsync(e)}static LoadScript(e,t,i,r,n=!1){if("function"==typeof importScripts){try{importScripts(e),t&&t()}catch(t){i?.(`Unable to load script '${e}' in worker`,t)}return}if(!(0,s.BA)())return void i?.(`Cannot load script '${e}' outside of a window or a worker`);const o=document.getElementsByTagName("head")[0],a=document.createElement("script");n?(a.setAttribute("type","module"),a.innerText=e):(a.setAttribute("type","text/javascript"),a.setAttribute("src",e)),r&&(a.id=r),a.onload=()=>{t&&t()},a.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},o.appendChild(a)}static LoadScriptAsync(e,t){return new Promise(((i,r)=>{this.LoadScript(e,(()=>{i()}),((e,t)=>{r(t||new Error(e))}),t)}))}static ReadFileAsDataURL(e,t,i){const s=new FileReader,n={onCompleteObservable:new r.cP,abort:()=>s.abort()};return s.onloadend=()=>{n.onCompleteObservable.notifyObservers(n)},s.onload=e=>{t(e.target.result)},s.onprogress=i,s.readAsDataURL(e),n}static ReadFile(e,t,i,r,s){return(0,u.NJ)(e,t,i,r,s)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,r){o.r.DeepCopy(e,t,i,r)}static IsEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i{const r=atob(this.toDataURL(t,i).split(",")[1]),s=r.length,n=new Uint8Array(s);for(let e=0;et(e))):e.toBlob((function(e){t(e)}),i,r)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){const e=new Date;t="screenshot_"+(e.getFullYear()+"-"+(e.getMonth()+1)).slice(2)+"-"+e.getDate()+"_"+e.getHours()+"-"+("0"+e.getMinutes()).slice(-2)+".png"}m.Download(e,t)}else if(e&&"undefined"!=typeof URL){const t=URL.createObjectURL(e),i=window.open("");if(!i)return;const r=i.document.createElement("img");r.onload=function(){URL.revokeObjectURL(t)},r.src=t,i.document.body.appendChild(r)}}static EncodeScreenshotCanvasData(e,t,i="image/png",r,s){if("string"!=typeof r&&t){if(t){if(m._IsOffScreenCanvas(e))return void e.convertToBlob({type:i,quality:s}).then((e=>{const i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{const e=i.result;t(e)}}));const r=e.toDataURL(i,s);t(r)}}else this.ToBlob(e,(function(e){e&&m.DownloadBlob(e,r),t&&t("")}),i,s)}static Download(e,t){if("undefined"==typeof URL)return;const i=window.URL.createObjectURL(e),r=document.createElement("a");document.body.appendChild(r),r.style.display="none",r.href=i,r.download=t,r.addEventListener("click",(()=>{r.parentElement&&r.parentElement.removeChild(r)})),r.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,i,r,s="image/png",n=!1,o){throw(0,l.n)("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,r="image/png",s){throw(0,l.n)("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,r,s="image/png",n=1,o=!1,a,h=!1,c=!1,u=!0,d,f){throw(0,l.n)("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,r="image/png",s=1,n=!1,o,a=!1,h=!1,c=!0,u,d){throw(0,l.n)("ScreenshotTools")}static RandomId(){return(0,p.z)()}static IsBase64(e){return(0,u.f2)(e)}static DecodeBase64(e){return(0,u.rz)(e)}static get errorsCount(){return n.V.errorsCount}static Log(e){n.V.Log(e)}static Warn(e){n.V.Warn(e)}static Error(e){n.V.Error(e)}static get LogCache(){return n.V.LogCache}static ClearLogCache(){n.V.ClearLogCache()}static set LogLevels(e){n.V.LogLevels=e}static set PerformanceLogLevel(e){return(e&m.PerformanceUserMarkLogLevel)===m.PerformanceUserMarkLogLevel?(m.StartPerformanceCounter=m._StartUserMark,void(m.EndPerformanceCounter=m._EndUserMark)):(e&m.PerformanceConsoleLogLevel)===m.PerformanceConsoleLogLevel?(m.StartPerformanceCounter=m._StartPerformanceConsole,void(m.EndPerformanceCounter=m._EndPerformanceConsole)):(m.StartPerformanceCounter=m._StartPerformanceCounterDisabled,void(m.EndPerformanceCounter=m._EndPerformanceCounterDisabled))}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!m._Performance){if(!(0,s.BA)())return;m._Performance=window.performance}t&&m._Performance.mark&&m._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&m._Performance.mark&&(m._Performance.mark(e+"-End"),m._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(m._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(m._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return a.j.Now}static GetClassName(e,t=!1){let i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),i}static First(e,t){for(const i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,r=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const s=t?e:Object.getPrototypeOf(e);i=s.constructor.__bjsclassName__,r=s.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=r?r+".":"")+i:null}static DelayAsync(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}static IsSafari(){return!!(0,s.XD)()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}function g(e,t){return i=>{i.__bjsclassName__=e,i.__bjsmoduleName__=null!=t?t:null}}m.UseCustomRequestHeaders=!1,m.CustomRequestHeaders=h.u.CustomRequestHeaders,m.GetDOMTextContent=s.Zl,m._DefaultCdnUrl="https://cdn.babylonjs.com",m.GetAbsoluteUrl="object"==typeof document?e=>{const t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?e=>new URL(e,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},m.NoneLogLevel=n.V.NoneLogLevel,m.MessageLogLevel=n.V.MessageLogLevel,m.WarningLogLevel=n.V.WarningLogLevel,m.ErrorLogLevel=n.V.ErrorLogLevel,m.AllLogLevel=n.V.AllLogLevel,m.IsWindowObjectExist=s.BA,m.PerformanceNoneLogLevel=0,m.PerformanceUserMarkLogLevel=1,m.PerformanceConsoleLogLevel=2,m.StartPerformanceCounter=m._StartPerformanceCounterDisabled,m.EndPerformanceCounter=m._EndPerformanceCounterDisabled;class v{constructor(e,t,i,r=0){this.iterations=e,this.index=r-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{s&&s()?r.breakLoop():setTimeout((()=>{for(let n=0;n=e)break;if(i(o),s&&s()){r.breakLoop();break}}r.executeNext()}),n)}),r)}}m.Mix=_.zF,m.IsExponentOfTwo=_.L8,c.q.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"},56225:(e,t,i)=>{"use strict";i.d(t,{Uu:()=>o,Y5:()=>s,n9:()=>n});const r={};function s(e,t){r[e]=t}function n(e){return r[e]}function o(e){for(const t in r)if(e instanceof r[t]&&!t.includes("Abstract"))return t;return"Unknown"}},83839:(e,t,i)=>{"use strict";i.d(t,{K:()=>r});class r{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}r._UniqueIdCounter=1},67313:(e,t,i)=>{"use strict";i.d(t,{u:()=>r});class r{constructor(){this._xhr="undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest,this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(r.CustomRequestHeaders).length>0||r.CustomRequestModifiers.length>0}get requestURL(){return this._requestURL}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in r.CustomRequestHeaders){const t=r.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return r.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){r.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const e of r.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;e(this._xhr,t)}t=(t=t.replace("file:http:","http:")).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)}}r.CustomRequestHeaders={},r.CustomRequestModifiers=new Array,r.SkipRequestModificationForBabylonCDN=!0},28382:(e,t,i)=>{"use strict";i.d(t,{T:()=>r,h:()=>s});class r{constructor(e){this._pendingActions=new Array,this._workerInfos=e.map((e=>({workerPromise:Promise.resolve(e),idle:!0})))}dispose(){for(const e of this._workerInfos)e.workerPromise.then((e=>{e.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 t=this._pendingActions.shift();t?this._execute(e,t):e.idle=!0}))}))}}class s extends r{constructor(e,t,i=s.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length{t(i,(()=>{r(),e.idle&&(e.timeoutId=setTimeout((()=>{e.workerPromise.then((e=>{e.terminate()}));const t=this._workerInfos.indexOf(e);-1!==t&&this._workerInfos.splice(t,1)}),this._options.idleTimeElapsedBeforeRelease))}))}))}}s.DefaultOptions={idleTimeElapsedBeforeRelease:1e3}},78239:(e,t,i)=>{"use strict";i.d(t,{s:()=>l,v:()=>a});var r=i(52660),s=i(55935),n=i(56225),o=i(89518);class a extends r.w{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,r,s,n,o=0,a=!1){super(e,"pass",null,null,t,i,r,s,n,void 0,o,void 0,null,a)}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,418))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,30927))])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return o.p.Parse((()=>new a(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,r)}}(0,n.Y5)("BABYLON.PassPostProcess",a);class l extends r.w{get face(){return this._face}set face(e){if(!(e<0||e>5))switch(this._face=e,this._face){case 0:this.updateEffect("#define POSITIVEX");break;case 1:this.updateEffect("#define NEGATIVEX");break;case 2:this.updateEffect("#define POSITIVEY");break;case 3:this.updateEffect("#define NEGATIVEY");break;case 4:this.updateEffect("#define POSITIVEZ");break;case 5:this.updateEffect("#define NEGATIVEZ")}}getClassName(){return"PassCubePostProcess"}constructor(e,t,i=null,r,s,n,o=0,a=!1){super(e,"passCube",null,null,t,i,r,s,n,"#define POSITIVEX",o,void 0,null,a),this._face=0}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,12253))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,88412))])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return o.p.Parse((()=>new l(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,r)}}s.$._RescalePostProcessFactory=e=>new a("rescale",1,null,2,e,!1,0)},52660:(e,t,i)=>{"use strict";i.d(t,{w:()=>p});var r=i(15287),s=i(39464),n=i(43279),o=i(94212),a=i(36217),l=i(40220),h=i(89518),c=i(56225),u=i(55935),d=i(44512),f=i(50606);u.$.prototype.setTextureFromPostProcess=function(e,t,i){let r=null;t&&(t._forcedOutputTexture?r=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(r=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,r?.texture??null,i)},u.$.prototype.setTextureFromPostProcessOutput=function(e,t,i){this._bindTexture(e,t?._outputTexture?.texture??null,i)},a.M.prototype.setTextureFromPostProcess=function(e,t){this._engine.setTextureFromPostProcess(this._samplers[e],t,e)},a.M.prototype.setTextureFromPostProcessOutput=function(e,t){this._engine.setTextureFromPostProcessOutput(this._samplers[e],t,e)};class p{static get ForceGLSL(){return f.$.ForceGLSL}static set ForceGLSL(e){f.$.ForceGLSL=e}static RegisterShaderCodeProcessing(e,t){f.$.RegisterShaderCodeProcessing(e,t)}get name(){return this._effectWrapper.name}set name(e){this._effectWrapper.name=e}get alphaMode(){return this._effectWrapper.alphaMode}set alphaMode(e){this._effectWrapper.alphaMode=e}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach((e=>{e.setSamples(this._samples)}))}get shaderLanguage(){return this._shaderLanguage}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,r,a,l,h=1,c,u,d=null,_=0,m="postprocess",g,v=!1,x=5,b,S){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._webGPUReady=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new s.L(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new o.I9(1,1),this._texelSize=o.I9.Zero(),this.onActivateObservable=new n.cP,this.onSizeChangedObservable=new n.cP,this.onApplyObservable=new n.cP,this.onBeforeRenderObservable=new n.cP,this.onAfterRenderObservable=new n.cP;let T,C=1,y=null;if(i&&!Array.isArray(i)){const e=i;i=e.uniforms??null,r=e.samplers??null,C=e.size??1,l=e.camera??null,h=e.samplingMode??1,c=e.engine,u=e.reusable,d=Array.isArray(e.defines)?e.defines.join("\n"):e.defines??null,_=e.textureType??0,m=e.vertexUrl??"postprocess",g=e.indexParameters,v=e.blockCompilation??!1,x=e.textureFormat??5,b=e.shaderLanguage??0,y=e.uniformBuffers??null,S=e.extraInitializations,T=e.effectWrapper}else a&&(C="number"==typeof a?a:{width:a.width,height:a.height});const E=!!T;if(this._effectWrapper=T??new f.$({name:e,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:t,engine:c||l?.getScene().getEngine(),uniforms:i,samplers:r,uniformBuffers:y,defines:d,vertexUrl:m,indexParameters:g,blockCompilation:!0,shaderLanguage:b,extraInitializations:void 0}),this.name=e,this.onEffectCreatedObservable=this._effectWrapper.onEffectCreatedObservable,null!=l?(this._camera=l,this._scene=l.getScene(),l.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):c&&(this._engine=c,this._engine.postProcesses.push(this)),this._options=C,this.renderTargetSamplingMode=h||1,this._reusable=u||!1,this._textureType=_,this._textureFormat=x,this._shaderLanguage=b||0,this._samplers=r||[],-1===this._samplers.indexOf("textureSampler")&&this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=m,this._parameters=i||[],-1===this._parameters.indexOf("scale")&&this._parameters.push("scale"),this._uniformBuffers=y||[],this._indexParameters=g,!E){this._webGPUReady=1===this._shaderLanguage;const e=[];this._gatherImports(this._engine.isWebGPU&&!p.ForceGLSL,e),this._effectWrapper._webGPUReady=this._webGPUReady,this._effectWrapper._postConstructor(v,d,S,e)}}_gatherImports(e=!1,t){e&&this._webGPUReady?t.push(Promise.all([Promise.resolve().then(i.bind(i,45010))])):t.push(Promise.all([Promise.resolve().then(i.bind(i,18013))]))}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._effectWrapper.drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){0==this._textures.length&&(this._textures=new s.L(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,r,s,n,o,a){this._effectWrapper.updateEffect(e,t,i,r,s,n,o,a),this._postProcessDefines=Array.isArray(this._effectWrapper.options.defines)?this._effectWrapper.options.defines.join("\n"):this._effectWrapper.options.defines}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 e=!1;for(let i=0;i0&&this._textures.reset(),this.width=e,this.height=t;let n=null;if(i)for(let e=0;e{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)})),this._flushTextureCache(),this._renderId++}return u||(u=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(o/l,a/h),this._engine.bindFramebuffer(u,0,o,a,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(u,0,void 0,void 0,this.forceFullscreenViewport)),this._engine._debugInsertMarker?.(`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(0===this.alphaMode||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:r.clearColor,r._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),u}get isSupported(){return this._effectWrapper.drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){return this._effectWrapper.isReady()}apply(){if(!this._effectWrapper.isReady())return null;let e;return this._engine.enableEffect(this._effectWrapper.drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),e=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._effectWrapper.drawWrapper.effect._bindTexture("textureSampler",e?.texture),this._effectWrapper.drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._effectWrapper.drawWrapper.effect),this._effectWrapper.bind(),this._effectWrapper.drawWrapper.effect}_disposeTextures(){this._shareOutputWithPostProcess||this._forcedOutputTexture?this._disposeTextureCache():(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)}dispose(e){let t;if(e=e||this._camera,this._disposeTextures(),this._scene&&(t=this._scene.postProcesses.indexOf(this),-1!==t&&this._scene.postProcesses.splice(t,1)),this._parentContainer){const e=this._parentContainer.postProcesses.indexOf(this);e>-1&&this._parentContainer.postProcesses.splice(e,1),this._parentContainer=null}if(t=this._engine.postProcesses.indexOf(this),-1!==t&&this._engine.postProcesses.splice(t,1),e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),0===t&&e._postProcesses.length>0){const e=this._camera._getFirstPostProcess();e&&e.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear(),this.onEffectCreatedObservable.clear()}}serialize(){const e=h.p.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.uniformBuffers=this._uniformBuffers,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=p.Parse(e,this._scene,"");return t?(t.onActivateObservable=this.onActivateObservable.clone(),t.onSizeChangedObservable=this.onSizeChangedObservable.clone(),t.onApplyObservable=this.onApplyObservable.clone(),t.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),t.onAfterRenderObservable=this.onAfterRenderObservable.clone(),t._prePassEffectConfiguration=this._prePassEffectConfiguration,t):null}static Parse(e,t,i){const r=(0,c.n9)(e.customType);if(!r||!r._Parse)return null;const s=t?t.getCameraById(e.cameraId):null;return r._Parse(e,s,t,i)}static _Parse(e,t,i,r){return h.p.Parse((()=>new p(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat)),e,i,r)}}(0,r.Cg)([(0,l.lK)()],p.prototype,"uniqueId",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"name",null),(0,r.Cg)([(0,l.lK)()],p.prototype,"width",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"height",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"renderTargetSamplingMode",void 0),(0,r.Cg)([(0,l.qK)()],p.prototype,"clearColor",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"autoClear",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"forceAutoClearInAlphaMode",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"alphaMode",null),(0,r.Cg)([(0,l.lK)()],p.prototype,"alphaConstants",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"enablePixelPerfectMode",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"forceFullscreenViewport",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"scaleMode",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"alwaysForcePOT",void 0),(0,r.Cg)([(0,l.lK)("samples")],p.prototype,"_samples",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"adaptScaleToCurrentViewport",void 0),(0,c.Y5)("BABYLON.PostProcess",p)},2449:(e,t,i)=>{"use strict";i.d(t,{X:()=>n});var r=i(12721),s=i(43279);class n{constructor(e){this._vertexBuffers={},this.onBeforeRenderObservable=new s.cP,this._scene=e}_prepareBuffers(){if(this._vertexBuffers[r.R.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[r.R.PositionKind]=new r.R(this._scene.getEngine(),e,r.R.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[r.R.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!(!i||!(t=t||i._postProcesses.filter((e=>null!=e)))||0===t.length||!this._scene.postProcessesEnabled||(t[0].activate(i,e,null!=t),0))}directRender(e,t=null,i=!1,r=0,s=0,n=!1){const o=this._scene.getEngine();for(let a=0;anull!=e))).length||!this._scene.postProcessesEnabled)return;const o=this._scene.getEngine();for(let a=0,l=r.length;a{"use strict";i.d(t,{P:()=>o});var r=i(43279),s=i(75653),n=i(34130);class o{get renderList(){return this._renderList}set renderList(e){this._renderList!==e&&(this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=(0,n.lL)(e,this._renderListHasChanged)),this._renderList=e)}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}setMaterialForRendering(e,t){let i;i=Array.isArray(e)?e:[e];for(let e=0;e{const i=this._renderList?this._renderList.length:0;(0===t&&i>0||0===i)&&this._scene.meshes.forEach((e=>{e._markSubMeshesAsLightDirty()}))},this.particleSystemList=null,this.getCustomRenderList=null,this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.onBeforeRenderObservable=new r.cP,this.onAfterRenderObservable=new r.cP,this.onBeforeRenderingManagerRenderObservable=new r.cP,this.onAfterRenderingManagerRenderObservable=new r.cP,this.onFastPathRenderObservable=new r.cP,this._currentRefreshId=-1,this._refreshRate=1,this._currentSceneCamera=null,this.name=e,this._scene=t,this.renderList=[],this._renderPassIds=[],this.options={numPasses:1,doNotChangeAspectRatio:!0,...i},this._createRenderPassId(),this.renderPassId=this._renderPassIds[0],this._renderingManager=new s.m(t),this._renderingManager._useSceneAutoClearSetup=!0}_releaseRenderPassId(){const e=this._scene.getEngine();for(let t=0;t1&&(e.incrementRenderId(),e.resetCachedMaterial())}const n=this.particleSystemList||e.particleSystems;for(const e of n)e.isReady()||(r=!1);return t.currentRenderPassId=i,r}_prepareRenderingManager(e,t,i){const r=this._scene,s=r.activeCamera;this._renderingManager.reset();const n=r.getRenderId();for(let o=0;o{"use strict";i.d(t,{U:()=>n});var r=i(39464),s=i(94212);class n{set opaqueSortCompareFn(e){this._opaqueSortCompareFn=e||n.PainterSortCompare,this._renderOpaque=this._renderOpaqueSorted}set alphaTestSortCompareFn(e){this._alphaTestSortCompareFn=e||n.PainterSortCompare,this._renderAlphaTest=this._renderAlphaTestSorted}set transparentSortCompareFn(e){this._transparentSortCompareFn=e||n.defaultTransparentSortCompare,this._renderTransparent=this._renderTransparentSorted}constructor(e,t,i=null,s=null,n=null){this.index=e,this._opaqueSubMeshes=new r.L(256),this._transparentSubMeshes=new r.L(256),this._alphaTestSubMeshes=new r.L(256),this._depthOnlySubMeshes=new r.L(256),this._particleSystems=new r.L(256),this._spriteManagers=new r.L(256),this._empty=!0,this._edgesRenderers=new r.b(16),this._scene=t,this.opaqueSortCompareFn=i,this.alphaTestSortCompareFn=s,this.transparentSortCompareFn=n}render(e,t,i,r){if(e)return void e(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,this._depthOnlySubMeshes);const s=this._scene.getEngine();0!==this._depthOnlySubMeshes.length&&(s.setColorWrite(!1),this._renderAlphaTest(this._depthOnlySubMeshes),s.setColorWrite(!0)),0!==this._opaqueSubMeshes.length&&this._renderOpaque(this._opaqueSubMeshes),0!==this._alphaTestSubMeshes.length&&this._renderAlphaTest(this._alphaTestSubMeshes);const n=s.getStencilBuffer();if(s.setStencilBuffer(!1),t&&this._renderSprites(),i&&this._renderParticles(r),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),0!==this._transparentSubMeshes.length||this._scene.useOrderIndependentTransparency){if(s.setStencilBuffer(n),this._scene.useOrderIndependentTransparency){const e=this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);e.length&&this._renderTransparent(e)}else this._renderTransparent(this._transparentSubMeshes);s.setAlphaMode(0)}if(s.setStencilBuffer(!1),this._edgesRenderers.length){for(let e=0;et._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){const i=e.getMesh(),r=t.getMesh();return i.material&&r.material?i.material.uniqueId-r.material.uniqueId:i.uniqueId-r.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(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(0===this._particleSystems.length)return;const t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i{"use strict";i.d(t,{m:()=>n,o:()=>s});var r=i(20005);class s{}class n{get maintainStateBetweenFrames(){return this._maintainStateBetweenFrames}set maintainStateBetweenFrames(e){e!==this._maintainStateBetweenFrames&&(this._maintainStateBetweenFrames=e,this._maintainStateBetweenFrames||this.restoreDispachedFlags())}restoreDispachedFlags(){for(const e of this._scene.meshes)if(e.subMeshes)for(const t of e.subMeshes)t._wasDispatched=!1;if(this._scene.spriteManagers)for(const e of this._scene.spriteManagers)e._wasDispatched=!1;for(const e of this._scene.particleSystems)e._wasDispatched=!1}constructor(e){this._useSceneAutoClearSetup=!1,this._renderingGroups=new Array,this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderingGroupInfo=new s,this._maintainStateBetweenFrames=!1,this._scene=e;for(let e=n.MIN_RENDERINGGROUPS;e{"use strict";var r=i(69841);i(32405);r.l.IncludesShadersStore.backgroundUboDeclaration="layout(std140,column_major) uniform;uniform Material\n{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;};\n#include\n"},95532:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.bakedVertexAnimation="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\n#ifdef INSTANCES\n#define BVASNAME bakedVertexAnimationSettingsInstanced\n#else\n#define BVASNAME bakedVertexAnimationSettings\n#endif\nfloat 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];\n#if NUM_BONE_INFLUENCERS>1\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3];\n#endif\nfinalWorld=finalWorld*VATInfluence;}\n#endif\n"},66682:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.bakedVertexAnimationDeclaration="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform float bakedVertexAnimationTime;uniform vec2 bakedVertexAnimationTextureSizeInverted;uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture;\n#ifdef INSTANCES\nattribute vec4 bakedVertexAnimationSettingsInstanced;\n#endif\n#define inline\nmat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame)\n{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);}\n#endif\n"},39948:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bonesDeclaration:()=>n});const r="bonesDeclaration",s="#if NUM_BONE_INFLUENCERS>0\nattribute vec4 matricesIndices;attribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra;\n#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nuniform highp sampler2D boneSampler;uniform float boneTextureWidth;\n#else\nuniform mat4 mBones[BonesPerMesh];\n#endif\n#ifdef BONES_VELOCITY_ENABLED\nuniform mat4 mPreviousBones[BonesPerMesh];\n#endif\n#ifdef BONETEXTURE\n#define inline\nmat4 readMatrixFromRawSampler(sampler2D smp,float index)\n{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);}\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},78792:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bonesVertex:()=>n});const r="bonesVertex",s="#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3];\n#endif\n#else\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\n#endif\nfinalWorld=finalWorld*influence;\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},97315:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.boundingBoxRendererUboDeclaration="#ifdef WEBGL2\nuniform vec4 color;uniform mat4 world;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#else\nlayout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;};\n#endif\n"},90249:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bumpFragment:()=>n});const r="bumpFragment",s="vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#elif defined(BUMP)\nfloat normalScale=vBumpInfos.y;\n#else\nfloat normalScale=1.0;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#elif defined(BUMP)\nvec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams);\n#else\nvec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.));\n#endif\n#elif defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nvec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.));\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef DETAIL\nvec4 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);\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\n#define CUSTOM_FRAGMENT_BUMP_FRAGMENT\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3(normalMatrix)*normalW);\n#elif !defined(DETAIL)\nnormalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y);\n#else\nvec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0;\n#if DETAIL_NORMALBLENDMETHOD==0 \ndetailNormal.xy*=vDetailInfos.z;vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z));\n#elif DETAIL_NORMALBLENDMETHOD==1 \ndetailNormal.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;\n#endif\nnormalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y);\n#endif\n#elif defined(DETAIL)\ndetailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z);\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},29424:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bumpFragmentFunctions:()=>o});var r=i(69841);i(5301);const s="bumpFragmentFunctions",n="#if defined(BUMP)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)\n#endif\n#if defined(DETAIL)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail)\n#endif\n#if defined(BUMP) && defined(PARALLAX)\nconst 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)\n{float delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;}\nelse\n{currRayHeight-=stepSize;vLastOffset=vCurrOffset;\n#ifdef PARALLAX_RHS\nvCurrOffset-=stepSize*vMaxOffset;\n#else\nvCurrOffset+=stepSize*vMaxOffset;\n#endif\nlastSampledHeight=currSampledHeight;}}\nreturn vCurrOffset;}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{float height=texture2D(bumpSampler,vBumpUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height;\n#ifdef PARALLAX_RHS\nreturn texCoordOffset;\n#else\nreturn -texCoordOffset;\n#endif\n}\n#endif\n";r.l.IncludesShadersStore[s]=n;const o={name:s,shader:n}},82267:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bumpFragmentMainFunctions:()=>n});const r="bumpFragmentMainFunctions",s="#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#if defined(WEBGL2) || defined(WEBGPU)\nmat4 toNormalMatrix(mat4 wMatrix)\n{mat4 ret=inverse(wMatrix);ret=transpose(ret);ret[0][3]=0.;ret[1][3]=0.;ret[2][3]=0.;ret[3]=vec4(0.,0.,0.,1.);return ret;}\n#else\nmat4 toNormalMatrix(mat4 m)\n{float\na00=m[0][0],a01=m[0][1],a02=m[0][2],a03=m[0][3],\na10=m[1][0],a11=m[1][1],a12=m[1][2],a13=m[1][3],\na20=m[2][0],a21=m[2][1],a22=m[2][2],a23=m[2][3],\na30=m[3][0],a31=m[3][1],a32=m[3][2],a33=m[3][3],\nb00=a00*a11-a01*a10,\nb01=a00*a12-a02*a10,\nb02=a00*a13-a03*a10,\nb03=a01*a12-a02*a11,\nb04=a01*a13-a03*a11,\nb05=a02*a13-a03*a12,\nb06=a20*a31-a21*a30,\nb07=a20*a32-a22*a30,\nb08=a20*a33-a23*a30,\nb09=a21*a32-a22*a31,\nb10=a21*a33-a23*a31,\nb11=a22*a33-a23*a32,\ndet=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;mat4 mi=mat4(\na11*b11-a12*b10+a13*b09,\na02*b10-a01*b11-a03*b09,\na31*b05-a32*b04+a33*b03,\na22*b04-a21*b05-a23*b03,\na12*b08-a10*b11-a13*b07,\na00*b11-a02*b08+a03*b07,\na32*b02-a30*b05-a33*b01,\na20*b05-a22*b02+a23*b01,\na10*b10-a11*b08+a13*b06,\na01*b08-a00*b10-a03*b06,\na30*b04-a31*b02+a33*b00,\na21*b02-a20*b04-a23*b00,\na11*b07-a10*b09-a12*b06,\na00*b09-a01*b07+a02*b06,\na31*b01-a30*b03-a32*b00,\na20*b03-a21*b01+a22*b00)/det;return mat4(mi[0][0],mi[1][0],mi[2][0],mi[3][0],\nmi[0][1],mi[1][1],mi[2][1],mi[3][1],\nmi[0][2],mi[1][2],mi[2][2],mi[3][2],\nmi[0][3],mi[1][3],mi[2][3],mi[3][3]);}\n#endif\n#endif\nvec3 perturbNormalBase(mat3 cotangentFrame,vec3 normal,float scale)\n{\n#ifdef NORMALXYSCALE\nnormal=normalize(normal*vec3(scale,scale,1.0));\n#endif\nreturn normalize(cotangentFrame*normal);}\nvec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale)\n{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);}\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams)\n{vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;float det=max(dot(tangent,tangent),dot(bitangent,bitangent));float invmax=det==0.0 ? 0.0 : inversesqrt(det);return mat3(tangent*invmax,bitangent*invmax,normal);}\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},78595:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.bumpVertex="#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif\n"},17727:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.bumpVertexDeclaration="#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n"},89797:(e,t,i)=>{"use strict";i.r(t),i.d(t,{clipPlaneFragment:()=>n});const r="clipPlaneFragment",s="#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nif (false) {}\n#endif\n#ifdef CLIPPLANE\nelse if (fClipDistance>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE2\nelse if (fClipDistance2>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE3\nelse if (fClipDistance3>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE4\nelse if (fClipDistance4>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE5\nelse if (fClipDistance5>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE6\nelse if (fClipDistance6>0.0)\n{discard;}\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},77165:(e,t,i)=>{"use strict";i.r(t),i.d(t,{clipPlaneFragmentDeclaration:()=>n});const r="clipPlaneFragmentDeclaration",s="#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nvarying float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nvarying float fClipDistance6;\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},71471:(e,t,i)=>{"use strict";i.r(t),i.d(t,{clipPlaneVertex:()=>n});const r="clipPlaneVertex",s="#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\n#endif\n#ifdef CLIPPLANE5\nfClipDistance5=dot(worldPos,vClipPlane5);\n#endif\n#ifdef CLIPPLANE6\nfClipDistance6=dot(worldPos,vClipPlane6);\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},18355:(e,t,i)=>{"use strict";i.r(t),i.d(t,{clipPlaneVertexDeclaration:()=>n});const r="clipPlaneVertexDeclaration",s="#ifdef CLIPPLANE\nuniform vec4 vClipPlane;varying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;varying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;varying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;varying float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nuniform vec4 vClipPlane5;varying float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nuniform vec4 vClipPlane6;varying float fClipDistance6;\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},22464:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.decalFragment="#ifdef DECAL\n#ifdef GAMMADECAL\ndecalColor.rgb=toLinearSpace(decalColor.rgb);\n#endif\n#ifdef DECAL_SMOOTHALPHA\ndecalColor.a*=decalColor.a;\n#endif\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a);\n#endif\n"},14774:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.decalFragmentDeclaration="#ifdef DECAL\nuniform vec4 vDecalInfos;\n#endif\n"},81160:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.decalVertexDeclaration="#ifdef DECAL\nuniform vec4 vDecalInfos;uniform mat4 decalMatrix;\n#endif\n"},16792:(e,t,i)=>{"use strict";var r=i(69841);i(32405),i(13580);r.l.IncludesShadersStore.defaultUboDeclaration="layout(std140,column_major) uniform;uniform Material\n{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;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n"},51314:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.depthPrePass="#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);return;\n#endif\n"},27185:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.fogFragment="#ifdef FOG\nfloat fog=CalcFogFactor();\n#ifdef PBR\nfog=toLinearSpace(fog);\n#endif\ncolor.rgb=mix(vFogColor,color.rgb,fog);\n#endif\n"},64657:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fogFragmentDeclaration:()=>n});const r="fogFragmentDeclaration",s="#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;uniform vec3 vFogColor;varying vec3 vFogDistance;float CalcFogFactor()\n{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)\n{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);}\nelse if (FOGMODE_EXP==vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDensity);}\nelse if (FOGMODE_EXP2==vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);}\nreturn clamp(fogCoeff,0.0,1.0);}\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},90715:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.fogVertex="#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif\n"},77735:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.fogVertexDeclaration="#ifdef FOG\nvarying vec3 vFogDistance;\n#endif\n"},49046:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.fresnelFunction="#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{float fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);}\n#endif\n"},93784:(e,t,i)=>{"use strict";i.d(t,{Q:()=>n});const r="gaussianSplattingVertexDeclaration",s="attribute vec2 position;uniform mat4 view;uniform mat4 projection;uniform mat4 world;";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},10316:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.harmonicsFunctions="#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nvec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00\n+ vSphericalL1_1*(normal.y)\n+ vSphericalL10*(normal.z)\n+ vSphericalL11*(normal.x)\n+ vSphericalL2_2*(normal.y*normal.x)\n+ vSphericalL2_1*(normal.y*normal.z)\n+ vSphericalL20*((3.0*normal.z*normal.z)-1.0)\n+ vSphericalL21*(normal.z*normal.x)\n+ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));}\n#else\nvec3 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;}\n#endif\n#endif\n"},98392:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.hdrFilteringFunctions="#ifdef NUM_SAMPLES\n#if NUM_SAMPLES>0\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfloat radicalInverse_VdC(uint bits) \n{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; }\nvec2 hammersley(uint i,uint N)\n{return vec2(float(i)/float(N),radicalInverse_VdC(i));}\n#else\nfloat vanDerCorpus(int n,int base)\n{float invBase=1.0/float(base);float denom =1.0;float result =0.0;for(int i=0; i<32; ++i)\n{if(n>0)\n{denom =mod(float(n),2.0);result+=denom*invBase;invBase=invBase/2.0;n =int(float(n)/2.0);}}\nreturn result;}\nvec2 hammersley(int i,int N)\n{return vec2(float(i)/float(N),vanDerCorpus(i,2));}\n#endif\nfloat log4(float x) {return log2(x)/2.;}\nconst float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);const float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;const float K=4.;\n#define inline\nvec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)\n{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);\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfor(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;\n#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\n#endif\nresult+=c;}}\nresult=result*NUM_SAMPLES_FLOAT_INVERSED;return result;}\n#define inline\nvec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)\n{vec3 n=normalize(inputN);vec3 c=textureCube(inputTexture,n).rgb; \nif (alphaG==0.) {\n#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\n#endif\nreturn 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.;\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfor(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;\n#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\n#endif\nresult+=c*NoL;}}\nresult=result/weight;return result;}}\n#endif\n#endif\n"},94388:(e,t,i)=>{"use strict";i.r(t),i.d(t,{helperFunctions:()=>n});const r="helperFunctions",s="const float PI=3.1415926535897932384626433832795;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float HALF_MIN=5.96046448e-08; \nconst 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;\n#define saturate(x) clamp(x,0.0,1.0)\n#define absEps(x) abs(x)+Epsilon\n#define maxEps(x) max(x,Epsilon)\n#define saturateEps(x) clamp(x,Epsilon,1.0)\nmat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);return outMatrix;}\nmat3 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),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;}\n#if USE_EXACT_SRGB_CONVERSIONS\nvec3 toLinearSpaceExact(vec3 color)\n{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));\n#else\nreturn\nvec3(\ncolor.r<=0.04045 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.04045 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.04045 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\nvec3 toGammaSpaceExact(vec3 color)\n{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055);\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));\n#else\nreturn\nvec3(\ncolor.r<=0.0031308 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.0031308 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.0031308 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\n#endif\nfloat toLinearSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,LinearEncodePowerApprox);\n#endif\n}\nvec3 toLinearSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3(LinearEncodePowerApprox));\n#endif\n}\nvec4 toLinearSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toLinearSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);\n#endif\n}\nfloat toGammaSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,GammaEncodePowerApprox);\n#endif\n}\nvec3 toGammaSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3(GammaEncodePowerApprox));\n#endif\n}\nvec4 toGammaSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toGammaSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);\n#endif\n}\nfloat square(float value)\n{return value*value;}\nvec3 square(vec3 value)\n{return value*value;}\nfloat pow5(float value) {float sq=value*value;return sq*sq*value;}\nfloat getLuminance(vec3 color)\n{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}\nfloat getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}\nfloat dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;}\nconst 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); }\nvec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;}\nvec3 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;}\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},65343:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.imageProcessingCompatibility="#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2));\n#endif\n"},75651:(e,t,i)=>{"use strict";i.r(t),i.d(t,{imageProcessingDeclaration:()=>n});const r="imageProcessingDeclaration",s="#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#if defined(VIGNETTE) || defined(DITHER)\nuniform vec2 vInverseScreenSize;\n#endif\n#ifdef VIGNETTE\nuniform vec4 vignetteSettings1;uniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;uniform vec4 vCameraColorCurveNeutral;uniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef DITHER\nuniform float ditherIntensity;\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},88658:(e,t,i)=>{"use strict";i.r(t),i.d(t,{imageProcessingFunctions:()=>n});const r="imageProcessingFunctions",s="#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n/** \n* Polyfill for SAMPLE_TEXTURE_3D,which is unsupported in WebGL.\n* sampler3dSetting.x=textureOffset (0.5/textureSize).\n* sampler3dSetting.y=textureSize.\n*/\n#define inline\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{float sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);float sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;sliceUV.x+=sliceInteger*sliceSize;sliceUV=saturate(sliceUV);vec4 slice0Color=texture2D(colorTransform,sliceUV);sliceUV.x+=sliceSize;sliceUV=saturate(sliceUV);vec4 slice1Color=texture2D(colorTransform,sliceUV);vec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;}\n#endif\n#if TONEMAPPING==3\nconst float PBRNeutralStartCompression=0.8-0.04;const float PBRNeutralDesaturation=0.15;vec3 PBRNeutralToneMapping( vec3 color ) {float x=min(color.r,min(color.g,color.b));float offset=x<0.08 ? x-6.25*x*x : 0.04;color-=offset;float peak=max(color.r,max(color.g,color.b));if (peak{"use strict";i(69841).l.IncludesShadersStore.importanceSampling="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);}\nvec3 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);}\nvec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { \nfloat 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);}"},56865:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.instancesDeclaration="#ifdef INSTANCES\nattribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;\n#ifdef INSTANCESCOLOR\nattribute vec4 instanceColor;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform mat4 world;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nattribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3;\n#ifdef THIN_INSTANCES\nuniform mat4 previousWorld;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform mat4 world;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nuniform mat4 previousWorld;\n#endif\n#endif\n"},18411:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.instancesVertex="#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nmat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,\npreviousWorld2,previousWorld3);\n#endif\n#ifdef THIN_INSTANCES\nfinalWorld=world*finalWorld;\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nfinalPreviousWorld=previousWorld*finalPreviousWorld;\n#endif\n#endif\n#else\nmat4 finalWorld=world;\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nmat4 finalPreviousWorld=previousWorld;\n#endif\n#endif\n"},953:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};"},81749:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lightFragment:()=>n});const r="lightFragment",s="#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n#else\nvec4 diffuse{X}=light{X}.vLightDiffuse;\n#define CUSTOM_LIGHT{X}_COLOR \n#ifdef PBR\n#ifdef SPOTLIGHT{X}\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,vPositionW);\n#elif defined(POINTLIGHT{X})\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,vPositionW);\n#elif defined(HEMILIGHT{X})\npreInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(DIRLIGHT{X})\npreInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#endif\npreInfo.NdotV=NdotV;\n#ifdef SPOTLIGHT{X}\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.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);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.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);\n#else\npreInfo.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);\n#endif\n#elif defined(POINTLIGHT{X})\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\n#else\npreInfo.attenuation=1.0;\n#endif\n#ifdef HEMILIGHT{X}\npreInfo.roughness=roughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#ifdef IRIDESCENCE\npreInfo.iridescenceIntensity=iridescenceIntensity;\n#endif\n#ifdef HEMILIGHT{X}\ninfo.diffuse=computeHemisphericDiffuseLighting(preInfo,diffuse{X}.rgb,light{X}.vLightGround);\n#elif defined(SS_TRANSLUCENCY)\ninfo.diffuse=computeDiffuseAndTransmittedLighting(preInfo,diffuse{X}.rgb,subSurfaceOut.transmittance);\n#else\ninfo.diffuse=computeDiffuseLighting(preInfo,diffuse{X}.rgb);\n#endif\n#ifdef SPECULARTERM\n#ifdef ANISOTROPIC\ninfo.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb);\n#else\ninfo.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb);\n#endif\n#endif\n#ifdef SHEEN\n#ifdef SHEEN_LINKWITHALBEDO\npreInfo.roughness=sheenOut.sheenIntensity;\n#else\n#ifdef HEMILIGHT{X}\npreInfo.roughness=sheenOut.sheenRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#endif\ninfo.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb);\n#endif\n#ifdef CLEARCOAT\n#ifdef HEMILIGHT{X}\npreInfo.roughness=clearcoatOut.clearCoatRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\ninfo.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,diffuse{X}.rgb);\n#ifdef CLEARCOAT_TINT\nabsorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption;\n#ifdef SPECULARTERM\ninfo.specular*=absorption;\n#endif\n#endif\ninfo.diffuse*=info.clearCoat.w;\n#ifdef SPECULARTERM\ninfo.specular*=info.clearCoat.w;\n#endif\n#ifdef SHEEN\ninfo.sheen*=info.clearCoat.w;\n#endif\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightTexture{X},textureProjectionMatrix{X},vPositionW);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nfor (int i=0; i=0.) {index{X}=i;break;}}\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nif (index{X}>=0)\n#endif\n{\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#else\nshadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#endif\n#else\nshadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}];\n#endif\n#ifndef SHADOWCSMNOBLEND{X}\nfloat frustumLength=frustumLengths{X}[index{X}];float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)\n{index{X}+=1;float nextShadow=0.;\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nnextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#else\nnextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#endif\n#else\nnextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\nshadow=mix(nextShadow,shadow,diffRatio);\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);\n#endif\n}\n#endif\n}\n#elif defined(SHADOWCLOSEESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;shadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\naggShadow+=shadow;numLights+=1.0;\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor.rgb*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef CLEARCOAT\n#ifndef LIGHTMAPNOSPECULAR{X}\nclearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef SHEEN\n#ifndef LIGHTMAPNOSPECULAR{X}\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#else\n#ifdef SHADOWCSMDEBUG{X}\ndiffuseBase+=info.diffuse*shadowDebug{X};\n#else \ndiffuseBase+=info.diffuse*shadow;\n#endif\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#ifdef CLEARCOAT\nclearCoatBase+=info.clearCoat.rgb*shadow;\n#endif\n#ifdef SHEEN\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},23133:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lightFragmentDeclaration:()=>n});const r="lightFragmentDeclaration",s="#ifdef LIGHT{X}\nuniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\n#else\nvec4 vLightSpecular{X}=vec4(0.);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform 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};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};\n#else\nuniform highp sampler2DArray shadowTexture{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);vec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowTexture{X};\n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowTexture{X};\n#else\nuniform sampler2D shadowTexture{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};uniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X};\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},58769:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lightUboDeclaration:()=>n});const r="lightUboDeclaration",s="#ifdef LIGHT{X}\nuniform Light{X}\n{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;vec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;vec2 depthValues;} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X};\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform 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};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};\n#else\nuniform highp sampler2DArray shadowTexture{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);vec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowTexture{X}; \n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowTexture{X};\n#else\nuniform sampler2D shadowTexture{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},96951:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lightVxFragmentDeclaration:()=>n});const r="lightVxFragmentDeclaration",s="#ifdef LIGHT{X}\nuniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\n#else\nvec4 vLightSpecular{X}=vec4(0.);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#elif defined(SHADOWCUBE{X})\n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};uniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},19215:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lightVxUboDeclaration:()=>n});const r="lightVxUboDeclaration",s="#ifdef LIGHT{X}\nuniform Light{X}\n{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;vec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;vec2 depthValues;} light{X};\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#elif defined(SHADOWCUBE{X})\n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},97295:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lightsFragmentFunctions:()=>n});const r="lightsFragmentFunctions",s="struct lightingInfo\n{vec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};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.)\n{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}\nelse\n{lightVectorW=normalize(-lightData.xyz);}\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nlightingInfo 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)\n{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;float ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;}\nlightingInfo 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;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;\n#endif\nreturn result;}\n#define inline\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix,vec3 posW){vec4 strq=textureProjectionMatrix*vec4(posW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},25012:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.logDepthDeclaration="#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;varying float vFragmentDepth;\n#endif\n"},6922:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.logDepthFragment="#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif\n"},88336:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.logDepthVertex="#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif\n"},40371:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.mainUVVaryingDeclaration="#ifdef MAINUV{X}\nvarying vec2 vMainUV{X};\n#endif\n"},13580:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.meshUboDeclaration="#ifdef WEBGL2\nuniform mat4 world;uniform float visibility;\n#else\nlayout(std140,column_major) uniform;uniform Mesh\n{mat4 world;float visibility;};\n#endif\n#define WORLD_UBO\n"},44219:(e,t,i)=>{"use strict";i.r(t),i.d(t,{morphTargetsVertex:()=>n});const r="morphTargetsVertex",s="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\n#if {X}==0\nfor (int i=0; i=morphTargetCount) break;vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;positionUpdated+=(readVector3FromRawSampler(i,vertexID)-position)*morphTargetInfluences[i];vertexID+=1.0;\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(readVector3FromRawSampler(i,vertexID) -normal)*morphTargetInfluences[i];vertexID+=1.0;\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated+=(readVector3FromRawSampler(i,vertexID).xy-uv)*morphTargetInfluences[i];vertexID+=1.0;\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(readVector3FromRawSampler(i,vertexID) -tangent.xyz)*morphTargetInfluences[i];\n#endif\n}\n#endif\n#else\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}];\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},11783:(e,t,i)=>{"use strict";i.r(t),i.d(t,{morphTargetsVertexDeclaration:()=>n});const r="morphTargetsVertexDeclaration",s="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#ifdef MORPHTARGETS_UV\nattribute vec2 uv_{X};\n#endif\n#elif {X}==0\nuniform int morphTargetCount;\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},99216:(e,t,i)=>{"use strict";i.r(t),i.d(t,{morphTargetsVertexGlobal:()=>n});const r="morphTargetsVertexGlobal",s="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nfloat vertexID;\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},9158:(e,t,i)=>{"use strict";i.r(t),i.d(t,{morphTargetsVertexGlobalDeclaration:()=>n});const r="morphTargetsVertexGlobalDeclaration",s="#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#ifdef MORPHTARGETS_TEXTURE \nuniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform highp sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex)\n{ \nfloat 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;}\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},36881:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.oitDeclaration="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out vec2 depth; \nlayout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor;\n#define MAX_DEPTH 99999.0\nhighp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler;\n#endif\n"},40401:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.oitFragment="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\nfloat fragDepth=gl_FragCoord.z; \n#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS\nuint halfFloat=packHalf2x16(vec2(fragDepth));vec2 full=unpackHalf2x16(halfFloat);fragDepth=full.x;\n#endif\nivec2 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);\n#ifdef USE_REVERSE_DEPTHBUFFER\nfloat furthestDepth=-lastDepth.x;float nearestDepth=lastDepth.y;\n#else\nfloat nearestDepth=-lastDepth.x;float furthestDepth=lastDepth.y;\n#endif\nfloat alphaMultiplier=1.0-lastFrontColor.a;\n#ifdef USE_REVERSE_DEPTHBUFFER\nif (fragDepth>nearestDepth || fragDepthfurthestDepth) {\n#endif\nreturn;}\n#ifdef USE_REVERSE_DEPTHBUFFER\nif (fragDepthfurthestDepth) {\n#else\nif (fragDepth>nearestDepth && fragDepth{"use strict";i.r(t),i.d(t,{packingFunctions:()=>n});const r="packingFunctions",s="vec4 pack(float depth)\n{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;}\nfloat unpack(vec4 color)\n{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);}";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},67350:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.pbrBRDFFunctions="#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);}\n#endif\n#ifdef ENVIRONMENTBRDF\nvec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV);\n#ifdef ENVIRONMENTBRDF_RGBD\nbrdfLookup.rgb=fromRGBD(brdfLookup.rgba);\n#endif\nreturn brdfLookup.rgb;}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y;\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y;\n#endif\nreturn reflectance;}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#endif\nreturn reflectance;}\n#endif\n/* NOT USED\n#if defined(SHEEN) && defined(SHEEN_SOFTER)\nfloat getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness)\n{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));}\n#endif\n*/\n#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)\nvec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF)\n/**\n* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture.\n* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table\n*/\nvec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;}\n#endif\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\nfloat fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\n#ifdef CLEARCOAT\nvec3 getR0RemappedForClearCoat(vec3 f0) {\n#ifdef CLEARCOAT_DEFAULTIOR\n#ifdef MOBILE\nreturn saturate(f0*(f0*0.526868+0.529324)-0.0482256);\n#else\nreturn saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);\n#endif\n#else\nvec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t);\n#endif\n}\n#endif\n#ifdef IRIDESCENCE\nconst mat3 XYZ_TO_REC709=mat3(\n3.2404542,-0.9692660, 0.0556434,\n-1.5371385, 1.8760108,-0.2040259,\n-0.4985314, 0.0415560, 1.0572252\n);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);}\nvec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));}\nfloat getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));}\nvec3 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;}\nvec3 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;}\nfloat 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 (iridescenceIOR{"use strict";var r=i(69841);i(32405),i(13580);r.l.IncludesShadersStore.pbrUboDeclaration="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;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n"},72992:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.pointCloudVertex="#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n"},59317:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.prePassDeclaration="#ifdef PREPASS\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor;\n#ifdef PREPASS_LOCAL_POSITION\nvarying highp vec3 vPosition;\n#endif\n#ifdef PREPASS_DEPTH\nvarying highp vec3 vViewPos;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)\nvarying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition;\n#endif\n#endif\n"},85639:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.prePassVertex="#ifdef PREPASS_DEPTH\nvViewPos=(view*worldPos).rgb;\n#endif\n#ifdef PREPASS_LOCAL_POSITION\nvPosition=positionUpdated.xyz;\n#endif\n#if (defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*worldPos;\n#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);\n#else\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#endif\n"},57819:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.prePassVertexDeclaration="#ifdef PREPASS\n#ifdef PREPASS_LOCAL_POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef PREPASS_DEPTH\nvarying vec3 vViewPos;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)\nuniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#endif\n"},51068:(e,t,i)=>{"use strict";i.r(t),i.d(t,{reflectionFunction:()=>n});const r="reflectionFunction",s="vec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)\n{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0); }\nvec3 computeMirroredFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)\n{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(1.0-s,t,0); }\nvec3 computeEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{vec3 cameraToVertex=normalize(worldPos.xyz-eyePosition);vec3 r=normalize(reflect(cameraToVertex,worldNormal));r=vec3(reflectionMatrix*vec4(r,0));float lon=atan(r.z,r.x);float lat=acos(r.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0);}\nvec3 computeSphericalCoords(vec4 worldPos,vec3 worldNormal,mat4 view,mat4 reflectionMatrix)\n{vec3 viewDir=normalize(vec3(view*worldPos));vec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));vec3 r=reflect(viewDir,viewNormal);r=vec3(reflectionMatrix*vec4(r,0));r.z=r.z-1.0;float m=2.0*length(r);return vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);}\nvec3 computePlanarCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{vec3 viewDir=worldPos.xyz-eyePosition;vec3 coords=normalize(reflect(viewDir,worldNormal));return vec3(reflectionMatrix*vec4(coords,1));}\nvec3 computeCubicCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;}\nvec3 computeCubicLocalCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix,vec3 reflectionSize,vec3 reflectionPosition)\n{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);coords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;}\nvec3 computeProjectionCoords(vec4 worldPos,mat4 view,mat4 reflectionMatrix)\n{return vec3(reflectionMatrix*(view*worldPos));}\nvec3 computeSkyBoxCoords(vec3 positionW,mat4 reflectionMatrix)\n{return vec3(reflectionMatrix*vec4(positionW,1.));}\n#ifdef REFLECTION\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);return computeFixedEquirectangularCoords(worldPos,worldNormal,direction);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nreturn computeEquirectangularCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nreturn computeSphericalCoords(worldPos,worldNormal,view,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nreturn computePlanarCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_CUBIC\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nreturn computeCubicLocalCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix,vReflectionSize,vReflectionPosition);\n#else\nreturn computeCubicCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn computeProjectionCoords(worldPos,view,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn computeSkyBoxCoords(vPositionUVW,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},5301:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.samplerFragmentDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying vec2 v_VARYINGNAME_UV;\n#endif\nuniform sampler2D _SAMPLERNAME_Sampler;\n#endif\n"},2251:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.samplerVertexDeclaration="#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0\nvarying vec2 v_VARYINGNAME_UV;\n#endif\n"},84525:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.samplerVertexImplementation="#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0\nif (v_INFONAME_==0.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));}\n#ifdef UV2\nelse if (v_INFONAME_==1.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2,1.0,0.0));}\n#endif\n#ifdef UV3\nelse if (v_INFONAME_==2.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));}\n#endif\n#ifdef UV4\nelse if (v_INFONAME_==3.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));}\n#endif\n#ifdef UV5\nelse if (v_INFONAME_==4.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));}\n#endif\n#ifdef UV6\nelse if (v_INFONAME_==5.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));}\n#endif\n#endif\n"},32405:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.sceneUboDeclaration="layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif \nmat4 view;mat4 projection;vec4 vEyePosition;};\n"},8338:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.screenSpaceRayTrace="float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); }\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nfloat linearizeDepth(float depth,float near,float far) {\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nreturn -(near*far)/(far-depth*(far-near));\n#else\nreturn (near*far)/(far-depth*(far-near));\n#endif\n}\n#endif\n/**\nparam csOrigin Camera-space ray origin,which must be \nwithin the view volume and must have z>0.01 and project within the valid screen rectangle\nparam csDirection Unit length camera-space ray direction\nparam projectToPixelMatrix A projection matrix that maps to **pixel** coordinates \n(**not** [-1,+1] normalized device coordinates).\nparam csZBuffer The camera-space Z buffer\nparam csZBufferSize Dimensions of csZBuffer\nparam csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer\nparam nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value\nfor clipping rays headed towards the camera\nparam stride Step in horizontal or vertical pixels between samples. This is a float\nbecause integer math is slow on GPUs,but should be set to an integer>=1\nparam jitterFraction Number between 0 and 1 for how far to bump the ray in stride units\nto conceal banding artifacts,plus the stride ray offset.\nparam maxSteps Maximum number of iterations. Higher gives better images but may be slow\nparam maxRayTraceDistance Maximum camera-space distance to trace before returning a miss\nparam selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions.\n1 is a reasonable value,depending on the scene you may need to set this value to 2\nparam hitPixel Pixel coordinates of the first intersection with the scene\nparam numIterations number of iterations performed\nparam csHitPoint Camera space location of the ray hit\n*/\n#define inline\nbool traceScreenSpaceRay1(\nvec3 csOrigin,\nvec3 csDirection,\nmat4 projectToPixelMatrix,\nsampler2D csZBuffer,\nvec2 csZBufferSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nsampler2D csZBackBuffer,\nfloat csZBackSizeFactor,\n#endif\nfloat csZThickness,\nfloat nearPlaneZ,\nfloat farPlaneZ,\nfloat stride,\nfloat jitterFraction,\nfloat maxSteps,\nfloat maxRayTraceDistance,\nfloat selfCollisionNumSkip,\nout vec2 startPixel,\nout vec2 hitPixel,\nout vec3 csHitPoint,\nout float numIterations\n#ifdef SSRAYTRACE_DEBUG\n,out vec3 debugColor\n#endif\n)\n{\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance;\n#else\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax) ? yMax : yMin))/(P1.y-P0.y);}\nif ((P1.x>xMax) || (P1.xxMax) ? xMax : xMin))/(P1.x-P0.x));}\nP1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha);\n#endif\nP1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)rayZMax) { \nfloat t=rayZMin; rayZMin=rayZMax; rayZMax=t;}\nsceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nsceneZMax=linearizeDepth(sceneZMax,nearPlaneZ,farPlaneZ);\n#endif\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nsceneBackZ=linearizeDepth(sceneBackZ,nearPlaneZ,farPlaneZ);\n#endif\nhit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax);\n#else\nhit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax);\n#endif\n#else\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nsceneBackZ=linearizeDepth(sceneBackZ,nearPlaneZ,farPlaneZ);\n#endif\nhit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0);\n#else\nhit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax);\n#endif\n#endif\n}\npqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;}\n#ifdef SSRAYTRACE_ENABLE_REFINEMENT\nif (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 ||\n(refinementStepCount<=stride*1.4) &&\n(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);}\n#endif\nreturn hit;}\n/**\ntexCoord: in the [0,1] range\ndepth: depth in view space (range [znear,zfar]])\n*/\nvec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef ORTHOGRAPHIC_CAMERA\nndc.z=-projection[2].z*depth+projection[3].z;\n#else\nndc.z=-projection[2].z-projection[3].z/depth;\n#endif\n#else\n#ifdef ORTHOGRAPHIC_CAMERA\nndc.z=projection[2].z*depth+projection[3].z;\n#else\nndc.z=projection[2].z+projection[3].z/depth;\n#endif\n#endif\nndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}\n"},73391:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowMapFragment:()=>n});const r="shadowMapFragment",s="float depthSM=vDepthMetricSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\n#if SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\ndepthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\ndepthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_FragDepth=clamp(1.0-depthSM,0.0,1.0);\n#else\ngl_FragDepth=clamp(depthSM,0.0,1.0); \n#endif\n#elif SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#if SM_ESM==1\ndepthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);\n#endif\n#if SM_FLOAT==1\ngl_FragColor=vec4(depthSM,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depthSM);\n#endif\nreturn;";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},19893:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowMapFragmentSoftTransparentShadow:()=>n});const r="shadowMapFragmentSoftTransparentShadow",s="#if SM_SOFTTRANSPARENTSHADOW==1\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM.x*alpha) discard;\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},94949:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowMapVertexMetric:()=>n});const r="shadowMapVertexMetric",s="#if SM_USEDISTANCE==1\nvPositionWSM=worldPos.xyz;\n#endif\n#if SM_DEPTHTEXTURE==1\n#ifdef IS_NDC_HALF_ZRANGE\n#define BIASFACTOR 0.5\n#else\n#define BIASFACTOR 1.0\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#else\ngl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#endif\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nzSM=gl_Position.z;gl_Position.z=0.0;\n#elif SM_USEDISTANCE==0\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\nvDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},34091:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowsFragmentFunctions:()=>n});const r="shadowsFragmentFunctions",s="#ifdef SHADOWS\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{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);}\n#endif\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}\n#define inline\nfloat computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{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;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nreturn depth>shadow ? darkness : 1.0;}\n#define inline\nfloat computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{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);\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}\n#endif\n#define inline\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{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)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadow=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nreturn shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}}\n#define inline\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{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)\n{return 1.0;}\nelse\n{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);\n#ifndef SHADOWFLOAT\nif (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{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)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\n#ifdef IS_NDC_HALF_ZRANGE\n#define ZINCLIP clipSpace.z\n#else\n#define ZINCLIP uvDepth.z\n#endif\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define GREATEST_LESS_THAN_ONE 0.99999994\n#define DISABLE_UNIFORMITY_ANALYSIS\n#define inline\nfloat computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{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);}\n#define inline\nfloat computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{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; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 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);}\n#define inline\nfloat computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{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; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 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);}\n#define inline\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{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);}}\n#define inline\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{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; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 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);}}\n#define inline\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{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; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 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);}}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.)\n);const vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n#define inline\nfloat 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)\n{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;}\nelse\n{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{"use strict";i.r(t),i.d(t,{shadowsVertex:()=>n});const r="shadowsVertex",s="#ifdef SHADOWS\n#if defined(SHADOWCSM{X})\nvPositionFromCamera{X}=view*worldPos;for (int i=0; i{"use strict";i(69841).l.IncludesShadersStore.subSurfaceScatteringFunctions="bool testLightingForSSS(float diffusionProfile)\n{return diffusionProfile<1.;}"},9482:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.uvAttributeDeclaration="#ifdef UV{X}\nattribute vec2 uv{X};\n#endif\n"},81448:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.uvVariableDeclaration="#if !defined(UV{X}) && defined(MAINUV{X})\nvec2 uv{X}=vec2(0.,0.);\n#endif\n#ifdef MAINUV{X}\nvMainUV{X}=uv{X};\n#endif\n"},61374:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.vertexColorMixing="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvColor=vec4(1.0);\n#ifdef VERTEXCOLOR\n#ifdef VERTEXALPHA\nvColor*=color;\n#else\nvColor.rgb*=color.rgb;\n#endif\n#endif\n#ifdef INSTANCESCOLOR\nvColor*=instanceColor;\n#endif\n#endif\n"},20692:(e,t,i)=>{"use strict";i.r(t),i.d(t,{anaglyphPixelShader:()=>n});const r="anaglyphPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{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);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},91341:(e,t,i)=>{"use strict";i.r(t),i.d(t,{backgroundPixelShader:()=>o});var r=i(69841);r.l.IncludesShadersStore.backgroundFragmentDeclaration="uniform vec4 vEyePosition;uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;uniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef PROJECTED_GROUND\nuniform vec2 projectedGroundInfos;\n#endif\n",i(29925),i(94388),i(51068),i(75651),i(23133),i(58769),i(97295),i(34091),i(88658),i(25012),i(77165),i(64657),i(89797),i(81749),i(6922),i(27185);const s="backgroundPixelShader",n="#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#include\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV==1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV==2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#ifdef PROJECTED_GROUND\nfloat diskIntersectWithBackFaceCulling(vec3 ro,vec3 rd,vec3 c,float r) {float d=rd.y;if(d>0.0) { return 1e6; }\nvec3 o=ro-c;float t=-o.y/d;vec3 q=o+rd*t;return (dot(q,q)\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\nfloat shadow=1.;float globalShadow=0.;float shadowLightCount=0.;float aggShadow=0.;float numLights=0.;\n#include[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n#ifndef BACKMAT_SHADOWONLY\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\n#ifdef PROJECTED_GROUND\nvec3 reflectionVector=project(viewDirectionW,vEyePosition.xyz);reflectionVector=vec3(reflectionMatrix*vec4(reflectionVector,1.));\n#else\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);} else {reflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\nvec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 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;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor;\n#endif\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\nvec4 color=vec4(finalColor,finalAlpha);\n#else\nvec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha);\n#endif\n#include\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n#if !defined(SKIPFINALCOLORCLAMP)\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#endif\n#else\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0);\n#endif\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},80723:(e,t,i)=>{"use strict";i.r(t),i.d(t,{backgroundVertexShader:()=>o});var r=i(69841);r.l.IncludesShadersStore.backgroundVertexDeclaration="uniform mat4 view;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n",i(29925),i(94388),i(39948),i(66682),i(56865),i(18355),i(77735),i(96951),i(19215),i(25012),i(18411),i(78792),i(95532),i(71471),i(90715),i(2946),i(88336);const s="backgroundVertexShader",n="precision highp float;\n#include<__decl__backgroundVertex>\n#include\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nvarying vec2 vDiffuseUV;\n#endif\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif\n#include\n#include\n#include\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);}\n#else\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#endif\nvec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 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));}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},41341:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bilateralBlurPixelShader:()=>n});const r="bilateralBlurPixelShader",s="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;}\nvec3 normal=textureLod(normalSampler,vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nfloat 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;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nfloat 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;}\nglFragColor=vec4(sum/wsum,1.);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},47318:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bilateralBlurQualityPixelShader:()=>n});const r="bilateralBlurQualityPixelShader",s="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;}\nvec3 normal=textureLod(normalSampler,vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nfloat 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;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nfloat 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;}}\nglFragColor=vec4(sum/wsum,1.);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},27897:(e,t,i)=>{"use strict";i.r(t),i.d(t,{blackAndWhitePixelShader:()=>n});const r="blackAndWhitePixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},94811:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bloomMergePixelShader:()=>n});const r="bloomMergePixelShader",s="uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); }\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},16400:(e,t,i)=>{"use strict";i.r(t),i.d(t,{boundingBoxRendererPixelShader:()=>o});var r=i(69841);r.l.IncludesShadersStore.boundingBoxRendererFragmentDeclaration="uniform vec4 color;\n",i(97315);const s="boundingBoxRendererPixelShader",n="#include<__decl__boundingBoxRendererFragment>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},81473:(e,t,i)=>{"use strict";i.r(t),i.d(t,{boundingBoxRendererVertexShader:()=>o});var r=i(69841);r.l.IncludesShadersStore.boundingBoxRendererVertexDeclaration="uniform mat4 world;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n",i(97315);const s="boundingBoxRendererVertexShader",n="attribute vec3 position;\n#include<__decl__boundingBoxRendererVertex>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec4 worldPos=world*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},76437:(e,t,i)=>{"use strict";i.r(t),i.d(t,{chromaticAberrationPixelShader:()=>n});const r="chromaticAberrationPixelShader",s="uniform sampler2D textureSampler; \nuniform float chromatic_aberration;uniform float radialIntensity;uniform vec2 direction;uniform vec2 centerPosition;uniform float screen_width;uniform float screen_height;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);vec2 directionOfEffect=direction;if(directionOfEffect.x==0. && directionOfEffect.y==0.){directionOfEffect=normalize(centered_screen_pos);}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+ centered_screen_pos.y*centered_screen_pos.y;float radius=sqrt(radius2);vec3 ref_indices=vec3(-0.3,0.0,0.3);float ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;float ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;vec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);vec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);vec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);vec4 r=texture2D(textureSampler,ref_coords_r);vec4 g=texture2D(textureSampler,ref_coords_g);vec4 b=texture2D(textureSampler,ref_coords_b);float a=clamp(r.a+g.a+b.a,0.,1.);gl_FragColor=vec4(r.r,g.g,b.b,a);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},29743:(e,t,i)=>{"use strict";i.r(t),i.d(t,{circleOfConfusionPixelShader:()=>n});const r="circleOfConfusionPixelShader",s="uniform sampler2D depthSampler;varying vec2 vUV;\n#ifndef COC_DEPTH_NOT_NORMALIZED\nuniform vec2 cameraMinMaxZ;\n#endif\nuniform float focusDistance;uniform float cocPrecalculation;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float depth=texture2D(depthSampler,vUV).r;\n#define CUSTOM_COC_DEPTH\n#ifdef COC_DEPTH_NOT_NORMALIZED\nfloat pixelDistance=depth*1000.0;\n#else\nfloat pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; \n#endif\n#define CUSTOM_COC_PIXELDISTANCE\nfloat coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},27683:(e,t,i)=>{"use strict";i.r(t),i.d(t,{colorPixelShader:()=>o});var r=i(69841);i(77165),i(64657),i(89797),i(27185);const s="colorPixelShader",n="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\n#define VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n#include(color,gl_FragColor)\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},53501:(e,t,i)=>{"use strict";i.r(t),i.d(t,{colorVertexShader:()=>o});var r=i(69841);i(39948),i(66682),i(18355),i(77735),i(56865),i(18411),i(78792),i(95532),i(71471),i(90715),i(61374);const s="colorVertexShader",n="attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\n#ifdef FOG\nuniform mat4 view;\n#endif\n#include\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},42711:(e,t,i)=>{"use strict";i.r(t),i.d(t,{colorCorrectionPixelShader:()=>n});const r="colorCorrectionPixelShader",s="uniform sampler2D textureSampler; \nuniform sampler2D colorTable; \nvarying vec2 vUV;const float SLICE_COUNT=16.0; \n#define inline\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat 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;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},59188:(e,t,i)=>{"use strict";i.r(t),i.d(t,{convolutionPixelShader:()=>n});const r="convolutionPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9];\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},76978:(e,t,i)=>{"use strict";i.r(t),i.d(t,{copyTexture3DLayerToTexturePixelShader:()=>n});const r="copyTexture3DLayerToTexturePixelShader",s="precision highp sampler3D;uniform sampler3D textureSampler;uniform int layerNum;varying vec2 vUV;void main(void) {vec3 coord=vec3(0.0,0.0,float(layerNum));coord.xy=vec2(vUV.x,vUV.y)*vec2(textureSize(textureSampler,0).xy);vec3 color=texelFetch(textureSampler,ivec3(coord),0).rgb;gl_FragColor=vec4(color,1);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},92224:(e,t,i)=>{"use strict";i.r(t),i.d(t,{copyTextureToTexturePixelShader:()=>o});var r=i(69841);i(94388);const s="copyTextureToTexturePixelShader",n="uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV;\n#include\nvoid main(void) \n{vec4 color=texture2D(textureSampler,vUV);\n#ifdef DEPTH_TEXTURE\ngl_FragDepth=color.r;\n#else\nif (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);}\ngl_FragColor=color;\n#endif\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},85800:(e,t,i)=>{"use strict";i.r(t),i.d(t,{defaultPixelShader:()=>o});var r=i(69841);i(14774);r.l.IncludesShadersStore.defaultFragmentDeclaration="uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;uniform vec4 vSpecularColor;uniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;uniform vec4 refractionRightColor;\n#endif\n#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D)\nuniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; \n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX)\nuniform mat4 reflectionMatrix;\n#endif\n#ifndef REFLECTIONMAP_SKYBOX\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include\n#define ADDITIONAL_FRAGMENT_DECLARATION\n",i(16792),i(59317),i(36881),i(40371),i(94388),i(23133),i(58769),i(97295),i(34091),i(5301),i(49046),i(51068),i(75651),i(88658),i(82267),i(29424),i(77165),i(25012),i(64657),i(89797),i(90249),i(22464),i(51314),i(81749),i(6922),i(27185),i(40401);const s="defaultPixelShader",n="#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#include[SCENE_MRT_COUNT]\n#include\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include[1..7]\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULARTERM)\n#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular)\n#endif\n#include\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS)\nif (baseColor.a(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)\n#endif\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef DETAIL\nbaseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y);\n#endif\n#if defined(DECAL) && defined(DECAL_AFTER_DETAIL)\nvec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset);\n#include(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\nfloat glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);specularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef LIGHTMAP\nvec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);\n#ifdef RGBDLIGHTMAP\nlightmapColor.rgb=fromRGBD(lightmapColor);\n#endif\nlightmapColor.rgb*=vLightmapInfos.y;\n#endif\n#include[0..maxSimultaneousLights]\naggShadow=aggShadow/numLights;vec4 refractionColor=vec4(0.,0.,0.,1.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\n#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC\nrefractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition);\n#endif\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;vec4 refractionLookup=textureCube(refractionCubeSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;}\n#else\nvec3 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);\n#endif\n#ifdef RGBDREFRACTION\nrefractionColor.rgb=fromRGBD(refractionColor);\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor.rgb=toGammaSpace(refractionColor.rgb);\n#endif\nrefractionColor.rgb*=vRefractionInfos.x;\n#endif\nvec4 reflectionColor=vec4(0.,0.,0.,1.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nvReflectionUVW.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias);\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW);\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;reflectionColor=texture2D(reflection2DSampler,coords);\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor.rgb=toGammaSpace(reflectionColor.rgb);\n#endif\nreflectionColor.rgb*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n#ifdef ALPHATEST\n#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS\nif (alpha\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color);\n#endif\n#endif\ncolor.a*=visibility;\n#ifdef PREMULTIPLYALPHA\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\n#ifdef PREPASS\nfloat writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;\n#ifdef PREPASS_COLOR\ngl_FragData[PREPASS_COLOR_INDEX]=color; \n#endif\n#ifdef PREPASS_POSITION\ngl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);\n#endif\n#ifdef PREPASS_LOCAL_POSITION\ngl_FragData[PREPASS_LOCAL_POSITION_INDEX]=vec4(vPosition,writeGeometryInfo);\n#endif\n#if defined(PREPASS_VELOCITY)\nvec2 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);\n#elif defined(PREPASS_VELOCITY_LINEAR)\nvec2 velocity=vec2(0.5)*((vPreviousPosition.xy/vPreviousPosition.w)-(vCurrentPosition.xy/vCurrentPosition.w));gl_FragData[PREPASS_VELOCITY_LINEAR_INDEX]=vec4(velocity,0.0,writeGeometryInfo);\n#endif\n#ifdef PREPASS_IRRADIANCE\ngl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); \n#endif\n#ifdef PREPASS_DEPTH\ngl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); \n#endif\n#ifdef PREPASS_SCREENSPACE_DEPTH\ngl_FragData[PREPASS_SCREENSPACE_DEPTH_INDEX]=vec4(gl_FragCoord.z,0.0,0.0,writeGeometryInfo);\n#endif\n#ifdef PREPASS_NORMAL\n#ifdef PREPASS_NORMAL_WORLDSPACE\ngl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo);\n#else\ngl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo);\n#endif\n#endif\n#ifdef PREPASS_WORLD_NORMAL\ngl_FragData[PREPASS_WORLD_NORMAL_INDEX]=vec4(normalW*0.5+0.5,writeGeometryInfo);\n#endif\n#ifdef PREPASS_ALBEDO\ngl_FragData[PREPASS_ALBEDO_INDEX]=vec4(baseColor.rgb,writeGeometryInfo);\n#endif\n#ifdef PREPASS_ALBEDO_SQRT\ngl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqrt(baseColor.rgb),writeGeometryInfo);\n#endif\n#ifdef PREPASS_REFLECTIVITY\n#if defined(SPECULAR)\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularMapColor))*writeGeometryInfo; \n#else\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularColor),1.0)*writeGeometryInfo;\n#endif\n#endif\n#endif\n#if !defined(PREPASS) || defined(WEBGL2)\ngl_FragColor=color;\n#endif\n#include\n#if ORDER_INDEPENDENT_TRANSPARENCY\nif (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-color.a);} else {backColor+=color;}\n#endif\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},35936:(e,t,i)=>{"use strict";i.r(t),i.d(t,{defaultVertexShader:()=>o});var r=i(69841);i(81160);r.l.IncludesShadersStore.defaultVertexDeclaration="uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif \nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;uniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;uniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform mat4 bumpMatrix;\n#endif\n#ifdef REFLECTION\nuniform mat4 reflectionMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;uniform mat4 detailMatrix;\n#endif\n#include\n#define ADDITIONAL_VERTEX_DECLARATION\n",i(16792),i(9482),i(94388),i(39948),i(66682),i(56865),i(57819),i(40371),i(2251),i(17727),i(18355),i(77735),i(96951),i(19215),i(9158),i(11783),i(25012),i(99216),i(44219),i(18411),i(78792),i(95532),i(85639),i(81448),i(84525),i(78595),i(71471),i(90715),i(2946),i(61374),i(72992),i(88336);const s="defaultVertexShader",n="#include<__decl__defaultVertex>\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#include[2..7]\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\n#include\n#include[1..7]\n#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)\n#if defined(SPECULARTERM)\n#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular)\n#endif\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include\n#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#endif\n#define CUSTOM_VERTEX_UPDATE_WORLDPOS\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\nvPositionW=vec3(worldPos);\n#ifdef PREPASS\n#include\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n#ifndef UV1\nvec2 uvUpdated=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uvUpdated;\n#endif\n#include[2..7]\n#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)\n#if defined(SPECULARTERM)\n#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x)\n#endif\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},2297:(e,t,i)=>{"use strict";i.r(t),i.d(t,{depthPixelShader:()=>o});var r=i(69841);i(77165),i(72693),i(89797);const s="depthPixelShader",n="#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\nvarying float vDepthMetric;\n#ifdef PACKED\n#include\n#endif\n#ifdef STORE_CAMERASPACE_Z\nvarying vec4 vViewPos;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef STORE_CAMERASPACE_Z\n#ifdef PACKED\ngl_FragColor=pack(vViewPos.z);\n#else\ngl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);\n#endif\n#else\n#ifdef NONLINEARDEPTH\n#ifdef PACKED\ngl_FragColor=pack(gl_FragCoord.z);\n#else\ngl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);\n#endif\n#else\n#ifdef PACKED\ngl_FragColor=pack(vDepthMetric);\n#else\ngl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);\n#endif\n#endif\n#endif\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},6069:(e,t,i)=>{"use strict";i.r(t),i.d(t,{depthVertexShader:()=>o});var r=i(69841);i(39948),i(66682),i(9158),i(11783),i(18355),i(56865);r.l.IncludesShadersStore.pointCloudVertexDeclaration="#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n",i(99216),i(44219),i(18411),i(78792),i(95532),i(71471),i(72992);const s="depthVertexShader",n="attribute vec3 position;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;uniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef STORE_CAMERASPACE_Z\nuniform mat4 view;varying vec4 vViewPos;\n#endif\n#include\nvarying float vDepthMetric;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#include\ngl_Position=viewProjection*worldPos;\n#ifdef STORE_CAMERASPACE_Z\nvViewPos=view*worldPos;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));\n#else\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#endif\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},16845:(e,t,i)=>{"use strict";i.r(t),i.d(t,{depthBoxBlurPixelShader:()=>n});const r="depthBoxBlurPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},95610:(e,t,i)=>{"use strict";i.r(t),i.d(t,{depthOfFieldMergePixelShader:()=>n});const r="depthOfFieldMergePixelShader",s="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r;\n#if BLUR_LEVEL==0\nvec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL==1\nif(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);}\n#endif\n#if BLUR_LEVEL==2\nif(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);}\n#endif\n}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},17239:(e,t,i)=>{"use strict";i.r(t),i.d(t,{displayPassPixelShader:()=>n});const r="displayPassPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D passSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(passSampler,vUV);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},83062:(e,t,i)=>{"use strict";i.r(t),i.d(t,{extractHighlightsPixelShader:()=>o});var r=i(69841);i(94388);const s="extractHighlightsPixelShader",n="#include\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},88770:(e,t,i)=>{"use strict";i.r(t),i.d(t,{filterPixelShader:()=>n});const r="filterPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},93705:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingBilateralBlurPixelShader:()=>n});const r="fluidRenderingBilateralBlurPixelShader",s="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;}\nint 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;}\nglFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},21959:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingParticleDepthPixelShader:()=>n});const r="fluidRenderingParticleDepthPixelShader",s="uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nvarying float velocityNorm;\n#endif\nvoid 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);\n#ifndef FLUIDRENDERING_RHS\nnormal.z=-normal.z;\n#endif\nvec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos;\n#ifdef WEBGPU\ngl_FragDepth=clipSpacePos.z/clipSpacePos.w;\n#else\ngl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5;\n#endif\n#ifdef FLUIDRENDERING_RHS\nrealViewPos.z=-realViewPos.z;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nglFragColor=vec4(realViewPos.z,velocityNorm,0.,1.);\n#else\nglFragColor=vec4(realViewPos.z,0.,0.,1.);\n#endif\n}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},49377:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingParticleDepthVertexShader:()=>n});const r="fluidRenderingParticleDepthVertexShader",s="attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nattribute vec3 velocity;varying float velocityNorm;\n#endif\nvoid 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;\n#ifdef FLUIDRENDERING_VELOCITY\nvelocityNorm=length(velocity);\n#endif\n}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},76558:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingParticleDiffusePixelShader:()=>n});const r="fluidRenderingParticleDiffusePixelShader",s="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);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},28566:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingParticleThicknessPixelShader:()=>n});const r="fluidRenderingParticleThicknessPixelShader",s="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);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},3420:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingParticleThicknessVertexShader:()=>n});const r="fluidRenderingParticleThicknessVertexShader",s="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;}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},35116:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingRenderPixelShader:()=>n});const r="fluidRenderingRenderPixelShader",s="#define DISABLE_UNIFORMITY_ANALYSIS\n#define IOR 1.333\n#define ETA 1.0/IOR\n#define F0 0.02\nuniform sampler2D textureSampler;uniform sampler2D depthSampler;\n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nuniform sampler2D diffuseSampler;\n#else\nuniform vec3 diffuseColor;\n#endif\n#ifdef FLUIDRENDERING_FIXED_THICKNESS\nuniform float thickness;uniform sampler2D bgDepthSampler;\n#else\nuniform float minimumThickness;uniform sampler2D thicknessSampler;\n#endif\n#ifdef FLUIDRENDERING_ENVIRONMENT\nuniform samplerCube reflectionSampler;\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nuniform sampler2D debugSampler;\n#endif\nuniform 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;\n#ifdef FLUIDRENDERING_RHS\nndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#else\nndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#endif\nndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}\nvec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);}\nvoid main(void) {vec2 texCoord=vUV;\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nvec4 color=texture2D(debugSampler,texCoord);\n#ifdef FLUIDRENDERING_DEBUG_DEPTH\nglFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);}\n#else\nglFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);}\n#endif\nreturn;\n#endif\nvec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r;\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nfloat thickness=texture2D(thicknessSampler,texCoord).x;\n#else\nfloat bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5;\n#endif\nvec4 backColor=texture2D(textureSampler,texCoord);\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nif (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) {\n#else\nif (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) {\n#endif\n#ifdef FLUIDRENDERING_COMPOSITE_MODE\nglFragColor.rgb=backColor.rgb*backColor.a;glFragColor.a=backColor.a;\n#else\nglFragColor=backColor;\n#endif\nreturn;}\nvec3 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;}\nvec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;}\nvec3 normal=normalize(cross(ddy,ddx));\n#ifdef FLUIDRENDERING_RHS\nnormal=-normal;\n#endif\n#ifndef WEBGPU\nif(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);}\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL)\nglFragColor=vec4(normal*0.5+0.5,1.0);return;\n#endif\nvec3 rayDir=normalize(viewPos); \n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nvec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb;\n#endif\nvec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower);\n#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING\nfloat 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;\n#endif\nvec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);\n#ifdef FLUIDRENDERING_COMPOSITE_MODE\nif (transmitted.a==0.) transmitted.a=thickness;\n#endif\nvec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); \nvec3 refractionColor=transmitted.rgb*transmittance;\n#ifdef FLUIDRENDERING_ENVIRONMENT\nvec3 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;\n#else\nvec3 finalColor=refractionColor+specular;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nfloat velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0));\n#endif\nglFragColor=vec4(finalColor,transmitted.a);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},53360:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingStandardBlurPixelShader:()=>n});const r="fluidRenderingStandardBlurPixelShader",s="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;}\nfloat 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;}\nsum/=wsum;glFragColor=vec4(sum.rgb,1.);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},75424:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fxaaPixelShader:()=>n});const r="fxaaPixelShader",s="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nuniform 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);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid 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);\n#ifndef MALI\nif(range=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan)\n{lumaN=lumaW;}\nif (!horzSpan) \n{lumaS=lumaE;}\nif (horzSpan) \n{lengthSign=texelSize.y;}\nfloat 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)\n{lengthSign=-lengthSign;}\nfloat 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) \n{posB.x+=lengthSign*0.5;}\nif (horzSpan)\n{posB.y+=lengthSign*0.5;}\nvec2 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) \n{lumaNN=lumaSS;}\nfloat 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) \n{posN.x-=offNP.x*3.0;}\nif (!doneN) \n{posN.y-=offNP.y*3.0;}\nbool doneNP=(!doneN) || (!doneP);if (!doneP) \n{posP.x+=offNP.x*3.0;}\nif (!doneP)\n{posP.y+=offNP.y*3.0;}\nif (doneNP)\n{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;}\nfloat dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan)\n{dstN=posM.y-posN.y;}\nif (!horzSpan) \n{dstP=posP.y-posM.y;}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN{"use strict";i.r(t),i.d(t,{fxaaVertexShader:()=>n});const r="fxaaVertexShader",s="attribute vec2 position;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 vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=(position*madd+madd);sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},67058:(e,t,i)=>{"use strict";i.r(t),i.d(t,{gaussianSplattingPixelShader:()=>o});var r=i(69841);i(77165),i(25012),i(64657),i(6922),i(27185);r.l.IncludesShadersStore.gaussianSplattingFragmentDeclaration="vec4 gaussianColor(vec4 inColor)\n{float A=-dot(vPosition,vPosition);if (A<-4.0) discard;float B=exp(A)*inColor.a;\n#include\nvec3 color=inColor.rgb;\n#ifdef FOG\n#include\n#endif\nreturn vec4(color,B);}\n",i(89797);const s="gaussianSplattingPixelShader",n="#include\n#include\n#include\nvarying vec4 vColor;varying vec2 vPosition;\n#include\nvoid main () { \n#include\ngl_FragColor=gaussianColor(vColor);}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},21325:(e,t,i)=>{"use strict";i.r(t),i.d(t,{gaussianSplattingVertexShader:()=>o});var r=i(69841);i(93784),i(32405),i(13580);r.l.IncludesShadersStore.gaussianSplattingUboDeclaration="#include\n#include\nattribute vec2 position;",i(18355),i(77735),i(25012);r.l.IncludesShadersStore.gaussianSplatting="#if !defined(WEBGL2) && !defined(WEBGPU) && !defined(NATIVE)\nmat3 transpose(mat3 matrix) {return mat3(matrix[0][0],matrix[1][0],matrix[2][0],\nmatrix[0][1],matrix[1][1],matrix[2][1],\nmatrix[0][2],matrix[1][2],matrix[2][2]);}\n#endif\nvec2 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);}\nstruct Splat {vec4 center;vec4 color;vec4 covA;vec4 covB;};Splat readSplat(float splatIndex)\n{Splat splat;vec2 splatUV=getDataUV(splatIndex,dataTextureSize);splat.center=texture2D(centersTexture,splatUV);splat.color=texture2D(colorsTexture,splatUV);splat.covA=texture2D(covariancesATexture,splatUV)*splat.center.w;splat.covB=texture2D(covariancesBTexture,splatUV)*splat.center.w;return splat;}\nvec4 gaussianSplatting(vec2 meshPos,vec3 worldPos,vec2 scale,vec3 covA,vec3 covB,mat4 worldMatrix,mat4 viewMatrix,mat4 projectionMatrix)\n{mat4 modelView=viewMatrix*worldMatrix;vec4 camspace=viewMatrix*vec4(worldPos,1.);vec4 pos2d=projectionMatrix*camspace;float bounds=1.2*pos2d.w;if (pos2d.z<-pos2d.w || pos2d.x<-bounds || pos2d.x>bounds\n|| pos2d.y<-bounds || pos2d.y>bounds) {return vec4(0.0,0.0,2.0,1.0);}\nmat3 Vrk=mat3(\ncovA.x,covA.y,covA.z,\ncovA.y,covB.x,covB.y,\ncovA.z,covB.y,covB.z\n);mat3 J=mat3(\nfocal.x/camspace.z,0.,-(focal.x*camspace.x)/(camspace.z*camspace.z),\n0.,focal.y/camspace.z,-(focal.y*camspace.y)/(camspace.z*camspace.z),\n0.,0.,0.\n);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)\n{return vec4(0.0,0.0,2.0,1.0);}\nvec2 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);vec2 vCenter=vec2(pos2d);return vec4(\nvCenter \n+ ((meshPos.x*majorAxis\n+ meshPos.y*minorAxis)*invViewport*pos2d.w)*scale,pos2d.zw);}",i(71471),i(90715),i(88336);const s="gaussianSplattingVertexShader",n="#include<__decl__gaussianSplattingVertex>\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\nattribute float splatIndex;uniform vec2 invViewport;uniform vec2 dataTextureSize;uniform vec2 focal;uniform sampler2D covariancesATexture;uniform sampler2D covariancesBTexture;uniform sampler2D centersTexture;uniform sampler2D colorsTexture;varying vec4 vColor;varying vec2 vPosition;\n#include\nvoid main () {Splat splat=readSplat(splatIndex);vec3 covA=splat.covA.xyz;vec3 covB=vec3(splat.covA.w,splat.covB.xy);vec4 worldPos=world*vec4(splat.center.xyz,1.0);vColor=splat.color;vPosition=position;gl_Position=gaussianSplatting(position,worldPos.xyz,vec2(1.,1.),covA,covB,world,view,projection);\n#include\n#include\n#include\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},2146:(e,t,i)=>{"use strict";i.r(t),i.d(t,{geometryPixelShader:()=>o});var r=i(69841);i(77165);r.l.IncludesShadersStore.mrtFragmentDeclaration="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n",i(82267),i(29424),i(94388),i(89797),i(90249);const s="geometryPixelShader",n="#extension GL_EXT_draw_buffers : require\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\nprecision highp float;\n#ifdef BUMP\nvarying mat4 vWorldView;varying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#if defined(VELOCITY) || defined(VELOCITY_LINEAR)\nvarying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#ifdef NEED_UV\nvarying vec2 vUV;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIVITY)\n#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nuniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV;\n#endif\n#ifdef ALBEDOTEXTURE\nvarying vec2 vAlbedoUV;uniform sampler2D albedoSampler;\n#endif\n#ifdef REFLECTIVITYCOLOR\nuniform vec3 reflectivityColor;\n#endif\n#ifdef ALBEDOCOLOR\nuniform vec3 albedoColor;\n#endif\n#ifdef METALLIC\nuniform float metallic;\n#endif\n#if defined(ROUGHNESS) || defined(GLOSSINESS)\nuniform float glossiness;\n#endif\n#endif\n#if defined(ALPHATEST) && defined(NEED_UV)\nuniform sampler2D diffuseSampler;\n#endif\n#include\n#include[SCENE_MRT_COUNT]\n#include\n#include\n#include\nvoid main() {\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nvec3 normalOutput;\n#ifdef BUMP\nvec3 normalW=normalize(vNormalW);\n#include\n#ifdef NORMAL_WORLDSPACE\nnormalOutput=normalW;\n#else\nnormalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0)));\n#endif\n#else\nnormalOutput=normalize(vNormalV);\n#endif\n#ifdef ENCODE_NORMAL\nnormalOutput=normalOutput*0.5+0.5;\n#endif\n#ifdef DEPTH\ngl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n#endif\n#ifdef NORMAL\ngl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0);\n#endif\n#ifdef SCREENSPACE_DEPTH\ngl_FragData[SCREENSPACE_DEPTH_INDEX]=vec4(gl_FragCoord.z,0.0,0.0,1.0);\n#endif\n#ifdef POSITION\ngl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0);\n#endif\n#ifdef VELOCITY\nvec2 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);\n#endif\n#ifdef VELOCITY_LINEAR\nvec2 velocity=vec2(0.5)*((vPreviousPosition.xy/vPreviousPosition.w) -\n(vCurrentPosition.xy/vCurrentPosition.w));gl_FragData[VELOCITY_LINEAR_INDEX]=vec4(velocity,0.0,1.0);\n#endif\n#ifdef REFLECTIVITY\nvec4 reflectivity=vec4(0.0,0.0,0.0,1.0);\n#ifdef METALLICWORKFLOW\nfloat metal=1.0;float roughness=1.0;\n#ifdef ORMTEXTURE\nmetal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g;\n#endif\n#ifdef METALLIC\nmetal*=metallic;\n#endif\n#ifdef ROUGHNESS\nroughness*=(1.0-glossiness); \n#endif\nreflectivity.a-=roughness;vec3 color=vec3(1.0);\n#ifdef ALBEDOTEXTURE\ncolor=texture2D(albedoSampler,vAlbedoUV).rgb;\n#ifdef GAMMAALBEDO\ncolor=toLinearSpace(color);\n#endif\n#endif\n#ifdef ALBEDOCOLOR\ncolor*=albedoColor.xyz;\n#endif\nreflectivity.rgb=mix(vec3(0.04),color,metal);\n#else\n#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nreflectivity=texture2D(reflectivitySampler,vReflectivityUV);\n#ifdef GAMMAREFLECTIVITYTEXTURE\nreflectivity.rgb=toLinearSpace(reflectivity.rgb);\n#endif\n#else \n#ifdef REFLECTIVITYCOLOR\nreflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0;\n#endif\n#endif\n#ifdef GLOSSINESSS\nreflectivity.a*=glossiness; \n#endif\n#endif\ngl_FragData[REFLECTIVITY_INDEX]=reflectivity;\n#endif\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},24077:(e,t,i)=>{"use strict";i.r(t),i.d(t,{geometryVertexShader:()=>o});var r=i(69841);i(39948),i(66682),i(9158),i(11783),i(56865);r.l.IncludesShadersStore.geometryVertexDeclaration="uniform mat4 viewProjection;uniform mat4 view;",i(32405);r.l.IncludesShadersStore.geometryUboDeclaration="#include\n",i(18355),i(99216),i(44219),i(18411),i(78792),i(95532),i(71471),i(78595);const s="geometryVertexShader",n="precision highp float;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include<__decl__geometryVertex>\n#include\nattribute vec3 position;attribute vec3 normal;\n#ifdef NEED_UV\nvarying vec2 vUV;\n#ifdef ALPHATEST\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef BUMP\nuniform mat4 bumpMatrix;varying vec2 vBumpUV;\n#endif\n#ifdef REFLECTIVITY\nuniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef BUMP\nvarying mat4 vWorldView;\n#endif\n#ifdef BUMP\nvarying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#if defined(VELOCITY) || defined(VELOCITY_LINEAR)\nuniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include\n#include\nvec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0));\n#ifdef BUMP\nvWorldView=view*finalWorld;mat3 normalWorld=mat3(finalWorld);vNormalW=normalize(normalWorld*normalUpdated);\n#else\n#ifdef NORMAL_WORLDSPACE\nvNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#else\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0)));\n#endif\n#endif\nvViewPos=view*worldPos;\n#if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);\n#else\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#endif\n#if defined(POSITION) || defined(BUMP)\nvPositionW=worldPos.xyz/worldPos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#include\n#ifdef NEED_UV\n#ifdef UV1\n#if defined(ALPHATEST) && defined(ALPHATEST_UV1)\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#else\nvUV=uv;\n#endif\n#ifdef BUMP_UV1\nvBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV1\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV1\nvAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#endif\n#ifdef UV2\n#if defined(ALPHATEST) && defined(ALPHATEST_UV2)\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#else\nvUV=uv2;\n#endif\n#ifdef BUMP_UV2\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV2\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV2\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#endif\n#include\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},16655:(e,t,i)=>{"use strict";i.r(t),i.d(t,{glowBlurPostProcessPixelShader:()=>n});const r="glowBlurPostProcessPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 direction;uniform float blurWidth;float getLuminance(vec3 color)\n{return dot(color,vec3(0.2126,0.7152,0.0722));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float weights[7];weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;vec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);vec2 texelStep=texelSize*direction*blurWidth;vec2 start=vUV-3.0*texelStep;vec4 baseColor=vec4(0.,0.,0.,0.);vec2 texelOffset=vec2(0.,0.);for (int i=0; i<7; i++)\n{vec4 texel=texture2D(textureSampler,start+texelOffset);baseColor.a+=texel.a*weights[i];float luminance=getLuminance(baseColor.rgb);float luminanceTexel=getLuminance(texel.rgb);float choice=step(luminanceTexel,luminance);baseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;texelOffset+=texelStep;}\ngl_FragColor=baseColor;}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},42591:(e,t,i)=>{"use strict";i.r(t),i.d(t,{glowMapGenerationPixelShader:()=>o});var r=i(69841);i(94388),i(77165),i(89797);const s="glowMapGenerationPixelShader",n="#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform sampler2D diffuseSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform sampler2D emissiveSampler;\n#endif\n#ifdef VERTEXALPHA\nvarying vec4 vColor;\n#endif\nuniform vec4 glowColor;uniform float glowIntensity;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\nvec4 finalColor=glowColor;\n#ifdef DIFFUSE\nvec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);\n#ifdef DIFFUSE_ISLINEAR\nalbedoTexture=toGammaSpace(albedoTexture);\n#endif\n#ifdef GLOW\nfinalColor.a*=albedoTexture.a;\n#endif\n#ifdef HIGHLIGHT\nfinalColor.a=albedoTexture.a;\n#endif\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vUVOpacity);\n#ifdef OPACITYRGB\nfinalColor.a*=getLuminance(opacityMap.rgb);\n#else\nfinalColor.a*=opacityMap.a;\n#endif\nfinalColor.a*=opacityIntensity;\n#endif\n#ifdef VERTEXALPHA\nfinalColor.a*=vColor.a;\n#endif\n#ifdef ALPHATEST\nif (finalColor.a{"use strict";i.r(t),i.d(t,{glowMapGenerationVertexShader:()=>o});var r=i(69841);i(39948),i(66682),i(9158),i(11783),i(18355),i(56865),i(99216),i(44219),i(18411),i(78792),i(95532),i(71471);const s="glowMapGenerationVertexShader",n="attribute vec3 position;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;varying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform mat4 diffuseMatrix;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform mat4 opacityMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform mat4 emissiveMatrix;\n#endif\n#ifdef VERTEXALPHA\nattribute vec4 color;varying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef CUBEMAP\nvPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*worldPos;gl_Position=vPosition;\n#endif\n#ifdef DIFFUSE\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef OPACITY\n#ifdef OPACITYUV1\nvUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef OPACITYUV2\nvUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef VERTEXALPHA\nvColor=color;\n#endif\n#include\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},74969:(e,t,i)=>{"use strict";i.r(t),i.d(t,{glowMapMergePixelShader:()=>n});const r="glowMapMergePixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\nuniform float offset;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);baseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\n#if LDR\nbaseColor=clamp(baseColor,0.,1.0);\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},99347:(e,t,i)=>{"use strict";i.r(t),i.d(t,{glowMapMergeVertexShader:()=>n});const r="glowMapMergeVertexShader",s="attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},55099:(e,t,i)=>{"use strict";i.r(t),i.d(t,{grainPixelShader:()=>o});var r=i(69841);i(94388);const s="grainPixelShader",n="#include\nuniform sampler2D textureSampler; \nuniform float intensity;uniform float animatedSeed;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{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);}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},80424:(e,t,i)=>{"use strict";i.r(t),i.d(t,{hdrFilteringPixelShader:()=>o});var r=i(69841);i(94388),i(71826),i(67350),i(98392);const s="hdrFilteringPixelShader",n="#include\n#include\n#include\n#include\nuniform 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);}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},77318:(e,t,i)=>{"use strict";i.r(t),i.d(t,{hdrFilteringVertexShader:()=>n});const r="hdrFilteringVertexShader",s="attribute vec2 position;varying vec3 direction;uniform vec3 up;uniform vec3 right;uniform vec3 front;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nmat3 view=mat3(up,right,front);direction=view*vec3(position,1.0);gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},13079:(e,t,i)=>{"use strict";i.r(t),i.d(t,{highlightsPixelShader:()=>n});const r="highlightsPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{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); }";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},17897:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblCombineVoxelGridsPixelShader:()=>n});const r="iblCombineVoxelGridsPixelShader",s="precision highp float;precision highp sampler3D;varying vec2 vUV;uniform sampler3D voxelXaxisSampler;uniform sampler3D voxelYaxisSampler;uniform sampler3D voxelZaxisSampler;uniform float layer;void main(void) {vec3 coordZ=vec3(vUV.x,vUV.y,layer);float voxelZ=texture(voxelZaxisSampler,coordZ).r;vec3 coordX=vec3(1.0-layer,vUV.y,vUV.x);float voxelX=texture(voxelXaxisSampler,coordX).r;vec3 coordY=vec3(layer,vUV.x,vUV.y);float voxelY=texture(voxelYaxisSampler,coordY).r;float voxel=(voxelX>0.0 || voxelY>0.0 || voxelZ>0.0) ? 1.0 : 0.0;glFragColor=vec4(vec3(voxel),1.0);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},99638:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblGenerateVoxelMipPixelShader:()=>n});const r="iblGenerateVoxelMipPixelShader",s="precision highp float;precision highp sampler3D;varying vec2 vUV;uniform sampler3D srcMip;uniform int layerNum;void main(void) {ivec3 Coords=ivec3(2)*ivec3(gl_FragCoord.x,gl_FragCoord.y,layerNum);uint tex =\nuint(texelFetch(srcMip,Coords+ivec3(0,0,0),0).x>0.0f ? 1u : 0u)\n<< 0u |\nuint(texelFetch(srcMip,Coords+ivec3(1,0,0),0).x>0.0f ? 1u : 0u)\n<< 1u |\nuint(texelFetch(srcMip,Coords+ivec3(0,1,0),0).x>0.0f ? 1u : 0u)\n<< 2u |\nuint(texelFetch(srcMip,Coords+ivec3(1,1,0),0).x>0.0f ? 1u : 0u)\n<< 3u |\nuint(texelFetch(srcMip,Coords+ivec3(0,0,1),0).x>0.0f ? 1u : 0u)\n<< 4u |\nuint(texelFetch(srcMip,Coords+ivec3(1,0,1),0).x>0.0f ? 1u : 0u)\n<< 5u |\nuint(texelFetch(srcMip,Coords+ivec3(0,1,1),0).x>0.0f ? 1u : 0u)\n<< 6u |\nuint(texelFetch(srcMip,Coords+ivec3(1,1,1),0).x>0.0f ? 1u : 0u)\n<< 7u;glFragColor.rgb=vec3(float(tex)/255.0f,0.0f,0.0f);glFragColor.a=1.0;}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},17864:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowAccumulationPixelShader:()=>n});const r="iblShadowAccumulationPixelShader",s="#ifdef GL_ES\nprecision mediump float;\n#endif\nvarying vec2 vUV;uniform vec4 accumulationParameters;\n#define remanence accumulationParameters.x\n#define resetb accumulationParameters.y\n#define sceneSize accumulationParameters.z\nuniform sampler2D motionSampler;uniform sampler2D positionSampler;uniform sampler2D spatialBlurSampler;uniform sampler2D oldAccumulationSampler;uniform sampler2D prevPositionSampler;vec2 max2(vec2 v,vec2 w) { return vec2(max(v.x,w.x),max(v.y,w.y)); }\nvoid main(void) {bool reset=bool(resetb);vec2 gbufferRes=vec2(textureSize(motionSampler,0));ivec2 gbufferPixelCoord=ivec2(vUV*gbufferRes);vec2 shadowRes=vec2(textureSize(spatialBlurSampler,0));ivec2 shadowPixelCoord=ivec2(vUV*shadowRes);vec4 LP=texelFetch(positionSampler,gbufferPixelCoord,0);if (0.0==LP.w) {gl_FragColor=vec4(1.0,0.0,0.0,1.0);return;}\nvec2 velocityColor=texelFetch(motionSampler,gbufferPixelCoord,0).xy;vec2 prevCoord=vUV+velocityColor;vec3 PrevLP=texture(prevPositionSampler,prevCoord).xyz;vec3 PrevShadows=texture(oldAccumulationSampler,prevCoord).xyz;vec2 newShadows=texelFetch(spatialBlurSampler,shadowPixelCoord,0).xy;PrevShadows.z =\n!reset && all(lessThan(abs(prevCoord-vec2(0.5)),vec2(0.5))) &&\ndistance(LP.xyz,PrevLP)<5e-2*sceneSize\n? max(PrevShadows.z/(1.0+PrevShadows.z),1.0-remanence)\n: 1.0;PrevShadows=max(vec3(0.0),PrevShadows);gl_FragColor =\nvec4(mix(PrevShadows.x,newShadows.x,PrevShadows.z),\nmix(PrevShadows.y,newShadows.y,PrevShadows.z),PrevShadows.z,1.0);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},73588:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowDebugPixelShader:()=>n});const r="iblShadowDebugPixelShader",s="#ifdef GL_ES\nprecision mediump float;\n#endif\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D debugSampler;uniform vec4 sizeParams;\n#define offsetX sizeParams.x\n#define offsetY sizeParams.y\n#define widthScale sizeParams.z\n#define heightScale sizeParams.w\nvoid main(void) {vec2 uv =\nvec2((offsetX+vUV.x)*widthScale,(offsetY+vUV.y)*heightScale);vec4 background=texture2D(textureSampler,vUV);vec4 debugColour=texture2D(debugSampler,vUV);if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {gl_FragColor.rgba=background;} else {gl_FragColor.rgb=mix(debugColour.rgb,background.rgb,0.0);gl_FragColor.a=1.0;}}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},64367:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowGBufferDebugPixelShader:()=>n});const r="iblShadowGBufferDebugPixelShader",s="#ifdef GL_ES\nprecision mediump float;\n#endif\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform sampler2D positionSampler;uniform sampler2D velocitySampler;uniform vec4 sizeParams;uniform float maxDepth;\n#define offsetX sizeParams.x\n#define offsetY sizeParams.y\n#define widthScale sizeParams.z\n#define heightScale sizeParams.w\nvoid main(void) {vec2 uv =\nvec2((offsetX+vUV.x)*widthScale,(offsetY+vUV.y)*heightScale);vec4 backgroundColour=texture2D(textureSampler,vUV).rgba;vec4 depth=texture2D(depthSampler,vUV);vec4 worldNormal=texture2D(normalSampler,vUV);vec4 worldPosition=texture2D(positionSampler,vUV);vec4 velocityLinear=texture2D(velocitySampler,vUV);if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {gl_FragColor.rgba=backgroundColour;} else {gl_FragColor.a=1.0;if (uv.x<=0.25) {gl_FragColor.rgb=depth.rgb;gl_FragColor.a=1.0;} else if (uv.x<=0.5) {velocityLinear.rg=velocityLinear.rg*0.5+0.5;gl_FragColor.rgb=velocityLinear.rgb;} else if (uv.x<=0.75) {gl_FragColor.rgb=worldPosition.rgb;} else {gl_FragColor.rgb=worldNormal.rgb;}}}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},80018:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowSpatialBlurPixelShader:()=>n});const r="iblShadowSpatialBlurPixelShader",s="precision highp sampler2D;\n#define PI 3.1415927\nvarying vec2 vUV;uniform sampler2D depthSampler;uniform sampler2D worldNormalSampler;uniform sampler2D voxelTracingSampler;uniform vec4 blurParameters;\n#define stridef blurParameters.x\n#define worldScale blurParameters.y\nconst float weights[5]=float[5](0.0625,0.25,0.375,0.25,0.0625);const int nbWeights=5;vec2 max2(vec2 v,vec2 w) {return vec2(max(v.x,w.x),max(v.y,w.y));}\nvoid main(void)\n{vec2 gbufferRes=vec2(textureSize(depthSampler,0));ivec2 gbufferPixelCoord=ivec2(vUV*gbufferRes);vec2 shadowRes=vec2(textureSize(voxelTracingSampler,0));ivec2 shadowPixelCoord=ivec2(vUV*shadowRes);vec3 N=texelFetch(worldNormalSampler,gbufferPixelCoord,0).xyz;if (length(N)<0.01) {glFragColor=vec4(1.0,1.0,0.0,1.0);return;}\nfloat depth=-texelFetch(depthSampler,gbufferPixelCoord,0).x;vec3 X=vec3(0.0);for(int y=0; y>1),y-(nbWeights>>1));ivec2 shadowCoords=shadowPixelCoord+int(stridef)*ivec2(x-(nbWeights>>1),y-(nbWeights>>1));vec2 T=texelFetch(voxelTracingSampler,shadowCoords,0).xy;float ddepth=-texelFetch(depthSampler,gBufferCoords,0).x-depth;vec3 dN=texelFetch(worldNormalSampler,gBufferCoords,0).xyz-N;float w=weights[x]*weights[y] *\nexp2(max(-1000.0/(worldScale*worldScale),-0.5) *\n(ddepth*ddepth) -\n1e1*dot(dN,dN));X+=vec3(w*T.x,w*T.y,w);}}\ngl_FragColor=vec4(X.x/X.z,X.y/X.z,1.0,1.0);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},74747:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowVoxelTracingPixelShader:()=>n});const r="iblShadowVoxelTracingPixelShader",s="precision highp sampler2D;precision highp sampler3D;\n#define PI 3.1415927\nvarying vec2 vUV;\n#define DISABLE_UNIFORMITY_ANALYSIS\nuniform sampler2D depthSampler;uniform sampler2D worldNormalSampler;uniform sampler2D blueNoiseSampler;uniform sampler2D icdfxSampler;uniform sampler2D icdfySampler;uniform sampler3D voxelGridSampler;uniform vec4 shadowParameters;\n#define SHADOWdirs shadowParameters.x\n#define SHADOWframe shadowParameters.y\n#define SHADOWenvRot shadowParameters.w\nuniform vec4 voxelBiasParameters;\n#define highestMipLevel voxelBiasParameters.z\nuniform vec4 sssParameters;\n#define SSSsamples sssParameters.x\n#define SSSstride sssParameters.y\n#define SSSmaxDistance sssParameters.z\n#define SSSthickness sssParameters.w\nuniform vec4 shadowOpacity;uniform mat4 projMtx;uniform mat4 viewMtx;uniform mat4 invProjMtx;uniform mat4 invViewMtx;uniform mat4 wsNormalizationMtx;uniform mat4 invVPMtx;\n#define PI 3.1415927\n#define GOLD 0.618034\nstruct AABB3f {vec3 m_min;vec3 m_max;};struct Ray {vec3 orig;vec3 dir;vec3 dir_rcp;float t_min;float t_max;};Ray make_ray(const vec3 origin,const vec3 direction,const float tmin,\nconst float tmax) {Ray ray;ray.orig=origin;ray.dir=direction;ray.dir_rcp=1.0f/direction;ray.t_min=tmin;ray.t_max=tmax;return ray;}\nbool ray_box_intersection(const in AABB3f aabb,const in Ray ray,\nout float distance_near,out float distance_far) {vec3 tbot=ray.dir_rcp*(aabb.m_min-ray.orig);vec3 ttop=ray.dir_rcp*(aabb.m_max-ray.orig);vec3 tmin=min(ttop,tbot);vec3 tmax=max(ttop,tbot);distance_near=max(ray.t_min,max(tmin.x,max(tmin.y,tmin.z)));distance_far=min(ray.t_max,min(tmax.x,min(tmax.y,tmax.z)));return distance_near<=distance_far;}\n#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nstruct VoxelMarchDiagnosticInfo {float heat;ivec3 voxel_intersect_coords;};\n#endif\nuint hash(uint i) {i ^= i>>16u;i*=0x7FEB352Du;i ^= i>>15u;i*=0x846CA68Bu;i ^= i>>16u;return i;}\nfloat uint2float(uint i) {return uintBitsToFloat(0x3F800000u | (i>>9u))-1.0;}\nvec3 uv_to_normal(vec2 uv) {vec3 N;vec2 uvRange=uv;float theta=uvRange.x*2.0*PI;float phi=uvRange.y*PI;N.x=cos(theta)*sin(phi);N.z=sin(theta)*sin(phi);N.y=cos(phi);return N;}\nvec2 plasticSequence(const uint rstate) {return vec2(uint2float(rstate*3242174889u),\nuint2float(rstate*2447445414u));}\nfloat goldenSequence(const uint rstate) {return uint2float(rstate*2654435769u);}\nfloat distanceSquared(vec2 a,vec2 b) {vec2 diff=a-b;return dot(diff,diff);}\nvoid genTB(const vec3 N,out vec3 T,out vec3 B) {float s=N.z<0.0 ? -1.0 : 1.0;float a=-1.0/(s+N.z);float b=N.x*N.y*a;T=vec3(1.0+s*N.x*N.x*a,s*b,-s*N.x);B=vec3(b,s+N.y*N.y*a,-N.y);}\nint stack[24]; \n#define PUSH(i) stack[stackLevel++]=i; \n#define POP() stack[--stackLevel] \n#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nbool anyHitVoxels(const Ray ray_vs,\nout VoxelMarchDiagnosticInfo voxel_march_diagnostic_info) {\n#else\nbool anyHitVoxels(const Ray ray_vs) {\n#endif\nvec3 invD=ray_vs.dir_rcp;vec3 D=ray_vs.dir;vec3 O=ray_vs.orig;ivec3 negD=ivec3(lessThan(D,vec3(0,0,0)));int voxel0=negD.x | negD.y<<1 | negD.z<<2;vec3 t0=-O*invD,t1=(vec3(1.0)-O)*invD;int maxLod=int(highestMipLevel);int stackLevel=0;\n#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nuint steps=0u;\n#endif\nPUSH(maxLod<<24);while (stackLevel>0) {int elem=POP();ivec4 Coords =\nivec4(elem & 0xFF,elem>>8 & 0xFF,elem>>16 & 0xFF,elem>>24);if (Coords.w==0) {\n#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nvoxel_march_diagnostic_info.heat=float(steps)/24.0;\n#endif\nreturn true;}\n#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\n++steps;\n#endif\nfloat invRes=exp2(float(Coords.w-maxLod));vec3 bbmin=invRes*vec3(Coords.xyz+negD);vec3 bbmax=invRes*vec3(Coords.xyz-negD+ivec3(1));vec3 mint=mix(t0,t1,bbmin);vec3 maxt=mix(t0,t1,bbmax);vec3 midt=0.5*(mint+maxt);mint.x=max(0.0,mint.x);midt.x=max(0.0,midt.x);int nodeMask=int(\nround(texelFetch(voxelGridSampler,Coords.xyz,Coords.w).x*255.0));Coords.w--;int voxelBit=voxel0;Coords.xyz=(Coords.xyz<<1)+negD;int packedCoords =\nCoords.x | Coords.y<<8 | Coords.z<<16 | Coords.w<<24;if (max(mint.x,max(mint.y,mint.z))0.0 && stepCountedge_tint_const) {vec4 VP2=VP;VP2.y*=-1.0;vec4 unormWP=invViewMtx*VP2;vec3 WP=(wsNormalizationMtx*unormWP).xyz;vec2 vxNoise =\nvec2(uint2float(hash(dirId*2u)),uint2float(hash(dirId*2u+1u)));\n#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nVoxelMarchDiagnosticInfo voxel_march_diagnostic_info;opacity=max(opacity,\nshadowOpacity.x*voxelShadow(WP,L.xyz,N,vxNoise,\nvoxel_march_diagnostic_info));heat+=voxel_march_diagnostic_info.heat;\n#else\nopacity =\nmax(opacity,shadowOpacity.x*voxelShadow(WP,L.xyz,N,vxNoise));\n#endif\nvec3 VL=(viewMtx*L).xyz;\n#ifdef RIGHT_HANDED\nfloat nearPlaneZ=-projMtx[3][2]/(projMtx[2][2]-1.0); \nfloat farPlaneZ=-projMtx[3][2]/(projMtx[2][2]+1.0);\n#else\nfloat nearPlaneZ=-projMtx[3][2]/(projMtx[2][2]+1.0); \nfloat farPlaneZ=-projMtx[3][2]/(projMtx[2][2]-1.0);\n#endif\nfloat ssShadow=shadowOpacity.y *\nscreenSpaceShadow(VP2.xyz,VL,Resolution,nearPlaneZ,farPlaneZ,\nabs(2.0*noise.z-1.0));opacity=max(opacity,ssShadow);shadowAccum+=min(1.0-opacity,cosNL);sampleWeight+=cosNL;vec3 VR=-(viewMtx*vec4(reflect(-L.xyz,N),0.0)).xyz;specShadowAccum+=max(1.0-(opacity*pow(VR.z,8.0)),0.0);}\nnoise.z=fract(noise.z+GOLD);}\n#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\ngl_FragColor=vec4(shadowAccum/float(sampleWeight),\nspecShadowAccum/float(sampleWeight),heat/float(sampleWeight),1.0);\n#else\ngl_FragColor=vec4(shadowAccum/float(sampleWeight),specShadowAccum/float(sampleWeight),0.0,1.0);\n#endif\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},47473:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowsCdfxPixelShader:()=>n});const r="iblShadowsCdfxPixelShader",s="precision highp sampler2D;\n#define PI 3.1415927\nvarying vec2 vUV;uniform sampler2D cdfy;void main(void) {ivec2 cdfyRes=textureSize(cdfy,0);ivec2 currentPixel=ivec2(gl_FragCoord.xy);float cdfx=0.0;for (int x=1; x<=currentPixel.x; x++) {cdfx+=texelFetch(cdfy,ivec2(x-1,cdfyRes.y-1),0).x;}\ngl_FragColor=vec4(vec3(cdfx),1.0);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},98824:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowsCdfyPixelShader:()=>n});const r="iblShadowsCdfyPixelShader",s="precision highp sampler2D;precision highp samplerCube;\n#define PI 3.1415927\nvarying vec2 vUV;\n#ifdef IBL_USE_CUBE_MAP\nuniform samplerCube iblSource;\n#else\nuniform sampler2D iblSource;\n#endif\nuniform int iblHeight;\n#ifdef IBL_USE_CUBE_MAP\nvec3 equirectangularToCubemapDirection(vec2 uv) {float longitude=uv.x*2.0*PI-PI;float latitude=PI*0.5-uv.y*PI;vec3 direction;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;}\nfloat fetchCube(vec2 uv) {vec3 direction=equirectangularToCubemapDirection(uv);return sin(PI*uv.y)*dot(textureCubeLodEXT(iblSource,direction,0.0).rgb,\nvec3(0.3,0.6,0.1));}\n#else\nfloat fetchPanoramic(ivec2 Coords,float envmapHeight) {return sin(PI*(float(Coords.y)+0.5)/envmapHeight) *\ndot(texelFetch(iblSource,Coords,0).rgb,vec3(0.3,0.6,0.1));}\n#endif\nvoid main(void) {ivec2 coords=ivec2(gl_FragCoord.x,gl_FragCoord.y);float cdfy=0.0;for (int y=1; y<=coords.y; y++) {\n#ifdef IBL_USE_CUBE_MAP\nvec2 uv=vec2(vUV.x,(float(y-1)+0.5)/float(iblHeight));cdfy+=fetchCube(uv);\n#else\ncdfy+=fetchPanoramic(ivec2(coords.x,y-1),float(iblHeight));\n#endif\n}\ngl_FragColor=vec4(cdfy,0.0,0.0,1.0);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},8970:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowsIcdfxPixelShader:()=>n});const r="iblShadowsIcdfxPixelShader",s="precision highp sampler2D;\n#define PI 3.1415927\nvarying vec2 vUV;uniform sampler2D cdfx;float fetchCDF(int x) {return texelFetch(cdfx,ivec2(x,0),0).x;}\nfloat bisect(int size,float targetValue)\n{int a=0,b=size-1;while (b-a>1) {int c=a+b>>1;if (fetchCDF(c){"use strict";i.r(t),i.d(t,{iblShadowsIcdfyPixelShader:()=>n});const r="iblShadowsIcdfyPixelShader",s="precision highp sampler2D;\n#define PI 3.1415927\nvarying vec2 vUV;uniform sampler2D cdfy;float fetchCDF(int y,int invocationId) {return texelFetch(cdfy,ivec2(invocationId,y),0).x;}\nfloat bisect(int size,float targetValue,int invocationId)\n{int a=0,b=size-1;while (b-a>1) {int c=a+b>>1;if (fetchCDF(c,invocationId){"use strict";i.r(t),i.d(t,{iblShadowsImportanceSamplingDebugPixelShader:()=>n});const r="iblShadowsImportanceSamplingDebugPixelShader",s="precision highp samplerCube;\n#define PI 3.1415927\nvarying vec2 vUV;uniform sampler2D cdfy;uniform sampler2D icdfy;uniform sampler2D cdfx;uniform sampler2D icdfx;\n#ifdef IBL_USE_CUBE_MAP\nuniform samplerCube iblSource;\n#else\nuniform sampler2D iblSource;\n#endif\nuniform sampler2D textureSampler;\n#define cdfyVSize 0.4\n#define cdfxVSize 0.1\n#define cdfyHSize 0.5\nuniform vec4 sizeParams;\n#define offsetX sizeParams.x\n#define offsetY sizeParams.y\n#define widthScale sizeParams.z\n#define heightScale sizeParams.w\n#ifdef IBL_USE_CUBE_MAP\nvec3 equirectangularToCubemapDirection(vec2 uv) {float longitude=uv.x*2.0*PI-PI;float latitude=PI*0.5-uv.y*PI;vec3 direction;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;}\n#endif\nvoid main(void) {vec3 colour=vec3(0.0);vec2 uv =\nvec2((offsetX+vUV.x)*widthScale,(offsetY+vUV.y)*heightScale);vec3 backgroundColour=texture2D(textureSampler,vUV).rgb;const float iblStart=1.0-cdfyVSize;const float cdfyStart=1.0-2.0*cdfyVSize;const float cdfxStart=1.0-2.0*cdfyVSize-cdfxVSize;const float icdfxStart=1.0-2.0*cdfyVSize-2.0*cdfxVSize;\n#ifdef IBL_USE_CUBE_MAP\nvec3 direction=equirectangularToCubemapDirection(\n(uv-vec2(0.0,iblStart))*vec2(1.0,1.0/cdfyVSize));vec3 iblColour=textureCubeLodEXT(iblSource,direction,0.0).rgb;\n#else\nvec3 iblColour=texture2D(iblSource,(uv-vec2(0.0,iblStart)) *\nvec2(1.0,1.0/cdfyVSize))\n.rgb;\n#endif\nfloat cdfyColour =\ntexture2D(cdfy,(uv-vec2(0.0,cdfyStart))*vec2(2.0,1.0/cdfyVSize))\n.r;float icdfyColour =\ntexture2D(icdfy,(uv-vec2(0.5,cdfyStart))*vec2(2.0,1.0/cdfyVSize))\n.r;float cdfxColour =\ntexture2D(cdfx,(uv-vec2(0.0,cdfxStart))*vec2(1.0,1.0/cdfxVSize))\n.r;float icdfxColour=texture2D(icdfx,(uv-vec2(0.0,icdfxStart)) *\nvec2(1.0,1.0/cdfxVSize))\n.r;if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {colour=backgroundColour;} else if (uv.y>iblStart) {colour+=iblColour;} else if (uv.y>cdfyStart && uv.x<0.5) {colour.r+=0.003*cdfyColour;} else if (uv.y>cdfyStart && uv.x>0.5) {colour.r+=icdfyColour;} else if (uv.y>cdfxStart) {colour.r+=0.00003*cdfxColour;} else if (uv.y>icdfxStart) {colour.r+=icdfxColour;}\ngl_FragColor=vec4(colour,1.0);glFragColor.rgb=mix(gl_FragColor.rgb,backgroundColour,0.5);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},83145:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblVoxelGridPixelShader:()=>n});const r="iblVoxelGridPixelShader",s="precision highp float;layout(location=0) out highp float glFragData[MAX_DRAW_BUFFERS];varying vec3 vNormalizedPosition;uniform float nearPlane;uniform float farPlane;uniform float stepSize;void main(void) {vec3 normPos=vNormalizedPosition.xyz;if (normPos.zfarPlane) {discard;}\nglFragData[0]=normPos.z=nearPlane+stepSize && normPos.z=nearPlane+2.0*stepSize && normPos.z=nearPlane+3.0*stepSize && normPos.z4\nglFragData[4]=normPos.z>=nearPlane+4.0*stepSize && normPos.z=nearPlane+5.0*stepSize && normPos.z=nearPlane+6.0*stepSize && normPos.z=nearPlane+7.0*stepSize && normPos.z{"use strict";i.r(t),i.d(t,{iblVoxelGridVertexShader:()=>n});const r="iblVoxelGridVertexShader",s="attribute vec3 position;attribute vec3 normal;varying vec3 vNormalizedPosition;uniform mat4 world;uniform mat4 invWorldScale;uniform mat4 viewMatrix;void main(void) {gl_Position=viewMatrix*invWorldScale*world*vec4(position,1.);vNormalizedPosition.xyz=gl_Position.xyz*0.5+0.5;\n#ifdef IS_NDC_HALF_ZRANGE\ngl_Position.z=gl_Position.z*0.5+0.5;\n#endif\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},68859:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblVoxelGrid2dArrayDebugPixelShader:()=>n});const r="iblVoxelGrid2dArrayDebugPixelShader",s="precision highp sampler2DArray;varying vec2 vUV;uniform sampler2DArray voxelTexture;uniform sampler2D textureSampler;uniform int slice;void main(void) {ivec3 size=textureSize(voxelTexture,0);float dimension=sqrt(float(size.z));vec2 samplePos=fract(vUV.xy*vec2(dimension));int sampleIndex=int(floor(vUV.x*float(dimension))+floor(vUV.y*float(dimension))*dimension);glFragColor.rgb=texture(voxelTexture,vec3(samplePos.xy,sampleIndex)).rrr;glFragColor.a=1.0;glFragColor.rgb+=texture(textureSampler,vUV.xy).rgb;}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},95171:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblVoxelGrid3dDebugPixelShader:()=>n});const r="iblVoxelGrid3dDebugPixelShader",s="precision highp sampler3D;varying vec2 vUV;uniform sampler3D voxelTexture;uniform sampler2D voxelSlabTexture;uniform sampler2D textureSampler;uniform vec4 sizeParams;\n#define offsetX sizeParams.x\n#define offsetY sizeParams.y\n#define widthScale sizeParams.z\n#define heightScale sizeParams.w\nuniform float mipNumber;void main(void) {vec2 uv =\nvec2((offsetX+vUV.x)*widthScale,(offsetY+vUV.y)*heightScale);vec4 background=texture2D(textureSampler,vUV);vec4 voxelSlab=texture2D(voxelSlabTexture,vUV);ivec3 size=textureSize(voxelTexture,int(mipNumber));float dimension=ceil(sqrt(float(size.z)));vec2 samplePos=fract(uv.xy*vec2(dimension));int sampleIndex=int(floor(uv.x*float(dimension)) +\nfloor(uv.y*float(dimension))*dimension);float mip_separator=0.0;if (samplePos.x<0.01 || samplePos.y<0.01) {mip_separator=1.0;}\nbool outBounds=sampleIndex>size.z-1 ? true : false;sampleIndex=clamp(sampleIndex,0,size.z-1);ivec2 samplePosInt=ivec2(samplePos.xy*vec2(size.xy));vec3 voxel=texelFetch(voxelTexture,\nivec3(samplePosInt.x,samplePosInt.y,sampleIndex),\nint(mipNumber))\n.rgb;if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {gl_FragColor.rgba=background;} else {if (outBounds) {voxel=vec3(0.15,0.0,0.0);} else {if (voxel.r>0.001) {voxel.g=1.0;}\nvoxel.r+=mip_separator;}\nglFragColor.rgb=mix(background.rgb,voxelSlab.rgb,voxelSlab.a)+voxel;glFragColor.a=1.0;}}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},81284:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblVoxelSlabDebugPixelShader:()=>n});const r="iblVoxelSlabDebugPixelShader",s="precision highp float;varying vec3 vNormalizedPosition;uniform float nearPlane;uniform float farPlane;uniform float stepSize;void main(void) {vec3 normPos=vNormalizedPosition.xyz;float chunkSize=stepSize*float(MAX_DRAW_BUFFERS);float numChunks=1.0/chunkSize;float positionInChunk=fract(normPos.z/chunkSize);float slab=floor(positionInChunk*float(MAX_DRAW_BUFFERS)) /\nfloat(MAX_DRAW_BUFFERS);if (normPos.x<0.0 || normPos.y<0.0 || normPos.z<0.0 ||\nnormPos.x>1.0 || normPos.y>1.0 || normPos.z>1.0) {gl_FragColor=vec4(0.0,0.0,0.0,0.0);} else {gl_FragColor=vec4(slab,0.0,0.0,0.75);}}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},71650:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblVoxelSlabDebugVertexShader:()=>n});const r="iblVoxelSlabDebugVertexShader",s="attribute vec3 position;varying vec3 vNormalizedPosition;uniform mat4 world;uniform mat4 invWorldScale;uniform mat4 cameraViewMatrix;uniform mat4 projection;uniform mat4 viewMatrix;void main(void) {vec4 worldPosition=(world*vec4(position,1.));gl_Position=projection*cameraViewMatrix*worldPosition;vNormalizedPosition=(viewMatrix*invWorldScale*worldPosition).rgb;vNormalizedPosition.xyz=vNormalizedPosition.xyz*vec3(0.5)+vec3(0.5);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},27220:(e,t,i)=>{"use strict";i.r(t),i.d(t,{imageProcessingPixelShader:()=>o});var r=i(69841);i(75651),i(94388),i(88658);const s="imageProcessingPixelShader",n="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},45245:(e,t,i)=>{"use strict";i.r(t),i.d(t,{kernelBlurPixelShader:()=>o});var r=i(69841);i(953),i(72693);r.l.IncludesShadersStore.kernelBlurFragment="#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif\n";r.l.IncludesShadersStore.kernelBlurFragment2="#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif\n";const s="kernelBlurPixelShader",n="uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; }\n#endif\n#include[0..varyingCount]\n#ifdef PACKEDFLOAT\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float computedWeight=0.0;\n#ifdef PACKEDFLOAT\nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include[0..varyingCount]\n#include[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},95527:(e,t,i)=>{"use strict";i.r(t),i.d(t,{kernelBlurVertexShader:()=>o});var r=i(69841);i(953);r.l.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";const s="kernelBlurVertexShader",n="attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter;\n#include[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nsampleCenter=(position*madd+madd);\n#include[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},59329:(e,t,i)=>{"use strict";i.r(t),i.d(t,{layerPixelShader:()=>o});var r=i(69841);i(94388);const s="layerPixelShader",n="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#if defined(CONVERT_TO_GAMMA)\nbaseColor.rgb=toGammaSpace(baseColor.rgb);\n#elif defined(CONVERT_TO_LINEAR)\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},11115:(e,t,i)=>{"use strict";i.r(t),i.d(t,{layerVertexShader:()=>n});const r="layerVertexShader",s="attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},54262:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lensFlarePixelShader:()=>n});const r="lensFlarePixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},45980:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lensFlareVertexShader:()=>n});const r="lensFlareVertexShader",s="attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},85550:(e,t,i)=>{"use strict";i.r(t),i.d(t,{linePixelShader:()=>o});var r=i(69841);i(77165),i(25012),i(6922),i(89797);const s="linePixelShader",n="#include\nuniform vec4 color;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},42644:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lineVertexShader:()=>o});var r=i(69841);r.l.IncludesShadersStore.lineVertexDeclaration="uniform mat4 viewProjection;\n#define ADDITIONAL_VERTEX_DECLARATION\n",i(32405),i(13580);r.l.IncludesShadersStore.lineUboDeclaration="layout(std140,column_major) uniform;\n#include\n#include\n",i(56865),i(18355),i(25012),i(18411),i(71471),i(88336);const s="lineVertexShader",n="#include<__decl__lineVertex>\n#include\n#include\nattribute vec3 position;attribute vec4 normal;uniform float width;uniform float aspectRatio;\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\nmat4 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;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#include\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},46143:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lodPixelShader:()=>n});const r="lodPixelShader",s="#extension GL_EXT_shader_texture_lod : enable\nprecision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform sampler2D textureSampler;uniform float lod;uniform vec2 texSize;uniform int gamma;void main(void)\n{gl_FragColor=texture2DLodEXT(textureSampler,vUV,lod);if (gamma==0) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},47084:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lodCubePixelShader:()=>n});const r="lodCubePixelShader",s="precision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform samplerCube textureSampler;uniform float lod;uniform int gamma;void main(void)\n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x),lod);\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x),lod);\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x),lod);\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x),lod);\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001),lod);\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001),lod);\n#endif\nif (gamma==0) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},33287:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererPixelShader:()=>n});const r="meshUVSpaceRendererPixelShader",s="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;}\ngl_FragColor=texture2D(textureSampler,vDecalTC);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},82017:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererVertexShader:()=>o});var r=i(69841);i(39948),i(66682),i(9158),i(11783),i(56865),i(99216),i(44219),i(18411),i(78792),i(95532);const s="meshUVSpaceRendererVertexShader",n="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nvoid main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW;\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvNormalW=normalize(normWorldSM*normalUpdated);\n#endif\nvec3 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);}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},33534:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererFinaliserPixelShader:()=>n});const r="meshUVSpaceRendererFinaliserPixelShader",s="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;}\nif (mask_p21>0.5) {col+=texture2D(textureSampler,uv_p21);total_weight+=1.0;}\nif (mask_p10>0.5) {col+=texture2D(textureSampler,uv_p10);total_weight+=1.0;}\nif (mask_p12>0.5) {col+=texture2D(textureSampler,uv_p12);total_weight+=1.0;}\nif (total_weight>0.0) {gl_FragColor=col/total_weight;} else {gl_FragColor=col;}}}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},13460:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererFinaliserVertexShader:()=>n});const r="meshUVSpaceRendererFinaliserVertexShader",s="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;}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},99990:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererMaskerPixelShader:()=>n});const r="meshUVSpaceRendererMaskerPixelShader",s="varying vec2 vUV;void main(void) {gl_FragColor=vec4(1.0,1.0,1.0,1.0);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},96924:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererMaskerVertexShader:()=>n});const r="meshUVSpaceRendererMaskerVertexShader",s="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;}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},28377:(e,t,i)=>{"use strict";i.r(t),i.d(t,{motionBlurPixelShader:()=>n});const r="motionBlurPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize;\n#ifdef OBJECT_BASED\nuniform sampler2D velocitySampler;\n#else\nuniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#ifdef GEOMETRY_SUPPORTED\n#ifdef OBJECT_BASED\nvec2 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)\nbreak;vec2 offset=vUV+velocity*(hlim+float(i));\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset,0.0);\n#else\nresult+=texture2D(textureSampler,offset);\n#endif\n}\ngl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0;\n#else\nvec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; \nvec4 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)\nbreak;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset1,0.0);\n#else\nresult+=texture2D(textureSampler,offset1);\n#endif\n}\ngl_FragColor=result/float(nSamples);\n#endif\n#else\ngl_FragColor=texture2D(textureSampler,vUV);\n#endif\n}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},17738:(e,t,i)=>{"use strict";i.r(t),i.d(t,{oitBackBlendPixelShader:()=>n});const r="oitBackBlendPixelShader",s="precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { \ndiscard;}}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},4172:(e,t,i)=>{"use strict";i.r(t),i.d(t,{oitFinalPixelShader:()=>n});const r="oitFinalPixelShader",s="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(\nfrontColor.rgb+alphaMultiplier*backColor.rgb,\nfrontColor.a+backColor.a\n);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},32192:(e,t,i)=>{"use strict";i.r(t),i.d(t,{outlinePixelShader:()=>o});var r=i(69841);i(77165),i(25012),i(89797),i(6922);const s="outlinePixelShader",n="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},65038:(e,t,i)=>{"use strict";i.r(t),i.d(t,{outlineVertexShader:()=>o});var r=i(69841);i(39948),i(66682),i(9158),i(11783),i(18355),i(56865),i(25012),i(99216),i(44219),i(18411),i(78792),i(95532),i(71471),i(88336);const s="outlineVertexShader",n="attribute vec3 position;attribute vec3 normal;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform float offset;\n#include\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\nvec3 offsetPosition=positionUpdated+(normalUpdated*offset);\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n#include\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},50619:(e,t,i)=>{"use strict";i.r(t),i.d(t,{particlesPixelShader:()=>o});var r=i(69841);i(77165),i(75651),i(25012),i(94388),i(88658),i(64657),i(89797),i(6922),i(27185);const s="particlesPixelShader",n="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nvarying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler;\n#include\n#include\n#include\n#include\n#include\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;uniform sampler2D rampSampler;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat 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);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n#include\n#include(color,baseColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},70917:(e,t,i)=>{"use strict";i.r(t),i.d(t,{particlesVertexShader:()=>o});var r=i(69841);i(18355),i(77735),i(25012),i(71471),i(90715),i(88336);const s="particlesVertexShader",n="attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD\nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;\n#ifdef ANIMATESHEET\nuniform vec3 particlesInfos; \n#endif\nvarying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include\n#include\n#include\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 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;}\n#ifdef BILLBOARDSTRETCHED\nvec3 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);\n#ifdef BILLBOARDSTRETCHED_LOCAL\nvec3 row1=direction;\n#else\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\n#endif\nmat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;}\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size;\n#ifdef BILLBOARD\nvec3 rotatedCorner;\n#ifdef BILLBOARDY\nrotatedCorner.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;\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.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;\n#else\nrotatedCorner.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;\n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\ngl_Position=projection*vec4(viewPos,1.0);\n#else\nvec3 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);\n#endif\nvColor=color;\n#ifdef ANIMATESHEET\nfloat 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;\n#else\nvUV=offset;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},30927:(e,t,i)=>{"use strict";i.r(t),i.d(t,{passPixelShader:()=>n});const r="passPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},88412:(e,t,i)=>{"use strict";i.r(t),i.d(t,{passCubePixelShader:()=>n});const r="passCubePixelShader",s="varying vec2 vUV;uniform samplerCube textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\n#endif\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},43004:(e,t,i)=>{"use strict";i.r(t),i.d(t,{pbrPixelShader:()=>o});var r=i(69841);i(59317),i(36881),i(14774);r.l.IncludesShadersStore.pbrFragmentDeclaration="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;\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REALTIME_FILTERING\nuniform vec2 vReflectionFilteringInfo;\n#endif\nuniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; \n#endif\n#endif\n#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)\nuniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; \n#endif\n#ifdef CLEARCOAT\nuniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams;\n#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\n#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\n#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\n#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT\nuniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance;\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix;\n#endif\n#endif\n#endif\n#ifdef IRIDESCENCE\nuniform vec4 vIridescenceParams;\n#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\n#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\n#endif\n#endif\n#ifdef ANISOTROPIC\nuniform vec3 vAnisotropy;\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix;\n#endif\n#endif\n#ifdef SHEEN\nuniform vec4 vSheenColor;\n#ifdef SHEEN_ROUGHNESS\nuniform float vSheenRoughness;\n#endif\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\n#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\n#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\n#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix;\n#ifdef REALTIME_FILTERING\nuniform vec2 vRefractionFilteringInfo;\n#endif\n#ifdef SS_DISPERSION\nuniform float dispersion;\n#endif\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix;\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix;\n#endif\nuniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity;uniform vec4 vTranslucencyColor;\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\nuniform vec2 vTranslucencyColorInfos;uniform mat4 translucencyColorMatrix;\n#endif\n#endif\n#ifdef PREPASS\n#ifdef SS_SCATTERING\nuniform float scatteringDiffusionProfile;\n#endif\n#endif\n#if DEBUGMODE>0\nuniform vec2 vDebugMode;\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform 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;\n#else\nuniform 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;\n#endif\n#endif\n#define ADDITIONAL_FRAGMENT_DECLARATION\n",i(42413),i(40371);r.l.IncludesShadersStore.pbrFragmentExtraDeclaration="varying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#include[1..7]\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n",i(23133),i(58769),i(5301);r.l.IncludesShadersStore.samplerFragmentAlternateDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying vec2 v_VARYINGNAME_UV;\n#endif\n#endif\n";r.l.IncludesShadersStore.pbrFragmentSamplersDeclaration="#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform sampler2D clearCoatRoughnessSampler;\n#endif\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform sampler2D sheenRoughnessSampler;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform samplerCube irradianceSampler;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform sampler2D irradianceSampler;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#ifdef SS_REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh;\n#endif\n#endif\n#endif\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_SAMPLERNAME_,translucencyColor)\n#endif\n",i(75651),i(77165),i(25012),i(64657),i(94388),i(34001),i(71826);r.l.IncludesShadersStore.pbrHelperFunctions="#define MINIMUMVARIANCE 0.0005\nfloat convertRoughnessToAverageSlope(float roughness)\n{return square(roughness)+MINIMUMVARIANCE;}\nfloat fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;}\nvec2 getAARoughnessFactors(vec3 normalVector) {\n#ifdef SPECULARAA\nvec3 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);\n#else\nreturn vec2(0.);\n#endif\n}\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_LEGACY\nvec2 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);}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection;if (anisotropy>=0.0) {anisotropicFrameDirection=B;} else {anisotropicFrameDirection=T;}\nvec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;}\n#else\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);}\nvec3 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;}\n#endif\n#endif\n#if defined(CLEARCOAT) || defined(SS_REFRACTION)\nvec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);}\nvec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));}\nvec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;}\nvec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0),\ncocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),\nclearCoatIntensity);return clearCoatAbsorption;}\n#endif\n#ifdef MICROSURFACEAUTOMATIC\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;}\n#endif\n",i(88658),i(34091),i(10316);r.l.IncludesShadersStore.pbrDirectLightingSetupFunctions="struct preLightingInfo\n{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness;\n#ifdef IRIDESCENCE\nfloat iridescenceIntensity;\n#endif\n};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N,vec3 posW) {preLightingInfo result;result.lightOffset=lightData.xyz-posW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\npreLightingInfo 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;}\npreLightingInfo 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;\n#ifdef SPECULARTERM\nresult.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));\n#endif\nreturn result;}";r.l.IncludesShadersStore.pbrDirectLightingFalloffFunctions="float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{return max(0.,1.0-length(lightOffset)/range);}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{return 1.0/maxEps(lightDistanceSquared);}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle)\n{falloff=max(0.,pow(cosAngle,exponent));}\nreturn falloff;}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}",i(67350),i(98392);r.l.IncludesShadersStore.pbrDirectLightingFunctions="#define CLEARCOATREFLECTANCE90 1.0\nstruct lightingInfo\n{vec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef CLEARCOAT\nvec4 clearCoat;\n#endif\n#ifdef SHEEN\nvec3 sheen;\n#endif\n};float adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) {\n#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\nfloat lightRoughness=lightRadius/lightDistance;float totalRoughness=saturate(lightRoughness+roughness);return totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nvec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {return mix(groundColor,lightColor,info.NdotL);}\nvec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {float diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;}\n#define inline\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix,vec3 posW){vec4 strq=textureProjectionMatrix*vec4(posW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return toLinearSpace(textureColor);}\n#ifdef SS_TRANSLUCENCY\nvec3 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;}\n#endif\n#ifdef SPECULARTERM\nvec3 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);\n#ifdef IRIDESCENCE\nfresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);\n#endif\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\n#ifdef BRDF_V_HEIGHT_CORRELATED\nfloat smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG);\n#else\nfloat smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG);\n#endif\nvec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;}\n#endif\n#ifdef ANISOTROPIC\nvec3 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);\n#ifdef IRIDESCENCE\nfresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);\n#endif\nfloat 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;}\n#endif\n#ifdef CLEARCOAT\nvec4 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(\nclearCoatTerm*info.attenuation*NccdotL*lightColor,\n1.0-fresnel\n);}\nvec3 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;}\n#endif\n#ifdef SHEEN\nvec3 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\nfloat visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG);\n#else */\nfloat visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */\nfloat sheenTerm=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;}\n#endif\n";r.l.IncludesShadersStore.pbrIBLFunctions="#if defined(REFLECTION) || defined(SS_REFRACTION)\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;float lod=log2(microsurfaceAverageSlopeTexels);return lod;}\nfloat getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {float lod=log2(cubeMapDimensionPixels)*roughness;return lod;}\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION)\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {float temp=NdotVUnclamped+ambientOcclusion;return saturate(square(temp)-1.0+ambientOcclusion);}\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION)\nfloat 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);}\n#endif\n#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA)\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {float microsurfaceAverageSlope=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);}\n#endif\n",i(82267),i(29424),i(51068),i(22464);r.l.IncludesShadersStore.pbrBlockAlbedoOpacity="struct albedoOpacityOutParams\n{vec3 surfaceAlbedo;float alpha;};\n#define pbr_inline\nalbedoOpacityOutParams albedoOpacityBlock(\nin vec4 vAlbedoColor\n#ifdef ALBEDO\n,in vec4 albedoTexture\n,in vec2 albedoInfos\n#endif\n#ifdef OPACITY\n,in vec4 opacityMap\n,in vec2 vOpacityInfos\n#endif\n#ifdef DETAIL\n,in vec4 detailColor\n,in vec4 vDetailInfos\n#endif\n#ifdef DECAL\n,in vec4 decalColor\n,in vec4 vDecalInfos\n#endif \n)\n{albedoOpacityOutParams outParams;vec3 surfaceAlbedo=vAlbedoColor.rgb;float alpha=vAlbedoColor.a;\n#ifdef ALBEDO\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\n#ifdef GAMMAALBEDO\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\n#else\nsurfaceAlbedo*=albedoTexture.rgb;\n#endif\nsurfaceAlbedo*=albedoInfos.y;\n#endif\n#ifndef DECAL_AFTER_DETAIL\n#include\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nsurfaceAlbedo*=vColor.rgb;\n#endif\n#ifdef DETAIL\nfloat detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; \n#endif\n#ifdef DECAL_AFTER_DETAIL\n#include\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALBEDO\n#ifdef OPACITY\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST \n#if DEBUGMODE != 88\nif (alpha{"use strict";i.r(t),i.d(t,{pbrVertexShader:()=>o});var r=i(69841);i(81160);r.l.IncludesShadersStore.pbrVertexDeclaration="uniform mat4 view;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif \n#ifdef ALBEDO\nuniform mat4 albedoMatrix;uniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;uniform vec4 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;uniform mat4 reflectivityMatrix;\n#endif\n#ifdef METALLIC_REFLECTANCE\nuniform vec2 vMetallicReflectanceInfos;uniform mat4 metallicReflectanceMatrix;\n#endif\n#ifdef REFLECTANCE\nuniform vec2 vReflectanceInfos;uniform mat4 reflectanceMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;uniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;\n#endif\n#ifdef CLEARCOAT\n#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\n#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\n#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\n#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;uniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix;\n#endif\n#endif\n#ifdef IRIDESCENCE\n#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\n#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix;\n#endif\n#endif\n#ifdef SHEEN\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\n#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\n#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\n#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionInfos;uniform mat4 refractionMatrix;\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix;\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\nuniform vec2 vTranslucencyColorInfos;uniform mat4 translucencyColorMatrix;\n#endif\n#endif\n#ifdef NORMAL\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform 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;\n#else\nuniform 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;\n#endif\n#endif\n#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;uniform mat4 detailMatrix;\n#endif\n#include\n#define ADDITIONAL_VERTEX_DECLARATION\n",i(42413),i(9482),i(40371),i(94388),i(39948),i(66682),i(56865),i(57819),i(2251),i(10316),i(17727),i(18355),i(77735),i(96951),i(19215),i(9158),i(11783),i(25012),i(99216),i(44219),i(18411),i(78792),i(95532),i(85639),i(81448),i(84525),i(78595),i(71471),i(90715),i(2946),i(61374),i(88336);const s="pbrVertexShader",n="precision highp float;\n#include<__decl__pbrVertex>\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#include[2..7]\n#include[1..7]\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\n#include\n#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy)\n#endif\n#ifdef SUBSURFACE\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor)\n#endif\nvarying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include\n#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos);\n#ifdef PREPASS\n#include\n#endif\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector);\n#endif\n#endif\n#define CUSTOM_VERTEX_UPDATE_WORLDPOS\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#if DEBUGMODE>0\nvClipSpacePosition=gl_Position;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n#ifndef UV1\nvec2 uvUpdated=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uvUpdated;\n#endif\n#include[2..7]\n#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z)\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheenRoughness,_INFONAME_,SheenInfos.z)\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x)\n#endif\n#ifdef SUBSURFACE\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x)\n#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_MATRIXNAME_,translucencyColor,_INFONAME_,TranslucencyColorInfos.x)\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},7987:(e,t,i)=>{"use strict";i.r(t),i.d(t,{pickingPixelShader:()=>n});const r="pickingPixelShader",s="#if defined(INSTANCES)\nvarying vec4 vMeshID;\n#else\nuniform vec4 meshID;\n#endif\nvoid main(void) {\n#if defined(INSTANCES)\ngl_FragColor=vMeshID;\n#else\ngl_FragColor=meshID;\n#endif\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},37837:(e,t,i)=>{"use strict";i.r(t),i.d(t,{pickingVertexShader:()=>o});var r=i(69841);i(39948),i(66682),i(9158),i(11783),i(56865),i(99216),i(44219),i(18411),i(78792),i(95532);const s="pickingVertexShader",n="attribute vec3 position;\n#if defined(INSTANCES)\nattribute vec4 instanceMeshID;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform mat4 viewProjection;\n#if defined(INSTANCES)\nvarying vec4 vMeshID;\n#endif\nvoid main(void) {\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;\n#if defined(INSTANCES)\nvMeshID=instanceMeshID;\n#endif\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},18013:(e,t,i)=>{"use strict";i.r(t),i.d(t,{postprocessVertexShader:()=>n});const r="postprocessVertexShader",s="attribute vec2 position;uniform vec2 scale;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=(position*madd+madd)*scale;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},92911:(e,t,i)=>{"use strict";i.r(t),i.d(t,{proceduralVertexShader:()=>n});const r="proceduralVertexShader",s="attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},64849:(e,t,i)=>{"use strict";i.r(t),i.d(t,{rgbdDecodePixelShader:()=>o});var r=i(69841);i(94388);const s="rgbdDecodePixelShader",n="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},32957:(e,t,i)=>{"use strict";i.r(t),i.d(t,{rgbdEncodePixelShader:()=>o});var r=i(69841);i(94388);const s="rgbdEncodePixelShader",n="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},69319:(e,t,i)=>{"use strict";i.r(t),i.d(t,{rsmFullGlobalIlluminationPixelShader:()=>n});const r="rsmFullGlobalIlluminationPixelShader",s="/**\n* The implementation is a direct application of the formula found in http:\n*/\nprecision 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;\n#ifdef TRANSFORM_NORMAL\nuniform mat4 invView;\n#endif\nvec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;int width=int(rsmInfo.x);int height=int(rsmInfo.y);for (int j=0; j{"use strict";i.r(t),i.d(t,{rsmGlobalIlluminationPixelShader:()=>n});const r="rsmGlobalIlluminationPixelShader",s="/**\n* The implementation is an application of the formula found in http:\n* 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).\n*/\nprecision 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;\n#ifdef TRANSFORM_NORMAL\nuniform mat4 invView;\n#endif\nfloat mod289(float x){return x-floor(x*(1.0/289.0))*289.0;}\nvec4 mod289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;}\nvec4 perm(vec4 x){return mod289(((x*34.0)+1.0)*x);}\nfloat 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);}\nvec3 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; \nfloat dist2=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*weightSquare*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}\nreturn clamp(indirectDiffuse*intensity,0.0,1.0);}\nvoid main(void) \n{vec3 positionW=texture2D(textureSampler,vUV).xyz;vec3 normalW=texture2D(normalSampler,vUV).xyz;\n#ifdef DECODE_NORMAL\nnormalW=normalW*2.0-1.0;\n#endif\n#ifdef TRANSFORM_NORMAL\nnormalW=(invView*vec4(normalW,0.)).xyz;\n#endif\ngl_FragColor.rgb=computeIndirect(positionW,normalW);gl_FragColor.a=1.0;}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},87193:(e,t,i)=>{"use strict";i.r(t),i.d(t,{screenSpaceReflection2PixelShader:()=>o});var r=i(69841);i(94388),i(67350),i(8338);const s="screenSpaceReflection2PixelShader",n="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSR_SUPPORTED\nuniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler;\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nuniform sampler2D backDepthSampler;uniform float backSizeFactor;\n#endif\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nuniform samplerCube envCubeSampler;\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize;\n#endif\n#endif\nuniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float farPlaneZ;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;\n#include\n#include\n#include\nvec3 hash(vec3 a)\n{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);}\nfloat computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0;\n#ifdef SSR_ATTENUATE_SCREEN_BORDERS\nvec2 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);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE\nattenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS\nattenuation*=1.0-(numIterations/maxSteps);\n#endif\n#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION\nvec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation;\n#endif\nreturn attenuation;}\n#endif\nvoid main()\n{\n#ifdef SSR_SUPPORTED\nvec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {\n#ifdef SSR_USE_BLUR\ngl_FragColor=vec4(0.);\n#else\ngl_FragColor=colorFull;\n#endif\nreturn;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\nvec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; \n#ifdef SSR_DECODE_NORMAL\ncsNormal=csNormal*2.0-1.0;\n#endif\n#ifdef SSR_NORMAL_IS_IN_WORLDSPACE\ncsNormal=(view*vec4(csNormal,0.0)).xyz;\n#endif\nfloat depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\ndepth=linearizeDepth(depth,nearPlaneZ,farPlaneZ);\n#endif\nvec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);\n#ifdef ORTHOGRAPHIC_CAMERA\nvec3 csViewDirection=vec3(0.,0.,1.);\n#else\nvec3 csViewDirection=normalize(csPosition);\n#endif\nvec3 csReflectedVector=reflect(csViewDirection,csNormal);\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nvec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0));\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nvec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition);\n#endif\n#ifdef SSR_INVERTCUBICMAP\nwReflectedVector.y*=-1.0;\n#endif\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nwReflectedVector.z*=-1.0;\n#endif\nvec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz;\n#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE\nenvColor=toLinearSpace(envColor);\n#endif\n#else\nvec3 envColor=color;\n#endif\nfloat reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations;\n#ifdef SSRAYTRACE_DEBUG\nvec3 debugColor;\n#endif\n#ifdef SSR_ATTENUATE_FACING_CAMERA\nreflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector));\n#endif\nif (reflectionAttenuation>0.0) {\n#ifdef SSR_USE_BLUR\nvec3 jitt=vec3(0.);\n#else\nfloat roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; \n#endif\nvec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); \nrayHasHit=traceScreenSpaceRay1(\ncsPosition,\nnormalize(csReflectedVector+jitt),\nprojectionPixel,\ndepthSampler,\ntexSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nbackDepthSampler,\nbackSizeFactor,\n#endif\nthickness,\nnearPlaneZ,\nfarPlaneZ,\nstepSize,\njitter,\nmaxSteps,\nmaxDistance,\nselfCollisionNumSkip,\nstartPixel,\nhitPixel,\nhitPoint,\nnumIterations\n#ifdef SSRAYTRACE_DEBUG\n,debugColor\n#endif\n);}\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=vec4(debugColor,1.);return;\n#endif\nvec3 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;\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\nreflectedColor=toLinearSpace(reflectedColor);\n#endif\nreflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;}\n#ifndef SSR_BLEND_WITH_FRESNEL\nSSR*=fresnel;\n#endif\n#ifdef SSR_USE_BLUR\nfloat 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; \nfloat 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);}\ngl_FragColor=vec4(SSR,blur_radius/255.0); \n#else\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,colorFull.a);\n#endif\n#else\ngl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0);\n#endif\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},83514:(e,t,i)=>{"use strict";i.r(t),i.d(t,{screenSpaceReflection2BlurPixelShader:()=>n});const r="screenSpaceReflection2BlurPixelShader",s="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform 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)\n{vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;}\nvoid main()\n{vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;}\nfloat blurRadius=colorFull.a*255.0; \nvec2 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);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},36253:(e,t,i)=>{"use strict";i.r(t),i.d(t,{screenSpaceReflection2BlurCombinerPixelShader:()=>o});var r=i(69841);i(94388),i(67350),i(8338);const s="screenSpaceReflection2BlurCombinerPixelShader",n="uniform sampler2D textureSampler; \nuniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV;\n#include\n#ifdef SSR_BLEND_WITH_FRESNEL\n#include\n#include\nuniform mat4 projection;uniform mat4 invProjectionMatrix;uniform sampler2D normalSampler;uniform sampler2D depthSampler;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nuniform float nearPlaneZ;uniform float farPlaneZ;\n#endif\n#endif\nvoid main()\n{\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=texture2D(textureSampler,vUV);\n#else\nvec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\ndepth=linearizeDepth(depth,nearPlaneZ,farPlaneZ);\n#endif\nvec3 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);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,color.a);\n#endif\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},42451:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowMapPixelShader:()=>o});var r=i(69841);i(72693);r.l.IncludesShadersStore.bayerDitherFunctions="float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);}\nfloat bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5*mod(_P,4.0)); \nreturn 4.0*bayerDither2(P1)+bayerDither2(P2);}\nfloat bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5 *mod(_P,4.0)); \nvec2 P4=floor(0.25*mod(_P,8.0)); \nreturn 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);}\n";r.l.IncludesShadersStore.shadowMapFragmentExtraDeclaration="#if SM_FLOAT==0\n#include\n#endif\n#if SM_SOFTTRANSPARENTSHADOW==1\n#include\nuniform vec2 softTransparentShadowSM;\n#endif\nvarying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nuniform vec3 lightDataSM;varying vec3 vPositionWSM;\n#endif\nuniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n",i(77165),i(89797),i(73391);const s="shadowMapPixelShader",n="#include\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEXTURE\nvec4 opacityMap=texture2D(diffuseSampler,vUV);float alphaFromAlphaTexture=opacityMap.a;\n#if SM_SOFTTRANSPARENTSHADOW==1\nif (softTransparentShadowSM.y==1.0) {opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alphaFromAlphaTexture=opacityMap.x+opacityMap.y+opacityMap.z;}\n#endif\n#ifdef ALPHATESTVALUE\nif (alphaFromAlphaTexture=softTransparentShadowSM.x*alphaFromAlphaTexture) discard;\n#else\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM.x) discard;\n#endif\n#endif\n#include\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},32166:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowMapVertexShader:()=>o});var r=i(69841);i(39948),i(66682),i(9158),i(11783),i(94388);r.l.IncludesShadersStore.sceneVertexDeclaration="uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\nuniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition;\n";r.l.IncludesShadersStore.meshVertexDeclaration="uniform mat4 world;uniform float visibility;\n";r.l.IncludesShadersStore.shadowMapVertexDeclaration="#include\n#include\n",i(32405),i(13580);r.l.IncludesShadersStore.shadowMapUboDeclaration="layout(std140,column_major) uniform;\n#include\n#include\n";r.l.IncludesShadersStore.shadowMapVertexExtraDeclaration="#if SM_NORMALBIAS==1\nuniform vec3 lightDataSM;\n#endif\nuniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nvarying vec3 vPositionWSM;\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n",i(18355),i(99216),i(44219),i(18411),i(78792),i(95532);r.l.IncludesShadersStore.shadowMapVertexNormalBias="#if SM_NORMALBIAS==1\n#if SM_DIRECTIONINLIGHTDATA==1\nvec3 worldLightDirSM=normalize(-lightDataSM.xyz);\n#else\nvec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM);\n#endif\nfloat ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM;\n#endif\n",i(94949),i(71471);const s="shadowMapVertexShader",n="attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef INSTANCES\nattribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;\n#endif\n#include\n#include<__decl__shadowMapVertex>\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef NORMAL\nmat3 normWorldSM=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvec3 vNormalW=normalize(normWorldSM*normalUpdated);\n#endif\n#endif\n#include\ngl_Position=viewProjection*worldPos;\n#include\n#ifdef ALPHATEXTURE\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},3367:(e,t,i)=>{"use strict";i.r(t),i.d(t,{sharpenPixelShader:()=>n});const r="sharpenPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},3916:(e,t,i)=>{"use strict";i.r(t),i.d(t,{spritesPixelShader:()=>o});var r=i(69841);i(64657),i(25012),i(6922),i(27185),i(65343);const s="spritesPixelShader",n="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler;\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#ifdef PIXEL_PERFECT\nvec2 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;}\n#endif\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#ifdef PIXEL_PERFECT\nvec2 uv=uvPixelPerfect(vUV);\n#else\nvec2 uv=vUV;\n#endif\nvec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.)\n{if (color.a<0.95)\ndiscard;}\ncolor*=vColor;\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},3290:(e,t,i)=>{"use strict";i.r(t),i.d(t,{spritesVertexShader:()=>o});var r=i(69841);i(77735),i(25012),i(88336);const s="spritesVertexShader",n="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;\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 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); \nvColor=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;\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},33258:(e,t,i)=>{"use strict";i.r(t),i.d(t,{ssao2PixelShader:()=>n});const r="ssao2PixelShader",s="precision highp float;uniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSAO\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);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()\n{vec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;float depth=textureLod(depthSampler,vUV,0.0).r;float depthSign=sign(depth);depth=depth*depthSign;vec3 normal=textureLod(normalSampler,vUV,0.0).rgb;float occlusion=0.0;float correctedRadius=min(radius,minZAspect*depth/near);vec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);vec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);vec3 origin=vViewRay*vDepthFactor;vec3 rvec=random*2.0-1.0;rvec.z=0.0;float dotProduct=dot(rvec,normal);rvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i1.0 || offset.y>1.0) {continue;}\nfloat 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;}\nocclusion=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);}\n#endif\n#ifdef BLUR\nuniform float outSize;uniform float soften;uniform float tolerance;uniform int samples;\n#ifndef BLUR_BYPASS\nuniform sampler2D depthSampler;\n#ifdef BLUR_LEGACY\n#define inline\nfloat 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;}\n#endif\n#endif\nvoid main()\n{float result=0.0;\n#ifdef BLUR_BYPASS\nresult=textureLod(textureSampler,vUV,0.0).r;\n#else\n#ifdef BLUR_H\nvec2 step=vec2(1.0/outSize,0.0);\n#else\nvec2 step=vec2(0.0,1.0/outSize);\n#endif\n#ifdef BLUR_LEGACY\nresult=blur13Bilateral(textureSampler,vUV,step);\n#else\nfloat compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; i{"use strict";i.r(t),i.d(t,{ssaoCombinePixelShader:()=>n});const r="ssaoCombinePixelShader",s="uniform sampler2D textureSampler;uniform sampler2D originalColor;uniform vec4 viewport;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);vec4 sceneColor=texture2D(originalColor,vUV);gl_FragColor=sceneColor*ssaoColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},7672:(e,t,i)=>{"use strict";i.r(t),i.d(t,{taaPixelShader:()=>n});const r="taaPixelShader",s="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);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},47088:(e,t,i)=>{"use strict";i.r(t),i.d(t,{tonemapPixelShader:()=>n});const r="tonemapPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst 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;\n#endif\nfloat Luminance(vec3 c)\n{return dot(c,vec3(0.22,0.707,0.071));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_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;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_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;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},44341:(e,t,i)=>{"use strict";i.r(t),i.d(t,{vrDistortionCorrectionPixelShader:()=>n});const r="vrDistortionCorrectionPixelShader",s="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; \nfloat 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;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},50128:(e,t,i)=>{"use strict";var r=i(69841);i(14910);r.l.IncludesShadersStoreWGSL.backgroundUboDeclaration="uniform vPrimaryColor: vec4f;uniform vPrimaryColorShadow: vec4f;uniform vDiffuseInfos: vec2f;uniform vReflectionInfos: vec2f;uniform diffuseMatrix: mat4x4f;uniform reflectionMatrix: mat4x4f;uniform vReflectionMicrosurfaceInfos: vec3f;uniform fFovMultiplier: f32;uniform pointSize: f32;uniform shadowLevel: f32;uniform alpha: f32;uniform vBackgroundCenter: vec3f;uniform vReflectionControl: vec4f;uniform projectedGroundInfos: vec2f;\n#include\n"},71281:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.bakedVertexAnimation="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\n#ifdef INSTANCES\nlet VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w;\n#else\nlet VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;\n#endif\nlet 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];\n#if NUM_BONE_INFLUENCERS>1\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3];\n#endif\nfinalWorld=finalWorld*VATInfluence;}\n#endif\n"},68273:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.bakedVertexAnimationDeclaration="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d;\n#ifdef INSTANCES\nattribute bakedVertexAnimationSettingsInstanced : vec4;\n#endif\nfn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4\n{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);}\n#endif\n"},25589:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bonesDeclarationWGSL:()=>n});const r="bonesDeclaration",s="#if NUM_BONE_INFLUENCERS>0\nattribute matricesIndices : vec4;attribute matricesWeights : vec4;\n#if NUM_BONE_INFLUENCERS>4\nattribute matricesIndicesExtra : vec4;attribute matricesWeightsExtra : vec4;\n#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nvar boneSampler : texture_2d;uniform boneTextureWidth : f32;\n#else\nuniform mBones : array;\n#ifdef BONES_VELOCITY_ENABLED\nuniform mPreviousBones : array;\n#endif\n#endif\n#ifdef BONETEXTURE\nfn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4\n{let offset=i32(index) *4; \nlet 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);}\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},40903:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bonesVertexWGSL:()=>n});const r="bonesVertex",s="#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nvar influence : mat4x4;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3];\n#endif \n#else \ninfluence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];\n#endif \n#endif\nfinalWorld=finalWorld*influence;\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},99312:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bumpFragmentWGSL:()=>n});const r="bumpFragment",s="var uvOffset: vec2f= vec2f(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL)\n#ifdef NORMALXYSCALE\nvar normalScale: f32=1.0;\n#elif defined(BUMP)\nvar normalScale: f32=uniforms.vBumpInfos.y;\n#else\nvar normalScale: f32=1.0;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nvar TBN: mat3x3f=mat3x3(input.vTBN0,input.vTBN1,input.vTBN2); \n#elif defined(BUMP)\nvar TBNUV: vec2f=select(-fragmentInputs.vBumpUV,fragmentInputs.vBumpUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,input.vPositionW,TBNUV,uniforms.vTangentSpaceParams);\n#else\nvar TBNUV: vec2f=select(-fragmentInputs.vDetailUV,fragmentInputs.vDetailUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,input.vPositionW,TBNUV, vec2f(1.,1.));\n#endif\n#elif defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nvar TBN: mat3x3f=mat3x3(input.vTBN0,input.vTBN1,input.vTBN2); \n#else\nvar TBNUV: vec2f=select( -fragmentInputs.vMainUV1,fragmentInputs.vMainUV1,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW,input.vPositionW,TBNUV, vec2f(1.,1.));\n#endif\n#endif\n#ifdef PARALLAX\nvar invTBN: mat3x3f=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,fragmentInputs.vBumpUV,uniforms.vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,uniforms.vBumpInfos.z);\n#endif\n#endif\n#ifdef DETAIL\nvar detailColor: vec4f=textureSample(detailSampler,detailSamplerSampler,fragmentInputs.vDetailUV+uvOffset);var detailNormalRG: vec2f=detailColor.wy*2.0-1.0;var detailNormalB: f32=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));var detailNormal: vec3f= vec3f(detailNormalRG,detailNormalB);\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\n#define CUSTOM_FRAGMENT_BUMP_FRAGMENT\nnormalW=normalize(textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3x3f(uniforms.normalMatrix[0].xyz,uniforms.normalMatrix[1].xyz,uniforms.normalMatrix[2].xyz)*normalW);\n#elif !defined(DETAIL)\nnormalW=perturbNormal(TBN,textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV+uvOffset).xyz,uniforms.vBumpInfos.y);\n#else\nvar bumpNormal: vec3f=textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV+uvOffset).xyz*2.0-1.0;\n#if DETAIL_NORMALBLENDMETHOD==0 \ndetailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);var blendedNormal: vec3f=normalize( vec3f(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z));\n#elif DETAIL_NORMALBLENDMETHOD==1 \ndetailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);bumpNormal+= vec3f(0.0,0.0,1.0);detailNormal*= vec3f(-1.0,-1.0,1.0);var blendedNormal: vec3f=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal;\n#endif\nnormalW=perturbNormalBase(TBN,blendedNormal,uniforms.vBumpInfos.y);\n#endif\n#elif defined(DETAIL)\ndetailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);normalW=perturbNormalBase(TBN,detailNormal,uniforms.vDetailInfos.z);\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},87087:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bumpFragmentFunctionsWGSL:()=>o});var r=i(69841);i(59224);const s="bumpFragmentFunctions",n="#if defined(BUMP)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)\n#endif\n#if defined(DETAIL)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail)\n#endif\n#if defined(BUMP) && defined(PARALLAX)\nconst minSamples: f32=4.;const maxSamples: f32=15.;const iMaxSamples: i32=15;fn parallaxOcclusion(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32)->vec2f {var parallaxLimit: f32=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;var vOffsetDir: vec2f=normalize(vViewDirCoT.xy);var vMaxOffset: vec2f=vOffsetDir*parallaxLimit;var numSamples: f32=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));var stepSize: f32=1.0/numSamples;var currRayHeight: f32=1.0;var vCurrOffset: vec2f= vec2f(0,0);var vLastOffset: vec2f= vec2f(0,0);var lastSampledHeight: f32=1.0;var currSampledHeight: f32=1.0;var keepWorking: bool=true;for (var i: i32=0; icurrRayHeight)\n{var delta1: f32=currSampledHeight-currRayHeight;var delta2: f32=(currRayHeight+stepSize)-lastSampledHeight;var ratio: f32=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;}\nelse\n{currRayHeight-=stepSize;vLastOffset=vCurrOffset;\n#ifdef PARALLAX_RHS\nvCurrOffset-=stepSize*vMaxOffset;\n#else\nvCurrOffset+=stepSize*vMaxOffset;\n#endif\nlastSampledHeight=currSampledHeight;}}\nreturn vCurrOffset;}\nfn parallaxOffset(viewDir: vec3f,heightScale: f32)->vec2f\n{var height: f32=textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV).w;var texCoordOffset: vec2f=heightScale*viewDir.xy*height;\n#ifdef PARALLAX_RHS\nreturn texCoordOffset;\n#else\nreturn -texCoordOffset;\n#endif\n}\n#endif\n";r.l.IncludesShadersStoreWGSL[s]=n;const o={name:s,shader:n}},56332:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bumpFragmentMainFunctionsWGSL:()=>n});const r="bumpFragmentMainFunctions",s="#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL)\n#if defined(TANGENT) && defined(NORMAL) \nvarying vTBN0: vec3f;varying vTBN1: vec3f;varying vTBN2: vec3f;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform normalMatrix: mat4x4f;fn toNormalMatrix(m: mat4x4f)->mat4x4f\n{var a00=m[0][0];var a01=m[0][1];var a02=m[0][2];var a03=m[0][3];var a10=m[1][0];var a11=m[1][1];var a12=m[1][2];var a13=m[1][3];var a20=m[2][0]; \nvar a21=m[2][1];var a22=m[2][2];var a23=m[2][3];var a30=m[3][0]; \nvar a31=m[3][1];var a32=m[3][2];var a33=m[3][3];var b00=a00*a11-a01*a10;var b01=a00*a12-a02*a10;var b02=a00*a13-a03*a10;var b03=a01*a12-a02*a11;var b04=a01*a13-a03*a11;var b05=a02*a13-a03*a12;var b06=a20*a31-a21*a30;var b07=a20*a32-a22*a30;var b08=a20*a33-a23*a30;var b09=a21*a32-a22*a31;var b10=a21*a33-a23*a31;var b11=a22*a33-a23*a32;var det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;var mi=mat4x4(\n(a11*b11-a12*b10+a13*b09)/det,\n(a02*b10-a01*b11-a03*b09)/det,\n(a31*b05-a32*b04+a33*b03)/det,\n(a22*b04-a21*b05-a23*b03)/det,\n(a12*b08-a10*b11-a13*b07)/det,\n(a00*b11-a02*b08+a03*b07)/det,\n(a32*b02-a30*b05-a33*b01)/det,\n(a20*b05-a22*b02+a23*b01)/det,\n(a10*b10-a11*b08+a13*b06)/det,\n(a01*b08-a00*b10-a03*b06)/det,\n(a30*b04-a31*b02+a33*b00)/det,\n(a21*b02-a20*b04-a23*b00)/det,\n(a11*b07-a10*b09-a12*b06)/det,\n(a00*b09-a01*b07+a02*b06)/det,\n(a31*b01-a30*b03-a32*b00)/det,\n(a20*b03-a21*b01+a22*b00)/det);return mat4x4(mi[0][0],mi[1][0],mi[2][0],mi[3][0],\nmi[0][1],mi[1][1],mi[2][1],mi[3][1],\nmi[0][2],mi[1][2],mi[2][2],mi[3][2],\nmi[0][3],mi[1][3],mi[2][3],mi[3][3]);}\n#endif\nfn perturbNormalBase(cotangentFrame: mat3x3f,normal: vec3f,scale: f32)->vec3f\n{var output=normal;\n#ifdef NORMALXYSCALE\noutput=normalize(output* vec3f(scale,scale,1.0));\n#endif\nreturn normalize(cotangentFrame*output);}\nfn perturbNormal(cotangentFrame: mat3x3f,textureSample: vec3f,scale: f32)->vec3f\n{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);}\nfn cotangent_frame(normal: vec3f,p: vec3f,uv: vec2f,tangentSpaceParams: vec2f)->mat3x3f\n{var dp1: vec3f=dpdx(p);var dp2: vec3f=dpdy(p);var duv1: vec2f=dpdx(uv);var duv2: vec2f=dpdy(uv);var dp2perp: vec3f=cross(dp2,normal);var dp1perp: vec3f=cross(normal,dp1);var tangent: vec3f=dp2perp*duv1.x+dp1perp*duv2.x;var bitangent: vec3f=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;var det: f32=max(dot(tangent,tangent),dot(bitangent,bitangent));var invmax: f32=select(inverseSqrt(det),0.0,det==0.0);return mat3x3f(tangent*invmax,bitangent*invmax,normal);}\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},73918:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.bumpVertex="#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nvar tbnNormal: vec3f=normalize(normalUpdated);var tbnTangent: vec3f=normalize(tangentUpdated.xyz);var tbnBitangent: vec3f=cross(tbnNormal,tbnTangent)*tangentUpdated.w;var matTemp= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz)* mat3x3f(tbnTangent,tbnBitangent,tbnNormal);vertexOutputs.vTBN0=matTemp[0];vertexOutputs.vTBN1=matTemp[1];vertexOutputs.vTBN2=matTemp[2];\n#endif\n#endif\n"},96760:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.bumpVertexDeclaration="#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL) \nvarying vTBN0: vec3f;varying vTBN1: vec3f;varying vTBN2: vec3f;\n#endif\n#endif\n"},76794:(e,t,i)=>{"use strict";i.r(t),i.d(t,{clipPlaneFragmentWGSL:()=>n});const r="clipPlaneFragment",s="#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nif (false) {}\n#endif\n#ifdef CLIPPLANE\nelse if (fragmentInputs.fClipDistance>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE2\nelse if (fragmentInputs.fClipDistance2>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE3\nelse if (fragmentInputs.fClipDistance3>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE4\nelse if (fragmentInputs.fClipDistance4>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE5\nelse if (fragmentInputs.fClipDistance5>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE6\nelse if (fragmentInputs.fClipDistance6>0.0)\n{discard;}\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},96140:(e,t,i)=>{"use strict";i.r(t),i.d(t,{clipPlaneFragmentDeclarationWGSL:()=>n});const r="clipPlaneFragmentDeclaration",s="#ifdef CLIPPLANE\nvarying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nvarying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nvarying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nvarying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nvarying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nvarying fClipDistance6: f32;\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},57728:(e,t,i)=>{"use strict";i.r(t),i.d(t,{clipPlaneVertexWGSL:()=>n});const r="clipPlaneVertex",s="#ifdef CLIPPLANE\nvertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nvertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nvertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nvertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4);\n#endif\n#ifdef CLIPPLANE5\nvertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5);\n#endif\n#ifdef CLIPPLANE6\nvertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6);\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},30486:(e,t,i)=>{"use strict";i.r(t),i.d(t,{clipPlaneVertexDeclarationWGSL:()=>n});const r="clipPlaneVertexDeclaration",s="#ifdef CLIPPLANE\nuniform vClipPlane: vec4;varying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nuniform vClipPlane2: vec4;varying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nuniform vClipPlane3: vec4;varying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nuniform vClipPlane4: vec4;varying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nuniform vClipPlane5: vec4;varying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nuniform vClipPlane6: vec4;varying fClipDistance6: f32;\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},17327:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.decalFragment="#ifdef DECAL\nvar decalTempColor=decalColor.rgb;var decalTempAlpha=decalColor.a;\n#ifdef GAMMADECAL\ndecalTempColor=toLinearSpaceVec3(decalColor.rgb);\n#endif\n#ifdef DECAL_SMOOTHALPHA\ndecalTempAlpha=decalColor.a*decalColor.a;\n#endif\nsurfaceAlbedo=mix(surfaceAlbedo.rgb,decalTempColor,decalTempAlpha);\n#endif\n"},59051:(e,t,i)=>{"use strict";var r=i(69841);i(14910),i(10598);r.l.IncludesShadersStoreWGSL.defaultUboDeclaration="uniform diffuseLeftColor: vec4f;uniform diffuseRightColor: vec4f;uniform opacityParts: vec4f;uniform reflectionLeftColor: vec4f;uniform reflectionRightColor: vec4f;uniform refractionLeftColor: vec4f;uniform refractionRightColor: vec4f;uniform emissiveLeftColor: vec4f;uniform emissiveRightColor: vec4f;uniform vDiffuseInfos: vec2f;uniform vAmbientInfos: vec2f;uniform vOpacityInfos: vec2f;uniform vReflectionInfos: vec2f;uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f;uniform vEmissiveInfos: vec2f;uniform vLightmapInfos: vec2f;uniform vSpecularInfos: vec2f;uniform vBumpInfos: vec3f;uniform diffuseMatrix: mat4x4f;uniform ambientMatrix: mat4x4f;uniform opacityMatrix: mat4x4f;uniform reflectionMatrix: mat4x4f;uniform emissiveMatrix: mat4x4f;uniform lightmapMatrix: mat4x4f;uniform specularMatrix: mat4x4f;uniform bumpMatrix: mat4x4f;uniform vTangentSpaceParams: vec2f;uniform pointSize: f32;uniform alphaCutOff: f32;uniform refractionMatrix: mat4x4f;uniform vRefractionInfos: vec4f;uniform vRefractionPosition: vec3f;uniform vRefractionSize: vec3f;uniform vSpecularColor: vec4f;uniform vEmissiveColor: vec3f;uniform vDiffuseColor: vec4f;uniform vAmbientColor: vec3f;\n#define ADDITIONAL_UBO_DECLARATION\n#include\n#include\n"},81859:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.depthPrePass="#ifdef DEPTHPREPASS\nfragmentOutputs.color= vec4f(0.,0.,0.,1.0);return fragmentOutputs;\n#endif\n"},31034:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.fogFragment="#ifdef FOG\nvar fog: f32=CalcFogFactor();\n#ifdef PBR\nfog=toLinearSpace(fog);\n#endif\ncolor= vec4f(mix(uniforms.vFogColor,color.rgb,fog),color.a);\n#endif\n"},10668:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fogFragmentDeclarationWGSL:()=>n});const r="fogFragmentDeclaration",s="#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\nconst E=2.71828;uniform vFogInfos: vec4f;uniform vFogColor: vec3f;varying vFogDistance: vec3f;fn CalcFogFactor()->f32\n{var fogCoeff: f32=1.0;var fogStart: f32=uniforms.vFogInfos.y;var fogEnd: f32=uniforms.vFogInfos.z;var fogDensity: f32=uniforms.vFogInfos.w;var fogDistance: f32=length(fragmentInputs.vFogDistance);if (FOGMODE_LINEAR==uniforms.vFogInfos.x)\n{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);}\nelse if (FOGMODE_EXP==uniforms.vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDensity);}\nelse if (FOGMODE_EXP2==uniforms.vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);}\nreturn clamp(fogCoeff,0.0,1.0);}\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},45184:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.fogVertex="#ifdef FOG\nvertexOutputs.vFogDistance=(scene.view*worldPos).xyz;\n#endif\n"},86934:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.fogVertexDeclaration="#ifdef FOG\nvarying vFogDistance: vec3f;\n#endif\n"},27493:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.fresnelFunction="#ifdef FRESNEL\nfn computeFresnelTerm(viewDirection: vec3f,worldNormal: vec3f,bias: f32,power: f32)->f32\n{let fresnelTerm: f32=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);}\n#endif\n"},36437:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.harmonicsFunctions="#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nfn computeEnvironmentIrradiance(normal: vec3f)->vec3f {return uniforms.vSphericalL00\n+ uniforms.vSphericalL1_1*(normal.y)\n+ uniforms.vSphericalL10*(normal.z)\n+ uniforms.vSphericalL11*(normal.x)\n+ uniforms.vSphericalL2_2*(normal.y*normal.x)\n+ uniforms.vSphericalL2_1*(normal.y*normal.z)\n+ uniforms.vSphericalL20*((3.0*normal.z*normal.z)-1.0)\n+ uniforms.vSphericalL21*(normal.z*normal.x)\n+ uniforms.vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));}\n#else\nfn computeEnvironmentIrradiance(normal: vec3f)->vec3f {var Nx: f32=normal.x;var Ny: f32=normal.y;var Nz: f32=normal.z;var C1: vec3f=uniforms.vSphericalZZ.rgb;var Cx: vec3f=uniforms.vSphericalX.rgb;var Cy: vec3f=uniforms.vSphericalY.rgb;var Cz: vec3f=uniforms.vSphericalZ.rgb;var Cxx_zz: vec3f=uniforms.vSphericalXX_ZZ.rgb;var Cyy_zz: vec3f=uniforms.vSphericalYY_ZZ.rgb;var Cxy: vec3f=uniforms.vSphericalXY.rgb;var Cyz: vec3f=uniforms.vSphericalYZ.rgb;var Czx: vec3f=uniforms.vSphericalZX.rgb;var a1: vec3f=Cyy_zz*Ny+Cy;var a2: vec3f=Cyz*Nz+a1;var b1: vec3f=Czx*Nz+Cx;var b2: vec3f=Cxy*Ny+b1;var b3: vec3f=Cxx_zz*Nx+b2;var t1: vec3f=Cz *Nz+C1;var t2: vec3f=a2 *Ny+t1;var t3: vec3f=b3 *Nx+t2;return t3;}\n#endif\n#endif\n"},49335:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.hdrFilteringFunctions="#ifdef NUM_SAMPLES\n#if NUM_SAMPLES>0\nfn radicalInverse_VdC(value: u32)->f32 \n{var bits=(value<<16u) | (value>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return f32(bits)*2.3283064365386963e-10; }\nfn hammersley(i: u32,N: u32)->vec2f\n{return vec2f( f32(i)/ f32(N),radicalInverse_VdC(i));}\nfn log4(x: f32)->f32 {return log2(x)/2.;}\nconst NUM_SAMPLES_FLOAT: f32= f32(NUM_SAMPLES);const NUM_SAMPLES_FLOAT_INVERSED: f32=1./NUM_SAMPLES_FLOAT;const K: f32=4.;fn irradiance(inputTexture: texture_cube,inputSampler: sampler,inputN: vec3f,filteringInfo: vec2f)->vec3f\n{var n: vec3f=normalize(inputN);var result: vec3f= vec3f(0.0);var tangent: vec3f=select(vec3f(1.,0.,0.),vec3f(0.,0.,1.),abs(n.z)<0.999);tangent=normalize(cross(tangent,n));var bitangent: vec3f=cross(n,tangent);var tbn: mat3x3f= mat3x3f(tangent,bitangent,n);var maxLevel: f32=filteringInfo.y;var dim0: f32=filteringInfo.x;var omegaP: f32=(4.*PI)/(6.*dim0*dim0);for(var i: u32=0u; i0.) {var pdf_inversed: f32=PI/NoL;var omegaS: f32=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;var l: f32=log4(omegaS)-log4(omegaP)+log4(K);var mipLevel: f32=clamp(l,0.0,maxLevel);var c: vec3f=textureSampleLevel(inputTexture,inputSampler,tbn*Ls,mipLevel).rgb;\n#ifdef GAMMA_INPUT\nc=toLinearSpaceVec3(c);\n#endif\nresult+=c;}}\nresult=result*NUM_SAMPLES_FLOAT_INVERSED;return result;}\nfn radiance(alphaG: f32,inputTexture: texture_cube,inputSampler: sampler,inputN: vec3f,filteringInfo: vec2f)->vec3f\n{var n: vec3f=normalize(inputN);var c: vec3f=textureSample(inputTexture,inputSampler,n).rgb; \nif (alphaG==0.) {\n#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\n#endif\nreturn c;} else {var result: vec3f= vec3f(0.);var tangent: vec3f=select(vec3f(1.,0.,0.),vec3f(0.,0.,1.),abs(n.z)<0.999);tangent=normalize(cross(tangent,n));var bitangent: vec3f=cross(n,tangent);var tbn: mat3x3f= mat3x3f(tangent,bitangent,n);var maxLevel: f32=filteringInfo.y;var dim0: f32=filteringInfo.x;var omegaP: f32=(4.*PI)/(6.*dim0*dim0);var weight: f32=0.;for(var i: u32=0u; i0.) {var pdf_inversed: f32=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);var omegaS: f32=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;var l: f32=log4(omegaS)-log4(omegaP)+log4(K);var mipLevel: f32=clamp( f32(l),0.0,maxLevel);weight+=NoL;var c: vec3f=textureSampleLevel(inputTexture,inputSampler,tbn*L,mipLevel).rgb;\n#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\n#endif\nresult+=c*NoL;}}\nresult=result/weight;return result;}}\n#endif\n#endif\n"},87647:(e,t,i)=>{"use strict";i.r(t),i.d(t,{helperFunctionsWGSL:()=>n});const r="helperFunctions",s="const PI: f32=3.1415926535897932384626433832795;const RECIPROCAL_PI: f32=0.3183098861837907;const RECIPROCAL_PI2: f32=0.15915494309189535;const HALF_MIN: f32=5.96046448e-08; \nconst LinearEncodePowerApprox: f32=2.2;const GammaEncodePowerApprox: f32=1.0/LinearEncodePowerApprox;const LuminanceEncodeApprox: vec3=vec3 (0.2126,0.7152,0.0722);const Epsilon:f32=0.0000001;fn square(x: f32)->f32 {return x*x;}\nfn saturate(x: f32)->f32 {return clamp(x,0.0,1.0);}\nfn saturateVec3(x: vec3f)->vec3f {return clamp(x,vec3f(0.0),vec3f(1.0));}\nfn saturateEps(x: f32)->f32 {return clamp(x,Epsilon,1.0);} \nfn maxEps(x: f32)->f32 {return max(x,Epsilon);}\nfn maxEpsVec3(x: vec3f)->vec3f {return max(x,vec3f(Epsilon));}\nfn absEps(x: f32)->f32 {return abs(x)+Epsilon;}\nfn transposeMat3(inMatrix: mat3x3f)->mat3x3f {let i0: vec3=inMatrix[0];let i1: vec3=inMatrix[1];let i2: vec3=inMatrix[2];let outMatrix:mat3x3f=mat3x3f(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);return outMatrix;}\nfn 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,\nb11/det,(a22*a00-a02*a20)/det,(-a12*a00+a02*a10)/det,\nb21/det,(-a21*a00+a01*a20)/det,(a11*a00-a01*a10)/det);}\n#if USE_EXACT_SRGB_CONVERSIONS\nfn toLinearSpaceExact(color: vec3)->vec3\n{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)));}\nfn toGammaSpaceExact(color: vec3)->vec3\n{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)));}\n#endif\nfn toLinearSpace(color: f32)->f32\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nvar nearZeroSection=0.0773993808*color;var remainingSection=pow(0.947867299*(color+0.055),2.4);return select(remainingSection,nearZeroSection,color<=0.04045);\n#else\nreturn pow(color,LinearEncodePowerApprox);\n#endif\n}\nfn toLinearSpaceVec3(color: vec3)->vec3\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3(LinearEncodePowerApprox));\n#endif\n}\nfn toLinearSpaceVec4(color: vec4)->vec4\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4f(toLinearSpaceExact(color.rgb),color.a);\n#else\nreturn vec4f(pow(color.rgb,vec3f(LinearEncodePowerApprox)),color.a);\n#endif\n}\nfn toGammaSpace(color: vec4)->vec4\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toGammaSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);\n#endif\n}\nfn toGammaSpaceVec3(color: vec3)->vec3\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3(GammaEncodePowerApprox));\n#endif\n}\nfn squareVec3(value: vec3)->vec3\n{return value*value;}\nfn pow5(value: f32)->f32 {let sq: f32=value*value;return sq*sq*value;}\nfn getLuminance(color: vec3)->f32\n{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}\nfn getRand(seed: vec2)->f32 {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}\nfn 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;}\nconst 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); }\nfn fromRGBD(rgbd: vec4)->vec3 {let rgb=toLinearSpaceVec3(rgbd.rgb);return rgb/rgbd.a;}\nfn 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;}\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},33882:(e,t,i)=>{"use strict";i.r(t),i.d(t,{imageProcessingDeclarationWGSL:()=>n});const r="imageProcessingDeclaration",s="#ifdef EXPOSURE\nuniform exposureLinear: f32;\n#endif\n#ifdef CONTRAST\nuniform contrast: f32;\n#endif\n#if defined(VIGNETTE) || defined(DITHER)\nuniform vInverseScreenSize: vec2f;\n#endif\n#ifdef VIGNETTE\nuniform vignetteSettings1: vec4f;uniform vignetteSettings2: vec4f;\n#endif\n#ifdef COLORCURVES\nuniform vCameraColorCurveNegative: vec4f;uniform vCameraColorCurveNeutral: vec4f;uniform vCameraColorCurvePositive: vec4f;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nvar txColorTransformSampler: sampler;var txColorTransform: texture_3d;\n#else\nvar txColorTransformSampler: sampler;var txColorTransform: texture_2d;\n#endif\nuniform colorTransformSettings: vec4f;\n#endif\n#ifdef DITHER\nuniform ditherIntensity: f32;\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},33731:(e,t,i)=>{"use strict";i.r(t),i.d(t,{imageProcessingFunctionsWGSL:()=>n});const r="imageProcessingFunctions",s="#if TONEMAPPING==3\nconst PBRNeutralStartCompression: f32=0.8-0.04;const PBRNeutralDesaturation: f32=0.15;fn PBRNeutralToneMapping( color: vec3f )->vec3f {var x: f32=min(color.r,min(color.g,color.b));var offset: f32=select(0.04,x-6.25*x*x,x<0.08);var result=color;result-=offset;var peak: f32=max(result.r,max(result.g,result.b));if (peakvec3f\n{var a: vec3f=v*(v+0.0245786)-0.000090537;var b: vec3f=v*(0.983729*v+0.4329510)+0.238081;return a/b;}\nfn ACESFitted(color: vec3f)->vec3f\n{var output=ACESInputMat*color;output=RRTAndODTFit(output);output=ACESOutputMat*output;output=saturateVec3(output);return output;}\n#endif\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_DEFINITIONS\nfn applyImageProcessing(result: vec4f)->vec4f {\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATSTART\nvar rgb=result.rgb;;\n#ifdef EXPOSURE\nrgb*=uniforms.exposureLinear;\n#endif\n#ifdef VIGNETTE\nvar viewportXY: vec2f=fragmentInputs.position.xy*uniforms.vInverseScreenSize;viewportXY=viewportXY*2.0-1.0;var vignetteXY1: vec3f= vec3f(viewportXY*uniforms.vignetteSettings1.xy+uniforms.vignetteSettings1.zw,1.0);var vignetteTerm: f32=dot(vignetteXY1,vignetteXY1);var vignette: f32=pow(vignetteTerm,uniforms.vignetteSettings2.w);var vignetteColor: vec3f=uniforms.vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvar vignetteColorMultiplier: vec3f=mix(vignetteColor, vec3f(1,1,1),vignette);rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nrgb=mix(vignetteColor,rgb,vignette);\n#endif\n#endif\n#if TONEMAPPING==3\nrgb=PBRNeutralToneMapping(rgb);\n#elif TONEMAPPING==2\nrgb=ACESFitted(rgb);\n#elif TONEMAPPING==1\nconst tonemappingCalibration: f32=1.590579;rgb=1.0-exp2(-tonemappingCalibration*rgb);\n#endif\nrgb=toGammaSpaceVec3(rgb);rgb=saturateVec3(rgb);\n#ifdef CONTRAST\nvar resultHighContrast: vec3f=rgb*rgb*(3.0-2.0*rgb);if (uniforms.contrast<1.0) {rgb=mix( vec3f(0.5,0.5,0.5),rgb,uniforms.contrast);} else {rgb=mix(rgb,resultHighContrast,uniforms.contrast-1.0);}\n#endif\n#ifdef COLORGRADING\nvar colorTransformInput: vec3f=rgb*uniforms.colorTransformSettings.xxx+uniforms.colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvar colorTransformOutput: vec3f=textureSample(txColorTransform,txColorTransformSampler,colorTransformInput).rgb;\n#else\nvar colorTransformOutput: vec3f=textureSample(txColorTransform,txColorTransformSampler,colorTransformInput,uniforms.colorTransformSettings.yz).rgb;\n#endif\nrgb=mix(rgb,colorTransformOutput,uniforms.colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\nvar luma: f32=getLuminance(rgb);var curveMix: vec2f=clamp( vec2f(luma*3.0-1.5,luma*-3.0+1.5), vec2f(0.0), vec2f(1.0));var colorCurve: vec4f=uniforms.vCameraColorCurveNeutral+curveMix.x*uniforms.vCameraColorCurvePositive-curveMix.y*uniforms.vCameraColorCurveNegative;rgb*=colorCurve.rgb;rgb=mix( vec3f(luma),rgb,colorCurve.a);\n#endif\n#ifdef DITHER\nvar rand: f32=getRand(fragmentInputs.position.xy*uniforms.vInverseScreenSize);var dither: f32=mix(-uniforms.ditherIntensity,uniforms.ditherIntensity,rand);rgb=saturateVec3(rgb+ vec3f(dither));\n#endif\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND\nreturn vec4f(rgb,result.a);}";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},60755:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.importanceSampling="fn hemisphereCosSample(u: vec2f)->vec3f {var phi: f32=2.*PI*u.x;var cosTheta2: f32=1.-u.y;var cosTheta: f32=sqrt(cosTheta2);var sinTheta: f32=sqrt(1.-cosTheta2);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}\nfn hemisphereImportanceSampleDggx(u: vec2f,a: f32)->vec3f {var phi: f32=2.*PI*u.x;var cosTheta2: f32=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));var cosTheta: f32=sqrt(cosTheta2);var sinTheta: f32=sqrt(1.-cosTheta2);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}\nfn hemisphereImportanceSampleDCharlie(u: vec2f,a: f32)->vec3f { \nvar phi: f32=2.*PI*u.x;var sinTheta: f32=pow(u.y,a/(2.*a+1.));var cosTheta: f32=sqrt(1.-sinTheta*sinTheta);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}"},41416:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.instancesDeclaration="#ifdef INSTANCES\nattribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4;\n#ifdef INSTANCESCOLOR\nattribute instanceColor : vec4;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nattribute previousWorld0 : vec4;attribute previousWorld1 : vec4;attribute previousWorld2 : vec4;attribute previousWorld3 : vec4;\n#ifdef THIN_INSTANCES\nuniform previousWorld : mat4x4;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nuniform previousWorld : mat4x4;\n#endif\n#endif\n"},32764:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.instancesVertex="#ifdef INSTANCES\nvar finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nvar finalPreviousWorld=mat4x4(\nvertexInputs.previousWorld0,vertexInputs.previousWorld1,\nvertexInputs.previousWorld2,vertexInputs.previousWorld3);\n#endif\n#ifdef THIN_INSTANCES\n#if !defined(WORLD_UBO)\nfinalWorld=uniforms.world*finalWorld;\n#else\nfinalWorld=mesh.world*finalWorld;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nfinalPreviousWorld=uniforms.previousWorld*finalPreviousWorld;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nvar finalWorld=uniforms.world;\n#else\nvar finalWorld=mesh.world;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nvar finalPreviousWorld=uniforms.previousWorld;\n#endif\n#endif\n"},57932:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.kernelBlurVaryingDeclaration="varying sampleCoord{X}: vec2f;"},55090:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lightFragmentWGSL:()=>n});const r="lightFragment",s="#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n#else\nvar diffuse{X}: vec4f=light{X}.vLightDiffuse;\n#define CUSTOM_LIGHT{X}_COLOR \n#ifdef PBR\n#ifdef SPOTLIGHT{X}\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,fragmentInputs.vPositionW);\n#elif defined(POINTLIGHT{X})\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,fragmentInputs.vPositionW);\n#elif defined(HEMILIGHT{X})\npreInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(DIRLIGHT{X})\npreInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#endif\npreInfo.NdotV=NdotV;\n#ifdef SPOTLIGHT{X}\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.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);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.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);\n#else\npreInfo.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);\n#endif\n#elif defined(POINTLIGHT{X})\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\n#else\npreInfo.attenuation=1.0;\n#endif\n#ifdef HEMILIGHT{X}\npreInfo.roughness=roughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#ifdef IRIDESCENCE\npreInfo.iridescenceIntensity=iridescenceIntensity;\n#endif\n#ifdef HEMILIGHT{X}\ninfo.diffuse=computeHemisphericDiffuseLighting(preInfo,diffuse{X}.rgb,light{X}.vLightGround);\n#elif defined(SS_TRANSLUCENCY)\ninfo.diffuse=computeDiffuseAndTransmittedLighting(preInfo,diffuse{X}.rgb,subSurfaceOut.transmittance);\n#else\ninfo.diffuse=computeDiffuseLighting(preInfo,diffuse{X}.rgb);\n#endif\n#ifdef SPECULARTERM\n#ifdef ANISOTROPIC\ninfo.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb);\n#else\ninfo.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb);\n#endif\n#endif\n#ifdef SHEEN\n#ifdef SHEEN_LINKWITHALBEDO\npreInfo.roughness=sheenOut.sheenIntensity;\n#else\n#ifdef HEMILIGHT{X}\npreInfo.roughness=sheenOut.sheenRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#endif\ninfo.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb);\n#endif\n#ifdef CLEARCOAT\n#ifdef HEMILIGHT{X}\npreInfo.roughness=clearcoatOut.clearCoatRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\ninfo.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,diffuse{X}.rgb);\n#ifdef CLEARCOAT_TINT\nabsorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption;\n#ifdef SPECULARTERM\ninfo.specular*=absorption;\n#endif\n#endif\ninfo.diffuse*=info.clearCoat.w;\n#ifdef SPECULARTERM\ninfo.specular*=info.clearCoat.w;\n#endif\n#ifdef SHEEN\ninfo.sheen*=info.clearCoat.w;\n#endif\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightTexture{X},projectionLightTexture{X}Sampler,uniforms.textureProjectionMatrix{X},fragmentInputs.vPositionW);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSMDEBUG{X}\nvar shadowDebug{X}: vec3f;\n#endif\n#ifdef SHADOWCSM{X}\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nvar index{X}: i32=-1;\n#else\nvar index{X}: i32=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nvar diff{X}: f32=0.;vPositionFromLight{X}[0]=fragmentInputs.vPositionFromLight{X}_0;vPositionFromLight{X}[1]=fragmentInputs.vPositionFromLight{X}_1;vPositionFromLight{X}[2]=fragmentInputs.vPositionFromLight{X}_2;vPositionFromLight{X}[3]=fragmentInputs.vPositionFromLight{X}_3;vDepthMetric{X}[0]=fragmentInputs.vDepthMetric{X}_0;vDepthMetric{X}[1]=fragmentInputs.vDepthMetric{X}_1;vDepthMetric{X}[2]=fragmentInputs.vDepthMetric{X}_2;vDepthMetric{X}[3]=fragmentInputs.vDepthMetric{X}_3;for (var i:i32=0; i=0.) {index{X}=i;break;}}\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nif (index{X}>=0)\n#endif\n{\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#else\nshadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#endif\n#else\nshadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=vec3f(shadow)*vCascadeColorsMultiplier{X}[index{X}];\n#endif\n#ifndef SHADOWCSMNOBLEND{X}\nvar frustumLength:f32=uniforms.frustumLengths{X}[index{X}];var diffRatio:f32=clamp(diff{X}/frustumLength,0.,1.)*uniforms.cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)\n{index{X}+=1;var nextShadow: f32=0.;\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],,shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nnextShadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#else\nnextShadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#endif\n#else\nnextShadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\nshadow=mix(nextShadow,shadow,diffRatio);\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);\n#endif\n}\n#endif\n}\n#elif defined(SHADOWCLOSEESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(fragmentInputs.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(fragmentInputs.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(fragmentInputs.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(fragmentInputs.vPositionW,light{X}.vLightData.xyz,shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;shadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\naggShadow+=shadow;numLights+=1.0;\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor.rgb*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef CLEARCOAT\n#ifndef LIGHTMAPNOSPECULAR{X}\nclearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef SHEEN\n#ifndef LIGHTMAPNOSPECULAR{X}\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#else\n#ifdef SHADOWCSMDEBUG{X}\ndiffuseBase+=info.diffuse*shadowDebug{X};\n#else \ndiffuseBase+=info.diffuse*shadow;\n#endif\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#ifdef CLEARCOAT\nclearCoatBase+=info.clearCoat.rgb*shadow;\n#endif\n#ifdef SHEEN\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},71426:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lightUboDeclarationWGSL:()=>n});const r="lightUboDeclaration",s="#ifdef LIGHT{X}\nstruct Light{X}\n{vLightData: vec4f,\nvLightDiffuse: vec4f,\nvLightSpecular: vec4f,\n#ifdef SPOTLIGHT{X}\nvLightDirection: vec4f,\nvLightFalloff: vec4f,\n#elif defined(POINTLIGHT{X})\nvLightFalloff: vec4f,\n#elif defined(HEMILIGHT{X})\nvLightGround: vec3f,\n#endif\nshadowsInfo: vec4f,\ndepthValues: vec2f} ;var light{X} : Light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform textureProjectionMatrix{X}: mat4x4f;var projectionLightTexture{X}Sampler: sampler;var projectionLightTexture{X}: texture_2d;\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform lightMatrix{X}: array;uniform viewFrustumZ{X}: array;uniform frustumLengths{X}: array;uniform cascadeBlendFactor{X}: f32;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f;var vPositionFromLight{X}: array;var vDepthMetric{X} : array;\n#if defined(SHADOWPCSS{X})\nvar shadowTexture{X}Sampler: sampler_comparison; \nvar shadowTexture{X}: texture_depth_2d_array;var depthTexture{X}Sampler: sampler;var depthTexture{X}: texture_2d_array;uniform lightSizeUVCorrection{X}: array;uniform depthCorrection{X}: array;uniform penumbraDarkness{X}: f32;\n#elif defined(SHADOWPCF{X})\nvar shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d_array;\n#else \nvar shadowTexture{X}Sampler: sampler; \nvar shadowTexture{X}: texture_2d_array;\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vCascadeColorsMultiplier{X}: array=array\n(\nvec3f ( 1.5,0.0,0.0 ),\nvec3f ( 0.0,1.5,0.0 ),\nvec3f ( 0.0,0.0,5.5 ),\nvec3f ( 1.5,0.0,5.5 ),\nvec3f ( 1.5,1.5,0.0 ),\nvec3f ( 1.0,1.0,1.0 ),\nvec3f ( 0.0,1.0,5.5 ),\nvec3f ( 0.5,3.5,0.75 )\n);\n#endif\n#elif defined(SHADOWCUBE{X})\nvar shadowTexture{X}Sampler: sampler;var shadowTexture{X}: texture_cube;\n#else\nvarying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;\n#if defined(SHADOWPCSS{X})\nvar shadowTexture{X}Sampler: sampler_comparison; \nvar shadowTexture{X}: texture_depth_2d;var depthTexture{X}Sampler: sampler; \nvar depthTexture{X}: texture_2d;\n#elif defined(SHADOWPCF{X})\nvar shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d;\n#else\nvar shadowTexture{X}Sampler: sampler; \nvar shadowTexture{X}: texture_2d;\n#endif\nuniform lightMatrix{X}: mat4x4f;\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},85188:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lightVxUboDeclarationWGSL:()=>n});const r="lightVxUboDeclaration",s="#ifdef LIGHT{X}\nstruct Light{X}\n{vLightData: vec4f,\nvLightDiffuse: vec4f,\nvLightSpecular: vec4f,\n#ifdef SPOTLIGHT{X}\nvLightDirection: vec4f,\nvLightFalloff: vec4f,\n#elif defined(POINTLIGHT{X})\nvLightFalloff: vec4f,\n#elif defined(HEMILIGHT{X})\nvLightGround: vec3f,\n#endif\nshadowsInfo: vec4f,\ndepthValues: vec2f} ;var light{X} : Light{X};\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform lightMatrix{X}: array;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f;\n#elif defined(SHADOWCUBE{X})\n#else\nvarying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;uniform lightMatrix{X}: mat4x4f;\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},34992:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lightsFragmentFunctionsWGSL:()=>n});const r="lightsFragmentFunctions",s="struct lightingInfo\n{diffuse: vec3f,\n#ifdef SPECULARTERM\nspecular: vec3f,\n#endif\n#ifdef NDOTL\nndl: f32,\n#endif\n};fn computeLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var result: lightingInfo;var lightVectorW: vec3f;var attenuation: f32=1.0;if (lightData.w==0.)\n{var direction: vec3f=lightData.xyz-fragmentInputs.vPositionW;var attenuation: f32=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}\nelse\n{lightVectorW=normalize(-lightData.xyz);}\nvar ndl: f32=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvar angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nfn computeSpotLighting(viewDirectionW: vec3f,vNormal: vec3f ,lightData: vec4f,lightDirection: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var result: lightingInfo;var direction: vec3f=lightData.xyz-fragmentInputs.vPositionW;var lightVectorW: vec3f=normalize(direction);var attenuation: f32=max(0.,1.0-length(direction)/range);var cosAngle: f32=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w)\n{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;var ndl: f32=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvar angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nresult.diffuse=vec3f(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3f(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;}\nfn computeHemisphericLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,groundColor: vec3f,glossiness: f32)->lightingInfo {var result: lightingInfo;var ndl: f32=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\nvar angleW: vec3f=normalize(viewDirectionW+lightData.xyz);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;\n#endif\nreturn result;}\nfn computeProjectionTextureDiffuseLighting(projectionLightTexture: texture_2d,projectionLightSampler: sampler,textureProjectionMatrix: mat4x4f,posW: vec3f)->vec3f {var strq: vec4f=textureProjectionMatrix*vec4f(posW,1.0);strq/=strq.w;var textureColor: vec3f=textureSample(projectionLightTexture,projectionLightSampler,strq.xy).rgb;return textureColor;}";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},21859:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.logDepthDeclaration="#ifdef LOGARITHMICDEPTH\nuniform logarithmicDepthConstant: f32;varying vFragmentDepth: f32;\n#endif\n"},85551:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.logDepthFragment="#ifdef LOGARITHMICDEPTH\nfragmentOutputs.fragDepth=log2(fragmentInputs.vFragmentDepth)*uniforms.logarithmicDepthConstant*0.5;\n#endif\n"},18201:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.logDepthVertex="#ifdef LOGARITHMICDEPTH\nvertexOutputs.vFragmentDepth=1.0+vertexOutputs.position.w;vertexOutputs.position.z=log2(max(0.000001,vertexOutputs.vFragmentDepth))*uniforms.logarithmicDepthConstant;\n#endif\n"},36174:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.mainUVVaryingDeclaration="#ifdef MAINUV{X}\nvarying vMainUV{X}: vec2f;\n#endif\n"},10598:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.meshUboDeclaration="struct Mesh {world : mat4x4,\nvisibility : f32,};var mesh : Mesh;\n#define WORLD_UBO\n"},43610:(e,t,i)=>{"use strict";i.r(t),i.d(t,{morphTargetsVertexWGSL:()=>n});const r="morphTargetsVertex",s="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\n#if {X}==0\nfor (var i=0; i=uniforms.morphTargetCount) {break;}\nvertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler(i,vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[i];vertexID=vertexID+1.0;\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated=normalUpdated+(readVector3FromRawSampler(i,vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[i];vertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(readVector3FromRawSampler(i,vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[i];vertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated=vec4f(tangentUpdated.xyz+(readVector3FromRawSampler(i,vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[i],tangentUpdated.a);\n#endif\n}\n#endif\n#else\npositionUpdated=positionUpdated+(vertexInputs.position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(vertexInputs.normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated=vec4f(tangentUpdated.xyz+(vertexInputs.tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}],tangentUpdated.a);\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(vertexInputs.uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},51148:(e,t,i)=>{"use strict";i.r(t),i.d(t,{morphTargetsVertexDeclarationWGSL:()=>n});const r="morphTargetsVertexDeclaration",s="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute position{X} : vec3;\n#ifdef MORPHTARGETS_NORMAL\nattribute normal{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute tangent{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_UV\nattribute uv_{X} : vec2;\n#endif\n#elif {X}==0\nuniform morphTargetCount: i32;\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},8573:(e,t,i)=>{"use strict";i.r(t),i.d(t,{morphTargetsVertexGlobalWGSL:()=>n});const r="morphTargetsVertexGlobal",s="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nvar vertexID : f32;\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},47381:(e,t,i)=>{"use strict";i.r(t),i.d(t,{morphTargetsVertexGlobalDeclarationWGSL:()=>n});const r="morphTargetsVertexGlobalDeclaration",s="#ifdef MORPHTARGETS\nuniform morphTargetInfluences : array;\n#ifdef MORPHTARGETS_TEXTURE \nuniform morphTargetTextureIndices : array;uniform morphTargetTextureInfo : vec3;var morphTargets : texture_2d_array;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3\n{ \nlet 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;}\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},73048:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.oitDeclaration="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\n#define MAX_DEPTH 99999.0\nvar oitDepthSamplerSampler: sampler;var oitDepthSampler: texture_2d;var oitFrontColorSamplerSampler: sampler;var oitFrontColorSampler: texture_2d;\n#endif\n"},63270:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.oitFragment="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\nvar fragDepth: f32=fragmentInputs.position.z; \n#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS\nvar halfFloat: i32=packHalf2x16( vec2f(fragDepth));var full: vec2f=unpackHalf2x16(halfFloat);fragDepth=full.x;\n#endif\nvar fragCoord: vec2i=vec2i(fragmentInputs.position.xy);var lastDepth: vec2f=textureLoad(oitDepthSampler,fragCoord,0).rg;var lastFrontColor: vec4f=textureLoad(oitFrontColorSampler,fragCoord,0);fragmentOutputs.depth=vec2f(-MAX_DEPTH);fragmentOutputs.frontColor=lastFrontColor;fragmentOutputs.backColor= vec4f(0.0);\n#ifdef USE_REVERSE_DEPTHBUFFER\nvar furthestDepth: f32=-lastDepth.x;var nearestDepth: f32=lastDepth.y;\n#else\nvar nearestDepth: f32=-lastDepth.x;var furthestDepth: f32=lastDepth.y;\n#endif\nvar alphaMultiplier: f32=1.0-lastFrontColor.a;\n#ifdef USE_REVERSE_DEPTHBUFFER\nif (fragDepth>nearestDepth || fragDepthfurthestDepth) {\n#endif\nreturn fragmentOutputs;}\n#ifdef USE_REVERSE_DEPTHBUFFER\nif (fragDepthfurthestDepth) {\n#else\nif (fragDepth>nearestDepth && fragDepth{"use strict";i.r(t),i.d(t,{packingFunctionsWGSL:()=>n});const r="packingFunctions",s="fn pack(depth: f32)->vec4f\n{const bit_shift: vec4f= vec4f(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const bit_mask: vec4f= vec4f(0.0,1.0/255.0,1.0/255.0,1.0/255.0);var res: vec4f=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}\nfn unpack(color: vec4f)->f32\n{const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},20427:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.pbrBRDFFunctions="#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nfn getEnergyConservationFactor(specularEnvironmentR0: vec3f,environmentBrdf: vec3f)->vec3f {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);}\n#endif\n#ifdef ENVIRONMENTBRDF\nfn getBRDFLookup(NdotV: f32,perceptualRoughness: f32)->vec3f {var UV: vec2f= vec2f(NdotV,perceptualRoughness);var brdfLookup: vec4f= textureSample(environmentBrdfSampler,environmentBrdfSamplerSampler,UV);\n#ifdef ENVIRONMENTBRDF_RGBD\nbrdfLookup=vec4f(fromRGBD(brdfLookup.rgba),brdfLookup.a);\n#endif\nreturn brdfLookup.rgb;}\nfn getReflectanceFromBRDFWithEnvLookup(specularEnvironmentR0: vec3f,specularEnvironmentR90: vec3f,environmentBrdf: vec3f)->vec3f {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvar reflectance: vec3f=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y;\n#else\nvar reflectance: vec3f=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y;\n#endif\nreturn reflectance;}\nfn getReflectanceFromBRDFLookup(specularEnvironmentR0: vec3f,environmentBrdf: vec3f)->vec3f {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvar reflectance: vec3f=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);\n#else\nvar reflectance: vec3f=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#endif\nreturn reflectance;}\n#endif\n/* NOT USED\n#if defined(SHEEN) && defined(SHEEN_SOFTER)\nfn getBRDFLookupCharlieSheen(NdotV: f32,perceptualRoughness: f32)->f32\n{var c: f32=1.0-NdotV;var c3: f32=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));}\n#endif\n*/\n#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)\nfn getReflectanceFromAnalyticalBRDFLookup_Jones(VdotN: f32,reflectance0: vec3f,reflectance90: vec3f,smoothness: f32)->vec3f\n{var weight: f32=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF)\n/**\n* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture.\n* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table\n*/\nfn getSheenReflectanceFromBRDFLookup(reflectance0: vec3f,environmentBrdf: vec3f)->vec3f {var sheenEnvironmentReflectance: vec3f=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;}\n#endif\nfn fresnelSchlickGGXVec3(VdotH: f32,reflectance0: vec3f,reflectance90: vec3f)->vec3f\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\nfn fresnelSchlickGGX(VdotH: f32,reflectance0: f32,reflectance90: f32)->f32\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\n#ifdef CLEARCOAT\nfn getR0RemappedForClearCoat(f0: vec3f)->vec3f {\n#ifdef CLEARCOAT_DEFAULTIOR\n#ifdef MOBILE\nreturn saturateVec3(f0*(f0*0.526868+0.529324)-0.0482256);\n#else\nreturn saturateVec3(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);\n#endif\n#else\nvar s: vec3f=sqrt(f0);var t: vec3f=(uniforms.vClearCoatRefractionParams.z+uniforms.vClearCoatRefractionParams.w*s)/(uniforms.vClearCoatRefractionParams.w+uniforms.vClearCoatRefractionParams.z*s);return squareVec3(t);\n#endif\n}\n#endif\n#ifdef IRIDESCENCE\nconst XYZ_TO_REC709: mat3x3f= mat3x3f(\n3.2404542,-0.9692660, 0.0556434,\n-1.5371385, 1.8760108,-0.2040259,\n-0.4985314, 0.0415560, 1.0572252\n);fn getIORTfromAirToSurfaceR0(f0: vec3f)->vec3f {var sqrtF0: vec3f=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);}\nfn getR0fromIORsVec3(iorT: vec3f,iorI: f32)->vec3f {return squareVec3((iorT- vec3f(iorI))/(iorT+ vec3f(iorI)));}\nfn getR0fromIORs(iorT: f32,iorI: f32)->f32 {return square((iorT-iorI)/(iorT+iorI));}\nfn evalSensitivity(opd: f32,shift: vec3f)->vec3f {var phase: f32=2.0*PI*opd*1.0e-9;const val: vec3f= vec3f(5.4856e-13,4.4201e-13,5.2481e-13);const pos: vec3f= vec3f(1.6810e+06,1.7953e+06,2.2084e+06);const vr: vec3f= vec3f(4.3278e+09,9.3046e+09,6.6121e+09);var xyz: vec3f=val*sqrt(2.0*PI*vr)*cos(pos*phase+shift)*exp(-square(phase)*vr);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;var srgb: vec3f=XYZ_TO_REC709*xyz;return srgb;}\nfn evalIridescence(outsideIOR: f32,eta2: f32,cosTheta1: f32,thinFilmThickness: f32,baseF0: vec3f)->vec3f {var I: vec3f= vec3f(1.0);var iridescenceIOR: f32=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));var sinTheta2Sq: f32=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));var cosTheta2Sq: f32=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;}\nvar cosTheta2: f32=sqrt(cosTheta2Sq);var R0: f32=getR0fromIORs(iridescenceIOR,outsideIOR);var R12: f32=fresnelSchlickGGX(cosTheta1,R0,1.);var R21: f32=R12;var T121: f32=1.0-R12;var phi12: f32=0.0;if (iridescenceIORf32\n{var a2: f32=alphaG*alphaG;var d: f32=NdotH*NdotH*(a2-1.0)+1.0;return a2/(PI*d*d);}\n#ifdef SHEEN\nfn normalDistributionFunction_CharlieSheen(NdotH: f32,alphaG: f32)->f32\n{var invR: f32=1./alphaG;var cos2h: f32=NdotH*NdotH;var sin2h: f32=1.-cos2h;return (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);}\n#endif\n#ifdef ANISOTROPIC\nfn normalDistributionFunction_BurleyGGX_Anisotropic(NdotH: f32,TdotH: f32,BdotH: f32,alphaTB: vec2f)->f32 {var a2: f32=alphaTB.x*alphaTB.y;var v: vec3f= vec3f(alphaTB.y*TdotH,alphaTB.x *BdotH,a2*NdotH);var v2: f32=dot(v,v);var w2: f32=a2/v2;return a2*w2*w2*RECIPROCAL_PI;}\n#endif\n#ifdef BRDF_V_HEIGHT_CORRELATED\nfn smithVisibility_GGXCorrelated(NdotL: f32,NdotV: f32,alphaG: f32)->f32 {\n#ifdef MOBILE\nvar GGXV: f32=NdotL*(NdotV*(1.0-alphaG)+alphaG);var GGXL: f32=NdotV*(NdotL*(1.0-alphaG)+alphaG);return 0.5/(GGXV+GGXL);\n#else\nvar a2: f32=alphaG*alphaG;var GGXV: f32=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);var GGXL: f32=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);return 0.5/(GGXV+GGXL);\n#endif\n}\n#else\nfn smithVisibilityG1_TrowbridgeReitzGGXFast(dot: f32,alphaG: f32)->f32\n{\n#ifdef MOBILE\nreturn 1.0/(dot+alphaG+(1.0-alphaG)*dot ));\n#else\nvar alphaSquared: f32=alphaG*alphaG;return 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot));\n#endif\n}\nfn smithVisibility_TrowbridgeReitzGGXFast(NdotL: f32,NdotV: f32,alphaG: f32)->f32\n{var visibility: f32=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);return visibility;}\n#endif\n#ifdef ANISOTROPIC\nfn smithVisibility_GGXCorrelated_Anisotropic(NdotL: f32,NdotV: f32,TdotV: f32,BdotV: f32,TdotL: f32,BdotL: f32,alphaTB: vec2f)->f32 {var lambdaV: f32=NdotL*length( vec3f(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));var lambdaL: f32=NdotV*length( vec3f(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));var v: f32=0.5/(lambdaV+lambdaL);return v;}\n#endif\n#ifdef CLEARCOAT\nfn visibility_Kelemen(VdotH: f32)->f32 {return 0.25/(VdotH*VdotH); }\n#endif\n#ifdef SHEEN\nfn visibility_Ashikhmin(NdotL: f32,NdotV: f32)->f32\n{return 1./(4.*(NdotL+NdotV-NdotL*NdotV));}\n/* NOT USED\n#ifdef SHEEN_SOFTER\nfn l(x: f32,alphaG: f32)->f32\n{var oneMinusAlphaSq: f32=(1.0-alphaG)*(1.0-alphaG);var a: f32=mix(21.5473,25.3245,oneMinusAlphaSq);var b: f32=mix(3.82987,3.32435,oneMinusAlphaSq);var c: f32=mix(0.19823,0.16801,oneMinusAlphaSq);var d: f32=mix(-1.97760,-1.27393,oneMinusAlphaSq);var e: f32=mix(-4.32054,-4.85967,oneMinusAlphaSq);return a/(1.0+b*pow(x,c))+d*x+e;}\nfn lambdaSheen(cosTheta: f32,alphaG: f32)->f32\n{return abs(cosTheta)<0.5 ? exp(l(cosTheta,alphaG)) : exp(2.0*l(0.5,alphaG)-l(1.0-cosTheta,alphaG));}\nfn visibility_CharlieSheen(NdotL: f32,NdotV: f32,alphaG: f32)->f32\n{var G: f32=1.0/(1.0+lambdaSheen(NdotV,alphaG)+lambdaSheen(NdotL,alphaG));return G/(4.0*NdotV*NdotL);}\n#endif\n*/\n#endif\nfn diffuseBRDF_Burley(NdotL: f32,NdotV: f32,VdotH: f32,roughness: f32)->f32 {var diffuseFresnelNV: f32=pow5(saturateEps(1.0-NdotL));var diffuseFresnelNL: f32=pow5(saturateEps(1.0-NdotV));var diffuseFresnel90: f32=0.5+2.0*VdotH*VdotH*roughness;var fresnel: f32 =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);return fresnel/PI;}\n#ifdef SS_TRANSLUCENCY\nfn transmittanceBRDF_Burley(tintColor: vec3f,diffusionDistance: vec3f,thickness: f32)->vec3f {var S: vec3f=1./maxEpsVec3(diffusionDistance);var temp: vec3f=exp((-0.333333333*thickness)*S);return tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);}\nfn computeWrappedDiffuseNdotL(NdotL: f32,w: f32)->f32 {var t: f32=1.0+w;var invt2: f32=1.0/(t*t);return saturate((NdotL+w)*invt2);}\n#endif\n"},53894:(e,t,i)=>{"use strict";var r=i(69841);i(14910),i(10598);r.l.IncludesShadersStoreWGSL.pbrUboDeclaration="uniform vAlbedoInfos: vec2f;uniform vAmbientInfos: vec4f;uniform vOpacityInfos: vec2f;uniform vEmissiveInfos: vec2f;uniform vLightmapInfos: vec2f;uniform vReflectivityInfos: vec3f;uniform vMicroSurfaceSamplerInfos: vec2f;uniform vReflectionInfos: vec2f;uniform vReflectionFilteringInfo: vec2f;uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f;uniform vBumpInfos: vec3f;uniform albedoMatrix: mat4x4f;uniform ambientMatrix: mat4x4f;uniform opacityMatrix: mat4x4f;uniform emissiveMatrix: mat4x4f;uniform lightmapMatrix: mat4x4f;uniform reflectivityMatrix: mat4x4f;uniform microSurfaceSamplerMatrix: mat4x4f;uniform bumpMatrix: mat4x4f;uniform vTangentSpaceParams: vec2f;uniform reflectionMatrix: mat4x4f;uniform vReflectionColor: vec3f;uniform vAlbedoColor: vec4f;uniform vLightingIntensity: vec4f;uniform vReflectionMicrosurfaceInfos: vec3f;uniform pointSize: f32;uniform vReflectivityColor: vec4f;uniform vEmissiveColor: vec3f;uniform vAmbientColor: vec3f;uniform vDebugMode: vec2f;uniform vMetallicReflectanceFactors: vec4f;uniform vMetallicReflectanceInfos: vec2f;uniform metallicReflectanceMatrix: mat4x4f;uniform vReflectanceInfos: vec2f;uniform reflectanceMatrix: mat4x4f;uniform vSphericalL00: vec3f;uniform vSphericalL1_1: vec3f;uniform vSphericalL10: vec3f;uniform vSphericalL11: vec3f;uniform vSphericalL2_2: vec3f;uniform vSphericalL2_1: vec3f;uniform vSphericalL20: vec3f;uniform vSphericalL21: vec3f;uniform vSphericalL22: vec3f;uniform vSphericalX: vec3f;uniform vSphericalY: vec3f;uniform vSphericalZ: vec3f;uniform vSphericalXX_ZZ: vec3f;uniform vSphericalYY_ZZ: vec3f;uniform vSphericalZZ: vec3f;uniform vSphericalXY: vec3f;uniform vSphericalYZ: vec3f;uniform vSphericalZX: vec3f;\n#define ADDITIONAL_UBO_DECLARATION\n#include\n#include\n"},85620:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.prePassDeclaration="#ifdef PREPASS\n#ifdef PREPASS_LOCAL_POSITION\nvarying vPosition : vec3f;\n#endif\n#ifdef PREPASS_DEPTH\nvarying vViewPos: vec3f;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)\nvarying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f;\n#endif\n#endif\n"},51152:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.prePassVertex="#ifdef PREPASS_DEPTH\nvertexOutputs.vViewPos=(scene.view*worldPos).rgb;\n#endif\n#ifdef PREPASS_LOCAL_POSITION\nvertexOutputs.vPosition=positionUpdated.xyz;\n#endif\n#if (defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED)\nvertexOutputs.vCurrentPosition=scene.viewProjection*worldPos;\n#if NUM_BONE_INFLUENCERS>0\nvar previousInfluence: mat4x4f;previousInfluence=mPreviousBones[ i32(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[ i32(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[ i32(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[ i32(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*previousInfluence* vec4f(positionUpdated,1.0);\n#else\nvertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0);\n#endif\n#endif\n"},17894:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.prePassVertexDeclaration="#ifdef PREPASS\n#ifdef PREPASS_LOCAL_POSITION\nvarying vPosition : vec3f;\n#endif\n#ifdef PREPASS_DEPTH\nvarying vViewPos: vec3f;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)\nuniform previousViewProjection: mat4x4f;varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f;\n#endif\n#endif\n"},7769:(e,t,i)=>{"use strict";i.r(t),i.d(t,{reflectionFunctionWGSL:()=>n});const r="reflectionFunction",s="fn computeFixedEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,direction: vec3f)->vec3f\n{var lon: f32=atan2(direction.z,direction.x);var lat: f32=acos(direction.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(s,t,0); }\nfn computeMirroredFixedEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,direction: vec3f)->vec3f\n{var lon: f32=atan2(direction.z,direction.x);var lat: f32=acos(direction.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(1.0-s,t,0); }\nfn computeEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f\n{var cameraToVertex: vec3f=normalize(worldPos.xyz-eyePosition);var r: vec3f=normalize(reflect(cameraToVertex,worldNormal));r= (reflectionMatrix* vec4f(r,0)).xyz;var lon: f32=atan2(r.z,r.x);var lat: f32=acos(r.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(s,t,0);}\nfn computeSphericalCoords(worldPos: vec4f,worldNormal: vec3f,view: mat4x4f,reflectionMatrix: mat4x4f)->vec3f\n{var viewDir: vec3f=normalize((view*worldPos).xyz);var viewNormal: vec3f=normalize((view* vec4f(worldNormal,0.0)).xyz);var r: vec3f=reflect(viewDir,viewNormal);r= (reflectionMatrix* vec4f(r,0)).xyz;r.z=r.z-1.0;var m: f32=2.0*length(r);return vec3f(r.x/m+0.5,1.0-r.y/m-0.5,0);}\nfn computePlanarCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f\n{var viewDir: vec3f=worldPos.xyz-eyePosition;var coords: vec3f=normalize(reflect(viewDir,worldNormal));return (reflectionMatrix* vec4f(coords,1)).xyz;}\nfn computeCubicCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f\n{var viewDir: vec3f=normalize(worldPos.xyz-eyePosition);var coords: vec3f=reflect(viewDir,worldNormal);coords= (reflectionMatrix* vec4f(coords,0)).xyz;\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;}\nfn computeCubicLocalCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f,reflectionSize: vec3f,reflectionPosition: vec3f)->vec3f\n{var viewDir: vec3f=normalize(worldPos.xyz-eyePosition);var coords: vec3f=reflect(viewDir,worldNormal);coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);coords=(reflectionMatrix* vec4f(coords,0)).xyz;\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;}\nfn computeProjectionCoords(worldPos: vec4f,view: mat4x4f,reflectionMatrix: mat4x4f)->vec3f\n{return (reflectionMatrix*(view*worldPos)).xyz;}\nfn computeSkyBoxCoords(positionW: vec3f,reflectionMatrix: mat4x4f)->vec3f\n{return (reflectionMatrix* vec4f(positionW,1.)).xyz;}\n#ifdef REFLECTION\nfn computeReflectionCoords(worldPos: vec4f,worldNormal: vec3f)->vec3f\n{\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nvar direction: vec3f=normalize(fragmentInputs.vDirectionW);return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvar direction: vec3f=normalize(fragmentInputs.vDirectionW);return computeFixedEquirectangularCoords(worldPos,worldNormal,direction);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nreturn computeEquirectangularCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nreturn computeSphericalCoords(worldPos,worldNormal,scene.view,uniforms.reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nreturn computePlanarCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_CUBIC\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nreturn computeCubicLocalCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix,uniforms.vReflectionSize,uniforms.vReflectionPosition);\n#else\nreturn computeCubicCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix);\n#endif\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn computeProjectionCoords(worldPos,scene.view,uniforms.reflectionMatrix);\n#endif\n#ifndef REFLECTIONMAP_CUBIC\n#ifdef REFLECTIONMAP_SKYBOX\nreturn computeSkyBoxCoords(fragmentInputs.vPositionUVW,uniforms.reflectionMatrix);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3f(0,0,0);\n#endif\n}\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},59224:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.samplerFragmentDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying v_VARYINGNAME_UV: vec2f;\n#endif\nvar _SAMPLERNAME_SamplerSampler: sampler;var _SAMPLERNAME_Sampler: texture_2d;\n#endif\n"},30642:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.samplerVertexDeclaration="#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0\nvarying v_VARYINGNAME_UV: vec2f;\n#endif\n"},84326:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.samplerVertexImplementation="#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0\nif (uniforms.v_INFONAME_==0.)\n{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(uvUpdated,1.0,0.0)).xy;}\n#ifdef UV2\nelse if (uniforms.v_INFONAME_==1.)\n{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv2,1.0,0.0)).xy;}\n#endif\n#ifdef UV3\nelse if (uniforms.v_INFONAME_==2.)\n{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv3,1.0,0.0)).xy;}\n#endif\n#ifdef UV4\nelse if (uniforms.v_INFONAME_==3.)\n{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv4,1.0,0.0)).xy;}\n#endif\n#ifdef UV5\nelse if (uniforms.v_INFONAME_==4.)\n{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv5,1.0,0.0)).xy;}\n#endif\n#ifdef UV6\nelse if (uniforms.v_INFONAME_==5.)\n{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv6,1.0,0.0)).xy;}\n#endif\n#endif\n"},14910:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.sceneUboDeclaration="struct Scene {viewProjection : mat4x4,\n#ifdef MULTIVIEW\nviewProjectionR : mat4x4,\n#endif \nview : mat4x4,\nprojection : mat4x4,\nvEyePosition : vec4,};var scene : Scene;\n"},46357:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.screenSpaceRayTrace="fn distanceSquared(a: vec2f,b: vec2f)->f32 { \nvar temp=a-b; \nreturn dot(temp,temp); }\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nfn linearizeDepth(depth: f32,near: f32,far: f32)->f32 {\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nreturn -(near*far)/(far-depth*(far-near));\n#else\nreturn (near*far)/(far-depth*(far-near));\n#endif\n}\n#endif\n/**\nparam csOrigin Camera-space ray origin,which must be \nwithin the view volume and must have z>0.01 and project within the valid screen rectangle\nparam csDirection Unit length camera-space ray direction\nparam projectToPixelMatrix A projection matrix that maps to **pixel** coordinates \n(**not** [-1,+1] normalized device coordinates).\nparam csZBuffer The camera-space Z buffer\nparam csZBufferSize Dimensions of csZBuffer\nparam csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer\nparam nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value\nfor clipping rays headed towards the camera. Should be the actual near plane if screen-space depth is enabled.\nparam farPlaneZ The far plane for the camera. Used when screen-space depth is enabled.\nparam stride Step in horizontal or vertical pixels between samples. This is a var because: f32 integer math is slow on GPUs,but should be set to an integer>=1\nparam jitterFraction Number between 0 and 1 for how far to bump the ray in stride units\nto conceal banding artifacts,plus the stride ray offset.\nparam maxSteps Maximum number of iterations. Higher gives better images but may be slow\nparam maxRayTraceDistance Maximum camera-space distance to trace before returning a miss\nparam selfCollisionNumSkip Number of steps to skip at start when raytracing to avar self: voidnull collisions.\n1 is a reasonable value,depending on the scene you may need to set this value to 2\nparam hitPixel Pixel coordinates of the first intersection with the scene\nparam numIterations number of iterations performed\nparam csHitPovar Camera: i32 space location of the ray hit\n*/\nfn traceScreenSpaceRay1(\ncsOrigin: vec3f,\ncsDirection: vec3f,\nprojectToPixelMatrix: mat4x4f,\ncsZBuffer: texture_2d,\ncsZBufferSize: vec2f,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\ncsZBackBuffer: texture_2d,\ncsZBackSizeFactor: f32,\n#endif\ncsZThickness: f32,\nnearPlaneZ: f32,\nfarPlaneZ: f32,\nstride: f32,\njitterFraction: f32,\nmaxSteps: f32,\nmaxRayTraceDistance: f32,\nselfCollisionNumSkip: f32,\nstartPixel: ptr,\nhitPixel: ptr,\ncsHitPoint: ptr,\nnumIterations: ptr\n#ifdef SSRAYTRACE_DEBUG\n,debugColor: ptr\n#endif\n)->bool\n{\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nvar rayLength: f32=select(maxRayTraceDistance,(-nearPlaneZ-csOrigin.z)/csDirection.z,(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ);\n#else\nvar rayLength: f32=select(maxRayTraceDistance,(nearPlaneZ-csOrigin.z)/csDirection.z,(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax)))/(P1.y-P0.y);}\nif ((P1.x>xMax) || (P1.xxMax)))/(P1.x-P0.x));}\nP1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha);\n#endif\nP1+= vec2f(select(0.0,0.01,distanceSquared(P0,P1)<0.0001));var delta: vec2f=P1-P0;var permute: bool=false;if (abs(delta.x)rayZMax) { \nvar t: f32=rayZMin; rayZMin=rayZMax; rayZMax=t;}\nsceneZMax=textureLoad(csZBuffer,vec2(*hitPixel),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nsceneZMax=linearizeDepth(sceneZMax,nearPlaneZ,farPlaneZ);\n#endif\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nvar sceneBackZ: f32=textureLoad(csZBackBuffer,vec2(*hitPixel/csZBackSizeFactor),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nsceneBackZ=linearizeDepth(sceneBackZ,nearPlaneZ,farPlaneZ);\n#endif\nhit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax);\n#else\nhit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax);\n#endif\n#else\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nvar sceneBackZ: f32=textureLoad(csZBackBuffer,vec2(*hitPixel/csZBackSizeFactor),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nsceneBackZ=linearizeDepth(sceneBackZ,nearPlaneZ,farPlaneZ);\n#endif\nhit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0);\n#else\nhit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax);\n#endif\n#endif\nstepCount+=1.0;}\npqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;}\n#ifdef SSRAYTRACE_ENABLE_REFINEMENT\nif (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;var invStride: f32=1.0/stride;dPQK*=invStride;var refinementStepCount: f32=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 ||\n((refinementStepCount<=stride*1.4) &&\n(rayZMax(*hitPixel),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nsceneZMax=linearizeDepth(sceneZMax,nearPlaneZ,farPlaneZ);\n#endif\nrefinementStepCount+=1.0;}\npqk-=dPQK;refinementStepCount-=1.0;stepCount+=refinementStepCount/stride;}\n#endif\nQ0=vec3f(Q0.xy+dQ.xy*stepCount,pqk.z);*csHitPoint=Q0/pqk.w;*numIterations=stepCount+1.0;\n#ifdef SSRAYTRACE_DEBUG\nif (((pqk.x+dPQK.x)*stepDirection)>end) {*debugColor= vec3f(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {*debugColor= vec3f(1,0,0);} else if (sceneZMax==0.0) {*debugColor= vec3f(1,1,0);} else {*debugColor= vec3f(0,stepCount/maxSteps,0);}\n#endif\nreturn hit;}\n/**\ntexCoord: in the [0,1] range\ndepth: depth in view space (range [znear,zfar]])\n*/\nfn computeViewPosFromUVDepth(texCoord: vec2f,depth: f32,projection: mat4x4f,invProjectionMatrix: mat4x4f)->vec3f {var xy=texCoord*2.0-1.0;var z: f32;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef ORTHOGRAPHIC_CAMERA\nz=-projection[2].z*depth+projection[3].z;\n#else\nz=-projection[2].z-projection[3].z/depth;\n#endif\n#else\n#ifdef ORTHOGRAPHIC_CAMERA\nz=projection[2].z*depth+projection[3].z;\n#else\nz=projection[2].z+projection[3].z/depth;\n#endif\n#endif\nvar w=1.0;var ndc=vec4f(xy,z,w);var eyePos: vec4f=invProjectionMatrix*ndc;var result=eyePos.xyz/eyePos.w;return result;}\n"},43140:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowMapFragmentWGSL:()=>n});const r="shadowMapFragment",s="var depthSM: f32=fragmentInputs.vDepthMetricSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\n#if SM_USEDISTANCE==1\ndepthSM=(length(fragmentInputs.vPositionWSM-uniforms.lightDataSM)+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\ndepthSM=(-fragmentInputs.zSM+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;\n#else\ndepthSM=(fragmentInputs.zSM+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;\n#endif\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\nfragmentOutputs.fragDepth=clamp(1.0-depthSM,0.0,1.0);\n#else\nfragmentOutputs.fragDepth=clamp(depthSM,0.0,1.0); \n#endif\n#elif SM_USEDISTANCE==1\ndepthSM=(length(fragmentInputs.vPositionWSM-uniforms.lightDataSM)+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;\n#endif\n#if SM_ESM==1\ndepthSM=clamp(exp(-min(87.,uniforms.biasAndScaleSM.z*depthSM)),0.,1.);\n#endif\n#if SM_FLOAT==1\nfragmentOutputs.color= vec4f(depthSM,1.0,1.0,1.0);\n#else\nfragmentOutputs.color=pack(depthSM);\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},17836:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowMapFragmentSoftTransparentShadowWGSL:()=>n});const r="shadowMapFragmentSoftTransparentShadow",s="#if SM_SOFTTRANSPARENTSHADOW==1\nif ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.softTransparentShadowSM.x*alpha) {discard;}\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},18902:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowMapVertexMetricWGSL:()=>n});const r="shadowMapVertexMetric",s="#if SM_USEDISTANCE==1\nvertexOutputs.vPositionWSM=worldPos.xyz;\n#endif\n#if SM_DEPTHTEXTURE==1\n#ifdef IS_NDC_HALF_ZRANGE\n#define BIASFACTOR 0.5\n#else\n#define BIASFACTOR 1.0\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.position.z-=uniforms.biasAndScaleSM.x*vertexOutputs.position.w*BIASFACTOR;\n#else\nvertexOutputs.position.z+=uniforms.biasAndScaleSM.x*vertexOutputs.position.w*BIASFACTOR;\n#endif\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvertexOutputs.zSM=vertexOutputs.position.z;vertexOutputs.position.z=0.0;\n#elif SM_USEDISTANCE==0\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetricSM=(-vertexOutputs.position.z+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;\n#else\nvertexOutputs.vDepthMetricSM=(vertexOutputs.position.z+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},94662:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowsFragmentFunctionsWGSL:()=>n});const r="shadowsFragmentFunctions",s="#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfn unpack(color: vec4f)->f32\n{const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}\n#endif\nfn computeFallOff(value: f32,clipSpace: vec2f,frustumEdgeFalloff: f32)->f32\n{var mask: f32=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}\nfn computeShadowCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,darkness: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadow: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nreturn select(darkness,1.0,depth>shadow);}\nfn computeShadowWithPoissonSamplingCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,mapSize: f32,darkness: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;var visibility: f32=1.;var poissonDisk: array;poissonDisk[0]= vec3f(-1.0,1.0,-1.0);poissonDisk[1]= vec3f(1.0,-1.0,-1.0);poissonDisk[2]= vec3f(-1.0,-1.0,-1.0);poissonDisk[3]= vec3f(1.0,-1.0,1.0);\n#ifndef SHADOWFLOAT\nif (unpack(textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[0]*mapSize)),shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nvar esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return esm;}\nfn computeShadowWithCloseESMCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nvar esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;}\nfn computeShadowCSM(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d_array,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,uv,layer));\n#else\nvar shadow: f32=textureSample(shadowTexture,shadowSampler,uv,layer).x;\n#endif\nreturn select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );}\nfn computeShadow(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadow: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nreturn select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );}}\nfn computeShadowWithPoissonSampling(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,mapSize: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);var visibility: f32=1.;var poissonDisk: array;poissonDisk[0]= vec2f(-0.94201624,-0.39906216);poissonDisk[1]= vec2f(0.94558609,-0.76890725);poissonDisk[2]= vec2f(-0.094184101,-0.92938870);poissonDisk[3]= vec2f(0.34495938,0.29387760);\n#ifndef SHADOWFLOAT\nif (unpack(textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[0]*mapSize,0.)),shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nvar esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithCloseESM(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nvar esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\nfn getZInClip(clipSpace: vec3f,uvDepth: vec3f)->f32\n{\n#ifdef IS_NDC_HALF_ZRANGE\nreturn clipSpace.z;\n#else\nreturn uvDepth.z;\n#endif\n}\nconst GREATEST_LESS_THAN_ONE: f32=0.99999994;\n#define DISABLE_UNIFORMITY_ANALYSIS\nfn computeShadowWithCSMPCF1(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var shadow: f32=textureSampleCompare(shadowTexture,shadowSampler,uvDepth.xy,layer,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithCSMPCF3(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithCSMPCF5(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),layer,uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),layer,uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),layer,uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),layer,uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithPCF1(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var shadow: f32=textureSampleCompareLevel(shadowTexture,shadowSampler,uvDepth.xy,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithPCF3(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithPCF5(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nconst PoissonSamplers32: array=array (\nvec3f(0.06407013,0.05409927,0.),\nvec3f(0.7366577,0.5789394,0.),\nvec3f(-0.6270542,-0.5320278,0.),\nvec3f(-0.4096107,0.8411095,0.),\nvec3f(0.6849564,-0.4990818,0.),\nvec3f(-0.874181,-0.04579735,0.),\nvec3f(0.9989998,0.0009880066,0.),\nvec3f(-0.004920578,-0.9151649,0.),\nvec3f(0.1805763,0.9747483,0.),\nvec3f(-0.2138451,0.2635818,0.),\nvec3f(0.109845,0.3884785,0.),\nvec3f(0.06876755,-0.3581074,0.),\nvec3f(0.374073,-0.7661266,0.),\nvec3f(0.3079132,-0.1216763,0.),\nvec3f(-0.3794335,-0.8271583,0.),\nvec3f(-0.203878,-0.07715034,0.),\nvec3f(0.5912697,0.1469799,0.),\nvec3f(-0.88069,0.3031784,0.),\nvec3f(0.5040108,0.8283722,0.),\nvec3f(-0.5844124,0.5494877,0.),\nvec3f(0.6017799,-0.1726654,0.),\nvec3f(-0.5554981,0.1559997,0.),\nvec3f(-0.3016369,-0.3900928,0.),\nvec3f(-0.5550632,-0.1723762,0.),\nvec3f(0.925029,0.2995041,0.),\nvec3f(-0.2473137,0.5538505,0.),\nvec3f(0.9183037,-0.2862392,0.),\nvec3f(0.2469421,0.6718712,0.),\nvec3f(0.3916397,-0.4328209,0.),\nvec3f(-0.03576927,-0.6220032,0.),\nvec3f(-0.04661255,0.7995201,0.),\nvec3f(0.4402924,0.3640312,0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.)\n);const PoissonSamplers64: array=array (\nvec3f(-0.613392,0.617481,0.),\nvec3f(0.170019,-0.040254,0.),\nvec3f(-0.299417,0.791925,0.),\nvec3f(0.645680,0.493210,0.),\nvec3f(-0.651784,0.717887,0.),\nvec3f(0.421003,0.027070,0.),\nvec3f(-0.817194,-0.271096,0.),\nvec3f(-0.705374,-0.668203,0.),\nvec3f(0.977050,-0.108615,0.),\nvec3f(0.063326,0.142369,0.),\nvec3f(0.203528,0.214331,0.),\nvec3f(-0.667531,0.326090,0.),\nvec3f(-0.098422,-0.295755,0.),\nvec3f(-0.885922,0.215369,0.),\nvec3f(0.566637,0.605213,0.),\nvec3f(0.039766,-0.396100,0.),\nvec3f(0.751946,0.453352,0.),\nvec3f(0.078707,-0.715323,0.),\nvec3f(-0.075838,-0.529344,0.),\nvec3f(0.724479,-0.580798,0.),\nvec3f(0.222999,-0.215125,0.),\nvec3f(-0.467574,-0.405438,0.),\nvec3f(-0.248268,-0.814753,0.),\nvec3f(0.354411,-0.887570,0.),\nvec3f(0.175817,0.382366,0.),\nvec3f(0.487472,-0.063082,0.),\nvec3f(-0.084078,0.898312,0.),\nvec3f(0.488876,-0.783441,0.),\nvec3f(0.470016,0.217933,0.),\nvec3f(-0.696890,-0.549791,0.),\nvec3f(-0.149693,0.605762,0.),\nvec3f(0.034211,0.979980,0.),\nvec3f(0.503098,-0.308878,0.),\nvec3f(-0.016205,-0.872921,0.),\nvec3f(0.385784,-0.393902,0.),\nvec3f(-0.146886,-0.859249,0.),\nvec3f(0.643361,0.164098,0.),\nvec3f(0.634388,-0.049471,0.),\nvec3f(-0.688894,0.007843,0.),\nvec3f(0.464034,-0.188818,0.),\nvec3f(-0.440840,0.137486,0.),\nvec3f(0.364483,0.511704,0.),\nvec3f(0.034028,0.325968,0.),\nvec3f(0.099094,-0.308023,0.),\nvec3f(0.693960,-0.366253,0.),\nvec3f(0.678884,-0.204688,0.),\nvec3f(0.001801,0.780328,0.),\nvec3f(0.145177,-0.898984,0.),\nvec3f(0.062655,-0.611866,0.),\nvec3f(0.315226,-0.604297,0.),\nvec3f(-0.780145,0.486251,0.),\nvec3f(-0.371868,0.882138,0.),\nvec3f(0.200476,0.494430,0.),\nvec3f(-0.494552,-0.711051,0.),\nvec3f(0.612476,0.705252,0.),\nvec3f(-0.578845,-0.768792,0.),\nvec3f(-0.772454,-0.090976,0.),\nvec3f(0.504440,0.372295,0.),\nvec3f(0.155736,0.065157,0.),\nvec3f(0.391522,0.849605,0.),\nvec3f(-0.620106,-0.328104,0.),\nvec3f(0.789239,-0.419965,0.),\nvec3f(-0.545396,0.538133,0.),\nvec3f(-0.178564,-0.596057,0.)\n);fn computeShadowWithCSMPCSS(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uvDepthLayer: vec4f= vec4f(uvDepth.x,uvDepth.y,f32(layer),uvDepth.z);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;for (var i: i32=0; i,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;var exitCondition: bool=depthMetric>1.0 || depthMetric<0.0;for (var i: i32=0; i,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);}\nfn computeShadowWithPCSS32(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);}\nfn computeShadowWithPCSS64(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);}\nfn computeShadowWithCSMPCSS16(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\nfn computeShadowWithCSMPCSS32(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\nfn computeShadowWithCSMPCSS64(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},48453:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowsVertexWGSL:()=>n});const r="shadowsVertex",s="#ifdef SHADOWS\n#if defined(SHADOWCSM{X})\nvertexOutputs.vPositionFromCamera{X}=scene.view*worldPos;\n#if SHADOWCSMNUM_CASCADES{X}>0\nvertexOutputs.vPositionFromLight{X}_0=uniforms.lightMatrix{X}[0]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_0=(-vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_0= (vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif\n#if SHADOWCSMNUM_CASCADES{X}>1\nvertexOutputs.vPositionFromLight{X}_1=uniforms.lightMatrix{X}[1]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_1=(-vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_1= (vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#if SHADOWCSMNUM_CASCADES{X}>2\nvertexOutputs.vPositionFromLight{X}_2=uniforms.lightMatrix{X}[2]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_2=(-vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_2= (vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#if SHADOWCSMNUM_CASCADES{X}>3\nvertexOutputs.vPositionFromLight{X}_3=uniforms.lightMatrix{X}[3]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_3=(-vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_3= (vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvertexOutputs.vPositionFromLight{X}=uniforms.lightMatrix{X}*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}=(-vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}=(vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},20115:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.uvAttributeDeclaration="#ifdef UV{X}\nattribute uv{X}: vec2f;\n#endif\n"},80699:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.uvVariableDeclaration="#ifdef MAINUV{X}\n#if !defined(UV{X})\nvar uv{X}: vec2f=vec2f(0.,0.);\n#else\nvar uv{X}: vec2f=vertexInputs.uv{X};\n#endif\nvertexOutputs.vMainUV{X}=uv{X};\n#endif\n"},42321:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.vertexColorMixing="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvertexOutputs.vColor=vec4f(1.0);\n#ifdef VERTEXCOLOR\n#ifdef VERTEXALPHA\nvertexOutputs.vColor*=vertexInputs.color;\n#else\nvertexOutputs.vColor=vec4f(vertexOutputs.vColor.rgb*vertexInputs.color.rgb,vertexOutputs.vColor.a);\n#endif\n#endif\n#ifdef INSTANCESCOLOR\nvertexOutputs.vColor*=vertexInputs.instanceColor;\n#endif\n#endif\n"},2153:(e,t,i)=>{"use strict";i.r(t),i.d(t,{anaglyphPixelShaderWGSL:()=>n});const r="anaglyphPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var leftSamplerSampler: sampler;var leftSampler: texture_2d;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var leftFrag: vec4f=textureSample(leftSampler,leftSamplerSampler,input.vUV);leftFrag= vec4f(1.0,leftFrag.g,leftFrag.b,1.0);var rightFrag: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);rightFrag= vec4f(rightFrag.r,1.0,1.0,1.0);fragmentOutputs.color= vec4f(rightFrag.rgb*leftFrag.rgb,1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},61853:(e,t,i)=>{"use strict";i.r(t),i.d(t,{backgroundPixelShaderWGSL:()=>o});var r=i(69841);i(50128),i(87647),i(7769),i(33882),i(71426),i(34992),i(94662),i(33731),i(21859),i(96140),i(10668),i(76794),i(55090),i(85551),i(31034);const s="backgroundPixelShader",n="#include\n#include\nvarying vPositionW: vec3f;\n#ifdef MAINUV1\nvarying vMainUV1: vec2f;\n#endif \n#ifdef MAINUV2 \nvarying vMainUV2: vec2f; \n#endif \n#ifdef NORMAL\nvarying vNormalW: vec3f;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV==1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV==2\n#define vDiffuseUV vMainUV2\n#else\nvarying vDiffuseUV: vec2f;\n#endif\nvar diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d;\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nvar reflectionSamplerSampler: sampler;var reflectionSampler: texture_cube;\n#ifdef TEXTURELODSUPPORT\n#else\nvar reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_cube;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_cube;\n#endif\n#else\nvar reflectionSamplerSampler: sampler;var reflectionSampler: texture_2d;\n#ifdef TEXTURELODSUPPORT\n#else\nvar reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_2d;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_2d;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vPositionUVW: vec3f;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vDirectionW: vec3f;\n#endif\n#endif\n#include\n#endif\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include\n#include\n#include\n#include\n#include\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nfn fresnelSchlickEnvironmentGGX(VdotN: f32,reflectance0: vec3f,reflectance90: vec3f,smoothness: f32)->vec3f\n{var weight: f32=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#ifdef PROJECTED_GROUND\nfn diskIntersectWithBackFaceCulling(ro: vec3f,rd: vec3f,c: vec3f,r: f32)->f32 {var d: f32=rd.y;if(d>0.0) { return 1e6; }\nvar o: vec3f=ro-c;var t: f32=-o.y/d;var q: vec3f=o+rd*t;return select(1e6,t,(dot(q,q)f32 {var b: f32=dot(ro,rd);var c: f32=dot(ro,ro)-ra*ra;var h: f32=b*b-c;if(h<0.0) { return -1.0; }\nh=sqrt(h);return-b+h;}\nfn project(viewDirectionW: vec3f,eyePosition: vec3f)->vec3f {var radius: f32=uniforms.projectedGroundInfos.x;var height: f32=uniforms.projectedGroundInfos.y;var camDir: vec3f=-viewDirectionW;var skySphereDistance: f32=sphereIntersect(eyePosition,camDir,radius);var skySpherePositionW: vec3f=eyePosition+camDir*skySphereDistance;var p: vec3f=normalize(skySpherePositionW);var upEyePosition=vec3f(eyePosition.x,eyePosition.y-height,eyePosition.z);var sIntersection: f32=sphereIntersect(upEyePosition,p,radius);var h: vec3f= vec3f(0.0,-height,0.0);var dIntersection: f32=diskIntersectWithBackFaceCulling(upEyePosition,p,h,radius);p=(upEyePosition+min(sIntersection,dIntersection)*p);return p;}\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvar viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-input.vPositionW);\n#ifdef NORMAL\nvar normalW: vec3f=normalize(fragmentInputs.vNormalW);\n#else\nvar normalW: vec3f= vec3f(0.0,1.0,0.0);\n#endif\nvar shadow: f32=1.;var globalShadow: f32=0.;var shadowLightCount: f32=0.;var aggShadow: f32=0.;var numLights: f32=0.;\n#include[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n#ifndef BACKMAT_SHADOWONLY\nvar reflectionColor: vec4f= vec4f(1.,1.,1.,1.);\n#ifdef REFLECTION\n#ifdef PROJECTED_GROUND\nvar reflectionVector: vec3f=project(viewDirectionW,scene.vEyePosition.xyz);reflectionVector= (uniforms.reflectionMatrix*vec4f(reflectionVector,1.)).xyz;\n#else\nvar reflectionVector: vec3f=computeReflectionCoords( vec4f(fragmentInputs.vPositionW,1.0),normalW);\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nvar reflectionCoords: vec3f=reflectionVector;\n#else\nvar reflectionCoords: vec2f=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nvar reflectionLOD: f32=uniforms.vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=textureSampleLevel(reflectionSampler,reflectionSamplerSampler,reflectionCoords,reflectionLOD);\n#else\nvar lodReflectionNormalized: f32=saturate(reflectionLOD);var lodReflectionNormalizedDoubled: f32=lodReflectionNormalized*2.0;var reflectionSpecularMid: vec4f=textureSample(reflectionSampler,reflectionSamplerSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix(\ntextureSample(reflectionrHighSampler,reflectionrHighSamplerSampler,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);} else {reflectionColor=mix(\nreflectionSpecularMid,\ntextureSample(reflectionLowSampler,reflectionLowSamplerSampler,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);}\n#endif\n#else\nvar reflectionSample: vec4f=textureSample(reflectionSampler,reflectionSamplerSampler,reflectionCoords);reflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor=vec4f(fromRGBD(reflectionColor).rgb,reflectionColor.a);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=vec4f(toLinearSpaceVec3(reflectionColor.rgb),reflectionColor.a);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=vec4f(reflectionColor.bgr,reflectionColor.a);\n#endif\nreflectionColor=vec4f(reflectionColor.rgb*uniforms.vReflectionInfos.x,reflectionColor.a);\n#endif\nvar diffuseColor: vec3f= vec3f(1.,1.,1.);var finalAlpha: f32=uniforms.alpha;\n#ifdef DIFFUSE\nvar diffuseMap: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,input.vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap=vec4f(toLinearSpaceVec3(diffuseMap.rgb),diffuseMap.a);\n#endif\ndiffuseMap=vec4f(diffuseMap.rgb *uniforms.vDiffuseInfos.y,diffuseMap.a);\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n#ifdef REFLECTIONFRESNEL\nvar colorBase: vec3f=diffuseColor;\n#else\nvar colorBase: vec3f=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,vec3f(0.0));\n#ifdef USERGBCOLOR\nvar finalColor: vec3f=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvar mainColor: vec3f=mix(uniforms.vPrimaryColorShadow.rgb,uniforms.vPrimaryColor.rgb,colorBase);\n#else\nvar mainColor: vec3f=uniforms.vPrimaryColor.rgb;\n#endif\nvar finalColor: vec3f=colorBase*mainColor;\n#endif\n#ifdef REFLECTIONFRESNEL\nvar reflectionAmount: vec3f=uniforms.vReflectionControl.xxx;var reflectionReflectance0: vec3f=uniforms.vReflectionControl.yyy;var reflectionReflectance90: vec3f=uniforms.vReflectionControl.zzz;var VdotN: f32=dot(normalize(scene.vEyePosition.xyz),normalW);var planarReflectionFresnel: vec3f=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nvar reflectionDistanceFalloff: f32=1.0-saturate(length(vPositionW.xyz-uniforms.vBackgroundCenter)*uniforms.vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,saturateVec3(reflectionAmount));\n#endif\n#ifdef OPACITYFRESNEL\nvar viewAngleToFloor: f32=dot(normalW,normalize(scene.vEyePosition.xyz-uniforms.vBackgroundCenter));const startAngle: f32=0.1;var fadeFactor: f32=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor;\n#endif\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*uniforms.shadowLevel,finalColor,globalShadow);\n#endif\nvar color: vec4f= vec4f(finalColor,finalAlpha);\n#else\nvar color: vec4f= vec4f(uniforms.vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*uniforms.alpha);\n#endif\n#include\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n#if !defined(SKIPFINALCOLORCLAMP)\ncolor=vec4f(clamp(color.rgb,vec3f(0.),vec3f(30.0)),color.a);\n#endif\n#else\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\ncolor=vec4f(color.rgb *color.a,color.a);\n#endif\n#ifdef NOISE\ncolor=vec4f(color.rgb+dither(fragmentInputs.vPositionW.xy,0.5),color.a);color=max(color,vec4f(0.0));\n#endif\nfragmentOutputs.color=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},18135:(e,t,i)=>{"use strict";i.r(t),i.d(t,{backgroundVertexShaderWGSL:()=>o});var r=i(69841);i(50128),i(87647),i(25589),i(68273),i(41416),i(30486),i(86934),i(85188),i(21859),i(32764),i(40903),i(71281),i(57728),i(45184),i(48453),i(18201);const s="backgroundVertexShader",n="#include\n#include\nattribute position: vec3f;\n#ifdef NORMAL\nattribute normal: vec3f;\n#endif\n#include\n#include\n#include\nvarying vPositionW: vec3f;\n#ifdef NORMAL\nvarying vNormalW: vec3f;\n#endif\n#ifdef UV1\nattribute uv: vec2f;\n#endif\n#ifdef UV2\nattribute uv2: vec2f;\n#endif\n#ifdef MAINUV1\nvarying vMainUV1: vec2f;\n#endif\n#ifdef MAINUV2\nvarying vMainUV2: vec2f;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nvarying vDiffuseUV: vec2f;\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vPositionUVW: vec3f;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vDirectionW: vec3f;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#ifdef REFLECTIONMAP_SKYBOX\nvertexOutputs.vPositionUVW=input.position;\n#endif\n#include\n#include\n#include\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {vertexOutputs.position=scene.viewProjection*finalWorld* vec4f(input.position,1.0);} else {vertexOutputs.position=scene.viewProjectionR*finalWorld* vec4f(input.position,1.0);}\n#else\nvertexOutputs.position=scene.viewProjection*finalWorld* vec4f(input.position,1.0);\n#endif\nvar worldPos: vec4f=finalWorld* vec4f(input.position,1.0);vertexOutputs.vPositionW= worldPos.xyz;\n#ifdef NORMAL\nvar normalWorld: mat3x3f=mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvertexOutputs.vNormalW=normalize(normalWorld*input.normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvertexOutputs.vDirectionW=normalize((finalWorld*vec4f(input.position,0.0)).xyz);\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nvar screenToWorld: mat3x3f=inverseMat3( mat3x3f(finalWorld*scene.viewProjection));var segment: vec3f=mix(vertexOutputs.vDirectionW,screenToWorld* vec3f(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vertexOutputs.vDirectionW=normalize(segment);} else {vertexOutputs.vDirectionW=normalize(vertexOutputs.vDirectionW+(vertexOutputs.vDirectionW-segment));}\n#endif\n#endif\n#ifndef UV1\nvar uv: vec2f=vec2f(0.,0.);\n#else\nvar uv=input.uv;\n#endif\n#ifndef UV2\nvar uv2: vec2f=vec2f(0.,0.);\n#else\nvar uv2=input.uv2;\n#endif\n#ifdef MAINUV1\nvertexOutputs.vMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvertexOutputs.vMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nif (uniforms.vDiffuseInfos.x==0.)\n{vertexOutputs.vDiffuseUV= (uniforms.diffuseMatrix* vec4f(uv,1.0,0.0)).xy;}\nelse\n{vertexOutputs.vDiffuseUV= (uniforms.diffuseMatrix* vec4f(uv2,1.0,0.0)).xy;}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\nvertexOutputs.vColor=vertexInputs.color;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},84910:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bilateralBlurPixelShaderWGSL:()=>n});const r="bilateralBlurPixelShader",s="var textureSamplerSampler: sampler;var textureSampler: texture_2d;var normalSamplerSampler: sampler;var normalSampler: texture_2d;var depthSamplerSampler: sampler;var depthSampler: texture_2d;uniform filterSize: i32;uniform blurDir: vec2f;uniform depthThreshold: f32;uniform normalThreshold: f32;varying vUV: vec2f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.).rgb;var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.).x;if (depth>=1e6 || depth<=0.) {fragmentOutputs.color= vec4f(color,1.);return fragmentOutputs;}\nvar normal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nvar sigma: f32= f32(uniforms.filterSize);var two_sigma2: f32=2.0*sigma*sigma;var sigmaDepth: f32=uniforms.depthThreshold;var two_sigmaDepth2: f32=2.0*sigmaDepth*sigmaDepth;var sigmaNormal: f32=uniforms.normalThreshold;var two_sigmaNormal2: f32=2.0*sigmaNormal*sigmaNormal;var sum: vec3f= vec3f(0.);var wsum: f32=0.;for (var x: i32=-uniforms.filterSize; x<=uniforms.filterSize; x++) {var coords=vec2f(f32(x));var sampleColor: vec3f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV+coords*uniforms.blurDir,0.).rgb;var sampleDepth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV+coords*uniforms.blurDir,0.).r;var sampleNormal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV+coords*uniforms.blurDir,0.).rgb;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nvar r: f32=dot(coords,coords);var w: f32=exp(-r/two_sigma2);var depthDelta: f32=abs(sampleDepth-depth);var wd: f32=step(depthDelta,uniforms.depthThreshold);var normalDelta: vec3f=abs(sampleNormal-normal);var wn: f32=step(normalDelta.x+normalDelta.y+normalDelta.z,uniforms.normalThreshold);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}\nfragmentOutputs.color= vec4f(sum/wsum,1.);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},46563:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bilateralBlurQualityPixelShaderWGSL:()=>n});const r="bilateralBlurQualityPixelShader",s="var textureSamplerSampler: sampler;var textureSampler: texture_2d;var normalSamplerSampler: sampler;var normalSampler: texture_2d;var depthSamplerSampler: sampler;var depthSampler: texture_2d;uniform filterSize: i32;uniform blurDir: vec2f;uniform depthThreshold: f32;uniform normalThreshold: f32;varying vUV: vec2f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.).rgb;var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.).x;if (depth>=1e6 || depth<=0.) {fragmentOutputs.color= vec4f(color,1.);return fragmentOutputs;}\nvar normal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nvar sigma: f32= f32(uniforms.filterSize);var two_sigma2: f32=2.0*sigma*sigma;var sigmaDepth: f32=uniforms.depthThreshold;var two_sigmaDepth2: f32=2.0*sigmaDepth*sigmaDepth;var sigmaNormal: f32=uniforms.normalThreshold;var two_sigmaNormal2: f32=2.0*sigmaNormal*sigmaNormal;var sum: vec3f= vec3f(0.);var wsum: f32=0.;for (var x: i32=-uniforms.filterSize; x<=uniforms.filterSize; x++) {for (var y: i32=-uniforms.filterSize; y<=uniforms.filterSize; y++) {var coords: vec2f= vec2f(f32(x),f32(y))*uniforms.blurDir;var sampleColor: vec3f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV+coords,0.).rgb;var sampleDepth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV+coords,0.).r;var sampleNormal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV+coords,0.).rgb;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nvar r: f32=dot(coords,coords);var w: f32=exp(-r/two_sigma2);var rDepth: f32=sampleDepth-depth;var wd: f32=exp(-rDepth*rDepth/two_sigmaDepth2);var rNormal: f32=abs(sampleNormal.x-normal.x)+abs(sampleNormal.y-normal.y)+abs(sampleNormal.z-normal.z);var wn: f32=exp(-rNormal*rNormal/two_sigmaNormal2);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}}\nfragmentOutputs.color= vec4f(sum/wsum,1.);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},31162:(e,t,i)=>{"use strict";i.r(t),i.d(t,{blackAndWhitePixelShaderWGSL:()=>n});const r="blackAndWhitePixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform degree: f32;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var luminance: f32=dot(color, vec3f(0.3,0.59,0.11)); \nvar blackAndWhite: vec3f= vec3f(luminance,luminance,luminance);fragmentOutputs.color= vec4f(color-((color-blackAndWhite)*uniforms.degree),1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},63186:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bloomMergePixelShaderWGSL:()=>n});const r="bloomMergePixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var bloomBlurSampler: sampler;var bloomBlur: texture_2d;uniform bloomWeight: f32;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);var blurred: vec3f=textureSample(bloomBlur,bloomBlurSampler,input.vUV).rgb;fragmentOutputs.color=vec4f(fragmentOutputs.color.rgb+(blurred.rgb*uniforms.bloomWeight),fragmentOutputs.color.a);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},83063:(e,t,i)=>{"use strict";i.r(t),i.d(t,{boundingBoxRendererPixelShaderWGSL:()=>n});const r="boundingBoxRendererPixelShader",s="uniform color: vec4f;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nfragmentOutputs.color=uniforms.color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},10737:(e,t,i)=>{"use strict";i.r(t),i.d(t,{boundingBoxRendererVertexShaderWGSL:()=>n});const r="boundingBoxRendererVertexShader",s="attribute position: vec3f;uniform world: mat4x4f;uniform viewProjection: mat4x4f;\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvar worldPos: vec4f=uniforms.world* vec4f(input.position,1.0);vertexOutputs.position=uniforms.viewProjection*worldPos;\n#define CUSTOM_VERTEX_MAIN_END\n}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},44134:(e,t,i)=>{"use strict";i.r(t),i.d(t,{chromaticAberrationPixelShaderWGSL:()=>n});const r="chromaticAberrationPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform chromatic_aberration: f32;uniform radialIntensity: f32;uniform direction: vec2f;uniform centerPosition: vec2f;uniform screen_width: f32;uniform screen_height: f32;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var centered_screen_pos: vec2f= vec2f(input.vUV.x-uniforms.centerPosition.x,input.vUV.y-uniforms.centerPosition.y);var directionOfEffect: vec2f=uniforms.direction;if(directionOfEffect.x==0. && directionOfEffect.y==0.){directionOfEffect=normalize(centered_screen_pos);}\nvar radius2: f32=centered_screen_pos.x*centered_screen_pos.x\n+ centered_screen_pos.y*centered_screen_pos.y;var radius: f32=sqrt(radius2);var ref_indices: vec3f= vec3f(-0.3,0.0,0.3);var ref_shiftX: f32=uniforms.chromatic_aberration*pow(radius,uniforms.radialIntensity)*directionOfEffect.x/uniforms.screen_width;var ref_shiftY: f32=uniforms.chromatic_aberration*pow(radius,uniforms.radialIntensity)*directionOfEffect.y/uniforms.screen_height;var ref_coords_r: vec2f=vec2f(input.vUV.x+ref_indices.r*ref_shiftX,input.vUV.y+ref_indices.r*ref_shiftY*0.5);var ref_coords_g: vec2f=vec2f(input.vUV.x+ref_indices.g*ref_shiftX,input.vUV.y+ref_indices.g*ref_shiftY*0.5);var ref_coords_b: vec2f=vec2f(input.vUV.x+ref_indices.b*ref_shiftX,input.vUV.y+ref_indices.b*ref_shiftY*0.5);var r=textureSample(textureSampler,textureSamplerSampler,ref_coords_r);var g=textureSample(textureSampler,textureSamplerSampler,ref_coords_g);var b=textureSample(textureSampler,textureSamplerSampler,ref_coords_b);var a=clamp(r.a+g.a+b.a,0.,1.);fragmentOutputs.color=vec4f(r.r,g.g,b.b,a);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},89328:(e,t,i)=>{"use strict";i.r(t),i.d(t,{circleOfConfusionPixelShaderWGSL:()=>n});const r="circleOfConfusionPixelShader",s="varying vUV: vec2f;var depthSamplerSampler: sampler;var depthSampler: texture_2d;\n#ifndef COC_DEPTH_NOT_NORMALIZED\nuniform cameraMinMaxZ: vec2f;\n#endif\nuniform focusDistance: f32;uniform cocPrecalculation: f32;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var depth: f32=textureSample(depthSampler,depthSamplerSampler,input.vUV).r;\n#define CUSTOM_COC_DEPTH\n#ifdef COC_DEPTH_NOT_NORMALIZED\nlet pixelDistance=depth*1000.0;\n#else\nlet pixelDistance: f32=(uniforms.cameraMinMaxZ.x+uniforms.cameraMinMaxZ.y*depth)*1000.0; \n#endif\n#define CUSTOM_COC_PIXELDISTANCE\nvar coc: f32=abs(uniforms.cocPrecalculation*((uniforms.focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);fragmentOutputs.color= vec4f(coc,coc,coc,1.0);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},88516:(e,t,i)=>{"use strict";i.r(t),i.d(t,{colorPixelShaderWGSL:()=>o});var r=i(69841);i(96140),i(10668),i(76794),i(31034);const s="colorPixelShader",n="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\n#define VERTEXCOLOR\nvarying vColor: vec4f;\n#else\nuniform color: vec4f;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nfragmentOutputs.color=input.vColor;\n#else\nfragmentOutputs.color=uniforms.color;\n#endif\n#include(color,fragmentOutputs.color)\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},88130:(e,t,i)=>{"use strict";i.r(t),i.d(t,{colorVertexShaderWGSL:()=>o});var r=i(69841);i(25589),i(68273),i(30486),i(86934),i(41416),i(32764),i(40903),i(71281),i(57728),i(45184),i(42321);const s="colorVertexShader",n="attribute position: vec3f;\n#ifdef VERTEXCOLOR\nattribute color: vec4f;\n#endif\n#include\n#include\n#include\n#include\n#ifdef FOG\nuniform view: mat4x4f;\n#endif\n#include\nuniform viewProjection: mat4x4f;\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vColor: vec4f;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvar worldPos: vec4f=finalWorld* vec4f(input.position,1.0);vertexOutputs.position=uniforms.viewProjection*worldPos;\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},82308:(e,t,i)=>{"use strict";i.r(t),i.d(t,{colorCorrectionPixelShaderWGSL:()=>n});const r="colorCorrectionPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;varying vUV: vec2f;var colorTableSampler: sampler;var colorTable: texture_2d;const SLICE_COUNT: f32=16.0; \nfn sampleAs3DTexture(uv: vec3f,width: f32)->vec4f {var sliceSize: f32=1.0/width; \nvar slicePixelSize: f32=sliceSize/width; \nvar sliceInnerSize: f32=slicePixelSize*(width-1.0); \nvar zSlice0: f32=min(floor(uv.z*width),width-1.0);var zSlice1: f32=min(zSlice0+1.0,width-1.0);var xOffset: f32=slicePixelSize*0.5+uv.x*sliceInnerSize;var s0: f32=xOffset+(zSlice0*sliceSize);var s1: f32=xOffset+(zSlice1*sliceSize);var slice0Color: vec4f=textureSample(colorTable,colorTableSampler,vec2f(s0,uv.y));var slice1Color: vec4f=textureSample(colorTable,colorTableSampler,vec2f(s1,uv.y));var zOffset: f32=((uv.z*width)%(1.0));return mix(slice0Color,slice1Color,zOffset);}\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var screen_color: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);fragmentOutputs.color=sampleAs3DTexture(screen_color.rgb,SLICE_COUNT);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},79799:(e,t,i)=>{"use strict";i.r(t),i.d(t,{convolutionPixelShaderWGSL:()=>n});const r="convolutionPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f;uniform kernel: array;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var onePixel: vec2f= vec2f(1.0,1.0)/uniforms.screenSize;var colorSum: vec4f =\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(-1,-1))*uniforms.kernel[0] +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(0,-1))*uniforms.kernel[1] +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(1,-1))*uniforms.kernel[2] +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(-1,0))*uniforms.kernel[3] +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(0,0))*uniforms.kernel[4] +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(1,0))*uniforms.kernel[5] +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(-1,1))*uniforms.kernel[6] +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(0,1))*uniforms.kernel[7] +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(1,1))*uniforms.kernel[8];var kernelWeight: f32 =\nuniforms.kernel[0] +\nuniforms.kernel[1] +\nuniforms.kernel[2] +\nuniforms.kernel[3] +\nuniforms.kernel[4] +\nuniforms.kernel[5] +\nuniforms.kernel[6] +\nuniforms.kernel[7] +\nuniforms.kernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;}\nfragmentOutputs.color= vec4f((colorSum/kernelWeight).rgb,1);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},4357:(e,t,i)=>{"use strict";i.r(t),i.d(t,{copyTexture3DLayerToTexturePixelShaderWGSL:()=>n});const r="copyTexture3DLayerToTexturePixelShader",s="var textureSampler: texture_3d;uniform layerNum: i32;varying vUV: vec2f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {let coord=vec3f(vec2f(input.vUV.x,input.vUV.y)*vec2f(textureDimensions(textureSampler,0).xy),f32(uniforms.layerNum));let color=textureLoad(textureSampler,vec3i(coord),0).rgb;fragmentOutputs.color= vec4f(color,1);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},89517:(e,t,i)=>{"use strict";i.r(t),i.d(t,{copyTextureToTexturePixelShaderWGSL:()=>o});var r=i(69841);i(87647);const s="copyTextureToTexturePixelShader",n="uniform conversion: f32;var textureSamplerSampler: sampler;var textureSampler: texture_2d;varying vUV: vec2f;\n#include\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var color: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);\n#ifdef DEPTH_TEXTURE\nfragmentOutputs.fragDepth=color.r;\n#else\nif (uniforms.conversion==1.) {color=toLinearSpaceVec4(color);} else if (uniforms.conversion==2.) {color=toGammaSpace(color);}\nfragmentOutputs.color=color;\n#endif\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},49694:(e,t,i)=>{"use strict";i.r(t),i.d(t,{defaultPixelShaderWGSL:()=>o});var r=i(69841);i(59051),i(85620),i(73048),i(36174),i(87647),i(71426),i(34992),i(94662),i(59224),i(27493),i(7769),i(33882),i(33731),i(56332),i(87087),i(96140),i(21859),i(10668),i(76794),i(99312),i(17327),i(81859),i(55090),i(85551),i(31034),i(63270);const s="defaultPixelShader",n="#include\n#include[SCENE_MRT_COUNT]\n#include\n#define CUSTOM_FRAGMENT_BEGIN\nvarying vPositionW: vec3f;\n#ifdef NORMAL\nvarying vNormalW: vec3f;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vColor: vec4f;\n#endif\n#include[1..7]\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include\n#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nvar refractionCubeSamplerSampler: sampler;var refractionCubeSampler: texture_cube;\n#else\nvar refraction2DSamplerSampler: sampler;var refraction2DSampler: texture_2d;\n#endif\n#endif\n#if defined(SPECULARTERM)\n#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular)\n#endif\n#include\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nvar reflectionCubeSamplerSampler: sampler;var reflectionCubeSampler: texture_cube;\n#else\nvar reflection2DSamplerSampler: sampler;var reflection2DSampler: texture_2d;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vPositionUVW: vec3f;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vDirectionW: vec3f;\n#endif\n#endif\n#include\n#endif\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvar viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-fragmentInputs.vPositionW);var baseColor: vec4f= vec4f(1.,1.,1.,1.);var diffuseColor: vec3f=uniforms.vDiffuseColor.rgb;var alpha: f32=uniforms.vDiffuseColor.a;\n#ifdef NORMAL\nvar normalW: vec3f=normalize(fragmentInputs.vNormalW);\n#else\nvar normalW: vec3f=normalize(-cross(dpdx(fragmentInputs.vPositionW),dpdy(fragmentInputs.vPositionW)));\n#endif\n#include\n#ifdef TWOSIDEDLIGHTING\nnormalW=select(-normalW,normalW,fragmentInputs.frontFacing);\n#endif\n#ifdef DIFFUSE\nbaseColor=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vDiffuseUV+uvOffset);\n#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS)\nif (baseColor.a(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)\n#endif\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor=vec4f(baseColor.rgb*fragmentInputs.vColor.rgb,baseColor.a);\n#endif\n#ifdef DETAIL\nbaseColor=vec4f(baseColor.rgb*2.0*mix(0.5,detailColor.r,uniforms.vDetailInfos.y),baseColor.a);\n#endif\n#if defined(DECAL) && defined(DECAL_AFTER_DETAIL)\nvar decalColor: vec4f=textureSample(decalSampler,decalSamplerSampler,fragmentInputs.vDecalUV+uvOffset);\n#include(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\nvar baseAmbientColor: vec3f= vec3f(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=textureSample(ambientSampler,ambientSamplerSampler,fragmentInputs.vAmbientUV+uvOffset).rgb*uniforms.vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\nvar glossiness: f32=uniforms.vSpecularColor.a;var specularColor: vec3f=uniforms.vSpecularColor.rgb;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\nvar specularMapColor: vec4f=textureSample(specularSampler,specularSamplerSampler,fragmentInputs.vSpecularUV+uvOffset);specularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#endif\nvar diffuseBase: vec3f= vec3f(0.,0.,0.);var info: lightingInfo;\n#ifdef SPECULARTERM\nvar specularBase: vec3f= vec3f(0.,0.,0.);\n#endif\nvar shadow: f32=1.;var aggShadow: f32=0.;var numLights: f32=0.;\n#ifdef LIGHTMAP\nvar lightmapColor: vec4f=textureSample(lightmapSampler,lightmapSamplerSampler,fragmentInputs.vLightmapUV+uvOffset);\n#ifdef RGBDLIGHTMAP\nlightmapColor=vec4f(fromRGBD(lightmapColor),lightmapColor.a);\n#endif\nlightmapColor=vec4f(lightmapColor.rgb*uniforms.vLightmapInfos.y,lightmapColor.a);\n#endif\n#include[0..maxSimultaneousLights]\naggShadow=aggShadow/numLights;var refractionColor: vec4f= vec4f(0.,0.,0.,1.);\n#ifdef REFRACTION\nvar refractionVector: vec3f=normalize(refract(-viewDirectionW,normalW,uniforms.vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\n#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC\nrefractionVector=parallaxCorrectNormal(fragmentInputs.vPositionW,refractionVector,uniforms.vRefractionSize,uniforms.vRefractionPosition);\n#endif\nrefractionVector.y=refractionVector.y*uniforms.vRefractionInfos.w;var refractionLookup: vec4f=textureSample(refractionCubeSampler,refractionCubeSamplerSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;}\n#else\nvar vRefractionUVW: vec3f= (uniforms.refractionMatrix*(scene.view* vec4f(fragmentInputs.vPositionW+refractionVector*uniforms.vRefractionInfos.z,1.0))).xyz;var refractionCoords: vec2f=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=textureSample(refraction2DSampler,refraction2DSamplerSampler,refractionCoords);\n#endif\n#ifdef RGBDREFRACTION\nrefractionColor=vec4f(fromRGBD(refractionColor),refractionColor.a);\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=vec4f(toGammaSpaceVec3(refractionColor.rgb),refractionColor.a);\n#endif\nrefractionColor=vec4f(refractionColor.rgb*uniforms.vRefractionInfos.x,refractionColor.a);\n#endif\nvar reflectionColor: vec4f= vec4f(0.,0.,0.,1.);\n#ifdef REFLECTION\nvar vReflectionUVW: vec3f=computeReflectionCoords( vec4f(fragmentInputs.vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nvReflectionUVW=vec3f(vReflectionUVW.x,vReflectionUVW.y,vReflectionUVW.z*-1.0);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nvar bias: f32=uniforms.vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureSampleLevel(reflectionCubeSampler,reflectionCubeSamplerSampler,vReflectionUVW,bias);\n#else\nreflectionColor=textureSample(reflectionCubeSampler,reflectionCubeSamplerSampler,vReflectionUVW);\n#endif\n#else\nvar coords: vec2f=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;reflectionColor=textureSample(reflection2DSampler,reflection2DSamplerSampler,coords);\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor=vec4f(fromRGBD(reflectionColor),reflectionColor.a);\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=vec4f(toGammaSpaceVec3(reflectionColor.rgb),reflectionColor.a);\n#endif\nreflectionColor=vec4f(reflectionColor.rgb*uniforms.vReflectionInfos.x,reflectionColor.a);\n#ifdef REFLECTIONFRESNEL\nvar reflectionFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.reflectionRightColor.a,uniforms.reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor=vec4f(reflectionColor.rgb*specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a);\n#else\nreflectionColor=vec4f(reflectionColor.rgb*uniforms.reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a);\n#endif\n#else\nreflectionColor=vec4f(reflectionColor.rgb*uniforms.reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a);\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nvar refractionFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.refractionRightColor.a,uniforms.refractionLeftColor.a);refractionColor=vec4f(refractionColor.rgb*uniforms.refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*uniforms.refractionRightColor.rgb,refractionColor.a);\n#endif\n#ifdef OPACITY\nvar opacityMap: vec4f=textureSample(opacitySampler,opacitySamplerSampler,fragmentInputs.vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap=vec4f(opacityMap.rgb* vec3f(0.3,0.59,0.11),opacityMap.a);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* uniforms.vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*uniforms.vOpacityInfos.y;\n#endif\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=fragmentInputs.vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nvar opacityFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.opacityParts.z,uniforms.opacityParts.w);alpha+=uniforms.opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*uniforms.opacityParts.y;\n#endif\n#ifdef ALPHATEST\n#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS\nif (alpha\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor=vec4f(toLinearSpaceVec3(color.rgb),color.a);\n#else\n#ifdef IMAGEPROCESSING\ncolor=vec4f(toLinearSpaceVec3(color.rgb),color.a);color=applyImageProcessing(color);\n#endif\n#endif\ncolor=vec4f(color.rgb,color.a*mesh.visibility);\n#ifdef PREMULTIPLYALPHA\ncolor=vec4f(color.rgb*color.a, color.a);\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\n#ifdef PREPASS\nvar writeGeometryInfo: f32=select(0.0,1.0,color.a>0.4);var fragData: array,SCENE_MRT_COUNT>;\n#ifdef PREPASS_COLOR\nfragData[PREPASS_COLOR_INDEX]=color; \n#endif\n#ifdef PREPASS_POSITION\nfragData[PREPASS_POSITION_INDEX]=vec4f(fragmentInputs.vPositionW,writeGeometryInfo);\n#endif\n#ifdef PREPASS_LOCAL_POSITION\nfragData[PREPASS_LOCAL_POSITION_INDEX]=vec4f(fragmentInputs.vPosition,writeGeometryInfo);\n#endif\n#ifdef PREPASS_VELOCITY\nvar a: vec2f=(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w)*0.5+0.5;var b: vec2f=(fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w)*0.5+0.5;var velocity: vec2f=abs(a-b);velocity= vec2f(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;fragData[PREPASS_VELOCITY_INDEX]= vec4f(velocity,0.0,writeGeometryInfo);\n#elif defined(PREPASS_VELOCITY_LINEAR)\nvar velocity : vec2f=vec2f(0.5)*((fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w) -\n(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w));fragData[PREPASS_VELOCITY_LINEAR_INDEX]=vec4f(velocity,0.0,writeGeometryInfo);\n#endif\n#ifdef PREPASS_IRRADIANCE\nfragData[PREPASS_IRRADIANCE_INDEX]=vec4f(0.0,0.0,0.0,writeGeometryInfo); \n#endif\n#ifdef PREPASS_DEPTH\nfragData[PREPASS_DEPTH_INDEX]=vec4f(fragmentInputs.vViewPos.z,0.0,0.0,writeGeometryInfo); \n#endif\n#ifdef PREPASS_SCREENSPACE_DEPTH\nfragData[PREPASS_SCREENSPACE_DEPTH_INDEX]=vec4f(fragmentInputs.position.z,0.0,0.0,writeGeometryInfo);\n#endif\n#ifdef PREPASS_NORMAL\n#ifdef PREPASS_NORMAL_WORLDSPACE\nfragData[PREPASS_NORMAL_INDEX]=vec4f(normalW,writeGeometryInfo);\n#else\nfragData[PREPASS_NORMAL_INDEX]=vec4f(normalize((scene.view*vec4f(normalW,0.0)).rgb),writeGeometryInfo);\n#endif\n#endif\n#ifdef PREPASS_WORLD_NORMAL\nfragData[PREPASS_WORLD_NORMAL_INDEX]=vec4f(normalW*0.5+0.5,writeGeometryInfo);\n#endif\n#ifdef PREPASS_ALBEDO\nfragData[PREPASS_ALBEDO_INDEX]=vec4f(baseColor.rgb,writeGeometryInfo);\n#endif\n#ifdef PREPASS_ALBEDO_SQRT\nfragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4f(sqrt(baseColor.rgb),writeGeometryInfo);\n#endif\n#ifdef PREPASS_REFLECTIVITY\n#if defined(SPECULAR)\nfragData[PREPASS_REFLECTIVITY_INDEX]=vec4f(toLinearSpaceVec4(specularMapColor))*writeGeometryInfo; \n#else\nfragData[PREPASS_REFLECTIVITY_INDEX]=vec4f(toLinearSpaceVec3(specularColor),1.0)*writeGeometryInfo;\n#endif\n#endif\n#if SCENE_MRT_COUNT>0\nfragmentOutputs.fragData0=fragData[0];\n#endif\n#if SCENE_MRT_COUNT>1\nfragmentOutputs.fragData1=fragData[1];\n#endif\n#if SCENE_MRT_COUNT>2\nfragmentOutputs.fragData2=fragData[2];\n#endif\n#if SCENE_MRT_COUNT>3\nfragmentOutputs.fragData3=fragData[3];\n#endif\n#if SCENE_MRT_COUNT>4\nfragmentOutputs.fragData4=fragData[4];\n#endif\n#if SCENE_MRT_COUNT>5\nfragmentOutputs.fragData5=fragData[5];\n#endif\n#if SCENE_MRT_COUNT>6\nfragmentOutputs.fragData6=fragData[6];\n#endif\n#if SCENE_MRT_COUNT>7\nfragmentOutputs.fragData7=fragData[7];\n#endif\n#endif\n#if !defined(PREPASS) && !defined(ORDER_INDEPENDENT_TRANSPARENCY)\nfragmentOutputs.color=color;\n#endif\n#include\n#if ORDER_INDEPENDENT_TRANSPARENCY\nif (fragDepth==nearestDepth) {fragmentOutputs.frontColor=vec4f(fragmentOutputs.frontColor.rgb+color.rgb*color.a*alphaMultiplier,1.0-alphaMultiplier*(1.0-color.a));} else {fragmentOutputs.backColor+=color;}\n#endif\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},22177:(e,t,i)=>{"use strict";i.r(t),i.d(t,{defaultVertexShaderWGSL:()=>o});var r=i(69841);i(59051),i(20115),i(87647),i(25589),i(68273),i(41416),i(17894),i(36174),i(30642),i(96760),i(30486),i(86934);r.l.IncludesShadersStoreWGSL.lightVxFragmentDeclaration="#ifdef LIGHT{X}\nuniform vLightData{X}: vec4f;uniform vLightDiffuse{X}: vec4f;\n#ifdef SPECULARTERM\nuniform vLightSpecular{X}: vec4f;\n#else\nvar vLightSpecular{X}: vec4f= vec4f(0.);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform lightMatrix{X}: mat4x4f[SHADOWCSMNUM_CASCADES{X}];varying var vPositionFromLight{X}: vec4f[SHADOWCSMNUM_CASCADES{X}];varying var vDepthMetric{X}: f32[SHADOWCSMNUM_CASCADES{X}];varying var vPositionFromCamera{X}: vec4f;\n#elif defined(SHADOWCUBE{X})\n#else\nvarying var vPositionFromLight{X}: vec4f;varying var vDepthMetric{X}: f32;uniform lightMatrix{X}: mat4x4f;\n#endif\nuniform shadowsInfo{X}: vec4f;uniform depthValues{X}: vec2f;\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vLightDirection{X}: vec4f;uniform vLightFalloff{X}: vec4f;\n#elif defined(POINTLIGHT{X})\nuniform vLightFalloff{X}: vec4f;\n#elif defined(HEMILIGHT{X})\nuniform vLightGround{X}: vec3f;\n#endif\n#endif\n",i(85188),i(47381),i(51148),i(21859),i(8573),i(43610),i(32764),i(40903),i(71281),i(51152),i(80699),i(84326),i(73918),i(57728),i(45184),i(48453),i(42321),i(18201);const s="defaultVertexShader",n="#include\n#define CUSTOM_VERTEX_BEGIN\nattribute position: vec3f;\n#ifdef NORMAL\nattribute normal: vec3f;\n#endif\n#ifdef TANGENT\nattribute tangent: vec4f;\n#endif\n#ifdef UV1\nattribute uv: vec2f;\n#endif\n#include[2..7]\n#ifdef VERTEXCOLOR\nattribute color: vec4f;\n#endif\n#include\n#include\n#include\n#include\n#include\n#include[1..7]\n#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)\n#if defined(SPECULARTERM)\n#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular)\n#endif\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)\nvarying vPositionW: vec3f;\n#ifdef NORMAL\nvarying vNormalW: vec3f;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vColor: vec4f;\n#endif\n#include\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vPositionUVW: vec3f;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vDirectionW: vec3f;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvar positionUpdated: vec3f=vertexInputs.position;\n#ifdef NORMAL\nvar normalUpdated: vec3f=vertexInputs.normal;\n#endif\n#ifdef TANGENT\nvar tangentUpdated: vec4f=vertexInputs.tangent;\n#endif\n#ifdef UV1\nvar uvUpdated: vec2f=vertexInputs.uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvertexOutputs.vPositionUVW=positionUpdated;\n#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include\n#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)\nvertexOutputs.vCurrentPosition=scene.viewProjection*finalWorld*vec4f(positionUpdated,1.0);vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*vec4f(positionUpdated,1.0);\n#endif\n#include\n#include\nvar worldPos: vec4f=finalWorld*vec4f(positionUpdated,1.0);\n#ifdef NORMAL\nvar normalWorld: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvertexOutputs.vNormalW=normalUpdated/ vec3f(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vertexOutputs.vNormalW=normalize(normalWorld*vertexOutputs.vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvertexOutputs.vNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#endif\n#define CUSTOM_VERTEX_UPDATE_WORLDPOS\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {vertexOutputs.position=scene.viewProjection*worldPos;} else {vertexOutputs.position=scene.viewProjectionR*worldPos;}\n#else\nvertexOutputs.position=scene.viewProjection*worldPos;\n#endif\nvertexOutputs.vPositionW= worldPos.xyz;\n#ifdef PREPASS\n#include\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvertexOutputs.vDirectionW=normalize((finalWorld* vec4f(positionUpdated,0.0)).xyz);\n#endif\n#ifndef UV1\nvar uvUpdated: vec2f=vec2f(0.,0.);\n#endif\n#ifdef MAINUV1\nvertexOutputs.vMainUV1=uvUpdated;\n#endif\n#include[2..7]\n#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)\n#if defined(SPECULARTERM)\n#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x)\n#endif\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},66246:(e,t,i)=>{"use strict";i.r(t),i.d(t,{depthPixelShaderWGSL:()=>o});var r=i(69841);i(96140),i(2456),i(76794);const s="depthPixelShader",n="#ifdef ALPHATEST\nvarying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d;\n#endif\n#include\nvarying vDepthMetric: f32;\n#ifdef PACKED\n#include\n#endif\n#ifdef STORE_CAMERASPACE_Z\nvarying vViewPos: vec4f;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#include\n#ifdef ALPHATEST\nif (textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV).a<0.4) {discard;}\n#endif\n#ifdef STORE_CAMERASPACE_Z\n#ifdef PACKED\nfragmentOutputs.color=pack(input.vViewPos.z);\n#else\nfragmentOutputs.color= vec4f(input.vViewPos.z,0.0,0.0,1.0);\n#endif\n#else\n#ifdef NONLINEARDEPTH\n#ifdef PACKED\nfragmentOutputs.color=pack(input.position.z);\n#else\nfragmentOutputs.color= vec4f(input.position.z,0.0,0.0,0.0);\n#endif\n#else\n#ifdef PACKED\nfragmentOutputs.color=pack(input.vDepthMetric);\n#else\nfragmentOutputs.color= vec4f(input.vDepthMetric,0.0,0.0,1.0);\n#endif\n#endif\n#endif\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},61420:(e,t,i)=>{"use strict";i.r(t),i.d(t,{depthVertexShaderWGSL:()=>o});var r=i(69841);i(25589),i(68273),i(47381),i(51148),i(30486),i(41416),i(8573),i(43610),i(32764),i(40903),i(71281),i(57728);const s="depthVertexShader",n="attribute position: vec3f;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform viewProjection: mat4x4f;uniform depthValues: vec2f;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vUV: vec2f;uniform diffuseMatrix: mat4x4f;\n#ifdef UV1\nattribute uv: vec2f;\n#endif\n#ifdef UV2\nattribute uv2: vec2f;\n#endif\n#endif\n#ifdef STORE_CAMERASPACE_Z\nuniform view: mat4x4f;varying vViewPos: vec4f;\n#endif\nvarying vDepthMetric: f32;\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;\n#ifdef UV1\nvar uvUpdated: vec2f=input.uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvar worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);\n#include\nvertexOutputs.position=uniforms.viewProjection*worldPos;\n#ifdef STORE_CAMERASPACE_Z\nvertexOutputs.vViewPos=uniforms.view*worldPos;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric=((-vertexOutputs.position.z+uniforms.depthValues.x)/(uniforms.depthValues.y));\n#else\nvertexOutputs.vDepthMetric=((vertexOutputs.position.z+uniforms.depthValues.x)/(uniforms.depthValues.y));\n#endif\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy;\n#endif\n#ifdef UV2\nvertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(input.uv2,1.0,0.0)).xy;\n#endif\n#endif\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},32472:(e,t,i)=>{"use strict";i.r(t),i.d(t,{depthBoxBlurPixelShaderWGSL:()=>n});const r="depthBoxBlurPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var colorDepth: vec4f=vec4f(0.0);for (var x: i32=-OFFSET; x<=OFFSET; x++) {for (var y: i32=-OFFSET; y<=OFFSET; y++) {colorDepth+=textureSample(textureSampler,textureSamplerSampler,input.vUV+ vec2f(f32(x),f32(y))/uniforms.screenSize);}}\nfragmentOutputs.color=(colorDepth/ f32((OFFSET*2+1)*(OFFSET*2+1)));}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},41289:(e,t,i)=>{"use strict";i.r(t),i.d(t,{depthOfFieldMergePixelShaderWGSL:()=>n});const r="depthOfFieldMergePixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var circleOfConfusionSamplerSampler: sampler;var circleOfConfusionSampler: texture_2d;var blurStep0Sampler: sampler;var blurStep0: texture_2d;\n#if BLUR_LEVEL>0\nvar blurStep1Sampler: sampler;var blurStep1: texture_2d;\n#endif\n#if BLUR_LEVEL>1\nvar blurStep2Sampler: sampler;var blurStep2: texture_2d;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var coc: f32=textureSampleLevel(circleOfConfusionSampler,circleOfConfusionSamplerSampler,input.vUV,0.0).r;\n#if BLUR_LEVEL==0\nvar original: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var blurred0: vec4f=textureSampleLevel(blurStep0,blurStep0Sampler,input.vUV,0.0);fragmentOutputs.color=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL==1\nif(coc<0.5){var original: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);fragmentOutputs.color=mix(original,blurred1,coc/0.5);}else{var blurred0: vec4f=textureSampleLevel(blurStep0,blurStep0Sampler,input.vUV,0.0);var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);fragmentOutputs.color=mix(blurred1,blurred0,(coc-0.5)/0.5);}\n#endif\n#if BLUR_LEVEL==2\nif(coc<0.33){var original: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var blurred2: vec4f=textureSampleLevel(blurStep2,blurStep2Sampler,input.vUV,0.0);fragmentOutputs.color=mix(original,blurred2,coc/0.33);}else if(coc<0.66){var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);var blurred2: vec4f=textureSampleLevel(blurStep2,blurStep2Sampler,input.vUV,0.0);fragmentOutputs.color=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{var blurred0: vec4f=textureSampleLevel(blurStep0,blurStep0Sampler,input.vUV,0.0);var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);fragmentOutputs.color=mix(blurred1,blurred0,(coc-0.66)/0.34);}\n#endif\n}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},63788:(e,t,i)=>{"use strict";i.r(t),i.d(t,{displayPassPixelShaderWGSL:()=>n});const r="displayPassPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var passSamplerSampler: sampler;var passSampler: texture_2d;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(passSampler,passSamplerSampler,input.vUV);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},9574:(e,t,i)=>{"use strict";i.r(t),i.d(t,{extractHighlightsPixelShaderWGSL:()=>o});var r=i(69841);i(87647);const s="extractHighlightsPixelShader",n="#include\nvarying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform threshold: f32;uniform exposure: f32;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);var luma: f32=dot(LuminanceEncodeApprox,fragmentOutputs.color.rgb*uniforms.exposure);fragmentOutputs.color=vec4f(step(uniforms.threshold,luma)*fragmentOutputs.color.rgb,fragmentOutputs.color.a);}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},26879:(e,t,i)=>{"use strict";i.r(t),i.d(t,{filterPixelShaderWGSL:()=>n});const r="filterPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform kernelMatrix: mat4x4f;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var baseColor: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var updatedColor: vec3f=(uniforms.kernelMatrix* vec4f(baseColor,1.0)).rgb;fragmentOutputs.color= vec4f(updatedColor,1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},92862:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingBilateralBlurPixelShaderWGSL:()=>n});const r="fluidRenderingBilateralBlurPixelShader",s="var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform maxFilterSize: i32;uniform blurDir: vec2f;uniform projectedParticleConstant: f32;uniform depthThreshold: f32;varying vUV: vec2f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var depth: f32=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.).x;if (depth>=1e6 || depth<=0.) {fragmentOutputs.color=vec4f(vec3f(depth),1.);return fragmentOutputs;}\nvar filterSize: i32=min(uniforms.maxFilterSize,i32(ceil(uniforms.projectedParticleConstant/depth)));var sigma: f32=f32(filterSize)/3.0;var two_sigma2: f32=2.0*sigma*sigma;var sigmaDepth: f32=uniforms.depthThreshold/3.0;var two_sigmaDepth2: f32=2.0*sigmaDepth*sigmaDepth;var sum: f32=0.;var wsum: f32=0.;var sumVel: f32=0.;for (var x: i32=-filterSize; x<=filterSize; x++) {var coords: vec2f=vec2f(f32(x));var sampleDepthVel: vec2f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV+coords*uniforms.blurDir,0.).rg;var r: f32=dot(coords,coords);var w: f32=exp(-r/two_sigma2);var rDepth: f32=sampleDepthVel.r-depth;var wd: f32=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;}\nfragmentOutputs.color=vec4f(sum/wsum,sumVel/wsum,0.,1.);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},40264:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingParticleDepthPixelShaderWGSL:()=>n});const r="fluidRenderingParticleDepthPixelShader",s="uniform projection: mat4x4f;varying uv: vec2f;varying viewPos: vec3f;varying sphereRadius: f32;\n#ifdef FLUIDRENDERING_VELOCITY\nvarying velocityNorm: f32;\n#endif\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var normalxy: vec2f=input.uv*2.0-1.0;var r2: f32=dot(normalxy,normalxy);if (r2>1.0) {discard;}\nvar normal: vec3f=vec3f(normalxy,sqrt(1.0-r2));\n#ifndef FLUIDRENDERING_RHS\nnormal.z=-normal.z;\n#endif\nvar realViewPos: vec4f=vec4f(input.viewPos+normal*input.sphereRadius,1.0);var clipSpacePos: vec4f=uniforms.projection*realViewPos;fragmentOutputs.fragDepth=clipSpacePos.z/clipSpacePos.w;\n#ifdef FLUIDRENDERING_RHS\nrealViewPos.z=-realViewPos.z;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nfragmentOutputs.color=vec4f(realViewPos.z,input.velocityNorm,0.,1.);\n#else\nfragmentOutputs.color=vec4f(realViewPos.z,0.,0.,1.);\n#endif\n}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},27014:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingParticleDepthVertexShaderWGSL:()=>n});const r="fluidRenderingParticleDepthVertexShader",s="attribute position: vec3f;attribute offset: vec2f;uniform view: mat4x4f;uniform projection: mat4x4f;uniform size: vec2f;varying uv: vec2f;varying viewPos: vec3f;varying sphereRadius: f32;\n#ifdef FLUIDRENDERING_VELOCITY\nattribute velocity: vec3f;varying velocityNorm: f32;\n#endif\n@vertex\nfn main(input: VertexInputs)->FragmentInputs {var cornerPos: vec3f=vec3f(\nvec2f(input.offset.x-0.5,input.offset.y-0.5)*uniforms.size,\n0.0\n);vertexOutputs.viewPos=(uniforms.view*vec4f(input.position,1.0)).xyz;vertexOutputs.position=uniforms.projection*vec4f(vertexOutputs.viewPos+cornerPos,1.0);vertexOutputs.uv=input.offset;vertexOutputs.sphereRadius=uniforms.size.x/2.0;\n#ifdef FLUIDRENDERING_VELOCITY\nvertexOutputs.velocityNorm=length(velocity);\n#endif\n}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},89753:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingParticleDiffusePixelShaderWGSL:()=>n});const r="fluidRenderingParticleDiffusePixelShader",s="uniform particleAlpha: f32;varying uv: vec2f;varying diffuseColor: vec3f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var normalxy: vec2f=input.uv*2.0-1.0;var r2: f32=dot(normalxy,normalxy);if (r2>1.0) {discard;}\nfragmentOutputs.color=vec4f(input.diffuseColor,1.0);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},45261:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingParticleThicknessPixelShaderWGSL:()=>n});const r="fluidRenderingParticleThicknessPixelShader",s="uniform particleAlpha: f32;varying uv: vec2f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var normalxy: vec2f=input.uv*2.0-1.0;var r2: f32=dot(normalxy,normalxy);if (r2>1.0) {discard;}\nvar thickness: f32=sqrt(1.0-r2);fragmentOutputs.color=vec4f(vec3f(uniforms.particleAlpha*thickness),1.0);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},64615:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingParticleThicknessVertexShaderWGSL:()=>n});const r="fluidRenderingParticleThicknessVertexShader",s="attribute position: vec3f;attribute offset: vec2f;uniform view: mat4x4f;uniform projection: mat4x4f;uniform size: vec2f;varying uv: vec2f;@vertex\nfn main(input: VertexInputs)->FragmentInputs {var cornerPos: vec3f=vec3f(\nvec2f(input.offset.x-0.5,input.offset.y-0.5)*uniforms.size,\n0.0\n);var viewPos: vec3f=(uniforms.view*vec4f(input.position,1.0)).xyz+cornerPos;vertexOutputs.position=uniforms.projection*vec4f(viewPos,1.0);vertexOutputs.uv=input.offset;}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},37009:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingRenderPixelShaderWGSL:()=>n});const r="fluidRenderingRenderPixelShader",s="#define DISABLE_UNIFORMITY_ANALYSIS\n#define IOR 1.333\n#define ETA 1.0/IOR\n#define F0 0.02\nvar textureSamplerSampler: sampler;var textureSampler: texture_2d;var depthSamplerSampler: sampler;var depthSampler: texture_2d;\n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nvar diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d;\n#else\nuniform diffuseColor: vec3f;\n#endif\n#ifdef FLUIDRENDERING_FIXED_THICKNESS\nuniform thickness: f32;var bgDepthSamplerSampler: sampler;var bgDepthSampler: texture_2d;\n#else\nuniform minimumThickness: f32;var thicknessSamplerSampler: sampler;var thicknessSampler: texture_2d;\n#endif\n#ifdef FLUIDRENDERING_ENVIRONMENT\nvar reflectionSamplerSampler: sampler;var reflectionSampler: texture_cube;\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nvar debugSamplerSampler: sampler;var debugSampler: texture_2d;\n#endif\nuniform viewMatrix: mat4x4f;uniform projectionMatrix: mat4x4f;uniform invProjectionMatrix: mat4x4f;uniform texelSize: vec2f;uniform dirLight: vec3f;uniform cameraFar: f32;uniform density: f32;uniform refractionStrength: f32;uniform fresnelClamp: f32;uniform specularPower: f32;varying vUV: vec2f;fn computeViewPosFromUVDepth(texCoord: vec2f,depth: f32)->vec3f {var ndc: vec4f=vec4f(texCoord*2.0-1.0,0.0,1.0);\n#ifdef FLUIDRENDERING_RHS\nndc.z=-uniforms.projectionMatrix[2].z+uniforms.projectionMatrix[3].z/depth;\n#else\nndc.z=uniforms.projectionMatrix[2].z+uniforms.projectionMatrix[3].z/depth;\n#endif\nndc.w=1.0;var eyePos: vec4f=uniforms.invProjectionMatrix*ndc;return eyePos.xyz/eyePos.w;}\nfn getViewPosFromTexCoord(texCoord: vec2f)->vec3f {var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);}\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var texCoord: vec2f=input.vUV;\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nvar color: vec4f=textureSample(debugSampler,debugSamplerSampler,texCoord);\n#ifdef FLUIDRENDERING_DEBUG_DEPTH\nfragmentOutputs.color=vec4f(color.rgb/vec3f(2.0),1.);if (color.r>0.999 && color.g>0.999) {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,texCoord);}\n#else\nfragmentOutputs.color=vec4f(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,texCoord);}\n#endif\nreturn fragmentOutputs;\n#endif\nvar depthVel: vec2f=textureSampleLevel(depthSampler,depthSamplerSampler,texCoord,0.).rg;var depth: f32=depthVel.r;\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nvar thickness: f32=textureSample(thicknessSampler,thicknessSamplerSampler,texCoord).x;\n#else\nvar thickness: f32=uniforms.thickness;var bgDepth: f32=textureSample(bgDepthSampler,bgDepthSamplerSampler,texCoord).x;var depthNonLinear: f32=uniforms.projectionMatrix[2].z+uniforms.projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5;\n#endif\nvar backColor: vec4f=textureSample(textureSampler,textureSamplerSampler,texCoord);\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nif (depth>=uniforms.cameraFar || depth<=0. || thickness<=uniforms.minimumThickness) {\n#else\nif (depth>=uniforms.cameraFar || depth<=0. || bgDepth<=depthNonLinear) {\n#endif\n#ifdef FLUIDRENDERING_COMPOSITE_MODE\nfragmentOutputs.color=vec4f(backColor.rgb*backColor.a,backColor.a);\n#else\nfragmentOutputs.color=backColor;\n#endif\nreturn fragmentOutputs;}\nvar viewPos: vec3f=computeViewPosFromUVDepth(texCoord,depth);var ddx: vec3f=getViewPosFromTexCoord(texCoord+vec2f(uniforms.texelSize.x,0.))-viewPos;var ddy: vec3f=getViewPosFromTexCoord(texCoord+vec2f(0.,uniforms.texelSize.y))-viewPos;var ddx2: vec3f=viewPos-getViewPosFromTexCoord(texCoord+vec2f(-uniforms.texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;}\nvar ddy2: vec3f=viewPos-getViewPosFromTexCoord(texCoord+vec2f(0.,-uniforms.texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;}\nvar normal: vec3f=normalize(cross(ddy,ddx));\n#ifdef FLUIDRENDERING_RHS\nnormal=-normal;\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL)\nfragmentOutputs.color=vec4f(normal*0.5+0.5,1.0);return fragmentOutputs;\n#endif\nvar rayDir: vec3f=normalize(viewPos); \n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nvar diffuseColor: vec3f=textureSampleLevel(diffuseSampler,diffuseSamplerSampler,texCoord,0.0).rgb;\n#else\nvar diffuseColor: vec3f=uniforms.diffuseColor;\n#endif\nvar lightDir: vec3f=normalize((uniforms.viewMatrix*vec4f(-uniforms.dirLight,0.)).xyz);var H: vec3f =normalize(lightDir-rayDir);var specular: f32 =pow(max(0.0,dot(H,normal)),uniforms.specularPower);\n#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING\nvar diffuse: f32 =max(0.0,dot(lightDir,normal))*1.0;fragmentOutputs.color=vec4f(vec3f(0.1) /*ambient*/+vec3f(0.42,0.50,1.00)*diffuse+vec3f(0,0,0.2)+specular,1.);return fragmentOutputs;\n#endif\nvar refractionDir: vec3f=refract(rayDir,normal,ETA);var transmitted: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,vec2f(texCoord+refractionDir.xy*thickness*uniforms.refractionStrength),0.0);\n#ifdef FLUIDRENDERING_COMPOSITE_MODE\nif (transmitted.a==0.) {transmitted.a=thickness;}\n#endif\nvar transmittance: vec3f=exp(-uniforms.density*thickness*(1.0-diffuseColor)); \nvar refractionColor: vec3f=transmitted.rgb*transmittance;\n#ifdef FLUIDRENDERING_ENVIRONMENT\nvar reflectionDir: vec3f=reflect(rayDir,normal);var reflectionColor: vec3f=(textureSample(reflectionSampler,reflectionSamplerSampler,reflectionDir).rgb);var fresnel: f32=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,uniforms.fresnelClamp);var finalColor: vec3f=mix(refractionColor,reflectionColor,fresnel)+specular;\n#else\nvar finalColor: vec3f=refractionColor+specular;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nvar velocity: f32=depthVel.g;finalColor=mix(finalColor,vec3f(1.0),smoothstep(0.3,1.0,velocity/6.0));\n#endif\nfragmentOutputs.color=vec4f(finalColor,transmitted.a);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},5769:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingStandardBlurPixelShaderWGSL:()=>n});const r="fluidRenderingStandardBlurPixelShader",s="var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform filterSize: i32;uniform blurDir: vec2f;varying vUV: vec2f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var s: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.);if (s.r==0.) {fragmentOutputs.color=vec4f(0.,0.,0.,1.);return fragmentOutputs;}\nvar sigma: f32=f32(uniforms.filterSize)/3.0;var twoSigma2: f32=2.0*sigma*sigma;var sum: vec4f=vec4f(0.);var wsum: f32=0.;for (var x: i32=-uniforms.filterSize; x<=uniforms.filterSize; x++) {var coords: vec2f=vec2f(f32(x));var sampl: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV+coords*uniforms.blurDir,0.);var w: f32=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;}\nsum/=wsum;fragmentOutputs.color=vec4f(sum.rgb,1.);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},54525:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fxaaPixelShaderWGSL:()=>n});const r="fxaaPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform texelSize: vec2f;varying sampleCoordS: vec2f;varying sampleCoordE: vec2f;varying sampleCoordN: vec2f;varying sampleCoordW: vec2f;varying sampleCoordNW: vec2f;varying sampleCoordSE: vec2f;varying sampleCoordNE: vec2f;varying sampleCoordSW: vec2f;const fxaaQualitySubpix: f32=1.0;const fxaaQualityEdgeThreshold: f32=0.166;const fxaaQualityEdgeThresholdMin: f32=0.0833;const kLumaCoefficients: vec3f= vec3f(0.2126,0.7152,0.0722);fn FxaaLuma(rgba: vec4f)->f32 {return dot(rgba.rgb,kLumaCoefficients);} \n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var posM: vec2f;posM.x=input.vUV.x;posM.y=input.vUV.y;var rgbyM: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var lumaM: f32=FxaaLuma(rgbyM);var lumaS: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordS,0.0));var lumaE: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordE,0.0));var lumaN: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordN,0.0));var lumaW: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordW,0.0));var maxSM: f32=max(lumaS,lumaM);var minSM: f32=min(lumaS,lumaM);var maxESM: f32=max(lumaE,maxSM);var minESM: f32=min(lumaE,minSM);var maxWN: f32=max(lumaN,lumaW);var minWN: f32=min(lumaN,lumaW);var rangeMax: f32=max(maxWN,maxESM);var rangeMin: f32=min(minWN,minESM);var rangeMaxScaled: f32=rangeMax*fxaaQualityEdgeThreshold;var range: f32=rangeMax-rangeMin;var rangeMaxClamped: f32=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range=edgeVert;var subpixA: f32=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan)\n{lumaN=lumaW;}\nif (!horzSpan) \n{lumaS=lumaE;}\nif (horzSpan) \n{lengthSign=uniforms.texelSize.y;}\nvar subpixB: f32=(subpixA*(1.0/12.0))-lumaM;var gradientN: f32=lumaN-lumaM;var gradientS: f32=lumaS-lumaM;var lumaNN: f32=lumaN+lumaM;var lumaSS: f32=lumaS+lumaM;var pairN: bool=abs(gradientN)>=abs(gradientS);var gradient: f32=max(abs(gradientN),abs(gradientS));if (pairN)\n{lengthSign=-lengthSign;}\nvar subpixC: f32=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);var posB: vec2f;posB.x=posM.x;posB.y=posM.y;var offNP: vec2f;offNP.x=select(uniforms.texelSize.x,0.0,(!horzSpan));offNP.y=select(uniforms.texelSize.y,0.0,(horzSpan));if (!horzSpan) \n{posB.x+=lengthSign*0.5;}\nif (horzSpan)\n{posB.y+=lengthSign*0.5;}\nvar posN: vec2f;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;var posP: vec2f;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;var subpixD: f32=((-2.0)*subpixC)+3.0;var lumaEndN: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posN,0.0));var subpixE: f32=subpixC*subpixC;var lumaEndP: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posP,0.0));if (!pairN) \n{lumaNN=lumaSS;}\nvar gradientScaled: f32=gradient*1.0/4.0;var lumaMM: f32=lumaM-lumaNN*0.5;var subpixF: f32=subpixD*subpixE;var lumaMLTZero: bool=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;var doneN: bool=abs(lumaEndN)>=gradientScaled;var doneP: bool=abs(lumaEndP)>=gradientScaled;if (!doneN) \n{posN.x-=offNP.x*3.0;}\nif (!doneN) \n{posN.y-=offNP.y*3.0;}\nvar doneNP: bool=(!doneN) || (!doneP);if (!doneP) \n{posP.x+=offNP.x*3.0;}\nif (!doneP)\n{posP.y+=offNP.y*3.0;}\nif (doneNP)\n{if (!doneN) {lumaEndN=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posN.xy,0.0));}\nif (!doneP) {lumaEndP=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posP.xy,0.0));}\nif (!doneN) {lumaEndN=lumaEndN-lumaNN*0.5;}\nif (!doneP) {lumaEndP=lumaEndP-lumaNN*0.5;}\ndoneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) {posN.x-=offNP.x*12.0;}\nif (!doneN) {posN.y-=offNP.y*12.0;}\ndoneNP=(!doneN) || (!doneP);if (!doneP) {posP.x+=offNP.x*12.0;}\nif (!doneP) {posP.y+=offNP.y*12.0;}}\nvar dstN: f32=posM.x-posN.x;var dstP: f32=posP.x-posM.x;if (!horzSpan)\n{dstN=posM.y-posN.y;}\nif (!horzSpan) \n{dstP=posP.y-posM.y;}\nvar goodSpanN: bool=(lumaEndN<0.0) != lumaMLTZero;var spanLength: f32=(dstP+dstN);var goodSpanP: bool=(lumaEndP<0.0) != lumaMLTZero;var spanLengthRcp: f32=1.0/spanLength;var directionN: bool=dstN{"use strict";i.r(t),i.d(t,{fxaaVertexShaderWGSL:()=>n});const r="fxaaVertexShader",s="attribute position: vec2f;uniform texelSize: vec2f;varying vUV: vec2f;varying sampleCoordS: vec2f;varying sampleCoordE: vec2f;varying sampleCoordN: vec2f;varying sampleCoordW: vec2f;varying sampleCoordNW: vec2f;varying sampleCoordSE: vec2f;varying sampleCoordNE: vec2f;varying sampleCoordSW: vec2f;const madd: vec2f= vec2f(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.vUV=(input.position*madd+madd);vertexOutputs.sampleCoordS=vertexOutputs.vUV+ vec2f( 0.0,1.0)*uniforms.texelSize;vertexOutputs.sampleCoordE=vertexOutputs.vUV+ vec2f( 1.0,0.0)*uniforms.texelSize;vertexOutputs.sampleCoordN=vertexOutputs.vUV+ vec2f( 0.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordW=vertexOutputs.vUV+ vec2f(-1.0,0.0)*uniforms.texelSize;vertexOutputs.sampleCoordNW=vertexOutputs.vUV+ vec2f(-1.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordSE=vertexOutputs.vUV+ vec2f( 1.0,1.0)*uniforms.texelSize;vertexOutputs.sampleCoordNE=vertexOutputs.vUV+ vec2f( 1.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordSW=vertexOutputs.vUV+ vec2f(-1.0,1.0)*uniforms.texelSize;vertexOutputs.position=vec4f(input.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},99407:(e,t,i)=>{"use strict";i.r(t),i.d(t,{gaussianSplattingPixelShaderWGSL:()=>o});var r=i(69841);i(96140),i(21859),i(10668),i(85551),i(31034);r.l.IncludesShadersStoreWGSL.gaussianSplattingFragmentDeclaration="fn gaussianColor(inColor: vec4f,inPosition: vec2f)->vec4f\n{var A : f32=-dot(inPosition,inPosition);if (A>-4.0)\n{var B: f32=exp(A)*inColor.a;\n#include\nvar color: vec3f=inColor.rgb;\n#ifdef FOG\n#include\n#endif\nreturn vec4f(color,B);} else {return vec4f(0.0);}}\n",i(76794);const s="gaussianSplattingPixelShader",n="#include\n#include\n#include\nvarying vColor: vec4f;varying vPosition: vec2f;\n#include\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#include\nfragmentOutputs.color=gaussianColor(input.vColor,input.vPosition);}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},92026:(e,t,i)=>{"use strict";i.r(t),i.d(t,{gaussianSplattingVertexShaderWGSL:()=>o});var r=i(69841);i(14910),i(10598),i(30486),i(86934),i(21859);r.l.IncludesShadersStoreWGSL.gaussianSplatting="fn getDataUV(index: f32,dataTextureSize: vec2f)->vec2 {let y: f32=floor(index/dataTextureSize.x);let x: f32=index-y*dataTextureSize.x;return vec2f((x+0.5),(y+0.5));}\nstruct Splat {center: vec4f,\ncolor: vec4f,\ncovA: vec4f,\ncovB: vec4f,};fn readSplat(splatIndex: f32,dataTextureSize: vec2f)->Splat {var splat: Splat;let splatUV=getDataUV(splatIndex,dataTextureSize);let splatUVi32=vec2(i32(splatUV.x),i32(splatUV.y));splat.center=textureLoad(centersTexture,splatUVi32,0);splat.color=textureLoad(colorsTexture,splatUVi32,0);splat.covA=textureLoad(covariancesATexture,splatUVi32,0)*splat.center.w;splat.covB=textureLoad(covariancesBTexture,splatUVi32,0)*splat.center.w;return splat;}\nfn gaussianSplatting(\nmeshPos: vec2,\nworldPos: vec3,\nscale: vec2,\ncovA: vec3,\ncovB: vec3,\nworldMatrix: mat4x4,\nviewMatrix: mat4x4,\nprojectionMatrix: mat4x4,\nfocal: vec2f,\ninvViewport: vec2f\n)->vec4f {let modelView=viewMatrix*worldMatrix;let camspace=viewMatrix*vec4f(worldPos,1.0);let pos2d=projectionMatrix*camspace;let bounds=1.2*pos2d.w;if (pos2d.z<0. || pos2d.x<-bounds || pos2d.x>bounds || pos2d.y<-bounds || pos2d.y>bounds) {return vec4f(0.0,0.0,2.0,1.0);}\nlet Vrk=mat3x3(\ncovA.x,covA.y,covA.z,\ncovA.y,covB.x,covB.y,\ncovA.z,covB.y,covB.z\n);let J=mat3x3(\nfocal.x/camspace.z,0.0,-(focal.x*camspace.x)/(camspace.z*camspace.z),\n0.0,focal.y/camspace.z,-(focal.y*camspace.y)/(camspace.z*camspace.z),\n0.0,0.0,0.0\n);let invy=mat3x3(\n1.0,0.0,0.0,\n0.0,-1.0,0.0,\n0.0,0.0,1.0\n);let T=invy*transpose(mat3x3(\nmodelView[0].xyz,\nmodelView[1].xyz,\nmodelView[2].xyz))*J;let cov2d=transpose(T)*Vrk*T;let mid=(cov2d[0][0]+cov2d[1][1])/2.0;let radius=length(vec2((cov2d[0][0]-cov2d[1][1])/2.0,cov2d[0][1]));let lambda1=mid+radius;let lambda2=mid-radius;if (lambda2<0.0) {return vec4f(0.0,0.0,2.0,1.0);}\nlet diagonalVector=normalize(vec2(cov2d[0][1],lambda1-cov2d[0][0]));let majorAxis=min(sqrt(2.0*lambda1),1024.0)*diagonalVector;let minorAxis=min(sqrt(2.0*lambda2),1024.0)*vec2(diagonalVector.y,-diagonalVector.x);let vCenter=vec2(pos2d.x,pos2d.y);return vec4f(\nvCenter+((meshPos.x*majorAxis+meshPos.y*minorAxis)*invViewport*pos2d.w)*scale,\npos2d.z,\npos2d.w\n);}\n",i(57728),i(45184),i(18201);const s="gaussianSplattingVertexShader",n="#include\n#include\n#include\n#include\n#include\nattribute splatIndex: f32;attribute position: vec2f;uniform invViewport: vec2f;uniform dataTextureSize: vec2f;uniform focal: vec2f;var covariancesATexture: texture_2d;var covariancesBTexture: texture_2d;var centersTexture: texture_2d;var colorsTexture: texture_2d;varying vColor: vec4f;varying vPosition: vec2f;\n#include\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {var splat: Splat=readSplat(input.splatIndex,uniforms.dataTextureSize);var covA: vec3f=splat.covA.xyz;var covB: vec3f=vec3f(splat.covA.w,splat.covB.xy);let worldPos: vec4f=mesh.world*vec4f(splat.center.xyz,1.0);vertexOutputs.vColor=splat.color;vertexOutputs.vPosition=input.position;vertexOutputs.position=gaussianSplatting(input.position,worldPos.xyz,vec2f(1.0,1.0),covA,covB,mesh.world,scene.view,scene.projection,uniforms.focal,uniforms.invViewport);\n#include\n#include\n#include\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},55745:(e,t,i)=>{"use strict";i.r(t),i.d(t,{geometryPixelShaderWGSL:()=>o});var r=i(69841);i(96140),i(56332),i(87087),i(87647),i(76794),i(99312);const s="geometryPixelShader",n="#ifdef BUMP\nvarying vWorldView0: vec4f;varying vWorldView1: vec4f;varying vWorldView2: vec4f;varying vWorldView3: vec4f;varying vNormalW: vec3f;\n#else\nvarying vNormalV: vec3f;\n#endif\nvarying vViewPos: vec4f;\n#if defined(POSITION) || defined(BUMP)\nvarying vPositionW: vec3f;\n#endif\n#if defined(VELOCITY) || defined(VELOCITY_LINEAR)\nvarying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f;\n#endif\n#ifdef NEED_UV\nvarying vUV: vec2f;\n#endif\n#ifdef BUMP\nuniform vBumpInfos: vec3f;uniform vTangentSpaceParams: vec2f;\n#endif\n#if defined(REFLECTIVITY)\n#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nvar reflectivitySamplerSampler: sampler;var reflectivitySampler: texture_2d;varying vReflectivityUV: vec2f;\n#endif\n#ifdef ALBEDOTEXTURE\nvarying vAlbedoUV: vec2f;var albedoSamplerSampler: sampler;var albedoSampler: texture_2d;\n#endif\n#ifdef REFLECTIVITYCOLOR\nuniform reflectivityColor: vec3f;\n#endif\n#ifdef ALBEDOCOLOR\nuniform albedoColor: vec3f;\n#endif\n#ifdef METALLIC\nuniform metallic: f32;\n#endif\n#if defined(ROUGHNESS) || defined(GLOSSINESS)\nuniform glossiness: f32;\n#endif\n#endif\n#if defined(ALPHATEST) && defined(NEED_UV)\nvar diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d;\n#endif\n#include\n#include\n#include\n#include\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#include\n#ifdef ALPHATEST\nif (textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV).a<0.4) {discard;}\n#endif\nvar normalOutput: vec3f;\n#ifdef BUMP\nvar normalW: vec3f=normalize(input.vNormalW);\n#include\n#ifdef NORMAL_WORLDSPACE\nnormalOutput=normalW;\n#else\nnormalOutput=normalize( vec3f(mat4x4f(input.vWorldView0,input.vWorldView0,input.vWorldView2,input.vWorldView3)* vec4f(normalW,0.0)));\n#endif\n#else\nnormalOutput=normalize(input.vNormalV);\n#endif\n#ifdef ENCODE_NORMAL\nnormalOutput=normalOutput*0.5+0.5;\n#endif\nvar fragData: array,SCENE_MRT_COUNT>;\n#ifdef DEPTH\nfragData[DEPTH_INDEX]=vec4f(input.vViewPos.z/input.vViewPos.w,0.0,0.0,1.0);\n#endif\n#ifdef NORMAL\nfragData[NORMAL_INDEX]=vec4f(normalOutput,1.0);\n#endif\n#ifdef SCREENSPACE_DEPTH\nfragData[SCREENSPACE_DEPTH_INDEX]=vec4f(fragmentInputs.position.z,0.0,0.0,1.0);\n#endif\n#ifdef POSITION\nfragData[POSITION_INDEX]= vec4f(input.vPositionW,1.0);\n#endif\n#ifdef VELOCITY\nvar a: vec2f=(input.vCurrentPosition.xy/input.vCurrentPosition.w)*0.5+0.5;var b: vec2f=(input.vPreviousPosition.xy/input.vPreviousPosition.w)*0.5+0.5;var velocity: vec2f=abs(a-b);velocity= vec2f(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;fragData[VELOCITY_INDEX]= vec4f(velocity,0.0,1.0);\n#endif\n#ifdef VELOCITY_LINEAR\nvar velocity : vec2f=vec2f(0.5)*((input.vPreviousPosition.xy /\ninput.vPreviousPosition.w) -\n(input.vCurrentPosition.xy /\ninput.vCurrentPosition.w));fragData[VELOCITY_LINEAR_INDEX]=vec4f(velocity,0.0,1.0);\n#endif\n#ifdef REFLECTIVITY\nvar reflectivity: vec4f= vec4f(0.0,0.0,0.0,1.0);\n#ifdef METALLICWORKFLOW\nvar metal: f32=1.0;var roughness: f32=1.0;\n#ifdef ORMTEXTURE\nmetal*=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV).b;roughness*=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV).g;\n#endif\n#ifdef METALLIC\nmetal*=uniforms.metallic;\n#endif\n#ifdef ROUGHNESS\nroughness*=(1.0-uniforms.glossiness); \n#endif\nreflectivity=vec4f(reflectivity.rgb,reflectivity.a-roughness);var color: vec3f= vec3f(1.0);\n#ifdef ALBEDOTEXTURE\ncolor=textureSample(albedoSampler,albedoSamplerSampler,input.vAlbedoUV).rgb;\n#ifdef GAMMAALBEDO\ncolor=toLinearSpaceVec4(color);\n#endif\n#endif\n#ifdef ALBEDOCOLOR\ncolor*=uniforms.albedoColor.xyz;\n#endif\nreflectivity=vec4f(mix( vec3f(0.04),color,metal),reflectivity.a);\n#else\n#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nreflectivity=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV);\n#ifdef GAMMAREFLECTIVITYTEXTURE\nreflectivity=vec4f(toLinearSpaceVec3(reflectivity.rgb),reflectivity.a);\n#endif\n#else \n#ifdef REFLECTIVITYCOLOR\nreflectivity=vec4f(toLinearSpaceVec3(uniforms.reflectivityColor.xyz),1.0);\n#endif\n#endif\n#ifdef GLOSSINESSS\nreflectivity=vec4f(reflectivity.rgb,reflectivity.a*glossiness); \n#endif\n#endif\nfragData[REFLECTIVITY_INDEX]=reflectivity;\n#endif\n#if SCENE_MRT_COUNT>0\nfragmentOutputs.fragData0=fragData[0];\n#endif\n#if SCENE_MRT_COUNT>1\nfragmentOutputs.fragData1=fragData[1];\n#endif\n#if SCENE_MRT_COUNT>2\nfragmentOutputs.fragData2=fragData[2];\n#endif\n#if SCENE_MRT_COUNT>3\nfragmentOutputs.fragData3=fragData[3];\n#endif\n#if SCENE_MRT_COUNT>4\nfragmentOutputs.fragData4=fragData[4];\n#endif\n#if SCENE_MRT_COUNT>5\nfragmentOutputs.fragData5=fragData[5];\n#endif\n#if SCENE_MRT_COUNT>6\nfragmentOutputs.fragData6=fragData[6];\n#endif\n#if SCENE_MRT_COUNT>7\nfragmentOutputs.fragData7=fragData[7];\n#endif\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},20267:(e,t,i)=>{"use strict";i.r(t),i.d(t,{geometryVertexShaderWGSL:()=>o});var r=i(69841);i(25589),i(68273),i(47381),i(51148),i(41416),i(14910),i(30486),i(8573),i(43610),i(32764),i(40903),i(71281),i(57728),i(73918);const s="geometryVertexShader",n="#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nattribute position: vec3f;attribute normal: vec3f;\n#ifdef NEED_UV\nvarying vUV: vec2f;\n#ifdef ALPHATEST\nuniform diffuseMatrix: mat4x4f;\n#endif\n#ifdef BUMP\nuniform bumpMatrix: mat4x4f;varying vBumpUV: vec2f;\n#endif\n#ifdef REFLECTIVITY\nuniform reflectivityMatrix: mat4x4f;uniform albedoMatrix: mat4x4f;varying vReflectivityUV: vec2f;varying vAlbedoUV: vec2f;\n#endif\n#ifdef UV1\nattribute uv: vec2f;\n#endif\n#ifdef UV2\nattribute uv2: vec2f;\n#endif\n#endif\n#ifdef BUMP\nvarying vWorldView0: vec4f;varying vWorldView1: vec4f;varying vWorldView2: vec4f;varying vWorldView3: vec4f;\n#endif\n#ifdef BUMP\nvarying vNormalW: vec3f;\n#else\nvarying vNormalV: vec3f;\n#endif\nvarying vViewPos: vec4f;\n#if defined(POSITION) || defined(BUMP)\nvarying vPositionW: vec3f;\n#endif\n#if defined(VELOCITY) || defined(VELOCITY_LINEAR)\nuniform previousViewProjection: mat4x4f;varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;var normalUpdated: vec3f=input.normal;\n#ifdef UV1\nvar uvUpdated: vec2f=input.uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=scene.viewProjection*finalWorld*vec4f(positionUpdated,1.0);vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0);\n#endif\n#include\n#include\nvar worldPos: vec4f= vec4f(finalWorld* vec4f(positionUpdated,1.0));\n#ifdef BUMP\nlet vWorldView=scene.view*finalWorld;vertexOutputs.vWorldView0=vWorldView[0];vertexOutputs.vWorldView1=vWorldView[1];vertexOutputs.vWorldView2=vWorldView[2];vertexOutputs.vWorldView3=vWorldView[3];let normalWorld: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);vertexOutputs.vNormalW=normalize(normalWorld*normalUpdated);\n#else\n#ifdef NORMAL_WORLDSPACE\nvertexOutputs.vNormalV=normalize((finalWorld* vec4f(normalUpdated,0.0)).xyz);\n#else\nvertexOutputs.vNormalV=normalize(((scene.view*finalWorld)* vec4f(normalUpdated,0.0)).xyz);\n#endif\n#endif\nvertexOutputs.vViewPos=scene.view*worldPos;\n#if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED)\nvertexOutputs.vCurrentPosition=scene.viewProjection*finalWorld* vec4f(positionUpdated,1.0);\n#if NUM_BONE_INFLUENCERS>0\nvar previousInfluence: mat4x4f;previousInfluence=mPreviousBones[ i32(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[ i32(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[ i32(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[ i32(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*previousInfluence* vec4f(positionUpdated,1.0);\n#else\nvertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0);\n#endif\n#endif\n#if defined(POSITION) || defined(BUMP)\nvertexOutputs.vPositionW=worldPos.xyz/worldPos.w;\n#endif\nvertexOutputs.position=scene.viewProjection*finalWorld* vec4f(positionUpdated,1.0);\n#include\n#ifdef NEED_UV\n#ifdef UV1\n#if defined(ALPHATEST) && defined(ALPHATEST_UV1)\nvertexOutputs.vUV=(uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy;\n#else\nvertexOutputs.vUV=input.uv;\n#endif\n#ifdef BUMP_UV1\nvertexOutputs.vBumpUV=(uniforms.bumpMatrix* vec4f(uvUpdated,1.0,0.0)).xy;\n#endif\n#ifdef REFLECTIVITY_UV1\nvertexOutputs.vReflectivityUV=(uniforms.reflectivityMatrix* vec4f(uvUpdated,1.0,0.0)).xy;\n#endif\n#ifdef ALBEDO_UV1\nvertexOutputs.vAlbedoUV=(uniforms.albedoMatrix* vec4f(uvUpdated,1.0,0.0)).xy;\n#endif\n#endif\n#ifdef UV2\n#if defined(ALPHATEST) && defined(ALPHATEST_UV2)\nvertexOutputs.vUV=(uniforms.diffuseMatrix* vec4f(input.uv2,1.0,0.0)).xy;\n#else\nvertexOutputs.vUV=input.uv2;\n#endif\n#ifdef BUMP_UV2\nvertexOutputs.vBumpUV=(uniforms.bumpMatrix* vec4f(input.uv2,1.0,0.0)).xy;\n#endif\n#ifdef REFLECTIVITY_UV2\nvertexOutputs.vReflectivityUV=(uniforms.reflectivityMatrix* vec4f(input.uv2,1.0,0.0)).xy;\n#endif\n#ifdef ALBEDO_UV2\nvertexOutputs.vAlbedoUV=(uniforms.albedoMatrix* vec4f(input.uv2,1.0,0.0)).xy;\n#endif\n#endif\n#endif\n#include\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},41368:(e,t,i)=>{"use strict";i.r(t),i.d(t,{glowBlurPostProcessPixelShaderWGSL:()=>n});const r="glowBlurPostProcessPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f;uniform direction: vec2f;uniform blurWidth: f32;fn getLuminance(color: vec3f)->f32\n{return dot(color, vec3f(0.2126,0.7152,0.0722));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var weights: array;weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;var texelSize: vec2f= vec2f(1.0/uniforms.screenSize.x,1.0/uniforms.screenSize.y);var texelStep: vec2f=texelSize*uniforms.direction*uniforms.blurWidth;var start: vec2f=input.vUV-3.0*texelStep;var baseColor: vec4f= vec4f(0.,0.,0.,0.);var texelOffset: vec2f= vec2f(0.,0.);for (var i: i32=0; i<7; i++)\n{var texel: vec4f=textureSample(textureSampler,textureSamplerSampler,start+texelOffset);baseColor=vec4f(baseColor.rgb,baseColor.a+texel.a*weights[i]);var luminance: f32=getLuminance(baseColor.rgb);var luminanceTexel: f32=getLuminance(texel.rgb);var choice: f32=step(luminanceTexel,luminance);baseColor=vec4f(choice*baseColor.rgb+(1.0-choice)*texel.rgb,baseColor.a);texelOffset+=texelStep;}\nfragmentOutputs.color=baseColor;}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},69276:(e,t,i)=>{"use strict";i.r(t),i.d(t,{glowMapGenerationPixelShaderWGSL:()=>o});var r=i(69841);i(87647),i(96140),i(76794);const s="glowMapGenerationPixelShader",n="#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)\n#include\n#endif\n#ifdef DIFFUSE\nvarying vUVDiffuse: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d;\n#endif\n#ifdef OPACITY\nvarying vUVOpacity: vec2f;var opacitySamplerSampler: sampler;var opacitySampler: texture_2d;uniform opacityIntensity: f32;\n#endif\n#ifdef EMISSIVE\nvarying vUVEmissive: vec2f;var emissiveSamplerSampler: sampler;var emissiveSampler: texture_2d;\n#endif\n#ifdef VERTEXALPHA\nvarying vColor: vec4f;\n#endif\nuniform glowColor: vec4f;uniform glowIntensity: f32;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#include\nvar finalColor: vec4f=uniforms.glowColor;\n#ifdef DIFFUSE\nvar albedoTexture: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vUVDiffuse);\n#ifdef DIFFUSE_ISLINEAR\nalbedoTexture=toGammaSpace(albedoTexture);\n#endif\n#ifdef GLOW\nfinalColor=vec4f(finalColor.rgb,finalColor.a*albedoTexture.a);\n#endif\n#ifdef HIGHLIGHT\nfinalColor=vec4f(finalColor.rgb,albedoTexture.a);\n#endif\n#endif\n#ifdef OPACITY\nvar opacityMap: vec4f=textureSample(opacitySampler,opacitySamplerSampler,fragmentInputs.vUVOpacity);\n#ifdef OPACITYRGB\nfinalColor=vec4f(finalColor.rgb,finalColor.a*getLuminance(opacityMap.rgb));\n#else\nfinalColor=vec4f(finalColor.rgb,finalColor.a*opacityMap.a);\n#endif\nfinalColor=vec4f(finalColor.rgb,finalColor.a*uniforms.opacityIntensity);\n#endif\n#ifdef VERTEXALPHA\nfinalColor=vec4f(finalColor.rgb,finalColor.a*fragmentInputs.vColor.a);\n#endif\n#ifdef ALPHATEST\nif (finalColor.a{"use strict";i.r(t),i.d(t,{glowMapGenerationVertexShaderWGSL:()=>o});var r=i(69841);i(25589),i(68273),i(47381),i(51148),i(30486),i(41416),i(8573),i(43610),i(32764),i(40903),i(71281),i(57728);const s="glowMapGenerationVertexShader",n="attribute position: vec3f;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform viewProjection: mat4x4f;varying vPosition: vec4f;\n#ifdef UV1\nattribute uv: vec2f;\n#endif\n#ifdef UV2\nattribute uv2: vec2f;\n#endif\n#ifdef DIFFUSE\nvarying vUVDiffuse: vec2f;uniform diffuseMatrix: mat4x4f;\n#endif\n#ifdef OPACITY\nvarying vUVOpacity: vec2f;uniform opacityMatrix: mat4x4f;\n#endif\n#ifdef EMISSIVE\nvarying vUVEmissive: vec2f;uniform emissiveMatrix: mat4x4f;\n#endif\n#ifdef VERTEXALPHA\nattribute color: vec4f;varying vColor: vec4f;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;\n#ifdef UV1\nvar uvUpdated: vec2f=input.uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvar worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);\n#ifdef CUBEMAP\nvertexOutputs.vPosition=worldPos;vertexOutputs.position=uniforms.viewProjection*finalWorld* vec4f(input.position,1.0);\n#else\nvertexOutputs.vPosition=uniforms.viewProjection*worldPos;vertexOutputs.position=vertexOutputs.vPosition;\n#endif\n#ifdef DIFFUSE\n#ifdef DIFFUSEUV1\nvertexOutputs.vUVDiffuse= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy;\n#endif\n#ifdef DIFFUSEUV2\nvertexOutputs.vUVDiffuse= (uniforms.diffuseMatrix* vec4f(input.uv2,1.0,0.0)).xy;\n#endif\n#endif\n#ifdef OPACITY\n#ifdef OPACITYUV1\nvertexOutputs.vUVOpacity= (uniforms.opacityMatrix* vec4f(uvUpdated,1.0,0.0)).xy;\n#endif\n#ifdef OPACITYUV2\nvertexOutputs.vUVOpacity= (uniforms.opacityMatrix* vec4f(input.uv2,1.0,0.0)).xy;\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvertexOutputs.vUVEmissive= (uniforms.emissiveMatrix* vec4f(uvUpdated,1.0,0.0)).xy;\n#endif\n#ifdef EMISSIVEUV2\nvertexOutputs.vUVEmissive= (uniforms.emissiveMatrix* vec4f(input.uv2,1.0,0.0)).xy;\n#endif\n#endif\n#ifdef VERTEXALPHA\nvertexOutputs.vColor=vertexInputs.color;\n#endif\n#include\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},68940:(e,t,i)=>{"use strict";i.r(t),i.d(t,{glowMapMergePixelShaderWGSL:()=>n});const r="glowMapMergePixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;\n#ifdef EMISSIVE\nvar textureSampler2Sampler: sampler;var textureSampler2: texture_2d;\n#endif\nuniform offset: f32;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvar baseColor: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);\n#ifdef EMISSIVE\nbaseColor+=textureSample(textureSampler2,textureSampler2Sampler,input.vUV);baseColor*=uniforms.offset;\n#else\nbaseColor=vec4f(baseColor.rgb,abs(uniforms.offset-baseColor.a));\n#ifdef STROKE\nvar alpha: f32=smoothstep(.0,.1,baseColor.a);baseColor=vec4f(baseColor.rgb*alpha,alpha);\n#endif\n#endif\n#if LDR\nbaseColor=clamp(baseColor,0.,1.0);\n#endif\nfragmentOutputs.color=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},86010:(e,t,i)=>{"use strict";i.r(t),i.d(t,{glowMapMergeVertexShaderWGSL:()=>n});const r="glowMapMergeVertexShader",s="attribute position: vec2f;varying vUV: vec2f;\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {const madd: vec2f= vec2f(0.5,0.5);\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.vUV=input.position*madd+madd;vertexOutputs.position= vec4f(input.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},35624:(e,t,i)=>{"use strict";i.r(t),i.d(t,{grainPixelShaderWGSL:()=>o});var r=i(69841);i(87647);const s="grainPixelShader",n="#include\nvarying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform intensity: f32;uniform animatedSeed: f32;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);var seed: vec2f=input.vUV*uniforms.animatedSeed;var grain: f32=dither(seed,uniforms.intensity);var lum: f32=getLuminance(fragmentOutputs.color.rgb);var grainAmount: f32=(cos(-PI+(lum*PI*2.))+1.)/2.;fragmentOutputs.color=vec4f(fragmentOutputs.color.rgb+grain*grainAmount,fragmentOutputs.color.a);fragmentOutputs.color=vec4f(max(fragmentOutputs.color.rgb,vec3f(0.0)),fragmentOutputs.color.a);}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},17477:(e,t,i)=>{"use strict";i.r(t),i.d(t,{hdrFilteringPixelShaderWGSL:()=>o});var r=i(69841);i(87647),i(60755),i(20427),i(49335);const s="hdrFilteringPixelShader",n="#include\n#include\n#include\n#include\nuniform alphaG: f32;var inputTextureSampler: sampler;var inputTexture: texture_cube;uniform vFilteringInfo: vec2f;uniform hdrScale: f32;varying direction: vec3f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=radiance(uniforms.alphaG,inputTexture,inputTextureSampler,input.direction,uniforms.vFilteringInfo);fragmentOutputs.color= vec4f(color*uniforms.hdrScale,1.0);}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},44623:(e,t,i)=>{"use strict";i.r(t),i.d(t,{hdrFilteringVertexShaderWGSL:()=>n});const r="hdrFilteringVertexShader",s="attribute position: vec2f;varying direction: vec3f;uniform up: vec3f;uniform right: vec3f;uniform front: vec3f;\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvar view: mat3x3f= mat3x3f(uniforms.up,uniforms.right,uniforms.front);vertexOutputs.direction=view*vec3f(input.position,1.0);vertexOutputs.position= vec4f(input.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},28162:(e,t,i)=>{"use strict";i.r(t),i.d(t,{highlightsPixelShaderWGSL:()=>n});const r="highlightsPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;const RGBLuminanceCoefficients: vec3f= vec3f(0.2126,0.7152,0.0722);\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var tex: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);var c: vec3f=tex.rgb;var luma: f32=dot(c.rgb,RGBLuminanceCoefficients);fragmentOutputs.color= vec4f(pow(c, vec3f(25.0-luma*15.0)),tex.a); }";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},48016:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblCombineVoxelGridsPixelShaderWGSL:()=>n});const r="iblCombineVoxelGridsPixelShader",s="varying vUV: vec2f;var voxelXaxisSamplerSampler: sampler;var voxelXaxisSampler: texture_3d;var voxelYaxisSamplerSampler: sampler;var voxelYaxisSampler: texture_3d;var voxelZaxisSamplerSampler: sampler;var voxelZaxisSampler: texture_3d;uniform layer: f32;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var coordZ: vec3f= vec3f(fragmentInputs.vUV.x,fragmentInputs.vUV.y,uniforms.layer);var voxelZ: f32=textureSample(voxelZaxisSampler,voxelZaxisSamplerSampler,coordZ).r;var coordX: vec3f= vec3f(1.0-uniforms.layer,fragmentInputs.vUV.y,fragmentInputs.vUV.x);var voxelX: f32=textureSample(voxelXaxisSampler,voxelXaxisSamplerSampler,coordX).r;var coordY: vec3f= vec3f(uniforms.layer,fragmentInputs.vUV.x,fragmentInputs.vUV.y);var voxelY: f32=textureSample(voxelYaxisSampler,voxelYaxisSamplerSampler,coordY).r;var voxel=select(0.0,1.0,(voxelX>0.0 || voxelY>0.0 || voxelZ>0.0));fragmentOutputs.color= vec4f( vec3f(voxel),1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},88789:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblGenerateVoxelMipPixelShaderWGSL:()=>n});const r="iblGenerateVoxelMipPixelShader",s="varying vUV: vec2f;var srcMip: texture_3d;uniform layerNum: i32;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var Coords=vec3i(2)*vec3i(vec2i(fragmentInputs.position.xy),uniforms.layerNum);var tex =\n(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(0,0,0),0).x>0.0f))\n<< 0u) |\n(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(1,0,0),0).x>0.0f))\n<< 1u) |\n(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(0,1,0),0).x>0.0f))\n<< 2u) |\n(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(1,1,0),0).x>0.0f))\n<< 3u) |\n(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(0,0,1),0).x>0.0f))\n<< 4u) |\n(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(1,0,1),0).x>0.0f))\n<< 5u) |\n(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(0,1,1),0).x>0.0f))\n<< 6u) |\n(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(1,1,1),0).x>0.0f))\n<< 7u);fragmentOutputs.color=vec4f( f32(tex)/255.0f,0.0f,0.0f,1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},41115:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowAccumulationPixelShaderWGSL:()=>n});const r="iblShadowAccumulationPixelShader",s="varying vUV: vec2f;uniform accumulationParameters: vec4f;\n#define remanence uniforms.accumulationParameters.x\n#define resetb uniforms.accumulationParameters.y\n#define sceneSize uniforms.accumulationParameters.z\nvar motionSampler: texture_2d;var positionSampler: texture_2d;var spatialBlurSampler : texture_2d;var oldAccumulationSamplerSampler: sampler;var oldAccumulationSampler: texture_2d;var prevPositionSamplerSampler: sampler;var prevPositionSampler: texture_2d;fn max2(v: vec2f,w: vec2f)->vec2f { \nreturn vec2f(max(v.x,w.x),max(v.y,w.y)); }\nfn lessThan(x: vec2f,y: vec2f)->vec2 {return xFragmentOutputs {var reset: bool= bool(resetb);var gbufferRes : vec2f=vec2f(textureDimensions(positionSampler,0));var gbufferPixelCoord: vec2i= vec2i(input.vUV*gbufferRes);var shadowRes : vec2f=vec2f(textureDimensions(spatialBlurSampler,0));var shadowPixelCoord: vec2i= vec2i(input.vUV*shadowRes);var LP: vec4f=textureLoad(positionSampler,gbufferPixelCoord,0);if (0.0==LP.w) {fragmentOutputs.color=vec4f(1.0,0.0,0.0,1.0);return fragmentOutputs;}\nvar velocityColor: vec2f=textureLoad(motionSampler,gbufferPixelCoord,0).xy;var prevCoord: vec2f=input.vUV+velocityColor;var PrevLP: vec3f=textureSampleLevel(prevPositionSampler,prevPositionSamplerSampler,prevCoord,0.0).xyz;var PrevShadows: vec3f=textureSampleLevel(oldAccumulationSampler,oldAccumulationSamplerSampler,prevCoord,0.0).xyz;var newShadows : vec2f=textureLoad(spatialBlurSampler,shadowPixelCoord,0).xy;PrevShadows.z=select(1.0,max(PrevShadows.z/(1.0+PrevShadows.z),1.0-remanence),!reset && all(lessThan(abs(prevCoord- vec2f(0.5)), vec2f(0.5))) &&\ndistance(LP.xyz,PrevLP)<5e-2*sceneSize);PrevShadows=max( vec3f(0.0),PrevShadows);fragmentOutputs.color= vec4f(mix(PrevShadows.x,newShadows.x,PrevShadows.z),\nmix(PrevShadows.y,newShadows.y,PrevShadows.z),PrevShadows.z,1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},65461:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowDebugPixelShaderWGSL:()=>n});const r="iblShadowDebugPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var debugSamplerSampler: sampler;var debugSampler: texture_2d;uniform sizeParams: vec4f;\n#define offsetX uniforms.sizeParams.x\n#define offsetY uniforms.sizeParams.y\n#define widthScale uniforms.sizeParams.z\n#define heightScale uniforms.sizeParams.w\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var uv: vec2f =\nvec2f((offsetX+fragmentInputs.vUV.x)*widthScale,(offsetY+fragmentInputs.vUV.y)*heightScale);var background: vec4f=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.vUV);var debugColour: vec4f=textureSample(debugSampler,debugSamplerSampler,fragmentInputs.vUV);if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {fragmentOutputs.color=background;} else {fragmentOutputs.color=vec4f(mix(debugColour.rgb,background.rgb,0.0),1.0);}}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},23008:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowGBufferDebugPixelShaderWGSL:()=>n});const r="iblShadowGBufferDebugPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var depthSampler: sampler;var depthTexture: texture_2d;var normalSampler: sampler;var normalTexture: texture_2d;var positionSampler: sampler;var positionTexture: texture_2d;var velocitySampler: sampler;var velocityTexture: texture_2d;uniform sizeParams: vec4f;uniform maxDepth: f32;\n#define offsetX uniforms.sizeParams.x\n#define offsetY uniforms.sizeParams.y\n#define widthScale uniforms.sizeParams.z\n#define heightScale uniforms.sizeParams.w\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var uv: vec2f =\nvec2f((offsetX+input.vUV.x)*widthScale,(offsetY+input.vUV.y)*heightScale);var backgroundColour: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgba;var depth: vec4f=textureSample(depthTexture,depthSampler,input.vUV);var worldNormal: vec4f=textureSample(normalTexture,normalSampler,input.vUV);var worldPosition: vec4f=textureSample(positionTexture,positionSampler,input.vUV);var velocityLinear: vec4f=textureSample(velocityTexture,velocitySampler,input.vUV);if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {fragmentOutputs.color=backgroundColour;} else {if (uv.x<=0.25) {fragmentOutputs.color=vec4f(depth.rgb,1.0);} else if (uv.x<=0.5) {velocityLinear=vec4f(velocityLinear.r*0.5+0.5,velocityLinear.g*0.5+0.5,velocityLinear.b,velocityLinear.a);fragmentOutputs.color=vec4f(velocityLinear.rgb,1.0);} else if (uv.x<=0.75) {fragmentOutputs.color=vec4f(worldPosition.rgb,1.0);} else {fragmentOutputs.color=vec4f(worldNormal.rgb,1.0);}}}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},45647:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowSpatialBlurPixelShaderWGSL:()=>n});const r="iblShadowSpatialBlurPixelShader",s="#define PI 3.1415927\nvarying vUV: vec2f;var depthSampler: texture_2d;var worldNormalSampler: texture_2d;var voxelTracingSampler : texture_2d;uniform blurParameters: vec4f;\n#define stridef uniforms.blurParameters.x\n#define worldScale uniforms.blurParameters.y\nconst weights=array(0.0625,0.25,0.375,0.25,0.0625);const nbWeights: i32=5;fn max2(v: vec2f,w: vec2f)->vec2f {return vec2f(max(v.x,w.x),max(v.y,w.y));}\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var gbufferRes=vec2f(textureDimensions(depthSampler,0));var gbufferPixelCoord= vec2i(fragmentInputs.vUV*gbufferRes);var shadowRes=vec2f(textureDimensions(voxelTracingSampler,0));var shadowPixelCoord= vec2i(fragmentInputs.vUV*shadowRes);var N: vec3f=textureLoad(worldNormalSampler,gbufferPixelCoord,0).xyz;if (length(N)<0.01) {fragmentOutputs.color=vec4f(1.0,1.0,0.0,1.0);return fragmentOutputs;}\nvar depth: f32=-textureLoad(depthSampler,gbufferPixelCoord,0).x;var X: vec3f= vec3f(0.0);for(var y: i32=0; y>1),y-(nbWeights>>1));var shadowCoords: vec2i=shadowPixelCoord+i32(stridef)*vec2i(x-(nbWeights>>1),y-(nbWeights>>1));var T : vec2f=textureLoad(voxelTracingSampler,shadowCoords,0).xy;var ddepth: f32=-textureLoad(depthSampler,gBufferCoords,0).x-depth;var dN: vec3f=textureLoad(worldNormalSampler,gBufferCoords,0).xyz-N;var w: f32=weights[x]*weights[y] *\nexp2(max(-1000.0/(worldScale*worldScale),-0.5) *\n(ddepth*ddepth) -\n1e1*dot(dN,dN));X+= vec3f(w*T.x,w*T.y,w);}}\nfragmentOutputs.color= vec4f(X.x/X.z,X.y/X.z,0.0,1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},35680:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowVoxelTracingPixelShaderWGSL:()=>n});const r="iblShadowVoxelTracingPixelShader",s="#define PI 3.1415927\nvarying vUV: vec2f;\n#define DISABLE_UNIFORMITY_ANALYSIS\nvar depthSampler: texture_2d;var worldNormalSampler : texture_2d;var blueNoiseSampler: texture_2d;var icdfxSamplerSampler: sampler;var icdfxSampler: texture_2d;var icdfySamplerSampler: sampler;var icdfySampler: texture_2d;var voxelGridSamplerSampler: sampler;var voxelGridSampler: texture_3d;uniform shadowParameters: vec4f;\n#define SHADOWdirs uniforms.shadowParameters.x\n#define SHADOWframe uniforms.shadowParameters.y\n#define SHADOWenvRot uniforms.shadowParameters.w\nuniform voxelBiasParameters : vec4f;\n#define highestMipLevel uniforms.voxelBiasParameters.z\nuniform sssParameters: vec4f;\n#define SSSsamples uniforms.sssParameters.x\n#define SSSstride uniforms.sssParameters.y\n#define SSSmaxDistance uniforms.sssParameters.z\n#define SSSthickness uniforms.sssParameters.w\nuniform shadowOpacity: vec4f;uniform projMtx: mat4x4f;uniform viewMtx: mat4x4f;uniform invProjMtx: mat4x4f;uniform invViewMtx: mat4x4f;uniform wsNormalizationMtx: mat4x4f;uniform invVPMtx: mat4x4f;\n#define PI 3.1415927\n#define GOLD 0.618034\nstruct AABB3f {m_min: vec3f,\nm_max: vec3f,};struct Ray {orig: vec3f,\ndir: vec3f,\ndir_rcp: vec3f,\nt_min: f32,\nt_max: f32,};fn make_ray(origin: vec3f,direction: vec3f,tmin: f32,\ntmax: f32)->Ray {var ray: Ray;ray.orig=origin;ray.dir=direction;ray.dir_rcp=1.0f/direction;ray.t_min=tmin;ray.t_max=tmax;return ray;}\nfn ray_box_intersection(aabb: AABB3f,ray: Ray ,\ndistance_near: ptr,distance_far: ptr)->bool{var tbot: vec3f=ray.dir_rcp*(aabb.m_min-ray.orig);var ttop: vec3f=ray.dir_rcp*(aabb.m_max-ray.orig);var tmin: vec3f=min(ttop,tbot);var tmax: vec3f=max(ttop,tbot);*distance_near=max(ray.t_min,max(tmin.x,max(tmin.y,tmin.z)));*distance_far=min(ray.t_max,min(tmax.x,min(tmax.y,tmax.z)));return *distance_near<=*distance_far;}\n#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nstruct VoxelMarchDiagnosticInfo {heat: f32,\nvoxel_intersect_coords: vec3i,};\n#endif\nfn hash(i: u32)->u32 {var temp=i ^ (i>>16u);temp*=0x7FEB352Du;temp ^= temp>>15u;temp*=0x846CA68Bu;temp ^= temp>>16u;return temp;}\nfn uintBitsToFloat(x: u32)->f32 {return bitcast(x);}\nfn uint2float(i: u32)->f32 {return uintBitsToFloat(0x3F800000u | (i>>9u))-1.0;}\nfn uv_to_normal(uv: vec2f)->vec3f {var N: vec3f;var uvRange: vec2f=uv;var theta: f32=uvRange.x*2.0*PI;var phi: f32=uvRange.y*PI;N.x=cos(theta)*sin(phi);N.z=sin(theta)*sin(phi);N.y=cos(phi);return N;}\nfn plasticSequence(rstate: u32)->vec2f {return vec2f(uint2float(rstate*3242174889u),\nuint2float(rstate*2447445414u));}\nfn goldenSequence(rstate: u32)->f32 {return uint2float(rstate*2654435769u);}\nfn distanceSquared(a: vec2f,b: vec2f)->f32 {var diff: vec2f=a-b;return dot(diff,diff);}\nfn genTB(N: vec3f,T: ptr,B: ptr) {var s: f32=select(1.0,-1.0,N.z<0.0);var a: f32=-1.0/(s+N.z);var b: f32=N.x*N.y*a;*T= vec3f(1.0+s*N.x*N.x*a,s*b,-s*N.x);*B= vec3f(b,s+N.y*N.y*a,-N.y);}\nfn lessThan(x: vec3f,y: vec3f)->vec3 {return x)->bool {\n#else\nfn anyHitVoxels(ray_vs: Ray)->bool {\n#endif\nvar stack=array(); \nvar invD: vec3f=ray_vs.dir_rcp;var D: vec3f=ray_vs.dir;var O: vec3f=ray_vs.orig;var negD=vec3i(lessThan(D, vec3f(0,0,0)));var voxel0: i32=negD.x | (negD.y<<1) | (negD.z<<2);var t0: vec3f=-O*invD;var t1=(vec3f(1.0)-O)*invD;var maxLod: i32= i32(highestMipLevel);var stackLevel: i32=0;\n#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nvar steps: u32=0u;\n#endif\nstack[stackLevel]=maxLod<<24;stackLevel++;while (stackLevel>0) {stackLevel=stackLevel-1;var elem: i32=stack[stackLevel];var Coords: vec4i =\nvec4i(elem & 0xFF,(elem>>8) & 0xFF,(elem>>16) & 0xFF,elem>>24);if (Coords.w==0) {\n#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\n*voxel_march_diagnostic_info.heat= f32(steps)/24.0;\n#endif\nreturn true;}\n#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\n++steps;\n#endif\nvar invRes: f32=exp2(f32(Coords.w-maxLod));var bbmin: vec3f=invRes*vec3f(Coords.xyz+negD);var bbmax: vec3f=invRes*vec3f(Coords.xyz-negD+vec3i(1));var mint: vec3f=mix(t0,t1,bbmin);var maxt: vec3f=mix(t0,t1,bbmax);var midt: vec3f=0.5*(mint+maxt);mint.x=max(0.0,mint.x);midt.x=max(0.0,midt.x);var nodeMask: u32= u32(\nround(textureLoad(voxelGridSampler,Coords.xyz,Coords.w).x*255.0));Coords.w--;var voxelBit: u32=u32(voxel0);Coords=vec4i((Coords.xyz<f32 {return (near*far)/(far-depth*(far-near));}\nfn screenSpaceShadow(csOrigin: vec3f,csDirection: vec3f,csZBufferSize: vec2f,\nnearPlaneZ: f32,farPlaneZ: f32,noise: f32)->f32 {\n#ifdef RIGHT_HANDED\nvar csZDir : f32=-1.0;\n#else \nvar csZDir : f32=1.0;\n#endif\nvar ssSamples: f32=SSSsamples;var ssMaxDist: f32=SSSmaxDistance;var ssStride: f32=SSSstride;var ssThickness: f32=SSSthickness;var rayLength: f32 =\nselect(ssMaxDist,(nearPlaneZ-csOrigin.z)/csDirection.z,\ncsZDir*(csOrigin.z+ssMaxDist*csDirection.z)0.0 && stepCount)->f32 {\n#else\nfn voxelShadow(wsOrigin: vec3f,wsDirection: vec3f,wsNormal: vec3f,\nDitherNoise: vec2f)->f32 {\n#endif\nvar vxResolution: f32=f32(textureDimensions(voxelGridSampler,0).x);var T: vec3f;var B: vec3f;genTB(wsDirection,&T,&B);var DitherXY: vec2f=sqrt(DitherNoise.x)* vec2f(cos(2.0*PI*DitherNoise.y),\nsin(2.0*PI*DitherNoise.y));var Dithering : vec3f=(uniforms.voxelBiasParameters.x*wsNormal +\nuniforms.voxelBiasParameters.y*wsDirection +\nDitherXY.x*T+DitherXY.y*B) /\nvxResolution;var O: vec3f=0.5*wsOrigin+0.5+Dithering;var ray_vs=make_ray(O,wsDirection,0.0,10.0);var voxel_aabb: AABB3f;voxel_aabb.m_min=vec3f(0);voxel_aabb.m_max=vec3f(1);var near: f32=0;var far: f32=0;if (!ray_box_intersection(voxel_aabb,ray_vs,&near,&far)) {return 0.0;}\nray_vs.t_min=max(ray_vs.t_min,near);ray_vs.t_max=min(ray_vs.t_max,far);\n#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nreturn select(0.0f,1.0f,anyHitVoxels(ray_vs,voxel_march_diagnostic_info));\n#else\nreturn select(0.0f,1.0f,anyHitVoxels(ray_vs));\n#endif\n}\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var nbDirs=u32(SHADOWdirs);var frameId=u32(SHADOWframe);var envRot: f32=SHADOWenvRot;var Resolution: vec2f= vec2f(textureDimensions(depthSampler,0));var currentPixel=vec2i(fragmentInputs.vUV*Resolution);var GlobalIndex =\n(frameId*u32(Resolution.y)+u32(currentPixel.y))*u32(Resolution.x) +\nu32(currentPixel.x);var N : vec3f=textureLoad(worldNormalSampler,currentPixel,0).xyz;if (length(N)<0.01) {fragmentOutputs.color=vec4f(1.0,1.0,0.0,1.0);return fragmentOutputs;}\nvar normalizedRotation: f32=envRot/(2.0*PI);var depth : f32=textureLoad(depthSampler,currentPixel,0).x;\n#ifndef IS_NDC_HALF_ZRANGE\ndepth=depth*2.0-1.0;\n#endif\nvar temp : vec2f=(vec2f(currentPixel)+vec2f(0.5))*2.0/Resolution -\nvec2f(1.0);var VP : vec4f=uniforms.invProjMtx*vec4f(temp.x,-temp.y,depth,1.0);VP/=VP.w;N=normalize(N);var noise\n: vec3f =\ntextureLoad(blueNoiseSampler,currentPixel & vec2i(0xFF),0).xyz;noise.z=fract(noise.z+goldenSequence(frameId*nbDirs));\n#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nvar heat: f32=0.0f;\n#endif\nvar shadowAccum: f32=0.0;var specShadowAccum: f32=0.0;var sampleWeight : f32=0;for (var i: u32=0; iedge_tint_const) {var VP2: vec4f=VP;VP2.y*=-1.0;var unormWP : vec4f=uniforms.invViewMtx*VP2;var WP: vec3f=(uniforms.wsNormalizationMtx*unormWP).xyz;var vxNoise: vec2f =\nvec2f(uint2float(hash(dirId*2)),uint2float(hash(dirId*2+1)));\n#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nVoxelMarchDiagnosticInfo voxel_march_diagnostic_info;opacity=max(opacity,\nuniforms.shadowOpacity.x*voxelShadow(WP,L.xyz,N,vxNoise,\nvoxel_march_diagnostic_info));heat+=voxel_march_diagnostic_info.heat;\n#else\nopacity =\nmax(opacity,uniforms.shadowOpacity.x*voxelShadow(WP,L.xyz,N,vxNoise));\n#endif\nvar VL : vec3f=(uniforms.viewMtx*L).xyz;\n#ifdef RIGHT_HANDED\nvar nearPlaneZ: f32=-2.0*uniforms.projMtx[3][2]/(uniforms.projMtx[2][2]-1.0); \nvar farPlaneZ: f32=-uniforms.projMtx[3][2]/(uniforms.projMtx[2][2]+1.0);\n#else\nvar nearPlaneZ: f32=-2.0*uniforms.projMtx[3][2]/(uniforms.projMtx[2][2]+1.0); \nvar farPlaneZ: f32=-uniforms.projMtx[3][2]/(uniforms.projMtx[2][2]-1.0);\n#endif\nvar ssShadow: f32=uniforms.shadowOpacity.y *\nscreenSpaceShadow(VP2.xyz,VL,Resolution,nearPlaneZ,farPlaneZ,\nabs(2.0*noise.z-1.0));opacity=max(opacity,ssShadow);shadowAccum+=min(1.0-opacity,cosNL);sampleWeight+=cosNL;var VR : vec3f=-(uniforms.viewMtx*vec4f(reflect(-L.xyz,N),0.0)).xyz;specShadowAccum+=max(1.0-(opacity*pow(VR.z,8.0)),0.0);}\nnoise.z=fract(noise.z+GOLD);}\n#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nfragmentOutputs.color =\nvec4f(shadowAccum/sampleWeight,specShadowAccum/sampleWeight,heat/sampleWeight,1.0);\n#else\nfragmentOutputs.color=vec4f(shadowAccum/sampleWeight,specShadowAccum/sampleWeight,0.0,1.0);\n#endif\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},43572:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowsCdfxPixelShaderWGSL:()=>n});const r="iblShadowsCdfxPixelShader",s="#define PI 3.1415927\nvarying vUV: vec2f;var cdfy: texture_2d;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var cdfyRes=textureDimensions(cdfy,0);var currentPixel=vec2u(fragmentInputs.position.xy);var cdfx: f32=0.0;for (var x: u32=1; x<=currentPixel.x; x++) {cdfx+=textureLoad(cdfy, vec2u(x-1,cdfyRes.y-1),0).x;}\nfragmentOutputs.color= vec4f( vec3f(cdfx),1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},85917:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowsCdfyPixelShaderWGSL:()=>n});const r="iblShadowsCdfyPixelShader",s="#define PI 3.1415927\nvarying vUV: vec2f;\n#ifdef IBL_USE_CUBE_MAP\nvar iblSourceSampler: sampler;var iblSource: texture_cube;\n#else\nvar iblSourceSampler: sampler;var iblSource: texture_2d;\n#endif\nuniform iblHeight: i32;\n#ifdef IBL_USE_CUBE_MAP\nfn equirectangularToCubemapDirection(uv: vec2f)->vec3f {var longitude: f32=uv.x*2.0*PI-PI;var latitude: f32=PI*0.5-uv.y*PI;var direction: vec3f;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;}\nfn fetchCube(uv: vec2f)->f32 {var direction: vec3f=equirectangularToCubemapDirection(uv);return sin(PI*uv.y)*dot(textureSampleLevel(iblSource,iblSourceSampler,direction,0.0).rgb,\nvec3f(0.3,0.6,0.1));}\n#else\nfn fetchPanoramic(Coords: vec2i,envmapHeight: f32)->f32 {return sin(PI*( f32(Coords.y)+0.5)/envmapHeight) *\ndot(textureLoad(iblSource,Coords,0).rgb, vec3f(0.3,0.6,0.1));}\n#endif\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var coords: vec2i= vec2i(fragmentInputs.position.xy);var cdfy: f32=0.0;for (var y: i32=1; y<=coords.y; y++) {\n#ifdef IBL_USE_CUBE_MAP\nvar uv: vec2f= vec2f(input.vUV.x,( f32(y-1)+0.5)/ f32(uniforms.iblHeight));cdfy+=fetchCube(uv);\n#else\ncdfy+=fetchPanoramic( vec2i(coords.x,y-1), f32(uniforms.iblHeight));\n#endif\n}\nfragmentOutputs.color= vec4f(cdfy,0.0,0.0,1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},38957:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowsIcdfxPixelShaderWGSL:()=>n});const r="iblShadowsIcdfxPixelShader",s="#define PI 3.1415927\nvarying vUV: vec2f;var cdfx: texture_2d;fn fetchCDF(x: u32)->f32 {return textureLoad(cdfx, vec2u(x,0),0).x;}\nfn bisect(size: u32,targetValue: f32)->f32\n{var a: u32=0;var b=size-1;while (b-a>1) {var c: u32=(a+b)>>1;if (fetchCDF(c)FragmentOutputs {var cdfSize: vec2u=textureDimensions(cdfx,0);var cdfWidth: u32=cdfSize.x;var icdfWidth: u32=cdfWidth-1;var currentPixel: vec2u= vec2u(fragmentInputs.position.xy);if (currentPixel.x==0)\n{fragmentOutputs.color= vec4f(0.0);}\nelse if (currentPixel.x==icdfWidth-1) {fragmentOutputs.color= vec4f(1.0);} else {var targetValue: f32=fetchCDF(cdfWidth-1)*input.vUV.x;fragmentOutputs.color= vec4f( vec3f(bisect(cdfWidth,targetValue)),1.0);}}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},27844:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowsIcdfyPixelShaderWGSL:()=>n});const r="iblShadowsIcdfyPixelShader",s="#define PI 3.1415927\nvarying vUV: vec2f;var cdfy: texture_2d;fn fetchCDF(y: u32,invocationId: u32)->f32 {return textureLoad(cdfy, vec2u(invocationId,y),0).x;}\nfn bisect(size: u32,targetValue: f32,invocationId: u32)->f32\n{var a: u32=0;var b=size-1;while (b-a>1) {var c=(a+b)>>1;if (fetchCDF(c,invocationId)FragmentOutputs {var cdfSize: vec2u=textureDimensions(cdfy,0);var cdfHeight: u32=cdfSize.y;var currentPixel: vec2u= vec2u(fragmentInputs.position.xy);if (currentPixel.y==0) {fragmentOutputs.color= vec4f(0.0);}\nelse if (currentPixel.y==cdfHeight-2) {fragmentOutputs.color= vec4f(1.0);} else {var targetValue: f32=fetchCDF(cdfHeight-1,currentPixel.x)*input.vUV.y;fragmentOutputs.color= vec4f( vec3f(bisect(cdfHeight,targetValue,currentPixel.x)),1.0);}}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},78685:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowsImportanceSamplingDebugPixelShaderWGSL:()=>n});const r="iblShadowsImportanceSamplingDebugPixelShader",s="#define PI 3.1415927\nvarying vUV: vec2f;var cdfySampler: sampler;var cdfy: texture_2d;var icdfySampler: sampler;var icdfy: texture_2d;var cdfxSampler: sampler;var cdfx: texture_2d;var icdfxSampler: sampler;var icdfx: texture_2d;\n#ifdef IBL_USE_CUBE_MAP\nvar iblSourceSampler: sampler;var iblSource: texture_cube;\n#else\nvar iblSourceSampler: sampler;var iblSource: texture_2d;\n#endif\nvar textureSamplerSampler: sampler;var textureSampler: texture_2d;\n#define cdfyVSize 0.4\n#define cdfxVSize 0.1\n#define cdfyHSize 0.5\nuniform sizeParams: vec4f;\n#ifdef IBL_USE_CUBE_MAP\nfn equirectangularToCubemapDirection(uv: vec2f)->vec3f {var longitude: f32=uv.x*2.0*PI-PI;var latitude: f32=PI*0.5-uv.y*PI;var direction: vec3f;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;}\n#endif\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs { \nvar colour: vec3f= vec3f(0.0);var uv: vec2f =\nvec2f((uniforms.sizeParams.x+input.vUV.x)*uniforms.sizeParams.z,(uniforms.sizeParams.y+input.vUV.y)*uniforms.sizeParams.w);var backgroundColour: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;const iblStart: f32=1.0-cdfyVSize;const cdfyStart: f32=1.0-2.0*cdfyVSize;const cdfxStart: f32=1.0-2.0*cdfyVSize-cdfxVSize;const icdfxStart: f32=1.0-2.0*cdfyVSize-2.0*cdfxVSize;\n#ifdef IBL_USE_CUBE_MAP\nvar direction: vec3f=equirectangularToCubemapDirection(\n(uv- vec2f(0.0,iblStart))* vec2f(1.0,1.0/cdfyVSize));var iblColour: vec3f=textureSampleLevel(iblSource,iblSourceSampler,direction,0.0).rgb;\n#else\nvar iblColour: vec3f=textureSample(iblSource,iblSourceSampler,(uv- vec2f(0.0,iblStart)) *\nvec2f(1.0,1.0/cdfyVSize))\n.rgb;\n#endif\nvar cdfyColour: f32 =\ntextureSample(cdfy,cdfySampler,(uv- vec2f(0.0,cdfyStart))* vec2f(2.0,1.0/cdfyVSize)).r;var icdfyColour: f32 =\ntextureSample(icdfy,icdfySampler,(uv- vec2f(0.5,cdfyStart))* vec2f(2.0,1.0/cdfyVSize)).r;var cdfxColour: f32 =\ntextureSample(cdfx,cdfxSampler,(uv- vec2f(0.0,cdfxStart))* vec2f(1.0,1.0/cdfxVSize)).r;var icdfxColour: f32=textureSample(icdfx,icdfxSampler,(uv- vec2f(0.0,icdfxStart)) *\nvec2f(1.0,1.0/cdfxVSize)).r;if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {colour=backgroundColour;} else if (uv.y>iblStart) {colour+=iblColour;} else if (uv.y>cdfyStart && uv.x<0.5) {colour.r+=0.003*cdfyColour;} else if (uv.y>cdfyStart && uv.x>0.5) {colour.r+=icdfyColour;} else if (uv.y>cdfxStart) {colour.r+=0.00003*cdfxColour;} else if (uv.y>icdfxStart) {colour.r+=icdfxColour;}\nfragmentOutputs.color =vec4(mix(colour,backgroundColour,0.5),1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},75904:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblVoxelGridPixelShaderWGSL:()=>n});const r="iblVoxelGridPixelShader",s="varying vNormalizedPosition: vec3f;uniform nearPlane: f32;uniform farPlane: f32;uniform stepSize: f32;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var normPos: vec3f=input.vNormalizedPosition.xyz;if (normPos.zuniforms.farPlane) {discard;}\nfragmentOutputs.fragData0=select(vec4f(0.0),vec4f(1.0),normPos.z=uniforms.nearPlane+uniforms.stepSize && normPos.z=uniforms.nearPlane+2.0*uniforms.stepSize && normPos.z=uniforms.nearPlane+3.0*uniforms.stepSize && normPos.z4\nfragmentOutputs.fragData4=select(vec4f(0.0),vec4f(1.0),normPos.z>=uniforms.nearPlane+4.0*uniforms.stepSize && normPos.z=uniforms.nearPlane+5.0*uniforms.stepSize && normPos.z=uniforms.nearPlane+6.0*uniforms.stepSize && normPos.z=uniforms.nearPlane+7.0*uniforms.stepSize && normPos.z{"use strict";i.r(t),i.d(t,{iblVoxelGridVertexShaderWGSL:()=>n});const r="iblVoxelGridVertexShader",s="attribute position: vec3f;attribute normal: vec3f;varying vNormalizedPosition: vec3f;uniform world: mat4x4f;uniform invWorldScale: mat4x4f;uniform viewMatrix: mat4x4f;@vertex\nfn main(input : VertexInputs)->FragmentInputs {vertexOutputs.position=uniforms.viewMatrix*uniforms.invWorldScale*uniforms.world* vec4f(input.position,1.);vertexOutputs.vNormalizedPosition=vertexOutputs.position.xyz*0.5+0.5;\n#ifdef IS_NDC_HALF_ZRANGE\nvertexOutputs.position=vec4f(vertexOutputs.position.x,vertexOutputs.position.y,vertexOutputs.position.z*0.5+0.5,vertexOutputs.position.w);\n#endif\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},7426:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblVoxelGrid2dArrayDebugPixelShaderWGSL:()=>n});const r="iblVoxelGrid2dArrayDebugPixelShader",s="varying vUV: vec2f;var voxelTextureSampler: sampler;var voxelTexture: texture_3d;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform slice: i32;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var size: vec3u=textureDimensions(voxelTexture,0);var dimension: f32=sqrt( f32(size.z));var samplePos: vec2f=fract(input.vUV.xy* vec2f(dimension));var sampleIndex: u32= u32(floor(input.vUV.x* f32(dimension))+floor(input.vUV.y* f32(dimension))*dimension);var color=textureSample(voxelTexture,voxelTextureSampler, vec3f(samplePos.xy,sampleIndex)).rrr;color+=textureSample(textureSampler,textureSamplerSampler,input.vUV.xy).rgb;fragmentOutputs.color=vec4f(color,1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},20008:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblVoxelGrid3dDebugPixelShaderWGSL:()=>n});const r="iblVoxelGrid3dDebugPixelShader",s="varying vUV: vec2f;var voxelTextureSampler: sampler;var voxelTexture: texture_3d;var voxelSlabTextureSampler: sampler;var voxelSlabTexture: texture_2d;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform sizeParams: vec4f;\n#define offsetX uniforms.sizeParams.x\n#define offsetY uniforms.sizeParams.y\n#define widthScale uniforms.sizeParams.z\n#define heightScale uniforms.sizeParams.w\nuniform mipNumber: f32;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var uv: vec2f =\nvec2f((offsetX+input.vUV.x)*widthScale,(offsetY+input.vUV.y)*heightScale);var background: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);var voxelSlab: vec4f=textureSample(voxelSlabTexture,voxelSlabTextureSampler,input.vUV);var size: vec3u=textureDimensions(voxelTexture, i32(uniforms.mipNumber));var dimension: f32=ceil(sqrt( f32(size.z)));var samplePos: vec2f=fract(uv.xy* vec2f(dimension));var sampleIndex: u32= u32(floor(uv.x* f32(dimension)) +\nfloor(uv.y* f32(dimension))*dimension);var mip_separator: f32=0.0;if (samplePos.x<0.01 || samplePos.y<0.01) {mip_separator=1.0;}\nvar outBounds: bool=select(false,true,sampleIndex>size.z-1);sampleIndex=clamp(sampleIndex,0,size.z-1);var samplePosInt: vec2i= vec2i(samplePos.xy* vec2f(size.xy));var voxel: vec3f=textureLoad(voxelTexture,\nvec3i(i32(samplePosInt.x),i32(samplePosInt.y),i32(sampleIndex)),\ni32(uniforms.mipNumber)).rgb;if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {fragmentOutputs.color=background;} else {if (outBounds) {voxel= vec3f(0.15,0.0,0.0);} else {if (voxel.r>0.001) {voxel.g=1.0;}\nvoxel.r+=mip_separator;}\nfragmentOutputs.color=vec4f(mix(background.rgb,voxelSlab.rgb,voxelSlab.a)+voxel,1.0);}}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},16615:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblVoxelSlabDebugPixelShaderWGSL:()=>n});const r="iblVoxelSlabDebugPixelShader",s="varying vNormalizedPosition: vec3f;uniform nearPlane: f32;uniform farPlane: f32;uniform stepSize: f32;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var normPos: vec3f=input.vNormalizedPosition.xyz;var chunkSize: f32=uniforms.stepSize* f32(MAX_DRAW_BUFFERS);var numChunks: f32=1.0/chunkSize;var positionInChunk: f32=fract(normPos.z/chunkSize);var slab: f32=floor(positionInChunk* f32(MAX_DRAW_BUFFERS)) /\nf32(MAX_DRAW_BUFFERS);if (normPos.x<0.0 || normPos.y<0.0 || normPos.z<0.0 ||\nnormPos.x>1.0 || normPos.y>1.0 || normPos.z>1.0) {fragmentOutputs.color= vec4f(0.0,0.0,0.0,0.0);} else {fragmentOutputs.color= vec4f(slab,0.0,0.0,0.75);}}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},94369:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblVoxelSlabDebugVertexShaderWGSL:()=>n});const r="iblVoxelSlabDebugVertexShader",s="attribute position: vec3f;varying vNormalizedPosition: vec3f;uniform world: mat4x4f;uniform invWorldScale: mat4x4f;uniform cameraViewMatrix: mat4x4f;uniform projection: mat4x4f;uniform viewMatrix: mat4x4f;@vertex\nfn main(input : VertexInputs)->FragmentInputs {var worldPosition: vec4f=(uniforms.world* vec4f(input.position,1.));vertexOutputs.position=uniforms.projection*uniforms.cameraViewMatrix*worldPosition;vertexOutputs.vNormalizedPosition=(uniforms.viewMatrix*uniforms.invWorldScale*worldPosition).rgb;vertexOutputs.vNormalizedPosition=vertexOutputs.vNormalizedPosition* vec3f(0.5)+ vec3f(0.5);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},41123:(e,t,i)=>{"use strict";i.r(t),i.d(t,{imageProcessingPixelShaderWGSL:()=>o});var r=i(69841);i(33882),i(87647),i(33731);const s="imageProcessingPixelShader",n="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var result: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\nresult=vec4f(toLinearSpaceVec3(result.rgb),result.a);\n#endif\nresult=applyImageProcessing(result);\n#else\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\nfragmentOutputs.color=result;}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},56558:(e,t,i)=>{"use strict";i.r(t),i.d(t,{kernelBlurPixelShaderWGSL:()=>o});var r=i(69841);i(57932),i(2456);r.l.IncludesShadersStoreWGSL.kernelBlurFragment="#ifdef DOF\nfactor=sampleCoC(fragmentInputs.sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCoord{X}))*computedWeight;\n#else\nblend+=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCoord{X})*computedWeight;\n#endif\n";r.l.IncludesShadersStoreWGSL.kernelBlurFragment2="#ifdef DOF\nfactor=sampleCoC(fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif\n";const s="kernelBlurPixelShader",n="var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform delta: vec2f;varying sampleCenter: vec2f;\n#ifdef DOF\nvar circleOfConfusionSamplerSampler: sampler;var circleOfConfusionSampler: texture_2d;fn sampleCoC(offset: vec2f)->f32 {var coc: f32=textureSample(circleOfConfusionSampler,circleOfConfusionSamplerSampler,offset).r;return coc; }\n#endif\n#include[0..varyingCount]\n#ifdef PACKEDFLOAT\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var computedWeight: f32=0.0;\n#ifdef PACKEDFLOAT\nvar blend: f32=0.;\n#else\nvar blend: vec4f= vec4f(0.);\n#endif\n#ifdef DOF\nvar sumOfWeights: f32=CENTER_WEIGHT; \nvar factor: f32=0.0;\n#ifdef PACKEDFLOAT\nblend+=unpack(textureSample(textureSampler,textureSamplerSampler,input.sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=textureSample(textureSampler,textureSamplerSampler,input.sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include[0..varyingCount]\n#include[0..depCount]\n#ifdef PACKEDFLOAT\nfragmentOutputs.color=pack(blend);\n#else\nfragmentOutputs.color=blend;\n#endif\n#ifdef DOF\nfragmentOutputs.color/=sumOfWeights;\n#endif\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},42876:(e,t,i)=>{"use strict";i.r(t),i.d(t,{kernelBlurVertexShaderWGSL:()=>o});var r=i(69841);i(57932);r.l.IncludesShadersStoreWGSL.kernelBlurVertex="vertexOutputs.sampleCoord{X}=vertexOutputs.sampleCenter+uniforms.delta*KERNEL_OFFSET{X};";const s="kernelBlurVertexShader",n="attribute position: vec2f;uniform delta: vec2f;varying sampleCenter: vec2f;\n#include[0..varyingCount]\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {const madd: vec2f= vec2f(0.5,0.5);\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.sampleCenter=(input.position*madd+madd);\n#include[0..varyingCount]\nvertexOutputs.position= vec4f(input.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},28246:(e,t,i)=>{"use strict";i.r(t),i.d(t,{layerPixelShaderWGSL:()=>o});var r=i(69841);i(87647);const s="layerPixelShader",n="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform color: vec4f;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvar baseColor: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);\n#if defined(CONVERT_TO_GAMMA)\nbaseColor=toGammaSpace(baseColor);\n#elif defined(CONVERT_TO_LINEAR)\nbaseColor=toLinearSpaceVec4(baseColor);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nfragmentOutputs.color=baseColor*uniforms.color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},56028:(e,t,i)=>{"use strict";i.r(t),i.d(t,{layerVertexShaderWGSL:()=>n});const r="layerVertexShader",s="attribute position: vec2f;uniform scale: vec2f;uniform offset: vec2f;uniform textureMatrix: mat4x4f;varying vUV: vec2f;const madd: vec2f= vec2f(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvar shiftedPosition: vec2f=input.position*uniforms.scale+uniforms.offset;vertexOutputs.vUV=(uniforms.textureMatrix* vec4f(shiftedPosition*madd+madd,1.0,0.0)).xy;vertexOutputs.position= vec4f(shiftedPosition,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},19121:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lensFlarePixelShaderWGSL:()=>n});const r="lensFlarePixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform color: vec4f;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvar baseColor: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);fragmentOutputs.color=baseColor*uniforms.color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},72987:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lensFlareVertexShaderWGSL:()=>n});const r="lensFlareVertexShader",s="attribute position: vec2f;uniform viewportMatrix: mat4x4f;varying vUV: vec2f;const madd: vec2f= vec2f(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.vUV=input.position*madd+madd;vertexOutputs.position=uniforms.viewportMatrix* vec4f(input.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},27127:(e,t,i)=>{"use strict";i.r(t),i.d(t,{linePixelShaderWGSL:()=>o});var r=i(69841);i(96140),i(21859),i(85551),i(76794);const s="linePixelShader",n="#include\nuniform color: vec4f;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#include\nfragmentOutputs.color=uniforms.color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},7217:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lineVertexShaderWGSL:()=>o});var r=i(69841);i(41416),i(30486),i(14910),i(10598),i(21859),i(32764),i(57728),i(18201);const s="lineVertexShader",n="#define ADDITIONAL_VERTEX_DECLARATION\n#include\n#include\n#include\n#include\nattribute position: vec3f;attribute normal: vec4f;uniform width: f32;uniform aspectRatio: f32;\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\nvar worldViewProjection: mat4x4f=scene.viewProjection*finalWorld;var viewPosition: vec4f=worldViewProjection* vec4f(input.position,1.0);var viewPositionNext: vec4f=worldViewProjection* vec4f(input.normal.xyz,1.0);var currentScreen: vec2f=viewPosition.xy/viewPosition.w;var nextScreen: vec2f=viewPositionNext.xy/viewPositionNext.w;currentScreen=vec2f(currentScreen.x*uniforms.aspectRatio,currentScreen.y);nextScreen=vec2f(nextScreen.x*uniforms.aspectRatio,nextScreen.y);var dir: vec2f=normalize(nextScreen-currentScreen);var normalDir: vec2f= vec2f(-dir.y,dir.x);normalDir*=uniforms.width/2.0;normalDir=vec2f(normalDir.x/uniforms.aspectRatio,normalDir.y);var offset: vec4f= vec4f(normalDir*input.normal.w,0.0,0.0);vertexOutputs.position=viewPosition+offset;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvar worldPos: vec4f=finalWorld*vec4f(input.position,1.0);\n#include\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},58316:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lodPixelShaderWGSL:()=>n});const r="lodPixelShader",s="const GammaEncodePowerApprox=1.0/2.2;varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform lod: f32;uniform gamma: i32;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,fragmentInputs.vUV,uniforms.lod);if (uniforms.gamma==0) {fragmentOutputs.color=vec4f(pow(fragmentOutputs.color.rgb,vec3f(GammaEncodePowerApprox)),fragmentOutputs.color.a);}}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},61951:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lodCubePixelShaderWGSL:()=>n});const r="lodCubePixelShader",s="const GammaEncodePowerApprox=1.0/2.2;varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_cube;uniform lod: f32;uniform gamma: i32;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {let uv=fragmentInputs.vUV*2.0-1.0;\n#ifdef POSITIVEX\nfragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(1.001,uv.y,uv.x),uniforms.lod);\n#endif\n#ifdef NEGATIVEX\nfragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(-1.001,uv.y,uv.x),uniforms.lod);\n#endif\n#ifdef POSITIVEY\nfragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(uv.y,1.001,uv.x),uniforms.lod);\n#endif\n#ifdef NEGATIVEY\nfragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(uv.y,-1.001,uv.x),uniforms.lod);\n#endif\n#ifdef POSITIVEZ\nfragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(uv,1.001),uniforms.lod);\n#endif\n#ifdef NEGATIVEZ\nfragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(uv,-1.001),uniforms.lod);\n#endif\nif (uniforms.gamma==0) {fragmentOutputs.color=vec4f(pow(fragmentOutputs.color.rgb,vec3f(GammaEncodePowerApprox)),fragmentOutputs.color.a);}}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},49584:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererPixelShaderWGSL:()=>n});const r="meshUVSpaceRendererPixelShader",s="varying vDecalTC: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {if (input.vDecalTC.x<0. || input.vDecalTC.x>1. || input.vDecalTC.y<0. || input.vDecalTC.y>1.) {discard;}\nfragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vDecalTC);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},4830:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererVertexShaderWGSL:()=>o});var r=i(69841);i(25589),i(68273),i(47381),i(51148),i(41416),i(8573),i(43610),i(32764),i(40903),i(71281);const s="meshUVSpaceRendererVertexShader",n="attribute position: vec3f;attribute normal: vec3f;attribute uv: vec2f;uniform projMatrix: mat4x4f;varying vDecalTC: vec2f;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;var normalUpdated: vec3f=input.normal;\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvar worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);var normWorldSM: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);var vNormalW: vec3f;\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/ vec3f(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvNormalW=normalize(normWorldSM*normalUpdated);\n#endif\nvar normalView: vec3f=normalize((uniforms.projMatrix* vec4f(vNormalW,0.0)).xyz);var decalTC: vec3f=(uniforms.projMatrix*worldPos).xyz;vertexOutputs.vDecalTC=decalTC.xy;vertexOutputs.position=vec4f(input.uv*2.0-1.0,select(decalTC.z,2.,normalView.z>0.0),1.0);}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},83479:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererFinaliserPixelShaderWGSL:()=>n});const r="meshUVSpaceRendererFinaliserPixelShader",s="#define DISABLE_UNIFORMITY_ANALYSIS\nvarying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var maskTextureSamplerSampler: sampler;var maskTextureSampler: texture_2d;uniform textureSize: vec2f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var mask: vec4f=textureSample(maskTextureSampler,maskTextureSamplerSampler,input.vUV).rgba;if (mask.r>0.5) {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);} else {var texelSize: vec2f=4.0/uniforms.textureSize;var uv_p01: vec2f=input.vUV+ vec2f(-1.0,0.0)*texelSize;var uv_p21: vec2f=input.vUV+ vec2f(1.0,0.0)*texelSize;var uv_p10: vec2f=input.vUV+ vec2f(0.0,-1.0)*texelSize;var uv_p12: vec2f=input.vUV+ vec2f(0.0,1.0)*texelSize;var mask_p01: f32=textureSample(maskTextureSampler,maskTextureSamplerSampler,uv_p01).r;var mask_p21: f32=textureSample(maskTextureSampler,maskTextureSamplerSampler,uv_p21).r;var mask_p10: f32=textureSample(maskTextureSampler,maskTextureSamplerSampler,uv_p10).r;var mask_p12: f32=textureSample(maskTextureSampler,maskTextureSamplerSampler,uv_p12).r;var col: vec4f= vec4f(0.0,0.0,0.0,0.0);var total_weight: f32=0.0;if (mask_p01>0.5) {col+=textureSample(textureSampler,textureSamplerSampler,uv_p01);total_weight+=1.0;}\nif (mask_p21>0.5) {col+=textureSample(textureSampler,textureSamplerSampler,uv_p21);total_weight+=1.0;}\nif (mask_p10>0.5) {col+=textureSample(textureSampler,textureSamplerSampler,uv_p10);total_weight+=1.0;}\nif (mask_p12>0.5) {col+=textureSample(textureSampler,textureSamplerSampler,uv_p12);total_weight+=1.0;}\nif (total_weight>0.0) {fragmentOutputs.color=col/total_weight;} else {fragmentOutputs.color=col;}}}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},55153:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererFinaliserVertexShaderWGSL:()=>n});const r="meshUVSpaceRendererFinaliserVertexShader",s="attribute position: vec3f;attribute uv: vec2f;uniform worldViewProjection: mat4x4f;varying vUV: vec2f;@vertex\nfn main(input : VertexInputs)->FragmentInputs {vertexOutputs.position=uniforms.worldViewProjection* vec4f(input.position,1.0);vertexOutputs.positionvUV=input.uv;}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},49373:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererMaskerPixelShaderWGSL:()=>n});const r="meshUVSpaceRendererMaskerPixelShader",s="varying vUV: vec2f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color= vec4f(1.0,1.0,1.0,1.0);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},72919:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererMaskerVertexShaderWGSL:()=>n});const r="meshUVSpaceRendererMaskerVertexShader",s="attribute uv: vec2f;varying vUV: vec2f;@vertex\nfn main(input : VertexInputs)->FragmentInputs {vertexOutputs.position= vec4f( vec2f(input.uv.x,input.uv.y)*2.0-1.0,0.,1.0);vertexOutputs.vUV=input.uv;}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},95400:(e,t,i)=>{"use strict";i.r(t),i.d(t,{motionBlurPixelShaderWGSL:()=>n});const r="motionBlurPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform motionStrength: f32;uniform motionScale: f32;uniform screenSize: vec2f;\n#ifdef OBJECT_BASED\nvar velocitySamplerSampler: sampler;var velocitySampler: texture_2d;\n#else\nvar depthSamplerSampler: sampler;var depthSampler: texture_2d;uniform inverseViewProjection: mat4x4f;uniform prevViewProjection: mat4x4f;uniform projection: mat4x4f;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#ifdef GEOMETRY_SUPPORTED\n#ifdef OBJECT_BASED\nvar texelSize: vec2f=1.0/uniforms.screenSize;var velocityColor: vec4f=textureSample(velocitySampler,velocitySamplerSampler,input.vUV);velocityColor=vec4f(velocityColor.rg*2.0- vec2f(1.0),velocityColor.b,velocityColor.a);var velocity: vec2f= vec2f(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=uniforms.motionScale*uniforms.motionStrength;var speed: f32=length(velocity/texelSize);var samplesCount: i32= i32(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;var hlim: f32= f32(-samplesCount)*0.5+0.5;var result: vec4f=textureSample(textureSampler,textureSamplerSampler, input.vUV);for (var i: i32=1; i< i32(SAMPLES); i++)\n{if (i>=samplesCount) {break;}\nvar offset: vec2f=input.vUV+velocity*(hlim+ f32(i));\n#if defined(WEBGPU)\nresult+=textureSampleLevel(textureSampler,textureSamplerSampler, offset,0.0);\n#else\nresult+=textureSample(textureSampler,textureSamplerSampler, offset);\n#endif\n}\nfragmentOutputs.color=vec4f(result.rgb/ f32(samplesCount),1.0);\n#else\nvar texelSize: vec2f=1.0/uniforms.screenSize;var depth: f32=textureSample(depthSampler,depthSamplerSampler,input.vUV).r;depth=uniforms.projection[2].z+uniforms.projection[3].z/depth; \nvar cpos: vec4f= vec4f(input.vUV*2.0-1.0,depth,1.0);cpos=uniforms.inverseViewProjection*cpos;cpos/=cpos.w;var ppos: vec4f=uniforms.prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;var velocity: vec2f=(ppos.xy-input.vUV)*uniforms.motionScale*uniforms.motionStrength;var speed: f32=length(velocity/texelSize);var nSamples: i32= i32(clamp(speed,1.0,SAMPLES));var result: vec4f=textureSample(textureSampler,textureSamplerSampler, input.vUV);for (var i: i32=1; i< i32(SAMPLES); i++) {if (i>=nSamples) {break;}\nvar offset1: vec2f=input.vUV+velocity*( f32(i)/ f32(nSamples-1)-0.5);\n#if defined(WEBGPU)\nresult+=textureSampleLevel(textureSampler,textureSamplerSampler, offset1,0.0);\n#else\nresult+=textureSample(textureSampler,textureSamplerSampler, offset1);\n#endif\n}\nfragmentOutputs.color=result/ f32(nSamples);\n#endif\n#else\nfragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler, input.vUV);\n#endif\n}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},29551:(e,t,i)=>{"use strict";i.r(t),i.d(t,{oitBackBlendPixelShaderWGSL:()=>n});const r="oitBackBlendPixelShader",s="var uBackColor: texture_2d;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureLoad(uBackColor,vec2i(fragmentInputs.position.xy),0);if (fragmentOutputs.color.a==0.0) {discard;}}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},21937:(e,t,i)=>{"use strict";i.r(t),i.d(t,{oitFinalPixelShaderWGSL:()=>n});const r="oitFinalPixelShader",s="var uFrontColor: texture_2d;var uBackColor: texture_2d;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var fragCoord: vec2i=vec2i(fragmentInputs.position.xy);var frontColor: vec4f=textureLoad(uFrontColor,fragCoord,0);var backColor: vec4f=textureLoad(uBackColor,fragCoord,0);var alphaMultiplier: f32=1.0-frontColor.a;fragmentOutputs.color=vec4f(\nfrontColor.rgb+alphaMultiplier*backColor.rgb,\nfrontColor.a+backColor.a\n);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},55515:(e,t,i)=>{"use strict";i.r(t),i.d(t,{outlinePixelShaderWGSL:()=>o});var r=i(69841);i(96140),i(21859),i(76794),i(85551);const s="outlinePixelShader",n="uniform color: vec4f;\n#ifdef ALPHATEST\nvarying vUV: vec2;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#ifdef ALPHATEST\nif (textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vUV).a<0.4) {discard;}\n#endif\n#include\nfragmentOutputs.color=uniforms.color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},18789:(e,t,i)=>{"use strict";i.r(t),i.d(t,{outlineVertexShaderWGSL:()=>o});var r=i(69841);i(25589),i(68273),i(47381),i(51148),i(30486),i(41416),i(21859),i(8573),i(43610),i(32764),i(40903),i(71281),i(57728),i(18201);const s="outlineVertexShader",n="attribute position: vec3f;attribute normal: vec3f;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform offset: f32;\n#include\nuniform viewProjection: mat4x4f;\n#ifdef ALPHATEST\nvarying vUV: vec2f;uniform diffuseMatrix: mat4x4f; \n#ifdef UV1\nattribute uv: vec2f;\n#endif\n#ifdef UV2\nattribute uv2: vec2f;\n#endif\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input: VertexInputs)->FragmentInputs {var positionUpdated: vec3f=vertexInputs.position;var normalUpdated: vec3f=vertexInputs.normal;\n#ifdef UV1\nvar uvUpdated: vec2f=vertexInputs.uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\nvar offsetPosition: vec3f=positionUpdated+(normalUpdated*uniforms.offset);\n#include\n#include\n#include\nvar worldPos: vec4f=finalWorld*vec4f(offsetPosition,1.0);vertexOutputs.position=uniforms.viewProjection*worldPos;\n#ifdef ALPHATEST\n#ifdef UV1\nvertexOutputs.vUV=(uniforms.diffuseMatrix*vec4f(uvUpdated,1.0,0.0)).xy;\n#endif\n#ifdef UV2\nvertexOutputs.vUV=(uniforms.diffuseMatrix*vec4f(vertexInputs.uv2,1.0,0.0)).xy;\n#endif\n#endif\n#include\n#include\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},86144:(e,t,i)=>{"use strict";i.r(t),i.d(t,{particlesPixelShaderWGSL:()=>o});var r=i(69841);i(96140),i(33882),i(21859),i(87647),i(33731),i(10668),i(76794),i(85551),i(31034);const s="particlesPixelShader",n="varying vUV: vec2f;varying vColor: vec4f;uniform textureMask: vec4f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d;\n#include\n#include\n#include\n#include\n#include\n#ifdef RAMPGRADIENT\nvarying remapRanges: vec4f;var rampSamplerSampler: sampler;var rampSampler: texture_2d;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvar textureColor: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV);var baseColor: vec4f=(textureColor*uniforms.textureMask+( vec4f(1.,1.,1.,1.)-uniforms.textureMask))*input.vColor;\n#ifdef RAMPGRADIENT\nvar alpha: f32=baseColor.a;var remappedColorIndex: f32=clamp((alpha-input.remapRanges.x)/input.remapRanges.y,0.0,1.0);var rampColor: vec4f=textureSample(rampSampler,rampSamplerSampler,vec2f(1.0-remappedColorIndex,0.));baseColor=vec4f(baseColor.rgb*rampColor.rgb,baseColor.a);var finalAlpha: f32=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-input.remapRanges.z)/input.remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nvar sourceAlpha: f32=input.vColor.a*textureColor.a;baseColor=vec4f(baseColor.rgb*sourceAlpha+ vec3f(1.0)*(1.0-sourceAlpha),baseColor.a);\n#endif\n#include\n#include(color,baseColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor=vec4f(toLinearSpaceVec3(baseColor.rgb),baseColor.a);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor=vec4f(toLinearSpaceVec3(baseColor.rgb),baseColor.a);baseColor=applyImageProcessing(baseColor);\n#endif\n#endif\nfragmentOutputs.color=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},25806:(e,t,i)=>{"use strict";i.r(t),i.d(t,{particlesVertexShaderWGSL:()=>o});var r=i(69841);i(30486),i(86934),i(21859),i(57728),i(45184),i(18201);const s="particlesVertexShader",n="attribute position: vec3f;attribute color: vec4f;attribute angle: f32;attribute size: vec2f;\n#ifdef ANIMATESHEET\nattribute cellIndex: f32;\n#endif\n#ifndef BILLBOARD\nattribute direction: vec3f;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute direction: vec3f;\n#endif\n#ifdef RAMPGRADIENT\nattribute remapData: vec4f;\n#endif\nattribute offset: vec2f;uniform view: mat4x4f;uniform projection: mat4x4f;uniform translationPivot: vec2f;\n#ifdef ANIMATESHEET\nuniform particlesInfos: vec3f; \n#endif\nvarying vUV: vec2f;varying vColor: vec4f;varying vPositionW: vec3f;\n#ifdef RAMPGRADIENT\nvarying remapRanges: vec4f;\n#endif\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform invView: mat4x4f;\n#endif\n#include\n#include\n#include\n#ifdef BILLBOARD\nuniform eyePosition: vec3f;\n#endif\nfn rotate(yaxis: vec3f,rotatedCorner: vec3f)->vec3f {var xaxis: vec3f=normalize(cross( vec3f(0.,1.0,0.),yaxis));var zaxis: vec3f=normalize(cross(yaxis,xaxis));var row0: vec3f= vec3f(xaxis.x,xaxis.y,xaxis.z);var row1: vec3f= vec3f(yaxis.x,yaxis.y,yaxis.z);var row2: vec3f= vec3f(zaxis.x,zaxis.y,zaxis.z);var rotMatrix: mat3x3f= mat3x3f(row0,row1,row2);var alignedCorner: vec3f=rotMatrix*rotatedCorner;return vertexInputs.position+alignedCorner;}\n#ifdef BILLBOARDSTRETCHED\nfn rotateAlign(toCamera: vec3f,rotatedCorner: vec3f)->vec3f {var normalizedToCamera: vec3f=normalize(toCamera);var normalizedCrossDirToCamera: vec3f=normalize(cross(normalize(vertexInputs.direction),normalizedToCamera));var row0: vec3f= vec3f(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);var row2: vec3f= vec3f(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\n#ifdef BILLBOARDSTRETCHED_LOCAL\nvar row1: vec3f=vertexInputs.direction;\n#else\nvar crossProduct: vec3f=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));var row1: vec3f= vec3f(crossProduct.x,crossProduct.y,crossProduct.z);\n#endif\nvar rotMatrix: mat3x3f= mat3x3f(row0,row1,row2);var alignedCorner: vec3f=rotMatrix*rotatedCorner;return input.position+alignedCorner;}\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvar cornerPos: vec2f;cornerPos=( vec2f(input.offset.x-0.5,input.offset.y -0.5)-uniforms.translationPivot)*input.size;\n#ifdef BILLBOARD\nvar rotatedCorner: vec3f;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.z=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.y=0.;var yaxis: vec3f=input.position-uniforms.eyePosition;yaxis.y=0.;vertexOutputs.vPositionW=rotate(normalize(yaxis),rotatedCorner);var viewPos: vec3f=(uniforms.view* vec4f(vertexOutputs.vPositionW,1.0)).xyz;\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.y=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.z=0.;var toCamera: vec3f=input.position-uniforms.eyePosition;vertexOutputs.vPositionW=rotateAlign(toCamera,rotatedCorner);var viewPos: vec3f=(uniforms.view* vec4f(vertexOutputs.vPositionW,1.0)).xyz;\n#else\nrotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.y=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.z=0.;var viewPos: vec3f=(uniforms.view* vec4f(input.position,1.0)).xyz+rotatedCorner;vertexOutputs.vPositionW=(uniforms.invView* vec4f(viewPos,1)).xyz;\n#endif\n#ifdef RAMPGRADIENT\nvertexOutputs.remapRanges=input.remapData;\n#endif\nvertexOutputs.position=uniforms.projection* vec4f(viewPos,1.0);\n#else\nvar rotatedCorner: vec3f;rotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.z=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.y=0.;var yaxis: vec3f=normalize(vertexInputs.direction);vertexOutputs.vPositionW=rotate(yaxis,rotatedCorner);vertexOutputs.position=uniforms.projection*uniforms.view* vec4f(vertexOutputs.vPositionW,1.0);\n#endif\nvertexOutputs.vColor=input.color;\n#ifdef ANIMATESHEET\nvar rowOffset: f32=floor(input.cellIndex*uniforms.particlesInfos.z);var columnOffset: f32=input.cellIndex-rowOffset/uniforms.particlesInfos.z;var uvScale: vec2f=uniforms.particlesInfos.xy;var uvOffset: vec2f= vec2f(input.offset.x ,1.0-input.offset.y);vertexOutputs.vUV=(uvOffset+ vec2f(columnOffset,rowOffset))*uvScale;\n#else\nvertexOutputs.vUV=input.offset;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)\nvar worldPos: vec4f= vec4f(vertexOutputs.vPositionW,1.0);\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},418:(e,t,i)=>{"use strict";i.r(t),i.d(t,{passPixelShaderWGSL:()=>n});const r="passPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},12253:(e,t,i)=>{"use strict";i.r(t),i.d(t,{passCubePixelShaderWGSL:()=>n});const r="passCubePixelShader",s="varying var vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_cube;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var uv: vec2f=input.vUV*2.0-1.0;\n#ifdef POSITIVEX\nfragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\nfragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\nfragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\nfragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\nfragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\nfragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv,-1.001));\n#endif\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},66854:(e,t,i)=>{"use strict";i.r(t),i.d(t,{pbrPixelShaderWGSL:()=>o});var r=i(69841);i(85620),i(73048),i(53894),i(36174);r.l.IncludesShadersStoreWGSL.pbrFragmentExtraDeclaration="varying vPositionW: vec3f;\n#if DEBUGMODE>0\nvarying vClipSpacePosition: vec4f;\n#endif\n#include[1..7]\n#ifdef NORMAL\nvarying vNormalW: vec3f;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vEnvironmentIrradiance: vec3f;\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vColor: vec4f;\n#endif\n",i(71426),i(59224);r.l.IncludesShadersStoreWGSL.samplerFragmentAlternateDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying v_VARYINGNAME_UV: vec2f;\n#endif\n#endif\n";r.l.IncludesShadersStoreWGSL.pbrFragmentSamplersDeclaration="#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nvar clearCoatRoughnessSamplerSampler: sampler;var clearCoatRoughnessSampler: texture_2d;\n#endif\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS)\nvar sheenRoughnessSamplerSampler: sampler;var sheenRoughnessSampler: texture_2d;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nvar reflectionSamplerSampler: sampler;var reflectionSampler: texture_cube;\n#ifdef LODBASEDMICROSFURACE\n#else\nvar reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_cube;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_cube;\n#endif\n#ifdef USEIRRADIANCEMAP\nvar irradianceSamplerSampler: sampler;var irradianceSampler: texture_cube;\n#endif\n#else\nvar reflectionSamplerSampler: sampler;var reflectionSampler: texture_2d;\n#ifdef LODBASEDMICROSFURACE\n#else\nvar reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_2d;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_2d;\n#endif\n#ifdef USEIRRADIANCEMAP\nvar irradianceSamplerSampler: sampler;var irradianceSampler: texture_2d;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vPositionUVW: vec3f;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vDirectionW: vec3f;\n#endif\n#endif\n#endif\n#ifdef ENVIRONMENTBRDF\nvar environmentBrdfSamplerSampler: sampler;var environmentBrdfSampler: texture_2d;\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#ifdef SS_REFRACTIONMAP_3D\nvar refractionSamplerSampler: sampler;var refractionSampler: texture_cube;\n#ifdef LODBASEDMICROSFURACE\n#else\nvar refractionLowSamplerSampler: sampler;var refractionLowSampler: texture_cube;var refractionHighSamplerSampler: sampler;var refractionHighSampler: texture_cube;\n#endif\n#else\nvar refractionSamplerSampler: sampler;var refractionSampler: texture_2d;\n#ifdef LODBASEDMICROSFURACE\n#else\nvar refractionLowSamplerSampler: sampler;var refractionLowSampler: texture_2d;var refractionHighSamplerSampler: sampler;var refractionHighSampler: texture_2d;\n#endif\n#endif\n#endif\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_SAMPLERNAME_,translucencyColor)\n#endif\n",i(33882),i(96140),i(21859),i(10668),i(87647);r.l.IncludesShadersStoreWGSL.subSurfaceScatteringFunctions="fn testLightingForSSS(diffusionProfile: f32)->bool\n{return diffusionProfile<1.;}",i(60755);r.l.IncludesShadersStoreWGSL.pbrHelperFunctions="#define MINIMUMVARIANCE 0.0005\nfn convertRoughnessToAverageSlope(roughness: f32)->f32\n{return roughness*roughness+MINIMUMVARIANCE;}\nfn fresnelGrazingReflectance(reflectance0: f32)->f32 {var reflectance90: f32=saturate(reflectance0*25.0);return reflectance90;}\nfn getAARoughnessFactors(normalVector: vec3f)->vec2f {\n#ifdef SPECULARAA\nvar nDfdx: vec3f=dpdx(normalVector.xyz);var nDfdy: vec3f=dpdy(normalVector.xyz);var slopeSquare: f32=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));var geometricRoughnessFactor: f32=pow(saturate(slopeSquare),0.333);var geometricAlphaGFactor: f32=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2f(geometricRoughnessFactor,geometricAlphaGFactor);\n#else\nreturn vec2f(0.);\n#endif\n}\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_LEGACY\nfn getAnisotropicRoughness(alphaG: f32,anisotropy: f32)->vec2f {var alphaT: f32=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);var alphaB: f32=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2f(alphaT,alphaB);}\nfn getAnisotropicBentNormals(T: vec3f,B: vec3f,N: vec3f,V: vec3f,anisotropy: f32,roughness: f32)->vec3f {var anisotropicFrameDirection: vec3f=select(T,B,anisotropy>=0.0);var anisotropicFrameTangent: vec3f=cross(normalize(anisotropicFrameDirection),V);var anisotropicFrameNormal: vec3f=cross(anisotropicFrameTangent,anisotropicFrameDirection);var anisotropicNormal: vec3f=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;}\n#else\nfn getAnisotropicRoughness(alphaG: f32,anisotropy: f32)->vec2f {var alphaT: f32=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);var alphaB: f32=max(alphaG,MINIMUMVARIANCE);return vec2f(alphaT,alphaB);}\nfn getAnisotropicBentNormals(T: vec3f,B: vec3f,N: vec3f,V: vec3f,anisotropy: f32,roughness: f32)->vec3f {var bentNormal: vec3f=cross(B,V);bentNormal=normalize(cross(bentNormal,B));var sq=1.0-anisotropy*(1.0-roughness);var a: f32=sq*sq*sq*sq;bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;}\n#endif\n#endif\n#if defined(CLEARCOAT) || defined(SS_REFRACTION)\nfn cocaLambertVec3(alpha: vec3f,distance: f32)->vec3f {return exp(-alpha*distance);}\nfn cocaLambert(NdotVRefract: f32,NdotLRefract: f32,alpha: vec3f,thickness: f32)->vec3f {return cocaLambertVec3(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));}\nfn computeColorAtDistanceInMedia(color: vec3f,distance: f32)->vec3f {return -log(color)/distance;}\nfn computeClearCoatAbsorption(NdotVRefract: f32,NdotLRefract: f32,clearCoatColor: vec3f,clearCoatThickness: f32,clearCoatIntensity: f32)->vec3f {var clearCoatAbsorption: vec3f=mix( vec3f(1.0),\ncocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),\nclearCoatIntensity);return clearCoatAbsorption;}\n#endif\n#ifdef MICROSURFACEAUTOMATIC\nfn computeDefaultMicroSurface(microSurface: f32,reflectivityColor: vec3f)->f32\n{const kReflectivityNoAlphaWorkflow_SmoothnessMax: f32=0.95;var reflectivityLuminance: f32=getLuminance(reflectivityColor);var reflectivityLuma: f32=sqrt(reflectivityLuminance);var resultMicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return resultMicroSurface;}\n#endif\n",i(33731),i(94662),i(36437);r.l.IncludesShadersStoreWGSL.pbrDirectLightingSetupFunctions="struct preLightingInfo\n{lightOffset: vec3f,\nlightDistanceSquared: f32,\nlightDistance: f32,\nattenuation: f32,\nL: vec3f,\nH: vec3f,\nNdotV: f32,\nNdotLUnclamped: f32,\nNdotL: f32,\nVdotH: f32,\nroughness: f32,\n#ifdef IRIDESCENCE\niridescenceIntensity: f32\n#endif\n};fn computePointAndSpotPreLightingInfo(lightData: vec4f,V: vec3f,N: vec3f,posW: vec3f)->preLightingInfo {var result: preLightingInfo;result.lightOffset=lightData.xyz-posW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\nfn computeDirectionalPreLightingInfo(lightData: vec4f,V: vec3f,N: vec3f)->preLightingInfo {var result: preLightingInfo;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\nfn computeHemisphericPreLightingInfo(lightData: vec4f,V: vec3f,N: vec3f)->preLightingInfo {var result: preLightingInfo;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL;\n#ifdef SPECULARTERM\nresult.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));\n#endif\nreturn result;}";r.l.IncludesShadersStoreWGSL.pbrDirectLightingFalloffFunctions="fn computeDistanceLightFalloff_Standard(lightOffset: vec3f,range: f32)->f32\n{return max(0.,1.0-length(lightOffset)/range);}\nfn computeDistanceLightFalloff_Physical(lightDistanceSquared: f32)->f32\n{return 1.0/maxEps(lightDistanceSquared);}\nfn computeDistanceLightFalloff_GLTF(lightDistanceSquared: f32,inverseSquaredRange: f32)->f32\n{var lightDistanceFalloff: f32=1.0/maxEps(lightDistanceSquared);var factor: f32=lightDistanceSquared*inverseSquaredRange;var attenuation: f32=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;}\nfn computeDistanceLightFalloff(lightOffset: vec3f,lightDistanceSquared: f32,range: f32,inverseSquaredRange: f32)->f32\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfn computeDirectionalLightFalloff_Standard(lightDirection: vec3f,directionToLightCenterW: vec3f,cosHalfAngle: f32,exponent: f32)->f32\n{var falloff: f32=0.0;var cosAngle: f32=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle)\n{falloff=max(0.,pow(cosAngle,exponent));}\nreturn falloff;}\nfn computeDirectionalLightFalloff_Physical(lightDirection: vec3f,directionToLightCenterW: vec3f,cosHalfAngle: f32)->f32\n{const kMinusLog2ConeAngleIntensityRatio: f32=6.64385618977; \nvar concentrationKappa: f32=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);var lightDirectionSpreadSG: vec4f= vec4f(-lightDirection*concentrationKappa,-concentrationKappa);var falloff: f32=exp2(dot( vec4f(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;}\nfn computeDirectionalLightFalloff_GLTF(lightDirection: vec3f,directionToLightCenterW: vec3f,lightAngleScale: f32,lightAngleOffset: f32)->f32\n{var cd: f32=dot(-lightDirection,directionToLightCenterW);var falloff: f32=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;}\nfn computeDirectionalLightFalloff(lightDirection: vec3f,directionToLightCenterW: vec3f,cosHalfAngle: f32,exponent: f32,lightAngleScale: f32,lightAngleOffset: f32)->f32\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}",i(20427),i(49335);r.l.IncludesShadersStoreWGSL.pbrDirectLightingFunctions="#define CLEARCOATREFLECTANCE90 1.0\nstruct lightingInfo\n{diffuse: vec3f,\n#ifdef SPECULARTERM\nspecular: vec3f,\n#endif\n#ifdef CLEARCOAT\nclearCoat: vec4f,\n#endif\n#ifdef SHEEN\nsheen: vec3f\n#endif\n};fn adjustRoughnessFromLightProperties(roughness: f32,lightRadius: f32,lightDistance: f32)->f32 {\n#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\nvar lightRoughness: f32=lightRadius/lightDistance;var totalRoughness: f32=saturate(lightRoughness+roughness);return totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfn computeHemisphericDiffuseLighting(info: preLightingInfo,lightColor: vec3f,groundColor: vec3f)->vec3f {return mix(groundColor,lightColor,info.NdotL);}\nfn computeDiffuseLighting(info: preLightingInfo,lightColor: vec3f)->vec3f {var diffuseTerm: f32=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;}\nfn computeProjectionTextureDiffuseLighting(projectionLightTexture: texture_2d,projectionLightSampler: sampler,textureProjectionMatrix: mat4x4f,posW: vec3f)->vec3f{var strq: vec4f=textureProjectionMatrix* vec4f(posW,1.0);strq/=strq.w;var textureColor: vec3f=textureSample(projectionLightTexture,projectionLightSampler,strq.xy).rgb;return toLinearSpaceVec3(textureColor);}\n#ifdef SS_TRANSLUCENCY\nfn computeDiffuseAndTransmittedLighting(info: preLightingInfo,lightColor: vec3f,transmittance: vec3f)->vec3f {var NdotL: f32=absEps(info.NdotLUnclamped);var wrapNdotL: f32=computeWrappedDiffuseNdotL(NdotL,0.02);var trAdapt: f32=step(0.,info.NdotLUnclamped);var transmittanceNdotL: vec3f=mix(transmittance*wrapNdotL, vec3f(wrapNdotL),trAdapt);var diffuseTerm: f32=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;}\n#endif\n#ifdef SPECULARTERM\nfn computeSpecularLighting(info: preLightingInfo,N: vec3f,reflectance0: vec3f,reflectance90: vec3f,geometricRoughnessFactor: f32,lightColor: vec3f)->vec3f {var NdotH: f32=saturateEps(dot(N,info.H));var roughness: f32=max(info.roughness,geometricRoughnessFactor);var alphaG: f32=convertRoughnessToAverageSlope(roughness);var fresnel: vec3f=fresnelSchlickGGXVec3(info.VdotH,reflectance0,reflectance90);\n#ifdef IRIDESCENCE\nfresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);\n#endif\nvar distribution: f32=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvar smithVisibility: f32=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG);\n#else\nvar smithVisibility: f32=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG);\n#endif\nvar specTerm: vec3f=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;}\n#endif\n#ifdef ANISOTROPIC\nfn computeAnisotropicSpecularLighting(info: preLightingInfo,V: vec3f,N: vec3f,T: vec3f,B: vec3f,anisotropy: f32,reflectance0: vec3f,reflectance90: vec3f,geometricRoughnessFactor: f32,lightColor: vec3f)->vec3f {var NdotH: f32=saturateEps(dot(N,info.H));var TdotH: f32=dot(T,info.H);var BdotH: f32=dot(B,info.H);var TdotV: f32=dot(T,V);var BdotV: f32=dot(B,V);var TdotL: f32=dot(T,info.L);var BdotL: f32=dot(B,info.L);var alphaG: f32=convertRoughnessToAverageSlope(info.roughness);var alphaTB: vec2f=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,vec2f(geometricRoughnessFactor*geometricRoughnessFactor));var fresnel: vec3f=fresnelSchlickGGXVec3(info.VdotH,reflectance0,reflectance90);\n#ifdef IRIDESCENCE\nfresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);\n#endif\nvar distribution: f32=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);var smithVisibility: f32=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);var specTerm: vec3f=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;}\n#endif\n#ifdef CLEARCOAT\nfn computeClearCoatLighting(info: preLightingInfo,Ncc: vec3f,geometricRoughnessFactor: f32,clearCoatIntensity: f32,lightColor: vec3f)->vec4f {var NccdotL: f32=saturateEps(dot(Ncc,info.L));var NccdotH: f32=saturateEps(dot(Ncc,info.H));var clearCoatRoughness: f32=max(info.roughness,geometricRoughnessFactor);var alphaG: f32=convertRoughnessToAverageSlope(clearCoatRoughness);var fresnel: f32=fresnelSchlickGGX(info.VdotH,uniforms.vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;var distribution: f32=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);var kelemenVisibility: f32=visibility_Kelemen(info.VdotH);var clearCoatTerm: f32=fresnel*distribution*kelemenVisibility;return vec4f(\nclearCoatTerm*info.attenuation*NccdotL*lightColor,\n1.0-fresnel\n);}\nfn computeClearCoatLightingAbsorption(NdotVRefract: f32,L: vec3f,Ncc: vec3f,clearCoatColor: vec3f,clearCoatThickness: f32,clearCoatIntensity: f32)->vec3f {var LRefract: vec3f=-refract(L,Ncc,uniforms.vClearCoatRefractionParams.y);var NdotLRefract: f32=saturateEps(dot(Ncc,LRefract));var absorption: vec3f=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;}\n#endif\n#ifdef SHEEN\nfn computeSheenLighting(info: preLightingInfo,N: vec3f,reflectance0: vec3f,reflectance90: vec3f,geometricRoughnessFactor: f32,lightColor: vec3f)->vec3f {var NdotH: f32=saturateEps(dot(N,info.H));var roughness: f32=max(info.roughness,geometricRoughnessFactor);var alphaG: f32=convertRoughnessToAverageSlope(roughness);var fresnel: f32=1.;var distribution: f32=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER\nvar visibility: f32=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG);\n#else */\nvar visibility: f32=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */\nvar sheenTerm: f32=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;}\n#endif\n";r.l.IncludesShadersStoreWGSL.pbrIBLFunctions="#if defined(REFLECTION) || defined(SS_REFRACTION)\nfn getLodFromAlphaG(cubeMapDimensionPixels: f32,microsurfaceAverageSlope: f32)->f32 {var microsurfaceAverageSlopeTexels: f32=cubeMapDimensionPixels*microsurfaceAverageSlope;var lod: f32=log2(microsurfaceAverageSlopeTexels);return lod;}\nfn getLinearLodFromRoughness(cubeMapDimensionPixels: f32,roughness: f32)->f32 {var lod: f32=log2(cubeMapDimensionPixels)*roughness;return lod;}\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION)\nfn environmentRadianceOcclusion(ambientOcclusion: f32,NdotVUnclamped: f32)->f32 {var temp: f32=NdotVUnclamped+ambientOcclusion;return saturate(temp*temp-1.0+ambientOcclusion);}\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION)\nfn environmentHorizonOcclusion(view: vec3f,normal: vec3f,geometricNormal: vec3f)->f32 {var reflection: vec3f=reflect(view,normal);var temp: f32=saturate(1.0+1.1*dot(reflection,geometricNormal));return temp*temp;}\n#endif\n#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA)\nfn UNPACK_LOD(x: f32)->f32 {return (1.0-x)*255.0;}\nfn getLodFromAlphaGNdotV(cubeMapDimensionPixels: f32,alphaG: f32,NdotV: f32)->f32 {var microsurfaceAverageSlope: f32=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);}\n#endif\n",i(56332),i(87087),i(7769),i(17327);r.l.IncludesShadersStoreWGSL.pbrBlockAlbedoOpacity="struct albedoOpacityOutParams\n{surfaceAlbedo: vec3f,\nalpha: f32};\n#define pbr_inline\nfn albedoOpacityBlock(\nvAlbedoColor: vec4f\n#ifdef ALBEDO\n,albedoTexture: vec4f\n,albedoInfos: vec2f\n#endif\n#ifdef OPACITY\n,opacityMap: vec4f\n,vOpacityInfos: vec2f\n#endif\n#ifdef DETAIL\n,detailColor: vec4f\n,vDetailInfos: vec4f\n#endif\n#ifdef DECAL\n,decalColor: vec4f\n,vDecalInfos: vec4f\n#endif\n)->albedoOpacityOutParams\n{var outParams: albedoOpacityOutParams;var surfaceAlbedo: vec3f=vAlbedoColor.rgb;var alpha: f32=vAlbedoColor.a;\n#ifdef ALBEDO\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\n#ifdef GAMMAALBEDO\nsurfaceAlbedo*=toLinearSpaceVec3(albedoTexture.rgb);\n#else\nsurfaceAlbedo*=albedoTexture.rgb;\n#endif\nsurfaceAlbedo*=albedoInfos.y;\n#endif\n#ifndef DECAL_AFTER_DETAIL\n#include\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nsurfaceAlbedo*=fragmentInputs.vColor.rgb;\n#endif\n#ifdef DETAIL\nvar detailAlbedo: f32=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; \n#endif\n#ifdef DECAL_AFTER_DETAIL\n#include\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALBEDO\n#ifdef OPACITY\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=fragmentInputs.vColor.a;\n#endif\n#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST \n#if DEBUGMODE != 88\nif (alpha{"use strict";i.r(t),i.d(t,{pbrVertexShaderWGSL:()=>o});var r=i(69841);i(53894),i(20115),i(36174),i(87647),i(25589),i(68273),i(41416),i(17894),i(30642),i(36437),i(96760),i(30486),i(86934),i(85188),i(47381),i(51148),i(21859),i(8573),i(43610),i(32764),i(40903),i(71281),i(51152),i(80699),i(84326),i(73918),i(57728),i(45184),i(48453),i(42321),i(18201);const s="pbrVertexShader",n="#include\n#define CUSTOM_VERTEX_BEGIN\nattribute position: vec3f;\n#ifdef NORMAL\nattribute normal: vec3f;\n#endif\n#ifdef TANGENT\nattribute tangent: vec4f;\n#endif\n#ifdef UV1\nattribute uv: vec2f;\n#endif\n#include[2..7]\n#include[1..7]\n#ifdef VERTEXCOLOR\nattribute color: vec4f;\n#endif\n#include\n#include\n#include\n#include\n#include\n#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy)\n#endif\n#ifdef SUBSURFACE\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor)\n#endif\nvarying vPositionW: vec3f;\n#if DEBUGMODE>0\nvarying vClipSpacePosition: vec4f;\n#endif\n#ifdef NORMAL\nvarying vNormalW: vec3f;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vEnvironmentIrradiance: vec3f;\n#include\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vColor: vec4f;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vPositionUVW: vec3f;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vDirectionW: vec3f;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvar positionUpdated: vec3f=vertexInputs.position;\n#ifdef NORMAL\nvar normalUpdated: vec3f=vertexInputs.normal;\n#endif\n#ifdef TANGENT\nvar tangentUpdated: vec4f=vertexInputs.tangent;\n#endif\n#ifdef UV1\nvar uvUpdated: vec2f=vertexInputs.uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvertexOutputs.vPositionUVW=positionUpdated;\n#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include\n#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)\nvertexOutputs.vCurrentPosition=scene.viewProjection*finalWorld*vec4f(positionUpdated,1.0);vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*vec4f(positionUpdated,1.0);\n#endif\n#include\n#include\nvar worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);vertexOutputs.vPositionW= worldPos.xyz;\n#ifdef PREPASS\n#include\n#endif\n#ifdef NORMAL\nvar normalWorld: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvertexOutputs.vNormalW=normalUpdated/ vec3f(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vertexOutputs.vNormalW=normalize(normalWorld*vertexOutputs.vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvertexOutputs.vNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvar reflectionVector: vec3f= (uniforms.reflectionMatrix* vec4f(vertexOutputs.vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvertexOutputs.vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector);\n#endif\n#endif\n#define CUSTOM_VERTEX_UPDATE_WORLDPOS\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {vertexOutputs.position=scene.viewProjection*worldPos;} else {vertexOutputs.position=scene.viewProjectionR*worldPos;}\n#else\nvertexOutputs.position=scene.viewProjection*worldPos;\n#endif\n#if DEBUGMODE>0\nvertexOutputs.vClipSpacePosition=vertexOutputs.position;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvertexOutputs.vDirectionW=normalize((finalWorld*vec4f(positionUpdated,0.0)).xyz);\n#endif\n#ifndef UV1\nvar uvUpdated: vec2f= vec2f(0.,0.);\n#endif\n#ifdef MAINUV1\nvertexOutputs.vMainUV1=uvUpdated;\n#endif\n#include[2..7]\n#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z)\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheenRoughness,_INFONAME_,SheenInfos.z)\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x)\n#endif\n#ifdef SUBSURFACE\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x)\n#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_MATRIXNAME_,translucencyColor,_INFONAME_,TranslucencyColorInfos.x)\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},38020:(e,t,i)=>{"use strict";i.r(t),i.d(t,{pickingPixelShaderWGSL:()=>n});const r="pickingPixelShader",s="#if defined(INSTANCES)\nvarying vMeshID: vec4f;\n#else\nuniform meshID: vec4f;\n#endif\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#if defined(INSTANCES)\nfragmentOutputs.color=input.vMeshID;\n#else\nfragmentOutputs.color=uniforms.meshID;\n#endif\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},17570:(e,t,i)=>{"use strict";i.r(t),i.d(t,{pickingVertexShaderWGSL:()=>o});var r=i(69841);i(25589),i(68273),i(47381),i(51148),i(41416),i(8573),i(43610),i(32764),i(40903),i(71281);const s="pickingVertexShader",n="attribute position: vec3f;\n#if defined(INSTANCES)\nattribute instanceMeshID: vec4f;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform viewProjection: mat4x4f;\n#if defined(INSTANCES)\nvarying vMeshID: vec4f;\n#endif\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvar worldPos: vec4f=finalWorld*vec4f(input.position,1.0);vertexOutputs.position=uniforms.viewProjection*worldPos;\n#if defined(INSTANCES)\nvertexOutputs.vMeshID=input.instanceMeshID;\n#endif\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},45010:(e,t,i)=>{"use strict";i.r(t),i.d(t,{postprocessVertexShaderWGSL:()=>n});const r="postprocessVertexShader",s="attribute position: vec2;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},67402:(e,t,i)=>{"use strict";i.r(t),i.d(t,{proceduralVertexShaderWGSL:()=>n});const r="proceduralVertexShader",s="attribute position: vec2f;varying vPosition: vec2f;varying vUV: vec2f;const madd: vec2f= vec2f(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.vPosition=input.position;vertexOutputs.vUV=input.position*madd+madd;vertexOutputs.position= vec4f(input.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},79388:(e,t,i)=>{"use strict";i.r(t),i.d(t,{rgbdDecodePixelShaderWGSL:()=>o});var r=i(69841);i(87647);const s="rgbdDecodePixelShader",n="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=vec4f(fromRGBD(textureSample(textureSampler,textureSamplerSampler,input.vUV)),1.0);}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},41572:(e,t,i)=>{"use strict";i.r(t),i.d(t,{rgbdEncodePixelShaderWGSL:()=>o});var r=i(69841);i(87647);const s="rgbdEncodePixelShader",n="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=toRGBD(textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb);}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},91944:(e,t,i)=>{"use strict";i.r(t),i.d(t,{rsmFullGlobalIlluminationPixelShaderWGSL:()=>n});const r="rsmFullGlobalIlluminationPixelShader",s="/**\n* The implementation is a direct application of the formula found in http:\n*/\nvarying vUV: vec2f;uniform rsmLightMatrix: mat4x4f;uniform rsmInfo: vec4f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var normalSamplerSampler: sampler;var normalSampler: texture_2d;var rsmPositionW: texture_2d;var rsmNormalW: texture_2d;var rsmFlux: texture_2d;\n#ifdef TRANSFORM_NORMAL\nuniform invView: mat4x4f;\n#endif\nfn computeIndirect(p: vec3f,n: vec3f)->vec3f {var indirectDiffuse: vec3f= vec3f(0.);var intensity: f32=uniforms.rsmInfo.z;var edgeArtifactCorrection: f32=uniforms.rsmInfo.w;var texRSM: vec4f=uniforms.rsmLightMatrix* vec4f(p,1.);texRSM=vec4f(texRSM.xy/texRSM.w,texRSM.z,texRSM.w);texRSM=vec4f(texRSM.xy*0.5+0.5,texRSM.z,texRSM.w);var width: i32= i32(uniforms.rsmInfo.x);var height: i32= i32(uniforms.rsmInfo.y);for (var j: i32=0; j(i,j);var vplPositionW: vec3f=textureLoad(rsmPositionW,uv,0).xyz;var vplNormalW: vec3f=textureLoad(rsmNormalW,uv,0).xyz*2.0-1.0;var vplFlux: vec3f=textureLoad(rsmFlux,uv,0).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; \nvar dist2: f32=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}}\nreturn clamp(indirectDiffuse*intensity,vec3f(0.0),vec3f(1.0));}\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var positionW: vec3f=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.vUV).xyz;var normalW: vec3f=textureSample(normalSampler,normalSamplerSampler,fragmentInputs.vUV).xyz;\n#ifdef DECODE_NORMAL\nnormalW=normalW*2.0-1.0;\n#endif\n#ifdef TRANSFORM_NORMAL\nnormalW=(uniforms.invView* vec4f(normalW,0.)).xyz;\n#endif\nfragmentOutputs.color=vec4f(computeIndirect(positionW,normalW),1.0);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},31583:(e,t,i)=>{"use strict";i.r(t),i.d(t,{rsmGlobalIlluminationPixelShaderWGSL:()=>n});const r="rsmGlobalIlluminationPixelShader",s="/**\n* The implementation is an application of the formula found in http:\n* 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).\n*/\nvarying vUV: vec2f;uniform rsmLightMatrix: mat4x4f;uniform rsmInfo: vec4f;uniform rsmInfo2: vec4f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var normalSamplerSampler: sampler;var normalSampler: texture_2d;var rsmPositionWSampler: sampler;var rsmPositionW: texture_2d;var rsmNormalWSampler: sampler;var rsmNormalW: texture_2d;var rsmFluxSampler: sampler;var rsmFlux: texture_2d;var rsmSamples: texture_2d;\n#ifdef TRANSFORM_NORMAL\nuniform invView: mat4x4f;\n#endif\nfn mod289(x: f32)->f32{return x-floor(x*(1.0/289.0))*289.0;}\nfn mod289Vec4(x: vec4f)->vec4f {return x-floor(x*(1.0/289.0))* 289.0;}\nfn perm(x: vec4f)->vec4f {return mod289Vec4(((x*34.0)+1.0)*x) ;}\nfn noise(p: vec3f)->f32{var a: vec3f=floor(p);var d: vec3f=p-a;d=d*d*(3.0-2.0*d);var b: vec4f=a.xxyy+ vec4f(0.0,1.0,0.0,1.0);var k1: vec4f=perm(b.xyxy);var k2: vec4f=perm(k1.xyxy+b.zzww);var c: vec4f=k2+a.zzzz;var k3: vec4f=perm(c);var k4: vec4f=perm(c+1.0);var o1: vec4f=fract(k3*(1.0/41.0));var o2: vec4f=fract(k4*(1.0/41.0));var o3: vec4f=o2*d.z+o1*(1.0-d.z);var o4: vec2f=o3.yw*d.x+o3.xz*(1.0-d.x);return o4.y*d.y+o4.x*(1.0-d.y);}\nfn computeIndirect(p: vec3f,n: vec3f)->vec3f {var indirectDiffuse: vec3f= vec3f(0.);var numSamples: i32= i32(uniforms.rsmInfo.x);var radius: f32=uniforms.rsmInfo.y;var intensity: f32=uniforms.rsmInfo.z;var edgeArtifactCorrection: f32=uniforms.rsmInfo.w;var texRSM: vec4f=uniforms.rsmLightMatrix* vec4f(p,1.);texRSM=vec4f(texRSM.xy/texRSM.w,texRSM.z,texRSM.w);texRSM=vec4f(texRSM.xy*0.5+0.5,texRSM.z,texRSM.w);var angle: f32=noise(p*uniforms.rsmInfo2.x);var c: f32=cos(angle);var s: f32=sin(angle);for (var i: i32=0; i(i,0),0).xyz;var weightSquare: f32=rsmSample.z;if (uniforms.rsmInfo2.y==1.0){rsmSample=vec3f(rsmSample.x*c+rsmSample.y*s,-rsmSample.x*s+rsmSample.y*c,rsmSample.z);}\nvar uv: vec2f=texRSM.xy+rsmSample.xy*radius;if (uv.x<0. || uv.x>1. || uv.y<0. || uv.y>1.) {continue;}\nvar vplPositionW: vec3f=textureSampleLevel(rsmPositionW,rsmPositionWSampler,uv,0.).xyz;var vplNormalW: vec3f=textureSampleLevel(rsmNormalW,rsmNormalWSampler,uv,0.).xyz*2.0-1.0;var vplFlux: vec3f=textureSampleLevel(rsmFlux,rsmFluxSampler,uv,0.).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; \nvar dist2: f32=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*weightSquare*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}\nreturn clamp(indirectDiffuse*intensity,vec3f(0.0),vec3f(1.0));}\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var positionW: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).xyz;var normalW: vec3f=textureSample(normalSampler,normalSamplerSampler,input.vUV).xyz;\n#ifdef DECODE_NORMAL\nnormalW=normalW*2.0-1.0;\n#endif\n#ifdef TRANSFORM_NORMAL\nnormalW=(uniforms.invView* vec4f(normalW,0.)).xyz;\n#endif\nfragmentOutputs.color=vec4f(computeIndirect(positionW,normalW),1.0);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},98e3:(e,t,i)=>{"use strict";i.r(t),i.d(t,{screenSpaceReflection2PixelShaderWGSL:()=>o});var r=i(69841);i(87647),i(20427),i(46357);const s="screenSpaceReflection2PixelShader",n="var textureSamplerSampler: sampler;var textureSampler: texture_2d;varying vUV: vec2f;\n#ifdef SSR_SUPPORTED\nvar reflectivitySamplerSampler: sampler;var reflectivitySampler: texture_2d;var normalSampler: texture_2d;var depthSampler: texture_2d;\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nvar backDepthSampler: texture_2d;uniform backSizeFactor: f32;\n#endif\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nvar envCubeSamplerSampler: sampler;var envCubeSampler: texture_cube;\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nuniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f;\n#endif\n#endif\nuniform view: mat4x4f;uniform invView: mat4x4f;uniform projection: mat4x4f;uniform invProjectionMatrix: mat4x4f;uniform projectionPixel: mat4x4f;uniform nearPlaneZ: f32;uniform farPlaneZ: f32;uniform stepSize: f32;uniform maxSteps: f32;uniform strength: f32;uniform thickness: f32;uniform roughnessFactor: f32;uniform reflectionSpecularFalloffExponent: f32;uniform maxDistance: f32;uniform selfCollisionNumSkip: f32;uniform reflectivityThreshold: f32;\n#include\n#include\n#include\nfn hash(a: vec3f)->vec3f\n{var result=fract(a*0.8);result+=dot(result,result.yxz+19.19);return fract((result.xxy+result.yxx)*result.zyx);}\nfn computeAttenuationForIntersection(ihitPixel: vec2f,hitUV: vec2f,vsRayOrigin: vec3f,vsHitPoint: vec3f,reflectionVector: vec3f,maxRayDistance: f32,numIterations: f32)->f32 {var attenuation: f32=1.0;\n#ifdef SSR_ATTENUATE_SCREEN_BORDERS\nvar dCoords: vec2f=smoothstep(vec2f(0.2),vec2f(0.6),abs( vec2f(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS\nattenuation*=1.0-(numIterations/uniforms.maxSteps);\n#endif\n#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION\nvar reflectionNormal: vec3f=texelFetch(normalSampler,hitPixel,0).xyz;var directionBasedAttenuation: f32=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation;\n#endif\nreturn attenuation;}\n#endif\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#ifdef SSR_SUPPORTED\nvar colorFull: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var color: vec3f=colorFull.rgb;var reflectivity: vec4f=textureSampleLevel(reflectivitySampler,reflectivitySamplerSampler,input.vUV,0.0);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=uniforms.reflectivityThreshold) {\n#ifdef SSR_USE_BLUR\nfragmentOutputs.color= vec4f(0.);\n#else\nfragmentOutputs.color=colorFull;\n#endif\nreturn fragmentOutputs;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpaceVec3(color);\n#endif\nvar texSize: vec2f= vec2f(textureDimensions(depthSampler,0));var csNormal: vec3f=textureLoad(normalSampler,vec2(input.vUV*texSize),0).xyz; \n#ifdef SSR_DECODE_NORMAL\ncsNormal=csNormal*2.0-1.0;\n#endif\n#ifdef SSR_NORMAL_IS_IN_WORLDSPACE\ncsNormal=(uniforms.view* vec4f(csNormal,0.0)).xyz;\n#endif\nvar depth: f32=textureLoad(depthSampler,vec2(input.vUV*texSize),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\ndepth=linearizeDepth(depth,uniforms.nearPlaneZ,uniforms.farPlaneZ);\n#endif\nvar csPosition: vec3f=computeViewPosFromUVDepth(input.vUV,depth,uniforms.projection,uniforms.invProjectionMatrix);\n#ifdef ORTHOGRAPHIC_CAMERA\nvar csViewDirection: vec3f= vec3f(0.,0.,1.);\n#else\nvar csViewDirection: vec3f=normalize(csPosition);\n#endif\nvar csReflectedVector: vec3f=reflect(csViewDirection,csNormal);\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nvar wReflectedVector: vec3f=(uniforms.invView* vec4f(csReflectedVector,0.0)).xyz;\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nvar worldPos: vec4f=uniforms.invView* vec4f(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),uniforms.vReflectionSize,uniforms.vReflectionPosition);\n#endif\n#ifdef SSR_INVERTCUBICMAP\nwReflectedVector.y*=-1.0;\n#endif\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nwReflectedVector.z*=-1.0;\n#endif\nvar envColor: vec3f=textureSampleLevel(envCubeSampler,envCubeSamplerSampler,wReflectedVector,0.0).xyz;\n#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE\nenvColor=toLinearSpaceVec3(envColor);\n#endif\n#else\nvar envColor: vec3f=color;\n#endif\nvar reflectionAttenuation: f32=1.0;var rayHasHit: bool=false;var startPixel: vec2f;var hitPixel: vec2f;var hitPoint: vec3f;var numIterations: f32;\n#ifdef SSRAYTRACE_DEBUG\nvar debugColor: vec3f;\n#endif\n#ifdef SSR_ATTENUATE_FACING_CAMERA\nreflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector));\n#endif\nif (reflectionAttenuation>0.0) {\n#ifdef SSR_USE_BLUR\nvar jitt: vec3f= vec3f(0.);\n#else\nvar roughness: f32=1.0-reflectivity.a;var jitt: vec3f=mix( vec3f(0.0),hash(csPosition)- vec3f(0.5),roughness)*uniforms.roughnessFactor; \n#endif\nvar uv2: vec2f=input.vUV*texSize;var c: f32=(uv2.x+uv2.y)*0.25;var jitter: f32=((c)%(1.0)); \nrayHasHit=traceScreenSpaceRay1(\ncsPosition,\nnormalize(csReflectedVector+jitt),\nuniforms.projectionPixel,\ndepthSampler,\ntexSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nbackDepthSampler,\nuniforms.backSizeFactor,\n#endif\nuniforms.thickness,\nuniforms.nearPlaneZ,\nuniforms.farPlaneZ,\nuniforms.stepSize,\njitter,\nuniforms.maxSteps,\nuniforms.maxDistance,\nuniforms.selfCollisionNumSkip,\n&startPixel,\n&hitPixel,\n&hitPoint,\n&numIterations\n#ifdef SSRAYTRACE_DEBUG\n,&debugColor\n#endif\n);}\n#ifdef SSRAYTRACE_DEBUG\nfragmentOutputs.color= vec4f(debugColor,1.);return fragmentOutputs;\n#endif\nvar F0: vec3f=reflectivity.rgb;var fresnel: vec3f=fresnelSchlickGGXVec3(max(dot(csNormal,-csViewDirection),0.0),F0, vec3f(1.));var SSR: vec3f=envColor;if (rayHasHit) {var reflectedColor: vec3f=textureLoad(textureSampler,vec2(hitPixel),0).rgb;\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\nreflectedColor=toLinearSpaceVec3(reflectedColor);\n#endif\nreflectionAttenuation*=computeAttenuationForIntersection(hitPixel,hitPixel/texSize,csPosition,hitPoint,csReflectedVector,uniforms.maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;}\n#ifndef SSR_BLEND_WITH_FRESNEL\nSSR*=fresnel;\n#endif\n#ifdef SSR_USE_BLUR\nvar blur_radius: f32=0.0;var roughness: f32=1.0-reflectivity.a*(1.0-uniforms.roughnessFactor);if (roughness>0.001) {var cone_angle: f32=min(roughness,0.999)*3.14159265*0.5;var cone_len: f32=distance(startPixel,hitPixel);var op_len: f32=2.0*tan(cone_angle)*cone_len; \nvar a: f32=op_len;var h: f32=cone_len;var a2: f32=a*a;var fh2: f32=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);}\nfragmentOutputs.color= vec4f(SSR,blur_radius/255.0); \n#else\n#ifdef SSR_BLEND_WITH_FRESNEL\nvar reflectionMultiplier: vec3f=clamp(pow(fresnel*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0));\n#else\nvar reflectionMultiplier: vec3f=clamp(pow(reflectivity.rgb*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0));\n#endif\nvar colorMultiplier: vec3f=1.0-reflectionMultiplier;var finalColor: vec3f=(color*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpaceVec3(finalColor);\n#endif\nfragmentOutputs.color= vec4f(finalColor,colorFull.a);\n#endif\n#else\nfragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);\n#endif\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},86763:(e,t,i)=>{"use strict";i.r(t),i.d(t,{screenSpaceReflection2BlurPixelShaderWGSL:()=>n});const r="screenSpaceReflection2BlurPixelShader",s="var textureSamplerSampler: sampler;var textureSampler: texture_2d;varying vUV: vec2f;uniform texelOffsetScale: vec2f;const weights: array=array(0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);fn processSample(uv: vec2f,i: f32,stepSize: vec2f,accumulator: ptr,denominator: ptr)\n{var offsetUV: vec2f=stepSize*i+uv;var coefficient: f32=weights[ i32(2.0-abs(i))];*accumulator+=textureSampleLevel(textureSampler,textureSamplerSampler,offsetUV,0.0)*coefficient;*denominator+=coefficient;}\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var colorFull: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);if (dot(colorFull, vec4f(1.0))==0.0) {fragmentOutputs.color=colorFull;return fragmentOutputs;}\nvar blurRadius: f32=colorFull.a*255.0; \nvar stepSize: vec2f=uniforms.texelOffsetScale.xy*blurRadius;var accumulator: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0)*0.214607;var denominator: f32=0.214607;processSample(input.vUV,1.0,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.2,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.4,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.6,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.8,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.2,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.4,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.6,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.8,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*2.0,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.2,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.4,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.6,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.8,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.2,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.4,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.6,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.8,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*2.0,stepSize,&accumulator,&denominator);fragmentOutputs.color= vec4f(accumulator.rgb/denominator,colorFull.a);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},20136:(e,t,i)=>{"use strict";i.r(t),i.d(t,{screenSpaceReflection2BlurCombinerPixelShaderWGSL:()=>o});var r=i(69841);i(87647),i(20427),i(46357);const s="screenSpaceReflection2BlurCombinerPixelShader",n="var textureSamplerSampler: sampler;var textureSampler: texture_2d; \nvar mainSamplerSampler: sampler;var mainSampler: texture_2d;var reflectivitySamplerSampler: sampler;var reflectivitySampler: texture_2d;uniform strength: f32;uniform reflectionSpecularFalloffExponent: f32;uniform reflectivityThreshold: f32;varying vUV: vec2f;\n#include\n#ifdef SSR_BLEND_WITH_FRESNEL\n#include\n#include\nuniform projection: mat4x4f;uniform invProjectionMatrix: mat4x4f;var normalSampler: texture_2d;var depthSampler: texture_2d;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nuniform nearPlaneZ: f32;uniform farPlaneZ: f32;\n#endif\n#endif\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#ifdef SSRAYTRACE_DEBUG\nfragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);\n#else\nvar SSR: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var color: vec4f=textureSample(mainSampler,textureSamplerSampler,input.vUV);var reflectivity: vec4f=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vUV);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=uniforms.reflectivityThreshold) {fragmentOutputs.color=color;return fragmentOutputs;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpaceVec4(color);\n#endif\n#ifdef SSR_BLEND_WITH_FRESNEL\nvar texSize: vec2f= vec2f(textureDimensions(depthSampler,0));var csNormal: vec3f=textureLoad(normalSampler,vec2(input.vUV*texSize),0).xyz;var depth: f32=textureLoad(depthSampler,vec2(input.vUV*texSize),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\ndepth=linearizeDepth(depth,uniforms.nearPlaneZ,uniforms.farPlaneZ);\n#endif\nvar csPosition: vec3f=computeViewPosFromUVDepth(input.vUV,depth,uniforms.projection,uniforms.invProjectionMatrix);var csViewDirection: vec3f=normalize(csPosition);var F0: vec3f=reflectivity.rgb;var fresnel: vec3f=fresnelSchlickGGXVec3(max(dot(csNormal,-csViewDirection),0.0),F0, vec3f(1.));var reflectionMultiplier: vec3f=clamp(pow(fresnel*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0));\n#else\nvar reflectionMultiplier: vec3f=clamp(pow(reflectivity.rgb*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0));\n#endif\nvar colorMultiplier: vec3f=1.0-reflectionMultiplier;var finalColor: vec3f=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpaceVec3(finalColor);\n#endif\nfragmentOutputs.color= vec4f(finalColor,color.a);\n#endif\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},89778:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowMapPixelShaderWGSL:()=>o});var r=i(69841);i(2456);r.l.IncludesShadersStoreWGSL.bayerDitherFunctions="fn bayerDither2(_P: vec2f)->f32 {return ((2.0*_P.y+_P.x+1.0)%(4.0));}\nfn bayerDither4(_P: vec2f)->f32 {var P1: vec2f=((_P)%(2.0)); \nvar P2: vec2f=floor(0.5*((_P)%(4.0))); \nreturn 4.0*bayerDither2(P1)+bayerDither2(P2);}\nfn bayerDither8(_P: vec2f)->f32 {var P1: vec2f=((_P)%(2.0)); \nvar P2: vec2f=floor(0.5 *((_P)%(4.0))); \nvar P4: vec2f=floor(0.25*((_P)%(8.0))); \nreturn 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);}\n";r.l.IncludesShadersStoreWGSL.shadowMapFragmentExtraDeclaration="#if SM_FLOAT==0\n#include\n#endif\n#if SM_SOFTTRANSPARENTSHADOW==1\n#include\nuniform softTransparentShadowSM: vec2f;\n#endif\nvarying vDepthMetricSM: f32;\n#if SM_USEDISTANCE==1\nuniform lightDataSM: vec3f;varying vPositionWSM: vec3f;\n#endif\nuniform biasAndScaleSM: vec3f;uniform depthValuesSM: vec2f;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying zSM: f32;\n#endif\n",i(96140),i(76794),i(43140);const s="shadowMapPixelShader",n="#include\n#ifdef ALPHATEXTURE\nvarying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#include\n#ifdef ALPHATEXTURE\nvar opacityMap: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vUV);var alphaFromAlphaTexture: f32=opacityMap.a;\n#if SM_SOFTTRANSPARENTSHADOW==1\nif (uniforms.softTransparentShadowSM.y==1.0) {opacityMap=vec4f(opacityMap.rgb* vec3f(0.3,0.59,0.11),opacityMap.a);alphaFromAlphaTexture=opacityMap.x+opacityMap.y+opacityMap.z;}\n#endif\n#ifdef ALPHATESTVALUE\nif (alphaFromAlphaTexture=uniforms.softTransparentShadowSM.x*alphaFromAlphaTexture) {discard;}\n#else\nif ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.softTransparentShadowSM.x) {discard;} \n#endif\n#endif\n#include\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},90396:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowMapVertexShaderWGSL:()=>o});var r=i(69841);i(25589),i(68273),i(47381),i(51148),i(87647),i(14910),i(10598);r.l.IncludesShadersStoreWGSL.shadowMapVertexExtraDeclaration="#if SM_NORMALBIAS==1\nuniform lightDataSM: vec3f;\n#endif\nuniform biasAndScaleSM: vec3f;uniform depthValuesSM: vec2f;varying vDepthMetricSM: f32;\n#if SM_USEDISTANCE==1\nvarying vPositionWSM: vec3f;\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying zSM: f32;\n#endif\n",i(30486),i(8573),i(43610),i(32764),i(40903),i(71281);r.l.IncludesShadersStoreWGSL.shadowMapVertexNormalBias="#if SM_NORMALBIAS==1\n#if SM_DIRECTIONINLIGHTDATA==1\nvar worldLightDirSM: vec3f=normalize(-uniforms.lightDataSM.xyz);\n#else\nvar directionToLightSM: vec3f=uniforms.lightDataSM.xyz-worldPos.xyz;var worldLightDirSM: vec3f=normalize(directionToLightSM);\n#endif\nvar ndlSM: f32=dot(vNormalW,worldLightDirSM);var sinNLSM: f32=sqrt(1.0-ndlSM*ndlSM);var normalBiasSM: f32=uniforms.biasAndScaleSM.y*sinNLSM;worldPos=vec4f(worldPos.xyz-vNormalW*normalBiasSM,worldPos.w);\n#endif\n",i(18902),i(57728);const s="shadowMapVertexShader",n="attribute position: vec3f;\n#ifdef NORMAL\nattribute normal: vec3f;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef INSTANCES\nattribute world0: vec4f;attribute world1: vec4f;attribute world2: vec4f;attribute world3: vec4f;\n#endif\n#include\n#include\n#include\n#ifdef ALPHATEXTURE\nvarying vUV: vec2f;uniform diffuseMatrix: mat4x4f;\n#ifdef UV1\nattribute uv: vec2f;\n#endif\n#ifdef UV2\nattribute uv2: vec2f;\n#endif\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;\n#ifdef UV1\nvar uvUpdated: vec2f=input.uv;\n#endif\n#ifdef NORMAL\nvar normalUpdated: vec3f=input.normal;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvar worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);\n#ifdef NORMAL\nvar normWorldSM: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvar vNormalW: vec3f=normalUpdated/ vec3f(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvar vNormalW: vec3f=normalize(normWorldSM*normalUpdated);\n#endif\n#endif\n#include\nvertexOutputs.position=scene.viewProjection*worldPos;\n#include\n#ifdef ALPHATEXTURE\n#ifdef UV1\nvertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy;\n#endif\n#ifdef UV2\nvertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(input.uv2,1.0,0.0)).xy;\n#endif\n#endif\n#include\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},68820:(e,t,i)=>{"use strict";i.r(t),i.d(t,{sharpenPixelShaderWGSL:()=>n});const r="sharpenPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f;uniform sharpnessAmounts: vec2f;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var onePixel: vec2f= vec2f(1.0,1.0)/uniforms.screenSize;var color: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);var edgeDetection: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(0,-1)) +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(-1,0)) +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(1,0)) +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(0,1)) -\ncolor*4.0;fragmentOutputs.color=max(vec4f(color.rgb*uniforms.sharpnessAmounts.y,color.a)-(uniforms.sharpnessAmounts.x* vec4f(edgeDetection.rgb,0)),vec4f(0.));}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},25151:(e,t,i)=>{"use strict";i.r(t),i.d(t,{spritesPixelShaderWGSL:()=>o});var r=i(69841);i(10668),i(21859),i(85551),i(31034);r.l.IncludesShadersStoreWGSL.imageProcessingCompatibility="#ifdef IMAGEPROCESSINGPOSTPROCESS\nfragmentOutputs.color=vec4f(pow(fragmentOutputs.color.rgb, vec3f(2.2)),fragmentOutputs.color.a);\n#endif\n";const s="spritesPixelShader",n="uniform alphaTest: i32;varying vColor: vec4f;varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d;\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#ifdef PIXEL_PERFECT\nfn uvPixelPerfect(uv: vec2f)->vec2f {var res: vec2f= vec2f(textureDimensions(diffuseSampler,0));var uvTemp=uv*res;var seam: vec2f=floor(uvTemp+0.5);uvTemp=seam+clamp((uvTemp-seam)/fwidth(uvTemp),vec2f(-0.5),vec2f(0.5));return uvTemp/res;}\n#endif\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#ifdef PIXEL_PERFECT\nvar uv: vec2f=uvPixelPerfect(input.vUV);\n#else\nvar uv: vec2f=input.vUV;\n#endif\nvar color: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,uv);var fAlphaTest: f32= f32(uniforms.alphaTest);if (fAlphaTest != 0.)\n{if (color.a<0.95) {discard;}}\ncolor*=input.vColor;\n#include\n#include\nfragmentOutputs.color=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},56029:(e,t,i)=>{"use strict";i.r(t),i.d(t,{spritesVertexShaderWGSL:()=>o});var r=i(69841);i(86934),i(21859),i(18201);const s="spritesVertexShader",n="attribute position: vec4f;attribute options: vec2f;attribute offsets: vec2f;attribute inverts: vec2f;attribute cellInfo: vec4f;attribute color: vec4f;uniform view: mat4x4f;uniform projection: mat4x4f;varying vUV: vec2f;varying vColor: vec4f;\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvar viewPos: vec3f=(uniforms.view* vec4f(input.position.xyz,1.0)).xyz; \nvar cornerPos: vec2f;var angle: f32=input.position.w;var size: vec2f= vec2f(input.options.x,input.options.y);var offset: vec2f=input.offsets.xy;cornerPos= vec2f(offset.x-0.5,offset.y -0.5)*size;var rotatedCorner: vec3f;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;vertexOutputs.position=uniforms.projection*vec4f(viewPos,1.0); \nvertexOutputs.vColor=input.color;var uvOffset: vec2f= vec2f(abs(offset.x-input.inverts.x),abs(1.0-offset.y-input.inverts.y));var uvPlace: vec2f=input.cellInfo.xy;var uvSize: vec2f=input.cellInfo.zw;vertexOutputs.vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vertexOutputs.vUV.y=uvPlace.y+uvSize.y*uvOffset.y;\n#ifdef FOG\nvertexOutputs.vFogDistance=viewPos;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},20661:(e,t,i)=>{"use strict";i.r(t),i.d(t,{ssao2PixelShaderWGSL:()=>n});const r="ssao2PixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;\n#ifdef SSAO\nconst scales: array=array(\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);uniform near: f32;uniform radius: f32;var depthSamplerSampler: sampler;var depthSampler: texture_2d;var randomSamplerSampler: sampler;var randomSampler: texture_2d;var normalSamplerSampler: sampler;var normalSampler: texture_2d;uniform randTextureTiles: f32;uniform samplesFactor: f32;uniform sampleSphere: array;uniform totalStrength: f32;uniform base: f32;uniform xViewport: f32;uniform yViewport: f32;uniform depthProjection: mat3x3f;uniform maxZ: f32;uniform minZAspect: f32;uniform texelSize: vec2f;uniform projection: mat4x4f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var random: vec3f=textureSampleLevel(randomSampler,randomSamplerSampler,input.vUV*uniforms.randTextureTiles,0.0).rgb;var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.0).r;var depthSign: f32=sign(depth);depth=depth*depthSign;var normal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV,0.0).rgb;var occlusion: f32=0.0;var correctedRadius: f32=min(uniforms.radius,uniforms.minZAspect*depth/uniforms.near);var vViewRay: vec3f= vec3f((input.vUV.x*2.0-1.0)*uniforms.xViewport,(input.vUV.y*2.0-1.0)*uniforms.yViewport,depthSign);var vDepthFactor: vec3f=uniforms.depthProjection* vec3f(1.0,1.0,depth);var origin: vec3f=vViewRay*vDepthFactor;var rvec: vec3f=random*2.0-1.0;rvec.z=0.0;var dotProduct: f32=dot(rvec,normal);rvec=select( vec3f(-rvec.y,0.0,rvec.x),rvec,1.0-abs(dotProduct)>1e-2);var tangent: vec3f=normalize(rvec-normal*dot(rvec,normal));var bitangent: vec3f=cross(normal,tangent);var tbn: mat3x3f= mat3x3f(tangent,bitangent,normal);var difference: f32;for (var i: i32=0; i1.0 || offset.y>1.0) {continue;}\nvar sampleDepth: f32=abs(textureSampleLevel(depthSampler,depthSamplerSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;var rangeCheck: f32=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;}\nocclusion=occlusion*(1.0-smoothstep(uniforms.maxZ*0.75,uniforms.maxZ,depth));var ao: f32=1.0-uniforms.totalStrength*occlusion*uniforms.samplesFactor;var result: f32=clamp(ao+uniforms.base,0.0,1.0);fragmentOutputs.color= vec4f( vec3f(result),1.0);}\n#else\n#ifdef BLUR\nuniform outSize: f32;uniform soften: f32;uniform tolerance: f32;uniform samples: i32;\n#ifndef BLUR_BYPASS\nvar depthSamplerSampler: sampler;var depthSampler: texture_2d;\n#ifdef BLUR_LEGACY\nfn blur13Bilateral(image: texture_2d,imageSampler: sampler,uv: vec2f,step: vec2f)->f32 {var result: f32=0.0;var off1: vec2f= vec2f(1.411764705882353)*step;var off2: vec2f= vec2f(3.2941176470588234)*step;var off3: vec2f= vec2f(5.176470588235294)*step;var compareDepth: f32=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv,0.0).r);var sampleDepth: f32;var weight: f32;var weightSum: f32=30.0;result+=textureSampleLevel(image,imageSampler,uv,0.0).r*30.0;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureSampleLevel(image,imageSampler,uv+off1,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureSampleLevel(image,imageSampler,uv-off1,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv+off2,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv-off2,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv+off3,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv-off3,0.0).r*weight;return result/weightSum;}\n#endif\n#endif\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var result: f32=0.0;\n#ifdef BLUR_BYPASS\nresult=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0).r;\n#else\n#ifdef BLUR_H\nvar step: vec2f= vec2f(1.0/uniforms.outSize,0.0);\n#else\nvar step: vec2f= vec2f(0.0,1.0/uniforms.outSize);\n#endif\n#ifdef BLUR_LEGACY\nresult=blur13Bilateral(textureSampler,textureSamplerSampler,input.vUV,step);\n#else\nvar compareDepth: f32=abs(textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.0).r);var weightSum: f32=0.0;for (var i: i32=-uniforms.samples; i{"use strict";i.r(t),i.d(t,{ssaoCombinePixelShaderWGSL:()=>n});const r="ssaoCombinePixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var originalColorSampler: sampler;var originalColor: texture_2d;uniform viewport: vec4f;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvar ssaoColor: vec4f=textureSample(textureSampler,textureSamplerSampler,uniforms.viewport.xy+input.vUV*uniforms.viewport.zw);var sceneColor: vec4f=textureSample(originalColor,originalColorSampler,input.vUV);fragmentOutputs.color=sceneColor*ssaoColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},88559:(e,t,i)=>{"use strict";i.r(t),i.d(t,{taaPixelShaderWGSL:()=>n});const r="taaPixelShader",s="var textureSampler: texture_2d;var historySampler: texture_2d;uniform factor: f32;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {let c=textureLoad(textureSampler,vec2(fragmentInputs.position.xy),0);let h=textureLoad(historySampler,vec2(fragmentInputs.position.xy),0);fragmentOutputs.color= mix(h,c,uniforms.factor);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},41739:(e,t,i)=>{"use strict";i.r(t),i.d(t,{tonemapPixelShaderWGSL:()=>n});const r="tonemapPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform _ExposureAdjustment: f32;\n#if defined(HABLE_TONEMAPPING)\nconst A: f32=0.15;const B: f32=0.50;const C: f32=0.10;const D: f32=0.20;const E: f32=0.02;const F: f32=0.30;const W: f32=11.2;\n#endif\nfn Luminance(c: vec3f)->f32\n{return dot(c, vec3f(0.22,0.707,0.071));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var colour: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nvar lum: f32=Luminance(colour.rgb); \nvar lumTm: f32=lum*uniforms._ExposureAdjustment;var scale: f32=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=uniforms._ExposureAdjustment;const ExposureBias: f32=2.0;var x: vec3f=ExposureBias*colour;var curr: vec3f=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x= vec3f(W,W,W);var whiteScale: vec3f=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=uniforms._ExposureAdjustment;var X: vec3f=max( vec3f(0.0,0.0,0.0),colour-0.004);var retColor: vec3f=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour= vec3f(1.0,1.0,1.0)-exp2(-uniforms._ExposureAdjustment*colour);\n#endif\nfragmentOutputs.color= vec4f(colour.rgb,1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},79132:(e,t,i)=>{"use strict";i.r(t),i.d(t,{vrDistortionCorrectionPixelShaderWGSL:()=>n});const r="vrDistortionCorrectionPixelShader",s="#define DISABLE_UNIFORMITY_ANALYSIS\nvarying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform LensCenter: vec2f;uniform Scale: vec2f;uniform ScaleIn: vec2f;uniform HmdWarpParam: vec4f;fn HmdWarp(in01: vec2f)->vec2f {var theta: vec2f=(in01-uniforms.LensCenter)*uniforms.ScaleIn; \nvar rSq: f32=theta.x*theta.x+theta.y*theta.y;var rvector: vec2f=theta*(uniforms.HmdWarpParam.x+uniforms.HmdWarpParam.y*rSq+uniforms.HmdWarpParam.z*rSq*rSq+uniforms.HmdWarpParam.w*rSq*rSq*rSq);return uniforms.LensCenter+uniforms.Scale*rvector;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var tc: vec2f=HmdWarp(input.vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0) {fragmentOutputs.color=vec4f(0.0,0.0,0.0,0.0);}\nelse{fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,tc);}}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},94895:(e,t,i)=>{"use strict";i.d(t,{i:()=>r});class r{constructor(){this._blendFunctionParameters=new Array(4),this._blendEquationParameters=new Array(2),this._blendConstants=new Array(4),this._isBlendConstantsDirty=!1,this._alphaBlend=!1,this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this.reset()}get isDirty(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty||this._isBlendEquationParametersDirty}get alphaBlend(){return this._alphaBlend}set alphaBlend(e){this._alphaBlend!==e&&(this._alphaBlend=e,this._isAlphaBlendDirty=!0)}setAlphaBlendConstants(e,t,i,r){this._blendConstants[0]===e&&this._blendConstants[1]===t&&this._blendConstants[2]===i&&this._blendConstants[3]===r||(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=i,this._blendConstants[3]=r,this._isBlendConstantsDirty=!0)}setAlphaBlendFunctionParameters(e,t,i,r){this._blendFunctionParameters[0]===e&&this._blendFunctionParameters[1]===t&&this._blendFunctionParameters[2]===i&&this._blendFunctionParameters[3]===r||(this._blendFunctionParameters[0]=e,this._blendFunctionParameters[1]=t,this._blendFunctionParameters[2]=i,this._blendFunctionParameters[3]=r,this._isBlendFunctionParametersDirty=!0)}setAlphaEquationParameters(e,t){this._blendEquationParameters[0]===e&&this._blendEquationParameters[1]===t||(this._blendEquationParameters[0]=e,this._blendEquationParameters[1]=t,this._isBlendEquationParametersDirty=!0)}reset(){this._alphaBlend=!1,this._blendFunctionParameters[0]=null,this._blendFunctionParameters[1]=null,this._blendFunctionParameters[2]=null,this._blendFunctionParameters[3]=null,this._blendEquationParameters[0]=null,this._blendEquationParameters[1]=null,this._blendConstants[0]=null,this._blendConstants[1]=null,this._blendConstants[2]=null,this._blendConstants[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1}apply(e){this.isDirty&&(this._isAlphaBlendDirty&&(this._alphaBlend?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),this._isBlendEquationParametersDirty&&(e.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1),this._isBlendConstantsDirty&&(e.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1))}}},14506:(e,t,i)=>{"use strict";i.d(t,{N:()=>r});class r{constructor(e=!0){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,e&&this.reset()}get isDirty(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0)}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0)}reset(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._zOffsetUnits=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!0,this._isFrontFaceDirty=!1}apply(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset||this.zOffsetUnits?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,this.zOffsetUnits)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(e.frontFace(this.frontFace),this._isFrontFaceDirty=!1))}}},69905:(e,t,i)=>{"use strict";i.d(t,{K:()=>r});class r{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=r.ALWAYS,this.funcRef=1,this.funcMask=255,this.opStencilFail=r.KEEP,this.opDepthFail=r.KEEP,this.opStencilDepthPass=r.REPLACE}get stencilFunc(){return this.func}set stencilFunc(e){this.func=e}get stencilFuncRef(){return this.funcRef}set stencilFuncRef(e){this.funcRef=e}get stencilFuncMask(){return this.funcMask}set stencilFuncMask(e){this.funcMask=e}get stencilOpStencilFail(){return this.opStencilFail}set stencilOpStencilFail(e){this.opStencilFail=e}get stencilOpDepthFail(){return this.opDepthFail}set stencilOpDepthFail(e){this.opDepthFail=e}get stencilOpStencilDepthPass(){return this.opStencilDepthPass}set stencilOpStencilDepthPass(e){this.opStencilDepthPass=e}get stencilMask(){return this.mask}set stencilMask(e){this.mask=e}get stencilTest(){return this.enabled}set stencilTest(e){this.enabled=e}}r.ALWAYS=519,r.KEEP=7680,r.REPLACE=7681},67715:(e,t,i)=>{"use strict";i.d(t,{u:()=>r});class r{get isDirty(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._isStencilFuncDirty=!0)}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef!==e&&(this._funcRef=e,this._isStencilFuncDirty=!0)}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._isStencilFuncDirty=!0)}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._isStencilOpDirty=!0)}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._isStencilOpDirty=!0)}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._isStencilOpDirty=!0)}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._isStencilMaskDirty=!0)}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._isStencilTestDirty=!0)}constructor(e=!0){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.useStencilGlobalOnly=!1,e&&this.reset()}reset(){this.stencilMaterial=void 0,this.stencilGlobal?.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){if(!e)return;const t=!this.useStencilGlobalOnly&&!!this.stencilMaterial?.enabled;this.enabled=t?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=t?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=t?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=t?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=t?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=t?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=t?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=t?this.stencilMaterial.mask:this.stencilGlobal.mask,this.isDirty&&(this._isStencilTestDirty&&(this.enabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.mask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFunc(this.func,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOp(this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),this._isStencilOpDirty=!1))}}},83194:(e,t,i)=>{"use strict";i.d(t,{h:()=>r});class r{}r._IsPickingAvailable=!1},14747:(e,t,i)=>{"use strict";i.d(t,{b:()=>u});var r=i(15287),s=i(94212),n=i(40220),o=i(43279),a=i(34268),l=i(75108),h=i(89518);class c{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new o.cP,this._onClonedObservable=new o.cP}}class u{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,r){const s=this._NodeConstructors[e];return s?s(t,i,r):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return!!this._nodeDataStorage._doNotSerialize||!!this._parentNode&&this._parentNode.doNotSerialize}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&&void 0!==this._parentNode._children&&null!==this._parentNode._children){const t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1),e||this._nodeDataStorage._isDisposed||this._addToSceneRootNodes()}this._parentNode=e,this._isDirty=!0,this._parentNode&&(void 0!==this._parentNode._children&&null!==this._parentNode._children||(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(){-1===this._nodeDataStorage._sceneRootNodesIndex&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(-1!==this._nodeDataStorage._sceneRootNodesIndex){const e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}getClassName(){return"Node"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onEnabledStateChangedObservable(){return this._nodeDataStorage._onEnabledStateChangedObservable}get onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null,i=!0){this._isDirty=!1,this._nodeDataStorage=new c,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new o.cP,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=s.uq.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new o.cP,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||a.q.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache(),i&&this._addToSceneRootNodes()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){return-1!==this._behaviors.indexOf(e)||(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-1===t||(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&&this._parentNode.isSynchronized()}isSynchronized(){return!(this._parentNode&&!this.isSynchronizedWithParent())&&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!1===e?this._nodeDataStorage._isEnabled:!!this._nodeDataStorage._isEnabled&&this._nodeDataStorage._isParentEnabled}_syncParentEnabledState(){this._nodeDataStorage._isParentEnabled=!this._parentNode||this._parentNode.isEnabled(),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||this.parent.isDescendantOf(e))}_getDescendants(e,t=!1,i){if(this._children)for(let r=0;r(!t||t(e))&&void 0!==e.cullingStrategy)),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){e!==this._nodeDataStorage._isReady&&(e?(this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0):this._nodeDataStorage._isReady=!1)}getAnimationByName(e){for(let t=0;tnew u(e,this.getScene())),this);if(t&&(r.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;i{throw(0,l.n)("AnimationRange")},u._NodeConstructors={},(0,r.Cg)([(0,n.lK)()],u.prototype,"name",void 0),(0,r.Cg)([(0,n.lK)()],u.prototype,"id",void 0),(0,r.Cg)([(0,n.lK)()],u.prototype,"uniqueId",void 0),(0,r.Cg)([(0,n.lK)()],u.prototype,"state",void 0),(0,r.Cg)([(0,n.lK)()],u.prototype,"metadata",void 0)},88193:(e,t,i)=>{"use strict";i.d(t,{Z:()=>k,F:()=>L});var r=i(9723),s=i(64736),n=i(43279),o=i(39464),a=i(47131),l=i(84015),h=i(94212),c=i(69648),u=i(4216),d=i(81310),f=i(89357),p=i(2449),_=i(75653),m=i(9180),g=i(68191),v=i(34268),x=i(75108),b=i(1241),S=i(96772),T=i(80109),C=i(58292),y=i(78035),E=i(83194);class P{constructor(){this._singleClick=!1,this._doubleClick=!1,this._hasSwiped=!1,this._ignore=!1}get singleClick(){return this._singleClick}get doubleClick(){return this._doubleClick}get hasSwiped(){return this._hasSwiped}get ignore(){return this._ignore}set singleClick(e){this._singleClick=e}set doubleClick(e){this._doubleClick=e}set hasSwiped(e){this._hasSwiped=e}set ignore(e){this._ignore=e}}class A{constructor(e){this._alreadyAttached=!1,this._meshPickProceed=!1,this._currentPickResult=null,this._previousPickResult=null,this._activePointerIds=new Array,this._activePointerIdsCount=0,this._doubleClickOccured=!1,this._isSwiping=!1,this._swipeButtonPressed=-1,this._skipPointerTap=!1,this._isMultiTouchGesture=!1,this._pointerX=0,this._pointerY=0,this._startingPointerPosition=new h.I9(0,0),this._previousStartingPointerPosition=new h.I9(0,0),this._startingPointerTime=0,this._previousStartingPointerTime=0,this._pointerCaptures={},this._meshUnderPointerId={},this._movePointerInfo=null,this._cameraObserverCount=0,this._delayedClicks=[null,null,null,null,null],this._deviceSourceManager=null,this._scene=e||v.q.LastCreatedScene,this._scene}get meshUnderPointer(){return this._movePointerInfo&&(this._movePointerInfo._generatePickInfo(),this._movePointerInfo=null),this._pointerOverMesh}getMeshUnderPointerByPointerId(e){return this._meshUnderPointerId[e]||null}get unTranslatedPointer(){return new h.I9(this._unTranslatedPointerX,this._unTranslatedPointerY)}get pointerX(){return this._pointerX}set pointerX(e){this._pointerX=e}get pointerY(){return this._pointerY}set pointerY(e){this._pointerY=e}_updatePointerPosition(e){const t=this._scene.getEngine().getInputElementClientRect();t&&(this._pointerX=e.clientX-t.left,this._pointerY=e.clientY-t.top,this._unTranslatedPointerX=this._pointerX,this._unTranslatedPointerY=this._pointerY)}_processPointerMove(e,t){const i=this._scene,r=i.getEngine(),s=r.getInputElement();s&&(s.tabIndex=r.canvasTabIndex,i.doNotHandleCursors||(s.style.cursor=i.defaultCursor)),this._setCursorAndPointerOverMesh(e,t,i);for(const r of i._pointerMoveStage){e=e||this._pickMove(t);const i=!!e?.pickedMesh;e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,i,s)}const n=t.inputIndex>=C.ST.MouseWheelX&&t.inputIndex<=C.ST.MouseWheelZ?b.Zp.POINTERWHEEL:b.Zp.POINTERMOVE;let o;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,n)),e?(o=new b.mx(n,t,e),this._setRayOnPointerInfo(e,t)):(o=new b.mx(n,t,null,this),this._movePointerInfo=o),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(o,n)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&E.h._IsPickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,h.uq.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){const r=this._scene,s=new b.tT(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(s.originalPickingInfo=e,s.ray=e.ray,"xr-near"===t.pointerType&&e.originMesh&&(s.nearInteractionPickingInfo=e)),r.onPrePointerObservable.notifyObservers(s,i),!!s.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const r=i.getEngine().getInputElement();if(e?.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&r&&this._pointerOverMesh){const e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(r.style.cursor=e.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=C.ST.Move,this._checkPrePointerObservable(e,i,b.Zp.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,b.Zp.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e?.pickedMesh){this._pickedDownMesh=e.pickedMesh;const r=e.pickedMesh._getActionManagerForTrigger();if(r){if(r.hasPickTriggers)switch(r.processTrigger(5,f.X.CreateNew(e.pickedMesh,t,e)),t.button){case 0:r.processTrigger(2,f.X.CreateNew(e.pickedMesh,t,e));break;case 1:r.processTrigger(4,f.X.CreateNew(e.pickedMesh,t,e));break;case 2:r.processTrigger(3,f.X.CreateNew(e.pickedMesh,t,e))}r.hasSpecificTrigger(8)&&window.setTimeout((()=>{const e=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,(e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh),!1,i.cameraToUseForPointers);e?.pickedMesh&&r&&0!==this._activePointerIdsCount&&Date.now()-this._startingPointerTime>A.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,r.processTrigger(8,f.X.CreateNew(e.pickedMesh,t)))}),A.LongPressDelay)}}else for(const r of i._pointerDownStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let r;const s=b.Zp.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,s),r=new b.mx(s,t,e),this._setRayOnPointerInfo(e,t)):r=new b.mx(s,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(r,s)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const r=new PointerEvent("pointerup",t);r.inputIndex=C.ST.Move;const s=new P;i?s.doubleClick=!0:s.singleClick=!0,this._checkPrePointerObservable(e,r,b.Zp.POINTERUP)||this._processPointerUp(e,r,s)}_processPointerUp(e,t,i){const r=this._scene;if(e?.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(r.onPointerPick&&r.onPointerPick(t,e),i.singleClick&&!i.ignore&&r.onPointerObservable.observers.length>this._cameraObserverCount)){const i=b.Zp.POINTERPICK,s=new b.mx(i,t,e);this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(s,i)}const s=e.pickedMesh._getActionManagerForTrigger();if(s&&!i.ignore){s.processTrigger(7,f.X.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&s.processTrigger(1,f.X.CreateNew(e.pickedMesh,t,e));const r=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&r&&r.processTrigger(6,f.X.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const s of r._pointerUpStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,f.X.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const s=new b.mx(b.Zp.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(s,b.Zp.POINTERUP),r.onPointerUp&&r.onPointerUp(t,e,b.Zp.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let s=0;if(i.singleClick?s=b.Zp.POINTERTAP:i.doubleClick&&(s=b.Zp.POINTERDOUBLETAP),s){const i=new b.mx(s,t,e);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(s)&&r.onPointerObservable.notifyObservers(i,s)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,r=null){const s=this._scene,n=s.getEngine();r||(r=n.getInputElement()),this._alreadyAttached&&this.detachControl(),r&&(this._alreadyAttachedTo=r),this._deviceSourceManager=new y.Z(n),this._initActionManager=e=>{if(!this._meshPickProceed){const t=s.skipPointerUpPicking||0===s._registeredActions&&!this._checkForPicking()&&!s.onPointerUp?null:s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerUpPredicate,s.pointerUpFastCheck,s.cameraToUseForPointers,s.pointerUpTrianglePredicate);this._currentPickResult=t,t&&(e=t.hit&&t.pickedMesh?t.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return e},this._delayedSimpleClick=(e,t,i)=>{if((Date.now()-this._previousStartingPointerTime>A.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,this._delayedClicks[e])){const t=this._delayedClicks[e].evt,i=b.Zp.POINTERTAP,r=new b.mx(i,t,this._currentPickResult);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(i)&&s.onPointerObservable.notifyObservers(r,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,r)=>{const s=new P;this._currentPickResult=null;let n=null,o=e.hasSpecificMask(b.Zp.POINTERPICK)||t.hasSpecificMask(b.Zp.POINTERPICK)||e.hasSpecificMask(b.Zp.POINTERTAP)||t.hasSpecificMask(b.Zp.POINTERTAP)||e.hasSpecificMask(b.Zp.POINTERDOUBLETAP)||t.hasSpecificMask(b.Zp.POINTERDOUBLETAP);!o&&S.G&&(n=this._initActionManager(n,s),n&&(o=n.hasPickTriggers));let a=!1;if(o){const o=i.button;if(s.hasSwiped=this._isPointerSwiping(),!s.hasSwiped){let l=!A.ExclusiveDoubleClickMode;if(l||(l=!e.hasSpecificMask(b.Zp.POINTERDOUBLETAP)&&!t.hasSpecificMask(b.Zp.POINTERDOUBLETAP),l&&!S.G.HasSpecificTrigger(6)&&(n=this._initActionManager(n,s),n&&(l=!n.hasSpecificTrigger(6)))),l)(Date.now()-this._previousStartingPointerTime>A.DoubleClickDelay||o!==this._previousButtonPressed)&&(s.singleClick=!0,r(s,this._currentPickResult),a=!0);else{const e={evt:i,clickInfo:s,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,o,s,r),A.DoubleClickDelay)};this._delayedClicks[o]=e}let h=e.hasSpecificMask(b.Zp.POINTERDOUBLETAP)||t.hasSpecificMask(b.Zp.POINTERDOUBLETAP);!h&&S.G.HasSpecificTrigger(6)&&(n=this._initActionManager(n,s),n&&(h=n.hasSpecificTrigger(6))),h&&(o===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>A.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>A.DragMovementThreshold),n.isPointerLock&&n._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=C.ST.MouseWheelX&&e.inputIndex<=C.ST.MouseWheelZ?b.Zp.POINTERWHEEL:b.Zp.POINTERMOVE))return;if(!s.cameraToUseForPointers&&!s.activeCamera)return;if(s.skipPointerMovePicking)return void this._processPointerMove(new d.G,e);s.pointerMovePredicate||(s.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||s.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!s.cameraToUseForPointers||!!(s.cameraToUseForPointers.layerMask&e.layerMask)));const t=s._registeredActions>0||s.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{const t=this._activePointerIds.indexOf(-1);if(-1===t?this._activePointerIds.push(e.pointerId):this._activePointerIds[t]=e.pointerId,this._activePointerIdsCount++,this._pickedDownMesh=null,this._meshPickProceed=!1,A.ExclusiveDoubleClickMode)for(let t=0;te.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!s.cameraToUseForPointers||!!(s.cameraToUseForPointers.layerMask&e.layerMask))),this._pickedDownMesh=null,i=s.skipPointerDownPicking||0===s._registeredActions&&!this._checkForPicking()&&!s.onPointerDown?new d.G:s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerDownPredicate,s.pointerDownFastCheck,s.cameraToUseForPointers,s.pointerDownTrianglePredicate),this._processPointerDown(i,e)},this._onPointerUp=e=>{const t=this._activePointerIds.indexOf(e.pointerId);-1!==t&&(this._activePointerIds[t]=-1,this._activePointerIdsCount--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),s.preventDefaultOnPointerUp&&r&&(e.preventDefault(),r.focus()),this._initClickEvent(s.onPrePointerObservable,s.onPointerObservable,e,((t,i)=>{if(s.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,b.Zp.POINTERUP))return this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),void(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1));t.hasSwiped||(t.singleClick&&s.onPrePointerObservable.hasSpecificMask(b.Zp.POINTERTAP)&&this._checkPrePointerObservable(null,e,b.Zp.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&s.onPrePointerObservable.hasSpecificMask(b.Zp.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,b.Zp.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}this._pointerCaptures[e.pointerId]?(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(s.cameraToUseForPointers||s.activeCamera)&&(s.pointerUpPredicate||(s.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!s.cameraToUseForPointers||!!(s.cameraToUseForPointers.layerMask&e.layerMask))),!this._meshPickProceed&&(S.G&&S.G.HasTriggers||this._checkForPicking()||s.onPointerUp)&&this._initActionManager(null,t),i||(i=this._currentPickResult),this._processPointerUp(i,e,t),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))):this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1)})))},this._onKeyDown=e=>{const t=T.TB.KEYDOWN;if(s.onPreKeyboardObservable.hasObservers()){const i=new T.Bu(t,e);if(s.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){const i=new T.W0(t,e);s.onKeyboardObservable.notifyObservers(i,t)}s.actionManager&&s.actionManager.processTrigger(14,f.X.CreateNewFromScene(s,e))},this._onKeyUp=e=>{const t=T.TB.KEYUP;if(s.onPreKeyboardObservable.hasObservers()){const i=new T.Bu(t,e);if(s.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){const i=new T.W0(t,e);s.onKeyboardObservable.notifyObservers(i,t)}s.actionManager&&s.actionManager.processTrigger(15,f.X.CreateNewFromScene(s,e))},this._deviceSourceManager.onDeviceConnectedObservable.add((r=>{r.deviceType===C.bq.Mouse?r.onInputChangedObservable.add((s=>{this._originMouseEvent=s,s.inputIndex===C.ST.LeftClick||s.inputIndex===C.ST.MiddleClick||s.inputIndex===C.ST.RightClick||s.inputIndex===C.ST.BrowserBack||s.inputIndex===C.ST.BrowserForward?t&&1===r.getInput(s.inputIndex)?this._onPointerDown(s):e&&0===r.getInput(s.inputIndex)&&this._onPointerUp(s):i&&(s.inputIndex===C.ST.Move?this._onPointerMove(s):s.inputIndex!==C.ST.MouseWheelX&&s.inputIndex!==C.ST.MouseWheelY&&s.inputIndex!==C.ST.MouseWheelZ||this._onPointerMove(s))})):r.deviceType===C.bq.Touch?r.onInputChangedObservable.add((s=>{s.inputIndex===C.ST.LeftClick&&(t&&1===r.getInput(s.inputIndex)?(this._onPointerDown(s),this._activePointerIdsCount>1&&(this._isMultiTouchGesture=!0)):e&&0===r.getInput(s.inputIndex)&&(this._onPointerUp(s),0===this._activePointerIdsCount&&(this._isMultiTouchGesture=!1))),i&&s.inputIndex===C.ST.Move&&this._onPointerMove(s)})):r.deviceType===C.bq.Keyboard&&r.onInputChangedObservable.add((e=>{"keydown"===e.type?this._onKeyDown(e):"keyup"===e.type&&this._onKeyUp(e)}))})),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,r){if(!(this._meshUnderPointerId[t]!==e||e&&e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const s=this._meshUnderPointerId[t];let n;s&&(n=s._getActionManagerForTrigger(10),n&&n.processTrigger(10,f.X.CreateNew(s,r,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,n=e._getActionManagerForTrigger(9),n&&n.processTrigger(9,f.X.CreateNew(e,r,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null);for(const t in this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}}A.DragMovementThreshold=10,A.LongPressDelay=500,A.DoubleClickDelay=300,A.ExclusiveDoubleClickMode=!1;var R=i(78641),I=i(11084),M=i(59881),O=i(83839),D=i(28909),w=i(14952),N=i(34130);class F{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var L,B=i(60590),V=i(56225);!function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(L||(L={}));class k{static DefaultMaterialFactory(e){throw(0,x.n)("StandardMaterial")}static CollisionCoordinatorFactory(){throw(0,x.n)("DefaultCollisionCoordinator")}get clearColor(){return this._clearColor}set clearColor(e){e!==this._clearColor&&(this._clearColor=e,this.onClearColorChangedObservable.notifyObservers(this._clearColor))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case 0:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case 1:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case 2:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1}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 environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}getNodes(){let e=[];return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach((t=>e=e.concat(t.bones))),e}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 A.DragMovementThreshold}static set DragMovementThreshold(e){A.DragMovementThreshold=e}static get LongPressDelay(){return A.LongPressDelay}static set LongPressDelay(e){A.LongPressDelay=e}static get DoubleClickDelay(){return A.DoubleClickDelay}static set DoubleClickDelay(e){A.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return A.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){A.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){const r=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,s=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return h.AA.Vector4[0].set(r.x,r.y,r.z,s?-1:1),e&&(i?e.setFloat3(t,h.AA.Vector4[0].x,h.AA.Vector4[0].y,h.AA.Vector4[0].z):e.setVector4(t,h.AA.Vector4[0])),h.AA.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=(0,N.lL)(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=k.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}get frameGraph(){return this._frameGraph}set frameGraph(e){if(this._frameGraph)return this._frameGraph=e,void(e||(this.customRenderFunction=this._currentCustomRenderFunction));this._frameGraph=e,e&&(this._currentCustomRenderFunction=this.customRenderFunction,this.customRenderFunction=this._renderWithFrameGraph)}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=k.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){this._inputManager=new A(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this._clearColor=new I.ov(.2,.2,.3,1),this.onClearColorChangedObservable=new n.cP,this.ambientColor=new I.v9(0,0,0),this.environmentIntensity=1,this._performancePriority=0,this.onScenePerformancePriorityChangedObservable=new n.cP,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[],this.effectLayers=[],this.sounds=null,this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],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 n.cP,this._onDisposeObserver=null,this.onBeforeRenderObservable=new n.cP,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new n.cP,this.onAfterRenderCameraObservable=new n.cP,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new n.cP,this.onAfterAnimationsObservable=new n.cP,this.onBeforeDrawPhaseObservable=new n.cP,this.onAfterDrawPhaseObservable=new n.cP,this.onReadyObservable=new n.cP,this.onBeforeCameraRenderObservable=new n.cP,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new n.cP,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new n.cP,this.onAfterActiveMeshesEvaluationObservable=new n.cP,this.onBeforeParticlesRenderingObservable=new n.cP,this.onAfterParticlesRenderingObservable=new n.cP,this.onDataLoadedObservable=new n.cP,this.onNewCameraAddedObservable=new n.cP,this.onCameraRemovedObservable=new n.cP,this.onNewLightAddedObservable=new n.cP,this.onLightRemovedObservable=new n.cP,this.onNewGeometryAddedObservable=new n.cP,this.onGeometryRemovedObservable=new n.cP,this.onNewTransformNodeAddedObservable=new n.cP,this.onTransformNodeRemovedObservable=new n.cP,this.onNewMeshAddedObservable=new n.cP,this.onMeshRemovedObservable=new n.cP,this.onNewSkeletonAddedObservable=new n.cP,this.onSkeletonRemovedObservable=new n.cP,this.onNewMaterialAddedObservable=new n.cP,this.onNewMultiMaterialAddedObservable=new n.cP,this.onMaterialRemovedObservable=new n.cP,this.onMultiMaterialRemovedObservable=new n.cP,this.onNewTextureAddedObservable=new n.cP,this.onTextureRemovedObservable=new n.cP,this.onBeforeRenderTargetsRenderObservable=new n.cP,this.onAfterRenderTargetsRenderObservable=new n.cP,this.onBeforeStepObservable=new n.cP,this.onAfterStepObservable=new n.cP,this.onActiveCameraChanged=new n.cP,this.onActiveCamerasChanged=new n.cP,this.onBeforeRenderingGroupObservable=new n.cP,this.onAfterRenderingGroupObservable=new n.cP,this.onMeshImportedObservable=new n.cP,this.onAnimationFileImportedObservable=new n.cP,this._registeredForLateAnimationBindings=new o.b(256),this._pointerPickingConfiguration=new F,this.onPrePointerObservable=new n.cP,this.onPointerObservable=new n.cP,this.onPreKeyboardObservable=new n.cP,this.onKeyboardObservable=new n.cP,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=k.FOGMODE_NONE,this.fogColor=new I.v9(.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._frameGraph=null,this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new h.Pq(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new o.b(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new R.A,this._activeIndices=new R.A,this._activeParticles=new R.A,this._activeBones=new R.A,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 o.L(256),this._processedMaterials=new o.L(256),this._renderTargets=new o.b(256),this._materialsRenderTargets=new o.b(256),this._activeParticleSystems=new o.L(256),this._activeSkeletons=new o.b(32),this._softwareSkinnedMeshes=new o.b(32),this._activeAnimatables=new Array,this._transformMatrix=h.uq.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=m.B.Create(),this._beforeClearStage=m.B.Create(),this._beforeRenderTargetClearStage=m.B.Create(),this._gatherRenderTargetsStage=m.B.Create(),this._gatherActiveCameraRenderTargetsStage=m.B.Create(),this._isReadyForMeshStage=m.B.Create(),this._beforeEvaluateActiveMeshStage=m.B.Create(),this._evaluateSubMeshStage=m.B.Create(),this._preActiveMeshStage=m.B.Create(),this._cameraDrawRenderTargetStage=m.B.Create(),this._beforeCameraDrawStage=m.B.Create(),this._beforeRenderTargetDrawStage=m.B.Create(),this._beforeRenderingGroupDrawStage=m.B.Create(),this._beforeRenderingMeshStage=m.B.Create(),this._afterRenderingMeshStage=m.B.Create(),this._afterRenderingGroupDrawStage=m.B.Create(),this._afterCameraDrawStage=m.B.Create(),this._afterCameraPostProcessStage=m.B.Create(),this._afterRenderTargetDrawStage=m.B.Create(),this._afterRenderTargetPostProcessStage=m.B.Create(),this._afterRenderStage=m.B.Create(),this._pointerMoveStage=m.B.Create(),this._pointerDownStage=m.B.Create(),this._pointerUpStage=m.B.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||v.q.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(v.q._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new _.m(this),p.X&&(this.postProcessManager=new p.X(this)),(0,g.BA)()&&this.attachControl(),this._createUbo(),c.p&&(this._imageProcessingConfiguration=new c.p),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 void 0!==this._animationRatio?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){if(this._isDisposed)return!1;let t;const i=this.getEngine(),r=i.currentRenderPassId;i.currentRenderPassId=this.activeCamera?.renderPassId??r;let s=!0;for(this._pendingData.length>0&&(s=!1),this.prePassRenderer?.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&s&&(s=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t0;for(const e of this._isReadyForMeshStage)e.action(r,n)||(s=!1);if(!e)continue;const o=r.material||this.defaultMaterial;if(o)if(o._storeEffectOnSubMeshes)for(const e of r.subMeshes){const t=e.getMaterial();t&&t.hasRenderTargetTextures&&null!=t.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(t)&&(this._processedMaterials.push(t),this._materialsRenderTargets.concatWithNoDuplicate(t.getRenderTargetTextures()))}else o.hasRenderTargetTextures&&null!=o.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(o)&&(this._processedMaterials.push(o),this._materialsRenderTargets.concatWithNoDuplicate(o.getRenderTargetTextures()))}if(e)for(t=0;t0)for(const e of this.activeCameras)e.isReady(!0)||(s=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(s=!1));for(const e of this.particleSystems)e.isReady()||(s=!1);if(this.layers)for(const e of this.layers)e.isReady()||(s=!1);return i.areAllEffectsReady()||(s=!1),i.currentRenderPassId=r,s}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){const t=()=>{e(),setTimeout((()=>{this.unregisterBeforeRender(t)}))};this.registerBeforeRender(t)}executeOnceBeforeRender(e,t){void 0!==t?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);-1!==i&&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),null===this._executeWhenReadyTimeoutId&&this._checkIsReady(t)}whenReadyAsync(e=!1){return new Promise((t=>{this.executeWhenReady((()=>{t()}),e)}))}_checkIsReady(e=!1){return this._registerTransientComponents(),this.isReady(e)?(this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):this._isDisposed?(this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):void(this._executeWhenReadyTimeoutId=setTimeout((()=>{this.incrementRenderId(),this._checkIsReady(e)}),100))}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=s.j.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,r){i||r||!this._multiviewSceneUbo||(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag||(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?M.P.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=M.P.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,r):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e){const t=new u.D(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 O.K.UniqueId}addMesh(e,t=!1){this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),r.S0.SetImmediate((()=>{this.onNewMeshAddedObservable.notifyObservers(e)})),t&&e.getChildMeshes().forEach((e=>{this.addMesh(e)})))}removeMesh(e,t=!1){const i=this.meshes.indexOf(e);return-1!==i&&(this.meshes.splice(i,1),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.removeMesh(e)})),i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneTransformNodesArray||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){const t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){const e=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=e,e._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-1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){const t=this.morphTargetManagers.indexOf(e);return-1!==t&&this.morphTargetManagers.splice(t,1),t}removeLight(e){const t=this.lights.indexOf(e);if(-1!==t){for(const t of this.meshes)t._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(-1!==t&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){const t=this.activeCameras.indexOf(e);-1!==t&&this.activeCameras.splice(t,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-1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){const t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){const t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){const t=this.multiMaterials.indexOf(e);return-1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){const t=e._indexInSceneMaterialArray;if(-1!==t&&t{this.onNewLightAddedObservable.notifyObservers(e)}))}}sortLightsByPriority(){this.requireLightSorting&&this.lights.sort(w.c.CompareLightsPriority)}addCamera(e){this._blockEntityCollection||(this.cameras.push(e),r.S0.SetImmediate((()=>{this.onNewCameraAddedObservable.notifyObservers(e)})),e.parent||e._addToSceneRootNodes())}addSkeleton(e){this._blockEntityCollection||(this.skeletons.push(e),r.S0.SetImmediate((()=>{this.onNewSkeletonAddedObservable.notifyObservers(e)})))}addParticleSystem(e){this._blockEntityCollection||this.particleSystems.push(e)}addAnimation(e){this._blockEntityCollection||this.animations.push(e)}addAnimationGroup(e){this._blockEntityCollection||this.animationGroups.push(e)}addMultiMaterial(e){this._blockEntityCollection||(this.multiMaterials.push(e),r.S0.SetImmediate((()=>{this.onNewMultiMaterialAddedObservable.notifyObservers(e)})))}addMaterial(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneMaterialArray||(e._indexInSceneMaterialArray=this.materials.length,this.materials.push(e),r.S0.SetImmediate((()=>{this.onNewMaterialAddedObservable.notifyObservers(e)})))}addMorphTargetManager(e){this._blockEntityCollection||this.morphTargetManagers.push(e)}addGeometry(e){this._blockEntityCollection||(this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=this.geometries.length),this.geometries.push(e))}addActionManager(e){this.actionManagers.push(e)}addTexture(e){this._blockEntityCollection||(this.textures.push(e),this.onNewTextureAddedObservable.notifyObservers(e))}switchActiveCamera(e,t=!0){this._engine.getInputElement()&&(this.activeCamera&&this.activeCamera.detachControl(),this.activeCamera=e,t&&e.attachControl())}setActiveCameraById(e){const t=this.getCameraById(e);return t?(this.activeCamera=t,t):null}setActiveCameraByName(e){const t=this.getCameraByName(e);return t?(this.activeCamera=t,t):null}getAnimationGroupByName(e){for(let t=0;tt.uniqueId===e))}getMaterialById(e,t=!1){return this._getMaterial(t,(t=>t.id===e))}getMaterialByName(e,t=!1){return this._getMaterial(t,(t=>t.name===e))}getLastMaterialById(e,t=!1){for(let t=this.materials.length-1;t>=0;t--)if(this.materials[t].id===e)return this.materials[t];if(t)for(let t=this.multiMaterials.length-1;t>=0;t--)if(this.multiMaterials[t].id===e)return this.multiMaterials[t];return null}getTextureByUniqueId(e){for(let t=0;t{this.onNewGeometryAddedObservable.notifyObservers(e)})),0))}removeGeometry(e){let t;if(this._geometriesByUniqueId){if(t=this._geometriesByUniqueId[e.uniqueId],void 0===t)return!1}else if(t=this.geometries.indexOf(e),t<0)return!1;if(t!==this.geometries.length-1){const e=this.geometries[this.geometries.length-1];e&&(this.geometries[t]=e,this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=t))}return this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=void 0),this.geometries.pop(),this.onGeometryRemovedObservable.notifyObservers(e),!0}getGeometries(){return this.geometries}getMeshById(e){for(let t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const r=this.getLightById(e);if(r)return r;const s=this.getCameraById(e);if(s)return s;return this.getBoneById(e)||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const r=this.getLightByName(e);if(r)return r;const s=this.getCameraByName(e);if(s)return s;return this.getBoneByName(e)||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){if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=s,this._skipEvaluateActiveMeshesCompletely=e,r)for(let e=0;ee.dispose()))}_evaluateActiveMeshes(){if(this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode)return void(this._activeMeshes.length>0&&(this.activeCamera?._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset()));if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const e=this._activeMeshes.length;for(let t=0;t0&&t.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||t.alwaysSelectAsActiveMesh||t.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(t),this.activeCamera._activeMeshes.push(t),r!==t&&r._activate(this._renderId,!1);for(const e of this._preActiveMeshStage)e.action(t);t._activate(this._renderId,!1)&&(t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(r=t):r._internalAbstractMeshDataInfo._onlyForInstances=!1,r._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(t,r)),t._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e0){const r=this.getActiveSubMeshCandidates(t),s=r.length;i=i||1===s;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 e of this._gatherActiveCameraRenderTargetsStage)e.action(this._renderTargets);let n=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){r.S0.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e0),this._renderId++}for(const e of this._cameraDrawRenderTargetStage)n=e.action(this.activeCamera)||n;this._intermediateRendering=!1}this._engine.currentRenderPassId=e.outputRenderTarget?.renderPassId??e.renderPassId??0,n&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame();for(const e of this._beforeCameraDrawStage)e.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),s.snapshotRendering&&1===s.snapshotRenderingMode&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const e of this._afterCameraDrawStage)e.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const t=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,t)}for(const e of this._afterCameraPostProcessStage)e.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(0===e.cameraRigMode||e._renderingMultiview)return e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),void this.onAfterRenderCameraObservable.notifyObservers(e);if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let t=0;t-1&&(13===i.trigger&&i._executeCurrent(f.X.CreateNew(t,void 0,r)),t.actionManager.hasSpecificTrigger(13,(e=>{const t=e.mesh?e.mesh:e;return r===t}))&&13!==i.trigger||t._intersectionsInProgress.splice(n,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(k.MinDeltaTime,Math.min(this._engine.getDeltaTime(),k.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let r=0;const s=this._engine.getLockstepMaxSteps();let n=Math.floor(e/t);for(n=Math.min(n,s);e>0&&r0)for(let e=0;e0),this._intermediateRendering=!0;for(let i=0;i0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=t?.renderPassId??0,this.activeCamera=t,this._activeCamera&&22!==this._activeCamera.cameraRigMode&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const e of this._beforeClearStage)e.action();this._clearFrameBuffer(this.activeCamera);for(const e of this._gatherRenderTargetsStage)e.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}}this._checkIntersections();for(const e of this._afterRenderStage)e.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let e=0;e{e.onAnimationEndObservable.clear(),e.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 t of e)t.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){B.V.Error("An error occurred while calling onDisposeObservable!",e)}if(this.detachControl(),this._engine.getInputElement())for(let e=0;ee.dispose(!0))),this._disposeList(this.transformNodes,(e=>e.dispose(!0)));const t=this.cameras;this._disposeList(t),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 i=this._engine.scenes.indexOf(this);i>-1&&this._engine.scenes.splice(i,1),v.q._LastCreatedScene===this&&(this._engine.scenes.length>0?v.q._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:v.q._LastCreatedScene=null),i=this._engine._virtualScenes.indexOf(this),i>-1&&this._engine._virtualScenes.splice(i,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.onClearColorChangedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){const i=e.slice(0);t=t??(e=>e.dispose());for(const e of i)t(e);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0),this.meshes.filter(e).forEach((e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;const r=e.getBoundingInfo(),s=r.boundingBox.minimumWorld,n=r.boundingBox.maximumWorld;h.Pq.CheckExtends(s,t,i),h.Pq.CheckExtends(n,t,i)})),{min:t,max:i}}createPickingRay(e,t,i,r,s=!1){throw(0,x.n)("Ray")}createPickingRayToRef(e,t,i,r,s,n=!1,o=!1){throw(0,x.n)("Ray")}createPickingRayInCameraSpace(e,t,i){throw(0,x.n)("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,r){throw(0,x.n)("Ray")}pick(e,t,i,r,s,n){const o=(0,x.n)("Ray",!0);return o&&B.V.Warn(o),new d.G}pickWithBoundingInfo(e,t,i,r,s){const n=(0,x.n)("Ray",!0);return n&&B.V.Warn(n),new d.G}pickWithRay(e,t,i,r){throw(0,x.n)("Ray")}multiPick(e,t,i,r,s){throw(0,x.n)("Ray")}multiPickWithRay(e,t,i){throw(0,x.n)("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(void 0===t)return e;const r=[];for(const s in e){const n=e[s];l.Y&&l.Y.MatchesQuery(n,t)&&(!i||i(n))&&r.push(n)}return r}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,i=null,r=null){this._renderingManager.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t,i=!0,r=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,r)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(const i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,r,s,n,o){const a=(0,D.zU)(e,t,i,r?this.offlineProvider:void 0,s,n,o);return this._activeRequests.push(a),a.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),a}_loadFileAsync(e,t,i,r,s){return new Promise(((n,o)=>{this._loadFile(e,(e=>{n(e)}),t,i,r,((e,t)=>{o(t)}),s)}))}_requestFile(e,t,i,r,s,n,o){const a=(0,D.sh)(e,t,i,r?this.offlineProvider:void 0,s,n,o);return this._activeRequests.push(a),a.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),a}_requestFileAsync(e,t,i,r,s){return new Promise(((n,o)=>{this._requestFile(e,(e=>{n(e)}),t,i,r,(e=>{o(e)}),s)}))}_readFile(e,t,i,r,s){const n=(0,D.NJ)(e,t,i,r,s);return this._activeRequests.push(n),n.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),n}_readFileAsync(e,t,i){return new Promise(((r,s)=>{this._readFile(e,(e=>{r(e)}),t,i,(e=>{s(e)}))}))}getPerfCollector(){throw(0,x.n)("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)}}k.FOGMODE_NONE=0,k.FOGMODE_EXP=1,k.FOGMODE_EXP2=2,k.FOGMODE_LINEAR=3,k.MinDeltaTime=1,k.MaxDeltaTime=1e3,(0,V.Y5)("BABYLON.Scene",k)},9180:(e,t,i)=>{"use strict";i.d(t,{B:()=>s,v:()=>r});class r{}r.NAME_EFFECTLAYER="EffectLayer",r.NAME_LAYER="Layer",r.NAME_LENSFLARESYSTEM="LensFlareSystem",r.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",r.NAME_PARTICLESYSTEM="ParticleSystem",r.NAME_GAMEPAD="Gamepad",r.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",r.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",r.NAME_PREPASSRENDERER="PrePassRenderer",r.NAME_DEPTHRENDERER="DepthRenderer",r.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer",r.NAME_IBLSHADOWSRENDERER="IblShadowsRenderer",r.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",r.NAME_SPRITE="Sprite",r.NAME_SUBSURFACE="SubSurface",r.NAME_OUTLINERENDERER="Outline",r.NAME_PROCEDURALTEXTURE="ProceduralTexture",r.NAME_SHADOWGENERATOR="ShadowGenerator",r.NAME_OCTREE="Octree",r.NAME_PHYSICSENGINE="PhysicsEngine",r.NAME_AUDIO="Audio",r.NAME_FLUIDRENDERER="FluidRenderer",r.STEP_ISREADYFORMESH_EFFECTLAYER=0,r.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,r.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,r.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0,r.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,r.STEP_BEFORECAMERADRAW_PREPASS=0,r.STEP_BEFORECAMERADRAW_EFFECTLAYER=1,r.STEP_BEFORECAMERADRAW_LAYER=2,r.STEP_BEFORERENDERTARGETDRAW_PREPASS=0,r.STEP_BEFORERENDERTARGETDRAW_LAYER=1,r.STEP_BEFORERENDERINGMESH_PREPASS=0,r.STEP_BEFORERENDERINGMESH_OUTLINE=1,r.STEP_AFTERRENDERINGMESH_PREPASS=0,r.STEP_AFTERRENDERINGMESH_OUTLINE=1,r.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,r.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,r.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,r.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,r.STEP_BEFORECLEAR_PREPASS=1,r.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0,r.STEP_AFTERRENDERTARGETDRAW_PREPASS=0,r.STEP_AFTERRENDERTARGETDRAW_LAYER=1,r.STEP_AFTERCAMERADRAW_PREPASS=0,r.STEP_AFTERCAMERADRAW_EFFECTLAYER=1,r.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2,r.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3,r.STEP_AFTERCAMERADRAW_LAYER=4,r.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5,r.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0,r.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0,r.STEP_AFTERRENDER_AUDIO=0,r.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0,r.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,r.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2,r.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,r.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,r.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1,r.STEP_POINTERMOVE_SPRITE=0,r.STEP_POINTERDOWN_SPRITE=0,r.STEP_POINTERUP_SPRITE=0;class s extends Array{constructor(e){super(...e)}static Create(){return Object.create(s.prototype)}registerStep(e,t,i){let r=0,s=Number.MAX_VALUE;for(;r{"use strict";function r(e,t,i,r){var s,n=arguments.length,o=n<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(s=e[a])&&(o=(n<3?s(o):n>3?s(t,i,o):s(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o}i.d(t,{Cg:()=>r}),Object.create,Object.create},66570:e=>{"use strict";function t(e,t,n){n=n||2;var o,a,l,u,d,p,_,m=t&&t.length,g=m?t[0]*n:e.length,v=i(e,0,g,n,!0),x=[];if(!v||v.next===v.prev)return x;if(m&&(v=function(e,t,s,n){var o,a,l,u=[];for(o=0,a=t.length;o80*n){o=l=e[0],a=u=e[1];for(var b=n;bl&&(l=d),p>u&&(u=p);_=0!==(_=Math.max(l-o,u-a))?1/_:0}return s(v,x,n,o,a,_),x}function i(e,t,i,r,s){var n,o;if(s===P(e,t,i,r)>0)for(n=t;n=t;n-=r)o=C(n,e[n],e[n+1],o);return o&&g(o,o.next)&&(y(o),o=o.next),o}function r(e,t){if(!e)return e;t||(t=e);var i,r=e;do{if(i=!1,r.steiner||!g(r,r.next)&&0!==m(r.prev,r,r.next))r=r.next;else{if(y(r),(r=t=r.prev)===r.next)break;i=!0}}while(i||r!==t);return t}function s(e,t,i,h,c,u,f){if(e){!f&&u&&function(e,t,i,r){var s=e;do{null===s.z&&(s.z=d(s.x,s.y,t,i,r)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next}while(s!==e);s.prevZ.nextZ=null,s.prevZ=null,function(e){var t,i,r,s,n,o,a,l,h=1;do{for(i=e,e=null,n=null,o=0;i;){for(o++,r=i,a=0,t=0;t0||l>0&&r;)0!==a&&(0===l||!r||i.z<=r.z)?(s=i,i=i.nextZ,a--):(s=r,r=r.nextZ,l--),n?n.nextZ=s:e=s,s.prevZ=n,n=s;i=r}n.nextZ=null,h*=2}while(o>1)}(s)}(e,h,c,u);for(var p,_,m=e;e.prev!==e.next;)if(p=e.prev,_=e.next,u?o(e,h,c,u):n(e))t.push(p.i/i),t.push(e.i/i),t.push(_.i/i),y(e),e=_.next,m=_.next;else if((e=_)===m){f?1===f?s(e=a(r(e),t,i),t,i,h,c,u,2):2===f&&l(e,t,i,h,c,u):s(r(e),t,i,h,c,u,1);break}}}function n(e){var t=e.prev,i=e,r=e.next;if(m(t,i,r)>=0)return!1;for(var s=e.next.next;s!==e.prev;){if(p(t.x,t.y,i.x,i.y,r.x,r.y,s.x,s.y)&&m(s.prev,s,s.next)>=0)return!1;s=s.next}return!0}function o(e,t,i,r){var s=e.prev,n=e,o=e.next;if(m(s,n,o)>=0)return!1;for(var a=s.xn.x?s.x>o.x?s.x:o.x:n.x>o.x?n.x:o.x,c=s.y>n.y?s.y>o.y?s.y:o.y:n.y>o.y?n.y:o.y,u=d(a,l,t,i,r),f=d(h,c,t,i,r),_=e.prevZ,g=e.nextZ;_&&_.z>=u&&g&&g.z<=f;){if(_!==e.prev&&_!==e.next&&p(s.x,s.y,n.x,n.y,o.x,o.y,_.x,_.y)&&m(_.prev,_,_.next)>=0)return!1;if(_=_.prevZ,g!==e.prev&&g!==e.next&&p(s.x,s.y,n.x,n.y,o.x,o.y,g.x,g.y)&&m(g.prev,g,g.next)>=0)return!1;g=g.nextZ}for(;_&&_.z>=u;){if(_!==e.prev&&_!==e.next&&p(s.x,s.y,n.x,n.y,o.x,o.y,_.x,_.y)&&m(_.prev,_,_.next)>=0)return!1;_=_.prevZ}for(;g&&g.z<=f;){if(g!==e.prev&&g!==e.next&&p(s.x,s.y,n.x,n.y,o.x,o.y,g.x,g.y)&&m(g.prev,g,g.next)>=0)return!1;g=g.nextZ}return!0}function a(e,t,i){var s=e;do{var n=s.prev,o=s.next.next;!g(n,o)&&v(n,s,s.next,o)&&S(n,o)&&S(o,n)&&(t.push(n.i/i),t.push(s.i/i),t.push(o.i/i),y(s),y(s.next),s=e=o),s=s.next}while(s!==e);return r(s)}function l(e,t,i,n,o,a){var l=e;do{for(var h=l.next.next;h!==l.prev;){if(l.i!==h.i&&_(l,h)){var c=T(l,h);return l=r(l,l.next),c=r(c,c.next),s(l,t,i,n,o,a),void s(c,t,i,n,o,a)}h=h.next}l=l.next}while(l!==e)}function h(e,t){return e.x-t.x}function c(e,t){var i=function(e,t){var i,r=t,s=e.x,n=e.y,o=-1/0;do{if(n<=r.y&&n>=r.next.y&&r.next.y!==r.y){var a=r.x+(n-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(a<=s&&a>o){if(o=a,a===s){if(n===r.y)return r;if(n===r.next.y)return r.next}i=r.x=r.x&&r.x>=c&&s!==r.x&&p(ni.x||r.x===i.x&&u(i,r)))&&(i=r,f=l)),r=r.next}while(r!==h);return i}(e,t);if(!i)return t;var s=T(i,e),n=r(i,i.next);return r(s,s.next),t===i?n:t}function u(e,t){return m(e.prev,e,t.prev)<0&&m(t.next,e,e.next)<0}function d(e,t,i,r,s){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-i)*s)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*s)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function f(e){var t=e,i=e;do{(t.x=0&&(e-o)*(r-a)-(i-o)*(t-a)>=0&&(i-o)*(n-a)-(s-o)*(r-a)>=0}function _(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){var i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&v(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}(e,t)&&(S(e,t)&&S(t,e)&&function(e,t){var i=e,r=!1,s=(e.x+t.x)/2,n=(e.y+t.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&s<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(r=!r),i=i.next}while(i!==e);return r}(e,t)&&(m(e.prev,e,t.prev)||m(e,t.prev,t))||g(e,t)&&m(e.prev,e,e.next)>0&&m(t.prev,t,t.next)>0)}function m(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function g(e,t){return e.x===t.x&&e.y===t.y}function v(e,t,i,r){var s=b(m(e,t,i)),n=b(m(e,t,r)),o=b(m(i,r,e)),a=b(m(i,r,t));return s!==n&&o!==a||!(0!==s||!x(e,i,t))||!(0!==n||!x(e,r,t))||!(0!==o||!x(i,e,r))||!(0!==a||!x(i,t,r))}function x(e,t,i){return t.x<=Math.max(e.x,i.x)&&t.x>=Math.min(e.x,i.x)&&t.y<=Math.max(e.y,i.y)&&t.y>=Math.min(e.y,i.y)}function b(e){return e>0?1:e<0?-1:0}function S(e,t){return m(e.prev,e,e.next)<0?m(e,t,e.next)>=0&&m(e,e.prev,t)>=0:m(e,t,e.prev)<0||m(e,e.next,t)<0}function T(e,t){var i=new E(e.i,e.x,e.y),r=new E(t.i,t.x,t.y),s=e.next,n=t.prev;return e.next=t,t.prev=e,i.next=s,s.prev=i,r.next=i,i.prev=r,n.next=r,r.prev=n,r}function C(e,t,i,r){var s=new E(e,t,i);return r?(s.next=r.next,s.prev=r,r.next.prev=s,r.next=s):(s.prev=s,s.next=s),s}function y(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function E(e,t,i){this.i=e,this.x=t,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function P(e,t,i,r){for(var s=0,n=t,o=i-r;n0&&(r+=e[s-1].length,i.holes.push(r))}return i}},34258:e=>{e.exports=function(){var e={},t=this,i=(new Function("try {return this===window;}catch(e){ return false;}"),new Function("try {return this===global;}catch(e){return false;}")),r=new Function("try {return typeof importScripts === 'function';}catch(e){return false;}");if(i()&&r(),i()||r()){var s=t;if(r()){onmessage=function(e){if(e.data.className&&e.data.methodName){var i=(r=e.data.className,s=e.data.methodName,n=t,r.split(".").forEach((function(e){n&&(n=n[e])})),n?n[s]:null);if(!i)return console.error("could not find "+e.data.className+"."+e.data.methodName);postMessage({result:i.apply(null,e.data.args),id:e.data.id})}var r,s,n}}}return function(e,t,i){"use strict";t.geom=t.geom||{},t.exe=t.exe||{},t.eval=t.eval||{},t.core=t.core||{},t.promhx=t.promhx||{};var r={},s=function(){return A.__string_rec(this,"")};function n(e,t){function i(){}i.prototype=e;var r=new i;for(var s in t)r[s]=t[s];return t.toString!==Object.prototype.toString&&(r.toString=t.toString),r}var o=function(){};r.HxOverrides=o,o.__name__=["HxOverrides"],o.strDate=function(e){switch(e.length){case 8:var t=e.split(":"),i=new Date;return i.setTime(0),i.setUTCHours(t[0]),i.setUTCMinutes(t[1]),i.setUTCSeconds(t[2]),i;case 10:var r=e.split("-");return new Date(r[0],r[1]-1,r[2],0,0,0);case 19:var s=e.split(" "),n=s[0].split("-"),o=s[1].split(":");return new Date(n[0],n[1]-1,n[2],o[0],o[1],o[2]);default:throw new P("Invalid date format : "+e)}},o.cca=function(e,t){var i=e.charCodeAt(t);if(i==i)return i},o.substr=function(e,t,i){return null!=t&&0!=t&&null!=i&&i<0?"":(null==i&&(i=e.length),t<0?(t=e.length+t)<0&&(t=0):i<0&&(i=e.length+i-t),e.substr(t,i))},o.iter=function(e){return{cur:0,arr:e,hasNext:function(){return this.cur0&&(1==n?this.buf.b+="n":(this.buf.b+="u",this.buf.b+=null==n?"null":""+n),n=0),this.serialize(e[d]))}n>0&&(1==n?this.buf.b+="n":(this.buf.b+="u",this.buf.b+=null==n?"null":""+n)),this.buf.b+="h";break;case l:this.buf.b+="l";for(var f=e.h,_=null;null!=f;){var m;_=f[0],f=f[1],m=_,this.serialize(m)}this.buf.b+="h";break;case Date:var v=e;this.buf.b+="v",this.buf.add(v.getTime());break;case T:this.buf.b+="b";for(var S=e,y=S.keys();y.hasNext();){var E=y.next();this.serializeString(E),this.serialize(null!=_t[E]?S.getReserved(E):S.h[E])}this.buf.b+="h";break;case x:this.buf.b+="q";for(var R=e,I=R.keys();I.hasNext();){var M=I.next();this.buf.b+=":",this.buf.b+=null==M?"null":""+M,this.serialize(R.h[M])}this.buf.b+="h";break;case b:this.buf.b+="M";for(var O=e,D=O.keys();D.hasNext();){var w=D.next(),N=h.field(w,"__id__");h.deleteField(w,"__id__"),this.serialize(w),w.__id__=N,this.serialize(O.h[w.__id__])}this.buf.b+="h";break;case C:for(var F=e,L=0,B=F.length-2,V=new u,k=g.BASE64;L>2)),V.add(k.charAt(63&(U<<4|G>>4))),V.add(k.charAt(63&(G<<2|z>>6))),V.add(k.charAt(63&z))}if(L==B){var W=F.get(L++),H=F.get(L++);V.add(k.charAt(W>>2)),V.add(k.charAt(63&(W<<4|H>>4))),V.add(k.charAt(H<<2&63))}else if(L==B+1){var X=F.get(L++);V.add(k.charAt(X>>2)),V.add(k.charAt(X<<4&63))}var q=V.b;this.buf.b+="s",null==q.length?this.buf.b+="null":this.buf.b+=""+q.length,this.buf.b+=":",this.buf.b+=null==q?"null":""+q;break;default:this.useCache&&this.cache.pop(),null!=e.hxSerialize?(this.buf.b+="C",this.serializeString(p.getClassName(s)),this.useCache&&this.cache.push(e),e.hxSerialize(this),this.buf.b+="g"):(this.buf.b+="c",this.serializeString(p.getClassName(s)),this.useCache&&this.cache.push(e),this.serializeFields(e))}break;case 4:if(A.__instanceof(e,ft)){var Y=p.getClassName(e);this.buf.b+="A",this.serializeString(Y)}else if(A.__instanceof(e,pt))this.buf.b+="B",this.serializeString(p.getEnumName(e));else{if(this.useCache&&this.serializeRef(e))return;this.buf.b+="o",this.serializeFields(e)}break;case 7:var K=t[2];if(this.useCache){if(this.serializeRef(e))return;this.cache.pop()}this.useEnumIndex?this.buf.b+="j":this.buf.b+="w",this.serializeString(p.getEnumName(K)),this.useEnumIndex?(this.buf.b+=":",this.buf.b+=c.string(e[1])):this.serializeString(e[0]),this.buf.b+=":";var j=e.length;this.buf.b+=c.string(j-2);for(var $=2;$57)break;e=10*e+(r-48),this.pos++}else{if(this.pos!=i)break;t=!0,this.pos++}}return t&&(e*=-1),e},readFloat:function(){for(var e=this.pos;;){var t=this.buf.charCodeAt(this.pos);if(!(t>=43&&t<58||101==t||69==t))break;this.pos++}return c.parseFloat(o.substr(this.buf,e,this.pos-e))},unserializeObject:function(e){for(;;){if(this.pos>=this.length)throw new P("Invalid object");if(103==this.buf.charCodeAt(this.pos))break;var t=this.unserialize();if("string"!=typeof t)throw new P("Invalid object key");var i=this.unserialize();e[t]=i}this.pos++},unserializeEnum:function(e,t){if(58!=this.get(this.pos++))throw new P("Invalid enum format");var i=this.readDigits();if(0==i)return p.createEnum(e,t);for(var r=[];i-- >0;)r.push(this.unserialize());return p.createEnum(e,t,r)},unserialize:function(){switch(this.get(this.pos++)){case 110:return null;case 116:return!0;case 102:return!1;case 122:return 0;case 105:return this.readDigits();case 100:return this.readFloat();case 121:var e=this.readDigits();if(58!=this.get(this.pos++)||this.length-this.pos=this.cache.length)throw new P("Invalid reference");return this.cache[a];case 82:var h=this.readDigits();if(h<0||h>=this.scache.length)throw new P("Invalid string reference");return this.scache[h];case 120:throw new P(this.unserialize());case 99:var c=this.unserialize(),u=this.resolver.resolveClass(c);if(null==u)throw new P("Class not found "+c);var f=p.createEmptyInstance(u);return this.cache.push(f),this.unserializeObject(f),f;case 119:var _=this.unserialize(),m=this.resolver.resolveEnum(_);if(null==m)throw new P("Enum not found "+_);var g=this.unserializeEnum(m,this.unserialize());return this.cache.push(g),g;case 106:var S=this.unserialize(),y=this.resolver.resolveEnum(S);if(null==y)throw new P("Enum not found "+S);this.pos++;var E=this.readDigits(),A=p.getEnumConstructs(y)[E];if(null==A)throw new P("Unknown enum index "+S+"@"+E);var R=this.unserializeEnum(y,A);return this.cache.push(R),R;case 108:var I=new l;for(this.cache.push(I),this.buf;104!=this.buf.charCodeAt(this.pos);)I.add(this.unserialize());return this.pos++,I;case 98:var M=new T;for(this.cache.push(M),this.buf;104!=this.buf.charCodeAt(this.pos);){var O=this.unserialize();M.set(O,this.unserialize())}return this.pos++,M;case 113:var D=new x;this.cache.push(D),this.buf;for(var w=this.get(this.pos++);58==w;){var N=this.readDigits();D.set(N,this.unserialize()),w=this.get(this.pos++)}if(104!=w)throw new P("Invalid IntMap format");return D;case 77:var F=new b;for(this.cache.push(F),this.buf;104!=this.buf.charCodeAt(this.pos);){var L=this.unserialize();F.set(L,this.unserialize())}return this.pos++,F;case 118:var B;if(this.buf.charCodeAt(this.pos)>=48&&this.buf.charCodeAt(this.pos)<=57&&this.buf.charCodeAt(this.pos+1)>=48&&this.buf.charCodeAt(this.pos+1)<=57&&this.buf.charCodeAt(this.pos+2)>=48&&this.buf.charCodeAt(this.pos+2)<=57&&this.buf.charCodeAt(this.pos+3)>=48&&this.buf.charCodeAt(this.pos+3)<=57&&45==this.buf.charCodeAt(this.pos+4)){var V=o.substr(this.buf,this.pos,19);B=o.strDate(V),this.pos+=19}else{var k=this.readFloat(),U=new Date;U.setTime(k),B=U}return this.cache.push(B),B;case 115:var G=this.readDigits(),z=this.buf;if(58!=this.get(this.pos++)||this.length-this.pos>2)+(q>=2?q-1:0);for(var Y=X+(G-q),K=C.alloc(H),j=0;X>4);var Z=W[d.fastCodeAt(z,X++)];K.set(j++,Q<<4|Z>>2);var J=W[d.fastCodeAt(z,X++)];K.set(j++,Z<<6|J)}if(q>=2){var ee=W[d.fastCodeAt(z,X++)],te=W[d.fastCodeAt(z,X++)];if(K.set(j++,ee<<2|te>>4),3==q){var ie=W[d.fastCodeAt(z,X++)];K.set(j++,te<<4|ie>>2)}}return this.pos+=G,this.cache.push(K),K;case 67:var re=this.unserialize(),se=this.resolver.resolveClass(re);if(null==se)throw new P("Class not found "+re);var ne=p.createEmptyInstance(se);if(this.cache.push(ne),ne.hxUnserialize(this),103!=this.get(this.pos++))throw new P("Invalid custom data");return ne;case 65:var oe=this.unserialize(),ae=this.resolver.resolveClass(oe);if(null==ae)throw new P("Class not found "+oe);return ae;case 66:var le=this.unserialize(),he=this.resolver.resolveEnum(le);if(null==he)throw new P("Enum not found "+le);return he}throw this.pos--,new P("Invalid char "+this.buf.charAt(this.pos)+" at position "+this.pos)},__class__:v};var x=function(){this.h={}};r["haxe.ds.IntMap"]=x,x.__name__=["haxe","ds","IntMap"],x.__interfaces__=[_],x.prototype={set:function(e,t){this.h[e]=t},remove:function(e){return!!this.h.hasOwnProperty(e)&&(delete this.h[e],!0)},keys:function(){var e=[];for(var t in this.h)this.h.hasOwnProperty(t)&&e.push(0|t);return o.iter(e)},__class__:x};var b=function(){this.h={},this.h.__keys__={}};r["haxe.ds.ObjectMap"]=b,b.__name__=["haxe","ds","ObjectMap"],b.__interfaces__=[_],b.prototype={set:function(e,t){var i=e.__id__||(e.__id__=++b.count);this.h[i]=t,this.h.__keys__[i]=e},keys:function(){var e=[];for(var t in this.h.__keys__)this.h.hasOwnProperty(t)&&e.push(this.h.__keys__[t]);return o.iter(e)},__class__:b};var S=r["haxe.ds.Option"]={__ename__:["haxe","ds","Option"],__constructs__:["Some","None"]};S.Some=function(e){var t=["Some",0,e];return t.__enum__=S,t.toString=s,t},S.None=["None",1],S.None.toString=s,S.None.__enum__=S;var T=function(){this.h={}};r["haxe.ds.StringMap"]=T,T.__name__=["haxe","ds","StringMap"],T.__interfaces__=[_],T.prototype={set:function(e,t){null!=_t[e]?this.setReserved(e,t):this.h[e]=t},get:function(e){return null!=_t[e]?this.getReserved(e):this.h[e]},setReserved:function(e,t){null==this.rh&&(this.rh={}),this.rh["$"+e]=t},getReserved:function(e){return null==this.rh?null:this.rh["$"+e]},keys:function(){var e=this.arrayKeys();return o.iter(e)},arrayKeys:function(){var e=[];for(var t in this.h)this.h.hasOwnProperty(t)&&e.push(t);if(null!=this.rh)for(var t in this.rh)36==t.charCodeAt(0)&&e.push(t.substr(1));return e},__class__:T};var C=function(e){this.length=e.byteLength,this.b=new gt(e),this.b.bufferValue=e,e.hxBytes=this,e.bytes=this.b};r["haxe.io.Bytes"]=C,C.__name__=["haxe","io","Bytes"],C.alloc=function(e){return new C(new mt(e))},C.prototype={get:function(e){return this.b[e]},set:function(e,t){this.b[e]=255&t},__class__:C};var y=r["haxe.io.Error"]={__ename__:["haxe","io","Error"],__constructs__:["Blocked","Overflow","OutsideBounds","Custom"]};y.Blocked=["Blocked",0],y.Blocked.toString=s,y.Blocked.__enum__=y,y.Overflow=["Overflow",1],y.Overflow.toString=s,y.Overflow.__enum__=y,y.OutsideBounds=["OutsideBounds",2],y.OutsideBounds.toString=s,y.OutsideBounds.__enum__=y,y.Custom=function(e){var t=["Custom",3,e];return t.__enum__=y,t.toString=s,t};var E=function(){};r["haxe.io.FPHelper"]=E,E.__name__=["haxe","io","FPHelper"],E.i32ToFloat=function(e){var t=e>>>23&255,i=8388607&e;return 0==i&&0==t?0:(1-(e>>>31<<1))*(1+Math.pow(2,-23)*i)*Math.pow(2,t-127)},E.floatToI32=function(e){if(0==e)return 0;var t;t=e<0?-e:e;var i=Math.floor(Math.log(t)/.6931471805599453);return i<-127?i=-127:i>128&&(i=128),(e<0?-2147483648:0)|i+127<<23|8388607&Math.round(8388608*(t/Math.pow(2,i)-1))},E.i64ToDouble=function(e,t){var i=(t>>20&2047)-1023,r=4294967296*(1048575&t)+2147483648*(e>>>31)+(2147483647&e);return 0==r&&-1023==i?0:(1-(t>>>31<<1))*(1+Math.pow(2,-52)*r)*Math.pow(2,i)},E.doubleToI64=function(e){var t=E.i64tmp;if(0==e)t.low=0,t.high=0;else{var i;i=e<0?-e:e;var r,s=Math.floor(Math.log(i)/.6931471805599453),n=4503599627370496*(i/Math.pow(2,s)-1),o=0|(r=Math.round(n)),a=r/4294967296|0;t.low=o,t.high=(e<0?-2147483648:0)|s+1023<<20|a}return t};var P=function(e){Error.call(this),this.val=e,this.message=String(e),Error.captureStackTrace&&Error.captureStackTrace(this,P)};r["js._Boot.HaxeError"]=P,P.__name__=["js","_Boot","HaxeError"],P.__super__=Error,P.prototype=n(Error.prototype,{__class__:P});var A=function(){};r["js.Boot"]=A,A.__name__=["js","Boot"],A.getClass=function(e){if(e instanceof Array&&null==e.__enum__)return Array;var t=e.__class__;if(null!=t)return t;var i=A.__nativeClassName(e);return null!=i?A.__resolveNativeClass(i):null},A.__string_rec=function(e,t){if(null==e)return"null";if(t.length>=5)return"<...>";var i=typeof e;switch("function"==i&&(e.__name__||e.__ename__)&&(i="object"),i){case"object":if(e instanceof Array){if(e.__enum__){if(2==e.length)return e[0];var r=e[0]+"(";t+="\t";for(var s=2,n=e.length;s0?",":"")+A.__string_rec(e[c],t)}return l+"]"}var u;try{u=e.toString}catch(e){return e instanceof P&&(e=e.val),"???"}if(null!=u&&u!=Object.toString&&"function"==typeof u){var d=e.toString();if("[object Object]"!=d)return d}var f=null,p="{\n";t+="\t";var _=null!=e.hasOwnProperty;for(var f in e)_&&!e.hasOwnProperty(f)||"prototype"!=f&&"__class__"!=f&&"__super__"!=f&&"__interfaces__"!=f&&"__properties__"!=f&&(2!=p.length&&(p+=", \n"),p+=t+f+" : "+A.__string_rec(e[f],t));return p+"\n"+(t=t.substring(1))+"}";case"function":return"";case"string":return e;default:return String(e)}},A.__interfLoop=function(e,t){if(null==e)return!1;if(e==t)return!0;var i=e.__interfaces__;if(null!=i)for(var r=0,s=i.length;re.byteLength)throw new P(y.OutsideBounds)};r["js.html.compat.DataView"]=I,I.__name__=["js","html","compat","DataView"],I.prototype={getInt8:function(e){var t=this.buf.a[this.offset+e];return t>=128?t-256:t},getUint8:function(e){return this.buf.a[this.offset+e]},getInt16:function(e,t){var i=this.getUint16(e,t);return i>=32768?i-65536:i},getUint16:function(e,t){return t?this.buf.a[this.offset+e]|this.buf.a[this.offset+e+1]<<8:this.buf.a[this.offset+e]<<8|this.buf.a[this.offset+e+1]},getInt32:function(e,t){var i=this.offset+e,r=this.buf.a[i++],s=this.buf.a[i++],n=this.buf.a[i++],o=this.buf.a[i++];return t?r|s<<8|n<<16|o<<24:o|n<<8|s<<16|r<<24},getUint32:function(e,t){var i=this.getInt32(e,t);return i<0?i+4294967296:i},getFloat32:function(e,t){return E.i32ToFloat(this.getInt32(e,t))},getFloat64:function(e,t){var i=this.getInt32(e,t),r=this.getInt32(e+4,t);return E.i64ToDouble(t?i:r,t?r:i)},setInt8:function(e,t){this.buf.a[e+this.offset]=t<0?t+128&255:255&t},setUint8:function(e,t){this.buf.a[e+this.offset]=255&t},setInt16:function(e,t,i){this.setUint16(e,t<0?t+65536:t,i)},setUint16:function(e,t,i){var r=e+this.offset;i?(this.buf.a[r]=255&t,this.buf.a[r++]=t>>8&255):(this.buf.a[r++]=t>>8&255,this.buf.a[r]=255&t)},setInt32:function(e,t,i){this.setUint32(e,t,i)},setUint32:function(e,t,i){var r=e+this.offset;i?(this.buf.a[r++]=255&t,this.buf.a[r++]=t>>8&255,this.buf.a[r++]=t>>16&255,this.buf.a[r++]=t>>>24):(this.buf.a[r++]=t>>>24,this.buf.a[r++]=t>>16&255,this.buf.a[r++]=t>>8&255,this.buf.a[r++]=255&t)},setFloat32:function(e,t,i){this.setUint32(e,E.floatToI32(t),i)},setFloat64:function(e,t,i){var r=E.doubleToI64(t);i?(this.setUint32(e,r.low),this.setUint32(e,r.high)):(this.setUint32(e,r.high),this.setUint32(e,r.low))},__class__:I};var M=function(){};r["js.html.compat.Uint8Array"]=M,M.__name__=["js","html","compat","Uint8Array"],M._new=function(e,t,i){var r;if("number"==typeof e){r=[];for(var s=0;si.byteLength)throw new P("set() outside of range");for(var s=0,n=e.byteLength;si.byteLength)throw new P("set() outside of range");for(var l=0,h=a.length;l0||t.handleError(e._errorVal),e._resolved&&!e._pending)try{t.handleResolve(i(e._val))}catch(e){e instanceof P&&(e=e.val),t.handleError(e)}},O.linkAll=function(e,t){for(var i=function(i,r,s){if(0==i.length||O.allFulfilled(i)){for(var n,o=[],a=nt(e)();a.hasNext();){var l=a.next();o.push(l==r?s:l._val)}n=o,t.handleResolve(n)}},r=nt(e)();r.hasNext();){var s=r.next();s._update.push({async:t,linkf:function(e,t,i){return function(r){e(t,i,r)}}(i,function(t){for(var i=[],r=nt(e)();r.hasNext();){var n=r.next();n!=s&&i.push(n)}return i}(),s)})}O.allFulfilled(e)&&t.handleResolve(function(t){for(var i=[],r=nt(e)();r.hasNext();){var s=r.next();i.push(s._val)}return i}())},O.pipeLink=function(e,t,i){var r=!1,s=function(e){if(!r){r=!0;var s=i(e);s._update.push({async:t,linkf:lt(t,t.handleResolve)}),O.immediateLinkUpdate(s,t,(function(e){return e}))}};if(e._update.push({async:t,linkf:s}),e._resolved&&!e._pending)try{s(e._val)}catch(e){e instanceof P&&(e=e.val),t.handleError(e)}},O.allResolved=function(e){for(var t=nt(e)();t.hasNext();)if(!t.next()._resolved)return!1;return!0},O.allFulfilled=function(e){for(var t=nt(e)();t.hasNext();)if(!t.next()._fulfilled)return!1;return!0},O.prototype={catchError:function(e){return this._error.push(e),this},errorThen:function(e){return this._errorMap=e,this},isResolved:function(){return this._resolved},isErrored:function(){return this._errored},isErrorHandled:function(){return this._error.length>0},isErrorPending:function(){return this._errorPending},isFulfilled:function(){return this._fulfilled},isPending:function(){return this._pending},handleResolve:function(e){this._resolve(e)},_resolve:function(e){var t,i,r=this;this._pending?L.enqueue((t=lt(this,this._resolve),i=e,function(){t(i)})):(this._resolved=!0,this._pending=!0,L.queue.add((function(){r._val=e;for(var t=0,i=r._update;t0)for(var i=0,r=t._error;i0))throw new P(e);for(var n=0,o=t._update;n0&&null!=(t=L.queue.pop());)t();return L.queue.isEmpty()},L.clear=function(){L.queue=new l},L.f=function(){var e=L.queue.pop();null!=e&&e(),L.queue.isEmpty()||L.continueOnNextLoop()},L.continueOnNextLoop=function(){null!=L.nextLoop?L.nextLoop(L.f):setImmediate(L.f)};var B=r["promhx.error.PromiseError"]={__ename__:["promhx","error","PromiseError"],__constructs__:["AlreadyResolved","DownstreamNotFullfilled"]};B.AlreadyResolved=function(e){var t=["AlreadyResolved",0,e];return t.__enum__=B,t.toString=s,t},B.DownstreamNotFullfilled=function(e){var t=["DownstreamNotFullfilled",1,e];return t.__enum__=B,t.toString=s,t};var V=function(){};r["verb.Verb"]=V,V.__name__=["verb","Verb"],V.main=function(){e.log("verb 2.1.0")};var k=function(){};r["verb.core.ArrayExtensions"]=k,k.__name__=["verb","core","ArrayExtensions"],k.alloc=function(e,t){if(!(t<0))for(;e.length0;){for(var r=e.pop(),s=!0,n=0;ne)return 0;if(t>e-t&&(t=e-t),U.memo_exists(e,t))return U.get_memo(e,t);for(var i=1,r=e,s=1,n=t+1;se)return 0;t>e-t&&(t=e-t);for(var i=1,r=1,s=t+1;r=l&&o<=h||a>=l&&a<=h||l>=o&&l<=a||h>=o&&h<=a},G.prototype={fromPoint:function(e){return new G([e])},add:function(e){if(!this.initialized)return this.dim=e.length,this.min=e.slice(0),this.max=e.slice(0),this.initialized=!0,this;for(var t=0,i=this.dim;tthis.max[r]&&(this.max[r]=e[r]),e[r]e&&(e=n,t=s)}return t},getAxisLength:function(e){return e<0||e>this.dim-1?0:Math.abs(this.min[e]-this.max[e])},intersect:function(e,t){if(!this.initialized)return null;var i=this.min,r=this.max,s=e.min,n=e.max;if(!this.intersects(e,t))return null;for(var o=[],a=[],l=0,h=this.dim;l0?1:-1})),r=Math.floor(e.length/2),(s=new ue(e[r],n,i)).left=this.buildTree(e.slice(0,r),t+1,s),s.right=this.buildTree(e.slice(r+1),t+1,s),s)},nearest:function(e,t,i){var r,s=this,n=new he((function(e){return-e.item1})),o=null;r=o=function(i){for(var r,a,l,h,c=i.dimension,u=s.distanceFunction(e,i.kdPoint.point),d=[],f=0,p=s.dim;ft&&n.pop()},m=0,g=s.dim;m0&&(this.content[0]=t,this.sinkDown(0)),e},peek:function(){return this.content[0]},remove:function(e){for(var t=this.content.length,i=0;i0;){var i=Math.floor((e+1)/2)-1,r=this.content[i];if(!(this.scoreFunction(t)=0;){for(o=[],a=e[c],d=s-1;d>=0;){for(l=a[r-1]*t[r-1][d],u=r-2;u>=1;)h=u-1,l+=a[u]*t[u][d]+a[h]*t[h][d],u-=2;0==u&&(l+=a[0]*t[0][d]),o[d]=l,d--}n[c]=o,c--}return n},ge.add=function(e,t){for(var i=[],r=0,s=e.length;r=0;){for(n=a[i],r=i+1;rr?1:-1}));for(var l=[],h=0,c=s.length;h=.1*m*n||isNaN(u));)m*=.5,++x;if(m*g20)throw new P("Numerical gradient fails");if(d[m]=t[m]+g,s=e(d),d[m]=t[m]-g,n=e(d),d[m]=t[m],isNaN(s)||isNaN(n))g/=16;else{if(f[m]=(s-n)/(2*g),o=t[m]-g,a=t[m],l=t[m]+g,h=(s-r)/g,c=(r-n)/g,u=Pe.max([Math.abs(f[m]),Math.abs(r),Math.abs(s),Math.abs(n),Math.abs(o),Math.abs(a),Math.abs(l),1e-8]),!(Math.min(Pe.max([Math.abs(h-f[m]),Math.abs(c-f[m]),Math.abs(h-c)])/u,g/u)>.001))break;g/=16}}return f},Se.tensor=function(e,t){for(var i,r,s=e.length,n=t.length,o=[],a=s-1;a>=0;){i=[],r=e[a];for(var l=n-1;l>=3;)i[l]=r*t[l],i[--l]=r*t[l],i[--l]=r*t[l],i[--l]=r*t[l],--l;for(;l>=0;)i[l]=r*t[l],--l;o[a]=i,a--}return o};var Te=function(e,t,i,r,s,n){this.solution=e,this.value=t,this.gradient=i,this.invHessian=r,this.iterations=s,this.message=n};r["verb.core.MinimizationResult"]=Te,Te.__name__=["verb","core","MinimizationResult"],Te.prototype={__class__:Te};var Ce=function(){};r["verb.core.ISerializable"]=Ce,Ce.__name__=["verb","core","ISerializable"],Ce.prototype={__class__:Ce};var ye=t.core.Deserializer=function(){};r["verb.core.Deserializer"]=ye,ye.__name__=["verb","core","Deserializer"],ye.deserialize=function(e){return new v(e).unserialize()};var Ee=t.core.Trig=function(){};r["verb.core.Trig"]=Ee,Ee.__name__=["verb","core","Trig"],Ee.isPointInPlane=function(e,t,i){return Math.abs(Pe.dot(Pe.sub(e,t.origin),t.normal))o?{u:s,pt:i}:{u:r+(s-r)*c/o,pt:Pe.add(a,Pe.mul(c,l))}};var Pe=t.core.Vec=function(){};r["verb.core.Vec"]=Pe,Pe.__name__=["verb","core","Vec"],Pe.angleBetween=function(e,t){return Math.acos(Pe.dot(e,t)/(Pe.norm(e)*Pe.norm(t)))},Pe.positiveAngleBetween=function(e,t,i){var r=Pe.cross(e,t),s=Pe.norm(e)*Pe.norm(t),n=Pe.dot(e,t),o=Pe.norm(r)/s,a=n/s,l=Math.atan2(o,a),h=Pe.dot(i,r);return Math.abs(h)0?l:-l},Pe.signedAngleBetween=function(e,t,i){var r=Pe.cross(e,t),s=Pe.norm(e)*Pe.norm(t),n=Pe.dot(e,t),o=Pe.norm(r)/s,a=n/s,l=Math.atan2(o,a);return Pe.dot(i,r)>0?l:2*Math.PI-l},Pe.angleBetweenNormalized2d=function(e,t){var i=e[0]*t[1]-e[1]*t[0];return Math.atan2(i,Pe.dot(e,t))},Pe.domain=function(e){return k.last(e)-k.first(e)},Pe.range=function(e){for(var t=[],i=0,r=0;rt&&i>0)return[];if(t>e&&i<0)return[];for(var r=[],s=e;s<=t;)r.push(s),s+=i;return r},Pe.neg=function(e){return e.map((function(e){return-e}))},Pe.min=function(e){return a.fold(e,(function(e,t){return Math.min(e,t)}),1/0)},Pe.max=function(e){return a.fold(e,(function(e,t){return Math.max(e,t)}),-1/0)},Pe.all=function(e){return a.fold(e,(function(e,t){return t&&e}),!0)},Pe.finite=function(e){return e.map((function(e){return isFinite(e)}))},Pe.onRay=function(e,t,i){return Pe.add(e,Pe.mul(i,t))},Pe.lerp=function(e,t,i){return Pe.add(Pe.mul(e,t),Pe.mul(1-e,i))},Pe.normalized=function(e){return Pe.div(e,Pe.norm(e))},Pe.cross=function(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]},Pe.dist=function(e,t){return Pe.norm(Pe.sub(e,t))},Pe.distSquared=function(e,t){return Pe.normSquared(Pe.sub(e,t))},Pe.sum=function(e){return a.fold(e,(function(e,t){return t+e}),0)},Pe.addAll=function(e){var t=nt(e)();if(!t.hasNext())return null;var i=t.next().length;return a.fold(e,(function(e,t){return Pe.add(t,e)}),Pe.rep(i,0))},Pe.addAllMutate=function(e){for(var t=e[0],i=1,r=e.length;iz.TOLERANCE)return!1}return!0},Pe.sortedSetUnion=function(e,t){for(var i=[],r=0,s=0;r=e.length)i.push(t[s]),s++;else if(s>=t.length)i.push(e[r]),r++;else{var n=e[r]-t[s];Math.abs(n)0?(i.push(t[s]),s++):(i.push(e[r]),r++)}return i},Pe.sortedSetSub=function(e,t){for(var i=[],r=0,s=0;r=t.length?(i.push(e[r]),r++):Math.abs(e[r]-t[s])z.EPSILON&&(i=new Re(s,0),t.push(i)),i.inc()}return t},Ae.isRationalSurfaceClosed=function(e,t){var i;null==t&&(t=!0);for(var r=0,s=(i=t?e.controlPoints:ge.transpose(e.controlPoints))[0].length;rh&&(P=d?[l+(P[0]-h),P[1]]:[h-z.EPSILON,P[1]]),P[1]u&&(P=f?[P[0],c+(P[0]-u)]:[P[0],u-z.EPSILON]),Pe.norm(Pe.mul(P[0]-s[0],i[1][0]))+Pe.norm(Pe.mul(P[1]-s[1],i[0][1]))x&&(P=b?v+(P-x):x),Pe.norm(Pe.mul(P-S,p[1]))(s=null!=r?r:Ae.rationalBezierCurveArcLength(e)))return k.last(e.knots);var n,o=e.knots[0],a=0,l=k.last(e.knots),h=s,c=0,u=0;for(n=null!=i?i:2*z.TOLERANCE;h-a>n;)c=(o+l)/2,(u=Ae.rationalBezierCurveArcLength(e,c))>t?(l=c,h=u):(o=c,a=u);return(o+l)/2},Ae.rationalCurveArcLength=function(e,t,i){null==i&&(i=16),null==t&&(t=k.last(e.knots));for(var r=Fe.decomposeCurveIntoBeziers(e),s=0,n=r[0],o=0;sz.EPSILON)return!1}i=k.last(e);for(var o=e.length-t-1,a=e.length;oz.EPSILON)return!1}return Ie.isNonDecreasing(e)},Ie.isNonDecreasing=function(e){for(var t=k.first(e),i=0,r=e.length;is)return n;for(var o,a=t,l=0,h=a,c=0,u=0;l=t[l+1];)l++;o.push(l),n.push(De.basisFunctionsGivenKnotSpanIndex(l,a,e,t)),a+=s}return new Q(o,n)},De.regularlySpacedDerivativeBasisFunctions=function(e,t,i){for(var r=t.length-e-2,s=(k.last(t)-t[0])/i,n=[],o=[],a=t[0],l=De.knotSpanGivenN(r,e,a,t),h=i+1,c=0;c=t[l+1];)l++;o.push(l),n.push(De.derivativeBasisFunctionsGivenNI(l,a,e,r,t)),a+=s}return new Q(o,n)},De.surfacePointGivenBasesKnotSpans=function(e,t,i,r,s,n,o,a){for(var l,h=Pe.zeros1d(a),c=r-e,u=s-t,d=0,f=t+1;d=M&&(m[v][0]=m[g][0]/n[S+1][b],x=m[v][0]*n[b][S]);for(var O=b>=-1?1:-b,D=1+(A-1<=S?M-1:i-A);Or[e+1]-z.EPSILON)return e;if(i=r[o+1];)iz.EPSILON})),(function(e,t){var i=Pe.sub(e.min.uv0,t.min.uv0),r=Pe.dot(i,i),s=Pe.sub(e.max.uv0,t.max.uv0),n=Pe.dot(s,s),o=Pe.sub(e.min.uv0,t.max.uv0),a=Pe.dot(o,o),l=Pe.sub(e.max.uv0,t.min.uv0),h=Pe.dot(l,l);return r0&&(_.push(_[_.length-1].opp),u.push(_))}if(0==c.length&&s.length>0&&(f||d0;){var o=r.pop(),a=s.pop();if(!o.empty()&&!a.empty()&&o.boundingBox().intersects(a.boundingBox(),i)){var l=o.indivisible(i),h=a.indivisible(i);if(l&&h)n.push(new Q(o.yield(),a.yield()));else if(!l||h)if(l||!h){var c=o.split(),u=a.split();r.push(c.item1),s.push(u.item1),r.push(c.item1),s.push(u.item0),r.push(c.item0),s.push(u.item1),r.push(c.item0),s.push(u.item0)}else{var d=o.split();r.push(d.item1),s.push(a),r.push(d.item0),s.push(a)}else{var f=a.split();r.push(o),s.push(f.item1),r.push(o),s.push(f.item0)}}}return n},we.curves=function(e,t,i){var r=we.boundingBoxTrees(new fe(e),new fe(t),0);return k.unique(r.map((function(r){return we.curvesWithEstimate(e,t,k.first(r.item0.knots),k.first(r.item1.knots),i)})).filter((function(e){return Pe.distSquared(e.point0,e.point1)h[f]+z.EPSILON||((null==c||vu.u)&&(u=new ne(v,Pe.onRay(e.origin,e.dir,v),Pe.onRay(n[f],o[f],g/h[f]))))}}return null==u||null==c?null:new Z(c,u)},we.mergeTriangleClipIntervals=function(e,t,i,r,s,n){if(t.min.u>e.max.u+z.EPSILON||e.min.u>t.max.u+z.EPSILON)return null;var o,a;o=e.min.u>t.min.u?new Q(e.min,0):new Q(t.min,1),a=e.max.uc&&(h=1,c=u),d>c&&(h=2,c=d),0==h?(n=t[1],o=t[2],a=r[1],l=r[2]):1==h?(n=t[0],o=t[2],a=r[0],l=r[2]):(n=t[0],o=t[1],a=r[0],l=r[1]);var f=-Pe.dot(e,t),p=-Pe.dot(i,r),_=n*l-o*a,m=(o*p-f*l)/_,g=(f*a-n*p)/_;return new X(0==h?[0,m,g]:1==h?[m,0,g]:[m,g,0],Pe.normalized(s))},we.threePlanes=function(e,t,i,r,s,n){var o=Pe.cross(i,s),a=Pe.dot(e,o);if(Math.abs(a)1)return null;var _=Pe.add(e,Pe.mul(p,c)),m=Pe.dot(a,l),g=Pe.dot(a,a),v=Pe.dot(l,l),x=Pe.sub(_,s),b=Pe.dot(x,a),S=Pe.dot(x,l),T=m*m-g*v;if(Math.abs(T)1+z.EPSILON||y>1+z.EPSILON||y<-z.EPSILON||C<-z.EPSILON||C+y>1+z.EPSILON?null:new se(_,C,y,p)},we.segmentAndPlane=function(e,t,i,r){var s=Pe.dot(r,Pe.sub(t,e));if(Math.abs(s)1+z.EPSILON||n<-z.EPSILON?null:{p:n}};var Ne=t.eval.Make=function(){};r["verb.eval.Make"]=Ne,Ne.__name__=["verb","eval","Make"],Ne.rationalTranslationalSurface=function(e,t){for(var i=De.rationalCurvePoint(t,k.first(t.knots)),r=k.first(t.knots),s=k.last(t.knots),n=2*t.controlPoints.length,o=(s-r)/(n-1),a=[],l=0;l=0&&(u-=n[o].mult),c=u>0?Fe.surfaceKnotRefine(e,Pe.rep(u,t),i):e;var d=De.knotSpan(s,t,r);return Math.abs(t-k.first(r))e.length-1&&(t=e.length-1);for(var r=e[0].knots,s=[],n=[],o=0,a=e[0].controlPoints.length;oz.EPSILON&&(E=Pe.mul(1/P,E),A=Pe.mul(1/P,A)),m[0][C]=o[C];var R=o[C];g[0][C]=a[C];for(var I=A,M=0,O=1,D=s+1;Ot?e:t},Fe.curveElevateDegree=function(e,t){if(t<=e.degree)return e;var i=e.knots.length-e.degree-2,r=e.degree,s=e.knots,n=e.controlPoints,o=t-e.degree,a=e.controlPoints[0].length,l=Pe.zeros2d(r+o+1,r+1),h=[],c=[],u=[],d=i+r+1,f=t,p=Math.floor(f/2),_=[],m=[];l[0][0]=1,l[f][r]=1;for(var g=1,v=p+1;g0?Math.floor((j+2)/2):1,X=D>0?Math.floor(f-(D+1)/2):f,D>0){for(var $=K-L,Q=[],Z=r;Z>Y;)Q[Z-Y-1]=$/(s[w+Z]-L),Z--;for(var J=1,ee=D+1;J=re;)h[se]=Pe.add(Pe.mul(Q[se-re],h[se]),Pe.mul(1-Q[se-re],h[se-1])),se--;u[ie]=h[r]}}for(var ne=H,oe=f+1;ne1)for(var de=O-2,fe=O,pe=K-L,_e=(K-m[O-1])/pe,me=1;mege;){if(ve=H){if(xe-ge<=O-f+j){var Te=(K-m[xe-ge])/pe;c[be]=Pe.lerp(Te,c[be],c[be+1])}}else c[be]=Pe.lerp(_e,c[be],c[be+1]);ve+=1,xe-=1,be-=1}de-=1,fe+=1}if(w!=r)for(var Ce=0,ye=f-j;Ce=0;){for(;t[P]<=s[y]&&y>l;)c[E-i-1]=r[y-i-1],u[E]=s[y],E-=1,y-=1;c[E-i-1]=c[E-i];for(var A=1,R=i+1;Ar||!Ee.threePointsAreFlat(n,l,o,r)){var u=t+.5*(i-t),d=Le.rationalCurveAdaptiveSampleRange(e,t,u,r,s),f=Le.rationalCurveAdaptiveSampleRange(e,u,i,r,s);return d.slice(0,-1).concat(f)}return s?[[t].concat(n),[i].concat(o)]:[n,o]},Le.rationalSurfaceNaive=function(e,t,i){t<1&&(t=1),i<1&&(i=1),e.degreeU,e.degreeV,e.controlPoints;for(var r=e.knotsU,s=e.knotsV,n=(k.last(r)-r[0])/t,o=(k.last(s)-s[0])/i,a=[],l=[],h=[],c=0,u=t+1;cs?t.minDivsU=t.minDivsU:t.minDivsU=s,r=t.minDivsV>n?t.minDivsV=t.minDivsV:t.minDivsV=n;for(var o=k.last(e.knotsU),a=e.knotsU[0],l=k.last(e.knotsV),h=e.knotsV[0],c=(o-a)/i,u=(l-h)/r,d=[],f=[],p=0,_=r+1;p<_;){for(var m=p++,g=[],v=0,x=i+1;vn.corners[0].uv[0]+s&&e.uv[0]n.corners[0].uv[1]+s&&e.uv[1]=e.maxDepth)return!1;if(this.hasBadNormals())return this.fixNormals(),!1;if(this.splitVert=Pe.normSquared(Pe.sub(this.corners[0].normal,this.corners[1].normal))>e.normTol||Pe.normSquared(Pe.sub(this.corners[2].normal,this.corners[3].normal))>e.normTol,this.splitHoriz=Pe.normSquared(Pe.sub(this.corners[1].normal,this.corners[2].normal))>e.normTol||Pe.normSquared(Pe.sub(this.corners[3].normal,this.corners[0].normal))>e.normTol,this.splitVert||this.splitHoriz)return!0;var i=this.center();return Pe.normSquared(Pe.sub(i.normal,this.corners[0].normal))>e.normTol||Pe.normSquared(Pe.sub(i.normal,this.corners[1].normal))>e.normTol||Pe.normSquared(Pe.sub(i.normal,this.corners[2].normal))>e.normTol||Pe.normSquared(Pe.sub(i.normal,this.corners[3].normal))>e.normTol},divide:function(e){null==e&&(e=new Be),null==e.normTol&&(e.normTol=.085),null==e.minDepth&&(e.minDepth=0),null==e.maxDepth&&(e.maxDepth=10),this._divide(e,0,!0)},_divide:function(e,t,i){if(this.evalCorners(),this.shouldDivide(e,t)){if(t++,this.splitVert&&!this.splitHoriz?i=!1:!this.splitVert&&this.splitHoriz&&(i=!0),this.horizontal=i,this.horizontal){var r=[this.corners[0],this.corners[1],this.midpoint(1),this.midpoint(3)],s=[this.midpoint(3),this.midpoint(1),this.corners[2],this.corners[3]];this.children=[new Ve(this.srf,r),new Ve(this.srf,s)],this.children[0].neighbors=[this.neighbors[0],this.neighbors[1],this.children[1],this.neighbors[3]],this.children[1].neighbors=[this.children[0],this.neighbors[1],this.neighbors[2],this.neighbors[3]]}else{var n=[this.corners[0],this.midpoint(0),this.midpoint(2),this.corners[3]],o=[this.midpoint(0),this.corners[1],this.corners[2],this.midpoint(2)];this.children=[new Ve(this.srf,n),new Ve(this.srf,o)],this.children[0].neighbors=[this.neighbors[0],this.children[1],this.neighbors[2],this.neighbors[3]],this.children[1].neighbors=[this.neighbors[0],this.neighbors[1],this.neighbors[2],this.children[0]]}for(var a=0,l=this.children;a0&&this._pool.length>0;){var i=this._queue.shift(),r=[i.id],s=[this._pool.shift()];this._working.h[r[0]]=s[0],s[0].onmessage=function(i,r){return function(s){t._working.remove(r[0]),t._pool.push(i[0]);try{t._callbacks.h.hasOwnProperty(r[0])&&(t._callbacks.h[r[0]](s.data.result),t._callbacks.remove(r[0]))}catch(t){t instanceof P&&(t=t.val),e.log(t)}t.processQueue()}}(s,r),s[0].postMessage(i)}},__class__:Ue};var Ge=function(e,t,i){this.className=e,this.methodName=t,this.args=i,this.id=Ge.uuid++};r["verb.exe._WorkerPool.Work"]=Ge,Ge.__name__=["verb","exe","_WorkerPool","Work"],Ge.prototype={__class__:Ge};var ze=function(){};r["verb.geom.ICurve"]=ze,ze.__name__=["verb","geom","ICurve"],ze.__interfaces__=[Ce],ze.prototype={__class__:ze};var We=t.geom.NurbsCurve=function(e){this._data=Ie.isValidNurbsCurveData(e)};r["verb.geom.NurbsCurve"]=We,We.__name__=["verb","geom","NurbsCurve"],We.__interfaces__=[ze],We.byKnotsControlPointsWeights=function(e,t,i,r){return new We(new q(e,t.slice(),De.homogenize1d(i,r)))},We.byPoints=function(e,t){return null==t&&(t=3),new We(Ne.rationalInterpCurve(e,t))},We.__super__=W,We.prototype=n(W.prototype,{degree:function(){return this._data.degree},knots:function(){return this._data.knots.slice(0)},controlPoints:function(){return De.dehomogenize1d(this._data.controlPoints)},weights:function(){return De.weight1d(this._data.controlPoints)},asNurbs:function(){return new q(this.degree(),this.knots(),De.homogenize1d(this.controlPoints(),this.weights()))},clone:function(){return new We(this._data)},domain:function(){return new Z(k.first(this._data.knots),k.last(this._data.knots))},transform:function(e){return new We(Fe.rationalCurveTransform(this._data,e))},transformAsync:function(e){return ke.dispatchMethod(Fe,"rationalCurveTransform",[this._data,e]).then((function(e){return new We(e)}))},point:function(e){return De.rationalCurvePoint(this._data,e)},pointAsync:function(e){return ke.dispatchMethod(De,"rationalCurvePoint",[this._data,e])},tangent:function(e){return De.rationalCurveTangent(this._data,e)},tangentAsync:function(e){return ke.dispatchMethod(De,"rationalCurveTangent",[this._data,e])},derivatives:function(e,t){return null==t&&(t=1),De.rationalCurveDerivatives(this._data,e,t)},derivativesAsync:function(e,t){return null==t&&(t=1),ke.dispatchMethod(De,"rationalCurveDerivatives",[this._data,e,t])},closestPoint:function(e){return Ae.rationalCurveClosestPoint(this._data,e)},closestPointAsync:function(e){return ke.dispatchMethod(Ae,"rationalCurveClosestPoint",[this._data,e])},closestParam:function(e){return Ae.rationalCurveClosestParam(this._data,e)},closestParamAsync:function(e){return ke.dispatchMethod(Ae,"rationalCurveClosestParam",[this._data,e])},length:function(){return Ae.rationalCurveArcLength(this._data)},lengthAsync:function(){return ke.dispatchMethod(Ae,"rationalCurveArcLength",[this._data])},lengthAtParam:function(e){return Ae.rationalCurveArcLength(this._data,e)},lengthAtParamAsync:function(){return ke.dispatchMethod(Ae,"rationalCurveArcLength",[this._data])},paramAtLength:function(e,t){return Ae.rationalCurveParamAtArcLength(this._data,e,t)},paramAtLengthAsync:function(e,t){return ke.dispatchMethod(Ae,"rationalCurveParamAtArcLength",[this._data,e,t])},divideByEqualArcLength:function(e){return Me.rationalCurveByEqualArcLength(this._data,e)},divideByEqualArcLengthAsync:function(e){return ke.dispatchMethod(Me,"rationalCurveByEqualArcLength",[this._data,e])},divideByArcLength:function(e){return Me.rationalCurveByArcLength(this._data,e)},divideByArcLengthAsync:function(e){return ke.dispatchMethod(Me,"rationalCurveByArcLength",[this._data,e])},split:function(e){return Me.curveSplit(this._data,e).map((function(e){return new We(e)}))},splitAsync:function(e){return ke.dispatchMethod(Me,"curveSplit",[this._data,e]).then((function(e){return e.map((function(e){return new We(e)}))}))},reverse:function(){return new We(Fe.curveReverse(this._data))},reverseAsync:function(){return ke.dispatchMethod(Fe,"curveReverse",[this._data]).then((function(e){return new We(e)}))},tessellate:function(e){return Le.rationalCurveAdaptiveSample(this._data,e,!1)},tessellateAsync:function(e){return ke.dispatchMethod(Le,"rationalCurveAdaptiveSample",[this._data,e,!1])},__class__:We});var He=t.geom.Arc=function(e,t,i,r,s,n){We.call(this,Ne.arc(e,t,i,r,s,n)),this._center=e,this._xaxis=t,this._yaxis=i,this._radius=r,this._minAngle=s,this._maxAngle=n};r["verb.geom.Arc"]=He,He.__name__=["verb","geom","Arc"],He.__super__=We,He.prototype=n(We.prototype,{center:function(){return this._center},xaxis:function(){return this._xaxis},yaxis:function(){return this._yaxis},radius:function(){return this._radius},minAngle:function(){return this._minAngle},maxAngle:function(){return this._maxAngle},__class__:He});var Xe=t.geom.BezierCurve=function(e,t){We.call(this,Ne.rationalBezierCurve(e,t))};r["verb.geom.BezierCurve"]=Xe,Xe.__name__=["verb","geom","BezierCurve"],Xe.__super__=We,Xe.prototype=n(We.prototype,{__class__:Xe});var qe=t.geom.Circle=function(e,t,i,r){He.call(this,e,t,i,r,0,2*Math.PI)};r["verb.geom.Circle"]=qe,qe.__name__=["verb","geom","Circle"],qe.__super__=He,qe.prototype=n(He.prototype,{__class__:qe});var Ye=function(){};r["verb.geom.ISurface"]=Ye,Ye.__name__=["verb","geom","ISurface"],Ye.__interfaces__=[Ce],Ye.prototype={__class__:Ye};var Ke=t.geom.NurbsSurface=function(e){this._data=Ie.isValidNurbsSurfaceData(e)};r["verb.geom.NurbsSurface"]=Ke,Ke.__name__=["verb","geom","NurbsSurface"],Ke.__interfaces__=[Ye],Ke.byKnotsControlPointsWeights=function(e,t,i,r,s,n){return new Ke(new Y(e,t,i,r,De.homogenize2d(s,n)))},Ke.byCorners=function(e,t,i,r){return new Ke(Ne.fourPointSurface(e,t,i,r))},Ke.byLoftingCurves=function(e,t){return new Ke(Ne.loftedSurface(function(t){for(var i=[],r=0;r{},12439:()=>{},87699:()=>{}},t={};function i(r){var s=t[r];if(void 0!==s)return s.exports;var n=t[r]={exports:{}};return e[r](n,n.exports,i),n.exports}i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};return(()=>{"use strict";i.r(r),i.d(r,{Runner:()=>mZ,fontsEnum:()=>aZ,getRunnerInstance:()=>_Z});var e={};i.r(e),i.d(e,{AbstractActionManager:()=>G.G,AbstractAssetContainer:()=>Qt,AbstractAssetTask:()=>$A,AbstractEngine:()=>Ot.$,AbstractMesh:()=>Nt,AcquireNativeObjectAsync:()=>dh,Action:()=>q,ActionEvent:()=>Y.X,ActionManager:()=>ue,AddAnimationExtensions:()=>me.SM,AddBlock:()=>KT,AddIndividualParser:()=>di,AddParser:()=>ci,AddRayExtensions:()=>Ki,AddressMode:()=>Dh,AdvancedTimer:()=>bd,Aggregations:()=>ZE,AggregatorBlock:()=>PA,AlignBlock:()=>zP,AlphaState:()=>aL.i,AmmoJSPlugin:()=>Yx,AnaglyphArcRotateCamera:()=>xs,AnaglyphFreeCamera:()=>bs,AnaglyphGamepadCamera:()=>Ss,AnaglyphPostProcess:()=>gs,AnaglyphUniversalCamera:()=>Ts,Analyser:()=>ti,AndOrNotEvaluator:()=>jA.Z,Angle:()=>hc.uM,Animatable:()=>me.rT,AnimatedInputBlockTypes:()=>Bg,Animation:()=>pe.X5,AnimationAssetTask:()=>eR,AnimationEvent:()=>we,AnimationGroup:()=>Fe.AnimationGroup,AnimationGroupMask:()=>ke,AnimationGroupMaskMode:()=>Le,AnimationKeyInterpolation:()=>Ne,AnimationPropertiesOverride:()=>ge,AnimationRange:()=>Be.K,AnisotropyBlock:()=>NC,ApplyLut:()=>kb.Kq,ApplyPostProcess:()=>Ac.Qs,Arc2:()=>hc.Xy,ArcFollowCamera:()=>ls,ArcRotateCamera:()=>is,ArcRotateCameraGamepadInput:()=>Er,ArcRotateCameraInputsManager:()=>Or,ArcRotateCameraKeyboardMoveInput:()=>Rr,ArcRotateCameraMouseWheelInput:()=>Ir,ArcRotateCameraPointersInput:()=>Mr,ArcRotateCameraVRDeviceOrientationInput:()=>Dr,ArcTan2Block:()=>gC,AssetContainer:()=>ei,AssetTaskState:()=>NA,AssetsManager:()=>lR,AssetsProgressEvent:()=>QA,AsyncLock:()=>jI,AsyncLoop:()=>Ue.LV,AttachToBoxBehavior:()=>Ii,AudioEngine:()=>ri,AudioSceneComponent:()=>_i,AutoLayoutMode:()=>Wh,AutoReleaseWorkerPool:()=>jy.h,AutoRotationBehavior:()=>Ei,AxesViewer:()=>Wo,Axis:()=>hc._0,AxisDragGizmo:()=>zo,AxisScaleGizmo:()=>J_,BRDFTextureTools:()=>Pm,BabylonFileLoaderConfiguration:()=>tb,BackEase:()=>Se,BackgroundMaterial:()=>xm,BakedVertexAnimationManager:()=>gi,BallAndSocketConstraint:()=>ZM,BaseCameraMouseWheelInput:()=>vr,BaseCameraPointersInput:()=>xr,BaseError:()=>nt.Cf,BaseParticleSystem:()=>nv,BaseSixDofDragBehavior:()=>tr,BaseTexture:()=>js.t,BasisFileInfo:()=>hR.$e,BasisTools:()=>hR.ED,BasisToolsOptions:()=>hR.Sl,BasisTranscodeConfiguration:()=>hR.SV,BezierCurve:()=>hc.vr,BezierCurveEase:()=>Oe,BiPlanarBlock:()=>ZC,BinaryFileAssetTask:()=>iR,BindBonesParameters:()=>Bt.f$,BindFogParameters:()=>Bt.Yy,BindLight:()=>Bt.Kd,BindLightProperties:()=>Bt.L0,BindLights:()=>Bt.RL,BindLogDepth:()=>Bt.DL,BindMorphTargetParameters:()=>Bt.nR,BindSceneUniformBuffer:()=>Bt._8,BindTextureMatrix:()=>Bt.mA,BlackAndWhitePostProcess:()=>PO,BlendFactor:()=>Kh,BlendOperation:()=>jh,BloomEffect:()=>MO,BloomMergePostProcess:()=>IO,BlurPostProcess:()=>_m,Bone:()=>Si.$,BoneAxesViewer:()=>Ho,BoneIKController:()=>dr,BoneLookController:()=>fr,BonesBlock:()=>gS,BooleanGeometryBlock:()=>aA,BooleanGeometryOperations:()=>$E,BounceEase:()=>Te,BouncingBehavior:()=>Pi,BoundingBlock:()=>oA,BoundingBox:()=>ht,BoundingBoxGizmo:()=>tm,BoundingBoxRenderer:()=>yw,BoundingInfo:()=>_t,BoundingInfoHelper:()=>Ao,BoundingSphere:()=>ct,BoxBlock:()=>sP,BoxBuilder:()=>jo,BoxParticleEmitter:()=>sI,Buffer:()=>st.h,BufferBindingType:()=>Bh,BufferMapState:()=>yh,BufferUsage:()=>Eh,CSG:()=>nE,CSG2:()=>VE,Camera:()=>rt,CameraGizmo:()=>pm,CameraInputTypes:()=>br,CameraInputsManager:()=>Sr,CannonJSPlugin:()=>Xx,CanvasAlphaMode:()=>nc,CanvasToneMappingMode:()=>oc,CapsuleBlock:()=>pP,CapsuleBuilder:()=>aa,CascadedShadowGenerator:()=>Cx,ChromaticAberrationPostProcess:()=>OO,CircleEase:()=>be,CircleOfConfusionPostProcess:()=>DO,ClampBlock:()=>$T,CleanGeometryBlock:()=>IP,ClearCoatBlock:()=>LC,ClipPlanesBlock:()=>gT,ClipboardEventTypes:()=>yu,ClipboardInfo:()=>Eu,CloudBlock:()=>KC,CloudPoint:()=>mM,Collider:()=>_o,Color3:()=>hc.v9,Color3Gradient:()=>QR,Color4:()=>hc.ov,ColorConverterBlock:()=>ry,ColorCorrectionPostProcess:()=>wO,ColorCurves:()=>mb.Q,ColorGradient:()=>$R,ColorGradingTexture:()=>Mb,ColorMergerBlock:()=>tC,ColorSplitterBlock:()=>ov,ColorWrite:()=>Yh,CombineAction:()=>oe,CompareFunction:()=>Fh,CompatibilityOptions:()=>Tt.p9,CompilationMessageType:()=>Gh,CompleteGreasedLineColorTable:()=>wE,CompleteGreasedLineWidthTable:()=>DE,CompressionCodes:()=>zb.he,ComputeBindingType:()=>kl,ComputeEffect:()=>Eo,ComputeNormalsBlock:()=>OP,ComputePassTimestampLocation:()=>ec,ComputeShader:()=>Po.H,ComputeShaderBoundingHelper:()=>Io.ComputeShaderBoundingHelper,ComputeShaderParticleSystem:()=>aM,Condition:()=>K,ConditionBlock:()=>yP,ConditionBlockTests:()=>qE,ConditionalBlock:()=>YC,ConditionalBlockConditions:()=>HC,ConeDirectedParticleEmitter:()=>vI,ConeParticleEmitter:()=>gI,Constants:()=>Il,ContainerAssetTask:()=>ZA,ConversionMode:()=>zp,ConvolutionPostProcess:()=>NO,Coordinate:()=>hc.xp,CopyFloatData:()=>Ct,CopyTextureToTexture:()=>Kp,CopyTools:()=>LI.D8,CreateBox:()=>Ko,CreateBoxVertexData:()=>qo,CreateCapsule:()=>oa,CreateCapsuleVertexData:()=>na,CreateCylinder:()=>No,CreateCylinderVertexData:()=>wo,CreateDashedLines:()=>Ia,CreateDashedLinesVertexData:()=>Pa,CreateDecal:()=>ol,CreateDecoderAsync:()=>Wb.d,CreateDisc:()=>da,CreateDiscVertexData:()=>ua,CreateEnvTextureAsync:()=>Wl.Hx,CreateGeodesic:()=>dl,CreateGoldberg:()=>_l,CreateGoldbergVertexData:()=>pl,CreateGreasedLine:()=>ME,CreateGreasedLineMaterial:()=>IE,CreateGround:()=>io,CreateGroundFromHeightMap:()=>so,CreateGroundFromHeightMapVertexData:()=>to,CreateGroundVertexData:()=>Jn,CreateHemisphere:()=>cm,CreateIcoSphere:()=>Qa,CreateIcoSphereVertexData:()=>$a,CreateImageBitmapFromSource:()=>Js,CreateImageDataArrayBufferViews:()=>Wl.$h,CreateLathe:()=>Wa,CreateLineSystem:()=>Aa,CreateLineSystemVertexData:()=>Ea,CreateLines:()=>Ra,CreatePickingRay:()=>Ni,CreatePickingRayInCameraSpace:()=>Li,CreatePickingRayInCameraSpaceToRef:()=>Bi,CreatePickingRayToRef:()=>Fi,CreatePlane:()=>Qi,CreatePlaneVertexData:()=>$i,CreatePolygon:()=>La,CreatePolygonVertexData:()=>Fa,CreatePolyhedron:()=>Ka,CreatePolyhedronVertexData:()=>Ya,CreateResizedCopy:()=>Ac.EE,CreateRibbon:()=>ha,CreateRibbonVertexData:()=>la,CreateScreenshot:()=>zR,CreateScreenshotAsync:()=>WR,CreateScreenshotUsingRenderTarget:()=>XR,CreateScreenshotUsingRenderTargetAsync:()=>qR,CreateScreenshotWithResizeAsync:()=>HR,CreateSegmentedBoxVertexData:()=>Yo,CreateSphere:()=>Qo,CreateSphereVertexData:()=>$o,CreateText:()=>xl,CreateTextShapePaths:()=>vl,CreateTiledBox:()=>va,CreateTiledBoxVertexData:()=>ga,CreateTiledGround:()=>ro,CreateTiledGroundVertexData:()=>eo,CreateTiledPlane:()=>_a,CreateTiledPlaneVertexData:()=>pa,CreateTorus:()=>ao,CreateTorusKnot:()=>Sa,CreateTorusKnotVertexData:()=>ba,CreateTorusVertexData:()=>oo,CreateTube:()=>Xa,CrossBlock:()=>QT,CubeMapToSphericalPolynomialTools:()=>Lx.d,CubeTexture:()=>gm,CubeTextureAssetTask:()=>nR,CubicEase:()=>Ce,CullMode:()=>qh,CurrentScreenBlock:()=>jg,Curve3:()=>hc.jj,CurveBlock:()=>iy,CurveBlockTypes:()=>qC,CustomBlock:()=>ZT,CustomOptimization:()=>CR,CustomParticleEmitter:()=>cI,CustomProceduralTexture:()=>Kb,CylinderBlock:()=>fP,CylinderBuilder:()=>Fo,CylinderDirectedParticleEmitter:()=>mI,CylinderParticleEmitter:()=>_I,DDSTools:()=>cR.DDSTools,DataBuffer:()=>pr.n,DataReader:()=>tI,DataStorage:()=>iI,Database:()=>sM,DebugBlock:()=>ZP,DebugLayer:()=>Xo,DebugLayerTab:()=>Uo,DecalBuilder:()=>al,DecalMapConfiguration:()=>my,DecalMapDefines:()=>_y,Decode:()=>bi.Tq,DecodeBase64ToBinary:()=>bi.yS,DecodeBase64ToString:()=>bi.AV,DecodeBase64UrlToBinary:()=>$m.rz,DecodeBase64UrlToString:()=>$m.dy,DecodeFloat32:()=>zb.Sn,DecodeRunLength:()=>Ub._,DeepCopier:()=>ce.r,DefaultCollisionCoordinator:()=>mo,DefaultKTX2DecoderOptions:()=>MI.$,DefaultLoadingScreen:()=>Nx,DefaultRenderingPipeline:()=>iD,Deferred:()=>uR,DepthCullingState:()=>Gc.N,DepthOfFieldBlurPostProcess:()=>FO,DepthOfFieldEffect:()=>BO,DepthOfFieldEffectBlurLevel:()=>DM,DepthOfFieldMergePostProcess:()=>LO,DepthPeelingRenderer:()=>Aw,DepthPeelingSceneComponent:()=>Rw,DepthReducer:()=>gx,DepthRenderer:()=>px,DepthRendererSceneComponent:()=>Ew,DepthSortedParticle:()=>fM,DerivativeBlock:()=>VS,DesaturateBlock:()=>DC,DetailMapConfiguration:()=>Nn,DeviceInputEventType:()=>gr.b,DeviceLostReason:()=>ac,DeviceOrientationCamera:()=>rs,DeviceSource:()=>Al.c,DeviceSourceManager:()=>Rl.Z,DeviceType:()=>Pl.bq,DirectionalLight:()=>hm,DirectionalLightFrustumViewer:()=>El,DiscBlock:()=>_P,DiscBuilder:()=>fa,DiscardBlock:()=>LS,DisplayPassPostProcess:()=>VO,DistanceBlock:()=>dC,DistanceConstraint:()=>JM,DistanceJoint:()=>ea,DivideBlock:()=>sC,DoNothingAction:()=>ne,DomManagement:()=>ii.Az,DotBlock:()=>JT,DracoCompression:()=>Zy,DragOperation:()=>em,DrawWrapper:()=>gt.E,DualSenseInput:()=>Pl.pI,DualShockButton:()=>Kr,DualShockDpad:()=>jr,DualShockInput:()=>Pl.h8,DualShockPad:()=>cs,DumpTools:()=>UR.DumpTools,DynamicFloat32Array:()=>kI,DynamicTexture:()=>Gn,EXROutputType:()=>Gb.V,EasingFunction:()=>xe,EdgesRenderer:()=>Mw,Effect:()=>Cl.M,EffectFallbacks:()=>Tn,EffectLayer:()=>Lv,EffectLayerSceneComponent:()=>Bv,EffectRenderer:()=>Yp.J,EffectWrapper:()=>Yp.$,ElasticEase:()=>ye,ElbowBlock:()=>$C,EncodeArrayBufferToBase64:()=>bi.EL,EndsWith:()=>bi.jq,Engine:()=>an,EngineFactory:()=>Cu,EngineFormat:()=>rS.GQ,EngineInstrumentation:()=>Nv,EngineStore:()=>he.q,EngineView:()=>Fl,EnvironmentHelper:()=>bm,EnvironmentTextureTools:()=>Wl.qY,Epsilon:()=>hc.bH,EquiRectangularCubeTexture:()=>Db,EquiRectangularCubeTextureAssetTask:()=>aR,ErrorCodes:()=>nt.tG,ErrorFilter:()=>lc,EventConstants:()=>gr.s,EventState:()=>z.qO,ExecuteCodeAction:()=>ae,ExitFullscreen:()=>rn,ExitPointerlock:()=>nn,ExponentialEase:()=>Ee,ExrLoaderGlobalConfiguration:()=>Gb.u,ExternalTexture:()=>Wc,ExtractHighlightsPostProcess:()=>RO,ExtrudePolygon:()=>Ba,ExtrudeShape:()=>ka,ExtrudeShapeCustom:()=>Ua,FactorGradient:()=>ZR,FadeInOutBehavior:()=>Mi,FeatureName:()=>Ch,FileTools:()=>$m.wS,FileToolsOptions:()=>$m.eC,FilesInput:()=>pR,FilesInputStore:()=>fR.T,FilterMode:()=>wh,FilterPostProcess:()=>kO,FixFlippedFaces:()=>mt.Y4,FlowGraph:()=>sd,FlowGraphAbsBlock:()=>pf,FlowGraphAcosBlock:()=>Xf,FlowGraphAcoshBlock:()=>Zf,FlowGraphAddBlock:()=>rf,FlowGraphAsinBlock:()=>Hf,FlowGraphAsinhBlock:()=>Qf,FlowGraphAtan2Block:()=>Yf,FlowGraphAtanBlock:()=>qf,FlowGraphAtanhBlock:()=>Jf,FlowGraphBitwiseAndBlock:()=>gp,FlowGraphBitwiseLeftShiftBlock:()=>bp,FlowGraphBitwiseNotBlock:()=>mp,FlowGraphBitwiseOrBlock:()=>vp,FlowGraphBitwiseRightShiftBlock:()=>Sp,FlowGraphBitwiseXorBlock:()=>xp,FlowGraphBlock:()=>ju,FlowGraphBranchBlock:()=>pd,FlowGraphCeilBlock:()=>vf,FlowGraphClampBlock:()=>Af,FlowGraphConditionalDataBlock:()=>wd,FlowGraphConnection:()=>Ru,FlowGraphConnectionType:()=>Pu,FlowGraphConsoleLogBlock:()=>ld,FlowGraphConstantBlock:()=>Ld,FlowGraphContext:()=>ed,FlowGraphContextLogger:()=>od,FlowGraphCoordinateTransformBlock:()=>Fd,FlowGraphCoordinator:()=>nd,FlowGraphCosBlock:()=>zf,FlowGraphCoshBlock:()=>jf,FlowGraphCountLeadingZerosBlock:()=>Tp,FlowGraphCountOneBitsBlock:()=>yp,FlowGraphCountTrailingZerosBlock:()=>Cp,FlowGraphCounterBlock:()=>Ed,FlowGraphCrossBlock:()=>hp,FlowGraphCubeRootBlock:()=>np,FlowGraphDataConnection:()=>Hu,FlowGraphDebounceBlock:()=>Ad,FlowGraphDegToRadBlock:()=>kf,FlowGraphDeterminantBlock:()=>fp,FlowGraphDivideBlock:()=>of,FlowGraphDoNBlock:()=>_d,FlowGraphDotBlock:()=>lf,FlowGraphEBlock:()=>hf,FlowGraphEqBlock:()=>Of,FlowGraphEventBlock:()=>Ju,FlowGraphExecutionBlock:()=>Qu,FlowGraphExpBlock:()=>ep,FlowGraphFlipFlopBlock:()=>Rd,FlowGraphFloorBlock:()=>gf,FlowGraphForLoopBlock:()=>md,FlowGraphFractBlock:()=>xf,FlowGraphGetPropertyBlock:()=>Bd,FlowGraphGetVariableBlock:()=>Nd,FlowGraphGreaterThanBlock:()=>Ff,FlowGraphGreaterThanOrEqualBlock:()=>Lf,FlowGraphInfBlock:()=>uf,FlowGraphInterpolateBlock:()=>Mf,FlowGraphInvertMatrixBlock:()=>pp,FlowGraphIsInfBlock:()=>Vf,FlowGraphIsNanBlock:()=>Bf,FlowGraphLengthBlock:()=>ap,FlowGraphLessThanBlock:()=>wf,FlowGraphLessThanOrEqualBlock:()=>Nf,FlowGraphLog10Block:()=>rp,FlowGraphLog2Block:()=>ip,FlowGraphLogBlock:()=>tp,FlowGraphLogicAndBlock:()=>Yd,FlowGraphLogicNotBlock:()=>jd,FlowGraphLogicOrBlock:()=>Kd,FlowGraphMatMulBlock:()=>_p,FlowGraphMaxBlock:()=>yf,FlowGraphMeshPickEventBlock:()=>id,FlowGraphMinBlock:()=>Cf,FlowGraphMultiGateBlock:()=>Td,FlowGraphMultiplyBlock:()=>nf,FlowGraphNaNBlock:()=>df,FlowGraphNegBlock:()=>bf,FlowGraphNormalizeBlock:()=>lp,FlowGraphPauseAnimationBlock:()=>Dd,FlowGraphPiBlock:()=>cf,FlowGraphPlayAnimationBlock:()=>Md,FlowGraphPowBlock:()=>op,FlowGraphRadToDegBlock:()=>Uf,FlowGraphRandomBlock:()=>af,FlowGraphReceiveCustomEventBlock:()=>Pp,FlowGraphRemainderBlock:()=>Tf,FlowGraphRotate2DBlock:()=>cp,FlowGraphRotate3DBlock:()=>up,FlowGraphSaturateBlock:()=>If,FlowGraphSceneReadyEventBlock:()=>Ep,FlowGraphSceneTickEventBlock:()=>Ap,FlowGraphSendCustomEventBlock:()=>fd,FlowGraphSequenceBlock:()=>Id,FlowGraphSetPropertyBlock:()=>dd,FlowGraphSetVariableBlock:()=>hd,FlowGraphSignBlock:()=>_f,FlowGraphSignalConnection:()=>$u,FlowGraphSinBlock:()=>Gf,FlowGraphSinhBlock:()=>Kf,FlowGraphSqrtBlock:()=>sp,FlowGraphState:()=>rd,FlowGraphStopAnimationBlock:()=>Od,FlowGraphSubtractBlock:()=>sf,FlowGraphSwitchBlock:()=>Cd,FlowGraphTanBlock:()=>Wf,FlowGraphTanhBlock:()=>$f,FlowGraphThrottleBlock:()=>gd,FlowGraphTimerBlock:()=>Sd,FlowGraphTransposeBlock:()=>dp,FlowGraphTruncBlock:()=>mf,FlowGraphWaitAllBlock:()=>yd,FlowGraphWhileLoopBlock:()=>Pd,FluidRenderer:()=>sN,FluidRendererSceneComponent:()=>rN,FluidRenderingDebug:()=>Yw,FluidRenderingObject:()=>jw,FluidRenderingObjectCustomParticles:()=>Jw,FluidRenderingObjectParticleSystem:()=>$w,FluidRenderingTargetRenderer:()=>Zw,FlyCamera:()=>ns,FlyCameraInputsManager:()=>ss,FlyCameraKeyboardInput:()=>wr,FlyCameraMouseInput:()=>Nr,FogBlock:()=>cT,FollowBehavior:()=>lr,FollowCamera:()=>as,FollowCameraInputsManager:()=>os,FollowCameraKeyboardMoveInput:()=>Fr,FollowCameraMouseWheelInput:()=>Lr,FollowCameraPointersInput:()=>Br,FragCoordBlock:()=>kS,FragDepthBlock:()=>HS,FragmentOutputBlock:()=>Hg,FragmentOutputBlockColorSpace:()=>Fg,FrameGraph:()=>e_,FrameGraphBlackAndWhiteTask:()=>c_,FrameGraphBloomTask:()=>x_,FrameGraphBlurTask:()=>v_,FrameGraphCircleOfConfusionTask:()=>C_,FrameGraphClearTextureTask:()=>r_,FrameGraphContext:()=>jp,FrameGraphCopyToBackbufferColorTask:()=>Up,FrameGraphCopyToTextureTask:()=>K_,FrameGraphCullObjectsTask:()=>w_,FrameGraphDepthOfFieldTask:()=>M_,FrameGraphExtractHighlightsTask:()=>g_,FrameGraphGeometryRendererTask:()=>B_,FrameGraphObjectList:()=>Z_,FrameGraphObjectRendererTask:()=>k_,FrameGraphPass:()=>Lp,FrameGraphPostProcessTask:()=>h_,FrameGraphRenderContext:()=>$p,FrameGraphRenderPass:()=>Vp,FrameGraphTAAObjectRendererTask:()=>H_,FrameGraphTask:()=>kp,FrameGraphTextureManager:()=>Jp,FramingBehavior:()=>Ai,FreeCamera:()=>es,FreeCameraDeviceOrientationInput:()=>Wr,FreeCameraGamepadInput:()=>Hr,FreeCameraInputsManager:()=>zr,FreeCameraKeyboardMoveInput:()=>Vr,FreeCameraMouseInput:()=>kr,FreeCameraMouseWheelInput:()=>Ur,FreeCameraTouchInput:()=>Gr,FreeCameraVirtualJoystickInput:()=>Zr,FresnelBlock:()=>hC,FresnelParameters:()=>gb,FromHalfFloat:()=>Ac.SX,FrontFace:()=>Xh,FrontFacingBlock:()=>BS,Frustum:()=>hc.PP,FxaaPostProcess:()=>kR,GIRSM:()=>MN,GIRSMManager:()=>ON,GIRSMRenderPluginMaterial:()=>wN,GPUParticleSystem:()=>lM,GPUPicker:()=>bo,GUID:()=>Au.S,Gamepad:()=>Cr,GamepadCamera:()=>ps,GamepadManager:()=>us,GamepadSystemSceneComponent:()=>ds,GaussianBlock:()=>dS,GaussianSplattingBlock:()=>uS,GaussianSplattingMaterial:()=>pS,GaussianSplattingMesh:()=>wA,GenerateBase64StringFromPixelData:()=>LI.c9,GenerateBase64StringFromTexture:()=>LI.lP,GenerateBase64StringFromTextureAsync:()=>LI.nh,GenericPad:()=>yr,GeodesicData:()=>ul,Geometry:()=>yt,GeometryArcTan2Block:()=>lA,GeometryBufferRenderer:()=>qO,GeometryBufferRendererSceneComponent:()=>KO,GeometryClampBlock:()=>_A,GeometryCollectionBlock:()=>RP,GeometryCrossBlock:()=>mA,GeometryCurveBlock:()=>gA,GeometryCurveBlockTypes:()=>QE,GeometryDesaturateBlock:()=>vA,GeometryDistanceBlock:()=>SA,GeometryDotBlock:()=>TA,GeometryElbowBlock:()=>MP,GeometryInfoBlock:()=>JP,GeometryInputBlock:()=>rP,GeometryInterceptorBlock:()=>EA,GeometryLengthBlock:()=>CA,GeometryLerpBlock:()=>hA,GeometryModBlock:()=>fA,GeometryNLerpBlock:()=>cA,GeometryOptimizeBlock:()=>oP,GeometryOutputBlock:()=>tP,GeometryPosterizeBlock:()=>xA,GeometryPowBlock:()=>pA,GeometryRenderingTextureClearType:()=>Fn,GeometryReplaceColorBlock:()=>bA,GeometryRotate2dBlock:()=>yA,GeometrySmoothStepBlock:()=>dA,GeometryStepBlock:()=>uA,GeometryTextureBlock:()=>sA,GeometryTextureFetchBlock:()=>nA,GeometryTransformBlock:()=>BP,GeometryTrigonometryBlock:()=>LP,GeometryTrigonometryBlockOperations:()=>KE,GetClass:()=>X.n9,GetClassName:()=>X.Uu,GetDOMTextContent:()=>ii.Zl,GetEnvInfo:()=>Wl.cU,GetEnvironmentBRDFTexture:()=>Em,GetExrHeader:()=>Hb.V,GetFogState:()=>Bt.qL,GetFontOffset:()=>Zs,GetForwardRay:()=>qi,GetForwardRayToRef:()=>Yi,GetHotSpotToRef:()=>Ky,GetIndividualParser:()=>fi,GetInternalFormatFromBasisFormat:()=>hR.yT,GetParser:()=>ui,GetPointsCount:()=>OE,GetTGAHeader:()=>BR.O_,GetTextureDataAsync:()=>Ac.Oz,GetTransformedPosition:()=>Yy,Gizmo:()=>Go,GizmoAnchorPoint:()=>Vo,GizmoCoordinatesMode:()=>ko,GizmoManager:()=>am,GlowLayer:()=>Vv,GoldbergMesh:()=>fl,GradientBlock:()=>yC,GradientBlockColorStep:()=>CC,GradientHelper:()=>JR,GrainPostProcess:()=>UO,GreasedLineBaseMesh:()=>PE,GreasedLineMaterialDefaults:()=>yy,GreasedLineMesh:()=>AE,GreasedLineMeshColorDistribution:()=>pE,GreasedLineMeshColorDistributionType:()=>Oy,GreasedLineMeshColorMode:()=>My,GreasedLineMeshMaterialType:()=>Iy,GreasedLineMeshWidthDistribution:()=>_E,GreasedLinePluginMaterial:()=>Ay,GreasedLineRibbonAutoDirectionMode:()=>fE,GreasedLineRibbonFacesMode:()=>dE,GreasedLineRibbonMesh:()=>RE,GreasedLineRibbonPointsMode:()=>uE,GreasedLineSimpleMaterial:()=>Ry,GreasedLineTools:()=>Ey,GridBlock:()=>uP,GroundBuilder:()=>no,GroundMesh:()=>Zn,HDRCubeTexture:()=>Vx,HDRCubeTextureAssetTask:()=>oR,HDRFiltering:()=>Bx,HDRTools:()=>Fx.I9,Halton2DSequence:()=>z_,HandConstraintBehavior:()=>ur,HandConstraintOrientation:()=>nr,HandConstraintVisibility:()=>or,HandConstraintZone:()=>sr,HandPart:()=>gv,HandleFallbacksForShadows:()=>Bt.c4,HardwareScalingOptimization:()=>xR,HavokPlugin:()=>fO,HeightToNormalBlock:()=>WS,HemisphereBuilder:()=>um,HemisphericLight:()=>Lo,HemisphericParticleEmitter:()=>dI,HighlightLayer:()=>Uv,HighlightsPostProcess:()=>GO,Hinge2Joint:()=>ra,HingeConstraint:()=>eO,HingeJoint:()=>ia,HtmlElementTexture:()=>wb,HufUncompress:()=>kb.ZR,IWebXRControllerPhysicsOptions:()=>_L,IblShadowsRenderPipeline:()=>kw,IcoSphereBlock:()=>hP,IcoSphereBuilder:()=>Za,ImageAssetTask:()=>rR,ImageProcessingBlock:()=>wS,ImageProcessingConfiguration:()=>gn.p,ImageProcessingPostProcess:()=>zO,ImageSourceBlock:()=>dT,IncrementValueAction:()=>ie,IndexFormat:()=>Qh,InitializeCSG2Async:()=>UE,InputBlock:()=>Kg,InspectableType:()=>jR,InstancedLinesMesh:()=>ya,InstancedMesh:()=>Kt,InstancesBlock:()=>vS,InstantiateBlock:()=>KP,InstantiateLinearBlock:()=>jP,InstantiateOnFacesBlock:()=>XP,InstantiateOnVerticesBlock:()=>HP,InstantiateOnVolumeBlock:()=>qP,InstantiateRadialBlock:()=>$P,InstantiatedEntries:()=>Jt,IntFloatConverterBlock:()=>QP,InterleaveScalar:()=>zb.KA,InternalTexture:()=>Fs.h,InternalTextureSource:()=>Fs.G,InterpolateValueAction:()=>_e,IntersectionInfo:()=>ot,IsBase64DataUrl:()=>$m.f2,IsCSG2Ready:()=>kE,IsDocumentAvailable:()=>ii.Nf,IsFileURL:()=>$m.my,IsNavigatorAvailable:()=>ii.XD,IsWindowObjectExist:()=>ii.BA,IsWrapper:()=>Ol.E,JoystickAxis:()=>Xr,KeepAssets:()=>Zt,KeyboardEventTypes:()=>Ar.TB,KeyboardInfo:()=>Ar.W0,KeyboardInfoPre:()=>Ar.Bu,KhronosTextureContainer:()=>_R.H,KhronosTextureContainer2:()=>MI.Z,LatheBuilder:()=>Ha,Lattice:()=>yE,LatticeBlock:()=>FP,LatticePluginMaterial:()=>EE,Layer:()=>zv,LayerSceneComponent:()=>Gv,LengthBlock:()=>fC,LensFlare:()=>rx,LensFlareSystem:()=>sx,LensFlareSystemSceneComponent:()=>nx,LensFlaresOptimization:()=>TR,LensRenderingPipeline:()=>sD,LerpBlock:()=>rC,Light:()=>$t,LightBlock:()=>uT,LightGizmo:()=>fm,LightInformationBlock:()=>bS,LineEdgesRenderer:()=>Ow,LinesBuilder:()=>Ma,LinesMesh:()=>Ca,LoadFile:()=>$m.zU,LoadFileError:()=>$m.hX,LoadImage:()=>$m.W$,LoadImageConfiguration:()=>$m.qc,LoadOp:()=>ic,LoadTextureFromTranscodeResult:()=>hR.aB,LockConstraint:()=>iO,Logger:()=>Z.V,LoopBlock:()=>sy,MapMode:()=>Ph,MapRangeBlock:()=>CP,MappingBlock:()=>eA,MappingTypes:()=>jE,Material:()=>Vt,MaterialAnisotropicDefines:()=>wm,MaterialClearCoatDefines:()=>Im,MaterialDefines:()=>xn,MaterialDetailMapDefines:()=>wn,MaterialFlags:()=>Sn,MaterialGreasedLineDefines:()=>Py,MaterialHelper:()=>vb,MaterialHelperGeometryRendering:()=>Bn,MaterialIridescenceDefines:()=>Om,MaterialPluginBase:()=>Dn,MaterialPluginEvent:()=>cy,MaterialPluginManager:()=>En,MaterialSheenDefines:()=>Fm,MaterialSubSurfaceDefines:()=>Bm,MathBlock:()=>TP,MathBlockOperations:()=>XE,Matrix:()=>hc.uq,MatrixBuilderBlock:()=>WC,MatrixComposeBlock:()=>tA,MatrixDeterminantBlock:()=>JC,MatrixTransposeBlock:()=>ey,MaxBlock:()=>cC,MergeGeometryBlock:()=>AP,MergeMeshesOptimization:()=>PR,Mesh:()=>Yt,MeshAssetTask:()=>JA,MeshAttributeExistsBlock:()=>ty,MeshAttributeExistsBlockTypes:()=>XC,MeshBlock:()=>lP,MeshBuilder:()=>bl,MeshDebugMode:()=>wy,MeshDebugPluginMaterial:()=>Fy,MeshExploder:()=>dR,MeshLODLevel:()=>Gt,MeshParticleEmitter:()=>hI,MeshUVSpaceRenderer:()=>oE,MeshoptCompression:()=>Jy,MinBlock:()=>uC,MinMaxReducer:()=>mx,MipmapFilterMode:()=>Nh,MirrorTexture:()=>mm,ModBlock:()=>zC,ModelShape:()=>dM,MorphTarget:()=>kx,MorphTargetManager:()=>Gx,MorphTargetsBlock:()=>xS,MotionBlurPostProcess:()=>jO,MotorEnabledJoint:()=>ta,MultiMaterial:()=>kt,MultiObserver:()=>mR,MultiPick:()=>Hi,MultiPickWithRay:()=>Xi,MultiPointerScaleBehavior:()=>er,MultiRenderTarget:()=>Xb,MultiplyBlock:()=>iv,NLerpBlock:()=>EC,NativeDataStream:()=>zl,NativeEngine:()=>gh,NativePointerInput:()=>Pl.Ze,NativeXRFrame:()=>ZL,NativeXRLayerRenderTargetTextureProvider:()=>jn,NativeXRLayerWrapper:()=>Kn,NativeXRRenderTarget:()=>$n,NegateBlock:()=>pC,Node:()=>Ze.b,NodeGeometry:()=>nP,NodeGeometryBlock:()=>eP,NodeGeometryBlockConnectionPointTypes:()=>GE,NodeGeometryBuildState:()=>iP,NodeGeometryConnectionPoint:()=>JE,NodeGeometryConnectionPointCompatibilityStates:()=>zE,NodeGeometryConnectionPointDirection:()=>WE,NodeGeometryContextualSources:()=>HE,NodeMaterial:()=>pv,NodeMaterialBlock:()=>Gg,NodeMaterialBlockConnectionPointMode:()=>iS,NodeMaterialBlockConnectionPointTypes:()=>Og,NodeMaterialBlockTargets:()=>Dg,NodeMaterialConnectionPoint:()=>Ug,NodeMaterialConnectionPointCompatibilityStates:()=>wg,NodeMaterialConnectionPointCustomObject:()=>cS,NodeMaterialConnectionPointDirection:()=>Ng,NodeMaterialDefines:()=>fv,NodeMaterialModes:()=>rv,NodeMaterialOptimizer:()=>dy,NodeMaterialSystemValues:()=>Lg,NodeMaterialTeleportInBlock:()=>qT,NodeMaterialTeleportOutBlock:()=>YT,NodeRenderGraph:()=>o_,NodeRenderGraphBlackAndWhitePostProcessBlock:()=>u_,NodeRenderGraphBlock:()=>wp,NodeRenderGraphBlockConnectionPointTypes:()=>Rp,NodeRenderGraphBloomPostProcessBlock:()=>b_,NodeRenderGraphBlurPostProcessBlock:()=>S_,NodeRenderGraphBuildState:()=>n_,NodeRenderGraphCircleOfConfusionPostProcessBlock:()=>y_,NodeRenderGraphClearBlock:()=>s_,NodeRenderGraphConnectionPoint:()=>Dp,NodeRenderGraphConnectionPointCompatibilityStates:()=>Ip,NodeRenderGraphConnectionPointDirection:()=>Mp,NodeRenderGraphCopyTextureBlock:()=>j_,NodeRenderGraphCullObjectsBlock:()=>N_,NodeRenderGraphDepthOfFieldPostProcessBlock:()=>O_,NodeRenderGraphElbowBlock:()=>a_,NodeRenderGraphExtractHighlightsPostProcessBlock:()=>D_,NodeRenderGraphGenerateMipmapsBlock:()=>Q_,NodeRenderGraphGeometryRendererBlock:()=>V_,NodeRenderGraphInputBlock:()=>i_,NodeRenderGraphObjectRendererBlock:()=>G_,NodeRenderGraphOutputBlock:()=>Gp,NodeRenderGraphTAAObjectRendererBlock:()=>X_,NodeRenderGraphTeleportInBlock:()=>q_,NodeRenderGraphTeleportOutBlock:()=>Y_,NoiseBlock:()=>PP,NoiseProceduralTexture:()=>jb,NormalBlendBlock:()=>RC,NormalizeBlock:()=>eC,NormalizeVectorBlock:()=>wP,NullBlock:()=>mP,NullEngine:()=>wl,NullEngineOptions:()=>Dl,ObjectRenderer:()=>F_.P,Observable:()=>z.cP,Observer:()=>z.nu,OcclusionMaterial:()=>Sb,Octree:()=>Oo,OctreeBlock:()=>Mo,OctreeSceneComponent:()=>Do,OimoJSPlugin:()=>qx,OnAfterEnteringVRObservableEvent:()=>uo,OneMinusBlock:()=>aC,Orientation:()=>hc.t4,OutlineRenderer:()=>qw,PBRAnisotropicConfiguration:()=>Nm,PBRBaseMaterial:()=>Gm,PBRBaseSimpleMaterial:()=>Tb,PBRClearCoatConfiguration:()=>Mm,PBRIridescenceConfiguration:()=>Dm,PBRMaterial:()=>zm,PBRMaterialDefines:()=>Um,PBRMetallicRoughnessBlock:()=>GC,PBRMetallicRoughnessMaterial:()=>Cb,PBRSheenConfiguration:()=>Lm,PBRSpecularGlossinessMaterial:()=>yb,PBRSubSurfaceConfiguration:()=>Vm,PHI:()=>hc.a6,PadNumber:()=>bi.LW,PanoramaToCubeMapTools:()=>Ob.D,Parse:()=>pi,ParseFloat16:()=>zb.LD,ParseFloat32:()=>zb.Ff,ParseInt32:()=>zb.cL,ParseInt64:()=>zb.tB,ParseNullTerminatedString:()=>zb.T$,ParseUint16:()=>zb.Jn,ParseUint32:()=>zb.PX,ParseUint8:()=>zb._S,ParseUint8Array:()=>zb.fz,ParseValue:()=>zb.zX,Particle:()=>rI,ParticleBlendMultiplyBlock:()=>Zg,ParticleHelper:()=>cM,ParticleRampGradientBlock:()=>Qg,ParticleSystem:()=>AI,ParticleSystemSet:()=>hM,ParticleTextureBlock:()=>$g,ParticlesOptimization:()=>yR,PassCubePostProcess:()=>_s.s,PassPostProcess:()=>_s.v,Path2:()=>hc.Cu,Path3D:()=>hc.tO,PathCursor:()=>Ve,PerfCollectionStrategy:()=>qI,PerfCounter:()=>on.A,PerformanceConfigurator:()=>Ml.I,PerformanceMonitor:()=>Bs,PerformanceViewerCollector:()=>HI,PerturbNormalBlock:()=>FS,PhotoDome:()=>Tm,Physics6DoFConstraint:()=>QM,Physics6DoFLimit:()=>$M,PhysicsActivationControl:()=>RM,PhysicsAggregate:()=>nO,PhysicsBody:()=>VM,PhysicsConstraint:()=>jM,PhysicsConstraintAxis:()=>SM,PhysicsConstraintAxisLimitMode:()=>bM,PhysicsConstraintMotorType:()=>yM,PhysicsConstraintType:()=>TM,PhysicsEngine:()=>Hx,PhysicsEngineV2:()=>BM,PhysicsEventType:()=>EM,PhysicsHelper:()=>mO,PhysicsImpostor:()=>sa,PhysicsJoint:()=>Jo,PhysicsMaterialCombineMode:()=>IM,PhysicsMotionType:()=>PM,PhysicsPrestepType:()=>AM,PhysicsRadialExplosionEventOptions:()=>SO,PhysicsRadialImpulseFalloff:()=>MM,PhysicsRaycastResult:()=>Wx,PhysicsShape:()=>kM,PhysicsShapeBox:()=>WM,PhysicsShapeCapsule:()=>GM,PhysicsShapeContainer:()=>qM,PhysicsShapeConvexHull:()=>HM,PhysicsShapeCylinder:()=>zM,PhysicsShapeGroundMesh:()=>KM,PhysicsShapeHeightField:()=>YM,PhysicsShapeMesh:()=>XM,PhysicsShapeSphere:()=>UM,PhysicsShapeType:()=>CM,PhysicsUpdraftEventOptions:()=>TO,PhysicsUpdraftMode:()=>OM,PhysicsViewer:()=>Sl,PhysicsVortexEventOptions:()=>CO,Pick:()=>zi,PickWithBoundingInfo:()=>Gi,PickWithRay:()=>Wi,PickingCustomization:()=>Di,PickingInfo:()=>At.G,PipelineErrorReason:()=>zh,PivotTools:()=>ji,Plane:()=>hc.Zc,PlaneBlock:()=>aP,PlaneBuilder:()=>Zi,PlaneDragGizmo:()=>sm,PlaneRotationGizmo:()=>im,PlayAnimationAction:()=>re,PlaySoundAction:()=>de,PointColor:()=>vM,PointLight:()=>wx,PointParticleEmitter:()=>uI,PointerDragBehavior:()=>Ji,PointerEventTypes:()=>yi.Zp,PointerInfo:()=>yi.mx,PointerInfoBase:()=>yi.Vn,PointerInfoPre:()=>yi.tT,PointerInput:()=>Pl.ST,PointsCloudSystem:()=>xM,PointsGroup:()=>gM,Polar:()=>zy,Polygon:()=>wa,PolygonBuilder:()=>Va,PolygonMeshBuilder:()=>Na,PolyhedronBuilder:()=>ja,PolyhedronData:()=>cl,PositionGizmo:()=>nm,PositionNormalTextureVertex:()=>hc.k0,PositionNormalVertex:()=>hc.B5,PostProcess:()=>ms.w,PostProcessManager:()=>_x.X,PostProcessRenderEffect:()=>AO,PostProcessRenderPipeline:()=>JO,PostProcessRenderPipelineManager:()=>eD,PostProcessRenderPipelineManagerSceneComponent:()=>tD,PostProcessesOptimization:()=>SR,PosterizeBlock:()=>SC,PowBlock:()=>_C,PowerEase:()=>Pe,PowerPreference:()=>Th,PrePassOutputBlock:()=>qS,PrePassRenderer:()=>Gw,PrePassRendererSceneComponent:()=>zw,PrePassTextureBlock:()=>XT,PrecisionDate:()=>ai.j,PredicateCondition:()=>$,Predictor:()=>zb.XE,PrepareAttributesForBakedVertexAnimation:()=>Bt.J2,PrepareAttributesForBones:()=>Bt.ni,PrepareAttributesForInstances:()=>Bt.ER,PrepareAttributesForMorphTargets:()=>Bt.IF,PrepareAttributesForMorphTargetsInfluencers:()=>Bt.MF,PrepareDefinesForAttributes:()=>Bt.qB,PrepareDefinesForBakedVertexAnimation:()=>Bt.wu,PrepareDefinesForBones:()=>Bt.IC,PrepareDefinesForCamera:()=>Bt.Y7,PrepareDefinesForFrameBoundValues:()=>Bt.OR,PrepareDefinesForLight:()=>Bt.lo,PrepareDefinesForLights:()=>Bt.az,PrepareDefinesForMergedUV:()=>Bt.YT,PrepareDefinesForMisc:()=>Bt.fm,PrepareDefinesForMorphTargets:()=>Bt.Jz,PrepareDefinesForMultiview:()=>Bt.VO,PrepareDefinesForOIT:()=>Bt.Nc,PrepareDefinesForPrePass:()=>Bt.N4,PrepareUniformsAndSamplersForLight:()=>Bt.GD,PrepareUniformsAndSamplersList:()=>Bt.Bb,PressureObserverWrapper:()=>VI,PrimitiveTopology:()=>Hh,PrismaticConstraint:()=>rO,ProceduralTexture:()=>cv,ProceduralTextureSceneComponent:()=>hv,PropertyTypeForEdition:()=>Xp,ProximityCastResult:()=>yO,PushAttributesForInstances:()=>Bt.te,PushMaterial:()=>bn,QuadraticEase:()=>Ae,QuadraticErrorSimplification:()=>bE,QuarticEase:()=>Re,Quaternion:()=>hc.PT,QueryType:()=>sc,QueueNewFrame:()=>Ot.r,QuinticEase:()=>Ie,RGBDTextureTools:()=>Cm.G,RSMCreatePluginMaterial:()=>IN,Ragdoll:()=>aO,RagdollBoneProperties:()=>oO,RandomBlock:()=>EP,RandomBlockLocks:()=>YE,RandomGUID:()=>Au.z,RandomNumberBlock:()=>mC,RawCubeTexture:()=>$b,RawTexture:()=>xi,RawTexture2DArray:()=>Ux,RawTexture3D:()=>Qb,Ray:()=>wi,RayHelper:()=>Tl,ReadFile:()=>$m.NJ,ReadFileError:()=>$m.VB,RecastJSCrowd:()=>rM,RecastJSPlugin:()=>iM,ReciprocalBlock:()=>xC,ReflectBlock:()=>MC,ReflectionBlock:()=>FC,ReflectionProbe:()=>Kx,ReflectionTextureBaseBlock:()=>pT,ReflectionTextureBlock:()=>_T,ReflectiveShadowMap:()=>AN,Reflector:()=>BI,RefractBlock:()=>OC,RefractionBlock:()=>VC,RefractionPostProcess:()=>$O,RefractionTexture:()=>Zb,RegisterClass:()=>X.Y5,RegisterMaterialPlugin:()=>In,RegisterNativeTypeAsync:()=>fh,RegisterTargetForLateAnimationBinding:()=>me.BT,RemapBlock:()=>ev,RenderPassTimestampLocation:()=>tc,RenderTargetTexture:()=>ln.$,RenderTargetWrapper:()=>qs,RenderTargetsOptimization:()=>ER,RenderingGroup:()=>Kw.U,RenderingGroupInfo:()=>cx.o,RenderingManager:()=>cx.m,ReplaceColorBlock:()=>bC,RequestFile:()=>$m.sh,RequestFileError:()=>$m.Mi,RequestFullscreen:()=>tn,RequestPointerlock:()=>sn,ResizeImageBitmap:()=>en,RetryStrategy:()=>eI.a,ReverseLutFromBitmap:()=>kb.FG,RibbonBuilder:()=>ca,RichType:()=>Mu,RichTypeAny:()=>Ou,RichTypeBoolean:()=>Nu,RichTypeColor3:()=>ku,RichTypeColor4:()=>Uu,RichTypeFlowGraphInteger:()=>zu,RichTypeMatrix:()=>Vu,RichTypeNumber:()=>wu,RichTypeQuaternion:()=>Gu,RichTypeString:()=>Du,RichTypeVector2:()=>Fu,RichTypeVector3:()=>Lu,RichTypeVector4:()=>Bu,RollingAverage:()=>Vs,Rotate2dBlock:()=>IC,RotationGizmo:()=>rm,RotationXBlock:()=>VP,RotationYBlock:()=>kP,RotationZBlock:()=>UP,RuntimeAnimation:()=>De.x,RuntimeError:()=>nt.bu,SSAO2RenderingPipeline:()=>oD,SSAORenderingPipeline:()=>lD,SSRRenderingPipeline:()=>_D,SamplerBindingType:()=>Vh,Scalar:()=>Gy,ScaleBlock:()=>jT,ScaleGizmo:()=>om,ScalingBlock:()=>GP,ScanData:()=>Wb.u,Scene:()=>oi.Z,SceneComponentConstants:()=>Ut.v,SceneDepthBlock:()=>mT,SceneInstrumentation:()=>Fv,SceneLoader:()=>xg,SceneLoaderAnimationGroupLoadingMode:()=>jm,SceneLoaderFlags:()=>St,SceneOptimization:()=>gR,SceneOptimizer:()=>RR,SceneOptimizerOptions:()=>AR,ScenePerformancePriority:()=>oi.F,SceneRecorder:()=>RI,SceneSerializer:()=>DR,ScreenSizeBlock:()=>US,ScreenSpaceBlock:()=>GS,ScreenSpaceCurvaturePostProcess:()=>ID,ScreenSpaceReflectionPostProcess:()=>cD,ScreenshotTools:()=>KR,SerializationHelper:()=>it.p,SetBasisTranscoderWorker:()=>hR.af,SetColorsBlock:()=>bP,SetCorsBehavior:()=>$m.M1,SetMaterialIDBlock:()=>NP,SetNormalsBlock:()=>vP,SetParentAction:()=>le,SetPositionsBlock:()=>gP,SetStateAction:()=>ee,SetTangentsBlock:()=>SP,SetToDefaultGaussianSplatting:()=>mS,SetUVsBlock:()=>xP,SetValueAction:()=>te,ShaderCodeInliner:()=>$l,ShaderLanguage:()=>Eb,ShaderMaterial:()=>xo,ShaderStage:()=>Lh,ShaderStore:()=>Cs.l,ShadowDepthWrapper:()=>py,ShadowGenerator:()=>ux,ShadowGeneratorSceneComponent:()=>yx,ShadowLight:()=>lm,ShadowMapBlock:()=>XS,ShadowsOptimization:()=>bR,ShapeBuilder:()=>za,ShapeCastResult:()=>EO,SharpenPostProcess:()=>ZO,SheenBlock:()=>wC,SimplexPerlin3DBlock:()=>AC,SimplicationQueueSceneComponent:()=>SE,SimplificationQueue:()=>hE,SimplificationSettings:()=>lE,SimplificationType:()=>cE,SineEase:()=>Me,SixDofDragBehavior:()=>ir,Size:()=>hc.or,Skeleton:()=>Ti,SkeletonViewer:()=>yl,SliderConstraint:()=>tO,SmartArray:()=>Qe.L,SmartArrayNoDuplicate:()=>Qe.b,SmoothStepBlock:()=>vC,SnapshotRenderingHelper:()=>YI,SolidParticle:()=>uM,SolidParticleSystem:()=>_M,SolidParticleVertex:()=>pM,Sound:()=>si,SoundTrack:()=>ni,SourceTextureFormat:()=>rS.Ok,Space:()=>hc.$x,SphereBlock:()=>cP,SphereBuilder:()=>Zo,SphereDirectedParticleEmitter:()=>pI,SphereParticleEmitter:()=>fI,Spherical:()=>Wy,SphericalHarmonics:()=>Ks.O,SphericalPolynomial:()=>Ks.Q,SplatReaderBlock:()=>_S,SpotLight:()=>dm,SpringConstraint:()=>sO,Sprite:()=>$x,SpriteManager:()=>Jx,SpriteMap:()=>JF,SpriteMapFrameRotationDirection:()=>ZF,SpritePackedManager:()=>eL,SpriteSceneComponent:()=>Qx,Stage:()=>Ut.B,StandardMaterial:()=>Un,StandardMaterialDefines:()=>kn,StandardRenderingPipeline:()=>uD,StartsWith:()=>bi.UH,StateCondition:()=>Q,StencilOperation:()=>$h,StencilState:()=>lL.K,StencilStateComposer:()=>kc.u,StepBlock:()=>oC,StereoscopicArcRotateCamera:()=>As,StereoscopicFreeCamera:()=>Rs,StereoscopicGamepadCamera:()=>Is,StereoscopicInterlacePostProcess:()=>Es,StereoscopicInterlacePostProcessI:()=>ys,StereoscopicScreenUniversalCamera:()=>Os,StereoscopicUniversalCamera:()=>Ms,StickValues:()=>Tr,StopAnimationAction:()=>se,StopSoundAction:()=>fe,StorageBuffer:()=>_r.K,StorageReadBlock:()=>ny,StorageTextureAccess:()=>Uh,StorageWriteBlock:()=>oy,StoreOp:()=>rc,StringDictionary:()=>$r.w,StringTools:()=>bi.nQ,SubEmitter:()=>lI,SubEmitterType:()=>nI,SubMesh:()=>vt,SubSurfaceBlock:()=>kC,SubSurfaceSceneComponent:()=>Xw,SubtractBlock:()=>nC,SurfaceMagnetismBehavior:()=>rr,SwitchBooleanAction:()=>J,SwitchInput:()=>Pl.dR,TAARenderingPipeline:()=>mD,TBNBlock:()=>NS,TGATools:()=>BR.uT,Tags:()=>Ge.Y,TargetCamera:()=>Jr,TargetedAnimation:()=>Fe.TargetedAnimation,TeleportInBlock:()=>iA,TeleportOutBlock:()=>rA,TestBase64DataUrl:()=>$m.ZP,TextFileAssetTask:()=>tR,Texture:()=>vi.g,TextureAspect:()=>Mh,TextureAssetTask:()=>sR,TextureBlock:()=>fT,TextureDimension:()=>Ah,TextureFormat:()=>Oh,TextureOptimization:()=>vR,TexturePacker:()=>Yb,TexturePackerFrame:()=>qb,TextureSampleType:()=>kh,TextureSampler:()=>Jb.u,TextureTools:()=>Ac.LO,TextureUsage:()=>Rh,TextureViewDimension:()=>Ih,ThinBlackAndWhitePostProcess:()=>l_,ThinBloomEffect:()=>m_,ThinBlurPostProcess:()=>p_,ThinCircleOfConfusionPostProcess:()=>T_,ThinDepthOfFieldEffect:()=>I_,ThinDepthOfFieldEffectBlurLevel:()=>qp,ThinEngine:()=>Ls.ThinEngine,ThinExtractHighlightsPostProcess:()=>__,ThinRenderTargetTexture:()=>tS,ThinTexture:()=>eS.D,TiledBoxBuilder:()=>xa,TiledPlaneBuilder:()=>ma,TimerState:()=>vd,TmpColors:()=>hc.IG,TmpVectors:()=>hc.AA,ToGammaSpace:()=>hc.rv,ToHalfFloat:()=>Ac.LZ,ToLinearSpace:()=>hc.tk,TonemapPostProcess:()=>AD,TonemappingOperator:()=>gD,Tools:()=>Ue.S0,TorusBlock:()=>dP,TorusBuilder:()=>lo,TorusKnotBuilder:()=>Ta,TouchCamera:()=>ts,TrailMesh:()=>aE,Trajectory:()=>OI,TrajectoryClassifier:()=>FI,TranscodeAsync:()=>hR.yk,TranscodeTarget:()=>rS.Xl,TransformBlock:()=>zg,TransformFeedbackBoundingHelper:()=>Ro.TransformFeedbackBoundingHelper,TransformNode:()=>Pt,TranslationBlock:()=>WP,TriPlanarBlock:()=>QC,TrigonometryBlock:()=>uv,TrigonometryBlockOperations:()=>av,TubeBuilder:()=>qa,TwirlBlock:()=>zS,UncompressPIZ:()=>Vb.tg,UncompressPXR:()=>Vb._k,UncompressRAW:()=>Vb.S4,UncompressRLE:()=>Vb.r,UncompressZIP:()=>Vb.VE,UniformBuffer:()=>Rt.D,UniversalCamera:()=>fs,UnregisterAllMaterialPlugins:()=>On,UnregisterMaterialPlugin:()=>Mn,UploadContent:()=>BR.FA,UploadEnvLevelsAsync:()=>Wl.o5,UploadEnvSpherical:()=>Wl.ow,UploadLevelsAsync:()=>Wl.bv,UtilityLayerRenderer:()=>Bo,VRCameraMetrics:()=>ws,VRDeviceOrientationArcRotateCamera:()=>pn,VRDeviceOrientationFreeCamera:()=>_n,VRDeviceOrientationGamepadCamera:()=>mn,VRDistortionCorrectionPostProcess:()=>Ns,VRExperienceHelper:()=>fo,VRMultiviewToSingleviewPostProcess:()=>dn,ValidatedNativeDataStream:()=>vh,ValueCondition:()=>j,Vector2:()=>hc.I9,Vector2ToFixed:()=>Hy,Vector3:()=>hc.Pq,Vector3ToFixed:()=>Xy,Vector4:()=>hc.IU,Vector4ToFixed:()=>qy,VectorConverterBlock:()=>DP,VectorMergerBlock:()=>Jg,VectorSplitterBlock:()=>iC,VertexAnimationBaker:()=>Ci,VertexBuffer:()=>st.R,VertexData:()=>bt,VertexDataMaterialInfo:()=>xt,VertexFormat:()=>Zh,VertexOutputBlock:()=>Wg,VertexStepMode:()=>Jh,VideoDome:()=>wv,VideoRecorder:()=>VR,VideoTexture:()=>Dv,ViewDirectionBlock:()=>lC,Viewport:()=>hc.LM,VirtualJoystick:()=>Qr,VirtualJoysticksCamera:()=>Ds,VolumetricLightScatteringPostProcess:()=>RD,VoronoiNoiseBlock:()=>jC,Wav2Decode:()=>kb.tb,WaveBlock:()=>TC,WaveBlockKind:()=>vT,WebGL2ParticleSystem:()=>oM,WebGL2ShaderProcessor:()=>Tu.B,WebGLDataBuffer:()=>ks.A,WebGLHardwareTexture:()=>Us.d,WebGLPipelineContext:()=>Su.x,WebGPUCacheBindGroups:()=>Kc,WebGPUCacheRenderPipeline:()=>Lc,WebGPUCacheRenderPipelineTree:()=>Vc,WebGPUCacheSampler:()=>Dc,WebGPUDataBuffer:()=>Pc,WebGPUDrawContext:()=>Xc,WebGPUEngine:()=>gu,WebGPUPipelineContext:()=>uc,WebGPURenderTargetWrapper:()=>fu,WebGPUShaderProcessor:()=>cc,WebGPUTintWASM:()=>lu,WebRequest:()=>go.u,WebXRAbstractFeature:()=>Ig,WebXRAbstractMotionController:()=>bg,WebXRAnchorSystem:()=>uL,WebXRBackgroundRemover:()=>pL,WebXRCamera:()=>qm,WebXRControllerComponent:()=>Km,WebXRControllerMovement:()=>yL,WebXRControllerPhysics:()=>mL,WebXRControllerPointerSelection:()=>Mg,WebXRDefaultExperience:()=>Iv,WebXRDefaultExperienceOptions:()=>Rv,WebXRDepthSensing:()=>kL,WebXRDomOverlay:()=>CL,WebXREnterExitUI:()=>Tv,WebXREnterExitUIButton:()=>bv,WebXREnterExitUIOptions:()=>Sv,WebXRExperienceHelper:()=>Ym,WebXREyeTracking:()=>PL,WebXRFeatureName:()=>hr,WebXRFeaturePointSystem:()=>vL,WebXRFeaturesManager:()=>cr,WebXRGenericHandController:()=>HL,WebXRGenericTriggerMotionController:()=>Sg,WebXRHTCViveMotionController:()=>$L,WebXRHand:()=>Ev,WebXRHandJoint:()=>vv,WebXRHandTracking:()=>Pv,WebXRHitTest:()=>gL,WebXRHitTestLegacy:()=>hL,WebXRImageTracking:()=>TL,WebXRInput:()=>Rg,WebXRInputSource:()=>Ag,WebXRLayerRenderTargetTextureProvider:()=>Wn,WebXRLayers:()=>VL,WebXRLightEstimation:()=>EL,WebXRManagedOutputCanvas:()=>Yn,WebXRManagedOutputCanvasOptions:()=>qn,WebXRMeshDetector:()=>bL,WebXRMicrosoftMixedRealityController:()=>qL,WebXRMotionControllerManager:()=>Eg,WebXRMotionControllerTeleportation:()=>Av,WebXRNearControllerMode:()=>mv,WebXRNearInteraction:()=>xv,WebXROculusTouchMotionController:()=>KL,WebXRPlaneDetector:()=>fL,WebXRProfiledMotionController:()=>Cg,WebXRRawCameraAccess:()=>WL,WebXRSessionManager:()=>Qn,WebXRSpaceWarp:()=>zL,WebXRSpaceWarpRenderTargetTextureProvider:()=>GL,WebXRState:()=>tL,WebXRTrackingState:()=>iL,WebXRWalkingLocomotion:()=>OL,WeightedSound:()=>mi,WorkerPool:()=>jy.T,WorleyNoise3DBlock:()=>PC,XRSpaceWarpRenderTarget:()=>UL,Xbox360Button:()=>qr,Xbox360Dpad:()=>Yr,Xbox360Pad:()=>hs,XboxInput:()=>Pl.sZ,_BabylonLoaderRegistered:()=>eb,_BasisTextureLoader:()=>Lb._BasisTextureLoader,_CommonDispose:()=>Qs,_CommonInit:()=>$s,_CreationDataStorage:()=>zt,_DDSTextureLoader:()=>Wm._DDSTextureLoader,_ENVTextureLoader:()=>Hm._ENVTextureLoader,_ExrTextureLoader:()=>Bb._ExrTextureLoader,_GetCompatibleTextureLoader:()=>ch.gT,_HDRTextureLoader:()=>Fb._HDRTextureLoader,_InstancesBatch:()=>Ht,_KTXTextureLoader:()=>Xm._KTXTextureLoader,_MeshCollisionData:()=>It,_OcclusionDataStorage:()=>Nl,_PrimaryIsoTriangle:()=>hl,_TGATextureLoader:()=>Nb._TGATextureLoader,_TimeToken:()=>Vl,_UpdateRGBDAsync:()=>Wl.gW,_forceSceneHelpersToBundle:()=>Mv,_forceTransformFeedbackToBundle:()=>Ul,_injectLTSFileTools:()=>$m.rh,_staticOffsetValueColor3:()=>pe.eA,_staticOffsetValueColor4:()=>pe.nl,_staticOffsetValueQuaternion:()=>pe.s$,_staticOffsetValueSize:()=>pe.vF,_staticOffsetValueVector2:()=>pe.rq,_staticOffsetValueVector3:()=>pe.y4,addClipPlaneUniforms:()=>Ln.TV,allocateAndCopyTypedBuffer:()=>Xs.kZ,anaglyphPixelShader:()=>lw.anaglyphPixelShader,anaglyphPixelShaderWGSL:()=>hw.anaglyphPixelShaderWGSL,appendSceneAsync:()=>ug,backbufferColorTextureHandle:()=>Np,backbufferDepthStencilTextureHandle:()=>Fp,backgroundPixelShader:()=>_b.backgroundPixelShader,backgroundPixelShaderWGSL:()=>fb.backgroundPixelShaderWGSL,backgroundVertexShader:()=>pb.backgroundVertexShader,backgroundVertexShaderWGSL:()=>db.backgroundVertexShaderWGSL,bilateralBlurPixelShader:()=>NN.bilateralBlurPixelShader,bilateralBlurPixelShaderWGSL:()=>VN.bilateralBlurPixelShaderWGSL,bilateralBlurQualityPixelShader:()=>FN.bilateralBlurQualityPixelShader,bilateralBlurQualityPixelShaderWGSL:()=>kN.bilateralBlurQualityPixelShaderWGSL,bindClipPlane:()=>Ln.gS,blackAndWhitePixelShader:()=>ow.blackAndWhitePixelShader,blackAndWhitePixelShaderWGSL:()=>aw.blackAndWhitePixelShaderWGSL,bloomMergePixelShader:()=>ZD.bloomMergePixelShader,bloomMergePixelShaderWGSL:()=>JD.bloomMergePixelShaderWGSL,bonesDeclaration:()=>CS.bonesDeclaration,bonesDeclarationWGSL:()=>SS.bonesDeclarationWGSL,bonesVertex:()=>yS.bonesVertex,bonesVertexWGSL:()=>TS.bonesVertexWGSL,boundingBoxRendererPixelShader:()=>qN.boundingBoxRendererPixelShader,boundingBoxRendererPixelShaderWGSL:()=>KN.boundingBoxRendererPixelShaderWGSL,boundingBoxRendererVertexShader:()=>YN.boundingBoxRendererVertexShader,boundingBoxRendererVertexShaderWGSL:()=>jN.boundingBoxRendererVertexShaderWGSL,bumpFragment:()=>tT.bumpFragment,bumpFragmentFunctions:()=>rT.bumpFragmentFunctions,bumpFragmentFunctionsWGSL:()=>eT.bumpFragmentFunctionsWGSL,bumpFragmentMainFunctions:()=>iT.bumpFragmentMainFunctions,bumpFragmentMainFunctionsWGSL:()=>JS.bumpFragmentMainFunctionsWGSL,bumpFragmentWGSL:()=>ZS.bumpFragmentWGSL,captureEquirectangularFromScene:()=>KI,chromaticAberrationPixelShader:()=>rD.chromaticAberrationPixelShader,chromaticAberrationPixelShaderWGSL:()=>YD.chromaticAberrationPixelShaderWGSL,circleOfConfusionPixelShader:()=>$D.circleOfConfusionPixelShader,circleOfConfusionPixelShaderWGSL:()=>QD.circleOfConfusionPixelShaderWGSL,className:()=>Ue.s7,clipPlaneFragment:()=>CT.clipPlaneFragment,clipPlaneFragmentDeclaration:()=>yT.clipPlaneFragmentDeclaration,clipPlaneFragmentDeclarationWGSL:()=>bT.clipPlaneFragmentDeclarationWGSL,clipPlaneFragmentWGSL:()=>xT.clipPlaneFragmentWGSL,clipPlaneVertex:()=>ET.clipPlaneVertex,clipPlaneVertexDeclaration:()=>PT.clipPlaneVertexDeclaration,clipPlaneVertexDeclarationWGSL:()=>TT.clipPlaneVertexDeclarationWGSL,clipPlaneVertexWGSL:()=>ST.clipPlaneVertexWGSL,colorCorrectionPixelShader:()=>dw.colorCorrectionPixelShader,colorCorrectionPixelShaderWGSL:()=>fw.colorCorrectionPixelShaderWGSL,colorPixelShader:()=>xb.colorPixelShader,colorPixelShaderWGSL:()=>FA.colorPixelShaderWGSL,colorVertexShader:()=>bb.colorVertexShader,colorVertexShaderWGSL:()=>LA.colorVertexShaderWGSL,computeMaxExtents:()=>CE,convolutionPixelShader:()=>cw.convolutionPixelShader,convolutionPixelShaderWGSL:()=>uw.convolutionPixelShaderWGSL,copyTexture3DLayerToTexturePixelShader:()=>sF.copyTexture3DLayerToTexturePixelShader,copyTexture3DLayerToTexturePixelShaderWGSL:()=>nF.copyTexture3DLayerToTexturePixelShaderWGSL,copyTextureToTexturePixelShader:()=>eM.copyTextureToTexturePixelShader,copyTextureToTexturePixelShaderWGSL:()=>tM.copyTextureToTexturePixelShaderWGSL,createDetailMapPlugin:()=>Cy,createPBRAnisotropicPlugin:()=>gy,createPBRBRDFPlugin:()=>vy,createPBRClearCoatPlugin:()=>xy,createPBRIridescencePlugin:()=>by,createPBRSheenPlugin:()=>Sy,createPBRSubSurfacePlugin:()=>Ty,createYieldingScheduler:()=>We,defaultPixelShader:()=>Ly.defaultPixelShader,defaultPixelShaderWGSL:()=>Vy.defaultPixelShaderWGSL,defaultVertexShader:()=>By.defaultVertexShader,defaultVertexShaderWGSL:()=>ky.defaultVertexShaderWGSL,depthBoxBlurPixelShader:()=>Ox.depthBoxBlurPixelShader,depthBoxBlurPixelShaderWGSL:()=>Ax.depthBoxBlurPixelShaderWGSL,depthOfFieldMergePixelShader:()=>KD.depthOfFieldMergePixelShader,depthOfFieldMergePixelShaderWGSL:()=>jD.depthOfFieldMergePixelShaderWGSL,depthPixelShader:()=>dx.depthPixelShader,depthPixelShaderWGSL:()=>zN.depthPixelShaderWGSL,depthVertexShader:()=>fx.depthVertexShader,depthVertexShaderWGSL:()=>WN.depthVertexShaderWGSL,displayPassPixelShader:()=>bw.displayPassPixelShader,displayPassPixelShaderWGSL:()=>Sw.displayPassPixelShaderWGSL,editableInPropertyPage:()=>t_,expandToProperty:()=>$e.$z,extractHighlightsPixelShader:()=>ew.extractHighlightsPixelShader,extractHighlightsPixelShaderWGSL:()=>tw.extractHighlightsPixelShaderWGSL,extractMinAndMax:()=>mt.b8,extractMinAndMaxIndexed:()=>mt.cD,filterPixelShader:()=>mw.filterPixelShader,filterPixelShaderWGSL:()=>gw.filterPixelShaderWGSL,fluidRenderingBilateralBlurPixelShader:()=>fN.fluidRenderingBilateralBlurPixelShader,fluidRenderingBilateralBlurPixelShaderWGSL:()=>yN.fluidRenderingBilateralBlurPixelShaderWGSL,fluidRenderingParticleDepthPixelShader:()=>oN.fluidRenderingParticleDepthPixelShader,fluidRenderingParticleDepthPixelShaderWGSL:()=>gN.fluidRenderingParticleDepthPixelShaderWGSL,fluidRenderingParticleDepthVertexShader:()=>nN.fluidRenderingParticleDepthVertexShader,fluidRenderingParticleDepthVertexShaderWGSL:()=>mN.fluidRenderingParticleDepthVertexShaderWGSL,fluidRenderingParticleDiffusePixelShader:()=>dN.fluidRenderingParticleDiffusePixelShader,fluidRenderingParticleDiffusePixelShaderWGSL:()=>CN.fluidRenderingParticleDiffusePixelShaderWGSL,fluidRenderingParticleDiffuseVertexShader:()=>uN,fluidRenderingParticleDiffuseVertexShaderWGSL:()=>TN,fluidRenderingParticleThicknessPixelShader:()=>lN.fluidRenderingParticleThicknessPixelShader,fluidRenderingParticleThicknessPixelShaderWGSL:()=>xN.fluidRenderingParticleThicknessPixelShaderWGSL,fluidRenderingParticleThicknessVertexShader:()=>aN.fluidRenderingParticleThicknessVertexShader,fluidRenderingParticleThicknessVertexShaderWGSL:()=>vN.fluidRenderingParticleThicknessVertexShaderWGSL,fluidRenderingRenderPixelShader:()=>_N.fluidRenderingRenderPixelShader,fluidRenderingRenderPixelShaderWGSL:()=>PN.fluidRenderingRenderPixelShaderWGSL,fluidRenderingStandardBlurPixelShader:()=>pN.fluidRenderingStandardBlurPixelShader,fluidRenderingStandardBlurPixelShaderWGSL:()=>EN.fluidRenderingStandardBlurPixelShaderWGSL,fogFragmentDeclaration:()=>RT.fogFragmentDeclaration,fogFragmentDeclarationWGSL:()=>AT.fogFragmentDeclarationWGSL,fxaaPixelShader:()=>iw.fxaaPixelShader,fxaaPixelShaderWGSL:()=>sw.fxaaPixelShaderWGSL,fxaaVertexShader:()=>rw.fxaaVertexShader,fxaaVertexShaderWGSL:()=>nw.fxaaVertexShaderWGSL,gaussianSplattingVertexDeclaration:()=>uy.Q,gaussianSplattingVertexDeclarationWGSL:()=>hy,geometryPixelShader:()=>WO.geometryPixelShader,geometryPixelShaderWGSL:()=>HN.geometryPixelShaderWGSL,geometryVertexShader:()=>HO.geometryVertexShader,geometryVertexShaderWGSL:()=>XN.geometryVertexShaderWGSL,getDimensionsFromTextureSize:()=>Zp,getRichTypeFromValue:()=>Wu,glowBlurPostProcessPixelShader:()=>jv.glowBlurPostProcessPixelShader,glowBlurPostProcessPixelShaderWGSL:()=>Zv.glowBlurPostProcessPixelShaderWGSL,glowMapGenerationPixelShader:()=>Wv.glowMapGenerationPixelShader,glowMapGenerationPixelShaderWGSL:()=>Xv.glowMapGenerationPixelShaderWGSL,glowMapGenerationVertexShader:()=>Hv.glowMapGenerationVertexShader,glowMapGenerationVertexShaderWGSL:()=>qv.glowMapGenerationVertexShaderWGSL,glowMapMergePixelShader:()=>Yv.glowMapMergePixelShader,glowMapMergePixelShaderWGSL:()=>$v.glowMapMergePixelShaderWGSL,glowMapMergeVertexShader:()=>Kv.glowMapMergeVertexShader,glowMapMergeVertexShaderWGSL:()=>Qv.glowMapMergeVertexShaderWGSL,grainPixelShader:()=>XD.grainPixelShader,grainPixelShaderWGSL:()=>qD.grainPixelShaderWGSL,hdrFilteringPixelShader:()=>aS.hdrFilteringPixelShader,hdrFilteringPixelShaderWGSL:()=>hS.hdrFilteringPixelShaderWGSL,hdrFilteringVertexShader:()=>oS.hdrFilteringVertexShader,hdrFilteringVertexShaderWGSL:()=>lS.hdrFilteringVertexShaderWGSL,helperFunctions:()=>jS.helperFunctions,helperFunctionsWGSL:()=>_c.helperFunctionsWGSL,highlightsPixelShader:()=>vw.highlightsPixelShader,highlightsPixelShaderWGSL:()=>xw.highlightsPixelShaderWGSL,iblCombineVoxelGridsPixelShader:()=>SF.iblCombineVoxelGridsPixelShader,iblCombineVoxelGridsPixelShaderWGSL:()=>bF.iblCombineVoxelGridsPixelShaderWGSL,iblGenerateVoxelMipPixelShader:()=>TF.iblGenerateVoxelMipPixelShader,iblGenerateVoxelMipPixelShaderWGSL:()=>CF.iblGenerateVoxelMipPixelShaderWGSL,iblShadowAccumulationPixelShader:()=>fF.iblShadowAccumulationPixelShader,iblShadowAccumulationPixelShaderWGSL:()=>dF.iblShadowAccumulationPixelShaderWGSL,iblShadowDebugPixelShader:()=>lF.iblShadowDebugPixelShader,iblShadowDebugPixelShaderWGSL:()=>hF.iblShadowDebugPixelShaderWGSL,iblShadowGBufferDebugPixelShader:()=>yF.iblShadowGBufferDebugPixelShader,iblShadowGBufferDebugPixelShaderWGSL:()=>EF.iblShadowGBufferDebugPixelShaderWGSL,iblShadowSpatialBlurPixelShader:()=>uF.iblShadowSpatialBlurPixelShader,iblShadowSpatialBlurPixelShaderWGSL:()=>cF.iblShadowSpatialBlurPixelShaderWGSL,iblShadowVoxelTracingPixelShader:()=>oF.iblShadowVoxelTracingPixelShader,iblShadowVoxelTracingPixelShaderWGSL:()=>aF.iblShadowVoxelTracingPixelShaderWGSL,iblShadowsCdfxPixelShader:()=>AF.iblShadowsCdfxPixelShader,iblShadowsCdfxPixelShaderWGSL:()=>PF.iblShadowsCdfxPixelShaderWGSL,iblShadowsCdfyPixelShader:()=>IF.iblShadowsCdfyPixelShader,iblShadowsCdfyPixelShaderWGSL:()=>RF.iblShadowsCdfyPixelShaderWGSL,iblShadowsCombinePixelShader:()=>mF,iblShadowsCombinePixelShaderWGSL:()=>xF,iblShadowsIcdfxPixelShader:()=>OF.iblShadowsIcdfxPixelShader,iblShadowsIcdfxPixelShaderWGSL:()=>MF.iblShadowsIcdfxPixelShaderWGSL,iblShadowsIcdfyPixelShader:()=>wF.iblShadowsIcdfyPixelShader,iblShadowsIcdfyPixelShaderWGSL:()=>DF.iblShadowsIcdfyPixelShaderWGSL,iblShadowsImportanceSamplingDebugPixelShader:()=>FF.iblShadowsImportanceSamplingDebugPixelShader,iblShadowsImportanceSamplingDebugPixelShaderWGSL:()=>NF.iblShadowsImportanceSamplingDebugPixelShaderWGSL,iblVoxelGrid2dArrayDebugPixelShader:()=>LF.iblVoxelGrid2dArrayDebugPixelShader,iblVoxelGrid2dArrayDebugPixelShaderWGSL:()=>BF.iblVoxelGrid2dArrayDebugPixelShaderWGSL,iblVoxelGrid3dDebugPixelShader:()=>zF.iblVoxelGrid3dDebugPixelShader,iblVoxelGrid3dDebugPixelShaderWGSL:()=>WF.iblVoxelGrid3dDebugPixelShaderWGSL,iblVoxelGridPixelShader:()=>VF.iblVoxelGridPixelShader,iblVoxelGridPixelShaderWGSL:()=>UF.iblVoxelGridPixelShaderWGSL,iblVoxelGridVertexShader:()=>kF.iblVoxelGridVertexShader,iblVoxelGridVertexShaderWGSL:()=>GF.iblVoxelGridVertexShaderWGSL,iblVoxelSlabDebugPixelShader:()=>XF.iblVoxelSlabDebugPixelShader,iblVoxelSlabDebugPixelShaderWGSL:()=>YF.iblVoxelSlabDebugPixelShaderWGSL,iblVoxelSlabDebugVertexShader:()=>HF.iblVoxelSlabDebugVertexShader,iblVoxelSlabDebugVertexShaderWGSL:()=>qF.iblVoxelSlabDebugVertexShaderWGSL,imageProcessingDeclaration:()=>$S.imageProcessingDeclaration,imageProcessingDeclarationWGSL:()=>YS.imageProcessingDeclarationWGSL,imageProcessingFunctions:()=>QS.imageProcessingFunctions,imageProcessingFunctionsWGSL:()=>KS.imageProcessingFunctionsWGSL,imageProcessingPixelShader:()=>WD.imageProcessingPixelShader,imageProcessingPixelShaderWGSL:()=>zD.imageProcessingPixelShaderWGSL,importAnimationsAsync:()=>gg,inlineScheduler:()=>ze,kernelBlurPixelShader:()=>DD.kernelBlurPixelShader,kernelBlurPixelShaderWGSL:()=>ND.kernelBlurPixelShaderWGSL,kernelBlurVertexShader:()=>wD.kernelBlurVertexShader,kernelBlurVertexShaderWGSL:()=>FD.kernelBlurVertexShaderWGSL,layerPixelShader:()=>Jv.layerPixelShader,layerPixelShaderWGSL:()=>tx.layerPixelShaderWGSL,layerVertexShader:()=>ex.layerVertexShader,layerVertexShaderWGSL:()=>ix.layerVertexShaderWGSL,lensFlarePixelShader:()=>ox.lensFlarePixelShader,lensFlarePixelShaderWGSL:()=>lx.lensFlarePixelShaderWGSL,lensFlareVertexShader:()=>ax.lensFlareVertexShader,lensFlareVertexShaderWGSL:()=>hx.lensFlareVertexShaderWGSL,lightFragment:()=>LT.lightFragment,lightFragmentDeclaration:()=>FT.lightFragmentDeclaration,lightFragmentWGSL:()=>IT.lightFragmentWGSL,lightUboDeclaration:()=>BT.lightUboDeclaration,lightUboDeclarationWGSL:()=>MT.lightUboDeclarationWGSL,lightVxFragmentDeclaration:()=>kT.lightVxFragmentDeclaration,lightVxUboDeclaration:()=>VT.lightVxUboDeclaration,lightVxUboDeclarationWGSL:()=>OT.lightVxUboDeclarationWGSL,lightsFragmentFunctions:()=>UT.lightsFragmentFunctions,lightsFragmentFunctionsWGSL:()=>DT.lightsFragmentFunctionsWGSL,linePixelShader:()=>$N.linePixelShader,linePixelShaderWGSL:()=>ZN.linePixelShaderWGSL,lineVertexShader:()=>QN.lineVertexShader,lineVertexShaderWGSL:()=>JN.lineVertexShaderWGSL,loadAssetContainerAsync:()=>pg,loadSceneAsync:()=>lg,lodCubePixelShader:()=>wR.lodCubePixelShader,lodCubePixelShaderWGSL:()=>FR.lodCubePixelShaderWGSL,lodPixelShader:()=>NR.lodPixelShader,lodPixelShaderWGSL:()=>LR.lodPixelShaderWGSL,makeAsyncFunction:()=>Ke,makeSyncFunction:()=>Ye,meshUVSpaceRendererFinaliserPixelShader:()=>GA.meshUVSpaceRendererFinaliserPixelShader,meshUVSpaceRendererFinaliserPixelShaderWGSL:()=>YA.meshUVSpaceRendererFinaliserPixelShaderWGSL,meshUVSpaceRendererFinaliserVertexShader:()=>zA.meshUVSpaceRendererFinaliserVertexShader,meshUVSpaceRendererFinaliserVertexShaderWGSL:()=>KA.meshUVSpaceRendererFinaliserVertexShaderWGSL,meshUVSpaceRendererMaskerPixelShader:()=>UA.meshUVSpaceRendererMaskerPixelShader,meshUVSpaceRendererMaskerPixelShaderWGSL:()=>qA.meshUVSpaceRendererMaskerPixelShaderWGSL,meshUVSpaceRendererMaskerVertexShader:()=>kA.meshUVSpaceRendererMaskerVertexShader,meshUVSpaceRendererMaskerVertexShaderWGSL:()=>XA.meshUVSpaceRendererMaskerVertexShaderWGSL,meshUVSpaceRendererPixelShader:()=>VA.meshUVSpaceRendererPixelShader,meshUVSpaceRendererPixelShaderWGSL:()=>HA.meshUVSpaceRendererPixelShaderWGSL,meshUVSpaceRendererVertexShader:()=>BA.meshUVSpaceRendererVertexShader,meshUVSpaceRendererVertexShaderWGSL:()=>WA.meshUVSpaceRendererVertexShaderWGSL,morphTargetsVertex:()=>IS.morphTargetsVertex,morphTargetsVertexDeclaration:()=>MS.morphTargetsVertexDeclaration,morphTargetsVertexDeclarationWGSL:()=>PS.morphTargetsVertexDeclarationWGSL,morphTargetsVertexGlobal:()=>OS.morphTargetsVertexGlobal,morphTargetsVertexGlobalDeclaration:()=>DS.morphTargetsVertexGlobalDeclaration,morphTargetsVertexGlobalDeclarationWGSL:()=>RS.morphTargetsVertexGlobalDeclarationWGSL,morphTargetsVertexGlobalWGSL:()=>AS.morphTargetsVertexGlobalWGSL,morphTargetsVertexWGSL:()=>ES.morphTargetsVertexWGSL,motionBlurPixelShader:()=>pw.motionBlurPixelShader,motionBlurPixelShaderWGSL:()=>_w.motionBlurPixelShaderWGSL,nativeOverride:()=>$e.Cx,normalizeEnvInfo:()=>Wl.RZ,oitBackBlendPixelShader:()=>KF.oitBackBlendPixelShader,oitBackBlendPixelShaderWGSL:()=>$F.oitBackBlendPixelShaderWGSL,oitFinalPixelShader:()=>jF.oitFinalPixelShader,oitFinalPixelShaderWGSL:()=>QF.oitFinalPixelShaderWGSL,outlinePixelShader:()=>eF.outlinePixelShader,outlinePixelShaderWGSL:()=>iF.outlinePixelShaderWGSL,outlineVertexShader:()=>tF.outlineVertexShader,outlineVertexShaderWGSL:()=>rF.outlineVertexShaderWGSL,packingFunctions:()=>lT.packingFunctions,packingFunctionsWGSL:()=>nT.packingFunctionsWGSL,particlesPixelShader:()=>wM.particlesPixelShader,particlesPixelShaderWGSL:()=>FM.particlesPixelShaderWGSL,particlesVertexShader:()=>NM.particlesVertexShader,particlesVertexShaderWGSL:()=>LM.particlesVertexShaderWGSL,passCubePixelShader:()=>BD.passCubePixelShader,passCubePixelShaderWGSL:()=>kD.passCubePixelShaderWGSL,passPixelShader:()=>LD.passPixelShader,passPixelShaderWGSL:()=>VD.passPixelShaderWGSL,pbrPixelShader:()=>Ib.pbrPixelShader,pbrPixelShaderWGSL:()=>Ab.pbrPixelShaderWGSL,pbrVertexShader:()=>Rb.pbrVertexShader,pbrVertexShaderWGSL:()=>Pb.pbrVertexShaderWGSL,pickingPixelShader:()=>So.pickingPixelShader,pickingPixelShaderWGSL:()=>Co.pickingPixelShaderWGSL,pickingVertexShader:()=>To.pickingVertexShader,pickingVertexShaderWGSL:()=>yo.pickingVertexShaderWGSL,postprocessVertexShader:()=>MD.postprocessVertexShader,postprocessVertexShaderWGSL:()=>OD.postprocessVertexShaderWGSL,prepareDefinesForClipPlanes:()=>Ln.Eq,prepareStringDefinesForClipPlanes:()=>Ln.tv,proceduralVertexShader:()=>nS.proceduralVertexShader,proceduralVertexShaderWGSL:()=>sS.proceduralVertexShaderWGSL,reflectionFunction:()=>HT.reflectionFunction,reflectionFunctionWGSL:()=>WT.reflectionFunctionWGSL,registerSceneLoaderPlugin:()=>ng,registerTextureLoader:()=>ch.kf,rgbdDecodePixelShader:()=>$I.rgbdDecodePixelShader,rgbdDecodePixelShaderWGSL:()=>ZI.rgbdDecodePixelShaderWGSL,rgbdEncodePixelShader:()=>QI.rgbdEncodePixelShader,rgbdEncodePixelShaderWGSL:()=>JI.rgbdEncodePixelShaderWGSL,rsmFullGlobalIlluminationPixelShader:()=>BN.rsmFullGlobalIlluminationPixelShader,rsmFullGlobalIlluminationPixelShaderWGSL:()=>GN.rsmFullGlobalIlluminationPixelShaderWGSL,rsmGlobalIlluminationPixelShader:()=>LN.rsmGlobalIlluminationPixelShader,rsmGlobalIlluminationPixelShaderWGSL:()=>UN.rsmGlobalIlluminationPixelShaderWGSL,runCoroutine:()=>He,runCoroutineAsync:()=>qe,runCoroutineSync:()=>Xe,screenSpaceReflection2BlurCombinerPixelShader:()=>CD.screenSpaceReflection2BlurCombinerPixelShader,screenSpaceReflection2BlurCombinerPixelShaderWGSL:()=>PD.screenSpaceReflection2BlurCombinerPixelShaderWGSL,screenSpaceReflection2BlurPixelShader:()=>TD.screenSpaceReflection2BlurPixelShader,screenSpaceReflection2BlurPixelShaderWGSL:()=>ED.screenSpaceReflection2BlurPixelShaderWGSL,screenSpaceReflection2PixelShader:()=>SD.screenSpaceReflection2PixelShader,screenSpaceReflection2PixelShaderWGSL:()=>yD.screenSpaceReflection2PixelShaderWGSL,serialize:()=>$e.lK,serializeAsCameraReference:()=>$e.fW,serializeAsColor3:()=>$e.jT,serializeAsColor4:()=>$e.qK,serializeAsColorCurves:()=>$e.wL,serializeAsFresnelParameters:()=>$e.Y9,serializeAsImageProcessingConfiguration:()=>$e.n1,serializeAsMatrix:()=>$e.GG,serializeAsMeshReference:()=>$e.xG,serializeAsQuaternion:()=>$e.bR,serializeAsTexture:()=>$e.uM,serializeAsVector2:()=>$e.WM,serializeAsVector3:()=>$e.P_,setAndStartTimer:()=>xd,setOpenGLOrientationForUV:()=>Tt.ge,setStereoscopicAnaglyphRigMode:()=>vs,setStereoscopicRigMode:()=>Ps,setVRRigMode:()=>fn,shadowMapFragment:()=>hT.shadowMapFragment,shadowMapFragmentSoftTransparentShadow:()=>Dx.shadowMapFragmentSoftTransparentShadow,shadowMapFragmentSoftTransparentShadowWGSL:()=>Rx.shadowMapFragmentSoftTransparentShadowWGSL,shadowMapFragmentWGSL:()=>oT.shadowMapFragmentWGSL,shadowMapPixelShader:()=>Ix.shadowMapPixelShader,shadowMapPixelShaderWGSL:()=>Ex.shadowMapPixelShaderWGSL,shadowMapVertexMetric:()=>aT.shadowMapVertexMetric,shadowMapVertexMetricWGSL:()=>sT.shadowMapVertexMetricWGSL,shadowMapVertexShader:()=>Mx.shadowMapVertexShader,shadowMapVertexShaderWGSL:()=>Px.shadowMapVertexShaderWGSL,shadowsFragmentFunctions:()=>GT.shadowsFragmentFunctions,shadowsFragmentFunctionsWGSL:()=>wT.shadowsFragmentFunctionsWGSL,shadowsVertex:()=>zT.shadowsVertex,shadowsVertexWGSL:()=>NT.shadowsVertexWGSL,sharpenPixelShader:()=>QO.sharpenPixelShader,sharpenPixelShaderWGSL:()=>HD.sharpenPixelShaderWGSL,spritesPixelShader:()=>rL.spritesPixelShader,spritesPixelShaderWGSL:()=>nL.spritesPixelShaderWGSL,spritesVertexShader:()=>sL.spritesVertexShader,spritesVertexShaderWGSL:()=>oL.spritesVertexShaderWGSL,ssao2PixelShader:()=>vD.ssao2PixelShader,ssao2PixelShaderWGSL:()=>xD.ssao2PixelShaderWGSL,ssaoCombinePixelShader:()=>aD.ssaoCombinePixelShader,ssaoCombinePixelShaderWGSL:()=>bD.ssaoCombinePixelShaderWGSL,textureSizeIsObject:()=>Qp,tonemapPixelShader:()=>Tw.tonemapPixelShader,tonemapPixelShaderWGSL:()=>Cw.tonemapPixelShaderWGSL,unregisterTextureLoader:()=>ch.hy,useOpenGLOrientationForUV:()=>Tt.rX,vrDistortionCorrectionPixelShader:()=>UD.vrDistortionCorrectionPixelShader,vrDistortionCorrectionPixelShaderWGSL:()=>GD.vrDistortionCorrectionPixelShaderWGSL});var t={};i.r(t),i.d(t,{AbstractButton3D:()=>nV,AdvancedDynamicTexture:()=>$B,AdvancedDynamicTextureInstrumentation:()=>QB,BaseGradient:()=>qB,BaseSlider:()=>IB,Button:()=>pB,Button3D:()=>oV,Checkbox:()=>mB,CheckboxGroup:()=>DB,ColorPicker:()=>bB,Container:()=>hB,Container3D:()=>aV,Control:()=>lB,Control3D:()=>rV,CornerHandle:()=>AV,CylinderPanel:()=>hV,DisplayGrid:()=>WB,Ellipse:()=>SB,FluentBackplateMaterial:()=>_V,FluentButtonMaterial:()=>xV,FluentMaterial:()=>uV,FluentMaterialDefines:()=>cV,FocusableButton:()=>TB,FrameGraphGUITask:()=>ZB,GUI3DManager:()=>QV,GizmoHandle:()=>EV,Grid:()=>xB,HandMenu:()=>fV,HandleMaterial:()=>CV,HandleState:()=>yV,HolographicBackplate:()=>mV,HolographicButton:()=>gV,HolographicSlate:()=>IV,Image:()=>fB,ImageBasedSlider:()=>HB,ImageScrollBar:()=>VB,InputPassword:()=>yB,InputText:()=>vB,InputTextArea:()=>CB,KeyPropertySet:()=>GB,Line:()=>EB,LinearGradient:()=>YB,MRDLBackplateMaterial:()=>kV,MRDLSliderBarMaterial:()=>FV,MRDLSliderThumbMaterial:()=>BV,MathTools:()=>aB,Matrix2D:()=>oB,Measure:()=>sB,MeshButton3D:()=>MV,MultiLine:()=>AB,MultiLinePoint:()=>PB,NearMenu:()=>OV,NodeRenderGraphGUIBlock:()=>JB,PlanePanel:()=>DV,RadialGradient:()=>KB,RadioButton:()=>RB,RadioGroup:()=>wB,Rectangle:()=>cB,ScatterPanel:()=>wV,ScrollBar:()=>BB,ScrollViewer:()=>kB,SelectionPanel:()=>FB,SelectorGroup:()=>OB,SideHandle:()=>PV,SlateGizmo:()=>RV,Slider:()=>MB,Slider3D:()=>UV,SliderGroup:()=>NB,SpherePanel:()=>GV,StackPanel:()=>_B,StackPanel3D:()=>zV,Style:()=>jB,TextBlock:()=>dB,TextWrapper:()=>gB,TextWrapping:()=>uB,ToggleButton:()=>UB,TouchButton3D:()=>bV,TouchHolographicButton:()=>SV,TouchHolographicButtonV3:()=>$V,TouchHolographicMenu:()=>dV,TouchMeshButton3D:()=>WV,ValueAndUnit:()=>JL,Vector2WithInfo:()=>nB,Vector3WithInfo:()=>iV,VirtualKeyboard:()=>zB,VolumeBasedPanel:()=>lV,XmlLoader:()=>tV,name:()=>XB});var s={};i.r(s),i.d(s,{LodDto:()=>ZK,lodEnum:()=>WK});var n={};i.r(n),i.d(n,{Part:()=>JK});var o={};i.r(o),i.d(o,{SerenitySwirlData:()=>tj,SerenitySwirlDto:()=>ej});var a={};i.r(a),i.d(a,{ArabicArchwayData:()=>sj,ArabicArchwayDrawingPart:()=>nj,ArabicArchwayDrawingPartShapes:()=>oj,ArabicArchwayDto:()=>rj,ArabicArchwayDtoBase:()=>ij});var l={};i.r(l),i.d(l,{ArabicArchway:()=>a,SerenitySwirl:()=>o});var h={};i.r(h),i.d(h,{EternalLoveData:()=>hj,EternalLoveDto:()=>lj,EternalLoveDtoBase:()=>aj});var c={};i.r(c),i.d(c,{EternalLove:()=>h});var u={};i.r(u),i.d(u,{CalmCupData:()=>dj,CalmCupDto:()=>uj,CalmCupDtoBase:()=>cj});var d={};i.r(d),i.d(d,{DragonCupData:()=>_j,DragonCupDto:()=>pj,DragonCupDtoBase:()=>fj,DragonCupModelDto:()=>mj});var f={};i.r(f),i.d(f,{CalmCup:()=>u,DragonCup:()=>d});var p={};i.r(p),i.d(p,{PhoneNestData:()=>xj,PhoneNestDrawDto:()=>yj,PhoneNestDrawingPart:()=>bj,PhoneNestDrawingPartShapes:()=>Sj,PhoneNestDto:()=>vj,PhoneNestDtoBase:()=>gj,PhoneNestMainPart:()=>Tj,PhoneNestModelDto:()=>Cj});var _={};i.r(_),i.d(_,{PhoneNest:()=>p});var m={};i.r(m),i.d(m,{SpicyBoxData:()=>Aj,SpicyBoxDto:()=>Pj,SpicyBoxDtoBase:()=>Ej,SpicyBoxModelDto:()=>Rj});var g={};i.r(g),i.d(g,{SpicyBox:()=>m});var v={};i.r(v),i.d(v,{Boxes:()=>g,Cups:()=>f,Desktop:()=>_,Medals:()=>c,Vases:()=>l});var x={};i.r(x),i.d(x,{ZenHideoutData:()=>Oj,ZenHideoutDrawingPart:()=>Dj,ZenHideoutDrawingPartShapes:()=>wj,ZenHideoutDto:()=>Mj,ZenHideoutDtoBase:()=>Ij});var b={};i.r(b),i.d(b,{ZenHideout:()=>x});var S={};i.r(S),i.d(S,{BeamPart:()=>Hj,CeilingPart:()=>Jj,ColumnPart:()=>Wj,CornerEntranceDto:()=>t$,CornerEntrancePart:()=>$j,CornerPart:()=>zj,CornerStairDto:()=>Kj,CornerStairPart:()=>jj,FloorPart:()=>e$,Houses:()=>b,RoofBeamsPart:()=>qj,RoofCoverOneSidedDto:()=>Qj,RoofCoverPart:()=>Zj,RoofPanelPart:()=>Yj,RoofPart:()=>Xj,SandwitchPanelDto:()=>Vj,SandwitchPanelFlexDto:()=>kj,SandwitchPart:()=>Uj,SandwitchPartFlex:()=>Gj,WindowCornerDto:()=>Nj,WindowCornerPart:()=>Bj,WindowRectangularDto:()=>Fj,WindowRectangularPart:()=>Lj});var T={};i.r(T),i.d(T,{WingtipVillaData:()=>r$,WingtipVillaDto:()=>i$});var C={};i.r(C),i.d(C,{ChirpyChaletData:()=>n$,ChirpyChaletDto:()=>s$});var y={};i.r(y),i.d(y,{ChirpyChalet:()=>C,WingtipVilla:()=>T});var E={};i.r(E),i.d(E,{BirdHouses:()=>y});var P={};i.r(P),i.d(P,{SnakeChairData:()=>l$,SnakeChairDrawDto:()=>f$,SnakeChairDrawingPart:()=>h$,SnakeChairDrawingPartShapes:()=>c$,SnakeChairDto:()=>a$,SnakeChairDtoBase:()=>o$,SnakeChairMainPart:()=>u$,SnakeChairModelDto:()=>d$});var A={};i.r(A),i.d(A,{SnakeChair:()=>P});var R={};i.r(R),i.d(R,{ElegantTableData:()=>m$,ElegantTableDrawDto:()=>C$,ElegantTableDrawingPart:()=>g$,ElegantTableDrawingPartShapes:()=>v$,ElegantTableDto:()=>_$,ElegantTableDtoBase:()=>p$,ElegantTableLegByIndexDto:()=>S$,ElegantTableLegPart:()=>x$,ElegantTableModelDto:()=>T$,ElegantTableTopPart:()=>b$});var I={};i.r(I),i.d(I,{GoodCoffeeTableData:()=>P$,GoodCoffeeTableDrawDto:()=>N$,GoodCoffeeTableDrawingPart:()=>A$,GoodCoffeeTableDrawingPartShapes:()=>R$,GoodCoffeeTableDto:()=>E$,GoodCoffeeTableDtoBase:()=>y$,GoodCoffeeTableLegByIndexDto:()=>D$,GoodCoffeeTableLegPart:()=>I$,GoodCoffeeTableModelDto:()=>w$,GoodCoffeeTableShelfPart:()=>M$,GoodCoffeeTableTopPart:()=>O$});var M={};i.r(M),i.d(M,{SnakeTableData:()=>B$,SnakeTableDrawDto:()=>z$,SnakeTableDrawingPart:()=>V$,SnakeTableDrawingPartShapes:()=>k$,SnakeTableDto:()=>L$,SnakeTableDtoBase:()=>F$,SnakeTableMainPart:()=>U$,SnakeTableModelDto:()=>G$});var O={};i.r(O),i.d(O,{ElegantTable:()=>R,GoodCoffeeTable:()=>I,SnakeTable:()=>M});var D={};i.r(D),i.d(D,{Chairs:()=>A,Tables:()=>O});var w={};i.r(w),i.d(w,{Architecture:()=>S,Enums:()=>s,Furniture:()=>D,KidsCorner:()=>E,Shared:()=>n,ThreeDPrinting:()=>v});var N={};i.r(N),i.d(N,{FontDefinition:()=>K$,Text3DData:()=>q$,Text3DDto:()=>H$,Text3DFaceDefinitionDto:()=>$$,Text3DFaceDto:()=>X$,Text3DLetterByIndexDto:()=>Y$,Text3DModelDto:()=>j$,Texts3DFaceDto:()=>Q$,faceTextVarEnum:()=>YK,faceTypeEnum:()=>KK,fontVariantsEnum:()=>qK,fontsEnum:()=>XK,fontsModel:()=>W$,recAlignmentEnum:()=>jK});var F={};i.r(F),i.d(F,{PyramidSimpeByIndexDto:()=>tQ,PyramidSimpleAffectorsDto:()=>J$,PyramidSimpleCellPart:()=>cQ,PyramidSimpleData:()=>eQ,PyramidSimpleDto:()=>Z$,PyramidSimpleFacePart:()=>uQ,PyramidSimpleModelCellDto:()=>nQ,PyramidSimpleModelCellsDto:()=>rQ,PyramidSimpleModelCellsIndexDto:()=>sQ,PyramidSimpleModelDto:()=>iQ,PyramidSimpleModelFaceCellIndexDto:()=>aQ,PyramidSimpleModelFaceCellsUIndexDto:()=>lQ,PyramidSimpleModelFaceCellsVIndexDto:()=>hQ,PyramidSimpleModelFaceIndexDto:()=>oQ});var L={};i.r(L),i.d(L,{PyramidSimple:()=>F});var B={};i.r(B),i.d(B,{FacePatterns:()=>L});var V={};i.r(V),i.d(V,{outputShapeEnum:()=>dQ});var k={};i.r(k),i.d(k,{Enums:()=>V,Patterns:()=>B,Text3D:()=>N});var U={};i.r(U),i.d(U,{Asset:()=>ZH,BabylonCamera:()=>wH,BabylonGaussianSplatting:()=>kH,BabylonGizmo:()=>qH,BabylonGui:()=>VH,BabylonIO:()=>NH,BabylonLight:()=>LH,BabylonMaterial:()=>FH,BabylonMesh:()=>UH,BabylonMeshBuilder:()=>XH,BabylonNode:()=>$H,BabylonPick:()=>zH,BabylonRay:()=>WH,BabylonScene:()=>jH,BabylonTexture:()=>BH,BabylonTools:()=>HH,BabylonTransforms:()=>GH,BabylonWebXR:()=>YH,Base:()=>Kz,Draw:()=>QH,JSCAD:()=>nX,JSON:()=>JH,Line:()=>eX,Manifold:()=>oX,OCCT:()=>Yz,Polyline:()=>tX,Tag:()=>iX,Time:()=>rX,Verb:()=>sX});var G=i(96772),z=i(43279),W=i(94212),H=i(11084),X=i(56225);class q{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new z.cP,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 e=this._condition.serialize();return e.children.push(i),t&&t.children.push(e),e}return t&&t.children.push(i),i}}q._SerializeValueAsString=e=>"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e instanceof W.I9?e.x+", "+e.y:e instanceof W.Pq?e.x+", "+e.y+", "+e.z:e instanceof H.v9?e.r+", "+e.g+", "+e.b:e instanceof H.ov?e.r+", "+e.g+", "+e.b+", "+e.a:e,q._GetTargetProperty=e=>({name:"target",targetType:e._isMesh?"MeshProperties":e._isLight?"LightProperties":e._isCamera?"CameraProperties":e._isMaterial?"MaterialProperties":"SceneProperties",value:e._isScene?"Scene":e.name}),(0,X.Y5)("BABYLON.Action",q);var Y=i(89357);class K{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 j extends K{static get IsEqual(){return j._IsEqual}static get IsDifferent(){return j._IsDifferent}static get IsGreater(){return j._IsGreater}static get IsLesser(){return j._IsLesser}constructor(e,t,i,r,s=j.IsEqual){super(e),this.propertyPath=i,this.value=r,this.operator=s,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case j.IsGreater:return this._effectiveTarget[this._property]>this.value;case j.IsLesser:return this._effectiveTarget[this._property]-1&&this._scene.actionManagers.splice(e,1);const t=this._scene.meshes.filter((e=>e.actionManager===this));for(const e of t)e.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=ue.OnPickTrigger&&t.trigger<=ue.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=ue.OnPickTrigger&&t.trigger<=ue.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===ue.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(Z.V.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,ue.Triggers[e.trigger]?ue.Triggers[e.trigger]++:ue.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){const t=this.actions.indexOf(e);return-1!==t&&(this.actions.splice(t,1),ue.Triggers[e.trigger]-=1,0===ue.Triggers[e.trigger]&&delete ue.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0)}processTrigger(e,t){for(let i=0;i{if(null===r){const e=parseFloat(t);return"true"===t||"false"===t?"true"===t:isNaN(e)?t:e}const s=r.split("."),n=t.split(",");for(let e=0;e{if(e.detached)return;const h=[];let c=null,u=null;const d=e.combine&&e.combine.length>0;if(2===e.type?h.push(r):h.push(t),d){const t=[];for(let i=0;i{const i=(0,X.n9)("BABYLON."+e);return i&&new i(...t)})(e.name,h);if(f instanceof K&&null!==o){const e=new ne(t,o);a?a.then(e):r.registerAction(e),a=e}null===l?f instanceof K?(o=f,f=a):(o=null,a?a.then(f):r.registerAction(f)):l.push(f);for(let i=0;i0){const e=s.properties[0].value,t=null===s.properties[0].targetType?e:i.getMeshByName(e);t._meshId&&(t.mesh=i.getMeshById(t._meshId)),r={trigger:ue[s.name],parameter:t}}else r=ue[s.name];for(let e=0;e{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()}))}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[q._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:q._SerializeValueAsString(this.value)},{name:"duration",value:q._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:q._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}}(0,X.Y5)("BABYLON.InterpolateValueAction",_e);var me=i(66418);class ge{constructor(){this.enableBlending=!1,this.blendingSpeed=.01,this.loopMode=pe.X5.ANIMATIONLOOPMODE_CYCLE}}var ve=i(50324);class xe{constructor(){this._easingMode=xe.EASINGMODE_EASEIN}setEasingMode(e){const t=Math.min(Math.max(e,0),2);this._easingMode=t}getEasingMode(){return this._easingMode}easeInCore(e){throw new Error("You must implement this method")}ease(e){switch(this._easingMode){case xe.EASINGMODE_EASEIN:return this.easeInCore(e);case xe.EASINGMODE_EASEOUT:return 1-this.easeInCore(1-e)}return e>=.5?.5*(1-this.easeInCore(2*(1-e)))+.5:.5*this.easeInCore(2*e)}}xe.EASINGMODE_EASEIN=0,xe.EASINGMODE_EASEOUT=1,xe.EASINGMODE_EASEINOUT=2;class be extends xe{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class Se extends xe{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 Te extends xe{constructor(e=3,t=2){super(),this.bounces=e,this.bounciness=t}easeInCore(e){const t=Math.max(0,this.bounces);let i=this.bounciness;i<=1&&(i=1.001);const r=Math.pow(i,t),s=1-i,n=(1-r)/s+.5*r,o=e*n,a=Math.log(-o*(1-i)+1)/Math.log(i),l=Math.floor(a),h=l+1,c=(1-Math.pow(i,l))/(s*n),u=.5*(c+(1-Math.pow(i,h))/(s*n)),d=e-u,f=u-c;return-Math.pow(1/i,t-l)/(f*f)*(d-f)*(d+f)}}class Ce extends xe{easeInCore(e){return e*e*e}}class ye extends xe{constructor(e=3,t=3){super(),this.oscillations=e,this.springiness=t}easeInCore(e){let t;const i=Math.max(0,this.oscillations),r=Math.max(0,this.springiness);return t=0==r?e:(Math.exp(r*e)-1)/(Math.exp(r)-1),t*Math.sin((6.283185307179586*i+1.5707963267948966)*e)}}class Ee extends xe{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 Pe extends xe{constructor(e=2){super(),this.power=e}easeInCore(e){const t=Math.max(0,this.power);return Math.pow(e,t)}}class Ae extends xe{easeInCore(e){return e*e}}class Re extends xe{easeInCore(e){return e*e*e*e}}class Ie extends xe{easeInCore(e){return e*e*e*e*e}}class Me extends xe{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}class Oe extends xe{constructor(e=0,t=0,i=1,r=1){super(),this.x1=e,this.y1=t,this.x2=i,this.y2=r}easeInCore(e){return ve.vr.Interpolate(e,this.x1,this.y1,this.x2,this.y2)}}var De=i(34493);class we{constructor(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}_clone(){return new we(this.frame,this.action,this.onlyOnce)}}var Ne,Fe=i(7042);!function(e){e[e.NONE=0]="NONE",e[e.STEP=1]="STEP"}(Ne||(Ne={}));var Le,Be=i(888);class Ve{constructor(e){this._path=e,this._onchange=new Array,this.value=0,this.animations=[]}getPoint(){const e=this._path.getPointAtLengthPosition(this.value);return new W.Pq(e.x,0,e.y)}moveAhead(e=.002){return this.move(e),this}moveBack(e=.002){return this.move(-e),this}move(e){if(Math.abs(e)>1)throw"step size should be less than 1.";return this.value+=e,this._ensureLimits(),this._raiseOnChange(),this}_ensureLimits(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this}_raiseOnChange(){return this._onchange.forEach((e=>e(this))),this}onchange(e){return this._onchange.push(e),this}}!function(e){e[e.Include=0]="Include",e[e.Exclude=1]="Exclude"}(Le||(Le={}));class ke{constructor(e,t=0){this.mode=t,this.disabled=!1,this._targetNames=new Set,e&&this.addTargetName(e)}addTargetName(e){if(Array.isArray(e))for(const t of e)this._targetNames.add(t);else this._targetNames.add(e)}removeTargetName(e){if(Array.isArray(e))for(const t of e)this._targetNames.delete(t);else this._targetNames.delete(e)}hasTarget(e){return this._targetNames.has(e)}retainsTarget(e){return this._targetNames.has(e)===(0===this.mode)}}var Ue=i(9723),Ge=i(84015);function ze(e,t,i){try{const r=e.next();r.done?t(r):r.value?r.value.then((()=>{r.value=void 0,t(r)}),i):t(r)}catch(e){i(e)}}function We(e=25){let t;return(i,r,s)=>{const n=performance.now();void 0===t||n-t>e?(t=n,setTimeout((()=>{ze(i,r,s)}),0)):ze(i,r,s)}}function He(e,t,i,r,s){const n=()=>{let o;const a=e=>{e.done?i(e.value):void 0===o?o=!0:n()};do{o=void 0,s&&s.aborted?r(new Error("Aborted")):t(e,a,r),void 0===o&&(o=!1)}while(o)};n()}function Xe(e,t){let i;return He(e,ze,(e=>i=e),(e=>{throw e}),t),i}function qe(e,t,i){return new Promise(((r,s)=>{He(e,t,r,s,i)}))}function Ye(e,t){return(...i)=>Xe(e(...i),t)}function Ke(e,t,i){return(...r)=>qe(e(...r),t,i)}var je=i(15287),$e=i(40220),Qe=i(39464),Ze=i(14747),Je=i(75108),et=i(13093),tt=i(59881),it=i(89518);class rt extends Ze.b{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===rt.PERSPECTIVE_CAMERA)this.fovMode===rt.FOVMODE_VERTICAL_FIXED?(t=2*this.minZ*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=2*this.minZ*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{const i=this.getEngine().getRenderWidth()/2,r=this.getEngine().getRenderHeight()/2;e=(this.orthoRight??i)-(this.orthoLeft??-i),t=(this.orthoTop??r)-(this.orthoBottom??-r)}return e*t}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}get hasMoved(){return this._hasMoved}constructor(e,t,i,r=!0){super(e,i,!1),this._position=W.Pq.Zero(),this._upVector=W.Pq.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=rt.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new et.L(0,0,1,1),this.layerMask=268435455,this.fovMode=rt.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=rt.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new z.cP,this.onProjectionMatrixChangedObservable=new z.cP,this.onAfterCheckInputsObservable=new z.cP,this.onRestoreStateObservable=new z.cP,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new W.uq,this._postProcesses=new Array,this._activeMeshes=new Qe.L(256),this._globalPosition=W.Pq.Zero(),this._computedViewMatrix=W.uq.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=W.uq.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=W.PT.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),r&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}hasStateStored(){return!!this._stateStored}_restoreStateValues(){return!!this._stateStored&&(this.fov=this._storedFov,!0)}restoreState(){return!!this._restoreStateValues()&&(this.onRestoreStateObservable.notifyObservers(this),!0)}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i-1?(Z.V.Error("You're trying to reuse a post process not defined as reusable."),0):(null==t||t<0?this._postProcesses.push(e):null===this._postProcesses[t]?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);-1!==t&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()}getWorldMatrix(){return this._isSynchronizedViewMatrix()||this.getViewMatrix(),this._worldMatrix}_getViewMatrix(){return W.uq.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()||(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,void 0!==e&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;const t=this.getEngine(),i=this.getScene(),r=t.useReverseDepthBuffer;if(this.mode===rt.PERSPECTIVE_CAMERA){let e;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),e=i.useRightHandedSystem?W.uq.PerspectiveFovRHToRef:W.uq.PerspectiveFovLHToRef,e(this.fov,t.getAspectRatio(this),r?this.maxZ:this.minZ,r?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===rt.FOVMODE_VERTICAL_FIXED,t.isNDCHalfZRange,this.projectionPlaneTilt,r)}else{const e=t.getRenderWidth()/2,s=t.getRenderHeight()/2;i.useRightHandedSystem?this.oblique?W.uq.ObliqueOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-s,this.orthoTop??s,r?this.maxZ:this.minZ,r?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):W.uq.OrthoOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-s,this.orthoTop??s,r?this.maxZ:this.minZ,r?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange):this.oblique?W.uq.ObliqueOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-s,this.orthoTop??s,r?this.maxZ:this.minZ,r?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):W.uq.OrthoOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-s,this.orthoTop??s,r?this.maxZ:this.minZ,r?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=this.oblique?.angle,this._cache.obliqueLength=this.oblique?.length,this._cache.obliqueOffset=this.oblique?.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){return(this.radius||(this.target?W.Pq.Distance(this.position,this.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?tt.P.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=tt.P.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let t=!1;return this.rigCameras.forEach((i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)})),t}return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw(0,Je.n)("Ray")}getForwardRayToRef(e,t=100,i,r){throw(0,Je.n)("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 e=this._rigCameras.pop();e&&e.dispose()}if(this._parentContainer){const e=this._parentContainer.cameras.indexOf(this);e>-1&&this._parentContainer.cameras.splice(e,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==rt.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let e=this._postProcesses.length;for(;--e>=0;){const t=this._postProcesses[e];t&&t.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 e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=Ue.S0.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==rt.RIG_MODE_NONE){const e=this.createRigCamera(this.name+"_L",0);e&&(e._isLeftCamera=!0);const t=this.createRigCamera(this.name+"_R",1);t&&(t._isRightCamera=!0),e&&t&&(this._rigCameras.push(e),this._rigCameras.push(t))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return W.uq.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,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=Ue.S0.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;ert._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,r=rt.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),s=it.p.Parse(r,e,t);if(void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),s.inputs&&(s.inputs.parse(e),s._setupInputs()),e.upVector&&(s.upVector=W.Pq.FromArray(e.upVector)),s.setPosition&&(s.position.copyFromFloats(0,0,0),s.setPosition(W.Pq.FromArray(e.position))),e.target&&s.setTarget&&s.setTarget(W.Pq.FromArray(e.target)),e.cameraRigMode){const t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};s.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;t{throw(0,Je.n)("UniversalCamera")},rt.PERSPECTIVE_CAMERA=0,rt.ORTHOGRAPHIC_CAMERA=1,rt.FOVMODE_VERTICAL_FIXED=0,rt.FOVMODE_HORIZONTAL_FIXED=1,rt.RIG_MODE_NONE=0,rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,rt.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,rt.RIG_MODE_STEREOSCOPIC_INTERLACED=14,rt.RIG_MODE_VR=20,rt.RIG_MODE_CUSTOM=22,rt.ForceAttachControlToAlwaysPreventDefault=!1,(0,je.Cg)([(0,$e.P_)("position")],rt.prototype,"_position",void 0),(0,je.Cg)([(0,$e.P_)("upVector")],rt.prototype,"_upVector",void 0),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"orthoLeft",null),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"orthoRight",null),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"orthoBottom",null),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"orthoTop",null),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"fov",void 0),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"projectionPlaneTilt",void 0),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"minZ",void 0),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"maxZ",void 0),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"inertia",void 0),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"mode",null),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"layerMask",void 0),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"fovMode",void 0),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"cameraRigMode",void 0),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"interaxialDistance",void 0),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"isStereoscopicSideBySide",void 0);var st=i(12721),nt=i(14914);class ot{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}var at=i(34130),lt=i(34910);class ht{constructor(e,t,i){this.vectors=(0,at.mI)(8,W.Pq.Zero),this.center=W.Pq.Zero(),this.centerWorld=W.Pq.Zero(),this.extendSize=W.Pq.Zero(),this.extendSizeWorld=W.Pq.Zero(),this.directions=(0,at.mI)(3,W.Pq.Zero),this.vectorsWorld=(0,at.mI)(8,W.Pq.Zero),this.minimumWorld=W.Pq.Zero(),this.maximumWorld=W.Pq.Zero(),this.minimum=W.Pq.Zero(),this.maximum=W.Pq.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const r=e.x,s=e.y,n=e.z,o=t.x,a=t.y,l=t.z,h=this.vectors;this.minimum.copyFromFloats(r,s,n),this.maximum.copyFromFloats(o,a,l),h[0].copyFromFloats(r,s,n),h[1].copyFromFloats(o,a,l),h[2].copyFromFloats(o,s,n),h[3].copyFromFloats(r,a,n),h[4].copyFromFloats(r,s,l),h[5].copyFromFloats(o,a,n),h[6].copyFromFloats(r,a,l),h[7].copyFromFloats(o,s,l),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||W.uq.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=ht._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),r=i.length();i.normalizeFromLength(r);const s=r*e,n=i.scaleInPlace(.5*s),o=this.center.subtractToRef(n,t[1]),a=this.center.addToRef(n,t[2]);return this.reConstruct(o,a,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,r=this.directions,s=this.vectorsWorld,n=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)s[e].copyFrom(n[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let r=0;r<8;++r){const o=s[r];W.Pq.TransformCoordinatesToRef(n[r],e,o),t.minimizeInPlace(o),i.maximizeInPlace(o)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}W.Pq.FromArrayToRef(e.m,0,r[0]),W.Pq.FromArrayToRef(e.m,4,r[1]),W.Pq.FromArrayToRef(e.m,8,r[2]),this._worldMatrix=e}isInFrustum(e){return ht.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return ht.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,r=t.x,s=t.y,n=t.z,o=i.x,a=i.y,l=i.z,h=e.x,c=e.y,u=e.z,d=-lt.bH;return!(o-hh-r||a-cc-s||l-uu-n)}intersectsSphere(e){return ht.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,r=this.maximumWorld,s=i.x,n=i.y,o=i.z,a=r.x,l=r.y,h=r.z,c=e.x,u=e.y,d=e.z,f=t.x,p=t.y,_=t.z;return!(af||lp||h_)}dispose(){this._drawWrapperFront?.dispose(),this._drawWrapperBack?.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,r){const s=ht._TmpVector3[0];return W.Pq.ClampToRef(i,e,t,s),W.Pq.DistanceSquared(i,s)<=r*r}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const r=t[i];for(let t=0;t<8;++t)if(r.dotCoordinate(e[t])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let r=!0;const s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])>=0){r=!1;break}if(r)return!1}return!0}}ht._TmpVector3=(0,at.mI)(3,W.Pq.Zero);class ct{constructor(e,t,i){this.center=W.Pq.Zero(),this.centerWorld=W.Pq.Zero(),this.minimum=W.Pq.Zero(),this.maximum=W.Pq.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const r=W.Pq.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*r,this._update(i||W.uq.IdentityReadOnly)}scale(e){const t=this.radius*e,i=ct._TmpVector3,r=i[0].setAll(t),s=this.center.subtractToRef(r,i[1]),n=this.center.addToRef(r,i[2]);return this.reConstruct(s,n,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{W.Pq.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=ct._TmpVector3[0];W.Pq.TransformNormalFromFloatsToRef(1,1,1,e,t),this.radiusWorld=Math.max(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z))*this.radius}}isInFrustum(e){const t=this.centerWorld,i=this.radiusWorld;for(let r=0;r<6;r++)if(e[r].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){const t=this.centerWorld;for(let i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0}intersectsPoint(e){const t=W.Pq.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const r=W.Pq.Dot(t.centerWorld,e),s=Math.abs(W.Pq.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(W.Pq.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(W.Pq.Dot(t.directions[2],e))*t.extendSize.z;i.min=r-s,i.max=r+s},pt=(e,t,i)=>(ft(e,t,ut),ft(e,i,dt),!(ut.min>dt.max||dt.min>ut.max));class _t{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new ht(e,t,i),this.boundingSphere=new ct(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=_t._TmpVector3[0].copyFrom(e).subtractInPlace(t),r=_t._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=W.Pq.Minimize(this.minimum,e),i=W.Pq.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=W.AA.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=W.AA.Vector3[0];return W.Pq.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),W.Pq.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!(2!==t&&3!==t||!this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(!(1!==t&&3!==t)||this.boundingBox.isInFrustum(e))}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,_t._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(!ct.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!ht.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,r=e.boundingBox;return!!(pt(i.directions[0],i,r)&&pt(i.directions[1],i,r)&&pt(i.directions[2],i,r)&&pt(r.directions[0],i,r)&&pt(r.directions[1],i,r)&&pt(r.directions[2],i,r)&&pt(W.Pq.Cross(i.directions[0],r.directions[0]),i,r)&&pt(W.Pq.Cross(i.directions[0],r.directions[1]),i,r)&&pt(W.Pq.Cross(i.directions[0],r.directions[2]),i,r)&&pt(W.Pq.Cross(i.directions[1],r.directions[0]),i,r)&&pt(W.Pq.Cross(i.directions[1],r.directions[1]),i,r)&&pt(W.Pq.Cross(i.directions[1],r.directions[2]),i,r)&&pt(W.Pq.Cross(i.directions[2],r.directions[0]),i,r)&&pt(W.Pq.Cross(i.directions[2],r.directions[1]),i,r)&&pt(W.Pq.Cross(i.directions[2],r.directions[2]),i,r))}}_t._TmpVector3=(0,at.mI)(2,W.Pq.Zero);var mt=i(890),gt=i(15311);class vt{get materialDefines(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:this._getDrawWrapper()?.defines}set materialDefines(e){(this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)).defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new gt.E(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){t&&this._drawWrappers[e]?.dispose(),this._drawWrappers[e]=void 0}get effect(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:this._getDrawWrapper()?.effect??null}get _drawWrapper(){return this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,r=!0){const s=this._drawWrapper;s.setEffect(e,t,r),void 0!==i&&(s.materialContext=i),e||(s.defines=null,s.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e)return void this._removeDrawWrapper(e);for(const e of this._drawWrappers)e?.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,r,s,n,o,a=!0){return new vt(e,t,i,r,s,n,o,a)}constructor(e,t,i,r,s,n,o,a=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=r,this.indexCount=s,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=n,this._renderingMesh=o||n,l&&n.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=n.subMeshes.length-1,a&&(this.refreshBoundingInfo(),n.computeWorldMatrix(!0))}get IsGlobal(){return 0===this.verticesStart&&this.verticesCount===this._mesh.getTotalVertices()&&0===this.indexStart&&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(){return(this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null)||this._renderingMesh}getMaterial(e=!0){const t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)??this._renderingMesh.material;if(!t)return e?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(t)){const e=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==e&&(this._currentMaterial=e,this.resetDrawCache()),e}return t}_isMultiMaterial(e){return void 0!==e.getSubMaterial}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(st.R.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;const t=this._renderingMesh.getIndices();let i;if(0===this.indexStart&&this.indexCount===t.length){const e=this._renderingMesh.getBoundingInfo();i={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else i=(0,mt.cD)(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new _t(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)}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isCompletelyInFrustum(e)}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 t=this.indexStart;ta&&(a=t)}return new vt(e,o,a-o+1,t,i,r,s,n)}}class xt{}class bt{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=Ye(this._applyToCoroutine.bind(this)),this.uniqueId=bt._UniqueIDGenerator,bt._UniqueIDGenerator++}set(e,t){switch(e.length||Z.V.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case st.R.PositionKind:this.positions=e;break;case st.R.NormalKind:this.normals=e;break;case st.R.TangentKind:this.tangents=e;break;case st.R.UVKind:this.uvs=e;break;case st.R.UV2Kind:this.uvs2=e;break;case st.R.UV3Kind:this.uvs3=e;break;case st.R.UV4Kind:this.uvs4=e;break;case st.R.UV5Kind:this.uvs5=e;break;case st.R.UV6Kind:this.uvs6=e;break;case st.R.ColorKind:this.colors=e;break;case st.R.MatricesIndicesKind:this.matricesIndices=e;break;case st.R.MatricesWeightsKind:this.matricesWeights=e;break;case st.R.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case st.R.MatricesWeightsExtraKind:this.matricesWeightsExtra=e}}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(st.R.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(st.R.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(st.R.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(st.R.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(st.R.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(st.R.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(st.R.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(st.R.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(st.R.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(st.R.ColorKind,this.colors,t),this.hasVertexAlpha&&void 0!==e.hasVertexAlpha&&(e.hasVertexAlpha=!0),i&&(yield)),this.matricesIndices&&(e.setVerticesData(st.R.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(st.R.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(st.R.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(st.R.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 t=e;t.subMeshes=[];for(const e of this.materialInfos)new vt(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,t)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(st.R.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(st.R.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(st.R.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(st.R.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(st.R.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(st.R.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(st.R.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(st.R.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(st.R.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(st.R.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(st.R.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(st.R.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(st.R.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(st.R.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,r=e.length){const s=W.AA.Vector3[0],n=W.AA.Vector3[1];for(let o=i;o({vertexData:e}))):[{vertexData:e}];return Xe(this._mergeCoroutine(void 0,n,t,!1,i,r,s))}*_mergeCoroutine(e,t,i=!1,r,s,n=!1,o=!1){this._validate();let a=t.map((e=>e.vertexData)),l=this;if(o)for(const e of a)e&&(e._validate(),!this.normals&&e.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&e.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&e.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&e.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&e.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&e.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&e.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&e.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&e.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&e.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&e.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&e.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&e.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const e of a)if(e)if(o)this.normals&&!e.normals&&(e.normals=new Float32Array(e.positions.length)),this.tangents&&!e.tangents&&(e.tangents=new Float32Array(e.positions.length/3*4)),this.uvs&&!e.uvs&&(e.uvs=new Float32Array(e.positions.length/3*2)),this.uvs2&&!e.uvs2&&(e.uvs2=new Float32Array(e.positions.length/3*2)),this.uvs3&&!e.uvs3&&(e.uvs3=new Float32Array(e.positions.length/3*2)),this.uvs4&&!e.uvs4&&(e.uvs4=new Float32Array(e.positions.length/3*2)),this.uvs5&&!e.uvs5&&(e.uvs5=new Float32Array(e.positions.length/3*2)),this.uvs6&&!e.uvs6&&(e.uvs6=new Float32Array(e.positions.length/3*2)),this.colors&&!e.colors&&(e.colors=new Float32Array(e.positions.length/3*4),e.colors.fill(1)),this.matricesIndices&&!e.matricesIndices&&(e.matricesIndices=new Float32Array(e.positions.length/3*4)),this.matricesWeights&&!e.matricesWeights&&(e.matricesWeights=new Float32Array(e.positions.length/3*4)),this.matricesIndicesExtra&&!e.matricesIndicesExtra&&(e.matricesIndicesExtra=new Float32Array(e.positions.length/3*4)),this.matricesWeightsExtra&&!e.matricesWeightsExtra&&(e.matricesWeightsExtra=new Float32Array(e.positions.length/3*4));else if(e._validate(),!this.normals!=!e.normals||!this.tangents!=!e.tangents||!this.uvs!=!e.uvs||!this.uvs2!=!e.uvs2||!this.uvs3!=!e.uvs3||!this.uvs4!=!e.uvs4||!this.uvs5!=!e.uvs5||!this.uvs6!=!e.uvs6||!this.colors!=!e.colors||!this.matricesIndices!=!e.matricesIndices||!this.matricesWeights!=!e.matricesWeights||!this.matricesIndicesExtra!=!e.matricesIndicesExtra||!this.matricesWeightsExtra!=!e.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes");if(n){let i=0,r=0,s=0;const n=[];let o=null;const h=[];for(const t of this.splitBasedOnMaterialID())h.push({vertexData:t,transform:e});for(const e of t)if(e.vertexData)for(const t of e.vertexData.splitBasedOnMaterialID())h.push({vertexData:t,transform:e.transform});h.sort(((e,t)=>{const i=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,r=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return i>r?1:i===r?0:-1}));for(const e of h){const t=e.vertexData;if(i=t.materialInfos?t.materialInfos[0].materialIndex:0,o&&o.materialIndex===i)o.indexCount+=t.indices.length,o.verticesCount+=t.positions.length/3;else{const e=new xt;e.materialIndex=i,e.indexStart=r,e.indexCount=t.indices.length,e.verticesStart=s,e.verticesCount=t.positions.length/3,n.push(e),o=e}r+=t.indices.length,s+=t.positions.length/3}const c=h.splice(0,1)[0];l=c.vertexData,e=c.transform,a=h.map((e=>e.vertexData)),t=h,this.materialInfos=n}const h=a.reduce(((e,t)=>e+(t.indices?.length??0)),l.indices?.length??0);let c=s||a.some((e=>e.indices===l.indices))?l.indices?.slice():l.indices;if(h>0){let s=c?.length??0;if(c||(c=new Array(h)),c.length!==h){if(Array.isArray(c))c.length=h;else{const e=i||c instanceof Uint32Array?new Uint32Array(h):new Uint16Array(h);e.set(c),c=e}e&&e.determinant()<0&&bt._FlipFaces(c,0,s)}let n=l.positions?l.positions.length/3:0;for(const{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;t[e.vertexData.positions,e.transform]))),r&&(yield),l.normals&&(this.normals=bt._MergeElement(st.R.NormalKind,l.normals,e,t.map((e=>[e.vertexData.normals,e.transform]))),r&&(yield)),l.tangents&&(this.tangents=bt._MergeElement(st.R.TangentKind,l.tangents,e,t.map((e=>[e.vertexData.tangents,e.transform]))),r&&(yield)),l.uvs&&(this.uvs=bt._MergeElement(st.R.UVKind,l.uvs,e,t.map((e=>[e.vertexData.uvs,e.transform]))),r&&(yield)),l.uvs2&&(this.uvs2=bt._MergeElement(st.R.UV2Kind,l.uvs2,e,t.map((e=>[e.vertexData.uvs2,e.transform]))),r&&(yield)),l.uvs3&&(this.uvs3=bt._MergeElement(st.R.UV3Kind,l.uvs3,e,t.map((e=>[e.vertexData.uvs3,e.transform]))),r&&(yield)),l.uvs4&&(this.uvs4=bt._MergeElement(st.R.UV4Kind,l.uvs4,e,t.map((e=>[e.vertexData.uvs4,e.transform]))),r&&(yield)),l.uvs5&&(this.uvs5=bt._MergeElement(st.R.UV5Kind,l.uvs5,e,t.map((e=>[e.vertexData.uvs5,e.transform]))),r&&(yield)),l.uvs6&&(this.uvs6=bt._MergeElement(st.R.UV6Kind,l.uvs6,e,t.map((e=>[e.vertexData.uvs6,e.transform]))),r&&(yield)),l.colors&&(this.colors=bt._MergeElement(st.R.ColorKind,l.colors,e,t.map((e=>[e.vertexData.colors,e.transform]))),(void 0!==l.hasVertexAlpha||t.some((e=>void 0!==e.vertexData.hasVertexAlpha)))&&(this.hasVertexAlpha=l.hasVertexAlpha||t.some((e=>e.vertexData.hasVertexAlpha))),r&&(yield)),l.matricesIndices&&(this.matricesIndices=bt._MergeElement(st.R.MatricesIndicesKind,l.matricesIndices,e,t.map((e=>[e.vertexData.matricesIndices,e.transform]))),r&&(yield)),l.matricesWeights&&(this.matricesWeights=bt._MergeElement(st.R.MatricesWeightsKind,l.matricesWeights,e,t.map((e=>[e.vertexData.matricesWeights,e.transform]))),r&&(yield)),l.matricesIndicesExtra&&(this.matricesIndicesExtra=bt._MergeElement(st.R.MatricesIndicesExtraKind,l.matricesIndicesExtra,e,t.map((e=>[e.vertexData.matricesIndicesExtra,e.transform]))),r&&(yield)),l.matricesWeightsExtra&&(this.matricesWeightsExtra=bt._MergeElement(st.R.MatricesWeightsExtraKind,l.matricesWeightsExtra,e,t.map((e=>[e.vertexData.matricesWeightsExtra,e.transform])))),this}static _MergeElement(e,t,i,r){const s=r.filter((e=>null!==e[0]&&void 0!==e[0]));if(!t&&0==s.length)return t;if(!t)return this._MergeElement(e,s[0][0],s[0][1],s.slice(1));const n=s.reduce(((e,t)=>e+t[0].length),t.length),o=e===st.R.PositionKind?bt._TransformVector3Coordinates:e===st.R.NormalKind?bt._TransformVector3Normals:e===st.R.TangentKind?bt._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const e=new Float32Array(n);e.set(t),i&&o(e,i,0,t.length);let r=t.length;for(const[t,i]of s)e.set(t,r),i&&o(e,i,r,t.length),r+=t.length;return e}{const e=new Array(n);for(let i=0;i{const i=st.R.DeduceStride(e);if(t.length%i!=0)throw new Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},t=e(st.R.PositionKind,this.positions),i=(i,r)=>{const s=e(i,r);if(s!==t)throw new Error("The "+i+"s element count ("+s+") does not match the positions count ("+t+")")};this.normals&&i(st.R.NormalKind,this.normals),this.tangents&&i(st.R.TangentKind,this.tangents),this.uvs&&i(st.R.UVKind,this.uvs),this.uvs2&&i(st.R.UV2Kind,this.uvs2),this.uvs3&&i(st.R.UV3Kind,this.uvs3),this.uvs4&&i(st.R.UV4Kind,this.uvs4),this.uvs5&&i(st.R.UV5Kind,this.uvs5),this.uvs6&&i(st.R.UV6Kind,this.uvs6),this.colors&&i(st.R.ColorKind,this.colors),this.matricesIndices&&i(st.R.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(st.R.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(st.R.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(st.R.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return bt.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 bt._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return bt._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const r=new bt;if(e.isVerticesDataPresent(st.R.PositionKind)&&(r.positions=e.getVerticesData(st.R.PositionKind,t,i)),e.isVerticesDataPresent(st.R.NormalKind)&&(r.normals=e.getVerticesData(st.R.NormalKind,t,i)),e.isVerticesDataPresent(st.R.TangentKind)&&(r.tangents=e.getVerticesData(st.R.TangentKind,t,i)),e.isVerticesDataPresent(st.R.UVKind)&&(r.uvs=e.getVerticesData(st.R.UVKind,t,i)),e.isVerticesDataPresent(st.R.UV2Kind)&&(r.uvs2=e.getVerticesData(st.R.UV2Kind,t,i)),e.isVerticesDataPresent(st.R.UV3Kind)&&(r.uvs3=e.getVerticesData(st.R.UV3Kind,t,i)),e.isVerticesDataPresent(st.R.UV4Kind)&&(r.uvs4=e.getVerticesData(st.R.UV4Kind,t,i)),e.isVerticesDataPresent(st.R.UV5Kind)&&(r.uvs5=e.getVerticesData(st.R.UV5Kind,t,i)),e.isVerticesDataPresent(st.R.UV6Kind)&&(r.uvs6=e.getVerticesData(st.R.UV6Kind,t,i)),e.isVerticesDataPresent(st.R.ColorKind)){const s=e.geometry||e,n=s.getVertexBuffer(st.R.ColorKind),o=s.getVerticesData(st.R.ColorKind,t,i);if(3===n.getSize()){const e=new Float32Array(4*o.length/3);for(let t=0,i=0;t!Array.isArray(e)))],bt,"_TransformVector3Coordinates",null),(0,je.Cg)([$e.Cx.filter(((...[e])=>!Array.isArray(e)))],bt,"_TransformVector3Normals",null),(0,je.Cg)([$e.Cx.filter(((...[e])=>!Array.isArray(e)))],bt,"_TransformVector4Normals",null),(0,je.Cg)([$e.Cx.filter(((...[e])=>!Array.isArray(e)))],bt,"_FlipFaces",null);class St{static get ForceFullSceneLoadingForIncremental(){return St._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){St._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return St._ShowLoadingScreen}static set ShowLoadingScreen(e){St._ShowLoadingScreen=e}static get loggingLevel(){return St._LoggingLevel}static set loggingLevel(e){St._LoggingLevel=e}static get CleanBoneMatrixWeights(){return St._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){St._CleanBoneMatrixWeights=e}}St._ForceFullSceneLoadingForIncremental=!1,St._ShowLoadingScreen=!0,St._CleanBoneMatrixWeights=!1,St._LoggingLevel=0;var Tt=i(75174);function Ct(e,t,i,r,s,n,o,a){const l=t*st.R.GetTypeByteLength(i),h=o*t;if(a.length!==h)throw new Error("Output length is not valid");if(i===st.R.FLOAT&&s===l)if(e instanceof Array){const t=r/4;a.set(e,t)}else if(e instanceof ArrayBuffer){const t=new Float32Array(e,r,h);a.set(t)}else{const t=e.byteOffset+r;if(t%4)return Z.V.Warn("CopyFloatData: copied misaligned data."),void a.set(new Float32Array(e.buffer.slice(t,t+4*h)));const i=new Float32Array(e.buffer,t,h);a.set(i)}else st.R.ForEach(e,r,s,t,i,h,n,((e,t)=>a[t]=e))}class yt{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 yt(yt.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,r=!1,s=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||he.q.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=r,i?this.setAllVerticesData(i,r):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),s&&(this.applyToMesh(s),s.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e{e._rebuild()}))}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,r){i&&Array.isArray(t)&&(t=new Float32Array(t));const s=new st.R(this._engine,t,e,{updatable:i,postponeInternalCreation:0===this._meshes.length,stride:r,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(s)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){const r=e.getKind();this._vertexBuffers[r]&&i&&this._vertexBuffers[r].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[r]=e;const s=this._meshes,n=s.length;if(r===st.R.PositionKind){this._totalVertices=t??e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const i=this._extend&&this._extend.minimum||new W.Pq(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),r=this._extend&&this._extend.maximum||new W.Pq(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let e=0;e65535);for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1,r=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),null!=t&&(this._totalVertices=t);for(const e of this._meshes)e._createGlobalSubMesh(!r),e.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?void 0!==this._totalIndices?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;const i=this._indices;return t||e&&1!==this._meshes.length?i.slice():i}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){e&&this._vertexArrayObjects&&this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){const i=this._meshes,r=i.indexOf(e);-1!==r&&(i.splice(r,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,0===i.length&&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(st.R.PositionKind)))return;this._extend=(0,mt.b8)(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){const t=this._meshes.length;for(const i in this._vertexBuffers)1===t&&this._vertexBuffers[i].create(),i===st.R.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());1===t&&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 e of this._meshes)e._markSubMeshesAsAttributesDirty()}load(e,t){2!==this.delayLoadState&&(this.isReady()?t&&t():(this.delayLoadState=2,this._queueLoad(e,t)))}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,(i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);const r=this._meshes,s=r.length;for(let e=0;e0){for(let t=0;t0){for(let e=0;e0){for(let e=0;e-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new bt;t.indices=[];const i=this.getIndices();if(i)for(let e=0;e0){const r=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(st.R.PositionKind,r,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){const r=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(st.R.NormalKind,r,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){const r=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(st.R.TangentKind,r,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){const r=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(Tt.rX)for(let e=1;e0){const r=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(Tt.rX)for(let e=1;e0){const r=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(Tt.rX)for(let e=1;e0){const r=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(Tt.rX)for(let e=1;e0){const r=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(Tt.rX)for(let e=1;e0){const r=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(Tt.rX)for(let e=1;e0){const r=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(st.R.ColorKind,r,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){const r=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),s=[];for(let e=0;e>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(st.R.MatricesIndicesKind,s,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){const r=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),s=[];for(let e=0;e>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(st.R.MatricesIndicesExtraKind,s,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){const r=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(st.R.MatricesWeightsKind,r,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){const r=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(r,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){const r=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e>8),i.push((16711680&r)>>16),i.push(r>>24&255)}t.setVerticesData(st.R.MatricesIndicesKind,i,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(st.R.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const i=[];for(let t=0;t>8),i.push((16711680&r)>>16),i.push(r>>24&255)}t.setVerticesData(st.R.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(yt._CleanMatricesWeights(e,t),t.setVerticesData(st.R.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(st.R.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i-1))return;{const i=t.getScene().getLastSkeletonById(e.skeletonId);if(!i)return;r=i.bones.length}const s=t.getVerticesData(st.R.MatricesIndicesKind),n=t.getVerticesData(st.R.MatricesIndicesExtraKind),o=e.matricesWeights,a=e.matricesWeightsExtra,l=e.numBoneInfluencer,h=o.length;for(let e=0;el-1)&&(h=l-1),t>i){const i=1/t;for(let t=0;t<4;t++)o[e+t]*=i;if(a)for(let t=0;t<4;t++)a[e+t]*=i}else h>=4?(a[e+h-4]=1-t,n[e+h-4]=r):(o[e+h]=1-t,s[e+h]=r)}t.setVerticesData(st.R.MatricesIndicesKind,s),e.matricesWeightsExtra&&t.setVerticesData(st.R.MatricesIndicesExtraKind,n)}static Parse(e,t,i){const r=new yt(e.id,t,void 0,e.updatable);return r._loadedUniqueId=e.uniqueId,Ge.Y&&Ge.Y.AddTagsTo(r,e.tags),e.delayLoadingFile?(r.delayLoadState=4,r.delayLoadingFile=i+e.delayLoadingFile,r._boundingInfo=new _t(W.Pq.FromArray(e.boundingBoxMinimum),W.Pq.FromArray(e.boundingBoxMaximum)),r._delayInfo=[],e.hasUVs&&r._delayInfo.push(st.R.UVKind),e.hasUVs2&&r._delayInfo.push(st.R.UV2Kind),e.hasUVs3&&r._delayInfo.push(st.R.UV3Kind),e.hasUVs4&&r._delayInfo.push(st.R.UV4Kind),e.hasUVs5&&r._delayInfo.push(st.R.UV5Kind),e.hasUVs6&&r._delayInfo.push(st.R.UV6Kind),e.hasColors&&r._delayInfo.push(st.R.ColorKind),e.hasMatricesIndices&&r._delayInfo.push(st.R.MatricesIndicesKind),e.hasMatricesWeights&&r._delayInfo.push(st.R.MatricesWeightsKind),r._delayLoadingFunction=bt.ImportVertexData):bt.ImportVertexData(e,r),t.pushGeometry(r,!0),r}}const Et=W.uq.Compose(W.Pq.One(),W.PT.FromEulerAngles(0,Math.PI,0),W.Pq.Zero());class Pt extends Ze.b{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=!!(this._billboardMode&Pt.BILLBOARDMODE_USE_POSITION),this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==Pt.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t,!1),this._forward=new W.Pq(0,0,1),this._up=new W.Pq(0,1,0),this._right=new W.Pq(1,0,0),this._position=W.Pq.Zero(),this._rotation=W.Pq.Zero(),this._rotationQuaternion=null,this._scaling=W.Pq.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=Pt.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=W.uq.Zero(),this._usePivotMatrix=!1,this._absolutePosition=W.Pq.Zero(),this._absoluteScaling=W.Pq.Zero(),this._absoluteRotationQuaternion=W.PT.Identity(),this._pivotMatrix=W.uq.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new z.cP,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._markAsDirtyInternal()}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._markAsDirtyInternal()}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._markAsDirtyInternal()}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._markAsDirtyInternal()}_markAsDirtyInternal(){this._isDirty||(this._isDirty=!0,this.customMarkAsDirty&&this.customMarkAsDirty())}get forward(){return W.Pq.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return W.Pq.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return W.Pq.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=W.uq.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==Pt.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=W.uq.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const r=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);r&&i&&i(this,r);for(const e of this.getChildTransformNodes(!0))e.instantiateHierarchy(r,t,i);return r}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||W.PT.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this}unfreezeWorldMatrix(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this}get isWorldMatrixFrozen(){return this._isWorldMatrixFrozen}getAbsolutePosition(){return this.computeWorldMatrix(),this._absolutePosition}setAbsolutePosition(e){if(!e)return this;let t,i,r;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],r=arguments[2]}else t=e.x,i=e.y,r=e.z;if(this.parent){const e=W.AA.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),W.Pq.TransformCoordinatesFromFloatsToRef(t,i,r,e,this.position)}else this.position.x=t,this.position.y=i,this.position.z=r;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=W.Pq.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=W.AA.Matrix[0];return this._localMatrix.invertToRef(e),W.Pq.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=W.Pq.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,r=0,s=0){const n=Pt._LookAtVectorCache,o=0===s?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,n),this.setDirection(n,t,i,r),1===s&&this.parent)if(this.rotationQuaternion){const e=W.AA.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);const t=W.AA.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{const e=W.AA.Quaternion[0];W.PT.FromEulerVectorToRef(this.rotation,e);const t=W.AA.Matrix[0];e.toRotationMatrix(t);const i=W.AA.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(i),i.invert(),t.multiplyToRef(i,t),e.fromRotationMatrix(t),e.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=W.Pq.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return W.Pq.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,r=0){const s=-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?W.PT.RotationYawPitchRollToRef(s+t,o+i,r,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=s+t,this.rotation.z=r),this}setPivotPoint(e,t=0){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(1==t){const t=W.AA.Matrix[0];i.invertToRef(t),e=W.Pq.TransformCoordinates(e,t)}return this.setPivotMatrix(W.uq.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=W.Pq.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=W.Pq.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),W.Pq.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(const t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;const r=W.AA.Quaternion[0],s=W.AA.Vector3[0],n=W.AA.Vector3[1],o=W.AA.Matrix[1];W.uq.IdentityToRef(o);const a=W.AA.Matrix[0];this.computeWorldMatrix(!0);let l=this.rotationQuaternion;return l||(l=Pt._TmpRotation,W.PT.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),W.uq.ComposeToRef(this.scaling,l,this.position,a),this.parent&&a.multiplyToRef(this.parent.computeWorldMatrix(!0),a),e&&(e.computeWorldMatrix(!0).invertToRef(o),a.multiplyToRef(o,a)),a.decompose(n,r,s,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(r):r.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(s),this.parent=e,i&&this.setPivotMatrix(W.uq.Identity()),this}addChild(e,t=!1){return e.setParent(this,t),this}removeChild(e,t=!1){return e.setParent(null,t),this}get nonUniformScaling(){return this._nonUniformScaling}_updateNonUniformScalingState(e){return this._nonUniformScaling!==e&&(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,this.parent=e?this._currentParentWhenAttachingToBone:null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){let r;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&0!==i){if(this.parent){const i=this.parent.getWorldMatrix(),r=W.AA.Matrix[0];i.invertToRef(r),e=W.Pq.TransformNormal(e,r),i.determinant()<0&&(t*=-1)}r=W.PT.RotationAxisToRef(e,t,Pt._RotationAxisCache),r.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else r=W.PT.RotationAxisToRef(e,t,Pt._RotationAxisCache),this.rotationQuaternion.multiplyToRef(r,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=W.PT.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const r=W.AA.Vector3[0],s=W.AA.Vector3[1],n=W.AA.Vector3[2],o=W.AA.Quaternion[0],a=W.AA.Matrix[0],l=W.AA.Matrix[1],h=W.AA.Matrix[2],c=W.AA.Matrix[3];return e.subtractToRef(this.position,r),W.uq.TranslationToRef(r.x,r.y,r.z,a),W.uq.TranslationToRef(-r.x,-r.y,-r.z,l),W.uq.RotationAxisToRef(t,i,h),l.multiplyToRef(h,c),c.multiplyToRef(a,c),c.decompose(s,o,n),this.position.addInPlace(n),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const r=e.scale(t);if(i&&0!==i)this.setAbsolutePosition(this.getAbsolutePosition().add(r));else{const e=this.getPositionExpressedInLocalSpace().add(r);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let r;this.rotationQuaternion?r=this.rotationQuaternion:(r=W.AA.Quaternion[1],W.PT.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,r));const s=W.AA.Quaternion[0];return W.PT.RotationYawPitchRollToRef(t,e,i,s),r.multiplyInPlace(s),this.rotationQuaternion||r.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==Pt.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();const r=this._cache;r.pivotMatrixUpdated=!1,r.billboardMode=this.billboardMode,r.infiniteDistance=this.infiniteDistance,r.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;const s=this._getEffectiveParent(),n=Pt._TmpScaling;let o,a=this._position;if(this._infiniteDistance&&!this.parent&&t){const e=t.getWorldMatrix(),i=new W.Pq(e.m[12],e.m[13],e.m[14]);a=Pt._TmpTranslation,a.copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(n.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,o=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(W.PT.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(o=Pt._TmpRotation,W.PT.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,o)),this._usePivotMatrix){const e=W.AA.Matrix[1];W.uq.ScalingToRef(n.x,n.y,n.z,e);const t=W.AA.Matrix[0];o.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,W.AA.Matrix[4]),W.AA.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(a.x,a.y,a.z)}else W.uq.ComposeToRef(n,o,a,this._localMatrix);if(s&&s.getWorldMatrix){if(e&&s.computeWorldMatrix(e),r.useBillboardPath){if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),W.AA.Matrix[7])}else W.AA.Matrix[7].copyFrom(s.getWorldMatrix());const e=W.AA.Vector3[5],t=W.AA.Vector3[6],i=W.AA.Quaternion[0];W.AA.Matrix[7].decompose(t,i,e),W.uq.ScalingToRef(t.x,t.y,t.z,W.AA.Matrix[7]),W.AA.Matrix[7].setTranslation(e),Pt.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(W.AA.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),W.AA.Matrix[6]),W.AA.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(s.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(r.useBillboardPath&&t&&this.billboardMode&&!r.useBillboardPosition){const e=W.AA.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),W.AA.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&W.AA.Matrix[1].multiplyToRef(Et,W.AA.Matrix[1]),W.AA.Matrix[1].setTranslationFromFloats(0,0,0),W.AA.Matrix[1].invertToRef(W.AA.Matrix[0]),(this.billboardMode&Pt.BILLBOARDMODE_ALL)!==Pt.BILLBOARDMODE_ALL){W.AA.Matrix[0].decompose(void 0,W.AA.Quaternion[0],void 0);const e=W.AA.Vector3[1];W.AA.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&Pt.BILLBOARDMODE_X)!==Pt.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&Pt.BILLBOARDMODE_Y)!==Pt.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&Pt.BILLBOARDMODE_Z)!==Pt.BILLBOARDMODE_Z&&(e.z=0),W.uq.RotationYawPitchRollToRef(e.y,e.x,e.z,W.AA.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(W.AA.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(W.AA.Vector3[0])}else if(r.useBillboardPath&&t&&r.useBillboardPosition){const e=W.AA.Vector3[0];this._worldMatrix.getTranslationToRef(e);const i=t.globalPosition;this._worldMatrix.invertToRef(W.AA.Matrix[1]);const r=W.AA.Vector3[1];W.Pq.TransformCoordinatesToRef(i,W.AA.Matrix[1],r),r.normalize();const s=-Math.atan2(r.z,r.x)+Math.PI/2,n=Math.sqrt(r.x*r.x+r.z*r.z),o=-Math.atan2(r.y,n);if(W.PT.RotationYawPitchRollToRef(s,o,0,W.AA.Quaternion[0]),(this.billboardMode&Pt.BILLBOARDMODE_ALL)!==Pt.BILLBOARDMODE_ALL){const e=W.AA.Vector3[1];W.AA.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&Pt.BILLBOARDMODE_X)!==Pt.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&Pt.BILLBOARDMODE_Y)!==Pt.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&Pt.BILLBOARDMODE_Z)!==Pt.BILLBOARDMODE_Z&&(e.z=0),W.uq.RotationYawPitchRollToRef(e.y,e.x,e.z,W.AA.Matrix[0])}else W.uq.FromQuaternionToRef(W.AA.Quaternion[0],W.AA.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(W.AA.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(W.AA.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):s&&s._nonUniformScaling?this._updateNonUniformScalingState(s._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=W.uq.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const e=this.getChildren();for(let t=0;tnew Pt(e,this.getScene())),this);if(r.name=e,r.id=e,t&&(r.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;inew Pt(e.name,t)),e,t,i);if(e.localMatrix?r.setPreTransformMatrix(W.uq.FromArray(e.localMatrix)):e.pivotMatrix&&r.setPivotMatrix(W.uq.FromArray(e.pivotMatrix)),r.setEnabled(e.isEnabled),r._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(let t=0;t(!t||t(e))&&e instanceof Pt)),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){const e=this._parentContainer.transformNodes.indexOf(this);e>-1&&this._parentContainer.transformNodes.splice(e,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){const e=this.getChildTransformNodes(!0);for(const t of e)t.parent=null,t.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let r=null,s=null;t&&(this.rotationQuaternion?(s=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(r=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const n=this.getHierarchyBoundingVectors(e,i),o=n.max.subtract(n.min),a=Math.max(o.x,o.y,o.z);if(0===a)return this;const l=1/a;return this.scaling.scaleInPlace(l),t&&(this.rotationQuaternion&&s?this.rotationQuaternion.copyFrom(s):this.rotation&&r&&this.rotation.copyFrom(r)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}Pt.BILLBOARDMODE_NONE=0,Pt.BILLBOARDMODE_X=1,Pt.BILLBOARDMODE_Y=2,Pt.BILLBOARDMODE_Z=4,Pt.BILLBOARDMODE_ALL=7,Pt.BILLBOARDMODE_USE_POSITION=128,Pt.BillboardUseParentOrientation=!1,Pt._TmpRotation=W.PT.Zero(),Pt._TmpScaling=W.Pq.Zero(),Pt._TmpTranslation=W.Pq.Zero(),Pt._LookAtVectorCache=new W.Pq(0,0,0),Pt._RotationAxisCache=new W.PT,(0,je.Cg)([(0,$e.P_)("position")],Pt.prototype,"_position",void 0),(0,je.Cg)([(0,$e.P_)("rotation")],Pt.prototype,"_rotation",void 0),(0,je.Cg)([(0,$e.bR)("rotationQuaternion")],Pt.prototype,"_rotationQuaternion",void 0),(0,je.Cg)([(0,$e.P_)("scaling")],Pt.prototype,"_scaling",void 0),(0,je.Cg)([(0,$e.lK)("billboardMode")],Pt.prototype,"_billboardMode",void 0),(0,je.Cg)([(0,$e.lK)()],Pt.prototype,"scalingDeterminant",void 0),(0,je.Cg)([(0,$e.lK)("infiniteDistance")],Pt.prototype,"_infiniteDistance",void 0),(0,je.Cg)([(0,$e.lK)()],Pt.prototype,"ignoreNonUniformScaling",void 0),(0,je.Cg)([(0,$e.lK)()],Pt.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);var At=i(81310),Rt=i(4216);class It{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new W.Pq(0,0,0),this._diffPositionForCollisions=new W.Pq(0,0,0),this._collisionResponse=!0}}var Mt=i(4514),Ot=i(55935);class Dt{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=W.Pq.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class wt{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new Dt,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 It,this._enableDistantPicking=!1,this._rawBoundingInfo=null,this._sideOrientationHint=!1,this._inheritVisibility=!1}}class Nt extends Pt{static get BILLBOARDMODE_NONE(){return Pt.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return Pt.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return Pt.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return Pt.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return Pt.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return Pt.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)}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,(1===t&&1!==e||1!==t&&1===e)&&this._markSubMeshesAsDirty((e=>{e.markAsMiscDirty(),e.markAsPrePassDirty()}))}get inheritVisibility(){return this._internalAbstractMeshDataInfo._inheritVisibility}set inheritVisibility(e){this._internalAbstractMeshDataInfo._inheritVisibility=e}get isVisible(){if(!this._isVisible||!this.inheritVisibility||!this._parentNode)return this._isVisible;if(this._isVisible){let e=this._parentNode;for(;e;){const t=e.isVisible;if(void 0!==t)return t;e=e.parent}}return this._isVisible}set isVisible(e){this._isVisible=e}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._setMaterial(e)}_setMaterial(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(),this._unBindEffect()))}getMaterialForRenderPass(e){return this._internalAbstractMeshDataInfo._materialForRenderPass?.[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new wt,this._waitingMaterialId=null,this._waitingMorphTargetManagerId=null,this.cullingStrategy=Nt.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new z.cP,this.onCollisionPositionChangeObservable=new z.cP,this.onMaterialChangedObservable=new z.cP,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=H.v9.Red(),this.outlineWidth=.02,this.overlayColor=H.v9.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 W.Pq(.5,1,.5),this.ellipsoidOffset=new W.Pq(0,0,0),this.edgesWidth=1,this.edgesColor=new H.ov(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 z.cP,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>Ot.$.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),i&&this.onCollideObservable.notifyObservers(i),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},(t=this.getScene()).addMesh(this),this._resyncLightSources(),this._uniformBuffer=new Rt.D(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case 2:this.doNotSyncBoundingInfo=!0;case 1:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1}}_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: "+("InstancedMesh"!==this.getClassName()?"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!==Pt.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive)){if(!e)return this.actionManager;if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),null!==this._occlusionQuery&&(this._occlusionQuery=null),this.subMeshes){for(const e of this.subMeshes)e._rebuild();this.resetDrawCache()}}_resyncLightSources(){this._lightSources.length=0;for(const e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){const t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e);let r=!1;if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;r=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(r)}_unBindEffect(){for(const e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){const i=this._lightSources.indexOf(e);-1!==i&&(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,super.markAsDirty(e),this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,r){return this}updateVerticesData(e,t,i,r){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){return this.rawBoundingInfo??this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,i){return this._boundingInfo=new _t(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(st.R.MatricesIndicesKind)&&this.isVerticesDataPresent(st.R.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===Pt.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():super.getWorldMatrix()}_getWorldMatrixDeterminant(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():super._getWorldMatrixDeterminant()}get isAnInstance(){return!1}get hasInstances(){return!1}get hasThinInstances(){return!1}movePOV(e,t,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){const r=new W.uq;(this.rotationQuaternion?this.rotationQuaternion:W.PT.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(r);const s=W.Pq.Zero(),n=this.definedFacingForward?-1:1;return W.Pq.TransformCoordinatesFromFloatsToRef(e*n,t,i*n,r,s),s}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const r=this.definedFacingForward?1:-1;return new W.Pq(e*r,t,i*r)}_refreshBoundingInfo(e,t){if(e){const i=(0,mt.b8)(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new _t(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t0&&(W.uq.FromFloat32ArrayToRefScaled(i,Math.floor(16*r[u+d]),f,h),l.addToSelf(h));if(n&&o)for(d=0;d<4;d++)f=o[u+d],f>0&&(W.uq.FromFloat32ArrayToRefScaled(i,Math.floor(16*n[u+d]),f,h),l.addToSelf(h));c(e[t],e[t+1],e[t+2],l,a),a.toArray(e,t)}}(e,t,i,r,s,n,o)}_getData(e,t,i=st.R.PositionKind){const r=e.cache,s=e=>{if(r){const t=r._vertexData||(r._vertexData={});return t[e]||this.copyVerticesData(e,t),t[e]}return this.getVerticesData(e)};if(t||(t=s(i)),!t)return null;if(r?(r._outputData?r._outputData.set(t):r._outputData=new Float32Array(t),t=r._outputData):(e.applyMorph&&this.morphTargetManager||e.applySkeleton&&this.skeleton)&&(t=t.slice()),e.applyMorph&&this.morphTargetManager&&function(e,t,i){let r=null;switch(t){case st.R.PositionKind:r=e=>e.getPositions();break;case st.R.NormalKind:r=e=>e.getNormals();break;case st.R.TangentKind:r=e=>e.getTangents();break;case st.R.UVKind:r=e=>e.getUVs();break;default:return}for(let t=0;t4,o=n?s(st.R.MatricesIndicesExtraKind):null,a=n?s(st.R.MatricesWeightsExtraKind):null,l=this.skeleton.getTransformMatrices(this);Nt._ApplySkeleton(t,i,l,e,r,o,a)}}if(!1!==e.updatePositionsArray&&i===st.R.PositionKind){const e=this._internalAbstractMeshDataInfo._positions||[],i=e.length;if(e.length=t.length/3,i1||!r.IsGlobal)&&r.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const r=this.getBoundingInfo(),s=e.getBoundingInfo();if(r.intersects(s,t))return!0;if(i)for(const i of this.getChildMeshes())if(i.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 t=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=t.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,t.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const i=e.verticesStart,r=e.verticesStart+e.verticesCount;for(let s=i;s1&&!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.AA.Matrix[0],i=W.AA.Matrix[1];return W.uq.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,r=!1,s,n=!1){const o=new At.G,a=this.getClassName(),l="InstancedLinesMesh"===a||"LinesMesh"===a||"GreasedLineMesh"===a?this.intersectionThreshold:0,h=this.getBoundingInfo();if(!this.subMeshes)return o;if(!(n||e.intersectsSphere(h.boundingSphere,l)&&e.intersectsBox(h.boundingBox,l)))return o;if(r)return o.hit=!n,o.pickedMesh=n?null:this,o.distance=n?0:W.Pq.Distance(e.origin,h.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let c=null;const u=this._scene.getIntersectingSubMeshCandidates(this,e),d=u.length;let f=!1;for(let e=0;e1&&!n&&!s.canIntersects(e))continue;const o=s.intersects(e,this._positions,this.getIndices(),t,i);if(o&&(t||!c||o.distancee!==this&&e.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 t=e.includedOnlyMeshes.indexOf(this);-1!==t&&e.includedOnlyMeshes.splice(t,1),t=e.excludedMeshes.indexOf(this),-1!==t&&e.excludedMeshes.splice(t,1);const i=e.getShadowGenerators();if(i){const e=i.values();for(let i=e.next();!0!==i.done;i=e.next()){const e=i.value.getShadowMap();e&&e.renderList&&(t=e.renderList.indexOf(this),-1!==t&&e.renderList.splice(t,1))}}})),"InstancedMesh"===this.getClassName()&&"InstancedLinesMesh"===this.getClassName()||this.releaseSubMeshes();const s=r.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,s.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),s.wipeCaches(),r.removeMesh(this),this._parentContainer){const e=this._parentContainer.meshes.indexOf(this);e>-1&&this._parentContainer.meshes.splice(e,1),this._parentContainer=null}if(t&&this.material&&("MultiMaterial"===this.material.getClassName()?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i65535){t=!0;break}e.depthSortedIndices=t?new Uint32Array(i):new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){const t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:W.Pq.Zero()}e.depthSortedFacets=[];for(let t=0;tlt.bH?s.maximum.x-s.minimum.x:lt.bH,e.bbSize.y=s.maximum.y-s.minimum.y>lt.bH?s.maximum.y-s.minimum.y:lt.bH,e.bbSize.z=s.maximum.z-s.minimum.z>lt.bH?s.maximum.z-s.minimum.z:lt.bH;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=s,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),W.Pq.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,r&&bt.ComputeNormals(t,i,r,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const t=e.depthSortedIndices.length/3|0;for(let r=0;rs.subDiv.max||o<0||o>s.subDiv.max||a<0||a>s.subDiv.max?null:s.facetPartitioning[n+s.subDiv.max*o+s.subDiv.max*s.subDiv.max*a]}getClosestFacetAtCoordinates(e,t,i,r,s=!1,n=!0){const o=this.getWorldMatrix(),a=W.AA.Matrix[5];o.invertToRef(a);const l=W.AA.Vector3[8];W.Pq.TransformCoordinatesFromFloatsToRef(e,t,i,a,l);const h=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.z,r,s,n);return r&&W.Pq.TransformCoordinatesFromFloatsToRef(r.x,r.y,r.z,o,r),h}getClosestFacetAtLocalCoordinates(e,t,i,r,s=!1,n=!0){let o=null,a=0,l=0,h=0,c=0,u=0,d=0,f=0,p=0;const _=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;let v,x,b,S=Number.MAX_VALUE,T=S;for(let C=0;C=0||s&&!n&&c<=0)&&(c=x.x*b.x+x.y*b.y+x.z*b.z,u=-(x.x*e+x.y*t+x.z*i-c)/(x.x*x.x+x.y*x.y+x.z*x.z),d=e+x.x*u,f=t+x.y*u,p=i+x.z*u,a=d-e,l=f-t,h=p-i,T=a*a+l*l+h*h,Te.emitter===this))}}Nt.OCCLUSION_TYPE_NONE=0,Nt.OCCLUSION_TYPE_OPTIMISTIC=1,Nt.OCCLUSION_TYPE_STRICT=2,Nt.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,Nt.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,Nt.CULLINGSTRATEGY_STANDARD=0,Nt.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Nt.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Nt.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,(0,je.Cg)([$e.Cx.filter(((...[e,t,i,r,s])=>!(Array.isArray(e)||Array.isArray(t)||Array.isArray(i)||Array.isArray(r)||Array.isArray(s))))],Nt,"_ApplySkeleton",null),(0,X.Y5)("BABYLON.AbstractMesh",Nt);var Ft=i(30573);class Lt{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){it.p.Clone((()=>e),this)}serialize(){return it.p.Serialize(this)}parse(e,t,i){it.p.Parse((()=>this),e,t,i)}}(0,je.Cg)([(0,$e.lK)()],Lt.prototype,"func",null),(0,je.Cg)([(0,$e.lK)()],Lt.prototype,"funcRef",null),(0,je.Cg)([(0,$e.lK)()],Lt.prototype,"funcMask",null),(0,je.Cg)([(0,$e.lK)()],Lt.prototype,"opStencilFail",null),(0,je.Cg)([(0,$e.lK)()],Lt.prototype,"opDepthFail",null),(0,je.Cg)([(0,$e.lK)()],Lt.prototype,"opStencilDepthPass",null),(0,je.Cg)([(0,$e.lK)()],Lt.prototype,"mask",null),(0,je.Cg)([(0,$e.lK)()],Lt.prototype,"enabled",null);var Bt=i(85770);class Vt{get shaderLanguage(){return this._shaderLanguage}get canRenderToMRT(){return!1}set alpha(e){if(this._alpha===e)return;const t=this._alpha;this._alpha=e,1!==t&&1!==e||this.markAsDirty(Vt.MiscDirtyFlag+Vt.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(Vt.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(Vt.TextureDirtyFlag))}get cullBackFaces(){return this._cullBackFaces}get blockDirtyMechanism(){return this._blockDirtyMechanism}set blockDirtyMechanism(e){this._blockDirtyMechanism!==e&&(this._blockDirtyMechanism=e,e||this.markDirty())}atomicMaterialsUpdate(e){this.blockDirtyMechanism=!0;try{e(this)}finally{this.blockDirtyMechanism=!1}}get hasRenderTargetTextures(){return this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._eventInfo.hasRenderTargetTextures}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new z.cP),this._onBindObservable}set onBind(e){this._onBindObserver&&this.onBindObservable.remove(this._onBindObserver),this._onBindObserver=this.onBindObservable.add(e)}get onUnBindObservable(){return this._onUnBindObservable||(this._onUnBindObservable=new z.cP),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new z.cP),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(Vt.TextureDirtyFlag))}get alphaMode(){return this._alphaMode}set needDepthPrePass(e){this._needDepthPrePass!==e&&(this._needDepthPrePass=e,this._needDepthPrePass&&(this.checkReadyOnEveryCall=!0))}get needDepthPrePass(){return this._needDepthPrePass}get isPrePassCapable(){return!1}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAsDirty(Vt.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case Vt.WireFrameFillMode:case Vt.LineListDrawMode:case Vt.LineLoopDrawMode:case Vt.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?Vt.WireFrameFillMode:Vt.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case Vt.PointFillMode:case Vt.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?Vt.PointFillMode:Vt.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(Vt.MiscDirtyFlag))}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){const t=this.getScene().getEngine().getCaps().fragmentDepthSupported;e&&!t&&Z.V.Warn("Logarithmic depth has been requested for a material on a device that doesn't support it."),this._useLogarithmicDepth=e&&t,this._markAllSubMeshesAsMiscDirty()}_getDrawWrapper(){return this._drawWrapper}_setDrawWrapper(e){this._drawWrapper=e}constructor(e,t,i,r=!1){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!0,this._shaderLanguage=0,this._forceGLSL=!1,this.metadata=null,this.reservedDataStore=null,this.checkReadyOnEveryCall=!1,this.checkReadyOnlyOnce=!1,this.state="",this._alpha=1,this._backFaceCulling=!0,this._cullBackFaces=!0,this._blockDirtyMechanism=!1,this.sideOrientation=null,this.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new z.cP,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=2,this._needDepthPrePass=!1,this.disableDepthWrite=!1,this.disableColorWrite=!1,this.forceDepthWrite=!1,this.depthFunction=0,this.separateCullingPass=!1,this._fogEnabled=!0,this.pointSize=1,this.zOffset=0,this.zOffsetUnits=0,this.stencil=new Lt,this._useUBO=!1,this._fillMode=Vt.TriangleFillMode,this._cachedDepthWriteState=!1,this._cachedColorWriteState=!1,this._cachedDepthFunctionState=0,this._indexInSceneMaterialArray=-1,this.meshMap=null,this._parentContainer=null,this._uniformBufferLayoutBuilt=!1,this._eventInfo={},this._callbackPluginEventGeneric=()=>{},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||he.q.LastCreatedScene;s&&(this._scene=s,this._dirtyCallbacks={},this._forceGLSL=r,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||Ue.S0.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new gt.E(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._uniformBuffer=new Rt.D(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,this._createUniformBuffer(),i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),Vt.OnEventObservable.notifyObservers(this,1))}_createUniformBuffer(){const e=this.getScene().getEngine();this._uniformBuffer?.dispose(),e.isWebGPU&&!this._forceGLSL?(this._uniformBuffer=new Rt.D(e,void 0,void 0,this.name,!0),this._shaderLanguage=1):this._uniformBuffer=new Rt.D(this._scene.getEngine(),void 0,void 0,this.name),this._uniformBufferLayoutBuilt=!1}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){const r=t.materialDefines;return!!r&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}_getEffectiveOrientation(e){return null!==this.sideOrientation?this.sideOrientation:e.sideOrientation}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===Vt.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===Vt.MATERIAL_OPAQUE||this._transparencyMode===Vt.MATERIAL_ALPHATEST}needAlphaBlending(){return!this._disableAlphaBlending&&this.alpha<1}needAlphaBlendingForMesh(e){return e.visibility<1||!this._disableAlphaBlending&&(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 t of i.subMeshes)if(t.getMaterial()===this)for(const i of t._drawWrappers)i&&this._materialContext===i.materialContext&&(i._wasPreviouslyReady=!1,i._wasPreviouslyUsingInstances=null,i._forceRebindOnNextCall=e);e&&this.markAsDirty(Vt.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),r=(null==t?this.sideOrientation:t)===Vt.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(8,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const r=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),r._forceRebindOnNextCall=!1}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null,i){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,(0,Bt._8)(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),this._scene._cachedVisibility=e?e.visibility:1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){const e=this._scene.getEngine();this._cachedDepthWriteState=e.getDepthWrite(),e.setDepthWrite(!1)}if(this.disableColorWrite){const e=this._scene.getEngine();this._cachedColorWriteState=e.getColorWrite(),e.setColorWrite(!1)}if(0!==this.depthFunction){const e=this._scene.getEngine();this._cachedDepthFunctionState=e.getDepthFunction()||0,e.setDepthFunction(this.depthFunction)}}unbind(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(256,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(512,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(1024,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),Vt._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(const t of this.pluginManager._plugins){const i=e.pluginManager.getPlugin(t.name);i&&t.copyTo(i)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}return this._scene.meshes.filter((e=>e.material===this))}forceCompilation(e,t,i,r){const s={clipPlane:!1,useInstances:!1,...i},n=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const a=()=>{if(!this._scene||!this._scene.getEngine())return;const i=n.clipPlane;if(s.clipPlane&&(n.clipPlane=new Ft.Z(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,n=null;if(e.subMeshes){const t=new vt(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,s.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?n=t.effect.getCompilationError():(i=!1,setTimeout(a,16)))}i&&(this.allowShaderHotSwapping=o,n&&r&&r(n),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(a,16);s.clipPlane&&(n.clipPlane=i)};a()}forceCompilationAsync(e,t){return new Promise(((i,r)=>{this.forceCompilation(e,(()=>{i()}),t,(e=>{r(e)}))}))}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(Vt._DirtyCallbackArray.length=0,e&Vt.TextureDirtyFlag&&Vt._DirtyCallbackArray.push(Vt._TextureDirtyCallBack),e&Vt.LightDirtyFlag&&Vt._DirtyCallbackArray.push(Vt._LightsDirtyCallBack),e&Vt.FresnelDirtyFlag&&Vt._DirtyCallbackArray.push(Vt._FresnelDirtyCallBack),e&Vt.AttributesDirtyFlag&&Vt._DirtyCallbackArray.push(Vt._AttributeDirtyCallBack),e&Vt.MiscDirtyFlag&&Vt._DirtyCallbackArray.push(Vt._MiscDirtyCallBack),e&Vt.PrePassDirtyFlag&&Vt._DirtyCallbackArray.push(Vt._PrePassDirtyCallBack),Vt._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(Vt._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){const e=this.getScene().meshes;for(const t of e)if(t.subMeshes)for(const e of t.subMeshes)e.getMaterial()===this&&e.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 t of i.subMeshes)if(t.getMaterial(!1)===this)for(const i of t._drawWrappers)i&&i.defines&&i.defines.markAllAsDirty&&this._materialContext===i.materialContext&&e(i.defines)}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(Vt._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(Vt._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(Vt._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(Vt._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(Vt._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(Vt._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(Vt._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(Vt._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(Vt._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(Vt._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(0!==this._scene.performancePriority){this.checkReadyOnlyOnce=!0;const e=this._scene.onScenePerformancePriorityChangedObservable.addOnce((()=>{this.checkReadyOnlyOnce=!1}));this.onDisposeObservable.add((()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)}))}}setPrePassRenderer(e){return!1}dispose(e,t,i){const r=this.getScene();if(r.stopAnimation(this),r.freeProcessedMaterials(),r.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(2,this._eventInfo),this._parentContainer){const e=this._parentContainer.materials.indexOf(this);e>-1&&this._parentContainer.materials.splice(e,1),this._parentContainer=null}if(!0!==i)if(this.meshMap)for(const e in this.meshMap){const t=this.meshMap[e];t&&(this.releaseVertexArrayObject(t,!0),t.material=null)}else{const e=r.meshes;for(const t of e)t.material!==this||t.sourceMesh||(this.releaseVertexArrayObject(t,!0),t.material=null)}this._uniformBuffer.dispose(),this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}releaseVertexArrayObject(e,t){const i=e.geometry;if(i)if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(const r of e.subMeshes)i._releaseVertexArrayObject(r.effect),t&&r.effect&&r.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}serialize(){const e=it.p.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){if("BABYLON.PBRMaterial"===e.customType&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return Z.V.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null}else e.customType="BABYLON.StandardMaterial";const r=Ue.S0.Instantiate(e.customType).Parse(e,t,i);return r._loadedUniqueId=e.uniqueId,r}static _ParsePlugins(e,t,i,r){if(e.plugins)for(const s in e.plugins){const n=e.plugins[s];let o=t.pluginManager?.getPlugin(n.name);if(!o){const e=Ue.S0.Instantiate("BABYLON."+s);e&&(o=new e(t))}o?.parse(n,i,r)}}}Vt.TriangleFillMode=0,Vt.WireFrameFillMode=1,Vt.PointFillMode=2,Vt.PointListDrawMode=3,Vt.LineListDrawMode=4,Vt.LineLoopDrawMode=5,Vt.LineStripDrawMode=6,Vt.TriangleStripDrawMode=7,Vt.TriangleFanDrawMode=8,Vt.ClockWiseSideOrientation=0,Vt.CounterClockWiseSideOrientation=1,Vt.TextureDirtyFlag=1,Vt.LightDirtyFlag=2,Vt.FresnelDirtyFlag=4,Vt.AttributesDirtyFlag=8,Vt.MiscDirtyFlag=16,Vt.PrePassDirtyFlag=32,Vt.AllDirtyFlag=63,Vt.MATERIAL_OPAQUE=0,Vt.MATERIAL_ALPHATEST=1,Vt.MATERIAL_ALPHABLEND=2,Vt.MATERIAL_ALPHATESTANDBLEND=3,Vt.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,Vt.MATERIAL_NORMALBLENDMETHOD_RNM=1,Vt.OnEventObservable=new z.cP,Vt._AllDirtyCallBack=e=>e.markAllAsDirty(),Vt._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),Vt._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),Vt._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),Vt._MiscDirtyCallBack=e=>e.markAsMiscDirty(),Vt._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),Vt._LightsDirtyCallBack=e=>e.markAsLightDirty(),Vt._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),Vt._FresnelAndMiscDirtyCallBack=e=>{Vt._FresnelDirtyCallBack(e),Vt._MiscDirtyCallBack(e)},Vt._TextureAndMiscDirtyCallBack=e=>{Vt._TextureDirtyCallBack(e),Vt._MiscDirtyCallBack(e)},Vt._DirtyCallbackArray=[],Vt._RunDirtyCallBacks=e=>{for(const t of Vt._DirtyCallbackArray)t(e)},(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"id",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"uniqueId",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"name",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"metadata",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"checkReadyOnEveryCall",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"checkReadyOnlyOnce",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"state",void 0),(0,je.Cg)([(0,$e.lK)("alpha")],Vt.prototype,"_alpha",void 0),(0,je.Cg)([(0,$e.lK)("backFaceCulling")],Vt.prototype,"_backFaceCulling",void 0),(0,je.Cg)([(0,$e.lK)("cullBackFaces")],Vt.prototype,"_cullBackFaces",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"sideOrientation",void 0),(0,je.Cg)([(0,$e.lK)("alphaMode")],Vt.prototype,"_alphaMode",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"_needDepthPrePass",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"disableDepthWrite",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"disableColorWrite",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"forceDepthWrite",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"depthFunction",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"separateCullingPass",void 0),(0,je.Cg)([(0,$e.lK)("fogEnabled")],Vt.prototype,"_fogEnabled",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"pointSize",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"zOffset",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"zOffsetUnits",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"pointsCloud",null),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"fillMode",null),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"useLogarithmicDepth",null),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"transparencyMode",null);class kt extends Vt{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=(...i)=>{const r=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),r};const i=e.splice;e.splice=(t,r)=>{const s=i.apply(e,[t,r]);return this._markAllSubMeshesAsTexturesDirty(),s}}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){if(super.hasTexture(e))return!0;for(let t=0;t=0&&r.multiMaterials.splice(s,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new kt(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,Ge.Y&&Ge.Y.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach((e=>i.subMaterials.push(t.getLastMaterialById(e)))),i}}(0,X.Y5)("BABYLON.MultiMaterial",kt);var Ut=i(9180);class Gt{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class zt{}class Wt{constructor(){this.visibleInstances={},this.batchCache=new Ht,this.batchCacheReplacementModeInFrozenMode=new Ht,this.instancesBufferSize=2048}}class Ht{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class Xt{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class qt{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 Yt extends Nt{static _GetDefaultSideOrientation(e){return e||Yt.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(st.R.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(st.R.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 z.cP),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new z.cP),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new z.cP),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new z.cP),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new z.cP),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get sideOrientation(){return this._internalMeshDataInfo._sideOrientation}set sideOrientation(e){this._internalMeshDataInfo._sideOrientation=e,this._internalAbstractMeshDataInfo._sideOrientationHint=this._scene.useRightHandedSystem&&1===e||!this._scene.useRightHandedSystem&&0===e}get overrideMaterialSideOrientation(){return this.sideOrientation}set overrideMaterialSideOrientation(e){this.sideOrientation=e,this.material&&(this.material.sideOrientation=null)}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){e&&(this.material&&null===this.material.sideOrientation||this._internalAbstractMeshDataInfo._sideOrientationHint)&&(e.sideOrientation=null),this._setMaterial(e)}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesData}get previousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesPreviousData}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}_copySource(e,t,i=!0){const r=this.getScene();if(e._geometry&&e._geometry.applyToMesh(this),ce.r.DeepCopy(e,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=e,r.useClonedMeshMap&&(e._internalMeshDataInfo.meshMap||(e._internalMeshDataInfo.meshMap={}),e._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=e._originalBuilderSideOrientation,this._creationDataStorage=e._creationDataStorage,e._ranges){const t=e._ranges;for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&t[e]&&this.createAnimationRange(e,t[e].from,t[e].to)}if(e.metadata&&e.metadata.clone?this.metadata=e.metadata.clone():this.metadata=e.metadata,this._internalMetadata=e._internalMetadata,Ge.Y&&Ge.Y.HasTags(e)&&Ge.Y.AddTagsTo(this,Ge.Y.GetTags(e,!0)),this.setEnabled(e.isEnabled(!1)),this.parent=e.parent,this.setPivotMatrix(e.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=this.name+"."+e.id,this.material=e.material,!t){const t=e.getDescendants(!0);for(let e=0;e{e&&i&&(this._uniformBuffer?this.transferToEffect(t):i.bindOnlyWorldMatrix(t))},r&&this._copySource(r,s,n),null!==i&&(this.parent=i),this._instanceDataStorage.hardwareInstancedRendering=this.getEngine().getCaps().instancedArrays,this._internalMeshDataInfo._onMeshReadyObserverAdded=e=>{e.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 z.cP(this._internalMeshDataInfo._onMeshReadyObserverAdded),r&&r.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const r=0===this.getTotalVertices()||t&&t.doNotInstantiate&&(!0===t.doNotInstantiate||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));r.parent=e||this.parent,r.position=this.position.clone(),r.scaling=this.scaling.clone(),this.rotationQuaternion?r.rotationQuaternion=this.rotationQuaternion.clone():r.rotation=this.rotation.clone(),i&&i(this,r);for(const e of this.getChildTransformNodes(!0))"InstancedMesh"===e.getClassName()&&"Mesh"===r.getClassName()&&e.sourceMesh===this?e.instantiateHierarchy(r,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:r},i):e.instantiateHierarchy(r,t,i);return r}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices(),t+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;i0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){const e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort(((t,i)=>t.distanceOrScreenCoveragei.distanceOrScreenCoverage?-e:0))}addLODLevel(e,t){if(t&&t._masterMesh)return Z.V.Warn("You cannot use a mesh as LOD level twice"),this;const i=new Gt(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 e=0;e0||this.hasThinInstances);this.computeWorldMatrix();const n=this.material||r.defaultMaterial;if(n)if(n._storeEffectOnSubMeshes)for(const e of this.subMeshes){const t=e.getMaterial();if(t)if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,s))return!1}else if(!t.isReady(this,s))return!1}else if(!n.isReady(this,s))return!1;const o=i.currentRenderPassId;for(const e of this.lightSources){const t=e.getShadowGenerators();if(!t)continue;const r=t.values();for(let e=r.next();!0!==e.done;e=r.next()){const t=e.value;if(t&&(!t.getShadowMap()?.renderList||t.getShadowMap()?.renderList&&-1!==t.getShadowMap()?.renderList?.indexOf(this))){const e=t.getShadowMap().renderPassIds??[i.currentRenderPassId];for(let r=0;r0){const i=this.getIndices();if(!i)return null;const r=i.length;let s=!1;if(e)s=!0;else for(const e of this.subMeshes){if(e.indexStart+e.indexCount>r){s=!0;break}if(e.verticesStart+e.verticesCount>t){s=!0;break}}if(!s)return this.subMeshes[0]}return this.releaseSubMeshes(),new vt(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,r=0;for(;i%3!=0;)i++;this.releaseSubMeshes();for(let s=0;s=t);s++)vt.CreateFromIndices(0,r,s===e-1?t-r:i,this,void 0,!1),r+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,r){if(this._geometry)this._geometry.setVerticesData(e,t,i,r);else{const r=new bt;r.set(t,e);const s=this.getScene();new yt(yt.RandomId(),s,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=yt.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,r){return this._geometry?(r?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){const i=this.getVerticesData(st.R.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(st.R.PositionKind,i,!1,!1),t){const e=this.getIndices(),t=this.getVerticesData(st.R.NormalKind);if(!t)return this;bt.ComputeNormals(i,e,t),this.updateVerticesData(st.R.NormalKind,t,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry)return this;if(1===this._geometry.meshes.length)return this;const e=this._geometry,t=this._geometry.copy(yt.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let r=this._geometry;r||(r=new yt(yt.RandomId(),this.getScene(),void 0,void 0,this)),r.setIndexBuffer(e,t,i)}setIndices(e,t=null,i=!1,r=!1){if(this._geometry)this._geometry.setIndices(e,t,i,r);else{const t=new bt;t.indices=e;const r=this.getScene();new yt(yt.RandomId(),r,t,i,this)}return this}updateIndices(e,t,i=!1){return this._geometry?(this._geometry.updateIndices(e,t,i),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,i,r=!0){if(!this._geometry)return this;const s=this.getScene().getEngine();let n;if(this._unIndexed)n=this._getRenderingFillMode(i)===Vt.WireFrameFillMode?e._getLinesIndexBuffer(this.getIndices(),s):null;else switch(this._getRenderingFillMode(i)){case Vt.PointFillMode:n=null;break;case Vt.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),s);break;default:case Vt.TriangleFillMode:n=this._geometry.getIndexBuffer()}return this._bindDirect(t,n,r)}_bindDirect(e,t,i=!0){return this._geometry?(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(e),i&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(e,t,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(e,t),this):this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);const r=this.getScene().getEngine();return this._unIndexed&&t!==Vt.WireFrameFillMode||t==Vt.PointFillMode?r.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==Vt.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(),r=i._isInIntermediateRendering(),s=r?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,n=this._instanceDataStorage.batchCache;if(n.mustReturn=!1,n.renderSelf[e]=t||!s&&this.isEnabled()&&this.isVisible,n.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const t=this._instanceDataStorage.visibleInstances,s=i.getRenderId(),o=r?t.intermediateDefaultRenderId:t.defaultRenderId;n.visibleInstances[e]=t[s],!n.visibleInstances[e]&&o&&(n.visibleInstances[e]=t[o])}return n.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==n.visibleInstances[e]&&void 0!==n.visibleInstances[e],this._instanceDataStorage.previousBatch=n,n}_renderWithInstances(e,t,i,r,s){const n=i.visibleInstances[e._id],o=n?n.length:0,a=this._instanceDataStorage,l=a.instancesBufferSize;let h=a.instancesBuffer,c=a.instancesPreviousBuffer;const u=16*(o+1)*4;for(;a.instancesBufferSizee._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera1&&r.activeCamera===r.activeCameras[0]||s<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const n=this._getInstancesRenderList(e._id,!!i);if(n.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const o=r.getEngine();let a=0,l=null;this.ignoreCameraMaxZ&&r.activeCamera&&!r._isInIntermediateRendering()&&(a=r.activeCamera.maxZ,l=r.activeCamera,r.activeCamera.maxZ=0,r.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const h=e.getRenderingMesh(),c=n.hardwareInstancedRendering[e._id]||h.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,u=this._instanceDataStorage,d=e.getMaterial();if(!d)return l&&(l.maxZ=a,r.updateTransformMatrix(!0)),this;if(u.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===d){if(d._storeEffectOnSubMeshes&&!e._drawWrapper?._wasPreviouslyReady||!d._storeEffectOnSubMeshes&&!d._getDrawWrapper()._wasPreviouslyReady)return l&&(l.maxZ=a,r.updateTransformMatrix(!0)),this}else{if(d._storeEffectOnSubMeshes){if(!d.isReadyForSubMesh(this,e,c))return l&&(l.maxZ=a,r.updateTransformMatrix(!0)),this}else if(!d.isReady(this,c))return l&&(l.maxZ=a,r.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=d}let f;t&&o.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode),f=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const p=f?.effect??null;for(const t of r._beforeRenderingMeshStage)t.action(this,e,n,p);if(!f||!p)return l&&(l.maxZ=a,r.updateTransformMatrix(!0)),this;const _=i||this;let m;if(u.isFrozen||!this._internalMeshDataInfo._effectiveMaterial.backFaceCulling&&null===this._internalMeshDataInfo._effectiveMaterial.sideOrientation&&!this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)m=u.sideOrientation;else{const e=_._getWorldMatrixDeterminant();m=this._internalMeshDataInfo._effectiveMaterial._getEffectiveOrientation(this),e<0&&(m=m===Vt.ClockWiseSideOrientation?Vt.CounterClockWiseSideOrientation:Vt.ClockWiseSideOrientation),u.sideOrientation=m}const g=this._internalMeshDataInfo._effectiveMaterial._preBind(f,m);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&o.setDepthWrite(!0);const v=this._internalMeshDataInfo._effectiveMaterial,x=v.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),c||this._bind(e,p,x,!1);const b=_.getWorldMatrix();v._storeEffectOnSubMeshes?v.bindForSubMesh(b,this,e):v.bind(b,this),!v.backFaceCulling&&v.separateCullingPass&&(o.setState(!0,v.zOffset,!1,!g,v.cullBackFaces,v.stencil,v.zOffsetUnits),this._processRendering(this,e,p,x,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),o.setState(!0,v.zOffset,!1,g,v.cullBackFaces,v.stencil,v.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,p,x,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const t of r._afterRenderingMeshStage)t.action(this,e,n,p);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),l&&(l.maxZ=a,r.updateTransformMatrix(!0)),2!==r.performancePriority||u.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(st.R.MatricesWeightsKind)&&(this.isVerticesDataPresent(st.R.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(st.R.MatricesWeightsKind),t=e.length;for(let i=0;ii&&r++,0!==n&&u++,c+=n,i=n}if(l[u]++,u>n&&(n=u),0===c)s++;else{const i=1/c;let r=0;for(let s=0;s.001&&o++}}const h=this.skeleton.bones.length,c=this.getVerticesData(st.R.MatricesIndicesKind),u=this.getVerticesData(st.R.MatricesIndicesExtraKind);let d=0;for(let e=0;e=h||i<0)&&d++}return{skinned:!0,valid:0===s&&0===o&&0===d,report:"Number of Weights = "+i/4+"\nMaximum influences = "+n+"\nMissing Weights = "+s+"\nNot Sorted = "+r+"\nNot Normalized = "+o+"\nWeightCounts = ["+l+"]\nNumber of bones = "+h+"\nBad Bone Indices = "+d}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):4===this.delayLoadState&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return Ue.S0.LoadFile(this.delayLoadingFile,(t=>{t instanceof ArrayBuffer?this._delayLoadingFunction(t,this):this._delayLoadingFunction(JSON.parse(t),this),this.instances.forEach((e=>{e.refreshBoundingInfo(),e._syncSubMeshes()})),this.delayLoadState=1,e.removePendingData(this)}),(()=>{}),e.offlineProvider,t),this}isInFrustum(e){return 2!==this.delayLoadState&&!!super.isInFrustum(e)&&(this._checkDelayState(),!0)}setMaterialById(e){const t=this.getScene().materials;let i;for(i=t.length-1;i>-1;i--)if(t[i].id===e)return this.material=t[i],this;const r=this.getScene().multiMaterials;for(i=r.length-1;i>-1;i--)if(r[i].id===e)return this.material=r[i],this;return this}getAnimatables(){const e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(st.R.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(st.R.PositionKind);const r=W.Pq.Zero();let s;for(s=0;s{const a=e.width,l=e.height,h=this.getEngine().createCanvas(a,l).getContext("2d");h.drawImage(e,0,0);const c=h.getImageData(0,0,a,l).data;this.applyDisplacementMapFromBuffer(c,a,l,t,i,s,n,o),r&&r(this)}),a||(()=>{}),l.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,r,s,n,o,a=!1){if(!this.isVerticesDataPresent(st.R.PositionKind)||!this.isVerticesDataPresent(st.R.NormalKind)||!this.isVerticesDataPresent(st.R.UVKind))return Z.V.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const l=this.getVerticesData(st.R.PositionKind,!0,!0),h=this.getVerticesData(st.R.NormalKind),c=this.getVerticesData(st.R.UVKind);let u=W.Pq.Zero();const d=W.Pq.Zero(),f=W.I9.Zero();n=n||W.I9.Zero(),o=o||new W.I9(1,1);for(let a=0;a!this.getVertexBuffer(e)?.getIsInstanced())),i=this.getIndices(),r={},s=(e,t)=>{const r=new Float32Array(i.length*t);let s=0;for(let n=0;n{const t=r.length-1-e,i=r[t];for(let e=0;e{for(let e=0;e-1&&(r._waitingMorphTargetManagerId=e.morphTargetManagerId),void 0!==e.skeletonId&&null!==e.skeletonId&&(r.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(r.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let t=0;t4,l=a?this.getVerticesData(st.R.MatricesIndicesExtraKind):null,h=a?this.getVerticesData(st.R.MatricesWeightsExtraKind):null,c=e.getTransformMatrices(this),u=W.Pq.Zero(),d=new W.uq,f=new W.uq;let p,_=0;for(let e=0;e0&&(W.uq.FromFloat32ArrayToRefScaled(c,Math.floor(16*n[_+p]),m,f),d.addToSelf(f));if(a)for(p=0;p<4;p++)m=h[_+p],m>0&&(W.uq.FromFloat32ArrayToRefScaled(c,Math.floor(16*l[_+p]),m,f),d.addToSelf(f));W.Pq.TransformCoordinatesFromFloatsToRef(i._sourcePositions[e],i._sourcePositions[e+1],i._sourcePositions[e+2],d,u),u.toArray(r,e),t&&(W.Pq.TransformNormalFromFloatsToRef(i._sourceNormals[e],i._sourceNormals[e+1],i._sourceNormals[e+2],d,u),u.toArray(s,e)),d.reset()}return this.updateVerticesData(st.R.PositionKind,r),t&&this.updateVerticesData(st.R.NormalKind,s),this}static MinMax(e){let t=null,i=null;return e.forEach((function(e){const r=e.getBoundingInfo().boundingBox;t&&i?(t.minimizeInPlace(r.minimumWorld),i.maximizeInPlace(r.maximumWorld)):(t=r.minimumWorld,i=r.maximumWorld)})),t&&i?{min:t,max:i}:{min:W.Pq.Zero(),max:W.Pq.Zero()}}static Center(e){const t=e instanceof Array?Yt.MinMax(e):e;return W.Pq.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,r,s,n){return Xe(Yt._MergeMeshesCoroutine(e,t,i,r,s,n,!1))}static MergeMeshesAsync(e,t=!0,i,r,s,n){return qe(Yt._MergeMeshesCoroutine(e,t,i,r,s,n,!0),We())}static*_MergeMeshesCoroutine(e,t=!0,i,r,s,n,o){if(0===(e=e.filter(Boolean)).length)return null;let a;if(!i){let t=0;for(a=0;a=65536)return Z.V.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}n&&(s=!1);const l=new Array,h=new Array,c=new Array,u=e[0].sideOrientation;for(a=0;a{const t=e.computeWorldMatrix(!0);return{vertexData:bt.ExtractFromMesh(e,!1,!1),transform:t}},{vertexData:p,transform:_}=f(d);o&&(yield);const m=new Array(e.length-1);for(let t=1;t{throw(0,Je.n)("GroundMesh")},Yt._GoldbergMeshParser=(e,t)=>{throw(0,Je.n)("GoldbergMesh")},Yt._LinesMeshParser=(e,t)=>{throw(0,Je.n)("LinesMesh")},Yt._GreasedLineMeshParser=(e,t)=>{throw(0,Je.n)("GreasedLineMesh")},Yt._GreasedLineRibbonMeshParser=(e,t)=>{throw(0,Je.n)("GreasedLineRibbonMesh")},Yt._TrailMeshParser=(e,t)=>{throw(0,Je.n)("TrailMesh")},(0,X.Y5)("BABYLON.Mesh",Yt),Yt._instancedMeshFactory=(e,t)=>{const i=new Kt(e,t);if(t.instancedBuffers){i.instancedBuffers={};for(const e in t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e]}return i};class Kt extends Nt{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 e of t.getAnimationRanges())null!=e&&this.createAnimationRange(e.name,e.from,e.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){this._sourceMesh?.receiveShadows!==e&&Ue.S0.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){this._sourceMesh?.material!==e&&Ue.S0.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){this._sourceMesh?.visibility!==e&&Ue.S0.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){this._sourceMesh?.skeleton!==e&&Ue.S0.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&&Z.V.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}copyVerticesData(e,t){this._sourceMesh.copyVerticesData(e,t)}setVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,r),this.sourceMesh}updateVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,r),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let i;i="object"==typeof e?e:{applySkeleton:e,applyMorph:t};const r=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getData(i,null,st.R.PositionKind),r),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||Z.V.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!==Pt.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new W.uq);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,W.AA.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.AA.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&&0!==t.length){const t=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,t.boundingSphere)}else this._currentLOD=this.sourceMesh;return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e0&&-1===this.includedOnlyMeshes.indexOf(e)||this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)||!(0===this.includeOnlyWithLayerMask||this.includeOnlyWithLayerMask&e.layerMask)||0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask))}dispose(e,t=!1){if(this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){const e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(const e of this.getScene().meshes)e._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=$t.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const r=it.p.Clone(i,this);return e&&(r.name=e),t&&(r.parent=t),r.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(r),r}serialize(){const e=it.p.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)}))),it.p.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){return Ze.b.Construct("Light_Type_"+e,t,i)||null}static Parse(e,t){const i=$t.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const r=it.p.Parse(i,e,t);if(e.excludedMeshesIds&&(r._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(r._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(r.falloffType=e.falloffType),void 0!==e.lightmapMode&&(r.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t{const r=t.apply(e,i);for(const e of i)e._resyncLightSource(this);return r};const i=e.splice;e.splice=(t,r)=>{const s=i.apply(e,[t,r]);for(const e of s)e._resyncLightSource(this);return s};for(const t of e)t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...i)=>{const r=t.apply(e,i);return this._resyncMeshes(),r};const i=e.splice;e.splice=(t,r)=>{const s=i.apply(e,[t,r]);return this._resyncMeshes(),s},this._resyncMeshes()}_resyncMeshes(){for(const e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(const e of this.getScene().meshes)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0;const t=this.getTypeID();let i=this.intensityMode;switch(i===$t.INTENSITYMODE_AUTOMATIC&&(i=t===$t.LIGHTTYPEID_DIRECTIONALLIGHT?$t.INTENSITYMODE_ILLUMINANCE:$t.INTENSITYMODE_LUMINOUSINTENSITY),t){case $t.LIGHTTYPEID_POINTLIGHT:case $t.LIGHTTYPEID_SPOTLIGHT:switch(i){case $t.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case $t.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case $t.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case $t.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case $t.INTENSITYMODE_ILLUMINANCE:e=1;break;case $t.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001),e=2*Math.PI*(1-Math.cos(t));break}}break;case $t.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){const e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}$t.FALLOFF_DEFAULT=jt.c.FALLOFF_DEFAULT,$t.FALLOFF_PHYSICAL=jt.c.FALLOFF_PHYSICAL,$t.FALLOFF_GLTF=jt.c.FALLOFF_GLTF,$t.FALLOFF_STANDARD=jt.c.FALLOFF_STANDARD,$t.LIGHTMAP_DEFAULT=jt.c.LIGHTMAP_DEFAULT,$t.LIGHTMAP_SPECULAR=jt.c.LIGHTMAP_SPECULAR,$t.LIGHTMAP_SHADOWSONLY=jt.c.LIGHTMAP_SHADOWSONLY,$t.INTENSITYMODE_AUTOMATIC=jt.c.INTENSITYMODE_AUTOMATIC,$t.INTENSITYMODE_LUMINOUSPOWER=jt.c.INTENSITYMODE_LUMINOUSPOWER,$t.INTENSITYMODE_LUMINOUSINTENSITY=jt.c.INTENSITYMODE_LUMINOUSINTENSITY,$t.INTENSITYMODE_ILLUMINANCE=jt.c.INTENSITYMODE_ILLUMINANCE,$t.INTENSITYMODE_LUMINANCE=jt.c.INTENSITYMODE_LUMINANCE,$t.LIGHTTYPEID_POINTLIGHT=jt.c.LIGHTTYPEID_POINTLIGHT,$t.LIGHTTYPEID_DIRECTIONALLIGHT=jt.c.LIGHTTYPEID_DIRECTIONALLIGHT,$t.LIGHTTYPEID_SPOTLIGHT=jt.c.LIGHTTYPEID_SPOTLIGHT,$t.LIGHTTYPEID_HEMISPHERICLIGHT=jt.c.LIGHTTYPEID_HEMISPHERICLIGHT,(0,je.Cg)([(0,$e.jT)()],$t.prototype,"diffuse",void 0),(0,je.Cg)([(0,$e.jT)()],$t.prototype,"specular",void 0),(0,je.Cg)([(0,$e.lK)()],$t.prototype,"falloffType",void 0),(0,je.Cg)([(0,$e.lK)()],$t.prototype,"intensity",void 0),(0,je.Cg)([(0,$e.lK)()],$t.prototype,"range",null),(0,je.Cg)([(0,$e.lK)()],$t.prototype,"intensityMode",null),(0,je.Cg)([(0,$e.lK)()],$t.prototype,"radius",null),(0,je.Cg)([(0,$e.lK)()],$t.prototype,"_renderPriority",void 0),(0,je.Cg)([(0,$e.$z)("_reorderLightsInScene")],$t.prototype,"renderPriority",void 0),(0,je.Cg)([(0,$e.lK)("shadowEnabled")],$t.prototype,"_shadowEnabled",void 0),(0,je.Cg)([(0,$e.lK)("excludeWithLayerMask")],$t.prototype,"_excludeWithLayerMask",void 0),(0,je.Cg)([(0,$e.lK)("includeOnlyWithLayerMask")],$t.prototype,"_includeOnlyWithLayerMask",void 0),(0,je.Cg)([(0,$e.lK)("lightmapMode")],$t.prototype,"_lightmapMode",void 0);class Qt{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[],this.sounds=null,this.effectLayers=[],this.layers=[],this.reflectionProbes=[]}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach((t=>e=e.concat(t.bones))),e}}class Zt extends Qt{}class Jt{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 ei extends Qt{constructor(e){super(),this._wasAddedToScene=!1,(e=e||he.q.LastCreatedScene)&&(this.scene=e,this.proceduralTextures=[],e.onDisposeObservable.add((()=>{this._wasAddedToScene||this.dispose()})),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();for(const e of this.particleSystems)e.rebuild();for(const e of this.textures)e._rebuild()})))}_topologicalSort(e){const t=new Map;for(const i of e)t.set(i.uniqueId,i);const i={dependsOn:new Map,dependedBy:new Map};for(const t of e){const e=t.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(const r of e){const e=r.uniqueId,s=i.dependsOn.get(e);if(r instanceof Kt){const n=r.sourceMesh;t.has(n.uniqueId)&&(s.add(n.uniqueId),i.dependedBy.get(n.uniqueId).add(e))}const n=i.dependedBy.get(e);for(const s of r.getDescendants()){const r=s.uniqueId;t.has(r)&&(n.add(r),i.dependsOn.get(r).add(e))}}const r=[],s=[];for(const r of e){const e=r.uniqueId;0===i.dependsOn.get(e).size&&(s.push(r),t.delete(e))}const n=s;for(;n.length>0;){const e=n.shift();r.push(e);const s=i.dependedBy.get(e.uniqueId);for(const r of Array.from(s.values())){const s=i.dependsOn.get(r);s.delete(e.uniqueId),0===s.size&&t.get(r)&&(n.push(t.get(r)),t.delete(r))}}return t.size>0&&(Z.V.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach((e=>Z.V.Error(e.name)))),r}_addNodeAndDescendantsToList(e,t,i,r){if(i&&(!r||r(i))&&!t.has(i.uniqueId)){e.push(i),t.add(i.uniqueId);for(const s of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,s,r)}}_isNodeInContainer(e){return e instanceof Nt&&-1!==this.meshes.indexOf(e)||e instanceof Pt&&-1!==this.transformNodes.indexOf(e)||e instanceof $t&&-1!==this.lights.indexOf(e)||e instanceof rt&&-1!==this.cameras.indexOf(e)}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return Z.V.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 Z.V.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 Z.V.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 Z.V.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||Ue.S0.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const r={},s={},n=new Jt,o=[],a=[],l={doNotInstantiate:!0,...i},h=[],c=new Set;for(const e of this.transformNodes)null===e.parent&&this._addNodeAndDescendantsToList(h,c,e,l.predicate);for(const e of this.meshes)null===e.parent&&this._addNodeAndDescendantsToList(h,c,e,l.predicate);const u=this._topologicalSort(h),d=(i,o)=>{if(((t,i)=>{if(r[t.uniqueId]=i.uniqueId,s[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof Yt){const e=i;if(e.morphTargetManager){const i=t.morphTargetManager;e.morphTargetManager=i.clone();for(let t=0;te&&s[r[e.uniqueId]]))}}"InstancedMesh"!==n.getClassName()&&(n.material=s[r[t.uniqueId]])}else"MultiMaterial"===n.material.getClassName()?-1===this.scene.multiMaterials.indexOf(n.material)&&this.scene.addMultiMaterial(n.material):-1===this.scene.materials.indexOf(n.material)&&this.scene.addMaterial(n.material)}null===o.parent&&n.rootNodes.push(o)};return u.forEach((e=>{if("InstancedMesh"===e.getClassName()){const t=e,i=t.sourceMesh,n=r[i.uniqueId],o=("number"==typeof n?s[n]:i).createInstance(t.name);d(t,o)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?t=!1:l.doNotInstantiate&&(t="function"==typeof l.doNotInstantiate?!l.doNotInstantiate(e):!l.doNotInstantiate);const i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw new Error(`Could not clone or instantiate node on Asset Container ${e.name}`);d(e,i)}})),this.skeletons.forEach((t=>{if(l.predicate&&!l.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name);for(const e of this.meshes)if(e.skeleton===t&&!e.isAnInstance){const t=s[r[e.uniqueId]];if(!t||t.isAnInstance)continue;if(t.skeleton=i,-1!==o.indexOf(i))continue;o.push(i);for(const e of i.bones)e._linkedTransformNode&&(e._linkedTransformNode=s[r[e._linkedTransformNode.uniqueId]])}n.skeletons.push(i)})),this.animationGroups.forEach((t=>{if(l.predicate&&!l.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name,(e=>s[r[e.uniqueId]]||e));n.animationGroups.push(i)})),n}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||Ue.S0.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((t=>{e&&!e(t)||this.scene.addSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.addAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.addAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.addMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.addMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.addMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.addGeometry(t)})),this.transformNodes.forEach((i=>{e&&!e(i)||(this.scene.addTransformNode(i),t.push(i))})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.addActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.addTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.addReflectionProbe(t)}));for(const e of t)e.parent&&-1===this.scene.getNodes().indexOf(e.parent)&&(e.setParent?e.setParent(null):e.parent=null)}removeAllFromScene(){this._isValidHierarchy()||Ue.S0.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!1,this.removeFromScene(null),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this)}removeFromScene(e=null){this.cameras.forEach((t=>{e&&!e(t)||this.scene.removeCamera(t)})),this.lights.forEach((t=>{e&&!e(t)||this.scene.removeLight(t)})),this.meshes.forEach((t=>{e&&!e(t)||this.scene.removeMesh(t,!0)})),this.skeletons.forEach((t=>{e&&!e(t)||this.scene.removeSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.removeAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.removeAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.removeMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.removeMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.removeMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.removeGeometry(t)})),this.transformNodes.forEach((t=>{e&&!e(t)||this.scene.removeTransformNode(t)})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.removeActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.removeTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.removeReflectionProbe(t)}))}dispose(){this.cameras.slice(0).forEach((e=>{e.dispose()})),this.cameras.length=0,this.lights.slice(0).forEach((e=>{e.dispose()})),this.lights.length=0,this.meshes.slice(0).forEach((e=>{e.dispose()})),this.meshes.length=0,this.skeletons.slice(0).forEach((e=>{e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((e=>{e.dispose()})),this.animationGroups.length=0,this.multiMaterials.slice(0).forEach((e=>{e.dispose()})),this.multiMaterials.length=0,this.materials.slice(0).forEach((e=>{e.dispose()})),this.materials.length=0,this.geometries.slice(0).forEach((e=>{e.dispose()})),this.geometries.length=0,this.transformNodes.slice(0).forEach((e=>{e.dispose()})),this.transformNodes.length=0,this.actionManagers.slice(0).forEach((e=>{e.dispose()})),this.actionManagers.length=0,this.textures.slice(0).forEach((e=>{e.dispose()})),this.textures.length=0,this.reflectionProbes.slice(0).forEach((e=>{e.dispose()})),this.reflectionProbes.length=0,this.morphTargetManagers.slice(0).forEach((e=>{e.dispose()})),this.morphTargetManagers.length=0,this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(e&&t)for(const r of e){let e=!0;if(i)for(const t of i)if(r===t){e=!1;break}e&&(t.push(r),r._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,void 0===e&&(e=new Zt);for(const t in this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||("_environmentTexture"===t?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()}createRootMesh(){const e=new Yt("assetContainerRootMesh",this.scene);return this.meshes.forEach((t=>{t.parent||e.addChild(t)})),this.meshes.unshift(e),e}mergeAnimationsTo(e=he.q.LastCreatedScene,t,i=null){if(!e)return Z.V.Error("No scene available to merge animations to"),[];const r=i||(t=>{let i=null;const r=t.animations.length?t.animations[0].targetProperty:"",s=t.name.split(".").join("").split("_primitive")[0];switch(r){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(s);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(s);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(s)}return i});this.getNodes().forEach((e=>{const t=r(e);if(null!==t){for(const i of e.animations){const e=t.animations.filter((e=>e.targetProperty===i.targetProperty));for(const i of e){const e=t.animations.indexOf(i,0);e>-1&&t.animations.splice(e,1)}}t.animations=t.animations.concat(e.animations)}}));const s=[];return this.animationGroups.slice().forEach((e=>{s.push(e.clone(e.name,r)),e.animatables.forEach((e=>{e.stop()}))})),t.forEach((t=>{const i=r(t.target);i&&(e.beginAnimation(i,t.fromFrame,t.toFrame,t.loopAnimation,t.speedRatio,t.onAnimationEnd?t.onAnimationEnd:void 0,void 0,!0,void 0,t.onAnimationLoop?t.onAnimationLoop:void 0),e.stopAnimation(t.target))})),s}populateRootNodes(){this.rootNodes.length=0,this.meshes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.transformNodes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.lights.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.cameras.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}))}addAllAssetsToContainer(e){if(!e)return;const t=[],i=new Set;for(t.push(e);t.length>0;){const e=t.pop();if(e instanceof Yt?(e.geometry&&-1===this.geometries.indexOf(e.geometry)&&this.geometries.push(e.geometry),this.meshes.push(e)):e instanceof Pt?this.transformNodes.push(e):e instanceof $t?this.lights.push(e):e instanceof rt&&this.cameras.push(e),e instanceof Nt){if(e.material&&-1===this.materials.indexOf(e.material)){this.materials.push(e.material);for(const t of e.material.getActiveTextures())-1===this.textures.indexOf(t)&&this.textures.push(t)}e.skeleton&&-1===this.skeletons.indexOf(e.skeleton)&&this.skeletons.push(e.skeleton),e.morphTargetManager&&-1===this.morphTargetManagers.indexOf(e.morphTargetManager)&&this.morphTargetManagers.push(e.morphTargetManager)}for(const r of e.getChildren())i.has(r)||t.push(r);i.add(e)}this.populateRootNodes()}}class ti{constructor(e){this.SMOOTHING=.75,this.FFT_SIZE=512,this.BARGRAPHAMPLITUDE=256,this.DEBUGCANVASPOS={x:20,y:20},this.DEBUGCANVASSIZE={width:320,height:200},(e=e||he.q.LastCreatedScene)&&(this._scene=e,Ot.$.audioEngine?(this._audioEngine=Ot.$.audioEngine,this._audioEngine.canUseWebAudio&&this._audioEngine.audioContext&&(this._webAudioAnalyser=this._audioEngine.audioContext.createAnalyser(),this._webAudioAnalyser.minDecibels=-140,this._webAudioAnalyser.maxDecibels=0,this._byteFreqs=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._byteTime=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._floatFreqs=new Float32Array(this._webAudioAnalyser.frequencyBinCount))):Ue.S0.Warn("No audio engine initialized, failed to create an audio analyser"))}getFrequencyBinCount(){return this._audioEngine.canUseWebAudio?this._webAudioAnalyser.frequencyBinCount:0}getByteFrequencyData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs)),this._byteFreqs}getByteTimeDomainData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteTimeDomainData(this._byteTime)),this._byteTime}getFloatFrequencyData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs)),this._floatFreqs}drawDebugCanvas(){if(this._audioEngine.canUseWebAudio&&(this._debugCanvas||(this._debugCanvas=document.createElement("canvas"),this._debugCanvas.width=this.DEBUGCANVASSIZE.width,this._debugCanvas.height=this.DEBUGCANVASSIZE.height,this._debugCanvas.style.position="absolute",this._debugCanvas.style.top=this.DEBUGCANVASPOS.y+"px",this._debugCanvas.style.left=this.DEBUGCANVASPOS.x+"px",this._debugCanvasContext=this._debugCanvas.getContext("2d"),document.body.appendChild(this._debugCanvas),this._registerFunc=()=>{this.drawDebugCanvas()},this._scene.registerBeforeRender(this._registerFunc)),this._registerFunc&&this._debugCanvasContext)){const e=this.getByteFrequencyData();this._debugCanvasContext.fillStyle="rgb(0, 0, 0)",this._debugCanvasContext.fillRect(0,0,this.DEBUGCANVASSIZE.width,this.DEBUGCANVASSIZE.height);for(let t=0;tnew ri(e,t,i);class ri{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 z.cP,this.onAudioLockedObservable=new z.cP,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!(0,ii.BA)())return;void 0!==window.AudioContext&&(this.canUseWebAudio=!0);const r=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{r&&r.canPlayType&&(r.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||r.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch(e){}try{r&&r.canPlayType&&r.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}lock(){this._triggerSuspendedState()}unlock(){if("running"===this._audioContext?.state)return this._hideMuteButton(),void(this.unlocked||(this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)));this._tryToRun?this._audioContext?.suspend().then((()=>{this._tryToRun=!1,this._triggerRunningState()})):this._triggerRunningState()}_resumeAudioContextOnStateChange(){this._audioContext?.addEventListener("statechange",(()=>{this.unlocked&&"running"!==this._audioContext?.state&&this._resumeAudioContext()}),{once:!0,passive:!0,signal:AbortSignal.timeout(3e3)})}_resumeAudioContext(){return this._audioContext?.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,"running"===this._audioContext.state&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,Z.V.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 e=".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) }",t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),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 si{get loop(){return this._loop}set loop(e){e!==this._loop&&(this._loop=e,this.updateOptions({loop:e}))}get currentTime(){if(this._htmlAudioElement)return this._htmlAudioElement.currentTime;if(Ot.$.audioEngine?.audioContext&&(this.isPlaying||this.isPaused)){const e=this.isPaused?0:Ot.$.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+e}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){if(e==this._spatialSound)return;const t=this.isPlaying;this.pause(),e?(this._spatialSound=e,this._updateSpatialParameters()):this._disableSpatialSound(),t&&this.play()}constructor(e,t,i,r=null,s){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 z.cP,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=W.Pq.Zero(),this._localDirection=new W.Pq(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||he.q.LastCreatedScene)if(this._scene=i,si._SceneComponentInitialization(i),this._readyToPlayCallback=r,this._customAttenuationFunction=(e,t,i,r,s)=>t0&&(r=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":i.push(t);case"Array":0===i.length&&(i=t);for(let e=0;e{this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback()}),{once:!0}),document.body.appendChild(this._htmlAudioElement),this._htmlAudioElement.load()):this._scene._loadFile(t,(e=>{this._soundLoaded(e)}),void 0,!0,!0,(e=>{e&&Z.V.Error("XHR "+e.status+" error on: "+t+"."),Z.V.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}));break}}break;default:e=!1}e?r||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)):Z.V.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){Z.V.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),Ot.$.audioEngine&&!Ot.$.audioEngine.WarnedWebAudioUnsupported&&(Z.V.Error("Web Audio is not supported by your browser."),Ot.$.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)}dispose(){Ot.$.audioEngine?.canUseWebAudio&&(this.isPlaying&&this.stop(),this._isReadyToPlay=!1,-1===this.soundTrackId?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._htmlAudioElement=null),this._streamingSource&&(this._streamingSource.disconnect(),this._streamingSource=null),this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedTransformNode=null),this._clearTimeoutsAndObservers())}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){Ot.$.audioEngine?.audioContext&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){Ot.$.audioEngine?.audioContext&&Ot.$.audioEngine.audioContext.decodeAudioData(e,(e=>{this._audioBufferLoaded(e)}),(e=>{Z.V.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)}))}setAudioBuffer(e){Ot.$.audioEngine?.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),void 0!==this._offset&&this._soundSource.loopStart!==this._offset&&(this._soundSource.loopStart=this._offset),void 0!==this._length&&this._length!==this._soundSource.loopEnd&&(this._soundSource.loopEnd=(0|this._offset)+this._length))))}_createSpatialParameters(){Ot.$.audioEngine?.canUseWebAudio&&Ot.$.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=this._soundPanner??Ot.$.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_disableSpatialSound(){this._spatialSound&&(this._inputAudioNode=this._soundGain,this._soundPanner?.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(){Ot.$.audioEngine?.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){Ot.$.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){t{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource&&(this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode)),this._htmlAudioElement){const e=()=>{if(Ot.$.audioEngine?.unlocked){if(!this._htmlAudioElement)return;this._htmlAudioElement.currentTime=t??0;const i=this._htmlAudioElement.play();void 0!==i&&i.catch((()=>{Ot.$.audioEngine?.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=Ot.$.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))}))}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=Ot.$.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))};e()}}else{const s=()=>{if(Ot.$.audioEngine?.audioContext){if(i=i||this._length,void 0!==t&&this._setOffset(t),this._soundSource){const e=this._soundSource;e.onended=()=>{e.disconnect()}}if(this._soundSource=Ot.$.audioEngine?.audioContext.createBufferSource(),this._soundSource&&this._inputAudioNode){this._soundSource.buffer=this._audioBuffer,this._soundSource.connect(this._inputAudioNode),this._soundSource.loop=this.loop,void 0!==t&&(this._soundSource.loopStart=t),void 0!==i&&(this._soundSource.loopEnd=(0|t)+i),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},r=e?Ot.$.audioEngine?.audioContext.currentTime+e:Ot.$.audioEngine.audioContext.currentTime;const s=((this.isPaused?this.currentTime:0)+(this._offset??0))%this._soundSource.buffer.duration;this._soundSource.start(r,s,this.loop?void 0:i)}}};"suspended"===Ot.$.audioEngine?.audioContext.state?this._tryToPlayTimeout=setTimeout((()=>{"suspended"===Ot.$.audioEngine?.audioContext.state?(Ot.$.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=Ot.$.audioEngine.onAudioUnlockedObservable.addOnce((()=>{s()})))):s()}),500):s()}this._startTime=r,this.isPlaying=!0,this.isPaused=!1}catch(e){Z.V.Error("Error while trying to play audio: "+this.name+", "+e.message)}}_onended(){this.isPlaying=!1,this._startTime=0,this._currentTime=0,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)}stop(e){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(Ot.$.audioEngine?.audioContext&&this._soundSource){const t=e?Ot.$.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(t)}else this.isPlaying=!1;else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource?.disconnect(),this.isPlaying=!1,this.isPaused=!0):Ot.$.audioEngine?.audioContext&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=Ot.$.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){Ot.$.audioEngine?.canUseWebAudio&&this._soundGain&&(t&&Ot.$.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(Ot.$.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,Ot.$.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,Ot.$.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=e=>this._onRegisterAfterWorldMatrixUpdate(e),this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)}detachFromMesh(){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedTransformNode=null)}_onRegisterAfterWorldMatrixUpdate(e){if(e.getBoundingInfo){const t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);Ot.$.audioEngine?.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 si(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,t);return this.useCustomAttenuation&&i.setAttenuationFunction(this._customAttenuationFunction),i.setPosition(this._position),i.setPlaybackRate(this._playbackRate),e(),i}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){const e={name:this.name,url:this._url,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this._spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e}static Parse(e,t,i,r){const s=e.name;let n;n=e.url?i+e.url:i+s;const o={autoplay:e.autoplay,loop:e.loop,volume:e.volume,spatialSound:e.spatialSound,maxDistance:e.maxDistance,rolloffFactor:e.rolloffFactor,refDistance:e.refDistance,distanceModel:e.distanceModel,playbackRate:e.playbackRate};let a;if(r){const e=()=>{r._isReadyToPlay?(a._audioBuffer=r.getAudioBuffer(),a._isReadyToPlay=!0,a.autoplay&&a.play(0,a._offset,a._length)):setTimeout(e,300)};a=new si(s,new ArrayBuffer(0),t,null,o),e()}else a=new si(s,n,t,(()=>{t.removePendingData(a)}),o),t.addPendingData(a);if(e.position){const t=W.Pq.FromArray(e.position);a.setPosition(t)}if(e.isDirectional&&(a.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const t=W.Pq.FromArray(e.localDirectionToMesh);a.setLocalDirectionToMesh(t)}if(e.connectedMeshId){const i=t.getMeshById(e.connectedMeshId);i&&a.attachToMesh(i)}return e.metadata&&(a.metadata=e.metadata),a}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}_clearTimeoutsAndObservers(){this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&(Ot.$.audioEngine?.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}si._SceneComponentInitialization=e=>{throw(0,Je.n)("AudioSceneComponent")},(0,X.Y5)("BABYLON.Sound",si);class ni{constructor(e,t={}){this.id=-1,this._isInitialized=!1,(e=e||he.q.LastCreatedScene)&&(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(){Ot.$.audioEngine?.canUseWebAudio&&Ot.$.audioEngine.audioContext&&(this._outputAudioNode=Ot.$.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(Ot.$.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(Ot.$.audioEngine&&Ot.$.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){this._isInitialized||this._initializeSoundTrackAudioGraph(),Ot.$.audioEngine?.canUseWebAudio&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),void 0!==e.soundTrackId&&(-1===e.soundTrackId?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);-1!==t&&this.soundCollection.splice(t,1)}setVolume(e){Ot.$.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){if(Ot.$.audioEngine?.canUseWebAudio)for(let e=0;e{let s,n=[];if(i.sounds=i.sounds||[],void 0!==e.sounds&&null!==e.sounds)for(let o=0,a=e.sounds.length;o{e.play(),e.autoplay=!0,this.scene.mainSoundTrack.addSound(e)}))}removeFromContainer(e,t=!1){e.sounds&&e.sounds.forEach((e=>{e.stop(),e.autoplay=!1,this.scene.mainSoundTrack.removeSound(e),t&&e.dispose()}))}dispose(){const e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t0&&(r=t.activeCameras[0]),this.audioListenerPositionProvider){const e=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(e.x||0,e.y||0,e.z||0)}else r?this._cachedCameraPosition.equals(r.globalPosition)||(this._cachedCameraPosition.copyFrom(r.globalPosition),i.audioContext.listener.setPosition(r.globalPosition.x,r.globalPosition.y,r.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){const e=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(e.x||0,e.y||0,e.z||0,0,1,0)}else r?(r.rigCameras&&r.rigCameras.length>0&&(r=r.rigCameras[0]),r.getViewMatrix().invertToRef(this._invertMatrixTemp),W.Pq.TransformNormalToRef(_i._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);for(e=0;e{let t=e._getComponent(Ut.v.NAME_AUDIO);t||(t=new _i(e),e._addComponent(t))};class mi{constructor(e,t,i){if(this.loop=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._volume=1,this.isPlaying=!1,this.isPaused=!1,this._sounds=[],this._weights=[],t.length!==i.length)throw new Error("Sounds length does not equal weights length");this.loop=e,this._weights=i;let r=0;for(const e of i)r+=e;const s=r>0?1/r:0;for(let e=0;e{this._onended()}))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!==this._coneInnerAngle){if(this._coneOuterAnglee),this)}serialize(){return it.p.Serialize(this)}parse(e,t,i){it.p.Parse((()=>this),e,t,i)}}(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markSubMeshesAsAttributesDirty")],gi.prototype,"texture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markSubMeshesAsAttributesDirty")],gi.prototype,"isEnabled",void 0),(0,je.Cg)([(0,$e.lK)()],gi.prototype,"animationParameters",void 0),(0,je.Cg)([(0,$e.lK)()],gi.prototype,"time",void 0);var vi=i(4756);class xi extends vi.g{constructor(e,t,i,r,s,n=!0,o=!1,a=3,l=0,h,c){super(null,s,!n,o,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,h),this.format=r,this._engine&&(this._engine._caps.textureFloatLinearFiltering||1!==l||(a=1),this._engine._caps.textureHalfFloatLinearFiltering||2!==l||(a=1),this._texture=this._engine.createRawTexture(e,t,i,r,n,o,a,null,l,h??0,c??!1),this.wrapU=vi.g.CLAMP_ADDRESSMODE,this.wrapV=vi.g.CLAMP_ADDRESSMODE)}update(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer)}clone(){if(!this._texture)return super.clone();const e=new xi(null,this.getSize().width,this.getSize().height,this.format,this.getScene(),this._texture.generateMipMaps,this._invertY,this.samplingMode,this._texture.type,this._texture._creationFlags,this._useSRGBBuffer);return e._texture=this._texture,this._texture.incrementReferences(),e}static CreateLuminanceTexture(e,t,i,r,s=!0,n=!1,o=3){return new xi(e,t,i,1,r,s,n,o)}static CreateLuminanceAlphaTexture(e,t,i,r,s=!0,n=!1,o=3){return new xi(e,t,i,2,r,s,n,o)}static CreateAlphaTexture(e,t,i,r,s=!0,n=!1,o=3){return new xi(e,t,i,0,r,s,n,o)}static CreateRGBTexture(e,t,i,r,s=!0,n=!1,o=3,a=0,l=0,h=!1){return new xi(e,t,i,4,r,s,n,o,a,l,h)}static CreateRGBATexture(e,t,i,r,s=!0,n=!1,o=3,a=0,l=0,h=!1){return new xi(e,t,i,5,r,s,n,o,a,l,h)}static CreateRGBAStorageTexture(e,t,i,r,s=!0,n=!1,o=3,a=0,l=!1){return new xi(e,t,i,5,r,s,n,o,a,1,l)}static CreateRTexture(e,t,i,r,s=!0,n=!1,o=vi.g.TRILINEAR_SAMPLINGMODE,a=1){return new xi(e,t,i,6,r,s,n,o,a)}static CreateRStorageTexture(e,t,i,r,s=!0,n=!1,o=vi.g.TRILINEAR_SAMPLINGMODE,a=1){return new xi(e,t,i,6,r,s,n,o,a,1)}}var bi=i(5800),Si=i(87665);class Ti{get useTextureToStoreBoneMatrices(){return this._useTextureToStoreBoneMatrices}set useTextureToStoreBoneMatrices(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}get isUsingTextureForMatrices(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones}get uniqueId(){return this._uniqueId}constructor(e,t,i){this.name=e,this.id=t,this.bones=[],this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=W.uq.Identity(),this._currentRenderId=-1,this._ranges={},this._absoluteTransformIsDirty=!0,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new z.cP,this.bones=[],this._scene=i||he.q.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;const r=this._scene.getEngine().getCaps();this._canUseTextureForBones=r.textureFloat&&r.maxVertexTextureImageUnits>0}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 e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;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 e of this.bones)if(e._linkedTransformNode){const t=e._linkedTransformNode;e.position=t.position,t.rotationQuaternion?e.rotationQuaternion=t.rotationQuaternion:e.rotation=t.rotation,e.scaling=t.scaling}if(this.needInitialSkinMatrix)for(const e of this._meshesWithPoseMatrix){const t=e.getPoseMatrix();let i=this._isDirty;if(e._bonesTransformMatrices&&e._bonesTransformMatrices.length===16*(this.bones.length+1)||(e._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),i=!0),i){if(this._synchronizedWithMesh!==e){this._synchronizedWithMesh=e;for(const e of this.bones)e.getParent()||(e.getBindMatrix().multiplyToRef(t,W.AA.Matrix[1]),e._updateAbsoluteBindMatrices(W.AA.Matrix[1]));if(this.isUsingTextureForMatrices){const t=4*(this.bones.length+1);e._transformMatrixTexture&&e._transformMatrixTexture.getSize().width===t||(e._transformMatrixTexture&&e._transformMatrixTexture.dispose(),e._transformMatrixTexture=xi.CreateRGBATexture(e._bonesTransformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))}}this._computeTransformMatrices(e._bonesTransformMatrices,t),this.isUsingTextureForMatrices&&e._transformMatrixTexture&&e._transformMatrixTexture.update(e._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=xi.CreateRGBATexture(this._transformMatrices,4*(this.bones.length+1),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((t=>{t.enableBlending=!0,t.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(){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 t=0;t0&&(s.animation=i.animations[0].serialize()),e.ranges=[];for(const t in this._ranges){const i=this._ranges[t];if(!i)continue;const r={};r.name=t,r.from=i.from,r.to=i.to,e.ranges.push(r)}}return e}static Parse(e,t){const i=new Ti(e.name,e.id,t);let r;for(e.dimensionsAtRest&&(i.dimensionsAtRest=W.Pq.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix,r=0;r-1&&(n=i.bones[t.parentBoneIndex]);const o=t.rest?W.uq.FromArray(t.rest):null,a=new Si.$(t.name,i,n,W.uq.FromArray(t.matrix),o,null,s);void 0!==t.id&&null!==t.id&&(a.id=t.id),t.length&&(a.length=t.length),t.metadata&&(a.metadata=t.metadata),t.animation&&a.animations.push(pe.X5.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(i._hasWaitingData=!0,a._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(r=0;r0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=[],t=new Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()}))}}class Ci{constructor(e,t){this._scene=e,t instanceof Ti?(this._skeleton=t,this._mesh=null):(this._mesh=t,this._skeleton=t.skeleton)}async bakeVertexData(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=e.reduce(((e,t)=>e+t.to-t.from+1),0);if(isNaN(i))throw new Error("Invalid animation ranges.");let r=0;const s=new Float32Array(4*(t+1)*4*i);this._scene.stopAnimation(this._skeleton),this._skeleton.returnToRest();for(const t of e)for(let e=t.from;e<=t.to;e++)await this._executeAnimationFrame(s,e,r++);return s}async _executeAnimationFrame(e,t,i){return new Promise(((r,s)=>{this._scene.beginAnimation(this._skeleton,t,t,!1,1,(()=>{const t=this._skeleton.getTransformMatrices(this._mesh);e.set(t,i*t.length),r()}))}))}textureFromBakedVertexData(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=xi.CreateRGBATexture(e,4*(t+1),e.length/(4*(t+1)*4),this._scene,!1,!1,vi.g.NEAREST_NEAREST,1);return i.name="VAT"+this._skeleton.name,i}serializeBakedVertexDataToObject(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=4*(t+1),r=e.length/(4*(t+1)*4);return{vertexData:(0,bi.EL)(e),width:i,height:r}}loadBakedVertexDataFromObject(e){return new Float32Array((0,bi.yS)(e.vertexData))}serializeBakedVertexDataToJSON(e){return JSON.stringify(this.serializeBakedVertexDataToObject(e))}loadBakedVertexDataFromJSON(e){return this.loadBakedVertexDataFromObject(JSON.parse(e))}}var yi=i(1241);class Ei{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((e=>{e.type!==yi.Zp.POINTERDOWN?e.type===yi.Zp.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{if(this._reachTargetAlpha())return;const e=ai.j.Now;let t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();const i=e-this._lastInteractionTime-this._idleRotationWaitTime,r=Math.max(Math.min(i/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*r,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/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,this._lastFrameTime=null}resetLastInteractionTime(e){this._lastInteractionTime=e??ai.j.Now}_reachTargetAlpha(){return!(!this._attachedCamera||!this.targetAlpha)&&Math.abs(this._attachedCamera.alpha-this.targetAlpha){if(e&&(e.computeWorldMatrix(!0),e.getBoundingInfo)){const t=e.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=.05*t,this.upperRadiusTransitionRange=.05*t}})):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}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(Pi.EasingFunction.setEasingMode(Pi.EasingMode),this._radiusBounceTransition=pe.X5.CreateAnimation("radius",pe.X5.ANIMATIONTYPE_FLOAT,60,Pi.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=pe.X5.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()}}Pi.EasingFunction=new Se(.3),Pi.EasingMode=xe.EASINGMODE_EASEOUT;class Ai{constructor(){this.onTargetFramingAnimationEndObservable=new z.cP,this._mode=Ai.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();Ai.EasingFunction.setEasingMode(Ai.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==yi.Zp.POINTERDOWN?e.type===yi.Zp.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add((e=>{e&&e.getBoundingInfo&&this.zoomOnMesh(e,void 0,(()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()}))})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}zoomOnMesh(e,t=!1,i=null){e.computeWorldMatrix(!0);const r=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(r.minimumWorld,r.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);const r=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(r.min,r.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){const r=new W.Pq(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new W.Pq(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t{this.stopAllAnimations(),r&&r(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()})),l&&this._animatables.push(l),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=this._attachedCamera;if(!i)return 0;let r=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===Ai.IgnoreBoundsSizeMode&&(r=ri.upperRadiusLimit?i.upperRadiusLimit:r),r}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=ai.j.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation,i=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=pe.X5.CreateAnimation("beta",pe.X5.ANIMATIONTYPE_FLOAT,60,Ai.EasingFunction));const e=pe.X5.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,(()=>{this._clearAnimationLocks(),this.stopAllAnimations()}));e&&this._animatables.push(e)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=ai.j.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&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)}}Ai.EasingFunction=new Ee,Ai.EasingMode=xe.EASINGMODE_EASEINOUT,Ai.IgnoreBoundsSizeMode=0,Ai.FitFrustumSidesMode=1;class Ri{constructor(e,t=new W.Pq,i=0,r=!1){this.direction=e,this.rotatedDirection=t,this.diff=i,this.ignore=r}}class Ii{constructor(e){this._ui=e,this.name="AttachToBoxBehavior",this.distanceAwayFromFace=.15,this.distanceAwayFromBottomOfFace=.15,this._faceVectors=[new Ri(W.Pq.Up()),new Ri(W.Pq.Down()),new Ri(W.Pq.Left()),new Ri(W.Pq.Right()),new Ri(W.Pq.Forward()),new Ri(W.Pq.Forward().scaleInPlace(-1))],this._tmpMatrix=new W.uq,this._tmpVector=new W.Pq,this._zeroVector=W.Pq.Zero(),this._lookAtTmpMatrix=new W.uq}init(){}_closestFace(e){return this._faceVectors.forEach((t=>{this._target.rotationQuaternion||(this._target.rotationQuaternion=W.PT.RotationYawPitchRoll(this._target.rotation.y,this._target.rotation.x,this._target.rotation.z)),this._target.rotationQuaternion.toRotationMatrix(this._tmpMatrix),W.Pq.TransformCoordinatesToRef(t.direction,this._tmpMatrix,t.rotatedDirection),t.diff=W.Pq.GetAngleBetweenVectors(t.rotatedDirection,e,W.Pq.Cross(t.rotatedDirection,e))})),this._faceVectors.reduce(((e,t)=>e.ignore?t:t.ignore||e.diff{if(!this._scene.activeCamera)return;let t=this._scene.activeCamera.position;this._scene.activeCamera.devicePosition&&(t=this._scene.activeCamera.devicePosition);const i=this._closestFace(t.subtract(e.position));this._scene.activeCamera.leftCamera?this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix):this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix),W.Pq.TransformCoordinatesToRef(W.Pq.Up(),this._tmpMatrix,this._tmpVector),this._faceVectors.forEach((e=>{i.direction.x&&e.direction.x&&(e.ignore=!0),i.direction.y&&e.direction.y&&(e.ignore=!0),i.direction.z&&e.direction.z&&(e.ignore=!0)}));const r=this._closestFace(this._tmpVector);this._faceVectors.forEach((e=>{e.ignore=!1})),this._ui.position.copyFrom(e.position),i.direction.x&&(i.rotatedDirection.scaleToRef(e.scaling.x/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),i.direction.y&&(i.rotatedDirection.scaleToRef(e.scaling.y/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),i.direction.z&&(i.rotatedDirection.scaleToRef(e.scaling.z/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),this._ui.rotationQuaternion||(this._ui.rotationQuaternion=W.PT.RotationYawPitchRoll(this._ui.rotation.y,this._ui.rotation.x,this._ui.rotation.z)),i.rotatedDirection.scaleToRef(-1,this._tmpVector),this._lookAtToRef(this._tmpVector,r.rotatedDirection,this._ui.rotationQuaternion),r.direction.x&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.x/2,this._tmpVector),r.direction.y&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.y/2,this._tmpVector),r.direction.z&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.z/2,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)}))}detach(){this._scene.onBeforeRenderObservable.remove(this._onRenderObserver)}}class Mi{get delay(){return this.fadeInDelay}set delay(e){this.fadeInDelay=e,this.fadeOutDelay=e}constructor(){this.fadeInDelay=0,this.fadeOutDelay=0,this.fadeInTime=300,this.fadeOutTime=300,this._millisecondsPerFrame=1e3/60,this._hovered=!1,this._hoverValue=0,this._ownerNode=null,this._delay=0,this._time=300,this._update=()=>{if(this._ownerNode){if(this._hoverValue+=this._hovered?this._millisecondsPerFrame:-this._millisecondsPerFrame,this._setAllVisibility(this._ownerNode,(this._hoverValue-this._delay)/this._time),this._ownerNode.visibility>1){if(this._setAllVisibility(this._ownerNode,1),this._hoverValue>this._time)return this._hoverValue=this._time,void this._detachObserver()}else if(this._ownerNode.visibility<0&&(this._setAllVisibility(this._ownerNode,0),this._hoverValue<0))return this._hoverValue=0,void this._detachObserver();this._attachObserver()}}}get name(){return"FadeInOut"}init(){}attach(e){this._ownerNode=e,this._setAllVisibility(this._ownerNode,0)}detach(){this._ownerNode=null}fadeIn(e=!0){this._delay=e?this.fadeInDelay:this.fadeOutDelay,this._time=e?this.fadeInTime:this.fadeOutTime,this._detachObserver(),this._ownerNode&&(e&&this._ownerNode.visibility>=1||!e&&this._ownerNode.visibility<=0)||(this._hovered=e,this._hovered||(this._delay*=-1),this._ownerNode.visibility>=1?this._hoverValue=this._time:this._ownerNode.visibility<=0&&(this._hoverValue=0),this._update())}fadeOut(){this.fadeIn(!1)}_setAllVisibility(e,t){e.visibility=t,e.getChildMeshes().forEach((e=>{this._setAllVisibility(e,t)}))}_attachObserver(){this._onBeforeRenderObserver||(this._onBeforeRenderObserver=this._ownerNode?.getScene().onBeforeRenderObservable.add(this._update))}_detachObserver(){this._onBeforeRenderObserver&&(this._ownerNode?.getScene().onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=null)}}var Oi=i(83194);const Di={internalPickerForMesh:void 0};class wi{constructor(e,t,i=Number.MAX_VALUE,r=lt.bH){this.origin=e,this.direction=t,this.length=i,this.epsilon=r}clone(){return new wi(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const r=wi._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),s=wi._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let n,o,a,l,h=0,c=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xs.x)return!1}else if(n=1/this.direction.x,o=(r.x-this.origin.x)*n,a=(s.x-this.origin.x)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.ys.y)return!1}else if(n=1/this.direction.y,o=(r.y-this.origin.y)*n,a=(s.y-this.origin.y)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zs.z)return!1}else if(n=1/this.direction.z,o=(r.z-this.origin.z)*n,a=(s.z-this.origin.z)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){const i=e.center.x-this.origin.x,r=e.center.y-this.origin.y,s=e.center.z-this.origin.z,n=i*i+r*r+s*s,o=e.radius+t,a=o*o;if(n<=a)return!0;const l=i*this.direction.x+r*this.direction.y+s*this.direction.z;return!(l<0)&&n-l*l<=a}intersectsTriangle(e,t,i){const r=wi._TmpVector3[0],s=wi._TmpVector3[1],n=wi._TmpVector3[2],o=wi._TmpVector3[3],a=wi._TmpVector3[4];t.subtractToRef(e,r),i.subtractToRef(e,s),W.Pq.CrossToRef(this.direction,s,n);const l=W.Pq.Dot(r,n);if(0===l)return null;const h=1/l;this.origin.subtractToRef(e,o);const c=W.Pq.Dot(o,n)*h;if(c<-this.epsilon||c>1+this.epsilon)return null;W.Pq.CrossToRef(o,r,a);const u=W.Pq.Dot(this.direction,a)*h;if(u<-this.epsilon||c+u>1+this.epsilon)return null;const d=W.Pq.Dot(s,a)*h;return d>this.length?null:new ot(1-c-u,c,d)}intersectsPlane(e){let t;const i=W.Pq.Dot(e.normal,this.direction);if(Math.abs(i)<9.99999997475243e-7)return null;{const r=W.Pq.Dot(e.normal,this.origin);return t=(-e.d-r)/i,t<0?t<-9.99999997475243e-7?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{const e=(this.origin.y-t)/this.direction.y;return e>0?null:new W.Pq(this.origin.x+this.direction.x*-e,t,this.origin.z+this.direction.z*-e)}case"x":{const e=(this.origin.x-t)/this.direction.x;return e>0?null:new W.Pq(t,this.origin.y+this.direction.y*-e,this.origin.z+this.direction.z*-e)}case"z":{const e=(this.origin.z-t)/this.direction.z;return e>0?null:new W.Pq(this.origin.x+this.direction.x*-e,this.origin.y+this.direction.y*-e,t)}default:return null}}intersectsMesh(e,t,i,r=!1,s,n=!1){const o=W.AA.Matrix[0];return e.getWorldMatrix().invertToRef(o),this._tmpRay?wi.TransformToRef(this,o,this._tmpRay):this._tmpRay=wi.Transform(this,o),e.intersects(this._tmpRay,t,i,r,s,n)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let r=0;rt.distance?1:0}intersectionSegment(e,t,i){const r=this.origin,s=W.AA.Vector3[0],n=W.AA.Vector3[1],o=W.AA.Vector3[2],a=W.AA.Vector3[3];t.subtractToRef(e,s),this.direction.scaleToRef(wi._Rayl,o),r.addToRef(o,n),e.subtractToRef(r,a);const l=W.Pq.Dot(s,s),h=W.Pq.Dot(s,o),c=W.Pq.Dot(o,o),u=W.Pq.Dot(s,a),d=W.Pq.Dot(o,a),f=l*c-h*h;let p,_,m=f,g=f;fm&&(p=m,_=d+h,g=c)),_<0?(_=0,-u<0?p=0:-u>l?p=m:(p=-u,m=l)):_>g&&(_=g,-u+h<0?p=0:-u+h>l?p=m:(p=-u+h,m=l));const v=Math.abs(p)0&&x<=this.length&&T.lengthSquared()=e.distance?null:h:null}function ki(e,t,i,r,s,n){let o=null;const a=!!(e.activeCameras&&e.activeCameras.length>1&&e.cameraToUseForPointers!==e.activeCamera),l=e.cameraToUseForPointers||e.activeCamera,h=Di.internalPickerForMesh||Vi;for(let c=0;c1&&e.cameraToUseForPointers!==e.activeCamera),o=e.cameraToUseForPointers||e.activeCamera,a=Di.internalPickerForMesh||Vi;for(let l=0;l(e._tempPickingRay||(e._tempPickingRay=wi.Zero()),Fi(e,t,i,r,e._tempPickingRay,n||null),e._tempPickingRay)),r,s,!0);return o&&(o.ray=Ni(e,t,i,W.uq.Identity(),n||null)),o}function zi(e,t,i,r,s,n,o,a=!1){const l=ki(e,((r,s)=>(e._tempPickingRay||(e._tempPickingRay=wi.Zero()),Fi(e,t,i,r,e._tempPickingRay,n||null,!1,s),e._tempPickingRay)),r,s,!1,o);return l&&(l.ray=Ni(e,t,i,W.uq.Identity(),n||null)),l}function Wi(e,t,i,r,s){const n=ki(e,(i=>(e._pickWithRayInverseMatrix||(e._pickWithRayInverseMatrix=W.uq.Identity()),i.invertToRef(e._pickWithRayInverseMatrix),e._cachedRayForTransform||(e._cachedRayForTransform=wi.Zero()),wi.TransformToRef(t,e._pickWithRayInverseMatrix,e._cachedRayForTransform),e._cachedRayForTransform)),i,r,!1,s);return n&&(n.ray=t),n}function Hi(e,t,i,r,s,n){return Ui(e,(r=>Ni(e,t,i,r,s||null)),r,n)}function Xi(e,t,i,r){return Ui(e,(i=>(e._pickWithRayInverseMatrix||(e._pickWithRayInverseMatrix=W.uq.Identity()),i.invertToRef(e._pickWithRayInverseMatrix),e._cachedRayForTransform||(e._cachedRayForTransform=wi.Zero()),wi.TransformToRef(t,e._pickWithRayInverseMatrix,e._cachedRayForTransform),e._cachedRayForTransform)),i,r)}function qi(e,t=100,i,r){return Yi(e,new wi(W.Pq.Zero(),W.Pq.Zero(),t),t,i,r)}function Yi(e,t,i=100,r,s){r||(r=e.getWorldMatrix()),t.length=i,s?t.origin.copyFrom(s):t.origin.copyFrom(e.position);const n=W.AA.Vector3[2];n.set(0,0,e._scene.useRightHandedSystem?-1:1);const o=W.AA.Vector3[3];return W.Pq.TransformNormalToRef(n,r,o),W.Pq.NormalizeToRef(o,t.direction),t}function Ki(e,t){t&&(t.prototype.getForwardRay=function(e=100,t,i){return Yi(this,new wi(W.Pq.Zero(),W.Pq.Zero(),e),e,t,i)},t.prototype.getForwardRayToRef=function(e,t=100,i,r){return Yi(this,e,t,i,r)}),e&&(Oi.h._IsPickingAvailable=!0,e.prototype.createPickingRay=function(e,t,i,r,s=!1){return Ni(this,e,t,i,r,s)})}wi._TmpVector3=(0,at.mI)(6,W.Pq.Zero),wi._RayDistant=wi.Zero(),wi._Smallnum=1e-8,wi._Rayl=1e9,Ki(oi.Z,rt),oi.Z.prototype.createPickingRayToRef=function(e,t,i,r,s,n=!1,o=!1){return Fi(this,e,t,i,r,s,n,o)},oi.Z.prototype.createPickingRayInCameraSpace=function(e,t,i){return Li(this,e,t,i)},oi.Z.prototype.createPickingRayInCameraSpaceToRef=function(e,t,i,r){return Bi(this,e,t,i,r)},oi.Z.prototype.pickWithBoundingInfo=function(e,t,i,r,s){return Gi(this,e,t,i,r,s)},oi.Z.prototype.pick=function(e,t,i,r,s,n,o=!1){return zi(this,e,t,i,r,s,n,o)},oi.Z.prototype.pickWithRay=function(e,t,i,r){return Wi(this,e,t,i,r)},oi.Z.prototype.multiPick=function(e,t,i,r,s){return Hi(this,e,t,i,r,s)},oi.Z.prototype.multiPickWithRay=function(e,t,i){return Xi(this,e,t,i)};class ji{static _RemoveAndStorePivotPoint(e){e&&0===ji._PivotCached&&(e.getPivotPointToRef(ji._OldPivotPoint),ji._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,ji._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(W.uq.IdentityReadOnly),ji._OldPivotPoint.subtractToRef(e.getPivotPoint(),ji._PivotTranslation),ji._PivotTmpVector.copyFromFloats(1,1,1),ji._PivotTmpVector.subtractInPlace(e.scaling),ji._PivotTmpVector.multiplyInPlace(ji._PivotTranslation),e.position.addInPlace(ji._PivotTmpVector))),ji._PivotCached++}static _RestorePivotPoint(e){e&&!ji._OldPivotPoint.equalsToFloats(0,0,0)&&1===ji._PivotCached&&(e.setPivotPoint(ji._OldPivotPoint),e._postMultiplyPivotMatrix=ji._PivotPostMultiplyPivotMatrix,ji._PivotTmpVector.copyFromFloats(1,1,1),ji._PivotTmpVector.subtractInPlace(e.scaling),ji._PivotTmpVector.multiplyInPlace(ji._PivotTranslation),e.position.subtractInPlace(ji._PivotTmpVector)),this._PivotCached--}}function $i(e){const t=[],i=[],r=[],s=[],n=e.width||e.size||1,o=e.height||e.size||1,a=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE,l=n/2,h=o/2;i.push(-l,-h,0),r.push(0,0,-1),s.push(0,Tt.rX?1:0),i.push(l,-h,0),r.push(0,0,-1),s.push(1,Tt.rX?1:0),i.push(l,h,0),r.push(0,0,-1),s.push(1,Tt.rX?0:1),i.push(-l,h,0),r.push(0,0,-1),s.push(0,Tt.rX?0:1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),bt._ComputeSides(a,i,t,r,s,e.frontUVs,e.backUVs);const c=new bt;return c.indices=t,c.positions=i,c.normals=r,c.uvs=s,c}function Qi(e,t={},i=null){const r=new Yt(e,i);return t.sideOrientation=Yt._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,$i(t).applyToMesh(r,t.updatable),t.sourcePlane&&(r.translate(t.sourcePlane.normal,-t.sourcePlane.d),r.setDirection(t.sourcePlane.normal.scale(-1))),r}ji._PivotCached=0,ji._OldPivotPoint=new W.Pq,ji._PivotTranslation=new W.Pq,ji._PivotTmpVector=new W.Pq,ji._PivotPostMultiplyPivotMatrix=!1;const Zi={CreatePlane:Qi};bt.CreatePlane=$i,Yt.CreatePlane=(e,t,i,r,s)=>Qi(e,{size:t,width:t,height:t,sideOrientation:s,updatable:r},i);class Ji{get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}set enabled(e){e!=this._enabled&&this.onEnabledObservable.notifyObservers(e),this._enabled=e}get enabled(){return this._enabled}get options(){return this._options}set options(e){this._options=e}constructor(e){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this._activeDragButton=-1,this.maxDragAngle=0,this.dragButtons=[0,1,2],this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerId=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new z.cP,this.onDragStartObservable=new z.cP,this.onDragEndObservable=new z.cP,this.onEnabledObservable=new z.cP,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=e=>!0,this._tmpVector=new W.Pq(0,0,0),this._alternatePickedPoint=new W.Pq(0,0,0),this._worldDragAxis=new W.Pq(0,0,0),this._targetPosition=new W.Pq(0,0,0),this._attachedToElement=!1,this._startDragRay=new wi(new W.Pq,new W.Pq),this._lastPointerRay={},this._dragDelta=new W.Pq,this._pointA=new W.Pq(0,0,0),this._pointC=new W.Pq(0,0,0),this._localAxis=new W.Pq(0,0,0),this._lookAt=new W.Pq(0,0,0),this._options=e||{};let t=0;if(this._options.dragAxis&&t++,this._options.dragPlaneNormal&&t++,t>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}get name(){return"PointerDrag"}init(){}attach(e,t){this._scene=e.getScene(),e.isNearGrabbable=!0,this.attachedNode=e,Ji._PlaneScene||(this._debugMode?Ji._PlaneScene=this._scene:(Ji._PlaneScene=new oi.Z(this._scene.getEngine(),{virtual:!0}),Ji._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce((()=>{Ji._PlaneScene.dispose(),Ji._PlaneScene=null})))),this._dragPlane=Qi("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:Yt.DOUBLESIDE},Ji._PlaneScene),this.lastDragPosition=new W.Pq(0,0,0);const i=t||(e=>this.attachedNode==e||e.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add((e=>{if(this.enabled){if(e.type==yi.Zp.POINTERDOWN)this.startAndReleaseDragOnPointerEvents&&!this.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&i(e.pickInfo.pickedMesh)&&-1===this._activeDragButton&&-1!==this.dragButtons.indexOf(e.event.button)&&(this._activeDragButton=e.event.button,this._activePointerInfo=e,this._startDrag(e.event.pointerId,e.pickInfo.ray,e.pickInfo.pickedPoint));else if(e.type==yi.Zp.POINTERUP)!this.startAndReleaseDragOnPointerEvents||this.currentDraggingPointerId!=e.event.pointerId||this._activeDragButton!==e.event.button&&-1!==this._activeDragButton||this.releaseDrag();else if(e.type==yi.Zp.POINTERMOVE){const t=e.event.pointerId;if(this.currentDraggingPointerId===Ji._AnyMouseId&&t!==Ji._AnyMouseId){const i=e.event;("mouse"===i.pointerType||!this._scene.getEngine().hostInformation.isMobile&&i instanceof MouseEvent)&&(this._lastPointerRay[this.currentDraggingPointerId]&&(this._lastPointerRay[t]=this._lastPointerRay[this.currentDraggingPointerId],delete this._lastPointerRay[this.currentDraggingPointerId]),this.currentDraggingPointerId=t)}this._lastPointerRay[t]||(this._lastPointerRay[t]=new wi(new W.Pq,new W.Pq)),e.pickInfo&&e.pickInfo.ray&&(this._lastPointerRay[t].origin.copyFrom(e.pickInfo.ray.origin),this._lastPointerRay[t].direction.copyFrom(e.pickInfo.ray.direction),this.currentDraggingPointerId==t&&this.dragging&&this._moveDrag(e.pickInfo.ray))}}else this._attachedToElement&&this.releaseDrag()})),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{if(this._moving&&this.moveAttached){let e=!1;ji._RemoveAndStorePivotPoint(this.attachedNode),this._targetPosition.subtractToRef(this.attachedNode.absolutePosition,this._tmpVector),this._tmpVector.scaleInPlace(this.dragDeltaRatio),this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector,this._tmpVector),this.validateDrag(this._tmpVector)&&(this.attachedNode.setAbsolutePosition(this._tmpVector),e=!0),ji._RestorePivotPoint(this.attachedNode),e&&this.attachedNode.computeWorldMatrix()}}))}releaseDrag(){if(this.dragging&&(this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo})),this.currentDraggingPointerId=-1,this._activeDragButton=-1,this._activePointerInfo=null,this._moving=!1,this.detachCameraControls&&this._attachedToElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera){if("ArcRotateCamera"===this._scene.activeCamera.getClassName()){const e=this._scene.activeCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._scene.activeCamera.attachControl(!this._scene.activeCamera.inputs||this._scene.activeCamera.inputs.noPreventDefault);this._attachedToElement=!1}}startDrag(e=Ji._AnyMouseId,t,i){this._startDrag(e,t,i);let r=this._lastPointerRay[e];e===Ji._AnyMouseId&&(r=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),r&&this._moveDrag(r)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;ji._RemoveAndStorePivotPoint(this.attachedNode),t?(this._startDragRay.direction.copyFrom(t.direction),this._startDragRay.origin.copyFrom(t.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,i||this._tmpVector);const r=this._pickWithRayOnDragPlane(this._startDragRay);r?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(r),this.onDragStartObservable.notifyObservers({dragPlanePoint:r,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),ji._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;const t=this._pickWithRayOnDragPlane(e);if(t){ji._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?W.Pq.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),this._worldDragAxis.normalize(),i=W.Pq.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(i,this._dragDelta)):(i=this._dragDelta.length(),t.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:i,delta:this._dragDelta,dragPlanePoint:t,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this.lastDragPosition.copyFrom(t),ji._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(W.Pq.Dot(this._dragPlane.forward,e.direction));if(t>Math.PI/2&&(t=Math.PI-t),this.maxDragAngle>0&&t>this.maxDragAngle){if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*W.Pq.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);const t=W.Pq.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-t,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}return null}const i=this._dragPlane.forward,r=this._dragPlane.position,s=e.direction.dot(i);if(Math.abs(s).999?Math.abs(W.Pq.Dot(W.Pq.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(W.Pq.Right()):this._lookAt.copyFrom(W.Pq.UpReadOnly):(W.Pq.CrossToRef(this._localAxis,this._pointC,this._lookAt),W.Pq.CrossToRef(this._localAxis,this._lookAt,this._lookAt),this._lookAt.normalize()),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrientationForDragging?W.Pq.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(e.origin)),this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()),this._dragPlane.computeWorldMatrix(!0)}detach(){this._lastPointerRay={},this.attachedNode&&(this.attachedNode.isNearGrabbable=!1),this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this._dragPlane&&this._dragPlane.dispose(),this.releaseDrag()}}Ji._AnyMouseId=-2;class er{constructor(){this._startDistance=0,this._initialScale=new W.Pq(0,0,0),this._targetScale=new W.Pq(0,0,0),this._sceneRenderObserver=null,this._dragBehaviorA=new Ji({}),this._dragBehaviorA.moveAttached=!1,this._dragBehaviorB=new Ji({}),this._dragBehaviorB.moveAttached=!1}get name(){return"MultiPointerScale"}init(){}_getCurrentDistance(){return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length()}attach(e){this._ownerNode=e,this._dragBehaviorA.onDragStartObservable.add((()=>{this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging&&(this._dragBehaviorA.currentDraggingPointerId==this._dragBehaviorB.currentDraggingPointerId?this._dragBehaviorA.releaseDrag():(this._initialScale.copyFrom(e.scaling),this._startDistance=this._getCurrentDistance()))})),this._dragBehaviorB.onDragStartObservable.add((()=>{this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging&&(this._dragBehaviorA.currentDraggingPointerId==this._dragBehaviorB.currentDraggingPointerId?this._dragBehaviorB.releaseDrag():(this._initialScale.copyFrom(e.scaling),this._startDistance=this._getCurrentDistance()))})),[this._dragBehaviorA,this._dragBehaviorB].forEach((e=>{e.onDragObservable.add((()=>{if(this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging){const e=this._getCurrentDistance()/this._startDistance;this._initialScale.scaleToRef(e,this._targetScale)}}))})),e.addBehavior(this._dragBehaviorA),e.addBehavior(this._dragBehaviorB),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add((()=>{if(this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging){const t=this._targetScale.subtract(e.scaling).scaleInPlace(.1);t.length()>.01&&e.scaling.addInPlace(t)}}))}detach(){this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),[this._dragBehaviorA,this._dragBehaviorB].forEach((e=>{e.onDragStartObservable.clear(),e.onDragObservable.clear(),this._ownerNode.removeBehavior(e)}))}}class tr{constructor(){this._attachedToElement=!1,this._virtualMeshesInfo={},this._tmpVector=new W.Pq,this._tmpQuaternion=new W.PT,this._dragType={NONE:0,DRAG:1,DRAG_WITH_CONTROLLER:2,NEAR_DRAG:3},this._moving=!1,this._dragging=this._dragType.NONE,this.draggableMeshes=null,this.zDragFactor=3,this.currentDraggingPointerIds=[],this.detachCameraControls=!0,this.onDragStartObservable=new z.cP,this.onDragObservable=new z.cP,this.onDragEndObservable=new z.cP,this.allowMultiPointer=!0}get currentDraggingPointerId(){return void 0!==this.currentDraggingPointerIds[0]?this.currentDraggingPointerIds[0]:-1}set currentDraggingPointerId(e){this.currentDraggingPointerIds[0]=e}get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}get name(){return"BaseSixDofDrag"}get isMoving(){return this._moving}init(){}get _pointerCamera(){return this._scene.cameraToUseForPointers?this._scene.cameraToUseForPointers:this._scene.activeCamera}_createVirtualMeshInfo(){const e=new Pt("",tr._virtualScene);e.rotationQuaternion=new W.PT;const t=new Pt("",tr._virtualScene);t.rotationQuaternion=new W.PT;const i=new Pt("",tr._virtualScene);return i.rotationQuaternion=new W.PT,{dragging:!1,moving:!1,dragMesh:e,originMesh:t,pivotMesh:i,startingPivotPosition:new W.Pq,startingPivotOrientation:new W.PT,startingPosition:new W.Pq,startingOrientation:new W.PT,lastOriginPosition:new W.Pq,lastDragPosition:new W.Pq}}_resetVirtualMeshesPosition(){for(let e=0;el&&(l=Math.min(h-a,0)),o.scaleInPlace(l),o.addToRef(s.pivotMesh.absolutePosition,this._tmpVector),s.pivotMesh.setAbsolutePosition(this._tmpVector),o.addToRef(s.dragMesh.absolutePosition,this._tmpVector),s.dragMesh.setAbsolutePosition(this._tmpVector)}}attach(e){this._ownerNode=e,this._scene=this._ownerNode.getScene(),tr._virtualScene||(tr._virtualScene=new oi.Z(this._scene.getEngine(),{virtual:!0}),tr._virtualScene.detachControl());const t=e=>this._ownerNode===e||e.isDescendantOf(this._ownerNode)&&(!this.draggableMeshes||-1!==this.draggableMeshes.indexOf(e));this._pointerObserver=this._scene.onPointerObservable.add((e=>{const i=e.event.pointerId;this._virtualMeshesInfo[i]||(this._virtualMeshesInfo[i]=this._createVirtualMeshInfo());const r=this._virtualMeshesInfo[i],s="xr-near"===e.event.pointerType||"xr"===e.event.pointerType;if(e.type==yi.Zp.POINTERDOWN){if(!r.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&(!s||e.pickInfo.aimTransform)&&t(e.pickInfo.pickedMesh)){if((!this.allowMultiPointer||s)&&this.currentDraggingPointerIds.length>0)return;!this._pointerCamera||this._pointerCamera.cameraRigMode!==rt.RIG_MODE_NONE||this._pointerCamera._isLeftCamera||this._pointerCamera._isRightCamera||e.pickInfo.ray.origin.copyFrom(this._pointerCamera.globalPosition),this._ownerNode.computeWorldMatrix(!0);const t=this._virtualMeshesInfo[i];s?(this._dragging=e.pickInfo.originMesh?this._dragType.NEAR_DRAG:this._dragType.DRAG_WITH_CONTROLLER,t.originMesh.position.copyFrom(e.pickInfo.aimTransform.position),this._dragging===this._dragType.NEAR_DRAG&&e.pickInfo.gripTransform?t.originMesh.rotationQuaternion.copyFrom(e.pickInfo.gripTransform.rotationQuaternion):t.originMesh.rotationQuaternion.copyFrom(e.pickInfo.aimTransform.rotationQuaternion)):(this._dragging=this._dragType.DRAG,t.originMesh.position.copyFrom(e.pickInfo.ray.origin)),t.lastOriginPosition.copyFrom(t.originMesh.position),t.dragMesh.position.copyFrom(e.pickInfo.pickedPoint),t.lastDragPosition.copyFrom(e.pickInfo.pickedPoint),t.pivotMesh.position.copyFrom(this._ownerNode.getAbsolutePivotPoint()),t.pivotMesh.rotationQuaternion.copyFrom(this._ownerNode.absoluteRotationQuaternion),t.startingPosition.copyFrom(t.dragMesh.position),t.startingPivotPosition.copyFrom(t.pivotMesh.position),t.startingOrientation.copyFrom(t.dragMesh.rotationQuaternion),t.startingPivotOrientation.copyFrom(t.pivotMesh.rotationQuaternion),s?(t.originMesh.addChild(t.dragMesh),t.originMesh.addChild(t.pivotMesh)):t.originMesh.lookAt(t.dragMesh.position),t.dragging=!0,-1===this.currentDraggingPointerIds.indexOf(i)&&this.currentDraggingPointerIds.push(i),this.detachCameraControls&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._pointerCamera.inputs&&this._pointerCamera.inputs.attachedToElement?(this._pointerCamera.detachControl(),this._attachedToElement=!0):this.allowMultiPointer&&0!==this.currentDraggingPointerIds.length||(this._attachedToElement=!1)),this._targetDragStart(t.pivotMesh.position,t.pivotMesh.rotationQuaternion,i),this.onDragStartObservable.notifyObservers({position:t.pivotMesh.position})}}else if(e.type==yi.Zp.POINTERUP||e.type==yi.Zp.POINTERDOUBLETAP){const e=this.currentDraggingPointerIds.indexOf(i);r.dragging=!1,-1!==e&&(this.currentDraggingPointerIds.splice(e,1),0===this.currentDraggingPointerIds.length&&(this._moving=!1,this._dragging=this._dragType.NONE,this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._reattachCameraControls(),this._attachedToElement=!1)),r.originMesh.removeChild(r.dragMesh),r.originMesh.removeChild(r.pivotMesh),this._targetDragEnd(i),this.onDragEndObservable.notifyObservers({}))}else if(e.type==yi.Zp.POINTERMOVE&&-1!==this.currentDraggingPointerIds.indexOf(i)&&r.dragging&&e.pickInfo&&(e.pickInfo.ray||e.pickInfo.aimTransform)){let t=this.zDragFactor;(this.currentDraggingPointerIds.length>1||e.pickInfo.originMesh)&&(t=0),this._ownerNode.computeWorldMatrix(!0),s?this._pointerUpdateXR(e.pickInfo.aimTransform,e.pickInfo.gripTransform,i,t):this._pointerUpdate2D(e.pickInfo.ray,i,t),this._tmpQuaternion.copyFrom(r.startingPivotOrientation),this._tmpQuaternion.x=-this._tmpQuaternion.x,this._tmpQuaternion.y=-this._tmpQuaternion.y,this._tmpQuaternion.z=-this._tmpQuaternion.z,r.pivotMesh.absoluteRotationQuaternion.multiplyToRef(this._tmpQuaternion,this._tmpQuaternion),r.pivotMesh.absolutePosition.subtractToRef(r.startingPivotPosition,this._tmpVector),this.onDragObservable.notifyObservers({delta:this._tmpVector,position:r.pivotMesh.position,pickInfo:e.pickInfo}),this._targetDrag(this._tmpVector,this._tmpQuaternion,i),r.lastDragPosition.copyFrom(r.dragMesh.absolutePosition),this._moving=!0}}))}_applyZOffset(e,t,i){e.position.z-=e.position.z<1?t*i:t*i*e.position.z,e.position.z<0&&(e.position.z=0)}_targetDragStart(e,t,i){}_targetDrag(e,t,i){}_targetDragEnd(e){}_reattachCameraControls(){if(this._pointerCamera)if("ArcRotateCamera"===this._pointerCamera.getClassName()){const e=this._pointerCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._pointerCamera.attachControl(!this._pointerCamera.inputs||this._pointerCamera.inputs.noPreventDefault)}detach(){this._scene&&(this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._reattachCameraControls(),this._attachedToElement=!1),this._scene.onPointerObservable.remove(this._pointerObserver));for(const e in this._virtualMeshesInfo)this._virtualMeshesInfo[e].originMesh.dispose(),this._virtualMeshesInfo[e].dragMesh.dispose();this.onDragEndObservable.clear(),this.onDragObservable.clear(),this.onDragStartObservable.clear()}}class ir extends tr{constructor(){super(...arguments),this._sceneRenderObserver=null,this._targetPosition=new W.Pq(0,0,0),this._targetOrientation=new W.PT,this._targetScaling=new W.Pq(1,1,1),this._startingPosition=new W.Pq(0,0,0),this._startingOrientation=new W.PT,this._startingScaling=new W.Pq(1,1,1),this.onPositionChangedObservable=new z.cP,this.dragDeltaRatio=.2,this.rotateDraggedObject=!0,this.rotateAroundYOnly=!1,this.rotateWithMotionController=!0,this.disableMovement=!1,this.faceCameraOnDragStart=!1}get name(){return"SixDofDrag"}attach(e){super.attach(e),e.isNearGrabbable=!0,e.getChildMeshes().forEach((e=>{e.isNearGrabbable=!0})),this._virtualTransformNode=new Pt("virtual_sixDof",tr._virtualScene),this._virtualTransformNode.rotationQuaternion=W.PT.Identity(),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add((()=>{if(1===this.currentDraggingPointerIds.length&&this._moving&&!this.disableMovement){const t=W.AA.Vector3[0];t.copyFrom(this._targetPosition).subtractInPlace(e.absolutePosition).scaleInPlace(this.dragDeltaRatio);const i=W.AA.Vector3[1];if(i.copyFrom(t),e.parent){const r=W.AA.Matrix[0];e.parent.absoluteRotationQuaternion.toRotationMatrix(r),r.invert(),W.Pq.TransformNormalToRef(t,r,i)}if(e.position.addInPlace(i),this.onPositionChangedObservable.notifyObservers({position:e.absolutePosition}),!e.parent||e.parent.scaling&&!e.parent.scaling.isNonUniformWithinEpsilon(.001)){const t=W.AA.Quaternion[0];if(t.copyFrom(this._targetOrientation),e.parent){const i=W.AA.Quaternion[0];i.copyFrom(e.parent.absoluteRotationQuaternion),i.invertInPlace(),i.multiplyToRef(this._targetOrientation,t)}W.PT.SlerpToRef(e.rotationQuaternion,t,this.dragDeltaRatio,e.rotationQuaternion)}}}))}_getPositionOffsetAround(e,t,i){const r=W.AA.Matrix[0],s=W.AA.Matrix[1],n=W.AA.Matrix[2],o=W.AA.Matrix[3],a=W.AA.Matrix[4];return W.uq.TranslationToRef(e.x,e.y,e.z,r),W.uq.TranslationToRef(-e.x,-e.y,-e.z,s),W.uq.FromQuaternionToRef(i,n),W.uq.ScalingToRef(t,t,t,o),s.multiplyToRef(n,a),a.multiplyToRef(o,a),a.multiplyToRef(r,a),a.getTranslation()}_onePointerPositionUpdated(e,t){W.AA.Vector3[0].setAll(0),this._dragging===this._dragType.DRAG?this.rotateDraggedObject&&(this.rotateAroundYOnly?W.PT.RotationYawPitchRollToRef(t.toEulerAngles().y,0,0,W.AA.Quaternion[0]):W.AA.Quaternion[0].copyFrom(t),W.AA.Quaternion[0].multiplyToRef(this._startingOrientation,this._targetOrientation)):(this._dragging===this._dragType.NEAR_DRAG||this._dragging===this._dragType.DRAG_WITH_CONTROLLER&&this.rotateWithMotionController)&&t.multiplyToRef(this._startingOrientation,this._targetOrientation),this._targetPosition.copyFrom(this._startingPosition).addInPlace(e)}_twoPointersPositionUpdated(){const e=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].startingPosition,t=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].startingPosition,i=W.AA.Vector3[0];e.addToRef(t,i),i.scaleInPlace(.5);const r=W.AA.Vector3[1];t.subtractToRef(e,r);const s=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].dragMesh.absolutePosition,n=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].dragMesh.absolutePosition,o=W.AA.Vector3[2];s.addToRef(n,o),o.scaleInPlace(.5);const a=W.AA.Vector3[3];n.subtractToRef(s,a);const l=a.length()/r.length(),h=o.subtract(i),c=W.PT.FromEulerAngles(0,W.Pq.GetAngleBetweenVectorsOnPlane(r.normalize(),a.normalize(),W.Pq.UpReadOnly),0),u=this._ownerNode.parent;this._ownerNode.setParent(null);const d=this._getPositionOffsetAround(i.subtract(this._virtualTransformNode.getAbsolutePivotPoint()),l,c);this._virtualTransformNode.rotationQuaternion.multiplyToRef(c,this._ownerNode.rotationQuaternion),this._virtualTransformNode.scaling.scaleToRef(l,this._ownerNode.scaling),this._virtualTransformNode.position.addToRef(h.addInPlace(d),this._ownerNode.position),this.onPositionChangedObservable.notifyObservers({position:this._ownerNode.position}),this._ownerNode.setParent(u)}_targetDragStart(){const e=this.currentDraggingPointerIds.length;this._ownerNode.rotationQuaternion||(this._ownerNode.rotationQuaternion=W.PT.RotationYawPitchRoll(this._ownerNode.rotation.y,this._ownerNode.rotation.x,this._ownerNode.rotation.z));const t=this._ownerNode.getAbsolutePivotPoint();if(1===e){if(this._targetPosition.copyFrom(this._ownerNode.absolutePosition),this._targetOrientation.copyFrom(this._ownerNode.rotationQuaternion),this._targetScaling.copyFrom(this._ownerNode.absoluteScaling),this.faceCameraOnDragStart&&this._scene.activeCamera){const e=W.AA.Vector3[0];this._scene.activeCamera.position.subtractToRef(t,e),e.normalize();const i=W.AA.Quaternion[0];this._scene.useRightHandedSystem?W.PT.FromLookDirectionRHToRef(e,new W.Pq(0,1,0),i):W.PT.FromLookDirectionLHToRef(e,new W.Pq(0,1,0),i),i.normalize(),W.PT.RotationYawPitchRollToRef(i.toEulerAngles().y,0,0,W.AA.Quaternion[0]),this._targetOrientation.copyFrom(W.AA.Quaternion[0])}this._startingPosition.copyFrom(this._targetPosition),this._startingOrientation.copyFrom(this._targetOrientation),this._startingScaling.copyFrom(this._targetScaling)}else 2===e&&(this._virtualTransformNode.setPivotPoint(new W.Pq(0,0,0),0),this._virtualTransformNode.position.copyFrom(this._ownerNode.absolutePosition),this._virtualTransformNode.scaling.copyFrom(this._ownerNode.absoluteScaling),this._virtualTransformNode.rotationQuaternion.copyFrom(this._ownerNode.absoluteRotationQuaternion),this._virtualTransformNode.setPivotPoint(t,1),this._resetVirtualMeshesPosition())}_targetDrag(e,t){1===this.currentDraggingPointerIds.length?this._onePointerPositionUpdated(e,t):2===this.currentDraggingPointerIds.length&&this._twoPointersPositionUpdated()}_targetDragEnd(){if(1===this.currentDraggingPointerIds.length){this._resetVirtualMeshesPosition();const e=this.faceCameraOnDragStart;this.faceCameraOnDragStart=!1,this._targetDragStart(),this.faceCameraOnDragStart=e}}detach(){super.detach(),this._ownerNode&&this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),this._virtualTransformNode&&this._virtualTransformNode.dispose()}}class rr{constructor(){this._attachPointLocalOffset=new W.Pq,this._workingPosition=new W.Pq,this._workingQuaternion=new W.PT,this._lastTick=-1,this._hit=!1,this.hitNormalOffset=.05,this.meshes=[],this.interpolatePose=!0,this.lerpTime=250,this.keepOrientationVertical=!0,this.enabled=!0,this.maxStickingDistance=.8}get name(){return"SurfaceMagnetism"}init(){}attach(e,t){this._attachedMesh=e,this._scene=t||e.getScene(),this._attachedMesh.rotationQuaternion||(this._attachedMesh.rotationQuaternion=W.PT.RotationYawPitchRoll(this._attachedMesh.rotation.y,this._attachedMesh.rotation.x,this._attachedMesh.rotation.z)),this.updateAttachPoint(),this._workingPosition.copyFrom(this._attachedMesh.position),this._workingQuaternion.copyFrom(this._attachedMesh.rotationQuaternion),this._addObservables()}detach(){this._attachedMesh=null,this._removeObservables()}_getTargetPose(e){if(!this._attachedMesh)return null;if(e&&e.hit){const t=e.getNormal(!0,!0),i=e.pickedPoint;if(!t||!i)return null;t.normalize();const r=W.AA.Vector3[0];return r.copyFrom(t),r.scaleInPlace(this.hitNormalOffset),r.addInPlace(i),this._attachedMesh.parent&&(W.AA.Matrix[0].copyFrom(this._attachedMesh.parent.getWorldMatrix()).invert(),W.Pq.TransformNormalToRef(r,W.AA.Matrix[0],r)),{position:r,quaternion:W.PT.RotationYawPitchRoll(-Math.atan2(t.x,-t.z),this.keepOrientationVertical?0:Math.atan2(t.y,Math.sqrt(t.z*t.z+t.x*t.x)),0)}}return null}updateAttachPoint(){this._getAttachPointOffsetToRef(this._attachPointLocalOffset)}findAndUpdateTarget(e){if(this._hit=!1,!e.ray)return!1;const t=e.ray.intersectsMeshes(this.meshes)[0];if(this._attachedMesh&&t&&t.hit&&t.pickedMesh){const e=this._getTargetPose(t);e&&W.Pq.Distance(this._attachedMesh.position,e.position){this.enabled&&e.type==yi.Zp.POINTERMOVE&&e.pickInfo&&this.findAndUpdateTarget(e.pickInfo)})),this._lastTick=Date.now(),this._onBeforeRender=this._scene.onBeforeRenderObservable.add((()=>{const e=Date.now();this._updateTransformToGoal(e-this._lastTick),this._lastTick=e}))}_removeObservables(){this._scene.onPointerObservable.remove(this._pointerObserver),this._scene.onBeforeRenderObservable.remove(this._onBeforeRender),this._pointerObserver=null,this._onBeforeRender=null}}var sr,nr,or,ar=i(56984);class lr{constructor(){this._tmpQuaternion=new W.PT,this._tmpVectors=[new W.Pq,new W.Pq,new W.Pq,new W.Pq,new W.Pq,new W.Pq,new W.Pq],this._tmpMatrix=new W.uq,this._tmpInvertView=new W.uq,this._tmpForward=new W.Pq,this._tmpNodeForward=new W.Pq,this._tmpPosition=new W.Pq,this._workingPosition=new W.Pq,this._workingQuaternion=new W.PT,this._lastTick=-1,this._recenterNextUpdate=!0,this.interpolatePose=!0,this.lerpTime=500,this.ignoreCameraPitchAndRoll=!1,this.pitchOffset=15,this.maxViewVerticalDegrees=30,this.maxViewHorizontalDegrees=30,this.orientToCameraDeadzoneDegrees=60,this.ignoreDistanceClamp=!1,this.ignoreAngleClamp=!1,this.verticalMaxDistance=0,this.defaultDistance=.8,this.maximumDistance=2,this.minimumDistance=.3,this.useFixedVerticalOffset=!1,this.fixedVerticalOffset=0,this._enabled=!0}get followedCamera(){return this._followedCamera||this._scene.activeCamera}set followedCamera(e){this._followedCamera=e}get name(){return"Follow"}init(){}attach(e,t){this._scene=e.getScene(),this.attachedNode=e,t&&(this.followedCamera=t),this._addObservables()}detach(){this.attachedNode=null,this._removeObservables()}recenter(){this._recenterNextUpdate=!0}_angleBetweenVectorAndPlane(e,t){return this._tmpVectors[0].copyFrom(e),e=this._tmpVectors[0],this._tmpVectors[1].copyFrom(t),t=this._tmpVectors[1],e.normalize(),t.normalize(),Math.PI/2-Math.acos(W.Pq.Dot(e,t))}_length2D(e){return Math.sqrt(e.x*e.x+e.z*e.z)}_distanceClamp(e,t=!1){let i=this.minimumDistance,r=this.maximumDistance;const s=this.defaultDistance,n=this._tmpVectors[0];n.copyFrom(e);let o=n.length();if(n.normalizeFromLength(o),this.ignoreCameraPitchAndRoll){i=this._length2D(n)*i,r=this._length2D(n)*r;const t=this._length2D(e);n.scaleInPlace(o/t),o=t}let a=o;return a=t?s:(0,ar.Clamp)(o,i,r),e.copyFrom(n).scaleInPlace(a),o!==a}_applyVerticalClamp(e){0!==this.verticalMaxDistance&&(e.y=(0,ar.Clamp)(e.y,-this.verticalMaxDistance,this.verticalMaxDistance))}_toOrientationQuatToRef(e,t){W.PT.RotationYawPitchRollToRef(Math.atan2(e.x,e.z),Math.atan2(e.y,Math.sqrt(e.z*e.z+e.x*e.x)),0,t)}_applyPitchOffset(e){const t=this._tmpVectors[0],i=this._tmpVectors[1];t.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),i.copyFromFloats(1,0,0),W.Pq.TransformNormalToRef(t,e,t),t.y=0,t.normalize(),W.Pq.TransformNormalToRef(i,e,i),W.PT.RotationAxisToRef(i,this.pitchOffset*Math.PI/180,this._tmpQuaternion),t.rotateByQuaternionToRef(this._tmpQuaternion,t),this._toOrientationQuatToRef(t,this._tmpQuaternion),this._tmpQuaternion.toRotationMatrix(this._tmpMatrix),e.copyFrom(this._tmpMatrix)}_angularClamp(e,t){const i=this._tmpVectors[5];i.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1);const r=this._tmpVectors[6];r.copyFromFloats(1,0,0),W.Pq.TransformNormalToRef(i,e,i),W.Pq.TransformNormalToRef(r,e,r);const s=W.Pq.UpReadOnly;if(t.length()s&&(W.PT.RotationAxisToRef(r,-e+s,o),t.rotateByQuaternionToRef(o,t),n=!0)}const a=this._angleBetweenVectorAndPlane(t,r)*(this._scene.useRightHandedSystem?-1:1),l=this.maxViewHorizontalDegrees*Math.PI/180*.5;return a<-l?(W.PT.RotationAxisToRef(s,-a-l,o),t.rotateByQuaternionToRef(o,t),n=!0):a>l&&(W.PT.RotationAxisToRef(s,-a+l,o),t.rotateByQuaternionToRef(o,t),n=!0),n}_orientationClamp(e,t){const i=this._tmpVectors[0];i.copyFrom(e).scaleInPlace(-1).normalize();const r=this._tmpVectors[1],s=this._tmpVectors[2];r.copyFromFloats(0,1,0),W.Pq.CrossToRef(i,r,s);const n=s.length();nthis.orientToCameraDeadzoneDegrees}_updateLeashing(e){if(this.attachedNode&&this._enabled){const t=this.attachedNode.parent;this.attachedNode.setParent(null);const i=this.attachedNode.getWorldMatrix(),r=this._workingPosition,s=this._workingQuaternion,n=this.attachedNode.getPivotPoint(),o=this._tmpInvertView;o.copyFrom(e.getViewMatrix()),o.invert(),W.Pq.TransformCoordinatesToRef(n,i,r);const a=this._tmpPosition;a.copyFromFloats(0,0,0),W.Pq.TransformCoordinatesToRef(a,i,a),a.scaleInPlace(-1).subtractInPlace(n),r.subtractInPlace(e.globalPosition),this.ignoreCameraPitchAndRoll&&this._applyPitchOffset(o);let l=!1;const h=this._tmpForward;h.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),W.Pq.TransformNormalToRef(h,o,h);const c=this._tmpNodeForward;if(c.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),W.Pq.TransformNormalToRef(c,i,c),this._recenterNextUpdate)r.copyFrom(h).scaleInPlace(this.defaultDistance);else if(this.ignoreAngleClamp){const e=r.length();r.copyFrom(h).scaleInPlace(e)}else l=this._angularClamp(o,r);let u=!1;this.ignoreDistanceClamp||(u=this._distanceClamp(r,l),this._applyVerticalClamp(r)),this.useFixedVerticalOffset&&(r.y=a.y-e.globalPosition.y+this.fixedVerticalOffset),(l||u||this._passedOrientationDeadzone(r,c)||this._recenterNextUpdate)&&this._orientationClamp(r,s),this._workingPosition.subtractInPlace(n),this._recenterNextUpdate=!1,this.attachedNode.setParent(t)}}_updateTransformToGoal(e){if(!this.attachedNode||!this.followedCamera||!this._enabled)return;this.attachedNode.rotationQuaternion||(this.attachedNode.rotationQuaternion=W.PT.Identity());const t=this.attachedNode.parent;if(this.attachedNode.setParent(null),!this.interpolatePose)return this.attachedNode.position.copyFrom(this.followedCamera.globalPosition).addInPlace(this._workingPosition),void this.attachedNode.rotationQuaternion.copyFrom(this._workingQuaternion);const i=new W.Pq;i.copyFrom(this.attachedNode.position).subtractInPlace(this.followedCamera.globalPosition),W.Pq.SmoothToRef(i,this._workingPosition,e,this.lerpTime,i),i.addInPlace(this.followedCamera.globalPosition),this.attachedNode.position.copyFrom(i);const r=new W.PT;r.copyFrom(this.attachedNode.rotationQuaternion),W.PT.SmoothToRef(r,this._workingQuaternion,e,this.lerpTime,this.attachedNode.rotationQuaternion),this.attachedNode.setParent(t)}_addObservables(){this._lastTick=Date.now(),this._onBeforeRender=this._scene.onBeforeRenderObservable.add((()=>{if(!this.followedCamera)return;const e=Date.now();this._updateLeashing(this.followedCamera),this._updateTransformToGoal(e-this._lastTick),this._lastTick=e}))}_removeObservables(){this._onBeforeRender&&this._scene.onBeforeRenderObservable.remove(this._onBeforeRender)}}class hr{}hr.ANCHOR_SYSTEM="xr-anchor-system",hr.BACKGROUND_REMOVER="xr-background-remover",hr.HIT_TEST="xr-hit-test",hr.MESH_DETECTION="xr-mesh-detection",hr.PHYSICS_CONTROLLERS="xr-physics-controller",hr.PLANE_DETECTION="xr-plane-detection",hr.POINTER_SELECTION="xr-controller-pointer-selection",hr.TELEPORTATION="xr-controller-teleportation",hr.FEATURE_POINTS="xr-feature-points",hr.HAND_TRACKING="xr-hand-tracking",hr.IMAGE_TRACKING="xr-image-tracking",hr.NEAR_INTERACTION="xr-near-interaction",hr.DOM_OVERLAY="xr-dom-overlay",hr.MOVEMENT="xr-controller-movement",hr.LIGHT_ESTIMATION="xr-light-estimation",hr.EYE_TRACKING="xr-eye-tracking",hr.WALKING_LOCOMOTION="xr-walking-locomotion",hr.LAYERS="xr-layers",hr.DEPTH_SENSING="xr-depth-sensing",hr.SPACE_WARP="xr-space-warp",hr.RAW_CAMERA_ACCESS="xr-raw-camera-access";class cr{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];!t.enabled||t.featureImplementation.attached||t.featureImplementation.disableAutoAttach||this.attachFeature(e)}))})),this._xrSessionManager.onXRSessionEnded.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];t.enabled&&t.featureImplementation.attached&&this.detachFeature(e)}))}))}static AddWebXRFeature(e,t,i=1,r=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),r&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,r){const s=this._AvailableFeatures[e][t];if(!s)throw new Error("feature not found");return s(i,r)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){const t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&(t.featureImplementation.attach()||Ue.S0.Warn(`Feature ${e} failed to attach`))}detachFeature(e){const t=this._features[e];t&&t.featureImplementation.attached&&(t.featureImplementation.detach()||Ue.S0.Warn(`Feature ${e} failed to detach`))}disableFeature(e){const t="string"==typeof e?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))}dispose(){this.getEnabledFeatures().forEach((e=>{this.disableFeature(e)}))}enableFeature(e,t="latest",i={},r=!0,s=!0){const n="string"==typeof e?e:e.Name;let o=0;if("string"==typeof t){if(!t)throw new Error(`Error in provided version - ${n} (${t})`);if(o="stable"===t?cr.GetStableVersionOfFeature(n):"latest"===t?cr.GetLatestVersionOfFeature(n):+t,-1===o||isNaN(o))throw new Error(`feature not found - ${n} (${t})`)}else o=t;const a=cr._ConflictingFeatures[n];if(void 0!==a&&-1!==this.getEnabledFeatures().indexOf(a))throw new Error(`Feature ${n} cannot be enabled while ${a} is enabled.`);const l=this._features[n],h=cr.ConstructFeature(n,o,this._xrSessionManager,i);if(!h)throw new Error(`feature not found - ${n}`);l&&this.disableFeature(n);const c=h();if(c.dependsOn){const e=c.dependsOn.every((e=>!!this._features[e]));if(!e)throw new Error(`Dependant features missing. Make sure the following features are enabled - ${c.dependsOn.join(", ")}`)}if(c.isCompatible())return this._features[n]={featureImplementation:c,enabled:!0,version:o,required:s},r?this._xrSessionManager.session&&!this._features[n].featureImplementation.attached&&this.attachFeature(n):this._features[n].featureImplementation.disableAutoAttach=!0,this._features[n].featureImplementation;if(s)throw new Error("required feature not compatible");return Ue.S0.Warn(`Feature ${n} not compatible with the current environment/browser and was not enabled.`),c}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 t=this._features[i],r=t.featureImplementation.xrNativeFeatureName;if(r&&(t.required?(e.requiredFeatures=e.requiredFeatures||[],-1===e.requiredFeatures.indexOf(r)&&e.requiredFeatures.push(r)):(e.optionalFeatures=e.optionalFeatures||[],-1===e.optionalFeatures.indexOf(r)&&e.optionalFeatures.push(r))),t.featureImplementation.getXRSessionInitExtension){const i=await t.featureImplementation.getXRSessionInitExtension();e={...e,...i}}}return e}}cr._AvailableFeatures={},cr._ConflictingFeatures={[hr.TELEPORTATION]:hr.MOVEMENT,[hr.MOVEMENT]:hr.TELEPORTATION},function(e){e[e.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",e[e.RADIAL_SIDE=1]="RADIAL_SIDE",e[e.ULNAR_SIDE=2]="ULNAR_SIDE",e[e.BELOW_WRIST=3]="BELOW_WRIST"}(sr||(sr={})),function(e){e[e.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",e[e.HAND_ROTATION=1]="HAND_ROTATION"}(nr||(nr={})),function(e){e[e.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",e[e.PALM_UP=1]="PALM_UP",e[e.GAZE_FOCUS=2]="GAZE_FOCUS",e[e.PALM_AND_GAZE=3]="PALM_AND_GAZE"}(or||(or={}));class ur{constructor(){this._sceneRenderObserver=null,this._zoneAxis={},this.handConstraintVisibility=3,this.palmUpStrictness=.95,this.gazeProximityRadius=.15,this.targetOffset=.1,this.targetZone=2,this.zoneOrientationMode=1,this.nodeOrientationMode=1,this.handedness="none",this.lerpTime=100,this._zoneAxis[0]=new W.Pq(0,1,0),this._zoneAxis[1]=new W.Pq(-1,0,0),this._zoneAxis[2]=new W.Pq(1,0,0),this._zoneAxis[3]=new W.Pq(0,-1,0)}get name(){return"HandConstraint"}enable(){this._node.setEnabled(!0)}disable(){this._node.setEnabled(!1)}_getHandPose(){if(!this._handTracking)return null;let e;if(e="none"===this.handedness?this._handTracking.getHandByHandedness("left")||this._handTracking.getHandByHandedness("right"):this._handTracking.getHandByHandedness(this.handedness),e){const t=e.getJointMesh("pinky-finger-metacarpal"),i=e.getJointMesh("middle-finger-metacarpal"),r=e.getJointMesh("wrist");if(r&&i&&t){const s={position:i.absolutePosition,quaternion:new W.PT,id:e.xrController.uniqueId},n=W.AA.Vector3[0],o=W.AA.Vector3[1],a=W.AA.Vector3[2];return n.copyFrom(i.absolutePosition).subtractInPlace(r.absolutePosition).normalize(),o.copyFrom(t.absolutePosition).subtractInPlace(i.absolutePosition).normalize(),W.Pq.CrossToRef(n,o,o),W.Pq.CrossToRef(o,n,a),W.PT.FromLookDirectionLHToRef(o,n,s.quaternion),s}}return null}init(){}attach(e){this._node=e,this._scene=e.getScene(),this._node.rotationQuaternion||(this._node.rotationQuaternion=W.PT.RotationYawPitchRoll(this._node.rotation.y,this._node.rotation.x,this._node.rotation.z));let t=Date.now();this._sceneRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{const e=this._getHandPose();if(this._node.reservedDataStore=this._node.reservedDataStore||{},this._node.reservedDataStore.nearInteraction=this._node.reservedDataStore.nearInteraction||{},this._node.reservedDataStore.nearInteraction.excludedControllerId=null,e){const i=W.AA.Vector3[0],r=this._scene.activeCamera;i.copyFrom(this._zoneAxis[this.targetZone]);const s=W.AA.Quaternion[0];if(r&&(0===this.zoneOrientationMode||0===this.nodeOrientationMode)){const t=W.AA.Vector3[1];t.copyFrom(r.position).subtractInPlace(e.position).normalize(),this._scene.useRightHandedSystem?W.PT.FromLookDirectionRHToRef(t,W.Pq.UpReadOnly,s):W.PT.FromLookDirectionLHToRef(t,W.Pq.UpReadOnly,s)}1===this.zoneOrientationMode?e.quaternion.toRotationMatrix(W.AA.Matrix[0]):s.toRotationMatrix(W.AA.Matrix[0]),W.Pq.TransformNormalToRef(i,W.AA.Matrix[0],i),i.scaleInPlace(this.targetOffset);const n=W.AA.Vector3[2],o=W.AA.Quaternion[1];n.copyFrom(e.position).addInPlace(i),1===this.nodeOrientationMode?o.copyFrom(e.quaternion):o.copyFrom(s);const a=Date.now()-t;W.Pq.SmoothToRef(this._node.position,n,a,this.lerpTime,this._node.position),W.PT.SmoothToRef(this._node.rotationQuaternion,o,a,this.lerpTime,this._node.rotationQuaternion),this._node.reservedDataStore.nearInteraction.excludedControllerId=e.id}this._setVisibility(e),t=Date.now()}))}_setVisibility(e){let t=!0,i=!0;const r=this._scene.activeCamera;if(r){const s=r.getForwardRay();if(2===this.handConstraintVisibility||3===this.handConstraintVisibility){let t;i=!1,this._eyeTracking&&(t=this._eyeTracking.getEyeGaze()),t=t||s;const r=W.AA.Vector3[0];e?e.position.subtractToRef(t.origin,r):this._node.getAbsolutePosition().subtractToRef(t.origin,r);const n=W.Pq.Dot(r,t.direction),o=n*n;n>0&&r.lengthSquared()-o2*this.palmUpStrictness-1&&(t=!0)}}this._node.setEnabled(t&&i)}detach(){this._scene.onBeforeRenderObservable.remove(this._sceneRenderObserver)}linkToXRExperience(e){const t=e.featuresManager?e.featuresManager:e;if(t){try{this._eyeTracking=t.getEnabledFeature(hr.EYE_TRACKING)}catch{}try{this._handTracking=t.getEnabledFeature(hr.HAND_TRACKING)}catch{Ue.S0.Error("Hand tracking must be enabled for the Hand Menu to work")}}else Ue.S0.Error("XR features manager must be available or provided directly for the Hand Menu to work")}}class dr{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=W.Pq.Zero(),this.poleTargetPosition=W.Pq.Zero(),this.poleTargetLocalOffset=W.Pq.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=W.PT.Identity(),this._bone1Mat=W.uq.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=W.Pq.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;const r=t.getParent();if(!r)return this._notEnoughInformation=!0,void Z.V.Error("BoneIKController: bone must have a parent for IK to work.");if(this._bone1=r,0===this._bone2.children.length&&!this._bone2.length)return this._notEnoughInformation=!0,void Z.V.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");this.mesh=e,t.getSkeleton().computeAbsoluteMatrices();const s=t.getPosition();if(t.getAbsoluteMatrix().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,s.x>s.y&&s.x>s.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length&&this._bone2.length){const e=this._bone1.getScale(),t=this._bone2.getScale();this._bone1Length=this._bone1.length*e.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y}else if(this._bone2.children[0]){e.computeWorldMatrix(!0);const t=this._bone2.children[0].getAbsolutePosition(e),i=this._bone2.getAbsolutePosition(e),r=this._bone1.getAbsolutePosition(e);this._bone2Length=W.Pq.Distance(t,i),this._bone1Length=W.Pq.Distance(i,r)}else{e.computeWorldMatrix(!0);const t=this._bone2.getScale();this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y;const i=this._bone2.getAbsolutePosition(e),r=this._bone1.getAbsolutePosition(e);this._bone1Length=W.Pq.Distance(i,r)}this._bone1.getRotationMatrixToRef(1,e,this._bone1Mat),this.maxAngle=Math.PI,i&&(i.targetMesh&&(this.targetMesh=i.targetMesh,this.targetMesh.computeWorldMatrix(!0)),i.poleTargetMesh?(this.poleTargetMesh=i.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):i.poleTargetBone?this.poleTargetBone=i.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),i.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(i.poleTargetLocalOffset),i.poleAngle&&(this.poleAngle=i.poleAngle),i.bendAxis&&this._bendAxis.copyFrom(i.bendAxis),i.maxAngle&&(this.maxAngle=i.maxAngle),i.slerpAmount&&(this.slerpAmount=i.slerpAmount))}_setMaxAngle(e){e<0&&(e=0),(e>Math.PI||null==e)&&(e=Math.PI),this._maxAngle=e;const t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))}update(){if(this._notEnoughInformation)return;const e=this.targetPosition,t=this.poleTargetPosition,i=dr._TmpMats[0],r=dr._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&W.Pq.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);const s=dr._TmpVecs[0],n=dr._TmpVecs[1],o=dr._TmpVecs[2],a=dr._TmpVecs[3],l=dr._TmpVecs[4],h=dr._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,s),t.subtractToRef(s,l),0==l.x&&0==l.y&&0==l.z?l.y=1:l.normalize(),e.subtractToRef(s,a),a.normalize(),W.Pq.CrossToRef(a,l,n),n.normalize(),W.Pq.CrossToRef(a,n,o),o.normalize(),W.uq.FromXYZAxesToRef(o,a,n,i);const c=this._bone1Length,u=this._bone2Length;let d=W.Pq.Distance(s,e);this._maxReach>0&&(d=Math.min(this._maxReach,d));let f=(u*u+d*d-c*c)/(2*u*d),p=(d*d+c*c-u*u)/(2*d*c);f>1&&(f=1),p>1&&(p=1),f<-1&&(f=-1),p<-1&&(p=-1);const _=Math.acos(f),m=Math.acos(p);let g=-_-m;if(this._rightHandedSystem)W.uq.RotationYawPitchRollToRef(0,0,this._adjustRoll,r),r.multiplyToRef(i,i),W.uq.RotationAxisToRef(this._bendAxis,m,r),r.multiplyToRef(i,i);else{const e=dr._TmpVecs[5];e.copyFrom(this._bendAxis),e.x*=-1,W.uq.RotationAxisToRef(e,-m,r),r.multiplyToRef(i,i)}this.poleAngle&&(W.uq.RotationAxisToRef(a,this.poleAngle,r),i.multiplyToRef(r,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||W.PT.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),W.PT.FromRotationMatrixToRef(i,h),W.PT.SlerpToRef(this._bone1Quat,h,this.slerpAmount,this._bone1Quat),g=this._bone2Ang*(1-this.slerpAmount)+g*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,1,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,1,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,g,0),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=g}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new W.PT),e.getRotationQuaternionToRef(0,null,e._linkedTransformNode.rotationQuaternion))}}dr._TmpVecs=[W.Pq.Zero(),W.Pq.Zero(),W.Pq.Zero(),W.Pq.Zero(),W.Pq.Zero(),W.Pq.Zero()],dr._TmpQuat=W.PT.Identity(),dr._TmpMats=[W.uq.Identity(),W.uq.Identity()];class fr{get minYaw(){return this._minYaw}set minYaw(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get maxYaw(){return this._maxYaw}set maxYaw(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch=e,this._minPitchTan=Math.tan(e)}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)}constructor(e,t,i,r){if(this.upAxis=W.Pq.Up(),this.upAxisSpace=0,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=W.PT.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=W.Pq.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,r){if(r.adjustYaw&&(this.adjustYaw=r.adjustYaw),r.adjustPitch&&(this.adjustPitch=r.adjustPitch),r.adjustRoll&&(this.adjustRoll=r.adjustRoll),null!=r.maxYaw?this.maxYaw=r.maxYaw:this.maxYaw=Math.PI,null!=r.minYaw?this.minYaw=r.minYaw:this.minYaw=-Math.PI,null!=r.maxPitch?this.maxPitch=r.maxPitch:this.maxPitch=Math.PI,null!=r.minPitch?this.minPitch=r.minPitch:this.minPitch=-Math.PI,null!=r.slerpAmount&&(this.slerpAmount=r.slerpAmount),null!=r.upAxis&&(this.upAxis=r.upAxis),null!=r.upAxisSpace&&(this.upAxisSpace=r.upAxisSpace),null!=r.yawAxis||null!=r.pitchAxis){let e=Mt._0.Y,t=Mt._0.X;null!=r.yawAxis&&(e=r.yawAxis.clone(),e.normalize()),null!=r.pitchAxis&&(t=r.pitchAxis.clone(),t.normalize());const i=W.Pq.Cross(t,e);this._transformYawPitch=W.uq.Identity(),W.uq.FromXYZAxesToRef(t,e,i,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}void 0!==r.useAbsoluteValueForYaw&&(this.useAbsoluteValueForYaw=r.useAbsoluteValueForYaw)}t.getParent()||2!=this.upAxisSpace||(this.upAxisSpace=0)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped)return void(this._firstFrameSkipped=!0);const e=this.bone,t=fr._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target;const r=fr._TmpMats[0],s=fr._TmpMats[1],n=this.mesh,o=e.getParent(),a=fr._TmpVecs[1];a.copyFrom(this.upAxis),2==this.upAxisSpace&&o?(this._transformYawPitch&&W.Pq.TransformCoordinatesToRef(a,this._transformYawPitchInv,a),o.getDirectionToRef(a,this.mesh,a)):0==this.upAxisSpace&&(n.getDirectionToRef(a,a),1==n.scaling.x&&1==n.scaling.y&&1==n.scaling.z||a.normalize());let l=!1,h=!1;if(this._maxYaw==Math.PI&&this._minYaw==-Math.PI||(l=!0),this._maxPitch==Math.PI&&this._minPitch==-Math.PI||(h=!0),l||h){const e=fr._TmpMats[2],r=fr._TmpMats[3];if(2==this.upAxisSpace&&1==a.y&&o)o.getRotationMatrixToRef(1,this.mesh,e);else if(0!=this.upAxisSpace||1!=a.y||o){let t=fr._TmpVecs[2];t.copyFrom(this._fowardAxis),this._transformYawPitch&&W.Pq.TransformCoordinatesToRef(t,this._transformYawPitchInv,t),o?o.getDirectionToRef(t,this.mesh,t):n.getDirectionToRef(t,t);const i=W.Pq.Cross(a,t);i.normalize(),t=W.Pq.Cross(i,a),W.uq.FromXYZAxesToRef(i,a,t,e)}else e.copyFrom(n.getWorldMatrix());e.invertToRef(r);let s=null;if(h){const n=fr._TmpVecs[3];i.subtractToRef(t,n),W.Pq.TransformCoordinatesToRef(n,r,n),s=Math.sqrt(n.x*n.x+n.z*n.z);const o=Math.atan2(n.y,s);let a=o;o>this._maxPitch?(n.y=this._maxPitchTan*s,a=this._maxPitch):othis._maxYaw||aMath.PI?this._isAngleBetween(o,this._maxYaw,this._midYawConstraint)?(n.z=this._maxYawCos*s,n.x=this._maxYawSin*s,l=this._maxYaw):this._isAngleBetween(o,this._midYawConstraint,this._minYaw)&&(n.z=this._minYawCos*s,n.x=this._minYawSin*s,l=this._minYaw):a>this._maxYaw?(n.z=this._maxYawCos*s,n.x=this._maxYawSin*s,o<0&&this.useAbsoluteValueForYaw&&(n.x*=-1),l=this._maxYaw):aMath.PI){const e=fr._TmpVecs[8];e.copyFrom(Mt._0.Z),this._transformYawPitch&&W.Pq.TransformCoordinatesToRef(e,this._transformYawPitchInv,e);const t=fr._TmpMats[4];this._boneQuat.toRotationMatrix(t),this.mesh.getWorldMatrix().multiplyToRef(t,t),W.Pq.TransformCoordinatesToRef(e,t,e),W.Pq.TransformCoordinatesToRef(e,r,e);const i=Math.atan2(e.x,e.z);if(this._getAngleBetween(i,o)>this._getAngleBetween(i,this._midYawConstraint)){null==s&&(s=Math.sqrt(n.x*n.x+n.z*n.z));const e=this._getAngleBetween(i,this._maxYaw);this._getAngleBetween(i,this._minYaw)Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i}_getAngleBetween(e,t){let i=0;return i=(e=(e%=2*Math.PI)<0?e+2*Math.PI:e)<(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)?t-e:e-t,i>Math.PI&&(i=2*Math.PI-i),i}_isAngleBetween(e,t,i){if(e=(e%=2*Math.PI)<0?e+2*Math.PI:e,(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)<(i=(i%=2*Math.PI)<0?i+2*Math.PI:i)){if(e>t&&ei&&e{const e=new Uint8Array(4);return!!((new Uint32Array(e.buffer)[0]=1)&e[0])})();Object.defineProperty(st.R.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0}),Object.defineProperty(st.R.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0}),Object.defineProperty(st.R.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0}),st.R.prototype._rebuild=function(){this._buffer?._rebuild(),this._alignedBuffer?._rebuild()},st.R.prototype.dispose=function(){this._ownsBuffer&&this._buffer.dispose(),this._alignedBuffer?.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0},st.R.prototype.getWrapperBuffer=function(){return this._alignedBuffer||this._buffer},st.R.prototype._alignBuffer=function(){const e=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideAndOffsetMultiple4Bytes||this.byteStride%4==0&&this.byteOffset%4==0||!e)return;const t=st.R.GetTypeByteLength(this.type),i=this.byteStride+3&-4,r=i/t,s=this._maxVerticesCount,n=s*i/t;let o,a;if(Array.isArray(e)){const t=new Float32Array(e);o=new DataView(t.buffer,t.byteOffset,t.byteLength)}else o=e instanceof ArrayBuffer?new DataView(e,0,e.byteLength):new DataView(e.buffer,e.byteOffset,e.byteLength);a=this.type===st.R.BYTE?new Int8Array(n):this.type===st.R.UNSIGNED_BYTE?new Uint8Array(n):this.type===st.R.SHORT?new Int16Array(n):this.type===st.R.UNSIGNED_SHORT?new Uint16Array(n):this.type===st.R.INT?new Int32Array(n):this.type===st.R.UNSIGNED_INT?new Uint32Array(n):new Float32Array(n);const l=this.getSize();let h=this.byteOffset;for(let e=0;e{if(t.type!==yi.Zp.POINTERWHEEL)return;const i=t.event,r=i.deltaMode===gr.s.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*r*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*r*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*r*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,yi.Zp.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"}}(0,je.Cg)([(0,$e.lK)()],vr.prototype,"wheelPrecisionX",void 0),(0,je.Cg)([(0,$e.lK)()],vr.prototype,"wheelPrecisionY",void 0),(0,je.Cg)([(0,$e.lK)()],vr.prototype,"wheelPrecisionZ",void 0);class xr{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=Ue.S0.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let r=0,s=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=n=>{const o=n.event,a="touch"===o.pointerType;if(n.type!==yi.Zp.POINTERMOVE&&-1===this.buttons.indexOf(o.button))return;const l=o.target;if(this._altKey=o.altKey,this._ctrlKey=o.ctrlKey,this._metaKey=o.metaKey,this._shiftKey=o.shiftKey,this._buttonsPressed=o.buttons,t.isPointerLock){const e=o.movementX,t=o.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else{if(n.type!==yi.Zp.POINTERDOWN&&n.type!==yi.Zp.POINTERDOUBLETAP&&a&&this._pointA?.pointerId!==o.pointerId&&this._pointB?.pointerId!==o.pointerId)return;if(n.type!==yi.Zp.POINTERDOWN||-1!==this._currentActiveButton&&!a)if(n.type===yi.Zp.POINTERDOUBLETAP)this.onDoubleTap(o.pointerType);else if(n.type!==yi.Zp.POINTERUP||this._currentActiveButton!==o.button&&!a){if(n.type===yi.Zp.POINTERMOVE)if(e||o.preventDefault(),this._pointA&&null===this._pointB){const e=o.clientX-this._pointA.x,t=o.clientY-this._pointA.y;this._pointA.x=o.clientX,this._pointA.y=o.clientY,this.onTouch(this._pointA,e,t)}else if(this._pointA&&this._pointB){const e=this._pointA.pointerId===o.pointerId?this._pointA:this._pointB;e.x=o.clientX,e.y=o.clientY;const t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,a=t*t+i*i,l={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:o.pointerId,type:n.type};this.onMultiTouch(this._pointA,this._pointB,r,a,s,l),s=l,r=a}}else{try{l?.releasePointerCapture(o.pointerId)}catch(e){}a||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==o.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==o.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==r||s)&&(this.onMultiTouch(this._pointA,this._pointB,r,0,s,null),r=0,s=null),this._currentActiveButton=-1,this.onButtonUp(o),e||o.preventDefault()}else{try{l?.setPointerCapture(o.pointerId)}catch(e){}if(null===this._pointA)this._pointA={x:o.clientX,y:o.clientY,pointerId:o.pointerId,type:o.pointerType};else{if(null!==this._pointB)return;this._pointB={x:o.clientX,y:o.clientY,pointerId:o.pointerId,type:o.pointerType}}-1!==this._currentActiveButton||a||(this._currentActiveButton=o.button),this.onButtonDown(o),e||(o.preventDefault(),i&&i.focus())}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,yi.Zp.POINTERDOWN|yi.Zp.POINTERUP|yi.Zp.POINTERMOVE|yi.Zp.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,r=0,s=null,this.onLostFocus()},this._contextMenuBind=e=>this.onContextMenu(e),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const n=this.camera.getScene().getEngine().getHostWindow();n&&Ue.S0.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&Ue.S0.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,r,s,n){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}(0,je.Cg)([(0,$e.lK)()],xr.prototype,"buttons",void 0);var br={};class Sr{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();this.attached[t]?Z.V.Warn("camera input of type "+t+" already exists on camera"):(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)return i.detachControl(),i.camera=null,delete this.attached[t],void this.rebuildInputCheck()}}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=!rt.ForceAttachControlToAlwaysPreventDefault&&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 e in this.attached){const i=this.attached[e],r=it.p.Serialize(i);t[i.getClassName()]=r}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const e in t){const i=br[e];if(i){const r=t[e],s=it.p.Parse((()=>new i),r,null);this.add(s)}}}else for(const t in this.attached){const i=br[this.attached[t].getClassName()];if(i){const r=it.p.Parse((()=>new i),e,null);this.remove(this.attached[t]),this.add(r)}}}}class Tr{constructor(e,t){this.x=e,this.y=t}}class Cr{get isConnected(){return this._isConnected}constructor(e,t,i,r=0,s=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=Cr.GAMEPAD,this._leftStickAxisX=r,this._leftStickAxisY=s,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(){}}Cr.GAMEPAD=0,Cr.GENERIC=1,Cr.XBOX=2,Cr.POSE_ENABLED=3,Cr.DUALSHOCK=4;class yr extends Cr{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new z.cP,this.onButtonUpObservable=new z.cP,this.type=Cr.GENERIC,this._buttons=new Array(i.buttons.length)}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}update(){super.update();for(let e=0;e{e.type!==Cr.POSE_ENABLED&&(this.gamepad&&e.type!==Cr.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType(Cr.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(0!=t.x){const i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){const i=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=i&&Math.abs(i)>.005&&(e.inertialBetaOffset+=i)}}const i=this.gamepad.leftStick;if(i&&0!=i.y){const e=i.y/this.gamepadMoveSensibility;0!=e&&Math.abs(e)>.005&&(this.camera.inertialRadiusOffset-=e)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}(0,je.Cg)([(0,$e.lK)()],Er.prototype,"gamepadRotationSensibility",void 0),(0,je.Cg)([(0,$e.lK)()],Er.prototype,"gamepadMoveSensibility",void 0),br.ArcRotateCameraGamepadInput=Er;var Pr,Ar=i(80109);class Rr{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=Ue.S0.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===Ar.TB.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(-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.keysReset.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-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.keysReset.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,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?r/(1+this.wheelDeltaPercentage):r*(1+this.wheelDeltaPercentage),i}attachControl(e){e=Ue.S0.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==yi.Zp.POINTERWHEEL)return;const i=t.event;let r=0;const s=i.deltaMode===gr.s.DOM_DELTA_LINE?40:1,n=-i.deltaY*s;if(this.customComputeDeltaFromMouseWheel)r=this.customComputeDeltaFromMouseWheel(n,this,i);else if(this.wheelDeltaPercentage){if(r=this._computeDeltaFromMouseWheelLegacyEvent(n,this.camera.radius),r>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+r;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=(0,ar.Clamp)(e,0,Number.MAX_VALUE),r=this._computeDeltaFromMouseWheelLegacyEvent(n,e)}}else r=n/(40*this.wheelPrecision);r&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(r)):this.camera.inertialRadiusOffset+=r),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,yi.Zp.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=Ft.Z.FromPositionAndNormal(e.target,t)}_getPosition(){const e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,W.uq.Identity(),e,!1);0===e.targetScreenOffset.x&&0===e.targetScreenOffset.y||(this._viewOffset.set(e.targetScreenOffset.x,e.targetScreenOffset.y,0),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),this._globalOffset=W.Pq.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let r=0;return this._hitPlane&&(r=i.intersectsPlane(this._hitPlane)??0),i.origin.addInPlace(i.direction.scaleInPlace(r))}_zoomToMouse(e){const t=this.camera,i=1-t.inertia;if(t.lowerRadiusLimit){const r=t.lowerRadiusLimit??0;t.radius-(t.inertialRadiusOffset+e)/ir&&(e=(t.radius-r)*i-t.inertialRadiusOffset)}const r=e/i/t.radius,s=this._getPosition(),n=W.AA.Vector3[6];s.subtractToRef(t.target,n),n.scaleInPlace(r),n.scaleInPlace(i),this._inertialPanning.addInPlace(n),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,r),this._isPinching=!0):this._computeMultiTouchPanning(s,n)):this.multiTouchPanning?this._computeMultiTouchPanning(s,n):this.pinchZoom&&this._computePinchZoom(i,r))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}Mr.MinimumRadiusForPinch=.001,(0,je.Cg)([(0,$e.lK)()],Mr.prototype,"buttons",void 0),(0,je.Cg)([(0,$e.lK)()],Mr.prototype,"angularSensibilityX",void 0),(0,je.Cg)([(0,$e.lK)()],Mr.prototype,"angularSensibilityY",void 0),(0,je.Cg)([(0,$e.lK)()],Mr.prototype,"pinchPrecision",void 0),(0,je.Cg)([(0,$e.lK)()],Mr.prototype,"pinchDeltaPercentage",void 0),(0,je.Cg)([(0,$e.lK)()],Mr.prototype,"useNaturalPinchZoom",void 0),(0,je.Cg)([(0,$e.lK)()],Mr.prototype,"pinchZoom",void 0),(0,je.Cg)([(0,$e.lK)()],Mr.prototype,"panningSensibility",void 0),(0,je.Cg)([(0,$e.lK)()],Mr.prototype,"multiTouchPanning",void 0),(0,je.Cg)([(0,$e.lK)()],Mr.prototype,"multiTouchPanAndZoom",void 0),br.ArcRotateCameraPointersInput=Mr;class Or extends Sr{constructor(e){super(e)}addMouseWheel(){return this.add(new Ir),this}addPointers(){return this.add(new Mr),this}addKeyboard(){return this.add(new Rr),this}}Or.prototype.addVRDeviceOrientation=function(){return this.add(new Dr),this};class Dr{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=Ue.S0.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);const t=this.camera.getScene().getEngine().getHostWindow();t&&("undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t.addEventListener("deviceorientation",this._deviceOrientationHandler):Ue.S0.Warn("Permission not granted.")})).catch((e=>{Ue.S0.Error(e)})):t.addEventListener("deviceorientation",this._deviceOrientationHandler))}_onOrientationEvent(e){null!==e.alpha&&(this._alpha=(0|+e.alpha)*this.alphaCorrection),null!==e.gamma&&(this._gamma=(0|+e.gamma)*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"}}br.ArcRotateCameraVRDeviceOrientationInput=Dr;class wr{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=Ue.S0.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===Ar.TB.KEYDOWN)-1===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)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-1!==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)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,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(e)}),yi.Zp.POINTERDOWN|yi.Zp.POINTERUP|yi.Zp.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,i=this.camera.getEngine();if(!this.touchEnabled&&"touch"===t.pointerType)return;if(e.type!==yi.Zp.POINTERMOVE&&-1===this.buttons.indexOf(t.button))return;const r=t.target;if(e.type===yi.Zp.POINTERDOWN){try{r?.setPointerCapture(t.pointerId)}catch(t){}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||t.preventDefault(),i.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===yi.Zp.POINTERUP){try{r?.releasePointerCapture(t.pointerId)}catch(t){}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===yi.Zp.POINTERMOVE){if(!this._previousPosition)return void(i.isPointerLock&&this._onMouseMove(e.event));const r=t.clientX-this._previousPosition.x,s=t.clientY-this._previousPosition.y;this._rotateCamera(r,s),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){if(!this.camera.getEngine().isPointerLock)return;const t=e.movementX,i=e.movementY;this._rotateCamera(t,i),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){const i=this.camera,r=(e*=i._calculateHandednessMultiplier())/this.angularSensibility,s=t/this.angularSensibility,n=W.PT.RotationYawPitchRoll(i.rotation.y,i.rotation.x,i.rotation.z);let o;if(this.buttonsPitch.some((e=>e===this.activeButton))&&(o=W.PT.RotationAxis(Mt._0.X,s),n.multiplyInPlace(o)),this.buttonsYaw.some((e=>e===this.activeButton))){o=W.PT.RotationAxis(Mt._0.Y,r),n.multiplyInPlace(o);const e=i.bankedTurnLimit+i._trackRoll;if(i.bankedTurn&&-ee===this.activeButton))&&(o=W.PT.RotationAxis(Mt._0.Z,-r),i._trackRoll-=r,n.multiplyInPlace(o)),n.toEulerAnglesToRef(i.rotation)}}(0,je.Cg)([(0,$e.lK)()],Nr.prototype,"buttons",void 0),(0,je.Cg)([(0,$e.lK)()],Nr.prototype,"angularSensibility",void 0),br.FlyCameraMouseInput=Nr;class Fr{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=Ue.S0.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===Ar.TB.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,this._shiftPressed=i.shiftKey,(-1!==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)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-1!==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)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,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=>{-1!==this.keysHeightOffsetIncr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset+=this.heightSensibility:-1!==this.keysHeightOffsetDecr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset-=this.heightSensibility:-1!==this.keysRotationOffsetIncr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset+=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRotationOffsetDecr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset-=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRadiusIncr.indexOf(e)&&this._modifierRadius()?this.camera.radius+=this.radiusSensibility:-1!==this.keysRadiusDecr.indexOf(e)&&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}}(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysHeightOffsetIncr",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysHeightOffsetDecr",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysHeightOffsetModifierAlt",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysHeightOffsetModifierCtrl",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysHeightOffsetModifierShift",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysRotationOffsetIncr",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysRotationOffsetDecr",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysRotationOffsetModifierAlt",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysRotationOffsetModifierCtrl",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysRotationOffsetModifierShift",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysRadiusIncr",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysRadiusDecr",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysRadiusModifierAlt",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysRadiusModifierCtrl",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysRadiusModifierShift",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"heightSensibility",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"rotationSensibility",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"radiusSensibility",void 0),br.FollowCameraKeyboardMoveInput=Fr;class Lr{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=Ue.S0.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==yi.Zp.POINTERWHEEL)return;const i=t.event;let r=0;const s=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(+this.axisControlRadius+ +this.axisControlHeight+ +this.axisControlRotation&&Z.V.Warn("wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?r=.01*s*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?r=.01*s*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(r=.01*s*this.wheelDeltaPercentage*this.camera.rotationOffset)):r=s*this.wheelPrecision,r&&(this.axisControlRadius?this.camera.radius+=r:this.axisControlHeight?this.camera.heightOffset-=r:this.axisControlRotation&&(this.camera.rotationOffset-=r)),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,yi.Zp.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}(0,je.Cg)([(0,$e.lK)()],Lr.prototype,"axisControlRadius",void 0),(0,je.Cg)([(0,$e.lK)()],Lr.prototype,"axisControlHeight",void 0),(0,je.Cg)([(0,$e.lK)()],Lr.prototype,"axisControlRotation",void 0),(0,je.Cg)([(0,$e.lK)()],Lr.prototype,"wheelPrecision",void 0),(0,je.Cg)([(0,$e.lK)()],Lr.prototype,"wheelDeltaPercentage",void 0),br.FollowCameraMouseWheelInput=Lr;class Br extends xr{constructor(){super(...arguments),this.angularSensibilityX=1,this.angularSensibilityY=1,this.pinchPrecision=1e4,this.pinchDeltaPercentage=0,this.axisXControlRadius=!1,this.axisXControlHeight=!1,this.axisXControlRotation=!0,this.axisYControlRadius=!1,this.axisYControlHeight=!0,this.axisYControlRotation=!1,this.axisPinchControlRadius=!0,this.axisPinchControlHeight=!1,this.axisPinchControlRotation=!1,this.warningEnable=!0,this._warningCounter=0}getClassName(){return"FollowCameraPointersInput"}onTouch(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)}onMultiTouch(e,t,i,r,s,n){if(0===i&&null===s)return;if(0===r&&null===n)return;let o=(r-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(o*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=o*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=o*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=o*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=o),this.axisPinchControlHeight&&(this.camera.heightOffset+=o),this.axisPinchControlRadius&&(this.camera.radius-=o))}_warning(){if(!this.warningEnable||this._warningCounter++%100!=0)return;const e="It probably only makes sense to control ONE camera property with each pointer axis. Set 'warningEnable = false' if you are sure. Currently enabled: ";+this.axisXControlRotation+ +this.axisXControlHeight+ +this.axisXControlRadius<=1&&Z.V.Warn(e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),+this.axisYControlRotation+ +this.axisYControlHeight+ +this.axisYControlRadius<=1&&Z.V.Warn(e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),+this.axisPinchControlRotation+ +this.axisPinchControlHeight+ +this.axisPinchControlRadius<=1&&Z.V.Warn(e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}(0,je.Cg)([(0,$e.lK)()],Br.prototype,"angularSensibilityX",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"angularSensibilityY",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"pinchPrecision",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"pinchDeltaPercentage",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"axisXControlRadius",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"axisXControlHeight",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"axisXControlRotation",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"axisYControlRadius",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"axisYControlHeight",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"axisYControlRotation",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"axisPinchControlRadius",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"axisPinchControlHeight",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"axisPinchControlRotation",void 0),br.FollowCameraPointersInput=Br;class Vr{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=Ue.S0.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===Ar.TB.KEYDOWN)-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.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)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-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.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)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.preventDefault()}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t{const s=r.event,n="touch"===s.pointerType;if(!this.touchEnabled&&n)return;if(r.type!==yi.Zp.POINTERMOVE&&-1===this.buttons.indexOf(s.button))return;const o=s.target;if(r.type===yi.Zp.POINTERDOWN){if(n&&-1!==this._activePointerId||!n&&-1!==this._currentActiveButton)return;this._activePointerId=s.pointerId;try{o?.setPointerCapture(s.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=s.button),this._previousPosition={x:s.clientX,y:s.clientY},e||(s.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(r.event)}else if(r.type===yi.Zp.POINTERUP){if(n&&this._activePointerId!==s.pointerId||!n&&this._currentActiveButton!==s.button)return;try{o?.releasePointerCapture(s.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||s.preventDefault(),this._activePointerId=-1}else if(r.type===yi.Zp.POINTERMOVE&&(this._activePointerId===s.pointerId||!n))if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(r.event);else if(this._previousPosition){const t=this.camera._calculateHandednessMultiplier(),i=(s.clientX-this._previousPosition.x)*t,r=s.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=i/this.angularSensibility,this.camera.cameraRotation.x+=r/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:i,offsetY:r}),this._previousPosition={x:s.clientX,y:s.clientY},e||s.preventDefault()}}),this._onMouseMove=i=>{if(!t.isPointerLock)return;const r=this.camera._calculateHandednessMultiplier(),s=i.movementX*r;this.camera.cameraRotation.y+=s/this.angularSensibility;const n=i.movementY;this.camera.cameraRotation.x+=n/this.angularSensibility,this._previousPosition=null,e||i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,yi.Zp.POINTERDOWN|yi.Zp.POINTERUP|yi.Zp.POINTERMOVE),i&&(this._contextMenuBind=e=>this.onContextMenu(e),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 e=this.camera.getEngine().getInputElement();e&&e.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"}}(0,je.Cg)([(0,$e.lK)()],kr.prototype,"buttons",void 0),(0,je.Cg)([(0,$e.lK)()],kr.prototype,"angularSensibility",void 0),br.FreeCameraMouseInput=kr,function(e){e[e.MoveRelative=0]="MoveRelative",e[e.RotateRelative=1]="RotateRelative",e[e.MoveScene=2]="MoveScene"}(Pr||(Pr={}));class Ur extends vr{constructor(){super(...arguments),this._moveRelative=W.Pq.Zero(),this._rotateRelative=W.Pq.Zero(),this._moveScene=W.Pq.Zero(),this._wheelXAction=Pr.MoveRelative,this._wheelXActionCoordinate=0,this._wheelYAction=Pr.MoveRelative,this._wheelYActionCoordinate=2,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){null===e&&this._wheelXAction!==Pr.MoveRelative||(this._wheelXAction=Pr.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==Pr.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){null===e&&this._wheelYAction!==Pr.MoveRelative||(this._wheelYAction=Pr.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==Pr.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){null===e&&this._wheelZAction!==Pr.MoveRelative||(this._wheelZAction=Pr.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==Pr.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){null===e&&this._wheelXAction!==Pr.RotateRelative||(this._wheelXAction=Pr.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==Pr.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){null===e&&this._wheelYAction!==Pr.RotateRelative||(this._wheelYAction=Pr.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==Pr.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){null===e&&this._wheelZAction!==Pr.RotateRelative||(this._wheelZAction=Pr.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==Pr.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){null===e&&this._wheelXAction!==Pr.MoveScene||(this._wheelXAction=Pr.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==Pr.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){null===e&&this._wheelYAction!==Pr.MoveScene||(this._wheelYAction=Pr.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==Pr.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){null===e&&this._wheelZAction!==Pr.MoveScene||(this._wheelZAction=Pr.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==Pr.MoveScene?null:this._wheelZActionCoordinate}checkInputs(){if(0===this._wheelDeltaX&&0===this._wheelDeltaY&&0==this._wheelDeltaZ)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=W.uq.Zero();this.camera.getViewMatrix().invertToRef(e);const t=W.Pq.Zero();W.Pq.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(0===e)return;if(null===t||null===i)return;let r=null;switch(t){case Pr.MoveRelative:r=this._moveRelative;break;case Pr.RotateRelative:r=this._rotateRelative;break;case Pr.MoveScene:r=this._moveScene}switch(i){case 0:r.set(e,0,0);break;case 1:r.set(0,e,0);break;case 2:r.set(0,0,e)}}}(0,je.Cg)([(0,$e.lK)()],Ur.prototype,"wheelXMoveRelative",null),(0,je.Cg)([(0,$e.lK)()],Ur.prototype,"wheelYMoveRelative",null),(0,je.Cg)([(0,$e.lK)()],Ur.prototype,"wheelZMoveRelative",null),(0,je.Cg)([(0,$e.lK)()],Ur.prototype,"wheelXRotateRelative",null),(0,je.Cg)([(0,$e.lK)()],Ur.prototype,"wheelYRotateRelative",null),(0,je.Cg)([(0,$e.lK)()],Ur.prototype,"wheelZRotateRelative",null),(0,je.Cg)([(0,$e.lK)()],Ur.prototype,"wheelXMoveScene",null),(0,je.Cg)([(0,$e.lK)()],Ur.prototype,"wheelYMoveScene",null),(0,je.Cg)([(0,$e.lK)()],Ur.prototype,"wheelZMoveScene",null),br.FreeCameraMouseWheelInput=Ur;class Gr{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=Ue.S0.IsSafari()}attachControl(e){e=Ue.S0.BackCompatCameraNoPreventDefault(arguments);let t=null;if(void 0===this._pointerInput&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{const r=i.event,s="mouse"===r.pointerType||this._isSafari&&void 0===r.pointerType;if(this.allowMouse||!s)if(i.type===yi.Zp.POINTERDOWN){if(e||r.preventDefault(),this._pointerPressed.push(r.pointerId),1!==this._pointerPressed.length)return;t={x:r.clientX,y:r.clientY}}else if(i.type===yi.Zp.POINTERUP){e||r.preventDefault();const i=this._pointerPressed.indexOf(r.pointerId);if(-1===i)return;if(this._pointerPressed.splice(i,1),0!=i)return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===yi.Zp.POINTERMOVE){if(e||r.preventDefault(),!t)return;if(0!=this._pointerPressed.indexOf(r.pointerId))return;this._offsetX=r.clientX-t.x,this._offsetY=-(r.clientY-t.y)}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,yi.Zp.POINTERDOWN|yi.Zp.POINTERUP|yi.Zp.POINTERMOVE),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null}this._pointerPressed.length=0,this._offsetX=null,this._offsetY=null}}checkInputs(){if(null===this._offsetX||null===this._offsetY)return;if(0===this._offsetX&&0===this._offsetY)return;const e=this.camera,t=e._calculateHandednessMultiplier();if(e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility,this.singleFingerRotate&&1===this._pointerPressed.length||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{const t=e._computeLocalCameraSpeed(),i=new W.Pq(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);W.uq.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(W.Pq.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}(0,je.Cg)([(0,$e.lK)()],Gr.prototype,"touchAngularSensibility",void 0),(0,je.Cg)([(0,$e.lK)()],Gr.prototype,"touchMoveSensibility",void 0),br.FreeCameraTouchInput=Gr;class zr extends Sr{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new Vr),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new kr(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new Ur,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new Gr),this}clear(){super.clear(),this._mouseInput=null}}zr.prototype.addDeviceOrientation=function(e){return this._deviceOrientationInput||(this._deviceOrientationInput=new Wr,e&&(this._deviceOrientationInput.smoothFactor=e),this.add(this._deviceOrientationInput)),this};class Wr{static WaitForOrientationChangeAsync(e){return new Promise(((t,i)=>{let r=!1;const s=()=>{window.removeEventListener("deviceorientation",s),r=!0,t()};e&&setTimeout((()=>{r||(window.removeEventListener("deviceorientation",s),i("WaitForOrientationChangeAsync timed out"))}),e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"==e?window.addEventListener("deviceorientation",s):Ue.S0.Warn("Permission not granted.")})).catch((e=>{Ue.S0.Error(e)})):window.addEventListener("deviceorientation",s)}))}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new W.PT,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new z.cP,this._orientationChanged=()=>{this._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-Ue.S0.ToRadians(this._screenOrientationAngle/2),this._screenQuaternion.copyFromFloats(0,Math.sin(this._screenOrientationAngle),0,Math.cos(this._screenOrientationAngle))},this._deviceOrientation=e=>{this.smoothFactor?(this._alpha=null!==e.alpha?Ue.S0.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=null!==e.beta?Ue.S0.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=null!==e.gamma?Ue.S0.SmoothAngleChange(this._gamma,e.gamma,this.smoothFactor):0):(this._alpha=null!==e.alpha?e.alpha:0,this._beta=null!==e.beta?e.beta:0,this._gamma=null!==e.gamma?e.gamma:0),null!==e.alpha&&this._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTransform=new W.PT(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}get camera(){return this._camera}set camera(e){this._camera=e,null==this._camera||this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new W.PT),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()};"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t():Ue.S0.Warn("Permission not granted.")})).catch((e=>{Ue.S0.Error(e)})):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(W.PT.RotationYawPitchRollToRef(Ue.S0.ToRadians(this._alpha),Ue.S0.ToRadians(this._beta),-Ue.S0.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTransform),this._camera.getScene().useRightHandedSystem?this._camera.rotationQuaternion.y*=-1:this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)}getClassName(){return"FreeCameraDeviceOrientationInput"}getSimpleName(){return"deviceOrientation"}}br.FreeCameraDeviceOrientationInput=Wr;class Hr{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=W.uq.Identity(),this._deltaTransform=W.Pq.Zero(),this._vector3=W.Pq.Zero(),this._vector2=W.I9.Zero()}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){const e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add((e=>{e.type!==Cr.POSE_ENABLED&&(this.gamepad&&e.type!==Cr.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType(Cr.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;0!==this.gamepadMoveSensibility&&(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&&0!==this.gamepadAngularSensibility?(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):W.uq.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);const r=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*r,0,-t.y*r),W.Pq.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"}}(0,je.Cg)([(0,$e.lK)()],Hr.prototype,"gamepadAngularSensibility",void 0),(0,je.Cg)([(0,$e.lK)()],Hr.prototype,"gamepadMoveSensibility",void 0),br.FreeCameraGamepadInput=Hr;var Xr,qr,Yr,Kr,jr,$r=i(47131);!function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(Xr||(Xr={}));class Qr{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={...Qr._GetDefaultOptions(),...t};if(this._leftJoystick=!!e,Qr._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=0,this._axisTargetedByUpAndDown=1,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new $r.w,this.deltaPosition=W.Pq.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{Qr._VJCanvasWidth=window.innerWidth,Qr._VJCanvasHeight=window.innerHeight,Qr.Canvas&&(Qr.Canvas.width=Qr._VJCanvasWidth,Qr.Canvas.height=Qr._VJCanvasHeight),Qr._HalfWidth=Qr._VJCanvasWidth/2},!Qr.Canvas){window.addEventListener("resize",this._onResize,!1),Qr.Canvas=document.createElement("canvas"),Qr._VJCanvasWidth=window.innerWidth,Qr._VJCanvasHeight=window.innerHeight,Qr.Canvas.width=window.innerWidth,Qr.Canvas.height=window.innerHeight,Qr.Canvas.style.width="100%",Qr.Canvas.style.height="100%",Qr.Canvas.style.position="absolute",Qr.Canvas.style.backgroundColor="transparent",Qr.Canvas.style.top="0px",Qr.Canvas.style.left="0px",Qr.Canvas.style.zIndex="5",Qr.Canvas.style.touchAction="none",Qr.Canvas.setAttribute("touch-action","none");const e=Qr.Canvas.getContext("2d");if(!e)throw new Error("Unable to create canvas for virtual joystick");Qr._VJCanvasContext=e,Qr._VJCanvasContext.strokeStyle="#ffffff",Qr._VJCanvasContext.lineWidth=2,document.body.appendChild(Qr.Canvas)}Qr._HalfWidth=Qr.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&&Qr._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new W.I9(0,0),this._joystickPreviousPointerPos=new W.I9(0,0),this._joystickPointerStartPos=new W.I9(0,0),this._deltaJoystickVector=new W.I9(0,0),this._onPointerDownHandlerRef=e=>{this._onPointerDown(e)},this._onPointerMoveHandlerRef=e=>{this._onPointerMove(e)},this._onPointerUpHandlerRef=e=>{this._onPointerUp(e)},Qr.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),Qr.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),Qr.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),Qr.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),Qr.Canvas.addEventListener("contextmenu",(e=>{e.preventDefault()}),!1),requestAnimationFrame((()=>{this._drawVirtualJoystick()}))}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){let t;e.preventDefault(),t=!0===this._leftJoystick?e.clientXQr._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)):Qr._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 t=new W.I9(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),i=t.length();i>this.containerSize&&t.scaleInPlace(this.containerSize/i),this._joystickPointerPos.x=this._joystickPointerStartPos.x+t.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+t.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?Qr._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,2*this.containerSize,2*this.containerSize):(Qr._VJCanvasContext.beginPath(),Qr._VJCanvasContext.strokeStyle=this._joystickColor,Qr._VJCanvasContext.lineWidth=2,Qr._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,2*Math.PI,!0),Qr._VJCanvasContext.stroke(),Qr._VJCanvasContext.closePath(),Qr._VJCanvasContext.beginPath(),Qr._VJCanvasContext.lineWidth=6,Qr._VJCanvasContext.strokeStyle=this._joystickColor,Qr._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,2*Math.PI,!0),Qr._VJCanvasContext.stroke(),Qr._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?Qr._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,2*this.puckSize,2*this.puckSize):(Qr._VJCanvasContext.beginPath(),Qr._VJCanvasContext.strokeStyle=this._joystickColor,Qr._VJCanvasContext.lineWidth=2,Qr._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,2*Math.PI,!0),Qr._VJCanvasContext.stroke(),Qr._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()):(Qr._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),Qr._VJCanvasContext.beginPath(),Qr._VJCanvasContext.fillStyle="white",Qr._VJCanvasContext.beginPath(),Qr._VJCanvasContext.strokeStyle="red",Qr._VJCanvasContext.lineWidth=6,Qr._VJCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),Qr._VJCanvasContext.stroke(),Qr._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)})),requestAnimationFrame((()=>{this._drawVirtualJoystick()})))}releaseCanvas(){Qr.Canvas&&(Qr.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),Qr.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),Qr.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),Qr.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(Qr.Canvas),Qr.Canvas=null),this._released=!0}}Qr._GlobalJoystickIndex=0,Qr._AlwaysVisibleSticks=0,zr.prototype.addVirtualJoystick=function(){return this.add(new Zr),this};class Zr{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){const e=this.camera,t=50*e._computeLocalCameraSpeed(),i=W.uq.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),r=W.Pq.TransformCoordinates(new W.Pq(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(r),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}}attachControl(){this._leftjoystick=new Qr(!0),this._leftjoystick.setAxisForUpDown(2),this._leftjoystick.setAxisForLeftRight(0),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new Qr(!1),this._rightjoystick.setAxisForUpDown(0),this._rightjoystick.setAxisForLeftRight(1),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")}detachControl(){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()}getClassName(){return"FreeCameraVirtualJoystickInput"}getSimpleName(){return"virtualJoystick"}}br.FreeCameraVirtualJoystickInput=Zr,Ze.b.AddNodeConstructor("TargetCamera",((e,t)=>()=>new Jr(e,W.Pq.Zero(),t)));class Jr extends rt{constructor(e,t,i,r=!0){super(e,t,i,r),this._tmpUpVector=W.Pq.Zero(),this._tmpTargetVector=W.Pq.Zero(),this.cameraDirection=new W.Pq(0,0,0),this.cameraRotation=new W.I9(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new W.PT,this.rotation=new W.Pq(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=W.Pq.Zero(),this._initialFocalDistance=1,this._viewMatrix=W.uq.Zero(),this._camMatrix=W.uq.Zero(),this._cameraTransformMatrix=W.uq.Zero(),this._cameraRotationMatrix=W.uq.Zero(),this._referencePoint=new W.Pq(0,0,1),this._transformedReferencePoint=W.Pq.Zero(),this._deferredPositionUpdate=new W.Pq,this._deferredRotationQuaternionUpdate=new W.PT,this._deferredRotationUpdate=new W.Pq,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=W.Pq.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)}_initCache(){super._initCache(),this._cache.lockedTarget=new W.Pq(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new W.Pq(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new W.PT(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()/(100*e.getFps()))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=lt.bH),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),W.uq.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&&W.PT.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)return this.parent.getWorldMatrix().invertToRef(W.AA.Matrix[0]),W.Pq.TransformNormalToRef(this.cameraDirection,W.AA.Matrix[0],W.AA.Vector3[0]),this._deferredPositionUpdate.addInPlace(W.AA.Vector3[0]),void(this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate));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;if(this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i){if(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,!this.noRotationConstraint){const e=1.570796;this._deferredRotationUpdate.x>e&&(this._deferredRotationUpdate.x=e),this._deferredRotationUpdate.x<-e&&(this._deferredRotationUpdate.x=-e)}this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(W.PT.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(t),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>Ot.$.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&i&&this.onCollide(i))},this.inputs=new zr(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Ue.S0.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new W.Pq(0,0,0),this.cameraRotation=new W.I9(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?W.Pq.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let r=e;this.applyGravity&&(r=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,r,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=W.Pq.Zero(),this._transformedDirection=W.Pq.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"}}(0,je.Cg)([(0,$e.P_)()],es.prototype,"ellipsoid",void 0),(0,je.Cg)([(0,$e.P_)()],es.prototype,"ellipsoidOffset",void 0),(0,je.Cg)([(0,$e.lK)()],es.prototype,"checkCollisions",void 0),(0,je.Cg)([(0,$e.lK)()],es.prototype,"applyGravity",void 0),(0,X.Y5)("BABYLON.FreeCamera",es),Ze.b.AddNodeConstructor("TouchCamera",((e,t)=>()=>new ts(e,W.Pq.Zero(),t)));class ts extends es{get touchAngularSensibility(){const e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){const e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addTouch(),this._setupInputs()}getClassName(){return"TouchCamera"}_setupInputs(){const e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!e:e.allowMouse=!t}}Ze.b.AddNodeConstructor("ArcRotateCamera",((e,t)=>()=>new is(e,0,0,1,W.Pq.Zero(),t)));class is extends Jr{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 W.uq,this._upToYMatrix=new W.uq,this._upVector=W.Pq.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){W.uq.RotationAlignToRef(W.Pq.UpReadOnly,this._upVector,this._yToUpMatrix),W.uq.RotationAlignToRef(this._upVector,W.Pq.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}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}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 null!=this._bouncingBehavior}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new Pi,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return null!=this._framingBehavior}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new Ai,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return null!=this._autoRotationBehavior}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new Ei,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,r,s,n,o=!0){super(e,W.Pq.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=W.Pq.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=W.I9.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this.restoreStateInterpolationFactor=0,this._viewMatrix=new W.uq,this.panningAxis=new W.Pq(1,1,0),this._transformedDirection=new W.Pq,this.mapPanning=!1,this._progressiveRestore=!1,this.onMeshTargetChangedObservable=new z.cP,this.checkCollisions=!1,this.collisionRadius=new W.Pq(.5,.5,.5),this._previousPosition=W.Pq.Zero(),this._collisionVelocity=W.Pq.Zero(),this._newPosition=W.Pq.Zero(),this._computationVector=W.Pq.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);const r=Math.cos(this.alpha),s=Math.sin(this.alpha),n=Math.cos(this.beta);let o=Math.sin(this.beta);0===o&&(o=1e-4);const a=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*r*o,this.radius*n,this.radius*s*o),a.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let l=this.upVector;this.allowUpsideDown&&this.beta<0&&(l=l.clone(),l=l.negate()),this._computeViewMatrix(this._position,a,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=W.Pq.Zero(),s&&this.setTarget(s),this.alpha=t,this.beta=i,this.radius=r,this.getViewMatrix(),this.inputs=new Or(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new W.Pq(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=W.I9.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 e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}return this._getLockedTargetPosition()||this._target}storeState(){return this._storedAlpha=this._goalAlpha=this.alpha,this._storedBeta=this._goalBeta=this.beta,this._storedRadius=this._goalRadius=this.radius,this._storedTarget=this._goalTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this._goalTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return this.hasStateStored()&&this.restoreStateInterpolationFactor>lt.bH&&this.restoreStateInterpolationFactor<1?(this.interpolateTo(this._storedAlpha,this._storedBeta,this._storedRadius,this._storedTarget,this._storedTargetScreenOffset),!0):!!super._restoreStateValues()&&(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)}interpolateTo(e=this.alpha,t=this.beta,i=this.radius,r=this.target,s=this.targetScreenOffset){this._progressiveRestore=!0,this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,e=(0,ar.Clamp)(e,this.lowerAlphaLimit??-1/0,this.upperAlphaLimit??1/0),t=(0,ar.Clamp)(t,this.lowerBetaLimit??-1/0,this.upperBetaLimit??1/0),i=(0,ar.Clamp)(i,this.lowerRadiusLimit??-1/0,this.upperRadiusLimit??1/0),this._goalAlpha=e,this._goalBeta=t,this._goalRadius=i,this._goalTarget=r,this._goalTargetScreenOffset=s}_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)}attachControl(e,t,i=!0,r=2){const s=arguments;t=Ue.S0.BackCompatCameraNoPreventDefault(s),this._useCtrlForPanning=i,this._panningMouseButton=r,"boolean"==typeof s[0]&&(s.length>1&&(this._useCtrlForPanning=s[1]),s.length>2&&(this._panningMouseButton=s[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),this._progressiveRestore){const e=this._scene.getEngine().getDeltaTime()/1e3,t=1-Math.pow(2,-e/this.restoreStateInterpolationFactor);this.setTarget(W.Pq.Lerp(this.getTarget(),this._goalTarget,t)),W.PT.RotationAlphaBetaGammaToRef(this._goalAlpha,this._goalBeta,0,W.AA.Quaternion[0]),W.PT.RotationAlphaBetaGammaToRef(this.alpha,this.beta,0,W.AA.Quaternion[1]),W.PT.SlerpToRef(W.AA.Quaternion[1],W.AA.Quaternion[0],t,W.AA.Quaternion[2]),W.AA.Quaternion[2].normalize(),W.AA.Quaternion[2].toAlphaBetaGammaToRef(W.AA.Vector3[0]),this.alpha=W.AA.Vector3[0].x,this.beta=W.AA.Vector3[0].y,this.radius+=(this._goalRadius-this.radius)*t,W.I9.LerpToRef(this.targetScreenOffset,this._goalTargetScreenOffset,t,this.targetScreenOffset),(W.Pq.DistanceSquared(this.getTarget(),this._goalTarget)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||W.Pq.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);const e=this.alpha;0===this._computationVector.x&&0===this._computationVector.z?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+=2*t*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,r=!1){if(r=this.overrideCloneAlphaBetaRadius??r,e.computeWorldMatrix)t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{const t=e,r=this._getTargetPosition();if(r&&!i&&r.equals(t))return;this._targetHost=null,this._target=t,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}r||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta);let r=Math.sin(this.beta);0===r&&(r=1e-4),0===this.radius&&(this.radius=1e-4);const s=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*r,this.radius*i,this.radius*t*r),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||W.Pq.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),s.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const e=this.getScene().collisionCoordinator;this._collider||(this._collider=e.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,e.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let e=this.upVector;this.allowUpsideDown&&r<0&&(e=e.negate()),this._computeViewMatrix(this._position,s,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=s,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=Yt.MinMax(e);let r=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);r=Math.max(Math.min(r,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=r*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:r},t)}focusOn(e,t=!1){let i,r;if(void 0===e.min){const t=e||this.getScene().meshes;i=Yt.MinMax(t),r=W.Pq.Distance(i.min,i.max)}else i=e,r=e.distance;this._target=Yt.Center(i),t||(this.maxZ=2*r)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case rt.RIG_MODE_STEREOSCOPIC_OVERUNDER:case rt.RIG_MODE_STEREOSCOPIC_INTERLACED:case rt.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}const r=new is(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return r._cameraRigParams={},r.isRigCamera=!0,r.rigParent=this,r.upVector=this.upVector,r.mode=this.mode,r.orthoLeft=this.orthoLeft,r.orthoRight=this.orthoRight,r.orthoBottom=this.orthoBottom,r.orthoTop=this.orthoTop,r}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case rt.RIG_MODE_STEREOSCOPIC_OVERUNDER:case rt.RIG_MODE_STEREOSCOPIC_INTERLACED:case rt.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){const r=W.Pq.Distance(e,t),s=this.getScene().getEngine().getAspectRatio(this),n=Math.tan(this.fov/2),o=n*s,a=.5*r*i,l=a*Math.sqrt(1+1/(o*o)),h=a*Math.sqrt(1+1/(n*n));return Math.max(l,h)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}(0,je.Cg)([(0,$e.lK)()],is.prototype,"alpha",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"beta",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"radius",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"overrideCloneAlphaBetaRadius",void 0),(0,je.Cg)([(0,$e.P_)("target")],is.prototype,"_target",void 0),(0,je.Cg)([(0,$e.xG)("targetHost")],is.prototype,"_targetHost",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"inertialAlphaOffset",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"inertialBetaOffset",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"inertialRadiusOffset",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"lowerAlphaLimit",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"upperAlphaLimit",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"lowerBetaLimit",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"upperBetaLimit",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"lowerRadiusLimit",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"upperRadiusLimit",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"inertialPanningX",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"inertialPanningY",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"pinchToPanMaxDistance",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"panningDistanceLimit",void 0),(0,je.Cg)([(0,$e.P_)()],is.prototype,"panningOriginTarget",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"panningInertia",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"zoomToMouseLocation",null),(0,je.Cg)([(0,$e.lK)()],is.prototype,"zoomOnFactor",void 0),(0,je.Cg)([(0,$e.WM)()],is.prototype,"targetScreenOffset",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"allowUpsideDown",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"useInputToRestoreState",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"restoreStateInterpolationFactor",void 0),(0,X.Y5)("BABYLON.ArcRotateCamera",is),Ze.b.AddNodeConstructor("DeviceOrientationCamera",((e,t)=>()=>new rs(e,W.Pq.Zero(),t)));class rs extends es{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new W.PT,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new W.PT,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((e=>{0!=this._dragFactor&&(this._initialQuaternion||(this._initialQuaternion=new W.PT),W.PT.FromEulerAnglesToRef(0,e.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=Mt._0.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new W.PT),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 ss extends Sr{constructor(e){super(e)}addKeyboard(){return this.add(new wr),this}addMouse(){return this.add(new Nr),this}}class ns extends Jr{get angularSensibility(){const e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){const t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysForward(){const e=this.inputs.attached.keyboard;return e?e.keysForward:[]}set keysForward(e){const t=this.inputs.attached.keyboard;t&&(t.keysForward=e)}get keysBackward(){const e=this.inputs.attached.keyboard;return e?e.keysBackward:[]}set keysBackward(e){const t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}constructor(e,t,i,r=!0){super(e,t,i,r),this.ellipsoid=new W.Pq(1,1,1),this.ellipsoidOffset=new W.Pq(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=W.Pq.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=W.Pq.Zero(),this._diffPosition=W.Pq.Zero(),this._newPosition=W.Pq.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{(e=>{this._newPosition.copyFrom(e),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>Ot.$.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new ss(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Ue.S0.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new W.Pq(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?W.Pq.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let r=e;this.applyGravity&&(r=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,r,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=W.Pq.Zero(),this._transformedDirection=W.Pq.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=t-this.rotation.z;Math.abs(i)>=.001&&(this.rotation.z+=i/e,Math.abs(t-this.rotation.z)<=.001&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}}(0,je.Cg)([(0,$e.P_)()],ns.prototype,"ellipsoid",void 0),(0,je.Cg)([(0,$e.P_)()],ns.prototype,"ellipsoidOffset",void 0),(0,je.Cg)([(0,$e.lK)()],ns.prototype,"checkCollisions",void 0),(0,je.Cg)([(0,$e.lK)()],ns.prototype,"applyGravity",void 0),(0,X.Y5)("BABYLON.FlyCamera",ns);class os extends Sr{constructor(e){super(e)}addKeyboard(){return this.add(new Fr),this}addMouseWheel(){return this.add(new Lr),this}addPointers(){return this.add(new Br),this}addVRDeviceOrientation(){return Z.V.Warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}Ze.b.AddNodeConstructor("FollowCamera",((e,t)=>()=>new as(e,W.Pq.Zero(),t))),Ze.b.AddNodeConstructor("ArcFollowCamera",((e,t)=>()=>new ls(e,0,0,1,null,t)));class as extends Jr{constructor(e,t,i,r=null){super(e,t,i),this.radius=12,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.rotationOffset=0,this.lowerRotationOffsetLimit=null,this.upperRotationOffsetLimit=null,this.heightOffset=4,this.lowerHeightOffsetLimit=null,this.upperHeightOffsetLimit=null,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=r,this.inputs=new os(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;const t=W.AA.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);const i=Math.atan2(t.m[8],t.m[10]),r=Ue.S0.ToRadians(this.rotationOffset)+i,s=e.getAbsolutePosition(),n=s.x+Math.sin(r)*this.radius,o=s.z+Math.cos(r)*this.radius,a=n-this.position.x,l=s.y+this.heightOffset-this.position.y,h=o-this.position.z;let c=a*this.cameraAcceleration*2,u=l*this.cameraAcceleration,d=h*this.cameraAcceleration*2;(c>this.maxCameraSpeed||c<-this.maxCameraSpeed)&&(c=c<1?-this.maxCameraSpeed:this.maxCameraSpeed),(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),this.position=new W.Pq(this.position.x+c,this.position.y+u,this.position.z+d),this.setTarget(s)}attachControl(e,t){t=Ue.S0.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(){null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffsetthis.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffsetthis.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}}(0,je.Cg)([(0,$e.lK)()],as.prototype,"radius",void 0),(0,je.Cg)([(0,$e.lK)()],as.prototype,"lowerRadiusLimit",void 0),(0,je.Cg)([(0,$e.lK)()],as.prototype,"upperRadiusLimit",void 0),(0,je.Cg)([(0,$e.lK)()],as.prototype,"rotationOffset",void 0),(0,je.Cg)([(0,$e.lK)()],as.prototype,"lowerRotationOffsetLimit",void 0),(0,je.Cg)([(0,$e.lK)()],as.prototype,"upperRotationOffsetLimit",void 0),(0,je.Cg)([(0,$e.lK)()],as.prototype,"heightOffset",void 0),(0,je.Cg)([(0,$e.lK)()],as.prototype,"lowerHeightOffsetLimit",void 0),(0,je.Cg)([(0,$e.lK)()],as.prototype,"upperHeightOffsetLimit",void 0),(0,je.Cg)([(0,$e.lK)()],as.prototype,"cameraAcceleration",void 0),(0,je.Cg)([(0,$e.lK)()],as.prototype,"maxCameraSpeed",void 0),(0,je.Cg)([(0,$e.xG)("lockedTargetId")],as.prototype,"lockedTarget",void 0);class ls extends Jr{constructor(e,t,i,r,s,n){super(e,W.Pq.Zero(),n),this.alpha=t,this.beta=i,this.radius=r,this._cartesianCoordinates=W.Pq.Zero(),this.setMeshTarget(s)}setMeshTarget(e){this._meshTarget=e,this._follow()}_follow(){if(!this._meshTarget)return;this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);const e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}_checkInputs(){super._checkInputs(),this._follow()}getClassName(){return"ArcFollowCamera"}}(0,X.Y5)("BABYLON.FollowCamera",as),(0,X.Y5)("BABYLON.ArcFollowCamera",ls),function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(qr||(qr={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Yr||(Yr={}));class hs extends Cr{constructor(e,t,i,r=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new z.cP,this.onButtonUpObservable=new z.cP,this.onPadDownObservable=new z.cP,this.onPadUpObservable=new z.cP,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=Cr.XBOX,this._isXboxOnePad=r}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,0)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,1)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,2)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,3)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,9)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,8)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,4)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,5)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,10)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,11)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,12)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,13)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,14)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,15)}update(){super.update(),this._isXboxOnePad,this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}!function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(Kr||(Kr={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(jr||(jr={}));class cs extends Cr{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 z.cP,this.onButtonUpObservable=new z.cP,this.onPadDownObservable=new z.cP,this.onPadUpObservable=new z.cP,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=Cr.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&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonCross(){return this._buttonCross}set buttonCross(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,0)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,1)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,2)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,3)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,9)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,8)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,4)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,5)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,10)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,11)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,12)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,13)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,14)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,15)}update(){super.update(),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}class us{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new z.cP,(0,ii.BA)()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new z.cP((e=>{for(const t in this._babylonGamepads){const i=this._babylonGamepads[t];i&&i._isConnected&&this.onGamepadConnectedObservable.notifyObserver(e,i)}})),this._onGamepadConnectedEvent=e=>{const t=e.gamepad;if(t.index in this._babylonGamepads&&this._babylonGamepads[t.index].isConnected)return;let i;this._babylonGamepads[t.index]?(i=this._babylonGamepads[t.index],i.browserGamepad=t,i._isConnected=!0):i=this._addNewGamepad(t),this.onGamepadConnectedObservable.notifyObservers(i),this._startMonitoringGamepads()},this._onGamepadDisconnectedEvent=e=>{const t=e.gamepad;for(const e in this._babylonGamepads)if(this._babylonGamepads[e].index===t.index){const t=this._babylonGamepads[e];t._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(t),t.dispose&&t.dispose();break}},this._gamepadSupport)if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){const e=this._scene?this._scene.getEngine().getHostWindow():window;e&&(e.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),e.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}get gamepads(){return this._babylonGamepads}getGamepadByType(e=Cr.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){let t;this._oneGamepadConnected||(this._oneGamepadConnected=!0);const i=-1!==e.id.search("054c")&&-1===e.id.search("0ce6"),r=-1!==e.id.search("Xbox One");return t=r||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")||-1!==e.id.search("045e")&&-1===e.id.search("Surface Dock")?new hs(e.id,e.index,e,r):i?new cs(e.id,e.index,e):new yr(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{-1===this._loggedErrors.indexOf(t.index)&&(Ue.S0.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&Ot.$.QueueNewFrame((()=>{this._checkGamepadsStatus()}))}_updateGamepadObjects(){const e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new fs(e,W.Pq.Zero(),t)));class fs extends ts{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"}}rt._CreateDefaultParsedCamera=(e,t)=>new fs(e,W.Pq.Zero(),t),Ze.b.AddNodeConstructor("GamepadCamera",((e,t)=>()=>new ps(e,W.Pq.Zero(),t)));class ps extends fs{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}var _s=i(78239),ms=i(52660);class gs extends ms.w{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,r,s,n){super(e,"anaglyph",null,["leftSampler"],t,i[1],r,s,n),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("leftSampler",this._passedProcess)}))}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(i.bind(i,2153)))):t.push(Promise.resolve().then(i.bind(i,20692))),super._gatherImports(e,t)}}function vs(e){e._rigCameras[0]._rigPostProcess=new _s.v(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new gs(e.name+"_anaglyph",1,e._rigCameras)}(0,X.Y5)("BABYLON.AnaglyphPostProcess",gs),Ze.b.AddNodeConstructor("AnaglyphArcRotateCamera",((e,t,i)=>()=>new xs(e,0,0,1,W.Pq.Zero(),i.interaxial_distance,t)));class xs extends is{constructor(e,t,i,r,s,n,o){super(e,t,i,r,s,o),this._setRigMode=()=>vs(this),this.interaxialDistance=n,this.setCameraRigMode(rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}getClassName(){return"AnaglyphArcRotateCamera"}}Ze.b.AddNodeConstructor("AnaglyphFreeCamera",((e,t,i)=>()=>new bs(e,W.Pq.Zero(),i.interaxial_distance,t)));class bs extends es{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>vs(this),this.interaxialDistance=i,this.setCameraRigMode(rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}Ze.b.AddNodeConstructor("AnaglyphGamepadCamera",((e,t,i)=>()=>new Ss(e,W.Pq.Zero(),i.interaxial_distance,t)));class Ss extends ps{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>vs(this),this.interaxialDistance=i,this.setCameraRigMode(rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}Ze.b.AddNodeConstructor("AnaglyphUniversalCamera",((e,t,i)=>()=>new Ts(e,W.Pq.Zero(),i.interaxial_distance,t)));class Ts extends fs{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>vs(this),this.interaxialDistance=i,this.setCameraRigMode(rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}var Cs=i(69841);Cs.l.ShadersStore.stereoscopicInterlacePixelShader="const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=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);\n#else\n#ifdef IS_STEREOSCOPIC_INTERLACED\nfloat 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);\n#else\nuseCamB=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);\n#endif\n#endif\nif (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;}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);}\n";class ys extends ms.w{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,r,s,n,o){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],s,n,o,r?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new W.I9(1/this.width,1/this.height),this.onSizeChangedObservable.add((()=>{this._stepSize=new W.I9(1/this.width,1/this.height)})),this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)}))}}class Es extends ms.w{getClassName(){return"StereoscopicInterlacePostProcess"}constructor(e,t,i,r,s,n){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],r,s,n,i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new W.I9(1/this.width,1/this.height),this.onSizeChangedObservable.add((()=>{this._stepSize=new W.I9(1/this.width,1/this.height)})),this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)}))}}function Ps(e){const t=e.cameraRigMode===rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,i=e.cameraRigMode===rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;e.cameraRigMode===rt.RIG_MODE_STEREOSCOPIC_INTERLACED?(e._rigCameras[0]._rigPostProcess=new _s.v(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new ys(e.name+"_stereoInterlace",e._rigCameras,!1,!0)):(e._rigCameras[i?1:0].viewport=new et.L(0,0,t?.5:1,t?1:.5),e._rigCameras[i?0:1].viewport=new et.L(t?.5:0,t?0:.5,t?.5:1,t?1:.5))}Ze.b.AddNodeConstructor("StereoscopicArcRotateCamera",((e,t,i)=>()=>new As(e,0,0,1,W.Pq.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class As extends is{constructor(e,t,i,r,s,n,o,a){super(e,t,i,r,s,a),this._setRigMode=()=>Ps(this),this.interaxialDistance=n,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:rt.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}getClassName(){return"StereoscopicArcRotateCamera"}}Ze.b.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new Rs(e,W.Pq.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Rs extends es{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>Ps(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:rt.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}Ze.b.AddNodeConstructor("StereoscopicGamepadCamera",((e,t,i)=>()=>new Is(e,W.Pq.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Is extends ps{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>Ps(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:rt.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}Ze.b.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new Ms(e,W.Pq.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Ms extends fs{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>Ps(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:rt.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}class Os extends fs{set distanceBetweenEyes(e){this._distanceBetweenEyes=e}get distanceBetweenEyes(){return this._distanceBetweenEyes}set distanceToProjectionPlane(e){this._distanceToProjectionPlane=e}get distanceToProjectionPlane(){return this._distanceToProjectionPlane}constructor(e,t,i,r=1,s=.065){super(e,t,i),this._distanceBetweenEyes=s,this._distanceToProjectionPlane=r,this.setCameraRigMode(rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL,{stereoHalfAngle:0}),this._cameraRigParams.stereoHalfAngle=0,this._cameraRigParams.interaxialDistance=s}getClassName(){return"StereoscopicUniversalCamera"}createRigCamera(e){const t=new Jr(e,W.Pq.Zero(),this.getScene()),i=new Pt("tm_"+e,this.getScene());return t.parent=i,i.setPivotMatrix(W.uq.Identity(),!1),t.isRigCamera=!0,t.rigParent=this,t}_updateRigCameras(){for(let e=0;e()=>new Ds(e,W.Pq.Zero(),t)));class Ds extends es{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class ws{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 e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return W.uq.Translation(e,0,0)}get rightHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return W.uq.Translation(-e,0,0)}get leftPreViewMatrix(){return W.uq.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return W.uq.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){const e=new ws;return e.hResolution=1280,e.vResolution=800,e.hScreenSize=.149759993,e.vScreenSize=.0935999975,e.vScreenCenter=.0467999987,e.eyeToScreenDistance=.0410000011,e.lensSeparationDistance=.063500002,e.interpupillaryDistance=.064000003,e.distortionK=[1,.219999999,.239999995,0],e.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],e.postProcessScaleFactor=1.714605507808412,e.lensCenterOffset=.151976421,e}}class Ns extends ms.w{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,r){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,r.postProcessScaleFactor,t,vi.g.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=r.distortionK,this._postProcessScaleFactor=r.postProcessScaleFactor,this._lensCenterOffset=r.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add((()=>{this._scaleIn=new W.I9(2,2/this.aspectRatio),this._scaleFactor=new W.I9(1/this._postProcessScaleFactor*.5,1/this._postProcessScaleFactor*.5*this.aspectRatio),this._lensCenter=new W.I9(this._isRightEye?.5-.5*this._lensCenterOffset:.5+.5*this._lensCenterOffset,.5)})),this.onApplyObservable.add((e=>{e.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),e.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),e.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),e.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])}))}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(i.bind(i,79132)))):t.push(Promise.resolve().then(i.bind(i,44341))),super._gatherImports(e,t)}}Cs.l.ShadersStore.vrMultiviewToSingleviewPixelShader="precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}";var Fs=i(7107),Ls=i(722);class Bs{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new Vs(e)}sampleFrame(e=ai.j.Now){if(this._enabled){if(null!=this._lastFrameTimeMs){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 0===e?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 Vs{constructor(e){this._samples=new Array(e),this.reset()}add(e){let t;if(this.isSaturated()){const e=this._samples[this._pos];t=e-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(e-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}}var ks=i(7240),Us=i(96281);Ls.ThinEngine.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode!==e){switch(e){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: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 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 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}t||(this.depthCullingState.depthMask=0===e),this._alphaMode=e}else if(!t){const t=0===e;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}};var Gs=i(44512);function zs(e,t,i,r){let s,n=1;1===r?s=new Float32Array(t*i*4):2===r?(s=new Uint16Array(t*i*4),n=15360):s=7===r?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let r=0;r{const i=f.width,n=o(e);if(n){if(a){const e=this._getWebGLTextureType(s);let t=this._getInternalFormat(r);const o=this._getRGBABufferInternalSizedFormat(s);let l=!1;t===d.RGB&&(t=d.RGBA,l=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,f,!0),this._unpackFlipY(!1);const h=a(n);for(let r=0;r>r;for(let i=0;i<6;i++){let a=h[r][i];l&&(a=zs(a,n,n,s)),d.texImage2D(i,r,o,n,n,0,t,e,a)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(f,n,r,s,u);f.isReady=!0,t?.removePendingData(f),f.onLoadedObservable.notifyObservers(f),f.onLoadedObservable.clear(),l&&l()}};return this._loadFile(e,(e=>{p(e)}),void 0,t?.offlineProvider,!0,((e,i)=>{t?.removePendingData(f),h&&e&&h(e.status+" "+e.statusText,i)})),f},Ls.ThinEngine.prototype.createRawTexture2DArray=Ws(!1),Ls.ThinEngine.prototype.createRawTexture3D=Ws(!0),Ls.ThinEngine.prototype.updateRawTexture2DArray=Hs(!1),Ls.ThinEngine.prototype.updateRawTexture3D=Hs(!0);var Xs=i(2636);Ls.ThinEngine.prototype._readTexturePixelsSync=function(e,t,i,r=-1,s=0,n=null,o=!0,a=!1,l=0,h=0){const c=this._gl;if(!c)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const e=c.createFramebuffer();if(!e)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}c.bindFramebuffer(c.FRAMEBUFFER,this._dummyFramebuffer),r>-1?c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_CUBE_MAP_POSITIVE_X+r,e._hardwareTexture?.underlyingResource,s):c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,e._hardwareTexture?.underlyingResource,s);let u=void 0!==e.type?this._getWebGLTextureType(e.type):c.UNSIGNED_BYTE;return a?n||(n=(0,Xs.kZ)(e.type,4*t*i)):u===c.UNSIGNED_BYTE?(n||(n=new Uint8Array(4*t*i)),u=c.UNSIGNED_BYTE):(n||(n=new Float32Array(4*t*i)),u=c.FLOAT),o&&this.flushFramebuffer(),c.readPixels(l,h,t,i,c.RGBA,u,n),c.bindFramebuffer(c.FRAMEBUFFER,this._currentFramebuffer),n},Ls.ThinEngine.prototype._readTexturePixels=function(e,t,i,r=-1,s=0,n=null,o=!0,a=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,r,s,n,o,a,l,h))},Ls.ThinEngine.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let r;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),r=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,r,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},Ls.ThinEngine.prototype.updateDynamicVertexBuffer=function(e,t,i,r){this.bindArrayBuffer(e),void 0===i&&(i=0);const s=t.byteLength||t.length;void 0===r||r>=s&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+r)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,r):new Uint8Array(t.buffer,t.byteOffset+i,r),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()},Ls.ThinEngine.prototype._createDepthStencilCubeTexture=function(e,t){const i=new Fs.h(this,12);if(i.isCube=!0,1===this.webGLVersion)return Z.V.Error("Depth cube texture is not supported by WebGL 1."),i;const r={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t},s=this._gl;this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,i,!0),this._setupDepthStencilTexture(i,e,r.bilinearFiltering,r.comparisonFunction);for(let t=0;t<6;t++)r.generateStencil?s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,s.DEPTH24_STENCIL8,e,e,0,s.DEPTH_STENCIL,s.UNSIGNED_INT_24_8,null):s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,s.DEPTH_COMPONENT24,e,e,0,s.DEPTH_COMPONENT,s.UNSIGNED_INT,null);return this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(i),i},Ls.ThinEngine.prototype._setCubeMapTextureParams=function(e,t,i){const r=this._gl;r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,t?r.LINEAR_MIPMAP_LINEAR:r.LINEAR),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),e.samplingMode=t?3:2,t&&this.getCaps().textureMaxLevel&&void 0!==i&&i>0&&(r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAX_LEVEL,i),e._maxLodLevel=i),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null)},Ls.ThinEngine.prototype.createCubeTexture=function(e,t,i,r,s=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d,f=!1,p=null){const _=this._gl;return this.createCubeTextureBase(e,t,i,!!r,s,n,o,a,l,h,c,u,(e=>this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,e,!0)),((e,t)=>{const i=this.needPOTTextures?(0,Gs.R)(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,n=i,a=[_.TEXTURE_CUBE_MAP_POSITIVE_X,_.TEXTURE_CUBE_MAP_POSITIVE_Y,_.TEXTURE_CUBE_MAP_POSITIVE_Z,_.TEXTURE_CUBE_MAP_NEGATIVE_X,_.TEXTURE_CUBE_MAP_NEGATIVE_Y,_.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(!1);const l=o?this._getInternalFormat(o,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:_.RGBA;let h=o?this._getInternalFormat(o):_.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(h=l);for(let e=0;e0}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(){return this._textures?.[0]??null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}getBaseArrayLayer(e){if(!this._textures)return-1;const t=this._textures[e],i=this._layerIndices?.[e]??0,r=this._faceIndices?.[e]??0;return t.isCube?6*i+r:t.is3D?0:i}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;const r=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,r}constructor(e,t,i,r,s){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=r,this._depthStencilTexture=null,this.label=s}setTextures(e){Array.isArray(e)?this._textures=e:this._textures=e?[e]: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=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==i&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,n){return this._depthStencilTexture?.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=n,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:r,depthTextureFormat:s,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(){let e=null;if(this._isMulti){const t=this.textures;if(t&&t.length>0){let i=!1,r=t.length,s=-1;const n=t[t.length-1]._source;14!==n&&12!==n||(i=!0,s=t[t.length-1].format,r--);const o=[],a=[],l=[],h=[],c=[],u=[],d=[],f={};for(let e=0;e1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){if(this._textures)for(let e=0;e1){const s=this._context,n=s["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=i??this.layerIndices?.[t]??0,s.framebufferTextureLayer(s.FRAMEBUFFER,n,e._hardwareTexture.underlyingResource,r,i)):e.isCube?(i=i??this.faceIndices?.[t]??0,s.framebufferTexture2D(s.FRAMEBUFFER,n,s.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,r)):s.framebufferTexture2D(s.FRAMEBUFFER,n,s.TEXTURE_2D,e._hardwareTexture.underlyingResource,r)}else{const s=this._context,n=s["COLOR_ATTACHMENT"+t+"_WEBGL"],o=void 0!==i?s.TEXTURE_CUBE_MAP_POSITIVE_X+i:s.TEXTURE_2D;s.framebufferTexture2D(s.FRAMEBUFFER,n,o,e._hardwareTexture.underlyingResource,r)}n._bindUnboundFramebuffer(o)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const i=this._attachments?.length??this.textures.length;for(let e=0;e1){const e=r._hardwareTexture.getMSAARenderBuffer(0);i._MSAAFramebuffer=f.createFramebuffer(),this._bindUnboundFramebuffer(i._MSAAFramebuffer),f.framebufferRenderbuffer(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.RENDERBUFFER,e),this._bindUnboundFramebuffer(null)}}else this.updateRenderTargetTextureSampleCount(i,l);return i},Ls.ThinEngine.prototype._createDepthStencilTexture=function(e,t,i){const r=this._gl,s=e.layers||0,n=e.depth||0;let o=r.TEXTURE_2D;0!==s?o=r.TEXTURE_2D_ARRAY:0!==n&&(o=r.TEXTURE_3D);const a=new Fs.h(this,12);if(a.label=t.label,!this._caps.depthTextureExtension)return Z.V.Error("Depth texture is not supported by your browser or hardware."),a;const l={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t};if(this._bindTextureDirectly(o,a,!0),this._setupDepthStencilTexture(a,e,0!==l.comparisonFunction&&l.bilinearFiltering,l.comparisonFunction,l.samples),void 0!==l.depthTextureFormat){if(15!==l.depthTextureFormat&&16!==l.depthTextureFormat&&17!==l.depthTextureFormat&&13!==l.depthTextureFormat&&14!==l.depthTextureFormat&&18!==l.depthTextureFormat)return Z.V.Error(`Depth texture ${l.depthTextureFormat} format is not supported.`),a;a.format=l.depthTextureFormat}else a.format=l.generateStencil?13:16;const h=17===a.format||13===a.format||18===a.format;let c=r.UNSIGNED_INT;15===a.format?c=r.UNSIGNED_SHORT:17===a.format||13===a.format?c=r.UNSIGNED_INT_24_8:14===a.format?c=r.FLOAT:18===a.format&&(c=r.FLOAT_32_UNSIGNED_INT_24_8_REV);const u=h?r.DEPTH_STENCIL:r.DEPTH_COMPONENT,d=this._getInternalFormatFromDepthTextureFormat(a.format,!0,h);return a.is2DArray?r.texImage3D(o,0,d,a.width,a.height,s,0,u,c,null):a.is3D?r.texImage3D(o,0,d,a.width,a.height,n,0,u,c,null):r.texImage2D(o,0,d,a.width,a.height,0,u,c,null),this._bindTextureDirectly(o,null),this._internalTexturesCache.push(a),i._depthStencilBuffer&&(r.deleteRenderbuffer(i._depthStencilBuffer),i._depthStencilBuffer=null),this._bindUnboundFramebuffer(i._MSAAFramebuffer??i._framebuffer),i._generateStencilBuffer=h,i._depthStencilTextureWithStencil=h,i._depthStencilBuffer=this._setupFramebufferDepthAttachments(i._generateStencilBuffer,i._generateDepthBuffer,i.width,i.height,i.samples,a.format),this._bindUnboundFramebuffer(null),a},Ls.ThinEngine.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e)return 1;if(e.samples===t)return t;const i=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null);const r=e.texture?._hardwareTexture;if(r?.releaseMSAARenderBuffers(),e.texture&&t>1&&"function"==typeof i.renderbufferStorageMultisample){const s=i.createFramebuffer();if(!s)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=s,this._bindUnboundFramebuffer(e._MSAAFramebuffer);const n=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBABufferInternalSizedFormat(e.texture.type,e.texture.format,e.texture._useSRGBBuffer),i.COLOR_ATTACHMENT0,!1);if(!n)throw new Error("Unable to create multi sampled framebuffer");r?.addMSAARenderBuffer(n)}this._bindUnboundFramebuffer(e._MSAAFramebuffer??e._framebuffer),e.texture&&(e.texture.samples=t),e._samples=t;const s=e._depthStencilTexture?e._depthStencilTexture.format:void 0;return e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.width,e.height,t,s),this._bindUnboundFramebuffer(null),t},Ls.ThinEngine.prototype._setupDepthStencilTexture=function(e,t,i,r,s=1){const n=t.width??t,o=t.height??t,a=t.layers||0,l=t.depth||0;e.baseWidth=n,e.baseHeight=o,e.width=n,e.height=o,e.is2DArray=a>0,e.depth=a||l,e.isReady=!0,e.samples=s,e.generateMipMaps=!1,e.samplingMode=i?2:1,e.type=0,e._comparisonFunction=r;const h=this._gl,c=this._getTextureTarget(e),u=this._getSamplingParameters(e.samplingMode,!1);h.texParameteri(c,h.TEXTURE_MAG_FILTER,u.mag),h.texParameteri(c,h.TEXTURE_MIN_FILTER,u.min),h.texParameteri(c,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(c,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===r?(h.texParameteri(c,h.TEXTURE_COMPARE_FUNC,515),h.texParameteri(c,h.TEXTURE_COMPARE_MODE,h.NONE)):(h.texParameteri(c,h.TEXTURE_COMPARE_FUNC,r),h.texParameteri(c,h.TEXTURE_COMPARE_MODE,h.COMPARE_REF_TO_TEXTURE)))},Ls.ThinEngine.prototype.setDepthStencilTexture=function(e,t,i,r){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,r):this._setTexture(e,null,void 0,void 0,r))},Ls.ThinEngine.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),r={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};r.generateStencilBuffer=r.generateDepthBuffer&&r.generateStencilBuffer,(1!==r.type||this._caps.textureFloatLinearFiltering)&&(2!==r.type||this._caps.textureHalfFloatLinearFiltering)||(r.samplingMode=1);const s=this._gl,n=new Fs.h(this,5);this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,n,!0);const o=this._getSamplingParameters(r.samplingMode,r.generateMipMaps);1!==r.type||this._caps.textureFloat||(r.type=0,Z.V.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,o.mag),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,o.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 t=0;t<6;t++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(r.type,r.format),e,e,0,this._getInternalFormat(r.format),this._getWebGLTextureType(r.type),null);const a=s.createFramebuffer();return this._bindUnboundFramebuffer(a),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(r.generateStencilBuffer,r.generateDepthBuffer,e,e),r.generateMipMaps&&s.generateMipmap(s.TEXTURE_CUBE_MAP),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=a,i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=r.generateStencilBuffer,n.width=e,n.height=e,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=r.generateMipMaps,n.samplingMode=r.samplingMode,n.type=r.type,n.format=r.format,this._internalTexturesCache.push(n),i.setTextures(n),i};var Ks=i(13798),js=i(23199);function $s(e,t,i){e._onCanvasFocus=()=>{e.onCanvasFocusObservable.notifyObservers(e)},e._onCanvasBlur=()=>{e.onCanvasBlurObservable.notifyObservers(e)},e._onCanvasContextMenu=t=>{e.disableContextMenu&&t.preventDefault()},t.addEventListener("focus",e._onCanvasFocus),t.addEventListener("blur",e._onCanvasBlur),t.addEventListener("contextmenu",e._onCanvasContextMenu),e._onBlur=()=>{e.disablePerformanceMonitorInBackground&&e.performanceMonitor.disable(),e._windowIsBackground=!0},e._onFocus=()=>{e.disablePerformanceMonitorInBackground&&e.performanceMonitor.enable(),e._windowIsBackground=!1},e._onCanvasPointerOut=i=>{document.elementFromPoint(i.clientX,i.clientY)!==t&&e.onCanvasPointerOutObservable.notifyObservers(i)};const r=e.getHostWindow();r&&"function"==typeof r.addEventListener&&(r.addEventListener("blur",e._onBlur),r.addEventListener("focus",e._onFocus)),t.addEventListener("pointerout",e._onCanvasPointerOut),i.doNotHandleTouchAction||function(e){e&&e.setAttribute&&(e.setAttribute("touch-action","none"),e.style.touchAction="none",e.style.webkitTapHighlightColor="transparent")}(t),!Ot.$.audioEngine&&i.audioEngine&&Ot.$.AudioEngineFactory&&(Ot.$.audioEngine=Ot.$.AudioEngineFactory(e.getRenderingCanvas(),e.getAudioContext(),e.getAudioDestination())),(0,ii.Nf)()&&(e._onFullscreenChange=()=>{e.isFullscreen=!!document.fullscreenElement,e.isFullscreen&&e._pointerLockRequested&&t&&sn(t)},document.addEventListener("fullscreenchange",e._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",e._onFullscreenChange,!1),e._onPointerLockChange=()=>{e.isPointerLock=document.pointerLockElement===t},document.addEventListener("pointerlockchange",e._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",e._onPointerLockChange,!1)),e.enableOfflineSupport=void 0!==Ot.$.OfflineProviderFactory,e._deterministicLockstep=!!i.deterministicLockstep,e._lockstepMaxSteps=i.lockstepMaxSteps||0,e._timeStep=i.timeStep||1/60}function Qs(e,t){1===he.q.Instances.length&&Ot.$.audioEngine&&(Ot.$.audioEngine.dispose(),Ot.$.audioEngine=null);const i=e.getHostWindow();i&&"function"==typeof i.removeEventListener&&(i.removeEventListener("blur",e._onBlur),i.removeEventListener("focus",e._onFocus)),t&&(t.removeEventListener("focus",e._onCanvasFocus),t.removeEventListener("blur",e._onCanvasBlur),t.removeEventListener("pointerout",e._onCanvasPointerOut),t.removeEventListener("contextmenu",e._onCanvasContextMenu)),(0,ii.Nf)()&&(document.removeEventListener("fullscreenchange",e._onFullscreenChange),document.removeEventListener("mozfullscreenchange",e._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",e._onFullscreenChange),document.removeEventListener("msfullscreenchange",e._onFullscreenChange),document.removeEventListener("pointerlockchange",e._onPointerLockChange),document.removeEventListener("mspointerlockchange",e._onPointerLockChange),document.removeEventListener("mozpointerlockchange",e._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",e._onPointerLockChange))}function Zs(e){const t=document.createElement("span");t.textContent="Hg",t.style.font=e;const i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";const r=document.createElement("div");r.style.whiteSpace="nowrap",r.appendChild(t),r.appendChild(i),document.body.appendChild(r);let s=0,n=0;try{n=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",s=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(r)}return{ascent:s,height:n,descent:n-s}}function Js(e,t,i){return new Promise(((r,s)=>{const n=new Image;n.onload=()=>{n.decode().then((()=>{e.createImageBitmap(n,i).then((e=>{r(e)}))}))},n.onerror=()=>{s(`Error loading image ${n.src}`)},n.src=t}))}function en(e,t,i,r){const s=e.createCanvas(i,r).getContext("2d");if(!s)throw new Error("Unable to get 2d context for resizeImageBitmap");return s.drawImage(t,0,0),s.getImageData(0,0,i,r).data}function tn(e){const t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}function rn(){const e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}function sn(e){if(e.requestPointerLock){const t=e.requestPointerLock();t instanceof Promise?t.then((()=>{e.focus()})).catch((()=>{})):e.focus()}}function nn(){document.exitPointerLock&&document.exitPointerLock()}Ls.ThinEngine.prototype.createPrefilteredCubeTexture=function(e,t,r,s,n=null,o=null,a,l=null,h=!0){return this.createCubeTexture(e,t,null,!1,(async e=>{if(!e)return void(n&&n(null));const o=e.texture;if(h?e.info.sphericalPolynomial&&(o._sphericalPolynomial=e.info.sphericalPolynomial):o._sphericalPolynomial=new Ks.Q,o._source=9,this.getCaps().textureLOD)return void(n&&n(o));const a=this._gl,l=e.width;if(!l)return;const{DDSTools:c}=await Promise.resolve().then(i.bind(i,26589)),u=[];for(let i=0;i<3;i++){const n=1-i/2,h=s,d=Math.log2(l)*r+s,f=h+(d-h)*n,p=Math.round(Math.min(Math.max(f,0),d)),_=new Fs.h(this,2);if(_.type=o.type,_.format=o.format,_.width=Math.pow(2,Math.max(Math.log2(l)-p,0)),_.height=_.width,_.isCube=!0,_._cachedWrapU=0,_._cachedWrapV=0,this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,_,!0),_.samplingMode=2,a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),e.isDDS){const t=e.info,i=e.data;this._unpackFlipY(t.isCompressed),c.UploadDDSLevels(this,_,i,t,!0,6,p)}else Z.V.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null);const m=new js.t(t);m._isCube=!0,m._texture=_,_.isReady=!0,u.push(m)}o._lodTextureHigh=u[2],o._lodTextureMid=u[1],o._lodTextureLow=u[0],n&&n(o)}),o,a,l,h,r,s)},Ls.ThinEngine.prototype.createUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create uniform buffer");const r=new ks.A(i);return this.bindUniformBuffer(r),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),r.references=1,r},Ls.ThinEngine.prototype.createDynamicUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create dynamic uniform buffer");const r=new ks.A(i);return this.bindUniformBuffer(r),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),r.references=1,r},Ls.ThinEngine.prototype.updateUniformBuffer=function(e,t,i,r){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===r?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+r)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+r)),this.bindUniformBuffer(null)},Ls.ThinEngine.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},Ls.ThinEngine.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},Ls.ThinEngine.prototype.bindUniformBlock=function(e,t,i){const r=e.program,s=this._gl.getUniformBlockIndex(r,t);4294967295!==s&&this._gl.uniformBlockBinding(r,s,i)},Ot.$.prototype.displayLoadingUI=function(){if(!(0,ii.BA)())return;const e=this.loadingScreen;e&&e.displayLoadingUI()},Ot.$.prototype.hideLoadingUI=function(){if(!(0,ii.BA)())return;const e=this._loadingScreen;e&&e.hideLoadingUI()},Object.defineProperty(Ot.$.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=Ot.$.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(e){this._loadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(Ot.$.prototype,"loadingUIText",{set:function(e){this.loadingScreen.loadingUIText=e},enumerable:!0,configurable:!0}),Object.defineProperty(Ot.$.prototype,"loadingUIBackgroundColor",{set:function(e){this.loadingScreen.loadingUIBackgroundColor=e},enumerable:!0,configurable:!0}),Ot.$.prototype.getInputElement=function(){return this._renderingCanvas},Ot.$.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null},Ot.$.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null},Ot.$.prototype.getAspectRatio=function(e,t=!1){const i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)},Ot.$.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)},Ot.$.prototype._verifyPointerLock=function(){this._onPointerLockChange?.()},Ot.$.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){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)}this._alphaEquation=e}},Ot.$.prototype.getInputElement=function(){return this._renderingCanvas},Ot.$.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc},Ot.$.prototype.setDepthFunction=function(e){this._depthCullingState.depthFunc=e},Ot.$.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(516)},Ot.$.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(518)},Ot.$.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(513)},Ot.$.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(515)},Ot.$.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask},Ot.$.prototype.setDepthWrite=function(e){this._depthCullingState.depthMask=e},Ot.$.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest},Ot.$.prototype.setStencilBuffer=function(e){this._stencilState.stencilTest=e},Ot.$.prototype.getStencilMask=function(){return this._stencilState.stencilMask},Ot.$.prototype.setStencilMask=function(e){this._stencilState.stencilMask=e},Ot.$.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc},Ot.$.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef},Ot.$.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask},Ot.$.prototype.setStencilFunction=function(e){this._stencilState.stencilFunc=e},Ot.$.prototype.setStencilFunctionReference=function(e){this._stencilState.stencilFuncRef=e},Ot.$.prototype.setStencilFunctionMask=function(e){this._stencilState.stencilFuncMask=e},Ot.$.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail},Ot.$.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail},Ot.$.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass},Ot.$.prototype.setStencilOperationFail=function(e){this._stencilState.stencilOpStencilFail=e},Ot.$.prototype.setStencilOperationDepthFail=function(e){this._stencilState.stencilOpDepthFail=e},Ot.$.prototype.setStencilOperationPass=function(e){this._stencilState.stencilOpStencilDepthPass=e},Ot.$.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()},Ot.$.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)},Ot.$.prototype.setAlphaConstants=function(e,t,i,r){this._alphaState.setAlphaBlendConstants(e,t,i,r)},Ot.$.prototype.getAlphaMode=function(){return this._alphaMode},Ot.$.prototype.getAlphaEquation=function(){return this._alphaEquation},Ot.$.prototype.getRenderPassNames=function(){return this._renderPassNames},Ot.$.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]},Ot.$.prototype.createRenderPassId=function(e){const t=++Ot.$._RenderPassIdCounter;return this._renderPassNames[t]=e??"NONAME",t},Ot.$.prototype.releaseRenderPassId=function(e){this._renderPassNames[e]=void 0;for(let t=0;t{this._loadFile(e,(e=>{r(e)}),void 0,t,i,((e,t)=>{s(t)}))}))}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}getFontOffset(e){return Zs(e)}_cancelFrame(){if(this.customAnimationFrameRequester){if(0!==this._frameHandler){this._frameHandler=0;const{cancelAnimationFrame:e}=this.customAnimationFrameRequester;e&&e(this.customAnimationFrameRequester.requestID)}}else super._cancelFrame()}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&0===this._frameHandler&&(this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}enterPointerlock(){this._renderingCanvas&&sn(this._renderingCanvas)}exitPointerlock(){nn()}beginFrame(){this._measureFps(),super.beginFrame()}_deletePipelineContext(e){const t=e;t&&t.program&&t.transformFeedback&&(this.deleteTransformFeedback(t.transformFeedback),t.transformFeedback=null),super._deletePipelineContext(e)}createShaderProgram(e,t,i,r,s,n=null){s=s||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);const o=super.createShaderProgram(e,t,i,r,s,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),o}_createShaderProgram(e,t,i,r,s=null){const n=r.createProgram();if(e.program=n,!n)throw new Error("Unable to create program");if(r.attachShader(n,t),r.attachShader(n,i),this.webGLVersion>1&&s){const t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(n,s),e.transformFeedback=t}return r.linkProgram(n),this.webGLVersion>1&&s&&this.bindTransformFeedback(null),e.context=r,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((t=>{t._outputTexture===e&&(t._outputTexture=null)})),t.cameras.forEach((t=>{t._postProcesses.forEach((t=>{t&&t._outputTexture===e&&(t._outputTexture=null)}))}))}))}_rescaleTexture(e,t,i,r,s){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);const n=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});if(!this._rescalePostProcess&&an._RescalePostProcessFactory&&(this._rescalePostProcess=an._RescalePostProcessFactory(this)),this._rescalePostProcess){this._rescalePostProcess.externalTextureSamplerBinding=!0;const o=()=>{this._rescalePostProcess.onApply=function(t){t._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,r,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),s&&s()},a=this._rescalePostProcess.getEffect();a?a.executeWhenCompiled(o):this._rescalePostProcess.onEffectCreatedObservable.addOnce((e=>{e.executeWhenCompiled(o)}))}}wrapWebGLTexture(e,t=!1,i=3,r=0,s=0){const n=new Us.d(e,this._gl),o=new Fs.h(this,0,!0);return o._hardwareTexture=n,o.baseWidth=r,o.baseHeight=s,o.width=r,o.height=s,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,r=0){const s=this._gl,n=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),a=this._getRGBABufferInternalSizedFormat(e.type,o),l=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=s.TEXTURE_2D;e.isCube&&(h=s.TEXTURE_CUBE_MAP_POSITIVE_X+i),s.texImage2D(h,r,a,o,n,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion)return void Z.V.Error("WebGL 1 does not support texture comparison.");const i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(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),0===t?(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 ks.A(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){const r=this._gl;return new Promise(((s,n)=>{const o=()=>{const a=r.clientWaitSync(e,t,0);a!=r.WAIT_FAILED?a!=r.TIMEOUT_EXPIRED?s():setTimeout(o,i):n()};o()}))}_readPixelsAsync(e,t,i,r,s,n,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const a=this._gl,l=a.createBuffer();a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.bufferData(a.PIXEL_PACK_BUFFER,o.byteLength,a.STREAM_READ),a.readPixels(e,t,i,r,s,n,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null);const h=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(a.flush(),this._clientWaitAsync(h,0,10).then((()=>(a.deleteSync(h),a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,o),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),a.deleteBuffer(l),o)))):null}dispose(){this.hideLoadingUI(),this._rescalePostProcess&&this._rescalePostProcess.dispose(),Qs(this,this._renderingCanvas),super.dispose()}}an.ALPHA_DISABLE=0,an.ALPHA_ADD=1,an.ALPHA_COMBINE=2,an.ALPHA_SUBTRACT=3,an.ALPHA_MULTIPLY=4,an.ALPHA_MAXIMIZED=5,an.ALPHA_ONEONE=6,an.ALPHA_PREMULTIPLIED=7,an.ALPHA_PREMULTIPLIED_PORTERDUFF=8,an.ALPHA_INTERPOLATE=9,an.ALPHA_SCREENMODE=10,an.DELAYLOADSTATE_NONE=0,an.DELAYLOADSTATE_LOADED=1,an.DELAYLOADSTATE_LOADING=2,an.DELAYLOADSTATE_NOTLOADED=4,an.NEVER=512,an.ALWAYS=519,an.LESS=513,an.EQUAL=514,an.LEQUAL=515,an.GREATER=516,an.GEQUAL=518,an.NOTEQUAL=517,an.KEEP=7680,an.REPLACE=7681,an.INCR=7682,an.DECR=7683,an.INVERT=5386,an.INCR_WRAP=34055,an.DECR_WRAP=34056,an.TEXTURE_CLAMP_ADDRESSMODE=0,an.TEXTURE_WRAP_ADDRESSMODE=1,an.TEXTURE_MIRROR_ADDRESSMODE=2,an.TEXTUREFORMAT_ALPHA=0,an.TEXTUREFORMAT_LUMINANCE=1,an.TEXTUREFORMAT_LUMINANCE_ALPHA=2,an.TEXTUREFORMAT_RGB=4,an.TEXTUREFORMAT_RGBA=5,an.TEXTUREFORMAT_RED=6,an.TEXTUREFORMAT_R=6,an.TEXTUREFORMAT_RG=7,an.TEXTUREFORMAT_RED_INTEGER=8,an.TEXTUREFORMAT_R_INTEGER=8,an.TEXTUREFORMAT_RG_INTEGER=9,an.TEXTUREFORMAT_RGB_INTEGER=10,an.TEXTUREFORMAT_RGBA_INTEGER=11,an.TEXTURETYPE_UNSIGNED_BYTE=0,an.TEXTURETYPE_UNSIGNED_INT=0,an.TEXTURETYPE_FLOAT=1,an.TEXTURETYPE_HALF_FLOAT=2,an.TEXTURETYPE_BYTE=3,an.TEXTURETYPE_SHORT=4,an.TEXTURETYPE_UNSIGNED_SHORT=5,an.TEXTURETYPE_INT=6,an.TEXTURETYPE_UNSIGNED_INTEGER=7,an.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,an.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,an.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,an.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,an.TEXTURETYPE_UNSIGNED_INT_24_8=12,an.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,an.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,an.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,an.TEXTURE_NEAREST_SAMPLINGMODE=1,an.TEXTURE_BILINEAR_SAMPLINGMODE=2,an.TEXTURE_TRILINEAR_SAMPLINGMODE=3,an.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,an.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,an.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,an.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,an.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,an.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,an.TEXTURE_NEAREST_LINEAR=7,an.TEXTURE_NEAREST_NEAREST=1,an.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,an.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,an.TEXTURE_LINEAR_LINEAR=2,an.TEXTURE_LINEAR_NEAREST=12,an.TEXTURE_EXPLICIT_MODE=0,an.TEXTURE_SPHERICAL_MODE=1,an.TEXTURE_PLANAR_MODE=2,an.TEXTURE_CUBIC_MODE=3,an.TEXTURE_PROJECTION_MODE=4,an.TEXTURE_SKYBOX_MODE=5,an.TEXTURE_INVCUBIC_MODE=6,an.TEXTURE_EQUIRECTANGULAR_MODE=7,an.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,an.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,an.SCALEMODE_FLOOR=1,an.SCALEMODE_NEAREST=2,an.SCALEMODE_CEILING=3;var ln=i(58059);class hn extends ln.${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}}function cn(e,t){const i=new Rt.D(e,void 0,!0,t);return i.addUniform("viewProjection",16),i.addUniform("viewProjectionR",16),i.addUniform("view",16),i.addUniform("projection",16),i.addUniform("vEyePosition",4),i}an.prototype.createMultiviewRenderTargetTexture=function(e,t,i,r){const s=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";const n=this._createHardwareRenderTargetWrapper(!1,!1,{width:e,height:t});n._framebuffer=s.createFramebuffer();const o=new Fs.h(this,0,!0);return o.width=e,o.height=t,o.isMultiview=!0,i||(i=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,i),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.RGBA8,e,t,2)),n._colorTextureArray=i,r||(r=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,r),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.DEPTH24_STENCIL8,e,t,2)),n._depthStencilTextureArray=r,o.isReady=!0,n.setTextures(o),n._depthStencilTexture=o,n},an.prototype.bindMultiviewFramebuffer=function(e){const t=e,i=this._gl,r=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw"Invalid multiview frame buffer";this.getCaps().oculusMultiview?(r.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,t.samples,0,2),r.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,t.samples,0,2)):(r.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),r.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,0,2))},an.prototype.bindSpaceWarpFramebuffer=function(e){const t=e,i=this._gl,r=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw new Error("Invalid Space Warp framebuffer");r.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),r.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_ATTACHMENT,t._depthStencilTextureArray,0,0,2)},rt.prototype._useMultiviewToSingleView=!1,rt.prototype._multiviewTexture=null,rt.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?this._multiviewTexture.getRenderWidth()==e&&this._multiviewTexture.getRenderHeight()==t||(this._multiviewTexture.dispose(),this._multiviewTexture=new hn(this.getScene(),{width:e,height:t})):this._multiviewTexture=new hn(this.getScene(),{width:e,height:t})};const un=oi.Z.prototype.createSceneUniformBuffer;oi.Z.prototype._transformMatrixR=W.uq.Zero(),oi.Z.prototype._multiviewSceneUbo=null,oi.Z.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=cn(this.getEngine(),"scene_multiview")},oi.Z.prototype.createSceneUniformBuffer=function(e){return this._multiviewSceneUbo?cn(this.getEngine(),e):un.bind(this)(e)},oi.Z.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,W.AA.Matrix[0]),tt.P.GetRightPlaneToRef(W.AA.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))},oi.Z.prototype._renderMultiviewToSingleView=function(e){e._resizeOrCreateMultiviewTexture(e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.width>0?e._rigPostProcess.width:this.getEngine().getRenderWidth(!0),e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.height>0?e._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),e.outputRenderTarget=e._multiviewTexture,this._renderForCamera(e),e.outputRenderTarget=null;for(let t=0;t{})),this.onApplyObservable.add((e=>{r._scene.activeCamera&&r._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",r._multiviewTexture)}))}}function fn(e,t){const i=t.vrCameraMetrics||ws.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new et.L(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new W.uq,e._rigCameras[0]._cameraRigParams.vrHMatrix=i.leftHMatrix,e._rigCameras[0]._cameraRigParams.vrPreViewMatrix=i.leftPreViewMatrix,e._rigCameras[0].getProjectionMatrix=e._rigCameras[0]._getVRProjectionMatrix,e._rigCameras[1]._cameraRigParams.vrMetrics=i,e._rigCameras[1].viewport=new et.L(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new W.uq,e._rigCameras[1]._cameraRigParams.vrHMatrix=i.rightHMatrix,e._rigCameras[1]._cameraRigParams.vrPreViewMatrix=i.rightPreViewMatrix,e._rigCameras[1].getProjectionMatrix=e._rigCameras[1]._getVRProjectionMatrix,i.multiviewEnabled&&(e.getScene().getEngine().getCaps().multiview?(e._useMultiviewToSingleView=!0,e._rigPostProcess=new dn("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(Z.V.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new Ns("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new Ns("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))}Ze.b.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",((e,t)=>()=>new pn(e,0,0,1,W.Pq.Zero(),t)));class pn extends is{constructor(e,t,i,r,s,n,o=!0,a=ws.GetDefault()){super(e,t,i,r,s,n),this._setRigMode=e=>fn(this,e),a.compensateDistortion=o,this.setCameraRigMode(rt.RIG_MODE_VR,{vrCameraMetrics:a}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}Ze.b.AddNodeConstructor("VRDeviceOrientationFreeCamera",((e,t)=>()=>new _n(e,W.Pq.Zero(),t)));class _n extends rs{constructor(e,t,i,r=!0,s=ws.GetDefault()){super(e,t,i),this._setRigMode=e=>fn(this,e),s.compensateDistortion=r,this.setCameraRigMode(rt.RIG_MODE_VR,{vrCameraMetrics:s})}getClassName(){return"VRDeviceOrientationFreeCamera"}}Ze.b.AddNodeConstructor("VRDeviceOrientationGamepadCamera",((e,t)=>()=>new mn(e,W.Pq.Zero(),t)));class mn extends _n{constructor(e,t,i,r=!0,s=ws.GetDefault()){super(e,t,i,r,s),this._setRigMode=e=>fn(this,e),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}var gn=i(69648);class vn{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,r,s){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&(-1!==t.prePassRenderer.getIndex(2)||-1!==t.prePassRenderer.getIndex(11))){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=r.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());const s=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==s.frameId&&(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=r.clone()}}}class xn{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)-1===this._keys.indexOf(e)&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;tthis._setDefaultValue(e)))}_setDefaultValue(e){const t=this._externalProperties?.[e]?.type??typeof this[e],i=this._externalProperties?.[e]?.default;switch(t){case"number":this[e]=i??0;break;case"string":this[e]=i??"";break;default:this[e]=i??!1}}toString(){let e="";for(let t=0;tthis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const i=this._mesh.getScene();for(let e=0;e0&&(r.computeBonesUsingShaders=!1)}}else{const t=this._defines[this._currentRank];if(t)for(let i=0;ithis._handlePluginEvent(e,t),this._plugins.push(e),this._plugins.sort(((e,t)=>e.priority-t.priority)),this._codeInjectionPoints={};const i={};i[En._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const e of this._plugins)e.collectDefines(i),this._collectPointNames("vertex",e.getCustomCode("vertex",this._material.shaderLanguage)),this._collectPointNames("fragment",e.getCustomCode("fragment",this._material.shaderLanguage));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){-1===this._activePlugins.indexOf(e)&&(this._activePlugins.push(e),this._activePlugins.sort(((e,t)=>e.priority-t.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(((e,t)=>e.priority-t.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&&e.uniforms.push(...this._uniformList),this._samplerList.length>0&&e.samplers.push(...this._samplerList),this._uboList.length>0&&e.uniformBuffersNames.push(...this._uboList),e.customCode=this._injectCustomCode(e,e.customCode);break}case 8:{const e=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];const i=1===this._material.shaderLanguage;for(const t of this._plugins){const r=t.getUniforms(this._material.shaderLanguage);if(r){if(r.ubo)for(const t of r.ubo){if(t.size&&t.type){const r=t.arraySize??0;if(e.ubo.addUniform(t.name,t.size,r),i){let e;switch(t.type){case"mat4":e="mat4x4f";break;case"float":e="f32";break;default:e=`${t.type}f`}this._uboDeclaration+=`uniform ${t.name}: ${e}${r>0?`[${r}]`:""};\n`}else this._uboDeclaration+=`${t.type} ${t.name}${r>0?`[${r}]`:""};\n`}this._uniformList.push(t.name)}r.vertex&&(this._vertexDeclaration+=r.vertex+"\n"),r.fragment&&(this._fragmentDeclaration+=r.fragment+"\n")}t.getSamplers(this._samplerList),t.getUniformBuffersNames(this._uboList)}break}}}_collectPointNames(e,t){if(t)for(const i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,r)=>{t&&(r=t(i,r)),this._uboDeclaration&&(r=r.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(r=r.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(r=r.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const s=this._codeInjectionPoints?.[i];if(!s)return r;let n=null;for(let t in s){let s="";for(const r of this._activePlugins){let o=r.getCustomCode(i,this._material.shaderLanguage)?.[t];if(o){if(r.resolveIncludes){if(null===n){const t=0;n={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:Cs.l.GetShadersRepository(t),includesShadersStore:Cs.l.GetIncludesShadersStore(t),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}n.isFragment="fragment"===i,(0,Cn.Iq)(o,n,(e=>o=e))}s+=o+"\n"}}if(s.length>0)if("!"===t.charAt(0)){t=t.substring(1);let e="g";if("!"===t.charAt(0))e="",t=t.substring(1);else{const i=yn.exec(t);i&&i.length>=2&&(e=i[1],t=t.substring(e.length+1))}e.indexOf("g")<0&&(e+="g");const i=r,n=new RegExp(t,e);let o=n.exec(i);for(;null!==o;){let e=s;for(let t=0;t{On()}));const Pn=[];let An=!1,Rn=null;function In(e,t){An||(Rn=Vt.OnEventObservable.add((e=>{for(const[,t]of Pn)t(e)}),1),An=!0);const i=Pn.filter((([t,i])=>t===e));i.length>0?i[0][1]=t:Pn.push([e,t])}function Mn(e){for(let t=0;t{e.pluginManager=void 0}))),this._pluginDefineNames=r,this._pluginManager=e.pluginManager,s&&this._pluginManager._addPlugin(this),n&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,r){return!0}hardBindForSubMesh(e,t,i,r){}bindForSubMesh(e,t,i,r){}dispose(e){}getCustomCode(e,t=0){return null}collectDefines(e){if(this._pluginDefineNames)for(const t of Object.keys(this._pluginDefineNames)){if("_"===t[0])continue;const i=typeof this._pluginDefineNames[t];e[t]={type:"number"===i?"number":"string"===i?"string":"boolean"===i?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(e=0){return{}}copyTo(e){it.p.Clone((()=>e),this)}serialize(){return it.p.Serialize(this)}parse(e,t,i){it.p.Parse((()=>this),e,t,i)}}(0,je.Cg)([(0,$e.lK)()],Dn.prototype,"name",void 0),(0,je.Cg)([(0,$e.lK)()],Dn.prototype,"priority",void 0),(0,je.Cg)([(0,$e.lK)()],Dn.prototype,"resolveIncludes",void 0),(0,je.Cg)([(0,$e.lK)()],Dn.prototype,"registerForExtraEvents",void 0),(0,X.Y5)("BABYLON.MaterialPluginBase",Dn);class wn extends xn{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class Nn extends Dn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"DetailMap",140,new wn,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=Vt.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&&Sn.DetailTextureEnabled&&!this._texture.isReady())}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;const i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&Sn.DetailTextureEnabled&&this._isEnabled?((0,Bt.YT)(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&&Sn.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),(0,Bt.mA)(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&Sn.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){e&&this._texture?.dispose()}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}(0,je.Cg)([(0,$e.uM)("detailTexture"),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Nn.prototype,"texture",void 0),(0,je.Cg)([(0,$e.lK)()],Nn.prototype,"diffuseBlendLevel",void 0),(0,je.Cg)([(0,$e.lK)()],Nn.prototype,"roughnessBlendLevel",void 0),(0,je.Cg)([(0,$e.lK)()],Nn.prototype,"bumpLevel",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Nn.prototype,"normalBlendMethod",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Nn.prototype,"isEnabled",void 0);var Fn,Ln=i(57551);!function(e){e[e.Zero=0]="Zero",e[e.One=1]="One",e[e.MaxViewZ=2]="MaxViewZ"}(Fn||(Fn={}));class Bn{static CreateConfiguration(e){return Bn._Configurations[e]={defines:{},previousWorldMatrices:{},previousViewProjection:W.uq.Zero(),currentViewProjection:W.uq.Zero(),previousBones:{},lastUpdateFrameId:-1,excludedSkinnedMesh:[]},Bn._Configurations[e]}static DeleteConfiguration(e){delete Bn._Configurations[e]}static GetConfiguration(e){return Bn._Configurations[e]}static AddUniformsAndSamplers(e,t){e.push("previousWorld","previousViewProjection","mPreviousBones")}static MarkAsDirty(e,t){for(const i of t)if(i.subMeshes)for(const t of i.subMeshes)t._removeDrawWrapper(e)}static PrepareDefines(e,t,i){if(!i._arePrePassDirty)return;const r=Bn._Configurations[e];if(!r)return;i.PREPASS=!0,i.PREPASS_COLOR=!1,i.PREPASS_COLOR_INDEX=-1;let s=0;for(let e=0;e{this._markAllSubMeshesAsImageProcessingDirty()}))))}get isPrePassCapable(){return!this.disableDepthWrite}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}get canRenderToMRT(){return!0}constructor(e,t,i=!1){super(e,t,void 0,i||Un.ForceGLSL),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 H.v9(0,0,0),this.diffuseColor=new H.v9(1,1,1),this.specularColor=new H.v9(1,1,1),this.emissiveColor=new H.v9(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._shadersLoaded=!1,this._renderTargets=new Qe.L(16),this._worldViewProjectionMatrix=W.uq.Zero(),this._globalAmbientColor=new H.v9(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new Nn(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new vn,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),Un.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),Un.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!!(Un.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||!!(Un.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled)}needAlphaTesting(){return!!this._forceAlphaTest||this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===Vt.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==Vt.MATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,r=!1){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===r)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new kn(this._eventInfo.defineNames));const n=this.getScene(),o=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const a=n.getEngine();o._needNormals=(0,Bt.az)(n,e,o,!0,this._maxSimultaneousLights,this._disableLighting),(0,Bt.VO)(n,o);const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if((0,Bt.N4)(n,o,this.canRenderToMRT&&!l),(0,Bt.Nc)(n,o,l),Bn.PrepareDefines(a.currentRenderPassId,e,o),o._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,o._needUVs=!1;for(let e=1;e<=6;++e)o["MAINUV"+e]=!1;if(n.texturesEnabled){if(o.DIFFUSEDIRECTUV=0,o.BUMPDIRECTUV=0,o.AMBIENTDIRECTUV=0,o.OPACITYDIRECTUV=0,o.EMISSIVEDIRECTUV=0,o.SPECULARDIRECTUV=0,o.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&Un.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;(0,Bt.YT)(this._diffuseTexture,o,"DIFFUSE")}else o.DIFFUSE=!1;if(this._ambientTexture&&Un.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;(0,Bt.YT)(this._ambientTexture,o,"AMBIENT")}else o.AMBIENT=!1;if(this._opacityTexture&&Un.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;(0,Bt.YT)(this._opacityTexture,o,"OPACITY"),o.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else o.OPACITY=!1;if(this._reflectionTexture&&Un.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(o._needNormals=!0,o.REFLECTION=!0,o.ROUGHNESS=this._roughness>0,o.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,o.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===vi.g.INVCUBIC_MODE,o.REFLECTIONMAP_3D=this._reflectionTexture.isCube,o.REFLECTIONMAP_OPPOSITEZ=o.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,o.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case vi.g.EXPLICIT_MODE:o.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case vi.g.PLANAR_MODE:o.setReflectionMode("REFLECTIONMAP_PLANAR");break;case vi.g.PROJECTION_MODE:o.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case vi.g.SKYBOX_MODE:o.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case vi.g.SPHERICAL_MODE:o.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case vi.g.EQUIRECTANGULAR_MODE:o.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case vi.g.FIXED_EQUIRECTANGULAR_MODE:o.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case vi.g.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:o.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case vi.g.CUBIC_MODE:case vi.g.INVCUBIC_MODE:default:o.setReflectionMode("REFLECTIONMAP_CUBIC")}o.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else o.REFLECTION=!1,o.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&Un.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;(0,Bt.YT)(this._emissiveTexture,o,"EMISSIVE")}else o.EMISSIVE=!1;if(this._lightmapTexture&&Un.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;(0,Bt.YT)(this._lightmapTexture,o,"LIGHTMAP"),o.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,o.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else o.LIGHTMAP=!1;if(this._specularTexture&&Un.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;(0,Bt.YT)(this._specularTexture,o,"SPECULAR"),o.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else o.SPECULAR=!1;if(n.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&Un.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;(0,Bt.YT)(this._bumpTexture,o,"BUMP"),o.PARALLAX=this._useParallax,o.PARALLAX_RHS=n.useRightHandedSystem,o.PARALLAXOCCLUSION=this._useParallaxOcclusion,o.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else o.BUMP=!1,o.PARALLAX=!1,o.PARALLAX_RHS=!1,o.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&Un.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;o._needUVs=!0,o.REFRACTION=!0,o.REFRACTIONMAP_3D=this._refractionTexture.isCube,o.RGBDREFRACTION=this._refractionTexture.isRGBD,o.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize}else o.REFRACTION=!1;o.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else o.DIFFUSE=!1,o.AMBIENT=!1,o.OPACITY=!1,o.REFLECTION=!1,o.EMISSIVE=!1,o.LIGHTMAP=!1,o.BUMP=!1,o.REFRACTION=!1;o.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),o.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,o.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,o.SPECULAROVERALPHA=this._useSpecularOverAlpha,o.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,o.ALPHATEST_AFTERALLALPHACOMPUTATIONS=null!==this.transparencyMode,o.ALPHABLEND=null===this.transparencyMode||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=o,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(o._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(o),o.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,o.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}o._areFresnelDirty&&(Un.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(o.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,o.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,o.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,o.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,o.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,o.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,o._needNormals=!0,o.FRESNEL=!0):o.FRESNEL=!1),(0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,o,this._applyDecalMapAfterDetailMap),(0,Bt.OR)(n,a,this,o,r,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=o,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),(0,Bt.qB)(e,o,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let h=!1;if(o.isDirty){const r=o._areLightsDisposed;o.markAsProcessed();const s=new Tn;o.REFLECTION&&s.addFallback(0,"REFLECTION"),o.SPECULAR&&s.addFallback(0,"SPECULAR"),o.BUMP&&s.addFallback(0,"BUMP"),o.PARALLAX&&s.addFallback(1,"PARALLAX"),o.PARALLAX_RHS&&s.addFallback(1,"PARALLAX_RHS"),o.PARALLAXOCCLUSION&&s.addFallback(0,"PARALLAXOCCLUSION"),o.SPECULAROVERALPHA&&s.addFallback(0,"SPECULAROVERALPHA"),o.FOG&&s.addFallback(1,"FOG"),o.POINTSIZE&&s.addFallback(0,"POINTSIZE"),o.LOGARITHMICDEPTH&&s.addFallback(0,"LOGARITHMICDEPTH"),(0,Bt.c4)(o,s,this._maxSimultaneousLights),o.SPECULARTERM&&s.addFallback(0,"SPECULARTERM"),o.DIFFUSEFRESNEL&&s.addFallback(1,"DIFFUSEFRESNEL"),o.OPACITYFRESNEL&&s.addFallback(2,"OPACITYFRESNEL"),o.REFLECTIONFRESNEL&&s.addFallback(3,"REFLECTIONFRESNEL"),o.EMISSIVEFRESNEL&&s.addFallback(4,"EMISSIVEFRESNEL"),o.FRESNEL&&s.addFallback(4,"FRESNEL"),o.MULTIVIEW&&s.addFallback(0,"MULTIVIEW");const l=[st.R.PositionKind];o.NORMAL&&l.push(st.R.NormalKind),o.TANGENT&&l.push(st.R.TangentKind);for(let e=1;e<=6;++e)o["UV"+e]&&l.push(`uv${1===e?"":e}`);o.VERTEXCOLOR&&l.push(st.R.ColorKind),(0,Bt.ni)(l,e,o,s),(0,Bt.ER)(l,o),(0,Bt.IF)(l,e,o),(0,Bt.J2)(l,e,o);let c="default";const u=["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"],d=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],f=["Material","Scene","Mesh"],p={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:o.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=s,this._eventInfo.fallbackRank=0,this._eventInfo.defines=o,this._eventInfo.uniforms=u,this._eventInfo.attributes=l,this._eventInfo.samplers=d,this._eventInfo.uniformBuffersNames=f,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=p,this._callbackPluginEventGeneric(128,this._eventInfo),Bn.AddUniformsAndSamplers(u,d),vn.AddUniforms(u),vn.AddSamplers(d),gn.p&&(gn.p.PrepareUniforms(u,o),gn.p.PrepareSamplers(d,o)),(0,Bt.Bb)({uniformsNames:u,uniformBuffersNames:f,samplers:d,defines:o,maxSimultaneousLights:this._maxSimultaneousLights}),(0,Ln.TV)(u);const _={};this.customShaderNameResolve&&(c=this.customShaderNameResolve(c,u,f,d,o,l,_));const m=o.toString(),g=t.effect;let v=n.getEngine().createEffect(c,{attributes:l,uniformsNames:u,uniformBuffersNames:f,samplers:d,defines:m,fallbacks:s,onCompiled:this.onCompiled,onError:this.onError,indexParameters:p,processFinalCode:_.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:o.PREPASS,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,22177)),Promise.resolve().then(i.bind(i,49694))]):await Promise.all([Promise.resolve().then(i.bind(i,35936)),Promise.resolve().then(i.bind(i,85800))]),this._shadersLoaded=!0}},a);if(this._eventInfo.customCode=void 0,v)if(this._onEffectCreatedObservable&&(Vn.effect=v,Vn.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Vn)),this.allowShaderHotSwapping&&g&&!v.isReady()){if(v=g,o.markAsUnprocessed(),h=this.isFrozen,r)return o._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(v,o,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(o._renderId=n.getRenderId(),s._wasPreviouslyReady=!h,s._wasPreviouslyUsingInstances=r,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){const r=this.getScene(),s=i.materialDefines;if(!s)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,r,t,e,this.isFrozen),Bn.Bind(r.getEngine().currentRenderPassId,this._activeEffect,t,e),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),s.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=this._mustRebind(r,n,i,t.visibility);(0,Bt.f$)(t,n);const a=this._uniformBuffer;if(o){if(this.bindViewProjection(n),!a.useUbo||!this.isFrozen||!a.isSync||i._drawWrapper._forceRebindOnNextCall){if(Un.FresnelEnabled&&s.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(a.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),a.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&a.updateColor4("opacityParts",new H.v9(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(a.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),a.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(a.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),a.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(a.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),a.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),r.texturesEnabled){if(this._diffuseTexture&&Un.DiffuseTextureEnabled&&(a.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),(0,Bt.mA)(this._diffuseTexture,a,"diffuse")),this._ambientTexture&&Un.AmbientTextureEnabled&&(a.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),(0,Bt.mA)(this._ambientTexture,a,"ambient")),this._opacityTexture&&Un.OpacityTextureEnabled&&(a.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),(0,Bt.mA)(this._opacityTexture,a,"opacity")),this._hasAlphaChannel()&&a.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&Un.ReflectionTextureEnabled&&(a.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),a.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const e=this._reflectionTexture;a.updateVector3("vReflectionPosition",e.boundingBoxPosition),a.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this._emissiveTexture&&Un.EmissiveTextureEnabled&&(a.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),(0,Bt.mA)(this._emissiveTexture,a,"emissive")),this._lightmapTexture&&Un.LightmapTextureEnabled&&(a.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),(0,Bt.mA)(this._lightmapTexture,a,"lightmap")),this._specularTexture&&Un.SpecularTextureEnabled&&(a.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),(0,Bt.mA)(this._specularTexture,a,"specular")),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&Un.BumpTextureEnabled&&(a.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),(0,Bt.mA)(this._bumpTexture,a,"bump"),r._mirroredCameraPosition?a.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):a.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&Un.RefractionTextureEnabled){let e=1;if(this._refractionTexture.isCube||(a.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(e=this._refractionTexture.depth)),a.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,e,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const e=this._refractionTexture;a.updateVector3("vRefractionPosition",e.boundingBoxPosition),a.updateVector3("vRefractionSize",e.boundingBoxSize)}}}this.pointsCloud&&a.updateFloat("pointSize",this.pointSize),a.updateColor4("vSpecularColor",this.specularColor,this.specularPower),a.updateColor3("vEmissiveColor",Un.EmissiveTextureEnabled?this.emissiveColor:H.v9.BlackReadOnly),a.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),r.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),a.updateColor3("vAmbientColor",this._globalAmbientColor)}r.texturesEnabled&&(this._diffuseTexture&&Un.DiffuseTextureEnabled&&n.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&Un.AmbientTextureEnabled&&n.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&Un.OpacityTextureEnabled&&n.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&Un.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?n.setTexture("reflectionCubeSampler",this._reflectionTexture):n.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&Un.EmissiveTextureEnabled&&n.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&Un.LightmapTextureEnabled&&n.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&Un.SpecularTextureEnabled&&n.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&Un.BumpTextureEnabled&&n.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&Un.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),(0,Ln.gS)(n,this,r),this.bindEyePosition(n)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!o&&this.isFrozen||(r.lightsEnabled&&!this._disableLighting&&(0,Bt.RL)(r,t,n,s,this._maxSimultaneousLights),(r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||s.PREPASS)&&this.bindView(n),(0,Bt.Yy)(r,t,n),s.NUM_MORPH_INFLUENCERS&&(0,Bt.nR)(t,n),s.BAKED_VERTEX_ANIMATION_TEXTURE&&t.bakedVertexAnimationManager?.bind(n,s.INSTANCES),this.useLogarithmicDepth&&(0,Bt.DL)(s,n,r),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),a.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){t&&(this._diffuseTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._specularTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._refractionTexture?.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const r=it.p.Clone((()=>new Un(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return r.name=e,r.id=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}static Parse(e,t,i){const r=it.p.Parse((()=>new Un(e.name,t)),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),Vt._ParsePlugins(e,r,t,i),r}static get DiffuseTextureEnabled(){return Sn.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){Sn.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return Sn.DetailTextureEnabled}static set DetailTextureEnabled(e){Sn.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return Sn.AmbientTextureEnabled}static set AmbientTextureEnabled(e){Sn.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return Sn.OpacityTextureEnabled}static set OpacityTextureEnabled(e){Sn.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return Sn.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){Sn.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return Sn.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){Sn.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return Sn.SpecularTextureEnabled}static set SpecularTextureEnabled(e){Sn.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return Sn.BumpTextureEnabled}static set BumpTextureEnabled(e){Sn.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return Sn.LightmapTextureEnabled}static set LightmapTextureEnabled(e){Sn.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return Sn.RefractionTextureEnabled}static set RefractionTextureEnabled(e){Sn.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return Sn.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){Sn.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return Sn.FresnelEnabled}static set FresnelEnabled(e){Sn.FresnelEnabled=e}}Un.ForceGLSL=!1,(0,je.Cg)([(0,$e.uM)("diffuseTexture")],Un.prototype,"_diffuseTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesAndMiscDirty")],Un.prototype,"diffuseTexture",void 0),(0,je.Cg)([(0,$e.uM)("ambientTexture")],Un.prototype,"_ambientTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"ambientTexture",void 0),(0,je.Cg)([(0,$e.uM)("opacityTexture")],Un.prototype,"_opacityTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesAndMiscDirty")],Un.prototype,"opacityTexture",void 0),(0,je.Cg)([(0,$e.uM)("reflectionTexture")],Un.prototype,"_reflectionTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"reflectionTexture",void 0),(0,je.Cg)([(0,$e.uM)("emissiveTexture")],Un.prototype,"_emissiveTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"emissiveTexture",void 0),(0,je.Cg)([(0,$e.uM)("specularTexture")],Un.prototype,"_specularTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"specularTexture",void 0),(0,je.Cg)([(0,$e.uM)("bumpTexture")],Un.prototype,"_bumpTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"bumpTexture",void 0),(0,je.Cg)([(0,$e.uM)("lightmapTexture")],Un.prototype,"_lightmapTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"lightmapTexture",void 0),(0,je.Cg)([(0,$e.uM)("refractionTexture")],Un.prototype,"_refractionTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"refractionTexture",void 0),(0,je.Cg)([(0,$e.jT)("ambient")],Un.prototype,"ambientColor",void 0),(0,je.Cg)([(0,$e.jT)("diffuse")],Un.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.jT)("specular")],Un.prototype,"specularColor",void 0),(0,je.Cg)([(0,$e.jT)("emissive")],Un.prototype,"emissiveColor",void 0),(0,je.Cg)([(0,$e.lK)()],Un.prototype,"specularPower",void 0),(0,je.Cg)([(0,$e.lK)("useAlphaFromDiffuseTexture")],Un.prototype,"_useAlphaFromDiffuseTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesAndMiscDirty")],Un.prototype,"useAlphaFromDiffuseTexture",void 0),(0,je.Cg)([(0,$e.lK)("useEmissiveAsIllumination")],Un.prototype,"_useEmissiveAsIllumination",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"useEmissiveAsIllumination",void 0),(0,je.Cg)([(0,$e.lK)("linkEmissiveWithDiffuse")],Un.prototype,"_linkEmissiveWithDiffuse",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"linkEmissiveWithDiffuse",void 0),(0,je.Cg)([(0,$e.lK)("useSpecularOverAlpha")],Un.prototype,"_useSpecularOverAlpha",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"useSpecularOverAlpha",void 0),(0,je.Cg)([(0,$e.lK)("useReflectionOverAlpha")],Un.prototype,"_useReflectionOverAlpha",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"useReflectionOverAlpha",void 0),(0,je.Cg)([(0,$e.lK)("disableLighting")],Un.prototype,"_disableLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],Un.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.lK)("useObjectSpaceNormalMap")],Un.prototype,"_useObjectSpaceNormalMap",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"useObjectSpaceNormalMap",void 0),(0,je.Cg)([(0,$e.lK)("useParallax")],Un.prototype,"_useParallax",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"useParallax",void 0),(0,je.Cg)([(0,$e.lK)("useParallaxOcclusion")],Un.prototype,"_useParallaxOcclusion",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"useParallaxOcclusion",void 0),(0,je.Cg)([(0,$e.lK)()],Un.prototype,"parallaxScaleBias",void 0),(0,je.Cg)([(0,$e.lK)("roughness")],Un.prototype,"_roughness",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"roughness",void 0),(0,je.Cg)([(0,$e.lK)()],Un.prototype,"indexOfRefraction",void 0),(0,je.Cg)([(0,$e.lK)()],Un.prototype,"invertRefractionY",void 0),(0,je.Cg)([(0,$e.lK)()],Un.prototype,"alphaCutOff",void 0),(0,je.Cg)([(0,$e.lK)("useLightmapAsShadowmap")],Un.prototype,"_useLightmapAsShadowmap",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"useLightmapAsShadowmap",void 0),(0,je.Cg)([(0,$e.Y9)("diffuseFresnelParameters")],Un.prototype,"_diffuseFresnelParameters",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsFresnelDirty")],Un.prototype,"diffuseFresnelParameters",void 0),(0,je.Cg)([(0,$e.Y9)("opacityFresnelParameters")],Un.prototype,"_opacityFresnelParameters",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsFresnelAndMiscDirty")],Un.prototype,"opacityFresnelParameters",void 0),(0,je.Cg)([(0,$e.Y9)("reflectionFresnelParameters")],Un.prototype,"_reflectionFresnelParameters",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsFresnelDirty")],Un.prototype,"reflectionFresnelParameters",void 0),(0,je.Cg)([(0,$e.Y9)("refractionFresnelParameters")],Un.prototype,"_refractionFresnelParameters",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsFresnelDirty")],Un.prototype,"refractionFresnelParameters",void 0),(0,je.Cg)([(0,$e.Y9)("emissiveFresnelParameters")],Un.prototype,"_emissiveFresnelParameters",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsFresnelDirty")],Un.prototype,"emissiveFresnelParameters",void 0),(0,je.Cg)([(0,$e.lK)("useReflectionFresnelFromSpecular")],Un.prototype,"_useReflectionFresnelFromSpecular",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsFresnelDirty")],Un.prototype,"useReflectionFresnelFromSpecular",void 0),(0,je.Cg)([(0,$e.lK)("useGlossinessFromSpecularMapAlpha")],Un.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"useGlossinessFromSpecularMapAlpha",void 0),(0,je.Cg)([(0,$e.lK)("maxSimultaneousLights")],Un.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],Un.prototype,"maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.lK)("invertNormalMapX")],Un.prototype,"_invertNormalMapX",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"invertNormalMapX",void 0),(0,je.Cg)([(0,$e.lK)("invertNormalMapY")],Un.prototype,"_invertNormalMapY",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"invertNormalMapY",void 0),(0,je.Cg)([(0,$e.lK)("twoSidedLighting")],Un.prototype,"_twoSidedLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"twoSidedLighting",void 0),(0,je.Cg)([(0,$e.lK)("applyDecalMapAfterDetailMap")],Un.prototype,"_applyDecalMapAfterDetailMap",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],Un.prototype,"applyDecalMapAfterDetailMap",void 0),(0,X.Y5)("BABYLON.StandardMaterial",Un),oi.Z.DefaultMaterialFactory=e=>new Un("default material",e),Ls.ThinEngine.prototype.createDynamicTexture=function(e,t,i,r){const s=new Fs.h(this,4);return s.baseWidth=e,s.baseHeight=t,i&&(e=this.needPOTTextures?(0,Gs.R)(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?(0,Gs.R)(t,this._caps.maxTextureSize):t),s.width=e,s.height=t,s.isReady=!1,s.generateMipMaps=i,s.samplingMode=r,this.updateTextureSamplingMode(r,s),this._internalTexturesCache.push(s),s},Ls.ThinEngine.prototype.updateDynamicTexture=function(e,t,i,r=!1,s,n=!1,o=!1){if(!e)return;const a=this._gl,l=a.TEXTURE_2D,h=this._bindTextureDirectly(l,e,!0,n);this._unpackFlipY(void 0===i?e.invertY:i),r&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(s||e.format),d=this._getRGBABufferInternalSizedFormat(e.type,u);a.texImage2D(l,0,d,u,c,t),e.generateMipMaps&&a.generateMipmap(l),h||this._bindTextureDirectly(l,null),r&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),s&&(e.format=s),e._dynamicTextureSource=t,e._premulAlpha=r,e.invertY=i||!1,e.isReady=!0};class Gn extends vi.g{constructor(e,t,i,r=!1,s=3,n=5,o){const a=!i||i._isScene;super(null,a?i:i?.scene,a?!r:i,o,s,void 0,void 0,void 0,void 0,n),this.name=e,this.wrapU=vi.g.CLAMP_ADDRESSMODE,this.wrapV=vi.g.CLAMP_ADDRESSMODE,this._generateMipMaps=r;const l=this._getEngine();if(!l)return;if(t.getContext)this._canvas=t,this._ownCanvas=!1,this._texture=l.createDynamicTexture(this._canvas.width,this._canvas.height,r,s);else{this._canvas=l.createCanvas(1,1),this._ownCanvas=!0;const e=t;e.width||0===e.width?this._texture=l.createDynamicTexture(e.width,e.height,r,s):this._texture=l.createDynamicTexture(t,t,r,s)}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,void 0===e||e,t,this._format||void 0,void 0,i)}drawText(e,t,i,r,s,n,o,a=!0){const l=this.getSize();if(n&&(this._context.fillStyle=n,this._context.fillRect(0,0,l.width,l.height)),this._context.font=r,null==t){const i=this._context.measureText(e);t=(l.width-i.width)/2}if(null==i){const e=parseInt(r.replace(/\D/g,""));i=l.height/2+e/3.65}this._context.fillStyle=s||"",this._context.fillText(e,t,i),a&&this.update(o)}dispose(){super.dispose(),this._ownCanvas&&this._canvas?.remove?.(),this._canvas=null,this._context=null}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Gn(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()&&Z.V.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return Gn._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return void 0!==e.toDataURL}_rebuild(){this.update()}}class zn{get isFixedFoveationSupported(){return"XRWebGLLayer"==this.layerType&&"number"==typeof this.layer.fixedFoveation}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){if(this.isFixedFoveationSupported){const t=Math.max(0,Math.min(1,e||0));this.layer.fixedFoveation=t}}createRenderTargetTextureProvider(e){return this._rttWrapper=this._createRenderTargetTextureProvider(e),this._rttWrapper}dispose(){this._rttWrapper&&(this._rttWrapper.dispose(),this._rttWrapper=null)}constructor(e,t,i,r,s){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this._createRenderTargetTextureProvider=s,this._rttWrapper=null}}class Wn{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}_createInternalTexture(e,t){const i=new Fs.h(this._engine,0,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new Us.d(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,r,s,n){if(!this._engine)throw new Error("Engine is disposed");const o={width:e,height:t},a=n?new hn(this._scene,o):new ln.$("XR renderTargetTexture",o,this._scene),l=a.renderTarget;if(l._samples=a.samples,!i&&r||(l._framebuffer=i),r)if(n)l._colorTextureArray=r;else{const e=this._createInternalTexture(o,r);l.setTexture(e,0),a._texture=e}return s&&(n?l._depthStencilTextureArray=s:l._depthStencilTexture=this._createInternalTexture(o,s)),a.disableRescaling(),this._renderTargetTextures.push(a),a}_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 Hn extends zn{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new Xn(e.scene,this))),this.layer=e}}class Xn extends Wn{constructor(e,t){super(e,t),this.layerWrapper=t,this._layer=t.layer,this._framebufferDimensions={framebufferWidth:this._layer.framebufferWidth,framebufferHeight:this._layer.framebufferHeight}}trySetViewportForView(e,t){const i=this._layer.getViewport(t);if(!i)return!1;const r=this._framebufferDimensions.framebufferWidth,s=this._framebufferDimensions.framebufferHeight;return e.x=i.x/r,e.y=i.y/s,e.width=i.width/r,e.height=i.height/s,!0}getRenderTargetTextureForEye(e){const t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,r=this._layer.framebuffer;return this._rtt&&t===this._framebufferDimensions.framebufferWidth&&i===this._framebufferDimensions.framebufferHeight&&r===this._framebuffer||(this._rtt=this._createRenderTargetTexture(t,i,r),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=r),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class qn{static GetDefaults(e){const t=new qn;return t.canvasOptions={antialias:!0,depth:!0,stencil:!e||e.isStencilEnable,alpha:!0,framebufferScaleFactor:1},t.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",t}}class Yn{constructor(e,t=qn.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new z.cP,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{const e=document.createElement("canvas");e.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(e)}e.onXRSessionInit.add((()=>{this._addCanvas()})),e.onXRSessionEnded.add((()=>{this._removeCanvas()})),this._makeCanvasCompatibleAsync()}dispose(){this._removeCanvas(),this._setManagedOutputCanvas(null),this.onXRLayerInitObservable.clear()}_makeCanvasCompatibleAsync(){this._canvasCompatiblePromise=new Promise(((e,t)=>{try{this.canvasContext&&this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then((()=>{e()}),(()=>{Ue.S0.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly."),e()})):e()}catch(e){t(e)}}))}async initializeXRLayerAsync(e){const t=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new Hn(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this._canvasCompatiblePromise.then((()=>{}),(()=>{})).then((()=>t()))}_addCanvas(){this._canvas&&this._engine&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce((()=>{this._setCanvasSize(!0)}))}_removeCanvas(){this._canvas&&this._engine&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)}_setCanvasSize(e=!0,t=this._xrLayerWrapper){this._canvas&&this._engine&&(e?t&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=t.getWidth()+"px",this._canvas.style.height=t.getHeight()+"px"):this._engine.setSize(t.getWidth(),t.getHeight())):this._originalCanvasSize&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=this._originalCanvasSize.width+"px",this._canvas.style.height=this._originalCanvasSize.height+"px"):this._engine.setSize(this._originalCanvasSize.width,this._originalCanvasSize.height)))}_setManagedOutputCanvas(e){this._removeCanvas(),e?(this._originalCanvasSize={width:e.offsetWidth,height:e.offsetHeight},this._canvas=e,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)}}class Kn extends zn{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new jn(e,this))),this.layer=e}}class jn extends Wn{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 $n{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 Qn{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 z.cP,this.onXRReferenceSpaceChanged=new z.cP,this.onXRSessionEnded=new z.cP,this.onXRSessionInit=new z.cP,this.onXRReferenceSpaceInitialized=new z.cP,this.onXRReady=new z.cP,this.inXRFrameLoop=!1,this.inXRSession=!1,this._worldScalingFactor=1,this.onWorldScaleFactorChangedObservable=new z.cP(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(){this.inXRSession&&this.exitXRAsync(),this.onXRReady.clear(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),this.onWorldScaleFactorChangedObservable.clear(),this._engine?.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}async exitXRAsync(){if(this.session&&this.inXRSession){this.inXRSession=!1;try{return await this.session.end()}catch{Z.V.Warn("Could not end XR session.")}}return Promise.resolve()}trySetViewportForView(e,t){return this._baseLayerRTTProvider?.trySetViewportForView(e,t)||!1}getRenderTargetTextureForEye(e){return this._baseLayerRTTProvider?.getRenderTargetTextureForEye(e)||null}getRenderTargetTextureForView(e){return this._baseLayerRTTProvider?.getRenderTargetTextureForView(e)||null}getWebXRRenderTarget(e){const t=this.scene.getEngine();return this._xrNavigator.xr.native?new $n(this):((e=e||qn.GetDefaults(t)).canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new Yn(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((t=>(this.session=t,this._sessionMode=e,this.inXRSession=!0,this.onXRSessionInit.notifyObservers(t),this.session.addEventListener("end",(()=>{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&&this._baseLayerRTTProvider?.dispose(),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null}),{once:!0}),this.session)))}isSessionSupportedAsync(e){return Qn.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){this.inXRSession&&this._engine&&(this._engine.customAnimationFrameRequester={requestAnimationFrame:e=>this.session.requestAnimationFrame(e),renderFunction:(e,t)=>{if(this.inXRSession&&this._engine&&(this.currentFrame=t,this.currentTimestamp=e,t)){this.inXRFrameLoop=!0;const e=this._baseLayerRTTProvider?.getFramebufferDimensions()||null;this._engine.framebufferDimensionsObject!==e&&(this._engine.framebufferDimensionsObject=e),this.onXRFrameObservable.notifyObservers(t),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1}}},this._engine.framebufferDimensionsObject=this._baseLayerRTTProvider?.getFramebufferDimensions()||null,this.onXRFrameObservable.addOnce((()=>{this.onXRReady.notifyObservers(this)})),"undefined"!=typeof window&&window.cancelAnimationFrame&&window.cancelAnimationFrame(this._engine._frameHandler),this._engine._renderLoop())}setReferenceSpaceTypeAsync(e="local-floor"){return this.session.requestReferenceSpace(e).then((e=>e),(e=>(Z.V.Error("XR.requestReferenceSpace failed for the following reason: "),Z.V.Error(e),Z.V.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then((e=>{const t=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(t)}),(e=>{throw Z.V.Error(e),'XR initialization failed: required "viewer" reference space type not supported.'}))))).then((e=>this.session.requestReferenceSpace("viewer").then((t=>(this.viewerReferenceSpace=t,e))))).then((e=>(this.referenceSpace=this.baseReferenceSpace=e,this.onXRReferenceSpaceInitialized.notifyObservers(e),this.referenceSpace)))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){this.isNative&&this._baseLayerRTTProvider?.dispose(),this._baseLayerWrapper=e,this._baseLayerRTTProvider=this._baseLayerWrapper?.createRenderTargetTextureProvider(this)||null}_getBaseLayerWrapper(){return this._baseLayerWrapper}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new Kn(e.baseLayer):new Hn(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((e=>{const t=void 0===e||e;return Promise.resolve(t)})).catch((e=>(Z.V.Warn(e),Promise.resolve(!1)))):Promise.resolve(!1)}get isNative(){return this._xrNavigator.xr.native??!1}get currentFrameRate(){return this.session?.frameRate}get supportedFrameRates(){return this.session?.supportedFrameRates}updateTargetFrameRate(e){return this.session.updateTargetFrameRate(e)}runInXRFrame(e,t=!0){this.inXRFrameLoop?e():!this.inXRSession&&t||this.onXRFrameObservable.addOnce(e)}get isFixedFoveationSupported(){return this._baseLayerWrapper?.isFixedFoveationSupported||!1}get fixedFoveation(){return this._baseLayerWrapper?.fixedFoveation||null}set fixedFoveation(e){const t=Math.max(0,Math.min(1,e||0));this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=t)}get enabledFeatures(){return this.session?.enabledFeatures??null}}Yt._GroundMeshParser=(e,t)=>Zn.Parse(e,t);class Zn extends Yt{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);this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){const i=this.getWorldMatrix(),r=W.AA.Matrix[5];i.invertToRef(r);const s=W.AA.Vector3[8];if(W.Pq.TransformCoordinatesFromFloatsToRef(e,0,t,r,s),e=s.x,t=s.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const n=this._getFacetAt(e,t),o=-(n.x*e+n.z*t+n.w)/n.y;return W.Pq.TransformCoordinatesFromFloatsToRef(0,o,0,i,s),s.y}getNormalAtCoordinates(e,t){const i=new W.Pq(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const r=this.getWorldMatrix(),s=W.AA.Matrix[5];r.invertToRef(s);const n=W.AA.Vector3[8];if(W.Pq.TransformCoordinatesFromFloatsToRef(e,0,t,s,n),e=n.x,t=n.z,ethis._maxX||tthis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const o=this._getFacetAt(e,t);return W.Pq.TransformNormalFromFloatsToRef(o.x,o.y,o.z,r,i),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){const i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),r=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),s=this._heightQuads[r*this._subdivisionsX+i];let n;return n=te.maxHeight){h=!0;const t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(n=0;n<=e.subdivisions;n++)for(o=0;o<=e.subdivisions;o++){const t=new W.Pq(o*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-n)*e.height/e.subdivisions-e.height/2),c=4*(((t.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(t.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth);let u=e.buffer[c]/255,d=e.buffer[c+1]/255,f=e.buffer[c+2]/255;const p=e.buffer[c+3]/255;h&&(u=1-u,d=1-d,f=1-f);const _=u*a.r+d*a.g+f*a.b;t.y=p>=l?e.minHeight+(e.maxHeight-e.minHeight)*_:e.minHeight-lt.bH,e.heightBuffer&&(e.heightBuffer[n*(e.subdivisions+1)+o]=t.y),i.push(t.x,t.y,t.z),r.push(0,0,0),s.push(o/e.subdivisions,1-n/e.subdivisions)}for(n=0;n=e.minHeight,c=i[3*s+1]>=e.minHeight,u=i[3*a+1]>=e.minHeight;h&&c&&u&&(t.push(r),t.push(s),t.push(a)),i[3*l+1]>=e.minHeight&&h&&u&&(t.push(l),t.push(r),t.push(a))}bt.ComputeNormals(i,t,r);const c=new bt;return c.indices=t,c.positions=i,c.normals=r,c.uvs=s,c}function io(e,t={},i){const r=new Zn(e,i);return r._setReady(!1),r._subdivisionsX=t.subdivisionsX||t.subdivisions||1,r._subdivisionsY=t.subdivisionsY||t.subdivisions||1,r._width=t.width||1,r._height=t.height||1,r._maxX=r._width/2,r._maxZ=r._height/2,r._minX=-r._maxX,r._minZ=-r._maxZ,Jn(t).applyToMesh(r,t.updatable),r._setReady(!0),r}function ro(e,t,i=null){const r=new Yt(e,i);return eo(t).applyToMesh(r,t.updatable),r}function so(e,t,i={},r=null){const s=i.width||10,n=i.height||10,o=i.subdivisions||1,a=i.minHeight||0,l=i.maxHeight||1,h=i.colorFilter||new H.v9(.3,.59,.11),c=i.alphaFilter||0,u=i.updatable,d=i.onReady;r=r||he.q.LastCreatedScene;const f=new Zn(e,r);let p;f._subdivisionsX=o,f._subdivisionsY=o,f._width=s,f._height=n,f._maxX=f._width/2,f._maxZ=f._height/2,f._minX=-f._maxX,f._minZ=-f._maxZ,f._setReady(!1),i.passHeightBufferInCallback&&(p=new Float32Array((o+1)*(o+1)));const _=(e,t,i)=>{to({width:s,height:n,subdivisions:o,minHeight:a,maxHeight:l,colorFilter:h,buffer:e,bufferWidth:t,bufferHeight:i,alphaFilter:c,heightBuffer:p}).applyToMesh(f,u),d&&d(f,p),f._setReady(!0)};if("string"==typeof t){const e=e=>{const t=e.width,i=e.height;if(r.isDisposed)return;const s=r?.getEngine().resizeImageBitmap(e,t,i);_(s,t,i)};Ue.S0.LoadImage(t,e,i.onError?i.onError:()=>{},r.offlineProvider)}else _(t.data,t.width,t.height);return f}const no={CreateGround:io,CreateGroundFromHeightMap:so,CreateTiledGround:ro};function oo(e){const t=[],i=[],r=[],s=[],n=e.diameter||1,o=e.thickness||.5,a=0|(e.tessellation||16),l=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE,h=a+1;for(let e=0;e<=a;e++){const l=e/a,c=e*Math.PI*2/a-Math.PI/2,u=W.uq.Translation(n/2,0,0).multiply(W.uq.RotationY(c));for(let n=0;n<=a;n++){const c=1-n/a,d=n*Math.PI*2/a+Math.PI,f=Math.cos(d),p=Math.sin(d);let _=new W.Pq(f,p,0),m=_.scale(o/2);const g=new W.I9(l,c);m=W.Pq.TransformCoordinates(m,u),_=W.Pq.TransformNormal(_,u),i.push(m.x,m.y,m.z),r.push(_.x,_.y,_.z),s.push(g.x,Tt.rX?1-g.y:g.y);const v=(e+1)%h,x=(n+1)%h;t.push(e*h+n),t.push(e*h+x),t.push(v*h+n),t.push(e*h+x),t.push(v*h+x),t.push(v*h+n)}}bt._ComputeSides(l,i,t,r,s,e.frontUVs,e.backUVs);const c=new bt;return c.indices=t,c.positions=i,c.normals=r,c.uvs=s,c}function ao(e,t={},i){const r=new Yt(e,i);return t.sideOrientation=Yt._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,oo(t).applyToMesh(r,t.updatable),r}bt.CreateGround=Jn,bt.CreateTiledGround=eo,bt.CreateGroundFromHeightMap=to,Yt.CreateGround=(e,t,i,r,s,n)=>io(e,{width:t,height:i,subdivisions:r,updatable:n},s),Yt.CreateTiledGround=(e,t,i,r,s,n,o,a,l)=>ro(e,{xmin:t,zmin:i,xmax:r,zmax:s,subdivisions:n,precision:o,updatable:l},a),Yt.CreateGroundFromHeightMap=(e,t,i,r,s,n,o,a,l,h,c)=>so(e,t,{width:i,height:r,subdivisions:s,minHeight:n,maxHeight:o,updatable:l,onReady:h,alphaFilter:c},a);const lo={CreateTorus:ao};bt.CreateTorus=oo,Yt.CreateTorus=(e,t,i,r,s,n,o)=>ao(e,{diameter:t,thickness:i,tessellation:r,sideOrientation:o,updatable:n},s);class ho{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=ho._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=ao("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;const t=new Un("targetMat",e);t.specularColor=H.v9.Black(),t.emissiveColor=new H.v9(.7,.7,.7),t.backFaceCulling=!1,this._gazeTracker.material=t}}_getForwardRay(e){return new wi(W.Pq.Zero(),new W.Pq(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()}}ho._IdCounter=0;class co extends ho{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){const t=this._getCamera();return t?t.getForwardRay(e):new wi(W.Pq.Zero(),W.Pq.Forward())}}class uo{}class fo{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 z.cP,this.onAfterEnteringVRObservable=new z.cP,this.onExitingVRObservable=new z.cP,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=fo.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new W.Pq(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new W.Pq(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new H.v9(.2,.2,1),this._pickedGazeColor=new H.v9(0,0,1),this.onNewMeshSelected=new z.cP,this.onNewMeshPicked=new z.cP,this.onBeforeCameraTeleport=new z.cP,this.onAfterCameraTeleport=new z.cP,this.onSelectedMeshUnselected=new z.cP,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=e=>{e.type!==Cr.POSE_ENABLED&&(e.leftStick&&e.onleftstickchanged((e=>{this._teleportationInitialized&&this.teleportationEnabled&&(this._checkTeleportWithRay(e,this._cameraGazer),this._checkTeleportBackwards(e,this._cameraGazer))})),e.rightStick&&e.onrightstickchanged((e=>{this._teleportationInitialized&&this._checkRotate(e,this._cameraGazer)})),e.type===Cr.XBOX&&(e.onbuttondown((e=>{this._interactionsEnabled&&0===e&&this._cameraGazer._selectionPointerDown()})),e.onbuttonup((e=>{this._interactionsEnabled&&0===e&&this._cameraGazer._selectionPointerUp()}))))},this._workingVector=W.Pq.Zero(),this._workingQuaternion=W.PT.Identity(),this._workingMatrix=W.uq.Identity(),Z.V.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||void 0!==t.useXR||(t.useXR=!0),void 0===t.createFallbackVRDeviceOrientationFreeCamera&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===t.createDeviceOrientationCamera&&(t.createDeviceOrientationCamera=!0),void 0===t.laserToggle&&(t.laserToggle=!0),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new W.Pq(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new rs("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 Jr&&this._scene.activeCamera.rotation)){const e=this._scene.activeCamera;e.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(W.PT.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z)),this._deviceOrientationCamera.rotation=e.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?Qn.IsSessionSupportedAsync("immersive-vr").then((i=>{i?(Z.V.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then((t=>{this.xr=t,this.xrTestDone=!0,this._cameraGazer=new co((()=>this.xr.baseExperience.camera),e),this.xr.baseExperience.onStateChangedObservable.add((e=>{switch(e){case 0:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case 1:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case 2:this._hasEnteredVR=!0;break;case 3:this._hasEnteredVR=!1}}))}))):this._completeVRInit(e,t)})):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new _n("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new co((()=>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 e=".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) }";e+=".babylonVRicon.vrdisplaypresenting { display: none; }";const t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),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=e=>{27===e.keyCode&&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())}),yi.Zp.POINTERDOUBLETAP,!1),e.onDisposeObservable.add((()=>{this.dispose()})),this._updateButtonVisibility(),this._circleEase=new be,this._circleEase.setEasingMode(xe.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add((t=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===yi.Zp.POINTERDOWN?this._cameraGazer._selectionPointerDown():t.type===yi.Zp.POINTERUP&&this._cameraGazer._selectionPointerUp())})),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&2===this.xr.baseExperience.state||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);else{if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){Z.V.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=W.PT.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();else if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){Z.V.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)return void(2===this.xr.baseExperience.state&&this.xr.pointerSelection.attach());this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>!!(this._isTeleportationFloor(e)||-1===e.name.indexOf("gazeTracker")&&-1===e.name.indexOf("teleportationTarget")&&-1===e.name.indexOf("torusTeleportation"))&&this.raySelectionPredicate(e),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);-1!==t&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){const t=e.floorMeshes||[];if(!t.length){const i=this._scene.getMeshByName(e.floorMeshName);i&&t.push(i)}if(this.xr)return t.forEach((e=>{this.xr.teleportation.addFloorMesh(e)})),void(this.xr.teleportation.attached||this.xr.teleportation.attach());if(!this.xrTestDone){const t=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(t),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};return void this._scene.registerBeforeRender(t)}}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),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction);const t=new gn.p;t.vignetteColor=new H.ov(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 e=W.PT.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),i=this.currentVRCamera.position;e.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,W.PT.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),W.Pq.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);const r=new wi(i,this._workingVector),s=this._scene.pickWithRay(r,this._raySelectionPredicate);s&&s.pickedPoint&&s.pickedMesh&&this._isTeleportationFloor(s.pickedMesh)&&s.distance<5&&this.teleportCamera(s.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}_createTeleportationCircles(){this._teleportationTarget=io("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;const e=new Gn("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;const t=e.getContext();t.beginPath(),t.arc(256,256,200,0,2*Math.PI,!1),t.fillStyle=this._teleportationFillColor,t.fill(),t.lineWidth=10,t.strokeStyle=this._teleportationBorderColor,t.stroke(),t.closePath(),e.update();const i=new Un("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;const r=ao("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);r.isPickable=!1,r.parent=this._teleportationTarget;const s=new pe.X5("animationInnerCircle","position.y",30,pe.X5.ANIMATIONTYPE_FLOAT,pe.X5.ANIMATIONLOOPMODE_CYCLE),n=[];n.push({frame:0,value:0}),n.push({frame:30,value:.4}),n.push({frame:60,value:0}),s.setKeys(n);const o=new Me;o.setEasingMode(xe.EASINGMODE_EASEINOUT),s.setEasingFunction(o),r.animations=[],r.animations.push(s),this._scene.beginAnimation(r,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 es))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];const t=W.PT.FromRotationMatrix(W.uq.RotationY(Math.PI/4*this._rotationAngle)),i=new pe.X5("animationRotation","rotationQuaternion",90,pe.X5.ANIMATIONTYPE_QUATERNION,pe.X5.ANIMATIONLOOPMODE_CONSTANT),r=[];r.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),r.push({frame:6,value:t}),i.setKeys(r),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];const s=new pe.X5("animationPP","vignetteWeight",90,pe.X5.ANIMATIONTYPE_FLOAT,pe.X5.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:0}),n.push({frame:3,value:4}),n.push({frame:6,value:0}),s.setKeys(n),s.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(s);const o=new pe.X5("animationPP2","vignetteStretch",90,pe.X5.ANIMATIONTYPE_FLOAT,pe.X5.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:3,value:10}),a.push({frame:6,value:0}),o.setKeys(a),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 es))return;let t,i;if(this._workingVector.copyFrom(e),this.isInVRMode||(this._workingVector.y+=this._defaultHeight),this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this._teleportationMode==fo.TELEPORTATIONMODE_CONSTANTSPEED){i=90;const e=W.Pq.Distance(this.currentVRCamera.position,this._workingVector);t=this._teleportationSpeed/e}else i=Math.round(90*this._teleportationTime/1e3),t=1;this.currentVRCamera.animations=[];const r=new pe.X5("animationCameraTeleportation","position",90,pe.X5.ANIMATIONTYPE_VECTOR3,pe.X5.ANIMATIONLOOPMODE_CONSTANT),s=[{frame:0,value:this.currentVRCamera.position},{frame:i,value:this._workingVector}];r.setKeys(s),r.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(r),this._postProcessMove.animations=[];const n=Math.round(i/2),o=new pe.X5("animationPP","vignetteWeight",90,pe.X5.ANIMATIONTYPE_FLOAT,pe.X5.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:n,value:8}),a.push({frame:i,value:0}),o.setKeys(a),this._postProcessMove.animations.push(o);const l=new pe.X5("animationPP2","vignetteStretch",90,pe.X5.ANIMATIONTYPE_FLOAT,pe.X5.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:n,value:10}),h.push({frame:i,value:0}),l.setKeys(h),this._postProcessMove.animations.push(l),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._scene.beginAnimation(this.currentVRCamera,0,i,!1,t,(()=>{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"}}fo.TELEPORTATIONMODE_CONSTANTTIME=0,fo.TELEPORTATIONMODE_CONSTANTSPEED=1;const po=function(){const e={root:0,found:!1};return function(t,i,r,s){e.root=0,e.found=!1;const n=i*i-4*t*r;if(n<0)return e;const o=Math.sqrt(n);let a=(-i-o)/(2*t),l=(-i+o)/(2*t);if(a>l){const e=l;l=a,a=e}return a>0&&a0&&l=0))}_canDoCollision(e,t,i,r){const s=W.Pq.Distance(this._basePointWorld,e),n=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(s>this._velocityWorldLength+n+t||!((e,t,i,r)=>!(e.x>i.x+r||i.x-r>t.x||e.y>i.y+r||i.y-r>t.y||e.z>i.z+r||i.z-r>t.z))(i,r,this._basePointWorld,this._velocityWorldLength+n))}_testTriangle(e,t,i,r,s,n,o){let a,l=!1;t||(t=[]),t[e]||(t[e]=new Ft.Z(0,0,0,0),t[e].copyFromPoints(i,r,s));const h=t[e];if(!n&&!h.isFrontFacingTo(this._normalizedVelocity,0))return;const c=h.signedDistanceTo(this._basePoint),u=W.Pq.Dot(h.normal,this._velocity);if(_o.DoubleSidedCheck&&u>1e-4)return;if(0==u){if(Math.abs(c)>=1)return;l=!0,a=0}else{a=(-1-c)/u;let e=(1-c)/u;if(a>e){const t=e;e=a,a=t}if(a>1||e<0)return;a<0&&(a=0),a>1&&(a=1)}this._collisionPoint.copyFromFloats(0,0,0);let d=!1,f=1;if(l||(this._basePoint.subtractToRef(h.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(a,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,r,s,h.normal)&&(d=!0,f=a,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!d){let e=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let t=2*W.Pq.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=po(e,t,n,f);o.found&&(f=o.root,d=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(r,this._tempVector),t=2*W.Pq.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=po(e,t,n,f),o.found&&(f=o.root,d=!0,this._collisionPoint.copyFrom(r)),this._basePoint.subtractToRef(s,this._tempVector),t=2*W.Pq.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=po(e,t,n,f),o.found&&(f=o.root,d=!0,this._collisionPoint.copyFrom(s)),r.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let a=this._edge.lengthSquared(),l=W.Pq.Dot(this._edge,this._velocity),h=W.Pq.Dot(this._edge,this._baseToVertex);if(e=a*-this._velocitySquaredLength+l*l,t=2*(a*W.Pq.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=po(e,t,n,f),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(f=o.root,d=!0,this._edge.scaleInPlace(e),i.addToRef(this._edge,this._collisionPoint))}if(s.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),a=this._edge.lengthSquared(),l=W.Pq.Dot(this._edge,this._velocity),h=W.Pq.Dot(this._edge,this._baseToVertex),e=a*-this._velocitySquaredLength+l*l,t=2*(a*W.Pq.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=po(e,t,n,f),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(f=o.root,d=!0,this._edge.scaleInPlace(e),r.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),a=this._edge.lengthSquared(),l=W.Pq.Dot(this._edge,this._velocity),h=W.Pq.Dot(this._edge,this._baseToVertex),e=a*-this._velocitySquaredLength+l*l,t=2*(a*W.Pq.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=po(e,t,n,f),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(f=o.root,d=!0,this._edge.scaleInPlace(e),s.addToRef(this._edge,this._collisionPoint))}}if(d){const e=f*f*this._velocitySquaredLength;(!this.collisionFound||e=r)return void s.copyFrom(e);const a=n?n.collisionMask:i.collisionMask;i._initialize(e,t,o);const l=n&&n.surroundingMeshes||this._scene.meshes;for(let e=0;enew mo;var go=i(67313);const vo={effect:null,subMesh:null};class xo extends bn{constructor(e,t,i,r={},s=!0){super(e,t,s),this._textures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new W.uq,this._cachedWorldViewProjectionMatrix=new W.uq,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options={needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1,...r}}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)}setTexture(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this}removeTexture(e){delete this._textures[e]}setTextureArray(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return-1===this._options.externalTextures.indexOf(e)&&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(((e,t)=>(t.toArray(e,e.length),e)),[]),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(((e,t)=>(t.toArray(e,e.length),e)),[]),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(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const i=new Float32Array(16*t.length);for(let e=0;et===e||t.startsWith(i)));return r>=0&&this.options.defines.splice(r,1),("boolean"!=typeof t||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){const r=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){const e=r?i._drawWrapper:this._drawWrapper;if(e.effect&&e._wasPreviouslyReady&&e._wasPreviouslyUsingInstances===t)return!0}const s=this.getScene(),n=s.getEngine(),o=[],a=[],l=new Tn;let h=this._shaderPath,c=this._options.uniforms,u=this._options.uniformBuffers,d=this._options.samplers;n.getCaps().multiview&&s.activeCamera&&s.activeCamera.outputRenderTarget&&s.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,o.push("#define MULTIVIEW"),-1!==c.indexOf("viewProjection")&&-1===c.indexOf("viewProjectionR")&&c.push("viewProjectionR"));for(let e=0;e4&&(a.push(st.R.MatricesIndicesExtraKind),a.push(st.R.MatricesWeightsExtraKind));const t=e.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),l.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(o.push("#define BONETEXTURE"),-1===c.indexOf("boneTextureWidth")&&c.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(o.push("#define BonesPerMesh "+(t.bones.length+1)),-1===c.indexOf("mBones")&&c.push("mBones"))}else o.push("#define NUM_BONE_INFLUENCERS 0");let f=0;const p=e?e.morphTargetManager:null;if(p){const e=p.supportsUVs&&-1!==o.indexOf("#define UV1"),t=p.supportsTangents&&-1!==o.indexOf("#define TANGENT"),i=p.supportsNormals&&-1!==o.indexOf("#define NORMAL");f=p.numMaxInfluencers||p.numInfluencers,e&&o.push("#define MORPHTARGETS_UV"),t&&o.push("#define MORPHTARGETS_TANGENT"),i&&o.push("#define MORPHTARGETS_NORMAL"),f>0&&o.push("#define MORPHTARGETS"),p.isUsingTextureForTargets&&(o.push("#define MORPHTARGETS_TEXTURE"),-1===c.indexOf("morphTargetTextureIndices")&&c.push("morphTargetTextureIndices"),-1===this._options.samplers.indexOf("morphTargets")&&this._options.samplers.push("morphTargets")),o.push("#define NUM_MORPH_INFLUENCERS "+f);for(let r=0;r0&&(c=c.slice(),c.push("morphTargetInfluences"),c.push("morphTargetCount"),c.push("morphTargetTextureInfo"),c.push("morphTargetTextureIndices"))}else o.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(o.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===c.indexOf("bakedVertexAnimationSettings")&&c.push("bakedVertexAnimationSettings"),-1===c.indexOf("bakedVertexAnimationTextureSizeInverted")&&c.push("bakedVertexAnimationTextureSizeInverted"),-1===c.indexOf("bakedVertexAnimationTime")&&c.push("bakedVertexAnimationTime"),-1===this._options.samplers.indexOf("bakedVertexAnimationTexture")&&this._options.samplers.push("bakedVertexAnimationTexture")),(0,Bt.J2)(a,e,o)}for(const e in this._textures)if(!this._textures[e].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&o.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&((0,Ln.TV)(c),(0,Ln.tv)(this,s,o)),s.fogEnabled&&e?.applyFog&&s.fogMode!==oi.Z.FOGMODE_NONE&&(o.push("#define FOG"),-1===c.indexOf("view")&&c.push("view"),-1===c.indexOf("vFogInfos")&&c.push("vFogInfos"),-1===c.indexOf("vFogColor")&&c.push("vFogColor")),this._useLogarithmicDepth&&(o.push("#define LOGARITHMICDEPTH"),-1===c.indexOf("logarithmicDepthConstant")&&c.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(c=c.slice(),u=u.slice(),d=d.slice(),h=this.customShaderNameResolve(this.name,c,u,d,o,a));const _=r?i._getDrawWrapper(void 0,!0):this._drawWrapper,m=_?.effect??null,g=_?.defines??null,v=o.join("\n");let x=m;return g!==v&&(x=n.createEffect(h,{attributes:a,uniformsNames:c,uniformBuffersNames:u,samplers:d,defines:v,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:f},shaderLanguage:this._options.shaderLanguage,extraInitializationsAsync:this._options.extraInitializationsAsync},n),r?i.setEffect(x,v,this._materialContext):_&&_.setEffect(x,v),this._onEffectCreatedObservable&&(vo.effect=x,vo.subMesh=i??e?.subMeshes[0]??null,this._onEffectCreatedObservable.notifyObservers(vo))),_._wasPreviouslyUsingInstances=!!t,!(!x?.isReady()??1)&&(m!==x&&s.resetCachedMaterial(),_._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){const i=this.getScene(),r=t??this.getEffect();r&&(-1!==this._options.uniforms.indexOf("world")&&r.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),r.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),r.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),-1!==this._options.uniforms.indexOf("view")&&r.setMatrix("view",i.getViewMatrix()))}bindForSubMesh(e,t,i){this.bind(e,t,i._drawWrapperOverride?.effect,i)}bind(e,t,i,r){const s=r&&this._storeEffectOnSubMeshes,n=i??(s?r.effect:this.getEffect());if(!n)return;const o=this.getScene();this._activeEffect=n,this.bindOnlyWorldMatrix(e,i);const a=this._options.uniformBuffers;let l=!1;if(n&&a&&a.length>0&&o.getEngine().supportsUniformBuffers)for(let i=0;i0&&(0,Bt.nR)(t,n);const i=t.bakedVertexAnimationManager;if(i&&i.isEnabled){const e=s?r._drawWrapper:this._drawWrapper;t.bakedVertexAnimationManager?.bind(n,!!e._wasPreviouslyUsingInstances)}}this._afterBind(t,n,r)}getActiveTextures(){const e=super.getActiveTextures();for(const t in this._textures)e.push(this._textures[t]);for(const t in this._textureArrays){const i=this._textureArrays[t];for(let t=0;tnew xo(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes)),this);t.name=e,t.id=e,"object"==typeof t._shaderPath&&(t._shaderPath={...t._shaderPath}),this._options={...this._options},Object.keys(this._options).forEach((e=>{const t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))})),this.stencil.copyTo(t.stencil);for(const e in this._textures)t.setTexture(e,this._textures[e]);for(const e in this._textureArrays)t.setTextureArray(e,this._textureArrays[e]);for(const e in this._externalTextures)t.setExternalTexture(e,this._externalTextures[e]);for(const e in this._ints)t.setInt(e,this._ints[e]);for(const e in this._uints)t.setUInt(e,this._uints[e]);for(const e in this._floats)t.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)t.setFloats(e,this._floatsArrays[e]);for(const e in this._colors3)t.setColor3(e,this._colors3[e]);for(const e in this._colors3Arrays)t._colors3Arrays[e]=this._colors3Arrays[e];for(const e in this._colors4)t.setColor4(e,this._colors4[e]);for(const e in this._colors4Arrays)t._colors4Arrays[e]=this._colors4Arrays[e];for(const e in this._vectors2)t.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)t.setVector3(e,this._vectors3[e]);for(const e in this._vectors4)t.setVector4(e,this._vectors4[e]);for(const e in this._quaternions)t.setQuaternion(e,this._quaternions[e]);for(const e in this._quaternionsArrays)t._quaternionsArrays[e]=this._quaternionsArrays[e];for(const e in this._matrices)t.setMatrix(e,this._matrices[e]);for(const e in this._matrixArrays)t._matrixArrays[e]=this._matrixArrays[e].slice();for(const e in this._matrices3x3)t.setMatrix3x3(e,this._matrices3x3[e]);for(const e in this._matrices2x2)t.setMatrix2x2(e,this._matrices2x2[e]);for(const e in this._vectors2Arrays)t.setArray2(e,this._vectors2Arrays[e]);for(const e in this._vectors3Arrays)t.setArray3(e,this._vectors3Arrays[e]);for(const e in this._vectors4Arrays)t.setArray4(e,this._vectors4Arrays[e]);for(const e in this._uniformBuffers)t.setUniformBuffer(e,this._uniformBuffers[e]);for(const e in this._textureSamplers)t.setTextureSampler(e,this._textureSamplers[e]);for(const e in this._storageBuffers)t.setStorageBuffer(e,this._storageBuffers[e]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){const t=this._textureArrays[e];for(let e=0;enew xo(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes)),e,t,i);let s;for(s in e.stencil&&r.stencil.parse(e.stencil,t,i),e.textures)r.setTexture(s,vi.g.Parse(e.textures[s],t,i));for(s in e.textureArrays){const n=e.textureArrays[s],o=[];for(let e=0;e(i%3==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>H.v9.FromArray(e)));r.setColor3Array(s,t)}for(s in e.colors4)r.setColor4(s,H.ov.FromArray(e.colors4[s]));for(s in e.colors4Arrays){const t=e.colors4Arrays[s].reduce(((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>H.ov.FromArray(e)));r.setColor4Array(s,t)}for(s in e.vectors2)r.setVector2(s,W.I9.FromArray(e.vectors2[s]));for(s in e.vectors3)r.setVector3(s,W.Pq.FromArray(e.vectors3[s]));for(s in e.vectors4)r.setVector4(s,W.IU.FromArray(e.vectors4[s]));for(s in e.quaternions)r.setQuaternion(s,W.PT.FromArray(e.quaternions[s]));for(s in e.matrices)r.setMatrix(s,W.uq.FromArray(e.matrices[s]));for(s in e.matrixArray)r._matrixArrays[s]=new Float32Array(e.matrixArray[s]);for(s in e.matrices3x3)r.setMatrix3x3(s,e.matrices3x3[s]);for(s in e.matrices2x2)r.setMatrix2x2(s,e.matrices2x2[s]);for(s in e.vectors2Arrays)r.setArray2(s,e.vectors2Arrays[s]);for(s in e.vectors3Arrays)r.setArray3(s,e.vectors3Arrays[s]);for(s in e.vectors4Arrays)r.setArray4(s,e.vectors4Arrays[s]);for(s in e.quaternionsArrays)r.setArray4(s,e.quaternionsArrays[s]);return r}static ParseFromFileAsync(e,t,i,r=""){return new Promise(((s,n)=>{const o=new go.u;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),n=this.Parse(t,i||he.q.LastCreatedScene,r);e&&(n.name=e),s(n)}else n("Unable to load the ShaderMaterial")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return new Promise(((r,s)=>{const n=new go.u;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const s=JSON.parse(JSON.parse(n.responseText).jsonPayload),o=JSON.parse(s.shaderMaterial),a=this.Parse(o,t||he.q.LastCreatedScene,i);a.snippetId=e,r(a)}else s("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}xo.SnippetUrl="https://snippet.babylonjs.com",xo.CreateFromSnippetAsync=xo.ParseFromSnippetAsync,(0,X.Y5)("BABYLON.ShaderMaterial",xo);class bo{constructor(){this._pickingTexture=null,this._idMap=[],this._thinIdMap=[],this._idColors=[],this._meshMaterialMap=new Map,this._meshRenderingCount=0,this._attributeName="instanceMeshID",this._shaderLanguage=0,this._pickingInProgress=!1}get shaderLanguage(){return this._shaderLanguage}get pickingInProgress(){return this._pickingInProgress}static _IdToRgb(e){bo._TempColor.r=(16711680&e)>>16,bo._TempColor.g=(65280&e)>>8,bo._TempColor.b=255&e}_getColorIdFromReadBuffer(e){return(this._readbuffer[e]<<16)+(this._readbuffer[e+1]<<8)+this._readbuffer[e+2]}static _SetColorData(e,t,i,r,s){e[t]=i/255,e[t+1]=r/255,e[t+2]=s/255,e[t+3]=1}_createRenderTarget(e,t,i){this._pickingTexture&&this._pickingTexture.dispose(),this._pickingTexture=new ln.$("pickingTexure",{width:t,height:i},e,!1,void 0,0,!1,1)}async _createColorMaterialAsync(e){this._defaultRenderMaterial&&this._defaultRenderMaterial.dispose(),this._defaultRenderMaterial=null,e.getEngine().isWebGPU&&(this._shaderLanguage=1);const t={attributes:[st.R.PositionKind,this._attributeName,"bakedVertexAnimationSettingsInstanced"],uniforms:["world","viewProjection","meshID"],needAlphaBlending:!1,defines:[],useClipPlane:null,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this.shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,38020)),Promise.resolve().then(i.bind(i,17570))]):await Promise.all([Promise.resolve().then(i.bind(i,7987)),Promise.resolve().then(i.bind(i,37837))])}};this._defaultRenderMaterial=new xo("pickingShader",e,"picking",t,!1),this._defaultRenderMaterial.onBindObservable.add(this._materialBindCallback,void 0,void 0,this)}_materialBindCallback(e){if(!e)return;const t=this._meshMaterialMap.get(e).getEffect();e.hasInstances||e.isAnInstance||e.hasThinInstances||t.setColor4("meshID",this._idColors[e.uniqueId],1),this._meshRenderingCount++}_generateColorData(e,t,i,r,s,n,o){const a=new Float32Array(4*(e+1));bo._SetColorData(a,0,r,s,n);for(let i=0;i{this._thinIdMap[i]={meshId:e,thinId:t}}));n+=t.thinInstanceCount,t.thinInstanceSetBuffer(this._attributeName,i,4)}else if(this._idMap[n]=e,n++,t.hasInstances){const i=t.instances,r=this._generateColorData(i.length,n,e,bo._TempColor.r,bo._TempColor.g,bo._TempColor.b,((e,t)=>{const r=i[e];this._idMap[t]=this._pickableMeshes.indexOf(r)}));n+=i.length;const s=t.getEngine(),o=new st.R(s,r,this._attributeName,!1,!1,4,!0);t.setVerticesBuffer(o,!0)}else this._idColors[t.uniqueId]=H.v9.FromInts(bo._TempColor.r,bo._TempColor.g,bo._TempColor.b)}}async pickAsync(e,t,i=!1){if(this._pickingInProgress)return null;if(!this._pickableMeshes||0===this._pickableMeshes.length)return null;const{x:r,y:s,rttSizeW:n,rttSizeH:o}=this._prepareForPicking(e,t);if(r<0||s<0||r>=n||s>=o)return null;this._pickingInProgress=!0;const a=o-s-1;return this._preparePickingBuffer(this._engine,n,o,r,a),this._executePicking(r,a,i)}async multiPickAsync(e,t=!1){if(this._pickingInProgress)return null;if(!this._pickableMeshes||0===this._pickableMeshes.length||0===e.length)return null;if(1===e.length){const i=await this.pickAsync(e[0].x,e[0].y,t);return{meshes:[i?.mesh??null],thinInstanceIndexes:i?.thinInstanceIndex?[i.thinInstanceIndex]:void 0}}this._pickingInProgress=!0;let i=e[0].x,r=e[0].x,s=e[0].y,n=e[0].y;for(let t=1;t{this._enableScissor(r,s,n,o)},this._cachedScene.customRenderTargets.push(this._pickingTexture)}_executePicking(e,t,i){return new Promise(((r,s)=>{if(!this._pickingTexture)return this._pickingInProgress=!1,void s();this._pickingTexture.onAfterRender=async()=>{if(this._disableScissor(),this._checkRenderStatus()){this._pickingTexture.onAfterRender=null;let s,n=null;const o=this._cachedScene.customRenderTargets.indexOf(this._pickingTexture);if(o>-1&&this._cachedScene.customRenderTargets.splice(o,1),await this._readTexturePixelsAsync(e,t)){const e=this._getColorIdFromReadBuffer(0);this._thinIdMap[e]?(n=this._pickableMeshes[this._thinIdMap[e].meshId],s=this._thinIdMap[e].thinId):n=this._pickableMeshes[this._idMap[e]]}i&&this.dispose(),this._pickingInProgress=!1,r(n?{mesh:n,thinInstanceIndex:s}:null)}}}))}_executeMultiPicking(e,t,i,r,s,n,o){return new Promise(((a,l)=>{if(!this._pickingTexture)return this._pickingInProgress=!1,void l();this._pickingTexture.onAfterRender=async()=>{if(this._disableScissor(),this._checkRenderStatus()){this._pickingTexture.onAfterRender=null;const l=[],h=[];if(await this._readTexturePixelsAsync(t,r-i-1,s,n))for(let r=0;r0){const e=this._cachedScene.customRenderTargets.indexOf(this._pickingTexture);return e>-1&&this._cachedScene.customRenderTargets.splice(e,1),!0}return this._meshRenderingCount=0,!1}_getMeshFromMultiplePoints(e,t,i,r,s){let n=4*(e-i-1),o=(r-t-1)*s*4;n=Math.max(n,0),o=Math.max(o,0);const a=this._getColorIdFromReadBuffer(n+o);let l,h=null;return a>0&&(this._thinIdMap[a]?(h=this._pickableMeshes[this._thinIdMap[a].meshId],l=this._thinIdMap[a].thinId):h=this._pickableMeshes[this._idMap[a]]),{pickedMesh:h,thinInstanceIndex:l}}_updateRenderList(){this._pickingTexture.renderList=[];for(const e of this._pickableMeshes)this._pickingTexture.setMaterialForRendering(e,this._meshMaterialMap.get(e)),this._pickingTexture.renderList.push(e)}async _readTexturePixelsAsync(e,t,i=1,r=1){if(!this._cachedScene||!this._pickingTexture?._texture)return!1;const s=this._cachedScene.getEngine();return await s._readTexturePixels(this._pickingTexture._texture,i,r,-1,0,this._readbuffer,!0,!0,e,t),!0}dispose(){this.setPickingList(null),this._cachedScene=null,this._pickingTexture?.dispose(),this._pickingTexture=null,this._defaultRenderMaterial?.dispose(),this._defaultRenderMaterial=null}}bo._TempColor={r:0,g:0,b:0};var So=i(7987),To=i(37837),Co=i(38020),yo=i(17570);class Eo{constructor(e,t,i,r=""){let s;this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new z.cP,this.onErrorObservable=new z.cP,this.onBindObservable=new z.cP,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=1,this.name=e,this._key=r,this._engine=i,this.uniqueId=Eo._UniqueIdSeed++,this.defines=t.defines??"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=t.entryPoint??"main",this._shaderStore=Cs.l.GetShadersStore(this._shaderLanguage),this._shaderRepository=Cs.l.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=Cs.l.GetIncludesShadersStore(this._shaderLanguage);const n=(0,ii.BA)()?this._engine.getHostDocument():null;s="string"==typeof e?e:e.computeSource?"source:"+e.computeSource:e.computeElement?n?.getElementById(e.computeElement)||e.computeElement:e.compute||e;const o={defines:this.defines.split("\n"),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:(e,t,i)=>{if(!i)return t;for(const e of i){const i=e.replace("#define","").replace(";","").trim().split(" ");if(2===i.length){const e=i[0],r=i[1];isNaN(parseInt(r))&&isNaN(parseFloat(r))||(t=`const ${e} = ${r};\n`+t)}}return t}};this._loadShader(s,"Compute","",(i=>{(0,Cn.pB)(o),(0,Cn.jC)(i,o,(r=>{this._rawComputeSourceCode=i,t.processFinalCode&&(r=t.processFinalCode(r));const s=(0,Cn.nO)(r,"",o);this._useFinalCode(s.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+"\n"+e}else this._computeSourceCode=e;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getCompilationError(){return this._compilationError}executeWhenCompiled(e){this.isReady()?e(this):(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){return void this._processCompilationErrors(t,e)}setTimeout((()=>{this._checkIsReady(e)}),16)}_loadShader(e,t,i,r){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void r((0,ii.Zl)(e));if("source:"===e.substring(0,7))return void r(e.substring(7));if("base64:"===e.substring(0,7))return void r(window.atob(e.substring(7)));if(this._shaderStore[e+t+"Shader"])return void r(this._shaderStore[e+t+"Shader"]);if(i&&this._shaderStore[e+i+"Shader"])return void r(this._shaderStore[e+i+"Shader"]);let s;s="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:this._shaderRepository+e,this._engine._loadFile(s+"."+t.toLowerCase()+".fx",r)}get computeSourceCode(){return this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._pipelineContext?._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,(e=>{e&&e.numErrors>0?this._processCompilationErrors(e,t):(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(e){this._processCompilationErrors(e,t)}}_processCompilationErrors(e,t=null){if(this._compilationError="",Z.V.Error("Unable to compile compute effect:"),this.defines&&Z.V.Error("Defines:\n"+this.defines),Eo.LogShaderCodeOnCompilationError){const e=this._pipelineContext?._getComputeShaderCode();e&&(Z.V.Error("Compute code:"),Z.V.Error(e))}if("string"==typeof e)this._compilationError=e,Z.V.Error("Error: "+this._compilationError);else for(const t of e.messages){let e="";void 0!==t.line&&(e+="Line "+t.line+", "),void 0!==t.offset&&(e+="Offset "+t.offset+", "),void 0!==t.length&&(e+="Length "+t.length+", "),e+=t.type+": "+t.text,this._compilationError&&(this._compilationError+="\n"),this._compilationError+=e,Z.V.Error(e)}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){Cs.l.GetShadersStore(1)[`${e}ComputeShader`]=t}}Eo._UniqueIdSeed=0,Eo.LogShaderCodeOnCompilationError=!0;var Po=i(62061);class Ao{constructor(e){this._engine=e}async _initializePlatform(){if(!this._platform)if(this._engine.getCaps().supportComputeShaders){const e=await Promise.resolve().then(i.bind(i,19164));this._platform=new e.ComputeShaderBoundingHelper(this._engine)}else{if(!this._engine.getCaps().supportTransformFeedbacks)throw new Error("Your engine does not support Compute Shaders or Transform Feedbacks");{const e=await Promise.resolve().then(i.bind(i,43306));this._platform=new e.TransformFeedbackBoundingHelper(this._engine)}}}async computeAsync(e){return await this._initializePlatform(),this._platform.processAsync(e)}async batchInitializeAsync(e){return await this._initializePlatform(),this._platform.registerMeshListAsync(e)}batchProcess(){this._platform.processMeshList()}async batchFetchResultsAsync(){return this._platform.fetchResultsForMeshListAsync()}dispose(){this._platform.dispose()}}var Ro=i(43306),Io=i(19164);class Mo{constructor(e,t,i,r,s,n){this.entries=[],this._boundingVectors=new Array,this._capacity=i,this._depth=r,this._maxDepth=s,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 i=e.getBoundingInfo();!e.isBlocked&&i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},Oo.CreationFuncForSubMeshes=(e,t)=>{e.getBoundingInfo().boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},oi.Z.prototype.createOrUpdateSelectionOctree=function(e=64,t=2){let i=this._getComponent(Ut.v.NAME_OCTREE);i||(i=new Do(this),this._addComponent(i)),this._selectionOctree||(this._selectionOctree=new Oo(Oo.CreationFuncForMeshes,e,t));const r=this.getWorldExtends();return this._selectionOctree.update(r.min,r.max,this.meshes),this._selectionOctree},Object.defineProperty(oi.Z.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),Nt.prototype.createOrUpdateSubmeshesOctree=function(e=64,t=2){const i=this.getScene();let r=i._getComponent(Ut.v.NAME_OCTREE);r||(r=new Do(i),i._addComponent(r)),this._submeshesOctree||(this._submeshesOctree=new Oo(Oo.CreationFuncForSubMeshes,e,t)),this.computeWorldMatrix(!0);const s=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(s.minimumWorld,s.maximumWorld,this.subMeshes),this._submeshesOctree};class Do{constructor(e){this.name=Ut.v.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new wi(W.Pq.Zero(),new W.Pq(1,1,1)),(e=e||he.q.LastCreatedScene)&&(this.scene=e,this.scene.getActiveMeshCandidates=()=>this.getActiveMeshCandidates(),this.scene.getActiveSubMeshCandidates=e=>this.getActiveSubMeshCandidates(e),this.scene.getCollidingSubMeshCandidates=(e,t)=>this.getCollidingSubMeshCandidates(e,t),this.scene.getIntersectingSubMeshCandidates=(e,t)=>this.getIntersectingSubMeshCandidates(e,t))}register(){this.scene.onMeshRemovedObservable.add((e=>{const t=this.scene.selectionOctree;if(null!=t){const i=t.dynamicContent.indexOf(e);-1!==i&&t.dynamicContent.splice(i,1)}})),this.scene.onMeshImportedObservable.add((e=>{const t=this.scene.selectionOctree;null!=t&&t.addMesh(e)}))}getActiveMeshCandidates(){return this.scene._selectionOctree?.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?(wi.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 wo(e){const t=e.height||2;let i=0===e.diameterTop?0:e.diameterTop||e.diameter||1,r=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;i=i||1e-5,r=r||1e-5;const s=0|(e.tessellation||24),n=0|(e.subdivisions||1),o=!!e.hasRings,a=!!e.enclose,l=0===e.cap?0:e.cap||Yt.CAP_ALL,h=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,c=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE,u=e.faceUV||new Array(3),d=e.faceColors,f=2+(1+(1!==h&&a?2:0))*(o?n:1);let p;for(p=0;p{const n=e?i/2:r/2;if(0===n)return;let o,a,l;const c=e?u[f-1]:u[0];let p=null;d&&(p=e?d[f-1]:d[0]);const b=m.length/3,S=e?t/2:-t/2,T=new W.Pq(0,S,0);m.push(T.x,T.y,T.z),g.push(0,e?1:-1,0);const C=c.y+.5*(c.w-c.y);v.push(c.x+.5*(c.z-c.x),Tt.rX?1-C:C),p&&x.push(p.r,p.g,p.b,p.a);const y=new W.I9(.5,.5);for(l=0;l<=s;l++){o=2*Math.PI*l*h/s;const t=Math.cos(-o),i=Math.sin(-o);a=new W.Pq(t*n,S,i*n);const r=new W.I9(t*y.x+.5,i*y.y+.5);m.push(a.x,a.y,a.z),g.push(0,e?1:-1,0);const u=c.y+(c.w-c.y)*r.y;v.push(c.x+(c.z-c.x)*r.x,Tt.rX?1-u:u),p&&x.push(p.r,p.g,p.b,p.a)}for(l=0;l(void 0!==o&&o instanceof oi.Z||(void 0!==o&&(l=a||Yt.DEFAULTSIDE,a=o),o=n,n=1),No(e,{height:t,diameterTop:i,diameterBottom:r,tessellation:s,subdivisions:n,sideOrientation:l,updatable:a},o)),Ze.b.AddNodeConstructor("Light_Type_3",((e,t)=>()=>new Lo(e,W.Pq.Zero(),t)));class Lo extends $t{constructor(e,t,i){super(e,i),this.groundColor=new H.v9(0,0,0),this.direction=t||W.Pq.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=W.Pq.Normalize(e.subtract(W.Pq.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=W.Pq.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=W.Pq.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=W.uq.Identity()),this._worldMatrix}getTypeID(){return $t.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}(0,je.Cg)([(0,$e.jT)()],Lo.prototype,"groundColor",void 0),(0,je.Cg)([(0,$e.P_)()],Lo.prototype,"direction",void 0),(0,X.Y5)("BABYLON.HemisphericLight",Lo);class Bo{getRenderCamera(e){if(this._renderCamera)return this._renderCamera;{let t;return t=this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera,e&&t&&t.isRigCamera?t.rigParent:t}}setRenderCamera(e){this._renderCamera=e}_getSharedGizmoLight(){return this._sharedGizmoLight||(this._sharedGizmoLight=new Lo("shared gizmo light",new W.Pq(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=H.v9.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return null==Bo._DefaultUtilityLayer?Bo._CreateDefaultUtilityLayerFromScene(he.q.LastCreatedScene):Bo._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return Bo._DefaultUtilityLayer=new Bo(e),Bo._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{Bo._DefaultUtilityLayer=null})),Bo._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return null==Bo._DefaultKeepDepthUtilityLayer&&(Bo._DefaultKeepDepthUtilityLayer=new Bo(he.q.LastCreatedScene),Bo._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,Bo._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{Bo._DefaultKeepDepthUtilityLayer=null}))),Bo._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 z.cP,this.utilityLayerScene=new oi.Z(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((t=>{if(!this.utilityLayerScene.activeCamera)return;if(!this.pickingEnabled)return;if(!this.processAllEvents&&t.type!==yi.Zp.POINTERMOVE&&t.type!==yi.Zp.POINTERUP&&t.type!==yi.Zp.POINTERDOWN&&t.type!==yi.Zp.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;const i=t.event;if(e.isPointerCaptured(i.pointerId))return void(this._pointerCaptures[i.pointerId]=!1);const r=i=>{let r=null;if(t.nearInteractionPickingInfo)r=t.nearInteractionPickingInfo.pickedMesh.getScene()==i?t.nearInteractionPickingInfo:new At.G;else if(i!==this.utilityLayerScene&&t.originalPickingInfo)r=t.originalPickingInfo;else{let s=null;this._renderCamera&&(s=i._activeCamera,i._activeCamera=this._renderCamera,t.ray=null),r=t.ray?i.pickWithRay(t.ray):i.pick(e.pointerX,e.pointerY),s&&(i._activeCamera=s)}return r},s=r(this.utilityLayerScene);if(!t.ray&&s&&(t.ray=s.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(t),this.onlyCheckPointerDownEvents&&t.type!=yi.Zp.POINTERDOWN)return t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new yi.mx(t.type,t.event,s),t.type),void(t.type===yi.Zp.POINTERUP&&this._pointerCaptures[i.pointerId]&&(this._pointerCaptures[i.pointerId]=!1));if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)s&&s.hit&&(t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new yi.mx(t.type,t.event,s),t.type),t.skipOnPointerObservable=!0);else{const i=r(e),n=t.event;i&&s&&(0===s.distance&&i.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):t.type===yi.Zp.POINTERDOWN?this._pointerCaptures[n.pointerId]=!0:t.type!==yi.Zp.POINTERMOVE&&t.type!==yi.Zp.POINTERUP||(this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,i,n)):!this._pointerCaptures[n.pointerId]&&(s.distance0)):!this._pointerCaptures[n.pointerId]&&s.distance>=i.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):(t.type!==yi.Zp.POINTERMOVE&&t.type!==yi.Zp.POINTERUP||this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,s,n))),t.type===yi.Zp.POINTERUP&&this._pointerCaptures[n.pointerId]&&(this._pointerCaptures[n.pointerId]=!1))}})),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add((e=>{this.shouldRender&&e==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 yi.mx(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()}}var Vo,ko,Uo;Bo._DefaultUtilityLayer=null,Bo._DefaultKeepDepthUtilityLayer=null,function(e){e[e.Origin=0]="Origin",e[e.Pivot=1]="Pivot"}(Vo||(Vo={})),function(e){e[e.World=0]="World",e[e.Local=1]="Local"}(ko||(ko={}));class Go{set scaleRatio(e){this._scaleRatio=e}get scaleRatio(){return this._scaleRatio}get isHovered(){return this._isHovered}get attachedMesh(){return this._attachedMesh}set attachedMesh(e){this._attachedMesh=e,e&&(this._attachedNode=e),this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}get attachedNode(){return this._attachedNode}set attachedNode(e){this._attachedNode=e,this._attachedMesh=null,this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._rootMesh.getChildMeshes().forEach((e=>{e.dispose()})),e.parent=this._rootMesh,this._customMeshSet=!0}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){this._additionalTransformNode=e}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){this._coordinatesMode=e;const t=1==e;this.updateGizmoRotationToMatchAttachedMesh=t,this.updateGizmoPositionToMatchAttachedMesh=!0}get coordinatesMode(){return this._coordinatesMode}set updateScale(e){this._updateScale=e}get updateScale(){return this._updateScale}_attachedNodeChanged(e){}constructor(e=Bo.DefaultUtilityLayer){this.gizmoLayer=e,this._attachedMesh=null,this._attachedNode=null,this._customRotationQuaternion=null,this._scaleRatio=1,this._isHovered=!1,this._customMeshSet=!1,this._updateGizmoRotationToMatchAttachedMesh=!0,this._updateGizmoPositionToMatchAttachedMesh=!0,this._anchorPoint=0,this._updateScale=!0,this._coordinatesMode=1,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=W.uq.RotationY(Math.PI),this._rootMesh=new Yt("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=W.PT.Identity(),this._beforeRenderObserver=this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add((()=>{this._update()}))}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e}_update(){if(this.attachedNode){let e=this.attachedNode;if(this.attachedMesh&&(e=this.attachedMesh||this.attachedNode),this.updateGizmoPositionToMatchAttachedMesh)if(1==this.anchorPoint&&e.getAbsolutePivotPoint){const t=e.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(t)}else{const t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new W.Pq(0,0,0);this._rootMesh.position.copyFrom(i)}if(this.updateGizmoRotationToMatchAttachedMesh){const t=e._isMesh||"AbstractMesh"===e.getClassName()||"TransformNode"===e.getClassName()||"InstancedMesh"===e.getClassName()?e:void 0;e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,Go.PreserveScaling?t:void 0),this._rootMesh.rotationQuaternion.normalize()}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){const t=this.gizmoLayer.utilityLayerScene.activeCamera,i=t.globalPosition;this._rootMesh.position.subtractToRef(i,W.AA.Vector3[0]);let r=this.scaleRatio;if(t.mode==rt.ORTHOGRAPHIC_CAMERA)t.orthoTop&&t.orthoBottom&&(r*=t.orthoTop-t.orthoBottom);else{const e=t.getScene().useRightHandedSystem?W.Pq.RightHandedForwardReadOnly:W.Pq.LeftHandedForwardReadOnly,i=t.getDirection(e);r*=W.Pq.Dot(W.AA.Vector3[0],i)}this._rootMesh.scaling.setAll(r),e._getWorldMatrixDeterminant()<0&&!Go.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}this.additionalTransformNode&&(this._rootMesh.computeWorldMatrix(!0),this._rootMesh.getWorldMatrix().multiplyToRef(this.additionalTransformNode.getWorldMatrix(),W.AA.Matrix[0]),W.AA.Matrix[0].decompose(this._rootMesh.scaling,this._rootMesh.rotationQuaternion,this._rootMesh.position))}_handlePivotMatrixInverse(e,t,i){if(e.isUsingPivotMatrix()&&!e.isUsingPostMultiplyPivotMatrix())return e.getPivotMatrix().invertToRef(W.AA.Matrix[5]),void W.AA.Matrix[5].multiplyToRef(t,i);i.copyFrom(t)}_matrixChanged(){if(this._attachedNode)if(this._attachedNode._isCamera){const e=this._attachedNode;let t,i;if(e.parent){const i=W.AA.Matrix[1];e.parent._worldMatrix.invertToRef(i),this._attachedNode._worldMatrix.multiplyToRef(i,W.AA.Matrix[0]),t=W.AA.Matrix[0]}else t=this._attachedNode._worldMatrix;if(e.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(t,W.AA.Matrix[1]),i=W.AA.Matrix[1]):i=t,i.decompose(W.AA.Vector3[1],W.AA.Quaternion[0],W.AA.Vector3[0]),"FreeCamera"===this._attachedNode.getClassName()||"FlyCamera"===this._attachedNode.getClassName()||"ArcFollowCamera"===this._attachedNode.getClassName()||"TargetCamera"===this._attachedNode.getClassName()||"TouchCamera"===this._attachedNode.getClassName()||"UniversalCamera"===this._attachedNode.getClassName()){const e=this._attachedNode;e.rotation=W.AA.Quaternion[0].toEulerAngles(),e.rotationQuaternion&&(e.rotationQuaternion.copyFrom(W.AA.Quaternion[0]),e.rotationQuaternion.normalize())}e.position.copyFrom(W.AA.Vector3[0])}else if(this._attachedNode._isMesh||"AbstractMesh"===this._attachedNode.getClassName()||"TransformNode"===this._attachedNode.getClassName()||"InstancedMesh"===this._attachedNode.getClassName()){const e=this._attachedNode;if(e.parent){const t=W.AA.Matrix[0],i=W.AA.Matrix[1];e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i);const r=W.AA.Matrix[4];if(this._handlePivotMatrixInverse(e,i,r),r.decompose(W.AA.Vector3[0],W.AA.Quaternion[0],e.position,Go.PreserveScaling?e:void 0,Go.UseAbsoluteScaling),W.AA.Quaternion[0].normalize(),e.isUsingPivotMatrix()){const t=W.AA.Quaternion[1];W.PT.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,t);const i=W.AA.Matrix[2];W.uq.ScalingToRef(e.scaling.x,e.scaling.y,e.scaling.z,i);const r=W.AA.Matrix[2];t.toRotationMatrix(r);const s=e.getPivotMatrix(),n=W.AA.Matrix[3];s.invertToRef(n),s.multiplyToRef(i,W.AA.Matrix[4]),W.AA.Matrix[4].multiplyToRef(r,W.AA.Matrix[5]),W.AA.Matrix[5].multiplyToRef(n,W.AA.Matrix[6]),W.AA.Matrix[6].getTranslationToRef(W.AA.Vector3[1]),e.position.subtractInPlace(W.AA.Vector3[1])}}else{const t=W.AA.Matrix[4];this._handlePivotMatrixInverse(e,this._attachedNode._worldMatrix,t),t.decompose(W.AA.Vector3[0],W.AA.Quaternion[0],e.position,Go.PreserveScaling?e:void 0,Go.UseAbsoluteScaling)}W.AA.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(W.AA.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(W.AA.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=W.AA.Quaternion[0].toEulerAngles())}else if("Bone"===this._attachedNode.getClassName()){const e=this._attachedNode,t=e.getParent();if(t){const i=W.AA.Matrix[0],r=W.AA.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,r),e.getLocalMatrix().copyFrom(r)}else e.getLocalMatrix().copyFrom(e.getFinalMatrix());e.markAsDirty()}else{const e=this._attachedNode;if(e.getTypeID){const t=e.getTypeID();if(t===$t.LIGHTTYPEID_DIRECTIONALLIGHT||t===$t.LIGHTTYPEID_SPOTLIGHT||t===$t.LIGHTTYPEID_POINTLIGHT){const t=e.parent;if(t){const i=W.AA.Matrix[0],r=W.AA.Matrix[1];t.getWorldMatrix().invertToRef(i),e.getWorldMatrix().multiplyToRef(i,r),r.decompose(void 0,W.AA.Quaternion[0],W.AA.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,W.AA.Quaternion[0],W.AA.Vector3[0]);e.position=new W.Pq(W.AA.Vector3[0].x,W.AA.Vector3[0].y,W.AA.Vector3[0].z),e.direction&&(e.direction=new W.Pq(e.direction.x,e.direction.y,e.direction.z))}}}}_setGizmoMeshMaterial(e,t){e&&e.forEach((e=>{e.material=t,e.color&&(e.color=t.diffuseColor)}))}static GizmoAxisPointerObserver(e,t){let i=!1;return e.utilityLayerScene.onPointerObservable.add((e=>{if(e.pickInfo){if(e.type===yi.Zp.POINTERMOVE){if(i)return;t.forEach((t=>{if(t.colliderMeshes&&t.gizmoMeshes){const i=-1!=t.colliderMeshes?.indexOf(e?.pickInfo?.pickedMesh),r=t.dragBehavior.enabled?i||t.active?t.hoverMaterial:t.material:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=r,e.color&&(e.color=r.diffuseColor)}))}}))}e.type===yi.Zp.POINTERDOWN&&t.has(e.pickInfo.pickedMesh?.parent)&&(i=!0,t.get(e.pickInfo.pickedMesh?.parent).active=!0,t.forEach((t=>{const i=(-1!=t.colliderMeshes?.indexOf(e?.pickInfo?.pickedMesh)||t.active)&&t.dragBehavior.enabled?t.hoverMaterial:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=i,e.color&&(e.color=i.diffuseColor)}))}))),e.type===yi.Zp.POINTERUP&&t.forEach((e=>{e.active=!1,i=!1,e.gizmoMeshes.forEach((t=>{t.material=e.dragBehavior.enabled?e.material:e.disableMaterial,t.color&&(t.color=e.material.diffuseColor)}))}))}}))}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}}Go.PreserveScaling=!1,Go.UseAbsoluteScaling=!0;class zo extends Go{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreateArrow(e,t,i=1,r=!1){const s=new Pt("arrow",e),n=No("cylinder",{diameterTop:0,height:.075,diameterBottom:.0375*(1+(i-1)/4),tessellation:96},e),o=No("cylinder",{diameterTop:.005*i,height:.275,diameterBottom:.005*i,tessellation:96},e);return n.parent=s,n.material=t,n.rotation.x=Math.PI/2,n.position.z+=.3,o.parent=s,o.material=t,o.position.z+=.1375,o.rotation.x=Math.PI/2,r&&(o.visibility=0,n.visibility=0),s}static _CreateArrowInstance(e,t){const i=new Pt("arrow",e);for(const e of t.getChildMeshes())e.createInstance(e.name).parent=i;return i}constructor(e,t=H.v9.Gray(),i=Bo.DefaultUtilityLayer,r=null,s=1,n=H.v9.Yellow(),o=H.v9.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new z.cP,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._parent=r,this._coloredMaterial=new Un("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new H.v9(.1,.1,.1)),this._hoverMaterial=new Un("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=n,this._disableMaterial=new Un("",i.utilityLayerScene),this._disableMaterial.diffuseColor=o,this._disableMaterial.alpha=.4;const a=zo._CreateArrow(i.utilityLayerScene,this._coloredMaterial,s),l=zo._CreateArrow(i.utilityLayerScene,this._coloredMaterial,s+4,!0);this._gizmoMesh=new Yt("",i.utilityLayerScene),this._gizmoMesh.addChild(a),this._gizmoMesh.addChild(l),this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._gizmoMesh.scaling.scaleInPlace(1/3),this._gizmoMesh.parent=this._rootMesh;let h=0;const c={snapDistance:0};this.dragBehavior=new Ji({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add((e=>{if(this.attachedNode){let t=!1;if(0==this.snapDistance)this.attachedNode.getWorldMatrix().getTranslationToRef(W.AA.Vector3[2]),W.AA.Vector3[2].addInPlace(e.delta),this.dragBehavior.validateDrag(W.AA.Vector3[2])&&(this.attachedNode.position&&this.attachedNode.position.addInPlaceFromFloats(e.delta.x,e.delta.y,e.delta.z),this.attachedNode.getWorldMatrix().addTranslationFromFloats(e.delta.x,e.delta.y,e.delta.z),this.attachedNode.updateCache(),t=!0);else if(h+=e.dragDistance,Math.abs(h)>this.snapDistance){const i=Math.floor(Math.abs(h)/this.snapDistance);h%=this.snapDistance,e.delta.normalizeToRef(W.AA.Vector3[1]),W.AA.Vector3[1].scaleInPlace(this.snapDistance*i),this.attachedNode.getWorldMatrix().getTranslationToRef(W.AA.Vector3[2]),W.AA.Vector3[2].addInPlace(W.AA.Vector3[1]),this.dragBehavior.validateDrag(W.AA.Vector3[2])&&(this.attachedNode.getWorldMatrix().addTranslationFromFloats(W.AA.Vector3[1].x,W.AA.Vector3[1].y,W.AA.Vector3[1].z),this.attachedNode.updateCache(),c.snapDistance=this.snapDistance*i*Math.sign(h),this.onSnapObservable.notifyObservers(c),t=!0)}t&&this._matrixChanged()}})),this.dragBehavior.onDragStartObservable.add((()=>{this._dragging=!0})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1}));const u=i._getSharedGizmoLight();u.includedOnlyMeshes=u.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const d={gizmoMeshes:a.getChildMeshes(),colliderMeshes:l.getChildMeshes(),material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(l,d),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(!this._customMeshSet&&(this._isHovered=!(-1==d.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),!this._parent)){const e=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(d.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(d.gizmoMeshes,e?d.material:d.disableMaterial)}))}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}}class Wo{get scaleLines(){return this._scaleLines}set scaleLines(e){this._scaleLines=e,this._xAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor),this._yAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor),this._zAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor)}get xAxis(){return this._xAxis}get yAxis(){return this._yAxis}get zAxis(){return this._zAxis}constructor(e,t=1,i=2,r,s,n,o=1){if(this._scaleLinesFactor=4,this._instanced=!1,this.scene=null,this._scaleLines=1,e=e||he.q.LastCreatedScene){if(!r){const t=new Un("xAxisMaterial",e);t.disableLighting=!0,t.emissiveColor=H.v9.Red().scale(.5),r=zo._CreateArrow(e,t,o)}if(!s){const t=new Un("yAxisMaterial",e);t.disableLighting=!0,t.emissiveColor=H.v9.Green().scale(.5),s=zo._CreateArrow(e,t,o)}if(!n){const t=new Un("zAxisMaterial",e);t.disableLighting=!0,t.emissiveColor=H.v9.Blue().scale(.5),n=zo._CreateArrow(e,t,o)}this._xAxis=r,this._yAxis=s,this._zAxis=n,this.scaleLines=t,null!=i&&(Wo._SetRenderingGroupId(this._xAxis,i),Wo._SetRenderingGroupId(this._yAxis,i),Wo._SetRenderingGroupId(this._zAxis,i)),this.scene=e,this.update(new W.Pq,W.Pq.Right(),W.Pq.Up(),W.Pq.Forward())}}update(e,t,i,r){this._xAxis.position.copyFrom(e),this._xAxis.setDirection(t),this._yAxis.position.copyFrom(e),this._yAxis.setDirection(i),this._zAxis.position.copyFrom(e),this._zAxis.setDirection(r)}createInstance(){const e=zo._CreateArrowInstance(this.scene,this._xAxis),t=zo._CreateArrowInstance(this.scene,this._yAxis),i=zo._CreateArrowInstance(this.scene,this._zAxis),r=new Wo(this.scene,this.scaleLines,null,e,t,i);return r._instanced=!0,r}dispose(){this._xAxis&&this._xAxis.dispose(!1,!this._instanced),this._yAxis&&this._yAxis.dispose(!1,!this._instanced),this._zAxis&&this._zAxis.dispose(!1,!this._instanced),this.scene=null}static _SetRenderingGroupId(e,t){e.getChildMeshes().forEach((e=>{e.renderingGroupId=t}))}}class Ho extends Wo{constructor(e,t,i,r=1){super(e,r),this.pos=W.Pq.Zero(),this.xaxis=W.Pq.Zero(),this.yaxis=W.Pq.Zero(),this.zaxis=W.Pq.Zero(),this.mesh=i,this.bone=t}update(){if(!this.mesh||!this.bone)return;const e=this.bone;e.getAbsolutePositionToRef(this.mesh,this.pos),e.getDirectionToRef(Mt._0.X,this.mesh,this.xaxis),e.getDirectionToRef(Mt._0.Y,this.mesh,this.yaxis),e.getDirectionToRef(Mt._0.Z,this.mesh,this.zaxis),super.update(this.pos,this.xaxis,this.yaxis,this.zaxis)}dispose(){this.mesh&&(this.mesh=null,this.bone=null,super.dispose())}}Object.defineProperty(oi.Z.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new Xo(this)),this._debugLayer},enumerable:!0,configurable:!0}),function(e){e[e.Properties=0]="Properties",e[e.Debug=1]="Debug",e[e.Statistics=2]="Statistics",e[e.Tools=3]="Tools",e[e.Settings=4]="Settings"}(Uo||(Uo={}));class Xo{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new z.cP),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new z.cP),this._onSelectionChangedObservable)}constructor(e){this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||he.q.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 e of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(e);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(const e of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(e);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}const t={...Xo.Config,...e};this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,t)}select(e,t){this.BJSINSPECTOR&&(t&&("[object String]"==Object.prototype.toString.call(t)?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))}_getGlobalInspector(){return"undefined"!=typeof INSPECTOR?INSPECTOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.Inspector?BABYLON:void 0}isVisible(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible}hide(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()}setAsActiveScene(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector._SetNewScene(this._scene)}popupSceneExplorer(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.PopupSceneExplorer()}popupInspector(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.PopupInspector()}popupEmbed(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.PopupEmbed()}show(e){return new Promise((t=>{if(void 0===this.BJSINSPECTOR){const i=e&&e.inspectorURL?e.inspectorURL:Xo.InspectorURL;Ue.S0.LoadBabylonScript(i,(()=>{this._createInspector(e),t(this)}))}else this._createInspector(e),t(this)}))}}function qo(e){let t=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23];const i=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],r=[];let s=[];const n=e.width||e.size||1,o=e.height||e.size||1,a=e.depth||e.size||1,l=e.wrap||!1;let h=void 0===e.topBaseAt?1:e.topBaseAt,c=void 0===e.bottomBaseAt?0:e.bottomBaseAt;h=(h+4)%4,c=(c+4)%4;let u=[2,0,3,1][h],d=[2,0,1,3][c],f=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-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(l){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],f=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,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 e=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],i=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const r=[17,18,19,16],s=[22,23,20,21];for(;u>0;)e.unshift(e.pop()),r.unshift(r.pop()),u--;for(;d>0;)i.unshift(i.pop()),s.unshift(s.pop()),d--;e=e.flat(),i=i.flat(),f=f.concat(e).concat(i),t.push(r[0],r[2],r[3],r[0],r[1],r[2]),t.push(s[0],s[2],s[3],s[0],s[1],s[2])}const p=[n/2,o/2,a/2];s=f.reduce(((e,t,i)=>e.concat(t*p[i%3])),[]);const _=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE,m=e.faceUV||new Array(6),g=e.faceColors,v=[];for(let e=0;e<6;e++)void 0===m[e]&&(m[e]=new W.IU(0,0,1,1)),g&&void 0===g[e]&&(g[e]=new H.ov(1,1,1,1));for(let e=0;e<6;e++)if(r.push(m[e].z,Tt.rX?1-m[e].w:m[e].w),r.push(m[e].x,Tt.rX?1-m[e].w:m[e].w),r.push(m[e].x,Tt.rX?1-m[e].y:m[e].y),r.push(m[e].z,Tt.rX?1-m[e].y:m[e].y),g)for(let t=0;t<4;t++)v.push(g[e].r,g[e].g,g[e].b,g[e].a);bt._ComputeSides(_,s,t,i,r,e.frontUVs,e.backUVs);const x=new bt;if(x.indices=t,x.positions=s,x.normals=i,x.uvs=r,g){const e=_===bt.DOUBLESIDE?v.concat(v):v;x.colors=e}return x}function Yo(e){const t=e.width||e.size||1,i=e.height||e.size||1,r=e.depth||e.size||1,s=0|(e.widthSegments||e.segments||1),n=0|(e.heightSegments||e.segments||1),o=0|(e.depthSegments||e.segments||1),a=new W.uq,l=new W.uq,h=new W.uq,c=Jn({width:t,height:r,subdivisionsX:s,subdivisionsY:o});W.uq.TranslationToRef(0,-i/2,0,l),W.uq.RotationZToRef(Math.PI,a),a.multiplyToRef(l,h),c.transform(h);const u=Jn({width:t,height:r,subdivisionsX:s,subdivisionsY:o});W.uq.TranslationToRef(0,i/2,0,h),u.transform(h);const d=Jn({width:i,height:r,subdivisionsX:n,subdivisionsY:o});W.uq.TranslationToRef(-t/2,0,0,l),W.uq.RotationZToRef(Math.PI/2,a),a.multiplyToRef(l,h),d.transform(h);const f=Jn({width:i,height:r,subdivisionsX:n,subdivisionsY:o});W.uq.TranslationToRef(t/2,0,0,l),W.uq.RotationZToRef(-Math.PI/2,a),a.multiplyToRef(l,h),f.transform(h);const p=Jn({width:t,height:i,subdivisionsX:s,subdivisionsY:n});W.uq.TranslationToRef(0,0,-r/2,l),W.uq.RotationXToRef(-Math.PI/2,a),a.multiplyToRef(l,h),p.transform(h);const _=Jn({width:t,height:i,subdivisionsX:s,subdivisionsY:n});return W.uq.TranslationToRef(0,0,r/2,l),W.uq.RotationXToRef(Math.PI/2,a),a.multiplyToRef(l,h),_.transform(h),c.merge([u,f,d,p,_],!0),c}function Ko(e,t={},i=null){const r=new Yt(e,i);return t.sideOrientation=Yt._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,qo(t).applyToMesh(r,t.updatable),r}Xo.InspectorURL=`${Ue.S0._DefaultCdnUrl}/v${Ot.$.Version}/inspector/babylon.inspector.bundle.js`,Xo.Config={overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0};const jo={CreateBox:Ko};function $o(e){const t=0|(e.segments||32),i=e.diameterX||e.diameter||1,r=e.diameterY||e.diameter||1,s=e.diameterZ||e.diameter||1,n=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,o=e.slice&&e.slice<=0?1:e.slice||1,a=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE,l=!!e.dedupTopBottomIndices,h=new W.Pq(i/2,r/2,s/2),c=2+t,u=2*c,d=[],f=[],p=[],_=[];for(let e=0;e<=c;e++){const t=e/c,i=t*Math.PI*o;for(let e=0;e<=u;e++){const r=e/u,s=r*Math.PI*2*n,o=W.uq.RotationZ(-i),a=W.uq.RotationY(s),l=W.Pq.TransformCoordinates(W.Pq.Up(),o),c=W.Pq.TransformCoordinates(l,a),d=c.multiply(h),m=c.divide(h).normalize();f.push(d.x,d.y,d.z),p.push(m.x,m.y,m.z),_.push(r,Tt.rX?1-t:t)}if(e>0){const t=f.length/3;for(let i=t-2*(u+1);i+u+21&&(d.push(i),d.push(i+1),d.push(i+u+1)),(eKo(e,{size:t,sideOrientation:s,updatable:r},i);const Zo={CreateSphere:Qo};bt.CreateSphere=$o,Yt.CreateSphere=(e,t,i,r,s,n)=>Qo(e,{segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:n,updatable:s},r);class Jo{constructor(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}get physicsJoint(){return this._physicsJoint}set physicsJoint(e){this._physicsJoint=e}set physicsPlugin(e){this._physicsPlugin=e}executeNativeFunction(e){e(this._physicsPlugin.world,this._physicsJoint)}}Jo.DistanceJoint=0,Jo.HingeJoint=1,Jo.BallAndSocketJoint=2,Jo.WheelJoint=3,Jo.SliderJoint=4,Jo.PrismaticJoint=5,Jo.UniversalJoint=6,Jo.Hinge2Joint=Jo.WheelJoint,Jo.PointToPointJoint=8,Jo.SpringJoint=9,Jo.LockJoint=10;class ea extends Jo{constructor(e){super(Jo.DistanceJoint,e)}updateDistance(e,t){this._physicsPlugin.updateDistanceJoint(this,e,t)}}class ta extends Jo{constructor(e,t){super(e,t)}setMotor(e,t){this._physicsPlugin.setMotor(this,e||0,t)}setLimit(e,t){this._physicsPlugin.setLimit(this,e,t)}}class ia extends ta{constructor(e){super(Jo.HingeJoint,e)}setMotor(e,t){this._physicsPlugin.setMotor(this,e||0,t)}setLimit(e,t){this._physicsPlugin.setLimit(this,e,t)}}class ra extends ta{constructor(e){super(Jo.Hinge2Joint,e)}setMotor(e,t,i=0){this._physicsPlugin.setMotor(this,e||0,t,i)}setLimit(e,t,i=0){this._physicsPlugin.setLimit(this,e,t,i)}}Yt._PhysicsImpostorParser=function(e,t,i){return new sa(t,i.physicsImpostor,{mass:i.physicsMass,friction:i.physicsFriction,restitution:i.physicsRestitution},e)};class sa{get isDisposed(){return this._isDisposed}get mass(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0}set mass(e){this.setMass(e)}get friction(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0}set friction(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,e)}get restitution(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0}set restitution(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,e)}get pressure(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0}set pressure(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}get stiffness(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0}set stiffness(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}get velocityIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0}set velocityIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}get positionIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0}set positionIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}constructor(e,t,i={mass:0},r){this.object=e,this.type=t,this._options=i,this._scene=r,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=W.Pq.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new W.PT,this._tmpQuat2=new W.PT,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 W.PT),this._options.disableBidirectionalTransformation||this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach((e=>{e(this)})))},this.afterStep=()=>{this._physicsEngine&&(this._onAfterPhysicsStepCallbacks.forEach((e=>{e(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,sa._TmpVecs[0]),this.object.translate(sa._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=e=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent)return;if(!this._physicsEngine)return;const t=this._physicsEngine.getImpostorWithPhysicsBody(e.body);t&&(this.onCollideEvent&&this.onCollideEvent(this,t),this._onPhysicsCollideCallbacks.filter((e=>-1!==e.otherImpostors.indexOf(t))).forEach((i=>{i.callback(this,t,e.point,e.distance,e.impulse,e.normal)})))},this.object?(this.object.parent&&0!==i.mass&&Z.V.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=W.PT.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new W.PT),this._options.mass=void 0===i.mass?0:i.mass,this._options.friction=void 0===i.friction?.2:i.friction,this._options.restitution=void 0===i.restitution?.2:i.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=void 0===i.pressure?200:i.pressure,this._options.stiffness=void 0===i.stiffness?1:i.stiffness,this._options.velocityIterations=void 0===i.velocityIterations?20:i.velocityIterations,this._options.positionIterations=void 0===i.positionIterations?20:i.positionIterations,this._options.fixedPoints=void 0===i.fixedPoints?0:i.fixedPoints,this._options.margin=void 0===i.margin?0:i.margin,this._options.damping=void 0===i.damping?0:i.damping,this._options.path=void 0===i.path?null:i.path,this._options.shape=void 0===i.shape?null:i.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&Z.V.Warn("You must affect impostors to children before affecting impostor to parent.")):Z.V.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))):Z.V.Error("No object was provided. A physics object is obligatory")}_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 Nt?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=sa.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}return sa.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):W.Pq.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):W.Pq.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):Z.V.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):Z.V.Warn("Function to remove was not found")}registerOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})}unregisterOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];let r=-1;this._onPhysicsCollideCallbacks.some(((e,s)=>{if(e.callback===t&&e.otherImpostors.length===i.length){const t=e.otherImpostors.every((e=>i.indexOf(e)>-1));return t&&(r=s),t}return!1}))?this._onPhysicsCollideCallbacks.splice(r,1):Z.V.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):W.PT.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),e=e.parent;return this._tmpQuat}applyForce(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this}applyImpulse(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this}createJoint(e,t,i){const r=new Jo(t,i);return this.addJoint(e,r),this}addJoint(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this}addAnchor(e,t,i,r,s){if(!this._physicsEngine)return this;const n=this._physicsEngine.getPhysicsPlugin();return n.appendAnchor?(this._physicsEngine&&n.appendAnchor(this,e,t,i,r,s),this):this}addHook(e,t,i,r){if(!this._physicsEngine)return this;const s=this._physicsEngine.getPhysicsPlugin();return s.appendAnchor?(this._physicsEngine&&s.appendHook(this,e,t,i,r),this):this}sleep(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this}wakeUp(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this}clone(e){return e?new sa(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 W.PT),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()}getBoxSizeToRef(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this}getRadius(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0}syncBoneWithImpostor(e,t,i,r,s){const n=sa._TmpVecs[0],o=this.object;if(o.rotationQuaternion)if(s){const i=sa._TmpQuat;o.rotationQuaternion.multiplyToRef(s,i),e.setRotationQuaternion(i,1,t)}else e.setRotationQuaternion(o.rotationQuaternion,1,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),null==r&&(r=i.length()),n.x*=r,n.y*=r,n.z*=r),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,r,s,n){const o=this.object;if(o.rotationQuaternion)if(s){const i=sa._TmpQuat;e.getRotationQuaternionToRef(1,t,i),i.multiplyToRef(s,o.rotationQuaternion)}else e.getRotationQuaternionToRef(1,t,o.rotationQuaternion);const a=sa._TmpVecs[0],l=sa._TmpVecs[1];n||((n=sa._TmpVecs[2]).x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,l),e.getAbsolutePositionToRef(t,a),null==r&&i&&(r=i.length()),null!=r&&(a.x+=l.x*r,a.y+=l.y*r,a.z+=l.z*r),o.setAbsolutePosition(a)}}function na(e={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const t=0|Math.max(e.subdivisions?e.subdivisions:2,1),i=0|Math.max(e.tessellation?e.tessellation:16,3),r=Math.max(e.height?e.height:1,0),s=Math.max(e.radius?e.radius:.25,0),n=0|Math.max(e.capSubdivisions?e.capSubdivisions:6,1),o=i,a=t,l=Math.max(e.radiusTop?e.radiusTop:s,0),h=Math.max(e.radiusBottom?e.radiusBottom:s,0),c=r-(l+h),u=2*Math.PI,d=Math.max(e.topCapSubdivisions?e.topCapSubdivisions:n,1),f=Math.max(e.bottomCapSubdivisions?e.bottomCapSubdivisions:n,1),p=Math.acos((h-l)/r);let _=[];const m=[],g=[],v=[];let x=0;const b=[],S=.5*c,T=.5*Math.PI;let C,y;const E=W.Pq.Zero(),P=W.Pq.Zero(),A=Math.cos(p),R=Math.sin(p),I=new W.I9(l*R,S+l*A).subtract(new W.I9(h*R,h*A-S)).length(),M=l*p+I+h*(T-p);let O=0;for(y=0;y<=d;y++){const e=[],t=T-p*(y/d);O+=l*p/d;const i=Math.cos(t),r=Math.sin(t),s=i*l;for(C=0;C<=o;C++){const t=C/o,n=t*u+0,a=Math.sin(n),h=Math.cos(n);P.x=s*a,P.y=S+r*l,P.z=s*h,m.push(P.x,P.y,P.z),E.set(i*a,r,i*h),g.push(E.x,E.y,E.z),v.push(t,Tt.rX?O/M:1-O/M),e.push(x),x++}b.push(e)}const D=r-l-h+A*l-A*h,w=R*(h-l)/D;for(y=1;y<=a;y++){const e=[];O+=I/a;const t=R*(y*(h-l)/a+l);for(C=0;C<=o;C++){const i=C/o,r=i*u+0,s=Math.sin(r),n=Math.cos(r);P.x=t*s,P.y=S+A*l-y*D/a,P.z=t*n,m.push(P.x,P.y,P.z),E.set(s,w,n).normalize(),g.push(E.x,E.y,E.z),v.push(i,Tt.rX?O/M:1-O/M),e.push(x),x++}b.push(e)}for(y=1;y<=f;y++){const e=[],t=T-p-(Math.PI-p)*(y/f);O+=h*p/f;const i=Math.cos(t),r=Math.sin(t),s=i*h;for(C=0;C<=o;C++){const t=C/o,n=t*u+0,a=Math.sin(n),l=Math.cos(n);P.x=s*a,P.y=r*h-S,P.z=s*l,m.push(P.x,P.y,P.z),E.set(i*a,r,i*l),g.push(E.x,E.y,E.z),v.push(t,Tt.rX?O/M:1-O/M),e.push(x),x++}b.push(e)}for(C=0;Cn?n:Math.floor(o);const a=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE,l=e.uvs,h=e.colors,c=[],u=[],d=[],f=[],p=[],_=[],m=[],g=[];let v;const x=[],b=[];let S,T,C;if(t.length<2){const e=[],i=[];for(T=0;T0&&(I=A[C].subtract(A[C-1]).length(),M=I+m[S],p[S].push(M),m[S]=M),C++;r&&(C--,c.push(A[0].x,A[0].y,A[0].z),I=A[C].subtract(A[0]).length(),M=I+m[S],p[S].push(M),m[S]=M),x[S]=R+E,b[S]=y,y+=R+E}let w,N,F=null,L=null;for(T=0;T{let s=r[0].length;const n=a;let o=0;const l=n._originalBuilderSideOrientation===Yt.DOUBLESIDE?2:1;for(let a=1;a<=l;++a)for(let a=0;aoa(e,t,i),bt.CreateCapsule=na;const ca={CreateRibbon:ha};function ua(e){const t=[],i=[],r=[],s=[],n=e.radius||.5,o=e.tessellation||64,a=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,l=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE;t.push(0,0,0),s.push(.5,.5);const h=2*Math.PI*a,c=1===a?h/o:h/(o-1);let u=0;for(let e=0;eha(e,{pathArray:t,closeArray:i,closePath:r,offset:s,updatable:o,sideOrientation:a,instance:l},n);const fa={CreateDisc:da};function pa(e){const t=e.pattern||Yt.NO_FLIP,i=e.tileWidth||e.tileSize||1,r=e.tileHeight||e.tileSize||1,s=e.alignHorizontal||0,n=e.alignVertical||0,o=e.width||e.size||1,a=Math.floor(o/i);let l=o-a*i;const h=e.height||e.size||1,c=Math.floor(h/r);let u=h-c*r;const d=i*a/2,f=r*c/2;let p=0,_=0,m=0,g=0,v=0,x=0;if(l>0||u>0){switch(m=-d,g=-f,v=d,x=f,s){case Yt.CENTER:l/=2,m-=l,v+=l;break;case Yt.LEFT:v+=l,p=-l/2;break;case Yt.RIGHT:m-=l,p=l/2}switch(n){case Yt.CENTER:u/=2,g-=u,x+=u;break;case Yt.BOTTOM:x+=u,_=-u/2;break;case Yt.TOP:g-=u,_=u/2}}const b=[],S=[],T=[];T[0]=[0,0,1,0,1,1,0,1],T[1]=[0,0,1,0,1,1,0,1],t!==Yt.ROTATE_TILE&&t!==Yt.ROTATE_ROW||(T[1]=[1,1,0,1,0,0,1,0]),t!==Yt.FLIP_TILE&&t!==Yt.FLIP_ROW||(T[1]=[1,0,0,0,0,1,1,1]),t!==Yt.FLIP_N_ROTATE_TILE&&t!==Yt.FLIP_N_ROTATE_ROW||(T[1]=[0,1,1,1,1,0,0,0]);let C=[];const y=[],E=[];let P=0;for(let e=0;e0||u>0){const e=u>0&&(n===Yt.CENTER||n===Yt.TOP),o=u>0&&(n===Yt.CENTER||n===Yt.BOTTOM),h=l>0&&(s===Yt.CENTER||s===Yt.RIGHT),T=l>0&&(s===Yt.CENTER||s===Yt.LEFT);let A,R,I,M,O=[];if(e&&h&&(b.push(m+p,g+_,0),b.push(-d+p,g+_,0),b.push(-d+p,g+u+_,0),b.push(m+p,g+u+_,0),E.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,A=1-l/i,R=1-u/r,I=1,M=1,O=[A,R,I,R,I,M,A,M],t===Yt.ROTATE_ROW&&(O=[1-A,1-R,1-I,1-R,1-I,1-M,1-A,1-M]),t===Yt.FLIP_ROW&&(O=[1-A,R,1-I,R,1-I,M,1-A,M]),t===Yt.FLIP_N_ROTATE_ROW&&(O=[A,1-R,I,1-R,I,1-M,A,1-M]),C=C.concat(O),y.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),e&&T&&(b.push(d+p,g+_,0),b.push(v+p,g+_,0),b.push(v+p,g+u+_,0),b.push(d+p,g+u+_,0),E.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,A=0,R=1-u/r,I=l/i,M=1,O=[A,R,I,R,I,M,A,M],(t===Yt.ROTATE_ROW||t===Yt.ROTATE_TILE&&a%2==0)&&(O=[1-A,1-R,1-I,1-R,1-I,1-M,1-A,1-M]),(t===Yt.FLIP_ROW||t===Yt.FLIP_TILE&&a%2==0)&&(O=[1-A,R,1-I,R,1-I,M,1-A,M]),(t===Yt.FLIP_N_ROTATE_ROW||t===Yt.FLIP_N_ROTATE_TILE&&a%2==0)&&(O=[A,1-R,I,1-R,I,1-M,A,1-M]),C=C.concat(O),y.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),o&&h&&(b.push(m+p,f+_,0),b.push(-d+p,f+_,0),b.push(-d+p,x+_,0),b.push(m+p,x+_,0),E.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,A=1-l/i,R=0,I=1,M=u/r,O=[A,R,I,R,I,M,A,M],(t===Yt.ROTATE_ROW&&c%2==1||t===Yt.ROTATE_TILE&&c%1==0)&&(O=[1-A,1-R,1-I,1-R,1-I,1-M,1-A,1-M]),(t===Yt.FLIP_ROW&&c%2==1||t===Yt.FLIP_TILE&&c%2==0)&&(O=[1-A,R,1-I,R,1-I,M,1-A,M]),(t===Yt.FLIP_N_ROTATE_ROW&&c%2==1||t===Yt.FLIP_N_ROTATE_TILE&&c%2==0)&&(O=[A,1-R,I,1-R,I,1-M,A,1-M]),C=C.concat(O),y.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),o&&T&&(b.push(d+p,f+_,0),b.push(v+p,f+_,0),b.push(v+p,x+_,0),b.push(d+p,x+_,0),E.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,A=0,R=0,I=l/i,M=u/r,O=[A,R,I,R,I,M,A,M],(t===Yt.ROTATE_ROW&&c%2==1||t===Yt.ROTATE_TILE&&(c+a)%2==1)&&(O=[1-A,1-R,1-I,1-R,1-I,1-M,1-A,1-M]),(t===Yt.FLIP_ROW&&c%2==1||t===Yt.FLIP_TILE&&(c+a)%2==1)&&(O=[1-A,R,1-I,R,1-I,M,1-A,M]),(t===Yt.FLIP_N_ROTATE_ROW&&c%2==1||t===Yt.FLIP_N_ROTATE_TILE&&(c+a)%2==1)&&(O=[A,1-R,I,1-R,I,1-M,A,1-M]),C=C.concat(O),y.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),e){const e=[];A=0,R=1-u/r,I=1,M=1,e[0]=[A,R,I,R,I,M,A,M],e[1]=[A,R,I,R,I,M,A,M],t!==Yt.ROTATE_TILE&&t!==Yt.ROTATE_ROW||(e[1]=[1-A,1-R,1-I,1-R,1-I,1-M,1-A,1-M]),t!==Yt.FLIP_TILE&&t!==Yt.FLIP_ROW||(e[1]=[1-A,R,1-I,R,1-I,M,1-A,M]),t!==Yt.FLIP_N_ROTATE_TILE&&t!==Yt.FLIP_N_ROTATE_ROW||(e[1]=[A,1-R,I,1-R,I,1-M,A,1-M]);for(let r=0;rda(e,{radius:t,tessellation:i,sideOrientation:n,updatable:s},r);const ma={CreateTiledPlane:_a};function ga(e){const t=e.faceUV||new Array(6),i=e.faceColors,r=e.pattern||Yt.NO_FLIP,s=e.width||e.size||1,n=e.height||e.size||1,o=e.depth||e.size||1,a=e.tileWidth||e.tileSize||1,l=e.tileHeight||e.tileSize||1,h=e.alignHorizontal||0,c=e.alignVertical||0,u=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE;for(let e=0;e<6;e++)void 0===t[e]&&(t[e]=new W.IU(0,0,1,1)),i&&void 0===i[e]&&(i[e]=new H.ov(1,1,1,1));const d=s/2,f=n/2,p=o/2,_=[];for(let e=0;e<2;e++)_[e]=pa({pattern:r,tileWidth:a,tileHeight:l,width:s,height:n,alignVertical:c,alignHorizontal:h,sideOrientation:u});for(let e=2;e<4;e++)_[e]=pa({pattern:r,tileWidth:a,tileHeight:l,width:o,height:n,alignVertical:c,alignHorizontal:h,sideOrientation:u});let m=c;c===Yt.BOTTOM?m=Yt.TOP:c===Yt.TOP&&(m=Yt.BOTTOM);for(let e=4;e<6;e++)_[e]=pa({pattern:r,tileWidth:a,tileHeight:l,width:s,height:o,alignVertical:m,alignHorizontal:h,sideOrientation:u});let g=[],v=[],x=[],b=[];const S=[],T=[],C=[],y=[];let E=0,P=0;for(let e=0;e<6;e++){const r=_[e].positions.length;T[e]=[],C[e]=[];for(let t=0;te+P))),P+=T[e].length,i)for(let t=0;t<4;t++)S.push(i[e].r,i[e].g,i[e].b,i[e].a)}const A=new W.Pq(0,0,p),R=W.uq.RotationY(Math.PI);g=T[0].map((e=>W.Pq.TransformNormal(e,R).add(A))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),v=C[0].map((e=>W.Pq.TransformNormal(e,R))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),g=g.concat(T[1].map((e=>e.subtract(A))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(C[1].map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const I=new W.Pq(d,0,0),M=W.uq.RotationY(-Math.PI/2);g=g.concat(T[2].map((e=>W.Pq.TransformNormal(e,M).add(I))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(C[2].map((e=>W.Pq.TransformNormal(e,M))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const O=W.uq.RotationY(Math.PI/2);g=g.concat(T[3].map((e=>W.Pq.TransformNormal(e,O).subtract(I))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(C[3].map((e=>W.Pq.TransformNormal(e,O))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const D=new W.Pq(0,f,0),w=W.uq.RotationX(Math.PI/2);g=g.concat(T[4].map((e=>W.Pq.TransformNormal(e,w).add(D))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(C[4].map((e=>W.Pq.TransformNormal(e,w))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const N=W.uq.RotationX(-Math.PI/2);g=g.concat(T[5].map((e=>W.Pq.TransformNormal(e,N).subtract(D))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(C[5].map((e=>W.Pq.TransformNormal(e,N))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),bt._ComputeSides(u,g,b,v,x);const F=new bt;if(F.indices=b,F.positions=g,F.normals=v,F.uvs=x,i){const e=u===bt.DOUBLESIDE?S.concat(S):S;F.colors=e}return F}function va(e,t,i=null){const r=new Yt(e,i);return t.sideOrientation=Yt._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,ga(t).applyToMesh(r,t.updatable),r}bt.CreateTiledPlane=pa;const xa={CreateTiledBox:va};function ba(e){const t=[],i=[],r=[],s=[],n=e.radius||2,o=e.tube||.5,a=e.radialSegments||32,l=e.tubularSegments||32,h=e.p||2,c=e.q||3,u=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE,d=e=>{const t=Math.cos(e),i=Math.sin(e),r=c/h*e,s=Math.cos(r),o=n*(2+s)*.5*t,a=n*(2+s)*i*.5,l=n*Math.sin(r)*.5;return new W.Pq(o,a,l)};let f,p;for(f=0;f<=a;f++){const e=f%a/a*2*h*Math.PI,t=d(e),r=d(e+.01),n=r.subtract(t);let c=r.add(t);const u=W.Pq.Cross(n,c);for(c=W.Pq.Cross(u,n),u.normalize(),c.normalize(),p=0;pSa(e,{radius:t,tube:i,radialSegments:r,tubularSegments:s,p:n,q:o,sideOrientation:h,updatable:l},a),Yt._LinesMeshParser=(e,t)=>Ca.Parse(e,t);class Ca extends Yt{_isShaderMaterial(e){return"ShaderMaterial"===e.getClassName()}constructor(e,t=null,r=null,s=null,n,o,a,l){super(e,t,r,s,n),this.useVertexColor=o,this.useVertexAlpha=a,this.color=new H.v9(1,1,1),this.alpha=1,this._shaderLanguage=0,s&&(this.color=s.color.clone(),this.alpha=s.alpha,this.useVertexColor=s.useVertexColor,this.useVertexAlpha=s.useVertexAlpha),this.intersectionThreshold=.1;const h={attributes:[st.R.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:[],useClipPlane:null,shaderLanguage:0};!1===a?h.needAlphaBlending=!1:h.defines.push("#define VERTEXALPHA"),o?(h.defines.push("#define VERTEXCOLOR"),h.attributes.push(st.R.ColorKind)):(h.uniforms.push("color"),this._color4=new H.ov),l?this.material=l:(this.getScene().getEngine().isWebGPU&&!Ca.ForceGLSL&&(this._shaderLanguage=1),h.shaderLanguage=this._shaderLanguage,h.extraInitializationsAsync=async()=>{1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,88130)),Promise.resolve().then(i.bind(i,88516))]):await Promise.all([Promise.resolve().then(i.bind(i,53501)),Promise.resolve().then(i.bind(i,27683))])},this.material=new xo("colorShader",this.getScene(),"color",h,!1),this.material.doNotSerialize=!0)}isReady(){return!!this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage||this.hasThinInstances)&&super.isReady()}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=Vt.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:e,g:t,b:i}=this.color;this._color4.set(e,t,i,this.alpha),this._lineMaterial.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const r=this.getScene().getEngine();return this._unIndexed?r.drawArraysType(Vt.LineListDrawMode,e.verticesStart,e.verticesCount,i):r.drawElementsType(Vt.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 Ca(e,this.getScene(),t,this,i)}createInstance(e){const t=new ya(e,this);if(this.instancedBuffers){t.instancedBuffers={};for(const e in this.instancedBuffers)t.instancedBuffers[e]=this.instancedBuffers[e]}return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){const i=new Ca(e.name,t);return i.color=H.v9.FromArray(e.color),i.alpha=e.alpha,i}}Ca.ForceGLSL=!1;class ya extends Kt{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function Ea(e){const t=[],i=[],r=e.lines,s=e.colors,n=[];let o=0;for(let e=0;e0&&(t.push(o-1),t.push(o)),o++}}const a=new bt;return a.indices=t,a.positions=i,s&&(a.colors=n),a}function Pa(e){const t=e.dashSize||3,i=e.gapSize||1,r=e.dashNb||200,s=e.points,n=[],o=[],a=W.Pq.Zero();let l=0,h=0,c=0,u=0,d=0,f=0,p=0;for(p=0;p{const t=W.Pq.Zero(),i=e.length/6;let n=0,o=0,a=0,l=0,h=0,c=0,u=0,d=0;for(u=0;uRa(e,{points:t,updatable:r,instance:s},i),Yt.CreateDashedLines=(e,t,i,r,s,n=null,o,a)=>Ia(e,{points:t,dashSize:i,gapSize:r,dashNb:s,updatable:o,instance:a},n);class Oa extends W.I9{constructor(e,t){super(e.x,e.y),this.index=t}}class Da{constructor(){this.elements=[]}add(e){const t=[];return e.forEach((e=>{const i=new Oa(e,this.elements.length);t.push(i),this.elements.push(i)})),t}computeBounds(){const e=new W.I9(this.elements[0].x,this.elements[0].y),t=new W.I9(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 wa{static Rectangle(e,t,i,r){return[new W.I9(e,t),new W.I9(i,t),new W.I9(i,r),new W.I9(e,r)]}static Circle(e,t=0,i=0,r=32){const s=[];let n=0;const o=2*Math.PI/r;for(let a=0;a!isNaN(e)));let i;const r=[];for(i=0;i<(2147483646&t.length);i+=2)r.push(new W.I9(t[i],t[i+1]));return r}static StartingAt(e,t){return ve.Cu.StartingAt(e,t)}}class Na{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,r=earcut){let s;this._points=new Da,this._outlinepoints=new Da,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=r,this._name=e,this._scene=i||he.q.LastCreatedScene,s=t instanceof ve.Cu?t.getPoints():t,this._addToepoint(s),this._points.add(s),this._outlinepoints.add(s),void 0===this.bjsEarcut&&Z.V.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new Da;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){const r=new Yt(this._name,this._scene),s=this.buildVertexData(t,i);return r.setVerticesData(st.R.PositionKind,s.positions,e),r.setVerticesData(st.R.NormalKind,s.normals,e),r.setVerticesData(st.R.UVKind,s.uvs,e),r.setIndices(s.indices),r}buildVertexData(e=0,t=2){const i=new bt,r=[],s=[],n=[],o=this._points.computeBounds();this._points.elements.forEach((e=>{r.push(0,1,0),s.push(e.x,0,e.y),n.push((e.x-o.min.x)/o.width,(e.y-o.min.y)/o.height)}));const a=[],l=this.bjsEarcut(this._epoints,this._eholes,2);for(let e=0;e0){const i=s.length/3;this._points.elements.forEach((t=>{r.push(0,-1,0),s.push(t.x,-e,t.y),n.push(1-(t.x-o.min.x)/o.width,1-(t.y-o.min.y)/o.height)}));const l=a.length;for(let e=0;e{this._addSide(s,r,n,a,o,i,e,!0,t)}))}return i.indices=a,i.positions=s,i.normals=r,i.uvs=n,i}_addSide(e,t,i,r,s,n,o,a,l){let h=e.length/3,c=0;for(let u=0;ul?Tl?C1),o=t.rotationFunction||(()=>0),a=t.closePath||t.ribbonCloseArray||!1,l=t.closeShape||t.ribbonClosePath||!1,h=0===t.cap?0:t.cap||Yt.NO_CAP,c=t.updatable,u=t.firstNormal||null,d=t.adjustFrame||!1;return Ga(e,s,r,null,null,n,o,a,l,h,!0,i,!!c,Yt._GetDefaultSideOrientation(t.sideOrientation),t.instance||null,t.invertUV||!1,t.frontUVs||null,t.backUVs||null,u,d)}function Ga(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m,g,v,x){const b=(e,t,i,r,s,n,o,a,l,h,c)=>{const u=i.getTangents(),d=i.getNormals(),f=i.getBinormals(),p=i.getDistances();if(c)for(let e=0;e0){let t=u[e-1];W.Pq.Dot(t,u[e])<0&&u[e].scaleInPlace(-1),t=d[e-1],W.Pq.Dot(t,d[e])<0&&d[e].scaleInPlace(-1),t=f[e-1],W.Pq.Dot(t,f[e])<0&&f[e].scaleInPlace(-1)}let _=0;const m=h&&a?a:()=>null!==n?n:0,g=h&&o?o:()=>null!==s?s:1;let v=l===Yt.NO_CAP||l===Yt.CAP_END?0:2;const x=W.AA.Matrix[0];for(let i=0;i{const t=Array(),i=W.Pq.Zero();let r;for(r=0;r3?0:h,c,x);const C=ha(e,{pathArray:T,closeArray:a,closePath:l,updatable:d,sideOrientation:f,invertUV:_,frontUVs:m||void 0,backUVs:g||void 0},u);return C._creationDataStorage.pathArray=T,C._creationDataStorage.path3D=S,C._creationDataStorage.cap=h,C}bt.CreatePolygon=Fa,Yt.CreatePolygon=(e,t,i,r,s,n,o=earcut)=>La(e,{shape:t,holes:r,updatable:s,sideOrientation:n},i,o),Yt.ExtrudePolygon=(e,t,i,r,s,n,o,a=earcut)=>Ba(e,{shape:t,holes:s,depth:i,updatable:n,sideOrientation:o},r,a);const za={ExtrudeShape:ka,ExtrudeShapeCustom:Ua};function Wa(e,t,i=null){const r=t.arc?t.arc<=0||t.arc>1?1:t.arc:1,s=void 0===t.closed||t.closed,n=t.shape,o=t.radius||1,a=t.tessellation||64,l=t.clip||0,h=t.updatable,c=Yt._GetDefaultSideOrientation(t.sideOrientation),u=t.cap||Yt.NO_CAP,d=2*Math.PI,f=[],p=t.invertUV||!1;let _=0,m=0;const g=d/a*r;let v,x;for(_=0;_<=a-l;_++){for(x=[],u!=Yt.CAP_START&&u!=Yt.CAP_ALL||(x.push(new W.Pq(0,n[0].y,0)),x.push(new W.Pq(Math.cos(_*g)*n[0].x*o,n[0].y,Math.sin(_*g)*n[0].x*o))),m=0;mka(e,{shape:t,path:i,scale:r,rotation:s,cap:0===n?0:n||Yt.NO_CAP,sideOrientation:l,instance:h,updatable:a},o),Yt.ExtrudeShapeCustom=(e,t,i,r,s,n,o,a,l,h,c,u)=>Ua(e,{shape:t,path:i,scaleFunction:r,rotationFunction:s,ribbonCloseArray:n,ribbonClosePath:o,cap:0===a?0:a||Yt.NO_CAP,sideOrientation:c,instance:u,updatable:h},l);const Ha={CreateLathe:Wa};function Xa(e,t,i=null){const r=t.path;let s=t.instance,n=1;void 0!==t.radius?n=t.radius:s&&(n=s._creationDataStorage.radius);const o=t.tessellation||64,a=t.radiusFunction||null;let l=t.cap||Yt.NO_CAP;const h=t.invertUV||!1,c=t.updatable,u=Yt._GetDefaultSideOrientation(t.sideOrientation);t.arc=t.arc&&(t.arc<=0||t.arc>1)?1:t.arc||1;const d=(e,t,i,r,s,n,o,a)=>{const l=t.getTangents(),h=t.getNormals(),c=t.getDistances(),u=2*Math.PI/s*a,d=n||(()=>r);let f,p,_,m;const g=W.AA.Matrix[0];let v=o===Yt.NO_CAP||o===Yt.CAP_END?0:2;for(let t=0;t{const r=Array();for(let s=0;s3?0:l,p=d(r,f,new Array,n,o,a,l,t.arc);const _=ha(e,{pathArray:p,closePath:!0,closeArray:!1,updatable:c,sideOrientation:u,invertUV:h,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return _._creationDataStorage.pathArray=p,_._creationDataStorage.path3D=f,_._creationDataStorage.tessellation=o,_._creationDataStorage.cap=l,_._creationDataStorage.arc=t.arc,_._creationDataStorage.radius=n,_}Yt.CreateLathe=(e,t,i,r,s,n,o)=>Wa(e,{shape:t,radius:i,tessellation:r,sideOrientation:o,updatable:n},s);const qa={CreateTube:Xa};function Ya(e){const t=[];t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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 i=e.type&&(e.type<0||e.type>=t.length)?0:e.type||0,r=e.size,s=e.sizeX||r||1,n=e.sizeY||r||1,o=e.sizeZ||r||1,a=e.custom||t[i],l=a.face.length,h=e.faceUV||new Array(l),c=e.faceColors,u=void 0===e.flat||e.flat,d=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE,f=[],p=[],_=[],m=[],g=[];let v=0,x=0;const b=[];let S,T,C,y,E,P,A=0,R=0;if(u)for(R=0;RXa(e,{path:t,radius:i,tessellation:r,radiusFunction:s,arc:1,cap:n,updatable:a,sideOrientation:l,instance:h},o);const ja={CreatePolyhedron:Ka};function $a(e){const t=e.sideOrientation||bt.DEFAULTSIDE,i=e.radius||1,r=void 0===e.flat||e.flat,s=0|(e.subdivisions||4),n=e.radiusX||i,o=e.radiusY||i,a=e.radiusZ||i,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=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],p=[],_=[],m=[],g=[];let v=0;const x=new Array(3),b=new Array(3);let S;for(S=0;S<3;S++)x[S]=W.Pq.Zero(),b[S]=W.I9.Zero();for(let e=0;e<20;e++){for(S=0;S<3;S++){const t=c[3*e+S];x[S].copyFromFloats(h[3*u[t]],h[3*u[t]+1],h[3*u[t]+2]),x[S].normalize(),b[S].copyFromFloats(.134765625*d[2*t]+.05859375+-.0390625*f[e],.2333984375*d[2*t+1]+.025390625+.01953125*f[e])}const t=(e,t,i,l)=>{const h=W.Pq.Lerp(x[0],x[2],t/s),c=W.Pq.Lerp(x[1],x[2],t/s),u=s===t?x[2]:W.Pq.Lerp(h,c,e/(s-t));let d;if(u.normalize(),r){const e=W.Pq.Lerp(x[0],x[2],l/s),t=W.Pq.Lerp(x[1],x[2],l/s);d=W.Pq.Lerp(e,t,i/(s-l))}else d=new W.Pq(u.x,u.y,u.z);d.x/=n,d.y/=o,d.z/=a,d.normalize();const f=W.I9.Lerp(b[0],b[2],t/s),S=W.I9.Lerp(b[1],b[2],t/s),T=s===t?b[2]:W.I9.Lerp(f,S,e/(s-t));_.push(u.x*n,u.y*o,u.z*a),m.push(d.x,d.y,d.z),g.push(T.x,Tt.rX?1-T.y:T.y),p.push(v),v++};for(let e=0;eKa(e,t,i);const Za={CreateIcoSphere:Qa};bt.CreateIcoSphere=$a,Yt.CreateIcoSphere=(e,t,i)=>Qa(e,t,i);const Ja=new W.Pq(1,0,0),el=new W.Pq(-1,0,0),tl=new W.Pq(0,1,0),il=new W.Pq(0,-1,0),rl=new W.Pq(0,0,1),sl=new W.Pq(0,0,-1);class nl{constructor(e=W.Pq.Zero(),t=W.Pq.Up(),i=W.I9.Zero(),r=0,s=0,n=null,o=null,a=null,l=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=r,this.vertexIdxForBones=s,this.localPositionOverride=n,this.localNormalOverride=o,this.matrixIndicesOverride=a,this.matrixWeightsOverride=l}clone(){return new nl(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,this.localPositionOverride?.slice(),this.localNormalOverride?.slice(),this.matrixIndicesOverride?.slice(),this.matrixWeightsOverride?.slice())}}function ol(e,t,i){const r=!!t.skeleton,s=i.localMode||r,n=t.getIndices(),o=r?t.getPositionData(!0,!0):t.getVerticesData(st.R.PositionKind),a=r?t.getNormalsData(!0,!0):t.getVerticesData(st.R.NormalKind),l=s?r?t.getVerticesData(st.R.PositionKind):o:null,h=s?r?t.getVerticesData(st.R.NormalKind):a:null,c=t.getVerticesData(st.R.UVKind),u=r?t.getVerticesData(st.R.MatricesIndicesKind):null,d=r?t.getVerticesData(st.R.MatricesWeightsKind):null,f=r?t.getVerticesData(st.R.MatricesIndicesExtraKind):null,p=r?t.getVerticesData(st.R.MatricesWeightsExtraKind):null,_=i.position||W.Pq.Zero();let m=i.normal||W.Pq.Up();const g=i.size||W.Pq.One(),v=i.angle||0;if(!m){const e=new W.Pq(0,0,1),i=t.getScene().activeCamera,r=W.Pq.TransformCoordinates(e,i.getWorldMatrix());m=i.globalPosition.subtract(r)}const x=-Math.atan2(m.z,m.x)-Math.PI/2,b=Math.sqrt(m.x*m.x+m.z*m.z),S=Math.atan2(m.y,b),T=new bt;T.indices=[],T.positions=[],T.normals=[],T.uvs=[],T.matricesIndices=r?[]:null,T.matricesWeights=r?[]:null,T.matricesIndicesExtra=f?[]:null,T.matricesWeightsExtra=p?[]:null;let C=0;const y=(e,t)=>{const r=new nl;if(!n||!o||!a)return r;const s=n[e];if(r.vertexIdx=3*s,r.vertexIdxForBones=4*s,r.position=new W.Pq(o[3*s],o[3*s+1],o[3*s+2]),W.Pq.TransformCoordinatesToRef(r.position,t,r.position),r.normal=new W.Pq(a[3*s],a[3*s+1],a[3*s+2]),W.Pq.TransformNormalToRef(r.normal,t,r.normal),i.captureUVS&&c){const e=c[2*s+1];r.uv=new W.I9(c[2*s],Tt.rX?1-e:e)}return r},E=[0,0,0,0],P=(e,t)=>{if(0===e.length)return e;const i=.5*Math.abs(W.Pq.Dot(g,t)),r=(e,t,i,r)=>{for(let s=0;s{const n=W.Pq.GetClipFactor(e.position,s.position,t,i);let o=E,a=E;if(u&&d){const t=e.matrixIndicesOverride?0:e.vertexIdxForBones,i=e.matrixIndicesOverride??u,l=e.matrixWeightsOverride??d,h=s.matrixIndicesOverride?0:s.vertexIdxForBones,c=s.matrixIndicesOverride??u,f=s.matrixWeightsOverride??d;o=[0,0,0,0],a=[0,0,0,0];let p=0;for(let e=0;e<4;++e)if(l[t+e]>0){const s=r(c,i[t+e],h,4);o[p]=i[t+e],a[p]=(0,ar.Lerp)(l[t+e],s>=0?f[s]:0,n),p++}for(let e=0;e<4&&p<4;++e){const s=c[h+e];-1===r(i,s,t,4)&&(o[p]=s,a[p]=(0,ar.Lerp)(0,f[h+e],n),p++)}const _=a[0]+a[1]+a[2]+a[3];a[0]/=_,a[1]/=_,a[2]/=_,a[3]/=_}const c=e.localPositionOverride?e.localPositionOverride[0]:l?.[e.vertexIdx]??0,f=e.localPositionOverride?e.localPositionOverride[1]:l?.[e.vertexIdx+1]??0,p=e.localPositionOverride?e.localPositionOverride[2]:l?.[e.vertexIdx+2]??0,_=s.localPositionOverride?s.localPositionOverride[0]:l?.[s.vertexIdx]??0,m=s.localPositionOverride?s.localPositionOverride[1]:l?.[s.vertexIdx+1]??0,g=s.localPositionOverride?s.localPositionOverride[2]:l?.[s.vertexIdx+2]??0,v=e.localNormalOverride?e.localNormalOverride[0]:h?.[e.vertexIdx]??0,x=e.localNormalOverride?e.localNormalOverride[1]:h?.[e.vertexIdx+1]??0,b=e.localNormalOverride?e.localNormalOverride[2]:h?.[e.vertexIdx+2]??0,S=v+((s.localNormalOverride?s.localNormalOverride[0]:h?.[s.vertexIdx]??0)-v)*n,T=x+((s.localNormalOverride?s.localNormalOverride[1]:h?.[s.vertexIdx+1]??0)-x)*n,C=b+((s.localNormalOverride?s.localNormalOverride[2]:h?.[s.vertexIdx+2]??0)-b)*n,y=Math.sqrt(S*S+T*T+C*C);return new nl(W.Pq.Lerp(e.position,s.position,n),W.Pq.Lerp(e.normal,s.normal,n).normalize(),W.I9.Lerp(e.uv,s.uv,n),-1,-1,l?[c+(_-c)*n,f+(m-f)*n,p+(g-p)*n]:null,h?[S/y,T/y,C/y]:null,o,a)};let n=null;e.length>3&&(n=[]);for(let r=0;r0,d=W.Pq.Dot(e[r+1].position,t)-i>0,f=W.Pq.Dot(e[r+2].position,t)-i>0;switch(o=(u?1:0)+(d?1:0)+(f?1:0),o){case 0:e.length>3?(n.push(e[r]),n.push(e[r+1]),n.push(e[r+2])):n=e;break;case 1:if(n=n??new Array,u&&(a=e[r+1],l=e[r+2],h=s(e[r],a),c=s(e[r],l)),d){a=e[r],l=e[r+2],h=s(e[r+1],a),c=s(e[r+1],l),n.push(h),n.push(l.clone()),n.push(a.clone()),n.push(l.clone()),n.push(h.clone()),n.push(c);break}f&&(a=e[r],l=e[r+1],h=s(e[r+2],a),c=s(e[r+2],l)),a&&l&&h&&c&&(n.push(a.clone()),n.push(l.clone()),n.push(h),n.push(c),n.push(h.clone()),n.push(l.clone()));break;case 2:n=n??new Array,u||(a=e[r].clone(),l=s(a,e[r+1]),h=s(a,e[r+2]),n.push(a),n.push(l),n.push(h)),d||(a=e[r+1].clone(),l=s(a,e[r+2]),h=s(a,e[r]),n.push(a),n.push(l),n.push(h)),f||(a=e[r+2].clone(),l=s(a,e[r]),h=s(a,e[r+1]),n.push(a),n.push(l),n.push(h))}}return n},A=t instanceof Yt?t:null,R=A?._thinInstanceDataStorage.matrixData,I=A?.thinInstanceCount||1,M=W.AA.Matrix[0];M.copyFrom(W.uq.IdentityReadOnly);for(let e=0;eol(e,t,{position:i,normal:r,size:s,angle:n});class ll{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&(e=Math.floor(e),Z.V.Warn("x is not an integer, floor(x) used")),t!==Math.floor(t)&&(t=Math.floor(t),Z.V.Warn("y is not an integer, floor(y) used"))}clone(){return new ll(this.x,this.y)}rotate60About(e){const t=this.x;return this.x=e.x+e.y-this.y,this.y=t+this.y-e.x,this}rotateNeg60About(e){const t=this.x;return this.x=t+this.y-e.y,this.y=e.x+e.y-t,this}rotate120(e,t){e!==Math.floor(e)&&(e=Math.floor(e),Z.V.Warn("m not an integer only floor(m) used")),t!==Math.floor(t)&&(t=Math.floor(t),Z.V.Warn("n not an integer only floor(n) used"));const i=this.x;return this.x=e-i-this.y,this.y=t+i,this}rotateNeg120(e,t){e!==Math.floor(e)&&(e=Math.floor(e),Z.V.Warn("m is not an integer, floor(m) used")),t!==Math.floor(t)&&(t=Math.floor(t),Z.V.Warn("n is not an integer, floor(n) used"));const i=this.x;return this.x=this.y-t,this.y=e+t-i-this.y,this}toCartesianOrigin(e,t){const i=W.Pq.Zero();return i.x=e.x+2*this.x*t+this.y*t,i.y=e.y+Math.sqrt(3)*this.y*t,i}static Zero(){return new ll(0,0)}}class hl{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new cl("icosahedron","Regular",[[0,lt.a6,-1],[-lt.a6,1,0],[-1,0,-lt.a6],[1,0,-lt.a6],[lt.a6,1,0],[0,lt.a6,1],[-1,0,lt.a6],[-lt.a6,-1,0],[0,-lt.a6,-1],[lt.a6,-1,0],[1,0,lt.a6],[0,-lt.a6,1]],[[0,2,1],[0,3,2],[0,4,3],[0,5,4],[0,1,5],[7,6,1],[8,7,2],[9,8,3],[10,9,4],[6,10,5],[2,7,1],[3,8,2],[4,9,3],[5,10,4],[1,6,5],[11,6,7],[11,7,8],[11,8,9],[11,9,10],[11,10,6]])}setIndices(){let e=12;const t={},i=this.m,r=this.n;let s,n,o,a,l,h=i,c=1,u=0;0!==r&&(h=(0,ar.HighestCommonFactor)(i,r)),c=i/h,u=r/h;const d=ll.Zero(),f=new ll(i,r),p=new ll(-r,i+r),_=ll.Zero(),m=ll.Zero(),g=ll.Zero();let v,x,b,S,T=[];const C=[],y=this.vertByDist,E=(i,r,s,n)=>{v=i+"|"+s,x=r+"|"+n,v in t||x in t?v in t&&!(x in t)?t[x]=t[v]:x in t&&!(v in t)&&(t[v]=t[x]):(t[v]=e,t[x]=e,e++),y[s][0]>2?C[t[v]]=[-y[s][0],y[s][1],t[v]]:C[t[v]]=[T[y[s][0]],y[s][1],t[v]]};this.IDATA.edgematch=[[1,"B"],[2,"B"],[3,"B"],[4,"B"],[0,"B"],[10,"O",14,"A"],[11,"O",10,"A"],[12,"O",11,"A"],[13,"O",12,"A"],[14,"O",13,"A"],[0,"O"],[1,"O"],[2,"O"],[3,"O"],[4,"O"],[19,"B",5,"A"],[15,"B",6,"A"],[16,"B",7,"A"],[17,"B",8,"A"],[18,"B",9,"A"]];for(let x=0;x<20;x++){if(T=this.IDATA.face[x],o=T[2],a=T[1],l=T[0],b=d.x+"|"+d.y,v=x+"|"+b,v in t||(t[v]=o,C[o]=[T[y[b][0]],y[b][1]]),b=f.x+"|"+f.y,v=x+"|"+b,v in t||(t[v]=a,C[a]=[T[y[b][0]],y[b][1]]),b=p.x+"|"+p.y,v=x+"|"+b,v in t||(t[v]=l,C[l]=[T[y[b][0]],y[b][1]]),s=this.IDATA.edgematch[x][0],n=this.IDATA.edgematch[x][1],"B"===n)for(let e=1;e2?C[t[v]]=[-y[b][0],y[b][1],t[v]]:C[t[v]]=[T[y[b][0]],y[b][1],t[v]])}this.closestTo=C,this.vecToidx=t}calcCoeffs(){const e=this.m,t=this.n,i=Math.sqrt(3)/3,r=e*e+t*t+e*t;this.coau=(e+t)/r,this.cobu=-t/r,this.coav=-i*(e-t)/r,this.cobv=i*(2*e+t)/r}createInnerFacets(){const e=this.m,t=this.n;for(let i=0;i0&&e0){const r=(0,ar.HighestCommonFactor)(e,t),s=e/r,n=t/r;for(let o=1;oe.x-t.x)),i.sort(((e,t)=>e.y-t.y));const o=new Array(e+t+1),a=new Array(e+t+1);for(let e=0;e{const s=i.clone();return"A"===r&&s.rotateNeg120(e,t),"B"===r&&s.rotate120(e,t),s.x<0?s.y:s.x+s.y},d=[],f=[],p=[],_=[],m={},g=[];let v=-1,x=-1;for(let e=0;ee[2]-t[2])),g.sort(((e,t)=>e[3]-t[3])),g.sort(((e,t)=>e[1]-t[1])),g.sort(((e,t)=>e[0]-t[0]));for(let e=0;et.vecToidx[e+i])))}mapABOBtoDATA(e,t){const i=t.IDATA.edgematch[e][0];for(let r=0;r-1?i[e][1]>0&&t[i[e][0]].push([e,i[e][1]]):t[12].push([e,i[e][0]]);const r=[];for(let e=0;e<12;e++)r[e]=e;let s=12;for(let e=0;e<12;e++){t[e].sort(((e,t)=>e[1]-t[1]));for(let i=0;ie[3]-t[3]));for(let e=0;e0;)s=t[a],this.face[s].indexOf(o)>-1?(n=(this.face[s].indexOf(o)+1)%3,o=this.face[s][n],i.push(o),r.push(s),t.splice(a,1),a=0):a++;return this.adjacentFaces.push(i),r}toGoldbergPolyhedronData(){const e=new cl("GeoDual","Goldberg",[],[]);e.name="GD dual";const t=this.vertex.length,i=new Array(t);for(let e=0;e{r=0,s=0,n=0,o=this.face[t];for(let e=0;e<3;e++)a=this.vertex[o[e]],r+=a[0],s+=a[1],n+=a[2];e.vertex[t]=[r/3,s/3,n/3]}));return e}static BuildGeodesicData(e){const t=new ul("Geodesic-m-n","Geodesic",[[0,lt.a6,-1],[-lt.a6,1,0],[-1,0,-lt.a6],[1,0,-lt.a6],[lt.a6,1,0],[0,lt.a6,1],[-1,0,lt.a6],[-lt.a6,-1,0],[0,-lt.a6,-1],[lt.a6,-1,0],[1,0,lt.a6],[0,-lt.a6,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let i=0;ir){const e=s;s=r,r=e,Z.V.Warn("n > m therefore m and n swapped")}const n=new hl;return n.build(r,s),Ka(e,{custom:ul.BuildGeodesicData(n),size:t.size,sizeX:t.sizeX,sizeY:t.sizeY,sizeZ:t.sizeZ,faceUV:t.faceUV,faceColors:t.faceColors,flat:t.flat,updatable:t.updatable,sideOrientation:t.sideOrientation,frontUVs:t.frontUVs,backUVs:t.backUVs},i)}Yt._GoldbergMeshParser=(e,t)=>fl.Parse(e,t);class fl extends Yt{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return void 0===t?(e>this.goldbergData.nbUnsharedFaces-1&&(Z.V.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(Z.V.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(Z.V.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let t=0;t1&&(c=1),l.push(c,u);for(let e=0;e<6;e++)c=n.x+o*Math.cos(a+e*Math.PI/3),u=n.y+o*Math.sin(a+e*Math.PI/3),c<0&&(c=0),c>1&&(c=1),h.push(c,u);for(let e=r;eH.ov.FromArray(e))),i.faceCenters=i.faceCenters.map((e=>W.Pq.FromArray(e))),i.faceZaxis=i.faceZaxis.map((e=>W.Pq.FromArray(e))),i.faceXaxis=i.faceXaxis.map((e=>W.Pq.FromArray(e))),i.faceYaxis=i.faceYaxis.map((e=>W.Pq.FromArray(e)));const r=new fl(e.name,t);return r.goldbergData=i,r}}function pl(e,t){const i=e.size,r=e.sizeX||i||1,s=e.sizeY||i||1,n=e.sizeZ||i||1,o=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE,a=[],l=[],h=[],c=[];let u=1/0,d=-1/0,f=1/0,p=-1/0;for(let e=0;ea){const e=l;l=a,a=e,Z.V.Warn("n > m therefore m and n swapped")}const h=new hl;h.build(a,l);const c=ul.BuildGeodesicData(h),u=c.toGoldbergPolyhedronData(),d=new fl(e,i);t.sideOrientation=Yt._GetDefaultSideOrientation(t.sideOrientation),d._originalBuilderSideOrientation=t.sideOrientation,pl(t,u).applyToMesh(d,t.updatable),d.goldbergData.nbSharedFaces=c.sharedNodes,d.goldbergData.nbUnsharedFaces=c.poleNodes,d.goldbergData.adjacentFaces=c.adjacentFaces,d.goldbergData.nbFaces=d.goldbergData.nbSharedFaces+d.goldbergData.nbUnsharedFaces,d.goldbergData.nbFacesAtPole=(d.goldbergData.nbUnsharedFaces-12)/12;for(let e=0;e0?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 gl(e,t,i,r,s,n){const o=n.glyphs[e]||n.glyphs["?"];if(!o)return null;const a=new ml(s);if(o.o){const e=o.o.split(" ");for(let s=0,n=e.length;slt.bH&&(e.x=1*Math.sign(e.x)),Math.abs(e.y-1)>lt.bH&&(e.y=1*Math.sign(e.y)),Math.abs(e.z-1)>lt.bH&&(e.z=1*Math.sign(e.z))}_updateDebugConstraint(e,t){if(!e._initOptions)return;const{pivotA:i,pivotB:r,axisA:s,axisB:n,perpAxisA:o,perpAxisB:a}=e._initOptions;i&&r&&s&&n&&o&&a&&t.getDescendants(!0).forEach((e=>{const t=e.getDescendants(!0)[0],l=e.getDescendants(!0)[1],{parentBody:h,parentBodyIndex:c}=t.metadata,{childBody:u,childBodyIndex:d}=l.metadata,f=this._getTransformFromBodyToRef(h,W.AA.Matrix[0],c),p=this._getTransformFromBodyToRef(u,W.AA.Matrix[1],d);f.decomposeToTransformNode(t),this._makeScalingUnitInPlace(t.scaling),p.decomposeToTransformNode(l),this._makeScalingUnitInPlace(l.scaling);const _=t.getDescendants(!0)[0];_.position.copyFrom(i);const m=l.getDescendants(!0)[0];m.position.copyFrom(r),W.PT.FromRotationMatrixToRef(W.uq.FromXYZAxesToRef(s,o,W.Pq.CrossToRef(s,o,W.AA.Vector3[0]),W.AA.Matrix[0]),_.rotationQuaternion),W.PT.FromRotationMatrixToRef(W.uq.FromXYZAxesToRef(n,a,W.Pq.CrossToRef(n,a,W.AA.Vector3[1]),W.AA.Matrix[1]),m.rotationQuaternion)}))}showImpostor(e,t){if(!this._scene)return null;for(let t=0;tthis._updateDebugMeshes(),this._scene.registerBeforeRender(this._renderFunction)),this._numMeshes++),i}showBody(e){if(!this._scene)return null;for(let t=0;tthis._updateDebugMeshes(),this._scene.registerBeforeRender(this._renderFunction)),this._numBodies++),t}showInertia(e){if(!this._scene)return null;for(let t=0;tthis._updateInertiaMeshes(),this._scene.registerBeforeRender(this._inertiaRenderFunction)),this._numInertiaBodies++),t}showConstraint(e){if(!this._scene)return null;for(let t=0;tthis._updateDebugConstraints(),this._scene.registerBeforeRender(this._constraintRenderFunction)),this._numConstraints++),t}hideImpostor(e){if(!e||!this._scene||!this._utilityLayer)return;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let r=0;r-1&&this._debugMeshMeshes.splice(s,1),this._numMeshes--,this._numMeshes>0?(this._meshes[r]=this._meshes[this._numMeshes],this._impostors[r]=this._impostors[this._numMeshes],this._meshes[this._numMeshes]=null,this._impostors[this._numMeshes]=null):(this._meshes[0]=null,this._impostors[0]=null),t=!0;break}t&&0===this._numMeshes&&this._scene.unregisterBeforeRender(this._renderFunction)}hideBody(e){if(!e||!this._scene||!this._utilityLayer)return!1;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let r=0;r0?(this._bodyMeshes[r]=this._bodyMeshes[this._numBodies],this._bodies[r]=this._bodies[this._numBodies],this._bodyMeshes[this._numBodies]=null,this._bodies[this._numBodies]=null):(this._bodyMeshes[0]=null,this._bodies[0]=null),t=!0;break}return t&&0===this._numBodies&&this._scene.unregisterBeforeRender(this._renderFunction),t}hideInertia(e){if(!e||!this._scene||!this._utilityLayer)return!1;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let r=0;r0?(this._constraints[r]=this._constraints[this._numConstraints],this._constraintMeshes[r]=this._constraintMeshes[this._numConstraints],this._constraints[this._numConstraints]=null,this._constraintMeshes[this._numConstraints]=null):(this._constraints[0]=null,this._constraintMeshes[0]=null),t=!0;break}t&&0===this._numConstraints&&this._scene.unregisterBeforeRender(this._constraintRenderFunction)}_getDebugMaterial(e){return this._debugMaterial||(this._debugMaterial=new Un("",e),this._debugMaterial.wireframe=!0,this._debugMaterial.emissiveColor=H.v9.White(),this._debugMaterial.disableLighting=!0),this._debugMaterial}_getDebugInertiaMaterial(e){return this._debugInertiaMaterial||(this._debugInertiaMaterial=new Un("",e),this._debugInertiaMaterial.disableLighting=!0,this._debugInertiaMaterial.alpha=0),this._debugInertiaMaterial}_getDebugBoxMesh(e){return this._debugBoxMesh||(this._debugBoxMesh=Ko("physicsBodyBoxViewMesh",{size:1},e),this._debugBoxMesh.rotationQuaternion=W.PT.Identity(),this._debugBoxMesh.material=this._getDebugMaterial(e),this._debugBoxMesh.setEnabled(!1)),this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance")}_getDebugSphereMesh(e){return this._debugSphereMesh||(this._debugSphereMesh=Qo("physicsBodySphereViewMesh",{diameter:1},e),this._debugSphereMesh.rotationQuaternion=W.PT.Identity(),this._debugSphereMesh.material=this._getDebugMaterial(e),this._debugSphereMesh.setEnabled(!1)),this._debugSphereMesh.createInstance("physicsBodySphereViewInstance")}_getDebugCapsuleMesh(e){return this._debugCapsuleMesh||(this._debugCapsuleMesh=oa("physicsBodyCapsuleViewMesh",{height:1},e),this._debugCapsuleMesh.rotationQuaternion=W.PT.Identity(),this._debugCapsuleMesh.material=this._getDebugMaterial(e),this._debugCapsuleMesh.setEnabled(!1)),this._debugCapsuleMesh.createInstance("physicsBodyCapsuleViewInstance")}_getDebugCylinderMesh(e){return this._debugCylinderMesh||(this._debugCylinderMesh=No("physicsBodyCylinderViewMesh",{diameterTop:1,diameterBottom:1,height:1},e),this._debugCylinderMesh.rotationQuaternion=W.PT.Identity(),this._debugCylinderMesh.material=this._getDebugMaterial(e),this._debugCylinderMesh.setEnabled(!1)),this._debugCylinderMesh.createInstance("physicsBodyCylinderViewInstance")}_getDebugMeshMesh(e,t){const i=new Yt(e.name,t,null,e);return i.setParent(e),i.position=W.Pq.Zero(),i.material=this._getDebugMaterial(t),this._debugMeshMeshes.push(i),i}_getDebugMesh(e,t){if(!this._utilityLayer)return null;if(t&&t.parent&&t.parent.physicsImpostor)return null;let i=null;const r=this._utilityLayer.utilityLayerScene;if(!e.physicsBody)return Z.V.Warn("Unable to get physicsBody of impostor. It might be initialized later by its parent's impostor."),null;switch(e.type){case sa.BoxImpostor:i=this._getDebugBoxMesh(r),e.getBoxSizeToRef(i.scaling);break;case sa.SphereImpostor:{i=this._getDebugSphereMesh(r);const t=e.getRadius();i.scaling.x=2*t,i.scaling.y=2*t,i.scaling.z=2*t;break}case sa.CapsuleImpostor:{i=this._getDebugCapsuleMesh(r);const t=e.object.getBoundingInfo();i.scaling.x=2*(t.boundingBox.maximum.x-t.boundingBox.minimum.x)*e.object.scaling.x,i.scaling.y=(t.boundingBox.maximum.y-t.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=2*(t.boundingBox.maximum.z-t.boundingBox.minimum.z)*e.object.scaling.z;break}case sa.MeshImpostor:t&&(i=this._getDebugMeshMesh(t,r));break;case sa.NoImpostor:t?t.getChildMeshes().filter((e=>e.physicsImpostor?1:0)).forEach((e=>{if(e.physicsImpostor&&"Mesh"===e.getClassName()){const t=e.getBoundingInfo(),s=t.boundingBox.minimum,n=t.boundingBox.maximum;switch(e.physicsImpostor.type){case sa.BoxImpostor:i=this._getDebugBoxMesh(r),i.position.copyFrom(s),i.position.addInPlace(n),i.position.scaleInPlace(.5);break;case sa.SphereImpostor:i=this._getDebugSphereMesh(r);break;case sa.CylinderImpostor:i=this._getDebugCylinderMesh(r);break;default:i=null}i&&(i.scaling.x=n.x-s.x,i.scaling.y=n.y-s.y,i.scaling.z=n.z-s.z,i.parent=e)}})):Z.V.Warn("No target mesh parameter provided for NoImpostor. Skipping."),i=null;break;case sa.CylinderImpostor:{i=this._getDebugCylinderMesh(r);const t=e.object.getBoundingInfo();i.scaling.x=(t.boundingBox.maximum.x-t.boundingBox.minimum.x)*e.object.scaling.x,i.scaling.y=(t.boundingBox.maximum.y-t.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=(t.boundingBox.maximum.z-t.boundingBox.minimum.z)*e.object.scaling.z;break}}return i}_getDebugBodyMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=new Yt("custom",t),r=new bt,s=e.getGeometry();if(r.positions=s.positions,r.indices=s.indices,r.applyToMesh(i),e._pluginDataInstances){const t=new Float32Array(16*e._pluginDataInstances.length);i.thinInstanceSetBuffer("matrix",t,16,!1)}return i.material=this._getDebugMaterial(t),i}_getMeshDebugInertiaMatrixToRef(e,t){const i=e.inertiaOrientation??W.PT.Identity(),r=e.inertia??W.Pq.Zero(),s=e.centerOfMass??W.Pq.Zero(),n=6*(r.x-r.y+r.z),o=Math.sqrt(Math.max(n,0)),a=12*r.x-n,l=Math.sqrt(Math.max(a,0)),h=12*r.z-n,c=Math.sqrt(Math.max(h,0)),u=W.AA.Vector3[0];u.set(c,o,l);const d=W.uq.ScalingToRef(u.x,u.y,u.z,W.AA.Matrix[0]),f=i.toRotationMatrix(W.AA.Matrix[1]),p=W.uq.TranslationToRef(s.x,s.y,s.z,W.AA.Matrix[2]);return d.multiplyToRef(f,t),t.multiplyToRef(p,t),t}_getDebugInertiaMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=bl.CreateBox("custom",{size:1},t),r=W.uq.Identity();if(e._pluginDataInstances.length){const t=new Float32Array(16*e._pluginDataInstances.length);for(let i=0;i=0?W.uq.FromArrayToRef(r._thinInstanceDataStorage.matrixData,i,t):t.copyFrom(r.getWorldMatrix())}_getDebugConstraintMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene;if(!e._initOptions)return null;const{pivotA:i,pivotB:r,axisA:s,axisB:n,perpAxisA:o,perpAxisB:a}=e._initOptions;if(!(i&&r&&s&&n&&o&&a))return null;const l=new Yt("parentingDebugConstraint",t),h=e.getBodiesUsingConstraint();for(const e of h){const h=new Pt("parentOfPair",t);h.parent=l;const{parentBody:c,parentBodyIndex:u,childBody:d,childBodyIndex:f}=e,p=this._getTransformFromBodyToRef(c,W.AA.Matrix[0],u),_=this._getTransformFromBodyToRef(d,W.AA.Matrix[1],f),m=new Pt("parentCoordSystem",t);m.parent=h,m.metadata={parentBody:c,parentBodyIndex:u},p.decomposeToTransformNode(m);const g=new Pt("childCoordSystem",t);g.parent=h,g.metadata={childBody:d,childBodyIndex:f},_.decomposeToTransformNode(g);const v=W.PT.FromRotationMatrix(W.uq.FromXYZAxesToRef(s,o,s.cross(o),W.AA.Matrix[0])),x=W.PT.FromRotationMatrix(W.uq.FromXYZAxesToRef(n,a,n.cross(a),W.AA.Matrix[0])),b=i,S=r,T=new Pt("constraint_parent",t);T.position.copyFrom(b),T.rotationQuaternion=v,T.parent=m;const C=new Pt("constraint_child",t);C.parent=g,C.position.copyFrom(S),C.rotationQuaternion=x;const y=new Wo(t,this._constraintAxesSize);y.xAxis.parent=T,y.yAxis.parent=T,y.zAxis.parent=T;const E=new Wo(t,this._constraintAxesSize);E.xAxis.parent=C,E.yAxis.parent=C,E.zAxis.parent=C}return l}dispose(){for(let e=this._numMeshes-1;e>=0;e--)this.hideImpostor(this._impostors[0]);for(let e=this._numBodies-1;e>=0;e--)this.hideBody(this._bodies[0]);for(let e=this._numInertiaBodies-1;e>=0;e--)this.hideInertia(this._inertiaBodies[0]);this._debugBoxMesh&&this._debugBoxMesh.dispose(),this._debugSphereMesh&&this._debugSphereMesh.dispose(),this._debugCylinderMesh&&this._debugCylinderMesh.dispose(),this._debugMaterial&&this._debugMaterial.dispose(),this._impostors.length=0,this._scene=null,this._physicsEnginePlugin=null,this._utilityLayer&&(this._utilityLayer.dispose(),this._utilityLayer=null)}}class Tl{static CreateAndShow(e,t,i){const r=new Tl(e);return r.show(t,i),r}constructor(e){this.ray=e}show(e,t){if(!this._renderFunction&&this.ray){const t=this.ray;this._renderFunction=()=>this._render(),this._scene=e,this._renderPoints=[t.origin,t.origin.add(t.direction.scale(t.length))],this._renderLine=Ra("ray",{points:this._renderPoints,updatable:!0},e),this._renderLine.isPickable=!1,this._renderFunction&&this._scene.registerBeforeRender(this._renderFunction)}t&&this._renderLine&&this._renderLine.color.copyFrom(t)}hide(){this._renderFunction&&this._scene&&(this._scene.unregisterBeforeRender(this._renderFunction),this._scene=null,this._renderFunction=null,this._renderLine&&(this._renderLine.dispose(),this._renderLine=null),this._renderPoints=[])}_render(){const e=this.ray;if(!e)return;const t=this._renderPoints[1],i=Math.min(e.length,1e6);t.copyFrom(e.direction),t.scaleInPlace(i),t.addInPlace(e.origin),this._renderPoints[0].copyFrom(e.origin),Ra("ray",{points:this._renderPoints,updatable:!0,instance:this._renderLine},this._scene),this._renderLine?.refreshBoundingInfo()}attachToMesh(e,t,i,r){this._attachedToMesh=e;const s=this.ray;s&&(s.direction||(s.direction=W.Pq.Zero()),s.origin||(s.origin=W.Pq.Zero()),r&&(s.length=r),i||(i=W.Pq.Zero()),t||(t=new W.Pq(0,0,-1)),this._scene||(this._scene=e.getScene()),this._meshSpaceDirection?(this._meshSpaceDirection.copyFrom(t),this._meshSpaceOrigin.copyFrom(i)):(this._meshSpaceDirection=t.clone(),this._meshSpaceOrigin=i.clone()),this._onAfterRenderObserver||(this._onAfterRenderObserver=this._scene.onBeforeRenderObservable.add((()=>this._updateToMesh())),this._onAfterStepObserver=this._scene.onAfterStepObservable.add((()=>this._updateToMesh()))),this._attachedToMesh.computeWorldMatrix(!0),this._updateToMesh())}detachFromMesh(){this._attachedToMesh&&this._scene&&(this._onAfterRenderObserver&&(this._scene.onBeforeRenderObservable.remove(this._onAfterRenderObserver),this._scene.onAfterStepObservable.remove(this._onAfterStepObserver)),this._attachedToMesh=null,this._onAfterRenderObserver=null,this._onAfterStepObserver=null,this._scene=null)}_updateToMesh(){const e=this.ray;this._attachedToMesh&&e&&(this._attachedToMesh.isDisposed()?this.detachFromMesh():(this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection,e.direction),W.Pq.TransformCoordinatesToRef(this._meshSpaceOrigin,this._attachedToMesh.getWorldMatrix(),e.origin)))}dispose(){this.hide(),this.detachFromMesh(),this.ray=null}}var Cl=i(36217);class yl{static CreateBoneWeightShader(e,t){const i=e.skeleton,r=e.colorBase??H.v9.Black(),s=e.colorZero??H.v9.Blue(),n=e.colorQuarter??H.v9.Green(),o=e.colorHalf??H.v9.Yellow(),a=e.colorFull??H.v9.Red(),l=e.targetBoneIndex??0;Cl.M.ShadersStore["boneWeights:"+i.name+"VertexShader"]="precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 view;\n uniform mat4 projection;\n uniform mat4 worldViewProjection;\n\n #include\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include\n\n #include\n\n varying vec3 vColor;\n\n uniform vec3 colorBase;\n uniform vec3 colorZero;\n uniform vec3 colorQuarter;\n uniform vec3 colorHalf;\n uniform vec3 colorFull;\n\n uniform float targetBoneIndex;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include\n #include\n #include\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n vec3 color = colorBase;\n float totalWeight = 0.;\n if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){\n totalWeight += matricesWeights[0];\n }\n if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){\n totalWeight += matricesWeights[1];\n }\n if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){\n totalWeight += matricesWeights[2];\n }\n if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){\n totalWeight += matricesWeights[3];\n }\n\n color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight));\n color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight));\n color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight));\n color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight));\n vColor = color;\n\n gl_Position = projection * view * worldPos;\n }",Cl.M.ShadersStore["boneWeights:"+i.name+"FragmentShader"]="\n precision highp float;\n varying vec3 vPosition;\n\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4(vColor, 1.0);\n gl_FragColor = color;\n }\n ";const h=new xo("boneWeight:"+i.name,t,{vertex:"boneWeights:"+i.name,fragment:"boneWeights:"+i.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return h.setColor3("colorBase",r),h.setColor3("colorZero",s),h.setColor3("colorQuarter",n),h.setColor3("colorHalf",o),h.setColor3("colorFull",a),h.setFloat("targetBoneIndex",l),h.getClassName=()=>"BoneWeightShader",h.transparencyMode=Vt.MATERIAL_OPAQUE,h}static CreateSkeletonMapShader(e,t){const i=e.skeleton,r=e.colorMap??[{color:new H.v9(1,.38,.18),location:0},{color:new H.v9(.59,.18,1),location:.2},{color:new H.v9(.59,1,.18),location:.4},{color:new H.v9(1,.87,.17),location:.6},{color:new H.v9(1,.17,.42),location:.8},{color:new H.v9(.17,.68,1),location:1}],s=i.bones.length+1,n=yl._CreateBoneMapColorBuffer(s,r,t),o=new xo("boneWeights:"+i.name,t,{vertexSource:"precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 view;\n uniform mat4 projection;\n uniform mat4 worldViewProjection;\n uniform float colorMap["+4*i.bones.length+"];\n\n #include\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include\n #include\n\n varying vec3 vColor;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include\n #include\n #include\n\n vec3 color = vec3(0.);\n bool first = true;\n\n for (int i = 0; i < 4; i++) {\n int boneIdx = int(matricesIndices[i]);\n float boneWgt = matricesWeights[i];\n\n vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]);\n\n if (boneWgt > 0.) {\n if (first) {\n first = false;\n color = c;\n } else {\n color = mix(color, c, boneWgt);\n }\n }\n }\n\n vColor = color;\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n gl_Position = projection * view * worldPos;\n }",fragmentSource:"\n precision highp float;\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4( vColor, 1.0 );\n gl_FragColor = color;\n }\n "},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return o.setFloats("colorMap",n),o.getClassName=()=>"SkeletonMapShader",o.transparencyMode=Vt.MATERIAL_OPAQUE,o}static _CreateBoneMapColorBuffer(e,t,i){const r=new Gn("temp",{width:e,height:1},i,!1),s=r.getContext(),n=s.createLinearGradient(0,0,e,0);t.forEach((e=>{n.addColorStop(e.location,e.color.toHexString())})),s.fillStyle=n,s.fillRect(0,0,e,1),r.update();const o=[],a=s.getImageData(0,0,e,1).data,l=1/255;for(let e=0;eyl.DISPLAY_SPHERE_AND_SPURS&&(e=yl.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,r=!0,s=3,n={}){if(this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=r,this.renderingGroupId=s,this.options=n,this.color=H.v9.White(),this._debugLines=new Array,this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,n.pauseAnimations=n.pauseAnimations??!0,n.returnToRest=n.returnToRest??!1,n.displayMode=n.displayMode??yl.DISPLAY_LINES,n.displayOptions=n.displayOptions??{},n.displayOptions.midStep=n.displayOptions.midStep??.235,n.displayOptions.midStepFactor=n.displayOptions.midStepFactor??.155,n.displayOptions.sphereBaseSize=n.displayOptions.sphereBaseSize??.15,n.displayOptions.sphereScaleUnit=n.displayOptions.sphereScaleUnit??2,n.displayOptions.sphereFactor=n.displayOptions.sphereFactor??.865,n.displayOptions.spurFollowsChild=n.displayOptions.spurFollowsChild??!1,n.displayOptions.showLocalAxes=n.displayOptions.showLocalAxes??!1,n.displayOptions.localAxesSize=n.displayOptions.localAxesSize??.075,n.computeBonesUsingShaders=n.computeBonesUsingShaders??!0,n.useAllBones=n.useAllBones??!0,this._boneIndices=new Set,!n.useAllBones){const e=t?.getVerticesData(st.R.MatricesIndicesKind),i=t?.getVerticesData(st.R.MatricesWeightsKind);if(e&&i)for(let t=0;tyl.DISPLAY_SPHERE_AND_SPURS&&(o=yl.DISPLAY_LINES),this.displayMode=o,this.update(),this._bindObs()}_bindObs(){this.displayMode===yl.DISPLAY_LINES&&(this._obs=this.scene.onBeforeRenderObservable.add((()=>{this._displayLinesUpdate()})))}update(){switch(this.displayMode){case yl.DISPLAY_LINES:this._displayLinesUpdate();break;case yl.DISPLAY_SPHERES:this._buildSpheresAndSpurs(!0);break;case yl.DISPLAY_SPHERE_AND_SPURS:this._buildSpheresAndSpurs(!1)}this._buildLocalAxes()}set isEnabled(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))}get isEnabled(){return this._isEnabled}_getBonePosition(e,t,i,r=0,s=0,n=0){const o=W.AA.Matrix[0],a=t.getParent();if(o.copyFrom(t.getLocalMatrix()),0!==r||0!==s||0!==n){const e=W.AA.Matrix[1];W.uq.IdentityToRef(e),e.setTranslationFromFloats(r,s,n),e.multiplyToRef(o,o)}a&&o.multiplyToRef(a.getAbsoluteMatrix(),o),o.multiplyToRef(i,o),e.x=o.m[12],e.y=o.m[13],e.z=o.m[14]}_getLinesForBonesWithLength(e,t){const i=e.length;let r,s;t?(r=t.getWorldMatrix(),s=t.position):(r=new W.uq,s=e[0].position);let n=0;for(let t=0;t=0;r--){const t=e[r],o=t.getParent();if(!o||!this._boneIndices.has(t.getIndex())&&!this.options.useAllBones)continue;let a=this._debugLines[i];a||(a=[W.Pq.Zero(),W.Pq.Zero()],this._debugLines[i]=a),t.getAbsolutePositionToRef(s,a[0]),o.getAbsolutePositionToRef(s,a[1]),a[0].subtractInPlace(n),a[1].subtractInPlace(n),i++}r||s.dispose()}_revert(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)}_getAbsoluteBindPoseToRef(e,t){null!==e&&-1!==e._index?(this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBindMatrix().multiplyToRef(t,t)):t.copyFrom(W.uq.Identity())}_createSpur(e,t,i,r,s,n){const o=i.subtract(e),a=o.length(),l=o.normalize().scale(a),h=s.midStep||.165,c=s.midStepFactor||.215,u=l.scale(h),d=Ua("skeletonViewer",{shape:[new W.Pq(1,-1,0),new W.Pq(1,1,0),new W.Pq(-1,1,0),new W.Pq(-1,-1,0),new W.Pq(1,-1,0)],path:[W.Pq.Zero(),u,l],scaleFunction:e=>{switch(e){case 0:case 2:return 0;case 1:return a*c}return 0},sideOrientation:Yt.DEFAULTSIDE,updatable:!1},n),f=d.getTotalVertices(),p=[],_=[];for(let e=0;e9?_.push(r.getIndex(),0,0,0):_.push(t.getIndex(),0,0,0);return d.position=e.clone(),d.setVerticesData(st.R.MatricesWeightsKind,p,!1),d.setVerticesData(st.R.MatricesIndicesKind,_,!1),d.convertToFlatShadedMesh(),d}_getBoundingSphereForBone(e){if(!this.mesh)return null;const t=this.mesh.getVerticesData(st.R.PositionKind),i=this.mesh.getIndices(),r=this.mesh.getVerticesData(st.R.MatricesWeightsKind),s=this.mesh.getVerticesData(st.R.MatricesIndicesKind);if(!(t&&i&&r&&s))return null;const n=new W.Pq(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),o=new W.Pq(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);let a=0;for(let l=0;l1e-5){W.Pq.FromArrayToRef(t,3*h,W.AA.Vector3[0]),n.minimizeInPlace(W.AA.Vector3[0]),o.maximizeInPlace(W.AA.Vector3[0]),a++;break}}}return a>1?{center:W.Pq.Center(n,o),radius:W.Pq.Distance(n,o)/2}:null}_buildSpheresAndSpurs(e=!0){this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;const t=this.utilityLayer?.utilityLayerScene,i=this.skeleton.bones,r=[],s=[],n=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,t.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();let o=Number.NEGATIVE_INFINITY;const a=this.options.displayOptions||{};for(let n=0;n0)l.children.forEach((i=>{const r=new W.uq;i.getLocalMatrix().multiplyToRef(h,r);const n=new W.Pq;r.decompose(void 0,void 0,n);const u=W.Pq.Distance(c,n);u>o&&(o=u),e||s.push(this._createSpur(c,l,n,i,a,t))}));else{const i=this._getBoundingSphereForBone(l.getIndex());if(i&&(i.radius>o&&(o=i.radius),!e)){let e;const r=l.getParent();r?(this._getAbsoluteBindPoseToRef(r,h),h.decompose(void 0,void 0,W.AA.Vector3[0]),e=c.subtract(W.AA.Vector3[0]).normalize().scale(i.radius).add(c)):e=i.center.subtract(c).normalize().scale(i.radius).add(c),s.push(this._createSpur(c,l,e,null,a,t))}}const u=Qo("skeletonViewer",{segments:6,diameter:a.sphereBaseSize||.2,updatable:!0},t),d=u.getTotalVertices(),f=[],p=[];for(let e=0;e{e.setEnabled(t<6&&this._showLines||t>=6&&this._showPlanes)})),this._oldPosition.set(Number.NaN,Number.NaN,Number.NaN),this._visible=!0}hide(){this._lightHelperFrustumMeshes.forEach((e=>{e.setEnabled(!1)})),this._visible=!1}update(){if(!this._visible)return;if(this._oldPosition.equals(this._light.position)&&this._oldDirection.equals(this._light.direction)&&this._oldAutoCalc===this._light.autoCalcShadowZBounds&&this._oldMinZ===this._light.shadowMinZ&&this._oldMaxZ===this._light.shadowMaxZ)return;this._oldPosition.copyFrom(this._light.position),this._oldDirection.copyFrom(this._light.direction),this._oldAutoCalc=this._light.autoCalcShadowZBounds,this._oldMinZ=this._light.shadowMinZ,this._oldMaxZ=this._light.shadowMaxZ,W.AA.Vector3[0].set(this._light.orthoLeft,this._light.orthoBottom,void 0!==this._light.shadowMinZ?this._light.shadowMinZ:this._camera.minZ),W.AA.Vector3[1].set(this._light.orthoRight,this._light.orthoTop,void 0!==this._light.shadowMaxZ?this._light.shadowMaxZ:this._camera.maxZ);const e=this._getInvertViewMatrix();W.AA.Vector3[2].copyFromFloats(W.AA.Vector3[1].x,W.AA.Vector3[1].y,W.AA.Vector3[0].z),W.AA.Vector3[3].copyFromFloats(W.AA.Vector3[1].x,W.AA.Vector3[0].y,W.AA.Vector3[0].z),W.AA.Vector3[4].copyFromFloats(W.AA.Vector3[0].x,W.AA.Vector3[0].y,W.AA.Vector3[0].z),W.AA.Vector3[5].copyFromFloats(W.AA.Vector3[0].x,W.AA.Vector3[1].y,W.AA.Vector3[0].z),W.Pq.TransformCoordinatesToRef(W.AA.Vector3[2],e,W.AA.Vector3[2]),W.Pq.TransformCoordinatesToRef(W.AA.Vector3[3],e,W.AA.Vector3[3]),W.Pq.TransformCoordinatesToRef(W.AA.Vector3[4],e,W.AA.Vector3[4]),W.Pq.TransformCoordinatesToRef(W.AA.Vector3[5],e,W.AA.Vector3[5]),W.AA.Vector3[6].copyFromFloats(W.AA.Vector3[1].x,W.AA.Vector3[1].y,W.AA.Vector3[1].z),W.AA.Vector3[7].copyFromFloats(W.AA.Vector3[1].x,W.AA.Vector3[0].y,W.AA.Vector3[1].z),W.AA.Vector3[8].copyFromFloats(W.AA.Vector3[0].x,W.AA.Vector3[0].y,W.AA.Vector3[1].z),W.AA.Vector3[9].copyFromFloats(W.AA.Vector3[0].x,W.AA.Vector3[1].y,W.AA.Vector3[1].z),W.Pq.TransformCoordinatesToRef(W.AA.Vector3[6],e,W.AA.Vector3[6]),W.Pq.TransformCoordinatesToRef(W.AA.Vector3[7],e,W.AA.Vector3[7]),W.Pq.TransformCoordinatesToRef(W.AA.Vector3[8],e,W.AA.Vector3[8]),W.Pq.TransformCoordinatesToRef(W.AA.Vector3[9],e,W.AA.Vector3[9]),Ra("nearlines",{updatable:!0,points:this._nearLinesPoints,instance:this._lightHelperFrustumMeshes[0]},this._scene),Ra("farlines",{updatable:!0,points:this._farLinesPoints,instance:this._lightHelperFrustumMeshes[1]},this._scene),Ra("trlines",{updatable:!0,points:this._trLinesPoints,instance:this._lightHelperFrustumMeshes[2]},this._scene),Ra("brlines",{updatable:!0,points:this._brLinesPoints,instance:this._lightHelperFrustumMeshes[3]},this._scene),Ra("tllines",{updatable:!0,points:this._tlLinesPoints,instance:this._lightHelperFrustumMeshes[4]},this._scene),Ra("bllines",{updatable:!0,points:this._blLinesPoints,instance:this._lightHelperFrustumMeshes[5]},this._scene),W.AA.Vector3[2].toArray(this._nearPlaneVertices,0),W.AA.Vector3[3].toArray(this._nearPlaneVertices,3),W.AA.Vector3[4].toArray(this._nearPlaneVertices,6),W.AA.Vector3[5].toArray(this._nearPlaneVertices,9),this._lightHelperFrustumMeshes[6].geometry?.updateVerticesDataDirectly("position",this._nearPlaneVertices,0),W.AA.Vector3[6].toArray(this._farPlaneVertices,0),W.AA.Vector3[7].toArray(this._farPlaneVertices,3),W.AA.Vector3[8].toArray(this._farPlaneVertices,6),W.AA.Vector3[9].toArray(this._farPlaneVertices,9),this._lightHelperFrustumMeshes[7].geometry?.updateVerticesDataDirectly("position",this._farPlaneVertices,0),W.AA.Vector3[2].toArray(this._rightPlaneVertices,0),W.AA.Vector3[6].toArray(this._rightPlaneVertices,3),W.AA.Vector3[7].toArray(this._rightPlaneVertices,6),W.AA.Vector3[3].toArray(this._rightPlaneVertices,9),this._lightHelperFrustumMeshes[8].geometry?.updateVerticesDataDirectly("position",this._rightPlaneVertices,0),W.AA.Vector3[5].toArray(this._leftPlaneVertices,0),W.AA.Vector3[9].toArray(this._leftPlaneVertices,3),W.AA.Vector3[8].toArray(this._leftPlaneVertices,6),W.AA.Vector3[4].toArray(this._leftPlaneVertices,9),this._lightHelperFrustumMeshes[9].geometry?.updateVerticesDataDirectly("position",this._leftPlaneVertices,0),W.AA.Vector3[2].toArray(this._topPlaneVertices,0),W.AA.Vector3[6].toArray(this._topPlaneVertices,3),W.AA.Vector3[9].toArray(this._topPlaneVertices,6),W.AA.Vector3[5].toArray(this._topPlaneVertices,9),this._lightHelperFrustumMeshes[10].geometry?.updateVerticesDataDirectly("position",this._topPlaneVertices,0),W.AA.Vector3[3].toArray(this._bottomPlaneVertices,0),W.AA.Vector3[7].toArray(this._bottomPlaneVertices,3),W.AA.Vector3[8].toArray(this._bottomPlaneVertices,6),W.AA.Vector3[4].toArray(this._bottomPlaneVertices,9),this._lightHelperFrustumMeshes[11].geometry?.updateVerticesDataDirectly("position",this._bottomPlaneVertices,0)}dispose(){this._lightHelperFrustumMeshes.forEach((e=>{e.material?.dispose(),e.dispose()})),this._rootNode.dispose()}_createGeometry(){this._rootNode=new Pt("directionalLightHelperRoot_"+this._light.name,this._scene),this._rootNode.parent=this._light.parent,this._nearLinesPoints=[W.AA.Vector3[0],W.AA.Vector3[1],W.AA.Vector3[2],W.AA.Vector3[3],W.AA.Vector3[4]];const e=Ra("nearlines",{updatable:!0,points:this._nearLinesPoints},this._scene);e.parent=this._rootNode,e.alwaysSelectAsActiveMesh=!0,this._farLinesPoints=[W.AA.Vector3[5],W.AA.Vector3[6],W.AA.Vector3[7],W.AA.Vector3[8],W.AA.Vector3[9]];const t=Ra("farlines",{updatable:!0,points:this._farLinesPoints},this._scene);t.parent=this._rootNode,t.alwaysSelectAsActiveMesh=!0,this._trLinesPoints=[W.AA.Vector3[10],W.AA.Vector3[11]];const i=Ra("trlines",{updatable:!0,points:this._trLinesPoints},this._scene);i.parent=this._rootNode,i.alwaysSelectAsActiveMesh=!0,this._brLinesPoints=[W.AA.Vector3[12],W.AA.Vector3[0]];const r=Ra("brlines",{updatable:!0,points:this._brLinesPoints},this._scene);r.parent=this._rootNode,r.alwaysSelectAsActiveMesh=!0,this._tlLinesPoints=[W.AA.Vector3[1],W.AA.Vector3[2]];const s=Ra("tllines",{updatable:!0,points:this._tlLinesPoints},this._scene);s.parent=this._rootNode,s.alwaysSelectAsActiveMesh=!0,this._blLinesPoints=[W.AA.Vector3[3],W.AA.Vector3[4]];const n=Ra("bllines",{updatable:!0,points:this._blLinesPoints},this._scene);n.parent=this._rootNode,n.alwaysSelectAsActiveMesh=!0,this._lightHelperFrustumMeshes.push(e,t,i,r,s,n);const o=(e,t,i)=>{const r=new Yt(e+"plane",this._scene),s=new Un(e+"PlaneMat",this._scene);r.material=s,r.parent=this._rootNode,r.alwaysSelectAsActiveMesh=!0,s.emissiveColor=t,s.alpha=this.transparency,s.backFaceCulling=!1,s.disableLighting=!0;const n=new bt;n.positions=i,n.indices=[0,1,2,0,2,3],n.applyToMesh(r,!0),this._lightHelperFrustumMeshes.push(r)};this._nearPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._farPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._rightPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._leftPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._topPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._bottomPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],o("near",new H.v9(1,0,0),this._nearPlaneVertices),o("far",new H.v9(.3,0,0),this._farPlaneVertices),o("right",new H.v9(0,1,0),this._rightPlaneVertices),o("left",new H.v9(0,.3,0),this._leftPlaneVertices),o("top",new H.v9(0,0,1),this._topPlaneVertices),o("bottom",new H.v9(0,0,.3),this._bottomPlaneVertices),this._nearLinesPoints[0]=W.AA.Vector3[2],this._nearLinesPoints[1]=W.AA.Vector3[3],this._nearLinesPoints[2]=W.AA.Vector3[4],this._nearLinesPoints[3]=W.AA.Vector3[5],this._nearLinesPoints[4]=W.AA.Vector3[2],this._farLinesPoints[0]=W.AA.Vector3[6],this._farLinesPoints[1]=W.AA.Vector3[7],this._farLinesPoints[2]=W.AA.Vector3[8],this._farLinesPoints[3]=W.AA.Vector3[9],this._farLinesPoints[4]=W.AA.Vector3[6],this._trLinesPoints[0]=W.AA.Vector3[2],this._trLinesPoints[1]=W.AA.Vector3[6],this._brLinesPoints[0]=W.AA.Vector3[3],this._brLinesPoints[1]=W.AA.Vector3[7],this._tlLinesPoints[0]=W.AA.Vector3[4],this._tlLinesPoints[1]=W.AA.Vector3[8],this._blLinesPoints[0]=W.AA.Vector3[5],this._blLinesPoints[1]=W.AA.Vector3[9]}_getInvertViewMatrix(){return W.uq.LookAtLHToRef(this._light.position,this._light.position.add(this._light.direction),W.Pq.UpReadOnly,this._inverseViewMatrix),this._inverseViewMatrix.invertToRef(this._inverseViewMatrix),this._inverseViewMatrix}}var Pl=i(58292),Al=i(77333),Rl=i(78035);class Il{}Il.AUTOSAMPLERSUFFIX="Sampler",Il.DISABLEUA="#define DISABLE_UNIFORMITY_ANALYSIS",Il.ALPHA_DISABLE=0,Il.ALPHA_ADD=1,Il.ALPHA_COMBINE=2,Il.ALPHA_SUBTRACT=3,Il.ALPHA_MULTIPLY=4,Il.ALPHA_MAXIMIZED=5,Il.ALPHA_ONEONE=6,Il.ALPHA_PREMULTIPLIED=7,Il.ALPHA_PREMULTIPLIED_PORTERDUFF=8,Il.ALPHA_INTERPOLATE=9,Il.ALPHA_SCREENMODE=10,Il.ALPHA_ONEONE_ONEONE=11,Il.ALPHA_ALPHATOCOLOR=12,Il.ALPHA_REVERSEONEMINUS=13,Il.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,Il.ALPHA_ONEONE_ONEZERO=15,Il.ALPHA_EXCLUSION=16,Il.ALPHA_LAYER_ACCUMULATE=17,Il.ALPHA_EQUATION_ADD=0,Il.ALPHA_EQUATION_SUBSTRACT=1,Il.ALPHA_EQUATION_REVERSE_SUBTRACT=2,Il.ALPHA_EQUATION_MAX=3,Il.ALPHA_EQUATION_MIN=4,Il.ALPHA_EQUATION_DARKEN=5,Il.DELAYLOADSTATE_NONE=0,Il.DELAYLOADSTATE_LOADED=1,Il.DELAYLOADSTATE_LOADING=2,Il.DELAYLOADSTATE_NOTLOADED=4,Il.NEVER=512,Il.ALWAYS=519,Il.LESS=513,Il.EQUAL=514,Il.LEQUAL=515,Il.GREATER=516,Il.GEQUAL=518,Il.NOTEQUAL=517,Il.KEEP=7680,Il.ZERO=0,Il.REPLACE=7681,Il.INCR=7682,Il.DECR=7683,Il.INVERT=5386,Il.INCR_WRAP=34055,Il.DECR_WRAP=34056,Il.TEXTURE_CLAMP_ADDRESSMODE=0,Il.TEXTURE_WRAP_ADDRESSMODE=1,Il.TEXTURE_MIRROR_ADDRESSMODE=2,Il.TEXTURE_CREATIONFLAG_STORAGE=1,Il.TEXTUREFORMAT_ALPHA=0,Il.TEXTUREFORMAT_LUMINANCE=1,Il.TEXTUREFORMAT_LUMINANCE_ALPHA=2,Il.TEXTUREFORMAT_RGB=4,Il.TEXTUREFORMAT_RGBA=5,Il.TEXTUREFORMAT_RED=6,Il.TEXTUREFORMAT_R=6,Il.TEXTUREFORMAT_RG=7,Il.TEXTUREFORMAT_RED_INTEGER=8,Il.TEXTUREFORMAT_R_INTEGER=8,Il.TEXTUREFORMAT_RG_INTEGER=9,Il.TEXTUREFORMAT_RGB_INTEGER=10,Il.TEXTUREFORMAT_RGBA_INTEGER=11,Il.TEXTUREFORMAT_BGRA=12,Il.TEXTUREFORMAT_DEPTH24_STENCIL8=13,Il.TEXTUREFORMAT_DEPTH32_FLOAT=14,Il.TEXTUREFORMAT_DEPTH16=15,Il.TEXTUREFORMAT_DEPTH24=16,Il.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17,Il.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18,Il.TEXTUREFORMAT_STENCIL8=19,Il.TEXTUREFORMAT_UNDEFINED=4294967295,Il.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492,Il.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493,Il.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495,Il.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494,Il.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779,Il.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919,Il.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778,Il.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918,Il.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777,Il.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776,Il.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917,Il.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916,Il.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808,Il.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840,Il.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196,Il.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492,Il.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493,Il.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494,Il.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495,Il.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496,Il.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497,Il.TEXTURETYPE_UNSIGNED_BYTE=0,Il.TEXTURETYPE_UNSIGNED_INT=0,Il.TEXTURETYPE_FLOAT=1,Il.TEXTURETYPE_HALF_FLOAT=2,Il.TEXTURETYPE_BYTE=3,Il.TEXTURETYPE_SHORT=4,Il.TEXTURETYPE_UNSIGNED_SHORT=5,Il.TEXTURETYPE_INT=6,Il.TEXTURETYPE_UNSIGNED_INTEGER=7,Il.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,Il.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,Il.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,Il.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,Il.TEXTURETYPE_UNSIGNED_INT_24_8=12,Il.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,Il.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,Il.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,Il.TEXTURETYPE_UNDEFINED=16,Il.TEXTURE_2D=3553,Il.TEXTURE_2D_ARRAY=35866,Il.TEXTURE_CUBE_MAP=34067,Il.TEXTURE_CUBE_MAP_ARRAY=3735928559,Il.TEXTURE_3D=32879,Il.TEXTURE_NEAREST_SAMPLINGMODE=1,Il.TEXTURE_NEAREST_NEAREST=1,Il.TEXTURE_BILINEAR_SAMPLINGMODE=2,Il.TEXTURE_LINEAR_LINEAR=2,Il.TEXTURE_TRILINEAR_SAMPLINGMODE=3,Il.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,Il.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,Il.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,Il.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,Il.TEXTURE_NEAREST_LINEAR=7,Il.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,Il.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,Il.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,Il.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,Il.TEXTURE_LINEAR_NEAREST=12,Il.TEXTURE_EXPLICIT_MODE=0,Il.TEXTURE_SPHERICAL_MODE=1,Il.TEXTURE_PLANAR_MODE=2,Il.TEXTURE_CUBIC_MODE=3,Il.TEXTURE_PROJECTION_MODE=4,Il.TEXTURE_SKYBOX_MODE=5,Il.TEXTURE_INVCUBIC_MODE=6,Il.TEXTURE_EQUIRECTANGULAR_MODE=7,Il.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,Il.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Il.TEXTURE_FILTERING_QUALITY_OFFLINE=4096,Il.TEXTURE_FILTERING_QUALITY_HIGH=64,Il.TEXTURE_FILTERING_QUALITY_MEDIUM=16,Il.TEXTURE_FILTERING_QUALITY_LOW=8,Il.SCALEMODE_FLOOR=1,Il.SCALEMODE_NEAREST=2,Il.SCALEMODE_CEILING=3,Il.MATERIAL_TextureDirtyFlag=1,Il.MATERIAL_LightDirtyFlag=2,Il.MATERIAL_FresnelDirtyFlag=4,Il.MATERIAL_AttributesDirtyFlag=8,Il.MATERIAL_MiscDirtyFlag=16,Il.MATERIAL_PrePassDirtyFlag=32,Il.MATERIAL_AllDirtyFlag=63,Il.MATERIAL_TriangleFillMode=0,Il.MATERIAL_WireFrameFillMode=1,Il.MATERIAL_PointFillMode=2,Il.MATERIAL_PointListDrawMode=3,Il.MATERIAL_LineListDrawMode=4,Il.MATERIAL_LineLoopDrawMode=5,Il.MATERIAL_LineStripDrawMode=6,Il.MATERIAL_TriangleStripDrawMode=7,Il.MATERIAL_TriangleFanDrawMode=8,Il.MATERIAL_ClockWiseSideOrientation=0,Il.MATERIAL_CounterClockWiseSideOrientation=1,Il.ACTION_NothingTrigger=0,Il.ACTION_OnPickTrigger=1,Il.ACTION_OnLeftPickTrigger=2,Il.ACTION_OnRightPickTrigger=3,Il.ACTION_OnCenterPickTrigger=4,Il.ACTION_OnPickDownTrigger=5,Il.ACTION_OnDoublePickTrigger=6,Il.ACTION_OnPickUpTrigger=7,Il.ACTION_OnPickOutTrigger=16,Il.ACTION_OnLongPressTrigger=8,Il.ACTION_OnPointerOverTrigger=9,Il.ACTION_OnPointerOutTrigger=10,Il.ACTION_OnEveryFrameTrigger=11,Il.ACTION_OnIntersectionEnterTrigger=12,Il.ACTION_OnIntersectionExitTrigger=13,Il.ACTION_OnKeyDownTrigger=14,Il.ACTION_OnKeyUpTrigger=15,Il.PARTICLES_BILLBOARDMODE_Y=2,Il.PARTICLES_BILLBOARDMODE_ALL=7,Il.PARTICLES_BILLBOARDMODE_STRETCHED=8,Il.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9,Il.MESHES_CULLINGSTRATEGY_STANDARD=0,Il.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Il.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Il.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,Il.SCENELOADER_NO_LOGGING=0,Il.SCENELOADER_MINIMAL_LOGGING=1,Il.SCENELOADER_SUMMARY_LOGGING=2,Il.SCENELOADER_DETAILED_LOGGING=3,Il.PREPASS_IRRADIANCE_TEXTURE_TYPE=0,Il.PREPASS_POSITION_TEXTURE_TYPE=1,Il.PREPASS_VELOCITY_TEXTURE_TYPE=2,Il.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3,Il.PREPASS_COLOR_TEXTURE_TYPE=4,Il.PREPASS_DEPTH_TEXTURE_TYPE=5,Il.PREPASS_NORMAL_TEXTURE_TYPE=6,Il.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7,Il.PREPASS_WORLD_NORMAL_TEXTURE_TYPE=8,Il.PREPASS_LOCAL_POSITION_TEXTURE_TYPE=9,Il.PREPASS_SCREENSPACE_DEPTH_TEXTURE_TYPE=10,Il.PREPASS_VELOCITY_LINEAR_TEXTURE_TYPE=11,Il.PREPASS_ALBEDO_TEXTURE_TYPE=12,Il.BUFFER_CREATIONFLAG_READ=1,Il.BUFFER_CREATIONFLAG_WRITE=2,Il.BUFFER_CREATIONFLAG_READWRITE=3,Il.BUFFER_CREATIONFLAG_UNIFORM=4,Il.BUFFER_CREATIONFLAG_VERTEX=8,Il.BUFFER_CREATIONFLAG_INDEX=16,Il.BUFFER_CREATIONFLAG_STORAGE=32,Il.BUFFER_CREATIONFLAG_INDIRECT=64,Il.RENDERPASS_MAIN=0,Il.INPUT_ALT_KEY=18,Il.INPUT_CTRL_KEY=17,Il.INPUT_META_KEY1=91,Il.INPUT_META_KEY2=92,Il.INPUT_META_KEY3=93,Il.INPUT_SHIFT_KEY=16,Il.SNAPSHOTRENDERING_STANDARD=0,Il.SNAPSHOTRENDERING_FAST=1,Il.PERSPECTIVE_CAMERA=0,Il.ORTHOGRAPHIC_CAMERA=1,Il.FOVMODE_VERTICAL_FIXED=0,Il.FOVMODE_HORIZONTAL_FIXED=1,Il.RIG_MODE_NONE=0,Il.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,Il.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,Il.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,Il.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,Il.RIG_MODE_STEREOSCOPIC_INTERLACED=14,Il.RIG_MODE_VR=20,Il.RIG_MODE_CUSTOM=22,Il.MAX_SUPPORTED_UV_SETS=6,Il.GL_ALPHA_EQUATION_ADD=32774,Il.GL_ALPHA_EQUATION_MIN=32775,Il.GL_ALPHA_EQUATION_MAX=32776,Il.GL_ALPHA_EQUATION_SUBTRACT=32778,Il.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779,Il.GL_ALPHA_FUNCTION_SRC=768,Il.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769,Il.GL_ALPHA_FUNCTION_SRC_ALPHA=770,Il.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771,Il.GL_ALPHA_FUNCTION_DST_ALPHA=772,Il.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773,Il.GL_ALPHA_FUNCTION_DST_COLOR=774,Il.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775,Il.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776,Il.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769,Il.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770,Il.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771,Il.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772,Il.GL_ALPHA_FUNCTION_SRC1_COLOR=35065,Il.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_COLOR=35066,Il.GL_ALPHA_FUNCTION_SRC1_ALPHA=34185,Il.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_ALPHA=35067,Il.SnippetUrl="https://snippet.babylonjs.com",Il.FOGMODE_NONE=0,Il.FOGMODE_EXP=1,Il.FOGMODE_EXP2=2,Il.FOGMODE_LINEAR=3,Il.BYTE=5120,Il.UNSIGNED_BYTE=5121,Il.SHORT=5122,Il.UNSIGNED_SHORT=5123,Il.INT=5124,Il.UNSIGNED_INT=5125,Il.FLOAT=5126,Il.PositionKind="position",Il.NormalKind="normal",Il.TangentKind="tangent",Il.UVKind="uv",Il.UV2Kind="uv2",Il.UV3Kind="uv3",Il.UV4Kind="uv4",Il.UV5Kind="uv5",Il.UV6Kind="uv6",Il.ColorKind="color",Il.ColorInstanceKind="instanceColor",Il.MatricesIndicesKind="matricesIndices",Il.MatricesWeightsKind="matricesWeights",Il.MatricesIndicesExtraKind="matricesIndicesExtra",Il.MatricesWeightsExtraKind="matricesWeightsExtra";var Ml=i(82352),Ol=i(61340);class Dl{constructor(){this.renderWidth=512,this.renderHeight=256,this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4}}class wl extends an{isDeterministicLockStep(){return this._options.deterministicLockstep}getLockstepMaxSteps(){return this._options.lockstepMaxSteps}getHardwareScalingLevel(){return 1}constructor(e=new Dl){super(null),void 0===e.deterministicLockstep&&(e.deterministicLockstep=!1),void 0!==e.timeStep&&(this._timeStep=e.timeStep),void 0===e.lockstepMaxSteps&&(e.lockstepMaxSteps=4),this._options=e,Ml.I.SetMatrixPrecision(!!e.useHighPrecisionMatrix),this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:512,maxCubemapTextureSize:512,maxDrawBuffers:0,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!1,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:0,uintIndices:!1,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloat:!1,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!1,textureLOD:!1,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!1,instancedArrays:!1,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,maxMSAASamples:1,blendMinMax:!1,canUseGLInstanceID:!1,canUseGLVertexID:!1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:128,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!1,supportSSAO2:!1,supportIBLShadows:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!1,_collectUbosUpdatedInFrame:!1},e.renderingCanvas&&(this._renderingCanvas=e.renderingCanvas),Z.V.Log(`Babylon.js v${an.Version} - Null engine`);const t="undefined"!=typeof self?self:void 0!==i.g?i.g:window;"undefined"==typeof URL&&(t.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(t.Blob=function(){})}createVertexBuffer(e){const t=new pr.n;return t.references=1,t}createIndexBuffer(e){const t=new pr.n;return t.references=1,t}clear(e,t,i,r=!1){}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._options.renderWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._options.renderHeight}setViewport(e,t,i){this._cachedViewport=e}createShaderProgram(e,t,i,r,s){return{__SPECTOR_rebuildProgram:null}}getUniforms(e,t){return[]}getAttributes(e,t){return[]}bindSamplers(e){this._currentEffect=null}enableEffect(e){e=null!==e&&(0,Ol.E)(e)?e.effect:e,this._currentEffect=e,e&&(e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setState(e,t=0,i,r=!1,s,n,o=0){}setIntArray(e,t){return!0}setIntArray2(e,t){return!0}setIntArray3(e,t){return!0}setIntArray4(e,t){return!0}setFloatArray(e,t){return!0}setFloatArray2(e,t){return!0}setFloatArray3(e,t){return!0}setFloatArray4(e,t){return!0}setArray(e,t){return!0}setArray2(e,t){return!0}setArray3(e,t){return!0}setArray4(e,t){return!0}setMatrices(e,t){return!0}setMatrix3x3(e,t){return!0}setMatrix2x2(e,t){return!0}setFloat(e,t){return!0}setFloat2(e,t,i){return!0}setFloat3(e,t,i,r){return!0}setBool(e,t){return!0}setFloat4(e,t,i,r,s){return!0}setAlphaMode(e,t=!1){this._alphaMode!==e&&(this.alphaState.alphaBlend=0!==e,t||this.setDepthWrite(0===e),this._alphaMode=e)}bindBuffers(e,t,i){}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this.depthCullingState.reset(),this.alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}draw(e,t,i,r){}drawElementsType(e,t,i,r){}drawArraysType(e,t,i,r){}_createTexture(){return{}}_releaseTexture(e){}createTexture(e,t,i,r,s=3,n=null,o=null,a=null,l=null,h=null,c=null,u){const d=new Fs.h(this,1),f=String(e);return d.url=f,d.generateMipMaps=!t,d.samplingMode=s,d.invertY=i,d.baseWidth=this._options.textureSize,d.baseHeight=this._options.textureSize,d.width=this._options.textureSize,d.height=this._options.textureSize,h&&(d.format=h),d.isReady=!0,n&&setTimeout((()=>{n(d)})),this._internalTexturesCache.push(d),d}_createHardwareRenderTargetWrapper(e,t,i){const r=new qs(e,t,i,this);return this._renderTargetWrapperCache.push(r),r}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e),r={};void 0!==t&&"object"==typeof t?(r.generateMipMaps=t.generateMipMaps,r.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,r.generateStencilBuffer=r.generateDepthBuffer&&t.generateStencilBuffer,r.type=void 0===t.type?0:t.type,r.samplingMode=void 0===t.samplingMode?3:t.samplingMode):(r.generateMipMaps=t,r.generateDepthBuffer=!0,r.generateStencilBuffer=!1,r.type=0,r.samplingMode=3);const s=new Fs.h(this,5),n=e.width||e,o=e.height||e;return i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=!!r.generateStencilBuffer,s.baseWidth=n,s.baseHeight=o,s.width=n,s.height=o,s.isReady=!0,s.samples=1,s.generateMipMaps=!!r.generateMipMaps,s.samplingMode=r.samplingMode,s.type=r.type,this._internalTexturesCache.push(s),i}createRenderTargetCubeTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),r={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};r.generateStencilBuffer=r.generateDepthBuffer&&r.generateStencilBuffer,(1!==r.type||this._caps.textureFloatLinearFiltering)&&(2!==r.type||this._caps.textureHalfFloatLinearFiltering)||(r.samplingMode=1),i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=!!r.generateStencilBuffer;const s=new Fs.h(this,5);return s.baseWidth=e,s.baseHeight=e,s.width=e,s.height=e,s.isReady=!0,s.isCube=!0,s.samples=1,s.generateMipMaps=!!r.generateMipMaps,s.samplingMode=r.samplingMode,s.type=r.type,this._internalTexturesCache.push(s),i}updateTextureSamplingMode(e,t){t.samplingMode=e}createRawTexture(e,t,i,r,s,n,o,a=null,l=0,h=0,c=!1){const u=new Fs.h(this,3);return u.baseWidth=t,u.baseHeight=i,u.width=t,u.height=i,u.format=r,u.generateMipMaps=s,u.samplingMode=o,u.invertY=n,u._compression=a,u.type=l,u._useSRGBBuffer=c,this._doNotHandleContextLost||(u._bufferView=e),u}updateRawTexture(e,t,i,r,s=null,n=0,o=!1){e&&(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s,e.type=n,e._useSRGBBuffer=o)}bindFramebuffer(e,t,i,r,s){this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._currentFramebuffer=null,this._cachedViewport&&!s&&this.setViewport(this._cachedViewport,i,r)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._currentFramebuffer=null}createDynamicVertexBuffer(e){const t=new pr.n;return t.references=1,t.capacity=1,t}updateDynamicTexture(e,t,i,r=!1,s){}areAllEffectsReady(){return!0}getError(){return 0}_getUnpackAlignement(){return 1}_unpackFlipY(e){}updateDynamicIndexBuffer(e,t,i=0){}updateDynamicVertexBuffer(e,t,i,r){}_bindTextureDirectly(e,t){return this._boundTexturesCache[this._activeChannel]!==t&&(this._boundTexturesCache[this._activeChannel]=t,!0)}_bindTexture(e,t){e<0||this._bindTextureDirectly(0,t)}_deleteBuffer(e){}releaseEffects(){}displayLoadingUI(){}hideLoadingUI(){}set loadingUIText(e){}flushFramebuffer(){}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,n=0,o=0){}_uploadDataToTextureDirectly(e,t,i=0,r=0){}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){}_uploadImageToTexture(e,t,i=0,r=0){}}i(7244);class Nl{constructor(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=Nt.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=Nt.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE,this.forceRenderingWhenOccluded=!1}}Ot.$.prototype.getGPUFrameTimeCounter=function(){return null},Ot.$.prototype.captureGPUFrameTime=function(e){},Ot.$.prototype.createQuery=function(){return null},Ot.$.prototype.deleteQuery=function(e){return this},Ot.$.prototype.isQueryResultAvailable=function(e){return!1},Ot.$.prototype.getQueryResult=function(e){return 0},Ot.$.prototype.beginOcclusionQuery=function(e,t){return!1},Ot.$.prototype.endOcclusionQuery=function(e){return this},Object.defineProperty(Nt.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(e){this._occlusionDataStorage.isOcclusionQueryInProgress=e},enumerable:!1,configurable:!0}),Object.defineProperty(Nt.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new Nl),this.__occlusionDataStorage},enumerable:!1,configurable:!0}),Object.defineProperty(Nt.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(e){this._occlusionDataStorage.isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(Nt.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(e){this._occlusionDataStorage.occlusionQueryAlgorithmType=e},enumerable:!0,configurable:!0}),Object.defineProperty(Nt.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(e){this._occlusionDataStorage.occlusionType=e},enumerable:!0,configurable:!0}),Object.defineProperty(Nt.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(e){this._occlusionDataStorage.occlusionRetryCount=e},enumerable:!0,configurable:!0}),Object.defineProperty(Nt.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(e){this._occlusionDataStorage.forceRenderingWhenOccluded=e},enumerable:!0,configurable:!0}),Nt.prototype._checkOcclusionQuery=function(){const e=this._occlusionDataStorage;if(e.occlusionType===Nt.OCCLUSION_TYPE_NONE)return e.isOccluded=!1,!1;const t=this.getEngine();if(!t.getCaps().supportOcclusionQuery)return e.isOccluded=!1,!1;if(!t.isQueryResultAvailable)return e.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&null!==this._occlusionQuery&&void 0!==this._occlusionQuery)if(t.isQueryResultAvailable(this._occlusionQuery)){const i=t.getQueryResult(this._occlusionQuery);e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=!(i>0)}else{if(e.occlusionInternalRetryCounter++,!(-1!==e.occlusionRetryCount&&e.occlusionInternalRetryCounter>e.occlusionRetryCount))return e.occlusionType!==Nt.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==Nt.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}const i=this.getScene();if(i.getBoundingBoxRenderer){const r=i.getBoundingBoxRenderer();null===this._occlusionQuery&&(this._occlusionQuery=t.createQuery()),this._occlusionQuery&&t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery)&&(r.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return e.isOccluded};class Fl{}const Ll=new z.cP,Bl=new z.cP;Object.defineProperty(Ot.$.prototype,"onBeforeViewRenderObservable",{get:function(){return Ll}}),Object.defineProperty(Ot.$.prototype,"onAfterViewRenderObservable",{get:function(){return Bl}}),Object.defineProperty(Ot.$.prototype,"inputElement",{get:function(){return this._inputElement},set:function(e){this._inputElement!==e&&(this._inputElement=e,this._onEngineViewChanged?.())}}),Ot.$.prototype.getInputElement=function(){return this.inputElement||this.getRenderingCanvas()},Ot.$.prototype.registerView=function(e,t,i){this.views||(this.views=[]);for(const t of this.views)if(t.target===e)return t;const r=this.getRenderingCanvas();r&&(e.width=r.width,e.height=r.height);const s={target:e,camera:t,clearBeforeCopy:i,enabled:!0,id:(1e5*Math.random()).toFixed()};return this.views.push(s),t&&!Array.isArray(t)&&t.onDisposeObservable.add((()=>{this.unRegisterView(e)})),s},Ot.$.prototype.unRegisterView=function(e){if(!this.views||0===this.views.length)return this;for(const t of this.views)if(t.target===e){const e=this.views.indexOf(t);-1!==e&&this.views.splice(e,1);break}return this},Ot.$.prototype._renderViewStep=function(e){const t=e.target,i=t.getContext("2d");if(!i)return!0;const r=this.getRenderingCanvas();Ll.notifyObservers(e);const s=e.camera;let n=null,o=null,a=null;if(s&&(a=Array.isArray(s)?s[0].getScene():s.getScene(),n=a.activeCamera,o=a.activeCameras,Array.isArray(s)?a.activeCameras=s:(a.activeCamera=s,a.activeCameras=null)),this.activeView=e,e.customResize)e.customResize(t);else{const e=Math.floor(t.clientWidth/this._hardwareScalingLevel),i=Math.floor(t.clientHeight/this._hardwareScalingLevel),s=e!==t.width||r.width!==t.width||i!==t.height||r.height!==t.height;t.clientWidth&&t.clientHeight&&s&&(t.width=e,t.height=i,this.setSize(e,i))}return!(!r.width||!r.height||(this._renderFrame(),this.flushFramebuffer(),e.clearBeforeCopy&&i.clearRect(0,0,r.width,r.height),i.drawImage(r,0,0),a&&(a.activeCameras=o,a.activeCamera=n),Bl.notifyObservers(e),0))},Ot.$.prototype._renderViews=function(){if(!this.views||0===this.views.length)return!1;if(!this.getRenderingCanvas())return!1;let e;for(const t of this.views)if(t.enabled)if(t.target!==this.inputElement){if(!this._renderViewStep(t))return!1}else e=t;return!(e&&!this._renderViewStep(e)||(this.activeView=null,0))},Ot.$.prototype._debugPushGroup=function(e,t){},Ot.$.prototype._debugPopGroup=function(e){},Ot.$.prototype._debugInsertMarker=function(e,t){},Ot.$.prototype._debugFlushPendingCommands=function(){};class Vl{constructor(){this._timeElapsedQueryEnded=!1}}an.prototype.createQuery=function(){const e=this._gl.createQuery();if(!e)throw new Error("Unable to create Occlusion Query");return e},an.prototype.deleteQuery=function(e){return this._gl.deleteQuery(e),this},an.prototype.isQueryResultAvailable=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT_AVAILABLE)},an.prototype.getQueryResult=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT)},an.prototype.beginOcclusionQuery=function(e,t){const i=this._getGlAlgorithmType(e);return this._gl.beginQuery(i,t),!0},an.prototype.endOcclusionQuery=function(e){const t=this._getGlAlgorithmType(e);return this._gl.endQuery(t),this},an.prototype._createTimeQuery=function(){const e=this.getCaps().timerQuery;return e.createQueryEXT?e.createQueryEXT():this.createQuery()},an.prototype._deleteTimeQuery=function(e){const t=this.getCaps().timerQuery;t.deleteQueryEXT?t.deleteQueryEXT(e):this.deleteQuery(e)},an.prototype._getTimeQueryResult=function(e){const t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT):this.getQueryResult(e)},an.prototype._getTimeQueryAvailability=function(e){const t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(e)},an.prototype.startTimeQuery=function(){const e=this.getCaps(),t=e.timerQuery;if(!t)return null;const i=new Vl;if(this._gl.getParameter(t.GPU_DISJOINT_EXT),e.canUseTimestampForTimerQuery)i._startTimeQuery=this._createTimeQuery(),i._startTimeQuery&&t.queryCounterEXT(i._startTimeQuery,t.TIMESTAMP_EXT);else{if(this._currentNonTimestampToken)return this._currentNonTimestampToken;i._timeElapsedQuery=this._createTimeQuery(),i._timeElapsedQuery&&(t.beginQueryEXT?t.beginQueryEXT(t.TIME_ELAPSED_EXT,i._timeElapsedQuery):this._gl.beginQuery(t.TIME_ELAPSED_EXT,i._timeElapsedQuery)),this._currentNonTimestampToken=i}return i},an.prototype.endTimeQuery=function(e){const t=this.getCaps(),i=t.timerQuery;if(!i||!e)return-1;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery)return-1;e._endTimeQuery||(e._endTimeQuery=this._createTimeQuery(),e._endTimeQuery&&i.queryCounterEXT(e._endTimeQuery,i.TIMESTAMP_EXT))}else if(!e._timeElapsedQueryEnded){if(!e._timeElapsedQuery)return-1;i.endQueryEXT?i.endQueryEXT(i.TIME_ELAPSED_EXT):(this._gl.endQuery(i.TIME_ELAPSED_EXT),this._currentNonTimestampToken=null),e._timeElapsedQueryEnded=!0}const r=this._gl.getParameter(i.GPU_DISJOINT_EXT);let s=!1;if(e._endTimeQuery?s=this._getTimeQueryAvailability(e._endTimeQuery):e._timeElapsedQuery&&(s=this._getTimeQueryAvailability(e._timeElapsedQuery)),s&&!r){let i=0;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery||!e._endTimeQuery)return-1;const t=this._getTimeQueryResult(e._startTimeQuery);i=this._getTimeQueryResult(e._endTimeQuery)-t,this._deleteTimeQuery(e._startTimeQuery),this._deleteTimeQuery(e._endTimeQuery),e._startTimeQuery=null,e._endTimeQuery=null}else{if(!e._timeElapsedQuery)return-1;i=this._getTimeQueryResult(e._timeElapsedQuery),this._deleteTimeQuery(e._timeElapsedQuery),e._timeElapsedQuery=null,e._timeElapsedQueryEnded=!1}return i}return-1},an.prototype._captureGPUFrameTime=!1,an.prototype._gpuFrameTime=new on.A,an.prototype.getGPUFrameTimeCounter=function(){return this._gpuFrameTime},an.prototype.captureGPUFrameTime=function(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,e?(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))},an.prototype._getGlAlgorithmType=function(e){return e===Nt.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED};var kl,Ul=!0;function Gl(e){if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some((t=>{const i="\\b"+t+"\\b";return e&&(e===t||e.match(new RegExp(i,"g")))})))return e;const t=e.lastIndexOf("."),i=e.lastIndexOf("?"),r=i>-1?e.substring(i,e.length):"";return(t>-1?e.substring(0,t):e)+this._textureFormatInUse+r}an.prototype.createTransformFeedback=function(){const e=this._gl.createTransformFeedback();if(!e)throw new Error("Unable to create Transform Feedback");return e},an.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},an.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},an.prototype.beginTransformFeedback=function(e=!0){this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},an.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},an.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},an.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)},an.prototype.readTransformFeedbackBuffer=function(e){this._gl.getBufferSubData(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e)},Ls.ThinEngine.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;const r=this._getInternalFormat(e.format),s=this._getRGBABufferInternalSizedFormat(0,e.format),n=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=this.createCanvas(e.width,e.height);const t=e._workingCanvas.getContext("2d");if(!t)throw new Error("Unable to get 2d context");e._workingContext=t,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.clearRect(0,0,e.width,e.height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),n||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}},Ls.ThinEngine.prototype.restoreSingleAttachment=function(){const e=this._gl;this.bindAttachments([e.BACK])},Ls.ThinEngine.prototype.restoreSingleAttachmentForRenderTarget=function(){const e=this._gl;this.bindAttachments([e.COLOR_ATTACHMENT0])},Ls.ThinEngine.prototype.buildTextureLayout=function(e){const t=this._gl,i=[];for(let r=0;r1?"COLOR_ATTACHMENT"+t:"COLOR_ATTACHMENT"+t+"_WEBGL"],r.readBuffer(s[t]),r.drawBuffers(s),r.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,r.COLOR_BUFFER_BIT,r.NEAREST)}for(let e=0;e1?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];r.drawBuffers(s)}for(let i=0;i1&&(13===t.depthTextureFormat||17===t.depthTextureFormat||16===t.depthTextureFormat||14===t.depthTextureFormat||18===t.depthTextureFormat)&&(a=t.depthTextureFormat));const b=this._gl,S=b.createFramebuffer();this._bindUnboundFramebuffer(S);const T=e.width??e,C=e.height??e,y=[],E=[],P=this.webGLVersion>1&&(13===a||17===a||18===a);x.label=t?.label??"MultiRenderTargetWrapper",x._framebuffer=S,x._generateDepthBuffer=o||s,x._generateStencilBuffer=o?P:n,x._depthStencilBuffer=this._setupFramebufferDepthAttachments(x._generateStencilBuffer,x._generateDepthBuffer,T,C,1,a),x._attachments=E;for(let e=0;e1||this.isWebGPU);const h=this.webGLVersion>1,_=b[h?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];if(E.push(_),-1===o)continue;const m=new Fs.h(this,6);y[e]=m,b.activeTexture(b["TEXTURE"+e]),b.bindTexture(o,m._hardwareTexture.underlyingResource),b.texParameteri(o,b.TEXTURE_MAG_FILTER,l.mag),b.texParameteri(o,b.TEXTURE_MIN_FILTER,l.min),b.texParameteri(o,b.TEXTURE_WRAP_S,b.CLAMP_TO_EDGE),b.texParameteri(o,b.TEXTURE_WRAP_T,b.CLAMP_TO_EDGE);const S=this._getRGBABufferInternalSizedFormat(i,n,s),P=this._getInternalFormat(n),A=this._getWebGLTextureType(i);if(!h||35866!==o&&32879!==o)if(34067===o){for(let e=0;e<6;e++)b.texImage2D(b.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,S,T,C,0,P,A,null);m.isCube=!0}else b.texImage2D(b.TEXTURE_2D,0,S,T,C,0,P,A,null);else 35866===o?m.is2DArray=!0:m.is3D=!0,m.baseDepth=m.depth=a,b.texImage3D(o,0,S,T,C,a,0,P,A,null);r&&b.generateMipmap(o),this._bindTextureDirectly(o,null),m.baseWidth=T,m.baseHeight=C,m.width=T,m.height=C,m.isReady=!0,m.samples=1,m.generateMipMaps=r,m.samplingMode=t,m.type=i,m._useSRGBBuffer=s,m.format=n,m.label=v[e]??x.label+"-Texture"+e,this._internalTexturesCache.push(m)}if(o&&this._caps.depthTextureExtension){const e=new Fs.h(this,14);let t=5,i=b.DEPTH_COMPONENT16,s=b.DEPTH_COMPONENT,n=b.UNSIGNED_SHORT,o=b.DEPTH_ATTACHMENT;this.webGLVersion<2?i=b.DEPTH_COMPONENT:14===a?(t=1,n=b.FLOAT,i=b.DEPTH_COMPONENT32F):18===a?(t=0,n=b.FLOAT_32_UNSIGNED_INT_24_8_REV,i=b.DEPTH32F_STENCIL8,s=b.DEPTH_STENCIL,o=b.DEPTH_STENCIL_ATTACHMENT):16===a?(t=0,n=b.UNSIGNED_INT,i=b.DEPTH_COMPONENT24,o=b.DEPTH_ATTACHMENT):13!==a&&17!==a||(t=12,n=b.UNSIGNED_INT_24_8,i=b.DEPTH24_STENCIL8,s=b.DEPTH_STENCIL,o=b.DEPTH_STENCIL_ATTACHMENT),this._bindTextureDirectly(b.TEXTURE_2D,e,!0),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MAG_FILTER,b.NEAREST),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MIN_FILTER,b.NEAREST),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_S,b.CLAMP_TO_EDGE),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_T,b.CLAMP_TO_EDGE),b.texImage2D(b.TEXTURE_2D,0,i,T,C,0,s,n,null),b.framebufferTexture2D(b.FRAMEBUFFER,o,b.TEXTURE_2D,e._hardwareTexture.underlyingResource,0),this._bindTextureDirectly(b.TEXTURE_2D,null),x._depthStencilTexture=e,x._depthStencilTextureWithStencil=P,e.baseWidth=T,e.baseHeight=C,e.width=T,e.height=C,e.isReady=!0,e.samples=1,e.generateMipMaps=r,e.samplingMode=1,e.format=a,e.type=t,e.label=x.label+"-DepthStencil",y[l]=e,this._internalTexturesCache.push(e)}return x.setTextures(y),i&&b.drawBuffers(E),this._bindUnboundFramebuffer(null),x.setLayerAndFaceIndices(m,_),this.resetTextureCache(),this.updateMultipleRenderTargetTextureSampleCount(x,h,i),x},Ls.ThinEngine.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t,i=!0){if(this.webGLVersion<2||!e)return 1;if(e.samples===t)return t;const r=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(r.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(r.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null);const s=e._attachments.length;for(let t=0;t1&&"function"==typeof r.renderbufferStorageMultisample){const n=r.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=n,this._bindUnboundFramebuffer(n);const o=[];for(let i=0;i1?"COLOR_ATTACHMENT"+i:"COLOR_ATTACHMENT"+i+"_WEBGL"],l=this._createRenderBuffer(s.width,s.height,t,-1,this._getRGBABufferInternalSizedFormat(s.type,s.format,s._useSRGBBuffer),a);if(!l)throw new Error("Unable to create multi sampled framebuffer");n.addMSAARenderBuffer(l),s.samples=t,o.push(a)}i&&r.drawBuffers(o)}else this._bindUnboundFramebuffer(e._framebuffer);const n=e._depthStencilTexture?e._depthStencilTexture.format:void 0;return e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.width,e.height,t,n),this._bindUnboundFramebuffer(null),e._samples=t,t},function(e){e[e.Texture=0]="Texture",e[e.StorageTexture=1]="StorageTexture",e[e.UniformBuffer=2]="UniformBuffer",e[e.StorageBuffer=3]="StorageBuffer",e[e.TextureWithoutSampler=4]="TextureWithoutSampler",e[e.Sampler=5]="Sampler",e[e.ExternalTexture=6]="ExternalTexture",e[e.DataBuffer=7]="DataBuffer"}(kl||(kl={})),Ls.ThinEngine.prototype.createComputeEffect=function(e,t){throw new Error("createComputeEffect: This engine does not support compute shaders!")},Ls.ThinEngine.prototype.createComputePipelineContext=function(){throw new Error("createComputePipelineContext: This engine does not support compute shaders!")},Ls.ThinEngine.prototype.createComputeContext=function(){},Ls.ThinEngine.prototype.computeDispatch=function(e,t,i,r,s,n,o){throw new Error("computeDispatch: This engine does not support compute shaders!")},Ls.ThinEngine.prototype.computeDispatchIndirect=function(e,t,i,r,s,n){throw new Error("computeDispatchIndirect: This engine does not support compute shaders!")},Ls.ThinEngine.prototype.areAllComputeEffectsReady=function(){return!0},Ls.ThinEngine.prototype.releaseComputeEffects=function(){},Ls.ThinEngine.prototype._prepareComputePipelineContext=function(e,t,i,r,s){},Ls.ThinEngine.prototype._rebuildComputeEffects=function(){},Ot.$.prototype._executeWhenComputeStateIsCompiled=function(e,t){t(null)},Ls.ThinEngine.prototype._releaseComputeEffect=function(e){},Ls.ThinEngine.prototype._deleteComputePipelineContext=function(e){},Object.defineProperty(an.prototype,"texturesSupported",{get:function(){const e=[];return this._caps.astc&&e.push("-astc.ktx"),this._caps.s3tc&&e.push("-dxt.ktx"),this._caps.pvrtc&&e.push("-pvrtc.ktx"),this._caps.etc2&&e.push("-etc2.ktx"),this._caps.etc1&&e.push("-etc1.ktx"),e},enumerable:!0,configurable:!0}),Object.defineProperty(an.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0}),an.prototype.setCompressedTextureExclusions=function(e){this._excludedCompressedTextures=e},an.prototype.setTextureFormatToUse=function(e){const t=this.texturesSupported;for(let i=0,r=t.length;i{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}}zl.DEFAULT_BUFFER_SIZE=65536;var Wl=i(48195);function Hl(e,t,i,r){let s=r,n=0,o="";for(;s=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95==t}function Yl(e){let t=0,i="",r=!1;const s=[];for(;t=0&&e.charAt(t)!==i&&(!r||e.charAt(t)!==r);)t--;return t}function jl(e,t,i,r){let s=e.indexOf(t);if(s<0)return e;if(i){for(;s++=0&&d.push(t.substring(i+1))}"void"!==s&&d.push("return"),this._functionDescr.push({name:n,type:s,parameters:d,body:c,callIndex:0}),e=h+1;const f=t>0?this._sourceCode.substring(0,t):"",p=h+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&Z.V.Log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(const t of this._functionDescr){const{name:i,type:r,parameters:s,body:n}=t;let o=0;for(;o{const t=[];let i=0,r=0;for(;i0?this._sourceCode.substring(0,a):"";const g=h+1{const a=s[0];return ql(e.charAt(a-1))||ql(e.charAt(a+n))?t[r]:o}))}return e}}$l._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;const Ql=/(flat\s)?\s*varying\s*.*/;class Zl{constructor(){this.shaderLanguage=0}initializeShaders(e){this._nativeProcessingContext=e,this._nativeProcessingContext&&(this._nativeProcessingContext.remappedAttributeNames={},this._nativeProcessingContext.injectInVertexMain="")}attributeProcessor(e){if(!this._nativeProcessingContext)return e.replace("attribute","in");const t=/\s*(?:attribute|in)\s+(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==t){const i=t[1],r=t[2],s=this._nativeProcessingContext.vertexBufferKindToNumberOfComponents[r];if(void 0!==s){const n=s<0?-1===s?"int":"ivec"+-s:1===s?"uint":"uvec"+s,o=`_int_${r}_`;e=e.replace(t[0],`in ${n} ${o}; ${i} ${r};`),this._nativeProcessingContext.injectInVertexMain+=`${r} = ${i}(${o});\n`,this._nativeProcessingContext.remappedAttributeNames[r]=o}else e=e.replace(t[0],`in ${i} ${r};`)}return e}varyingCheck(e,t){return Ql.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const r=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){const t=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(r||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else if(this._nativeProcessingContext?.injectInVertexMain&&(e=jl(e,"void main",this._nativeProcessingContext.injectInVertexMain)),-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e}}class Jl{get isReady(){if(this.compilationError){const e=this.compilationError.message;throw new Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}return this.isCompiled}_getVertexShaderCode(){return null}_getFragmentShaderCode(){return null}constructor(e,t,i){this.isCompiled=!1,this.vertexBufferKindToType={},this._valueCache={},this._engine=e,this.isAsync=t,this.shaderProcessingContext=i}_fillEffectInformation(e,t,i,r,s,n,o,a){const l=this._engine;if(l.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let h;for(this._engine.getUniforms(this,i).forEach(((e,t)=>{r[i[t]]=e})),this._uniforms=r,h=0;h{n[e]=t})),a.push(...l.getAttributes(this,o))}setEngine(e){this._engine=e}dispose(){this._uniforms={}}_cacheMatrix(e,t){const i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s)return s=[t,i,r],this._valueCache[e]=s,!0;let n=!1;return s[0]!==t&&(s[0]=t,n=!0),s[1]!==i&&(s[1]=i,n=!0),s[2]!==r&&(s[2]=r,n=!0),n}_cacheFloat4(e,t,i,r,s){let n=this._valueCache[e];if(!n)return n=[t,i,r,s],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]!==r&&(n[2]=r,o=!0),n[3]!==s&&(n[3]=s,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this._engine.setInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this._engine.setInt4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this._engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this._engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this._engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this._engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this._engine.setUInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this._engine.setUInt4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this._engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this._engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this._engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this._engine.setUIntArray4(this._uniforms[e],t)}setFloatArray(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)}setFloatArray2(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)}setFloatArray3(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)}setFloatArray4(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this._engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this._engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this._engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this._engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this._engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this._engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this._engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this._engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this._engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this._engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this._engine.setFloat3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this._engine.setFloat4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this._engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}}class eh extends qs{get _framebuffer(){return this.__framebuffer}set _framebuffer(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e}get _framebufferDepthStencil(){return this.__framebufferDepthStencil}set _framebufferDepthStencil(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e}constructor(e,t,i,r){super(e,t,i,r),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=r}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}}class th{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 ih(e,t){switch(e){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: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(t){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(t){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(t){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(t){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:if(0===t)return _native.Engine.TEXTURE_FORMAT_BGRA8}throw new nt.bu(`Unsupported texture format or type: format ${e}, type ${t}.`,nt.tG.UnsupportedTextureError)}function rh(e){switch(e){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: ${e}.`)}}function sh(e){switch(e){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: "+e+".")}}function nh(e){switch(e){case st.R.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case st.R.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case st.R.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case st.R.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case st.R.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error(`Unsupported attribute type: ${e}.`)}}const oh={[st.R.PositionKind]:!0,[st.R.NormalKind]:!0,[st.R.TangentKind]:!0,[st.R.UVKind]:!0,[st.R.UV2Kind]:!0,[st.R.UV3Kind]:!0,[st.R.UV4Kind]:!0,[st.R.UV5Kind]:!0,[st.R.UV6Kind]:!0,[st.R.ColorKind]:!0,[st.R.ColorInstanceKind]:!0,[st.R.MatricesIndicesKind]:!0,[st.R.MatricesWeightsKind]:!0,[st.R.MatricesIndicesExtraKind]:!0,[st.R.MatricesWeightsExtraKind]:!0};function ah(e){switch(e){case st.R.BYTE:case st.R.SHORT:case st.R.INT:case st.R.FLOAT:return!0;case st.R.UNSIGNED_BYTE:case st.R.UNSIGNED_SHORT:case st.R.UNSIGNED_INT:return!1;default:throw new Error(`Invalid type '${e}'`)}}function lh(e,t){const i=t.getEngine(),r=t._pipelineContext;if(!r?.vertexBufferKindToType)return;let s=null;for(const n in e){const o=e[n];if(!o||!oh[n])continue;const a=o.normalized?st.R.FLOAT:o.type,l=r.vertexBufferKindToType[n];(a!==st.R.FLOAT&&void 0===l||void 0!==l&&l!==a)&&(s||(s=i._getShaderProcessingContext(t.shaderLanguage,!1)),r.vertexBufferKindToType[n]=a,a!==st.R.FLOAT&&(s.vertexBufferKindToNumberOfComponents[n]=st.R.DeduceStride(n),ah(a)&&(s.vertexBufferKindToNumberOfComponents[n]*=-1)))}if(s){const e=i._caps.parallelShaderCompile;i._caps.parallelShaderCompile=void 0,t._processShaderCodeAsync(null,i._features._checkNonFloatVertexBuffersDontRecreatePipelineContext,s),i._caps.parallelShaderCompile=e}}class hh{constructor(){this.vertexBufferKindToNumberOfComponents={},this.remappedAttributeNames={},this.injectInVertexMain=""}}var ch=i(47221);const uh=new z.cP;if("undefined"!=typeof self&&!Object.prototype.hasOwnProperty.call(self,"_native")){let e;Object.defineProperty(self,"_native",{get:()=>e,set:t=>{e=t,e&&uh.notifyObservers(e)}})}function dh(){return new Promise((e=>{"undefined"==typeof _native?uh.addOnce((t=>e(t))):e(_native)}))}async function fh(e,t){(await dh())[e]=t}class ph extends pr.n{}class _h{constructor(e){this._engine=e,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=gh._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}beginCommandScope(){if(this._isCommandBufferScopeActive)throw new Error("Command scope already active.");this._isCommandBufferScopeActive=!0}endCommandScope(){if(!this._isCommandBufferScopeActive)throw new Error("Command scope is not active.");this._isCommandBufferScopeActive=!1,this._submit()}startEncodingCommand(e){this._commandStream.writeNativeData(e)}encodeCommandArgAsUInt32(e){this._commandStream.writeUint32(e)}encodeCommandArgAsUInt32s(e){this._commandStream.writeUint32Array(e)}encodeCommandArgAsInt32(e){this._commandStream.writeInt32(e)}encodeCommandArgAsInt32s(e){this._commandStream.writeInt32Array(e)}encodeCommandArgAsFloat32(e){this._commandStream.writeFloat32(e)}encodeCommandArgAsFloat32s(e){this._commandStream.writeFloat32Array(e)}encodeCommandArgAsNativeData(e){this._commandStream.writeNativeData(e),this._pending.push(e)}finishEncodingCommand(){this._isCommandBufferScopeActive||this._submit()}_submit(){this._engine.submitCommands(),this._pending.length=0}}const mh=[];class gh extends an{setHardwareScalingLevel(e){super.setHardwareScalingLevel(e),this._engine.setHardwareScalingLevel(e)}constructor(e={}){if(super(null,!1,void 0,e.adaptToDeviceRatio),this._engine=new _native.Engine({version:an.Version,nonFloatVertexBuffers:!0}),this._camera=_native.Camera?new _native.Camera:null,this._commandBufferEncoder=new _h(this._engine),this._boundBuffersVertexArray=null,this._currentDepthTest=_native.Engine.DEPTH_TEST_LEQUAL,this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=519,this._stencilFuncRef=0,this._stencilFuncMask=255,this._stencilOpStencilFail=7680,this._stencilOpDepthFail=7680,this._stencilOpStencilDepthPass=7681,this._zOffset=0,this._zOffsetUnits=0,this._depthWrite=!0,this._fillModeWarningDisplayed=!1,_native.Engine.PROTOCOL_VERSION!==gh.PROTOCOL_VERSION)throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${gh.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,maxDrawBuffers:8,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!0,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!0,textureFloatLinearFiltering:!0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:16,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1,parallelShaderCompile:{COMPLETION_STATUS_KHR:0}},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!0,supportSSAO2:!1,supportIBLShadows:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!1,_collectUbosUpdatedInFrame:!1},Ue.S0.Log("Babylon Native (v"+an.Version+") launched"),Ue.S0.LoadScript=function(e,t,i,r){Ue.S0.LoadFile(e,(e=>{Function(e).apply(null),t&&t()}),void 0,void 0,!1,((e,t)=>{i&&i("LoadScript Error",t)}))},"undefined"==typeof URL&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(window.Blob=function(e){return e}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function e(){const t=isNaN(arguments[0])?1:Number(arguments[0]);return t?Array.prototype.reduce.call(this,(function(i,r){return Array.isArray(r)?i.push.apply(i,e.call(r,t-1)):i.push(r),i}),[]):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 Zl,this.onNewSceneAddedObservable.add((e=>{const t=e.render;e.render=(...i)=>{this._commandBufferEncoder.beginCommandScope(),t.apply(e,i),this._commandBufferEncoder.endCommandScope()}}))}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new zl}_queueNewFrame(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0}_restoreEngineAfterContextLost(){this._clearEmptyResources();const e=this._depthCullingState.depthTest,t=this._depthCullingState.depthFunc,i=this._depthCullingState.depthMask,r=this._stencilState.stencilTest;this._rebuildGraphicsResources(),this._depthCullingState.depthTest=e,this._depthCullingState.depthFunc=t,this._depthCullingState.depthMask=i,this._stencilState.stencilTest=r,this._flagContextRestored()}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),this._commandBufferEncoder.finishEncodingCommand()),e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()),this._currentFramebuffer=e)}getHostDocument(){return null}clear(e,t,i,r=!1){if(this.useReverseDepthBuffer)throw new Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(r?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t,i){const r=this._normalizeIndexData(e),s=new ph;return s.references=1,s.is32Bits=4===r.BYTES_PER_ELEMENT,r.byteLength&&(s.nativeIndexBuffer=this._engine.createIndexBuffer(r.buffer,r.byteOffset,r.byteLength,s.is32Bits,t??!1)),s}createVertexBuffer(e,t,i){const r=ArrayBuffer.isView(e)?e:new Float32Array(e),s=new ph;return s.references=1,r.byteLength&&(s.nativeVertexBuffer=this._engine.createVertexBuffer(r.buffer,r.byteOffset,r.byteLength,t??!1)),s}_recordVertexArrayObject(e,t,i,r,s){r._checkedNonFloatVertexBuffers||(lh(t,r),r._checkedNonFloatVertexBuffers=!0),i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);const n=r.getAttributesNames();for(let i=0;i=0){const r=n[i];let a=null;if(s&&(a=s[r]),a||(a=t[r]),a){const t=a.effectiveBuffer;t&&t.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,t.nativeVertexBuffer,o,a.effectiveByteOffset,a.effectiveByteStride,a.getSize(),nh(a.type),a.normalized,a.getInstanceDivisor())}}}}bindBuffers(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)}recordVertexArrayObject(e,t,i,r){const s=this._engine.createVertexArray();return this._recordVertexArrayObject(s,e,t,i,r),s}_deleteVertexArray(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}bindVertexArrayObject(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}releaseVertexArrayObject(e){this._deleteVertexArray(e)}getAttributes(e,t){const i=e,r=i.shaderProcessingContext;mh.length=0;for(let e=0;e{e(),t()}}else i.onCompiled=t;else t()}createRawShaderProgram(){throw new Error("Not Supported")}createShaderProgram(e,t,i,r){const s=e;this.onBeforeShaderCompilationObservable.notifyObservers(this);const n=new $l(t);n.processCode(),t=n.code;const o=new $l(i);o.processCode(),i=o.code,t=Ls.ThinEngine._ConcatenateShader(t,r),i=Ls.ThinEngine._ConcatenateShader(i,r);const a=()=>{s.isCompiled=!0,s.onCompiled?.(),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(e.isAsync)s.program=this._engine.createProgramAsync(t,i,a,(e=>{s.compilationError=e}));else try{s.program=this._engine.createProgram(t,i),a()}catch(e){const t=e?.message;throw new Error("SHADER ERROR"+("string"==typeof t?"\n"+t:""))}return s.program}inlineShaderCode(e){const t=new $l(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 t=0;t{}}}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}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,function(e){switch(e){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: ${e}.`)}}(this._stencilOpStencilFail),function(e){switch(e){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: ${e}.`)}}(this._stencilOpDepthFail),function(e){switch(e){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: ${e}.`)}}(this._stencilOpStencilDepthPass),function(e){switch(e){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: ${e}.`)}}(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,r,s,n){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),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,r){throw new Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;const i=function(e){switch(e){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: ${e}.`)}}(e);this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t||this.setDepthWrite(0===e),this._alphaMode=e}setInt(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setArray(e,t){return!!e&&this.setFloatArray(e,new Float32Array(t))}setArray2(e,t){return!!e&&this.setFloatArray2(e,new Float32Array(t))}setArray3(e,t){return!!e&&this.setFloatArray3(e,new Float32Array(t))}setArray4(e,t){return!!e&&this.setFloatArray4(e,new Float32Array(t))}setMatrices(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix3x3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix2x2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}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)}setFloat3(e,t,i,r){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat4(e,t,i,r,s){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0)}setColor3(e,t){return!!e&&(this.setFloat3(e,t.r,t.g,t.b),!0)}setColor4(e,t,i){return!!e&&(this.setFloat4(e,t.r,t.g,t.b,i),!0)}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}_createTexture(){return this._engine.createTexture()}_deleteTexture(e){e&&this._engine.deleteTexture(e.underlyingResource)}updateDynamicTexture(e,t,i,r=!1,s){if(void 0===r&&(r=!1),e&&e._hardwareTexture){const i=t.getCanvasTexture(),r=e._hardwareTexture.underlyingResource;this._engine.copyTexture(r,i),e.isReady=!0}}createDynamicTexture(e,t,i,r){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,r)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){const r=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(r,t,i)}}createRawTexture(e,t,i,r,s,n,o,a=null,l=0,h=0,c=!1){const u=new Fs.h(this,3);if(u.format=r,u.generateMipMaps=s,u.samplingMode=o,u.invertY=n,u.baseWidth=t,u.baseHeight=i,u.width=u.baseWidth,u.height=u.baseHeight,u._compression=a,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!s),this.updateRawTexture(u,e,r,n,a,l,u._useSRGBBuffer),u._hardwareTexture){const e=u._hardwareTexture.underlyingResource,t=rh(o);this._setTextureSampling(e,t)}return this._internalTexturesCache.push(u),u}createRawTexture2DArray(e,t,i,r,s,n,o,a,l=null,h=0){const c=new Fs.h(this,11);if(c.baseWidth=t,c.baseHeight=i,c.baseDepth=r,c.width=t,c.height=i,c.depth=r,c.format=s,c.type=h,c.generateMipMaps=n,c.samplingMode=a,c.is2DArray=!0,c._hardwareTexture){const l=c._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(l,e,t,i,r,ih(s,h),n,o);const u=rh(a);this._setTextureSampling(l,u)}return c.isReady=!0,this._internalTexturesCache.push(c),c}updateRawTexture(e,t,i,r,s=null,n=0,o=!1){if(e){if(t&&e._hardwareTexture){const r=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(r,t,e.width,e.height,ih(i,n),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,r,s=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,f,p=!1){const _="data:"===(e=e||"").substring(0,5),m=_&&-1!==e.indexOf(";base64,"),g=l||new Fs.h(this,1),v=e;!this._transformTextureUrl||m||l||a||(e=this._transformTextureUrl(e));const x=e.lastIndexOf("."),b=c||(x>-1?e.substring(x).toLowerCase():"");let S=null;(b.endsWith(".basis")||b.endsWith(".ktx")||b.endsWith(".ktx2")||"image/ktx"===u||"image/ktx2"===u)&&(S=(0,ch.gT)(b)),r&&r.addPendingData(g),g.url=e,g.generateMipMaps=!t,g.samplingMode=s,g.invertY=i,g._useSRGBBuffer=this._getUseSRGBBuffer(p,t),this.doNotHandleContextLost||(g._buffer=a);let T=null;n&&!l&&(T=g.onLoadedObservable.add(n)),l||this._internalTexturesCache.push(g);const C=(i,l)=>{r&&r.removePendingData(g),e===v?(T&&g.onLoadedObservable.remove(T),he.q.UseFallbackTexture&&this.createTexture(he.q.FallbackTexture,t,g.invertY,r,s,null,o,a,g),o&&o((i||"Unknown error")+(he.q.UseFallbackTexture?" - Fallback texture was used":""),l)):(Z.V.Warn(`Failed to load ${e}, falling back to ${v}`),this.createTexture(v,t,g.invertY,r,s,n,o,a,g,h,c,u,d))};if(S)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");{const n=e=>{if(!g._hardwareTexture)return void(r&&r.removePendingData(g));const n=g._hardwareTexture.underlyingResource;this._engine.loadTexture(n,e,!t,i,g._useSRGBBuffer,(()=>{g.baseWidth=this._engine.getTextureWidth(n),g.baseHeight=this._engine.getTextureHeight(n),g.width=g.baseWidth,g.height=g.baseHeight,g.isReady=!0;const e=rh(s);this._setTextureSampling(n,e),r&&r.removePendingData(g),g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear()}),(()=>{throw new Error("Could not load a native texture.")}))};if(_&&a)if(a instanceof ArrayBuffer)n(new Uint8Array(a));else if(ArrayBuffer.isView(a))n(a);else{if("string"!=typeof a)throw new Error("Unsupported buffer type");n(new Uint8Array(Ue.S0.DecodeBase64(a)))}else m?n(new Uint8Array(Ue.S0.DecodeBase64(e))):this._loadFile(e,(e=>n(new Uint8Array(e))),void 0,void 0,!0,((e,t)=>{C("Unable to load "+(e&&e.responseURL,t))}))}return g}wrapNativeTexture(e,t=!1,i=3){const r=new th(e,this._engine),s=new Fs.h(this,0,!0);return s._hardwareTexture=r,s.baseWidth=this._engine.getTextureWidth(e),s.baseHeight=this._engine.getTextureHeight(e),s.width=s.baseWidth,s.height=s.baseHeight,s.isReady=!0,s.useMipMaps=t,this.updateTextureSamplingMode(i,s),s}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){const r=t.generateStencil||!1,s=t.samples||1,n=i,o=new Fs.h(this,12),a=e.width??e,l=e.height??e,h=this._engine.createFrameBuffer(o._hardwareTexture.underlyingResource,a,l,r,!0,s);return n._framebufferDepthStencil=h,o}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){const i=new Promise(((t,i)=>{const r=this.createCanvasImage();r.onload=()=>{try{const e=this._engine.createImageBitmap(r);t(e)}catch(e){i(`Error loading image ${r.src} with exception: ${e}`)}},r.onerror=e=>{i(`Error loading image ${r.src} with exception: ${e}`)},r.src=e}));return i}createImageBitmap(e,t){return new Promise(((t,i)=>{if(Array.isArray(e)){const i=e;if(i.length){const e=this._engine.createImageBitmap(i[0]);if(e)return void t(e)}}i("Unsupported data for createImageBitmap.")}))}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,r,s=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d,f=!1,p=null){const _=u||new Fs.h(this,7);_.isCube=!0,_.url=e,_.generateMipMaps=!r,_._lodGenerationScale=h,_._lodGenerationOffset=c,_._useSRGBBuffer=this._getUseSRGBBuffer(f,!!r),this._doNotHandleContextLost||(_._extension=a,_._files=i,_._buffer=p);const m=e.lastIndexOf(".");if(".env"===(a||(m>-1?e.substring(m).toLowerCase():""))){const t=e=>{const t=(0,Wl.cU)(e);_.width=t.width,_.height=t.width,(0,Wl.ow)(_,t);const i=t.specular;if(!i)throw new Error("Nothing else parsed so far");_._lodGenerationScale=i.lodGenerationScale;const r=(0,Wl.$h)(e,t);_.format=5,_.type=0,_.generateMipMaps=!0,_.getEngine().updateTextureSamplingMode(vi.g.TRILINEAR_SAMPLINGMODE,_),_._isRGBD=!0,_.invertY=!0,this._engine.loadCubeTextureWithMips(_._hardwareTexture.underlyingResource,r,!1,_._useSRGBBuffer,(()=>{_.isReady=!0,s&&s()}),(()=>{throw new Error("Could not load a native cube texture.")}))};if(p)t(p);else{if(i&&6===i.length)throw new Error("Multi-file loading not allowed on env files.");{const i=(e,t)=>{n&&e&&n(e.status+" "+e.statusText,t)};this._loadFile(e,(e=>{t(new Uint8Array(e,0,e.byteLength))}),void 0,void 0,!0,i)}}}else{if(!i||6!==i.length)throw new Error("Cannot load cubemap because 6 files were not defined");const e=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(e.map((e=>this._loadFileAsync(e,void 0,!0).then((e=>new Uint8Array(e,0,e.byteLength)))))).then((e=>new Promise(((t,i)=>{this._engine.loadCubeTexture(_._hardwareTexture.underlyingResource,e,!r,!0,_._useSRGBBuffer,t,i)})))).then((()=>{_.isReady=!0,s&&s()}),(e=>{n&&n(`Failed to load cubemap: ${e.message}`,e)}))}return this._internalTexturesCache.push(_),_}_createHardwareTexture(){return new th(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){const r=new eh(e,t,i,this);return this._renderTargetWrapperCache.push(r),r}_createInternalTexture(e,t,i=!0,r=0){let s,n=!1,o=0,a=3,l=5,h=!1,c=1;void 0!==t&&"object"==typeof t?(n=!!t.generateMipMaps,o=void 0===t.type?0:t.type,a=void 0===t.samplingMode?3:t.samplingMode,l=void 0===t.format?5:t.format,h=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,c=t.samples??1,s=t.label):n=!!t,h=this._getUseSRGBBuffer(h,!n),(1!==o||this._caps.textureFloatLinearFiltering)&&(2!==o||this._caps.textureHalfFloatLinearFiltering)||(a=1),1!==o||this._caps.textureFloat||(o=0,Z.V.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=new Fs.h(this,r),d=e.width??e,f=e.height??e,p=e.layers||0;if(0!==p)throw new Error("Texture layers are not supported in Babylon Native");const _=u._hardwareTexture.underlyingResource,m=ih(l,o);return this._engine.initializeTexture(_,d,f,n,m,!0,h,c),this._setTextureSampling(_,rh(a)),u._useSRGBBuffer=h,u.baseWidth=d,u.baseHeight=f,u.width=d,u.height=f,u.depth=p,u.isReady=!0,u.samples=c,u.generateMipMaps=n,u.samplingMode=a,u.type=o,u.format=l,u.label=s,this._internalTexturesCache.push(u),u}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e);let r,s=!0,n=!1,o=!1,a=1;void 0!==t&&"object"==typeof t&&(s=t.generateDepthBuffer??!0,n=!!t.generateStencilBuffer,o=!!t.noColorAttachment,r=t.colorAttachment,a=t.samples??1);const l=r||(o?null:this._createInternalTexture(e,t,!0,5)),h=e.width??e,c=e.height??e,u=this._engine.createFrameBuffer(l?l._hardwareTexture.underlyingResource:null,h,c,n,s,a);return i._framebuffer=u,i._generateDepthBuffer=s,i._generateStencilBuffer=n,i._samples=a,i.setTextures(l),i}updateRenderTargetTextureSampleCount(e,t){return Z.V.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){const i=rh(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,r,s){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||r)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 r=e,s=this._normalizeIndexData(t);r.is32Bits=4===s.BYTES_PER_ELEMENT,this._engine.updateDynamicIndexBuffer(r.nativeIndexBuffer,s.buffer,s.byteOffset,s.byteLength,i)}updateDynamicVertexBuffer(e,t,i=0,r){const s=e,n=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,o=new Uint8Array(n.buffer,n.byteOffset,r??n.byteLength);this._engine.updateDynamicVertexBuffer(s.nativeVertexBuffer,o.buffer,o.byteOffset,o.byteLength,i)}_setTexture(e,t,i=!1,r=!1){const s=this._boundUniforms[e];if(!s)return!1;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._boundTexturesCache[e]=null,this._unsetNativeTexture(s)),!1;if(t.video)this._activeChannel=e,t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;let n;return n=r?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!(!n||!n._hardwareTexture||(this._setTextureWrapMode(n._hardwareTexture.underlyingResource,sh(t.wrapU),sh(t.wrapV),sh(t.wrapR)),this._updateAnisotropicLevel(t),this._setNativeTexture(s,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,r){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.finishEncodingCommand()}_setNativeTexture(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()}_unsetNativeTexture(e){_native.Engine.COMMAND_UNSETTEXTURE&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNSETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_updateAnisotropicLevel(e){const t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;t&&t._hardwareTexture&&t._cachedAnisotropicFilteringLevel!==i&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(t._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t._cachedAnisotropicFilteringLevel=i)}_bindTexture(e,t){const i=this._boundUniforms[e];if(i)if(t&&t._hardwareTexture){const e=t._hardwareTexture.underlyingResource;this._setNativeTexture(i,e)}else this._unsetNativeTexture(i)}unbindAllTextures(){_native.Engine.COMMAND_DISCARDALLTEXTURES&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DISCARDALLTEXTURES),this._commandBufferEncoder.finishEncodingCommand())}_deleteBuffer(e){e.nativeIndexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeIndexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeVertexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeVertexBuffer)}createCanvas(e,t){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");const i=new _native.Canvas;return i.width=e,i.height=t,i}createCanvasImage(){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");return new _native.Image}updateTextureData(e,t,i,r,s,n,o=0,a=0,l=!1){throw new Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,n=0,o=0){throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,r=0){throw new Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,r=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}getFontOffset(e){return{ascent:0,height:0,descent:0}}flushFramebuffer(){}_readTexturePixels(e,t,i,r,s,n,o,a,l,h){if(void 0!==r&&-1!==r)throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${r}.`);return this._engine.readTexture(e._hardwareTexture?.underlyingResource,s??0,l??0,h??0,t,i,n?.buffer??null,n?.byteOffset??0,n?.byteLength??0).then((e=>(n||(n=new Uint8Array(e)),n)))}}gh.PROTOCOL_VERSION=8,gh._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new vh:new zl};class vh extends zl{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)}}class xh{static ComputeNumMipmapLevels(e,t){return(0,ar.ILog2)(Math.max(e,t))+1}static GetTextureTypeFromFormat(e){switch(e){case"r8unorm":case"r8uint":case"rg8unorm":case"rg8uint":case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8uint":case"bgra8unorm":case"bgra8unorm-srgb":case"rgb10a2uint":case"rgb10a2unorm":case"rgb9e5ufloat":case"rg11b10ufloat":case"bc7-rgba-unorm":case"bc7-rgba-unorm-srgb":case"bc6h-rgb-ufloat":case"bc5-rg-unorm":case"bc3-rgba-unorm":case"bc3-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc2-rgba-unorm-srgb":case"bc4-r-unorm":case"bc1-rgba-unorm":case"bc1-rgba-unorm-srgb":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"eac-r11unorm":case"eac-rg11unorm":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":case"stencil8":return 0;case"r8snorm":case"r8sint":case"rg8snorm":case"rg8sint":case"rgba8snorm":case"rgba8sint":case"bc6h-rgb-float":case"bc5-rg-snorm":case"bc4-r-snorm":case"eac-r11snorm":case"eac-rg11snorm":return 3;case"r16uint":case"rg16uint":case"rgba16uint":case"depth16unorm":return 5;case"r16sint":case"rg16sint":case"rgba16sint":return 4;case"r16float":case"rg16float":case"rgba16float":return 2;case"r32uint":case"rg32uint":case"rgba32uint":case"r32sint":case"rg32sint":case"rgba32sint":return 7;case"r32float":case"rg32float":case"rgba32float":case"depth32float":case"depth32float-stencil8":case"depth24plus":case"depth24plus-stencil8":return 1}return 0}static GetBlockInformationFromFormat(e){switch(e){case"r8unorm":case"r8snorm":case"r8uint":case"r8sint":return{width:1,height:1,length:1};case"r16uint":case"r16sint":case"r16float":case"rg8unorm":case"rg8snorm":case"rg8uint":case"rg8sint":case"depth16unorm":return{width:1,height:1,length:2};case"r32uint":case"r32sint":case"r32float":case"rg16uint":case"rg16sint":case"rg16float":case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8snorm":case"rgba8uint":case"rgba8sint":case"bgra8unorm":case"bgra8unorm-srgb":case"rgb9e5ufloat":case"rgb10a2uint":case"rgb10a2unorm":case"rg11b10ufloat":case"depth32float":return{width:1,height:1,length:4};case"rg32uint":case"rg32sint":case"rg32float":case"rgba16uint":case"rgba16sint":case"rgba16float":return{width:1,height:1,length:8};case"rgba32uint":case"rgba32sint":case"rgba32float":return{width:1,height:1,length:16};case"stencil8":throw"No fixed size for Stencil8 format!";case"depth24plus":throw"No fixed size for Depth24Plus format!";case"depth24plus-stencil8":throw"No fixed size for Depth24PlusStencil8 format!";case"depth32float-stencil8":return{width:1,height:1,length:5};case"bc7-rgba-unorm":case"bc7-rgba-unorm-srgb":case"bc6h-rgb-ufloat":case"bc6h-rgb-float":case"bc5-rg-unorm":case"bc5-rg-snorm":case"bc3-rgba-unorm":case"bc3-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc2-rgba-unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"eac-rg11unorm":case"eac-rg11snorm":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":return{width:4,height:4,length:16};case"bc4-r-unorm":case"bc4-r-snorm":case"bc1-rgba-unorm":case"bc1-rgba-unorm-srgb":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"eac-r11unorm":case"eac-r11snorm":return{width:4,height:4,length:8};case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":return{width:5,height:4,length:16};case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":return{width:5,height:5,length:16};case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":return{width:6,height:5,length:16};case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":return{width:6,height:6,length:16};case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":return{width:8,height:5,length:16};case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":return{width:8,height:6,length:16};case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":return{width:8,height:8,length:16};case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":return{width:10,height:5,length:16};case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":return{width:10,height:6,length:16};case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":return{width:10,height:8,length:16};case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":return{width:10,height:10,length:16};case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":return{width:12,height:10,length:16};case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":return{width:12,height:12,length:16}}return{width:1,height:1,length:4}}static IsHardwareTexture(e){return!!e.release}static IsInternalTexture(e){return!!e.dispose}static IsImageBitmap(e){return void 0!==e.close}static IsImageBitmapArray(e){return Array.isArray(e)&&void 0!==e[0].close}static IsCompressedFormat(e){switch(e){case"bc7-rgba-unorm-srgb":case"bc7-rgba-unorm":case"bc6h-rgb-float":case"bc6h-rgb-ufloat":case"bc5-rg-snorm":case"bc5-rg-unorm":case"bc4-r-snorm":case"bc4-r-unorm":case"bc3-rgba-unorm-srgb":case"bc3-rgba-unorm":case"bc2-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc1-rgba-unorm-srgb":case"bc1-rgba-unorm":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"eac-r11unorm":case"eac-r11snorm":case"eac-rg11unorm":case"eac-rg11snorm":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return"depth16unorm";case 16:return"depth24plus";case 13:return"depth24plus-stencil8";case 14:return"depth32float";case 18:return"depth32float-stencil8";case 19:return"stencil8";case 36492:return i?"bc7-rgba-unorm-srgb":"bc7-rgba-unorm";case 36495:return"bc6h-rgb-ufloat";case 36494:return"bc6h-rgb-float";case 33779:return i?"bc3-rgba-unorm-srgb":"bc3-rgba-unorm";case 33778:return i?"bc2-rgba-unorm-srgb":"bc2-rgba-unorm";case 33777:case 33776:return i?"bc1-rgba-unorm-srgb":"bc1-rgba-unorm";case 37808:return i?"astc-4x4-unorm-srgb":"astc-4x4-unorm";case 36196:case 37492:return i?"etc2-rgb8unorm-srgb":"etc2-rgb8unorm";case 37496:return i?"etc2-rgba8unorm-srgb":"etc2-rgba8unorm"}switch(e){case 3:switch(t){case 6:return"r8snorm";case 7:return"rg8snorm";case 4:throw"RGB format not supported in WebGPU";case 8:return"r8sint";case 9:return"rg8sint";case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return"rgba8sint";default:return"rgba8snorm"}case 0:switch(t){case 6:return"r8unorm";case 7:return"rg8unorm";case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?"rgba8unorm-srgb":"rgba8unorm";case 12:return i?"bgra8unorm-srgb":"bgra8unorm";case 8:return"r8uint";case 9:return"rg8uint";case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return"rgba8uint";case 0:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case 1:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case 2:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return"rgba8unorm"}case 4:switch(t){case 8:return"r16sint";case 9:return"rg16sint";case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return"rgba16sint"}case 5:switch(t){case 8:return"r16uint";case 9:return"rg16uint";case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return"rgba16uint"}case 6:switch(t){case 8:return"r32sint";case 9:return"rg32sint";case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return"rgba32sint"}case 7:switch(t){case 8:return"r32uint";case 9:return"rg32uint";case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return"rgba32uint"}case 1:switch(t){case 6:return"r32float";case 7:return"rg32float";case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return"rgba32float"}case 2:switch(t){case 6:return"r16float";case 7:return"rg16float";case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return"rgba16float"}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:default:return"rg11b10ufloat";case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV"}case 14:switch(t){case 5:default:return"rgb9e5ufloat";case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV"}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:default:return"rgb10a2unorm";case 11:return"rgb10a2uint"}}return i?"rgba8unorm-srgb":"rgba8unorm"}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case"r8unorm":case"r8snorm":case"r8uint":case"r8sint":case"bc4-r-unorm":case"bc4-r-snorm":case"r16uint":case"r16sint":case"depth16unorm":case"r16float":case"r32uint":case"r32sint":case"r32float":case"depth32float":case"stencil8":case"depth24plus":case"eac-r11unorm":case"eac-r11snorm":return 1;case"rg8unorm":case"rg8snorm":case"rg8uint":case"rg8sint":case"depth32float-stencil8":case"bc5-rg-unorm":case"bc5-rg-snorm":case"rg16uint":case"rg16sint":case"rg16float":case"rg32uint":case"rg32sint":case"rg32float":case"depth24plus-stencil8":case"eac-rg11unorm":case"eac-rg11snorm":return 2;case"rgb9e5ufloat":case"rg11b10ufloat":case"bc6h-rgb-ufloat":case"bc6h-rgb-float":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":return 3;case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8snorm":case"rgba8uint":case"rgba8sint":case"bgra8unorm":case"bgra8unorm-srgb":case"rgb10a2uint":case"rgb10a2unorm":case"bc7-rgba-unorm":case"bc7-rgba-unorm-srgb":case"bc3-rgba-unorm":case"bc3-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc2-rgba-unorm-srgb":case"bc1-rgba-unorm":case"bc1-rgba-unorm-srgb":case"rgba16uint":case"rgba16sint":case"rgba16float":case"rgba32uint":case"rgba32sint":case"rgba32float":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case"stencil8":case"depth32float-stencil8":case"depth24plus-stencil8":return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case"depth32float-stencil8":case"depth24plus-stencil8":return!0}return!1}static GetDepthFormatOnly(e){switch(e){case"depth16unorm":return"depth16unorm";case"depth24plus":case"depth24plus-stencil8":return"depth24plus";case"depth32float":case"depth32float-stencil8":return"depth32float"}return e}static GetSample(e){return e>1?4:1}}var bh=i(89237);class Sh extends Ot.${constructor(){super(...arguments),this.dbgShowShaderCode=!1,this.dbgSanityChecks=!0,this.dbgVerboseLogsNumFrames=10,this.dbgLogIfNotDrawWrapper=!0,this.dbgShowEmptyEnableEffectCalls=!0,this.dbgVerboseLogsForFirstFrames=!1,this._currentRenderPass=null,this._snapshotRenderingMode=0,this._timestampIndex=0}get enableGPUTimingMeasurements(){return this._timestampQuery.enable}set enableGPUTimingMeasurements(e){this._timestampQuery.enable!==e&&(this.gpuTimeInFrameForMainPass=e?new bh.e:void 0,this._timestampQuery.enable=e)}_currentPassIsMainPass(){return null===this._currentRenderTarget}_endCurrentRenderPass(){if(!this._currentRenderPass)return 0;const e=this._currentPassIsMainPass()?2:1;return this._snapshotRendering.endRenderPass(this._currentRenderPass)||this.compatibilityMode||(this._bundleList.run(this._currentRenderPass),this._bundleList.reset()),this._currentRenderPass.end(),this._timestampQuery.endPass(this._timestampIndex,this._currentRenderTarget&&this._currentRenderTarget.gpuTimeInFrame?this._currentRenderTarget.gpuTimeInFrame:this.gpuTimeInFrameForMainPass),this._timestampIndex+=2,this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count=0&&(u.push(o[c]),d.push(e))}this.shaderProcessingContext.attributeNamesFromEffect=u,this.shaderProcessingContext.attributeLocationsFromEffect=d}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer?.dispose(),this.uniformBuffer=new Rt.D(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=cc.UniformSizes[t];this.uniformBuffer.addUniform(e.name,i,e.length),this._leftOverUniformsByName[e.name]=e.type}this.uniformBuffer.create()}}setEngine(e){this.engine=e}dispose(){this.uniformBuffer&&this.uniformBuffer.dispose()}setInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt(e,t)}setInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt2(e,t,i)}setInt3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt3(e,t,i,r)}setInt4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt4(e,t,i,r,s)}setIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt3(e,t,i,r)}setUInt4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt4(e,t,i,r,s)}setUIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat3(e,t,i,r)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat4(e,t,i,r,s)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){return this.sources?.vertex}_getFragmentShaderCode(){return this.sources?.fragment}}const dc={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class fc{static get KnownUBOs(){return fc._SimplifiedKnownBindings?fc._SimplifiedKnownUBOs:fc._KnownUBOs}constructor(e,t=!1){this.vertexBufferKindToNumberOfComponents={},this.shaderLanguage=e,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],t||this._findStartingGroupBinding()}_findStartingGroupBinding(){const e=fc.KnownUBOs,t=[];for(const i in e){const r=e[i].binding;-1!==r.groupIndex&&(void 0===t[r.groupIndex]?t[r.groupIndex]=r.bindingIndex:t[r.groupIndex]=Math.max(t[r.groupIndex],r.bindingIndex))}this.freeGroupIndex=t.length-1,0===this.freeGroupIndex?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){const i=this._attributeNextLocation;return this._attributeNextLocation+=(dc[e]??1)*(t||1),i}getVaryingNextLocation(e,t=0){const i=this._varyingNextLocation;return this._varyingNextLocation+=(dc[e]??1)*(t||1),i}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>65536-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),4===this.freeGroupIndex)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}}fc._SimplifiedKnownBindings=!0,fc._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}}},fc._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 pc extends cc{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=0,this.parseGLES3=!0}_getArraySize(e,t,i){let r=0;const s=e.indexOf("["),n=e.indexOf("]");if(s>0&&n>0){const t=e.substring(s+1,n);r=+t,isNaN(r)&&(r=+i[t.trim()]),e=e.substring(0,s)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){const i=`// Internals UBO\nuniform ${cc.InternalsUBOName} {\nfloat yFactor_;\nfloat textureOutputHeight_;\n};\n`,r=-1!==e.indexOf("// Internals UBO");return t?(this._fragmentIsGLES3=-1!==e.indexOf("#version 3"),this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),r?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=-1!==e.indexOf("#version 3"),this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),r?e:i+e)}varyingCheck(e,t){return(t&&this._fragmentIsGLES3?/(flat\s)?\s*\bin\b/:!t&&this._vertexIsGLES3?/(flat\s)?\s*\bout\b/:/(flat\s)?\s*\bvarying\b/).test(e)}varyingProcessor(e,t,i){this._preProcessors=i;const r=(t&&this._fragmentIsGLES3?/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:!t&&this._vertexIsGLES3?/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==r){const s=r[1]??"",n=r[2],o=r[3];let a;t?(a=this._webgpuProcessingContext.availableVaryings[o],this._missingVaryings[a]="",void 0===a&&Z.V.Warn(`Invalid fragment shader: The varying named "${o}" is not declared in the vertex shader! This declaration will be ignored.`)):(a=this._webgpuProcessingContext.getVaryingNextLocation(n,this._getArraySize(o,n,i)[2]),this._webgpuProcessingContext.availableVaryings[o]=a,this._missingVaryings[a]=`layout(location = ${a}) ${s} in ${n} ${o};`),e=e.replace(r[0],void 0===a?"":`layout(location = ${a}) ${s} ${t?"in":"out"} ${n} ${o};`)}return e}attributeProcessor(e,t){this._preProcessors=t;const i=(this._vertexIsGLES3?/\s*in\s+(\S+)\s+(\S+)\s*;/gm:/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==i){const r=i[1],s=i[2],n=this._webgpuProcessingContext.getAttributeNextLocation(r,this._getArraySize(s,r,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=n,this._webgpuProcessingContext.orderedAttributes[n]=s;const o=this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[s];if(void 0!==o){const t=o<0?-1===o?"int":"ivec"+-o:1===o?"uint":"uvec"+o,a=`_int_${s}_`;e=e.replace(i[0],`layout(location = ${n}) in ${t} ${a}; ${r} ${s} = ${r}(${a});`)}else e=e.replace(i[0],`layout(location = ${n}) in ${r} ${s};`)}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(null!==r){let s=r[1],n=r[2];if(0===s.indexOf("sampler")||1===s.indexOf("sampler")){let r=0;[n,s,r]=this._getArraySize(n,s,i);let o=this._webgpuProcessingContext.availableTextures[n];if(!o){o={autoBindSampler:!0,isTextureArray:r>0,isStorageTexture:!1,textures:[],sampleType:"float"};for(let e=0;e<(r||1);++e)o.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const a=cc._SamplerTypeByWebGLSamplerType[s]??"sampler",l=!!cc._IsComparisonSamplerByWebGPUSamplerType[a],h=l?"comparison":"filtering",c=n+"Sampler";let u=this._webgpuProcessingContext.availableSamplers[c];u||(u={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:h});const d="u"===s.charAt(0)?"u":"i"===s.charAt(0)?"i":"";d&&(s=s.substring(1));const f=l?"depth":"u"===d?"uint":"i"===d?"sint":"float";o.sampleType=f;const p=r>0,_=u.binding.groupIndex,m=u.binding.bindingIndex,g=cc._SamplerFunctionByWebGLSamplerType[s],v=cc._TextureTypeByWebGLSamplerType[s],x=cc._GpuTextureViewDimensionByWebGPUTextureType[v];if(p){const t=[];t.push(`layout(set = ${_}, binding = ${m}) uniform ${d}${a} ${c};`),e="\n";for(let i=0;i0?"\n":""}#define ${n}${i} ${d}${g}(${n}Texture${i}, ${c})`}e=t.join("\n")+e,this._textureArrayProcessing.push(n)}else r=1,e=`layout(set = ${_}, binding = ${m}) uniform ${a} ${c};\n layout(set = ${o.textures[0].groupIndex}, binding = ${o.textures[0].bindingIndex}) uniform ${d}${v} ${n}Texture;\n #define ${n} ${d}${g}(${n}Texture, ${c})`;this._webgpuProcessingContext.availableTextures[n]=o,this._webgpuProcessingContext.availableSamplers[c]=u,this._addSamplerBindingDescription(c,u,!t);for(let e=0;e=0,i="\n glFragCoord_ = gl_FragCoord;\n if (yFactor_ == 1.) {\n glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y;\n }\n ",r=t?"vec4 glFragCoord_;\n":"",s=-1!==e.search(/layout *\(location *= *0\) *out/g);if(e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/gl_FragCoord/g,"glFragCoord_"),this._fragmentIsGLES3){const t=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);null!==t&&(e=e.substring(0,t.index)+"layout(location = 0) "+e.substring(t.index))}else e=e.replace(/void\s+?main\s*\(/g,(n||s?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");e=(e=e.replace(/dFdy/g,"(-yFactor_)*dFdy")).replace("##INJECTCODE##",r),t&&(e=jl(e,"void main",i))}else if(e=(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex")).replace(/gl_VertexID/g,"gl_VertexIndex"),-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;if(!i){const t=e.lastIndexOf("}");e=e.substring(0,t),e+="gl_Position.y *= yFactor_;\n",e+="}"}return e}_applyTextureArrayProcessing(e,t){const i=new RegExp(t+"\\s*\\[(.+)?\\]","gm");let r=i.exec(e);for(;null!==r;){const s=r[1];let n=+s;this._preProcessors&&isNaN(n)&&(n=+this._preProcessors[s.trim()]),e=e.replace(r[0],t+n),r=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} {\n `;for(const e of this._webgpuProcessingContext.leftOverUniforms)e.length>0?i+=` ${e.type} ${e.name}[${e.length}];\n`:i+=` ${e.type} ${e.name};\n`;return i+="};\n\n",i}finalizeShaders(e,t){for(let i=0;i0&&(t=i+"\n"+t)}const i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}}i(68273),i(71281),i(41416),i(32764);var _c=i(87647);i(27493),i(10598),i(14910),i(17327);const mc={texture_1d:"1d",texture_2d:"2d",texture_2d_array:"2d-array",texture_3d:"3d",texture_cube:"cube",texture_cube_array:"cube-array",texture_multisampled_2d:"2d",texture_depth_2d:"2d",texture_depth_2d_array:"2d-array",texture_depth_cube:"cube",texture_depth_cube_array:"cube-array",texture_depth_multisampled_2d:"2d",texture_storage_1d:"1d",texture_storage_2d:"2d",texture_storage_2d_array:"2d-array",texture_storage_3d:"3d",texture_external:null};class gc extends cc{constructor(){super(...arguments),this.shaderLanguage=1,this.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,this.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,this.noPrecision=!0,this.pureMode=!1}preProcessor(e,t,i,r,s){for(const t in i){if("__VERSION__"===t)continue;const r=i[t];isNaN(parseInt(r))&&isNaN(parseFloat(r))||(e=`const ${t} = ${r};\n`+e)}return e}_getArraySize(e,t,i){let r=0;const s=t.lastIndexOf(">");if(t.indexOf("array")>=0&&s>0){let e=s;for(;e>0&&" "!==t.charAt(e)&&","!==t.charAt(e);)e--;const n=t.substring(e+1,s);for(r=+n,isNaN(r)&&(r=+i[n.trim()]);e>0&&(" "===t.charAt(e)||","===t.charAt(e));)e--;t=t.substring(t.indexOf("<")+1,e+1)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){const t=this.pureMode?"":`struct ${cc.InternalsUBOName} {\n yFactor_: f32,\n textureOutputHeight_: f32,\n};\nvar internals : ${cc.InternalsUBOName};\n`;return-1!==e.indexOf(t)?e:t+Yl(e)}varyingCheck(e){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(null!==r){const s=r[1]??"perspective",n=r[2]??"center",o=r[4],a=r[3],l="flat"===s?`@interpolate(${s})`:`@interpolate(${s}, ${n})`;let h;t?(h=this._webgpuProcessingContext.availableVaryings[a],void 0===h&&Z.V.Warn(`Invalid fragment shader: The varying named "${a}" is not declared in the vertex shader! This declaration will be ignored.`)):(h=this._webgpuProcessingContext.getVaryingNextLocation(o,this._getArraySize(a,o,i)[2]),this._webgpuProcessingContext.availableVaryings[a]=h,this._varyingsWGSL.push(` @location(${h}) ${l} ${a} : ${o},`),this._varyingNamesWGSL.push(a)),e=""}return e}attributeProcessor(e,t){const i=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==i){const r=i[2],s=i[1],n=this._webgpuProcessingContext.getAttributeNextLocation(r,this._getArraySize(s,r,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=n,this._webgpuProcessingContext.orderedAttributes[n]=s;const o=this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[s];if(void 0!==o){const e=o<0?-1===o?"i32":"vec"+-o+"":1===o?"u32":"vec"+o+"",t=`_int_${s}_`;this._attributesInputWGSL.push(`@location(${n}) ${t} : ${e},`),this._attributesWGSL.push(`${s} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${s} = ${r}(vertexInputs_.${t});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${n}) ${s} : ${r},`),this._attributesWGSL.push(`${s} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${s} = vertexInputs_.${s};`);e=""}return e}uniformProcessor(e,t,i){const r=this.uniformRegexp.exec(e);if(null!==r){const t=r[2],s=r[1];this._addUniformToLeftOverUBO(s,t,i),e=""}return e}textureProcessor(e,t,i){const r=this.textureRegexp.exec(e);if(null!==r){const s=r[1],n=r[2],o=!!r[3],a=r[4],l=a.indexOf("storage")>0,h=r[6],c=l?h.substring(0,h.indexOf(",")).trim():null;let u=o?this._getArraySize(s,n,i)[2]:0,d=this._webgpuProcessingContext.availableTextures[s];if(d)u=d.textures.length;else{d={isTextureArray:u>0,isStorageTexture:l,textures:[],sampleType:"float"},u=u||1;for(let e=0;e0,p=mc[a],_=f?"depth":"u32"===h?"uint":"i32"===h?"sint":"float";if(d.sampleType=_,void 0===p)throw`Can't get the texture dimension corresponding to the texture function "${a}"!`;for(let i=0;i=0&&!this.pureMode?"\n if (internals.yFactor_ == 1.) {\n fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y;\n }\n ":"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);const r=this._buildLeftOverUBO();t=r+t,e=(e=(e=r+e).replace(/#define (\w+)\s+(\d+\.?\d*)/g,"const $1 = $2;")).replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let s="struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n";this._attributesInputWGSL.length>0&&(s+=this._attributesInputWGSL.join("\n")),s+="\n};\nvar vertexInputs"+(this._hasNonFloatAttribute?"_":"")+" : VertexInputs;\n",this._hasNonFloatAttribute&&(s+="struct VertexInputs_ {\n vertexIndex : u32, instanceIndex : u32,\n",s+=this._attributesWGSL.join("\n"),s+="\n};\nvar vertexInputs : VertexInputs_;\n");let n="struct FragmentInputs {\n @builtin(position) position : vec4,\n";this._varyingsWGSL.length>0&&(n+=this._varyingsWGSL.join("\n")),n+="\n};\nvar vertexOutputs : FragmentInputs;\n",e=s+n+e;let o=`\n vertexInputs${this._hasNonFloatAttribute?"_":""} = input;\n`;this._hasNonFloatAttribute&&(o+="vertexInputs.vertexIndex = vertexInputs_.vertexIndex;\nvertexInputs.instanceIndex = vertexInputs_.instanceIndex;\n",o+=this._attributesConversionCodeWGSL.join("\n"),o+="\n");const a=this.pureMode?" return vertexOutputs;":" vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;\n return vertexOutputs;";let l=-1!==e.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS");e=(l?"diagnostic(off, derivative_uniformity);\n":"")+"diagnostic(off, chromium.unreachable_code);\n"+jl(e,"fn main",o,a),t=(t=t.replace(/#define (\w+)\s+(\d+\.?\d*)/g,"const $1 = $2;")).replace(/#define /g,"//#define "),t=this._processStridedUniformArrays(t),this.pureMode||(t=t.replace(/dpdy/g,"(-internals.yFactor_)*dpdy"));let h="struct FragmentInputs {\n @builtin(position) position : vec4,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(h+=this._varyingsWGSL.join("\n")),h+="\n};\nvar fragmentInputs : FragmentInputs;\n";let c="struct FragmentOutputs {\n";const u="fragmentOutputs\\.fragData";let d=t.match(new RegExp(u+"0","g")),f=0;if(d){c+=` @location(${f}) fragData0 : vec4,\n`,f++;for(let e=1;e<8;e++)d=t.match(new RegExp(u+e,"g")),d&&(c+=` @location(${f}) fragData${f} : vec4,\n`,f++);-1!==t.indexOf("MRT_AND_COLOR")&&(c+=` @location(${f}) color : vec4,\n`,f++)}d=t.match(/oitDepthSampler/),d&&(c+=` @location(${f++}) depth : vec2,\n`,c+=` @location(${f++}) frontColor : vec4,\n`,c+=` @location(${f++}) backColor : vec4,\n`),0===f&&(c+=" @location(0) color : vec4,\n",f++);let p=!1,_=0;for(;!(p||(_=t.indexOf("fragmentOutputs.fragDepth",_),_<0));){const e=_;for(p=!0;_>1&&"\n"!==t.charAt(_);){if("/"===t.charAt(_)&&"/"===t.charAt(_-1)){p=!1;break}_--}_=e+25}p&&(c+=" @builtin(frag_depth) fragDepth: f32,\n"),c+="};\nvar fragmentOutputs : FragmentOutputs;\n";const m=" fragmentInputs = input;\n "+i;return l=-1!==(t=h+c+t).indexOf("#define DISABLE_UNIFORMITY_ANALYSIS"),t=(l?"diagnostic(off, derivative_uniformity);\n":"")+"diagnostic(off, chromium.unreachable_code);\n"+jl(t,"fn main",m," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",r=`struct ${e} {\n`;for(const t of this._webgpuProcessingContext.leftOverUniforms){const s=t.type.replace(/^(.*?)(<.*>)?$/,"$1"),n=cc.UniformSizes[s];if(t.length>0)if(n<=2){const n=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${n} {\n @size(16)\n el: ${s},\n }`,this._stridedUniformArrays.push(t.name),r+=` @align(16) ${t.name} : array<${n}, ${t.length}>,\n`}else r+=` ${t.name} : array<${t.type}, ${t.length}>,\n`;else r+=` ${t.name} : ${t.type},\n`}return r+="};\n",r=`${i}\n${r}`,r+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var uniforms : ${e};\n`,r}_processSamplers(e,t){const i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){const r=i.exec(e);if(null===r)break;const s=r[1],n=r[2],o=s.length-7,a=s.lastIndexOf("Sampler")===o?s.substring(0,o):null,l="sampler_comparison"===n?"comparison":"filtering";if(a){const e=this._webgpuProcessingContext.availableTextures[a];e&&(e.autoBindSampler=!0)}let h=this._webgpuProcessingContext.availableSamplers[s];h||(h={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:l},this._webgpuProcessingContext.availableSamplers[s]=h),this._addSamplerBindingDescription(s,h,t);const c=e.substring(0,r.index),u=`@group(${h.binding.groupIndex}) @binding(${h.binding.bindingIndex}) `,d=e.substring(r.index);e=c+u+d,i.lastIndex+=u.length}return e}_processCustomBuffers(e,t){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(null===r)break;const s=r[1],n=r[3];let o=r[4];const a=r[5];let l=this._webgpuProcessingContext.availableBuffers[o];if(!l){const e="uniform"===s?fc.KnownUBOs[a]:null;let t;e?(o=a,t=e.binding,-1===t.groupIndex&&(t=this._webgpuProcessingContext.availableBuffers[o]?.binding,t||(t=this._webgpuProcessingContext.getNextFreeUBOBinding()))):t=this._webgpuProcessingContext.getNextFreeUBOBinding(),l={binding:t},this._webgpuProcessingContext.availableBuffers[o]=l}this._addBufferBindingDescription(o,this._webgpuProcessingContext.availableBuffers[o],"read_write"===n?"storage":"storage"===s?"read-only-storage":"uniform",t);const h=l.binding.groupIndex,c=l.binding.bindingIndex,u=e.substring(0,r.index),d=`@group(${h}) @binding(${c}) `,f=e.substring(r.index);e=u+d+f,i.lastIndex+=d.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 vc{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e){return this._webgpuMSAATexture?.[e]??null}setMSAATexture(e,t){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),this._webgpuMSAATexture[t]=e}releaseMSAATexture(e){if(this._webgpuMSAATexture)if(e)this._webgpuMSAATexture[e]?.destroy(),delete this._webgpuMSAATexture[e];else{for(const e of this._webgpuMSAATexture)e?.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this._originalFormatIsRGB=!1,this.format="rgba8unorm",this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,r,s,n,o,a){let l="2d",h=1;r?(l=i?"cube-array":"cube",h=6*(a||1)):s?(l="3d",h=1):i&&(l="2d-array",h=a);const c=xh.GetDepthFormatOnly(this.format),u=xh.HasDepthAndStencilAspects(this.format)?"depth-only":"all";this.createView({label:`TextureView${s?"3D":r?"Cube":"2D"}${i?"_Array"+h:""}_${n}x${o}_${t?"wmips":"womips"}_${this.format}_${l}`,format:c,dimension:l,mipLevelCount:t?(0,ar.ILog2)(Math.max(n,o))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:h,aspect:u})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){const t=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=t}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}release(){this._webgpuTexture?.destroy(),this.releaseMSAATexture(),this._copyInvertYTempTexture?.destroy(),this.reset()}}const xc="\n const pos = array, 4>( vec2f(-1.0f, 1.0f), vec2f(1.0f, 1.0f), vec2f(-1.0f, -1.0f), vec2f(1.0f, -1.0f));\n const tex = array, 4>( vec2f(0.0f, 0.0f), vec2f(1.0f, 0.0f), vec2f(0.0f, 1.0f), vec2f(1.0f, 1.0f));\n\n var img: texture_2d;\n\n #ifdef INVERTY\n varying vTextureSize: vec2f;\n #endif\n\n @vertex\n fn main(input : VertexInputs) -> FragmentInputs {\n #ifdef INVERTY\n vertexOutputs.vTextureSize = vec2f(textureDimensions(img, 0));\n #endif\n vertexOutputs.position = vec4f(pos[input.vertexIndex], 0.0, 1.0);\n }\n ",bc=xc;var Sc,Tc;!function(e){e[e.MipMap=0]="MipMap",e[e.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",e[e.Clear=2]="Clear",e[e.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"}(Sc||(Sc={})),function(e){e[e.DontInvertY=0]="DontInvertY",e[e.InvertY=1]="InvertY"}(Tc||(Tc={}));const Cc=[{vertex:"\n const pos = array, 4>( vec2f(-1.0f, 1.0f), vec2f(1.0f, 1.0f), vec2f(-1.0f, -1.0f), vec2f(1.0f, -1.0f));\n const tex = array, 4>( vec2f(0.0f, 0.0f), vec2f(1.0f, 0.0f), vec2f(0.0f, 1.0f), vec2f(1.0f, 1.0f));\n\n varying vTex: vec2f;\n\n @vertex\n fn main(input : VertexInputs) -> FragmentInputs {\n vertexOutputs.vTex = tex[input.vertexIndex];\n vertexOutputs.position = vec4f(pos[input.vertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n var imgSampler: sampler;\n var img: texture_2d;\n\n varying vTex: vec2f;\n\n @fragment\n fn main(input: FragmentInputs) -> FragmentOutputs {\n fragmentOutputs.color = textureSample(img, imgSampler, input.vTex);\n }\n "},{vertex:xc,fragment:"\n var img: texture_2d;\n\n #ifdef INVERTY\n varying vTextureSize: vec2f;\n #endif\n\n @fragment\n fn main(input: FragmentInputs) -> FragmentOutputs {\n #ifdef INVERTY\n var color: vec4f = textureLoad(img, vec2i(i32(input.position.x), i32(input.vTextureSize.y - input.position.y)), 0);\n #else\n var color: vec4f = textureLoad(img, vec2i(input.position.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n fragmentOutputs.color = vec4f(color.rgb * color.a, color.a);\n #endif\n fragmentOutputs.color = color;\n }\n "},{vertex:"\n const pos = array, 4>( vec2f(-1.0f, 1.0f), vec2f(1.0f, 1.0f), vec2f(-1.0f, -1.0f), vec2f(1.0f, -1.0f));\n\n @vertex\n fn main(input : VertexInputs) -> FragmentInputs {\n vertexOutputs.position = vec4f(pos[input.vertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n uniform color: vec4f;\n\n\n @fragment\n fn main(input: FragmentInputs) -> FragmentOutputs {\n fragmentOutputs.color = uniforms.color;\n }\n "},{vertex:bc,fragment:"\n var img: texture_2d;\n uniform ofstX: f32;\n uniform ofstY: f32;\n uniform width: f32;\n uniform height: f32;\n\n #ifdef INVERTY\n varying vTextureSize: vec2f;\n #endif\n\n @fragment\n fn main(input: FragmentInputs) -> FragmentOutputs {\n if (input.position.x < uniforms.ofstX || input.position.x >= uniforms.ofstX + uniforms.width) {\n discard;\n }\n if (input.position.y < uniforms.ofstY || input.position.y >= uniforms.ofstY + uniforms.height) {\n discard;\n }\n #ifdef INVERTY\n var color: vec4f = textureLoad(img, vec2i(i32(input.position.x), i32(uniforms.ofstY + uniforms.height - (input.position.y - uniforms.ofstY))), 0);\n #else\n var color: vec4f = textureLoad(img, vec2i(input.position.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color = vec4f(color.rgb * color.a, color.a);\n #endif\n fragmentOutputs.color = color;\n }\n "}],yc={"":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 Ec{constructor(e,t,i,r){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._engine=e,this._device=t,this._bufferManager=i,-1!==r.indexOf("rg11b10ufloat-renderable")){const e=Object.keys(yc);yc.rg11b10ufloat=yc[e[e.length-1]]+1}this._mipmapSampler=t.createSampler({minFilter:"linear"}),this._videoSampler=t.createSampler({minFilter:"linear"}),this._ubCopyWithOfst=this._bufferManager.createBuffer(16,Eh.Uniform|Eh.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline("rgba8unorm"),this._getVideoPipeline("rgba8unorm")}_getPipeline(e,t=Sc.MipMap,i){const r=t===Sc.MipMap?1:t===Sc.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===Sc.Clear?8:t===Sc.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let s=this._pipelines[e][r];if(!s){let n="";t!==Sc.InvertYPremultiplyAlpha&&t!==Sc.InvertYPremultiplyAlphaWithOfst||(i.invertY&&(n+="#define INVERTY\n"),i.premultiplyAlpha&&(n+="#define PREMULTIPLYALPHA\n"));let o=this._compiledShaders[r];if(!o){let e=Cc[t].vertex,i=Cc[t].fragment;const s={defines:n.split("\n"),indexParameters:null,isFragment:!1,shouldUseHighPrecisionShader:!0,processor:this._engine._getShaderProcessor(1),supportsUniformBuffers:!0,shadersRepository:"",includesShadersStore:{},version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._engine._getShaderProcessingContext(1,!0),isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};(0,Cn.pB)(s),s.processor.pureMode=!0,(0,Cn.M0)(e,s,(t=>{e=t}),this._engine),s.isFragment=!0,(0,Cn.M0)(i,s,(e=>{i=e}),this._engine);const a=(0,Cn.nO)(e,i,s);s.processor.pureMode=!1;const l=this._device.createShaderModule({code:a.vertexCode}),h=this._device.createShaderModule({code:a.fragmentCode});o=this._compiledShaders[r]=[l,h]}const a=this._device.createRenderPipeline({layout:"auto",vertex:{module:o[0],entryPoint:"main"},fragment:{module:o[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:"triangle-strip",stripIndexFormat:"uint16"}});s=this._pipelines[e][r]=[a,a.getBindGroupLayout(0)]}return s}_getVideoPipeline(e,t=Tc.DontInvertY){const i=t===Tc.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let r=this._videoPipelines[e][i];if(!r){let t=this._videoCompiledShaders[i];if(!t){const e=this._device.createShaderModule({code:"\n struct VertexOutput {\n @builtin(position) Position : vec4,\n @location(0) fragUV : vec2\n }\n\n @vertex\n fn main(\n @builtin(vertex_index) VertexIndex : u32\n ) -> VertexOutput {\n var pos = array, 4>(\n vec2(-1.0, 1.0),\n vec2( 1.0, 1.0),\n vec2(-1.0, -1.0),\n vec2( 1.0, -1.0)\n );\n var tex = array, 4>(\n vec2(0.0, 0.0),\n vec2(1.0, 0.0),\n vec2(0.0, 1.0),\n vec2(1.0, 1.0)\n );\n\n var output: VertexOutput;\n\n output.Position = vec4(pos[VertexIndex], 0.0, 1.0);\n output.fragUV = tex[VertexIndex];\n\n return output;\n }\n "}),r=this._device.createShaderModule({code:0===i?"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV);\n }\n ":"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y));\n }\n "});t=this._videoCompiledShaders[i]=[e,r]}const s=this._device.createRenderPipeline({label:`BabylonWebGPUDevice${this._engine.uniqueId}_CopyVideoToTexture_${e}_${0===i?"DontInvertY":"InvertY"}`,layout:"auto",vertex:{module:t[0],entryPoint:"main"},fragment:{module:t[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:"triangle-strip",stripIndexFormat:"uint16"}});r=this._videoPipelines[e][i]=[s,s.getBindGroupLayout(0)]}return r}setCommandEncoder(e){this._commandEncoderForCreation=e}copyVideoToTexture(e,t,i,r=!1,s){const n=void 0===s,[o,a]=this._getVideoPipeline(i,r?Tc.InvertY:Tc.DontInvertY);n&&(s=this._device.createCommandEncoder({})),s.pushDebugGroup?.(`copy video to texture - invertY=${r}`);const l=t._hardwareTexture,h={label:`BabylonWebGPUDevice${this._engine.uniqueId}_copyVideoToTexture_${i}_${r?"InvertY":"DontInvertY"}${t.label?"_"+t.label:""}`,colorAttachments:[{view:l.underlyingResource.createView({format:i,dimension:"2d",mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:"all"}),loadOp:"load",storeOp:"store"}]},c=s.beginRenderPass(h),u={layout:a,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},d=this._device.createBindGroup(u);c.setPipeline(o),c.setBindGroup(0,d),c.draw(4,1,0,0),c.end(),s.popDebugGroup?.(),n&&(this._device.queue.submit([s.finish()]),s=null)}invertYPreMultiplyAlpha(e,t,i,r,s=!1,n=!1,o=0,a=0,l=1,h=0,c=0,u=0,d=0,f,p){const _=0!==u,m=void 0===f,[g,v]=this._getPipeline(r,_?Sc.InvertYPremultiplyAlphaWithOfst:Sc.InvertYPremultiplyAlpha,{invertY:s,premultiplyAlpha:n});let x;if(o=Math.max(o,0),m&&(f=this._device.createCommandEncoder({})),f.pushDebugGroup?.(`internal process texture - invertY=${s} premultiplyAlpha=${n}`),xh.IsHardwareTexture(e)?(x=e.underlyingResource,s&&!n&&1===l&&0===o||(e=void 0)):(x=e,e=void 0),!x)return;_&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([h,c,u,d]),0,16);const b=e,S=b?._copyInvertYTempTexture??this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,r,1,f,21,void 0,"TempTextureForCopyWithInvertY"),T=b?._copyInvertYRenderPassDescr??{label:`BabylonWebGPUDevice${this._engine.uniqueId}_invertYPreMultiplyAlpha_${r}_${s?"InvertY":"DontInvertY"}_${n?"PremultiplyAlpha":"DontPremultiplyAlpha"}`,colorAttachments:[{view:S.createView({format:r,dimension:"2d",baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:"load",storeOp:"store"}]},C=f.beginRenderPass(T);let y=_?b?._copyInvertYBindGroupWithOfst:b?._copyInvertYBindGroup;if(!y){const e={layout:v,entries:[{binding:0,resource:x.createView({format:r,dimension:"2d",baseMipLevel:a,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:o})}]};_&&e.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),y=this._device.createBindGroup(e)}C.setPipeline(g),C.setBindGroup(0,y),C.draw(4,1,0,0),C.end(),f.copyTextureToTexture({texture:S},{texture:x,mipLevel:a,origin:{x:0,y:0,z:o}},{width:t,height:i,depthOrArrayLayers:1}),b?(b._copyInvertYTempTexture=S,b._copyInvertYRenderPassDescr=T,_?b._copyInvertYBindGroupWithOfst=y:b._copyInvertYBindGroup=y):this._deferredReleaseTextures.push([S,null]),f.popDebugGroup?.(),m&&(this._device.queue.submit([f.finish()]),f=null)}copyWithInvertY(e,t,i,r){const s=void 0===r,[n,o]=this._getPipeline(t,Sc.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});s&&(r=this._device.createCommandEncoder({})),r.pushDebugGroup?.("internal copy texture with invertY");const a=r.beginRenderPass(i),l=this._device.createBindGroup({layout:o,entries:[{binding:0,resource:e}]});a.setPipeline(n),a.setBindGroup(0,l),a.draw(4,1,0,0),a.end(),r.popDebugGroup?.(),s&&(this._device.queue.submit([r.finish()]),r=null)}createTexture(e,t=!1,i=!1,r=!1,s=!1,n=!1,o="rgba8unorm",a=1,l,h=-1,c=0,u){a=xh.GetSample(a);const d=e.layers||1,f={width:e.width,height:e.height,depthOrArrayLayers:d},p=yc[o]?16:0,_=xh.IsCompressedFormat(o),m=t?xh.ComputeNumMipmapLevels(e.width,e.height):1,g=h>=0?h:7;c|=t&&!_?1|p:0,_||n||(c|=2|p);const v=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_Texture${n?"3D":"2D"}_${u?u+"_":""}${f.width}x${f.height}x${f.depthOrArrayLayers}_${t?"wmips":"womips"}_${o}_samples${a}`,size:f,dimension:n?"3d":"2d",format:o,usage:g|c,sampleCount:a,mipLevelCount:m});return xh.IsImageBitmap(e)&&(this.updateTexture(e,v,e.width,e.height,d,o,0,0,r,s,0,0),t&&i&&this.generateMipmaps(v,o,m,0,n,l)),v}createCubeTexture(e,t=!1,i=!1,r=!1,s=!1,n="rgba8unorm",o=1,a,l=-1,h=0,c){o=xh.GetSample(o);const u=xh.IsImageBitmapArray(e)?e[0].width:e.width,d=xh.IsImageBitmapArray(e)?e[0].height:e.height,f=yc[n]?16:0,p=xh.IsCompressedFormat(n),_=t?xh.ComputeNumMipmapLevels(u,d):1,m=l>=0?l:7;h|=t&&!p?1|f:0,p||(h|=2|f);const g=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_TextureCube_${c?c+"_":""}${u}x${d}x6_${t?"wmips":"womips"}_${n}_samples${o}`,size:{width:u,height:d,depthOrArrayLayers:6},dimension:"2d",format:n,usage:m|h,sampleCount:o,mipLevelCount:_});return xh.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,g,u,d,n,r,s,0,0),t&&i&&this.generateCubeMipmaps(g,n,_,a)),g}generateCubeMipmaps(e,t,i,r){const s=void 0===r;s&&(r=this._device.createCommandEncoder({})),r.pushDebugGroup?.(`create cube mipmaps - ${i} levels`);for(let s=0;s<6;++s)this.generateMipmaps(e,t,i,s,!1,r);r.popDebugGroup?.(),s&&(this._device.queue.submit([r.finish()]),r=null)}generateMipmaps(e,t,i,r=0,s=!1,n){const o=void 0===n,[a,l]=this._getPipeline(t);let h;if(r=Math.max(r,0),o&&(n=this._device.createCommandEncoder({})),n.pushDebugGroup?.(`create mipmaps for face #${r} - ${i} levels`),xh.IsHardwareTexture(e)?(h=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(h=e,e=void 0),!h)return;const c=e;for(let e=1;eh;)this._device.queue.writeBuffer(n,t+c,i.buffer,o+c,h),c+=h;this._device.queue.writeBuffer(n,t+c,i.buffer,o+c,s-c)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const r=new Uint16Array(t);for(;e--;)i[e]=(0,Ac.SX)(r[e]);return i}readDataFromBuffer(e,t,i,r,s,n,o=0,a=0,l=null,h=!0,c=!1){const u=1===o?2:2===o?1:0,d=this._engine.uniqueId;return new Promise(((i,f)=>{e.mapAsync(1,a,t).then((()=>{const d=e.getMappedRange(a,t);let f=l;if(c)f=null===f?(0,Xs.kZ)(o,t,!0,d):(0,Xs.kZ)(o,f.buffer,void 0,d);else if(null===f)switch(u){case 0:f=new Uint8Array(t),f.set(new Uint8Array(d));break;case 1:f=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d);break;case 2:f=new Float32Array(t/4),f.set(new Float32Array(d))}else switch(u){case 0:f=new Uint8Array(f.buffer),f.set(new Uint8Array(d));break;case 1:f=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d,l);break;case 2:f=new Float32Array(f.buffer),f.set(new Float32Array(d))}if(s!==n){1!==u||c||(s*=2,n*=2);const e=new Uint8Array(f.buffer);let t=s,i=0;for(let o=1;o{this._engine.isDisposed||this._engine.uniqueId!==d?i(new Uint8Array):f(e)}))}))}releaseBuffer(e){return Rc._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,0===e.references&&(this._deferredReleaseBuffers.push(e.underlyingResource),!0))}destroyDeferredBuffers(){for(let e=0;e1&&(0!==n||0!==o)&&"nearest"!==s?{magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",anisotropyEnabled:!0}:{magFilter:i,minFilter:r,mipmapFilter:s,lodMinClamp:n,lodMaxClamp:o}}static _GetWrappingMode(e){switch(e){case 1:return"repeat";case 0:return"clamp-to-edge";case 2:return"mirror-repeat"}return"repeat"}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e,t){const i=e.useMipMaps&&e._cachedAnisotropicFilteringLevel?e._cachedAnisotropicFilteringLevel:1,r=this._GetSamplerFilterDescriptor(e,i);return{label:t,...r,...this._GetSamplerWrappingDescriptor(e),compare:e._comparisonFunction?Dc.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:r.anisotropyEnabled?i:1}}static GetCompareFunction(e){switch(e){case 519:return"always";case 514:return"equal";case 516:return"greater";case 518:return"greater-equal";case 513:default:return"less";case 515:return"less-equal";case 512:return"never";case 517:return"not-equal"}}getSampler(e,t=!1,i=0,r){if(this.disabled)return this._device.createSampler(Dc._GetSamplerDescriptor(e,r));t?i=0:0===i&&(i=Dc.GetSamplerHashCode(e));let s=t?void 0:this._samplers[i];return s||(s=this._device.createSampler(Dc._GetSamplerDescriptor(e,r)),t||(this._samplers[i]=s)),s}}var wc;!function(e){e[e.StencilReadMask=0]="StencilReadMask",e[e.StencilWriteMask=1]="StencilWriteMask",e[e.DepthBias=2]="DepthBias",e[e.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",e[e.DepthStencilState=4]="DepthStencilState",e[e.MRTAttachments1=5]="MRTAttachments1",e[e.MRTAttachments2=6]="MRTAttachments2",e[e.RasterizationState=7]="RasterizationState",e[e.ColorStates=8]="ColorStates",e[e.ShaderStage=9]="ShaderStage",e[e.TextureStage=10]="TextureStage",e[e.VertexState=11]="VertexState",e[e.NumStates=12]="NumStates"}(wc||(wc={}));const Nc={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},Fc={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7};class Lc{constructor(e,t){this.mrtTextureCount=0,this._device=e,this._useTextureStage=!0,this._states=new Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}reset(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=["bgra8unorm"],this.setColorFormat("bgra8unorm"),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat("depth24plus-stencil8"),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)}get colorFormats(){return this._mrtAttachments1>0?this._mrtFormats:this._webgpuColorFormat}getRenderPipeline(e,t,i,r=0){if(i=xh.GetSample(i),this.disabled){const s=Lc._GetTopology(e);return this._setVertexState(t),this._setTextureState(r),this._parameter.pipeline=this._createRenderPipeline(t,s,i),Lc.NumCacheMiss++,Lc._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(r),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,Lc.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return Lc.NumCacheHitWithHash++,this._parameter.pipeline;const s=Lc._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,s,i),this._setRenderPipeline(this._parameter),Lc.NumCacheMiss++,Lc._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){Lc.NumPipelineCreationLastFrame=Lc._NumPipelineCreationCurrentFrame,Lc._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,r,s,n,o,a){this._depthWriteEnabled=o,this._depthTestEnabled=n,this._depthCompare=(a??519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(r),this.setDepthBias(s)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[wc.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,wc.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[wc.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,wc.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=yc[e??""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;const i=[0,0];let r=0,s=0,n=0;for(let o=0;o=32&&(s=0,r++)}this._mrtFormats.length=n,this._mrtAttachments1===i[0]&&this._mrtAttachments2===i[1]||(this._mrtAttachments1=i[0],this._mrtAttachments2=i[1],this._states[wc.MRTAttachments1]=i[0],this._states[wc.MRTAttachments2]=i[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,wc.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=void 0===e?0:yc[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=null===e?1:Fc[e]}setStencilPassOp(e){this._stencilFrontPassOp=null===e?2:Fc[e]}setStencilFailOp(e){this._stencilFrontFailOp=null===e?1:Fc[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[wc.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,wc.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[wc.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,wc.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,r,s,n,o){this._stencilEnabled=e,this._stencilFrontCompare=(t??519)-512,this._stencilFrontDepthFailOp=null===i?1:Fc[i],this._stencilFrontPassOp=null===r?2:Fc[r],this._stencilFrontFailOp=null===s?1:Fc[s],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:default:return"triangle-list";case 2:case 3:return"point-list";case 1:case 4:return"line-list";case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return"line-strip";case 7:return"triangle-strip";case 8:throw"TriangleFan is an unsupported fillmode in WebGPU"}}static _GetAphaBlendOperation(e){switch(e){case 32774:default:return"add";case 32778:return"subtract";case 32779:return"reverse-subtract";case 32775:return"min";case 32776:return"max"}}static _GetAphaBlendFactor(e){switch(e){case 0:return"zero";case 1:default:return"one";case 768:return"src";case 769:return"one-minus-src";case 770:return"src-alpha";case 771:return"one-minus-src-alpha";case 772:return"dst-alpha";case 773:return"one-minus-dst-alpha";case 774:return"dst";case 775:return"one-minus-dst";case 776:return"src-alpha-saturated";case 32769:case 32771:return"constant";case 32770:case 32772:return"one-minus-constant";case 35065:return"src1";case 35066:return"one-minus-src1";case 34185:return"src1-alpha";case 35067:return"one-minus-src1-alpha"}}static _GetCompareFunction(e){switch(e){case 0:return"never";case 1:return"less";case 2:return"equal";case 3:return"less-equal";case 4:return"greater";case 5:return"not-equal";case 6:return"greater-equal";case 7:return"always"}return"never"}static _GetStencilOpFunction(e){switch(e){case 0:return"zero";case 1:return"keep";case 2:return"replace";case 3:return"increment-clamp";case 4:return"decrement-clamp";case 5:return"invert";case 6:return"increment-wrap";case 7:return"decrement-wrap"}return"keep"}static _GetVertexInputDescriptorFormat(e){const t=e.type,i=e.normalized,r=e.getSize();switch(t){case st.R.BYTE:switch(r){case 1:case 2:return i?"snorm8x2":"sint8x2";case 3:case 4:return i?"snorm8x4":"sint8x4"}break;case st.R.UNSIGNED_BYTE:switch(r){case 1:case 2:return i?"unorm8x2":"uint8x2";case 3:case 4:return i?"unorm8x4":"uint8x4"}break;case st.R.SHORT:switch(r){case 1:case 2:return i?"snorm16x2":"sint16x2";case 3:case 4:return i?"snorm16x4":"sint16x4"}break;case st.R.UNSIGNED_SHORT:switch(r){case 1:case 2:return i?"unorm16x2":"uint16x2";case 3:case 4:return i?"unorm16x4":"uint16x4"}break;case st.R.INT:switch(r){case 1:return"sint32";case 2:return"sint32x2";case 3:return"sint32x3";case 4:return"sint32x4"}break;case st.R.UNSIGNED_INT:switch(r){case 1:return"uint32";case 2:return"uint32x2";case 3:return"uint32x3";case 4:return"uint32x4"}break;case st.R.FLOAT:switch(r){case 1:return"float32";case 2:return"float32x2";case 3:return"float32x3";case 4:return"float32x4"}}throw new Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${r}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:Lc._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:Lc._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:Lc._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:Lc._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:Lc._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:Lc._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[wc.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,wc.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace-1+((this._cullEnabled?this._cullFace:0)<<1)+((this._clampDepth?1:0)<<3)+((this._alphaToCoverageEnabled?1:0)<<4)+(e<<5)+(t<<8);this._rasterizationState!==i&&(this._rasterizationState=i,this._states[wc.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,wc.RasterizationState))}_setColorStates(){let e=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(e+=(0|(null===this._alphaBlendFuncParams[0]?2:Nc[this._alphaBlendFuncParams[0]]))+((null===this._alphaBlendFuncParams[1]?2:Nc[this._alphaBlendFuncParams[1]])<<4)+((null===this._alphaBlendFuncParams[2]?2:Nc[this._alphaBlendFuncParams[2]])<<8)+((null===this._alphaBlendFuncParams[3]?2:Nc[this._alphaBlendFuncParams[3]])<<12)+((null===this._alphaBlendEqParams[0]?1:this._alphaBlendEqParams[0]-32773)<<16)+((null===this._alphaBlendEqParams[1]?1:this._alphaBlendEqParams[1]-32773)<<19)),e!==this._colorStates&&(this._colorStates=e,this._states[wc.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,wc.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[wc.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,wc.DepthStencilState))}_setVertexState(e){const t=this._statesLength;let i=wc.VertexState;const r=e._pipelineContext,s=r.shaderProcessingContext.attributeNamesFromEffect,n=r.shaderProcessingContext.attributeLocationsFromEffect;let o,a=0;for(let e=0;e0)for(let e=0;e=this._video.HAVE_CURRENT_DATA}dispose(){}}class Hc{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatOrDepthTextures(){return this._numFloatOrDepthTextures>0}constructor(){this.uniqueId=Hc._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatOrDepthTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],r=-1;i?r=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?Dc.GetSamplerHashCode(t):0;const s=r!==i.hashCode;s&&this.updateId++,this.isDirty||(this.isDirty=s)}setTexture(e,t){let i=this.textures[e],r=-1;i?r=i.texture?.uniqueId??-1:this.textures[e]=i={texture:t,isFloatOrDepthTexture:!1,isExternalTexture:!1},i.isExternalTexture&&this._numExternalTextures--,i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures--,t?(i.isFloatOrDepthTexture=1===t.type||t.format>=13&&t.format<=18,i.isExternalTexture=Wc.IsExternalTexture(t),i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,i.isExternalTexture&&this._numExternalTextures++):(i.isFloatOrDepthTexture=!1,i.isExternalTexture=!1),i.texture=t;const s=r!==(t?.uniqueId??-1);s&&this.updateId++,this.isDirty||(this.isDirty=s)}}Hc._Counter=0;class Xc{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,Eh.CopyDst|Eh.Indirect|Eh.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=Xc._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){this._isDirty||(this._isDirty=t?.uniqueId!==this.buffers[e]?.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}}Xc._Counter=0;const qc=2**35;class Yc{constructor(){this.values={}}}class Kc{static get Statistics(){return{totalCreated:Kc.NumBindGroupsCreatedTotal,lastFrameCreated:Kc.NumBindGroupsCreatedLastFrame,lookupLastFrame:Kc.NumBindGroupsLookupLastFrame,noLookupLastFrame:Kc.NumBindGroupsNoLookupLastFrame}}static ResetCache(){Kc._Cache=new Yc,Kc.NumBindGroupsCreatedTotal=0,Kc.NumBindGroupsCreatedLastFrame=0,Kc.NumBindGroupsLookupLastFrame=0,Kc.NumBindGroupsNoLookupLastFrame=0,Kc._NumBindGroupsCreatedCurrentFrame=0,Kc._NumBindGroupsLookupCurrentFrame=0,Kc._NumBindGroupsNoLookupCurrentFrame=0}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){Kc.NumBindGroupsCreatedLastFrame=Kc._NumBindGroupsCreatedCurrentFrame,Kc.NumBindGroupsLookupLastFrame=Kc._NumBindGroupsLookupCurrentFrame,Kc.NumBindGroupsNoLookupLastFrame=Kc._NumBindGroupsNoLookupCurrentFrame,Kc._NumBindGroupsCreatedCurrentFrame=0,Kc._NumBindGroupsLookupCurrentFrame=0,Kc._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){let r,s=Kc._Cache;const n=this.disabled||i.forceBindGroupCreation;if(!n){if(!t.isDirty(i.updateId)&&!i.isDirty)return Kc._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const i of e.shaderProcessingContext.bufferNames){const e=(t.buffers[i]?.uniqueId??0)+1048576;let r=s.values[e];r||(r=new Yc,s.values[e]=r),s=r}for(const t of e.shaderProcessingContext.samplerNames){const e=i.samplers[t]?.hashCode??0;let r=s.values[e];r||(r=new Yc,s.values[e]=r),s=r}for(const t of e.shaderProcessingContext.textureNames){const e=(i.textures[t]?.texture?.uniqueId??0)+qc;let r=s.values[e];r||(r=new Yc,s.values[e]=r),s=r}r=s.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,r)return t.bindGroups=r,Kc._NumBindGroupsLookupCurrentFrame++,r;r=[],t.bindGroups=r,n||(s.bindGroups=r),Kc.NumBindGroupsCreatedTotal++,Kc._NumBindGroupsCreatedCurrentFrame++;const o=e.bindGroupLayouts[i.textureState];for(let s=0;s"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[r].resource=this._cacheSampler.getSampler(t,!1,e.hashCode,t.label)}else Z.V.Error(`Sampler "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.texture||n.storageTexture){const e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){Z.V.Error(`Trying to bind a null texture! entry=${JSON.stringify(n)}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!t||n.texture&&!t.view||n.storageTexture&&!t.viewForWriting)){Z.V.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, isReady=${e.texture?.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[r].resource=n.storageTexture?t.viewForWriting:t.view}else Z.V.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.externalTexture){const e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){Z.V.Error(`Trying to bind a null external texture! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!t){Z.V.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, isReady=${e.texture?.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[r].resource=this._device.importExternalTexture({source:t})}else Z.V.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.buffer){const e=t.buffers[l];if(e){const t=e.underlyingResource;a[r].resource.buffer=t,a[r].resource.size=e.capacity}else Z.V.Error(`Can't find buffer "${l}". entry=${JSON.stringify(n)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}const l=o[s];r[s]=this._device.createBindGroup({layout:l,entries:a})}return r}}Kc.NumBindGroupsCreatedTotal=0,Kc.NumBindGroupsCreatedLastFrame=0,Kc.NumBindGroupsLookupLastFrame=0,Kc.NumBindGroupsNoLookupLastFrame=0,Kc._Cache=new Yc,Kc._NumBindGroupsCreatedCurrentFrame=0,Kc._NumBindGroupsLookupCurrentFrame=0,Kc._NumBindGroupsNoLookupCurrentFrame=0;Cs.l.ShadersStoreWGSL.clearQuadVertexShader="uniform depthValue: f32;const pos=array(\nvec2f(-1.0,1.0),\nvec2f(1.0,1.0),\nvec2f(-1.0,-1.0),\nvec2f(1.0,-1.0)\n);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.position=vec4f(pos[input.vertexIndex],uniforms.depthValue,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";Cs.l.ShadersStoreWGSL.clearQuadPixelShader="uniform color: vec4f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=uniforms.color;}\n";class jc{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 Vc(this._device,i),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"],void 0,void 0,void 0,void 0,void 0,void 0,1)}clear(e,t,i,r,s=1){let n,o,a=null;const l=!!this._engine._currentRenderTarget;if(e)n=e;else{let e=0;this._keyTemp.length=0;for(let t=0;t1?2**36:0)+h*2**37,o=this._keyTemp.join("_"),a=this._bundleCache[o],a)return a;n=this._device.createRenderBundleEncoder({label:"clearQuadRenderBundle",colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:xh.GetSample(s)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!r&&!!this._depthTextureFormat&&xh.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(r?255:0),this._cacheRenderPipeline.setStencilCompare(r?519:512),this._cacheRenderPipeline.setStencilPassOp(r?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);const h=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,s),c=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),c.uniformBuffer.update();const u=l?this._engine._ubInvertY:this._engine._ubDontInvertY,d=c.uniformBuffer.getBuffer(),f=d.uniqueId+"-"+u.uniqueId;let p=this._bindGroups[f];if(!p){const e=c.bindGroupLayouts[0];p=this._bindGroups[f]=[],p.push(this._device.createBindGroup({label:`clearQuadBindGroup0-${f}`,layout:e[0],entries:[]})),fc._SimplifiedKnownBindings||p.push(this._device.createBindGroup({label:`clearQuadBindGroup1-${f}`,layout:e[1],entries:[]})),p.push(this._device.createBindGroup({label:`clearQuadBindGroup${fc._SimplifiedKnownBindings?1:2}-${f}`,layout:e[fc._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:u.underlyingResource,size:u.capacity}},{binding:1,resource:{buffer:d.underlyingResource,size:d.capacity}}]}))}n.setPipeline(h);for(let e=0;e{const e=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,e}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==r)return null;throw e}))}async readValue(e=0){const t=this._getBuffer(e,1);if(null===t)return null;const i=this._engine.uniqueId;return t.mapAsync(1).then((()=>{const e=new BigUint64Array(t.getMappedRange()),i=Number(e[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,i}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw e}))}async readTwoValuesAndSubtract(e=0){const t=this._getBuffer(e,2);if(null===t)return null;const i=this._engine.uniqueId;return t.mapAsync(1).then((()=>{const e=new BigUint64Array(t.getMappedRange()),i=Number(e[1]-e[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,i}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw e}))}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e{null!==e&&e>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(e,!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((e=>{t._addDuration(i,null!==e&&e>0?e:0)}))}dispose(){this._measureDuration?.dispose()}}class ou{constructor(e,t,i,r=2,s){this._count=r,this._querySet=new su(e,r,"timestamp",t,i,!0,s)}start(e){e.writeTimestamp?.(this._querySet.querySet,0)}async stop(e){return e.writeTimestamp?.(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 au{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=void 0!==this._engine._getCurrentRenderPassWrapper().renderPassDescriptor.occlusionQuerySet;return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,i,r=50,s=100){this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=s,this._allocateNewIndices(r)}createQuery(){0===this._availableIndices.length&&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(){this._querySet?.dispose(),this._availableIndices.length=0}}class lu{async initTwgsl(e){if(!lu._Twgsl)return e=e||{},(e={...lu._TWgslDefaultOptions,...e}).twgsl?(lu._Twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await Ue.S0.LoadBabylonScriptAsync(e.jsPath),self.twgsl?(lu._Twgsl=await self.twgsl(Ue.S0.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=lu._Twgsl.convertSpirV2WGSL(e,lu.DisableUniformityAnalysis||t);return lu.ShowWGSLShaderCode&&(Z.V.Log(i),Z.V.Log("***********************************************")),lu.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}}lu._TWgslDefaultOptions={jsPath:`${Ue.S0._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${Ue.S0._DefaultCdnUrl}/twgsl/twgsl.wasm`},lu.ShowWGSLShaderCode=!1,lu.DisableUniformityAnalysis=!1,lu._Twgsl=null;class hu{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),1===this._mode&&this._engine._reportDrawCall(t.numDrawCalls),!0}endFrame(){this._record&&(this._record=!1,this._play=!0,this._mode=this._modeSaved),this._playBundleListIndex=0}reset(){this._record&&(this._mode=this._modeSaved),this.enabled=!1,this.enabled=!0}}var cu=i(73010);class uu extends Wc{constructor(e){super(e)}}function du(e,t,i,r){let s,n=1;1===r?s=new Float32Array(t*i*4):2===r?(s=new Uint16Array(t*i*4),n=15360):s=7===r?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let r=0;r{const i=d.width,n=o(e);if(n){if(a){const e=4===r,t=a(n),o=d._hardwareTexture,l=[0,1,2,3,4,5];for(let r=0;r>r,a=[];for(let i=0;i<6;i++){let o=t[r][l[i]];e&&(o=du(o,n,n,s)),a.push(new Uint8Array(o.buffer,o.byteOffset,o.byteLength))}this._textureHelper.updateCubeTextures(a,o.underlyingResource,n,n,o.format,u,!1,0,0)}}else this.updateRawCubeTexture(d,n,r,s,u);d.isReady=!0,t?.removePendingData(d),l&&l()}};return this._loadFile(e,(e=>{f(e)}),void 0,t?.offlineProvider,!0,((e,i)=>{t?.removePendingData(d),h&&e&&h(e.status+" "+e.statusText,i)})),d},Sh.prototype.createRawTexture3D=function(e,t,i,r,s,n,o,a,l=null,h=0,c=0){const u=new Fs.h(this,10);return u.baseWidth=t,u.baseHeight=i,u.baseDepth=r,u.width=t,u.height=i,u.depth=r,u.format=s,u.type=h,u.generateMipMaps=n,u.samplingMode=a,u.is3D=!0,u._creationFlags=c,this._doNotHandleContextLost||(u._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(u,t,i,void 0,c),this.updateRawTexture3D(u,e,s,o,l,h),this._internalTexturesCache.push(u),u},Sh.prototype.updateRawTexture3D=function(e,t,i,r,s=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s),t){const s=e._hardwareTexture;4===i&&(t=du(t,e.width,e.height,n));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},Sh.prototype.createRawTexture2DArray=function(e,t,i,r,s,n,o,a,l=null,h=0,c=0){const u=new Fs.h(this,11);return u.baseWidth=t,u.baseHeight=i,u.baseDepth=r,u.width=t,u.height=i,u.depth=r,u.format=s,u.type=h,u.generateMipMaps=n,u.samplingMode=a,u.is2DArray=!0,u._creationFlags=c,this._doNotHandleContextLost||(u._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(u,t,i,r,c),this.updateRawTexture2DArray(u,e,s,o,l,h),this._internalTexturesCache.push(u),u},Sh.prototype.updateRawTexture2DArray=function(e,t,i,r,s=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s),t){const s=e._hardwareTexture;4===i&&(t=du(t,e.width,e.height,n));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},Sh.prototype._readTexturePixels=function(e,t,i,r=-1,s=0,n=null,o=!0,a=!1,l=0,h=0){const c=e._hardwareTexture;return o&&this.flushFramebuffer(),this._textureHelper.readPixels(c.underlyingResource,l,h,t,i,c.format,r,s,n,a)},Sh.prototype._readTexturePixelsSync=function(){throw"_readTexturePixelsSync is unsupported in WebGPU!"},Sh.prototype._createDepthStencilCubeTexture=function(e,t){const i=new Fs.h(this,t.generateStencil?12:14);i.isCube=!0,i.label=t.label;const r={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14,...t};i.format=r.depthTextureFormat,this._setupDepthStencilTexture(i,e,r.bilinearFiltering,r.comparisonFunction,r.samples),this._textureHelper.createGPUTextureForInternalTexture(i);const s=i._hardwareTexture;return i.type=xh.GetTextureTypeFromFormat(s.format),this._internalTexturesCache.push(i),i},Sh.prototype.createCubeTexture=function(e,t,i,r,s=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d,f=!1,p=null){return this.createCubeTextureBase(e,t,i,!!r,s,n,o,a,l,h,c,u,null,((e,t)=>{const i=t,n=i[0].width,a=n;this._setCubeMapTextureParams(e,!r),e.format=o??-1;const l=this._textureHelper.createGPUTextureForInternalTexture(e,n,a);this._textureHelper.updateCubeTextures(i,l.underlyingResource,n,a,l.format,!1,!1,0,0),r||this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),s&&s()}),!!f,p)},Sh.prototype._setCubeMapTextureParams=function(e,t,i){e.samplingMode=t?3:2,e._cachedWrapU=0,e._cachedWrapV=0,i&&(e._maxLodLevel=i)},Sh.prototype.generateMipMapsForCubemap=function(e){if(e.generateMipMaps){const t=e._hardwareTexture?.underlyingResource;t||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e)}};class fu extends qs{constructor(e,t,i,r,s){super(e,t,i,r,s),r.enableGPUTimingMeasurements&&(this.gpuTimeInFrame=new bh.e)}}Sh.prototype._createHardwareRenderTargetWrapper=function(e,t,i){const r=new fu(e,t,i,this);return this._renderTargetWrapperCache.push(r),r},Sh.prototype.createRenderTargetTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e),r={};void 0!==t&&"object"==typeof t?(r.generateMipMaps=t.generateMipMaps,r.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,r.generateStencilBuffer=r.generateDepthBuffer&&t.generateStencilBuffer,r.samplingMode=void 0===t.samplingMode?3:t.samplingMode,r.creationFlags=t.creationFlags??0,r.noColorAttachment=!!t.noColorAttachment,r.colorAttachment=t.colorAttachment,r.samples=t.samples,r.label=t.label,r.format=t.format,r.type=t.type):(r.generateMipMaps=t,r.generateDepthBuffer=!0,r.generateStencilBuffer=!1,r.samplingMode=3,r.creationFlags=0,r.noColorAttachment=!1);const s=r.colorAttachment||(r.noColorAttachment?null:this._createInternalTexture(e,r,!0,5));return i.label=r.label??"RenderTargetWrapper",i._samples=r.colorAttachment?.samples??r.samples??1,i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=!!r.generateStencilBuffer,i.setTextures(s),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,!1,i._generateStencilBuffer,i.samples,r.generateStencilBuffer?13:14,r.label?r.label+"-DepthStencil":void 0),s&&!r.colorAttachment&&(void 0!==t&&"object"==typeof t&&t.createMipMaps&&!r.generateMipMaps&&(s.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(s,void 0,void 0,void 0,r.creationFlags),void 0!==t&&"object"==typeof t&&t.createMipMaps&&!r.generateMipMaps&&(s.generateMipMaps=!1)),i},Sh.prototype._createDepthStencilTexture=function(e,t,i){const r={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14,...t},s=17===r.depthTextureFormat||13===r.depthTextureFormat||18===r.depthTextureFormat;i._depthStencilTextureWithStencil=s;const n=new Fs.h(this,s?12:14);n.label=t.label,n.format=r.depthTextureFormat,this._setupDepthStencilTexture(n,e,r.bilinearFiltering,r.comparisonFunction,r.samples),this._textureHelper.createGPUTextureForInternalTexture(n);const o=n._hardwareTexture;return n.type=xh.GetTextureTypeFromFormat(o.format),this._internalTexturesCache.push(n),n},Sh.prototype._setupDepthStencilTexture=function(e,t,i,r,s=1){const n=t.width??t,o=t.height??t,a=t.layers||0,l=t.depth||0;e.baseWidth=n,e.baseHeight=o,e.width=n,e.height=o,e.is2DArray=a>0,e.is3D=l>0,e.depth=a||l,e.isReady=!0,e.samples=s,e.generateMipMaps=!1,e.samplingMode=i?2:1,e.type=1,e._comparisonFunction=r,e._cachedWrapU=0,e._cachedWrapV=0},Sh.prototype.updateRenderTargetTextureSampleCount=function(e,t){return e&&e.texture&&e.samples!==t?(t=Math.min(t,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(e.texture,t),e._depthStencilTexture&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),e._samples=t,e.texture.samples=t,t):t},Sh.prototype.setDepthStencilTexture=function(e,t,i,r){i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,r):this._setTexture(e,null,void 0,void 0,r)},Sh.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),r={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1,...t};r.generateStencilBuffer=r.generateDepthBuffer&&r.generateStencilBuffer,i.label=r.label??"RenderTargetWrapper",i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=r.generateStencilBuffer;const s=new Fs.h(this,5);return s.width=e,s.height=e,s.depth=0,s.isReady=!0,s.isCube=!0,s.samples=r.samples,s.generateMipMaps=r.generateMipMaps,s.samplingMode=r.samplingMode,s.type=r.type,s.format=r.format,this._internalTexturesCache.push(s),i.setTextures(s),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,void 0===r.samplingMode||2===r.samplingMode||2===r.samplingMode||3===r.samplingMode||3===r.samplingMode||5===r.samplingMode||6===r.samplingMode||7===r.samplingMode||11===r.samplingMode,i._generateStencilBuffer,i.samples),t&&t.createMipMaps&&!r.generateMipMaps&&(s.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(s),t&&t.createMipMaps&&!r.generateMipMaps&&(s.generateMipMaps=!1),i},Sh.prototype.getGPUFrameTimeCounter=function(){return this._timestampQuery.gpuFrameTimeCounter},Sh.prototype.captureGPUFrameTime=function(e){this._timestampQuery.enable=e&&!!this._caps.timerQuery},Sh.prototype.createQuery=function(){return this._occlusionQuery.createQuery()},Sh.prototype.deleteQuery=function(e){return this._occlusionQuery.deleteQuery(e),this},Sh.prototype.isQueryResultAvailable=function(e){return this._occlusionQuery.isQueryResultAvailable(e)},Sh.prototype.getQueryResult=function(e){return this._occlusionQuery.getQueryResult(e)},Sh.prototype.beginOcclusionQuery=function(e,t){return this.compatibilityMode?!!this._occlusionQuery.canBeginQuery(t)&&(this._currentRenderPass?.beginOcclusionQuery(t),!0):(this._bundleList.addItem(new eu(t)),!0)},Sh.prototype.endOcclusionQuery=function(){return this.compatibilityMode?this._currentRenderPass?.endOcclusionQuery():this._bundleList.addItem(new tu),this};const pu={label:"TextureView_SwapChain_ResolveTarget",dimension:"2d",format:void 0,mipLevelCount:1,arrayLayerCount:1},_u={label:"TextureView_SwapChain",dimension:"2d",format:void 0,mipLevelCount:1,arrayLayerCount:1},mu=new hc.ov;class gu extends Sh{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}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return!!this._cacheRenderPipeline&&this._cacheRenderPipeline.disabled}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return!!this._cacheBindGroups&&this._cacheBindGroups.disabled}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}areAllEffectsReady(){return!0}getFontOffset(e){return Zs(e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then((e=>!!e),(()=>!1)).catch((()=>!1)):Promise.resolve(!1)}static get IsSupported(){return Z.V.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 currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const i=new gu(e,t);return new Promise((e=>{i.initAsync(t.glslangOptions,t.twgslOptions).then((()=>e(i)))}))}constructor(e,t={}){super(t.antialias??!0,t),this.uniqueId=-1,this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._clearDepthValue=1,this._clearReverseDepthValue=0,this._clearStencilValue=0,this._defaultSampleCount=4,this._glslang=null,this._tintWASM=null,this._glslangAndTintAreFullyLoaded=!1,this._adapterInfo={vendor:"",architecture:"",device:"",description:""},this._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._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._debugStackRenderPass=[],this._currentOverrideVertexBuffers=null,this._currentIndexBuffer=null,this._colorWriteLocal=!0,this._forceEnableEffect=!1,this.isNDCHalfZRange=!0,this.hasOriginBottomLeft=!1,this._workingGlslangAndTintPromise=null,this._viewportsCurrent={x:0,y:0,w:0,h:0},this._scissorsCurrent={x:0,y:0,w:0,h:0},this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=-1,this._blendColorsCurrent=[null,null,null,null],this._performanceMonitor=new Bs,this._name="WebGPU",this._drawCalls=new on.A,t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=t.enableGPUDebugMarkers??!1,Z.V.Log(`Babylon.js v${Ot.$.Version} - ${this.description} engine`),navigator.gpu?(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 pc,this._shaderProcessorWGSL=new gc):Z.V.Error("WebGPU is not supported by your browser.")}prepareGlslangAndTintAsync(){return this._workingGlslangAndTintPromise||(this._workingGlslangAndTintPromise=new Promise((e=>{this._initGlslang(this._glslangOptions??this._options?.glslangOptions).then((t=>{this._glslang=t,this._tintWASM=new lu,this._tintWASM.initTwgsl(this._twgslOptions??this._options?.twgslOptions).then((()=>{this._glslangAndTintAreFullyLoaded=!0,e()}))}))}))),this._workingGlslangAndTintPromise}initAsync(e,t){return this.uniqueId=gu._InstanceId++,this._glslangOptions=e,this._twgslOptions=t,navigator.gpu.requestAdapter(this._options).then((e=>{if(e){this._adapter=e,this._adapterSupportedExtensions=[],this._adapter.features?.forEach((e=>this._adapterSupportedExtensions.push(e))),this._adapterSupportedLimits=this._adapter.limits,this._adapterInfo=this._adapter.info;const t=this._options.deviceDescriptor??{},i=t?.requiredFeatures??(this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0);if(i){const e=i,r=[];for(const t of e)-1!==this._adapterSupportedExtensions.indexOf(t)&&r.push(t);t.requiredFeatures=r}if(this._options.setMaximumLimits&&!t.requiredLimits){t.requiredLimits={};for(const e in this._adapterSupportedLimits)"minSubgroupSize"!==e&&"maxSubgroupSize"!==e&&(t.requiredLimits[e]=this._adapterSupportedLimits[e])}return t.label=`BabylonWebGPUDevice${this.uniqueId}`,this._adapter.requestDevice(t)}throw"Could not retrieve a WebGPU adapter (adapter is null)."})).then((e=>{this._device=e,this._deviceEnabledExtensions=[],this._device.features?.forEach((e=>this._deviceEnabledExtensions.push(e))),this._deviceLimits=e.limits;let t=-1;this._device.addEventListener("uncapturederror",(e=>{++t{this._isDisposed||(this._contextWasLost=!0,Z.V.Warn("WebGPU context lost. "+e),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost((async()=>{const e=this.snapshotRenderingMode,t=this.snapshotRendering,i=this.disableCacheSamplers,r=this.disableCacheRenderPipelines,s=this.disableCacheBindGroups,n=this.enableGPUTimingMeasurements;await this.initAsync(this._glslangOptions??this._options?.glslangOptions,this._twgslOptions??this._options?.twgslOptions),this.snapshotRenderingMode=e,this.snapshotRendering=t,this.disableCacheSamplers=i,this.disableCacheRenderPipelines=r,this.disableCacheBindGroups=s,this.enableGPUTimingMeasurements=n,this._currentRenderPass=null})))}))})).then((()=>{this._initializeLimits(),this._bufferManager=new Rc(this,this._device),this._textureHelper=new Ec(this,this._device,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new Dc(this._device),this._cacheBindGroups=new Kc(this._device,this._cacheSampler,this),this._timestampQuery=new nu(this,this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new au(this,this._device,this._bufferManager):void 0,this._bundleList=new ru(this._device),this._snapshotRendering=new hu(this,this._snapshotRenderingMode,this._bundleList),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),Eh.Uniform|Eh.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),Eh.Uniform|Eh.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&void 0===this._count&&(this._count=0,Z.V.Log(["%c frame #"+this._count+" - begin","background: #ffff00"])),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._emptyVertexBuffer=new st.R(this,[0],"",{stride:1,offset:0,size:1,label:"EmptyVertexBuffer"}),this._cacheRenderPipeline=new Vc(this._device,this._emptyVertexBuffer),this._depthCullingState=new zc(this._cacheRenderPipeline),this._stencilStateComposer=new Uc(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 jc(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((e=>{throw Z.V.Error("A fatal error occurred during WebGPU creation/initialization."),e}))}_initGlslang(e){return e=e||{},(e={...gu._GlslangDefaultOptions,...e}).glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?Ue.S0.LoadBabylonScriptAsync(e.jsPath).then((()=>self.glslang(Ue.S0.GetBabylonScriptURL(e.wasmPath)))):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:2*this._deviceLimits.maxSampledTexturesPerShaderStage,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxDrawBuffers:8,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf("texture-compression-astc")>=0||void 0,s3tc:this._deviceEnabledExtensions.indexOf("texture-compression-bc")>=0||void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf("texture-compression-etc2")>=0||void 0,bptc:this._deviceEnabledExtensions.indexOf("texture-compression-bc")>=0||void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:this._deviceEnabledExtensions.indexOf("rg11b10ufloat-renderable")>=0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf("float32-filterable")>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:"undefined"!=typeof BigUint64Array&&-1!==this._deviceEnabledExtensions.indexOf("timestamp-query")||void 0,supportOcclusionQuery:"undefined"!=typeof BigUint64Array,canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportIBLShadows:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!0,_collectUbosUpdatedInFrame:!1}}_initializeContextAndSwapChain(){if(!this._renderingCanvas)throw"The rendering canvas has not been set!";this._context=this._renderingCanvas.getContext("webgpu"),this._configureContext(),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new vc],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)]);let t;if(this._bufferManager.setSubData(this._ubInvertY,4,e),this._bufferManager.setSubData(this._ubDontInvertY,4,e),this._options.antialias){const e={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:"2d",format:this._options.swapChainFormat,usage:16};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(e),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:"2d",format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new hc.ov(0,0,0,1),loadOp:"clear",storeOp:"store"}]}else t=[{view:void 0,clearValue:new hc.ov(0,0,0,1),loadOp:"clear",storeOp:"store"}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?"depth24plus-stencil8":"depth32float",this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper);const i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:"2d",format:this._mainRenderPassWrapper.depthTextureFormat,usage:16};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);const r={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:"2d",format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:"clear",depthStoreOp:"store",stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?"clear":void 0,stencilStoreOp:this.isStencilEnable?"store":void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:t,depthStencilAttachment:r}}_sharedInit(e){super._sharedInit(e),$s(this,e,this._creationOptions)}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:17,alphaMode:this.premultipliedAlpha?"premultiplied":"opaque"})}resizeImageBitmap(e,t,i){return en(this,e,t,i)}_createImageBitmapFromSource(e,t){return Js(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&tn(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&rn()}enterPointerlock(){this._renderingCanvas&&sn(this._renderingCanvas)}exitPointerlock(){nn()}_rebuildBuffers(){super._rebuildBuffers();for(const e of this._storageBuffers)e.getBuffer().engineId!==this.uniqueId&&e._rebuild()}_restoreEngineAfterContextLost(e){Vc.ResetCache(),Kc.ResetCache();const t=e=>{for(const t of e){for(const e of t.meshes){const t=e.subMeshes;if(t)for(const e of t)e._drawWrappers=[]}for(const e of t.materials)e._materialContext?.reset()}};t(this.scenes),t(this._virtualScenes);const i=[];for(const e of this._uniformBuffers)e.name.indexOf("leftOver")<0&&i.push(e);this._uniformBuffers=i,super._restoreEngineAfterContextLost(e)}setSize(e,t,i=!1){return!!super.setSize(e,t,i)&&(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count=0,s=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,n=0===i?this._compileRawShaderToSpirV(e,"vertex"):e,o=0===i?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(n,o,i,r,s)}_compilePipelineStageDescriptor(e,t,i,r){this.onBeforeShaderCompilationObservable.notifyObservers(this);const s=e.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,n=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,o="#version 450\n",a=0===r?this._compileShaderToSpirV(e,"vertex",i,o):this._getWGSLShader(e,"vertex",i),l=0===r?this._compileShaderToSpirV(t,"fragment",i,o):this._getWGSLShader(t,"fragment",i),h=this._createPipelineStageDescriptor(a,l,r,s,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){const t=new $l(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new uc(e,this)}createMaterialContext(){return new Hc}createDrawContext(){return new Xc(this._bufferManager)}async _preparePipelineContext(e,t,i,r,s,n,o,a,l,h,c){const u=e,d=u.shaderProcessingContext.shaderLanguage;0!==d||this._glslangAndTintAreFullyLoaded||await this.prepareGlslangAndTintAsync(),this.dbgShowShaderCode&&(Z.V.Log(["defines",a]),Z.V.Log(t),Z.V.Log(i),Z.V.Log("***********************************************")),u.sources={fragment:i,vertex:t,rawVertex:s,rawFragment:n},u.stages=r?this._compileRawPipelineStageDescriptor(t,i,d):this._compilePipelineStageDescriptor(t,i,a,d),c()}getAttributes(e,t){const i=new Array(t.length),r=e;for(let e=0;e0,n.is3D=l>0,n._cachedWrapU=0,n._cachedWrapV=0,n._useSRGBBuffer=s.useSRGBBuffer,n.label=s.label,this._internalTexturesCache.push(n),i||this._textureHelper.createGPUTextureForInternalTexture(n,o,a,h||1,s.creationFlags),n}createTexture(e,t,i,r,s=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,f,p){return this._createTextureBase(e,t,i,r,s,n,o,((e,t,i,r,s,n,o,a)=>{const l=r;if(e.baseWidth=l.width,e.baseHeight=l.height,e.width=l.width,e.height=l.height,e.format=-1!==e.format?e.format:h??5,e.type=-1!==e.type?e.type:0,e._creationFlags=f??0,a(e.width,e.height,l,t,e,(()=>{})),e._hardwareTexture?.underlyingResource)n||o||this._generateMipmaps(e,this._uploadEncoder);else{const t=this._textureHelper.createGPUTextureForInternalTexture(e,l.width,l.height,void 0,f);xh.IsImageBitmap(l)&&(this._textureHelper.updateTexture(l,e,l.width,l.height,e.depth,t.format,0,0,s,!1,0,0),n||o||this._generateMipmaps(e,this._uploadEncoder))}i&&i.removePendingData(e),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}),(()=>!1),a,l,h,c,u,d,p)}wrapWebGPUTexture(e){const t=new vc(e),i=new Fs.h(this,0,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers}_unpackFlipY(e){}updateTextureSamplingMode(e,t,i=!1){i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,i=null,r=null){null!==t&&(e._cachedWrapU=t),null!==i&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==r&&(e._cachedWrapR=r)}updateTextureDimensions(e,t,i,r=1){if(!e._hardwareTexture)return;if(e.width===t&&e.height===i&&e.depth===r)return;const s=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,r,s)}_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 e=i+"Sampler";this._currentMaterialContext.setSampler(e,t)}}}createPrefilteredCubeTexture(e,t,i,r,s=null,n=null,o,a=null,l=!0){return this.createCubeTexture(e,t,null,!1,(e=>{if(!e)return void(s&&s(null));const t=e.texture;l?e.info.sphericalPolynomial&&(t._sphericalPolynomial=e.info.sphericalPolynomial):t._sphericalPolynomial=new Ks.Q,t._source=9,s&&s(t)}),n,o,a,l,i,r)}setTexture(e,t,i,r){this._setTexture(e,i,!1,!1,r,r)}setTextureArray(e,t,i,r){for(let e=0;e{const o=()=>{e.mapAsync(1,0,t).then((()=>{const r=e.getMappedRange(0,t);let n=i;if(void 0===n)n=new Uint8Array(t),n.set(new Uint8Array(r));else{const e=n.constructor;n=new e(n.buffer),n.set(new e(r))}e.unmap(),this._bufferManager.releaseBuffer(e),s(n)}),(e=>{this.isDisposed?s(new Uint8Array):n(e)}))};r?(this.flushFramebuffer(),o()):this.onEndFrameObservable.addOnce((()=>{o()}))}))}readFromStorageBuffer(e,t,i,r,s){i=i||e.capacity;const n=this._bufferManager.createRawBuffer(i,Eh.MapRead|Eh.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderEncoder.copyBufferToBuffer(e.underlyingResource,t??0,n,0,i),this._readFromGPUBuffer(n,i,r,s)}readFromMultipleStorageBuffers(e,t,i,r,s){i=i||e[0].capacity;const n=this._bufferManager.createRawBuffer(i*e.length,Eh.MapRead|Eh.CopyDst,void 0,"TempReadFromMultipleStorageBuffers");for(let r=0;r0;for(const t in e){const s=e[t],n=i[t],o=n.group,a=n.binding,l=s.type,h=s.object;let c=s.indexInGroupEntries,u=this._bindGroupEntries[o];switch(u||(u=this._bindGroupEntries[o]=[]),l){case 5:{const e=h;void 0!==c&&r?u[c].resource=this._cacheSampler.getSampler(e):(s.indexInGroupEntries=u.length,u.push({binding:a,resource:this._cacheSampler.getSampler(e)}));break}case 0:case 4:{const e=h,t=e._texture._hardwareTexture;void 0!==c&&r?(0===l&&(u[c++].resource=this._cacheSampler.getSampler(e._texture)),u[c].resource=t.view):(s.indexInGroupEntries=u.length,0===l&&u.push({binding:a-1,resource:this._cacheSampler.getSampler(e._texture)}),u.push({binding:a,resource:t.view}));break}case 1:{const e=h,t=e._texture._hardwareTexture;8&t.textureAdditionalUsages||Z.V.Error(`computeDispatch: The texture (name=${e.name}, uniqueId=${e.uniqueId}) is not a storage texture!`,50),void 0!==c&&r?u[c].resource=t.viewForWriting:(s.indexInGroupEntries=u.length,u.push({binding:a,resource:t.viewForWriting}));break}case 6:{const e=h.underlyingResource;void 0!==c&&r?u[c].resource=this._device.importExternalTexture({source:e}):(s.indexInGroupEntries=u.length,u.push({binding:a,resource:this._device.importExternalTexture({source:e})}));break}case 2:case 3:case 7:{const e=7===l?h:h.getBuffer(),t=e.underlyingResource;void 0!==c&&r?(u[c].resource.buffer=t,u[c].resource.size=e.capacity):(s.indexInGroupEntries=u.length,u.push({binding:a,resource:{buffer:t,offset:0,size:e.capacity}}));break}}}for(let e=0;e0&&d.dispatchWorkgroups(r,s,n),d.end(),h&&(this._timestampQuery.endPass(this._timestampIndex,h),this._timestampIndex+=2)},gu.prototype.releaseComputeEffects=function(){for(const e in this._compiledComputeEffects){const t=this._compiledComputeEffects[e].getPipelineContext();this._deleteComputePipelineContext(t)}this._compiledComputeEffects={}},gu.prototype._prepareComputePipelineContext=function(e,t,i,r,s){const n=e;this.dbgShowShaderCode&&(Z.V.Log(r),Z.V.Log(t)),n.sources={compute:t,rawCompute:i},n.stage=this._createComputePipelineStageDescriptor(t,r,s)},gu.prototype._releaseComputeEffect=function(e){this._compiledComputeEffects[e._key]&&(delete this._compiledComputeEffects[e._key],this._deleteComputePipelineContext(e.getPipelineContext()))},gu.prototype._rebuildComputeEffects=function(){for(const e in this._compiledComputeEffects){const t=this._compiledComputeEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}},gu.prototype._executeWhenComputeStateIsCompiled=function(e,t){e.stage.module.getCompilationInfo().then((e=>{const i={numErrors:0,messages:[]};for(const t of e.messages)"error"===t.type&&i.numErrors++,i.messages.push({type:t.type,text:t.message,line:t.lineNum,column:t.linePos,length:t.length,offset:t.offset});t(i)}))},gu.prototype._deleteComputePipelineContext=function(e){e&&e.dispose()},gu.prototype._createComputePipelineStageDescriptor=function(e,t,i){return t=t?"//"+t.split("\n").join("\n//")+"\n":"",{module:this._device.createShaderModule({code:t+e}),entryPoint:i}},gu.prototype._debugPushGroup=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?(1===t&&(this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._endCurrentRenderPass()),this._renderEncoder.pushDebugGroup(e)):this._currentRenderPass?(this._currentRenderPass.pushDebugGroup(e),this._debugStackRenderPass.push(e)):this._pendingDebugCommands.push(["push",e,t]))},gu.prototype._debugPopGroup=function(e){this._options.enableGPUDebugMarkers&&(0===e||1===e?(1===e&&(this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._endCurrentRenderPass()),this._renderEncoder.popDebugGroup()):this._currentRenderPass?(this._currentRenderPass.popDebugGroup(),this._debugStackRenderPass.pop()):this._pendingDebugCommands.push(["pop",null,e]))},gu.prototype._debugInsertMarker=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?(1===t&&(this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._endCurrentRenderPass()),this._renderEncoder.insertDebugMarker(e)):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(e):this._pendingDebugCommands.push(["insert",e,t]))},gu.prototype._debugFlushPendingCommands=function(){if(0!==this._debugStackRenderPass.length){const e=this._debugStackRenderPass.slice();this._debugStackRenderPass.length=0;for(let t=0;t{this._textureHelper.updateTexture(t,e,e.width,e.height,e.depth,r.format,0,0,!i,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e),e.isReady=!0})).catch((()=>{e.isReady=!0}))};var Su=i(42167),Tu=i(16964);class Cu{static async CreateAsync(e,t){return await gu.IsSupportedAsync?gu.CreateAsync(e,t):an.IsSupported?new an(e,void 0,t):new wl(t)}}class yu{}yu.COPY=1,yu.CUT=2,yu.PASTE=3;class Eu{constructor(e,t){this.type=e,this.event=t}static GetTypeFromCharacter(e){switch(e){case 67:return yu.COPY;case 86:return yu.PASTE;case 88:return yu.CUT;default:return-1}}}var Pu,Au=i(71627);!function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(Pu||(Pu={}));class Ru{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=(0,Au.z)(),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=new(Ue.S0.Instantiate(e.className))(e.name,e._connectionType,t);return i.deserialize(e),i}}class Iu{constructor(e){this.value=this._toInt(e)}_toInt(e){return 0|e}add(e){return new Iu(this.value+e.value)}subtract(e){return new Iu(this.value-e.value)}multiply(e){return new Iu(Math.imul(this.value,e.value))}divide(e){return new Iu(this.value/e.value)}getClassName(){return Iu.ClassName}equals(e){return this.value===e.value}static Parse(e){return new Iu(e.value)}}Iu.ClassName="FlowGraphInteger",(0,X.Y5)("FlowGraphInteger",Iu);class Mu{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new Mu(e.typeName,e.defaultValue)}}const Ou=new Mu("any",void 0),Du=new Mu("string",""),wu=new Mu("number",0),Nu=new Mu("boolean",!1),Fu=new Mu("Vector2",W.I9.Zero()),Lu=new Mu("Vector3",W.Pq.Zero()),Bu=new Mu("Vector4",W.IU.Zero()),Vu=new Mu("Matrix",W.uq.Identity()),ku=new Mu("Color3",H.v9.Black()),Uu=new Mu("Color4",new H.ov(0,0,0,0)),Gu=new Mu("Quaternion",W.PT.Identity()),zu=new Mu("FlowGraphInteger",new Iu(0));function Wu(e){switch(typeof e){case"string":return Du;case"number":return wu;case"boolean":return Nu;case"object":return e instanceof W.I9?Fu:e instanceof W.Pq?Lu:e instanceof W.IU?Bu:e instanceof H.v9?ku:e instanceof H.ov?Uu:e instanceof W.PT?Gu:e instanceof Iu?zu:Ou;default:return Ou}}class Hu extends Ru{constructor(e,t,i,r){super(e,t,i),this.richType=r}_isSingularConnection(){return 0===this.connectionType}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 1===this.connectionType?(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=Ru.Parse(e,t);return i.richType=Mu.Parse(e.richType),i}}function Xu(e){return"Mesh"===e||"AbstractMesh"===e||"GroundMesh"===e||"InstanceMesh"===e||"LinesMesh"===e||"GoldbergMesh"===e||"GreasedLineMesh"===e||"TrailMesh"===e}function qu(e){return"Vector2"===e||"Vector3"===e||"Vector4"===e||"Quaternion"===e||"Color3"===e||"Color4"===e}function Yu(e,t,i){const r=t?.getClassName?.()??"";Xu(r)?i[e]={name:t.name,className:r}:qu(r)?i[e]={value:t.asArray(),className:r}:i[e]=t}function Ku(e,t,i){const r=t[e];let s;const n=r?.className;return s=Xu(n)?i.getMeshByName(r.name):qu(n)?function(e,t){if("Vector2"===e)return W.I9.FromArray(t);if("Vector3"===e)return W.Pq.FromArray(t);if("Vector4"===e)return W.IU.FromArray(t);if("Quaternion"===e)return W.PT.FromArray(t);if("Color3"===e)return new H.v9(t[0],t[1],t[2]);if("Color4"===e)return new H.ov(t[0],t[1],t[2],t[3]);throw new Error(`Unknown vector class name ${e}`)}(n,r.value):"Matrix"===n?W.uq.FromArray(r.value):n===Iu.ClassName?Iu.Parse(r):r&&void 0!==r.value?r.value:r,s}(0,X.Y5)("FGDataConnection",Hu);class ju{constructor(e){this.config=e,this.uniqueId=(0,Au.z)(),this.name=this.config?.name??this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){const i=new Hu(e,0,this,t);return this.dataInputs.push(i),i}registerDataOutput(e,t){const i=new Hu(e,1,this,t);return this.dataOutputs.push(i),i}getDataInput(e){return this.dataInputs.find((t=>t.name===e))}getDataOutput(e){return this.dataOutputs.find((t=>t.name===e))}serialize(e={},t=Yu){e.uniqueId=this.uniqueId,e.config={},this.config&&(e.config.name=this.config.name),e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName();for(const t of this.dataInputs){const i={};t.serialize(i),e.dataInputs.push(i)}for(const t of this.dataOutputs){const i={};t.serialize(i),e.dataOutputs.push(i)}}getClassName(){return"FGBlock"}static Parse(e,t){const i=Ue.S0.Instantiate(e.className),r={},s=t.valueParseFunction??Ku;if(e.config)for(const i in e.config)r[i]=s(i,e.config,t.scene);var n;("FGSetPropertyBlock"===(n=e.className)||"FGGetPropertyBlock"===n||"FGPlayAnimationBlock"===n||"FGMeshPickEventBlock"===n)&&(r.pathConverter=t.pathConverter);const o=new i(r);o.uniqueId=e.uniqueId;for(let t=0;tt.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{t.type===yi.Zp.POINTERPICK&&t.pickInfo?.pickedMesh&&(t.pickInfo?.pickedMesh===i||td(t.pickInfo?.pickedMesh,i))&&this._execute(e)}));const r=i.onDisposeObservable.add((()=>this._onDispose));e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",r)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"mesh"),i=e._getExecutionVariable(this,"meshPickObserver"),r=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(r),e._deleteExecutionVariable(this,"mesh"),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return id.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path}}var rd;id.ClassName="FGMeshPickEventBlock",(0,X.Y5)(id.ClassName,id),function(e){e[e.Stopped=0]="Stopped",e[e.Started=1]="Started"}(rd||(rd={}));class sd{constructor(e){this._eventBlocks=[],this._executionContexts=[],this.state=0,this._scene=e.scene,this._coordinator=e.coordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add((()=>this.dispose()))}createContext(){const e=new ed({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(1!==this.state){this.state=1,0===this._executionContexts.length&&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()===id.ClassName){const i=t._getReferencedMesh();let r=0;for(;r0;){const r=t.pop();e(r);for(const e of r.dataInputs)for(const r of e._connectedPoint)i.has(r._ownerBlock.uniqueId)||(t.push(r._ownerBlock),i.add(r._ownerBlock.uniqueId));if(r instanceof Qu)for(const e of r.signalOutputs)for(const r of e._connectedPoint)i.has(r._ownerBlock.uniqueId)||(t.push(r._ownerBlock),i.add(r._ownerBlock.uniqueId))}}serialize(e={},t){e.allBlocks=[],this.visitAllBlocks((t=>{const i={};t.serialize(i),e.allBlocks.push(i)})),e.executionContexts=[];for(const i of this._executionContexts){const r={};i.serialize(r,t),e.executionContexts.push(r)}}static GetDataOutConnectionByUniqueId(e,t){for(const i of e)for(const e of i.dataOutputs)if(e.uniqueId===t)return e;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 Qu)for(const e of i.signalInputs)if(e.uniqueId===t)return e;throw new Error("Could not find signal in connection with unique id "+t)}static Parse(e,t){const i=t.coordinator.createGraph(),r=[],s=t.valueParseFunction??Ku;for(const n of e.allBlocks){const e=ju.Parse(n,{scene:t.coordinator.config.scene,pathConverter:t.pathConverter,valueParseFunction:s});r.push(e),e instanceof Ju&&i.addEventBlock(e)}for(const e of r){for(const t of e.dataInputs)for(const e of t.connectedPointIds){const i=sd.GetDataOutConnectionByUniqueId(r,e);t.connectTo(i)}if(e instanceof Qu)for(const t of e.signalOutputs)for(const e of t.connectedPointIds){const i=sd.GetSignalInConnectionByUniqueId(r,e);t.connectTo(i)}}for(const t of e.executionContexts)ed.Parse(t,{graph:i,valueParseFunction:s});return i}}class nd{constructor(e){this.config=e,this._flowGraphs=[],this._customEventsMap=new Map,this.config.scene.onDisposeObservable.add((()=>{this.dispose()})),(nd.SceneCoordinators.get(this.config.scene)??[]).push(this)}createGraph(){const e=new sd({scene:this.config.scene,coordinator:this});return this._flowGraphs.push(e),e}removeGraph(e){const t=this._flowGraphs.indexOf(e);-1!==t&&(e.dispose(),this._flowGraphs.splice(t,1))}start(){this._flowGraphs.forEach((e=>e.start()))}dispose(){this._flowGraphs.forEach((e=>e.dispose())),this._flowGraphs.length=0;const e=nd.SceneCoordinators.get(this.config.scene)??[],t=e.indexOf(this);-1!==t&&e.splice(t,1)}serialize(e,t){e._flowGraphs=[],this._flowGraphs.forEach((i=>{const r={};i.serialize(r,t),e._flowGraphs.push(r)}))}static Parse(e,t){const i=t.valueParseFunction??Ku,r=new nd({scene:t.scene});return e._flowGraphs?.forEach((e=>{sd.Parse(e,{coordinator:r,valueParseFunction:i,pathConverter:t.pathConverter})})),r}get flowGraphs(){return this._flowGraphs}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new z.cP,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){const i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}}nd.SceneCoordinators=new Map;class od{constructor(e){this._context=e,this._context.onNodeExecutedObservable.add((e=>{Ue.S0.Log(`Node executed: ${e.getClassName()}`)}))}}class ad extends Qu{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class ld extends ad{constructor(e){super(e),this.message=this.registerDataInput("message",Ou)}_execute(e){const t=this.message.getValue(e);Z.V.Log(t),this.out._activateSignal(e)}getClassName(){return ld.ClassName}}ld.ClassName="FGConsoleLogBlock",(0,X.Y5)(ld.ClassName,ld);class hd extends ad{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,Ou)}_execute(e){const t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)}getClassName(){return hd.ClassName}}hd.ClassName="FGSetVariableBlock",(0,X.Y5)(hd.ClassName,hd);const cd=new RegExp(/\{(\w+)\}/g);class ud{constructor(e,t){this.path=e,this.ownerBlock=t,this.templatedInputs=[];let i=cd.exec(e);for(;i;){const[,r]=i;this.templatedInputs.push(t.registerDataInput(r,zu)),i=cd.exec(e)}}getAccessor(e,t){let i=this.path;for(const e of this.templatedInputs){const r=e.getValue(t).value;i=i.replace(`{${e.name}}`,r.toString())}return e.convert(i)}}class dd extends ad{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",Ou),this.templateComponent=new ud(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 dd.ClassName}}dd.ClassName="FGSetPropertyBlock",(0,X.Y5)("FGSetPropertyBlock",dd);class fd extends ad{constructor(e){super(e),this.config=e;for(let e=0;et.getValue(e)));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)}getClassName(){return fd.ClassName}}fd.ClassName="FGSendCustomEventBlock",(0,X.Y5)("FGSendCustomEventBlock",fd);class pd extends Qu{constructor(e){super(e),this.condition=this.registerDataInput("condition",Nu),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"}}(0,X.Y5)("FGBranchBlock",pd);class _d extends ad{constructor(e={startIndex:new Iu(0)}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",zu),this.value=this.registerDataOutput("value",zu)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{const t=this.value.getValue(e);t.valuer)this.timeRemaining.setValue(0,e),this.out._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",s);else{const t=r-(s-i);this.timeRemaining.setValue(t,e)}}getClassName(){return"FGThrottleBlock"}}var vd;function xd(e){let t=0;const i=Date.now();e.observableParameters=e.observableParameters??{};const r=e.contextObservable.add((s=>{const n=Date.now();t=n-i;const o={startTime:i,currentTime:n,deltaTime:t,completeRate:t/e.timeout,payload:s};e.onTick&&e.onTick(o),e.breakCondition&&e.breakCondition()&&(e.contextObservable.remove(r),e.onAborted&&e.onAborted(o)),t>=e.timeout&&(e.contextObservable.remove(r),e.onEnded&&e.onEnded(o))}),e.observableParameters.mask,e.observableParameters.insertFirst,e.observableParameters.scope);return r}(0,X.Y5)("FGThrottleBlock",gd),function(e){e[e.INIT=0]="INIT",e[e.STARTED=1]="STARTED",e[e.ENDED=2]="ENDED"}(vd||(vd={}));class bd{constructor(e){this.onEachCountObservable=new z.cP,this.onTimerAbortedObservable=new z.cP,this.onTimerEndedObservable=new z.cP,this.onStateChangedObservable=new z.cP,this._observer=null,this._breakOnNextTick=!1,this._tick=e=>{const t=Date.now();this._timer=t-this._startTime;const i={startTime:this._startTime,currentTime:t,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:e},r=this._breakOnNextTick||this._breakCondition(i);r||this._timer>=this._timeToEnd?this._stop(i,r):this.onEachCountObservable.notifyObservers(i)},this._setState(0),this._contextObservable=e.contextObservable,this._observableParameters=e.observableParameters??{},this._breakCondition=e.breakCondition??(()=>!1),this._timeToEnd=e.timeout,e.onEnded&&this.onTimerEndedObservable.add(e.onEnded),e.onTick&&this.onEachCountObservable.add(e.onTick),e.onAborted&&this.onTimerAbortedObservable.add(e.onAborted)}set breakCondition(e){this._breakCondition=e}clearObservables(){this.onEachCountObservable.clear(),this.onTimerAbortedObservable.clear(),this.onTimerEndedObservable.clear(),this.onStateChangedObservable.clear()}start(e=this._timeToEnd){if(1===this._state)throw new Error("Timer already started. Please stop it before starting again");this._timeToEnd=e,this._startTime=Date.now(),this._timer=0,this._observer=this._contextObservable.add(this._tick,this._observableParameters.mask,this._observableParameters.insertFirst,this._observableParameters.scope),this._setState(1)}stop(){1===this._state&&(this._breakOnNextTick=!0)}dispose(){this._observer&&this._contextObservable.remove(this._observer),this.clearObservables()}_setState(e){this._state=e,this.onStateChangedObservable.notifyObservers(this._state)}_stop(e,t=!1){this._contextObservable.remove(this._observer),this._setState(2),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}}class Sd extends Zu{constructor(e){super(e),this.timeout=this.registerDataInput("timeout",wu)}_preparePendingTasks(e){const t=this.timeout.getValue(e);if(void 0!==t&&t>=0){const i=e._getExecutionVariable(this,"runningTimers")||[],r=e.configuration.scene,s=new bd({timeout:t,contextObservable:r.onBeforeRenderObservable,onEnded:()=>this._onEnded(s,e)});s.start(),i.push(s),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onEnded(e,t){const i=t._getExecutionVariable(this,"runningTimers")||[],r=i.indexOf(e);-1!==r?i.splice(r,1):Ue.S0.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 e of t)e.dispose();e._deleteExecutionVariable(this,"runningTimers")}getClassName(){return Sd.ClassName}}Sd.ClassName="FGTimerBlock",(0,X.Y5)("FGTimerBlock",Sd);class Td extends Qu{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this.registerDataOutput("currentIndex",wu),this.config.startIndex=void 0!==this.config.startIndex?this.config.startIndex:0,this.config.startIndex=Math.max(0,Math.min(this.config.startIndex,this.config.numberOutputFlows-1)),this.outFlows=[];for(let e=0;e=this.config.numberOutputFlows&&this.config.loop)s=0;else if(s>=this.config.numberOutputFlows&&!this.config.loop)return;if(r=r.filter((e=>e!==s)),0===r.length)for(let e=0;e=0&&(i[e+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every((e=>e))){this.out._activateSignal(e);for(let e=0;e=i&&(this.out._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}}(0,X.Y5)("FGDebounceBlock",Ad);class Rd extends Qu{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this.registerDataOutput("isOn",Nu)}_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"}}(0,X.Y5)("FGFlipFlopBlock",Rd);class Id extends Qu{constructor(e){super(e),this.config=e,this.outFlows=[];for(let e=0;ethis._onAnimationEnd(t,e)));this.runningAnimatable.setValue(t,e),n.push(t)}e._setExecutionVariable(this,"runningAnimatables",n)}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onAnimationEnd(e,t){const i=t._getExecutionVariable(this,"runningAnimatables")??[],r=i.indexOf(e);-1!==r&&i.splice(r,1),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningAnimatables")??[];for(const e of t)e.stop();e._deleteExecutionVariable(this,"runningAnimatables")}getClassName(){return Md.ClassName}serialize(e={}){super.serialize(e),e.config.targetPath=this.config.targetPath,e.config.animationPath=this.config.animationPath}}Md.ClassName="FGPlayAnimationBlock",(0,X.Y5)(Md.ClassName,Md);class Od extends ad{constructor(e){super(e),this.animationToStop=this.registerDataInput("animationToStop",Ou)}_execute(e){this.animationToStop.getValue(e).stop(),this.out._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}}(0,X.Y5)("FGStopAnimationBlock",Od);class Dd extends ad{constructor(e){super(e),this.animationToPause=this.registerDataInput("animationToPause",Ou)}_execute(e){this.animationToPause.getValue(e).pause(),this.out._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}}(0,X.Y5)("FGPauseAnimationBlock",Dd);class wd extends ju{constructor(e){super(e),this.condition=this.registerDataInput("condition",Nu),this.trueValue=this.registerDataInput("trueValue",Ou),this.falseValue=this.registerDataInput("falseValue",Ou),this.output=this.registerDataOutput("output",Ou)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}}(0,X.Y5)("FGConditionalDataBlock",wd);class Nd extends ju{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,Ou)}_updateOutputs(e){const t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return Nd.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}Nd.ClassName="FGGetVariableBlock",(0,X.Y5)(Nd.ClassName,Nd);class Fd extends ju{constructor(e){super(e),this.sourceSystem=this.registerDataInput("sourceSystem",Ou),this.destinationSystem=this.registerDataInput("destinationSystem",Ou),this.inputCoordinates=this.registerDataInput("inputCoordinates",Lu),this.outputCoordinates=this.registerDataOutput("outputCoordinates",Lu)}_updateOutputs(e){const t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),r=this.inputCoordinates.getValue(e),s=t.getWorldMatrix(),n=i.getWorldMatrix(),o=W.AA.Matrix[0].copyFrom(n);o.invert();const a=W.AA.Matrix[1];o.multiplyToRef(s,a);const l=this.outputCoordinates.getValue(e);W.Pq.TransformCoordinatesToRef(r,a,l)}getClassName(){return"FGCoordinateTransformBlock"}}(0,X.Y5)("FGCoordinateTransformBlock",Fd);class Ld extends ju{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput("output",Wu(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}serialize(e={},t=Yu){super.serialize(e),t("value",this.config.value,e.config)}}(0,X.Y5)("FGConstantBlock",Ld);class Bd extends ju{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",Ou),this.templateComponent=new ud(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 Bd.ClassName}serialize(e={}){super.serialize(e),e.config.path=this.config.path}}Bd.ClassName="FGGetPropertyBlock",(0,X.Y5)(Bd.ClassName,Bd);const Vd="cachedOperationValue",kd="cachedExecutionId";class Ud extends ju{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){const t=e._getExecutionVariable(this,kd),i=e._getExecutionVariable(this,Vd);if(void 0!==i&&t===e.executionId)this.value.setValue(i,e);else{const t=this._doOperation(e);e._setExecutionVariable(this,Vd,t),e._setExecutionVariable(this,kd,e.executionId),this.value.setValue(t,e)}}}class Gd extends Ud{constructor(e,t,i,r,s,n){super(i,n),this._operation=r,this._className=s,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e))}getClassName(){return this._className}}class zd extends Ud{constructor(e,t,i,r,s){super(t,s),this._operation=i,this._className=r,this.a=this.registerDataInput("a",e)}_doOperation(e){return this._operation(this.a.getValue(e))}getClassName(){return this._className}}const Wd="FGLogic",Hd="AndBlock",Xd="OrBlock",qd="NotBlock";class Yd extends Gd{constructor(e){super(Nu,Nu,Nu,((e,t)=>e&&t),`${Wd}${Hd}`,e)}}(0,X.Y5)(`${Wd}${Hd}`,Yd);class Kd extends Gd{constructor(e){super(Nu,Nu,Nu,((e,t)=>e||t),`${Wd}${Xd}`,e)}}(0,X.Y5)(`${Wd}${Xd}`,Kd);class jd extends zd{constructor(e){super(Nu,Nu,(e=>!e),`${Wd}${qd}`,e)}}(0,X.Y5)(`${Wd}${qd}`,jd);class $d extends Ud{constructor(e,t,i,r){super(e,r),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}}class Qd extends Ud{constructor(e,t,i,r,s,n,o){super(r,o),this._operation=s,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 Zd(e){return e.getClassName?e.getClassName():""}function Jd(e,t){return"Vector2"===e&&"Vector2"===t||"Vector3"===e&&"Vector3"===t||"Vector4"===e&&"Vector4"===t}function ef(e,t){return"Matrix"===e&&"Matrix"===t}function tf(e,t){return"FlowGraphInteger"===e&&"FlowGraphInteger"===t}class rf extends Gd{constructor(e){super(Ou,Ou,Ou,((e,t)=>this._polymorphicAdd(e,t)),rf.ClassName,e)}_polymorphicAdd(e,t){const i=Zd(e),r=Zd(t);return Jd(i,r)||ef(i,r)||tf(i,r)?e.add(t):e+t}}rf.ClassName="FGAddBlock",(0,X.Y5)(rf.ClassName,rf);class sf extends Gd{constructor(e){super(Ou,Ou,Ou,((e,t)=>this._polymorphicAdd(e,t)),sf.ClassName,e)}_polymorphicAdd(e,t){const i=Zd(e),r=Zd(t);return Jd(i,r)||tf(i,r)?e.subtract(t):ef(i,r)?e.add(t.scale(-1)):e-t}}sf.ClassName="FGSubBlock",(0,X.Y5)(sf.ClassName,sf);class nf extends Gd{constructor(e){super(Ou,Ou,Ou,((e,t)=>this._polymorphicMultiply(e,t)),nf.ClassName,e)}_polymorphicMultiply(e,t){const i=Zd(e),r=Zd(t);return Jd(i,r)||tf(i,r)?e.multiply(t):ef(i,r)?W.uq.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}}nf.ClassName="FGMultiplyBlock",(0,X.Y5)(nf.ClassName,nf);class of extends Gd{constructor(e){super(Ou,Ou,Ou,((e,t)=>this._polymorphicDivide(e,t)),of.ClassName,e)}_polymorphicDivide(e,t){const i=Zd(e),r=Zd(t);return Jd(i,r)||tf(i,r)?e.divide(t):ef(i,r)?W.uq.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}}of.ClassName="FGDivideBlock",(0,X.Y5)(of.ClassName,of);class af extends $d{constructor(e){super(wu,(()=>Math.random()),af.ClassName,e)}}af.ClassName="FGRandomBlock",(0,X.Y5)(af.ClassName,af);class lf extends Gd{constructor(e){super(Ou,Ou,wu,((e,t)=>this._polymorphicDot(e,t)),lf.ClassName,e)}_polymorphicDot(e,t){switch(Zd(e)){case"Vector2":return W.I9.Dot(e,t);case"Vector3":return W.Pq.Dot(e,t);case"Vector4":return W.IU.Dot(e,t);default:throw new Error(`Cannot get dot product of ${e} and ${t}`)}}}lf.ClassName="FGDotBlock",(0,X.Y5)(lf.ClassName,lf);class hf extends $d{constructor(e){super(wu,(()=>Math.E),hf.ClassName,e)}}hf.ClassName="FGEBlock",(0,X.Y5)(hf.ClassName,hf);class cf extends $d{constructor(e){super(wu,(()=>Math.PI),cf.ClassName,e)}}cf.ClassName="FGPIBlock",(0,X.Y5)(cf.ClassName,cf);class uf extends $d{constructor(e){super(wu,(()=>Number.POSITIVE_INFINITY),uf.ClassName,e)}}uf.ClassName="FGInfBlock",(0,X.Y5)(uf.ClassName,uf);class df extends $d{constructor(e){super(wu,(()=>Number.NaN),df.ClassName,e)}}function ff(e,t){switch(Zd(e)){case"FlowGraphInteger":return new Iu(t(e.value));case"Vector2":return new W.I9(t(e.x),t(e.y));case"Vector3":return new W.Pq(t(e.x),t(e.y),t(e.z));case"Vector4":return new W.IU(t(e.x),t(e.y),t(e.z),t(e.w));case"Matrix":return W.uq.FromValues(t(e.m[0]),t(e.m[4]),t(e.m[8]),t(e.m[12]),t(e.m[1]),t(e.m[5]),t(e.m[9]),t(e.m[13]),t(e.m[2]),t(e.m[6]),t(e.m[10]),t(e.m[14]),t(e.m[3]),t(e.m[7]),t(e.m[11]),t(e.m[15]));default:return t(e)}}df.ClassName="FGNaNBlock",(0,X.Y5)(df.ClassName,df);class pf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicAbs(e)),pf.ClassName,e)}_polymorphicAbs(e){return ff(e,Math.abs)}}pf.ClassName="FGAbsBlock",(0,X.Y5)(pf.ClassName,pf);class _f extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicSign(e)),_f.ClassName,e)}_polymorphicSign(e){return ff(e,Math.sign)}}_f.ClassName="FGSignBlock",(0,X.Y5)(_f.ClassName,_f);class mf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicTrunc(e)),mf.ClassName,e)}_polymorphicTrunc(e){return ff(e,Math.trunc)}}mf.ClassName="FGTruncBlock",(0,X.Y5)(mf.ClassName,mf);class gf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicFloor(e)),gf.ClassName,e)}_polymorphicFloor(e){return ff(e,Math.floor)}}gf.ClassName="FGFloorBlock",(0,X.Y5)(gf.ClassName,gf);class vf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicCeiling(e)),vf.ClassName,e)}_polymorphicCeiling(e){return ff(e,Math.ceil)}}vf.ClassName="FGCeilBlock",(0,X.Y5)(vf.ClassName,vf);class xf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicFract(e)),xf.ClassName,e)}_polymorphicFract(e){return ff(e,(e=>e-Math.floor(e)))}}xf.ClassName="FGFractBlock",(0,X.Y5)(xf.ClassName,xf);class bf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicNeg(e)),bf.ClassName,e)}_polymorphicNeg(e){return ff(e,(e=>-e))}}function Sf(e,t,i){switch(Zd(e)){case"FlowGraphInteger":return new Iu(i(e.value,t.value));case"Vector2":return new W.I9(i(e.x,t.x),i(e.y,t.y));case"Vector3":return new W.Pq(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z));case"Vector4":return new W.IU(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z),i(e.w,t.w));case"Matrix":return W.uq.FromValues(i(e.m[0],t.m[0]),i(e.m[4],t.m[4]),i(e.m[8],t.m[8]),i(e.m[12],t.m[12]),i(e.m[1],t.m[1]),i(e.m[5],t.m[5]),i(e.m[9],t.m[9]),i(e.m[13],t.m[13]),i(e.m[2],t.m[2]),i(e.m[6],t.m[6]),i(e.m[10],t.m[10]),i(e.m[14],t.m[14]),i(e.m[3],t.m[3]),i(e.m[7],t.m[7]),i(e.m[11],t.m[11]),i(e.m[15],t.m[15]));default:return i(e,t)}}bf.ClassName="FGNegBlock",(0,X.Y5)(bf.ClassName,bf);class Tf extends Gd{constructor(e){super(Ou,Ou,Ou,((e,t)=>this._polymorphicRemainder(e,t)),Tf.ClassName,e)}_polymorphicRemainder(e,t){return Sf(e,t,((e,t)=>e%t))}}Tf.ClassName="FGRemainderBlock",(0,X.Y5)(Tf.ClassName,Tf);class Cf extends Gd{constructor(e){super(Ou,Ou,Ou,((e,t)=>this._polymorphicMin(e,t)),Cf.ClassName,e)}_polymorphicMin(e,t){return Sf(e,t,Math.min)}}Cf.ClassName="FGMinBlock",(0,X.Y5)(Cf.ClassName,Cf);class yf extends Gd{constructor(e){super(Ou,Ou,Ou,((e,t)=>this._polymorphicMax(e,t)),yf.ClassName,e)}_polymorphicMax(e,t){return Sf(e,t,Math.max)}}function Ef(e,t,i){return Math.min(Math.max(e,Math.min(t,i)),Math.max(t,i))}function Pf(e,t,i,r){switch(Zd(e)){case"FlowGraphInteger":return new Iu(r(e.value,t.value,i.value));case"Vector2":return new W.I9(r(e.x,t.x,i.x),r(e.y,t.y,i.y));case"Vector3":return new W.Pq(r(e.x,t.x,i.x),r(e.y,t.y,i.y),r(e.z,t.z,i.z));case"Vector4":return new W.IU(r(e.x,t.x,i.x),r(e.y,t.y,i.y),r(e.z,t.z,i.z),r(e.w,t.w,i.w));case"Matrix":return W.uq.FromValues(r(e.m[0],t.m[0],i.m[0]),r(e.m[4],t.m[4],i.m[4]),r(e.m[8],t.m[8],i.m[8]),r(e.m[12],t.m[12],i.m[12]),r(e.m[1],t.m[1],i.m[1]),r(e.m[5],t.m[5],i.m[5]),r(e.m[9],t.m[9],i.m[9]),r(e.m[13],t.m[13],i.m[13]),r(e.m[2],t.m[2],i.m[2]),r(e.m[6],t.m[6],i.m[6]),r(e.m[10],t.m[10],i.m[10]),r(e.m[14],t.m[14],i.m[14]),r(e.m[3],t.m[3],i.m[3]),r(e.m[7],t.m[7],i.m[7]),r(e.m[11],t.m[11],i.m[11]),r(e.m[15],t.m[15],i.m[15]));default:return r(e,t,i)}}yf.ClassName="FGMaxBlock",(0,X.Y5)(yf.ClassName,yf);class Af extends Qd{constructor(e){super(Ou,Ou,Ou,Ou,((e,t,i)=>this._polymorphicClamp(e,t,i)),Af.ClassName,e)}_polymorphicClamp(e,t,i){return Pf(e,t,i,Ef)}}function Rf(e){return Math.min(Math.max(e,0),1)}Af.ClassName="FGClampBlock",(0,X.Y5)(Af.ClassName,Af);class If extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicSaturate(e)),If.ClassName,e)}_polymorphicSaturate(e){return ff(e,Rf)}}If.ClassName="FGSaturateBlock",(0,X.Y5)(If.ClassName,If);class Mf extends Qd{constructor(e){super(Ou,Ou,Ou,Ou,((e,t,i)=>this._polymorphicInterpolate(e,t,i)),Mf.ClassName,e)}_interpolate(e,t,i){return(1-i)*e+i*t}_polymorphicInterpolate(e,t,i){return Pf(e,t,i,this._interpolate)}}Mf.ClassName="FGInterpolateBlock",(0,X.Y5)(Mf.ClassName,Mf);class Of extends Gd{constructor(e){super(Ou,Ou,Nu,((e,t)=>this._polymorphicEq(e,t)),Of.ClassName,e)}_polymorphicEq(e,t){const i=Zd(e),r=Zd(t);return Jd(i,r)||ef(i,r)||tf(i,r)?e.equals(t):e===t}}function Df(e,t,i){const r=Zd(e);if(r===Zd(t)){if(""===r)return i(e,t);if("FlowGraphInteger"===r)return i(e.value,t.value);throw new Error(`Cannot compare ${e} and ${t}`)}throw new Error(`${e} and ${t} are of different types.`)}Of.ClassName="FGEqBlock",(0,X.Y5)(Of.ClassName,Of);class wf extends Gd{constructor(e){super(Ou,Ou,Nu,((e,t)=>this._polymorphicLessThan(e,t)),wf.ClassName,e)}_polymorphicLessThan(e,t){return Df(e,t,((e,t)=>ethis._polymorphicLessThanOrEqual(e,t)),Nf.ClassName,e)}_polymorphicLessThanOrEqual(e,t){return Df(e,t,((e,t)=>e<=t))}}Nf.ClassName="FGLessThanOrEqualBlock";class Ff extends Gd{constructor(e){super(Ou,Ou,Nu,((e,t)=>this._polymorphicGreaterThan(e,t)),Ff.ClassName,e)}_polymorphicGreaterThan(e,t){return Df(e,t,((e,t)=>e>t))}}Ff.ClassName="FGGreaterThanBlock",(0,X.Y5)(Ff.ClassName,Ff);class Lf extends Gd{constructor(e){super(Ou,Ou,Nu,((e,t)=>this._polymorphicGreaterThanOrEqual(e,t)),Lf.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){return Df(e,t,((e,t)=>e>=t))}}Lf.ClassName="FGGreaterThanOrEqualBlock",(0,X.Y5)(Lf.ClassName,Lf);class Bf extends zd{constructor(e){super(Ou,Nu,(e=>this._polymorphicIsNan(e)),Bf.ClassName,e)}_polymorphicIsNan(e){const t=Zd(e);if(""===t)return isNaN(e);if("FlowGraphInteger"===t)return isNaN(e.value);throw new Error(`Cannot get NaN of ${e}`)}}Bf.ClassName="FGIsNanBlock",(0,X.Y5)(Bf.ClassName,Bf);class Vf extends zd{constructor(e){super(Ou,Nu,(e=>this._polymorphicIsInf(e)),Vf.ClassName,e)}_polymorphicIsInf(e){const t=Zd(e);if(""===t)return!isFinite(e);if("FlowGraphInteger"===t)return!isFinite(e.value);throw new Error(`Cannot get isInf of ${e}`)}}Vf.ClassName="FGIsInfBlock";class kf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicDegToRad(e)),kf.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return ff(e,this._degToRad)}}kf.ClassName="FGDegToRadBlock",(0,X.Y5)(kf.ClassName,kf);class Uf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicRadToDeg(e)),Uf.ClassName,e)}_radToDeg(e){return 180*e/Math.PI}_polymorphicRadToDeg(e){return ff(e,this._radToDeg)}}Uf.ClassName="FGRadToDegBlock",(0,X.Y5)(Uf.ClassName,Uf);class Gf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicSin(e)),Gf.ClassName,e)}_polymorphicSin(e){return ff(e,Math.sin)}}Gf.ClassName="FGSinBlock",(0,X.Y5)(Gf.ClassName,Gf);class zf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicCos(e)),zf.ClassName,e)}_polymorphicCos(e){return ff(e,Math.cos)}}zf.ClassName="FGCosBlock",(0,X.Y5)(zf.ClassName,zf);class Wf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicTan(e)),Wf.ClassName,e)}_polymorphicTan(e){return ff(e,Math.tan)}}Wf.ClassName="FGTanBlock",(0,X.Y5)(Wf.ClassName,Wf);class Hf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicAsin(e)),Hf.ClassName,e)}_polymorphicAsin(e){return ff(e,Math.asin)}}Hf.ClassName="FGAsinBlock",(0,X.Y5)(Hf.ClassName,Hf);class Xf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicAcos(e)),Xf.ClassName,e)}_polymorphicAcos(e){return ff(e,Math.acos)}}Xf.ClassName="FGAcosBlock",(0,X.Y5)(Xf.ClassName,Xf);class qf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicAtan(e)),qf.ClassName,e)}_polymorphicAtan(e){return ff(e,Math.atan)}}qf.ClassName="FGAtanBlock",(0,X.Y5)(qf.ClassName,qf);class Yf extends Gd{constructor(e){super(Ou,Ou,Ou,((e,t)=>this._polymorphicAtan2(e,t)),Yf.ClassName,e)}_polymorphicAtan2(e,t){return Sf(e,t,Math.atan2)}}Yf.ClassName="FGAtan2Block",(0,X.Y5)(Yf.ClassName,Yf);class Kf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicSinh(e)),Kf.ClassName,e)}_polymorphicSinh(e){return ff(e,Math.sinh)}}Kf.ClassName="FGSinhBlock",(0,X.Y5)(Kf.ClassName,Kf);class jf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicCosh(e)),jf.ClassName,e)}_polymorphicCosh(e){return ff(e,Math.cosh)}}jf.ClassName="FGCoshBlock",(0,X.Y5)(jf.ClassName,jf);class $f extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicTanh(e)),$f.ClassName,e)}_polymorphicTanh(e){return ff(e,Math.tanh)}}$f.ClassName="FGTanhBlock",(0,X.Y5)($f.ClassName,$f);class Qf extends zd{constructor(e){super(Ou,wu,(e=>this._polymorphicAsinh(e)),Qf.ClassName,e)}_polymorphicAsinh(e){return ff(e,Math.asinh)}}Qf.ClassName="FGAsinhBlock",(0,X.Y5)(Qf.ClassName,Qf);class Zf extends zd{constructor(e){super(Ou,wu,(e=>this._polymorphicAcosh(e)),Zf.ClassName,e)}_polymorphicAcosh(e){return ff(e,Math.acosh)}}Zf.ClassName="FGAcoshBlock",(0,X.Y5)(Zf.ClassName,Zf);class Jf extends zd{constructor(e){super(Ou,wu,(e=>this._polymorphicAtanh(e)),Jf.ClassName,e)}_polymorphicAtanh(e){return ff(e,Math.atanh)}}Jf.ClassName="FGAtanhBlock",(0,X.Y5)(Jf.ClassName,Jf);class ep extends zd{constructor(e){super(Ou,wu,(e=>this._polymorphicExp(e)),ep.ClassName,e)}_polymorphicExp(e){return ff(e,Math.exp)}}ep.ClassName="FGExpBlock",(0,X.Y5)(ep.ClassName,ep);class tp extends zd{constructor(e){super(Ou,wu,(e=>this._polymorphicLog(e)),tp.ClassName,e)}_polymorphicLog(e){return ff(e,Math.log)}}tp.ClassName="FGLogBlock",(0,X.Y5)(tp.ClassName,tp);class ip extends zd{constructor(e){super(Ou,wu,(e=>this._polymorphicLog2(e)),ip.ClassName,e)}_polymorphicLog2(e){return ff(e,Math.log2)}}ip.ClassName="FGLog2Block",(0,X.Y5)(ip.ClassName,ip);class rp extends zd{constructor(e){super(Ou,wu,(e=>this._polymorphicLog10(e)),rp.ClassName,e)}_polymorphicLog10(e){return ff(e,Math.log10)}}rp.ClassName="FGLog10Block",(0,X.Y5)(rp.ClassName,rp);class sp extends zd{constructor(e){super(Ou,wu,(e=>this._polymorphicSqrt(e)),sp.ClassName,e)}_polymorphicSqrt(e){return ff(e,Math.sqrt)}}sp.ClassName="FGSqrtBlock",(0,X.Y5)(sp.ClassName,sp);class np extends zd{constructor(e){super(Ou,wu,(e=>this._polymorphicCubeRoot(e)),np.ClassName,e)}_polymorphicCubeRoot(e){return ff(e,Math.cbrt)}}np.ClassName="FGCubeRootBlock",(0,X.Y5)(np.ClassName,np);class op extends Gd{constructor(e){super(Ou,wu,wu,((e,t)=>this._polymorphicPow(e,t)),op.ClassName,e)}_polymorphicPow(e,t){return Sf(e,t,Math.pow)}}op.ClassName="FGPowBlock",(0,X.Y5)(op.ClassName,op);class ap extends zd{constructor(e){super(Ou,wu,(e=>this._polymorphicLength(e)),ap.ClassName,e)}_polymorphicLength(e){switch(Zd(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw new Error(`Cannot compute length of value ${e}`)}}}ap.ClassName="FGLengthBlock",(0,X.Y5)(ap.ClassName,ap);class lp extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicNormalize(e)),lp.ClassName,e)}_polymorphicNormalize(e){switch(Zd(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw new Error(`Cannot normalize value ${e}`)}}}lp.ClassName="FGNormalizeBlock",(0,X.Y5)(lp.ClassName,lp);class hp extends Gd{constructor(e){super(Lu,Lu,Lu,((e,t)=>W.Pq.Cross(e,t)),hp.ClassName,e)}}hp.ClassName="FGCrossBlock",(0,X.Y5)(hp.ClassName,hp);class cp extends Gd{constructor(e){super(Fu,wu,Fu,((e,t)=>W.I9.Transform(e,W.uq.RotationZ(t))),cp.ClassName,e)}}cp.ClassName="FGRotate2DBlock",(0,X.Y5)(cp.ClassName,cp);class up extends Qd{constructor(e){super(Lu,Lu,wu,Lu,((e,t,i)=>W.Pq.TransformCoordinates(e,W.uq.RotationAxis(t,i))),up.ClassName,e)}}up.ClassName="FGRotate3DBlock",(0,X.Y5)(up.ClassName,up);class dp extends zd{constructor(e){super(Vu,Vu,(e=>W.uq.Transpose(e)),dp.ClassName,e)}}dp.ClassName="FGTransposeBlock",(0,X.Y5)(dp.ClassName,dp);class fp extends zd{constructor(e){super(Vu,wu,(e=>e.determinant()),fp.ClassName,e)}}fp.ClassName="FGDeterminantBlock",(0,X.Y5)(fp.ClassName,fp);class pp extends zd{constructor(e){super(Vu,Vu,(e=>W.uq.Invert(e)),pp.ClassName,e)}}pp.ClassName="FGInvertMatrixBlock",(0,X.Y5)(pp.ClassName,pp);class _p extends Gd{constructor(e){super(Vu,Vu,Vu,((e,t)=>t.multiply(e)),_p.ClassName,e)}}_p.ClassName="FGMatMulBlock",(0,X.Y5)(_p.ClassName,_p);class mp extends zd{constructor(e){super(zu,zu,(e=>new Iu(~e.value)),mp.ClassName,e)}}mp.ClassName="FGBitwiseNotBlock",(0,X.Y5)(mp.ClassName,mp);class gp extends Gd{constructor(e){super(zu,zu,zu,((e,t)=>new Iu(e.value&t.value)),gp.ClassName,e)}}gp.ClassName="FGBitwiseAndBlock",(0,X.Y5)(gp.ClassName,gp);class vp extends Gd{constructor(e){super(zu,zu,zu,((e,t)=>new Iu(e.value|t.value)),vp.ClassName,e)}}vp.ClassName="FGBitwiseOrBlock",(0,X.Y5)(vp.ClassName,vp);class xp extends Gd{constructor(e){super(zu,zu,zu,((e,t)=>new Iu(e.value^t.value)),xp.ClassName,e)}}xp.ClassName="FGBitwiseXorBlock",(0,X.Y5)(xp.ClassName,xp);class bp extends Gd{constructor(e){super(zu,zu,zu,((e,t)=>new Iu(e.value<new Iu(e.value>>t.value)),Sp.ClassName,e)}}Sp.ClassName="FGBitwiseRightShiftBlock",(0,X.Y5)(Sp.ClassName,Sp);class Tp extends zd{constructor(e){super(zu,zu,(e=>new Iu(Math.clz32(e.value))),Tp.ClassName,e)}}Tp.ClassName="FGCountLeadingZerosBlock",(0,X.Y5)(Tp.ClassName,Tp);class Cp extends zd{constructor(e){super(zu,zu,(e=>new Iu(e.value?31-Math.clz32(e.value&-e.value):32)),Cp.ClassName,e)}}Cp.ClassName="FGCountTrailingZerosBlock",(0,X.Y5)(Cp.ClassName,Cp);class yp extends zd{constructor(e){super(zu,zu,(e=>new Iu(function(e){let t=0;for(;e;)t+=1&e,e>>=1;return t}(e.value))),yp.ClassName,e)}}yp.ClassName="FGCountOneBitsBlock",(0,X.Y5)(yp.ClassName,yp);class Ep extends Ju{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){const t=e.configuration.scene.onReadyObservable.add((()=>{this._execute(e)}));e._setExecutionVariable(this,"sceneReadyObserver",t)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneReadyObserver");e.configuration.scene.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return Ep.ClassName}}Ep.ClassName="FGSceneReadyEventBlock",(0,X.Y5)("FGSceneReadyEventBlock",Ep);class Pp extends Ju{constructor(e){super(e),this.config=e;for(let e=0;e{for(let i=0;i{this._execute(e)}));e._setExecutionVariable(this,"sceneBeforeRender",t)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneBeforeRender");e.configuration.scene.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}getClassName(){return Ap.ClassName}}Ap.ClassName="FGSceneTickEventBlock",(0,X.Y5)(Ap.ClassName,Ap);var Rp,Ip,Mp,Op=i(83839);!function(e){e[e.Texture=1]="Texture",e[e.TextureBackBuffer=2]="TextureBackBuffer",e[e.TextureBackBufferDepthStencilAttachment=4]="TextureBackBufferDepthStencilAttachment",e[e.TextureDepthStencilAttachment=8]="TextureDepthStencilAttachment",e[e.TextureViewDepth=16]="TextureViewDepth",e[e.TextureViewNormal=32]="TextureViewNormal",e[e.TextureAlbedo=64]="TextureAlbedo",e[e.TextureReflectivity=128]="TextureReflectivity",e[e.TextureWorldPosition=256]="TextureWorldPosition",e[e.TextureVelocity=512]="TextureVelocity",e[e.TextureIrradiance=1024]="TextureIrradiance",e[e.TextureAlbedoSqrt=2048]="TextureAlbedoSqrt",e[e.TextureScreenDepth=4096]="TextureScreenDepth",e[e.TextureWorldNormal=8192]="TextureWorldNormal",e[e.TextureLocalPosition=16384]="TextureLocalPosition",e[e.TextureLinearVelocity=32768]="TextureLinearVelocity",e[e.TextureAllButBackBufferDepthStencil=16777211]="TextureAllButBackBufferDepthStencil",e[e.TextureAllButBackBuffer=16777209]="TextureAllButBackBuffer",e[e.TextureAll=16777215]="TextureAll",e[e.Camera=16777216]="Camera",e[e.ObjectList=33554432]="ObjectList",e[e.AutoDetect=268435456]="AutoDetect",e[e.BasedOnInput=536870912]="BasedOnInput",e[e.Undefined=1073741824]="Undefined",e[e.All=4294967295]="All"}(Rp||(Rp={})),function(e){e[e.Compatible=0]="Compatible",e[e.TypeIncompatible=1]="TypeIncompatible",e[e.HierarchyIssue=2]="HierarchyIssue"}(Ip||(Ip={})),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(Mp||(Mp={}));class Dp{get direction(){return this._direction}get type(){if(this._type===Rp.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.type}if(this._type===Rp.BasedOnInput){if(this._typeConnectionSource){const e="function"==typeof this._typeConnectionSource?this._typeConnectionSource():this._typeConnectionSource;return e.isConnected?e._connectedPoint.type:this._defaultConnectionPointType??e.type}if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type}set type(e){this._type=e}get isConnected(){return null!==this.connectedPoint||this.hasEndpoints}get connectedPoint(){return this._connectedPoint}get ownerBlock(){return this._ownerBlock}get sourceBlock(){return this._connectedPoint?this._connectedPoint.ownerBlock:null}get connectedBlocks(){return 0===this._endpoints.length?[]:this._endpoints.map((e=>e.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}constructor(e,t,i){this._connectedPoint=null,this._acceptedConnectionPointType=null,this._endpoints=new Array,this._type=Rp.Undefined,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new z.cP,this.onDisconnectionObservable=new z.cP,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeRenderGraphConnectionPoint"}canConnectTo(e){return 0===this.checkCompatibilityState(e)}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==Rp.AutoDetect)return e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)?0:1;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return 1;let r=i,s=t;return 0===this.direction&&(r=t,s=i),r.isAnAncestorOf(s)?2:0}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this)),this}addExcludedConnectionPointFromAllowedTypes(e){let t=0,i=2**t;for(;i=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear(),this.onDisconnectionObservable.clear()}}class wp{get disabled(){return!!this._frameGraphTask?.disabled}set disabled(e){this._frameGraphTask&&(this._frameGraphTask.disabled=e)}get task(){return this._frameGraphTask}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"NodeRenderGraphBlock"}_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)return!0;if(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 t=i.ownerBlock.getDescendantOfPredicate(e);if(t)return t}return null}constructor(e,t,i,...r){this._name="",this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._isDebug=!1,this._isUnique=!1,this.onBuildObservable=new z.cP,this._inputs=new Array,this._outputs=new Array,this._codeVariableName="",this._additionalConstructionParameters=null,this.visibleOnFrame=!1,this._name=e,this._frameGraph=t,this._scene=i,this._engine=i.getEngine(),this.uniqueId=Op.K.UniqueId}registerInput(e,t,i=!1,r){return(r=r??new Dp(e,this,0)).type=t,r.isOptional=i,this._inputs.push(r),this}registerOutput(e,t,i){return(i=i??new Dp(e,this,1)).type=t,this._outputs.push(i),this}_buildBlock(e){}_customBuildStep(e){}_propagateInputValueToOutput(e,t){e.connectedPoint&&(t.value=e.connectedPoint.value)}build(e){if(this._buildId===e.buildId)return!0;this._buildId=e.buildId;for(const t of this._inputs){if(!t.connectedPoint){t.isOptional||e._notConnectedNonOptionalInputs.push(t);continue}const i=t.connectedPoint.ownerBlock;i&&i!==this&&i.build(e)}return this._customBuildStep(e),e.verbose&&Z.V.Log(`Building ${this.name} [${this.getClassName()}]`),this._buildBlock(e),this._frameGraphTask&&this._frameGraph.addTask(this._frameGraphTask),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((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.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.disabled=this.disabled,this._additionalConstructionParameters&&(e.additionalConstructionParameters=this._additionalConstructionParameters),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.disabled=e.disabled,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach((e=>{const t=this.inputs.find((t=>t.name===e.name));t&&(e.displayName&&(t.displayName=e.displayName),e.isExposedOnFrame&&(t.isExposedOnFrame=e.isExposedOnFrame,t.exposedPortPosition=e.exposedPortPosition))})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}_dumpPropertiesCode(){const e=this._codeVariableName;return`${e}.visibleOnFrame = ${this.visibleOnFrame};\n${e}.disabled = ${this.disabled};\n`}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e),t+=`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\n`}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}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=i+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let r=`\n// ${this.getClassName()}\n`;this.comments&&(r+=`// ${this.comments}\n`);const s=this.getClassName();if("RenderGraphInputBlock"===s){const e=this.type;r+=`var ${this._codeVariableName} = new BABYLON.NodeRenderGraphInputBlock("${this.name}", nodeRenderGraph.frameGraph, scene, BABYLON.NodeRenderGraphBlockConnectionPointTypes.${Rp[e]});\n`}else this._additionalConstructionParameters?r+=`var ${this._codeVariableName} = new BABYLON.${s}("${this.name}", nodeRenderGraph.frameGraph, scene, ...${JSON.stringify(this._additionalConstructionParameters)});\n`:r+=`var ${this._codeVariableName} = new BABYLON.${s}("${this.name}", nodeRenderGraph.frameGraph, scene);\n`;r+=this._dumpPropertiesCode()+"\n";for(const i of this.inputs){if(!i.isConnected)continue;const s=i.connectedPoint.ownerBlock;-1===t.indexOf(s)&&(r+=s._dumpCode(e,t))}for(const i of this.outputs)if(i.hasEndpoints)for(const s of i.endpoints){const i=s.ownerBlock;i&&-1===t.indexOf(i)&&(r+=i._dumpCode(e,t))}return r}clone(){const e=this.serialize(),t=(0,X.n9)(e.customType);if(t){const i=e.additionalConstructionParameters,r=i?new t("",this._frameGraph,this._scene,...i):new t("",this._frameGraph,this._scene);return r._deserialize(e),r}return null}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose();this._frameGraphTask?.dispose(),this._frameGraphTask=void 0,this.onBuildObservable.clear()}}(0,je.Cg)([(0,$e.lK)("comment")],wp.prototype,"comments",void 0);const Np=0,Fp=1;class Lp{constructor(e,t,i){this.name=e,this._parentTask=t,this._context=i}setExecuteFunc(e){this._executeFunc=e}_execute(){this._executeFunc(this._context)}_isValid(){return void 0!==this._executeFunc?null:"Execute function is not set (call setExecuteFunc to set it)"}}class Bp extends Lp{static IsCullPass(e){return void 0!==e.setObjectList}get objectList(){return this._objectList}setObjectList(e){this._objectList=e}constructor(e,t,i,r){super(e,t,i),this._engine=r}_isValid(){return super._isValid()||(void 0!==this._objectList?null:"Object list is not set (call setObjectList to set it)")}}class Vp extends Lp{static IsRenderPass(e){return void 0!==e.setRenderTarget}get renderTarget(){return this._renderTarget}get renderTargetDepth(){return this._renderTargetDepth}constructor(e,t,i,r){super(e,t,i),this._usedTextures=[],this._depthShared=!1,this._engine=r}useTexture(e){this._usedTextures.push(e)}setRenderTarget(e){this._renderTarget=e}setRenderTargetDepth(e){this._renderTargetDepth=e}_execute(){this._renderTargetDepth&&!this._depthShared&&(this._context._shareDepth(this._renderTargetDepth,this._renderTarget),this._depthShared=!0),this._context.bindRenderTarget(this._renderTarget,`frame graph - render pass '${this.name}'`),super._execute(),this._context._flushDebugMessages()}_isValid(){return super._isValid()||(void 0!==this._renderTarget?null:"Render target is not set (call setRenderTarget to set it)")}}class kp{get name(){return this._name}set name(e){this._name=e}get disabled(){return this._disabled}set disabled(e){this._disabled=e}isReady(){return!0}dispose(){this._reset()}constructor(e,t){this._passes=[],this._passesDisabled=[],this._disabled=!1,this.name=e,this._frameGraph=t,this._reset()}_reset(){this._passes.length=0,this._passesDisabled.length=0}_addPass(e,t){t?this._passesDisabled.push(e):this._passes.push(e)}_checkTask(){let e,t=null,i=null;for(const r of this._passes){const s=r._isValid();if(s)throw new Error(`Pass "${r.name}" is not valid. ${s}`);Vp.IsRenderPass(r)?(t=this._frameGraph.getTexture(r.renderTarget),i=void 0!==r.renderTargetDepth?this._frameGraph.getTexture(r.renderTargetDepth):null):Bp.IsCullPass(r)&&(e=r.objectList)}let r,s=null,n=-1,o=null;for(const e of this._passesDisabled){const t=e._isValid();if(t)throw new Error(`Pass "${e.name}" is not valid. ${t}`);Vp.IsRenderPass(e)?(s=this._frameGraph.getTexture(e.renderTarget),n=e.renderTarget,o=void 0!==e.renderTargetDepth?this._frameGraph.getTexture(e.renderTargetDepth):null):Bp.IsCullPass(e)&&(r=e.objectList)}if(this._passesDisabled.length>0){if(t!==s&&!this._frameGraph.isHistoryTexture(n))throw new Error(`The output texture of the task "${this.name}" is different when it is enabled or disabled.`);if(i!==o)throw new Error(`The output depth texture of the task "${this.name}" is different when it is enabled or disabled.`);if(e!==r)throw new Error(`The output object list of the task "${this.name}" is different when it is enabled or disabled.`)}}_getPasses(){return this.disabled&&this._passesDisabled.length>0?this._passesDisabled:this._passes}}class Up extends kp{record(){if(void 0===this.sourceTexture)throw new Error(`FrameGraphCopyToBackbufferColorTask "${this.name}": sourceTexture is required`);const e=this._frameGraph.addRenderPass(this.name);e.setRenderTarget(Np),e.setExecuteFunc((e=>{e.isBackbuffer(this.sourceTexture)||e.copyTexture(this.sourceTexture)}));const t=this._frameGraph.addRenderPass(this.name+"_disabled",!0);t.setRenderTarget(Np),t.setExecuteFunc((e=>{}))}}class Gp extends wp{get task(){return this._frameGraphTask}constructor(e,t,i){super(e,t,i),this._isUnique=!0,this.registerInput("texture",Rp.Texture),this.texture.addAcceptedConnectionPointTypes(Rp.TextureAll),this._frameGraphTask=new Up(e,t)}getClassName(){return"NodeRenderGraphOutputBlock"}get texture(){return this._inputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name;const t=this.texture.connectedPoint;t&&(this._frameGraphTask.sourceTexture=t.value)}}(0,X.Y5)("BABYLON.NodeRenderGraphOutputBlock",Gp);var zp,Wp,Hp,Xp,qp,Yp=i(50606);!function(e){e[e.None=0]="None",e[e.ToLinearSpace=1]="ToLinearSpace",e[e.ToGammaSpace=2]="ToGammaSpace"}(zp||(zp={}));class Kp{get shaderLanguage(){return this._shaderLanguage}_textureIsInternal(e){return void 0===e.getInternalTexture}constructor(e,t=!1){this._shaderLanguage=0,this._shadersLoaded=!1,this._engine=e,this._isDepthTexture=t,this._renderer=new Yp.J(e),this._initShaderSourceAsync(t)}async _initShaderSourceAsync(e){const t=this._engine;t.isWebGPU?(this._shaderLanguage=1,await Promise.resolve().then(i.bind(i,89517))):await Promise.resolve().then(i.bind(i,92224)),this._shadersLoaded=!0,this._effectWrapper=new Yp.$({engine:t,name:"CopyTextureToTexture",fragmentShader:"copyTextureToTexture",useShaderStore:!0,uniformNames:["conversion"],samplerNames:["textureSampler"],defines:e?["#define DEPTH_TEXTURE"]:[],shaderLanguage:this._shaderLanguage}),this._effectWrapper.onApplyObservable.add((()=>{e?(t.setState(!1),t.setDepthBuffer(!0),t.depthCullingState.depthMask=!0,t.depthCullingState.depthFunc=519):t.depthCullingState.depthMask=!1,this._textureIsInternal(this._source)?this._effectWrapper.effect._bindTexture("textureSampler",this._source):this._effectWrapper.effect.setTexture("textureSampler",this._source),this._effectWrapper.effect.setFloat("conversion",this._conversion)}))}isReady(){return this._shadersLoaded&&this._effectWrapper.effect.isReady()}copy(e,t=null,i=0){if(!this.isReady())return!1;this._source=e,this._conversion=i;const r=this._engine.getDepthFunction(),s=this._engine.getDepthWrite();return this._renderer.render(this._effectWrapper,t),this._engine.setDepthWrite(s),this._isDepthTexture&&r&&this._engine.setDepthFunction(r),!0}dispose(){this._effectWrapper?.dispose(),this._renderer.dispose()}}class jp{}class $p extends jp{static _IsObjectRenderer(e){return void 0!==e.initRender}constructor(e,t,i){super(),this._engine=e,this._textureManager=t,this._scene=i,this._debugMessageHasBeenPushed=!1,this._renderTargetIsBound=!0,this._effectRenderer=new Yp.J(this._engine),this._copyTexture=new Kp(this._engine),this._currentRenderTargetHandle=Np}isBackbuffer(e){return this._textureManager.isBackbuffer(e)}isBackbufferColor(e){return this._textureManager.isBackbufferColor(e)}isBackbufferDepthStencil(e){return this._textureManager.isBackbufferDepthStencil(e)}clear(e,t,i,r){this._applyRenderTarget(),this._engine.clear(e,t,i,r)}clearColorAttachments(e,t){this._applyRenderTarget(),this._engine.bindAttachments(t),this._engine.clear(e,!0,!1,!1)}bindAttachments(e){this._applyRenderTarget(),this._engine.bindAttachments(e)}generateMipMaps(){const e=this._textureManager.getTextureFromHandle(this._currentRenderTargetHandle);e&&(this._renderTargetIsBound&&(this._flushDebugMessages(),this._engine.unBindFramebuffer(e),this._renderTargetIsBound=!1),this._engine.generateMipmaps(e.texture))}setTextureSamplingMode(e,t){const i=this._textureManager.getTextureFromHandle(e)?.texture;i&&i.samplingMode!==t&&this._engine.updateTextureSamplingMode(t,i)}bindTextureHandle(e,t,i){const r=this._textureManager.getTextureFromHandle(i);r&&e._bindTexture(t,r.texture)}setDepthStates(e,t){this._engine.setDepthBuffer(e),this._engine.setDepthWrite(t)}applyFullScreenEffect(e,t){if(!e.effect?.isReady())return!1;this._applyRenderTarget();const i=this._engine.getDepthWrite();return this._effectRenderer.saveStates(),this._effectRenderer.setViewport(),this._engine.enableEffect(e),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._effectRenderer.bindBuffers(e.effect),t?.(),this._effectRenderer.draw(),this._effectRenderer.restoreStates(),this._engine.setDepthWrite(i),this._engine.setAlphaMode(0),!0}copyTexture(e,t=!1){t&&this.bindRenderTarget(),this._applyRenderTarget(),this._copyTexture.copy(this._textureManager.getTextureFromHandle(e).texture)}render(e,t,i){$p._IsObjectRenderer(e)?e.shouldRender()&&(this._scene?.incrementRenderId(),this._scene?.resetCachedMaterial(),e.prepareRenderList(),e.initRender(t,i),this._applyRenderTarget(),e.render(),e.finishRender()):(this._applyRenderTarget(),e.render())}bindRenderTarget(e=Np,t){if(e===this._currentRenderTargetHandle)return this._flushDebugMessages(),void(void 0!==t&&(this._engine._debugPushGroup?.(t,2),this._debugMessageWhenTargetBound=void 0,this._debugMessageHasBeenPushed=!0));this._currentRenderTargetHandle=e,this._debugMessageWhenTargetBound=t,this._renderTargetIsBound=!1}_flushDebugMessages(){this._debugMessageHasBeenPushed&&(this._engine._debugPopGroup?.(2),this._debugMessageHasBeenPushed=!1)}_shareDepth(e,t){const i=this._textureManager.getTextureFromHandle(e),r=this._textureManager.getTextureFromHandle(t);i&&r&&i.shareDepth(r)}_applyRenderTarget(){if(this._renderTargetIsBound)return;const e=this._currentRenderTargetHandle,t=this._textureManager._textures.get(e);let i=t.texture;if(t.creationOptions.isHistoryTexture){const r=this._textureManager._historyTextures.get(t.refHandle??e);i=r.textures[r.index]}this._flushDebugMessages(),i?this._engine.bindFramebuffer(i):e===Np||t.refHandle===Np?this._engine.restoreDefaultFramebuffer():e!==Fp&&t.refHandle!==Fp||this._engine.restoreDefaultFramebuffer(),void 0!==this._debugMessageWhenTargetBound&&(this._engine._debugPushGroup?.(this._debugMessageWhenTargetBound,2),this._debugMessageWhenTargetBound=void 0,this._debugMessageHasBeenPushed=!0),this._renderTargetIsBound=!0}_dispose(){this._effectRenderer.dispose(),this._copyTexture.dispose()}}function Qp(e){return void 0!==e.width}function Zp(e){return Qp(e)?{width:e.width,height:e.height}:{width:e,height:e}}!function(e){e[e.Task=0]="Task",e[e.Graph=1]="Graph",e[e.External=2]="External"}(Wp||(Wp={}));class Jp{constructor(e,t=!1,i){this._engine=e,this._debugTextures=t,this._scene=i,this._textures=new Map,this._historyTextures=new Map,this._addSystemTextures()}isBackbuffer(e){if(e===Np||e===Fp)return!0;const t=this._textures.get(e);return!!t&&(t.refHandle===Np||t.refHandle===Fp)}isBackbufferColor(e){if(e===Np)return!0;const t=this._textures.get(e);return!!t&&t.refHandle===Np}isBackbufferDepthStencil(e){if(e===Fp)return!0;const t=this._textures.get(e);return!!t&&t.refHandle===Fp}getTextureCreationOptions(e){return this._textures.get(e).creationOptions}getTextureFromHandle(e){const t=this._historyTextures.get(e);return t?t.textures[1^t.index]:this._textures.get(e).texture}importTexture(e,t,i){const r=t.texture;if(!r)throw new Error("importTexture: Texture must have an internal texture to be imported");void 0!==i&&this._freeEntry(i);const s={size:{width:t.width,height:t.height},options:{generateMipMaps:r.generateMipMaps,generateDepthBuffer:t._generateDepthBuffer,generateStencilBuffer:t._generateStencilBuffer,samples:r.samples,label:r.label,types:[r.type],samplingModes:[r.samplingMode],formats:[r.format],targetTypes:[r.isCube?34067:r.is3D?32879:r.is2DArray?35866:3553],useSRGBBuffers:[r._useSRGBBuffer],labels:r.label?[r.label]:void 0},sizeIsPercentage:!1};return this._createHandleForTexture(e,t,s,Wp.External,!1,i)}createRenderTargetTexture(e,t,i,r=!1,s){return this._createHandleForTexture(e,null,i,t?Wp.Task:Wp.Graph,r,s)}getAbsoluteDimensions(e,t=this._engine.getRenderWidth(!0),i=this._engine.getRenderHeight(!0)){const{width:r,height:s}=Zp(e);return{width:Math.floor(r*t/100),height:Math.floor(s*i/100)}}updateHistoryTextures(){this._historyTextures.forEach((e=>{e.index=1^e.index;for(const t of e.refHandles)this._textures.get(t).texture=e.textures[e.index]}))}dispose(){this.releaseTextures()}allocateTextures(){this._textures.forEach((e=>{if(!e.texture)if(void 0!==e.refHandle){const t=this._textures.get(e.refHandle);e.texture=t.texture,e.texture?.texture?.incrementReferences(),t.refHandle===Np&&(e.refHandle=Np),t.refHandle===Fp&&(e.refHandle=Fp)}else if(e.namespace!==Wp.External)if(void 0!==e.parentHandle){const t=e.creationOptions,i=t.sizeIsPercentage?this.getAbsoluteDimensions(t.size):t.size,r=this._textures.get(e.parentHandle).texture.textures[e.parentTextureIndex],s={createMipMaps:t.options.createMipMaps,generateMipMaps:t.options.generateMipMaps,generateDepthBuffer:t.options.generateDepthBuffer,generateStencilBuffer:t.options.generateStencilBuffer,samples:t.options.samples,type:t.options.types[0],format:t.options.formats[0],useSRGBBuffer:t.options.useSRGBBuffers[0],colorAttachment:r,label:t.options.label};e.texture=this._engine.createRenderTargetTexture(i,s),r.incrementReferences()}else{const t=e.creationOptions,i=t.sizeIsPercentage?this.getAbsoluteDimensions(t.size):t.size;e.texture=this._engine.createMultipleRenderTarget(i,t.options,!1)}e.texture&&void 0===e.refHandle&&(e.debug?.dispose(),e.debug=this._createDebugTexture(e.name,e.texture))})),this._historyTextures.forEach((e=>{for(let t=0;t{(e||t.namespace!==Wp.External)&&(t.debug?.dispose(),t.debug=void 0),t.namespace!==Wp.External&&(t.texture?.dispose(),t.texture=null,(e||t.namespace===Wp.Task)&&this._textures.delete(i))})),this._historyTextures.forEach((e=>{for(let t=0;tt.name===e))}addTask(e){if(null!==this._currentProcessedTask)throw new Error(`FrameGraph.addTask: Can't add the task "${e.name}" while another task is currently building (task: ${this._currentProcessedTask.name}).`);this._tasks.push(e)}addRenderPass(e,t=!1){return this._addPass(e,Hp.Render,t)}addCullPass(e,t=!1){return this._addPass(e,Hp.Cull,t)}_addPass(e,t,i=!1){if(!this._currentProcessedTask)throw new Error("FrameGraph: A pass must be created during a Task.record execution only.");let r;switch(t){case Hp.Render:r=new Vp(e,this._currentProcessedTask,this._renderContext,this._engine);break;case Hp.Cull:r=new Bp(e,this._currentProcessedTask,this._passContext,this._engine);break;default:r=new Lp(e,this._currentProcessedTask,this._passContext)}return this._currentProcessedTask._addPass(r,i),r}build(){this._textureManager.releaseTextures(!1);for(const e of this._tasks)e._reset(),this._currentProcessedTask=e,e.record(),this._currentProcessedTask=null;this._textureManager.allocateTextures();for(const e of this._tasks)e._checkTask();this.onBuildObservable.notifyObservers(this)}whenReadyAsync(e=16){return new Promise((t=>{const i=()=>{let r=!0;for(const e of this._tasks)r&&(r=e.isReady());r?t():setTimeout(i,e)};i()}))}execute(){this._renderContext.bindRenderTarget(),this._textureManager.updateHistoryTextures();for(const e of this._tasks){const t=e._getPasses();for(const e of t)e._execute()}}importTexture(e,t,i){return this._textureManager.importTexture(e,t,i)}getTextureCreationOptions(e,t=!1){const i=this._textureManager.getTextureCreationOptions(e);return t?{size:Zp(i.size),options:{...i.options},sizeIsPercentage:i.sizeIsPercentage}:i}getTextureDescription(e){const t=this.getTextureCreationOptions(e);return{size:t.sizeIsPercentage?this._textureManager.getAbsoluteDimensions(t.size):Qp(t.size)?{width:t.size.width,height:t.size.height}:{width:t.size,height:t.size},options:{...t.options}}}getTextureHandleOrCreateTexture(e,t,i){if(void 0===e){if(void 0===t||void 0===i)throw new Error("getTextureHandleOrCreateTexture: Either handle or newTextureName and creationOptions must be provided.");return this.createRenderTargetTexture(t,i)}return e}getTexture(e){return this._textureManager.getTextureFromHandle(e)}createRenderTargetTexture(e,t,i=!1){return this._textureManager.createRenderTargetTexture(e,!!this._currentProcessedTask,t,i)}createDanglingHandle(){return this._textureManager.createDanglingHandle()}resolveDanglingHandle(e,t,i,r){if(void 0!==t)this._textureManager.resolveDanglingHandle(e,t);else{if(void 0===i||void 0===r)throw new Error("resolveDanglingHandle: Either handle or newTextureName and creationOptions must be provided.");this._textureManager.createRenderTargetTexture(i,!!this._currentProcessedTask,r,!1,e)}}isHistoryTexture(e){const t=this._textureManager._textures.get(e);return!!t&&(e=t.refHandle??e,this._textureManager._historyTextures.has(e))}clear(){for(const e of this._tasks)e._reset();this._tasks.length=0,this._textureManager.releaseTextures(),this._currentProcessedTask=null}dispose(){this.clear(),this._textureManager.dispose(),this._renderContext._dispose()}}function t_(e,t=0,i="PROPERTIES",r){return(s,n)=>{let o=s._propStore;o||(o=[],s._propStore=o),o.push({propertyName:n,displayName:e,type:t,groupName:i,options:r??{},className:s.constructor.name})}}!function(e){e[e.Boolean=0]="Boolean",e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=3]="Vector2",e[e.List=4]="List",e[e.Color4=5]="Color4",e[e.SamplingMode=6]="SamplingMode",e[e.TextureFormat=7]="TextureFormat",e[e.TextureType=8]="TextureType"}(Xp||(Xp={}));class i_ extends wp{get type(){return this._type}constructor(e,t,i,r=Rp.Undefined){super(e,t,i),this._storedValue=null,this._type=Rp.Undefined,this.onValueChangedObservable=new z.cP,this.isExternal=!1,this._type=r,this._isInput=!0,this.registerOutput("output",r),this.setDefaultValue()}setDefaultValue(){switch(this.type){case Rp.Texture:case Rp.TextureViewDepth:case Rp.TextureScreenDepth:case Rp.TextureViewNormal:case Rp.TextureWorldNormal:case Rp.TextureAlbedo:case Rp.TextureReflectivity:case Rp.TextureLocalPosition:case Rp.TextureWorldPosition:case Rp.TextureVelocity:case Rp.TextureLinearVelocity:case Rp.TextureIrradiance:case Rp.TextureAlbedoSqrt:{const e={size:{width:100,height:100},options:{createMipMaps:!1,generateMipMaps:!1,types:[0],formats:[5],samples:1,useSRGBBuffers:[!1],generateDepthBuffer:!1},sizeIsPercentage:!0};this.creationOptions=e;break}case Rp.TextureDepthStencilAttachment:{const e={size:{width:100,height:100},options:{createMipMaps:!1,generateMipMaps:!1,depthTextureFormat:13,textureCount:0,samples:1,generateDepthTexture:!0,generateDepthBuffer:!0,generateStencilBuffer:!0},sizeIsPercentage:!0};this.creationOptions=e;break}case Rp.ObjectList:this.value={meshes:[],particleSystems:[]},this.isExternal=!0;break;case Rp.Camera:this.value=this._scene.cameras[0],this.isExternal=!0;break;default:this.isExternal=!0}}get value(){return this._storedValue}set value(e){this._storedValue=e,this.output.value=void 0,this.onValueChangedObservable.notifyObservers(this)}getTypedValue(){return this._storedValue}getValueAsRenderTargetWrapper(){return this._storedValue.shareDepth?this._storedValue:null}getInternalTextureFromValue(){return this._storedValue.shareDepth?this._storedValue.texture:null}getClassName(){return"NodeRenderGraphInputBlock"}get output(){return this._outputs[0]}isAnyTexture(){return!!(this.type&Rp.TextureAll)}isBackBuffer(){return!!(this.type&Rp.TextureBackBuffer)}isBackBufferDepthStencilAttachment(){return!!(this.type&Rp.TextureBackBufferDepthStencilAttachment)}isCamera(){return!!(this.type&Rp.Camera)}isObjectList(){return!!(this.type&Rp.ObjectList)}_buildBlock(e){if(super._buildBlock(e),this.isExternal)if(this.isBackBuffer())this.output.value=Np;else if(this.isBackBufferDepthStencilAttachment())this.output.value=Fp;else if(this.isCamera())this.output.value=this.getTypedValue();else if(this.isObjectList())this.output.value=this.getTypedValue();else{if(void 0===this._storedValue||null===this._storedValue)throw new Error(`NodeRenderGraphInputBlock: External input "${this.name}" is not set`);const e=this.getValueAsRenderTargetWrapper();e&&(this.output.value=this._frameGraph.importTexture(this.name,e,this.output.value))}else if(this.type&Rp.TextureAllButBackBuffer){const e=this.creationOptions;if(!e)throw new Error(`NodeRenderGraphInputBlock: Creation options are missing for texture "${this.name}"`);this.output.value=this._frameGraph.createRenderTargetTexture(this.name,e)}}dispose(){this._storedValue=null,this.onValueChangedObservable.clear(),super.dispose()}_dumpPropertiesCode(){const e=[];return e.push(`${this._codeVariableName}.isExternal = ${this.isExternal};`),this.isAnyTexture()?this.isExternal?e.push(`${this._codeVariableName}.value = EXTERNAL_TEXTURE; // TODO: set the external texture`):e.push(`${this._codeVariableName}.creationOptions = ${JSON.stringify(this.creationOptions)};`):this.isCamera()?e.push(`${this._codeVariableName}.value = EXTERNAL_CAMERA; // TODO: set the external camera`):this.isObjectList()&&e.push(`${this._codeVariableName}.value = EXTERNAL_OBJECT_LIST; // TODO: set the external object list`),super._dumpPropertiesCode()+e.join("\n")}serialize(){const e=super.serialize();return e.type=this.type,e.isExternal=this.isExternal,this.creationOptions&&(e.creationOptions=this.creationOptions),e}_deserialize(e){super._deserialize(e),this._type=e.type,this.output.type=this._type,this.isExternal=e.isExternal,e.creationOptions&&(this.creationOptions=e.creationOptions)}}(0,je.Cg)([t_("Is external",0,"PROPERTIES")],i_.prototype,"isExternal",void 0),(0,X.Y5)("BABYLON.NodeRenderGraphInputBlock",i_);class r_ extends kp{constructor(e,t){super(e,t),this.color=new H.ov(.2,.2,.3,1),this.clearColor=!0,this.clearDepth=!1,this.clearStencil=!1,this.outputTexture=this._frameGraph.createDanglingHandle()}record(){if(void 0===this.destinationTexture)throw new Error(`FrameGraphClearTextureTask ${this.name}: destinationTexture is required`);this._frameGraph.resolveDanglingHandle(this.outputTexture,this.destinationTexture);const e=this._frameGraph.addRenderPass(this.name);e.setRenderTarget(this.destinationTexture),e.setExecuteFunc((e=>{e.clear(this.color,!!this.clearColor,!!this.clearDepth,!!this.clearStencil)}));const t=this._frameGraph.addRenderPass(this.name+"_disabled",!0);t.setRenderTarget(this.destinationTexture),t.setExecuteFunc((e=>{}))}}class s_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i){super(e,t,i),this.registerInput("texture",Rp.Texture),this.registerOutput("output",Rp.BasedOnInput),this.texture.addAcceptedConnectionPointTypes(Rp.TextureAll),this.output._typeConnectionSource=this.texture,this._frameGraphTask=new r_(e,t)}get color(){return this._frameGraphTask.color}set color(e){this._frameGraphTask.color=e}get clearColor(){return!!this._frameGraphTask.clearColor}set clearColor(e){this._frameGraphTask.clearColor=e}get clearDepth(){return!!this._frameGraphTask.clearDepth}set clearDepth(e){this._frameGraphTask.clearDepth=e}get clearStencil(){return!!this._frameGraphTask.clearStencil}set clearStencil(e){this._frameGraphTask.clearStencil=e}getClassName(){return"NodeRenderGraphClearBlock"}get texture(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this._propagateInputValueToOutput(this.texture,this.output);const t=this.texture.connectedPoint;t&&(this._frameGraphTask.destinationTexture=t.value)}_dumpPropertiesCode(){const e=[];return e.push(`${this._codeVariableName}.color = new BABYLON.Color4(${this.color.r}, ${this.color.g}, ${this.color.b}, ${this.color.a});`),e.push(`${this._codeVariableName}.clearColor = ${this.clearColor};`),e.push(`${this._codeVariableName}.clearDepth = ${this.clearDepth};`),e.push(`${this._codeVariableName}.clearStencil = ${this.clearStencil};`),super._dumpPropertiesCode()+e.join("\n")}serialize(){const e=super.serialize();return e.color=this.color.asArray(),e.clearColor=this.clearColor,e.clearDepth=this.clearDepth,e.clearStencil=this.clearStencil,e}_deserialize(e){super._deserialize(e),this.color=H.ov.FromArray(e.color),this.clearColor=e.clearColor,this.clearDepth=e.clearDepth,this.clearStencil=e.clearStencil}}(0,je.Cg)([t_("Color",5)],s_.prototype,"color",null),(0,je.Cg)([t_("Clear color",0,void 0,{embedded:!0})],s_.prototype,"clearColor",null),(0,je.Cg)([t_("Clear depth",0,void 0,{embedded:!0})],s_.prototype,"clearDepth",null),(0,je.Cg)([t_("Clear stencil",0,void 0,{embedded:!0})],s_.prototype,"clearStencil",null),(0,X.Y5)("BABYLON.NodeRenderGraphClearBlock",s_);class n_{constructor(){this.verbose=!1,this._notConnectedNonOptionalInputs=[]}emitErrors(e=null){let t="";for(const e of this._notConnectedNonOptionalInputs)t+=`input "${e.name}" from block "${e.ownerBlock.name}"[${e.ownerBlock.getClassName()}] is not connected and is not optional.\n`;return!t||(e&&e.notifyObservers(t),Z.V.Error("Build of node render graph failed:\n"+t),!1)}}class o_{_getGlobalNodeRenderGraphEditor(){return"undefined"!=typeof NODERENDERGRAPHEDITOR?NODERENDERGRAPHEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeRenderGraphEditor?BABYLON:void 0}get frameGraph(){return this._frameGraph}getScene(){return this._scene}constructor(e,t,i){this._buildId=o_._BuildIdGenerator++,this.BJSNODERENDERGRAPHEDITOR=this._getGlobalNodeRenderGraphEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new z.cP,this.onBuildErrorObservable=new z.cP,this.outputBlock=null,this._resizeObserver=null,this.name=e,this._scene=t,this._engine=t.getEngine(),i={debugTextures:!1,autoConfigure:!1,verbose:!1,rebuildGraphOnEngineResize:!0,autoFillExternalInputs:!0,...i},this._options=i,this._frameGraph=new e_(this._engine,i.debugTextures,this._scene),i.rebuildGraphOnEngineResize&&(this._resizeObserver=this._engine.onResizeObservable.add((()=>{this.build()})))}getClassName(){return"NodeRenderGraph"}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e){if(t)return Ue.S0.Warn("More than one block was found with the name `"+e+"`"),t;t=i}return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getBlocksByPredicate(e){const t=[];for(const i of this.attachedBlocks)e(i)&&t.push(i);return t}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}edit(e){return new Promise((t=>{if(this.BJSNODERENDERGRAPHEDITOR=this.BJSNODERENDERGRAPHEDITOR||this._getGlobalNodeRenderGraphEditor(),void 0===this.BJSNODERENDERGRAPHEDITOR){const i=e&&e.editorURL?e.editorURL:o_.EditorURL;Ue.S0.LoadBabylonScript(i,(()=>{this.BJSNODERENDERGRAPHEDITOR=this.BJSNODERENDERGRAPHEDITOR||this._getGlobalNodeRenderGraphEditor(),this._createNodeEditor(e?.nodeRenderGraphEditorConfig),t()}))}else this._createNodeEditor(e?.nodeRenderGraphEditorConfig),t()}))}_createNodeEditor(e){const t={nodeRenderGraph:this,...e};this.BJSNODERENDERGRAPHEDITOR.NodeRenderGraphEditor.Show(t)}build(){if(!this.outputBlock)throw new Error("You must define the outputBlock property before building the node render graph");this._initializeBlock(this.outputBlock),this._frameGraph.clear();const e=new n_;e.buildId=this._buildId,e.verbose=this._options.verbose,this._options.autoFillExternalInputs&&this._autoFillExternalInputs(),this.outputBlock.build(e),this._frameGraph.build(),this._buildId=o_._BuildIdGenerator++,e.emitErrors(this.onBuildErrorObservable)&&this.onBuildObservable.notifyObservers(this)}_autoFillExternalInputs(){const e=this.getInputBlocks();let t=0;for(const i of e)if(i.isExternal&&i.isAnAncestorOfType("NodeRenderGraphOutputBlock"))if(i.type&Rp.TextureAllButBackBuffer);else if(i.isCamera()){const e=this._scene.cameras[t++]||this._scene.cameras[0];this._scene.cameraToUseForPointers||(this._scene.cameraToUseForPointers=e),i.value=e}else i.isObjectList()&&(i.value={meshes:this._scene.meshes,particleSystems:this._scene.particleSystems})}whenReadyAsync(e=16){return this._frameGraph.whenReadyAsync(e)}execute(){this._frameGraph.execute()}_initializeBlock(e){e.initialize(),this._options.autoConfigure&&e.autoConfigure(),-1===this.attachedBlocks.indexOf(e)&&this.attachedBlocks.push(e);for(const t of e.inputs){const i=t.connectedPoint;if(i){const t=i.ownerBlock;t!==e&&this._initializeBlock(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 t of e.blocks){const e=(0,X.n9)(t.customType);if(e){const r=t.additionalConstructionParameters,s=r?new e("",this._frameGraph,this._scene,...r):new e("",this._frameGraph,this._scene);s._deserialize(t),i[t.id]=s,this.attachedBlocks.push(s)}}for(const e of this.attachedBlocks)if(e.isTeleportOut){const t=e,r=t._tempEntryPointUniqueId;if(r){const e=i[r];e&&e.attachToEndpoint(t)}}for(let r=0;re.targetConnectionName))&&!t||this._restoreConnections(n,e,i))}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){const r=e.locations||e.editorData.locations;for(const e of r)i[e.blockId]&&(e.blockId=i[e.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&r.concat(this.editorData.locations),e.locations?this.editorData={locations:r}:(this.editorData=e.editorData,this.editorData.locations=r);const s=[];for(const e in i)s[e]=i[e].uniqueId;this.editorData.map=s}this.comment=e.comment}_restoreConnections(e,t,i){for(const r of e.outputs)for(const s of t.blocks){const n=i[s.id];if(n)for(const o of s.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==r.name);else{const e=n.getInputByName(o.inputName);if(!e||e.isConnected)continue;r.connectTo(e,!0),this._restoreConnections(n,t,i)}}}generateCode(){let e=[];const t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);const r=JSON.stringify(this._options);let s=`let nodeRenderGraph = new BABYLON.NodeRenderGraph("${this.name||"render graph"}", scene, ${r});\n`;for(const r of t)r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e)+"\n");return this.outputBlock&&(e=[],s+="// Connections\n",s+=this.outputBlock._dumpCodeForOutputConnections(e),s+="// Output nodes\n",s+=`nodeRenderGraph.outputBlock = ${this.outputBlock._codeVariableName};\n`,s+="nodeRenderGraph.build();\n"),s}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const r=i.connectedPoint;if(r){const i=r.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}setToDefault(){this.clear(),this.editorData=null;const e=new i_("BackBuffer color",this._frameGraph,this._scene,Rp.TextureBackBuffer),t=new s_("Clear",this._frameGraph,this._scene);e.output.connectTo(t.texture);const i=new Gp("Output",this._frameGraph,this._scene);t.output.connectTo(i.texture),this.outputBlock=i}clone(e){const t=this.serialize(),i=it.p.Clone((()=>new o_(e,this._scene)),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(),i}serialize(e){const t=e?{}:it.p.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];e?i=e:(t.customType="BABYLON.NodeRenderGraph",this.outputBlock&&(t.outputNodeId=this.outputBlock.uniqueId)),t.blocks=[];for(const e of i)t.blocks.push(e.serialize());if(!e)for(const e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}dispose(){for(const e of this.attachedBlocks)e.dispose();this._frameGraph.dispose(),this._frameGraph=void 0,this._engine.onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null,this.attachedBlocks.length=0,this.onBuildObservable.clear(),this.onBuildErrorObservable.clear()}static CreateDefault(e,t,i){const r=new o_(e,t,i);return r.setToDefault(),r.build(),r}static Parse(e,t,i,r=!0){const s=it.p.Parse((()=>new o_(e.name,t,i)),e,null);return s.parseSerializedObject(e),r||s.build(),s}static ParseFromSnippetAsync(e,t,i,r,s=!0){return"_BLANK"===e?Promise.resolve(o_.CreateDefault("blank",t,i)):new Promise(((n,o)=>{const a=new go.u;a.addEventListener("readystatechange",(()=>{if(4==a.readyState)if(200==a.status){const l=JSON.parse(JSON.parse(a.responseText).jsonPayload),h=JSON.parse(l.nodeRenderGraph);r||(r=it.p.Parse((()=>new o_(e,t,i)),h,null)),r.parseSerializedObject(h),r.snippetId=e;try{s||r.build(),n(r)}catch(e){o(e)}}else o("Unable to load the snippet "+e)})),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()}))}}o_._BuildIdGenerator=0,o_.EditorURL=`${Ue.S0._DefaultCdnUrl}/v${an.Version}/NodeRenderGraph/babylon.nodeRenderGraph.js`,o_.SnippetUrl="https://snippet.babylonjs.com",(0,je.Cg)([(0,$e.lK)()],o_.prototype,"name",void 0),(0,je.Cg)([(0,$e.lK)("comment")],o_.prototype,"comment",void 0);class a_ extends wp{constructor(e,t,i){super(e,t,i),this.registerInput("input",Rp.AutoDetect),this.registerOutput("output",Rp.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NodeRenderGraphElbowBlock"}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];this._propagateInputValueToOutput(i,t)}}(0,X.Y5)("BABYLON.NodeRenderGraphElbowBlock",a_);class l_ extends Yp.${_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(i.bind(i,31162)))):t.push(Promise.resolve().then(i.bind(i,27897)))}constructor(e,t=null,i){super({...i,name:e,engine:t||an.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:l_.FragmentUrl,uniforms:l_.Uniforms}),this.degree=1}bind(){super.bind(),this._drawWrapper.effect.setFloat("degree",this.degree)}}l_.FragmentUrl="blackAndWhite",l_.Uniforms=["degree"];class h_ extends kp{constructor(e,t,i){super(e,t),this.sourceSamplingMode=2,this.postProcess=i,this._postProcessDrawWrapper=this.postProcess.drawWrapper,this.outputTexture=this._frameGraph.createDanglingHandle()}isReady(){return this.postProcess.isReady()}record(e=!1,t,i){if(void 0===this.sourceTexture)throw new Error(`FrameGraphPostProcessTask "${this.name}": sourceTexture is required`);const r=this._frameGraph.getTextureCreationOptions(this.sourceTexture,!0);r.options.generateDepthBuffer=!1,r.options.generateStencilBuffer=!1,r.options.samples=1,this._frameGraph.resolveDanglingHandle(this.outputTexture,this.destinationTexture,this.name,r);const s=this._frameGraph.getTextureDescription(this.outputTexture);this._outputWidth=s.size.width,this._outputHeight=s.size.height;const n=this._frameGraph.addRenderPass(this.name);if(n.useTexture(this.sourceTexture),n.setRenderTarget(this.outputTexture),n.setExecuteFunc((e=>{e.setTextureSamplingMode(this.sourceTexture,this.sourceSamplingMode),t?.(e),e.applyFullScreenEffect(this._postProcessDrawWrapper,(()=>{e.bindTextureHandle(this._postProcessDrawWrapper.effect,"textureSampler",this.sourceTexture),i?.(e),this.postProcess.bind()}))})),!e){const e=this._frameGraph.addRenderPass(this.name+"_disabled",!0);e.setRenderTarget(this.outputTexture),e.setExecuteFunc((e=>{e.copyTexture(this.sourceTexture)}))}return n}dispose(){this.postProcess.dispose(),super.dispose()}}class c_ extends h_{constructor(e,t,i){super(e,t,i||new l_(e,t.engine))}}class u_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i){super(e,t,i),this.registerInput("source",Rp.Texture),this.registerInput("destination",Rp.Texture,!0),this.registerOutput("output",Rp.BasedOnInput),this.source.addAcceptedConnectionPointTypes(Rp.TextureAllButBackBuffer),this.destination.addAcceptedConnectionPointTypes(Rp.TextureAll),this.output._typeConnectionSource=()=>this.destination.isConnected?this.destination:this.source,this._frameGraphTask=new c_(this.name,t,new l_(e,i.getEngine()))}get sourceSamplingMode(){return this._frameGraphTask.sourceSamplingMode}set sourceSamplingMode(e){this._frameGraphTask.sourceSamplingMode=e}get degree(){return this._frameGraphTask.postProcess.degree}set degree(e){this._frameGraphTask.postProcess.degree=e}getClassName(){return"NodeRenderGraphBlackAndWhitePostProcessBlock"}get source(){return this._inputs[0]}get destination(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this.output.value=this._frameGraphTask.outputTexture;const t=this.source.connectedPoint;t&&(this._frameGraphTask.sourceTexture=t.value);const i=this.destination.connectedPoint;i&&(this._frameGraphTask.destinationTexture=i.value)}_dumpPropertiesCode(){const e=[];return e.push(`${this._codeVariableName}.degree = ${this.degree};`),e.push(`${this._codeVariableName}.sourceSamplingMode = ${this.sourceSamplingMode};`),super._dumpPropertiesCode()+e.join("\n")}serialize(){const e=super.serialize();return e.degree=this.degree,e.sourceSamplingMode=this.sourceSamplingMode,e}_deserialize(e){super._deserialize(e),this.degree=e.degree,this.sourceSamplingMode=e.sourceSamplingMode}}(0,je.Cg)([t_("Source sampling mode",6,"PROPERTIES")],u_.prototype,"sourceSamplingMode",null),(0,je.Cg)([t_("Degree",1,"PROPERTIES",{min:0,max:1})],u_.prototype,"degree",null),(0,X.Y5)("BABYLON.NodeRenderGraphBlackAndWhitePostProcessBlock",u_);class d_ extends Yp.${_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(i.bind(i,63186)))):t.push(Promise.resolve().then(i.bind(i,94811)))}constructor(e,t=null,i){super({...i,name:e,engine:t||an.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:d_.FragmentUrl,uniforms:d_.Uniforms,samplers:d_.Samplers}),this.weight=1}bind(){super.bind(),this._drawWrapper.effect.setFloat("bloomWeight",this.weight)}}d_.FragmentUrl="bloomMerge",d_.Uniforms=["bloomWeight"],d_.Samplers=["bloomBlur"];class f_ extends h_{constructor(e,t,i){super(e,t,i||new d_(e,t.engine))}record(e=!1){if(void 0===this.sourceTexture||void 0===this.blurTexture)throw new Error(`FrameGraphBloomMergeTask "${this.name}": sourceTexture and blurTexture are required`);const t=super.record(e,void 0,(e=>{e.bindTextureHandle(this._postProcessDrawWrapper.effect,"bloomBlur",this.blurTexture)}));return t.useTexture(this.blurTexture),t}}class p_ extends Yp.${_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,56558)),Promise.resolve().then(i.bind(i,42876))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,45245)),Promise.resolve().then(i.bind(i,95527))]))}constructor(e,t=null,i,r,s){const n=!!s?.blockCompilation;super({...s,name:e,engine:t||an.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:p_.FragmentUrl,uniforms:p_.Uniforms,samplers:p_.Samplers,vertexUrl:p_.VertexUrl,blockCompilation:!0}),this._packedFloat=!1,this._staticDefines="",this.textureWidth=0,this.textureHeight=0,this.options.blockCompilation=n,void 0!==i&&(this.direction=i),void 0!==r&&(this.kernel=r)}set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this.options.blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this.options.blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}bind(){super.bind(),this._drawWrapper.effect.setFloat2("delta",1/this.textureWidth*this.direction.x,1/this.textureHeight*this.direction.y)}_updateParameters(e,t){const i=this._kernel,r=(i-1)/2;let s=[],n=[],o=0;for(let e=0;e0)return Math.max(e,3);return Math.max(t,3)}_gaussianWeight(e){const t=1/3,i=-e*e/(2*t*t);return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(i)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}}p_.VertexUrl="kernelBlur",p_.FragmentUrl="kernelBlur",p_.Uniforms=["delta","direction"],p_.Samplers=["circleOfConfusionSampler"];class __ extends Yp.${_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(i.bind(i,9574)))):t.push(Promise.resolve().then(i.bind(i,83062)))}constructor(e,t=null,i){super({...i,name:e,engine:t||an.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:__.FragmentUrl,uniforms:__.Uniforms}),this.threshold=.9,this._exposure=1}bind(){super.bind();const e=this._drawWrapper.effect;e.setFloat("threshold",Math.pow(this.threshold,lt.rv)),e.setFloat("exposure",this._exposure)}}__.FragmentUrl="extractHighlights",__.Uniforms=["threshold","exposure"];class m_{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.scale}set kernel(e){this._blurX.kernel=e*this.scale,this._blurY.kernel=e*this.scale}constructor(e,t,i,r=!1){this.scale=i,this._downscale=new __(e+"_downscale",t,{blockCompilation:r}),this._blurX=new p_(e+"_blurX",t,new W.I9(1,0),10,{blockCompilation:r}),this._blurY=new p_(e+"_blurY",t,new W.I9(0,1),10,{blockCompilation:r}),this._merge=new d_(e+"_merge",t,{blockCompilation:r})}isReady(){return this._downscale.isReady()&&this._blurX.isReady()&&this._blurY.isReady()&&this._merge.isReady()}}class g_ extends h_{constructor(e,t,i){super(e,t,i||new __(e,t.engine))}}class v_ extends h_{constructor(e,t,i){super(e,t,i||new p_(e,t.engine,new W.I9(1,0),10))}record(e=!1,t,i){const r=super.record(e,t,i);return this.postProcess.textureWidth=this._outputWidth,this.postProcess.textureHeight=this._outputHeight,r}}class x_ extends kp{constructor(e,t,i,r,s,n,o=!1,a=.5){if(super(e,t),this.sourceSamplingMode=2,this.hdr=o,this._defaultPipelineTextureType=0,o){const e=i.getCaps();e.textureHalfFloatRender?this._defaultPipelineTextureType=2:e.textureFloatRender&&(this._defaultPipelineTextureType=1)}this.bloom=new m_(e,i,a),this.bloom.threshold=n,this.bloom.kernel=s,this.bloom.weight=r,this._downscale=new g_(`${e} Downscale`,this._frameGraph,this.bloom._downscale),this._blurX=new v_(`${e} Blur X`,this._frameGraph,this.bloom._blurX),this._blurY=new v_(`${e} Blur Y`,this._frameGraph,this.bloom._blurY),this._merge=new f_(`${e} Merge`,this._frameGraph,this.bloom._merge),this.outputTexture=this._frameGraph.createDanglingHandle()}isReady(){return this.bloom.isReady()}record(){if(void 0===this.sourceTexture)throw new Error("FrameGraphBloomTask: sourceTexture is required");const e=this._frameGraph.getTextureDescription(this.sourceTexture),t={size:{width:Math.floor(e.size.width*this.bloom.scale),height:Math.floor(e.size.height*this.bloom.scale)},options:{createMipMaps:!1,generateMipMaps:!1,types:[this._defaultPipelineTextureType],samplingModes:[2],formats:[5],samples:1,useSRGBBuffers:[!1],generateDepthBuffer:!1,generateStencilBuffer:!1,label:""},sizeIsPercentage:!1},i=this._frameGraph.createRenderTargetTexture(this._downscale.name,t);this._downscale.sourceTexture=this.sourceTexture,this._downscale.sourceSamplingMode=2,this._downscale.destinationTexture=i,this._downscale.record(!0);const r=this._frameGraph.createRenderTargetTexture(this._blurX.name,t);this._blurX.sourceTexture=i,this._blurX.sourceSamplingMode=2,this._blurX.destinationTexture=r,this._blurX.record(!0);const s=this._frameGraph.createRenderTargetTexture(this._blurY.name,t);this._blurY.sourceTexture=r,this._blurY.sourceSamplingMode=2,this._blurY.destinationTexture=s,this._blurY.record(!0);const n=this._frameGraph.getTextureCreationOptions(this.sourceTexture,!0);n.options.generateDepthBuffer=!1,n.options.generateStencilBuffer=!1,this._frameGraph.resolveDanglingHandle(this.outputTexture,this.destinationTexture,this._merge.name,n),this._merge.sourceTexture=this.sourceTexture,this._merge.sourceSamplingMode=this.sourceSamplingMode,this._merge.blurTexture=s,this._merge.destinationTexture=this.outputTexture,this._merge.record(!0);const o=this._frameGraph.addRenderPass(this.name+"_disabled",!0);o.setRenderTarget(this.outputTexture),o.setExecuteFunc((e=>{e.copyTexture(this.sourceTexture)}))}dispose(){this._downscale.dispose(),this._blurX.dispose(),this._blurY.dispose(),this._merge.dispose(),super.dispose()}}class b_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i,r=!1,s=.5){super(e,t,i),this._additionalConstructionParameters=[r,s],this.registerInput("source",Rp.Texture),this.registerInput("destination",Rp.Texture,!0),this.registerOutput("output",Rp.BasedOnInput),this.source.addAcceptedConnectionPointTypes(Rp.TextureAllButBackBuffer),this.destination.addAcceptedConnectionPointTypes(Rp.TextureAll),this.output._typeConnectionSource=()=>this.destination.isConnected?this.destination:this.source,this._frameGraphTask=new x_(this.name,t,i.getEngine(),.75,64,.2,r,s)}_createTask(e,t){const i=this._frameGraphTask.sourceSamplingMode,r=this._frameGraphTask.bloom.threshold,s=this._frameGraphTask.bloom.weight,n=this._frameGraphTask.bloom.kernel;this._frameGraphTask.dispose(),this._frameGraphTask=new x_(this.name,this._frameGraph,this._scene.getEngine(),s,n,r,t,e),this._frameGraphTask.sourceSamplingMode=i,this._additionalConstructionParameters=[t,e]}get bloomScale(){return this._frameGraphTask.bloom.scale}set bloomScale(e){this._createTask(e,this._frameGraphTask.hdr)}get hdr(){return this._frameGraphTask.hdr}set hdr(e){this._createTask(this._frameGraphTask.bloom.scale,e)}get sourceSamplingMode(){return this._frameGraphTask.sourceSamplingMode}set sourceSamplingMode(e){this._frameGraphTask.sourceSamplingMode=e}get threshold(){return this._frameGraphTask.bloom.threshold}set threshold(e){this._frameGraphTask.bloom.threshold=e}get weight(){return this._frameGraphTask.bloom.weight}set weight(e){this._frameGraphTask.bloom.weight=e}get kernel(){return this._frameGraphTask.bloom.kernel}set kernel(e){this._frameGraphTask.bloom.kernel=e}getClassName(){return"NodeRenderGraphBloomPostProcessBlock"}get source(){return this._inputs[0]}get destination(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this.output.value=this._frameGraphTask.outputTexture;const t=this.source.connectedPoint;t&&(this._frameGraphTask.sourceTexture=t.value);const i=this.destination.connectedPoint;i&&(this._frameGraphTask.destinationTexture=i.value)}_dumpPropertiesCode(){const e=[];return e.push(`${this._codeVariableName}.threshold = ${this.threshold};`),e.push(`${this._codeVariableName}.weight = ${this.weight};`),e.push(`${this._codeVariableName}.kernel = ${this.kernel};`),e.push(`${this._codeVariableName}.sourceSamplingMode = ${this.sourceSamplingMode};`),super._dumpPropertiesCode()+e.join("\n")}serialize(){const e=super.serialize();return e.threshold=this.threshold,e.weight=this.weight,e.kernel=this.kernel,e.sourceSamplingMode=this.sourceSamplingMode,e}_deserialize(e){super._deserialize(e),this.threshold=e.threshold,this.weight=e.weight,this.kernel=e.kernel,this.sourceSamplingMode=e.sourceSamplingMode}}(0,je.Cg)([t_("Bloom scale",1,"PROPERTIES")],b_.prototype,"bloomScale",null),(0,je.Cg)([t_("HDR",0,"PROPERTIES")],b_.prototype,"hdr",null),(0,je.Cg)([t_("Source sampling mode",6)],b_.prototype,"sourceSamplingMode",null),(0,je.Cg)([t_("Threshold",1,"PROPERTIES",{min:0,max:2})],b_.prototype,"threshold",null),(0,je.Cg)([t_("Weight",1,"PROPERTIES",{min:0,max:3})],b_.prototype,"weight",null),(0,je.Cg)([t_("Kernel",2,"PROPERTIES",{min:1,max:128})],b_.prototype,"kernel",null),(0,X.Y5)("BABYLON.NodeRenderGraphBloomPostProcessBlock",b_);class S_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i){super(e,t,i),this.registerInput("source",Rp.Texture),this.registerInput("destination",Rp.Texture,!0),this.registerOutput("output",Rp.BasedOnInput),this.source.addAcceptedConnectionPointTypes(Rp.TextureAllButBackBuffer),this.destination.addAcceptedConnectionPointTypes(Rp.TextureAll),this.output._typeConnectionSource=()=>this.destination.isConnected?this.destination:this.source,this._frameGraphTask=new v_(this.name,t,new p_(e,i.getEngine(),new W.I9(1,0),32))}get sourceSamplingMode(){return this._frameGraphTask.sourceSamplingMode}set sourceSamplingMode(e){this._frameGraphTask.sourceSamplingMode=e}get direction(){return this._frameGraphTask.postProcess.direction}set direction(e){this._frameGraphTask.postProcess.direction=e}get kernel(){return this._frameGraphTask.postProcess.kernel}set kernel(e){this._frameGraphTask.postProcess.kernel=e}getClassName(){return"NodeRenderGraphBlurPostProcessBlock"}get source(){return this._inputs[0]}get destination(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this.output.value=this._frameGraphTask.outputTexture;const t=this.source.connectedPoint;t&&(this._frameGraphTask.sourceTexture=t.value);const i=this.destination.connectedPoint;i&&(this._frameGraphTask.destinationTexture=i.value)}_dumpPropertiesCode(){const e=[];return e.push(`${this._codeVariableName}.direction = new BABYLON.Vector2(${this.direction.x}, ${this.direction.y});`),e.push(`${this._codeVariableName}.kernel = ${this.kernel};`),e.push(`${this._codeVariableName}.sourceSamplingMode = ${this.sourceSamplingMode};`),super._dumpPropertiesCode()+e.join("\n")}serialize(){const e=super.serialize();return e.direction=this.direction.asArray(),e.kernel=this.kernel,e.sourceSamplingMode=this.sourceSamplingMode,e}_deserialize(e){super._deserialize(e),this.direction.fromArray(e.direction),this.kernel=e.kernel,this.sourceSamplingMode=e.sourceSamplingMode}}(0,je.Cg)([t_("Source sampling mode",6,"PROPERTIES")],S_.prototype,"sourceSamplingMode",null),(0,je.Cg)([t_("Direction",3,"PROPERTIES")],S_.prototype,"direction",null),(0,je.Cg)([t_("Kernel",2,"PROPERTIES",{min:1,max:256})],S_.prototype,"kernel",null),(0,X.Y5)("BABYLON.NodeRenderGraphBlurPostProcessBlock",S_);class T_ extends Yp.${_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(i.bind(i,89328)))):t.push(Promise.resolve().then(i.bind(i,29743)))}constructor(e,t=null,i){super({...i,name:e,engine:t||an.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:T_.FragmentUrl,uniforms:T_.Uniforms,samplers:T_.Samplers,defines:i?.depthNotNormalized?T_.DefinesDepthNotNormalized:void 0}),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50}bind(){super.bind();const e=this.options,t=this._drawWrapper.effect;e.depthNotNormalized||t.setFloat2("cameraMinMaxZ",this.camera.minZ,this.camera.maxZ-this.camera.minZ);const i=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);t.setFloat("focusDistance",this.focusDistance),t.setFloat("cocPrecalculation",i)}}T_.FragmentUrl="circleOfConfusion",T_.Uniforms=["cameraMinMaxZ","focusDistance","cocPrecalculation"],T_.Samplers=["depthSampler"],T_.DefinesDepthNotNormalized="#define COC_DEPTH_NOT_NORMALIZED";class C_ extends h_{constructor(e,t,i){super(e,t,i||new T_(e,t.engine)),this.depthSamplingMode=2}record(e=!1){if(void 0===this.sourceTexture||void 0===this.depthTexture||void 0===this.camera)throw new Error(`FrameGraphCircleOfConfusionTask "${this.name}": sourceTexture, depthTexture and camera are required`);const t=super.record(e,(e=>{e.setTextureSamplingMode(this.depthTexture,this.depthSamplingMode)}),(e=>{this.postProcess.camera=this.camera,e.bindTextureHandle(this._postProcessDrawWrapper.effect,"depthSampler",this.depthTexture)}));return t.useTexture(this.depthTexture),t}}class y_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i){super(e,t,i),this.registerInput("source",Rp.Texture),this.registerInput("geomViewDepth",Rp.TextureViewDepth),this.registerInput("destination",Rp.Texture,!0),this.registerInput("camera",Rp.Camera),this.registerOutput("output",Rp.BasedOnInput),this.source.addAcceptedConnectionPointTypes(Rp.TextureAllButBackBuffer),this.destination.addAcceptedConnectionPointTypes(Rp.TextureAll),this.output._typeConnectionSource=()=>this.destination.isConnected?this.destination:this.source,this._frameGraphTask=new C_(this.name,t,new T_(e,i.getEngine(),{depthNotNormalized:!0}))}get sourceSamplingMode(){return this._frameGraphTask.sourceSamplingMode}set sourceSamplingMode(e){this._frameGraphTask.sourceSamplingMode=e}get depthSamplingMode(){return this._frameGraphTask.depthSamplingMode}set depthSamplingMode(e){this._frameGraphTask.depthSamplingMode=e}get lensSize(){return this._frameGraphTask.postProcess.lensSize}set lensSize(e){this._frameGraphTask.postProcess.lensSize=e}get fStop(){return this._frameGraphTask.postProcess.fStop}set fStop(e){this._frameGraphTask.postProcess.fStop=e}get focusDistance(){return this._frameGraphTask.postProcess.focusDistance}set focusDistance(e){this._frameGraphTask.postProcess.focusDistance=e}get focalLength(){return this._frameGraphTask.postProcess.focalLength}set focalLength(e){this._frameGraphTask.postProcess.focalLength=e}getClassName(){return"NodeRenderGraphCircleOfConfusionPostProcessBlock"}get source(){return this._inputs[0]}get geomViewDepth(){return this._inputs[1]}get destination(){return this._inputs[2]}get camera(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this.output.value=this._frameGraphTask.outputTexture;const t=this.source.connectedPoint;t&&(this._frameGraphTask.sourceTexture=t.value);const i=this.geomViewDepth.connectedPoint;i&&(this._frameGraphTask.depthTexture=i.value);const r=this.destination.connectedPoint;r&&(this._frameGraphTask.destinationTexture=r.value);const s=this.camera.connectedPoint;s&&(this._frameGraphTask.camera=s.value)}_dumpPropertiesCode(){const e=[];return e.push(`${this._codeVariableName}.lensSize = ${this.lensSize};`),e.push(`${this._codeVariableName}.fStop = ${this.fStop};`),e.push(`${this._codeVariableName}.focusDistance = ${this.focusDistance};`),e.push(`${this._codeVariableName}.focalLength = ${this.focalLength};`),e.push(`${this._codeVariableName}.sourceSamplingMode = ${this.sourceSamplingMode};`),e.push(`${this._codeVariableName}.depthSamplingMode = ${this.depthSamplingMode};`),super._dumpPropertiesCode()+e.join("\n")}serialize(){const e=super.serialize();return e.lensSize=this.lensSize,e.fStop=this.fStop,e.focusDistance=this.focusDistance,e.focalLength=this.focalLength,e.sourceSamplingMode=this.sourceSamplingMode,e.depthSamplingMode=this.depthSamplingMode,e}_deserialize(e){super._deserialize(e),this.lensSize=e.lensSize,this.fStop=e.fStop,this.focusDistance=e.focusDistance,this.focalLength=e.focalLength,this.sourceSamplingMode=e.sourceSamplingMode,this.depthSamplingMode=e.depthSamplingMode}}(0,je.Cg)([t_("Source sampling mode",6,"PROPERTIES")],y_.prototype,"sourceSamplingMode",null),(0,je.Cg)([t_("Depth sampling mode",6,"PROPERTIES")],y_.prototype,"depthSamplingMode",null),(0,je.Cg)([t_("Lens size",1,"PROPERTIES")],y_.prototype,"lensSize",null),(0,je.Cg)([t_("F-Stop",1,"PROPERTIES")],y_.prototype,"fStop",null),(0,je.Cg)([t_("Focus distance",1,"PROPERTIES")],y_.prototype,"focusDistance",null),(0,je.Cg)([t_("Focal length",1,"PROPERTIES")],y_.prototype,"focalLength",null),(0,X.Y5)("BABYLON.NodeRenderGraphCircleOfConfusionPostProcessBlock",y_);class E_ extends Yp.${_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(i.bind(i,41289)))):t.push(Promise.resolve().then(i.bind(i,95610)))}constructor(e,t=null,i){super({...i,name:e,engine:t||an.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:E_.FragmentUrl,samplers:E_.Samplers})}}E_.FragmentUrl="depthOfFieldMerge",E_.Samplers=["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"];class P_ extends h_{constructor(e,t,i){super(e,t,i||new E_(e,t.engine)),this.blurSteps=[]}record(e=!1){if(void 0===this.sourceTexture||void 0===this.circleOfConfusionTexture||0===this.blurSteps.length)throw new Error(`FrameGraphBloomMergeTask "${this.name}": sourceTexture, circleOfConfusionTexture and blurSteps are required`);this.postProcess.updateEffect("#define BLUR_LEVEL "+(this.blurSteps.length-1)+"\n");const t=super.record(e,void 0,(e=>{e.bindTextureHandle(this._postProcessDrawWrapper.effect,"circleOfConfusionSampler",this.circleOfConfusionTexture),this.blurSteps.forEach(((t,i)=>{e.bindTextureHandle(this._postProcessDrawWrapper.effect,"blurStep"+(this.blurSteps.length-i-1),t)}))}));t.useTexture(this.circleOfConfusionTexture);for(const e of this.blurSteps)t.useTexture(e);return t}}class A_ extends p_{constructor(e,t=null,i,r,s){super(e,t,i,r,{...s,defines:"#define DOF 1\n"})}}class R_ extends v_{constructor(e,t,i){super(e,t,i||new A_(e,t.engine,new W.I9(1,0),10)),this.circleOfConfusionSamplingMode=2}record(e=!1){if(void 0===this.sourceTexture||void 0===this.circleOfConfusionTexture)throw new Error(`FrameGraphDepthOfFieldBlurTask "${this.name}": sourceTexture and circleOfConfusionTexture are required`);const t=super.record(e,(e=>{e.setTextureSamplingMode(this.circleOfConfusionTexture,this.circleOfConfusionSamplingMode)}),(e=>{e.bindTextureHandle(this._postProcessDrawWrapper.effect,"circleOfConfusionSampler",this.circleOfConfusionTexture)}));return t.useTexture(this.circleOfConfusionTexture),t}}!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(qp||(qp={}));class I_{set focalLength(e){this._circleOfConfusion.focalLength=e}get focalLength(){return this._circleOfConfusion.focalLength}set fStop(e){this._circleOfConfusion.fStop=e}get fStop(){return this._circleOfConfusion.fStop}set focusDistance(e){this._circleOfConfusion.focusDistance=e}get focusDistance(){return this._circleOfConfusion.focusDistance}set lensSize(e){this._circleOfConfusion.lensSize=e}get lensSize(){return this._circleOfConfusion.lensSize}constructor(e,t,i=0,r=!1,s=!1){this._depthOfFieldBlurX=[],this._depthOfFieldBlurY=[],this._circleOfConfusion=new T_(e,t,{depthNotNormalized:r,blockCompilation:s}),this.blurLevel=i;let n=1,o=15;switch(i){case 2:n=3,o=51;break;case 1:n=2,o=31;break;default:o=15,n=1}const a=o/Math.pow(2,n-1);let l=1;for(let i=0;i1?6:5,r={size:t,options:{createMipMaps:!1,generateMipMaps:!1,types:[this._defaultPipelineTextureType],formats:[i],samples:1,useSRGBBuffers:[!1],generateDepthBuffer:!1,generateStencilBuffer:!1,label:""},sizeIsPercentage:!1},s=this._frameGraph.createRenderTargetTexture(this._circleOfConfusion.name,r);this._circleOfConfusion.sourceTexture=this.sourceTexture,this._circleOfConfusion.depthTexture=this.depthTexture,this._circleOfConfusion.depthSamplingMode=this.depthSamplingMode,this._circleOfConfusion.camera=this.camera,this._circleOfConfusion.destinationTexture=s,this._circleOfConfusion.record(!0),r.options.formats=[5];const n=[];for(let i=0;i{e.copyTexture(this.sourceTexture)}))}dispose(){this._circleOfConfusion.dispose();for(let e=0;ethis.destination.isConnected?this.destination:this.source,this._frameGraphTask=new M_(this.name,t,i.getEngine(),r,s)}_createTask(e,t){const i=this._frameGraphTask.sourceSamplingMode,r=this._frameGraphTask.depthSamplingMode,s=this._frameGraphTask.depthOfField.focalLength,n=this._frameGraphTask.depthOfField.fStop,o=this._frameGraphTask.depthOfField.focusDistance,a=this._frameGraphTask.depthOfField.lensSize;this._frameGraphTask.dispose(),this._frameGraphTask=new M_(this.name,this._frameGraph,this._scene.getEngine(),e,t),this._frameGraphTask.sourceSamplingMode=i,this._frameGraphTask.depthSamplingMode=r,this._frameGraphTask.depthOfField.focalLength=s,this._frameGraphTask.depthOfField.fStop=n,this._frameGraphTask.depthOfField.focusDistance=o,this._frameGraphTask.depthOfField.lensSize=a,this._additionalConstructionParameters=[e,t]}get blurLevel(){return this._frameGraphTask.depthOfField.blurLevel}set blurLevel(e){this._createTask(e,this._frameGraphTask.hdr)}get hdr(){return this._frameGraphTask.hdr}set hdr(e){this._createTask(this._frameGraphTask.depthOfField.blurLevel,e)}get sourceSamplingMode(){return this._frameGraphTask.sourceSamplingMode}set sourceSamplingMode(e){this._frameGraphTask.sourceSamplingMode=e}get depthSamplingMode(){return this._frameGraphTask.depthSamplingMode}set depthSamplingMode(e){this._frameGraphTask.depthSamplingMode=e}get focalLength(){return this._frameGraphTask.depthOfField.focalLength}set focalLength(e){this._frameGraphTask.depthOfField.focalLength=e}get fStop(){return this._frameGraphTask.depthOfField.fStop}set fStop(e){this._frameGraphTask.depthOfField.fStop=e}get focusDistance(){return this._frameGraphTask.depthOfField.focusDistance}set focusDistance(e){this._frameGraphTask.depthOfField.focusDistance=e}get lensSize(){return this._frameGraphTask.depthOfField.lensSize}set lensSize(e){this._frameGraphTask.depthOfField.lensSize=e}getClassName(){return"NodeRenderGraphDepthOfFieldPostProcessBlock"}get source(){return this._inputs[0]}get geomViewDepth(){return this._inputs[1]}get destination(){return this._inputs[2]}get camera(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this.output.value=this._frameGraphTask.outputTexture;const t=this.source.connectedPoint;t&&(this._frameGraphTask.sourceTexture=t.value);const i=this.geomViewDepth.connectedPoint;i&&(this._frameGraphTask.depthTexture=i.value);const r=this.destination.connectedPoint;r&&(this._frameGraphTask.destinationTexture=r.value);const s=this.camera.connectedPoint;s&&(this._frameGraphTask.camera=s.value)}_dumpPropertiesCode(){const e=[];return e.push(`${this._codeVariableName}.lensSize = ${this.lensSize};`),e.push(`${this._codeVariableName}.fStop = ${this.fStop};`),e.push(`${this._codeVariableName}.focusDistance = ${this.focusDistance};`),e.push(`${this._codeVariableName}.focalLength = ${this.focalLength};`),e.push(`${this._codeVariableName}.sourceSamplingMode = ${this.sourceSamplingMode};`),e.push(`${this._codeVariableName}.depthSamplingMode = ${this.depthSamplingMode};`),super._dumpPropertiesCode()+e.join("\n")}serialize(){const e=super.serialize();return e.lensSize=this.lensSize,e.fStop=this.fStop,e.focusDistance=this.focusDistance,e.focalLength=this.focalLength,e.sourceSamplingMode=this.sourceSamplingMode,e.depthSamplingMode=this.depthSamplingMode,e}_deserialize(e){super._deserialize(e),this.lensSize=e.lensSize,this.fStop=e.fStop,this.focusDistance=e.focusDistance,this.focalLength=e.focalLength,this.sourceSamplingMode=e.sourceSamplingMode,this.depthSamplingMode=e.depthSamplingMode}}(0,je.Cg)([t_("Blur level",4,"PROPERTIES",{options:[{label:"Low",value:0},{label:"Medium",value:1},{label:"High",value:2}]})],O_.prototype,"blurLevel",null),(0,je.Cg)([t_("HDR",0,"PROPERTIES")],O_.prototype,"hdr",null),(0,je.Cg)([t_("Source sampling mode",6,"PROPERTIES")],O_.prototype,"sourceSamplingMode",null),(0,je.Cg)([t_("Depth sampling mode",6,"PROPERTIES")],O_.prototype,"depthSamplingMode",null),(0,je.Cg)([t_("Focal length",1,"PROPERTIES")],O_.prototype,"focalLength",null),(0,je.Cg)([t_("F-Stop",1,"PROPERTIES")],O_.prototype,"fStop",null),(0,je.Cg)([t_("Focus distance",1,"PROPERTIES")],O_.prototype,"focusDistance",null),(0,je.Cg)([t_("Lens size",1,"PROPERTIES")],O_.prototype,"lensSize",null),(0,X.Y5)("BABYLON.NodeRenderGraphDepthOfFieldPostProcessBlock",O_);class D_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i){super(e,t,i),this.registerInput("source",Rp.Texture),this.registerInput("destination",Rp.Texture,!0),this.registerOutput("output",Rp.BasedOnInput),this.source.addAcceptedConnectionPointTypes(Rp.TextureAllButBackBuffer),this.destination.addAcceptedConnectionPointTypes(Rp.TextureAll),this.output._typeConnectionSource=()=>this.destination.isConnected?this.destination:this.source,this._frameGraphTask=new g_(this.name,t,new __(e,i.getEngine()))}get sourceSamplingMode(){return this._frameGraphTask.sourceSamplingMode}set sourceSamplingMode(e){this._frameGraphTask.sourceSamplingMode=e}get threshold(){return this._frameGraphTask.postProcess.threshold}set threshold(e){this._frameGraphTask.postProcess.threshold=e}getClassName(){return"NodeRenderGraphExtractHighlightsPostProcessBlock"}get source(){return this._inputs[0]}get destination(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this.output.value=this._frameGraphTask.outputTexture;const t=this.source.connectedPoint;t&&(this._frameGraphTask.sourceTexture=t.value);const i=this.destination.connectedPoint;i&&(this._frameGraphTask.destinationTexture=i.value)}_dumpPropertiesCode(){const e=[];return e.push(`${this._codeVariableName}.threshold = ${this.threshold};`),e.push(`${this._codeVariableName}.sourceSamplingMode = ${this.sourceSamplingMode};`),super._dumpPropertiesCode()+e.join("\n")}serialize(){const e=super.serialize();return e.threshold=this.threshold,e.sourceSamplingMode=this.sourceSamplingMode,e}_deserialize(e){super._deserialize(e),this.threshold=e.threshold,this.sourceSamplingMode=e.sourceSamplingMode}}(0,je.Cg)([t_("Source sampling mode",6,"PROPERTIES")],D_.prototype,"sourceSamplingMode",null),(0,je.Cg)([t_("Threshold",1,"PROPERTIES",{min:0,max:1})],D_.prototype,"threshold",null),(0,X.Y5)("BABYLON.NodeRenderGraphExtractHighlightsPostProcessBlock",D_);class w_ extends kp{constructor(e,t,i){super(e,t),this._scene=i,this.outputObjectList={meshes:[],particleSystems:[]}}record(){if(void 0===this.objectList||void 0===this.camera)throw new Error(`FrameGraphCullObjectsTask ${this.name}: objectList and camera are required`);const e=this._frameGraph.addCullPass(this.name);e.setObjectList(this.outputObjectList),e.setExecuteFunc((e=>{this.outputObjectList.meshes=[],this.camera._updateFrustumPlanes();const t=this.camera._frustumPlanes,i=this.objectList.meshes||this._scene.meshes;for(let e=0;e0&&r.layerMask&this.camera.layerMask&&(this._scene.skipFrustumClipping||r.alwaysSelectAsActiveMesh||r.isInFrustum(t))&&this.outputObjectList.meshes.push(r)}}));const t=this._frameGraph.addCullPass(this.name+"_disabled",!0);t.setObjectList(this.outputObjectList),t.setExecuteFunc((e=>{this.outputObjectList.meshes=this.objectList.meshes,this.outputObjectList.particleSystems=this.objectList.particleSystems}))}}class N_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i){super(e,t,i),this.registerInput("camera",Rp.Camera),this.registerInput("objects",Rp.ObjectList),this.registerOutput("output",Rp.ObjectList),this._frameGraphTask=new w_(this.name,t,i)}getClassName(){return"NodeRenderGraphCullObjectsBlock"}get camera(){return this._inputs[0]}get objects(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this.output.value=this._frameGraphTask.outputObjectList;const t=this.camera.connectedPoint;t&&(this._frameGraphTask.camera=t.value);const i=this.objects.connectedPoint;i&&(this._frameGraphTask.objectList=i.value)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+[].join("\n")}serialize(){return super.serialize()}_deserialize(e){super._deserialize(e)}}(0,X.Y5)("BABYLON.NodeRenderGraphCullObjectsBlock",N_);var F_=i(25266);const L_=[new H.ov(0,0,0,0),new H.ov(1,1,1,1),new H.ov(1e8,1e8,1e8,1e8)];class B_ extends kp{get camera(){return this._camera}set camera(e){this._camera=e,this._renderer.activeCamera=this.camera}get objectRenderer(){return this._renderer}get name(){return this._name}set name(e){this._name=e,this._renderer&&(this._renderer.name=e)}constructor(e,t,i,r){super(e,t),this.depthTest=!0,this.depthWrite=!0,this.size={width:100,height:100},this.sizeIsPercentage=!0,this.samples=1,this.textureDescriptions=[],this._scene=i,this._engine=this._scene.getEngine(),this._renderer=new F_.P(e,i,r),this._renderer.renderSprites=!1,this._renderer.renderParticles=!1,this._renderer.onBeforeRenderingManagerRenderObservable.add((()=>{this._renderer.options.doNotChangeAspectRatio||i.updateTransformMatrix(!0)})),this.name=e,this._clearAttachmentsLayout=new Map,this._allAttachmentsLayout=[],this.outputDepthTexture=this._frameGraph.createDanglingHandle(),this.geometryViewDepthTexture=this._frameGraph.createDanglingHandle(),this.geometryScreenDepthTexture=this._frameGraph.createDanglingHandle(),this.geometryViewNormalTexture=this._frameGraph.createDanglingHandle(),this.geometryWorldNormalTexture=this._frameGraph.createDanglingHandle(),this.geometryLocalPositionTexture=this._frameGraph.createDanglingHandle(),this.geometryWorldPositionTexture=this._frameGraph.createDanglingHandle(),this.geometryAlbedoTexture=this._frameGraph.createDanglingHandle(),this.geometryReflectivityTexture=this._frameGraph.createDanglingHandle(),this.geometryVelocityTexture=this._frameGraph.createDanglingHandle(),this.geometryLinearVelocityTexture=this._frameGraph.createDanglingHandle()}get excludedSkinnedMeshFromVelocityTexture(){return Bn.GetConfiguration(this._renderer.renderPassId).excludedSkinnedMesh}isReady(){return this._renderer.isReadyForRendering(this._textureWidth,this._textureHeight)}record(){if(0===this.textureDescriptions.length||void 0===this.objectList)throw new Error(`FrameGraphGeometryRendererTask ${this.name}: object list and at least one geometry texture description must be provided`);const e=this._createMultiRenderTargetTexture(),t=this._checkDepthTextureCompatibility();this._buildClearAttachmentsLayout(),this._registerForRenderPassId(this._renderer.renderPassId);const i=this._frameGraph.getTextureDescription(e);this._textureWidth=i.size.width,this._textureHeight=i.size.height,Bn.MarkAsDirty(this._renderer.renderPassId,this.objectList.meshes||this._scene.meshes);const r=this._frameGraph.addRenderPass(this.name);r.setRenderTarget(e);let s=e+1;for(let e=0;ee.type===t.type));switch(Bn.GeometryTextureDescriptions[i].type){case 5:this._frameGraph.resolveDanglingHandle(this.geometryViewDepthTexture,s++);break;case 10:this._frameGraph.resolveDanglingHandle(this.geometryScreenDepthTexture,s++);break;case 6:this._frameGraph.resolveDanglingHandle(this.geometryViewNormalTexture,s++);break;case 8:this._frameGraph.resolveDanglingHandle(this.geometryWorldNormalTexture,s++);break;case 9:this._frameGraph.resolveDanglingHandle(this.geometryLocalPositionTexture,s++);break;case 1:this._frameGraph.resolveDanglingHandle(this.geometryWorldPositionTexture,s++);break;case 12:this._frameGraph.resolveDanglingHandle(this.geometryAlbedoTexture,s++);break;case 3:this._frameGraph.resolveDanglingHandle(this.geometryReflectivityTexture,s++);break;case 2:this._frameGraph.resolveDanglingHandle(this.geometryVelocityTexture,s++);break;case 11:this._frameGraph.resolveDanglingHandle(this.geometryLinearVelocityTexture,s++)}}void 0!==this.depthTexture&&r.setRenderTargetDepth(this.depthTexture),r.setExecuteFunc((e=>{this._renderer.renderList=this.objectList.meshes,this._renderer.particleSystemList=this.objectList.particleSystems,e.setDepthStates(this.depthTest&&t,this.depthWrite&&t),this._clearAttachmentsLayout.forEach(((t,i)=>{e.clearColorAttachments(L_[i],t)})),e.bindAttachments(this._allAttachmentsLayout),e.render(this._renderer,this._textureWidth,this._textureHeight)}))}dispose(){Bn.DeleteConfiguration(this._renderer.renderPassId),this._renderer.dispose(),super.dispose()}_createMultiRenderTargetTexture(){const e=[],t=[],i=[],r=[];for(let s=0;se.type===n.type));if(-1===o)throw new Error(`FrameGraphGeometryRendererTask ${this.name}: unknown texture type ${n.type}`);e[s]=n.textureType,t[s]=n.textureFormat,i[s]=Bn.GeometryTextureDescriptions[o].name,r[s]=!1}return this._frameGraph.createRenderTargetTexture(this.name,{size:this.size,sizeIsPercentage:this.sizeIsPercentage,options:{createMipMaps:!1,generateDepthBuffer:!1,textureCount:this.textureDescriptions.length,samples:this.samples,types:e,formats:t,useSRGBBuffers:r,labels:i}},!0)}_checkDepthTextureCompatibility(){let e=!1;if(void 0!==this.depthTexture){if(this.depthTexture===Fp)throw new Error(`FrameGraphGeometryRendererTask ${this.name}: the depth/stencil back buffer is not allowed as a depth texture`);if(this._frameGraph.getTextureDescription(this.depthTexture).options.samples!==this.samples)throw new Error(`FrameGraphGeometryRendererTask ${this.name}: the depth texture and the output texture must have the same number of samples`);this._frameGraph.resolveDanglingHandle(this.outputDepthTexture,this.depthTexture),e=!0}return e}_buildClearAttachmentsLayout(){const e=new Map,t=[];for(let i=0;ie.type===r.type)),n=Bn.GeometryTextureDescriptions[s];let o=e.get(n.clearType);if(void 0===o){o=[],e.set(n.clearType,o);for(let e=0;e{e.push(t===n.clearType)})),t.push(!0)}this._clearAttachmentsLayout=new Map,e.forEach(((e,t)=>{this._clearAttachmentsLayout.set(t,this._engine.buildTextureLayout(e))})),this._allAttachmentsLayout=this._engine.buildTextureLayout(t)}_registerForRenderPassId(e){const t=Bn.CreateConfiguration(e);for(let e=0;ee.type===i.type)),s=Bn.GeometryTextureDescriptions[r];t.defines[s.defineIndex]=e}}}class V_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i,r=!0){super(e,t,i),this.viewDepthFormat=6,this.viewDepthType=2,this.screenDepthFormat=6,this.screenDepthType=2,this.viewNormalFormat=5,this.viewNormalType=0,this.worldNormalFormat=5,this.worldNormalType=0,this.localPositionFormat=5,this.localPositionType=2,this.worldPositionFormat=5,this.worldPositionType=2,this.albedoFormat=5,this.albedoType=0,this.reflectivityFormat=5,this.reflectivityType=0,this.velocityFormat=5,this.velocityType=0,this.linearVelocityFormat=5,this.linearVelocityType=0,this._additionalConstructionParameters=[r],this.registerInput("depth",Rp.TextureBackBufferDepthStencilAttachment,!0),this.registerInput("camera",Rp.Camera),this.registerInput("objects",Rp.ObjectList),this.registerOutput("outputDepth",Rp.BasedOnInput),this.registerOutput("geomViewDepth",Rp.TextureViewDepth),this.registerOutput("geomScreenDepth",Rp.TextureScreenDepth),this.registerOutput("geomViewNormal",Rp.TextureViewNormal),this.registerOutput("geomWorldNormal",Rp.TextureViewNormal),this.registerOutput("geomLocalPosition",Rp.TextureLocalPosition),this.registerOutput("geomWorldPosition",Rp.TextureWorldPosition),this.registerOutput("geomAlbedo",Rp.TextureAlbedo),this.registerOutput("geomReflectivity",Rp.TextureReflectivity),this.registerOutput("geomVelocity",Rp.TextureVelocity),this.registerOutput("geomLinearVelocity",Rp.TextureLinearVelocity),this.depth.addAcceptedConnectionPointTypes(Rp.TextureDepthStencilAttachment),this.outputDepth._typeConnectionSource=this.depth,this._frameGraphTask=new B_(this.name,t,i,{doNotChangeAspectRatio:r})}get depthTest(){return this._frameGraphTask.depthTest}set depthTest(e){this._frameGraphTask.depthTest=e}get depthWrite(){return this._frameGraphTask.depthWrite}set depthWrite(e){this._frameGraphTask.depthWrite=e}get doNotChangeAspectRatio(){return this._frameGraphTask.objectRenderer.options.doNotChangeAspectRatio}set doNotChangeAspectRatio(e){this._frameGraphTask.dispose(),this._frameGraphTask=new B_(this.name,this._frameGraph,this._scene,{doNotChangeAspectRatio:e}),this._additionalConstructionParameters=[e]}get width(){return this._frameGraphTask.size.width}set width(e){this._frameGraphTask.size.width=e}get height(){return this._frameGraphTask.size.height}set height(e){this._frameGraphTask.size.height=e}get sizeInPercentage(){return this._frameGraphTask.sizeIsPercentage}set sizeInPercentage(e){this._frameGraphTask.sizeIsPercentage=e}get samples(){return this._frameGraphTask.samples}set samples(e){this._frameGraphTask.samples=e}getClassName(){return"NodeRenderGraphGeometryRendererBlock"}get depth(){return this._inputs[0]}get camera(){return this._inputs[1]}get objects(){return this._inputs[2]}get outputDepth(){return this._outputs[0]}get geomViewDepth(){return this._outputs[1]}get geomScreenDepth(){return this._outputs[2]}get geomViewNormal(){return this._outputs[3]}get geomWorldNormal(){return this._outputs[4]}get geomLocalPosition(){return this._outputs[5]}get geomWorldPosition(){return this._outputs[6]}get geomAlbedo(){return this._outputs[7]}get geomReflectivity(){return this._outputs[8]}get geomVelocity(){return this._outputs[9]}get geomLinearVelocity(){return this._outputs[10]}_buildBlock(e){super._buildBlock(e);const t=[this.geomViewDepth.isConnected,this.geomScreenDepth.isConnected,this.geomViewNormal.isConnected,this.geomWorldNormal.isConnected,this.geomLocalPosition.isConnected,this.geomWorldPosition.isConnected,this.geomAlbedo.isConnected,this.geomReflectivity.isConnected,this.geomVelocity.isConnected,this.geomLinearVelocity.isConnected];if(t.every((e=>!e)))throw new Error("NodeRenderGraphGeometryRendererBlock: At least one output geometry buffer must be connected");this._frameGraphTask.name=this.name,this.outputDepth.value=this._frameGraphTask.outputDepthTexture,this.geomViewDepth.value=this._frameGraphTask.geometryViewDepthTexture,this.geomScreenDepth.value=this._frameGraphTask.geometryScreenDepthTexture,this.geomViewNormal.value=this._frameGraphTask.geometryViewNormalTexture,this.geomWorldNormal.value=this._frameGraphTask.geometryWorldNormalTexture,this.geomLocalPosition.value=this._frameGraphTask.geometryLocalPositionTexture,this.geomWorldPosition.value=this._frameGraphTask.geometryWorldPositionTexture,this.geomAlbedo.value=this._frameGraphTask.geometryAlbedoTexture,this.geomReflectivity.value=this._frameGraphTask.geometryReflectivityTexture,this.geomVelocity.value=this._frameGraphTask.geometryVelocityTexture,this.geomLinearVelocity.value=this._frameGraphTask.geometryLinearVelocityTexture;const i=this.depth.connectedPoint;i&&(this._frameGraphTask.depthTexture=i.value);const r=this.camera.connectedPoint;r&&(this._frameGraphTask.camera=r.value);const s=this.objects.connectedPoint;s&&(this._frameGraphTask.objectList=s.value),this._frameGraphTask.textureDescriptions=[];const n=[this.viewDepthFormat,this.screenDepthFormat,this.viewNormalFormat,this.worldNormalFormat,this.localPositionFormat,this.worldPositionFormat,this.albedoFormat,this.reflectivityFormat,this.velocityFormat,this.linearVelocityFormat],o=[this.viewDepthType,this.screenDepthType,this.viewNormalType,this.worldNormalType,this.localPositionType,this.worldPositionType,this.albedoType,this.reflectivityType,this.velocityType,this.linearVelocityType],a=[5,10,6,8,9,1,12,3,2,11];for(let e=0;e{this._renderer.options.doNotChangeAspectRatio||i.updateTransformMatrix(!0)})),this.outputTexture=this._frameGraph.createDanglingHandle(),this.outputDepthTexture=this._frameGraph.createDanglingHandle()}isReady(){return this._renderer.isReadyForRendering(this._textureWidth,this._textureHeight)}record(e=!1,t){if(void 0===this.destinationTexture||void 0===this.objectList)throw new Error(`FrameGraphObjectRendererTask ${this.name}: destinationTexture and objectList are required`);const i=this._frameGraph.getTextureDescription(this.destinationTexture);let r=!1;if(void 0!==this.depthTexture){if(this.depthTexture===Fp&&this.destinationTexture!==Np)throw new Error(`FrameGraphObjectRendererTask ${this.name}: the back buffer color texture is the only color texture allowed when the depth is the back buffer depth/stencil`);if(this.depthTexture!==Fp&&this.destinationTexture===Np)throw new Error(`FrameGraphObjectRendererTask ${this.name}: the back buffer depth/stencil texture is the only depth texture allowed when the destination is the back buffer color`);if(this._frameGraph.getTextureDescription(this.depthTexture).options.samples!==i.options.samples)throw new Error(`FrameGraphObjectRendererTask ${this.name}: the depth texture and the output texture must have the same number of samples`);r=!0}this._frameGraph.resolveDanglingHandle(this.outputTexture,this.destinationTexture),void 0!==this.depthTexture&&this._frameGraph.resolveDanglingHandle(this.outputDepthTexture,this.depthTexture),this._textureWidth=i.size.width,this._textureHeight=i.size.height;const s=this._frameGraph.addRenderPass(this.name);if(s.setRenderTarget(this.destinationTexture),void 0!==this.depthTexture&&s.setRenderTargetDepth(this.depthTexture),s.setExecuteFunc((e=>{this._renderer.renderList=this.objectList.meshes,this._renderer.particleSystemList=this.objectList.particleSystems,e.setDepthStates(this.depthTest&&r,this.depthWrite&&r),e.render(this._renderer,this._textureWidth,this._textureHeight),t?.(e)})),void 0!==this.dependencies)for(const e of this.dependencies)s.useTexture(e);if(!e){const e=this._frameGraph.addRenderPass(this.name+"_disabled",!0);if(e.setRenderTarget(this.destinationTexture),void 0!==this.depthTexture&&e.setRenderTargetDepth(this.depthTexture),e.setExecuteFunc((e=>{})),void 0!==this.dependencies)for(const t of this.dependencies)e.useTexture(t)}}dispose(){this._renderer.dispose(),super.dispose()}}class U_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i){super(e,t,i),this.registerInput("destination",Rp.Texture),this.registerInput("depth",Rp.TextureBackBufferDepthStencilAttachment,!0),this.registerInput("camera",Rp.Camera),this.registerInput("objects",Rp.ObjectList),this.registerInput("dependencies",Rp.Texture,!0),this.registerOutput("output",Rp.BasedOnInput),this.registerOutput("outputDepth",Rp.BasedOnInput),this.destination.addAcceptedConnectionPointTypes(Rp.TextureAllButBackBufferDepthStencil),this.depth.addAcceptedConnectionPointTypes(Rp.TextureDepthStencilAttachment),this.dependencies.addAcceptedConnectionPointTypes(Rp.TextureAllButBackBuffer),this.output._typeConnectionSource=this.destination,this.outputDepth._typeConnectionSource=this.depth}get depthTest(){return this._frameGraphTask.depthTest}set depthTest(e){this._frameGraphTask.depthTest=e}get depthWrite(){return this._frameGraphTask.depthWrite}set depthWrite(e){this._frameGraphTask.depthWrite=e}getClassName(){return"NodeRenderGraphBaseObjectRendererBlock"}get destination(){return this._inputs[0]}get depth(){return this._inputs[1]}get camera(){return this._inputs[2]}get objects(){return this._inputs[3]}get dependencies(){return this._inputs[4]}get output(){return this._outputs[0]}get outputDepth(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this.output.value=this._frameGraphTask.outputTexture,this.outputDepth.value=this._frameGraphTask.outputDepthTexture;const t=this.destination.connectedPoint;t&&(this._frameGraphTask.destinationTexture=t.value);const i=this.depth.connectedPoint;i&&(this._frameGraphTask.depthTexture=i.value);const r=this.camera.connectedPoint;r&&(this._frameGraphTask.camera=r.value);const s=this.objects.connectedPoint;s&&(this._frameGraphTask.objectList=s.value),this._frameGraphTask.dependencies=[];const n=this.dependencies.connectedPoint;n&&(this._frameGraphTask.dependencies[0]=n.value)}_dumpPropertiesCode(){const e=[];return e.push(`${this._codeVariableName}.depthTest = ${this.depthTest};`),e.push(`${this._codeVariableName}.depthWrite = ${this.depthWrite};`),super._dumpPropertiesCode()+e.join("\n")}serialize(){const e=super.serialize();return e.depthTest=this.depthTest,e.depthWrite=this.depthWrite,e}_deserialize(e){super._deserialize(e),this.depthTest=e.depthTest,this.depthWrite=e.depthWrite}}(0,je.Cg)([t_("Depth test",0,"PROPERTIES")],U_.prototype,"depthTest",null),(0,je.Cg)([t_("Depth write",0,"PROPERTIES")],U_.prototype,"depthWrite",null);class G_ extends U_{constructor(e,t,i,r=!0){super(e,t,i),this._additionalConstructionParameters=[r],this._frameGraphTask=new k_(this.name,t,i,{doNotChangeAspectRatio:r})}get doNotChangeAspectRatio(){return this._frameGraphTask.objectRenderer.options.doNotChangeAspectRatio}set doNotChangeAspectRatio(e){this._frameGraphTask.dispose(),this._frameGraphTask=new k_(this.name,this._frameGraph,this._scene,{doNotChangeAspectRatio:e}),this._additionalConstructionParameters=[e]}getClassName(){return"NodeRenderGraphObjectRendererBlock"}}(0,je.Cg)([t_("Do not change aspect ratio",0,"PROPERTIES")],G_.prototype,"doNotChangeAspectRatio",null),(0,X.Y5)("BABYLON.NodeRenderGraphObjectRendererBlock",G_);class z_{constructor(e,t=2,i=3,r=1,s=1){this._curIndex=0,this._sequence=[],this._numSamples=0,this.x=0,this.y=0,this._width=r,this._height=s,this._baseX=t,this._baseY=i,this._generateSequence(e),this.next()}regenerate(e){this._generateSequence(e),this.next()}setDimensions(e,t){this._width=e,this._height=t}next(){this.x=this._sequence[this._curIndex]/this._width,this.y=this._sequence[this._curIndex+1]/this._height,this._curIndex+=2,this._curIndex>=2*this._numSamples&&(this._curIndex=0)}_generateSequence(e){this._sequence=[],this._curIndex=0,this._numSamples=e;for(let t=1;t<=e;++t)this._sequence.push(this._halton(t,this._baseX)-.5,this._halton(t,this._baseY)-.5)}_halton(e,t){let i=1,r=0;for(;e>0;)i/=t,r+=i*(e%t),e=~~(e/t);return r}}class W_ extends Yp.${_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(i.bind(i,88559)))):t.push(Promise.resolve().then(i.bind(i,7672)))}set samples(e){this._samples!==e&&(this._samples=e,this._hs.regenerate(e))}get samples(){return this._samples}get disabled(){return this._disabled}set disabled(e){this._disabled!==e&&(this._disabled=e,this._reset())}get textureWidth(){return this._textureWidth}set textureWidth(e){this._textureWidth!==e&&(this._textureWidth=e,this._reset())}get textureHeight(){return this._textureHeight}set textureHeight(e){this._textureHeight!==e&&(this._textureHeight=e,this._reset())}constructor(e,t=null,i){super({...i,name:e,engine:t||an.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:W_.FragmentUrl,uniforms:W_.Uniforms,samplers:W_.Samplers}),this._samples=8,this.factor=.05,this._disabled=!1,this._textureWidth=0,this._textureHeight=0,this.disableOnCameraMove=!0,this._firstUpdate=!0,this._hs=new z_(this.samples)}_reset(){this._hs.setDimensions(this._textureWidth/2,this._textureHeight/2),this._hs.next(),this._firstUpdate=!0}updateProjectionMatrix(){if(!this.disabled){if(this.camera&&!this.camera.hasMoved)if(this.camera.mode===rt.PERSPECTIVE_CAMERA){const e=this.camera.getProjectionMatrix();e.setRowFromFloats(2,this._hs.x,this._hs.y,e.m[10],e.m[11])}else{const e=this.camera.getProjectionMatrix(!0);e.setRowFromFloats(3,this._hs.x+e.m[12],this._hs.y+e.m[13],e.m[14],e.m[15])}this._hs.next()}}bind(){super.bind(),this.disabled||(this._drawWrapper.effect.setFloat("factor",this.camera?.hasMoved&&this.disableOnCameraMove||this._firstUpdate?1:this.factor),this._firstUpdate=!1)}}W_.FragmentUrl="taa",W_.Uniforms=["factor"],W_.Samplers=["historySampler"];class H_ extends k_{constructor(e,t,i,r){super(e,t,i,r),this.postProcess=new W_(`${e} post-process`,i.getEngine()),this._postProcessDrawWrapper=this.postProcess.drawWrapper}record(){if(void 0===this.destinationTexture||void 0===this.objectList)throw new Error(`FrameGraphTAAObjectRendererTask ${this.name}: destinationTexture and objectList are required`);if(this.destinationTexture===Np||this.depthTexture===Fp)throw new Error(`FrameGraphTAAObjectRendererTask ${this.name}: the back buffer color/depth textures are not allowed. Use regular textures instead.`);const e=this._frameGraph.getTextureDescription(this.destinationTexture);let t=!1;if(void 0!==this.depthTexture){if(this._frameGraph.getTextureDescription(this.depthTexture).options.samples!==e.options.samples)throw new Error(`FrameGraphTAAObjectRendererTask ${this.name}: the depth texture and the output texture must have the same number of samples`);t=!0}this.postProcess.camera=this.camera,this.postProcess.textureWidth=e.size.width,this.postProcess.textureHeight=e.size.height;const i={size:e.size,options:{createMipMaps:!1,generateMipMaps:!1,types:[2],samplingModes:[1],formats:[5],samples:1,useSRGBBuffers:[!1],generateDepthBuffer:!1,generateStencilBuffer:!1,label:""},sizeIsPercentage:!1,isHistoryTexture:!0},r=this._frameGraph.createRenderTargetTexture(`${this.name} history`,i);this._frameGraph.resolveDanglingHandle(this.outputTexture,r),void 0!==this.depthTexture&&this._frameGraph.resolveDanglingHandle(this.outputDepthTexture,this.depthTexture),this._textureWidth=e.size.width,this._textureHeight=e.size.height;const s=this._frameGraph.addRenderPass(this.name);s.setRenderTarget(this.destinationTexture),void 0!==this.depthTexture&&s.setRenderTargetDepth(this.depthTexture),s.setExecuteFunc((e=>{this._renderer.renderList=this.objectList.meshes,this._renderer.particleSystemList=this.objectList.particleSystems,this.postProcess.updateProjectionMatrix(),e.setDepthStates(this.depthTest&&t,this.depthWrite&&t),this.postProcess.disabled||(this._scene.activeCamera=this.camera,this._scene.setTransformMatrix(this.camera.getViewMatrix(),this.camera.getProjectionMatrix())),e.render(this._renderer,this._textureWidth,this._textureHeight),this._scene.activeCamera=null,e.bindRenderTarget(r,"frame graph - TAA merge with history texture"),this.postProcess.disabled?e.copyTexture(this.destinationTexture):e.applyFullScreenEffect(this._postProcessDrawWrapper,(()=>{this.postProcess.bind(),e.bindTextureHandle(this._postProcessDrawWrapper.effect,"textureSampler",this.destinationTexture),e.bindTextureHandle(this._postProcessDrawWrapper.effect,"historySampler",r)}))}));const n=this._frameGraph.addRenderPass(this.name+"_disabled",!0);if(n.setRenderTarget(this.outputTexture),void 0!==this.depthTexture&&n.setRenderTargetDepth(this.depthTexture),n.setExecuteFunc((e=>{e.copyTexture(this.destinationTexture)})),void 0!==this.dependencies)for(const e of this.dependencies)s.useTexture(e),n.useTexture(e)}}class X_ extends U_{get task(){return this._frameGraphTask}constructor(e,t,i,r=!0){super(e,t,i),this._additionalConstructionParameters=[r],this._frameGraphTask=new H_(this.name,t,i,{doNotChangeAspectRatio:r})}get doNotChangeAspectRatio(){return this._frameGraphTask.objectRenderer.options.doNotChangeAspectRatio}set doNotChangeAspectRatio(e){this._frameGraphTask.dispose(),this._frameGraphTask=new H_(this.name,this._frameGraph,this._scene,{doNotChangeAspectRatio:e}),this._additionalConstructionParameters=[e]}get samples(){return this._frameGraphTask.postProcess.samples}set samples(e){this._frameGraphTask.postProcess.samples=e}get factor(){return this._frameGraphTask.postProcess.factor}set factor(e){this._frameGraphTask.postProcess.factor=e}get disableOnCameraMove(){return this._frameGraphTask.postProcess.disableOnCameraMove}set disableOnCameraMove(e){this._frameGraphTask.postProcess.disableOnCameraMove=e}get disableTAA(){return this._frameGraphTask.postProcess.disabled}set disableTAA(e){this._frameGraphTask.postProcess.disabled=e}getClassName(){return"NodeRenderGraphTAAObjectRendererBlock"}_dumpPropertiesCode(){const e=[];return e.push(`${this._codeVariableName}.samples = ${this.samples};`),e.push(`${this._codeVariableName}.factor = ${this.factor};`),e.push(`${this._codeVariableName}.disableOnCameraMove = ${this.disableOnCameraMove};`),e.push(`${this._codeVariableName}.disableTAA = ${this.disableTAA};`),super._dumpPropertiesCode()+e.join("\n")}serialize(){const e=super.serialize();return e.samples=this.samples,e.factor=this.factor,e.disableOnCameraMove=this.disableOnCameraMove,e.disableTAA=this.disableTAA,e}_deserialize(e){super._deserialize(e),this.samples=e.samples,this.factor=e.factor,this.disableOnCameraMove=e.disableOnCameraMove,this.disableTAA=e.disableTAA}}(0,je.Cg)([t_("Do not change aspect ratio",0,"PROPERTIES")],X_.prototype,"doNotChangeAspectRatio",null),(0,je.Cg)([t_("Samples",2,"TEMPORAL ANTI-ALIASING")],X_.prototype,"samples",null),(0,je.Cg)([t_("Factor",1,"TEMPORAL ANTI-ALIASING")],X_.prototype,"factor",null),(0,je.Cg)([t_("Disable on camera move",0,"TEMPORAL ANTI-ALIASING")],X_.prototype,"disableOnCameraMove",null),(0,je.Cg)([t_("Disable TAA",0,"TEMPORAL ANTI-ALIASING")],X_.prototype,"disableTAA",null),(0,X.Y5)("BABYLON.NodeRenderGraphTAAObjectRendererBlock",X_);class q_ extends wp{get endpoints(){return this._endpoints}constructor(e,t,i){super(e,t,i),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",Rp.AutoDetect)}getClassName(){return"NodeRenderGraphTeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const r of this.endpoints)-1===t.indexOf(r)&&(i+=r._dumpCode(e,t));return i}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(const t of this.endpoints)if(t.isAnAncestorOfType(e))return!0;return!1}isAnAncestorOf(e){for(const t of this.endpoints){if(t===e)return!0;if(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);-1!==t&&(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=[]}}(0,X.Y5)("BABYLON.NodeRenderGraphTeleportInBlock",q_);class Y_ extends wp{constructor(e,t,i){super(e,t,i),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",Rp.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"NodeRenderGraphTeleportOutBlock"}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&&-1===t.indexOf(this.entryPoint)&&(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});\n`),e}serialize(){const e=super.serialize();return e.entryPoint=this.entryPoint?.uniqueId??"",e}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}}(0,X.Y5)("BABYLON.NodeRenderGraphTeleportOutBlock",Y_);class K_ extends kp{constructor(e,t){super(e,t),this.outputTexture=this._frameGraph.createDanglingHandle()}record(){if(void 0===this.sourceTexture||void 0===this.destinationTexture)throw new Error(`FrameGraphCopyToTextureTask "${this.name}": sourceTexture and destinationTexture are required`);this._frameGraph.resolveDanglingHandle(this.outputTexture,this.destinationTexture);const e=this._frameGraph.addRenderPass(this.name);e.useTexture(this.sourceTexture),e.setRenderTarget(this.outputTexture),e.setExecuteFunc((e=>{e.copyTexture(this.sourceTexture)}));const t=this._frameGraph.addRenderPass(this.name+"_disabled",!0);t.setRenderTarget(this.outputTexture),t.setExecuteFunc((e=>{}))}}class j_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i){super(e,t,i),this.registerInput("source",Rp.Texture),this.registerInput("destination",Rp.Texture),this.registerOutput("output",Rp.BasedOnInput),this.source.addAcceptedConnectionPointTypes(Rp.TextureAllButBackBuffer),this.destination.addAcceptedConnectionPointTypes(Rp.TextureAll),this.output._typeConnectionSource=this.destination,this._frameGraphTask=new K_(e,t)}getClassName(){return"NodeRenderGraphCopyTextureBlock"}get source(){return this._inputs[0]}get destination(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this.output.value=this._frameGraphTask.outputTexture;const t=this.source.connectedPoint;t&&(this._frameGraphTask.sourceTexture=t.value);const i=this.destination.connectedPoint;i&&(this._frameGraphTask.destinationTexture=i.value)}}(0,X.Y5)("BABYLON.NodeRenderGraphCopyTextureBlock",j_);class $_ extends kp{constructor(e,t){super(e,t),this.outputTexture=this._frameGraph.createDanglingHandle()}record(){if(void 0===this.destinationTexture)throw new Error(`FrameGraphGenerateMipMapsTask ${this.name}: destinationTexture is required`);if(this._frameGraph.resolveDanglingHandle(this.outputTexture,this.destinationTexture),!this._frameGraph.getTextureDescription(this.destinationTexture).options.createMipMaps)throw new Error(`FrameGraphGenerateMipMapsTask ${this.name}: destinationTexture must have createMipMaps set to true`);const e=this._frameGraph.addRenderPass(this.name);e.setRenderTarget(this.outputTexture),e.setExecuteFunc((e=>{e.generateMipMaps()}));const t=this._frameGraph.addRenderPass(this.name+"_disabled",!0);t.setRenderTarget(this.outputTexture),t.setExecuteFunc((e=>{}))}}class Q_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i){super(e,t,i),this.registerInput("texture",Rp.Texture),this.registerOutput("output",Rp.BasedOnInput),this.texture.addAcceptedConnectionPointTypes(Rp.TextureAllButBackBuffer),this.output._typeConnectionSource=this.texture,this._frameGraphTask=new $_(e,t)}getClassName(){return"NodeRenderGraphGenerateMipmapsBlock"}get texture(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this._propagateInputValueToOutput(this.texture,this.output);const t=this.texture.connectedPoint;t&&(this._frameGraphTask.destinationTexture=t.value)}}(0,X.Y5)("BABYLON.NodeRenderGraphGenerateMipmapsBlock",Q_);class Z_{}class J_ extends Go{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=H.v9.Gray(),i=Bo.DefaultUtilityLayer,r=null,s=1,n=H.v9.Yellow(),o=H.v9.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new z.cP,this.uniformScaling=!1,this.sensitivity=1,this.dragScale=1,this.incrementalSnap=!1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._tmpVector=new W.Pq(0,0,0),this._incrementalStartupValue=W.Pq.Zero(),this._parent=r,this._coloredMaterial=new Un("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new H.v9(.1,.1,.1)),this._hoverMaterial=new Un("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=n,this._disableMaterial=new Un("",i.utilityLayerScene),this._disableMaterial.diffuseColor=o,this._disableMaterial.alpha=.4,this._gizmoMesh=new Yt("axis",i.utilityLayerScene);const{arrowMesh:a,arrowTail:l}=this._createGizmoMesh(this._gizmoMesh,s),h=this._createGizmoMesh(this._gizmoMesh,s+4,!0);this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,Go.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3);const c=a.position.clone(),u=l.position.clone(),d=l.scaling.clone(),f=e=>{const t=e*(3/this._rootMesh.scaling.length())*6;a.position.z+=t/3.5,l.scaling.y+=t,this.dragScale=l.scaling.y,l.position.z=a.position.z/2},p=()=>{a.position.set(c.x,c.y,c.z),l.position.set(u.x,u.y,u.z),l.scaling.set(d.x,d.y,d.z),this.dragScale=l.scaling.y,this._dragging=!1};this.dragBehavior=new Ji({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior);let _=0,m=0;const g={snapDistance:0};this.dragBehavior.onDragObservable.add((t=>{if(this.attachedNode){const i=this.sensitivity*t.dragDistance*(3*this.scaleRatio/this._rootMesh.scaling.length()),r=this._tmpVector;let s=!1,n=0;if(this.uniformScaling?r.setAll(.57735):r.copyFrom(e),0==this.snapDistance)r.scaleToRef(i,r);else{_+=i,m+=i;const e=this.incrementalSnap?m:_;Math.abs(e)>this.snapDistance?(n=Math.floor(Math.abs(e)/this.snapDistance),e<0&&(n*=-1),_%=this.snapDistance,r.scaleToRef(this.snapDistance*n,r),s=!0):r.scaleInPlace(0)}r.addInPlaceFromFloats(1,1,1),r.x=Math.abs(r.x)0&&this.incrementalSnap?(this.attachedNode.getWorldMatrix().decompose(void 0,W.AA.Quaternion[0],W.AA.Vector3[2],Go.PreserveScaling?o:void 0),r.addInPlace(this._incrementalStartupValue),r.addInPlaceFromFloats(-1,-1,-1),r.x=Math.abs(r.x)*(this._incrementalStartupValue.x>0?1:-1),r.y=Math.abs(r.y)*(this._incrementalStartupValue.y>0?1:-1),r.z=Math.abs(r.z)*(this._incrementalStartupValue.z>0?1:-1),W.uq.ComposeToRef(r,W.AA.Quaternion[0],W.AA.Vector3[2],W.AA.Matrix[1])):(W.uq.ScalingToRef(r.x,r.y,r.z,W.AA.Matrix[2]),W.AA.Matrix[2].multiplyToRef(this.attachedNode.getWorldMatrix(),W.AA.Matrix[1])),W.AA.Matrix[1].decompose(W.AA.Vector3[1],void 0,void 0,Go.PreserveScaling?o:void 0);const a=1e5;Math.abs(W.AA.Vector3[1].x){this._dragging=!0;const e=this.attachedNode._isMesh?this.attachedNode:void 0;this.attachedNode?.getWorldMatrix().decompose(this._incrementalStartupValue,void 0,void 0,Go.PreserveScaling?e:void 0),_=0,m=0})),this.dragBehavior.onDragObservable.add((e=>f(e.dragDistance))),this.dragBehavior.onDragEndObservable.add(p),r?.uniformScaleGizmo?.dragBehavior?.onDragObservable?.add((e=>f(e.delta.y))),r?.uniformScaleGizmo?.dragBehavior?.onDragEndObservable?.add(p);const v={gizmoMeshes:[a,l],colliderMeshes:[h.arrowMesh,h.arrowTail],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,v),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(this._customMeshSet)return;let t=this._parent?.getAxisCache(this._gizmoMesh);if(this._isHovered=!(!t||-1==t.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),t=this._parent?.getAxisCache(this._rootMesh),this._isHovered||(this._isHovered=!(!t||-1==t.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh))),!this._parent){const e=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(v.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(v.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}));const x=i._getSharedGizmoLight();x.includedOnlyMeshes=x.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes())}_createGizmoMesh(e,t,i=!1){const r=Ko("yPosMesh",{size:.4*(1+(t-1)/4)},this.gizmoLayer.utilityLayerScene),s=No("cylinder",{diameterTop:.005*t,height:.275,diameterBottom:.005*t,tessellation:96},this.gizmoLayer.utilityLayerScene);return r.scaling.scaleInPlace(.1),r.material=this._coloredMaterial,r.rotation.x=Math.PI/2,r.position.z+=.3,s.material=this._coloredMaterial,s.position.z+=.1375,s.rotation.x=Math.PI/2,i&&(r.visibility=0,s.visibility=0),e.addChild(r),e.addChild(s),{arrowMesh:r,arrowTail:s}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}setCustomMesh(e,t=!1){super.setCustomMesh(e),t&&(this._rootMesh.getChildMeshes().forEach((e=>{e.material=this._coloredMaterial,e.color&&(e.color=this._coloredMaterial.diffuseColor)})),this._customMeshSet=!1)}}var em;J_.MinimumAbsoluteScale=lt.bH,function(e){e[e.Rotation=0]="Rotation",e[e.Scaling=1]="Scaling"}(em||(em={}));class tm extends Go{set axisFactor(e){this._axisFactor=e;const t=this._scaleBoxesParent.getChildMeshes();let i=0;for(let e=0;e<3;e++)for(let r=0;r<3;r++)for(let s=0;s<3;s++){const n=(1===e?1:0)+(1===r?1:0)+(1===s?1:0);if(1!==n&&3!==n){if(t[i]){const n=new W.Pq(e-1,r-1,s-1);n.multiplyInPlace(this._axisFactor),t[i].setEnabled(n.lengthSquared()>lt.bH)}i++}}}get axisFactor(){return this._axisFactor}set scaleDragSpeed(e){this._scaleDragSpeed=e}get scaleDragSpeed(){return this._scaleDragSpeed}get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverColoredMaterial}get pointerDragBehavior(){return this._pointerDragBehavior}get isDragging(){return this._dragging||this._pointerDragBehavior.dragging}setColor(e){this._coloredMaterial.emissiveColor=e,this._hoverColoredMaterial.emissiveColor=e.clone().add(new H.v9(.3,.3,.3)),this._lineBoundingBox.getChildren().forEach((t=>{t.color&&(t.color=e)}))}constructor(e=H.v9.Gray(),t=Bo.DefaultKeepDepthUtilityLayer){super(t),this._boundingDimensions=new W.Pq(1,1,1),this._renderObserver=null,this._pointerObserver=null,this._scaleDragSpeed=.2,this._rotateAnchorsDragBehaviors=[],this._scaleBoxesDragBehaviors=[],this._dragging=!1,this._tmpQuaternion=new W.PT,this._tmpVector=new W.Pq(0,0,0),this._tmpRotationMatrix=new W.uq,this._incrementalStartupValue=W.Pq.Zero(),this._incrementalAnchorStartupValue=W.Pq.Zero(),this.ignoreChildren=!1,this.includeChildPredicate=null,this.rotationSphereSize=.1,this.scaleBoxSize=.1,this.fixedDragMeshScreenSize=!1,this.fixedDragMeshBoundsSize=!1,this.fixedDragMeshScreenSizeDistanceFactor=10,this.scalingSnapDistance=0,this.rotationSnapDistance=0,this.onDragStartObservable=new z.cP,this.onHoverStartObservable=new z.cP,this.onHoverEndObservable=new z.cP,this.onScaleBoxDragObservable=new z.cP,this.onScaleBoxDragEndObservable=new z.cP,this.onRotationSphereDragObservable=new z.cP,this.onRotationSphereDragEndObservable=new z.cP,this.scalePivot=null,this._axisFactor=new W.Pq(1,1,1),this.incrementalSnap=!1,this._existingMeshScale=new W.Pq,this._dragMesh=null,this._pointerDragBehavior=new Ji,this._cornerMesh=null,this.updateScale=!1,this._anchorMesh=new Pt("anchor",t.utilityLayerScene),this._coloredMaterial=new Un("",t.utilityLayerScene),this._coloredMaterial.disableLighting=!0,this._hoverColoredMaterial=new Un("",t.utilityLayerScene),this._hoverColoredMaterial.disableLighting=!0,this._lineBoundingBox=new Pt("",t.utilityLayerScene),this._lineBoundingBox.rotationQuaternion=new W.PT;const i=[];i.push(Ra("lines",{points:[new W.Pq(0,0,0),new W.Pq(this._boundingDimensions.x,0,0)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(0,0,0),new W.Pq(0,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(0,0,0),new W.Pq(0,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(this._boundingDimensions.x,0,0),new W.Pq(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(this._boundingDimensions.x,0,0),new W.Pq(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(0,this._boundingDimensions.y,0),new W.Pq(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(0,this._boundingDimensions.y,0),new W.Pq(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(0,0,this._boundingDimensions.z),new W.Pq(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(0,0,this._boundingDimensions.z),new W.Pq(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new W.Pq(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new W.Pq(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new W.Pq(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.forEach((t=>{t.color=e,t.position.addInPlace(new W.Pq(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),t.isPickable=!1,this._lineBoundingBox.addChild(t)})),this._rootMesh.addChild(this._lineBoundingBox),this.setColor(e),this._rotateAnchorsParent=new Pt("",t.utilityLayerScene),this._rotateAnchorsParent.rotationQuaternion=new W.PT;for(let e=0;e<12;e++){const i=Ko("",{width:e<4||e>=8?1.6:.4,height:e>=4&&e<8?1.6:.4,depth:.4},t.utilityLayerScene);i.rotation.x=e<4||e>=8?.25*Math.PI:0,i.rotation.y=e>=4&&e<8?.25*Math.PI:0,i.bakeTransformIntoVertices(i.computeWorldMatrix(!0)),i.rotationQuaternion=new W.PT,i.material=this._coloredMaterial,i.isNearGrabbable=!0;const r=new Ji({});r.moveAttached=!1,r.updateDragPlane=!1,i.addBehavior(r);const s=new W.Pq(1,0,0);let n=0,o=0;r.onDragStartObservable.add((()=>{s.copyFrom(i.forward),n=0,o=0}));const a=function(){const t=Math.floor(e/4);return W.AA.Vector3[0].set(0==t?1:0,1==t?1:0,2==t?1:0),W.AA.Vector3[0]};r.onDragObservable.add((t=>{if(this.onRotationSphereDragObservable.notifyObservers({dragOperation:0,dragAxis:a().clone()}),this.attachedMesh){const i=this.attachedMesh.parent;if(i&&i.scaling&&i.scaling.isNonUniformWithinEpsilon(.001))return void Z.V.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");ji._RemoveAndStorePivotPoint(this.attachedMesh);const r=s,a=t.dragPlaneNormal.scale(W.Pq.Dot(t.dragPlaneNormal,r)),l=r.subtract(a).normalizeToNew();let h=W.Pq.Dot(l,t.delta)<0?Math.abs(t.delta.length()):-Math.abs(t.delta.length());if(h=h/this._boundingDimensions.length()*this._anchorMesh.scaling.length(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=W.PT.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=W.PT.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),n+=h,Math.abs(n)<=2*Math.PI){if(this.rotationSnapDistance>0){const e=Math.floor(Math.abs(n)/this.rotationSnapDistance)*(n<0?-1:1),t=this.rotationSnapDistance*e;h=t-o,o=t}e>=8?W.PT.RotationYawPitchRollToRef(0,0,h,this._tmpQuaternion):e>=4?W.PT.RotationYawPitchRollToRef(h,0,0,this._tmpQuaternion):W.PT.RotationYawPitchRollToRef(0,h,0,this._tmpQuaternion),this.attachedMesh.isUsingPivotMatrix()&&this._anchorMesh.position.copyFrom(this.attachedMesh.position),this._anchorMesh.addChild(this.attachedMesh),this._anchorMesh.getScene().useRightHandedSystem&&this._tmpQuaternion.conjugateInPlace(),this._tmpQuaternion.normalize(),this._anchorMesh.rotationQuaternion.multiplyToRef(this._tmpQuaternion,this._anchorMesh.rotationQuaternion),this._anchorMesh.rotationQuaternion.normalize(),this._anchorMesh.removeChild(this.attachedMesh),this.attachedMesh.setParent(i)}this.updateBoundingBox(),ji._RestorePivotPoint(this.attachedMesh)}this._updateDummy()})),r.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({dragOperation:0,dragAxis:a().clone()}),this._dragging=!0,this._selectNode(i)})),r.onDragEndObservable.add((e=>{this.onRotationSphereDragEndObservable.notifyObservers({dragOperation:0,dragAxis:a().clone()}),this._dragging=!1,this._selectNode(null),this._updateDummy(),this._unhoverMeshOnTouchUp(e.pointerInfo,i)})),this._rotateAnchorsDragBehaviors.push(r),this._rotateAnchorsParent.addChild(i)}this._rootMesh.addChild(this._rotateAnchorsParent),this._scaleBoxesParent=new Pt("",t.utilityLayerScene),this._scaleBoxesParent.rotationQuaternion=new W.PT;for(let e=0;e<3;e++)for(let i=0;i<3;i++)for(let r=0;r<3;r++){const s=(1===e?1:0)+(1===i?1:0)+(1===r?1:0);if(1===s||3===s)continue;const n=2===s?Ko("",{size:1},t.utilityLayerScene):this._getCornerMesh(t);0===s&&(n.rotationQuaternion=W.PT.FromEulerAngles(.25*i*Math.PI,.25*(r+3*e-e*r)*Math.PI,0)),n.material=this._coloredMaterial,n._internalMetadata=2===s,n.isNearGrabbable=!0,W.AA.Vector3[0].set(e-1,i-1,r-1),W.AA.Vector3[0].normalize(),n.computeWorldMatrix(!0).invertToRef(W.AA.Matrix[0]);const o=W.Pq.TransformCoordinates(W.AA.Vector3[0],W.AA.Matrix[0]);o.normalize();const a=new Ji({dragAxis:o});a.updateDragPlane=!1,a.moveAttached=!1;let l=0,h=0;n.addBehavior(a),a.onDragObservable.add((t=>{if(this.onScaleBoxDragObservable.notifyObservers({dragOperation:1,dragAxis:new W.Pq(e-1,i-1,r-1)}),this.attachedMesh){const e=this.attachedMesh.parent;if(e&&e.scaling&&e.scaling.isNonUniformWithinEpsilon(.001))return void Z.V.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");ji._RemoveAndStorePivotPoint(this.attachedMesh);let i=t.dragDistance/this._boundingDimensions.length()*this._anchorMesh.scaling.length();if(l+=i,this.scalingSnapDistance>0){const e=Math.floor(Math.abs(l)/this.scalingSnapDistance)*(l<0?-1:1),t=this.scalingSnapDistance*e;i=t-h,h=t}const r=new W.Pq(i,i,i),a=new W.Pq(h,h,h);2===s&&(r.x*=Math.abs(o.x),r.y*=Math.abs(o.y),r.z*=Math.abs(o.z)),r.scaleInPlace(this._scaleDragSpeed),r.multiplyInPlace(this._axisFactor),a.scaleInPlace(this._scaleDragSpeed),a.multiplyInPlace(this._axisFactor),a.addInPlace(this._incrementalStartupValue),this.updateBoundingBox(),this.scalePivot?(this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(this._tmpRotationMatrix),this._boundingDimensions.scaleToRef(.5,this._tmpVector),W.Pq.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector),this._boundingDimensions.multiplyToRef(this.scalePivot,this._tmpVector),W.Pq.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.addInPlace(this._tmpVector)):(n.absolutePosition.subtractToRef(this._anchorMesh.position,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector),this.attachedMesh.isUsingPivotMatrix()&&this._anchorMesh.position.subtractInPlace(this.attachedMesh.getPivotPoint())),this._anchorMesh.addChild(this.attachedMesh),this.incrementalSnap?(a.x/=Math.abs(this._incrementalStartupValue.x){this.onDragStartObservable.notifyObservers({dragOperation:1,dragAxis:new W.Pq(e-1,i-1,r-1)}),this._dragging=!0,this._selectNode(n),l=0,h=0,this._incrementalStartupValue.copyFrom(this.attachedMesh.scaling),this._incrementalAnchorStartupValue.copyFrom(this._anchorMesh.scaling)})),a.onDragEndObservable.add((t=>{this.onScaleBoxDragEndObservable.notifyObservers({dragOperation:1,dragAxis:new W.Pq(e-1,i-1,r-1)}),this._dragging=!1,this._selectNode(null),this._updateDummy(),this._unhoverMeshOnTouchUp(t.pointerInfo,n)})),this._scaleBoxesParent.addChild(n),this._scaleBoxesDragBehaviors.push(a)}this._rootMesh.addChild(this._scaleBoxesParent);const r=[];this._pointerObserver=t.utilityLayerScene.onPointerObservable.add((e=>{r[e.event.pointerId]?e.pickInfo&&e.pickInfo.pickedMesh!=r[e.event.pointerId]&&(r[e.event.pointerId].material=this._coloredMaterial,delete r[e.event.pointerId],this.onHoverEndObservable.notifyObservers(),this._isHovered=!1):this._rotateAnchorsParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach((t=>{e.pickInfo&&e.pickInfo.pickedMesh==t&&(r[e.event.pointerId]=t,t.material=this._hoverColoredMaterial,this.onHoverStartObservable.notifyObservers(),this._isHovered=!0)}))})),this._renderObserver=this.gizmoLayer.originalScene.onBeforeRenderObservable.add((()=>{this.attachedMesh&&!this._existingMeshScale.equals(this.attachedMesh.scaling)?this.updateBoundingBox():(this.fixedDragMeshScreenSize||this.fixedDragMeshBoundsSize)&&(this._updateRotationAnchors(),this._updateScaleBoxes()),this._dragMesh&&this.attachedMesh&&this._pointerDragBehavior.dragging&&(this._lineBoundingBox.position.rotateByQuaternionToRef(this._rootMesh.rotationQuaternion,this._tmpVector),this.attachedMesh.setAbsolutePosition(this._dragMesh.position.add(this._tmpVector.scale(-1))))})),this.updateBoundingBox()}_getCornerMesh(e){if(!this._cornerMesh){const t=Ko("",{width:.4,height:.4,depth:1.6},e.utilityLayerScene);t.position.z=.6;const i=Ko("",{width:.4,height:1.6,depth:.4},e.utilityLayerScene);i.position.y=.6;const r=Ko("",{width:1.6,height:.4,depth:.4},e.utilityLayerScene);return r.position.x=.6,this._cornerMesh=Yt.MergeMeshes([r,i,t],!0),this._cornerMesh}return this._cornerMesh.clone()}_attachedNodeChanged(e){if(e){this._anchorMesh.scaling.setAll(1),ji._RemoveAndStorePivotPoint(e);const t=e.parent;this._anchorMesh.addChild(e),this._anchorMesh.removeChild(e),e.setParent(t),ji._RestorePivotPoint(e),this.updateBoundingBox(),e.getChildMeshes(!1).forEach((e=>{e.markAsDirty("scaling")})),this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce((()=>{this._updateDummy()}))}}_selectNode(e){this._rotateAnchorsParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach((t=>{t.isVisible=!e||t==e}))}_unhoverMeshOnTouchUp(e,t){e?.event instanceof PointerEvent&&"touch"===e?.event.pointerType&&(t.material=this._coloredMaterial)}getScaleBoxes(){return this._scaleBoxesParent.getChildMeshes()}updateBoundingBox(){if(this.attachedMesh){ji._RemoveAndStorePivotPoint(this.attachedMesh);const e=this.attachedMesh.parent;this.attachedMesh.setParent(null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=W.PT.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=W.PT.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);const t=this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren,this.includeChildPredicate);t.max.subtractToRef(t.min,this._boundingDimensions),this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions),this._lineBoundingBox.position.set((t.max.x+t.min.x)/2,(t.max.y+t.min.y)/2,(t.max.z+t.min.z)/2),this._rotateAnchorsParent.position.copyFrom(this._lineBoundingBox.position),this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position),this._lineBoundingBox.computeWorldMatrix(),this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),this.attachedMesh.setParent(e)}this._updateRotationAnchors(),this._updateScaleBoxes(),this.attachedMesh&&(this._existingMeshScale.copyFrom(this.attachedMesh.scaling),ji._RestorePivotPoint(this.attachedMesh))}_updateRotationAnchors(){const e=this._rotateAnchorsParent.getChildMeshes();for(let t=0;t<3;t++)for(let i=0;i<2;i++)for(let r=0;r<2;r++){const s=4*t+2*i+r;e[s].position.normalizeToRef(W.AA.Vector3[0]),0==t&&(e[s].position.set(0,this._boundingDimensions.y*(i-.5),this._boundingDimensions.z*(r-.5)),W.AA.Vector3[1].set(1,0,0)),1==t&&(e[s].position.set(this._boundingDimensions.x*(i-.5),0,this._boundingDimensions.z*(r-.5)),W.AA.Vector3[1].set(0,1,0)),2==t&&(e[s].position.set(this._boundingDimensions.x*(i-.5),this._boundingDimensions.y*(r-.5),0),W.AA.Vector3[1].set(0,0,1));const n=W.AA.Vector3[2];if(W.Pq.CrossToRef(W.AA.Vector3[0],W.AA.Vector3[1],n),n.normalize(),n.addInPlace(e[s].position),e[s].lookAt(n),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[s].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);const t=this.rotationSphereSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[s].scaling.set(t,t,t)}else this.fixedDragMeshBoundsSize?e[s].scaling.set(this.rotationSphereSize*this._boundingDimensions.x,this.rotationSphereSize*this._boundingDimensions.y,this.rotationSphereSize*this._boundingDimensions.z):e[s].scaling.set(this.rotationSphereSize,this.rotationSphereSize,this.rotationSphereSize)}}_updateScaleBoxes(){const e=this._scaleBoxesParent.getChildMeshes();let t=0;for(let i=0;i<3;i++)for(let r=0;r<3;r++)for(let s=0;s<3;s++){const n=(1===i?1:0)+(1===r?1:0)+(1===s?1:0);if(1!==n&&3!==n){if(e[t])if(e[t].position.set(this._boundingDimensions.x*(i/2),this._boundingDimensions.y*(r/2),this._boundingDimensions.z*(s/2)),e[t].position.addInPlace(new W.Pq(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[t].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.globalPosition,this._tmpVector);const i=this.scaleBoxSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[t].scaling.set(i,i,i)}else this.fixedDragMeshBoundsSize?e[t].scaling.set(this.scaleBoxSize*this._boundingDimensions.x,this.scaleBoxSize*this._boundingDimensions.y,this.scaleBoxSize*this._boundingDimensions.z):e[t].scaling.set(this.scaleBoxSize,this.scaleBoxSize,this.scaleBoxSize);t++}}}setEnabledRotationAxis(e){this._rotateAnchorsParent.getChildMeshes().forEach(((t,i)=>{i<4?t.setEnabled(-1!=e.indexOf("x")):i<8?t.setEnabled(-1!=e.indexOf("y")):t.setEnabled(-1!=e.indexOf("z"))}))}setEnabledScaling(e,t=!1){this._scaleBoxesParent.getChildMeshes().forEach((i=>{let r=e;t&&!0===i._internalMetadata&&(r=!1),i.setEnabled(r)}))}_updateDummy(){this._dragMesh&&(this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition()),this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling),this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion))}enableDragBehavior(){this._dragMesh=Ko("dummy",{size:1},this.gizmoLayer.utilityLayerScene),this._dragMesh.visibility=0,this._dragMesh.rotationQuaternion=new W.PT,this._pointerDragBehavior.useObjectOrientationForDragging=!1,this._dragMesh.addBehavior(this._pointerDragBehavior)}releaseDrag(){this._scaleBoxesDragBehaviors.forEach((e=>{e.releaseDrag()})),this._rotateAnchorsDragBehaviors.forEach((e=>{e.releaseDrag()})),this._pointerDragBehavior.releaseDrag()}dispose(){this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver),this._lineBoundingBox.dispose(),this._rotateAnchorsParent.dispose(),this._scaleBoxesParent.dispose(),this._dragMesh&&this._dragMesh.dispose(),this._scaleBoxesDragBehaviors.length=0,this._rotateAnchorsDragBehaviors.length=0,this.onDragStartObservable.clear(),this.onHoverStartObservable.clear(),this.onHoverEndObservable.clear(),this.onScaleBoxDragObservable.clear(),this.onScaleBoxDragEndObservable.clear(),this.onRotationSphereDragObservable.clear(),this.onRotationSphereDragEndObservable.clear(),super.dispose()}static MakeNotPickableAndWrapInBoundingBox(e){const t=e=>{e.isPickable=!1,e.getChildMeshes().forEach((e=>{t(e)}))};t(e),e.rotationQuaternion||(e.rotationQuaternion=W.PT.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z));const i=e.position.clone(),r=e.rotationQuaternion.clone();e.rotationQuaternion.set(0,0,0,1),e.position.set(0,0,0);const s=Ko("box",{size:1},e.getScene()),n=e.getHierarchyBoundingVectors();return n.max.subtractToRef(n.min,s.scaling),0===s.scaling.y&&(s.scaling.y=lt.bH),0===s.scaling.x&&(s.scaling.x=lt.bH),0===s.scaling.z&&(s.scaling.z=lt.bH),s.position.set((n.max.x+n.min.x)/2,(n.max.y+n.min.y)/2,(n.max.z+n.min.z)/2),e.addChild(s),e.rotationQuaternion.copyFrom(r),e.position.copyFrom(i),e.removeChild(s),s.addChild(e),s.visibility=0,s}setCustomMesh(){Z.V.Error("Custom meshes are not supported on this gizmo")}}class im extends Go{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}set rotationColor(e){this._rotationShaderMaterial.setColor3("rotationColor",e)}get disableMaterial(){return this._disableMaterial}constructor(e,t=H.v9.Gray(),i=Bo.DefaultUtilityLayer,r=32,s=null,n=!1,o=1,a=H.v9.Yellow(),l=H.v9.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new z.cP,this.angle=0,this.sensitivity=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new W.Pq,this._parent=s,this._coloredMaterial=new Un("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new H.v9(.1,.1,.1)),this._hoverMaterial=new Un("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=a,this._hoverMaterial.specularColor=a,this._disableMaterial=new Un("",i.utilityLayerScene),this._disableMaterial.diffuseColor=l,this._disableMaterial.alpha=.4,this._gizmoMesh=new Yt("",i.utilityLayerScene);const{rotationMesh:h,collider:c}=this._createGizmoMesh(this._gizmoMesh,o,r);this._rotationDisplayPlane=Qi("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=.5*Math.PI,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),Cl.M.ShadersStore.rotationGizmoVertexShader=im._RotationGizmoVertexShader,Cl.M.ShadersStore.rotationGizmoFragmentShader=im._RotationGizmoFragmentShader,this._rotationShaderMaterial=new xo("shader",this.gizmoLayer.utilityLayerScene,{vertex:"rotationGizmo",fragment:"rotationGizmo"},{attributes:["position","uv"],uniforms:["worldViewProjection","angles","rotationColor"]}),this._rotationShaderMaterial.backFaceCulling=!1,this.rotationColor=a,this._rotationDisplayPlane.material=this._rotationShaderMaterial,this._rotationDisplayPlane.visibility=.999,this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,Go.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new Ji({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=im.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);const u=new W.Pq,d=new W.uq,f=new W.Pq;let p=new W.Pq;this.dragBehavior.onDragStartObservable.add((e=>{this.attachedNode&&(u.copyFrom(e.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(d),W.Pq.TransformCoordinatesToRef(e.dragPlanePoint,d,u),this._angles.x=Math.atan2(u.y,u.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,u.copyFrom(e.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)}));const _={snapDistance:0};let m=0;const g=new W.uq,v=new W.PT;this.dragBehavior.onDragObservable.add((t=>{if(this.attachedNode){const r=new W.Pq(1,1,1),s=new W.PT(0,0,0,1),n=new W.Pq(0,0,0);if(this.attachedNode.getWorldMatrix().decompose(r,s,n),!(Math.abs(Math.abs(r.x)-Math.abs(r.y))<=lt.bH&&Math.abs(Math.abs(r.x)-Math.abs(r.z))<=lt.bH)&&this.updateGizmoRotationToMatchAttachedMesh)return void Z.V.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");s.normalize();const o=this.updateGizmoPositionToMatchAttachedMesh?n:this._rootMesh.absolutePosition,a=t.dragPlanePoint.subtract(o).normalize(),l=u.subtract(o).normalize(),h=W.Pq.Cross(a,l),c=W.Pq.Dot(a,l);let x=Math.atan2(h.length(),c)*this.sensitivity;f.copyFrom(e),p.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(s.toRotationMatrix(d),p=W.Pq.TransformCoordinates(f,d));let b=!1;if(i.utilityLayerScene.activeCamera){const e=i.utilityLayerScene.activeCamera.position.subtract(o).normalize();W.Pq.Dot(e,p)>0&&(f.scaleInPlace(-1),p.scaleInPlace(-1),b=!0)}W.Pq.Dot(p,h)>0&&(x=-x),W.AA.Vector3[0].set(x,0,0),this.dragBehavior.validateDrag(W.AA.Vector3[0])||(x=0);let S=!1;if(0!=this.snapDistance)if(m+=x,Math.abs(m)>this.snapDistance){let e=Math.floor(Math.abs(m)/this.snapDistance);m<0&&(e*=-1),m%=this.snapDistance,x=this.snapDistance*e,S=!0}else x=0;const T=Math.sin(x/2);if(v.set(f.x*T,f.y*T,f.z*T,Math.cos(x/2)),g.determinant()>0){const e=new W.Pq;v.toEulerAnglesToRef(e),W.PT.RotationYawPitchRollToRef(e.y,-e.x,-e.z,v)}if(this.updateGizmoRotationToMatchAttachedMesh)s.multiplyToRef(v,s),s.normalize(),W.uq.ComposeToRef(r,s,n,this.attachedNode.getWorldMatrix());else{v.toRotationMatrix(W.AA.Matrix[0]);const e=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(W.AA.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(e)}u.copyFrom(t.dragPlanePoint),S&&(_.snapDistance=x,this.onSnapObservable.notifyObservers(_)),this._angles.y+=x,this.angle+=b?-x:x,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}}));const x=i._getSharedGizmoLight();x.includedOnlyMeshes=x.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const b={colliderMeshes:[c],gizmoMeshes:[h],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,b),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=im.MaxDragAngle,this._isHovered=!(-1==b.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),!this._parent)){const e=b.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(b.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(b.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}))}_createGizmoMesh(e,t,i){const r=ao("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);r.visibility=0;const s=ao("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,r.rotation.x=Math.PI/2,e.addChild(s,Go.PreserveScaling),e.addChild(r,Go.PreserveScaling),{rotationMesh:s,collider:r}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}}im.MaxDragAngle=9*Math.PI/20,im._RotationGizmoVertexShader="\n precision highp float;\n attribute vec3 position;\n attribute vec2 uv;\n uniform mat4 worldViewProjection;\n varying vec3 vPosition;\n varying vec2 vUV;\n\n void main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n vUV = uv;\n }",im._RotationGizmoFragmentShader="\n precision highp float;\n varying vec2 vUV;\n varying vec3 vPosition;\n uniform vec3 angles;\n uniform vec3 rotationColor;\n\n #define twopi 6.283185307\n\n void main(void) {\n vec2 uv = vUV - vec2(0.5);\n float angle = atan(uv.y, uv.x) + 3.141592;\n float delta = gl_FrontFacing ? angles.y : -angles.y;\n float begin = angles.x - delta * angles.z;\n float start = (begin < (begin + delta)) ? begin : (begin + delta);\n float end = (begin > (begin + delta)) ? begin : (begin + delta);\n float len = sqrt(dot(uv,uv));\n float opacity = 1. - step(0.5, len);\n\n float base = abs(floor(start / twopi)) * twopi;\n start += base;\n end += base;\n\n float intensity = 0.;\n for (int i = 0; i < 5; i++)\n {\n intensity += max(step(start, angle) - step(end, angle), 0.);\n angle += twopi;\n }\n gl_FragColor = vec4(rotationColor, min(intensity * 0.25, 0.8)) * opacity;\n }\n ";class rm extends Go{get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}_checkBillboardTransform(){this._nodeAttached&&this._nodeAttached.billboardMode&&Z.V.Log("Rotation Gizmo will not work with transforms in billboard mode.")}set sensitivity(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t&&(t.sensitivity=e)}))}get sensitivity(){return this._sensitivity}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.additionalTransformNode=e}))}constructor(e=Bo.DefaultUtilityLayer,t=32,i=!1,r=1,s,n){super(e),this.onDragStartObservable=new z.cP,this.onDragObservable=new z.cP,this.onDragEndObservable=new z.cP,this._observables=[],this._sensitivity=1,this._gizmoAxisCache=new Map;const o=n&&n.xOptions&&n.xOptions.color?n.xOptions.color:H.v9.Red().scale(.5),a=n&&n.yOptions&&n.yOptions.color?n.yOptions.color:H.v9.Green().scale(.5),l=n&&n.zOptions&&n.zOptions.color?n.zOptions.color:H.v9.Blue().scale(.5);this.xGizmo=new im(new W.Pq(1,0,0),o,e,t,this,i,r),this.yGizmo=new im(new W.Pq(0,1,0),a,e,t,this,i,r),this.zGizmo=new im(new W.Pq(0,0,1),l,e,t,this,i,r),this.additionalTransformNode=n?.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((e=>{n&&null!=n.updateScale&&(e.updateScale=n.updateScale),e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((()=>{this.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,this.attachedNode=null,s?s.addToAxisCache(this._gizmoAxisCache):Go.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}set updateGizmoRotationToMatchAttachedMesh(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)}get updateGizmoRotationToMatchAttachedMesh(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this.xGizmo&&(this.xGizmo.updateGizmoPositionToMatchAttachedMesh=e,this.yGizmo.updateGizmoPositionToMatchAttachedMesh=e,this.zGizmo.updateGizmoPositionToMatchAttachedMesh=e)}get updateGizmoPositionToMatchAttachedMesh(){return this.xGizmo.updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.anchorPoint=e}))}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.coordinatesMode=e}))}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}set snapDistance(e){this.xGizmo&&(this.xGizmo.snapDistance=e,this.yGizmo.snapDistance=e,this.zGizmo.snapDistance=e)}get snapDistance(){return this.xGizmo.snapDistance}set scaleRatio(e){this.xGizmo&&(this.xGizmo.scaleRatio=e,this.yGizmo.scaleRatio=e,this.zGizmo.scaleRatio=e)}get scaleRatio(){return this.xGizmo.scaleRatio}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t&&(t.customRotationQuaternion=e)}))}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag()}dispose(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose(),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear(),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)})),super.dispose()}setCustomMesh(){Z.V.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)")}}class sm extends Go{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreatePlane(e,t){const i=new Pt("plane",e),r=Qi("dragPlane",{width:.1375,height:.1375,sideOrientation:2},e);return r.material=t,r.parent=i,i}constructor(e,t=H.v9.Gray(),i=Bo.DefaultUtilityLayer,r=null,s=H.v9.Yellow(),n=H.v9.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new z.cP,this._isEnabled=!1,this._parent=null,this._dragging=!1,this._parent=r,this._coloredMaterial=new Un("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new H.v9(.1,.1,.1)),this._hoverMaterial=new Un("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=s,this._disableMaterial=new Un("",i.utilityLayerScene),this._disableMaterial.diffuseColor=n,this._disableMaterial.alpha=.4,this._gizmoMesh=sm._CreatePlane(i.utilityLayerScene,this._coloredMaterial),this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._gizmoMesh.scaling.scaleInPlace(1/3),this._gizmoMesh.parent=this._rootMesh;let o=0;const a=new W.Pq,l={snapDistance:0};this.dragBehavior=new Ji({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add((e=>{if(this.attachedNode){if(0==this.snapDistance)this.attachedNode.getWorldMatrix().getTranslationToRef(W.AA.Vector3[0]),W.AA.Vector3[0].addToRef(e.delta,W.AA.Vector3[0]),this.dragBehavior.validateDrag(W.AA.Vector3[0])&&this.attachedNode.getWorldMatrix().addTranslationFromFloats(e.delta.x,e.delta.y,e.delta.z);else if(o+=e.dragDistance,Math.abs(o)>this.snapDistance){const t=Math.floor(Math.abs(o)/this.snapDistance);o%=this.snapDistance,e.delta.normalizeToRef(a),a.scaleInPlace(this.snapDistance*t),this.attachedNode.getWorldMatrix().getTranslationToRef(W.AA.Vector3[0]),W.AA.Vector3[0].addToRef(a,W.AA.Vector3[0]),this.dragBehavior.validateDrag(W.AA.Vector3[0])&&(this.attachedNode.getWorldMatrix().addTranslationFromFloats(a.x,a.y,a.z),l.snapDistance=this.snapDistance*t,this.onSnapObservable.notifyObservers(l))}this._matrixChanged()}})),this.dragBehavior.onDragStartObservable.add((()=>{this._dragging=!0})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1}));const h=i._getSharedGizmoLight();h.includedOnlyMeshes=h.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const c={gizmoMeshes:this._gizmoMesh.getChildMeshes(),colliderMeshes:this._gizmoMesh.getChildMeshes(),material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,c),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(!this._customMeshSet&&(this._isHovered=!(-1==c.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),!this._parent)){const e=c.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(c.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(c.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}))}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedNode=this._parent.attachedNode):this.attachedNode=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),super.dispose(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()}))}}class nm extends Go{get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered||this.xPlaneGizmo.isHovered||this.yPlaneGizmo.isHovered||this.zPlaneGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging||this.xPlaneGizmo.dragBehavior.dragging||this.yPlaneGizmo.dragBehavior.dragging||this.zPlaneGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.additionalTransformNode=e}))}constructor(e=Bo.DefaultUtilityLayer,t=1,i,r){super(e),this._meshAttached=null,this._nodeAttached=null,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new z.cP,this.onDragObservable=new z.cP,this.onDragEndObservable=new z.cP,this._planarGizmoEnabled=!1,this.xGizmo=new zo(new W.Pq(1,0,0),H.v9.Red().scale(.5),e,this,t),this.yGizmo=new zo(new W.Pq(0,1,0),H.v9.Green().scale(.5),e,this,t),this.zGizmo=new zo(new W.Pq(0,0,1),H.v9.Blue().scale(.5),e,this,t),this.xPlaneGizmo=new sm(new W.Pq(1,0,0),H.v9.Red().scale(.5),this.gizmoLayer,this),this.yPlaneGizmo=new sm(new W.Pq(0,1,0),H.v9.Green().scale(.5),this.gizmoLayer,this),this.zPlaneGizmo=new sm(new W.Pq(0,0,1),H.v9.Blue().scale(.5),this.gizmoLayer,this),this.additionalTransformNode=r?.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((e=>{e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((()=>{this.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,i?i.addToAxisCache(this._gizmoAxisCache):Go.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}set planarGizmoEnabled(e){this._planarGizmoEnabled=e,[this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.isEnabled=e,e&&(t.attachedMesh?t.attachedMesh=this.attachedMesh:t.attachedNode=this.attachedNode))}),this)}get planarGizmoEnabled(){return this._planarGizmoEnabled}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.customRotationQuaternion=e)}))}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.updateGizmoRotationToMatchAttachedMesh=e)}))}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.updateGizmoPositionToMatchAttachedMesh=e)}))}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.anchorPoint=e}))}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.coordinatesMode=e}))}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}set snapDistance(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.snapDistance=e)}))}get snapDistance(){return this._snapDistance}set scaleRatio(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag(),this.xPlaneGizmo.dragBehavior.releaseDrag(),this.yPlaneGizmo.dragBehavior.releaseDrag(),this.zPlaneGizmo.dragBehavior.releaseDrag()}dispose(){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((e=>{e&&e.dispose()})),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)})),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear(),super.dispose()}setCustomMesh(){Z.V.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo,gizmo.xPlaneGizmo, gizmo.yPlaneGizmo, gizmo.zPlaneGizmo)")}}class om extends Go{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered||this.uniformScaleGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging||this.uniformScaleGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t.additionalTransformNode=e}))}constructor(e=Bo.DefaultUtilityLayer,t=1,i,r){super(e),this._meshAttached=null,this._nodeAttached=null,this._incrementalSnap=!1,this._sensitivity=1,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new z.cP,this.onDragObservable=new z.cP,this.onDragEndObservable=new z.cP,this.uniformScaleGizmo=this._createUniformScaleMesh(),this.xGizmo=new J_(new W.Pq(1,0,0),H.v9.Red().scale(.5),e,this,t),this.yGizmo=new J_(new W.Pq(0,1,0),H.v9.Green().scale(.5),e,this,t),this.zGizmo=new J_(new W.Pq(0,0,1),H.v9.Blue().scale(.5),e,this,t),this.additionalTransformNode=r?.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((e=>{e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((()=>{this.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,this.attachedNode=null,i?i.addToAxisCache(this._gizmoAxisCache):Go.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}_createUniformScaleMesh(){this._coloredMaterial=new Un("",this.gizmoLayer.utilityLayerScene),this._coloredMaterial.diffuseColor=H.v9.Gray(),this._hoverMaterial=new Un("",this.gizmoLayer.utilityLayerScene),this._hoverMaterial.diffuseColor=H.v9.Yellow(),this._disableMaterial=new Un("",this.gizmoLayer.utilityLayerScene),this._disableMaterial.diffuseColor=H.v9.Gray(),this._disableMaterial.alpha=.4;const e=new J_(new W.Pq(0,1,0),H.v9.Gray().scale(.5),this.gizmoLayer,this);e.updateGizmoRotationToMatchAttachedMesh=!1,e.uniformScaling=!0,this._uniformScalingMesh=Ka("uniform",{type:1},e.gizmoLayer.utilityLayerScene),this._uniformScalingMesh.scaling.scaleInPlace(.01),this._uniformScalingMesh.visibility=0,this._octahedron=Ka("",{type:1},e.gizmoLayer.utilityLayerScene),this._octahedron.scaling.scaleInPlace(.007),this._uniformScalingMesh.addChild(this._octahedron),e.setCustomMesh(this._uniformScalingMesh,!0);const t=this.gizmoLayer._getSharedGizmoLight();t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._octahedron);const i={gizmoMeshes:[this._octahedron,this._uniformScalingMesh],colliderMeshes:[this._octahedron,this._uniformScalingMesh],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:e.dragBehavior};return this.addToAxisCache(e._rootMesh,i),e}set updateGizmoRotationToMatchAttachedMesh(e){e?(this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.updateGizmoRotationToMatchAttachedMesh=e)}))):Z.V.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.")}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.anchorPoint=e)}))}get anchorPoint(){return this._anchorPoint}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.customRotationQuaternion=e)}))}set coordinatesMode(e){0==e&&Z.V.Warn("Setting coordinates Mode to world on scaling gizmo is not supported."),[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((e=>{e.coordinatesMode=1}))}set snapDistance(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.snapDistance=e)}))}get snapDistance(){return this._snapDistance}set incrementalSnap(e){this._incrementalSnap=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.incrementalSnap=e)}))}get incrementalSnap(){return this._incrementalSnap}set scaleRatio(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}set sensitivity(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.sensitivity=e)}))}get sensitivity(){return this._sensitivity}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}getAxisCache(e){return this._gizmoAxisCache.get(e)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag(),this.uniformScaleGizmo.dragBehavior.releaseDrag()}dispose(){[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((e=>{e&&e.dispose()})),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)})),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear(),[this._uniformScalingMesh,this._octahedron].forEach((e=>{e&&e.dispose()})),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()}))}}class am{get keepDepthUtilityLayer(){return this._defaultKeepDepthUtilityLayer}get utilityLayer(){return this._defaultUtilityLayer}get isHovered(){let e=!1;for(const t in this.gizmos){const i=this.gizmos[t];if(i&&i.isHovered){e=!0;break}}return e}get isDragging(){let e=!1;return[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo,this.gizmos.boundingBoxGizmo].forEach((t=>{t&&t.isDragging&&(e=!0)})),e}set scaleRatio(e){this._scaleRatio=e,[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}set coordinatesMode(e){this._coordinatesMode=e,[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo].forEach((t=>{t&&(t.coordinatesMode=e)}))}get coordinatesMode(){return this._coordinatesMode}get attachedMesh(){return this._attachedMesh}get attachedNode(){return this._attachedNode}get additionalTransformNode(){return this._additionalTransformNode}constructor(e,t=1,i=Bo.DefaultUtilityLayer,r=Bo.DefaultKeepDepthUtilityLayer){this._scene=e,this.clearGizmoOnEmptyPointerEvent=!1,this.enableAutoPicking=!0,this.onAttachedToMeshObservable=new z.cP,this.onAttachedToNodeObservable=new z.cP,this._gizmosEnabled={positionGizmo:!1,rotationGizmo:!1,scaleGizmo:!1,boundingBoxGizmo:!1},this._pointerObservers=[],this._attachedMesh=null,this._attachedNode=null,this._boundingBoxColor=H.v9.FromHexString("#0984e3"),this._thickness=1,this._scaleRatio=1,this._coordinatesMode=1,this._gizmoAxisCache=new Map,this.boundingBoxDragBehavior=new ir,this.attachableMeshes=null,this.attachableNodes=null,this.usePointerToAttachGizmos=!0,this._defaultUtilityLayer=i,this._defaultKeepDepthUtilityLayer=r,this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,this._thickness=t,this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null};const s=this._attachToMeshPointerObserver(e),n=Go.GizmoAxisPointerObserver(this._defaultUtilityLayer,this._gizmoAxisCache);this._pointerObservers=[s,n]}_attachToMeshPointerObserver(e){const t=e.onPointerObservable.add((e=>{if(this.usePointerToAttachGizmos&&e.type==yi.Zp.POINTERDOWN)if(e.pickInfo&&e.pickInfo.pickedMesh){if(this.enableAutoPicking){let t=e.pickInfo.pickedMesh;if(null==this.attachableMeshes)for(;t&&null!=t.parent;)t=t.parent;else{let e=!1;this.attachableMeshes.forEach((i=>{t&&(t==i||t.isDescendantOf(i))&&(t=i,e=!0)})),e||(t=null)}t instanceof Nt?this._attachedMesh!=t&&this.attachToMesh(t):this.clearGizmoOnEmptyPointerEvent&&this.attachToMesh(null)}}else this.clearGizmoOnEmptyPointerEvent&&this.attachToMesh(null)}));return t}attachToMesh(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=e,this._attachedNode=null;for(const t in this.gizmos){const i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedMesh=e)}this.boundingBoxGizmoEnabled&&this._attachedMesh&&this._attachedMesh.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToMeshObservable.notifyObservers(e)}attachToNode(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=null,this._attachedNode=e;for(const t in this.gizmos){const i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedNode=e)}this.boundingBoxGizmoEnabled&&this._attachedNode&&this._attachedNode.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToNodeObservable.notifyObservers(e)}set positionGizmoEnabled(e){e?(this.gizmos.positionGizmo||(this.gizmos.positionGizmo=new nm(this._defaultUtilityLayer,this._thickness,this)),this._attachedNode?this.gizmos.positionGizmo.attachedNode=this._attachedNode:this.gizmos.positionGizmo.attachedMesh=this._attachedMesh):this.gizmos.positionGizmo&&(this.gizmos.positionGizmo.attachedNode=null),this._gizmosEnabled.positionGizmo=e,this._setAdditionalTransformNode()}get positionGizmoEnabled(){return this._gizmosEnabled.positionGizmo}set rotationGizmoEnabled(e){e?(this.gizmos.rotationGizmo||(this.gizmos.rotationGizmo=new rm(this._defaultUtilityLayer,32,!1,this._thickness,this)),this._attachedNode?this.gizmos.rotationGizmo.attachedNode=this._attachedNode:this.gizmos.rotationGizmo.attachedMesh=this._attachedMesh):this.gizmos.rotationGizmo&&(this.gizmos.rotationGizmo.attachedNode=null),this._gizmosEnabled.rotationGizmo=e,this._setAdditionalTransformNode()}get rotationGizmoEnabled(){return this._gizmosEnabled.rotationGizmo}set scaleGizmoEnabled(e){e?(this.gizmos.scaleGizmo=this.gizmos.scaleGizmo||new om(this._defaultUtilityLayer,this._thickness,this),this._attachedNode?this.gizmos.scaleGizmo.attachedNode=this._attachedNode:this.gizmos.scaleGizmo.attachedMesh=this._attachedMesh):this.gizmos.scaleGizmo&&(this.gizmos.scaleGizmo.attachedNode=null),this._gizmosEnabled.scaleGizmo=e,this._setAdditionalTransformNode()}get scaleGizmoEnabled(){return this._gizmosEnabled.scaleGizmo}set boundingBoxGizmoEnabled(e){e?(this.gizmos.boundingBoxGizmo=this.gizmos.boundingBoxGizmo||new tm(this._boundingBoxColor,this._defaultKeepDepthUtilityLayer),this._attachedMesh?this.gizmos.boundingBoxGizmo.attachedMesh=this._attachedMesh:this.gizmos.boundingBoxGizmo.attachedNode=this._attachedNode,this._attachedMesh?(this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh.addBehavior(this.boundingBoxDragBehavior)):this._attachedNode&&(this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode.addBehavior(this.boundingBoxDragBehavior))):this.gizmos.boundingBoxGizmo&&(this._attachedMesh?this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior):this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this.gizmos.boundingBoxGizmo.attachedNode=null),this._gizmosEnabled.boundingBoxGizmo=e,this._setAdditionalTransformNode()}get boundingBoxGizmoEnabled(){return this._gizmosEnabled.boundingBoxGizmo}set additionalTransformNode(e){this._additionalTransformNode=e,this._setAdditionalTransformNode()}_setAdditionalTransformNode(){for(const e in this.gizmos){const t=this.gizmos[e];t&&this._gizmosEnabled[e]&&(t.additionalTransformNode=this._additionalTransformNode)}}addToAxisCache(e){e.size>0&&e.forEach(((e,t)=>{this._gizmoAxisCache.set(t,e)}))}releaseDrag(){[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo,this.gizmos.boundingBoxGizmo].forEach((e=>{e?.releaseDrag()}))}dispose(){this._pointerObservers.forEach((e=>{this._scene.onPointerObservable.remove(e)}));for(const e in this.gizmos){const t=this.gizmos[e];t&&t.dispose()}this._defaultKeepDepthUtilityLayer!==Bo._DefaultKeepDepthUtilityLayer&&this._defaultKeepDepthUtilityLayer?.dispose(),this._defaultUtilityLayer!==Bo._DefaultUtilityLayer&&this._defaultUtilityLayer?.dispose(),this.boundingBoxDragBehavior.detach(),this.onAttachedToMeshObservable.clear()}}class lm extends $t{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=W.uq.Identity(),this._projectionMatrix=W.uq.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=W.Pq.Zero()),W.Pq.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=W.Pq.Zero()),W.Pq.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),0))}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=W.Pq.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=W.Pq.Cross(this.direction,Mt._0.Y),t=W.Pq.Cross(e,this.direction);return W.Pq.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=W.Pq.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=W.uq.Identity()),W.uq.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 void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ}getDepthMaxZ(e){return void 0!==this.shadowMaxZ?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.AA.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),W.Pq.NormalizeToRef(this.getShadowDirection(e),t),1===Math.abs(W.Pq.Dot(t,W.Pq.Up()))&&(t.z=1e-13);const r=W.AA.Vector3[1];return i.addToRef(t,r),W.uq.LookAtLHToRef(i,r,W.Pq.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}(0,je.Cg)([(0,$e.P_)()],lm.prototype,"position",null),(0,je.Cg)([(0,$e.P_)()],lm.prototype,"direction",null),(0,je.Cg)([(0,$e.lK)()],lm.prototype,"shadowMinZ",null),(0,je.Cg)([(0,$e.lK)()],lm.prototype,"shadowMaxZ",null),Ze.b.AddNodeConstructor("Light_Type_1",((e,t)=>()=>new hm(e,W.Pq.Zero(),t)));class hm extends lm{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 $t.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&&W.uq.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:t.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:t.maxZ,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,i){const r=this.getScene().activeCamera;if(!r)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const e=W.Pq.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let r=Number.MAX_VALUE,s=-Number.MAX_VALUE;for(let n=0;nthis._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.zs&&(s=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=r,this._shadowMaxZ=s)}const s=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,o=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;W.uq.OrthoOffCenterLHToRef(this._orthoLeft-s*this.shadowOrthoScale,this._orthoRight+s*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,l?a:o,l?o:a,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}}function cm(e,t={},i){t.diameter||(t.diameter=1),t.segments||(t.segments=16);const r=Qo("",{slice:.5,diameter:t.diameter,segments:t.segments},i),s=da("",{radius:t.diameter/2,tessellation:3*t.segments+(4-t.segments)},i);s.rotation.x=-Math.PI/2,s.parent=r;const n=Yt.MergeMeshes([s,r],!0);return n.name=e,n}(0,je.Cg)([(0,$e.lK)()],hm.prototype,"shadowFrustumSize",null),(0,je.Cg)([(0,$e.lK)()],hm.prototype,"shadowOrthoScale",null),(0,je.Cg)([(0,$e.lK)()],hm.prototype,"autoUpdateExtends",void 0),(0,je.Cg)([(0,$e.lK)()],hm.prototype,"autoCalcShadowZBounds",void 0),(0,je.Cg)([(0,$e.lK)("orthoLeft")],hm.prototype,"_orthoLeft",void 0),(0,je.Cg)([(0,$e.lK)("orthoRight")],hm.prototype,"_orthoRight",void 0),(0,je.Cg)([(0,$e.lK)("orthoTop")],hm.prototype,"_orthoTop",void 0),(0,je.Cg)([(0,$e.lK)("orthoBottom")],hm.prototype,"_orthoBottom",void 0),(0,X.Y5)("BABYLON.DirectionalLight",hm);const um={CreateHemisphere:cm};Yt.CreateHemisphere=(e,t,i,r)=>cm(e,{segments:t,diameter:i},r),Ze.b.AddNodeConstructor("Light_Type_2",((e,t)=>()=>new dm(e,W.Pq.Zero(),W.Pq.Zero(),0,0,t)));class dm extends lm{get angle(){return this._angle}set angle(e){this._angle=e,this._cosHalfAngle=Math.cos(.5*e),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()&&(dm._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled((()=>{this._markMeshesAsLightDirty()})):dm._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce((()=>{this._markMeshesAsLightDirty()}))))}static _IsProceduralTexture(e){return void 0!==e.onGeneratedObservable}static _IsTexture(e){return void 0!==e.onLoadObservable}get projectionTextureProjectionLightMatrix(){return this._projectionTextureProjectionLightMatrix}set projectionTextureProjectionLightMatrix(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0}constructor(e,t,i,r,s,n){super(e,n),this._innerAngle=0,this._projectionTextureMatrix=W.uq.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=W.Pq.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=W.Pq.Zero(),this._projectionTextureViewLightMatrix=W.uq.Zero(),this._projectionTextureProjectionLightMatrix=W.uq.Zero(),this._projectionTextureScalingMatrix=W.uq.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=r,this.exponent=s}getClassName(){return"SpotLight"}getTypeID(){return $t.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const r=this.getScene().activeCamera;if(!r)return;this._shadowAngleScale=this._shadowAngleScale||1;const s=this._shadowAngleScale*this._angle,n=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;W.uq.PerspectiveFovLHToRef(s,1,a?o:n,a?n:o,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,a)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.getShadowDirection(),this._projectionTextureViewTargetVector),W.uq.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;const e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),r=-i*t,s=1/Math.tan(this._angle/2);W.uq.FromValuesToRef(s/1,0,0,0,0,s,0,0,0,0,i,1,0,0,r,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof vi.g){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;W.uq.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(.5*this._innerAngle)-this._cosHalfAngle),this._lightAngleOffset=-this._cosHalfAngle*this._lightAngleScale}transferTexturesToEffect(e,t){return this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+t,this._projectionTextureMatrix),e.setTexture("projectionLightTexture"+t,this.projectionTexture)),this}transferToEffect(e,t){let i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=W.Pq.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=W.Pq.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 i=this.computeTransformedInformation()?W.Pq.Normalize(this.transformedDirection):W.Pq.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=void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMaxZ?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())}}(0,je.Cg)([(0,$e.lK)()],dm.prototype,"angle",null),(0,je.Cg)([(0,$e.lK)()],dm.prototype,"innerAngle",null),(0,je.Cg)([(0,$e.lK)()],dm.prototype,"shadowAngleScale",null),(0,je.Cg)([(0,$e.lK)()],dm.prototype,"exponent",void 0),(0,je.Cg)([(0,$e.lK)()],dm.prototype,"projectionTextureLightNear",null),(0,je.Cg)([(0,$e.lK)()],dm.prototype,"projectionTextureLightFar",null),(0,je.Cg)([(0,$e.lK)()],dm.prototype,"projectionTextureUpDirection",null),(0,je.Cg)([(0,$e.uM)("projectedLightTexture")],dm.prototype,"_projectionTexture",void 0),(0,X.Y5)("BABYLON.SpotLight",dm);class fm extends Go{constructor(e=Bo.DefaultUtilityLayer){super(e),this._cachedPosition=new W.Pq,this._cachedForward=new W.Pq(0,0,1),this._pointerObserver=null,this.onClickedObservable=new z.cP,this._light=null,this.attachedMesh=new Yt("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new Pt("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new Un("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new H.v9(.5,.5,.5),this._material.specularColor=new H.v9(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._light&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._light))}),yi.Zp.POINTERDOWN)}get attachedNode(){return this.attachedMesh}set attachedNode(e){Z.V.Warn("Nodes cannot be attached to LightGizmo. Attach to a mesh instead.")}set light(e){if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),this._lightMesh=e instanceof Lo?fm._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof hm?fm._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof dm?fm._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):fm._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._lightMesh.parent=this._rootMesh;const t=this.gizmoLayer._getSharedGizmoLight();if(t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new W.PT,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.parent&&this._attachedMeshParent.freezeWorldMatrix(e.parent.getWorldMatrix()),e.position&&(this.attachedMesh.position.copyFrom(e.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)),e.direction){this.attachedMesh.setDirection(e.direction),this.attachedMesh.computeWorldMatrix(!0);const t=this._getMeshForward();this._cachedForward.copyFrom(t)}this._update()}}get light(){return this._light}get material(){return this._material}_getMeshForward(){let e=this.attachedMesh.forward;return this.attachedMesh.getScene().useRightHandedSystem&&(e.negateToRef(W.AA.Vector3[0]),e=W.AA.Vector3[0]),e}_update(){if(super._update(),this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position)if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{const e=this.attachedMesh.position;this._light.position=new W.Pq(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}if(this._light.direction){const e=this._getMeshForward();if(W.Pq.DistanceSquared(e,this._cachedForward)>1e-4){const t=e;this._light.direction=new W.Pq(t.x,t.y,t.z),this._cachedForward.copyFrom(e)}else W.Pq.DistanceSquared(e,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(e))}}}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),super.dispose(),this._attachedMeshParent.dispose()}static _CreateHemisphericLightMesh(e){const t=new Yt("hemisphereLight",e),i=cm(t.name,{segments:10,diameter:1},e);return i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(3,e).parent=t,t.scaling.scaleInPlace(fm._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){const t=new Yt("pointLight",e),i=Qo(t.name,{segments:10,diameter:1},e);return i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(5,e).parent=t,t.scaling.scaleInPlace(fm._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){const t=new Yt("spotLight",e);Qo(t.name,{segments:10,diameter:1},e).parent=t;const i=cm(t.name,{segments:10,diameter:2},e);return i.parent=t,i.rotation.x=-Math.PI/2,this._CreateLightLines(2,e).parent=t,t.scaling.scaleInPlace(fm._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){const t=new Yt("directionalLight",e),i=new Yt(t.name,e);i.parent=t,Qo(t.name,{diameter:1.2,segments:10},e).parent=i;const r=No(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);r.parent=i;let s=r.clone(t.name);s.scaling.y=.5,s.position.x+=1.25;let n=r.clone(t.name);n.scaling.y=.5,n.position.x+=-1.25;const o=No(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return o.position.y+=3,o.parent=i,s=o.clone(t.name),s.position.y=1.5,s.position.x+=1.25,n=o.clone(t.name),n.position.y=1.5,n.position.x+=-1.25,i.scaling.scaleInPlace(fm._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}}fm._Scale=.007,fm._CreateLightLines=(e,t)=>{const i=new Yt("root",t);i.rotation.x=Math.PI/2;const r=new Yt("linePivot",t);r.parent=i;const s=No("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},t);if(s.position.y=s.scaling.y/2+1.2,s.parent=r,e<2)return r;for(let e=0;e<4;e++){const t=r.clone("lineParentClone");t.rotation.z=Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(let e=0;e<4;e++){const t=r.clone("linePivotClone");t.rotation.z=Math.PI/2,t.rotation.y=Math.PI/2*e}if(e<4)return i;for(let e=0;e<4;e++){const t=r.clone("linePivotClone");t.rotation.z=Math.PI+Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}return e<5||(r.clone("linePivotClone").rotation.z=Math.PI),i};class pm extends Go{constructor(e=Bo.DefaultUtilityLayer,t,i){super(e),this._pointerObserver=null,this.onClickedObservable=new z.cP,this._camera=null,this._invProjection=new hc.uq,this._material=new Un("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._frustumLinesColor=i,this._material.diffuseColor=t??new H.v9(.5,.5,.5),this._material.specularColor=new H.v9(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._camera&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._camera))}),yi.Zp.POINTERDOWN)}get displayFrustum(){return this._cameraLinesMesh.isEnabled()}set displayFrustum(e){this._cameraLinesMesh.setEnabled(e)}set camera(e){if(this._camera=e,this.attachedNode=e,e){this._customMeshSet||(this._cameraMesh&&this._cameraMesh.dispose(),this._cameraMesh=pm._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._cameraMesh.parent=this._rootMesh),this._cameraLinesMesh&&this._cameraLinesMesh.dispose();const t=this._frustumLinesColor?.toColor4(1)??new H.ov(1,1,1,1);this._cameraLinesMesh=pm._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene,t),this._cameraLinesMesh.parent=this._rootMesh,this.gizmoLayer.utilityLayerScene.activeCamera&&this.gizmoLayer.utilityLayerScene.activeCamera.maxZ<1.5*e.maxZ&&(this.gizmoLayer.utilityLayerScene.activeCamera.maxZ=1.5*e.maxZ),this.attachedNode.reservedDataStore||(this.attachedNode.reservedDataStore={}),this.attachedNode.reservedDataStore.cameraGizmo=this;const i=this.gizmoLayer._getSharedGizmoLight();i.includedOnlyMeshes=i.includedOnlyMeshes.concat(this._cameraMesh.getChildMeshes(!1)),this._update()}}get camera(){return this._camera}get material(){return this._material}_update(){super._update(),this._camera&&(this._camera.getProjectionMatrix().invertToRef(this._invProjection),this._cameraLinesMesh.setPivotMatrix(this._invProjection,!1),this._cameraLinesMesh.scaling.x=1/this._rootMesh.scaling.x,this._cameraLinesMesh.scaling.y=1/this._rootMesh.scaling.y,this._cameraLinesMesh.scaling.z=1/this._rootMesh.scaling.z,this._cameraMesh.parent=null,this._cameraMesh.rotation.y=.5*Math.PI*(this._camera.getScene().useRightHandedSystem?1:-1),this._cameraMesh.parent=this._rootMesh)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._cameraMesh&&this._cameraMesh.dispose(),this._cameraMesh=e,this._cameraMesh.parent=this._rootMesh,this._customMeshSet=!0}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._material.dispose(),super.dispose()}static _CreateCameraMesh(e){const t=new Yt("rootCameraGizmo",e),i=new Yt(t.name,e);i.parent=t,Ko(t.name,{width:1,height:.8,depth:.5},e).parent=i;const r=No(t.name,{height:.5,diameterTop:.8,diameterBottom:.8},e);r.parent=i,r.position.y=.3,r.position.x=-.6,r.rotation.x=.5*Math.PI;const s=No(t.name,{height:.5,diameterTop:.6,diameterBottom:.6},e);s.parent=i,s.position.y=.5,s.position.x=.4,s.rotation.x=.5*Math.PI;const n=No(t.name,{height:.5,diameterTop:.5,diameterBottom:.5},e);return n.parent=i,n.position.y=0,n.position.x=.6,n.rotation.z=.5*Math.PI,t.scaling.scaleInPlace(pm._Scale),i.position.x=-.9,t}static _CreateCameraFrustum(e,t){const i=new Yt("rootCameraGizmo",e),r=new Yt(i.name,e);r.parent=i;for(let i=0;i<4;i+=2)for(let s=0;s<4;s+=2){let n=Ra("lines",{points:[new W.Pq(-1+s,-1+i,-1),new W.Pq(-1+s,-1+i,1)],colors:[t,t]},e);n.parent=r,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1,n=Ra("lines",{points:[new W.Pq(-1,-1+s,-1+i),new W.Pq(1,-1+s,-1+i)],colors:[t,t]},e),n.parent=r,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1,n=Ra("lines",{points:[new W.Pq(-1+s,-1,-1+i),new W.Pq(-1+s,1,-1+i)],colors:[t,t]},e),n.parent=r,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1}return i}}pm._Scale=.05;class _m extends ms.w{get direction(){return this._effectWrapper.direction}set direction(e){this._effectWrapper.direction=e}set kernel(e){this._effectWrapper.kernel=e}get kernel(){return this._effectWrapper.kernel}set packedFloat(e){this._effectWrapper.packedFloat=e}get packedFloat(){return this._effectWrapper.packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,r,s=null,n=vi.g.BILINEAR_SAMPLINGMODE,o,a,l=0,h="",c=!1,u=5){const d="number"==typeof r?c:!!r.blockCompilation,f={uniforms:p_.Uniforms,samplers:p_.Samplers,size:"number"==typeof r?r:void 0,camera:s,samplingMode:n,engine:o,reusable:a,textureType:l,vertexUrl:p_.VertexUrl,indexParameters:{varyingCount:0,depCount:0},textureFormat:u,defines:h,...r,blockCompilation:!0};super(e,p_.FragmentUrl,{effectWrapper:"number"!=typeof r&&r.effectWrapper?void 0:new p_(e,o,void 0,void 0,f),...f}),this._effectWrapper.options.blockCompilation=d,this.direction=t,this.onApplyObservable.add((()=>{this._effectWrapper.textureWidth=this._outputTexture?this._outputTexture.width:this.width,this._effectWrapper.textureHeight=this._outputTexture?this._outputTexture.height:this.height})),this.kernel=i}updateEffect(e=null,t=null,i=null,r,s,n){this._effectWrapper._updateParameters(s,n)}static _Parse(e,t,i,r){return it.p.Parse((()=>new _m(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1)),e,i,r)}}(0,je.Cg)([(0,$e.WM)()],_m.prototype,"direction",null),(0,je.Cg)([(0,$e.lK)()],_m.prototype,"kernel",null),(0,je.Cg)([(0,$e.lK)()],_m.prototype,"packedFloat",null),(0,X.Y5)("BABYLON.BlurPostProcess",_m);class mm extends ln.${set blurRatio(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())}get blurRatio(){return this._blurRatio}set adaptiveBlurKernel(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()}set blurKernel(e){this.blurKernelX=e,this.blurKernelY=e}set blurKernelX(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())}get blurKernelX(){return this._blurKernelX}set blurKernelY(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())}get blurKernelY(){return this._blurKernelY}_autoComputeBlurKernel(){const e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i}_onRatioRescale(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()}_updateGammaSpace(){const e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}constructor(e,t,i,r,s=0,n=vi.g.BILINEAR_SAMPLINGMODE,o=!0){if(super(e,t,i,r,!0,s,!1,n,o),this.mirrorPlane=new Ft.Z(0,1,0,1),this._transformMatrix=W.uq.Zero(),this._mirrorMatrix=W.uq.Zero(),this._adaptiveBlurKernel=0,this._blurKernelX=0,this._blurKernelY=0,this._blurRatio=1,!(i=this.getScene()))return this;let a;this.ignoreCameraViewport=!0,this._updateGammaSpace(),this._imageProcessingConfigChangeObserver=i.imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateGammaSpace()})),i.getEngine().supportsUniformBuffers&&(this._sceneUBO=i.createSceneUniformBuffer(`Scene for Mirror Texture (name "${e}")`)),this.onBeforeRenderObservable.add((()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),W.uq.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),a=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=W.Pq.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)})),this.onAfterRenderObservable.add((()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=a}))}_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 _m("horizontal blur",new W.I9(1,0),this._blurKernelX,this._blurRatio,null,vi.g.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new _m("vertical blur",new W.I9(0,1),this._blurKernelY,this._blurRatio,null,vi.g.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,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 mm(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(){super.dispose();const e=this.getScene();e&&e.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),this._sceneUBO?.dispose()}}vi.g._CreateMirror=(e,t,i,r)=>new mm(e,t,i,r);class gm extends js.t{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(W.uq.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let r="";return e.forEach((e=>r+=e)),new gm(r,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,r=!0){const s=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const n=new gm(e,t,null,!1,null,null,null,void 0,!0,i,r);return t.useDelayedTextureLoading=s,n}constructor(e,t,i=null,r=!1,s=null,n=null,o=null,a=5,l=!1,h=null,c=!1,u=.8,d=0,f,p){super(t),this.onLoadObservable=new z.cP,this.boundingBoxPosition=W.Pq.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new W.uq,this._buffer=null,this.name=e,this.url=e,this._noMipmap=r,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=W.uq.Identity(),this.coordinatesMode=vi.g.CUBIC_MODE;let _=null,m=null;null===i||Array.isArray(i)?(this._noMipmap=r,this._format=a,this._createPolynomials=c,_=i,this._loaderOptions=f,this._useSRGBBuffer=p,this._lodScale=u,this._lodOffset=d):(_=i.extensions??null,this._noMipmap=i.noMipmap??!1,s=i.files??null,m=i.buffer??null,this._format=i.format??5,l=i.prefiltered??!1,h=i.forcedExtension??null,this._createPolynomials=i.createPolynomials??!1,this._lodScale=i.lodScale??.8,this._lodOffset=i.lodOffset??0,this._loaderOptions=i.loaderOptions,this._useSRGBBuffer=i.useSRGBBuffer,n=i.onLoad??null,o=i.onError??null),(e||s)&&this.updateURL(e,h,n,l,o,_,this.getScene()?.useDelayedTextureLoading,s,m)}getClassName(){return"CubeTexture"}updateURL(e,t=null,i=null,r=!1,s=null,n=null,o=!1,a=null,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=0===c.indexOf(".dds"),d=0===c.indexOf(".env"),f=0===c.indexOf(".basis");if(d?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=r,r&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),a)this._files=a;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 t=0;t-1!==e.getActiveTextures().indexOf(this))),this._textureMatrix=e,!this.getScene()?.useRightHandedSystem)return;const t=W.AA.Vector3[0],i=W.AA.Quaternion[0],r=W.AA.Vector3[1];this._textureMatrix.decompose(t,i,r),i.z*=-1,i.w*=-1,W.uq.ComposeToRef(t,i,r,this._textureMatrixRefraction)}getRefractionTextureMatrix(){return this.getScene()?.useRightHandedSystem?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){const i=this.getScene(),r=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const s=()=>{this.onLoadObservable.notifyObservers(this),r&&(r.dispose(),this.getScene()?.markAllMaterialsAsDirty(1)),e&&e()},n=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),vi.g.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?Ue.S0.SetImmediate((()=>s())):this._texture.onLoadedObservable.add((()=>s())):(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,this._buffer),this._texture?.onLoadedObservable.add((()=>this.onLoadObservable.notifyObservers(this))))}static Parse(e,t,i){const r=it.p.Parse((()=>{let r=!1;return e.prefiltered&&(r=e.prefiltered),new gm(i+(e.url??e.name),t,e.extensions,!1,e.files||null,null,null,void 0,r,e.forcedExtension)}),e,t);if(e.boundingBoxPosition&&(r.boundingBoxPosition=W.Pq.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=W.Pq.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t{const t=new gm(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t}),this);return t.uniqueId=e,t}}(0,je.Cg)([(0,$e.lK)()],gm.prototype,"url",void 0),(0,je.Cg)([(0,$e.P_)()],gm.prototype,"boundingBoxPosition",void 0),(0,je.Cg)([(0,$e.P_)()],gm.prototype,"boundingBoxSize",null),(0,je.Cg)([(0,$e.lK)("rotationY")],gm.prototype,"rotationY",null),(0,je.Cg)([(0,$e.lK)("files")],gm.prototype,"_files",void 0),(0,je.Cg)([(0,$e.lK)("forcedExtension")],gm.prototype,"_forcedExtension",void 0),(0,je.Cg)([(0,$e.lK)("extensions")],gm.prototype,"_extensions",void 0),(0,je.Cg)([(0,$e.GG)("textureMatrix")],gm.prototype,"_textureMatrix",void 0),(0,je.Cg)([(0,$e.GG)("textureMatrixRefraction")],gm.prototype,"_textureMatrixRefraction",void 0),vi.g._CubeTextureParser=gm.Parse,(0,X.Y5)("BABYLON.CubeTexture",gm);class vm extends xn{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 xm extends bn{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*=2,this.reflectionReflectance0=xm.StandardReflectance0*t,this.reflectionReflectance90=xm.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=xm.StandardReflectance0+(1-xm.StandardReflectance0)*t,this.reflectionReflectance90=xm.StandardReflectance90+(1-xm.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),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()}))))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this.imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this.imageProcessingConfiguration.colorCurves=e}constructor(e,t,i=!1){super(e,t,void 0,i),this.primaryColor=H.v9.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=W.Pq.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 Qe.L(16),this._reflectionControls=W.IU.Zero(),this._white=H.v9.White(),this._primaryShadowColor=H.v9.Black(),this._primaryHighlightColor=H.v9.Black(),this._shadersLoaded=!1,this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._renderTargets.push(this._diffuseTexture),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._renderTargets)}get hasRenderTargetTextures(){return!(!this._diffuseTexture||!this._diffuseTexture.isRenderTarget)||!(!this._reflectionTexture||!this._reflectionTexture.isRenderTarget)}needAlphaTesting(){return!0}needAlphaBlending(){return this.alpha<1||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||this._shadowOnly}isReadyForSubMesh(e,t,r=!1){const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===r)return!0;t.materialDefines||(t.materialDefines=new vm);const n=this.getScene(),o=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const a=n.getEngine();if((0,Bt.az)(n,e,o,!1,this._maxSimultaneousLights),o._needNormals=!0,(0,Bt.VO)(n,o),o._areTexturesDirty){if(o._needUVs=!1,n.texturesEnabled){if(n.getEngine().getCaps().textureLOD&&(o.TEXTURELODSUPPORT=!0),this._diffuseTexture&&Sn.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;(0,Bt.YT)(this._diffuseTexture,o,"DIFFUSE"),o.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,o.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,o.OPACITYFRESNEL=this._opacityFresnel}else o.DIFFUSE=!1,o.DIFFUSEDIRECTUV=0,o.DIFFUSEHASALPHA=!1,o.GAMMADIFFUSE=!1,o.OPACITYFRESNEL=!1;const e=this._reflectionTexture;if(e&&Sn.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;switch(o.REFLECTION=!0,o.GAMMAREFLECTION=e.gammaSpace,o.RGBDREFLECTION=e.isRGBD,o.REFLECTIONBLUR=this._reflectionBlur>0,o.LODINREFLECTIONALPHA=e.lodLevelInAlpha,o.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,o.REFLECTIONBGR=this.switchToBGR,e.coordinatesMode===vi.g.INVCUBIC_MODE&&(o.INVERTCUBICMAP=!0),o.REFLECTIONMAP_3D=e.isCube,o.REFLECTIONMAP_OPPOSITEZ=o.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,e.coordinatesMode){case vi.g.EXPLICIT_MODE:o.REFLECTIONMAP_EXPLICIT=!0;break;case vi.g.PLANAR_MODE:o.REFLECTIONMAP_PLANAR=!0;break;case vi.g.PROJECTION_MODE:o.REFLECTIONMAP_PROJECTION=!0;break;case vi.g.SKYBOX_MODE:o.REFLECTIONMAP_SKYBOX=!0;break;case vi.g.SPHERICAL_MODE:o.REFLECTIONMAP_SPHERICAL=!0;break;case vi.g.EQUIRECTANGULAR_MODE:o.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case vi.g.FIXED_EQUIRECTANGULAR_MODE:o.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case vi.g.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:o.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case vi.g.CUBIC_MODE:case vi.g.INVCUBIC_MODE:default:o.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(o.REFLECTIONFRESNEL=!0,o.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):(o.REFLECTIONFRESNEL=!1,o.REFLECTIONFALLOFF=!1)}else o.REFLECTION=!1,o.REFLECTIONFRESNEL=!1,o.REFLECTIONFALLOFF=!1,o.REFLECTIONBLUR=!1,o.REFLECTIONMAP_3D=!1,o.REFLECTIONMAP_SPHERICAL=!1,o.REFLECTIONMAP_PLANAR=!1,o.REFLECTIONMAP_CUBIC=!1,o.REFLECTIONMAP_PROJECTION=!1,o.REFLECTIONMAP_SKYBOX=!1,o.REFLECTIONMAP_EXPLICIT=!1,o.REFLECTIONMAP_EQUIRECTANGULAR=!1,o.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,o.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,o.INVERTCUBICMAP=!1,o.REFLECTIONMAP_OPPOSITEZ=!1,o.LODINREFLECTIONALPHA=!1,o.GAMMAREFLECTION=!1,o.RGBDREFLECTION=!1}o.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,o.USERGBCOLOR=this._useRGBColor,o.NOISE=this._enableNoise}if(o._areLightsDirty&&(o.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel),o.BACKMAT_SHADOWONLY=this._shadowOnly),o._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(o)}if(o._areMiscDirty&&(o.REFLECTIONMAP_3D&&this._enableGroundProjection?(o.PROJECTED_GROUND=!0,o.REFLECTIONMAP_SKYBOX=!0):o.PROJECTED_GROUND=!1),(0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),o),(0,Bt.OR)(n,a,this,o,r,null,t.getRenderingMesh().hasThinInstances),(0,Bt.qB)(e,o,!1,!0,!1)&&e&&(n.getEngine().getCaps().standardDerivatives||e.isVerticesDataPresent(st.R.NormalKind)||(e.createNormals(!0),Z.V.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name))),o.isDirty){o.markAsProcessed(),n.resetCachedMaterial();const r=new Tn;o.FOG&&r.addFallback(0,"FOG"),o.POINTSIZE&&r.addFallback(1,"POINTSIZE"),o.MULTIVIEW&&r.addFallback(0,"MULTIVIEW"),(0,Bt.c4)(o,r,this._maxSimultaneousLights);const s=[st.R.PositionKind];o.NORMAL&&s.push(st.R.NormalKind),o.UV1&&s.push(st.R.UVKind),o.UV2&&s.push(st.R.UV2Kind),(0,Bt.ni)(s,e,o,r),(0,Bt.ER)(s,o);const l=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos","logarithmicDepthConstant"];(0,Ln.TV)(l);const h=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],c=["Material","Scene"];gn.p&&(gn.p.PrepareUniforms(l,o),gn.p.PrepareSamplers(h,o)),(0,Bt.Bb)({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:o,maxSimultaneousLights:this._maxSimultaneousLights});const u=o.toString(),d=n.getEngine().createEffect("background",{attributes:s,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:u,fallbacks:r,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights},shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{1===this.shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,18135)),Promise.resolve().then(i.bind(i,61853))]):await Promise.all([Promise.resolve().then(i.bind(i,80723)),Promise.resolve().then(i.bind(i,91341))]),this._shadersLoaded=!0}},a);t.setEffect(d,o,this._materialContext),this.buildUniformLayout()}return!(!t.effect||!t.effect.isReady()||(o._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=r,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(){0===this._primaryColorShadowLevel&&0===this._primaryColorHighlightLevel||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))}buildUniformLayout(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.addUniform("projectedGroundInfos",2),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),(0,Bt.f$)(t,this._activeEffect);const o=this._mustRebind(r,n,i,t.visibility);if(o){this._uniformBuffer.bindToEffect(n,"Material"),this.bindViewProjection(n);const e=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync&&!i._drawWrapper._forceRebindOnNextCall||(r.texturesEnabled&&(this._diffuseTexture&&Sn.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),(0,Bt.mA)(this._diffuseTexture,this._uniformBuffer,"diffuse")),e&&Sn.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",e.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",e.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",e.getSize().width,e.lodGenerationScale,e.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),s.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),r.texturesEnabled&&(this._diffuseTexture&&Sn.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),e&&Sn.ReflectionTextureEnabled&&(s.REFLECTIONBLUR&&s.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",e):s.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",e._lodTextureMid||e),this._uniformBuffer.setTexture("reflectionSamplerLow",e._lodTextureLow||e),this._uniformBuffer.setTexture("reflectionSamplerHigh",e._lodTextureHigh||e)):this._uniformBuffer.setTexture("reflectionSampler",e),s.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w))),s.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),(0,Ln.gS)(this._activeEffect,this,r),r.bindEyePosition(n)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(n,"Material"),this._needToBindSceneUbo=!0);!o&&this.isFrozen||(r.lightsEnabled&&(0,Bt.RL)(r,t,this._activeEffect,s,this._maxSimultaneousLights),this.bindView(n),(0,Bt.Yy)(r,t,this._activeEffect,!0),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),this._uniformBuffer.update()}hasTexture(e){return!!super.hasTexture(e)||this._reflectionTexture===e||this._diffuseTexture===e}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return it.p.Clone((()=>new xm(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new xm(e.name,t)),e,t,i)}}xm.StandardReflectance0=.05,xm.StandardReflectance90=.5,(0,je.Cg)([(0,$e.jT)()],xm.prototype,"_primaryColor",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],xm.prototype,"primaryColor",void 0),(0,je.Cg)([(0,$e.jT)()],xm.prototype,"__perceptualColor",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_primaryColorShadowLevel",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_primaryColorHighlightLevel",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],xm.prototype,"primaryColorHighlightLevel",null),(0,je.Cg)([(0,$e.uM)()],xm.prototype,"_reflectionTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"reflectionTexture",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_reflectionBlur",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"reflectionBlur",void 0),(0,je.Cg)([(0,$e.uM)()],xm.prototype,"_diffuseTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"diffuseTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"shadowLights",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_shadowLevel",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"shadowLevel",void 0),(0,je.Cg)([(0,$e.P_)()],xm.prototype,"_sceneCenter",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"sceneCenter",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_opacityFresnel",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"opacityFresnel",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_reflectionFresnel",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"reflectionFresnel",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_reflectionFalloffDistance",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"reflectionFalloffDistance",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_reflectionAmount",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"reflectionAmount",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_reflectionReflectance0",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"reflectionReflectance0",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_reflectionReflectance90",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"reflectionReflectance90",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_useRGBColor",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"useRGBColor",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_enableNoise",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"enableNoise",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_shadowOnly",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],xm.prototype,"shadowOnly",void 0),(0,je.Cg)([(0,$e.n1)()],xm.prototype,"_imageProcessingConfiguration",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],xm.prototype,"enableGroundProjection",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"projectedGroundRadius",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"projectedGroundHeight",void 0),(0,X.Y5)("BABYLON.BackgroundMaterial",xm);class bm{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new H.v9(.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 H.v9(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:W.Pq.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=(e,t)=>{this.onErrorObservable.notifyObservers({message:e,exception:t})},this._options={...bm._GetDefaultOptions(t),...e},this._scene=t,this.onErrorObservable=new z.cP,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 H.ov(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 js.t)return void(this._scene.environmentTexture=this._options.environmentTexture);const e=gm.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new Yt("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||1===this._scene.meshes.length)return{groundSize:e,skyboxSize:t,rootPosition:i};const r=this._scene.getWorldExtends((e=>e!==this._ground&&e!==this._rootMesh&&e!==this._skybox)),s=r.max.subtract(r.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof is&&this._scene.activeCamera.upperRadiusLimit&&(e=2*this._scene.activeCamera.upperRadiusLimit,t=e);const n=s.length();n>e&&(e=2*n,t=e),e*=1.1,t*=1.5,i=r.min.add(s.scale(.5)),i.y=r.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){this._ground&&!this._ground.isDisposed()||(this._ground=Qi("BackgroundPlane",{size:e.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.isPickable=!1,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add((()=>{this._ground=null}))),this._ground.receiveShadows=this._options.enableGroundShadow}_setupGroundMaterial(){this._groundMaterial||(this._groundMaterial=new xm("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(){this._groundMaterial&&(this._groundTexture||(this._options.groundTexture instanceof js.t?this._groundMaterial.diffuseTexture=this._options.groundTexture:(this._groundTexture=new vi.g(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=vi.g.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new mm("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,vi.g.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new Ft.Z(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let e=0;e{this._skybox=null}))),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new xm("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){this._skyboxMaterial&&(this._skyboxTexture||(this._options.skyboxTexture instanceof js.t?this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture:(this._skyboxTexture=new gm(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=vi.g.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)}}bm._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",bm._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",bm._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class Sm extends Pt{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=vi.g.CLAMP_ADDRESSMODE,this._texture.wrapV=vi.g.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=vi.g.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=vi.g.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}constructor(e,t,i,r,s=null){super(e,r),this.onError=s,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=Sm.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new z.cP,this.onLoadObservable=new z.cP,r=this.getScene(),e=e||"textureDome",i.resolution=0|Math.abs(i.resolution)||32,i.clickToPlay=Boolean(i.clickToPlay),i.autoPlay=void 0===i.autoPlay||Boolean(i.autoPlay),i.loop=void 0===i.loop||Boolean(i.loop),i.size=Math.abs(i.size)||(r.activeCamera?.48*r.activeCamera.maxZ:1e3),void 0===i.useDirectMapping?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,void 0===i.faceForward&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=Qo(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:Yt.BACKSIDE},r);const n=this._material=new xm(e+"_material",r);n.useEquirectangularFOV=!0,n.fovMultiplier=1,n.opacityFresnel=!1;const o=this._initTexture(t,r,i);if(this.texture=o,this._mesh.material=n,this._mesh.parent=this,this._halfDomeMask=Qo("",{slice:.5,diameter:.98*i.size,segments:2*i.resolution,sideOrientation:Yt.BACKSIDE},r),this._halfDomeMask.rotate(hc._0.X,-Math.PI/2),this._halfDomeMask.parent=this._mesh,this._halfDome=!!i.halfDomeMode,this._halfDomeMask.setEnabled(this._halfDome),this._crossEye=!!i.crossEyeMode,this._texture.anisotropicFilteringLevel=1,this._texture.onLoadObservable.addOnce((()=>{this._setReady(!0)})),i.faceForward&&r.activeCamera){const e=r.activeCamera,t=W.Pq.Forward(),i=W.Pq.TransformNormal(t,e.getViewMatrix());i.normalize(),this.rotation.y=Math.acos(W.Pq.Dot(t,i))}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 Sm.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case Sm.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;const e=this._halfDome?0:.5,t=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((i=>{let r=i.isRightCamera;this._crossEye&&(r=!r),this._texture.uOffset=r?e:t}));break}case Sm.MODE_TOPBOTTOM:this._texture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((e=>{let t=e.isRightCamera;this._crossEye&&(t=!t),this._texture.vOffset=t?.5:0}))}}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)}}Sm.MODE_MONOSCOPIC=0,Sm.MODE_TOPBOTTOM=1,Sm.MODE_SIDEBYSIDE=2;class Tm extends Sm{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 vi.g(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,(()=>{this.onLoadObservable.notifyObservers()}),((e,t)=>{this.onLoadErrorObservable.notifyObservers(e||"Unknown error occured"),this.onError&&this.onError(e,t)}))}}Tm.MODE_MONOSCOPIC=Sm.MODE_MONOSCOPIC,Tm.MODE_TOPBOTTOM=Sm.MODE_TOPBOTTOM,Tm.MODE_SIDEBYSIDE=Sm.MODE_SIDEBYSIDE;var Cm=i(2069);let ym=0;const Em=e=>{if(!e.environmentBRDFTexture){const t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;const i=e._blockEntityCollection;e._blockEntityCollection=!1;const r=vi.g.CreateFromBase64String("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==","EnvironmentBRDFTexture"+ym++,e,!0,!1,vi.g.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;const s=e.getEngine().getLoadedTexturesCache(),n=s.indexOf(r.getInternalTexture());-1!==n&&s.splice(n,1),r.isRGBD=!0,r.wrapU=vi.g.CLAMP_ADDRESSMODE,r.wrapV=vi.g.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=r,e.useDelayedTextureLoading=t,Cm.G.ExpandRGBDTexture(r);const o=e.getEngine().onContextRestoredObservable.add((()=>{r.isRGBD=!0;const t=e.onBeforeRenderObservable.add((()=>{r.isReady()&&(e.onBeforeRenderObservable.remove(t),Cm.G.ExpandRGBDTexture(r))}))}));e.onDisposeObservable.add((()=>{e.getEngine().onContextRestoredObservable.remove(o)}))}return e.environmentBRDFTexture},Pm={GetEnvironmentBRDFTexture:Em};class Am extends xn{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 Rm extends Dn{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRBRDF",90,new Am,t),this._useEnergyConservation=Rm.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=Rm.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=Rm.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=Rm.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=Rm.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=Rm.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=Rm.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=Rm.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"}}Rm.DEFAULT_USE_ENERGY_CONSERVATION=!0,Rm.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,Rm.DEFAULT_USE_SPHERICAL_HARMONICS=!0,Rm.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],Rm.prototype,"useEnergyConservation",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],Rm.prototype,"useSmithVisibilityHeightCorrelated",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],Rm.prototype,"useSphericalHarmonics",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],Rm.prototype,"useSpecularGlossinessInputEnergyConservation",void 0),i(54699);class Im extends xn{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 Mm extends Dn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRClearCoat",100,new Im,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=Mm._DefaultIndexOfRefraction,this.indexOfRefraction=Mm._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=H.v9.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){if(!this._isEnabled)return!0;const r=this._material._disableBumpMap;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&Sn.ClearCoatTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&Sn.ClearCoatTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1;if(i.getCaps().standardDerivatives&&this._bumpTexture&&Sn.ClearCoatBumpTextureEnabled&&!r&&!this._bumpTexture.isReady())return!1;if(this._isTintEnabled&&this._tintTexture&&Sn.ClearCoatTintTextureEnabled&&!this._tintTexture.isReadyOrNotBlocking())return!1}return!0}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&&Sn.ClearCoatTextureEnabled?(0,Bt.YT)(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&Sn.ClearCoatTextureEnabled?(0,Bt.YT)(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&Sn.ClearCoatBumpTextureEnabled?(0,Bt.YT)(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===Mm._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&Sn.ClearCoatTintTextureEnabled?((0,Bt.YT)(this._tintTexture,e,"CLEARCOAT_TINT_TEXTURE"),e.CLEARCOAT_TINT_GAMMATEXTURE=this._tintTexture.gammaSpace):e.CLEARCOAT_TINT_TEXTURE=!1):(e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1))):(e.CLEARCOAT=!1,e.CLEARCOAT_TEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.CLEARCOAT_DEFAULTIOR=!1,e.CLEARCOAT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,e.CLEARCOAT_BUMPDIRECTUV=0,e.CLEARCOAT_REMAP_F0=!1,e.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TINT_GAMMATEXTURE=!1)}bindForSubMesh(e,t,i,r){if(!this._isEnabled)return;const s=r.materialDefines,n=this._material.isFrozen,o=this._material._disableBumpMap,a=this._material._invertNormalMapX,l=this._material._invertNormalMapY;if(!e.useUbo||!n||!e.isSync){(this._texture||this._textureRoughness)&&Sn.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._textureRoughness?.coordinatesIndex??0,this._textureRoughness?.level??0),this._texture&&(0,Bt.mA)(this._texture,e,"clearCoat"),this._textureRoughness&&!s.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&(0,Bt.mA)(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&Sn.ClearCoatTextureEnabled&&!o&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),(0,Bt.mA)(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",a?1:-1,l?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",a?-1:1,l?-1:1)),this._tintTexture&&Sn.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),(0,Bt.mA)(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);const r=1-this._indexOfRefraction,n=1+this._indexOfRefraction,h=Math.pow(-r/n,2),c=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",h,c,r,n),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&&Sn.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!s.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&Sn.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&Sn.ClearCoatBumpTextureEnabled&&!o&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&Sn.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){e&&(this._texture?.dispose(),this._textureRoughness?.dispose(),this._bumpTexture?.dispose(),this._tintTexture?.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"}]}}}Mm._DefaultIndexOfRefraction=1.5,(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"isEnabled",void 0),(0,je.Cg)([(0,$e.lK)()],Mm.prototype,"intensity",void 0),(0,je.Cg)([(0,$e.lK)()],Mm.prototype,"roughness",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"indexOfRefraction",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"texture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"useRoughnessFromMainTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"textureRoughness",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"remapF0OnInterfaceChange",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"bumpTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"isTintEnabled",void 0),(0,je.Cg)([(0,$e.jT)()],Mm.prototype,"tintColor",void 0),(0,je.Cg)([(0,$e.lK)()],Mm.prototype,"tintColorAtDistance",void 0),(0,je.Cg)([(0,$e.lK)()],Mm.prototype,"tintThickness",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"tintTexture",void 0);class Om extends xn{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 Dm extends Dn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRIridescence",110,new Om,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=Dm._DefaultMinimumThickness,this.maximumThickness=Dm._DefaultMaximumThickness,this.indexOfRefraction=Dm._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&Sn.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._thicknessTexture&&Sn.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.IRIDESCENCE=!0,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Sn.IridescenceTextureEnabled?(0,Bt.YT)(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,this._thicknessTexture&&Sn.IridescenceTextureEnabled?(0,Bt.YT)(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){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||((this._texture||this._thicknessTexture)&&Sn.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._thicknessTexture?.coordinatesIndex??0,this._thicknessTexture?.level??0),this._texture&&(0,Bt.mA)(this._texture,e,"iridescence"),this._thicknessTexture&&(0,Bt.mA)(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&Sn.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&Sn.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){e&&(this._texture?.dispose(),this._thicknessTexture?.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"}]}}}Dm._DefaultMinimumThickness=100,Dm._DefaultMaximumThickness=400,Dm._DefaultIndexOfRefraction=1.3,(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Dm.prototype,"isEnabled",void 0),(0,je.Cg)([(0,$e.lK)()],Dm.prototype,"intensity",void 0),(0,je.Cg)([(0,$e.lK)()],Dm.prototype,"minimumThickness",void 0),(0,je.Cg)([(0,$e.lK)()],Dm.prototype,"maximumThickness",void 0),(0,je.Cg)([(0,$e.lK)()],Dm.prototype,"indexOfRefraction",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Dm.prototype,"texture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Dm.prototype,"thicknessTexture",void 0);class wm extends xn{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class Nm extends Dn{set angle(e){this.direction.x=Math.cos(e),this.direction.y=Math.sin(e)}get angle(){return Math.atan2(this.direction.y,this.direction.x)}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markAllSubMeshesAsMiscDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsMiscDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new wm,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new W.I9(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&&Sn.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(st.R.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Sn.AnisotropicTextureEnabled?(0,Bt.YT)(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&&Sn.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),(0,Bt.mA)(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&Sn.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),void 0===e.legacy&&(this.legacy=!0)}}(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Nm.prototype,"isEnabled",void 0),(0,je.Cg)([(0,$e.lK)()],Nm.prototype,"intensity",void 0),(0,je.Cg)([(0,$e.WM)()],Nm.prototype,"direction",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Nm.prototype,"texture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],Nm.prototype,"legacy",void 0);class Fm extends xn{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 Lm extends Dn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"Sheen",120,new Fm,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=H.v9.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){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&Sn.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&Sn.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.SHEEN=!0,e.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,e.SHEEN_ROUGHNESS=null!==this._roughness,e.SHEEN_ALBEDOSCALING=this._albedoScaling,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Sn.SheenTextureEnabled?((0,Bt.YT)(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&Sn.SheenTextureEnabled?(0,Bt.YT)(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,r){if(!this._isEnabled)return;const s=r.materialDefines,n=this._material.isFrozen;e.useUbo&&n&&e.isSync||((this._texture||this._textureRoughness)&&Sn.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._textureRoughness?.coordinatesIndex??0,this._textureRoughness?.level??0),this._texture&&(0,Bt.mA)(this._texture,e,"sheen"),this._textureRoughness&&!s.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&(0,Bt.mA)(this._textureRoughness,e,"sheenRoughness")),e.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity),null!==this._roughness&&e.updateFloat("vSheenRoughness",this._roughness)),t.texturesEnabled&&(this._texture&&Sn.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!s.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&Sn.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){e&&(this._texture?.dispose(),this._textureRoughness?.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"}]}}}(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Lm.prototype,"isEnabled",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Lm.prototype,"linkSheenWithAlbedo",void 0),(0,je.Cg)([(0,$e.lK)()],Lm.prototype,"intensity",void 0),(0,je.Cg)([(0,$e.jT)()],Lm.prototype,"color",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Lm.prototype,"texture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Lm.prototype,"useRoughnessFromMainTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Lm.prototype,"roughness",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Lm.prototype,"textureRoughness",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Lm.prototype,"albedoScaling",void 0);class Bm extends xn{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 Vm extends Dn{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){this._volumeIndexOfRefraction=e>=1?e:-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRSubSurface",130,new Bm,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=H.v9.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=H.v9.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&&Sn.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;if(this._translucencyColorTexture&&Sn.TranslucencyColorTextureEnabled&&!this._translucencyColorTexture.isReadyOrNotBlocking())return!1;if(this._translucencyIntensityTexture&&Sn.TranslucencyIntensityTextureEnabled&&!this._translucencyIntensityTexture.isReadyOrNotBlocking())return!1;const e=this._getRefractionTexture(t);if(e&&Sn.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return 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,void(e.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0);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&&Sn.ThicknessTextureEnabled&&(0,Bt.YT)(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&Sn.RefractionIntensityTextureEnabled&&(0,Bt.YT)(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&Sn.TranslucencyIntensityTextureEnabled&&(0,Bt.YT)(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE"),this._translucencyColorTexture&&Sn.TranslucencyColorTextureEnabled&&(0,Bt.YT)(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&&Sn.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,r){if(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled)if(0===this.maximumThickness&&0===this.minimumThickness)e.updateFloat2("vThicknessParam",0,0);else{r.getRenderingMesh().getWorldMatrix().decompose(W.AA.Vector3[0]);const t=Math.max(Math.abs(W.AA.Vector3[0].x),Math.abs(W.AA.Vector3[0].y),Math.abs(W.AA.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*t,(this.maximumThickness-this.minimumThickness)*t)}}bindForSubMesh(e,t,i,r){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const s=r.materialDefines,n=this._material.isFrozen,o=this._material.realTimeFiltering,a=s.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&Sn.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),(0,Bt.mA)(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&Sn.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),(0,Bt.mA)(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyColorTexture&&Sn.TranslucencyColorTextureEnabled&&s.SS_TRANSLUCENCYCOLOR_TEXTURE&&(e.updateFloat2("vTranslucencyColorInfos",this._translucencyColorTexture.coordinatesIndex,this._translucencyColorTexture.level),(0,Bt.mA)(this._translucencyColorTexture,e,"translucencyColor")),this._translucencyIntensityTexture&&Sn.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),(0,Bt.mA)(this._translucencyIntensityTexture,e,"translucencyIntensity")),l&&Sn.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",l.getRefractionTextureMatrix());let t=1;l.isCube||l.depth&&(t=l.depth);const i=l.getSize().width,r=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",l.level,1/r,t,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",i,l.lodGenerationScale,l.lodGenerationOffset,1/this.indexOfRefraction),o&&e.updateFloat2("vRefractionFilteringInfo",i,Math.log2(i)),l.boundingBoxSize){const t=l;e.updateVector3("vRefractionPosition",t.boundingBoxPosition),e.updateVector3("vRefractionSize",t.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&&Sn.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&Sn.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&Sn.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),this._translucencyColorTexture&&Sn.TranslucencyColorTextureEnabled&&s.SS_TRANSLUCENCYCOLOR_TEXTURE&&e.setTexture("translucencyColorSampler",this._translucencyColorTexture),l&&Sn.RefractionTextureEnabled&&(a?e.setTexture("refractionSampler",l):(e.setTexture("refractionSampler",l._lodTextureMid||l),e.setTexture("refractionSamplerLow",l._lodTextureLow||l),e.setTexture("refractionSamplerHigh",l._lodTextureHigh||l))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){Sn.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!!(Sn.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture),this._translucencyColorTexture&&e.push(this._translucencyColorTexture),this._translucencyIntensityTexture&&e.push(this._translucencyIntensityTexture)}getAnimatables(e){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),this._translucencyColorTexture&&this._translucencyColorTexture.animations&&this._translucencyColorTexture.animations.length>0&&e.push(this._translucencyColorTexture),this._translucencyIntensityTexture&&this._translucencyIntensityTexture.animations&&this._translucencyIntensityTexture.animations.length>0&&e.push(this._translucencyIntensityTexture)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose(),this._translucencyColorTexture&&this._translucencyColorTexture.dispose(),this._translucencyIntensityTexture&&this._translucencyIntensityTexture.dispose())}getClassName(){return"PBRSubSurfaceConfiguration"}addFallbacks(e,t,i){return e.SS_SCATTERING&&t.addFallback(i++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i}getSamplers(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh","translucencyColorSampler")}getUniforms(){return{ubo:[{name:"vRefractionMicrosurfaceInfos",size:4,type:"vec4"},{name:"vRefractionFilteringInfo",size:2,type:"vec2"},{name:"vTranslucencyIntensityInfos",size:2,type:"vec2"},{name:"vRefractionInfos",size:4,type:"vec4"},{name:"refractionMatrix",size:16,type:"mat4"},{name:"vThicknessInfos",size:2,type:"vec2"},{name:"vRefractionIntensityInfos",size:2,type:"vec2"},{name:"thicknessMatrix",size:16,type:"mat4"},{name:"refractionIntensityMatrix",size:16,type:"mat4"},{name:"translucencyIntensityMatrix",size:16,type:"mat4"},{name:"vThicknessParam",size:2,type:"vec2"},{name:"vDiffusionDistance",size:3,type:"vec3"},{name:"vTintColor",size:4,type:"vec4"},{name:"vSubSurfaceIntensity",size:3,type:"vec3"},{name:"vRefractionPosition",size:3,type:"vec3"},{name:"vRefractionSize",size:3,type:"vec3"},{name:"scatteringDiffusionProfile",size:1,type:"float"},{name:"dispersion",size:1,type:"float"},{name:"vTranslucencyColor",size:4,type:"vec4"},{name:"vTranslucencyColorInfos",size:2,type:"vec2"},{name:"translucencyColorMatrix",size:16,type:"mat4"}]}}}(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"isRefractionEnabled",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"isTranslucencyEnabled",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"isDispersionEnabled",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markScenePrePassDirty")],Vm.prototype,"isScatteringEnabled",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"_scatteringDiffusionProfileIndex",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"refractionIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"translucencyIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"useAlbedoToTintRefraction",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"useAlbedoToTintTranslucency",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"thicknessTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"refractionTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"indexOfRefraction",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"_volumeIndexOfRefraction",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"volumeIndexOfRefraction",null),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"invertRefractionY",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"linkRefractionWithTransparency",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"minimumThickness",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"maximumThickness",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"useThicknessAsDepth",void 0),(0,je.Cg)([(0,$e.jT)()],Vm.prototype,"tintColor",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"tintColorAtDistance",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"dispersion",void 0),(0,je.Cg)([(0,$e.jT)()],Vm.prototype,"diffusionDistance",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"useMaskFromThicknessTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"refractionIntensityTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"translucencyIntensityTexture",void 0),(0,je.Cg)([(0,$e.jT)()],Vm.prototype,"translucencyColor",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"translucencyColorTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"useGltfStyleTextures",void 0);const km={effect:null,subMesh:null};class Um extends xn{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_COLOR=!1,this.PREPASS_COLOR_INDEX=-1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO=!1,this.PREPASS_ALBEDO_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_SCREENSPACE_DEPTH=!1,this.PREPASS_SCREENSPACE_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_WORLD_NORMAL=!1,this.PREPASS_WORLD_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_LOCAL_POSITION=!1,this.PREPASS_LOCAL_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_VELOCITY_LINEAR=!1,this.PREPASS_VELOCITY_LINEAR_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}}class Gm extends bn{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),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}constructor(e,t,i=!1){super(e,t,void 0,i||Gm.ForceGLSL),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new W.IU(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=Gm.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=H.v9.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new H.v9(0,0,0),this._albedoColor=new H.v9(1,1,1),this._reflectivityColor=new H.v9(1,1,1),this._reflectionColor=new H.v9(1,1,1),this._emissiveColor=new H.v9(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=Gm.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 Qe.L(16),this._globalAmbientColor=new H.v9(0,0,0),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this._shadersLoaded=!1,this._breakShaderLoadedCheck=!1,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new Rm(this),this.clearCoat=new Mm(this),this.iridescence=new Dm(this),this.anisotropy=new Nm(this),this.sheen=new Lm(this),this.subSurface=new Vm(this),this.detailMap=new Nn(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),Sn.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=Em(this.getScene()),this.prePassConfiguration=new vn}get hasRenderTargetTextures(){return!!(Sn.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){return this._transparencyMode===Gm.PBRMATERIAL_OPAQUE||this._transparencyMode===Gm.PBRMATERIAL_ALPHATEST||this.subSurface?.disableAlphaBlending}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromAlbedoTexture())}needAlphaTesting(){return!!this._forceAlphaTest||!this.subSurface?.disableAlphaBlending&&this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===Gm.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==Gm.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new Um(this._eventInfo.defineNames));const s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=this.getScene(),o=n.getEngine();if(s._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n.texturesEnabled)){if(this._albedoTexture&&Sn.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking())return!1;if(this._ambientTexture&&Sn.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking())return!1;if(this._opacityTexture&&Sn.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const e=this._getReflectionTexture();if(e&&Sn.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture){if(!e.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!e.sphericalPolynomial&&e.getInternalTexture()?._sphericalPolynomialPromise)return!1}if(this._lightmapTexture&&Sn.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking())return!1;if(this._emissiveTexture&&Sn.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(Sn.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())return!1;if(this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking())return!1;if(this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(o.getCaps().standardDerivatives&&this._bumpTexture&&Sn.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady())return!1;if(this._environmentBRDFTexture&&Sn.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(s._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;o.getCaps().standardDerivatives||e.isVerticesDataPresent(st.R.NormalKind)||(e.createNormals(!0),Z.V.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const a=t.effect,l=s._areLightsDisposed;let h=this._prepareEffect(e,s,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),c=!1;if(h)if(this._onEffectCreatedObservable&&(km.effect=h,km.subMesh=t,this._onEffectCreatedObservable.notifyObservers(km)),this.allowShaderHotSwapping&&a&&!h.isReady()){if(h=a,s.markAsUnprocessed(),c=this.isFrozen,l)return s._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(h,s,this._materialContext);return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!c,r._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),0))}isMetallicWorkflow(){return!(null==this._metallic&&null==this._roughness&&!this._metallicTexture)}_prepareEffect(e,t,r=null,s=null,n=null,o=null,a){if(this._prepareDefines(e,t,n,o,a),!t.isDirty)return null;t.markAsProcessed();const l=this.getScene().getEngine(),h=new Tn;let c=0;t.USESPHERICALINVERTEX&&h.addFallback(c++,"USESPHERICALINVERTEX"),t.FOG&&h.addFallback(c,"FOG"),t.SPECULARAA&&h.addFallback(c,"SPECULARAA"),t.POINTSIZE&&h.addFallback(c,"POINTSIZE"),t.LOGARITHMICDEPTH&&h.addFallback(c,"LOGARITHMICDEPTH"),t.PARALLAX&&h.addFallback(c,"PARALLAX"),t.PARALLAX_RHS&&h.addFallback(c,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&h.addFallback(c++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&h.addFallback(c++,"ENVIRONMENTBRDF"),t.TANGENT&&h.addFallback(c++,"TANGENT"),t.BUMP&&h.addFallback(c++,"BUMP"),c=(0,Bt.c4)(t,h,this._maxSimultaneousLights,c++),t.SPECULARTERM&&h.addFallback(c++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&h.addFallback(c++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&h.addFallback(c++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&h.addFallback(c++,"LIGHTMAP"),t.NORMAL&&h.addFallback(c++,"NORMAL"),t.AMBIENT&&h.addFallback(c++,"AMBIENT"),t.EMISSIVE&&h.addFallback(c++,"EMISSIVE"),t.VERTEXCOLOR&&h.addFallback(c++,"VERTEXCOLOR"),t.MORPHTARGETS&&h.addFallback(c++,"MORPHTARGETS"),t.MULTIVIEW&&h.addFallback(0,"MULTIVIEW");const u=[st.R.PositionKind];t.NORMAL&&u.push(st.R.NormalKind),t.TANGENT&&u.push(st.R.TangentKind);for(let e=1;e<=6;++e)t["UV"+e]&&u.push(`uv${1===e?"":e}`);t.VERTEXCOLOR&&u.push(st.R.ColorKind),(0,Bt.ni)(u,e,t,h),(0,Bt.ER)(u,t),(0,Bt.IF)(u,e,t),(0,Bt.J2)(u,e,t);let d="pbr";const f=["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"],p=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],_=["Material","Scene","Mesh"],m={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=h,this._eventInfo.fallbackRank=c,this._eventInfo.defines=t,this._eventInfo.uniforms=f,this._eventInfo.attributes=u,this._eventInfo.samplers=p,this._eventInfo.uniformBuffersNames=_,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=m,this._callbackPluginEventGeneric(128,this._eventInfo),Bn.AddUniformsAndSamplers(f,p),vn.AddUniforms(f),vn.AddSamplers(p),(0,Ln.TV)(f),gn.p&&(gn.p.PrepareUniforms(f,t),gn.p.PrepareSamplers(p,t)),(0,Bt.Bb)({uniformsNames:f,uniformBuffersNames:_,samplers:p,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const g={};this.customShaderNameResolve&&(d=this.customShaderNameResolve(d,f,_,p,t,u,g));const v=t.toString(),x=l.createEffect(d,{attributes:u,uniformsNames:f,uniformBuffersNames:_,samplers:p,defines:v,fallbacks:h,onCompiled:r,onError:s,indexParameters:m,processFinalCode:g.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{1===this.shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,431)),Promise.resolve().then(i.bind(i,66854))]):await Promise.all([Promise.resolve().then(i.bind(i,60693)),Promise.resolve().then(i.bind(i,43004))]),this._shadersLoaded=!0}},l);return this._eventInfo.customCode=void 0,x}_prepareDefines(e,t,i=null,r=null,s=!1){const n=this.getScene(),o=n.getEngine();(0,Bt.az)(n,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,(0,Bt.VO)(n,t);const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if((0,Bt.N4)(n,t,this.canRenderToMRT&&!a),(0,Bt.Nc)(n,t,a),Bn.PrepareDefines(o.currentRenderPassId,e,t),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=6;++e)t["MAINUV"+e]=!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&&Sn.DiffuseTextureEnabled?((0,Bt.YT)(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&Sn.AmbientTextureEnabled?((0,Bt.YT)(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&Sn.OpacityTextureEnabled?((0,Bt.YT)(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const e=this._getReflectionTexture();if(e&&Sn.ReflectionTextureEnabled){switch(t.REFLECTION=!0,t.GAMMAREFLECTION=e.gammaSpace,t.RGBDREFLECTION=e.isRGBD,t.LODINREFLECTIONALPHA=e.lodLevelInAlpha,t.LINEARSPECULARREFLECTION=e.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=e.coordinatesMode===vi.g.INVCUBIC_MODE,t.REFLECTIONMAP_3D=e.isCube,t.REFLECTIONMAP_OPPOSITEZ=t.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.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,e.coordinatesMode){case vi.g.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case vi.g.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case vi.g.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case vi.g.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case vi.g.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case vi.g.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case vi.g.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case vi.g.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case vi.g.CUBIC_MODE:case vi.g.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==vi.g.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.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&&Sn.LightmapTextureEnabled?((0,Bt.YT)(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&Sn.EmissiveTextureEnabled?((0,Bt.YT)(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,Sn.SpecularTextureEnabled?(this._metallicTexture?((0,Bt.YT)(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?((0,Bt.YT)(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?((0,Bt.YT)(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?((0,Bt.YT)(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1):(t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1),this._microSurfaceTexture?(0,Bt.YT)(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1):(t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1),o.getCaps().standardDerivatives&&this._bumpTexture&&Sn.BumpTextureEnabled&&!this._disableBumpMap?((0,Bt.YT)(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&Sn.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&&Sn.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===Gm.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===Gm.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=7===this.alphaMode||8===this.alphaMode,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&&((0,Bt.fm)(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(st.R.NormalKind),t.DEBUGMODE=this._debugMode),(0,Bt.OR)(n,o,this,t,!!i,r,s),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),(0,Bt.qB)(e,t,!0,!0,!0,this._transparencyMode!==Gm.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const r={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(4,this._eventInfo),(()=>{if(this._breakShaderLoadedCheck)return;const i=new Um(this._eventInfo.defineNames),s=this._prepareEffect(e,i,void 0,void 0,r.useInstances,r.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(km.effect=s,km.subMesh=null,this._onEffectCreatedObservable.notifyObservers(km)),s.isReady()?t&&t(this):s.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){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e);const o=r.getEngine();this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,r,t,e,this.isFrozen),Bn.Bind(o.currentRenderPassId,this._activeEffect,t,e),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),s.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const a=this._mustRebind(r,n,i,t.visibility);(0,Bt.f$)(t,this._activeEffect,this.prePassConfiguration);let l=null;const h=this._uniformBuffer;if(a){if(this.bindViewProjection(n),l=this._getReflectionTexture(),!h.useUbo||!this.isFrozen||!h.isSync||i._drawWrapper._forceRebindOnNextCall){if(r.texturesEnabled){if(this._albedoTexture&&Sn.DiffuseTextureEnabled&&(h.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),(0,Bt.mA)(this._albedoTexture,h,"albedo")),this._ambientTexture&&Sn.AmbientTextureEnabled&&(h.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),(0,Bt.mA)(this._ambientTexture,h,"ambient")),this._opacityTexture&&Sn.OpacityTextureEnabled&&(h.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),(0,Bt.mA)(this._opacityTexture,h,"opacity")),l&&Sn.ReflectionTextureEnabled){if(h.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),h.updateFloat2("vReflectionInfos",l.level,0),l.boundingBoxSize){const e=l;h.updateVector3("vReflectionPosition",e.boundingBoxPosition),h.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){const e=l.getSize().width;h.updateFloat2("vReflectionFilteringInfo",e,Math.log2(e))}if(!s.USEIRRADIANCEMAP){const e=l.sphericalPolynomial;if(s.USESPHERICALFROMREFLECTIONMAP&&e)if(s.SPHERICAL_HARMONICS){const t=e.preScaledHarmonics;h.updateVector3("vSphericalL00",t.l00),h.updateVector3("vSphericalL1_1",t.l1_1),h.updateVector3("vSphericalL10",t.l10),h.updateVector3("vSphericalL11",t.l11),h.updateVector3("vSphericalL2_2",t.l2_2),h.updateVector3("vSphericalL2_1",t.l2_1),h.updateVector3("vSphericalL20",t.l20),h.updateVector3("vSphericalL21",t.l21),h.updateVector3("vSphericalL22",t.l22)}else h.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),h.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),h.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),h.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),h.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),h.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),h.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),h.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),h.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}h.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset)}this._emissiveTexture&&Sn.EmissiveTextureEnabled&&(h.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),(0,Bt.mA)(this._emissiveTexture,h,"emissive")),this._lightmapTexture&&Sn.LightmapTextureEnabled&&(h.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),(0,Bt.mA)(this._lightmapTexture,h,"lightmap")),Sn.SpecularTextureEnabled&&(this._metallicTexture?(h.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),(0,Bt.mA)(this._metallicTexture,h,"reflectivity")):this._reflectivityTexture&&(h.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),(0,Bt.mA)(this._reflectivityTexture,h,"reflectivity")),this._metallicReflectanceTexture&&(h.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),(0,Bt.mA)(this._metallicReflectanceTexture,h,"metallicReflectance")),this._reflectanceTexture&&s.REFLECTANCE&&(h.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),(0,Bt.mA)(this._reflectanceTexture,h,"reflectance")),this._microSurfaceTexture&&(h.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),(0,Bt.mA)(this._microSurfaceTexture,h,"microSurfaceSampler"))),this._bumpTexture&&o.getCaps().standardDerivatives&&Sn.BumpTextureEnabled&&!this._disableBumpMap&&(h.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),(0,Bt.mA)(this._bumpTexture,h,"bump"),r._mirroredCameraPosition?h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&h.updateFloat("pointSize",this.pointSize),s.METALLICWORKFLOW){H.IG.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,H.IG.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,h.updateColor4("vReflectivityColor",H.IG.Color3[0],1);const e=this.subSurface?._indexOfRefraction??1.5,t=1,i=Math.pow((e-t)/(e+t),2);this._metallicReflectanceColor.scaleToRef(i*this._metallicF0Factor,H.IG.Color3[0]);const r=this._metallicF0Factor;h.updateColor4("vMetallicReflectanceFactors",H.IG.Color3[0],r)}else h.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);h.updateColor3("vEmissiveColor",Sn.EmissiveTextureEnabled?this._emissiveColor:H.v9.BlackReadOnly),h.updateColor3("vReflectionColor",this._reflectionColor),!s.SS_REFRACTION&&this.subSurface?._linkRefractionWithTransparency?h.updateColor4("vAlbedoColor",this._albedoColor,1):h.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*r.environmentIntensity,this._lightingInfos.w=this._specularIntensity,h.updateVector4("vLightingIntensity",this._lightingInfos),r.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),h.updateColor3("vAmbientColor",this._globalAmbientColor),h.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}r.texturesEnabled&&(this._albedoTexture&&Sn.DiffuseTextureEnabled&&h.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&Sn.AmbientTextureEnabled&&h.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&Sn.OpacityTextureEnabled&&h.setTexture("opacitySampler",this._opacityTexture),l&&Sn.ReflectionTextureEnabled&&(s.LODBASEDMICROSFURACE?h.setTexture("reflectionSampler",l):(h.setTexture("reflectionSampler",l._lodTextureMid||l),h.setTexture("reflectionSamplerLow",l._lodTextureLow||l),h.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l)),s.USEIRRADIANCEMAP&&h.setTexture("irradianceSampler",l.irradianceTexture)),s.ENVIRONMENTBRDF&&h.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&Sn.EmissiveTextureEnabled&&h.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&Sn.LightmapTextureEnabled&&h.setTexture("lightmapSampler",this._lightmapTexture),Sn.SpecularTextureEnabled&&(this._metallicTexture?h.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&h.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&h.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&s.REFLECTANCE&&h.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&h.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&o.getCaps().standardDerivatives&&Sn.BumpTextureEnabled&&!this._disableBumpMap&&h.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),(0,Ln.gS)(this._activeEffect,this,r),this.bindEyePosition(n)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!a&&this.isFrozen||(r.lightsEnabled&&!this._disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s,this._maxSimultaneousLights),(r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE||l||this.subSurface.refractionTexture||t.receiveShadows||s.PREPASS)&&this.bindView(n),(0,Bt.Yy)(r,t,this._activeEffect,!0),s.NUM_MORPH_INFLUENCERS&&(0,Bt.nR)(t,this._activeEffect),s.BAKED_VERTEX_ANIMATION_TEXTURE&&t.bakedVertexAnimationManager?.bind(n,s.INSTANCES),this._imageProcessingConfiguration.bind(this._activeEffect),(0,Bt.DL)(s,this._activeEffect,r)),this._afterBind(t,this._activeEffect,i),h.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(){if(!this.subSurface?.isScatteringEnabled)return!1;const e=this.getScene().enableSubSurfaceForPrePass();return e&&(e.enabled=!0),!0}dispose(e,t){this._breakShaderLoadedCheck=!0,t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),this._albedoTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._metallicTexture?.dispose(),this._reflectivityTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._metallicReflectanceTexture?.dispose(),this._reflectanceTexture?.dispose(),this._microSurfaceTexture?.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}Gm.PBRMATERIAL_OPAQUE=Vt.MATERIAL_OPAQUE,Gm.PBRMATERIAL_ALPHATEST=Vt.MATERIAL_ALPHATEST,Gm.PBRMATERIAL_ALPHABLEND=Vt.MATERIAL_ALPHABLEND,Gm.PBRMATERIAL_ALPHATESTANDBLEND=Vt.MATERIAL_ALPHATESTANDBLEND,Gm.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,Gm.LIGHTFALLOFF_PHYSICAL=0,Gm.LIGHTFALLOFF_GLTF=1,Gm.LIGHTFALLOFF_STANDARD=2,Gm.ForceGLSL=!1,(0,je.Cg)([(0,$e.n1)()],Gm.prototype,"_imageProcessingConfiguration",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],Gm.prototype,"debugMode",void 0);class zm extends Gm{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===Gm.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Gm.LIGHTFALLOFF_PHYSICAL:Gm.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===Gm.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Gm.LIGHTFALLOFF_GLTF:Gm.LIGHTFALLOFF_STANDARD)}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}constructor(e,t,i=!1){super(e,t,i),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=zm.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=H.v9.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new H.v9(0,0,0),this.albedoColor=new H.v9(1,1,1),this.reflectivityColor=new H.v9(1,1,1),this.reflectionColor=new H.v9(1,1,1),this.emissiveColor=new H.v9(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=Em(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){const r=it.p.Clone((()=>new zm(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return r.id=e,r.name=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}serialize(){const e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){const r=it.p.Parse((()=>new zm(e.name,t)),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),Vt._ParsePlugins(e,r,t,i),e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}zm.PBRMATERIAL_OPAQUE=Gm.PBRMATERIAL_OPAQUE,zm.PBRMATERIAL_ALPHATEST=Gm.PBRMATERIAL_ALPHATEST,zm.PBRMATERIAL_ALPHABLEND=Gm.PBRMATERIAL_ALPHABLEND,zm.PBRMATERIAL_ALPHATESTANDBLEND=Gm.PBRMATERIAL_ALPHATESTANDBLEND,zm.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=Gm.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"directIntensity",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"emissiveIntensity",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"environmentIntensity",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"specularIntensity",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"disableBumpMap",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"albedoTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"ambientTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"ambientTextureStrength",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesAndMiscDirty")],zm.prototype,"opacityTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"reflectionTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"emissiveTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"reflectivityTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"metallicTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"metallic",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"roughness",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"metallicF0Factor",void 0),(0,je.Cg)([(0,$e.jT)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"metallicReflectanceColor",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"metallicReflectanceTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"reflectanceTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"microSurfaceTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"bumpTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty",null)],zm.prototype,"lightmapTexture",void 0),(0,je.Cg)([(0,$e.jT)("ambient"),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"ambientColor",void 0),(0,je.Cg)([(0,$e.jT)("albedo"),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"albedoColor",void 0),(0,je.Cg)([(0,$e.jT)("reflectivity"),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"reflectivityColor",void 0),(0,je.Cg)([(0,$e.jT)("reflection"),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"reflectionColor",void 0),(0,je.Cg)([(0,$e.jT)("emissive"),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"emissiveColor",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"microSurface",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useLightmapAsShadowmap",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesAndMiscDirty")],zm.prototype,"useAlphaFromAlbedoTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesAndMiscDirty")],zm.prototype,"forceAlphaTest",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesAndMiscDirty")],zm.prototype,"alphaCutOff",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useSpecularOverAlpha",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useRoughnessFromMetallicTextureGreen",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useMetallnessFromMetallicTextureBlue",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useAmbientInGrayScale",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),(0,je.Cg)([(0,$e.lK)()],zm.prototype,"usePhysicalLightFalloff",null),(0,je.Cg)([(0,$e.lK)()],zm.prototype,"useGLTFLightFalloff",null),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useRadianceOverAlpha",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useObjectSpaceNormalMap",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useParallax",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useParallaxOcclusion",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"parallaxScaleBias",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],zm.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"forceIrradianceInFragment",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],zm.prototype,"maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"invertNormalMapX",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"invertNormalMapY",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"twoSidedLighting",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useAlphaFresnel",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useLinearAlphaFresnel",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"environmentBRDFTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"forceNormalForward",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"enableSpecularAntiAliasing",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useHorizonOcclusion",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useRadianceOcclusion",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],zm.prototype,"unlit",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],zm.prototype,"applyDecalMapAfterDetailMap",void 0),(0,X.Y5)("BABYLON.PBRMaterial",zm);var Wm=i(50153),Hm=i(33815),Xm=i(53797);class qm extends es{constructor(e,t,i){super(e,W.Pq.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=W.PT.Identity(),this._referencedPosition=new W.Pq,this._trackingState=0,this.onXRCameraInitializedObservable=new z.cP,this.onBeforeCameraTeleport=new z.cP,this.onAfterCameraTeleport=new z.cP,this.onTrackingStateChanged=new z.cP,this.compensateOnFirstFrame=!0,this._rotate180=new W.PT(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new W.PT,this.cameraRigMode=rt.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 et.L(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new et.L(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){e&&e!==this&&(e.computeWorldMatrix().decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,W.PT.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace())}getClassName(){return"WebXRCamera"}setTarget(e){const t=W.AA.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();const i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),W.PT.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0,this.onTrackingStateChanged.clear()}_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)return void this._setTrackingState(0);const t=e.emulatedPosition?1:2;if(this._setTrackingState(t),this.minZ===this._cache.minZ&&this.maxZ===this._cache.maxZ||this._updateDepthNearFar(),e.transform){const t=e.transform.orientation;if(void 0===e.transform.orientation.x)return;const i=e.transform.position;this._referencedPosition.set(i.x,i.y,i.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._referenceQuaternion.set(t.x,t.y,t.z,t.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(((e,t)=>{const i=this.rigCameras[t];i.isLeftCamera||i.isRightCamera||("right"===e.eye?i._isRightCamera=!0:"left"===e.eye&&(i._isLeftCamera=!0));const r=this.getScene().customRenderTargets;for(let e=0;ee;){const e=this.rigCameras.pop();e&&e.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){const e=W.AA.Matrix[0],t=W.AA.Matrix[1],i=W.AA.Matrix[2];W.uq.ComposeToRef(qm._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),W.uq.ComposeToRef(qm._ScaleReadOnly,this.rotationQuaternion,this.position,t),e.invert().multiplyToRef(t,i),i.invert(),this._scene.useRightHandedSystem||i.toggleModelMatrixHandInPlace(),i.decompose(void 0,this._referenceQuaternion,this._referencedPosition);const r=new XRRigidTransform({x:this._referencedPosition.x/this._xrSessionManager.worldScalingFactor,y:this._referencedPosition.y/this._xrSessionManager.worldScalingFactor,z:this._referencedPosition.z/this._xrSessionManager.worldScalingFactor},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(r)}}}qm._ScaleReadOnly=W.Pq.One();class Ym{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 z.cP,this.onStateChangedObservable=new z.cP,this.state=3,this.sessionManager=new Qn(e),this.camera=new qm("webxr",e,this.sessionManager),this.featuresManager=new cr(this.sessionManager),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}static CreateAsync(e){const t=new Ym(e);return t.sessionManager.initializeAsync().then((()=>(t._supported=!0,t))).catch((e=>{throw t._setState(3),t.dispose(),e}))}dispose(){this.exitXRAsync(),this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),this._spectatorCamera?.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),r={}){if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(0),"viewer"!==t&&"local"!==t&&(r.optionalFeatures=r.optionalFeatures||[],r.optionalFeatures.push(t)),r=await this.featuresManager._extendXRSessionInitObject(r),"immersive-ar"===e&&"unbounded"!==t&&Z.V.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,r),await this.sessionManager.setReferenceSpaceTypeAsync(t);const s={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};if(!this.featuresManager.getEnabledFeature(hr.LAYERS)){const e=await i.initializeXRLayerAsync(this.sessionManager.session);s.baseLayer=e}return this.sessionManager.updateRenderState(s),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!this._nonVRCamera?.inputs?.attachedToElement,this._nonVRCamera?.detachControl(),this._scene.activeCamera=this.camera,"immersive-ar"!==e?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)),Ot.$.audioEngine?._resumeAudioContextOnStateChange(),this.sessionManager.onXRSessionEnded.addOnce((()=>{1!==this.state&&this._setState(1),this.camera.rigCameras.forEach((e=>{e.outputRenderTarget=null})),this._scene.autoClear=this._originalSceneAutoClear,this._scene.activeCamera=this._nonVRCamera,this._attachedToElement&&this._nonVRCamera&&this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault),"immersive-ar"!==e&&this.camera.compensateOnFirstFrame&&(this._nonVRCamera.setPosition?this._nonVRCamera.setPosition(this.camera.position):this._nonVRCamera.position.copyFrom(this.camera.position)),this._setState(3)})),this.sessionManager.onXRFrameObservable.addOnce((()=>{this._setState(2)})),this.sessionManager}catch(e){throw Z.V.Log(e),Z.V.Log(e.message),this._setState(3),e}}exitXRAsync(){return 2!==this.state?Promise.resolve():(this._setState(1),this.sessionManager.exitXRAsync())}enableSpectatorMode(e){this._spectatorMode||(this._spectatorMode=!0,this._switchSpectatorMode(e))}disableSpecatatorMode(){this._spectatorMode&&(this._spectatorMode=!1,this._switchSpectatorMode())}_switchSpectatorMode(e){const t=1/(e?.fps?e.fps:1e3)*1e3,i=e?.preferredCameraIndex?e?.preferredCameraIndex:0,r=()=>{this._spectatorCamera&&this.sessionManager.currentTimestamp-this._lastTimestamp>=t&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[i].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[i].absoluteRotation))};if(this._spectatorMode){if(i>=this.camera.rigCameras.length)throw new Error("the preferred camera index is beyond the length of rig camera array.");const e=()=>{2===this.state?(this._spectatorCamera=new fs("webxr-spectator",W.Pq.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new W.PT,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(r),this._scene.onAfterRenderCameraObservable.add((e=>{e===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)}))):1===this.state&&(this.sessionManager.onXRFrameObservable.removeCallback(r),this._scene.activeCameras=null)};this.onStateChangedObservable.add(e),e()}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 Km{constructor(e,t,i=-1,r=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=r,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new z.cP,this.onButtonStateChangedObservable=new z.cP}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 0!==this._axesIndices.length}isButton(){return-1!==this._buttonIndex}update(e){let t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){const i=e.buttons[this._buttonIndex];if(!i)return;this._currentValue!==i.value&&(this.changes.value={current:i.value,previous:this._currentValue},t=!0,this._currentValue=i.value),this._touched!==i.touched&&(this.changes.touched={current:i.touched,previous:this._touched},t=!0,this._touched=i.touched),this._pressed!==i.pressed&&(this.changes.pressed={current:i.pressed,previous:this._pressed},t=!0,this._pressed=i.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))}}Km.BUTTON_TYPE="button",Km.SQUEEZE_TYPE="squeeze",Km.THUMBSTICK_TYPE="thumbstick",Km.TOUCHPAD_TYPE="touchpad",Km.TRIGGER_TYPE="trigger";var jm,$m=i(28909);!function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(jm||(jm={}));const Qm=new z.cP,Zm={};let Jm=!1;function eg(){return Zm[".babylon"]}function tg(e,t){return Zm[e]||(Z.V.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"),t?eg():void 0)}function ig(e,t,i){let r="Unable to load from "+(e.rawData?"binary data":e.url);return t?r+=`: ${t}`:i&&(r+=`: ${i}`),r}async function rg(e,t,i,r,s,n,o,a,l){const h="data:"===(c=e.url).substring(0,5)?c.substring(5):null;var c;if(e.rawData&&!o)throw"When using ArrayBufferView to load data the file extension must be provided.";const u=h||o?"":function(e){const t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));const i=e.lastIndexOf(".");return e.substring(i,e.length).toLowerCase()}(e.url);let d=o?tg(o,!0):h?function(e){for(const t in Zm){const i=Zm[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return Zm[t]}return eg()}(e.url):tg(u,!1);if(!d&&u){if(e.url&&!e.url.startsWith("blob:")){const t=await function(e,t){const i=t.method||"GET";return new Promise(((r,s)=>{const n=new go.u;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const e={};if(t.responseHeaders)for(const i of t.responseHeaders)e[i]=n.getResponseHeader(i)||"";r({response:n.response,headerValues:e})}else s(`Unable to fetch data from ${e}. Error code: ${n.status}`)})),n.open(i,e),n.send()}))}(e.url,{method:"HEAD",responseHeaders:["Content-Type"]}),i=t.headerValues?t.headerValues["Content-Type"]:"";i&&(d=function(e){for(const t in Zm){const i=Zm[t];if(i.mimeType===e)return i}}(i))}d||(d=eg())}if(!d)throw new Error(`No plugin or fallback for ${o??e.url}`);if(!1===l?.[d.plugin.name]?.enabled)throw new Error(`The '${d.plugin.name}' plugin is disabled via the loader options passed to the loading operation.`);if(e.rawData&&!d.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";return(e=>{if(d.plugin.createPlugin){const t=d.plugin.createPlugin(l??{});return t instanceof Promise?(t.then(e).catch((e=>{s("Error instantiating plugin.",e)})),null):(e(t),t)}return e(d.plugin),d.plugin})((l=>{if(!l)throw`The loader plugin corresponding to the '${o}' file type has not been found. If using es6, please import the plugin you wish to use before.`;if(Qm.notifyObservers(l),h&&(l.canDirectLoad&&l.canDirectLoad(e.url)||!(0,$m.f2)(e.url))){if(l.directLoad){const e=l.directLoad(t,h);e instanceof Promise?e.then((e=>{i(l,e)})).catch((e=>{s("Error in directLoad of _loadData: "+e,e)})):i(l,e)}else i(l,h);return}const c=d.isBinary,u=(e,r)=>{t.isDisposed?s("Scene has been disposed"):i(l,e,r)};let f=null,p=!1;l.onDisposeObservable?.add((()=>{p=!0,f&&(f.abort(),f=null),n()}));const _=()=>{if(p)return;const i=(e,t)=>{s(e?.statusText,t)};if(!l.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";f=l.loadFile?l.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,u,r,c,i,a):t._loadFile(e.file||e.url,u,r,!0,c,i)},m=t.getEngine();let g=m.enableOfflineSupport;if(g){let i=!1;for(const r of t.disableOfflineSupportExceptionRules)if(r.test(e.url)){i=!0;break}g=!i}g&&Ot.$.OfflineProviderFactory?t.offlineProvider=Ot.$.OfflineProviderFactory(e.url,_,m.disableManifestCheck):_()}))}function sg(e,t){let i,r,s=null,n=null;if(t)if(t.name)i=`file:${t.name}`,r=t.name,s=t;else if(ArrayBuffer.isView(t))i="",r=(0,Au.z)(),n=t;else if(t.startsWith("data:"))i=t,r="";else if(e){const s=t;if("/"===s.substring(0,1))return Ue.S0.Error("Wrong sceneFilename parameter"),null;i=e+s,r=s}else i=t,r=Ue.S0.GetFilename(t),e=Ue.S0.GetFolderPath(t);else i=e,r=Ue.S0.GetFilename(e),e=Ue.S0.GetFolderPath(e);return{url:i,rootUrl:e,name:r,file:s,rawData:n}}function ng(e){if("string"==typeof e.extensions){const t=e.extensions;Zm[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach((i=>{Zm[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary,mimeType:t[i].mimeType}}))}}async function og(e,t,i="",r=he.q.LastCreatedScene,s=null,n=null,o=null,a=null,l="",h={}){if(!r)return Z.V.Error("No scene available to import mesh to"),null;const c=sg(t,i);if(!c)return null;const u={};r.addPendingData(u);const d=()=>{r.removePendingData(u)},f=(e,t)=>{const i=ig(c,e,t);o?o(r,i,new nt.bu(i,nt.tG.SceneLoaderError,t)):Z.V.Error(i),d()},p=n?e=>{try{n(e)}catch(e){f("Error in onProgress callback: "+e,e)}}:void 0,_=(e,t,i,n,o,a,l,h)=>{if(r.importedMeshesFiles.push(c.url),s)try{s(e,t,i,n,o,a,l,h)}catch(e){f("Error in onSuccess callback: "+e,e)}r.removePendingData(u)};return await rg(c,r,((t,i,s)=>{if(t.rewriteRootURL&&(c.rootUrl=t.rewriteRootURL(c.rootUrl,s)),t.importMesh){const s=[],n=[],o=[];if(!t.importMesh(e,r,i,c.rootUrl,s,n,o,f))return;r.loadingPluginName=t.name,_(s,n,o,[],[],[],[],[])}else t.importMeshAsync(e,r,i,c.rootUrl,p,c.name).then((e=>{r.loadingPluginName=t.name,_(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights,e.spriteManagers)})).catch((e=>{f(e.message,e)}))}),p,f,d,a,l,h)}function ag(e,t="",i=he.q.LastCreatedEngine,r=null,s=null,n=null,o=null,a="",l={}){i?cg(e,t,new oi.Z(i),r,s,n,o,a,l):Ue.S0.Error("No engine available")}function lg(e,t,i){const{rootUrl:r="",onProgress:s,pluginExtension:n,name:o,pluginOptions:a}=i??{};return hg(r,e,t,s,n,o,a)}function hg(e,t,i,r,s,n,o){return new Promise(((a,l)=>{ag(e,t,i,(e=>{a(e)}),r,((e,t,i)=>{l(i||new Error(t))}),s,n,o)}))}async function cg(e,t="",i=he.q.LastCreatedScene,r=null,s=null,n=null,o=null,a="",l={}){if(!i)return Z.V.Error("No scene available to append to"),null;const h=sg(e,t);if(!h)return null;const c={};i.addPendingData(c);const u=()=>{i.removePendingData(c)};St.ShowLoadingScreen&&!Jm&&(Jm=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady((()=>{i.getEngine().hideLoadingUI(),Jm=!1})));const d=(e,t)=>{const r=ig(h,e,t);n?n(i,r,new nt.bu(r,nt.tG.SceneLoaderError,t)):Z.V.Error(r),u()},f=s?e=>{try{s(e)}catch(e){d("Error in onProgress callback",e)}}:void 0,p=()=>{if(r)try{r(i)}catch(e){d("Error in onSuccess callback",e)}i.removePendingData(c)};return await rg(h,i,((e,t)=>{if(e.load){if(!e.load(i,t,h.rootUrl,d))return;i.loadingPluginName=e.name,p()}else e.loadAsync(i,t,h.rootUrl,f,h.name).then((()=>{i.loadingPluginName=e.name,p()})).catch((e=>{d(e.message,e)}))}),f,d,u,o,a,l)}async function ug(e,t,i){const{rootUrl:r="",onProgress:s,pluginExtension:n,name:o,pluginOptions:a}=i??{};await dg(r,e,t,s,n,o,a)}function dg(e,t,i,r,s,n,o){return new Promise(((a,l)=>{cg(e,t,i,(e=>{a(e)}),r,((e,t,i)=>{l(i||new Error(t))}),s,n,o)}))}async function fg(e,t="",i=he.q.LastCreatedScene,r=null,s=null,n=null,o=null,a="",l={}){if(!i)return Z.V.Error("No scene available to load asset container to"),null;const h=sg(e,t);if(!h)return null;const c={};i.addPendingData(c);const u=()=>{i.removePendingData(c)},d=(e,t)=>{const r=ig(h,e,t);n?n(i,r,new nt.bu(r,nt.tG.SceneLoaderError,t)):Z.V.Error(r),u()},f=s?e=>{try{s(e)}catch(e){d("Error in onProgress callback",e)}}:void 0,p=e=>{if(r)try{r(e)}catch(e){d("Error in onSuccess callback",e)}i.removePendingData(c)};return await rg(h,i,((e,t)=>{if(e.loadAssetContainer){const r=e.loadAssetContainer(i,t,h.rootUrl,d);if(!r)return;r.populateRootNodes(),i.loadingPluginName=e.name,p(r)}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(i,t,h.rootUrl,f,h.name).then((t=>{t.populateRootNodes(),i.loadingPluginName=e.name,p(t)})).catch((e=>{d(e.message,e)})):d("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")}),f,d,u,o,a,l)}function pg(e,t,i){const{rootUrl:r="",onProgress:s,pluginExtension:n,name:o,pluginOptions:a}=i??{};return _g(r,e,t,s,n,o,a)}function _g(e,t,i,r,s,n,o){return new Promise(((a,l)=>{fg(e,t,i,(e=>{a(e)}),r,((e,t,i)=>{l(i||new Error(t))}),s,n,o)}))}function mg(e,t="",i=he.q.LastCreatedScene,r=!0,s=0,n=null,o=null,a=null,l=null,h=null,c="",u={}){if(!i)return void Z.V.Error("No scene available to load animations to");if(r){for(const e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach((e=>{e.dispose()})),i.getNodes().forEach((e=>{e.animations&&(e.animations=[])}))}else switch(s){case 0:i.animationGroups.slice().forEach((e=>{e.dispose()}));break;case 1:i.animationGroups.forEach((e=>{e.stop()}));break;case 2:i.animationGroups.forEach((e=>{e.reset(),e.restart()}));break;case 3:break;default:return void Z.V.Error("Unknown animation group loading mode value '"+s+"'")}const d=i.animatables.length;fg(e,t,i,(e=>{e.mergeAnimationsTo(i,i.animatables.slice(d),n),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),o&&o(i)}),a,l,h,c,u)}async function gg(e,t,i){const{rootUrl:r="",overwriteAnimations:s,animationGroupLoadingMode:n,targetConverter:o,onProgress:a,pluginExtension:l,name:h,pluginOptions:c}=i??{};await vg(r,e,t,s,n,o,a,l,h,c)}function vg(e,t,i,r,s,n,o,a,l,h){return new Promise(((c,u)=>{mg(e,t,i,r,s,n,(e=>{c(e)}),o,((e,t,i)=>{u(i||new Error(t))}),a,l,h)}))}class xg{static get ForceFullSceneLoadingForIncremental(){return St.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){St.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return St.ShowLoadingScreen}static set ShowLoadingScreen(e){St.ShowLoadingScreen=e}static get loggingLevel(){return St.loggingLevel}static set loggingLevel(e){St.loggingLevel=e}static get CleanBoneMatrixWeights(){return St.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){St.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return eg()}static GetPluginForExtension(e){return tg(e,!0)?.plugin}static IsPluginForExtensionAvailable(e){return function(e){return!!Zm[e]}(e)}static RegisterPlugin(e){ng(e)}static ImportMesh(e,t,i,r,s,n,o,a,l){og(e,t,i,r,s,n,o,a,l)}static ImportMeshAsync(e,t,i,r,s,n,o){return function(e,t,i,r,s,n,o,a){return new Promise(((a,l)=>{og(e,t,i,r,((e,t,i,r,s,n,o,l)=>{a({meshes:e,particleSystems:t,skeletons:i,animationGroups:r,transformNodes:s,geometries:n,lights:o,spriteManagers:l})}),s,((e,t,i)=>{l(i||new Error(t))}),n,o,undefined)}))}(e,t,i,r,s,n,o)}static Load(e,t,i,r,s,n,o,a){ag(e,t,i,r,s,n,o,a)}static LoadAsync(e,t,i,r,s,n){return hg(e,t,i,r,s,n)}static Append(e,t,i,r,s,n,o,a){cg(e,t,i,r,s,n,o,a)}static AppendAsync(e,t,i,r,s,n){return dg(e,t,i,r,s,n)}static LoadAssetContainer(e,t,i,r,s,n,o,a){fg(e,t,i,r,s,n,o,a)}static LoadAssetContainerAsync(e,t,i,r,s,n){return _g(e,t,i,r,s,n)}static ImportAnimations(e,t,i,r,s,n,o,a,l,h,c){mg(e,t,i,r,s,n,o,a,l,h,c)}static ImportAnimationsAsync(e,t,i,r,s,n,o,a,l,h,c){return vg(e,t,i,r,s,n,a,h,c)}}xg.NO_LOGGING=0,xg.MINIMAL_LOGGING=1,xg.SUMMARY_LOGGING=2,xg.DETAILED_LOGGING=3,xg.OnPluginActivatedObservable=Qm;class bg{constructor(e,t,i,r,s=!1,n){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=r,this._doNotLoadControllerMesh=s,this._controllerCache=n,this._initComponent=e=>{if(!e)return;const t=this.layout.components[e],i=t.type,r=t.gamepadIndices.button,s=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&s.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),this.components[e]=new Km(e,i,r,s)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new z.cP,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)),this.onModelLoadedObservable.clear()}getAllComponentsOfType(e){return this.getComponentIds().map((e=>this.components[e])).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?Z.V.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise(((i,r)=>{const s=t=>{e?this._getGenericParentMesh(t):this._setRootMesh(t),this._processLoadedModel(t),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){const e=this._controllerCache.filter((e=>e.filename===t.filename&&e.path===t.path));if(e[0])return e[0].meshes.forEach((e=>e.setEnabled(!0))),void s(e[0].meshes)}xg.ImportMesh("",t.path,t.filename,this.scene,(e=>{this._controllerCache&&this._controllerCache.push({...t,meshes:e}),s(e)}),null,((e,i)=>{Z.V.Log(i),Z.V.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),r(i)}))}))}updateFromXRFrame(e){this.getComponentIds().forEach((e=>this.getComponent(e).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((e=>e.name===t),!1)[0]}_getImmediateChildByName(e,t){return e.getChildren((e=>e.name==t),!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh)return;if(!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;const r=i?.5*t+.5:t;W.PT.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,r,e.valueMesh.rotationQuaternion),W.Pq.LerpToRef(e.minMesh.position,e.maxMesh.position,r,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new Yt(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.parent||(e.isPickable=!1,e.setParent(this.rootMesh))})),this.rootMesh.rotationQuaternion=W.PT.FromEulerAngles(0,Math.PI,0)}}class Sg extends bg{constructor(e,t,i){super(e,Tg[i],t,i),this.profileId=Sg.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new Yt(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1,e.parent||e.setParent(this.rootMesh)})),this.rootMesh.rotationQuaternion=W.PT.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}Sg.ProfileId="generic-trigger";const Tg={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 Cg extends bg{constructor(e,t,i,r,s){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,s),this._repositoryUrl=r,this.controllerCache=s,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach((e=>{this._touchDots[e].dispose()}))}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){const e=xg.IsPluginForExtensionAvailable(".glb");return e||Z.V.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=this.layout.components[e];this._buttonMeshMapping[e]={mainMesh:this._getChildByName(this.rootMesh,t.rootNodeName),states:{}},Object.keys(t.visualResponses).forEach((i=>{const r=t.visualResponses[i];if("transform"===r.valueNodeProperty)this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,r.valueNodeName),minMesh:this._getChildByName(this.rootMesh,r.minNodeName),maxMesh:this._getChildByName(this.rootMesh,r.maxNodeName)};else{const s=t.type===Km.TOUCHPAD_TYPE&&t.touchPointNodeName?t.touchPointNodeName:r.valueNodeName;if(this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,s)},t.type===Km.TOUCHPAD_TYPE&&!this._touchDots[i]){const t=Qo(i+"dot",{diameter:.0015,segments:8},this.scene);t.material=new Un(i+"mat",this.scene),t.material.diffuseColor=H.v9.Red(),t.parent=this._buttonMeshMapping[e].states[i].valueMesh||null,t.isVisible=!1,this._touchDots[i]=t}}}))}))}_setRootMesh(e){let t;this.rootMesh=new Yt(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i{const t=this.getComponent(e);if(!t.hasChanges)return;const i=this._buttonMeshMapping[e],r=this.layout.components[e];Object.keys(r.visualResponses).forEach((e=>{const s=r.visualResponses[e];let n=t.value;if("xAxis"===s.componentProperty?n=t.axes.x:"yAxis"===s.componentProperty&&(n=t.axes.y),"transform"===s.valueNodeProperty)this._lerpTransform(i.states[e],n,"button"!==s.componentProperty);else{const r=i.states[e].valueMesh;r&&(r.isVisible=t.touched||t.pressed),this._touchDots[e]&&(this._touchDots[e].isVisible=t.touched||t.pressed)}}))}))}}const yg=[];class Eg{static ClearProfilesCache(){this._ProfilesList=null,this._ProfileLoadingPromises={}}static DefaultFallbacks(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])}static FindFallbackWithProfileId(e){const t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){const r=[];i&&r.push(i),r.push(...e.profiles||[]),r.length&&!r[0]&&r.pop(),e.gamepad&&e.gamepad.id&&e.gamepad.id===(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0)&&r.push("oculus-touch-v2");const s=r.indexOf("windows-mixed-reality");if(-1!==s&&r.splice(s,0,"microsoft-mixed-reality"),r.length||r.push("generic-trigger"),this.UseOnlineRepository){const i=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,s=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return i.call(this,r,e,t).catch((()=>s.call(this,r,e,t)))}return this._LoadProfilesFromAvailableControllers(r,e,t)}static RegisterController(e,t){this._AvailableControllers[e]=t}static RegisterFallbacksForProfileId(e,t){this._Fallbacks[e]?this._Fallbacks[e].push(...t):this._Fallbacks[e]=t}static UpdateProfilesList(){return this._ProfilesList=Ue.S0.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then((e=>JSON.parse(e))),this._ProfilesList}static ClearControllerCache(){yg.forEach((e=>{e.meshes.forEach((e=>{e.dispose(!1,!0)}))})),yg.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then((()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList())).then((t=>{for(let i=0;i(this._ProfileLoadingPromises[e]||(this._ProfileLoadingPromises[e]=Ue.S0.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${e}/profile.json`,!1).then((e=>JSON.parse(e)))),this._ProfileLoadingPromises[e]))).then((e=>new Cg(i,t,e,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:yg)))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let r=0;rnew Sg(t,e.gamepad,e.handedness))),Eg.DefaultFallbacks();let Pg=0;class Ag{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new W.Pq,this._disposed=!1,this.onDisposeObservable=new z.cP,this.onMeshLoadedObservable=new z.cP,this.onMotionControllerInitObservable=new z.cP,this._uniqueId=`controller-${Pg++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new Yt(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new W.PT,this.inputSource.gripSpace&&(this.grip=new Yt(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new W.PT),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&"tracked-pointer"===this.inputSource.targetRayMode&&Eg.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then((e=>{this.motionController=e,this.onMotionControllerInitObservable.notifyObservers(e),this._options.doNotLoadControllerMesh||this.motionController._doNotLoadControllerMesh||this.motionController.loadModel().then((e=>{e&&this.motionController&&this.motionController.rootMesh&&(this._options.renderingGroupId&&(this.motionController.rootMesh.renderingGroupId=this._options.renderingGroupId,this.motionController.rootMesh.getChildMeshes(!1).forEach((e=>e.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&&this.motionController?.dispose()}))}),(()=>{Ue.S0.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;W.Pq.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i,r){const s=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=s,s){const e=s.transform.position;this.pointer.position.set(e.x,e.y,e.z).scaleInPlace(r.worldScalingFactor);const t=s.transform.orientation;this.pointer.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent,this.pointer.scaling.setAll(r.worldScalingFactor)}if(this.inputSource.gripSpace&&this.grip){const s=e.getPose(this.inputSource.gripSpace,t);if(s){const e=s.transform.position,t=s.transform.orientation;this.grip.position.set(e.x,e.y,e.z).scaleInPlace(r.worldScalingFactor),this.grip.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent,this.grip.scaling.setAll(r.worldScalingFactor)}this.motionController&&this.motionController.updateFromXRFrame(e)}}class Rg{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new z.cP,this.onControllerRemovedObservable=new z.cP,this._onInputSourcesChange=e=>{this._addAndRemoveControllers(e.added,e.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add((()=>{this._addAndRemoveControllers([],this.controllers.map((e=>e.inputSource)))})),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add((e=>{e.addEventListener("inputsourceschange",this._onInputSourcesChange)})),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add((e=>{this.controllers.forEach((t=>{t.updateFromXRFrame(e,this.xrSessionManager.referenceSpace,this.xrCamera,this.xrSessionManager)}))})),this._options.customControllersRepositoryURL&&(Eg.BaseRepositoryUrl=this._options.customControllersRepositoryURL),Eg.UseOnlineRepository=!this._options.disableOnlineControllerRepository,Eg.UseOnlineRepository)try{Eg.UpdateProfilesList().catch((()=>{Eg.UseOnlineRepository=!1}))}catch(e){Eg.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){const i=this.controllers.map((e=>e.inputSource));for(const t of e)if(-1===i.indexOf(t)){const e=new Ag(this.xrSessionManager.scene,t,{...this._options.controllerOptions||{},forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation});this.controllers.push(e),this.onControllerAddedObservable.notifyObservers(e)}const r=[],s=[];this.controllers.forEach((e=>{-1===t.indexOf(e.inputSource)?r.push(e):s.push(e)})),this.controllers=r,s.forEach((e=>{this.onControllerRemovedObservable.notifyObservers(e),e.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(),Eg.ClearControllerCache()}}class Ig{get xrNativeFeatureName(){return this._xrNativeFeatureName}set xrNativeFeatureName(e){!this._xrSessionManager.isNative&&e&&this._xrSessionManager.inXRSession&&-1===this._xrSessionManager.enabledFeatures?.indexOf(e)&&Z.V.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 z.cP,this.onFeatureDetachObservable=new z.cP}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){if(!this._xrSessionManager.isNative&&this.xrNativeFeatureName&&-1===this._xrSessionManager.enabledFeatures.indexOf(this.xrNativeFeatureName))return!1}else Z.V.Warn("session.enabledFeatures is not available on this device. It is possible that this feature is not supported.");return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,(e=>this._onXRFrame(e))),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 Mg extends Ig{constructor(e,t){super(e),this._options=t,this._attachController=e=>{if(this._controllers[e.uniqueId])return;const{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(this._options.forceGripIfAvailable&&e.grip?e.grip:e.pointer);switch(this._controllers[e.uniqueId]={xrController:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new wi(new W.Pq,new W.Pq),disabledByNearInteraction:!1,id:Mg._IdCounter++},this._attachedController?!this._options.enablePointerSelectionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enablePointerSelectionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachTrackedPointerRayMode(e);case"gaze":return this._attachGazeMode(e);case"screen":case"transient-pointer":return this._attachScreenRayMode(e)}},this._controllers={},this._tmpVectorForPickCompare=new W.Pq,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new H.v9(.9,.9,.9),this.laserPointerDefaultColor=new H.v9(.7,.7,.7),this.selectionMeshDefaultColor=new H.v9(.8,.8,.8),this.selectionMeshPickedColor=new H.v9(.3,.3,1),this._identityMatrix=W.uq.Identity(),this._screenCoordinatesRef=W.Pq.Zero(),this._viewportRef=new et.L(0,0,0,0),this._scene=this._xrSessionManager.scene,void 0===this._options.lookAndPickMode&&(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 wi(new W.Pq,new W.Pq),disabledByNearInteraction:!1,id:Mg._IdCounter++},this._attachGazeMode()}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;i{const t=this._controllers[e];if(this._options.lookAndPickMode&&"transient-pointer"!==t.xrController?.inputSource.targetRayMode)return;if(!this._options.enablePointerSelectionOnAllControllers&&e!==this._attachedController||t.disabledByNearInteraction)return t.selectionMesh.isVisible=!1,t.laserPointer.isVisible=!1,void(t.pick=null);let i;if(t.laserPointer.isVisible=this.displayLaserPointer,t.xrController)i=this._options.forceGripIfAvailable&&t.xrController.grip?t.xrController.grip.position:t.xrController.pointer.position,t.xrController.getWorldPointerRayToRef(t.tmpRay,this._options.forceGripIfAvailable);else{if(!t.webXRCamera)return;i=t.webXRCamera.position,t.webXRCamera.getForwardRayToRef(t.tmpRay)}if(this._options.maxPointerDistance&&(t.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&i){const e=this._xrSessionManager.scene,r=this._options.xrInput.xrCamera;r&&(r.viewport.toGlobalToRef(e.getEngine().getRenderWidth()/r.rigCameras.length,e.getEngine().getRenderHeight(),this._viewportRef),W.Pq.ProjectToRef(i,this._identityMatrix,r.getTransformationMatrix(),this._viewportRef,this._screenCoordinatesRef),"number"!=typeof this._screenCoordinatesRef.x||"number"!=typeof this._screenCoordinatesRef.y||isNaN(this._screenCoordinatesRef.x)||isNaN(this._screenCoordinatesRef.y)||this._screenCoordinatesRef.x===1/0||this._screenCoordinatesRef.y===1/0||(e.pointerX=this._screenCoordinatesRef.x,e.pointerY=this._screenCoordinatesRef.y,t.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let r=null;this._utilityLayerScene&&(r=this._utilityLayerScene.pickWithRay(t.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));const s=this._scene.pickWithRay(t.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);r&&r.hit?s&&s.hit?r.distance{if(t.pick){if(this._augmentPointerInit(l,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,n.isVisible=!1,t.pick.hit)if(this._pickingMoved(s,t.pick))a&&(this._options.disablePointerUpOnTouchOut||this._scene.simulatePointerUp(t.pick,l)),a=!1,o=0;else if(o>i/10&&(n.isVisible=!0),o+=this._scene.getEngine().getDeltaTime(),o>=i)this._scene.simulatePointerDown(t.pick,l),a=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),n.isVisible=!1;else{const e=1-o/i;n.scaling.set(e,e,e)}else a=!1,o=0;this._scene.simulatePointerMove(t.pick,l),s=t.pick}})),void 0!==this._options.renderingGroupId&&(n.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce((()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&a&&(this._scene.simulatePointerUp(t.pick,l),t.finalPointerUpTriggered=!0),n.dispose()}))}_attachScreenRayMode(e){const t=this._controllers[e.uniqueId];let i=!1;const r={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),!t.pick||this._options.disablePointerUpOnTouchOut&&i||(i?this._scene.simulatePointerMove(t.pick,r):(this._scene.simulatePointerDown(t.pick,r),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,r)))})),e.onDisposeObservable.addOnce((()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame((()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,r),t.finalPointerUpTriggered=!0)}))}))}_attachTrackedPointerRayMode(e){const t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);const i={pointerId:t.id,pointerType:"xr"};if(t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{t.laserPointer.material.disableLighting=this.disablePointerLighting,t.selectionMesh.material.disableLighting=this.disableSelectionMeshLighting,t.pick&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerMove(t.pick,i))})),e.inputSource.gamepad){const r=r=>{this._options.overrideButtonId&&(t.selectionComponent=r.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=r.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((r=>{if(r.changes.pressed){const s=r.changes.pressed.current;if(t.pick)(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),s?(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(s&&!this._options.enablePointerSelectionOnAllControllers&&!this._options.disableSwitchOnClick){const t=this._controllers[this._attachedController];t&&t.pointerDownTriggered&&!t.finalPointerUpTriggered&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerUp(new At.G,{pointerId:t.id,pointerType:"xr"}),t.finalPointerUpTriggered=!0),this._attachedController=e.uniqueId}}}))};e.motionController?r(e.motionController):e.onMotionControllerInitObservable.add(r)}else{const e=e=>{this._xrSessionManager.onXRFrameObservable.addOnce((()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.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=e=>{this._xrSessionManager.onXRFrameObservable.addOnce((()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.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:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",r)}}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(W.Pq.Dot(e,t.direction)){const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),!t.finalPointerUpTriggered&&t.pointerDownTriggered){const e={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame((()=>{this._augmentPointerInit(e,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new At.G,e),t.finalPointerUpTriggered=!0}))}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce((()=>{try{if(t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e],this._attachedController===e){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}catch(e){Ue.S0.Warn("controller already detached.")}}))}}_generateNewMeshPair(e){const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Bo.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():No("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;const r=new Un("laserPointerMat",t);r.emissiveColor=this.laserPointerDefaultColor,r.alpha=.7,i.material=r,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;const s=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():ao("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);s.bakeCurrentTransformIntoVertices(),s.isPickable=!1,s.isVisible=!1;const n=new Un("targetMat",t);return n.specularColor=H.v9.Black(),n.emissiveColor=this.selectionMeshDefaultColor,n.backFaceCulling=!1,s.material=n,void 0!==this._options.renderingGroupId&&(i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:s}}_pickingMoved(e,t){if(!e.hit||!t.hit)return!0;if(!(e.pickedMesh&&e.pickedPoint&&t.pickedMesh&&t.pickedPoint))return!0;if(e.pickedMesh!==t.pickedMesh)return!0;e.pickedPoint?.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=.01*(this._options.gazeModePointerMovedFactor||1)*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}}var Og,Dg,wg,Ng,Fg,Lg,Bg;Mg._IdCounter=200,Mg.Name=hr.POINTER_SELECTION,Mg.Version=1,cr.AddWebXRFeature(Mg.Name,((e,t)=>()=>new Mg(e,t)),Mg.Version,!0),function(e){e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=4]="Vector2",e[e.Vector3=8]="Vector3",e[e.Vector4=16]="Vector4",e[e.Color3=32]="Color3",e[e.Color4=64]="Color4",e[e.Matrix=128]="Matrix",e[e.Object=256]="Object",e[e.AutoDetect=1024]="AutoDetect",e[e.BasedOnInput=2048]="BasedOnInput",e[e.All=4095]="All"}(Og||(Og={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Neutral=4]="Neutral",e[e.VertexAndFragment=3]="VertexAndFragment"}(Dg||(Dg={}));class Vg{constructor(){this.supportUniformBuffers=!1,this.attributes=[],this.uniforms=[],this.constants=[],this.samplers=[],this.functions={},this.extensions={},this.prePassOutput={},this.counters={},this._terminalBlocks=new Set,this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}get shaderLanguage(){return this.sharedData.nodeMaterial.shaderLanguage}get fSuffix(){return 1===this.shaderLanguage?"f":""}finalize(e){const t=e.sharedData.emitComments,i=this.target===Dg.Fragment;1===this.shaderLanguage?this.compilationString=i?`\n${t?"//Entry point\n":""}@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${this.compilationString}`:`\n${t?"//Entry point\n":""}@vertex\nfn main(input: VertexInputs) -> FragmentInputs{\n${this.compilationString}`:this.compilationString=`\n${t?"//Entry point\n":""}void main(void) {\n${this.compilationString}`,this._constantDeclaration&&(this.compilationString=`\n${t?"//Constants\n":""}${this._constantDeclaration}\n${this.compilationString}`);let r="";for(const e in this.functions)r+=this.functions[e]+"\n";if(this.compilationString=`\n${r}\n${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString}\n${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString}\n${this._injectAtEnd}`),this.compilationString=`${this.compilationString}\n}`,this.sharedData.varyingDeclaration&&(this.compilationString=`\n${t?"//Varyings\n":""}${this.sharedData.varyingDeclaration}\n${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=`\n${t?"//Samplers\n":""}${this._samplerDeclaration}\n${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=`\n${t?"//Uniforms\n":""}${this._uniformDeclaration}\n${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=`\n${t?"//Attributes\n":""}${this._attributeDeclaration}\n${this.compilationString}`),1!==this.shaderLanguage){this.compilationString="precision highp float;\n"+this.compilationString,this.compilationString="#if defined(WEBGL2) || defined(WEBGPU)\nprecision highp sampler2DArray;\n#endif\n"+this.compilationString,i&&(this.compilationString="#if defined(PREPASS)\r\n#extension GL_EXT_draw_buffers : require\r\nlayout(location = 0) out highp vec4 glFragData[SCENE_MRT_COUNT];\r\nhighp vec4 gl_FragColor;\r\n#endif\r\n"+this.compilationString);for(const e in this.extensions){const t=this.extensions[e];this.compilationString=`\n${t}\n${this.compilationString}`}}this._builtCompilationString=this.compilationString}get _repeatableContentAnchor(){return`###___ANCHOR${this._repeatableContentAnchorIndex++}___###`}_getFreeVariableName(e){return e=e.replace(/[^a-zA-Z_]+/g,""),void 0===this.sharedData.variableNames[e]?(this.sharedData.variableNames[e]=0,"output"===e||"texture"===e?e+this.sharedData.variableNames[e]:e):(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])}_getFreeDefineName(e){return void 0===this.sharedData.defineNames[e]?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]}_excludeVariableName(e){this.sharedData.variableNames[e]=0}_emit2DSampler(e,t="",i=!1){(this.samplers.indexOf(e)<0||i)&&(t&&(this._samplerDeclaration+=`#if ${t}\n`),1===this.shaderLanguage?(this._samplerDeclaration+=`var ${e+"Sampler"}: sampler;\n`,this._samplerDeclaration+=`var ${e}: texture_2d;\n`):this._samplerDeclaration+=`uniform sampler2D ${e};\n`,t&&(this._samplerDeclaration+="#endif\n"),i||this.samplers.push(e))}_emitCubeSampler(e,t="",i=!1){(this.samplers.indexOf(e)<0||i)&&(t&&(this._samplerDeclaration+=`#if ${t}\n`),1===this.shaderLanguage?(this._samplerDeclaration+=`var ${e+"Sampler"}: sampler;\n`,this._samplerDeclaration+=`var ${e}: texture_cube;\n`):this._samplerDeclaration+=`uniform samplerCube ${e};\n`,t&&(this._samplerDeclaration+="#endif\n"),i||this.samplers.push(e))}_emit2DArraySampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2DArray ${e};\n`,this.samplers.push(e))}_getGLType(e){switch(e){case Og.Float:return"float";case Og.Int:return"int";case Og.Vector2:return"vec2";case Og.Color3:case Og.Vector3:return"vec3";case Og.Color4:case Og.Vector4:return"vec4";case Og.Matrix:return"mat4"}return""}_getShaderType(e){const t=1===this.shaderLanguage;switch(e){case Og.Float:return t?"f32":"float";case Og.Int:return t?"i32":"int";case Og.Vector2:return t?"vec2f":"vec2";case Og.Color3:case Og.Vector3:return t?"vec3f":"vec3";case Og.Color4:case Og.Vector4:return t?"vec4f":"vec4";case Og.Matrix:return t?"mat4x4f":"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i}\n${t}\n#endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+"\n"+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){const r=Cs.l.GetIncludesShadersStore(this.shaderLanguage);if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\n`;let s=r[e]+"\n";if(this.sharedData.emitComments&&(s=t+"\n"+s),!i)return s;if(i.replaceStrings)for(let e=0;e${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\n`:this.functions[s]=`#include<${e}>${i?.substitutionVars?"("+i?.substitutionVars+")":""}\n`,void(this.sharedData.emitComments&&(this.functions[s]=t+"\n"+this.functions[s]));if(this.functions[s]=n[e],this.sharedData.emitComments&&(this.functions[s]=t+"\n"+this.functions[s]),i.removeIfDef&&(this.functions[s]=this.functions[s].replace(/^\s*?#ifdef.+$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#endif.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#else.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[s]=this.functions[s].replace(/\s*?attribute .+?;/g,"\n")),i.removeUniforms&&(this.functions[s]=this.functions[s].replace(/\s*?uniform .*?;/g,"\n")),i.removeVaryings&&(this.functions[s]=this.functions[s].replace(/\s*?(varying|in) .+?;/g,"\n")),i.replaceStrings)for(let e=0;e")}_convertTernaryOperandsToWGSL(e){return e.replace(new RegExp("\\[(.*?)\\?(.*?):(.*)\\]","g"),((e,t,i,r)=>`select(${r}, ${i}, ${t})`))}_convertModOperatorsToWGSL(e){return e.replace(new RegExp("mod\\((.+?),\\s*(.+?)\\)","g"),((e,t,i)=>`((${t})%(${i}))`))}_convertConstToWGSL(e){return e.replace(new RegExp("const var","g"),"const")}_convertInnerFunctionsToWGSL(e){return e.replace(new RegExp("inversesqrt","g"),"inverseSqrt")}_convertFunctionsToWGSL(e){const t=/var\s+(\w+)\s*:\s*(\w+)\((.*)\)/g;let i;for(;null!==(i=t.exec(e));){const t=i[1],r=i[2],s=i[3].replace(/var\s/g,"");e=e.replace(i[0],`fn ${t}(${s}) -> ${r}`)}return e}_babylonSLtoWGSL(e){return e=this._convertVariableDeclarationToWGSL("void","voidnull",e),e=this._convertVariableDeclarationToWGSL("bool","bool",e),e=this._convertVariableDeclarationToWGSL("int","i32",e),e=this._convertVariableDeclarationToWGSL("uint","u32",e),e=this._convertVariableDeclarationToWGSL("float","f32",e),e=this._convertVariableDeclarationToWGSL("vec2","vec2f",e),e=this._convertVariableDeclarationToWGSL("vec3","vec3f",e),e=this._convertVariableDeclarationToWGSL("vec4","vec4f",e),e=this._convertVariableDeclarationToWGSL("mat2","mat2x2f",e),e=this._convertVariableDeclarationToWGSL("mat3","mat3x3f",e),e=this._convertVariableDeclarationToWGSL("mat4","mat4x4f",e),e=this._convertVariableConstructorsToWGSL("float","f32",e),e=this._convertVariableConstructorsToWGSL("vec2","vec2f",e),e=this._convertVariableConstructorsToWGSL("vec3","vec3f",e),e=this._convertVariableConstructorsToWGSL("vec4","vec4f",e),e=this._convertVariableConstructorsToWGSL("mat2","mat2x2f",e),e=this._convertVariableConstructorsToWGSL("mat3","mat3x3f",e),e=this._convertVariableConstructorsToWGSL("mat4","mat4x4f",e),e=this._convertTernaryOperandsToWGSL(e),e=this._convertModOperatorsToWGSL(e),e=this._convertConstToWGSL(e),e=this._convertInnerFunctionsToWGSL(e),e=(e=this._convertOutParametersToWGSL(e)).replace(/\[\*\]/g,"*"),(e=(e=(e=this._convertFunctionsToWGSL(e)).replace(/\s->\svoidnull/g,"")).replace(/dFdx/g,"dpdx")).replace(/dFdy/g,"dpdy")}_convertTernaryOperandsToGLSL(e){return e.replace(new RegExp("\\[(.+?)\\?(.+?):(.+)\\]","g"),((e,t,i,r)=>`${t} ? ${i} : ${r}`))}_babylonSLtoGLSL(e){return e=e.replace(/\[\*\]/g,""),this._convertTernaryOperandsToGLSL(e)}}class kg{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(e=null){let t="";this.checks.emitVertex||this.allowEmptyVertexProgram||(t+="NodeMaterial does not have a vertex output. You need to at least add a block that generates a position value.\n"),this.checks.emitFragment||(t+="NodeMaterial does not have a fragment output. You need to at least add a block that generates a color value.\n");for(const e of this.checks.notConnectedNonOptionalInputs)t+=`input ${e.name} from block ${e.ownerBlock.name}[${e.ownerBlock.getClassName()}] is not connected and is not optional.\n`;return!t||(e&&e.notifyObservers(t),Z.V.Error("Build of NodeMaterial failed:\n"+t),!1)}}!function(e){e[e.Compatible=0]="Compatible",e[e.TypeIncompatible=1]="TypeIncompatible",e[e.TargetIncompatible=2]="TargetIncompatible",e[e.HierarchyIssue=3]="HierarchyIssue"}(wg||(wg={})),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(Ng||(Ng={}));class Ug{static AreEquivalentTypes(e,t){switch(e){case Og.Vector3:if(t===Og.Color3)return!0;break;case Og.Vector4:if(t===Og.Color4)return!0;break;case Og.Color3:if(t===Og.Vector3)return!0;break;case Og.Color4:if(t===Og.Vector4)return!0}return!1}get _connectedPoint(){return this._connectedPointBackingField}set _connectedPoint(e){this._connectedPointBackingField!==e&&(this._connectedPointTypeChangedObserver?.remove(),this._updateTypeDependentState((()=>this._connectedPointBackingField=e)),this._connectedPointBackingField&&(this._connectedPointTypeChangedObserver=this._connectedPointBackingField.onTypeChangedObservable.add((()=>{this._notifyTypeChanged()}))))}get _typeConnectionSource(){return this._typeConnectionSourceBackingField}set _typeConnectionSource(e){this._typeConnectionSourceBackingField!==e&&(this._typeConnectionSourceTypeChangedObserver?.remove(),this._updateTypeDependentState((()=>this._typeConnectionSourceBackingField=e)),this._typeConnectionSourceBackingField&&(this._typeConnectionSourceTypeChangedObserver=this._typeConnectionSourceBackingField.onTypeChangedObservable.add((()=>{this._notifyTypeChanged()}))))}get _defaultConnectionPointType(){return this._defaultConnectionPointTypeBackingField}set _defaultConnectionPointType(e){this._updateTypeDependentState((()=>this._defaultConnectionPointTypeBackingField=e))}get _linkedConnectionSource(){return this._linkedConnectionSourceBackingField}set _linkedConnectionSource(e){this._linkedConnectionSourceBackingField!==e&&(this._linkedConnectionSourceTypeChangedObserver?.remove(),this._updateTypeDependentState((()=>this._linkedConnectionSourceBackingField=e)),this._linkedConnectionSourceBackingField&&(this._linkedConnectionSourceTypeChangedObserver=this._linkedConnectionSourceBackingField.onTypeChangedObservable.add((()=>{this._notifyTypeChanged()}))))}get direction(){return this._direction}get declarationVariableName(){return this._ownerBlock.isInput?this._ownerBlock.declarationVariableName:this._enforceAssociatedVariableName&&this._associatedVariableName||!this._connectedPoint?this._associatedVariableName:this._connectedPoint.declarationVariableName}get associatedVariableName(){return this._ownerBlock.isInput?this._ownerBlock.associatedVariableName:this._enforceAssociatedVariableName&&this._associatedVariableName||!this._connectedPoint?this._associatedVariableName:this._connectedPoint.associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}get type(){if(this._type===Og.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.connectedPoint._redirectedSource&&this._linkedConnectionSource.connectedPoint._redirectedSource.isConnected?this._linkedConnectionSource.connectedPoint._redirectedSource.type:this._linkedConnectionSource.type}if(this._type===Og.BasedOnInput){if(this._typeConnectionSource)return!this._typeConnectionSource.isConnected&&this._defaultConnectionPointType?this._defaultConnectionPointType:this._typeConnectionSource.type;if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type}set type(e){this._updateTypeDependentState((()=>this._type=e))}get target(){return this._prioritizeVertex&&this._ownerBlock?this._target!==Dg.VertexAndFragment?this._target:this._ownerBlock.target===Dg.Fragment?Dg.Fragment:Dg.Vertex:this._target}set target(e){this._target=e}get isConnected(){return null!==this.connectedPoint||this.hasEndpoints}get isConnectedToInputBlock(){return null!==this.connectedPoint&&this.connectedPoint.ownerBlock.isInput}get connectInputBlock(){return this.isConnectedToInputBlock?this.connectedPoint.ownerBlock:null}get connectedPoint(){return this._connectedPoint}get ownerBlock(){return this._ownerBlock}get sourceBlock(){return this._connectedPoint?this._connectedPoint.ownerBlock:null}get connectedBlocks(){return 0===this._endpoints.length?[]:this._endpoints.map((e=>e.ownerBlock))}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===Dg.Vertex)return!0;if((e.ownerBlock.target===Dg.Neutral||e.ownerBlock.target===Dg.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isDirectlyConnectedToVertexOutput)))return!0}return!1}get isConnectedInVertexShader(){if(this.target===Dg.Vertex)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===Dg.Vertex)return!0;if(e.target===Dg.Vertex)return!0;if((e.ownerBlock.target===Dg.Neutral||e.ownerBlock.target===Dg.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isConnectedInVertexShader)))return!0}return!1}get isConnectedInFragmentShader(){if(this.target===Dg.Fragment)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===Dg.Fragment)return!0;if((e.ownerBlock.target===Dg.Neutral||e.ownerBlock.target===Dg.VertexAndFragment)&&e.ownerBlock.isConnectedInFragmentShader())return!0}return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._preventBubbleUp=!1,this._connectedPointBackingField=null,this._endpoints=new Array,this._redirectedSource=null,this._typeConnectionSourceBackingField=null,this._defaultConnectionPointTypeBackingField=null,this._linkedConnectionSourceBackingField=null,this._acceptedConnectionPointType=null,this._type=Og.Float,this._enforceAssociatedVariableName=!1,this._forPostBuild=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new z.cP,this.onDisconnectionObservable=new z.cP,this.onTypeChangedObservable=new z.cP,this._isTypeChangeObservableNotifying=!1,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=Dg.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return 0===this.checkCompatibilityState(e)}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(t.target===Dg.Fragment){if(i.target===Dg.Vertex)return 2;for(const e of i.outputs)if(e.ownerBlock.target!=Dg.Neutral&&e.isConnectedInVertexShader)return 2}if(this.type!==e.type&&e.innerType!==Og.AutoDetect)return Ug.AreEquivalentTypes(this.type,e.type)||e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)||e._acceptedConnectionPointType&&Ug.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?0:1;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return 1;let r=i,s=t;return 0===this.direction&&(r=t,s=i),r.isAnAncestorOf(s)?3:0}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this)),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear(),this.onDisconnectionObservable.clear(),this.onTypeChangedObservable.clear(),this._connectedPoint=null,this._typeConnectionSource=null,this._linkedConnectionSource=null}_updateTypeDependentState(e){const t=this.type;e(),this.type!==t&&this._notifyTypeChanged()}_notifyTypeChanged(){this._isTypeChangeObservableNotifying||(this._isTypeChangeObservableNotifying=!0,this.onTypeChangedObservable.notifyObservers(this.type),this._isTypeChangeObservableNotifying=!1)}}class Gg{get name(){return this._name}get codeIsReady(){return this._codeIsReady}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get isLoop(){return this._isLoop}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((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.name===e));return t.length?t[0]:null}constructor(e,t=Dg.Vertex,i=!1){switch(this._isFinalMerger=!1,this._isInput=!1,this._isLoop=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._name="",this._isUnique=!1,this._codeIsReady=!0,this.onCodeIsReadyObservable=new z.cP,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===Dg.Neutral,this._isFinalMerger=i,this.getClassName()){case"InputBlock":this._isInput=!0;break;case"NodeMaterialTeleportOutBlock":this._isTeleportOut=!0;break;case"NodeMaterialTeleportInBlock":this._isTeleportIn=!0;break;case"LoopBlock":this._isLoop=!0}this._name=e,this.uniqueId=Op.K.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===Dg.Neutral}initialize(e){}bind(e,t,i,r){}_writeVariable(e){return e.connectedPoint?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return-1===t.indexOf(".")&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}isConnectedInFragmentShader(){return this.outputs.some((e=>e.isConnectedInFragmentShader))}registerInput(e,t,i=!1,r,s){return(s=s??new Ug(e,this,0)).type=t,s.isOptional=i,r&&(s.target=r),this._inputs.push(s),this}registerOutput(e,t,i,r){return(r=r??new Ug(e,this,1)).type=t,i&&(r.target=i),this._outputs.push(r),this}getFirstAvailableInput(e=null){for(const t of this._inputs)if(!(t.connectedPoint||e&&e.type!==t.type&&t.type!==Og.AutoDetect&&-1===t.acceptedConnectionPointTypes.indexOf(e.type)))return t;return null}getFirstAvailableOutput(e=null){for(const t of this._outputs)if(!e||!e.target||e.target===Dg.Neutral||e.target&t.target)return t;return null}getSiblingOutput(e){const t=this._outputs.indexOf(e);return-1===t||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)return!0;if(i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(0===this._outputs.length)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),r=!0;for(;r;){const s=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&s&&i.canConnectTo(s))i.connectTo(s),r=!1;else{if(!i)throw"Unable to find a compatible match";i=this.getSiblingOutput(i)}}return this}_buildBlock(e){}_postBuildBlock(e){}updateUniformsAndSamples(e,t,i,r){}provideFallbacks(e,t){}initializeDefines(e,t,i,r=!1){}prepareDefines(e,t,i,r=!1,s){}autoConfigure(e,t=(()=>!0)){}replaceRepeatableContent(e,t,i,r){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return!(this.isInput||this.isFinalMerger||this._outputs.some((e=>e.isDirectlyConnectedToVertexOutput))||this.target===Dg.Vertex||this.target!==Dg.VertexAndFragment&&this.target!==Dg.Neutral||!this._outputs.some((e=>e.isConnectedInVertexShader)))}isReady(e,t,i,r=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,r){e.build(t,r);const s=null!=t._vertexState,n=e._buildTarget===Dg.Vertex&&e.target!==Dg.VertexAndFragment;if(s&&(!(e.target&e._buildTarget)||!(e.target&i.target)||this.target!==Dg.VertexAndFragment&&n)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){const e=i.connectedPoint;if(t._vertexState._emitVaryingFromString("v_"+e.declarationVariableName,e.type)){const i=1===t.shaderLanguage?"vertexOutputs.":"";t._vertexState.compilationString+=`${i}${"v_"+e.declarationVariableName} = ${e.associatedVariableName};\n`}const r=1===t.shaderLanguage?"fragmentInputs.":"";i.associatedVariableName=r+"v_"+e.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 t of this._outputs)t.associatedVariableName||(t.associatedVariableName=e._getFreeVariableName(t.name));for(const i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==Dg.Neutral){if(!(i.target&this.target))continue;if(!(i.target&e.target))continue}const r=i.connectedPoint.ownerBlock;r&&r!==this&&this._processBuild(r,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&Z.V.Log(`${e.target===Dg.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case Dg.Vertex:e.sharedData.checks.emitVertex=!0;break;case Dg.Fragment:e.sharedData.checks.emitFragment=!0}!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=`\n//${this.name}\n`),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target;for(const i of this._outputs)if(!i._forPostBuild&&i.target&e.target)for(const r of i.endpoints){const i=r.ownerBlock;i&&(i.target&e.target&&-1!==t.indexOf(i)||e._terminalBlocks.has(i))&&this._processBuild(i,e,r,t)}this._postBuildBlock(e);for(const i of this._outputs)if(i._forPostBuild&&i.target&e.target)for(const r of i.endpoints){const i=r.ownerBlock;i&&i.target&e.target&&-1!==t.indexOf(i)&&this._processBuild(i,e,r,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){const e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector};\n${e}.visibleOnFrame = ${this.visibleOnFrame};\n${e}.target = ${this.target};\n`}_dumpCode(e,t){t.push(this);const i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=i+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let r=`\n// ${this.getClassName()}\n`;this.comments&&(r+=`// ${this.comments}\n`),r+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}");\n`,r+=this._dumpPropertiesCode();for(const i of this.inputs){if(!i.isConnected)continue;const s=i.connectedPoint.ownerBlock;-1===t.indexOf(s)&&(r+=s._dumpCode(e,t))}for(const i of this.outputs)if(i.hasEndpoints)for(const s of i.endpoints){const i=s.ownerBlock;i&&-1===t.indexOf(i)&&(r+=i._dumpCode(e,t))}return r}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e),t+=`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\n`}return t}clone(e,t=""){const i=this.serialize(),r=(0,X.n9)(i.customType);if(r){const s=new r;return s._deserialize(i,e,t),s}return null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.visibleInInspector=this.visibleInInspector,e.visibleOnFrame=this.visibleOnFrame,e.target=this.target,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i,r){this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=e.target??this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach(((e,t)=>{e.displayName&&(this.inputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.inputs[t].isExposedOnFrame=e.isExposedOnFrame,this.inputs[t].exposedPortPosition=e.exposedPortPosition)})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}dispose(){this.onCodeIsReadyObservable.clear();for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose()}}class zg extends Gg{get transformAsDirection(){return 0===this.complementW}set transformAsDirection(e){this.complementW=e?0:1}constructor(e){super(e,Dg.Neutral),this.complementW=1,this.complementZ=0,this.target=Dg.Vertex,this.registerInput("vector",Og.AutoDetect),this.registerInput("transform",Og.Matrix),this.registerOutput("output",Og.Vector4),this.registerOutput("xyz",Og.Vector3),this._inputs[0].onConnectionObservable.add((e=>{if(e.ownerBlock.isInput){const t=e.ownerBlock;"normal"!==t.name&&"tangent"!==t.name||(this.complementW=0)}}))}getClassName(){return"TransformBlock"}get vector(){return this._inputs[0]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}get transform(){return this._inputs[1]}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.transform,r=e._getShaderType(Og.Vector4),s=e._getShaderType(Og.Vector3);if(t.connectedPoint){if(0===this.complementW||this.transformAsDirection){const n=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",n),e.sharedData.blocksWithDefines.push(this);const o=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(1===e.shaderLanguage?e.compilationString+=`var ${o}: mat3x3f = mat3x3f(${i.associatedVariableName}[0].xyz, ${i.associatedVariableName}[1].xyz, ${i.associatedVariableName}[2].xyz);\n`:e.compilationString+=`mat3 ${o} = mat3(${i.associatedVariableName});\n`,e.compilationString+="#ifdef NONUNIFORMSCALING\n",e.compilationString+=`${o} = transposeMat3(inverseMat3(${o}));\n`,e.compilationString+="#endif\n",t.connectedPoint.type){case Og.Vector2:e.compilationString+=e._declareOutput(this.output)+` = ${r}(${o} * ${s}(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)});\n`;break;case Og.Vector3:case Og.Color3:e.compilationString+=e._declareOutput(this.output)+` = ${r}(${o} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\n`;break;default:e.compilationString+=e._declareOutput(this.output)+` = ${r}(${o} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)});\n`}}else{const s=i.associatedVariableName;switch(t.connectedPoint.type){case Og.Vector2:e.compilationString+=e._declareOutput(this.output)+` = ${s} * ${r}(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)});\n`;break;case Og.Vector3:case Og.Color3:e.compilationString+=e._declareOutput(this.output)+` = ${s} * ${r}(${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\n`;break;default:e.compilationString+=e._declareOutput(this.output)+` = ${s} * ${t.associatedVariableName};\n`}}this.xyz.hasEndpoints&&(e.compilationString+=e._declareOutput(this.xyz)+` = ${this.output.associatedVariableName}.xyz;\n`)}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=void 0!==e.complementZ?e.complementZ:0,this.complementW=void 0!==e.complementW?e.complementW:1}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ};\n`;return e+=`${this._codeVariableName}.complementW = ${this.complementW};\n`,e}}(0,je.Cg)([t_("Transform as direction",0,void 0,{embedded:!0})],zg.prototype,"transformAsDirection",null),(0,X.Y5)("BABYLON.TransformBlock",zg);class Wg extends Gg{constructor(e){super(e,Dg.Vertex,!0),this.registerInput("vector",Og.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e,t){if(t)return!0;for(const t of e)if(t.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=1===e.shaderLanguage;if(1===e.shaderLanguage?e.compilationString+=`vertexOutputs.position = ${t.associatedVariableName};\n`:e.compilationString+=`gl_Position = ${t.associatedVariableName};\n`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes,e.sharedData.nodeMaterial.useLogarithmicDepth)){e._emitUniformFromString("logarithmicDepthConstant",Og.Float),e._emitVaryingFromString("vFragmentDepth",Og.Float);const t=i?"vertexOutputs.vFragmentDepth":"vFragmentDepth",r=i?"uniforms.":"",s=i?"vertexOutputs.position":"gl_Position";e.compilationString+=`${t} = 1.0 + ${s}.w;\n`,e.compilationString+=`${s}.z = log2(max(0.000001, ${t})) * ${r}logarithmicDepthConstant;\n`}return this}}(0,X.Y5)("BABYLON.VertexOutputBlock",Wg),function(e){e[e.NoColorSpace=0]="NoColorSpace",e[e.Gamma=1]="Gamma",e[e.Linear=2]="Linear"}(Fg||(Fg={}));class Hg extends Gg{constructor(e){super(e,Dg.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",Og.Color4,!0),this.registerInput("rgb",Og.Color3,!0),this.registerInput("a",Og.Float,!0),this.rgb.acceptedConnectionPointTypes.push(Og.Vector3),this.rgb.acceptedConnectionPointTypes.push(Og.Float)}get colorSpace(){return this.convertToGammaSpace?Fg.Gamma:this.convertToLinearSpace?Fg.Linear:Fg.NoColorSpace}set colorSpace(e){this.convertToGammaSpace=e===Fg.Gamma,this.convertToLinearSpace=e===Fg.Linear}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&&(0,Bt.DL)(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=this.rgba,i=this.rgb,r=this.a,s=1===e.shaderLanguage;e.sharedData.hints.needAlphaBlending=t.isConnected||r.isConnected,e.sharedData.blocksWithDefines.push(this),(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant",Og.Float),e._emitVaryingFromString("vFragmentDepth",Og.Float),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");const n=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",n);let o="gl_FragColor";1===e.shaderLanguage&&(e.compilationString+="var fragmentOutputsColor : vec4;\r\n",o="fragmentOutputsColor");const a=e._getShaderType(Og.Vector4);if(t.connectedPoint)r.isConnected?e.compilationString+=`${o} = ${a}(${t.associatedVariableName}.rgb, ${r.associatedVariableName});\n`:e.compilationString+=`${o} = ${t.associatedVariableName};\n`;else if(i.connectedPoint){let t="1.0";r.connectedPoint&&(t=r.associatedVariableName),i.connectedPoint.type===Og.Float?e.compilationString+=`${o} = ${a}(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${t});\n`:e.compilationString+=`${o} = ${a}(${i.associatedVariableName}, ${t});\n`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);if(e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${o} = toLinearSpace(${o});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${o} = toGammaSpace(${o});\n`,e.compilationString+="#endif\n",1===e.shaderLanguage&&(e.compilationString+="#if !defined(PREPASS)\r\n",e.compilationString+="fragmentOutputs.color = fragmentOutputsColor;\r\n",e.compilationString+="#endif\r\n"),this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth){const t=s?"input.vFragmentDepth":"vFragmentDepth",i=s?"uniforms.":"",r=s?"fragmentOutputs.fragDepth":"gl_FragDepthEXT";e.compilationString+=`${r} = log2(${t}) * ${i}logarithmicDepthConstant * 0.5;\n`}return e.compilationString+="#if defined(PREPASS)\r\n",e.compilationString+=`${s?"fragmentOutputs.fragData0":"gl_FragData[0]"} = ${o};\r\n`,e.compilationString+="#endif\r\n",this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth};\n`,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}}(0,je.Cg)([t_("Use logarithmic depth",0,"PROPERTIES",{embedded:!0})],Hg.prototype,"useLogarithmicDepth",void 0),(0,je.Cg)([t_("Color space",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"No color space",value:Fg.NoColorSpace},{label:"Gamma",value:Fg.Gamma},{label:"Linear",value:Fg.Linear}]})],Hg.prototype,"colorSpace",null),(0,X.Y5)("BABYLON.FragmentOutputBlock",Hg),function(e){e[e.World=1]="World",e[e.View=2]="View",e[e.Projection=3]="Projection",e[e.ViewProjection=4]="ViewProjection",e[e.WorldView=5]="WorldView",e[e.WorldViewProjection=6]="WorldViewProjection",e[e.CameraPosition=7]="CameraPosition",e[e.FogColor=8]="FogColor",e[e.DeltaTime=9]="DeltaTime",e[e.CameraParameters=10]="CameraParameters",e[e.MaterialAlpha=11]="MaterialAlpha"}(Lg||(Lg={})),function(e){e[e.None=0]="None",e[e.Time=1]="Time",e[e.RealTime=2]="RealTime",e[e.MouseInfo=3]="MouseInfo"}(Bg||(Bg={}));const Xg={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},qg={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},Yg={particle_texturemask:!0};class Kg extends Gg{get type(){if(this._type===Og.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=Og.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=Og.Vector2,this._type;case"Vector3":return this._type=Og.Vector3,this._type;case"Vector4":return this._type=Og.Vector4,this._type;case"Color3":return this._type=Og.Color3,this._type;case"Color4":return this._type=Og.Color4,this._type;case"Matrix":return this._type=Og.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"splatIndex":return this._type=Og.Float,this._type;case"position":case"normal":case"particle_positionw":case"splatPosition":return this._type=Og.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":case"splatScale":return this._type=Og.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=Og.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":case"splatColor":return this._type=Og.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case Lg.World:case Lg.WorldView:case Lg.WorldViewProjection:case Lg.View:case Lg.ViewProjection:case Lg.Projection:return this._type=Og.Matrix,this._type;case Lg.CameraPosition:return this._type=Og.Vector3,this._type;case Lg.FogColor:return this._type=Og.Color3,this._type;case Lg.DeltaTime:case Lg.MaterialAlpha:return this._type=Og.Float,this._type;case Lg.CameraParameters:return this._type=Og.Vector4,this._type}}return this._type}constructor(e,t=Dg.Vertex,i=Og.AutoDetect){super(e,t,!1),this._mode=3,this._animationType=Bg.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 z.cP,this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._type=i,this.setDefaultValue(),this.registerOutput("output",i)}validateBlockName(e){return!!this.isAttribute||super.validateBlockName(e)}get output(){return this._outputs[0]}setAsAttribute(e){return this._mode=1,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===Og.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=0,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=0}get declarationVariableName(){return this._associatedVariableName}get associatedVariableName(){return this._prefix+this._associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get animationType(){return this._animationType}set animationType(e){this._animationType=e}get isUndefined(){return 3===this._mode}get isUniform(){return 0===this._mode}set isUniform(e){this._mode=e?0:3,this.associatedVariableName=""}get isAttribute(){return 1===this._mode}set isAttribute(e){this._mode=e?1:3,this.associatedVariableName=""}get isVarying(){return 2===this._mode}set isVarying(e){this._mode=e?2:3,this.associatedVariableName=""}get isSystemValue(){return null!=this._systemValue}get systemValue(){return this._systemValue}set systemValue(e){this._mode=0,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case Bg.Time:this.type===Og.Float&&(this.value+=.01*e.getAnimationRatio());break;case Bg.RealTime:this.type===Og.Float&&(this.value=(ai.j.Now-e.getEngine().startTime)/1e3);break;case Bg.MouseInfo:if(this.type===Og.Vector4){const t=e._inputManager._originMouseEvent;if(t){const e=t.offsetX,i=t.offsetY,r=1&t.buttons?1:0,s=2&t.buttons?1:0;this.value=new W.IU(e,i,r,s)}else this.value=new W.IU(0,0,0,0)}}}_emitDefine(e){return"!"===e[0]?`#ifndef ${e.substring(1)}\n`:`#ifdef ${e}\n`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case Og.Float:this.value=0;break;case Og.Vector2:this.value=W.I9.Zero();break;case Og.Vector3:this.value=W.Pq.Zero();break;case Og.Vector4:this.value=W.IU.Zero();break;case Og.Color3:this.value=hc.v9.White();break;case Og.Color4:this.value=new hc.ov(1,1,1,1);break;case Og.Matrix:this.value=W.uq.Identity()}}_emitConstant(e){switch(this.type){case Og.Float:return`${e._emitFloat(this.value)}`;case Og.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case Og.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case Og.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case Og.Color3:return hc.IG.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&hc.IG.Color3[0].toGammaSpaceToRef(hc.IG.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&hc.IG.Color3[0].toLinearSpaceToRef(hc.IG.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${hc.IG.Color3[0].r}, ${hc.IG.Color3[0].g}, ${hc.IG.Color3[0].b})`;case Og.Color4:return hc.IG.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&hc.IG.Color4[0].toGammaSpaceToRef(hc.IG.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&hc.IG.Color4[0].toLinearSpaceToRef(hc.IG.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${hc.IG.Color4[0].r}, ${hc.IG.Color4[0].g}, ${hc.IG.Color4[0].b}, ${hc.IG.Color4[0].a})`}return""}get _noContextSwitch(){return qg[this.name]}_emit(e,t){if(this.isUniform){if(this._associatedVariableName||(this._associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(-1!==e.constants.indexOf(this.associatedVariableName))return;return e.constants.push(this.associatedVariableName),void(e._constantDeclaration+=e._declareOutput(this.output,!0)+` = ${this._emitConstant(e)};\n`)}if(-1!==e.uniforms.indexOf(this.associatedVariableName))return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t));const i=e._getShaderType(this.type);1===e.shaderLanguage?(e._uniformDeclaration+=`uniform ${this._associatedVariableName}: ${i};\n`,this._prefix="uniforms."):e._uniformDeclaration+=`uniform ${i} ${this.associatedVariableName};\n`,t&&(e._uniformDeclaration+="#endif\n");const r=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case Lg.WorldView:r.needWorldViewMatrix=!0;break;case Lg.WorldViewProjection:r.needWorldViewProjectionMatrix=!0}else this._animationType!==Bg.None&&e.sharedData.animatedInputs.push(this)}else if(this.isAttribute){if(this.associatedVariableName=Xg[this.name]??this.name,this.target===Dg.Vertex&&e._vertexState)return void(qg[this.name]?Yg[this.name]?(e._emitUniformFromString(this.declarationVariableName,this.type,t),1===e.shaderLanguage&&(this._prefix="vertexInputs.")):e._emitVaryingFromString(this.declarationVariableName,this.type,t):this._emit(e._vertexState,t));const i=-1!==e.attributes.indexOf(this.declarationVariableName);i||e.attributes.push(this.declarationVariableName),qg[this.name]?Yg[this.name]?(i||e._emitUniformFromString(this.declarationVariableName,this.type,t),1===e.shaderLanguage&&(this._prefix="uniforms.")):(i||e._emitVaryingFromString(this.declarationVariableName,this.type,t),1===e.shaderLanguage&&(this._prefix="fragmentInputs.")):(t&&!i&&(e._attributeDeclaration+=this._emitDefine(t)),1===e.shaderLanguage?(i||(e._attributeDeclaration+=`attribute ${this.declarationVariableName}: ${e._getShaderType(this.type)};\n`),this._prefix="vertexInputs."):i||(e._attributeDeclaration+=`attribute ${e._getShaderType(this.type)} ${this.declarationVariableName};\n`),t&&!i&&(e._attributeDeclaration+="#endif\n"))}}_transmitWorld(e,t,i,r){if(!this._systemValue)return;const s=this._associatedVariableName;switch(this._systemValue){case Lg.World:e.setMatrix(s,t);break;case Lg.WorldView:e.setMatrix(s,i);break;case Lg.WorldViewProjection:e.setMatrix(s,r)}}_transmit(e,t,i){if(this.isAttribute)return;const r=this._associatedVariableName;if(this._systemValue){switch(this._systemValue){case Lg.World:case Lg.WorldView:case Lg.WorldViewProjection:return;case Lg.View:e.setMatrix(r,t.getViewMatrix());break;case Lg.Projection:e.setMatrix(r,t.getProjectionMatrix());break;case Lg.ViewProjection:e.setMatrix(r,t.getTransformMatrix());break;case Lg.CameraPosition:t.bindEyePosition(e,r,!0);break;case Lg.FogColor:e.setColor3(r,t.fogColor);break;case Lg.DeltaTime:e.setFloat(r,t.deltaTime/1e3);break;case Lg.CameraParameters:t.activeCamera&&e.setFloat4(r,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case Lg.MaterialAlpha:e.setFloat(r,i.alpha)}return}const s=this._valueCallback?this._valueCallback():this._storedValue;if(null!==s)switch(this.type){case Og.Float:e.setFloat(r,s);break;case Og.Int:e.setInt(r,s);break;case Og.Color3:hc.IG.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&hc.IG.Color3[0].toGammaSpaceToRef(hc.IG.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&hc.IG.Color3[0].toLinearSpaceToRef(hc.IG.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(r,hc.IG.Color3[0]);break;case Og.Color4:hc.IG.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&hc.IG.Color4[0].toGammaSpaceToRef(hc.IG.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&hc.IG.Color4[0].toLinearSpaceToRef(hc.IG.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(r,hc.IG.Color4[0]);break;case Og.Vector2:e.setVector2(r,s);break;case Og.Vector3:e.setVector3(r,s);break;case Og.Vector4:e.setVector4(r,s);break;case Og.Matrix:e.setMatrix(r,s)}}_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}");\n`;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${Lg[this._systemValue]});\n`;if(this.isUniform){const t=[];let i="";switch(this.type){case Og.Float:i=`${this.value}`;break;case Og.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case Og.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case Og.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case Og.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case Og.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 Og.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`}return t.push(`${e}.value = ${i}`),this.type===Og.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${Bg[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}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,null!=this._storedValue&&0===this._mode&&(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,"tangent"===e.name&&1===e.mode&&e.type===Og.Vector3&&(this._type=Og.Vector4),e.valueType)if("number"===e.valueType)this._storedValue=e.value;else{const t=(0,X.n9)(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}(0,X.Y5)("BABYLON.InputBlock",Kg);class jg extends Gg{constructor(e){super(e,Dg.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",Og.AutoDetect,!1,Dg.VertexAndFragment),this.registerOutput("rgba",Og.Color4,Dg.Neutral),this.registerOutput("rgb",Og.Color3,Dg.Neutral),this.registerOutput("r",Og.Float,Dg.Neutral),this.registerOutput("g",Og.Float,Dg.Neutral),this.registerOutput("b",Og.Float,Dg.Neutral),this.registerOutput("a",Og.Float,Dg.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(Og.Vector2|Og.Vector3|Og.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"CurrentScreenBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName(this._samplerName)}get target(){return this.uv.isConnected?this.uv.sourceBlock.isInput?Dg.VertexAndFragment:Dg.Fragment:Dg.VertexAndFragment}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,Og.Vector2)),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,Og.Vector2),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name,!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===Dg.Fragment)return;const t=0===e.shaderLanguage?`texture2D(${this._samplerName},`:`textureSampleLevel(${this._samplerName}, ${this._samplerName+"Sampler"},`,r=0===e.shaderLanguage?"":", 0";return void(e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = ${t} ${i.associatedVariableName}${r});\n`)}const r=0===e.shaderLanguage?`texture2D(${this._samplerName},`:`textureSample(${this._samplerName}, ${this._samplerName+"Sampler"},`;this.uv.ownerBlock.target!==Dg.Fragment?e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = ${r} ${this._mainUVName});\n`:e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = ${r} ${i.associatedVariableName});\n`}_writeOutput(e,t,i,r=!1){if(r){if(e.target===Dg.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}else this.uv.ownerBlock.target!==Dg.Fragment?(e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n"):e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}_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!==Dg.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(!this._outputs.some((e=>e.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 t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.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=0===e.texture.url.indexOf("data:")?"":i,this.texture=vi.g.Parse(e.texture,t,i))}}(0,X.Y5)("BABYLON.CurrentScreenBlock",jg);class $g extends Gg{constructor(e){super(e,Dg.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",Og.AutoDetect,!1,Dg.VertexAndFragment),this.registerOutput("rgba",Og.Color4,Dg.Neutral),this.registerOutput("rgb",Og.Color3,Dg.Neutral),this.registerOutput("r",Og.Float,Dg.Neutral),this.registerOutput("g",Og.Float,Dg.Neutral),this.registerOutput("b",Og.Float,Dg.Neutral),this.registerOutput("a",Og.Float,Dg.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(Og.Vector2|Og.Vector3|Og.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((e=>e.isAttribute&&"particle_uv"===e.name&&t(e)));i||(i=new Kg("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};\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n"}_buildBlock(e){if(super._buildBlock(e),e.target===Dg.Vertex)return;this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e._emit2DSampler(this._samplerName),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = ${e._generateTextureSample(this.uv.associatedVariableName,this._samplerName)};\n`;for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.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=0===e.texture.url.indexOf("data:")?"":i,this.texture=vi.g.Parse(e.texture,t,i))}}(0,X.Y5)("BABYLON.ParticleTextureBlock",$g);class Qg extends Gg{constructor(e){super(e,Dg.Fragment),this._isUnique=!0,this.registerInput("color",Og.Color4,!1,Dg.Fragment),this.registerOutput("rampColor",Og.Color4,Dg.Fragment)}getClassName(){return"ParticleRampGradientBlock"}get color(){return this._inputs[0]}get rampColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("remapRanges"),e._excludeVariableName("rampSampler"),e._excludeVariableName("baseColor"),e._excludeVariableName("alpha"),e._excludeVariableName("remappedColorIndex"),e._excludeVariableName("rampColor")}_buildBlock(e){if(super._buildBlock(e),e.target!==Dg.Vertex)return e._emit2DSampler("rampSampler","RAMPGRADIENT"),e._emitVaryingFromString("remapRanges",Og.Vector4,"RAMPGRADIENT"),e.compilationString+=`\n #ifdef RAMPGRADIENT\n ${e._declareLocalVar("baseColor",Og.Vector4)} = ${this.color.associatedVariableName};\n ${e._declareLocalVar("alpha",Og.Float)} = ${this.color.associatedVariableName}.a;\n\n ${e._declareLocalVar("remappedColorIndex",Og.Float)} = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0);\n\n ${e._declareLocalVar("rampColor",Og.Vector4)} = ${e._generateTextureSample("vec2(1.0 - remappedColorIndex, 0.)","rampSampler")};\n\n // Remapped alpha\n ${e._declareOutput(this.rampColor)} = vec4${e.fSuffix}(baseColor.rgb * rampColor.rgb, clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0));\n #else\n ${e._declareOutput(this.rampColor)} = ${this.color.associatedVariableName};\n #endif\n `,this}}(0,X.Y5)("BABYLON.ParticleRampGradientBlock",Qg);class Zg extends Gg{constructor(e){super(e,Dg.Fragment),this._isUnique=!0,this.registerInput("color",Og.Color4,!1,Dg.Fragment),this.registerInput("alphaTexture",Og.Float,!1,Dg.Fragment),this.registerInput("alphaColor",Og.Float,!1,Dg.Fragment),this.registerOutput("blendColor",Og.Color4,Dg.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!==Dg.Vertex)return e.compilationString+=`\n #ifdef BLENDMULTIPLYMODE\n ${e._declareOutput(this.blendColor)};\n ${e._declareLocalVar("sourceAlpha",Og.Float)} = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName};\n ${this.blendColor.associatedVariableName} = vec4${e.fSuffix}(${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha), ${this.color.associatedVariableName}.a);\n #else\n ${e._declareOutput(this.blendColor)} = ${this.color.associatedVariableName};\n #endif\n `,this}}(0,X.Y5)("BABYLON.ParticleBlendMultiplyBlock",Zg);class Jg extends Gg{constructor(e){super(e,Dg.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",Og.Vector4,!0),this.registerInput("xyz ",Og.Vector3,!0),this.registerInput("xy ",Og.Vector2,!0),this.registerInput("zw ",Og.Vector2,!0),this.registerInput("x",Og.Float,!0),this.registerInput("y",Og.Float,!0),this.registerInput("z",Og.Float,!0),this.registerInput("w",Og.Float,!0),this.registerOutput("xyzw",Og.Vector4),this.registerOutput("xyz",Og.Vector3),this.registerOutput("xy",Og.Vector2),this.registerOutput("zw",Og.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"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":e}_buildSwizzle(e){return"."+(this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle).substring(0,e)}_buildBlock(e){super._buildBlock(e);const t=this.x,i=this.y,r=this.z,s=this.w,n=this.xyIn,o=this.zwIn,a=this.xyzIn,l=this.xyzwIn,h=this._outputs[0],c=this._outputs[1],u=this._outputs[2],d=this._outputs[3],f=e._getShaderType(Og.Vector4),p=e._getShaderType(Og.Vector3),_=e._getShaderType(Og.Vector2);return l.isConnected?(h.hasEndpoints&&(e.compilationString+=e._declareOutput(h)+` = ${l.associatedVariableName}${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${l.associatedVariableName}${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${l.associatedVariableName}${this._buildSwizzle(2)};\n`)):a.isConnected?(h.hasEndpoints&&(e.compilationString+=e._declareOutput(h)+` = ${f}(${a.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${a.associatedVariableName}${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${a.associatedVariableName}${this._buildSwizzle(2)};\n`)):n.isConnected?(h.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(h)+` = ${f}(${n.associatedVariableName}, ${o.associatedVariableName})${this._buildSwizzle(4)};\n`:e.compilationString+=e._declareOutput(h)+` = ${f}(${n.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${p}(${n.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${n.associatedVariableName}${this._buildSwizzle(2)};\n`),d.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(d)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\n`:e.compilationString+=e._declareOutput(d)+` = ${_}(${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(2)};\n`)):(h.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(h)+` = ${f}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${o.associatedVariableName})${this._buildSwizzle(4)};\n`:e.compilationString+=e._declareOutput(h)+` = ${f}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${p}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${_}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)};\n`),d.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(d)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\n`:e.compilationString+=e._declareOutput(d)+` = ${_}(${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(2)};\n`)),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}";\n`,e+=`${this._codeVariableName}.ySwizzle = "${this.ySwizzle}";\n`,e+=`${this._codeVariableName}.zSwizzle = "${this.zSwizzle}";\n`,e+=`${this._codeVariableName}.wSwizzle = "${this.wSwizzle}";\n`,e}}(0,X.Y5)("BABYLON.VectorMergerBlock",Jg);class ev extends Gg{constructor(e){super(e,Dg.Neutral),this.sourceRange=new W.I9(-1,1),this.targetRange=new W.I9(0,1),this.registerInput("input",Og.AutoDetect),this.registerInput("sourceMin",Og.Float,!0),this.registerInput("sourceMax",Og.Float,!0),this.registerInput("targetMin",Og.Float,!0),this.registerInput("targetMax",Og.Float,!0),this.registerOutput("output",Og.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"RemapBlock"}get input(){return this._inputs[0]}get sourceMin(){return this._inputs[1]}get sourceMax(){return this._inputs[2]}get targetMin(){return this._inputs[3]}get targetMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),r=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),s=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)+` = ${s} + (${this._inputs[0].associatedVariableName} - ${i}) * (${n} - ${s}) / (${r} - ${i});\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y});\n`;return e+=`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y});\n`,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=W.I9.FromArray(e.sourceRange),this.targetRange=W.I9.FromArray(e.targetRange)}}(0,je.Cg)([t_("From",3)],ev.prototype,"sourceRange",void 0),(0,je.Cg)([t_("To",3)],ev.prototype,"targetRange",void 0),(0,X.Y5)("BABYLON.RemapBlock",ev);class tv extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("left",Og.AutoDetect),this.registerInput("right",Og.AutoDetect),this.registerOutput("output",Og.BasedOnInput),this.output._typeConnectionSource=this.left,this._linkConnectionTypes(0,1,!0),this.left.acceptedConnectionPointTypes.push(Og.Float),this.right.acceptedConnectionPointTypes.push(Og.Float),this._connectionObservers=[this.left.onTypeChangedObservable.add((()=>this._updateInputOutputTypes())),this.right.onTypeChangedObservable.add((()=>this._updateInputOutputTypes()))]}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_updateInputOutputTypes(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===Og.Int||this.left.type===Og.Float&&this.right.type!==Og.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=[Og.Int,Og.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),t.type!==Og.Int&&t.type!==Og.Float||e.acceptedConnectionPointTypes.push(Og.Vector2,Og.Vector3,Og.Vector4,Og.Color3,Og.Color4,Og.Matrix))}dispose(){super.dispose(),this._connectionObservers.forEach((e=>e.remove())),this._connectionObservers.length=0}}class iv extends tv{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};\n`,this}}var rv;(0,X.Y5)("BABYLON.MultiplyBlock",iv),function(e){e[e.Material=0]="Material",e[e.PostProcess=1]="PostProcess",e[e.Particle=2]="Particle",e[e.ProceduralTexture=3]="ProceduralTexture",e[e.GaussianSplatting=4]="GaussianSplatting"}(rv||(rv={}));class sv extends xn{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 nv{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:W.Pq.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:W.Pq.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:W.Pq.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:W.Pq.Zero()}set maxEmitBox(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())}get isBillboardBased(){return this._isBillboardBased}set isBillboardBased(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)}_reset(){}_removeGradientAndTexture(e,t,i){if(!t)return this;let r=0;for(const i of t){if(i.gradient===e){t.splice(r,1);break}r++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=W.Pq.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 W.Pq(10,10,10),this.onAnimationEnd=null,this.blendMode=nv.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 W.I9(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new W.Pq(0,0,0),this._useLogarithmicDepth=!1,this.gravity=W.Pq.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 H.ov(1,1,1,1),this.color2=new H.ov(1,1,1,1),this.colorDead=new H.ov(0,0,0,1),this.textureMask=new H.ov(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new sv,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 W.Pq(0,1,0),i=new W.Pq(0,1,0)){throw new Error("Method not implemented.")}createCylinderEmitter(e=1,t=1,i=1,r=0){throw new Error("Method not implemented.")}createDirectedCylinderEmitter(e=1,t=1,i=1,r=new W.Pq(0,1,0),s=new W.Pq(0,1,0)){throw new Error("Method not implemented.")}createConeEmitter(e=1,t=Math.PI/4){throw new Error("Method not implemented.")}createDirectedConeEmitter(e=1,t=Math.PI/4,i=new W.Pq(0,1,0),r=new W.Pq(0,1,0)){throw new Error("Method not implemented.")}createBoxEmitter(e,t,i,r){throw new Error("Method not implemented.")}}nv.BLENDMODE_ONEONE=0,nv.BLENDMODE_STANDARD=1,nv.BLENDMODE_ADD=2,nv.BLENDMODE_MULTIPLY=3,nv.BLENDMODE_MULTIPLYADD=4,(0,X.Y5)("BABYLON.BaseParticleSystem",nv);class ov extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("rgba",Og.Color4,!0),this.registerInput("rgb ",Og.Color3,!0),this.registerOutput("rgb",Og.Color3),this.registerOutput("r",Og.Float),this.registerOutput("g",Og.Float),this.registerOutput("b",Og.Float),this.registerOutput("a",Og.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"rgb "===e?"rgbIn":e}_outputRename(e){return"rgb"===e?"rgbOut":e}_buildBlock(e){super._buildBlock(e);const t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;const i=this._outputs[0],r=this._outputs[1],s=this._outputs[2],n=this._outputs[3],o=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=e._declareOutput(i)+` = ${t.associatedVariableName}.rgb;\n`),r.hasEndpoints&&(e.compilationString+=e._declareOutput(r)+` = ${t.associatedVariableName}.r;\n`),s.hasEndpoints&&(e.compilationString+=e._declareOutput(s)+` = ${t.associatedVariableName}.g;\n`),n.hasEndpoints&&(e.compilationString+=e._declareOutput(n)+` = ${t.associatedVariableName}.b;\n`),o.hasEndpoints&&(e.compilationString+=e._declareOutput(o)+` = ${t.associatedVariableName}.a;\n`),this}}(0,X.Y5)("BABYLON.ColorSplitterBlock",ov);var av,lv=i(72649);class hv{constructor(e){this.name=Ut.v.NAME_PROCEDURALTEXTURE,this.scene=e}register(){this.scene._beforeClearStage.registerStep(Ut.v.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){Ue.S0.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}}class cv extends vi.g{get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,r,s=null,n=!0,o=!1,a=0){super(null,r,!n),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new z.cP,this.onBeforeGenerationObservable=new z.cP,this.nodeMaterialSource=null,this.defines="",this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=new Array,this._samplers=new Array,this._floats={},this._ints={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._vectors4={},this._matrices={},this._fallbackTextureUsed=!1,this._cachedDefines=null,this._contentUpdateId=-1,this._rtWrapper=null,null===s||s instanceof vi.g?(this._options={},this._fallbackTexture=s):(this._options=s,this._fallbackTexture=s.fallbackTexture??null),this._shaderLanguage=this._options.shaderLanguage??0;let l=(r=this.getScene()||he.q.LastCreatedScene)._getComponent(Ut.v.NAME_PROCEDURALTEXTURE);l||(l=new hv(r),r._addComponent(l)),r.proceduralTextures.push(this),this._fullEngine=r.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=a,this._generateMipMaps=n,this._drawWrapper=new gt.E(this._fullEngine),this.setFragment(i);const h=this._createRtWrapper(o,t,n,a);this._texture=h.texture;const c=[];c.push(1,1),c.push(-1,1),c.push(-1,-1),c.push(1,-1),this._vertexBuffers[st.R.PositionKind]=new st.R(this._fullEngine,c,st.R.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,r){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r,...this._options}),this.setFloat("face",0)):(this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r,...this._options}),this._rtWrapper.is3D&&(this.setFloat("layer",0),this.setInt("layerNum",0))),this._rtWrapper}getEffect(){return this._drawWrapper.effect}_setEffect(e){this._drawWrapper.effect=e}getContent(){return this._contentData&&this._frameId===this._contentUpdateId||(this._contentData?this._contentData.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[st.R.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===ln.$.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=ln.$.REFRESHRATE_RENDER_ONCE)}reset(){this._drawWrapper.effect?.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null}_getDefines(){return this.defines}executeWhenReady(e){if(this.isReady())return void e(this);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 r={vertex:"procedural",fragmentElement:this._fragment.fragmentElement,fragmentSource:this._fragment.fragmentSource,fragment:"string"==typeof this._fragment?this._fragment:void 0};return this._cachedDefines!==t&&(this._cachedDefines=t,this._drawWrapper.effect=e.createEffect(r,[st.R.PositionKind],this._uniforms,this._samplers,t,void 0,void 0,(()=>{this._rtWrapper?.dispose(),this._rtWrapper=this._texture=null,this._fallbackTexture&&(this._texture=this._fallbackTexture._texture,this._texture&&this._texture.incrementReferences()),this._fallbackTextureUsed=!0}),void 0,this._shaderLanguage,(async()=>{this._options.extraInitializationsAsync?1===this.shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,67402)),this._options.extraInitializationsAsync()]):await Promise.all([Promise.resolve().then(i.bind(i,92911)),this._options.extraInitializationsAsync()]):1===this.shaderLanguage?await Promise.resolve().then(i.bind(i,67402)):await Promise.resolve().then(i.bind(i,92911))}))),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._fallbackTextureUsed&&(-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)):(this._texture&&(this._texture.isReady=!1),!1)}getRenderSize(){return this._size}resize(e,t){if(this._fallbackTextureUsed||!this._rtWrapper||!this._texture)return;const i=this._texture.isCube;this._rtWrapper.dispose();const r=this._createRtWrapper(i,e,t,this._textureType);this._texture=r.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)}setTexture(e,t){return-1===this._samplers.indexOf(e)&&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){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 e in this._textures)this._drawWrapper.effect.setTexture(e,this._textures[e]);for(const e in this._ints)this._drawWrapper.effect.setInt(e,this._ints[e]);for(const e in this._floats)this._drawWrapper.effect.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)this._drawWrapper.effect.setArray(e,this._floatsArrays[e]);for(const e in this._colors3)this._drawWrapper.effect.setColor3(e,this._colors3[e]);for(const e in this._colors4){const t=this._colors4[e];this._drawWrapper.effect.setFloat4(e,t.r,t.g,t.b,t.a)}for(const e in this._vectors2)this._drawWrapper.effect.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)this._drawWrapper.effect.setVector3(e,this._vectors3[e]);for(const e in this._vectors4)this._drawWrapper.effect.setVector4(e,this._vectors4[e]);for(const e in this._matrices)this._drawWrapper.effect.setMatrix(e,this._matrices[e])}if(!this._texture||!this._rtWrapper)return;i._debugPushGroup?.(`procedural texture generation for ${this.name}`,1);const r=i.currentViewport;if(this.isCube)for(let e=0;e<6;e++)i.bindFramebuffer(this._rtWrapper,e,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",e),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(Vt.TriangleFillMode,0,6),i.unBindFramebuffer(this._rtWrapper,!0);else{let e=1;this._rtWrapper.is3D?e=this._rtWrapper.depth:this._rtWrapper.is2DArray&&(e=this._rtWrapper.layers);for(let r=0;r=0&&e.proceduralTextures.splice(t,1);const i=this._vertexBuffers[st.R.PositionKind];i&&(i.dispose(),this._vertexBuffers[st.R.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}(0,je.Cg)([(0,$e.lK)()],cv.prototype,"isEnabled",void 0),(0,je.Cg)([(0,$e.lK)()],cv.prototype,"autoClear",void 0),(0,je.Cg)([(0,$e.lK)()],cv.prototype,"_generateMipMaps",void 0),(0,je.Cg)([(0,$e.lK)()],cv.prototype,"_size",void 0),(0,je.Cg)([(0,$e.lK)()],cv.prototype,"refreshRate",null),(0,X.Y5)("BABYLON.ProceduralTexture",cv),function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Exp2=4]="Exp2",e[e.Round=5]="Round",e[e.Floor=6]="Floor",e[e.Ceiling=7]="Ceiling",e[e.Sqrt=8]="Sqrt",e[e.Log=9]="Log",e[e.Tan=10]="Tan",e[e.ArcTan=11]="ArcTan",e[e.ArcCos=12]="ArcCos",e[e.ArcSin=13]="ArcSin",e[e.Fract=14]="Fract",e[e.Sign=15]="Sign",e[e.Radians=16]="Radians",e[e.Degrees=17]="Degrees",e[e.Set=18]="Set"}(av||(av={}));class uv extends Gg{constructor(e){super(e,Dg.Neutral),this.operation=av.Cos,this.registerInput("input",Og.AutoDetect),this.registerOutput("output",Og.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 av.Cos:i="cos";break;case av.Sin:i="sin";break;case av.Abs:i="abs";break;case av.Exp:i="exp";break;case av.Exp2:i="exp2";break;case av.Round:i="round";break;case av.Floor:i="floor";break;case av.Ceiling:i="ceil";break;case av.Sqrt:i="sqrt";break;case av.Log:i="log";break;case av.Tan:i="tan";break;case av.ArcTan:i="atan";break;case av.ArcCos:i="acos";break;case av.ArcSin:i="asin";break;case av.Fract:i="fract";break;case av.Sign:i="sign";break;case av.Radians:i="radians";break;case av.Degrees:i="degrees";break;case av.Set:i=""}return e.compilationString+=e._declareOutput(t)+` = ${i}(${this.input.associatedVariableName});\n`,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.${av[this.operation]};\n`}}(0,je.Cg)([t_("Operation",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"Cos",value:av.Cos},{label:"Sin",value:av.Sin},{label:"Abs",value:av.Abs},{label:"Exp",value:av.Exp},{label:"Exp2",value:av.Exp2},{label:"Round",value:av.Round},{label:"Floor",value:av.Floor},{label:"Ceiling",value:av.Ceiling},{label:"Sqrt",value:av.Sqrt},{label:"Log",value:av.Log},{label:"Tan",value:av.Tan},{label:"ArcTan",value:av.ArcTan},{label:"ArcCos",value:av.ArcCos},{label:"ArcSin",value:av.ArcSin},{label:"Fract",value:av.Fract},{label:"Sign",value:av.Sign},{label:"Radians",value:av.Radians},{label:"Degrees",value:av.Degrees},{label:"Set",value:av.Set}]})],uv.prototype,"operation",void 0),(0,X.Y5)("BABYLON.TrigonometryBlock",uv);const dv={effect:null,subMesh:null};class fv extends xn{constructor(){super(),this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR_NME=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.PREPASS=!1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_WORLD_NORMAL=!1,this.PREPASS_WORLD_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_LOCAL_POSITION=!1,this.PREPASS_LOCAL_POSITION_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_SCREENSPACE_DEPTH=!1,this.PREPASS_SCREENSPACE_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){void 0===this[e]&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t}}class pv extends bn{static _BlockIsTextureBlock(e){return"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"===e.getClassName()}_getGlobalNodeMaterialEditor(){return"undefined"!=typeof NODEEDITOR?NODEEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeEditor?BABYLON:void 0}get shaderLanguage(){return this._options.shaderLanguage}set shaderLanguage(e){this._options.shaderLanguage=e}get options(){return this._options}set options(e){this._options=e}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get mode(){return this._mode}set mode(e){this._mode=e}get buildId(){return this._buildId}set buildId(e){this._buildId=e}constructor(e,t,i={}){if(super(e,t||he.q.LastCreatedScene),this._buildId=pv._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new W.uq,this._cachedWorldViewProjectionMatrix=new W.uq,this._optimizers=new Array,this._animationFrame=-1,this._buildIsInProgress=!1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new z.cP,this.onBuildErrorObservable=new z.cP,this._vertexOutputNodes=new Array,this._fragmentOutputNodes=new Array,this.attachedBlocks=[],this._mode=rv.Material,this.forceAlphaBlending=!1,i&&1===i.shaderLanguage&&!this.getScene().getEngine().isWebGPU)throw new Error("WebGPU shader language is only supported with WebGPU engine");this._options={emitComments:!1,shaderLanguage:pv.DefaultShaderLanguage,...i},this._attachImageProcessingConfiguration(null)}getClassName(){return"NodeMaterial"}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||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)return Ue.S0.Warn("More than one block was found with the name `"+e+"`"),t;t=i}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(-1!==t)return this._optimizers.splice(t,1),this}addOutputNode(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return e.target&Dg.Vertex&&this._addVertexOutputNode(e),e.target&Dg.Fragment&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return null===e.target||(e.target&Dg.Vertex&&this._removeVertexOutputNode(e),e.target&Dg.Fragment&&this._removeFragmentOutputNode(e)),this}_addVertexOutputNode(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=Dg.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){const t=this._vertexOutputNodes.indexOf(e);if(-1!==t)return this._vertexOutputNodes.splice(t,1),this}_addFragmentOutputNode(e){if(-1===this._fragmentOutputNodes.indexOf(e))return e.target=Dg.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){const t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return!this.ignoreAlpha&&(this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_processInitializeOnLink(e,t,i,r=!0){(e.target===Dg.VertexAndFragment||t.target===Dg.Fragment&&e.target===Dg.Vertex&&e._preparationId!==this._buildId)&&i.push(e),this._initializeBlock(e,t,i,r)}_attachBlock(e){if(-1===this.attachedBlocks.indexOf(e)){if(e.isUnique){const t=e.getClassName();for(const e of this.attachedBlocks)if(e.getClassName()===t)throw`Cannot have multiple blocks of type ${t} in the same NodeMaterial`}this.attachedBlocks.push(e)}}_initializeBlock(e,t,i,r=!0){e.initialize(t),r&&e.autoConfigure(this),e._preparationId=this._buildId,this._attachBlock(e);for(const s of e.inputs){s.associatedVariableName="";const n=s.connectedPoint;if(n&&!n._preventBubbleUp){const s=n.ownerBlock;s!==e&&this._processInitializeOnLink(s,t,i,r)}}if(e.isLoop){const s=e;if(s.loopID.hasEndpoints)for(const e of s.loopID.endpoints){const s=e.ownerBlock;0===s.outputs.length&&(t._terminalBlocks.add(s),this._processInitializeOnLink(s,t,i,r))}}else if(e.isTeleportOut){const s=e;s.entryPoint&&this._processInitializeOnLink(s.entryPoint,t,i,r)}for(const t of e.outputs)t.associatedVariableName=""}_resetDualBlocks(e,t){e.target===Dg.VertexAndFragment&&(e.buildId=t);for(const i of e.inputs){const r=i.connectedPoint;if(r&&!r._preventBubbleUp){const i=r.ownerBlock;i!==e&&this._resetDualBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._resetDualBlocks(i.entryPoint,t)}else if(e.isLoop){const i=e;if(i.loopID.hasEndpoints)for(const e of i.loopID.endpoints){const i=e.ownerBlock;0===i.outputs.length&&this._resetDualBlocks(i,t)}}}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!1){if(this._buildIsInProgress)return void Z.V.Warn("Build is already in progress, You can use NodeMaterial.onBuildObservable to determine when the build is completed.");this._buildIsInProgress=!0,this._vertexCompilationState||i||(i=!0),this._buildWasSuccessful=!1;const r=this.getScene().getEngine(),s=this._mode===rv.Particle;if(0===this._vertexOutputNodes.length&&!s)throw"You must define at least one vertexOutputNode";if(0===this._fragmentOutputNodes.length)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new Vg,this._vertexCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._vertexCompilationState.target=Dg.Vertex,this._fragmentCompilationState=new Vg,this._fragmentCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._fragmentCompilationState.target=Dg.Fragment,this._sharedData=new kg,this._sharedData.nodeMaterial=this,this._sharedData.fragmentOutputNodes=this._fragmentOutputNodes,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene(),this._sharedData.allowEmptyVertexProgram=s;const n=[],o=[];for(const e of this._vertexOutputNodes)n.push(e),this._initializeBlock(e,this._vertexCompilationState,o,i);for(const e of this._fragmentOutputNodes)o.push(e),this._initializeBlock(e,this._fragmentCompilationState,n,i);let a=0;for(const i of this.attachedBlocks)i.codeIsReady||(a++,i.onCodeIsReadyObservable.addOnce((()=>{a--,0===a&&this._finishBuildProcess(e,t,n,o)})));0===a&&this._finishBuildProcess(e,t,n,o)}_finishBuildProcess(e=!1,t=!0,i,r){this.optimize();for(const e of i)e.build(this._vertexCompilationState,i);this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState;for(const e of r)this._resetDualBlocks(e,this._buildId-1);for(const e of r)e.build(this._fragmentCompilationState,r);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=pv._BuildIdGenerator++);const s=this._sharedData.emitErrors(this.onBuildErrorObservable);e&&(Z.V.Log("Vertex shader:"),Z.V.Log(this._vertexCompilationState.compilationString),Z.V.Log("Fragment shader:"),Z.V.Log(this._fragmentCompilationState.compilationString)),this._buildIsInProgress=!1,this._buildWasSuccessful=!0,s&&this.onBuildObservable.notifyObservers(this);const n=this.getScene().meshes;for(const e of n)if(e.subMeshes)for(const t of e.subMeshes){if(t.getMaterial()!==this)continue;if(!t.materialDefines)continue;const e=t.materialDefines;e.markAllAsDirty(),e.reset()}this.prePassTextureInputs.length&&this.getScene().enablePrePassRenderer();const o=this.getScene().prePassRenderer;o&&o.markAsDirty()}optimize(){for(const e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){const i=t.NORMAL,r=t.TANGENT,s=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(st.R.NormalKind),t.TANGENT=e.isVerticesDataPresent(st.R.TangentKind);const n=e.useVertexColors&&e.isVerticesDataPresent(st.R.ColorKind);t.VERTEXCOLOR_NME=n;let o=!1;for(let i=1;i<=6;++i){const r=t["UV"+i];t["UV"+i]=e.isVerticesDataPresent(`uv${1===i?"":i}`),o=o||t["UV"+i]!==r}const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;(0,Bt.N4)(this.getScene(),t,!a),(i!==t.NORMAL||r!==t.TANGENT||s!==t.VERTEXCOLOR_NME||o)&&t.markAsAttributesDirty()}get isPrePassCapable(){return!0}get prePassTextureOutputs(){const e=this.getBlockByPredicate((e=>"PrePassOutputBlock"===e.getClassName())),t=[4];return e?(this.prePassTextureInputs.length||(e.viewDepth.isConnected&&t.push(5),e.screenDepth.isConnected&&t.push(10),e.viewNormal.isConnected&&t.push(6),e.worldNormal.isConnected&&t.push(8),e.worldPosition.isConnected&&t.push(1)),t):t}get prePassTextureInputs(){const e=this.getAllTextureBlocks().filter((e=>"PrePassTextureBlock"===e.getClassName())),t=[];for(const i of e)i.position.isConnected&&!t.includes(1)&&t.push(1),i.localPosition.isConnected&&!t.includes(9)&&t.push(9),i.depth.isConnected&&!t.includes(5)&&t.push(5),i.screenDepth.isConnected&&!t.includes(10)&&t.push(10),i.normal.isConnected&&!t.includes(6)&&t.push(6),i.worldNormal.isConnected&&!t.includes(8)&&t.push(8);return t}setPrePassRenderer(e){const t=this.prePassTextureInputs.concat(this.prePassTextureOutputs);if(e&&t.length>1){let i=e.getEffectConfiguration("nodeMaterial");i||(i=e.addEffectConfiguration({enabled:!0,needsImageProcessing:!1,name:"nodeMaterial",texturesRequired:[]}));for(const e of t)i.texturesRequired.includes(e)||i.texturesRequired.push(e);i.enabled=!0}return t.length>1}createPostProcess(e,t=1,i=1,r,s,n=0,o=5){return this.mode!==rv.PostProcess?(Z.V.Log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,r,s,n,o)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,r=1,s,n,o=0,a=5){let l=this.name+this._buildId;const h=new fv,c=new Yt(l+"PostProcess",this.getScene());let u=this._buildId;return this._processDefines(c,h),Cl.M.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString,this.shaderLanguage),e?e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l):e=new ms.w(this.name+"PostProcess",l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,r,s,n,h.toString(),o,l,{maxSimultaneousLights:this.maxSimultaneousLights},!1,a,this.shaderLanguage),e.nodeMaterialSource=this,e.onApplyObservable.add((t=>{u!==this._buildId&&(delete Cl.M.ShadersStore[l+"VertexShader"],delete Cl.M.ShadersStore[l+"PixelShader"],l=this.name+this._buildId,h.markAllAsDirty(),u=this._buildId),this._processDefines(c,h)&&(Cl.M.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),lv._.SetImmediate((()=>e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l)))),this._checkInternals(t)})),e}createProceduralTexture(e,t){if(this.mode!==rv.ProceduralTexture)return Z.V.Log("Incompatible material mode"),null;let i=this.name+this._buildId;const r=new cv(i,e,null,t),s=new Yt(i+"Procedural",this.getScene());s.reservedDataStore={hidden:!0};const n=new fv,o=this._processDefines(s,n);Cl.M.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString,this.shaderLanguage);let a=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[st.R.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),o?.fallbacks,void 0,void 0,void 0,this.shaderLanguage);r.nodeMaterialSource=this,r._setEffect(a);let l=this._buildId;const h=()=>{l!==this._buildId&&(delete Cl.M.ShadersStore[i+"VertexShader"],delete Cl.M.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,n.markAllAsDirty(),l=this._buildId);const e=this._processDefines(s,n);e&&(Cl.M.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString,this.shaderLanguage),lv._.SetImmediate((()=>{a=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[st.R.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),e?.fallbacks,void 0),r._setEffect(a)}))),this._checkInternals(a)};return r.onBeforeGenerationObservable.add((()=>{h()})),this.onBuildObservable.add((()=>{h()})),r}_createEffectForParticles(e,t,i,r,s,n,o,a=""){let l=this.name+this._buildId+"_"+t;n||(n=new fv),o||(o=this.getScene().getMeshByName(this.name+"Particle"))||((o=new Yt(this.name+"Particle",this.getScene())).reservedDataStore={hidden:!0});let h=this._buildId;const c=[];let u=a;if(!s){const a=this._processDefines(o,n);Cl.M.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,void 0,this.shaderLanguage),e.fillDefines(c,t,!1),u=c.join("\n"),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+u,a?.fallbacks,i,r,e,this.shaderLanguage),e.setCustomEffect(s,t)}s.onBindObservable.add((s=>{h!==this._buildId&&(delete Cl.M.ShadersStore[l+"PixelShader"],l=this.name+this._buildId+"_"+t,n.markAllAsDirty(),h=this._buildId),c.length=0,e.fillDefines(c,t,!1);const d=c.join("\n");d!==u&&(n.markAllAsDirty(),u=d);const f=this._processDefines(o,n);if(f)return Cl.M.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,void 0,this.shaderLanguage),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+u,f?.fallbacks,i,r,e),e.setCustomEffect(s,t),void this._createEffectForParticles(e,t,i,r,s,n,o,a);this._checkInternals(s)}))}_checkInternals(e){if(this._sharedData.animatedInputs){const e=this.getScene(),t=e.getFrameId();if(this._animationFrame!==t){for(const t of this._sharedData.animatedInputs)t.animate(e);this._animationFrame=t}}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){this.mode===rv.Particle?(this._createEffectForParticles(e,nv.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,nv.BLENDMODE_MULTIPLY,t,i)):Z.V.Log("Incompatible material mode")}createAsShadowDepthWrapper(e){this.mode===rv.Material?e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene()):Z.V.Log("Incompatible material mode")}_processDefines(e,t,i=!1,r){let s=null;const n=this.getScene();if((0,Bt.Y7)(n,t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach((r=>{r.initializeDefines(e,this,t,i)})),this._sharedData.blocksWithDefines.forEach((s=>{s.prepareDefines(e,this,t,i,r)})),t.isDirty){const i=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach((i=>{i.replaceRepeatableContent(this._vertexCompilationState,this._fragmentCompilationState,e,t)}));const r=[];this._sharedData.dynamicUniformBlocks.forEach((e=>{e.updateUniformsAndSamples(this._vertexCompilationState,this,t,r)}));const n=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach((e=>{-1===n.indexOf(e)&&n.push(e)}));const o=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach((e=>{-1===o.indexOf(e)&&o.push(e)}));const a=new Tn;this._sharedData.blocksWithFallbacks.forEach((t=>{t.provideFallbacks(e,a)})),s={lightDisposed:i,uniformBuffers:r,mergedUniforms:n,mergedSamplers:o,fallbacks:a}}return s}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;const r=this.getScene();if(this._sharedData.animatedInputs){const e=r.getFrameId();if(this._animationFrame!==e){for(const e of this._sharedData.animatedInputs)e.animate(r);this._animationFrame=e}}const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new fv);const n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();if(this._prepareDefinesForAttributes(e,n),this._sharedData.blockingBlocks.some((t=>!t.isReady(e,this,n,i))))return!1;const a=this._processDefines(e,n,i,t);if(a){const e=t.effect,i=n.toString();let s=o.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:a.mergedUniforms,uniformBuffersNames:a.uniformBuffers,samplers:a.mergedSamplers,defines:i,fallbacks:a.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:n.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS},shaderLanguage:this.shaderLanguage},o);if(s)if(this._onEffectCreatedObservable&&(dv.effect=s,dv.subMesh=t,this._onEffectCreatedObservable.notifyObservers(dv)),this.allowShaderHotSwapping&&e&&!s.isReady()){if(s=e,n.markAsUnprocessed(),a.lightDisposed)return n._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(s,n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}get compiledShaders(){return this._buildWasSuccessful||this.build(),`// Vertex shader\n${this._vertexCompilationState.compilationString}\n\n// Fragment shader\n${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 t of this._sharedData.inputBlocks)t._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.effect;if(!s)return;this._activeEffect=s,this.bindOnlyWorldMatrix(e);const n=this._mustRebind(r,s,i,t.visibility),o=this._sharedData;if(n){for(const e of o.bindableBlocks)e.bind(s,this,t,i);for(const e of o.forcedBindableBlocks)e.bind(s,this,t,i);for(const e of o.inputBlocks)e._transmit(s,r,this)}else if(!this.isFrozen)for(const e of o.forcedBindableBlocks)e.bind(s,this,t,i);this._afterBind(t,this._activeEffect,i)}getActiveTextures(){const e=super.getActiveTextures();return this._sharedData&&e.push(...this._sharedData.textureBlocks.filter((e=>e.texture)).map((e=>e.texture))),e}getTextureBlocks(){return this._sharedData?this._sharedData.textureBlocks:[]}getAllTextureBlocks(){const e=[];for(const t of this.attachedBlocks)pv._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 e of this.getTextureBlocks().filter((e=>e.texture)).map((e=>e.texture)))e.dispose();for(const e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this.onBuildErrorObservable.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(),void 0===this.BJSNODEMATERIALEDITOR){const i=e&&e.editorURL?e.editorURL:pv.EditorURL;Ue.S0.LoadBabylonScript(i,(()=>{this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this._createNodeEditor(e?.nodeEditorConfig),t()}))}else this._createNodeEditor(e?.nodeEditorConfig),t()}))}clear(){this._vertexOutputNodes.length=0,this._fragmentOutputNodes.length=0,this.attachedBlocks.length=0,this._buildIsInProgress=!1}setToDefault(){this.clear(),this.editorData=null;const e=new Kg("Position");e.setAsAttribute("position");const t=new Kg("World");t.setAsSystemValue(Lg.World);const i=new zg("WorldPos");e.connectTo(i),t.connectTo(i);const r=new Kg("ViewProjection");r.setAsSystemValue(Lg.ViewProjection);const s=new zg("WorldPos * ViewProjectionTransform");i.connectTo(s),r.connectTo(s);const n=new Wg("VertexOutput");s.connectTo(n);const o=new Kg("color");o.value=new H.ov(.8,.8,.8,1);const a=new Hg("FragmentOutput");o.connectTo(a),this.addOutputNode(n),this.addOutputNode(a),this._mode=rv.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;const e=new Kg("Position");e.setAsAttribute("position2d");const t=new Kg("Constant1");t.isConstant=!0,t.value=1;const i=new Jg("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const r=new Wg("VertexOutput");i.connectTo(r);const s=new Kg("Scale");s.visibleInInspector=!0,s.value=new W.I9(1,1);const n=new ev("uv0");e.connectTo(n);const o=new iv("UV scale");n.connectTo(o),s.connectTo(o);const a=new jg("CurrentScreen");o.connectTo(a),a.texture=new vi.g("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());const l=new Hg("FragmentOutput");a.connectTo(l,{output:"rgba"}),this.addOutputNode(r),this.addOutputNode(l),this._mode=rv.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;const e=new Kg("Position");e.setAsAttribute("position2d");const t=new Kg("Constant1");t.isConstant=!0,t.value=1;const i=new Jg("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const r=new Wg("VertexOutput");i.connectTo(r);const s=new Kg("Time");s.value=0,s.min=0,s.max=0,s.isBoolean=!1,s.matrixMode=0,s.animationType=Bg.Time,s.isConstant=!1;const n=new Kg("Color3");n.value=new H.v9(1,1,1),n.isConstant=!1;const o=new Hg("FragmentOutput"),a=new Jg("VectorMerger");a.visibleInInspector=!1;const l=new uv("Cos");l.operation=av.Cos,e.connectTo(a),s.output.connectTo(l.input),l.output.connectTo(a.z),a.xyzOut.connectTo(o.rgb),this.addOutputNode(r),this.addOutputNode(o),this._mode=rv.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;const e=new Kg("uv");e.setAsAttribute("particle_uv");const t=new $g("ParticleTexture");e.connectTo(t);const i=new Kg("Color");i.setAsAttribute("particle_color");const r=new iv("Texture * Color");t.connectTo(r),i.connectTo(r);const s=new Qg("ParticleRampGradient");r.connectTo(s);const n=new ov("ColorSplitter");i.connectTo(n);const o=new Zg("ParticleBlendMultiply");s.connectTo(o),t.connectTo(o,{output:"a"}),n.connectTo(o,{output:"a"});const a=new Hg("FragmentOutput");o.connectTo(a),this.addOutputNode(a),this._mode=rv.Particle}async loadAsync(e,t=""){return pv.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const r=i.connectedPoint;if(r){const i=r.ownerBlock;i!==e&&this._gatherBlocks(i,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 e of this._vertexOutputNodes)this._gatherBlocks(e,t);const r=[];for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,r);let s=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}");\n`;s+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${rv[this.mode]};\n`;for(const r of t)r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e));for(const t of r)t.isInput&&-1===e.indexOf(t)&&(s+=t._dumpCode(i,e));e=[],s+="\n// Connections\n";for(const t of this._vertexOutputNodes)s+=t._dumpCodeForOutputConnections(e);for(const t of this._fragmentOutputNodes)s+=t._dumpCodeForOutputConnections(e);s+="\n// Output nodes\n";for(const e of this._vertexOutputNodes)s+=`nodeMaterial.addOutputNode(${e._codeVariableName});\n`;for(const e of this._fragmentOutputNodes)s+=`nodeMaterial.addOutputNode(${e._codeVariableName});\n`;return s+="nodeMaterial.build();\n",s}serialize(e){const t=e?{}:it.p.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 e of this._vertexOutputNodes)this._gatherBlocks(e,i),t.outputNodes.push(e.uniqueId);for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,i),-1===t.outputNodes.indexOf(e.uniqueId)&&t.outputNodes.push(e.uniqueId)}t.blocks=[];for(const e of i)t.blocks.push(e.serialize());if(!e)for(const e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t.uniqueId=this.uniqueId,t}_restoreConnections(e,t,i){for(const r of e.outputs)for(const s of t.blocks){const n=i[s.id];if(n)for(const o of s.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==r.name);else{const e=n.getInputByName(o.inputName);if(!e||e.isConnected)continue;r.connectTo(e,!0),this._restoreConnections(n,t,i)}}}parseSerializedObject(e,t="",i=!1,r){i||this.clear();const s={};for(const i of e.blocks){const e=(0,X.n9)(i.customType);if(e){const n=new e;n._deserialize(i,this.getScene(),t,r),s[i.id]=n,this.attachedBlocks.push(n)}}for(const e of this.attachedBlocks)if(e.isTeleportOut){const t=e,i=t._tempEntryPointUniqueId;i&&s[i].attachToEndpoint(t)}for(let t=0;tnew pv(e,this.getScene(),this.options)),this);return r.id=e,r.name=e,r.parseSerializedObject(i),r._buildId=this._buildId,r.build(!1,!t),r}whenTexturesReadyAsync(){const e=[];return this.getActiveTextures().forEach((t=>{const i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise(((e,t)=>{i.onLoadedObservable.addOnce((()=>{e()})),i.onErrorObservable.addOnce((e=>{t(e)}))})))})),Promise.all(e)}static Parse(e,t,i="",r=0){const s=it.p.Parse((()=>new pv(e.name,t,{shaderLanguage:r})),e,t,i);return s.parseSerializedObject(e,i),s.build(),s}static async ParseFromFileAsync(e,t,i,r="",s=!1,n,o){const a=n??new pv(e,i),l=await i._loadFileAsync(t),h=JSON.parse(l);return a.parseSerializedObject(h,r,void 0,o),s||a.build(),a}static ParseFromSnippetAsync(e,t=he.q.LastCreatedScene,i="",r,s=!1,n=!1,o){return"_BLANK"===e?Promise.resolve(pv.CreateDefault("blank",t)):new Promise(((a,l)=>{const h=new go.u;h.addEventListener("readystatechange",(()=>{if(4==h.readyState)if(200==h.status){const c=JSON.parse(JSON.parse(h.responseText).jsonPayload),u=JSON.parse(c.nodeMaterial);r||((r=it.p.Parse((()=>new pv(e,t)),u,t,i)).uniqueId=t.getUniqueId()),r.parseSerializedObject(u,void 0,void 0,o),r.snippetId=e,r.sideOrientation=null;try{s||r.build()}catch(e){l(e)}n?r.whenTexturesReadyAsync().then((()=>{a(r)})).catch((e=>{l(e)})):a(r)}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 pv(e,t);return i.setToDefault(),i.build(),i}}var _v,mv,gv,vv;pv._BuildIdGenerator=0,pv.EditorURL=`${Ue.S0._DefaultCdnUrl}/v${Ot.$.Version}/nodeEditor/babylon.nodeEditor.js`,pv.SnippetUrl="https://snippet.babylonjs.com",pv.IgnoreTexturesAtLoadTime=!1,pv.DefaultShaderLanguage=0,(0,je.Cg)([(0,$e.lK)()],pv.prototype,"ignoreAlpha",void 0),(0,je.Cg)([(0,$e.lK)()],pv.prototype,"maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.lK)("mode")],pv.prototype,"_mode",void 0),(0,je.Cg)([(0,$e.lK)("comment")],pv.prototype,"comment",void 0),(0,je.Cg)([(0,$e.lK)()],pv.prototype,"forceAlphaBlending",void 0),(0,X.Y5)("BABYLON.NodeMaterial",pv),vt.prototype._projectOnTrianglesToRef=function(e,t,i,r,s,n){const o=W.AA.Vector3[0],a=W.AA.Vector3[1];let l=1/0;for(let n=this.indexStart;n{if(this._controllers[e.uniqueId])return;const{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:r}=this._generateNewTouchPointMesh(),s=this._generateVisualCue();switch(this._controllers[e.uniqueId]={xrController:e,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:r,currentAnimationState:_v.DEHYDRATED,grabRay:new wi(new W.Pq,new W.Pq),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,downTriggered:!1,id:xv._IdCounter++,pickedPointVisualCue:s},this._controllers[e.uniqueId]._worldScaleObserver=this._controllers[e.uniqueId]._worldScaleObserver||this._xrSessionManager.onWorldScaleFactorChangedObservable.add((t=>{if(t.newScaleFactor!==t.previousScaleFactor){this._controllers[e.uniqueId].touchCollisionMesh.dispose(),this._controllers[e.uniqueId].pickedPointVisualCue.dispose();const{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:r}=this._generateNewTouchPointMesh();this._controllers[e.uniqueId].touchCollisionMesh=t,this._controllers[e.uniqueId].touchCollisionMeshFunction=i,this._controllers[e.uniqueId].hydrateCollisionMeshFunction=r,this._controllers[e.uniqueId].pickedPointVisualCue=this._generateVisualCue()}})),this._attachedController?!this._options.enableNearInteractionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enableNearInteractionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachNearInteractionMode(e);case"gaze":case"screen":return null}},this._controllers={},this._farInteractionFeature=null,this.selectionMeshDefaultColor=new H.v9(.8,.8,.8),this.selectionMeshPickedColor=new H.v9(.3,.3,1),this._hoverRadius=.1,this._pickRadius=.02,this._controllerPickRadius=.03,this._nearGrabLengthScale=5,this._scene=this._xrSessionManager.scene,void 0===this._options.nearInteractionControllerMode&&(this._options.nearInteractionControllerMode=2),this._options.farInteractionFeature&&(this._farInteractionFeature=this._options.farInteractionFeature)}attach(){return!!super.attach()&&(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._scene.constantlyUpdateMeshUnderPointer=!0,!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}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 _v.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===_v.HOVER)break;case _v.HOVER:if(e.touchCollisionMeshFunction(!0),t===_v.TOUCH)break}else switch(e.currentAnimationState){case _v.TOUCH:if(e.touchCollisionMeshFunction(!1),t===_v.HOVER)break;case _v.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===_v.DEHYDRATED)break}e.currentAnimationState=t}}_processTouchPoint(e,t,i){const r=this._controllers[e];r.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(W.AA.Vector3[0]),r.grabRay.direction.copyFrom(W.AA.Vector3[0]),2!==this._options.nearInteractionControllerMode||r.xrController?.inputSource.hand||(r.xrController.getWorldPointerRayToRef(this._tmpRay),r.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),r.grabRay.length=this._nearGrabLengthScale*this._hoverRadius*this._xrSessionManager.worldScalingFactor,r.touchCollisionMesh.position.copyFrom(r.grabRay.origin).scaleInPlace(this._xrSessionManager.worldScalingFactor)}_onXRFrame(e){Object.keys(this._controllers).forEach((t=>{const i=this._controllers[t],r=i.xrController?.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!i.xrController||!r&&(!this._options.nearInteractionControllerMode||!i.xrController.inputSource.gamepad))return void(i.pick=null);if(i.hoverInteraction=!1,i.nearInteraction=!1,!i.xrController)return;if(r){const i=r.get("index-finger-tip");if(i){const r=e.getJointPose(i,this._xrSessionManager.referenceSpace);if(r&&r.transform){const e=this._scene.useRightHandedSystem?1:-1;W.AA.Vector3[0].set(r.transform.position.x,r.transform.position.y,r.transform.position.z*e),W.AA.Quaternion[0].set(r.transform.orientation.x,r.transform.orientation.y,r.transform.orientation.z*e,r.transform.orientation.w*e),this._processTouchPoint(t,W.AA.Vector3[0],W.AA.Quaternion[0])}}}else if(i.xrController.inputSource.gamepad&&0!==this._options.nearInteractionControllerMode){let e=i.xrController.pointer;i.xrController.grip&&1===this._options.nearInteractionControllerMode&&(e=i.xrController.grip),this._processTouchPoint(t,e.position,e.rotationQuaternion)}const s=(e,t)=>{let i=null;return i=t&&t.hit?e&&e.hit?t.distance{let t=new At.G,i=!1;const r=e&&e.pickedPoint&&e.hit;return e?.pickedPoint&&(i=0===e.pickedPoint.x&&0===e.pickedPoint.y&&0===e.pickedPoint.z),r&&!i&&(t=e),t};if(!i.grabInteraction){let e=null,t=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._utilityLayerScene,(e=>this._nearInteractionPredicate(e))));const o=s(this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._scene,(e=>this._nearInteractionPredicate(e))),t);if(o&&o.hit&&(e=n(o),e.hit&&(i.hoverInteraction=!0)),i.hoverInteraction){let t=null;const o=(r?this._pickRadius:this._controllerPickRadius)*this._xrSessionManager.worldScalingFactor;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(i,o,this._utilityLayerScene,(e=>this._nearPickPredicate(e))));const a=n(s(this._pickWithSphere(i,o,this._scene,(e=>this._nearPickPredicate(e))),t));a.hit&&(e=a,i.nearInteraction=!0)}i.stalePick=i.pick,i.pick=e,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=_v.DEHYDRATED;i.grabInteraction||i.nearInteraction?o=_v.TOUCH:i.hoverInteraction&&(o=_v.HOVER),this._handleTransitionAnimation(i,o)}))}get _utilityLayerScene(){return this._options.customUtilityLayerScene||Bo.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Bo.DefaultUtilityLayer.utilityLayerScene:this._scene,t=Qo("nearInteraction",{diameter:.0105*this._xrSessionManager.worldScalingFactor},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=W.PT.Identity();const i=new Un("targetMat",e);return i.specularColor=H.v9.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return!this._farInteractionFeature||this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e)}_attachNearInteractionMode(e){const t=this._controllers[e.uniqueId],i={pointerId:t.id,pointerType:"xr-near"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{(this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController)&&t.xrController&&(t.xrController.inputSource.hand||this._options.nearInteractionControllerMode&&t.xrController.inputSource.gamepad)&&(t.pick&&(t.pick.ray=t.grabRay),t.pick&&this._isControllerReadyForNearInteraction(t.id)&&this._scene.simulatePointerMove(t.pick,i),t.nearInteraction&&t.pick&&t.pick.hit?t.nearInteractionTargetMesh||(this._scene.simulatePointerDown(t.pick,i),t.nearInteractionTargetMesh=t.meshUnderPointer,t.downTriggered=!0):t.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.downTriggered=!1,t.nearInteractionTargetMesh=null))}));const r=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 i=e=>{t.squeezeComponent=e.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;r(t)}})):(t.selectionComponent=e.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;r(t)}})))};e.motionController?i(e.motionController):e.onMotionControllerInitObservable.add(i)}else{const e=e=>{t.xrController&&e.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)},r=e=>{t.xrController&&e.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:r,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",r)}}_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((e=>{const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame((()=>{if(!t.downTriggered)return;const e={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new At.G,e)})),t._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(t._worldScaleObserver),delete this._controllers[e],this._attachedController===e)){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}_generateNewTouchPointMesh(){const e=this._xrSessionManager.worldScalingFactor,t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Bo.DefaultUtilityLayer.utilityLayerScene:this._scene,i=Qo("PickSphere",{diameter:1*e},t);if(i.isVisible=!1,this._options.motionControllerOrbMaterial)i.material=this._options.motionControllerOrbMaterial;else{let e;e=this._options.motionControllerTouchMaterialSnippetUrl?pv.ParseFromFileAsync("motionControllerTouchMaterial",this._options.motionControllerTouchMaterialSnippetUrl,t):pv.ParseFromSnippetAsync("8RUNKL#3",t),e.then((e=>{i.material=e})).catch((e=>{Z.V.Warn(`Error creating touch material in WebXRNearInteraction: ${e}`)}))}const r=new Ae;r.setEasingMode(xe.EASINGMODE_EASEINOUT);const s=new W.Pq(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius).scaleInPlace(e),n=this._controllerPickRadius*(4/3),o=new W.Pq(n,n,n).scaleInPlace(e),a=this._controllerPickRadius*(7/6),l=new W.Pq(a,a,a).scaleInPlace(e),h=.8*this._controllerPickRadius,c=new W.Pq(h,h,h).scaleInPlace(e),u=1.5*this._controllerPickRadius,d=[{frame:0,value:s},{frame:10,value:new W.Pq(u,u,u).scaleInPlace(e)},{frame:18,value:o}],f=[{frame:0,value:o},{frame:10,value:c},{frame:18,value:s}],p=[{frame:0,value:W.Pq.ZeroReadOnly},{frame:12,value:l},{frame:15,value:s}],_=[{frame:0,value:s},{frame:10,value:W.Pq.ZeroReadOnly},{frame:15,value:W.Pq.ZeroReadOnly}],m=new pe.X5("touch","scaling",60,pe.X5.ANIMATIONTYPE_VECTOR3,pe.X5.ANIMATIONLOOPMODE_CONSTANT),g=new pe.X5("release","scaling",60,pe.X5.ANIMATIONTYPE_VECTOR3,pe.X5.ANIMATIONLOOPMODE_CONSTANT),v=new pe.X5("hydrate","scaling",60,pe.X5.ANIMATIONTYPE_VECTOR3,pe.X5.ANIMATIONLOOPMODE_CONSTANT),x=new pe.X5("dehydrate","scaling",60,pe.X5.ANIMATIONTYPE_VECTOR3,pe.X5.ANIMATIONLOOPMODE_CONSTANT);return m.setEasingFunction(r),g.setEasingFunction(r),v.setEasingFunction(r),x.setEasingFunction(r),m.setKeys(d),g.setKeys(f),v.setKeys(p),x.setKeys(_),{touchCollisionMesh:i,touchCollisionMeshFunction:e=>{const r=e?m:g;t.beginDirectAnimation(i,[r],0,18,!1,1)},hydrateCollisionMeshFunction:e=>{const r=e?v:x;e&&(i.isVisible=!0),t.beginDirectAnimation(i,[r],0,15,!1,1,(()=>{e||(i.isVisible=!1)}))}}}_pickWithSphere(e,t,i,r){const s=new At.G;if(s.distance=1/0,e.touchCollisionMesh&&e.xrController){const n=e.touchCollisionMesh.position,o=ct.CreateFromCenterAndRadius(n,t);for(let t=0;tc&&(h=0,a.copyFrom(t.center)),-1!==h&&h()=>new xv(e,t)),xv.Version,!0);class bv{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class Sv{}class Tv{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new z.cP,this._onSessionGranted=e=>{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),"undefined"!=typeof window&&window.location&&"http:"===window.location.protocol&&"localhost"!==window.location.hostname)throw Ue.S0.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 e=t.sessionMode||"immersive-vr",i=t.referenceSpaceType||"local-floor";let r=".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("+("undefined"==typeof SVGSVGElement?"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) }";r+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';const s=document.createElement("style");s.appendChild(document.createTextNode(r)),document.getElementsByTagName("head")[0].appendChild(s);const n=document.createElement("button");n.className="babylonVRicon",n.title=`${e} - ${i}`,this._buttons.push(new bv(n,e,i)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",n.className="babylonVRicon"+(e===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((t=>e.sessionManager.isSessionSupportedAsync(t.sessionMode)));e.onStateChangedObservable.add((e=>{3==e&&this._updateButtons(null)})),(await Promise.all(i)).forEach(((e,t)=>{e?(this.overlay.appendChild(this._buttons[t].element),this._buttons[t].element.onclick=this._enterXRWithButtonIndex.bind(this,t)):Ue.S0.Warn(`Session mode "${this._buttons[t].sessionMode}" not supported in browser`)}))}static async CreateAsync(e,t,i){const r=new Tv(e,i);return await r.setHelperAsync(t,i.renderTarget||void 0),r}async _enterXRWithButtonIndex(e=0){if(2==this._helper.state)await this._helper.exitXRAsync(),this._updateButtons(null);else if(3==this._helper.state)try{await this._helper.enterXRAsync(this._buttons[e].sessionMode,this._buttons[e].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures}),this._updateButtons(this._buttons[e])}catch(t){this._updateButtons(null);const i=this._buttons[e].element,r=i.title;i.title="Error entering XR session : "+r,i.classList.add("xr-error"),this.options.onError&&this.options.onError(t)}}dispose(){const e=this._scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this.overlay)&&e.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)}_updateButtons(e){this._activeButton=e,this._buttons.forEach((e=>{e.update(this._activeButton)})),this.activeButtonChangedObservable.notifyObservers(this._activeButton)}}!function(e){e.WRIST="wrist",e.THUMB="thumb",e.INDEX="index",e.MIDDLE="middle",e.RING="ring",e.LITTLE="little"}(gv||(gv={})),function(e){e.WRIST="wrist",e.THUMB_METACARPAL="thumb-metacarpal",e.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",e.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",e.THUMB_TIP="thumb-tip",e.INDEX_FINGER_METACARPAL="index-finger-metacarpal",e.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",e.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",e.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",e.INDEX_FINGER_TIP="index-finger-tip",e.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",e.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",e.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",e.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",e.MIDDLE_FINGER_TIP="middle-finger-tip",e.RING_FINGER_METACARPAL="ring-finger-metacarpal",e.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",e.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",e.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",e.RING_FINGER_TIP="ring-finger-tip",e.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",e.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",e.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",e.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",e.PINKY_FINGER_TIP="pinky-finger-tip"}(vv||(vv={}));const Cv=["wrist","thumb-metacarpal","thumb-phalanx-proximal","thumb-phalanx-distal","thumb-tip","index-finger-metacarpal","index-finger-phalanx-proximal","index-finger-phalanx-intermediate","index-finger-phalanx-distal","index-finger-tip","middle-finger-metacarpal","middle-finger-phalanx-proximal","middle-finger-phalanx-intermediate","middle-finger-phalanx-distal","middle-finger-tip","ring-finger-metacarpal","ring-finger-phalanx-proximal","ring-finger-phalanx-intermediate","ring-finger-phalanx-distal","ring-finger-tip","pinky-finger-metacarpal","pinky-finger-phalanx-proximal","pinky-finger-phalanx-intermediate","pinky-finger-phalanx-distal","pinky-finger-tip"],yv={wrist:["wrist"],thumb:["thumb-metacarpal","thumb-phalanx-proximal","thumb-phalanx-distal","thumb-tip"],index:["index-finger-metacarpal","index-finger-phalanx-proximal","index-finger-phalanx-intermediate","index-finger-phalanx-distal","index-finger-tip"],middle:["middle-finger-metacarpal","middle-finger-phalanx-proximal","middle-finger-phalanx-intermediate","middle-finger-phalanx-distal","middle-finger-tip"],ring:["ring-finger-metacarpal","ring-finger-phalanx-proximal","ring-finger-phalanx-intermediate","ring-finger-phalanx-distal","ring-finger-tip"],little:["pinky-finger-metacarpal","pinky-finger-phalanx-proximal","pinky-finger-phalanx-intermediate","pinky-finger-phalanx-distal","pinky-finger-tip"]};class Ev{get handMesh(){return this._handMesh}getHandPartMeshes(e){return yv[e].map((e=>this._jointMeshes[Cv.indexOf(e)]))}getJointMesh(e){return this._jointMeshes[Cv.indexOf(e)]}constructor(e,t,i,r,s=!1,n=!1,o=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=r,this._leftHandedMeshes=s,this._jointsInvisible=n,this._jointScaleFactor=o,this.onHandMeshSetObservable=new z.cP,this._jointTransforms=new Array(Cv.length),this._jointTransformMatrices=new Float32Array(16*Cv.length),this._tempJointMatrix=new W.uq,this._jointRadii=new Float32Array(Cv.length),this._scene=t[0].getScene();for(let e=0;e{e._doNotLoadControllerMesh=!0}))}setHandMesh(e,t,i){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach((e=>{e.alwaysSelectAsActiveMesh=!0})),this._handMesh.skeleton){const e=this._handMesh.skeleton;Cv.forEach(((i,r)=>{const s=e.getBoneIndexByName(t?t[i]:i);-1!==s&&e.bones[s].linkTransformNode(this._jointTransforms[r])}))}this.onHandMeshSetObservable.notifyObservers(this)}updateFromXRFrame(e,t){const i=this.xrController.inputSource.hand;if(!i)return;const r=i,s=Cv.map((e=>r[e]||i.get(e)));let n=!1;if(e.fillPoses&&e.fillJointRadii)n=e.fillPoses(s,t,this._jointTransformMatrices)&&e.fillJointRadii(s,this._jointRadii);else if(e.getJointPose){n=!0;for(let i=0;i{const i=this._jointTransforms[t];W.uq.FromArrayToRef(this._jointTransformMatrices,16*t,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,i.rotationQuaternion,i.position);const r=this._jointRadii[t]*this._jointScaleFactor,s=this._jointMeshes[t];s.isVisible=!this._handMesh&&!this._jointsInvisible,s.position.copyFrom(i.position),s.rotationQuaternion.copyFrom(i.rotationQuaternion),s.scaling.setAll(r),this._scene.useRightHandedSystem||(s.position.z*=-1,s.rotationQuaternion.z*=-1,s.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(i.position.z*=-1,i.rotationQuaternion.z*=-1,i.rotationQuaternion.w*=-1))})),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(e=!1){this._handMesh&&(e?(this._handMesh.skeleton?.dispose(),this._handMesh.dispose(!1,!0)):this._handMesh.isVisible=!1),this._jointTransforms.forEach((e=>e.dispose())),this._jointTransforms.length=0,this.onHandMeshSetObservable.clear()}}class Pv extends Ig{static _GenerateTrackedJointMeshes(e,t=Qa("jointParent",Pv._ICOSPHERE_PARAMS)){const i={};return["left","right"].map((r=>{const s=[];t.isVisible=!!e.jointMeshes?.keepOriginalVisible;for(let i=0;i{const s={};Pv._RightHandGLB?.meshes[1]?.isDisposed()&&(Pv._RightHandGLB=null),Pv._LeftHandGLB?.meshes[1]?.isDisposed()&&(Pv._LeftHandGLB=null);const n=!(!Pv._RightHandGLB||!Pv._LeftHandGLB),o=await Promise.all([Pv._RightHandGLB||xg.ImportMeshAsync("",Pv.DEFAULT_HAND_MODEL_BASE_URL,Pv.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),Pv._LeftHandGLB||xg.ImportMeshAsync("",Pv.DEFAULT_HAND_MODEL_BASE_URL,Pv.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);Pv._RightHandGLB=o[0],Pv._LeftHandGLB=o[1];const a=await pv.ParseFromFileAsync("handShader",Pv.DEFAULT_HAND_MODEL_SHADER_URL,e,void 0,!0);a.needDepthPrePass=!0,a.transparencyMode=Vt.MATERIAL_ALPHABLEND,a.alphaMode=2,a.build(!1);const l={base:H.v9.FromInts(116,63,203),fresnel:H.v9.FromInts(149,102,229),fingerColor:H.v9.FromInts(177,130,255),tipFresnel:H.v9.FromInts(220,200,255),...i?.handMeshes?.customColors},h={base:a.getBlockByName("baseColor"),fresnel:a.getBlockByName("fresnelColor"),fingerColor:a.getBlockByName("fingerColor"),tipFresnel:a.getBlockByName("tipFresnelColor")};h.base.value=l.base,h.fresnel.value=l.fresnel,h.fingerColor.value=l.fingerColor,h.tipFresnel.value=l.tipFresnel;const c=t._getBaseLayerWrapper()?.isMultiview;["left","right"].forEach((t=>{const r="left"==t?Pv._LeftHandGLB:Pv._RightHandGLB;if(!r)throw new Error("Could not load hand model");const o=r.meshes[1];o._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,c||i?.handMeshes?.disableHandShader||(o.material=a.clone(`${t}HandShaderClone`,!0)),o.isVisible=!1,s[t]=o,n||e.useRightHandedSystem||r.meshes[1].rotate(Mt._0.Y,Math.PI)})),a.dispose(),r({left:s.left,right:s.right})}))}static _GenerateDefaultHandMeshRigMapping(e){const t="right"==e?"R":"L";return{wrist:`wrist_${t}`,"thumb-metacarpal":`thumb_metacarpal_${t}`,"thumb-phalanx-proximal":`thumb_proxPhalanx_${t}`,"thumb-phalanx-distal":`thumb_distPhalanx_${t}`,"thumb-tip":`thumb_tip_${t}`,"index-finger-metacarpal":`index_metacarpal_${t}`,"index-finger-phalanx-proximal":`index_proxPhalanx_${t}`,"index-finger-phalanx-intermediate":`index_intPhalanx_${t}`,"index-finger-phalanx-distal":`index_distPhalanx_${t}`,"index-finger-tip":`index_tip_${t}`,"middle-finger-metacarpal":`middle_metacarpal_${t}`,"middle-finger-phalanx-proximal":`middle_proxPhalanx_${t}`,"middle-finger-phalanx-intermediate":`middle_intPhalanx_${t}`,"middle-finger-phalanx-distal":`middle_distPhalanx_${t}`,"middle-finger-tip":`middle_tip_${t}`,"ring-finger-metacarpal":`ring_metacarpal_${t}`,"ring-finger-phalanx-proximal":`ring_proxPhalanx_${t}`,"ring-finger-phalanx-intermediate":`ring_intPhalanx_${t}`,"ring-finger-phalanx-distal":`ring_distPhalanx_${t}`,"ring-finger-tip":`ring_tip_${t}`,"pinky-finger-metacarpal":`little_metacarpal_${t}`,"pinky-finger-phalanx-proximal":`little_proxPhalanx_${t}`,"pinky-finger-phalanx-intermediate":`little_intPhalanx_${t}`,"pinky-finger-phalanx-distal":`little_distPhalanx_${t}`,"pinky-finger-tip":`little_tip_${t}`}}isCompatible(){return"undefined"!=typeof XRHand}getHandByControllerId(e){return this._attachedHands[e]}getHandByHandedness(e){return"none"==e?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 z.cP,this.onHandRemovedObservable=new z.cP,this._attachHand=e=>{if(!e.inputSource.hand||"none"==e.inputSource.handedness||!this._handResources.jointMeshes)return;const t=e.inputSource.handedness,i=new Ev(e,this._handResources.jointMeshes[t],this._handResources.handMeshes&&this._handResources.handMeshes[t],this._handResources.rigMappings&&this._handResources.rigMappings[t],this.options.handMeshes?.meshesUseLeftHandedCoordinates,this.options.jointMeshes?.invisible,this.options.jointMeshes?.scaleFactor);this._attachedHands[e.uniqueId]=i,this._trackingHands[t]=i,this.onHandAddedObservable.notifyObservers(i)},this._detachHand=e=>{this._detachHandById(e.uniqueId)},this.xrNativeFeatureName="hand-tracking";const i=t.jointMeshes;if(i&&(void 0!==i.disableDefaultHandMesh&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=i.disableDefaultHandMesh),void 0!==i.handMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=i.handMeshes),void 0!==i.leftHandedSystemMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=i.leftHandedSystemMeshes),void 0!==i.rigMapping)){t.handMeshes=t.handMeshes||{};const e={},r={};[[i.rigMapping.left,e],[i.rigMapping.right,r]].forEach((e=>{const t=e[0],i=e[1];t.forEach(((e,t)=>{i[Cv[t]]=e}))})),t.handMeshes.customRigMappings={left:e,right:r}}}attach(){return!!super.attach()&&(this._handResources.jointMeshes||(this._originalMesh=this._originalMesh||this.options.jointMeshes?.sourceMesh||Qa("jointParent",Pv._ICOSPHERE_PARAMS),this._originalMesh.isVisible=!1,this._handResources.jointMeshes=Pv._GenerateTrackedJointMeshes(this.options,this._originalMesh)),this._handResources.handMeshes=this.options.handMeshes?.customMeshes||null,this._handResources.rigMappings=this.options.handMeshes?.customRigMappings||null,this.options.handMeshes?.customMeshes||this.options.handMeshes?.disableDefaultMeshes||(Pv._GenerateDefaultHandMeshesAsync(he.q.LastCreatedScene,this._xrSessionManager,this.options).then((e=>{this._handResources.handMeshes=e,this._handResources.rigMappings={left:Pv._GenerateDefaultHandMeshRigMapping("left"),right:Pv._GenerateDefaultHandMeshRigMapping("right")},this._trackingHands.left?.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left,this._xrSessionManager),this._trackingHands.right?.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((e=>{this._handResources.handMeshes&&(this._handResources.handMeshes.left.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor),this._handResources.handMeshes.right.scaling.scaleInPlace(e.newScaleFactor/e.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)}_onXRFrame(e){this._trackingHands.left?.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),this._trackingHands.right?.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e,t){const i=this.getHandByControllerId(e);if(i){const r="left"==i.xrController.inputSource.handedness?"left":"right";this._trackingHands[r]?.xrController.uniqueId===e&&(this._trackingHands[r]=null),this.onHandRemovedObservable.notifyObservers(i),i.dispose(t),delete this._attachedHands[e]}}detach(){return!!super.detach()&&(Object.keys(this._attachedHands).forEach((e=>this._detachHandById(e,this.options.handMeshes?.disposeOnSessionEnd))),this.options.handMeshes?.disposeOnSessionEnd&&(this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((e=>e.dispose())),this._handResources.jointMeshes.right.forEach((e=>e.dispose())),this._handResources.jointMeshes=null),this._handResources.handMeshes&&(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),this._handResources.handMeshes=null),Pv._RightHandGLB?.meshes.forEach((e=>e.dispose())),Pv._LeftHandGLB?.meshes.forEach((e=>e.dispose())),Pv._RightHandGLB=null,Pv._LeftHandGLB=null,this._originalMesh?.dispose(),this._originalMesh=void 0),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver),!0)}dispose(){super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),this._handResources.handMeshes&&!this.options.handMeshes?.customMeshes&&(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),Pv._RightHandGLB?.meshes.forEach((e=>e.dispose())),Pv._LeftHandGLB?.meshes.forEach((e=>e.dispose())),Pv._RightHandGLB=null,Pv._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((e=>e.dispose())),this._handResources.jointMeshes.right.forEach((e=>e.dispose())))}}Pv.Name=hr.HAND_TRACKING,Pv.Version=1,Pv.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/",Pv.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb",Pv.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb",Pv.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json",Pv._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2},Pv._RightHandGLB=null,Pv._LeftHandGLB=null,cr.AddWebXRFeature(Pv.Name,((e,t)=>()=>new Pv(e,t)),Pv.Version,!1);class Av extends Ig{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){const t=this._options.teleportationTargetMesh.getChildMeshes(!1,(e=>"rotationCone"===e.name));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 H.ov(1,1,1,1),this._tmpRay=new wi(new W.Pq,new W.Pq),this._tmpVector=new W.Pq,this._tmpQuaternion=new W.PT,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 z.cP,this.teleportationEnabled=!0,this._rotationEnabled=!0,this.onBeforeCameraTeleportRotation=new z.cP,this.onAfterCameraTeleportRotation=new z.cP,this._attachController=e=>{if(this._controllers[e.uniqueId]||this._options.forceHandedness&&e.inputSource.handedness!==this._options.forceHandedness)return;this._controllers[e.uniqueId]={xrController:e,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0,blocked:!1,initialHit:!1,mainComponentUsed:!1}};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController){const i=e.motionController.getComponentOfType(Km.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(Km.TOUCHPAD_TYPE);if(!i||this._options.useMainComponentOnly){const i=e.motionController.getMainComponent();if(!i)return;t.teleportationState.mainComponentUsed=!0,t.teleportationComponent=i,t.onButtonChangedObserver=i.onButtonStateChangedObservable.add((()=>{if(!this.teleportationEnabled)return;const r=()=>{t.teleportationState.forward=!0,t.teleportationState.initialHit=!1,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,xd({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!i.pressed,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})};i.changes.pressed&&(i.changes.pressed.current?this._options.timeToTeleportStart?xd({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{i.pressed&&r()}}):r():(t.teleportationState.forward=!1,this._currentTeleportationControllerId=""))}))}else t.teleportationComponent=i,t.onAxisChangedObserver=i.onAxisValueChangedObservable.add((i=>{if(i.y<=.7&&t.teleportationState.backwards&&(t.teleportationState.backwards=!1),i.y>.7&&!t.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!t.teleportationState.backwards){t.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,W.PT.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 e=this._xrSessionManager.scene.pickWithRay(this._tmpRay,(e=>-1!==this._floorMeshes.indexOf(e)));e&&e.pickedPoint&&(this._options.xrInput.xrCamera.position.x=e.pickedPoint.x,this._options.xrInput.xrCamera.position.z=e.pickedPoint.z)}if(i.y<-.7&&!this._currentTeleportationControllerId&&!t.teleportationState.rotating&&this.teleportationEnabled&&(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),i.x){if(t.teleportationState.forward)this._currentTeleportationControllerId===t.xrController.uniqueId&&(this.rotationEnabled?setTimeout((()=>{t.teleportationState.currentRotation=Math.atan2(i.x,i.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))})):t.teleportationState.currentRotation=0);else if(!t.teleportationState.rotating&&Math.abs(i.x)>.7){t.teleportationState.rotating=!0;const e=this.rotationAngle*(i.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this.onBeforeCameraTeleportRotation.notifyObservers(e),W.PT.FromEulerAngles(0,e,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleportRotation.notifyObservers(this._options.xrInput.xrCamera.rotationQuaternion)}}else t.teleportationState.rotating=!1;0===i.x&&0===i.y&&(t.teleportationState.blocked&&(t.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),t.teleportationState.forward&&this._teleportForward(e.uniqueId))}))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}else{t.teleportationState.mainComponentUsed=!0;let i=!1;const r=()=>{this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.forward=!0,t.teleportationState.initialHit=!1,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,xd({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})};this._xrSessionManager.scene.onPointerObservable.add((e=>{e.type===yi.Zp.POINTERDOWN?(i=!1,this._options.timeToTeleportStart?xd({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&r()},breakCondition:()=>!!i&&(i=!1,!0)}):r()):e.type===yi.Zp.POINTERUP&&(i=!0,t.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 H.ov(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((e=>{this.parabolicCheckRadius=this.parabolicCheckRadius/e.previousScaleFactor*e.newScaleFactor,this._options.teleportationTargetMesh?.scaling.scaleInPlace(e.newScaleFactor/e.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)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0)}dispose(){super.dispose(),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver),this.onTargetMeshPositionUpdatedObservable.clear(),this.onTargetMeshPositionUpdatedObservable.clear(),this.onBeforeCameraTeleportRotation.clear(),this.onAfterCameraTeleportRotation.clear(),this.onBeforeCameraTeleport.clear(),this.onAfterCameraTeleport.clear()}removeFloorMesh(e){const t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];const t=this._options.pickBlockerMeshes.indexOf(e);-1!==t&&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(-1===t)for(let i=0;i{if(this._options.blockerMeshesPredicate&&this._options.blockerMeshesPredicate(e))return!0;if(this._options.blockAllPickableMeshes&&e.isPickable)return!0;if(this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e))return!0;const t=this._floorMeshes.indexOf(e);return-1!==t&&this._floorMeshes[t].absolutePosition.y!(!this._options.blockerMeshesPredicate||!this._options.blockerMeshesPredicate(e))||!(!this._options.blockAllPickableMeshes||!e.isPickable)||!(!this._options.pickBlockerMeshes||-1===this._options.pickBlockerMeshes.indexOf(e))||-1!==this._floorMeshes.indexOf(e))),l=a&&a.pickedMesh&&-1!==this._floorMeshes.indexOf(a.pickedMesh);if(a&&a.pickedMesh&&!l)return e.teleportationState.mainComponentUsed&&!e.teleportationState.initialHit?void(e.teleportationState.forward=!1):(e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1,!1,s),void this._showParabolicPath(a));a&&a.pickedPoint&&(e.teleportationState.initialHit=!0,e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(a),this._setTargetMeshVisibility(!0,!1,s),this._showParabolicPath(a))}this._setTargetMeshVisibility(t,!1,s)}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||Bo.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=io("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{const i=512,r=new Gn("teleportationPlaneDynamicTexture",i,e,!0);r.hasAlpha=!0;const s=r.getContext(),n=i/2,o=i/2,a=200;s.beginPath(),s.arc(n,o,a,0,2*Math.PI,!1),s.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",s.fill(),s.lineWidth=10,s.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",s.stroke(),s.closePath(),r.update();const l=new Un("teleportationPlaneMaterial",e);l.diffuseTexture=r,t.material=l}const i=ao("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){const t=new pe.X5("animationInnerCircle","position.y",30,pe.X5.ANIMATIONTYPE_FLOAT,pe.X5.ANIMATIONLOOPMODE_CYCLE),r=[];r.push({frame:0,value:0}),r.push({frame:30,value:.4}),r.push({frame:60,value:0}),t.setKeys(r);const s=new Me;s.setEasingMode(xe.EASINGMODE_EASEINOUT),t.setEasingFunction(s),i.animations=[],i.animations.push(t),e.beginAnimation(i,0,60,!0)}const r=No("rotationCone",{diameterTop:0,tessellation:4},e);if(r.isPickable=!1,r.scaling.set(.5,.12,.2),r.rotate(Mt._0.X,Math.PI/2),r.position.z=.6,r.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,r.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{const t=new Un("torusConsMat",e);t.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,t.disableLighting?t.emissiveColor=new H.v9(.3,.3,1):t.diffuseColor=new H.v9(.3,.3,1),t.alpha=.9,i.material=t,r.material=t,this._teleportationRingMaterial=t}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._options.teleportationTargetMesh.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._setTargetMeshVisibility(!1)}_detachController(e){const t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,r=Number.MAX_VALUE;if(this._snapToPositions.length){const s=t*t;this._snapToPositions.forEach((t=>{const n=W.Pq.DistanceSquared(t,e);n<=s&&n{t.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||Bo.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],r=ve.jj.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),s=i.teleportationState.blocked?this._blockedRayColor:void 0,n=this._colorArray.fill(s||this._cachedColor4White),o=r.getPoints();o.shift(),o.shift(),this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(r.getPoints(),e):this._quadraticBezierCurve=Ra("teleportation path line",{points:o,instance:this._quadraticBezierCurve,updatable:!0,colors:n},t),this._quadraticBezierCurve.isPickable=!1,void 0!==this._options.renderingGroupId&&(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;else if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){const e=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+=e,W.PT.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)}}}Av.Name=hr.TELEPORTATION,Av.Version=1,cr.AddWebXRFeature(Av.Name,((e,t)=>()=>new Av(e,t)),Av.Version,!0);class Rv{}class Iv{constructor(){}static CreateAsync(e,t={}){const i=new Iv;if(e.onDisposeObservable.addOnce((()=>{i.dispose()})),!t.disableDefaultUI){const r={renderTarget:i.renderTarget,...t.uiOptions||{}};t.optionalFeatures&&("boolean"==typeof t.optionalFeatures?r.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:r.optionalFeatures=t.optionalFeatures),i.enterExitUI=new Tv(e,r)}return Ym.CreateAsync(e).then((e=>{if(i.baseExperience=e,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new Rg(e.sessionManager,e.camera,{controllerOptions:{renderingGroupId:t.renderingGroupId},...t.inputOptions||{}}),!t.disablePointerSelection){const e={...t.pointerSelectionOptions,xrInput:i.input,renderingGroupId:t.renderingGroupId};i.pointerSelection=i.baseExperience.featuresManager.enableFeature(Mg.Name,t.useStablePlugins?"stable":"latest",e),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(Av.Name,t.useStablePlugins?"stable":"latest",{floorMeshes:t.floorMeshes,xrInput:i.input,renderingGroupId:t.renderingGroupId,...t.teleportationOptions}),i.teleportation.setSelectionFeature(i.pointerSelection))}return t.disableNearInteraction||(i.nearInteraction=i.baseExperience.featuresManager.enableFeature(xv.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(Pv.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,...t.handSupportOptions},void 0,!1),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),t.disableDefaultUI?void 0:i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)})).then((()=>i)).catch((e=>(Z.V.Error("Error initializing XR"),Z.V.Error(e),i)))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}var Mv=!0;function Ov(e){for(;e.firstChild;)e.removeChild(e.firstChild);e.srcObject=null,e.src="",e.removeAttribute("src")}oi.Z.prototype.createDefaultLight=function(e=!1){if(e&&this.lights)for(let e=0;ee.isVisible&&e.isEnabled())),r=t.max.subtract(t.min),s=t.min.add(r.scale(.5));let n,o=1.5*r.length();if(isFinite(o)||(o=1,s.copyFromFloats(0,0,0)),e){const e=new is("default camera",-Math.PI/2,Math.PI/2,o,s,this);e.lowerRadiusLimit=.01*o,e.wheelPrecision=100/o,n=e}else{const e=new es("default camera",new W.Pq(s.x,s.y,-o),this);e.setTarget(s),n=e}n.minZ=.01*o,n.maxZ=1e3*o,n.speed=.2*o,this.activeCamera=n,i&&n.attachControl()}},oi.Z.prototype.createDefaultCameraOrLight=function(e=!1,t=!1,i=!1){this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},oi.Z.prototype.createDefaultSkybox=function(e,t=!1,i=1e3,r=0,s=!0){if(!e)return Z.V.Warn("Can not create default skybox without environment texture."),null;s&&e&&(this.environmentTexture=e);const n=Ko("hdrSkyBox",{size:i},this);if(t){const t=new zm("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=vi.g.SKYBOX_MODE),t.microSurface=1-r,t.disableLighting=!0,t.twoSidedLighting=!0,n.material=t}else{const t=new Un("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=vi.g.SKYBOX_MODE),t.disableLighting=!0,n.material=t}return n.isPickable=!1,n.infiniteDistance=!0,n.ignoreCameraMaxZ=!0,n},oi.Z.prototype.createDefaultEnvironment=function(e){return bm?new bm(e,this):null},oi.Z.prototype.createDefaultVRExperience=function(e={}){return new fo(this,e)},oi.Z.prototype.createDefaultXRExperienceAsync=function(e={}){return Iv.CreateAsync(this,e).then((e=>e))};class Dv extends vi.g{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new z.cP),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(e?.message):Z.V.Error(e?.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch((e=>{if("NotAllowedError"===e?.name){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers())return void this._onUserActionRequestedObservable.notifyObservers(this);if(!this.video.muted)return Z.V.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,void this.video.play().catch((e=>{this._processError(e)}))}this._processError(e)}))}constructor(e,t,i,r=!1,s=!1,n=vi.g.TRILINEAR_SAMPLINGMODE,o={},a,l=5){super(null,i,!r,s),this._externalTexture=null,this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this.isVideo=!0,this._resizeInternalTexture=()=>{null!=this._texture&&this._texture.dispose(),!this._getEngine().needPOTTextures||Ue.S0.IsExponentOfTwo(this.video.videoWidth)&&Ue.S0.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=vi.g.WRAP_ADDRESSMODE,this.wrapV=vi.g.WRAP_ADDRESSMODE):(this.wrapU=vi.g.CLAMP_ADDRESSMODE,this.wrapV=vi.g.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(null!=this._texture){if(!this._displayingPosterTexture)return;this._displayingPosterTexture=!1}if(this.video.addEventListener("resize",this._resizeInternalTexture),this._resizeInternalTexture(),this.video.autoplay||this._settings.poster||this._settings.independentVideoSource)this._updateInternalTexture(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this);else{const e=this.video.onplaying,t=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=t,this.video.onplaying=e,this._updateInternalTexture(),this._errorFound||this.video.pause(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._handlePlay()}},this._reset=()=>{null!=this._texture&&(this._displayingPosterTexture||(this._texture.dispose(),this._texture=null))},this._updateInternalTexture=()=>{if(null==this._texture)return;if(this.video.readyState=this.video.HAVE_CURRENT_DATA;!this._settings.poster||this._settings.autoPlay&&u?u&&this._createInternalTexture():(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0)}getClassName(){return"VideoTexture"}_getName(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e}_getVideo(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return Ue.S0.SetCorsBehavior(e.currentSrc,e),e;const t=document.createElement("video");return"string"==typeof e?(Ue.S0.SetCorsBehavior(e,t),t.src=e):(Ue.S0.SetCorsBehavior(e[0],t),e.forEach((e=>{const i=document.createElement("source");i.src=e,t.appendChild(i)}))),this.onDisposeObservable.addOnce((()=>{Ov(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 Dv(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)}dispose(){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()),this._externalTexture?.dispose()}static CreateFromStreamAsync(e,t,i,r=!0){const s=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(s),s.style.transform="scale(0.0001, 0.0001)",s.style.opacity="0",s.style.position="fixed",s.style.bottom="0px",s.style.right="0px"),s.setAttribute("autoplay",""),s.setAttribute("muted","true"),s.setAttribute("playsinline",""),s.muted=!0,s.isNative||("object"==typeof s.srcObject?s.srcObject=t:s.src=window.URL&&window.URL.createObjectURL(t)),new Promise((t=>{const i=()=>{const n=new Dv("video",s,e,!0,r,void 0,void 0,void 0,4);e.getEngine()._badOS&&n.onDisposeObservable.addOnce((()=>{s.remove()})),n.onDisposeObservable.addOnce((()=>{Ov(s)})),t(n),s.removeEventListener("playing",i)};s.addEventListener("playing",i),s.play()}))}static async CreateFromWebCamAsync(e,t,i=!1,r=!0){if(navigator.mediaDevices){const s=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),n=await this.CreateFromStreamAsync(e,s,t,r);return n.onDisposeObservable.addOnce((()=>{s.getTracks().forEach((e=>{e.stop()}))})),n}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,r=!1,s=!0){this.CreateFromWebCamAsync(e,i,r,s).then((function(e){t&&t(e)})).catch((function(e){Z.V.Error(e.name)}))}}(0,je.Cg)([(0,$e.lK)("settings")],Dv.prototype,"_settings",void 0),(0,je.Cg)([(0,$e.lK)("src")],Dv.prototype,"_currentSrc",void 0),(0,je.Cg)([(0,$e.lK)()],Dv.prototype,"isVideo",void 0),vi.g._CreateVideoTexture=(e,t,i,r=!1,s=!1,n=vi.g.TRILINEAR_SAMPLINGMODE,o={},a,l=5)=>new Dv(e,t,i,r,s,n,o,a,l),(0,X.Y5)("BABYLON.VideoTexture",Dv);class wv extends Sm{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){const r={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},s=new Dv((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,vi.g.TRILINEAR_SAMPLINGMODE,r);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add((e=>{e.pickInfo?.pickedMesh===this.mesh&&this._texture.video.play()}),yi.Zp.POINTERDOWN)),this._textureObserver=s.onLoadObservable.add((()=>{this.onLoadObservable.notifyObservers()})),s}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}}wv.MODE_MONOSCOPIC=Sm.MODE_MONOSCOPIC,wv.MODE_TOPBOTTOM=Sm.MODE_TOPBOTTOM,wv.MODE_SIDEBYSIDE=Sm.MODE_SIDEBYSIDE;class Nv{get gpuFrameTimeCounter(){return this.engine.getGPUFrameTimeCounter()}get captureGPUFrameTime(){return this._captureGPUFrameTime}set captureGPUFrameTime(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,this.engine.captureGPUFrameTime(e))}get shaderCompilationTimeCounter(){return this._shaderCompilationTime}get captureShaderCompilationTime(){return this._captureShaderCompilationTime}set captureShaderCompilationTime(e){e!==this._captureShaderCompilationTime&&(this._captureShaderCompilationTime=e,e?(this._onBeforeShaderCompilationObserver=this.engine.onBeforeShaderCompilationObservable.add((()=>{this._shaderCompilationTime.fetchNewFrame(),this._shaderCompilationTime.beginMonitoring()})),this._onAfterShaderCompilationObserver=this.engine.onAfterShaderCompilationObservable.add((()=>{this._shaderCompilationTime.endMonitoring()}))):(this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null))}constructor(e){this.engine=e,this._captureGPUFrameTime=!1,this._captureShaderCompilationTime=!1,this._shaderCompilationTime=new on.A,this._onBeginFrameObserver=null,this._onEndFrameObserver=null,this._onBeforeShaderCompilationObserver=null,this._onAfterShaderCompilationObserver=null}dispose(){this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null,this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null,this.engine=null}}class Fv{get activeMeshesEvaluationTimeCounter(){return this._activeMeshesEvaluationTime}get captureActiveMeshesEvaluationTime(){return this._captureActiveMeshesEvaluationTime}set captureActiveMeshesEvaluationTime(e){e!==this._captureActiveMeshesEvaluationTime&&(this._captureActiveMeshesEvaluationTime=e,e?(this._onBeforeActiveMeshesEvaluationObserver=this.scene.onBeforeActiveMeshesEvaluationObservable.add((()=>{Ue.S0.StartPerformanceCounter("Active meshes evaluation"),this._activeMeshesEvaluationTime.beginMonitoring()})),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add((()=>{Ue.S0.EndPerformanceCounter("Active meshes evaluation"),this._activeMeshesEvaluationTime.endMonitoring(!1)}))):(this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null))}get renderTargetsRenderTimeCounter(){return this._renderTargetsRenderTime}get captureRenderTargetsRenderTime(){return this._captureRenderTargetsRenderTime}set captureRenderTargetsRenderTime(e){e!==this._captureRenderTargetsRenderTime&&(this._captureRenderTargetsRenderTime=e,e?(this._onBeforeRenderTargetsRenderObserver=this.scene.onBeforeRenderTargetsRenderObservable.add((()=>{Ue.S0.StartPerformanceCounter("Render targets rendering"),this._renderTargetsRenderTime.beginMonitoring()})),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add((()=>{Ue.S0.EndPerformanceCounter("Render targets rendering"),this._renderTargetsRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null))}get particlesRenderTimeCounter(){return this._particlesRenderTime}get captureParticlesRenderTime(){return this._captureParticlesRenderTime}set captureParticlesRenderTime(e){e!==this._captureParticlesRenderTime&&(this._captureParticlesRenderTime=e,e?(this._onBeforeParticlesRenderingObserver=this.scene.onBeforeParticlesRenderingObservable.add((()=>{Ue.S0.StartPerformanceCounter("Particles"),this._particlesRenderTime.beginMonitoring()})),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add((()=>{Ue.S0.EndPerformanceCounter("Particles"),this._particlesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null))}get spritesRenderTimeCounter(){return this._spritesRenderTime}get captureSpritesRenderTime(){return this._captureSpritesRenderTime}set captureSpritesRenderTime(e){e!==this._captureSpritesRenderTime&&(this._captureSpritesRenderTime=e,this.scene.spriteManagers&&(e?(this._onBeforeSpritesRenderingObserver=this.scene.onBeforeSpritesRenderingObservable.add((()=>{Ue.S0.StartPerformanceCounter("Sprites"),this._spritesRenderTime.beginMonitoring()})),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add((()=>{Ue.S0.EndPerformanceCounter("Sprites"),this._spritesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null)))}get physicsTimeCounter(){return this._physicsTime}get capturePhysicsTime(){return this._capturePhysicsTime}set capturePhysicsTime(e){e!==this._capturePhysicsTime&&this.scene.onBeforePhysicsObservable&&(this._capturePhysicsTime=e,e?(this._onBeforePhysicsObserver=this.scene.onBeforePhysicsObservable.add((()=>{Ue.S0.StartPerformanceCounter("Physics"),this._physicsTime.beginMonitoring()})),this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add((()=>{Ue.S0.EndPerformanceCounter("Physics"),this._physicsTime.endMonitoring()}))):(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null))}get animationsTimeCounter(){return this._animationsTime}get captureAnimationsTime(){return this._captureAnimationsTime}set captureAnimationsTime(e){e!==this._captureAnimationsTime&&(this._captureAnimationsTime=e,e?this._onAfterAnimationsObserver=this.scene.onAfterAnimationsObservable.add((()=>{this._animationsTime.endMonitoring()})):(this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null))}get frameTimeCounter(){return this._frameTime}get captureFrameTime(){return this._captureFrameTime}set captureFrameTime(e){this._captureFrameTime=e}get interFrameTimeCounter(){return this._interFrameTime}get captureInterFrameTime(){return this._captureInterFrameTime}set captureInterFrameTime(e){this._captureInterFrameTime=e}get renderTimeCounter(){return this._renderTime}get captureRenderTime(){return this._captureRenderTime}set captureRenderTime(e){e!==this._captureRenderTime&&(this._captureRenderTime=e,e?(this._onBeforeDrawPhaseObserver=this.scene.onBeforeDrawPhaseObservable.add((()=>{this._renderTime.beginMonitoring(),Ue.S0.StartPerformanceCounter("Main render")})),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add((()=>{this._renderTime.endMonitoring(!1),Ue.S0.EndPerformanceCounter("Main render")}))):(this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null))}get cameraRenderTimeCounter(){return this._cameraRenderTime}get captureCameraRenderTime(){return this._captureCameraRenderTime}set captureCameraRenderTime(e){e!==this._captureCameraRenderTime&&(this._captureCameraRenderTime=e,e?(this._onBeforeCameraRenderObserver=this.scene.onBeforeCameraRenderObservable.add((e=>{this._cameraRenderTime.beginMonitoring(),Ue.S0.StartPerformanceCounter(`Rendering camera ${e.name}`)})),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add((e=>{this._cameraRenderTime.endMonitoring(!1),Ue.S0.EndPerformanceCounter(`Rendering camera ${e.name}`)}))):(this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null))}get drawCallsCounter(){return this.scene.getEngine()._drawCalls}constructor(e){this.scene=e,this._captureActiveMeshesEvaluationTime=!1,this._activeMeshesEvaluationTime=new on.A,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new on.A,this._captureFrameTime=!1,this._frameTime=new on.A,this._captureRenderTime=!1,this._renderTime=new on.A,this._captureInterFrameTime=!1,this._interFrameTime=new on.A,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new on.A,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new on.A,this._capturePhysicsTime=!1,this._physicsTime=new on.A,this._captureAnimationsTime=!1,this._animationsTime=new on.A,this._captureCameraRenderTime=!1,this._cameraRenderTime=new on.A,this._onBeforeActiveMeshesEvaluationObserver=null,this._onAfterActiveMeshesEvaluationObserver=null,this._onBeforeRenderTargetsRenderObserver=null,this._onAfterRenderTargetsRenderObserver=null,this._onAfterRenderObserver=null,this._onBeforeDrawPhaseObserver=null,this._onAfterDrawPhaseObserver=null,this._onBeforeAnimationsObserver=null,this._onBeforeParticlesRenderingObserver=null,this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver=null,this._onAfterSpritesRenderingObserver=null,this._onBeforePhysicsObserver=null,this._onAfterPhysicsObserver=null,this._onAfterAnimationsObserver=null,this._onBeforeCameraRenderObserver=null,this._onAfterCameraRenderObserver=null,this._onBeforeAnimationsObserver=e.onBeforeAnimationsObservable.add((()=>{this._captureActiveMeshesEvaluationTime&&this._activeMeshesEvaluationTime.fetchNewFrame(),this._captureRenderTargetsRenderTime&&this._renderTargetsRenderTime.fetchNewFrame(),this._captureFrameTime&&(Ue.S0.StartPerformanceCounter("Scene rendering"),this._frameTime.beginMonitoring()),this._captureInterFrameTime&&this._interFrameTime.endMonitoring(),this._captureParticlesRenderTime&&this._particlesRenderTime.fetchNewFrame(),this._captureSpritesRenderTime&&this._spritesRenderTime.fetchNewFrame(),this._captureAnimationsTime&&this._animationsTime.beginMonitoring(),this._captureRenderTime&&this._renderTime.fetchNewFrame(),this._captureCameraRenderTime&&this._cameraRenderTime.fetchNewFrame(),this.scene.getEngine()._drawCalls.fetchNewFrame()})),this._onAfterRenderObserver=e.onAfterRenderObservable.add((()=>{this._captureFrameTime&&(Ue.S0.EndPerformanceCounter("Scene rendering"),this._frameTime.endMonitoring()),this._captureRenderTime&&this._renderTime.endMonitoring(!1),this._captureInterFrameTime&&this._interFrameTime.beginMonitoring(),this._captureActiveMeshesEvaluationTime&&this._activeMeshesEvaluationTime.endFrame(),this._captureRenderTargetsRenderTime&&this._renderTargetsRenderTime.endFrame(),this._captureParticlesRenderTime&&this._particlesRenderTime.endFrame(),this._captureSpritesRenderTime&&this._spritesRenderTime.endFrame(),this._captureRenderTime&&this._renderTime.endFrame(),this._captureCameraRenderTime&&this._cameraRenderTime.endFrame()}))}dispose(){this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=null,this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null,this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null,this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver),this._onBeforeAnimationsObserver=null,this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver&&(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null),this._onAfterSpritesRenderingObserver&&(this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null),this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null,this._onBeforePhysicsObserver&&(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null),this._onAfterPhysicsObserver&&(this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null),this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null,this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null,this.scene=null}}class Lv{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}get shaderLanguage(){return this._shaderLanguage}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i{if((i||0===t)&&e.subMeshes)for(let t=0;t{let s;this.onBeforeRenderMainTextureObservable.notifyObservers(this);const n=this._scene.getEngine();if(r.length){for(n.setColorWrite(!1),s=0;s{e.clear(this.neutralColor,!0,!0,!0)})),this._scene.getBoundingBoxRenderer){const e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e})),this._mainTexture.onAfterUnbindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=e}))}}_addCustomEffectDefines(e){}_isReady(e,t,i){const r=this._scene.getEngine(),s=e.getMesh(),n=s._internalAbstractMeshDataInfo._materialForRenderPass?.[r.currentRenderPassId];if(n)return n.isReadyForSubMesh(s,e,t);const o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);const a=[],l=[st.R.PositionKind];let h=!1,c=!1;if(o){const e=o.needAlphaTesting(),t=o.getAlphaTestTexture(),i=t&&t.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);t&&(e||i)&&(a.push("#define DIFFUSE"),s.isVerticesDataPresent(st.R.UV2Kind)&&1===t.coordinatesIndex?(a.push("#define DIFFUSEUV2"),c=!0):s.isVerticesDataPresent(st.R.UVKind)&&(a.push("#define DIFFUSEUV1"),h=!0),e&&(a.push("#define ALPHATEST"),a.push("#define ALPHATESTVALUE 0.4")),t.gammaSpace||a.push("#define DIFFUSE_ISLINEAR"));const r=o.opacityTexture;r&&(a.push("#define OPACITY"),s.isVerticesDataPresent(st.R.UV2Kind)&&1===r.coordinatesIndex?(a.push("#define OPACITYUV2"),c=!0):s.isVerticesDataPresent(st.R.UVKind)&&(a.push("#define OPACITYUV1"),h=!0))}i&&(a.push("#define EMISSIVE"),s.isVerticesDataPresent(st.R.UV2Kind)&&1===i.coordinatesIndex?(a.push("#define EMISSIVEUV2"),c=!0):s.isVerticesDataPresent(st.R.UVKind)&&(a.push("#define EMISSIVEUV1"),h=!0),i.gammaSpace||a.push("#define EMISSIVE_ISLINEAR")),s.useVertexColors&&s.isVerticesDataPresent(st.R.ColorKind)&&s.hasVertexAlpha&&o.transparencyMode!==Vt.MATERIAL_OPAQUE&&(l.push(st.R.ColorKind),a.push("#define VERTEXALPHA")),h&&(l.push(st.R.UVKind),a.push("#define UV1")),c&&(l.push(st.R.UV2Kind),a.push("#define UV2"));const u=new Tn;if(s.useBones&&s.computeBonesUsingShaders){l.push(st.R.MatricesIndicesKind),l.push(st.R.MatricesWeightsKind),s.numBoneInfluencers>4&&(l.push(st.R.MatricesIndicesExtraKind),l.push(st.R.MatricesWeightsExtraKind)),a.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers);const e=s.skeleton;e&&e.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(e?e.bones.length+1:0)),s.numBoneInfluencers>0&&u.addCPUSkinningFallback(0,s)}else a.push("#define NUM_BONE_INFLUENCERS 0");const d=s.morphTargetManager;let f=0;d&&(f=d.numMaxInfluencers||d.numInfluencers,f>0&&(a.push("#define MORPHTARGETS"),a.push("#define NUM_MORPH_INFLUENCERS "+f),d.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),(0,Bt.MF)(l,s,f))),t&&(a.push("#define INSTANCES"),(0,Bt.te)(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),(0,Ln.tv)(o,this._scene,a),this._addCustomEffectDefines(a);const p=e._getDrawWrapper(void 0,!0),_=p.defines,m=a.join("\n");if(_!==m){const e=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];(0,Ln.TV)(e),p.setEffect(this._engine.createEffect("glowMapGeneration",l,e,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],m,u,void 0,void 0,{maxSimultaneousMorphTargets:f},this._shaderLanguage,this._shadersLoaded?void 0:async()=>{await this._importShadersAsync(),this._shadersLoaded=!0}),m)}const g=p.effect.isReady();return this._arePostProcessAndMergeReady()&&g}async _importShadersAsync(){1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,58186)),Promise.resolve().then(i.bind(i,69276))]):await Promise.all([Promise.resolve().then(i.bind(i,91337)),Promise.resolve().then(i.bind(i,42591))])}_arePostProcessAndMergeReady(){let e=!0;for(let t=0;th.setMatrix("world",t)))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(r)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[st.R.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 Ue.S0.Instantiate(e.customType).Parse(e,t,i)}}Lv.ForceGLSL=!1,Lv._SceneComponentInitialization=e=>{throw(0,Je.n)("EffectLayerSceneComponent")},(0,je.Cg)([(0,$e.lK)()],Lv.prototype,"name",void 0),(0,je.Cg)([(0,$e.qK)()],Lv.prototype,"neutralColor",void 0),(0,je.Cg)([(0,$e.lK)()],Lv.prototype,"isEnabled",void 0),(0,je.Cg)([(0,$e.fW)()],Lv.prototype,"camera",null),(0,je.Cg)([(0,$e.lK)()],Lv.prototype,"renderingGroupId",null),(0,je.Cg)([(0,$e.lK)()],Lv.prototype,"disableBoundingBoxesFromEffectLayer",void 0),ci(Ut.v.NAME_EFFECTLAYER,((e,t,i,r)=>{if(e.effectLayers){i.effectLayers||(i.effectLayers=[]);for(let s=0;s{this.scene.addEffectLayer(e)}))}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach((e=>{this.scene.removeEffectLayer(e),t&&e.dispose()}))}dispose(){const e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){const i=this._engine.currentRenderPassId,r=this.scene.effectLayers;for(const s of r){if(!s.hasMesh(e))continue;const r=s._mainTexture;this._engine.currentRenderPassId=r.renderPassId;for(const r of e.subMeshes)if(!s.isReady(r,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1;const i=this.scene.effectLayers;if(i&&i.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(const r of i)if(r.shouldRender()&&(!r.camera||r.camera.cameraRigMode===rt.RIG_MODE_NONE&&e===r.camera||r.camera.cameraRigMode!==rt.RIG_MODE_NONE&&r.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||r.needStencil();const e=r._mainTexture;e._shouldRender()&&(this.scene.incrementRenderId(),e.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 t=e._getComponent(Ut.v.NAME_EFFECTLAYER);t||(t=new Bv(e),e._addComponent(t))},oi.Z.prototype.getGlowLayerByName=function(e){for(let t=0;t{await this._importShadersAsync(),this._shadersLoaded=!0})}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width,t=this._mainTextureDesiredSize.height;e=this._engine.needPOTTextures?(0,Gs.R)(e,this._maxSize):e,t=this._engine.needPOTTextures?(0,Gs.R)(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture1=new ln.$("GlowLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture1.wrapU=vi.g.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=vi.g.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(vi.g.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;const r=Math.floor(e/2),s=Math.floor(t/2);this._blurTexture2=new ln.$("GlowLayerBlurRTT2",{width:r,height:s},this._scene,!1,!0,i),this._blurTexture2.wrapU=vi.g.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=vi.g.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(vi.g.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2];const n=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new _m("GlowLayerHBP1",new W.I9(1,0),n,{width:e,height:t},null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess1.width=e,this._horizontalBlurPostprocess1.height=t,this._horizontalBlurPostprocess1.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess1.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess1=new _m("GlowLayerVBP1",new W.I9(0,1),n,{width:e,height:t},null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new _m("GlowLayerHBP2",new W.I9(1,0),n,{width:r,height:s},null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=r,this._horizontalBlurPostprocess2.height=s,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._blurTexture1)})),this._verticalBlurPostprocess2=new _m("GlowLayerVBP2",new W.I9(0,1),n,{width:r,height:s},null,vi.g.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 e=this._blurTexture1.renderTarget;if(e){this._scene.postProcessManager.directRender(this._postProcesses1,e,!0);const t=this._blurTexture2.renderTarget;t&&this._scene.postProcessManager.directRender(this._postProcesses2,t,!0),this._engine.unBindFramebuffer(t??e,!0)}})),this._postProcesses.map((e=>{e.autoClear=!1}))}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){const i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r)return!1;const s=i.emissiveTexture;return super._isReady(e,t,s)}needStencil(){return!1}_canRenderMesh(e,t){return!0}_internalRender(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);const t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(Vt.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){let r=1;this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(r=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector?this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color):i.emissiveColor?(r*=i.emissiveIntensity??1,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*r,i.emissiveColor.g*r,i.emissiveColor.b*r,i.alpha)):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){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){-1===this._includedOnlyMeshes.indexOf(e.uniqueId)&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){const t=this._includedOnlyMeshes.indexOf(e.uniqueId);-1!==t&&this._includedOnlyMeshes.splice(t,1)}hasMesh(e){return!!super.hasMesh(e)&&(this._includedOnlyMeshes.length?-1!==this._includedOnlyMeshes.indexOf(e.uniqueId):!this._excludedMeshes.length||-1===this._excludedMeshes.indexOf(e.uniqueId))}_useMeshMaterial(e){return 0!=this._meshesUsingTheirOwnMaterials.length&&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=it.p.Serialize(this);let t;if(e.customType="BABYLON.GlowLayer",e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;tnew Vv(e.name,t,e.options)),e,t,i);let s;for(s=0;s{e.setFloat2("screenSize",this.width,this.height),e.setVector2("direction",this.direction),e.setFloat("blurWidth",this.kernel)}))}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(i.bind(i,41368)))):t.push(Promise.resolve().then(i.bind(i,16655))),super._gatherImports(e,t)}}class Uv extends Lv{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,void 0!==i&&!!i.forceGLSL),this.name=e,this.innerGlow=!0,this.outerGlow=!0,this.onBeforeBlurObservable=new z.cP,this.onAfterBlurObservable=new z.cP,this._instanceGlowingMeshStencilReference=Uv.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=Uv.NeutralColor,this._engine.isStencilEnable||Z.V.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options={mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,forceGLSL:!1,...i},this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}async _importShadersAsync(){1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,68940)),Promise.resolve().then(i.bind(i,86010)),Promise.resolve().then(i.bind(i,41368))]):await Promise.all([Promise.resolve().then(i.bind(i,74969)),Promise.resolve().then(i.bind(i,99347)),Promise.resolve().then(i.bind(i,16655))]),await super._importShadersAsync()}getEffectName(){return Uv.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[st.R.PositionKind],["offset"],["textureSampler"],this._options.isStroke?"#define STROKE \n":void 0,void 0,void 0,void 0,void 0,this._shaderLanguage,this._shadersLoaded?void 0:async()=>{await this._importShadersAsync(),this._shadersLoaded=!0})}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?(0,Gs.R)(e,this._maxSize):e,t=this._engine.needPOTTextures?(0,Gs.R)(t,this._maxSize):t;let i=0;if(i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture=new ln.$("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=vi.g.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=vi.g.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(vi.g.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],2===this._options.alphaBlendingMode)this._downSamplePostprocess=new _s.v("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._horizontalBlurPostprocess=new kv("HighlightLayerHBP",new W.I9(1,0),this._options.blurHorizontalSize,1,null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._verticalBlurPostprocess=new kv("HighlightLayerVBP",new W.I9(0,1),this._options.blurVerticalSize,1,null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess];else{this._horizontalBlurPostprocess=new _m("HighlightLayerHBP",new W.I9(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i);const r=this._horizontalBlurPostprocess;r.width=e,r.height=t,r.externalTextureSamplerBinding=!0,r.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess=new _m("HighlightLayerVBP",new W.I9(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]}this._mainTexture.onAfterUnbindObservable.add((()=>{this.onBeforeBlurObservable.notifyObservers(this);const e=this._blurTexture.renderTarget;e&&(this._scene.postProcessManager.directRender(this._postProcesses,e,!0),this._engine.unBindFramebuffer(e,!0)),this.onAfterBlurObservable.notifyObservers(this)})),this._postProcesses.map((e=>{e.autoClear=!1}))}needStencil(){return!0}isReady(e,t){const i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r||!this._meshes)return!1;let s=null;const n=this._meshes[r.uniqueId];return n&&n.glowEmissiveOnly&&i&&(s=i.emissiveTexture),super._isReady(e,t,s)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);const i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&0===t&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(Vt.TriangleFillMode,0,6)),this.innerGlow&&1===t&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(Vt.TriangleFillMode,0,6)),i.restoreStencilState()}shouldRender(){return!!super.shouldRender()&&!!this._meshes}_shouldRenderMesh(e){return!(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]||!super.hasMesh(e))}_canRenderMesh(e,t){return!0}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}_setEmissiveTextureAndColor(e,t,i){const r=this._meshes[e.uniqueId];r?this._emissiveTextureAndColor.color.set(r.color.r,r.color.g,r.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),r&&r.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(this._excludedMeshes&&!this._excludedMeshes[e.uniqueId]){const t={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};t.beforeBind=e.onBeforeBindObservable.add((e=>{t.stencilState=e.getEngine().getStencilBuffer(),e.getEngine().setStencilBuffer(!1)})),t.afterRender=e.onAfterRenderObservable.add((e=>{e.getEngine().setStencilBuffer(t.stencilState)})),this._excludedMeshes[e.uniqueId]=t}}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)&&void 0!==this._meshes[e.uniqueId]&&null!==this._meshes[e.uniqueId]}addMesh(e,t,i=!1){if(!this._meshes)return;const r=this._meshes[e.uniqueId];r?r.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add((e=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?this._defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))})),observerDefault:e.onAfterRenderObservable.add((e=>{this.isEnabled&&this._defaultStencilReference(e)})),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 e in this._meshes)if(this._meshes[e]){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(Uv.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=it.p.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(const t in this._meshes){const i=this._meshes[t];i&&e.meshes.push({glowEmissiveOnly:i.glowEmissiveOnly,color:i.color.asArray(),meshId:i.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(const t in this._excludedMeshes){const i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){const r=it.p.Parse((()=>new Uv(e.name,t,e.options)),e,t,i);let s;for(s=0;sthis._drawCameraPredicate(t,!0,!0,e.layerMask)))}_drawCameraForegroundWithPostProcessing(e){this._draw((t=>this._drawCameraPredicate(t,!1,!0,e.layerMask)))}_drawCameraForegroundWithoutPostProcessing(e){this._draw((t=>this._drawCameraPredicate(t,!1,!1,e.layerMask)))}_drawRenderTargetPredicate(e,t,i,r,s){return e.renderTargetTextures.length>0&&e.isBackground===t&&e.applyPostProcess===i&&e.renderTargetTextures.indexOf(s)>-1&&!!(e.layerMask&r)}_drawRenderTargetBackground(e){this._draw((t=>this._drawRenderTargetPredicate(t,!0,!0,this.scene.activeCamera.layerMask,e)))}_drawRenderTargetForegroundWithPostProcessing(e){this._draw((t=>this._drawRenderTargetPredicate(t,!1,!0,this.scene.activeCamera.layerMask,e)))}_drawRenderTargetForegroundWithoutPostProcessing(e){this._draw((t=>this._drawRenderTargetPredicate(t,!1,!1,this.scene.activeCamera.layerMask,e)))}addFromContainer(e){e.layers&&e.layers.forEach((e=>{this.scene.layers.push(e)}))}removeFromContainer(e,t=!1){e.layers&&e.layers.forEach((e=>{const i=this.scene.layers.indexOf(e);-1!==i&&this.scene.layers.splice(i,1),t&&e.dispose()}))}}class zv{set applyPostProcess(e){this._applyPostProcess=e}get applyPostProcess(){return this.isBackground||this._applyPostProcess}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,r,s,n=!1){this.name=e,this._applyPostProcess=!0,this.scale=new W.I9(1,1),this.offset=new W.I9(0,0),this.alphaBlendingMode=2,this.layerMask=268435455,this.renderTargetTextures=[],this.renderOnlyInRenderTargetTextures=!1,this.convertToLinearSpace=!1,this.isEnabled=!0,this._vertexBuffers={},this.onDisposeObservable=new z.cP,this.onBeforeRenderObservable=new z.cP,this.onAfterRenderObservable=new z.cP,this._shaderLanguage=0,this._shadersLoaded=!1,this.texture=t?new vi.g(t,i,!0):null,this.isBackground=void 0===r||r,this.color=void 0===s?new H.ov(1,1,1,1):s,this._scene=i||he.q.LastCreatedScene;const o=this._scene.getEngine();!o.isWebGPU||n||zv.ForceGLSL||(this._shaderLanguage=1);let a=this._scene._getComponent(Ut.v.NAME_LAYER);a||(a=new Gv(this._scene),this._scene._addComponent(a)),this._scene.layers.push(this),this._drawWrapper=new gt.E(o);const l=[];l.push(1,1),l.push(-1,1),l.push(-1,-1),l.push(1,-1);const h=new st.R(o,l,st.R.PositionKind,!1,!1,2);this._vertexBuffers[st.R.PositionKind]=h,this._createIndexBuffer()}_createIndexBuffer(){const e=this._scene.getEngine(),t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[st.R.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}isReady(){const e=this._scene.getEngine();let t="";this.alphaTest&&(t="#define ALPHATEST"),this.texture&&(this.texture.gammaSpace?this.convertToLinearSpace&&(t+="\n#define CONVERT_TO_LINEAR"):this.convertToLinearSpace||(t+="\n#define CONVERT_TO_GAMMA")),this._previousDefines!==t&&(this._previousDefines=t,this._drawWrapper.effect=e.createEffect("layer",[st.R.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],t,void 0,void 0,void 0,void 0,this._shaderLanguage,this._shadersLoaded?void 0:async()=>{1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,56028)),Promise.resolve().then(i.bind(i,28246))]):await Promise.all([Promise.resolve().then(i.bind(i,11115)),Promise.resolve().then(i.bind(i,59329))]),this._shadersLoaded=!0}));const r=this._drawWrapper.effect;return!!r?.isReady()&&(!this.texture||this.texture.isReady())}render(){if(!this.isEnabled)return;const e=this._scene.getEngine();if(!this.isReady())return;const t=this._drawWrapper.effect;this.onBeforeRenderObservable.notifyObservers(this),e.enableEffect(this._drawWrapper),e.setState(!1),this.texture&&(t.setTexture("textureSampler",this.texture),t.setMatrix("textureMatrix",this.texture.getTextureMatrix())),t.setFloat4("color",this.color.r,this.color.g,this.color.b,this.color.a),t.setVector2("offset",this.offset),t.setVector2("scale",this.scale),e.bindBuffers(this._vertexBuffers,this._indexBuffer,t),this.alphaTest?e.drawElementsType(Vt.TriangleFillMode,0,6):(e.setAlphaMode(this.alphaBlendingMode),e.drawElementsType(Vt.TriangleFillMode,0,6),e.setAlphaMode(0)),this.onAfterRenderObservable.notifyObservers(this)}dispose(){const e=this._vertexBuffers[st.R.PositionKind];e&&(e.dispose(),this._vertexBuffers[st.R.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.texture&&(this.texture.dispose(),this.texture=null),this.renderTargetTextures=[];const t=this._scene.layers.indexOf(this);this._scene.layers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderObservable.clear()}}zv.ForceGLSL=!1;var Wv=i(42591),Hv=i(91337),Xv=i(69276),qv=i(58186),Yv=i(74969),Kv=i(99347),jv=i(16655),$v=i(68940),Qv=i(86010),Zv=i(41368),Jv=i(59329),ex=i(11115),tx=i(28246),ix=i(56028);class rx{static AddFlare(e,t,i,r,s){return new rx(e,t,i,r,s)}constructor(e,t,i,r,s){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new H.v9(1,1,1),this.texture=r?new vi.g(r,s.getScene(),!0):null,this._system=s;const n=s.scene.getEngine();s._onShadersLoaded.addOnce((()=>{this._drawWrapper=new gt.E(n),this._drawWrapper.effect=n.createEffect("lensFlare",[st.R.PositionKind],["color","viewportMatrix"],["textureSampler"],"",void 0,void 0,void 0,void 0,s.shaderLanguage)})),s.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();const e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}}class sx{get scene(){return this._scene}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i){this.name=e,this.lensFlares=[],this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._shaderLanguage=0,this._vertexBuffers={},this._isEnabled=!0,this._onShadersLoaded=new z.cP(void 0,!0),this._shadersLoaded=!1,this._scene=i||he.q.LastCreatedScene,sx._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=e=>i.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&!!(e.layerMask&i.activeCamera.layerMask);const r=i.getEngine(),s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1),this._vertexBuffers[st.R.PositionKind]=new st.R(r,s,st.R.PositionKind,!1,!1,2),this._createIndexBuffer(),this._initShaderSourceAsync()}async _initShaderSourceAsync(){this._scene.getEngine().isWebGPU&&!sx.ForceGLSL?(this._shaderLanguage=1,await Promise.all([Promise.resolve().then(i.bind(i,19121)),Promise.resolve().then(i.bind(i,72987))])):await Promise.all([Promise.resolve().then(i.bind(i,54262)),Promise.resolve().then(i.bind(i,45980))]),this._shadersLoaded=!0,this._onShadersLoaded.notifyObservers()}_createIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled=e}getScene(){return this._scene}getEmitter(){return this._emitter}setEmitter(e){this._emitter=e}getEmitterPosition(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position}computeEffectivePosition(e){let t=this.getEmitterPosition();t=W.Pq.Project(t,W.uq.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=W.Pq.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=2*this.viewportBorder,e.height+=2*this.viewportBorder,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._positionY,e.y,e.height),!0)}_isVisible(){if(!this._isEnabled||!this._scene.activeCamera)return!1;const e=this.getEmitterPosition().subtract(this._scene.activeCamera.globalPosition),t=e.length();e.normalize();const i=new wi(this._scene.activeCamera.globalPosition,e),r=this._scene.pickWithRay(i,this.meshesSelectionPredicate,!0);return!r||!r.hit||r.distance>t}render(){if(!this._scene.activeCamera||!this._shadersLoaded)return!1;const e=this._scene.getEngine(),t=this._scene.activeCamera.viewport.toGlobal(e.getRenderWidth(!0),e.getRenderHeight(!0));if(!this.computeEffectivePosition(t))return!1;if(!this._isVisible())return!1;let i,r;i=this._positionXt.x+t.width-this.borderLimit?this._positionX-t.x-t.width+this.borderLimit:0,r=this._positionYt.y+t.height-this.borderLimit?this._positionY-t.y-t.height+this.borderLimit:0;let s=i>r?i:r;s-=this.viewportBorder,s>this.borderLimit&&(s=this.borderLimit);let n=1-(0,ar.Clamp)(s/this.borderLimit,0,1);if(n<0)return!1;n>1&&(n=1),this.viewportBorder>0&&(t.x+=this.viewportBorder,t.y+=this.viewportBorder,t.width-=2*this.viewportBorder,t.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);const o=t.x+t.width/2,a=t.y+t.height/2,l=o-this._positionX,h=a-this._positionY;e.setState(!1),e.setDepthBuffer(!1);for(let i=0;i{throw(0,Je.n)("LensFlareSystemSceneComponent")},ci(Ut.v.NAME_LENSFLARESYSTEM,((e,t,i,r)=>{if(void 0!==e.lensFlareSystems&&null!==e.lensFlareSystems){i.lensFlareSystems||(i.lensFlareSystems=[]);for(let s=0,n=e.lensFlareSystems.length;s{this.scene.addLensFlareSystem(e)}))}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach((e=>{this.scene.removeLensFlareSystem(e),t&&e.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;Ue.S0.StartPerformanceCounter("Lens flares",t.length>0);for(const i of t)e.layerMask&i.layerMask&&i.render();Ue.S0.EndPerformanceCounter("Lens flares",t.length>0)}}}sx._SceneComponentInitialization=e=>{let t=e._getComponent(Ut.v.NAME_LENSFLARESYSTEM);t||(t=new nx(e),e._addComponent(t))};var ox=i(54262),ax=i(45980),lx=i(19121),hx=i(72987),cx=i(75653);class ux{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 void 0!==this._depthScale?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===ux.FILTER_BLUREXPONENTIALSHADOWMAP)return void(this.useExponentialShadowMap=!0);if(e===ux.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)return void(this.useCloseExponentialShadowMap=!0);if(e===ux.FILTER_PCF||e===ux.FILTER_PCSS)return void(this.usePoissonSampling=!0)}e!==ux.FILTER_PCF&&e!==ux.FILTER_PCSS||this._scene.getEngine()._features.supportShadowSamplers?this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty()):this.usePoissonSampling=!0}get usePoissonSampling(){return this.filter===ux.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(ux.FILTER_POISSONSAMPLING);(e||this.filter===ux.FILTER_POISSONSAMPLING)&&(this.filter=e?t:ux.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===ux.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(ux.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===ux.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:ux.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===ux.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(ux.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===ux.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:ux.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===ux.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(ux.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===ux.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:ux.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===ux.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(ux.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===ux.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:ux.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===ux.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(ux.FILTER_PCF);(e||this.filter===ux.FILTER_PCF)&&(this.filter=e?t:ux.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===ux.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(ux.FILTER_PCSS);(e||this.filter===ux.FILTER_PCSS)&&(this.filter=e?t:ux.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 this._darkness=e>=1?1:e<=0?0: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 ux.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),-1===this._shadowMap.renderList.indexOf(e)&&this._shadowMap.renderList.push(e),t)for(const t of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(t)&&this._shadowMap.renderList.push(t);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;const i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(const t of e.getChildren())this.removeShadowCaster(t);return this}getLight(){return this._light}get shaderLanguage(){return this._shaderLanguage}_getCamera(){return this._camera??this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,r,s,n=!1){this.onBeforeShadowMapRenderObservable=new z.cP,this.onAfterShadowMapRenderObservable=new z.cP,this.onBeforeShadowMapRenderMeshObservable=new z.cP,this.onAfterShadowMapRenderMeshObservable=new z.cP,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=ux.FILTER_NONE,this._filteringQuality=ux.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this._shaderLanguage=0,this.forceBackFacesOnly=!1,this._lightDirection=W.Pq.Zero(),this._viewMatrix=W.uq.Zero(),this._projectionMatrix=W.uq.Zero(),this._transformMatrix=W.uq.Zero(),this._cachedPosition=new W.Pq(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new W.Pq(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=W.uq.Identity(),this._shadersLoaded=!1,this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=r??null,this._useRedTextureType=!!s,this._initShaderSourceAsync(n);let o=t._shadowGenerators;o||(o=t._shadowGenerators=new Map),o.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),ux._SceneComponentInitialization(this._scene);const a=this._scene.getEngine().getCaps();i?a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:a.textureFloatRender&&a.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 ln.$(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 ln.$(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),null===this._shadowMap)return;this._shadowMap.wrapU=vi.g.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=vi.g.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(vi.g.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(e,t,i,r)=>this._renderForShadowMap(e,t,i,r),this._shadowMap.customIsReadyFunction=()=>!0;const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add((()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._debugPushGroup?.(`shadow map generation for pass id ${e.currentRenderPassId}`,1)})),this._shadowMap.onBeforeRenderObservable.add((t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=t,this._filter===ux.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((()=>{if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===ux.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap)return void e._debugPopGroup?.(1);const t=this.getShadowMapForRendering();t&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,t.renderTarget,!0),e.unBindFramebuffer(t.renderTarget,!0)),e._debugPopGroup?.(1)}));const t=new H.ov(0,0,0,0),i=new H.ov(1,1,1,1);this._shadowMap.onClearObservable.add((e=>{this._filter===ux.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)})),this._shadowMap.onResizeObservable.add((e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}));for(let e=cx.m.MIN_RENDERINGGROUPS;e{e.setTexture("textureSampler",this._shadowMap)})),this._kernelBlurYPostprocess=new _m(this._light.name+"KernelBlurY",new W.I9(0,1),this.blurKernel,1,null,vi.g.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,0===this._textureType&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new ms.w(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,vi.g.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType,void 0,void 0,void 0,void 0,this._shaderLanguage),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add((e=>{e.setFloat2("screenSize",t,t),e.setTexture("textureSampler",this._shadowMap)})),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,r){let s;if(r.length)for(s=0;s{r===i||e?(r.getMeshUniformBuffer().bindToEffect(h,"Mesh"),r.transferToEffect(e?t:f)):(i.getMeshUniformBuffer().bindToEffect(h,"Mesh"),i.transferToEffect(t))})),this.forceBackFacesOnly&&n.setState(!0,0,!1,!1,o.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(h),this.onAfterShadowMapRenderMeshObservable.notifyObservers(i)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===ux.FILTER_NONE||this.filter===ux.FILTER_PCSS?this._shadowMap.updateSamplingMode(vi.g.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(vi.g.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i={useInstances:!1,...t},r=this.getShadowMap();if(!r)return void(e&&e(this));const s=r.renderList;if(!s)return void(e&&e(this));const n=[];for(const e of s)n.push(...e.subMeshes);if(0===n.length)return void(e&&e(this));let o=0;const a=()=>{if(this._scene&&this._scene.getEngine()){for(;this.isReady(n[o],i.useInstances,n[o].getMaterial()?.needAlphaBlendingForMesh(n[o].getMesh())??!1);)if(o++,o>=n.length)return void(e&&e(this));setTimeout(a,16)}};a()}forceCompilationAsync(e){return new Promise((t=>{this.forceCompilation((()=>{t()}),e)}))}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,r){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));const s=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&s.isVerticesDataPresent(st.R.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===$t.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&r?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){if(!this._shadersLoaded)return!1;const r=e.getMaterial(),s=r?.shadowDepthWrapper;if(this._opacityTexture=null,!r)return!1;const n=[];if(this._prepareShadowDefines(e,t,n,i),s){if(!s.isReadyForSubMesh(e,n,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const i=e._getDrawWrapper(void 0,!0);let s=i.effect,o=i.defines;const a=[st.R.PositionKind],l=e.getMesh();this.normalBias&&l.isVerticesDataPresent(st.R.NormalKind)&&(a.push(st.R.NormalKind),n.push("#define NORMAL"),l.nonUniformScaling&&n.push("#define NONUNIFORMSCALING"));const h=r.needAlphaTesting();if((h||r.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=r.opacityTexture:this._opacityTexture=r.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const e=r.alphaCutOff??ux.DEFAULT_ALPHA_CUTOFF;n.push("#define ALPHATEXTURE"),h&&n.push(`#define ALPHATESTVALUE ${e}${e%1==0?".":""}`),l.isVerticesDataPresent(st.R.UVKind)&&(a.push(st.R.UVKind),n.push("#define UV1")),l.isVerticesDataPresent(st.R.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(a.push(st.R.UV2Kind),n.push("#define UV2"))}const c=new Tn;if(l.useBones&&l.computeBonesUsingShaders&&l.skeleton){a.push(st.R.MatricesIndicesKind),a.push(st.R.MatricesWeightsKind),l.numBoneInfluencers>4&&(a.push(st.R.MatricesIndicesExtraKind),a.push(st.R.MatricesWeightsExtraKind));const e=l.skeleton;n.push("#define NUM_BONE_INFLUENCERS "+l.numBoneInfluencers),l.numBoneInfluencers>0&&c.addCPUSkinningFallback(0,l),e.isUsingTextureForMatrices?n.push("#define BONETEXTURE"):n.push("#define BonesPerMesh "+(e.bones.length+1))}else n.push("#define NUM_BONE_INFLUENCERS 0");const u=l.morphTargetManager;let d=0;if(u&&(d=u.numMaxInfluencers||u.numInfluencers,d>0&&(n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+d),u.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),(0,Bt.MF)(a,l,d))),(0,Ln.tv)(r,this._scene,n),t&&(n.push("#define INSTANCES"),(0,Bt.te)(a),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const e of this.customShaderOptions.defines)-1===n.indexOf(e)&&n.push(e);const f=l.bakedVertexAnimationManager;f&&f.isEnabled&&(n.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&a.push("bakedVertexAnimationSettingsInstanced"));const p=n.join("\n");if(o!==p){o=p;let e="shadowMap";const t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","morphTargetCount","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],r=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"],n=["Scene","Mesh"];if((0,Ln.TV)(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const e of this.customShaderOptions.attributes)-1===a.indexOf(e)&&a.push(e);if(this.customShaderOptions.uniforms)for(const e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(const e of this.customShaderOptions.samplers)-1===r.indexOf(e)&&r.push(e)}const l=this._scene.getEngine();s=l.createEffect(e,{attributes:a,uniformsNames:t,uniformBuffersNames:n,samplers:r,defines:p,fallbacks:c,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:d},shaderLanguage:this._shaderLanguage},l),i.setEffect(s,o)}if(!s.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(this._blurPostProcesses&&this._blurPostProcesses.length||this._initializeBlurRTTAndPostProcesses()),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady()||this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady()||this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){const i=this._scene,r=this._light;i.shadowsEnabled&&r.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===ux.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===ux.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===ux.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===ux.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),r.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const r=this._getCamera();if(!r)return;const s=this.getShadowMap();if(!s)return;i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix());const n=this.getShadowMapForRendering();this._filter===ux.FILTER_PCF?(t.setDepthStencilTexture("shadowTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),s.getSize().width,1/s.getSize().width,this.frustumEdgeFalloff,e)):this._filter===ux.FILTER_PCSS?(t.setDepthStencilTexture("shadowTexture"+e,n),t.setTexture("depthTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/s.getSize().width,this._contactHardeningLightSizeUVRatio*s.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/s.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),W.Pq.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(W.Pq.Dot(this._lightDirection,W.Pq.Up()))&&(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),W.uq.LookAtLHToRef(t,t.add(this._lightDirection),W.Pq.Up(),this._viewMatrix);const e=this.getShadowMap();if(e){const t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}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 e of t)this._shadowMap.renderList.push(e)}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();!0!==t.done;t=e.next()){const[e,i]=t.value;i===this&&this._light._shadowGenerators.delete(e)}0===this._light._shadowGenerators.size&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()}serialize(){const e={},t=this.getShadowMap();if(!t)return e;if(e.className=this.getClassName(),e.lightId=this._light.id,e.cameraId=this._camera?.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 i=0;i{throw(0,Je.n)("ShadowGeneratorSceneComponent")};var dx=i(2297),fx=i(6069);class px{get shaderLanguage(){return this._shaderLanguage}setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,r=!1,s=vi.g.TRILINEAR_SAMPLINGMODE,n=!1,o){this._shaderLanguage=0,this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._shadersLoaded=!1,this._scene=e,this._storeNonLinearDepth=r,this._storeCameraSpaceZ=n,this.isPacked=0===t,this.isPacked?this.clearColor=new H.ov(1,1,1,1):this.clearColor=new H.ov(n?1e8:1,0,0,1),this._initShaderSourceAsync(),px._SceneComponentInitialization(this._scene);const a=e.getEngine();this._camera=i,s!==vi.g.NEAREST_SAMPLINGMODE&&(1!==t||a._caps.textureFloatLinearFiltering||(s=vi.g.NEAREST_SAMPLINGMODE),2!==t||a._caps.textureHalfFloatLinearFiltering||(s=vi.g.NEAREST_SAMPLINGMODE));const l=this.isPacked||!a._features.supportExtendedTextureFormats?5:6;this._depthMap=new ln.$(o??"DepthRenderer",{width:a.getRenderWidth(),height:a.getRenderHeight()},this._scene,!1,!0,t,!1,s,void 0,void 0,void 0,l),this._depthMap.wrapU=vi.g.CLAMP_ADDRESSMODE,this._depthMap.wrapV=vi.g.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((e=>{e.clear(this.clearColor,!0,!0,!0)})),this._depthMap.onBeforeBindObservable.add((()=>{a._debugPushGroup?.("depth renderer",1)})),this._depthMap.onAfterUnbindObservable.add((()=>{a._debugPopGroup?.(1)})),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),r=this._scene,s=r.getEngine(),n=e.getMaterial();if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!n||i.infiniteDistance||n.disableDepthWrite||0===e.verticesCount||e._renderId===r.getRenderId())return;const o=i._getWorldMatrixDeterminant()<0;let a=n._getEffectiveOrientation(t);o&&(a=0===a?1:0);const l=0===a;s.setState(n.backFaceCulling,0,!1,l,this.reverseCulling?!n.cullBackFaces:n.cullBackFaces);const h=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(h.mustReturn)return;const c=s.getCaps().instancedArrays&&(null!==h.visibleInstances[e._id]&&void 0!==h.visibleInstances[e._id]||t.hasThinInstances),u=this._camera||r.activeCamera;if(this.isReady(e,c)&&u){e._renderId=r.getRenderId();const o=i._internalAbstractMeshDataInfo._materialForRenderPass?.[s.currentRenderPassId];let a=e._getDrawWrapper();!a&&o&&(a=o._getDrawWrapper());const l=u.mode===rt.ORTHOGRAPHIC_CAMERA;if(!a)return;const d=a.effect;let f,p;if(s.enableEffect(a),c||t._bind(e,d,n.fillMode),o?o.bindForSubMesh(i.getWorldMatrix(),i,e):(d.setMatrix("viewProjection",r.getTransformMatrix()),d.setMatrix("world",i.getWorldMatrix()),this._storeCameraSpaceZ&&d.setMatrix("view",r.getViewMatrix())),l?(f=!s.useReverseDepthBuffer&&s.isNDCHalfZRange?0:1,p=s.useReverseDepthBuffer&&s.isNDCHalfZRange?0:1):(f=s.useReverseDepthBuffer&&s.isNDCHalfZRange?u.minZ:s.isNDCHalfZRange?0:u.minZ,p=s.useReverseDepthBuffer&&s.isNDCHalfZRange?0:u.maxZ),d.setFloat2("depthValues",f,f+p),!o){if(n.needAlphaTesting()){const e=n.getAlphaTestTexture();e&&(d.setTexture("diffuseSampler",e),d.setMatrix("diffuseMatrix",e.getTextureMatrix()))}(0,Bt.f$)(t,d),(0,Ln.gS)(d,n,r),(0,Bt.nR)(t,d),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(d);const i=e.getMesh().bakedVertexAnimationManager;i&&i.isEnabled&&i.bind(d,c),n.pointsCloud&&d.setFloat("pointSize",n.pointSize)}t._processRendering(i,e,d,n.fillMode,h,c,((e,t)=>d.setMatrix("world",t)))}};this._depthMap.customRenderFunction=(e,t,i,r)=>{let s;if(r.length)for(s=0;s4&&(l.push(st.R.MatricesIndicesExtraKind),l.push(st.R.MatricesWeightsExtraKind)),a.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),r.numBoneInfluencers>0&&h.addCPUSkinningFallback(0,r);const e=r.skeleton;e.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(e.bones.length+1))}else a.push("#define NUM_BONE_INFLUENCERS 0");const c=r.morphTargetManager;let u=0;c&&(u=c.numMaxInfluencers||c.numInfluencers,u>0&&(a.push("#define MORPHTARGETS"),a.push("#define NUM_MORPH_INFLUENCERS "+u),c.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),(0,Bt.MF)(l,r,u))),o.pointsCloud&&a.push("#define POINTSIZE"),t&&(a.push("#define INSTANCES"),(0,Bt.te)(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES"));const d=r.bakedVertexAnimationManager;d&&d.isEnabled&&(a.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&l.push("bakedVertexAnimationSettingsInstanced")),this._storeNonLinearDepth&&a.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&a.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&a.push("#define PACKED"),(0,Ln.tv)(o,s,a);const f=e._getDrawWrapper(void 0,!0),p=f.defines,_=a.join("\n");if(p!==_){const e=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],t=["diffuseSampler","morphTargets","boneSampler","bakedVertexAnimationTexture"];(0,Ln.TV)(e),f.setEffect(i.createEffect("depth",{attributes:l,uniformsNames:e,uniformBuffersNames:[],samplers:t,defines:_,fallbacks:h,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:u},shaderLanguage:this._shaderLanguage},i))}return f.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]}}}px.ForceGLSL=!1,px._SceneComponentInitialization=e=>{throw(0,Je.n)("DepthRendererSceneComponent")};var _x=i(2449);Cs.l.ShadersStore.minmaxReduxPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#if defined(INITIAL)\nuniform sampler2D sourceTexture;uniform vec2 texSize;void main(void)\n{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);\n#ifdef DEPTH_REDUX\nfloat maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);\n#else\nfloat maxz=max(max(max(f1,f2),f3),f4);\n#endif\nglFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(MAIN)\nuniform vec2 texSize;void main(void)\n{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.);}\n#elif defined(ONEBEFORELAST)\nuniform ivec2 texSize;void main(void)\n{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.);}\n#elif defined(LAST)\nvoid main(void)\n{glFragColor=vec4(0.);if (true) { \ndiscard;}}\n#endif\n";class mx{constructor(e){this.onAfterReductionPerformed=new z.cP,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new _x.X(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{this._postProcessManager._rebuild()}))}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,r=!0){if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=r;const s=this._camera.getScene(),n=new ms.w("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,s.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,7);n.autoClear=!1,n.forceFullscreenViewport=r;let o=this._sourceTexture.getRenderWidth(),a=this._sourceTexture.getRenderHeight();n.onApply=((e,t)=>i=>{i.setTexture("sourceTexture",this._sourceTexture),i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(n);let l=1;for(;o>1||a>1;){o=Math.max(Math.round(o/2),1),a=Math.max(Math.round(a/2),1);const e=new ms.w("Reduction phase "+l,"minmaxRedux",["texSize"],null,{width:o,height:a},null,1,s.getEngine(),!1,"#define "+(1==o&&1==a?"LAST":1==o||1==a?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(e.autoClear=!1,e.forceFullscreenViewport=r,e.onApply=((e,t)=>i=>{1==e||1==t?i.setInt2("texSize",e,t):i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(e),l++,1==o&&1==a){const t=(e,t,i)=>{const r=new Float32Array(4*e*t),n={min:0,max:0};return()=>{s.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,r,!1),n.min=r[0],n.max=r[1],this.onAfterReductionPerformed.notifyObservers(n)}};e.onAfterRenderObservable.add(t(o,a,e))}}}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((()=>{const e=this._camera.getScene().getEngine();e._debugPushGroup?.("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),e._debugPopGroup?.(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 e=0;ethis._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 t=0;tt&&(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 Cx.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ&&0!==t.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0):this._shadowMaxZ=e}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 t=e.min,i=e.max;t>=i&&(t=0,i=1),t==this._minDistance&&i==this._maxDistance||this.setMinMaxDistance(t,i)})),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){return this._depthReducer?.depthRenderer?.getDepthMap().refreshRate??-1}set autoCalcDepthBoundsRefreshRate(e){this._depthReducer?.depthRenderer&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){const e=this._getCamera();if(!e)return;const t=e.minZ,i=e.maxZ||this._shadowMaxZ,r=i-t,s=this._minDistance,n=t+s*r,o=t+(this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance)*r,a=o-n,l=o/n;for(let e=0;e{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===ux.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((()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._debugPushGroup?.(`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!==ux.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,r=this._light;if(!i.shadowsEnabled||!r.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const s=this._getCamera();s&&this._shadowMaxZ<=(s.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),0===this.cascadeBlendPercentage&&(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 s=this.getShadowMap();if(!s)return;const n=s.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,0===this.cascadeBlendPercentage?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===ux.FILTER_PCF)t.setDepthStencilTexture("shadowTexture"+e,s),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n,1/n,this.frustumEdgeFalloff,e);else if(this._filter===ux.FILTER_PCSS){for(let e=0;enew Cx(e,t,void 0,i)));return void 0!==e.numCascades&&(i.numCascades=e.numCascades),void 0!==e.debug&&(i.debug=e.debug),void 0!==e.stabilizeCascades&&(i.stabilizeCascades=e.stabilizeCascades),void 0!==e.lambda&&(i.lambda=e.lambda),void 0!==e.cascadeBlendPercentage&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),void 0!==e.depthClamp&&(i.depthClamp=e.depthClamp),void 0!==e.autoCalcDepthBounds&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),void 0!==e.shadowMaxZ&&(i.shadowMaxZ=e.shadowMaxZ),void 0!==e.penumbraDarkness&&(i.penumbraDarkness=e.penumbraDarkness),void 0!==e.freezeShadowCastersBoundingInfo&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),void 0!==e.minDistance&&void 0!==e.maxDistance&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}}Cx._FrustumCornersNDCSpace=[new W.Pq(-1,1,-1),new W.Pq(1,1,-1),new W.Pq(1,-1,-1),new W.Pq(-1,-1,-1),new W.Pq(-1,1,1),new W.Pq(1,1,1),new W.Pq(1,-1,1),new W.Pq(-1,-1,1)],Cx.CLASSNAME="CascadedShadowGenerator",Cx.DEFAULT_CASCADES_COUNT=4,Cx.MIN_CASCADES_COUNT=2,Cx.MAX_CASCADES_COUNT=4,Cx._SceneComponentInitialization=e=>{throw(0,Je.n)("ShadowGeneratorSceneComponent")},ci(Ut.v.NAME_SHADOWGENERATOR,((e,t)=>{if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(let i=0,r=e.shadowGenerators.length;i{let t=e._getComponent(Ut.v.NAME_SHADOWGENERATOR);t||(t=new yx(e),e._addComponent(t))};var Ex=i(89778),Px=i(90396),Ax=i(32472),Rx=i(17836),Ix=i(42451),Mx=i(32166),Ox=i(16845),Dx=i(19893);Ze.b.AddNodeConstructor("Light_Type_0",((e,t)=>()=>new wx(e,W.Pq.Zero(),t)));class wx extends lm{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 e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.recreateShadowMap()}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return $t.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new W.Pq(1,0,0);case 1:return new W.Pq(-1,0,0);case 2:return new W.Pq(0,-1,0);case 3:return new W.Pq(0,1,0);case 4:return new W.Pq(0,0,1);case 5:return new W.Pq(0,0,-1)}return W.Pq.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const r=this.getScene().activeCamera;if(!r)return;const s=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,n=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;W.uq.PerspectiveFovLHToRef(this.shadowAngle,1,o?n:s,o?s: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}}(0,je.Cg)([(0,$e.lK)()],wx.prototype,"shadowAngle",null),(0,X.Y5)("BABYLON.PointLight",wx);class Nx{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{const e=this._renderingCanvas.getBoundingClientRect(),t=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position="fixed"===t?"fixed":"absolute",this._loadingDiv.style.left=e.left+"px",this._loadingDiv.style.top=e.top+"px",this._loadingDiv.style.width=e.width+"px",this._loadingDiv.style.height=e.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",this._style.innerHTML="@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }",document.getElementsByTagName("head")[0].appendChild(this._style);const e=!!window.SVGSVGElement,t=new Image;Nx.DefaultLogoUrl?t.src=Nx.DefaultLogoUrl:t.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",t.style.width="150px",t.style.gridColumn="1",t.style.gridRow="1",t.style.top="50%",t.style.left="50%",t.style.transform="translate(-50%, -50%)",t.style.position="absolute";const i=document.createElement("div");i.style.width="300px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";const r=new Image;if(Nx.DefaultSpinnerUrl?r.src=Nx.DefaultSpinnerUrl:r.src=e?"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.transformOrigin="50% 50%",!e){const e={w:16,h:18.5},i={w:30,h:30};t.style.width=`${e.w}vh`,t.style.height=`${e.h}vh`,t.style.left=`calc(50% - ${e.w/2}vh)`,t.style.top=`calc(50% - ${e.h/2}vh)`,r.style.width=`${i.w}vh`,r.style.height=`${i.h}vh`,r.style.left=`calc(50% - ${i.w/2}vh)`,r.style.top=`calc(50% - ${i.h/2}vh)`}i.appendChild(r),this._loadingDiv.appendChild(t),this._loadingDiv.appendChild(i),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){this._loadingDiv&&(this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",(()=>{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)})))}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)}}Nx.DefaultLogoUrl="",Nx.DefaultSpinnerUrl="",Ot.$.DefaultLoadingScreenFactory=e=>new Nx(e);var Fx=i(22377),Lx=i(82266);class Bx{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=(0,ar.ILog2)(t)+1,r=this._effectWrapper.effect,s=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 hc.Pq(0,0,-1),new hc.Pq(0,-1,0),new hc.Pq(1,0,0)],[new hc.Pq(0,0,1),new hc.Pq(0,-1,0),new hc.Pq(-1,0,0)],[new hc.Pq(1,0,0),new hc.Pq(0,0,1),new hc.Pq(0,1,0)],[new hc.Pq(1,0,0),new hc.Pq(0,0,-1),new hc.Pq(0,-1,0)],[new hc.Pq(1,0,0),new hc.Pq(0,-1,0),new hc.Pq(0,0,1)],[new hc.Pq(-1,0,0),new hc.Pq(0,-1,0),new hc.Pq(0,0,-1)]];r.setFloat("hdrScale",this.hdrScale),r.setFloat2("vFilteringInfo",e.getSize().width,i),r.setTexture("inputTexture",e);for(let e=0;e<6;e++){r.setVector3("up",o[e][0]),r.setVector3("right",o[e][1]),r.setVector3("front",o[e][2]);for(let n=0;n{s?await Promise.all([Promise.resolve().then(i.bind(i,44623)),Promise.resolve().then(i.bind(i,17477))]):await Promise.all([Promise.resolve().then(i.bind(i,77318)),Promise.resolve().then(i.bind(i,80424))])}})}isReady(e){return e.isReady()&&this._effectWrapper.effect.isReady()}prefilter(e,t=null){return this._engine._features.allowTexturePrefiltering?new Promise((i=>{this._effectRenderer=new Yp.J(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled((()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()}))})):(Z.V.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 Vx extends js.t{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(W.uq.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,r=!1,s=!0,n=!1,o=!1,a=null,l=null,h=!1){super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=W.Pq.Zero(),this.onLoadObservable=new z.cP,e&&(this._coordinatesMode=vi.g.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=W.uq.Identity(),this._prefilterOnLoad=o,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),a&&a()},this._onError=l,this.gammaSpace=n,this._noMipmap=r,this._size=i,this._supersample=h,this._generateHarmonics=s,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?Ue.S0.SetImmediate((()=>this._onLoad())):this._texture.onLoadedObservable.add(this._onLoad):this.getScene()?.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture())}getClassName(){return"HDRCubeTexture"}_loadTexture(){const e=this._getEngine(),t=e.getCaps();let i=0;if(t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2),e._features.allowTexturePrefiltering&&this._prefilterOnLoad){const t=this._onLoad,i=new Bx(e);this._onLoad=()=>{i.prefilter(this,t)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,(e=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;const t=(0,Fx.VH)(e,this._size,this._supersample);if(this._generateHarmonics){const e=Lx.d.ConvertCubeMapToSphericalPolynomial(t);this.sphericalPolynomial=e}const r=[];let s=null,n=null;for(let e=0;e<6;e++){2===i?n=new Uint16Array(this._size*this._size*3):0===i&&(s=new Uint8Array(this._size*this._size*3));const o=t[Vx._FacesMapping[e]];if(this.gammaSpace||n||s)for(let e=0;e255){const e=255/n;t*=e,i*=e,r*=e}s[3*e+0]=t,s[3*e+1]=i,s[3*e+2]=r}n?r.push(n):s?r.push(s):r.push(o)}return r}),null,this._onLoad,this._onError)}clone(){const e=new Vx(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(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this._loadTexture())}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&this.getScene()?.markAllMaterialsAsDirty(1,(e=>-1!==e.getActiveTextures().indexOf(this)))}dispose(){this.onLoadObservable.clear(),super.dispose()}static Parse(e,t,i){let r=null;return e.name&&!e.isRenderTarget&&(r=new Vx(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace),r.name=e.name,r.hasAlpha=e.hasAlpha,r.level=e.level,r.coordinatesMode=e.coordinatesMode,r.isBlocking=e.isBlocking),r&&(e.boundingBoxPosition&&(r.boundingBoxPosition=W.Pq.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=W.Pq.FromArray(e.boundingBoxSize)),e.rotationY&&(r.rotationY=e.rotationY)),r}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e}}Vx._FacesMapping=["right","left","up","down","front","back"],(0,X.Y5)("BABYLON.HDRCubeTexture",Vx);class kx{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(0===t||0===e)}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 z.cP,this._onDataLayoutChanged=new z.cP,this._animationPropertiesOverride=null,this.id=e,this._scene=i||he.q.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=it.p.Clone((()=>new kx(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()),null!=this.id&&(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())),it.p.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new kx(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(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 t=0;t0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new Qe.L(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._numMaxInfluencers=0,this._useTextureToStoreTargets=!0,e||(e=he.q.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();const e=this._scene.getEngine().getCaps();this._canUseTextureForTargets=e.canUseGLVertexID&&e.textureFloat&&e.maxVertexTextureImageUnits>0&&e.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(){return Gx.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!this._scene?.getEngine().getCaps().disableMorphTargetTexture}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}getTargetByName(e){for(const t of this._targets)if(t.name===e)return t;return null}addTarget(e){this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add((e=>{this._syncActiveTargets(e)}))),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 Gx(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 e of this._targets){if(i++,0===e.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=Gx.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(e),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=e.influence,this._supportsNormals=this._supportsNormals&&e.hasNormals,this._supportsTangents=this._supportsTangents&&e.hasTangents,this._supportsUVs=this._supportsUVs&&e.hasUVs;const r=e.getPositions();if(r){const e=r.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e)return void Z.V.Error("Incompatible target. Targets must all have the same vertices count.")}}this._morphTargetTextureIndices.length!==t&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,t)),this._influences&&this._influences.length===t||(this._influences=new Float32Array(t));for(let e=0;e0)){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 e=this._targetStoreTexture.getSize();e.width===this._textureWidth&&e.height===this._textureHeight&&this._targetStoreTexture.depth===this._targets.length&&(t=!1)}if(t){this._targetStoreTexture&&this._targetStoreTexture.dispose();const e=this._targets.length,t=new Float32Array(e*this._textureWidth*this._textureHeight*4);let i=0;for(let r=0;r-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 Gx(t);for(const r of e.targets)i.addTarget(kx.Parse(r,t));return i}}Gx.EnableTextureStorage=!0,Gx.MaxActiveMorphTargetsInVertexAttributeMode=8;class zx{constructor(){this._hasHit=!1,this._hitNormal=W.Pq.Zero(),this._hitPoint=W.Pq.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 Wx extends zx{constructor(){super(...arguments),this._hitDistance=0,this._rayFromWorld=W.Pq.Zero(),this._rayToWorld=W.Pq.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=W.Pq.Distance(this._rayFromWorld,this._hitPoint)}reset(e=W.Pq.Zero(),t=W.Pq.Zero()){super.reset(),this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hitDistance=0}}class Hx{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw(0,Je.n)("CannonJSPlugin")}constructor(e,t=Hx.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 W.Pq(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._impostors.forEach((function(e){e.dispose()})),this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}addImpostor(e){this._impostors.push(e),e.uniqueId=this._uniqueIdCounter++,e.parent||this._physicsPlugin.generatePhysicsBody(e)}removeImpostor(e){const t=this._impostors.indexOf(e);t>-1&&this._impostors.splice(t,1).length&&this.getPhysicsPlugin().removePhysicsBody(e)}addJoint(e,t,i){const r={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(r),this._physicsPlugin.generateJoint(r)}removeJoint(e,t,i){const r=this._joints.filter((function(r){return r.connectedImpostor===t&&r.joint===i&&r.mainImpostor===e}));r.length&&this._physicsPlugin.removeJoint(r[0])}_step(e){this._impostors.forEach((e=>{e.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(e)})),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=>{"function"==typeof this.world.removeBody?this.world.removeBody(e):this.world.remove(e)})),this._physicsBodiesToRemoveAfterStep.length=0)}applyImpulse(e,t,i){const r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(s,r)}applyForce(e,t,i){const r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(s,r)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){const t=this._createShape(e);if(!t)return void Z.V.Warn("It was not possible to create a physics body for this object.");const i=e.physicsBody;i&&this.removePhysicsBody(e);const r=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),s={mass:e.getParam("mass"),material:r},n=e.getParam("nativeOptions");for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(s[e]=n[e]);e.physicsBody=new this.BJSCANNON.Body(s),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),"function"==typeof this.world.addBody?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach((function(t){const r=i[t];e.physicsBody[t].set(r.x,r.y,r.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 i=t=>{if(!t.rotationQuaternion)return;const r=t.getPhysicsImpostor();if(r&&r.parent!==e&&t.parent){const i=t.getAbsolutePosition().subtract(t.parent.getAbsolutePosition()),s=t.rotationQuaternion.multiply(this._tmpQuaternion);r.physicsBody&&(this.removePhysicsBody(r),r.physicsBody=null),r.parent=e,r.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(r),new this.BJSCANNON.Vec3(i.x,i.y,i.z),new this.BJSCANNON.Quaternion(s.x,s.y,s.z,s.w)),e.physicsBody.mass+=r.getParam("mass")}t.getChildMeshes(!0).filter((e=>!!e.physicsImpostor)).forEach(i)};t.filter((e=>!!e.physicsImpostor)).forEach(i)}}removePhysicsBody(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),-1===this._physicsBodiesToRemoveAfterStep.indexOf(e.physicsBody)&&this._physicsBodiesToRemoveAfterStep.push(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;let r;const s=e.joint.jointData,n={pivotA:s.mainPivot?(new this.BJSCANNON.Vec3).set(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z):null,pivotB:s.connectedPivot?(new this.BJSCANNON.Vec3).set(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z):null,axisA:s.mainAxis?(new this.BJSCANNON.Vec3).set(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z):null,axisB:s.connectedAxis?(new this.BJSCANNON.Vec3).set(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z):null,maxForce:s.nativeParams.maxForce,collideConnected:!!s.collision};switch(e.joint.type){case Jo.HingeJoint:case Jo.Hinge2Joint:r=new this.BJSCANNON.HingeConstraint(t,i,n);break;case Jo.DistanceJoint:r=new this.BJSCANNON.DistanceConstraint(t,i,s.maxDistance||2);break;case Jo.SpringJoint:{const e=s;r=new this.BJSCANNON.Spring(t,i,{restLength:e.length,stiffness:e.stiffness,damping:e.damping,localAnchorA:n.pivotA,localAnchorB:n.pivotB});break}case Jo.LockJoint:r=new this.BJSCANNON.LockConstraint(t,i,n);break;case Jo.PointToPointJoint:case Jo.BallAndSocketJoint:default:r=new this.BJSCANNON.PointToPointConstraint(t,n.pivotA,i,n.pivotB,n.maxForce)}r.collideConnected=!!s.collision,e.joint.physicsJoint=r,e.joint.type!==Jo.SpringJoint?this.world.addConstraint(r):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){r.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==Jo.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let r,s;for(r=0;r1e3*i));e++);this.time+=r;const a=this.time%i/i,l=e,h=this.bodies;for(let e=0;e!==h.length;e++){const i=h[e];i.type!==t.Body.STATIC&&i.sleepState!==t.Body.SLEEPING?(i.position.vsub(i.previousPosition,l),l.scale(a,l),i.position.vadd(l,i.interpolatedPosition)):(i.interpolatedPosition.set(i.position.x,i.position.y,i.position.z),i.interpolatedQuaternion.set(i.quaternion.x,i.quaternion.y,i.quaternion.z,i.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))}}Hx.DefaultPluginFactory=()=>new Xx;class qx{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=W.Pq.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new Wx}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(e){e.beforeStep()})),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach((e=>{e.afterStep(),this._tmpImpostorsArray[e.uniqueId]=e}));let i=this.world.contacts;for(;null!==i;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}const e=this._tmpImpostorsArray[+i.body1.name],t=this._tmpImpostorsArray[+i.body2.name];e&&t?(e.onCollide({body:t.physicsBody,point:null,distance:0,impulse:0,normal:null}),t.onCollide({body:e.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next):i=i.next}}applyImpulse(e,t,i){const r=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*r))}applyForce(e,t,i){Z.V.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());else{if(e.isBodyInitRequired()){const i={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},r=[e];(t=e.object).getChildMeshes&&t.getChildMeshes().forEach((function(e){e.physicsImpostor&&r.push(e.physicsImpostor)}));const s=e=>Math.max(e,lt.bH),n=new W.PT;r.forEach((t=>{if(!t.object.rotationQuaternion)return;const r=t.object.rotationQuaternion;n.copyFrom(r),t.object.rotationQuaternion.set(0,0,0,1),t.object.computeWorldMatrix(!0);const o=n.toEulerAngles(),a=t.getObjectExtents(),l=57.29577951308232;if(t===e){const t=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(t,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),i.pos.push(t.x),i.pos.push(t.y),i.pos.push(t.z),i.posShape.push(0,0,0),i.rotShape.push(0,0,0)}else{const e=t.object.position.clone();i.posShape.push(e.x),i.posShape.push(e.y),i.posShape.push(e.z),i.rotShape.push(o.x*l,o.y*l,o.z*l)}switch(t.object.rotationQuaternion.copyFrom(n),t.type){case sa.ParticleImpostor:Z.V.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case sa.SphereImpostor:{const e=a.x,t=a.y,r=a.z,n=Math.max(s(e),s(t),s(r))/2;i.type.push("sphere"),i.size.push(n),i.size.push(n),i.size.push(n);break}case sa.CylinderImpostor:{const e=s(a.x)/2,t=s(a.y);i.type.push("cylinder"),i.size.push(e),i.size.push(t),i.size.push(t);break}case sa.PlaneImpostor:case sa.BoxImpostor:default:{const e=s(a.x),t=s(a.y),r=s(a.z);i.type.push("box"),i.size.push(e),i.size.push(t),i.size.push(r);break}}t.object.rotationQuaternion=r})),e.physicsBody=this.world.add(i),e.physicsBody.resetQuaternion(n),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpPositionVector)}var t}removePhysicsBody(e){this.world.removeRigidBody(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const r=e.joint.jointData,s=r.nativeParams||{};let n;const o={body1:t,body2:i,axe1:s.axe1||(r.mainAxis?r.mainAxis.asArray():null),axe2:s.axe2||(r.connectedAxis?r.connectedAxis.asArray():null),pos1:s.pos1||(r.mainPivot?r.mainPivot.asArray():null),pos2:s.pos2||(r.connectedPivot?r.connectedPivot.asArray():null),min:s.min,max:s.max,collision:s.collision||r.collision,spring:s.spring,world:this.world};switch(e.joint.type){case Jo.BallAndSocketJoint:n="jointBall";break;case Jo.SpringJoint:{Z.V.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");const e=r;o.min=e.length||o.min,o.max=Math.max(o.min,o.max)}case Jo.DistanceJoint:n="jointDistance",o.max=r.maxDistance;break;case Jo.PrismaticJoint:n="jointPrisme";break;case Jo.SliderJoint:n="jointSlide";break;case Jo.WheelJoint:n="jointWheel";break;case Jo.HingeJoint:default:n="jointHinge"}o.type=n,e.joint.physicsJoint=this.world.add(o)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(e){Z.V.Warn(e)}}isSupported(){return void 0!==this.BJSOIMO}setTransformationFromPhysicsBody(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){let t=e.physicsBody.shapes;for(;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{const t=e.physicsBody.getPosition();e.object.position.set(t.x,t.y,t.z)}if(e.object.rotationQuaternion){const t=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}}setPhysicsBodyTransformation(e,t,i){const r=e.physicsBody;e.physicsBody.shapes.next||(r.position.set(t.x,t.y,t.z),r.orientation.set(i.x,i.y,i.z,i.w),r.syncShapes(),r.awake())}setLinearVelocity(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){const t=e.physicsBody.linearVelocity;return t?new W.Pq(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new W.Pq(t.x,t.y,t.z):null}setBodyMass(e,t){const i=0===t;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,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,r){void 0!==i?Z.V.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;const s=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setMotor(t,i)}setLimit(e,t,i,r){const s=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setLimit(t,void 0===i?-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=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth}dispose(){this.world.clear()}raycast(e,t){return Z.V.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){Z.V.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class Yx{constructor(e=!0,t=Ammo,i=null){this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new W.PT,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new W.Pq,this._tmpContactNormal=new W.Pq,this._tmpVec3=new W.Pq,this._tmpMatrix=new W.uq,"function"!=typeof t?(this.bjsAMMO=t,this.isSupported()?(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=e=>{const t=(e=this.bjsAMMO.wrapPointer(e,this.bjsAMMO.btManifoldPoint)).getPositionWorldOnA(),i=e.m_normalWorldOnB;this._tmpContactPoint.x=t.x(),this._tmpContactPoint.y=t.y(),this._tmpContactPoint.z=t.z(),this._tmpContactNormal.x=i.x(),this._tmpContactNormal.y=i.y(),this._tmpContactNormal.z=i.z(),this._tmpContactImpulse=e.getAppliedImpulse(),this._tmpContactDistance=e.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new Wx,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)):Z.V.Error("AmmoJS is not available. Please make sure you included the js file.")):Z.V.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.")}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(0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i0&&this._isImpostorInContact(e))for(const t of e._onPhysicsCollideCallbacks)for(const i of t.otherImpostors)(e.physicsBody.isActive()||i.physicsBody.isActive())&&this._isImpostorPairInContact(e,i)&&(e.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),i.onCollide({body:e.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===sa.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){const t=e.physicsBody.get_m_nodes(),i=t.size();let r,s,n,o,a;const l=new Array;for(let e=0;e{this.bjsAMMO.destroy(e)})),e._pluginData.toDispose=[]))}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;if(e.joint.physicsJoint)return;const r=e.joint.jointData;let s;switch(r.mainPivot||(r.mainPivot=new W.Pq(0,0,0)),r.connectedPivot||(r.connectedPivot=new W.Pq(0,0,0)),e.joint.type){case Jo.DistanceJoint:{const e=r.maxDistance;e&&(r.mainPivot=new W.Pq(0,-e/2,0),r.connectedPivot=new W.Pq(0,e/2,0));const n=this._tmpAmmoVectorA;n.setValue(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z);const o=this._tmpAmmoVectorB;o.setValue(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z),s=new this.bjsAMMO.btPoint2PointConstraint(t,i,n,o);break}case Jo.HingeJoint:{r.mainAxis||(r.mainAxis=new W.Pq(0,0,0)),r.connectedAxis||(r.connectedAxis=new W.Pq(0,0,0));const e=this._tmpAmmoVectorA;e.setValue(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z);const n=this._tmpAmmoVectorB;n.setValue(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z);const o=this._tmpAmmoVectorC;o.setValue(r.mainAxis.x,r.mainAxis.y,r.mainAxis.z);const a=this._tmpAmmoVectorD;a.setValue(r.connectedAxis.x,r.connectedAxis.y,r.connectedAxis.z),s=new this.bjsAMMO.btHingeConstraint(t,i,e,n,o,a);break}case Jo.BallAndSocketJoint:{const e=this._tmpAmmoVectorA;e.setValue(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z);const n=this._tmpAmmoVectorB;n.setValue(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z),s=new this.bjsAMMO.btPoint2PointConstraint(t,i,e,n);break}default:{Z.V.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint");const e=this._tmpAmmoVectorA;e.setValue(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z);const n=this._tmpAmmoVectorB;n.setValue(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z),s=new this.bjsAMMO.btPoint2PointConstraint(t,i,e,n);break}}this.world.addConstraint(s,!e.joint.jointData.collision),e.joint.physicsJoint=s}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint),this.bjsAMMO.destroy(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let n,o=i.getVerticesData(st.R.PositionKind);if(o||(o=[]),t&&t!==i){let e;e=t.rotationQuaternion?t.rotationQuaternion:t.rotation?W.PT.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):W.PT.Identity(),W.uq.Compose(W.Pq.One(),e,t.position).invertToRef(this._tmpMatrix),n=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else W.uq.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),n=this._tmpMatrix;const a=s.length/3;for(let t=0;t{r+=this._addMeshVerts(e,t,i)}))}return r}_softVertexData(e){const t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){let e=t.getIndices();e||(e=[]);let i=t.getVerticesData(st.R.PositionKind);i||(i=[]);let r=t.getVerticesData(st.R.NormalKind);r||(r=[]),t.computeWorldMatrix(!1);const s=[],n=[];for(let e=0;ee*e)).reduce(((e,t)=>e+t)))t=s.length,i=t/3-1,this._tmpAmmoVectorA.setValue(s[0],s[1],s[2]),this._tmpAmmoVectorB.setValue(s[t-3],s[t-2],s[t-1]);else{e._isFromLine=!1;const r=e.getParam("path");if(null===e.getParam("shape"))return Z.V.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;t=r.length,i=t-1,this._tmpAmmoVectorA.setValue(r[0].x,r[0].y,r[0].z),this._tmpAmmoVectorB.setValue(r[t-1].x,r[t-1].y,r[t-1].z)}e.segments=i;let o=e.getParam("fixedPoints");o=o>3?3:o;const a=(new this.bjsAMMO.btSoftBodyHelpers).CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,o);return a.get_m_cfg().set_collisions(17),a}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),null==t&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let n=i.getVerticesData(st.R.PositionKind);n||(n=[]),i.computeWorldMatrix(!1);const o=s.length/3;for(let t=0;t{r+=this._addHullVerts(e,t,i)}))}return r}_createShape(e,t=!1){const i=e.object;let r;const s=e.getObjectExtents();if(!t){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];r=new this.bjsAMMO.btCompoundShape;let i=0;if(t.forEach((e=>{const t=e.getPhysicsImpostor();if(t){if(t.type==sa.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";const s=this._createShape(t),n=e.parent.getWorldMatrix().clone(),o=new W.Pq;n.decompose(o),this._tmpAmmoTransform.getOrigin().setValue(e.position.x*o.x,e.position.y*o.y,e.position.z*o.z),this._tmpAmmoQuaternion.setValue(e.rotationQuaternion.x,e.rotationQuaternion.y,e.rotationQuaternion.z,e.rotationQuaternion.w),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),r.addChildShape(this._tmpAmmoTransform,s),t.dispose(),i++}})),i>0){if(e.type!=sa.NoImpostor){const t=this._createShape(e,!0);t&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),r.addChildShape(this._tmpAmmoTransform,t))}return r}this.bjsAMMO.destroy(r),r=null}switch(e.type){case sa.SphereImpostor:if((0,ar.WithinEpsilon)(s.x,s.y,1e-4)&&(0,ar.WithinEpsilon)(s.x,s.z,1e-4))r=new this.bjsAMMO.btSphereShape(s.x/2);else{this._tmpAmmoVectorA.setValue(0,0,0);const e=[this._tmpAmmoVectorA],t=[1];r=new this.bjsAMMO.btMultiSphereShape(e,t,1),this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),r.setLocalScaling(this._tmpAmmoVectorA)}break;case sa.CapsuleImpostor:{const e=s.x/2;r=new this.bjsAMMO.btCapsuleShape(e,s.y-2*e)}break;case sa.CylinderImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),r=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case sa.PlaneImpostor:case sa.BoxImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),r=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case sa.MeshImpostor:if(0==e.getParam("mass")){if(this.onCreateCustomMeshImpostor)r=this.onCreateCustomMeshImpostor(e);else{const t=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(t);const s=this._addMeshVerts(t,i,i);r=0==s?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(t)}break}case sa.ConvexHullImpostor:if(this.onCreateCustomConvexHullImpostor)r=this.onCreateCustomConvexHullImpostor(e);else{const t=new this.bjsAMMO.btConvexHullShape;0==this._addHullVerts(t,i,i)?(e._pluginData.toDispose.push(t),r=new this.bjsAMMO.btCompoundShape):r=t}break;case sa.NoImpostor:r=new this.bjsAMMO.btSphereShape(s.x/2);break;case sa.CustomImpostor:r=this._createCustom(e);break;case sa.SoftbodyImpostor:r=this._createSoftbody(e);break;case sa.ClothImpostor:r=this._createCloth(e);break;case sa.RopeImpostor:r=this._createRope(e);break;default:Z.V.Warn("The impostor type is not currently supported by the ammo plugin.")}return r}setTransformationFromPhysicsBody(e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),e.object.rotationQuaternion?e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):e.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))}setPhysicsBodyTransformation(e,t,i){const r=e.physicsBody.getWorldTransform();if(Math.abs(r.getOrigin().x()-t.x)>lt.bH||Math.abs(r.getOrigin().y()-t.y)>lt.bH||Math.abs(r.getOrigin().z()-t.z)>lt.bH||Math.abs(r.getRotation().x()-i.x)>lt.bH||Math.abs(r.getRotation().y()-i.y)>lt.bH||Math.abs(r.getRotation().z()-i.z)>lt.bH||Math.abs(r.getRotation().w()-i.w)>lt.bH)if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),r.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),r.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(r),0==e.mass){const t=e.physicsBody.getMotionState();t&&t.setWorldTransform(r)}else e.physicsBody.activate()}isSupported(){return void 0!==this.bjsAMMO}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(t=e.soft?e.physicsBody.linearVelocity():e.physicsBody.getLinearVelocity(),!t)return null;const i=new W.Pq(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}getAngularVelocity(e){let t;if(t=e.soft?e.physicsBody.angularVelocity():e.physicsBody.getAngularVelocity(),!t)return null;const i=new W.Pq(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:(Z.V.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===sa.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):Z.V.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(Z.V.Warn("Stiffness is not a property of a rigid body"),0)}setBodyStiffness(e,t){e.soft?(t=(t=t<0?0:t)>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):Z.V.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(Z.V.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):Z.V.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(Z.V.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):Z.V.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,r,s=1,n=!1){const o=e.segments,a=Math.round((o-1)*i)+o*(o-1-Math.round((o-1)*r));e.physicsBody.appendAnchor(a,t.physicsBody,n,s)}appendHook(e,t,i,r=1,s=!1){const n=Math.round(e.segments*i);e.physicsBody.appendAnchor(n,t.physicsBody,s,r)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){Z.V.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){Z.V.Warn("setLimit is not currently supported by the Ammo physics plugin")}syncMeshWithImpostor(e,t){t.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.position.x=this._tmpAmmoTransform.getOrigin().x(),e.position.y=this._tmpAmmoTransform.getOrigin().y(),e.position.z=this._tmpAmmoTransform.getOrigin().z(),e.rotationQuaternion&&(e.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),e.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),e.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),e.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())}getRadius(e){return e.getObjectExtents().x/2}getBoxSizeToRef(e,t){const i=e.getObjectExtents();t.x=i.x,t.y=i.y,t.z=i.z}dispose(){this.bjsAMMO.destroy(this.world),this.bjsAMMO.destroy(this._softBodySolver),this.bjsAMMO.destroy(this._solver),this.bjsAMMO.destroy(this._overlappingPairCache),this.bjsAMMO.destroy(this._dispatcher),this.bjsAMMO.destroy(this._collisionConfiguration),this.bjsAMMO.destroy(this._tmpAmmoVectorA),this.bjsAMMO.destroy(this._tmpAmmoVectorB),this.bjsAMMO.destroy(this._tmpAmmoVectorC),this.bjsAMMO.destroy(this._tmpAmmoVectorD),this.bjsAMMO.destroy(this._tmpAmmoTransform),this.bjsAMMO.destroy(this._tmpAmmoQuaternion),this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null}raycast(e,t){return this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(e.x,e.y,e.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(t.x,t.y,t.z);const r=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,r),i.reset(e,t),r.hasHit()&&(i.setHitData({x:r.get_m_hitNormalWorld().x(),y:r.get_m_hitNormalWorld().y(),z:r.get_m_hitNormalWorld().z()},{x:r.get_m_hitPointWorld().x(),y:r.get_m_hitPointWorld().y(),z:r.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(r),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}}Yx._DISABLE_COLLISION_FLAG=4,Yx._KINEMATIC_FLAG=2,Yx._DISABLE_DEACTIVATION_FLAG=4,oi.Z.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return-1;const t=this.reflectionProbes.indexOf(e);return-1!==t&&this.reflectionProbes.splice(t,1),t},oi.Z.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};class Kx{constructor(e,t,i,r=!0,s=!1,n=!1){if(this.name=e,this._viewMatrix=W.uq.Identity(),this._target=W.Pq.Zero(),this._add=W.Pq.Zero(),this._invertYAxis=!1,this.position=W.Pq.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(let t=0;t<6;++t)this._sceneUBOs.push(i.createSceneUniformBuffer(`Scene for Reflection Probe (name "${e}") face #${t}`))}this._scene.reflectionProbes||(this._scene.reflectionProbes=[]),this._scene.reflectionProbes.push(this);let o=0;if(s){const e=this._scene.getEngine().getCaps();e.textureHalfFloatRender?o=2:e.textureFloatRender&&(o=1)}this._renderTargetTexture=new ln.$(e,t,i,r,!0,o,!0),this._renderTargetTexture.gammaSpace=!n,this._renderTargetTexture.invertZ=i.useRightHandedSystem;const a=i.getEngine().useReverseDepthBuffer;let l;this._renderTargetTexture.onBeforeRenderObservable.add((e=>{switch(this._sceneUBOs&&(i.setSceneUniformBuffer(this._sceneUBOs[e]),i.getSceneUniformBuffer().unbindEffect()),e){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)}this._attachedMesh&&this.position.copyFrom(this._attachedMesh.getAbsolutePosition()),this.position.addToRef(this._add,this._target);const t=i.useRightHandedSystem?W.uq.LookAtRHToRef:W.uq.LookAtLHToRef,r=i.useRightHandedSystem?W.uq.PerspectiveFovRH:W.uq.PerspectiveFovLH;t(this.position,this._target,W.Pq.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=r(Math.PI/2,1,a?i.activeCamera.maxZ:i.activeCamera.minZ,a?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})),this._renderTargetTexture.onBeforeBindObservable.add((()=>{this._currentSceneUBO=i.getSceneUniformBuffer(),i.getEngine()._debugPushGroup?.(`reflection probe generation for ${e}`,1),l=this._scene.imageProcessingConfiguration.applyByPostProcess,n&&(i.imageProcessingConfiguration.applyByPostProcess=!0)})),this._renderTargetTexture.onAfterUnbindObservable.add((()=>{i.imageProcessingConfiguration.applyByPostProcess=l,i._forcedViewPosition=null,this._sceneUBOs&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(!0),i.getEngine()._debugPopGroup?.(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(-1!==e&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){const e=this._parentContainer.reflectionProbes.indexOf(this);e>-1&&this._parentContainer.reflectionProbes.splice(e,1),this._parentContainer=null}if(this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null),this._sceneUBOs){for(const e of this._sceneUBOs)e.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=it.p.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let r=null;if(t.reflectionProbes)for(let i=0;ir||new Kx(e.name,e.renderTargetSize,t,e._generateMipMaps)),e,t,i),r.cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&r.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(r.metadata=e.metadata),r}}(0,je.Cg)([(0,$e.xG)()],Kx.prototype,"_attachedMesh",void 0),(0,je.Cg)([(0,$e.P_)()],Kx.prototype,"position",void 0);class jx{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,r,s){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=r||1,this._animationStarted=!0,this._onBaseAnimationEnd=s,ethis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}}class $x extends jx{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 z.cP,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new H.ov(1,1,1,1),this.position=W.Pq.Zero(),this._manager=t,this._manager.sprites.push(this),this.uniqueId=this._manager.scene.getUniqueId()}getClassName(){return"Sprite"}get fromIndex(){return this._fromIndex}set fromIndex(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)}get toIndex(){return this._toIndex}set toIndex(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)}get delay(){return Math.max(this._delay,1)}set delay(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)}playAnimation(e,t,i,r,s=null){this._onAnimationEnd=s,super.playAnimation(e,t,i,r,this._endAnimation)}dispose(){for(let e=0;e0)for(let n=0;n=s.distance))&&(s=a,i))break}return s||new At.G},oi.Z.prototype._internalMultiPickSprites=function(e,t,i){if(!At.G)return null;let r=[];if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let s=0;s!!e.actionManager&&e.isPickable&&e.actionManager.hasPointerTriggers}register(){this.scene._pointerMoveStage.registerStep(Ut.v.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(Ut.v.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(Ut.v.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();const e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,r,s){const n=this.scene.pickSprite(t,i,this._spritePredicate,r,s);return n&&(n.ray=e?e.ray:null),n}_pointerMove(e,t,i,r,s){const n=this.scene;return r?n.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,n.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(n.setPointerOverSprite(i.pickedSprite),!n.doNotHandleCursors&&s&&(n._pointerOverSprite&&n._pointerOverSprite.actionManager&&n._pointerOverSprite.actionManager.hoverCursor?s.style.cursor=n._pointerOverSprite.actionManager.hoverCursor:s.style.cursor=n.hoverCursor)):n.setPointerOverSprite(null),i}_pointerDown(e,t,i,r){const s=this.scene;if(s._pickedDownSprite=null,s.spriteManagers&&s.spriteManagers.length>0&&(i=s.pickSprite(e,t,this._spritePredicate,!1,s.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(s._pickedDownSprite=i.pickedSprite,r.button){case 0:i.pickedSprite.actionManager.processTrigger(2,Y.X.CreateNewFromSprite(i.pickedSprite,s,r));break;case 1:i.pickedSprite.actionManager.processTrigger(4,Y.X.CreateNewFromSprite(i.pickedSprite,s,r));break;case 2:i.pickedSprite.actionManager.processTrigger(3,Y.X.CreateNewFromSprite(i.pickedSprite,s,r))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,Y.X.CreateNewFromSprite(i.pickedSprite,s,r))}return i}_pointerUp(e,t,i,r,s){const n=this.scene;if(n.spriteManagers&&n.spriteManagers.length>0){const i=n.pickSprite(e,t,this._spritePredicate,!1,n.cameraToUseForPointers||void 0);i&&(i.hit&&i.pickedSprite&&i.pickedSprite.actionManager&&(i.pickedSprite.actionManager.processTrigger(7,Y.X.CreateNewFromSprite(i.pickedSprite,n,r)),i.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||i.pickedSprite.actionManager.processTrigger(1,Y.X.CreateNewFromSprite(i.pickedSprite,n,r)),s&&i.pickedSprite.actionManager.processTrigger(6,Y.X.CreateNewFromSprite(i.pickedSprite,n,r)))),n._pickedDownSprite&&n._pickedDownSprite.actionManager&&n._pickedDownSprite!==i.pickedSprite&&n._pickedDownSprite.actionManager.processTrigger(16,Y.X.CreateNewFromSprite(n._pickedDownSprite,n,r)))}return i}}class Zx{get fogEnabled(){return this._fogEnabled}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this._createEffects())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){const t=!!this._scene?.getEngine().getCaps().fragmentDepthSupported;e&&!t&&Z.V.Warn("Logarithmic depth has been requested for a sprite renderer on a device that doesn't support it."),this._useLogarithmicDepth=e&&t,this._createEffects()}get capacity(){return this._capacity}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(e){this._pixelPerfect!==e&&(this._pixelPerfect=e,this._createEffects())}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i=.01,r=null,s){this.blendMode=2,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this._fogEnabled=!0,this._pixelPerfect=!1,this._shaderLanguage=0,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._isDisposed=!1,this._shadersLoaded=!1,this._pixelPerfect=s?.pixelPerfect??!1,this._capacity=t,this._epsilon=i,this._engine=e,this._useInstancing=e.getCaps().instancedArrays&&e._features.supportSpriteInstancing,this._useVAO=e.getCaps().vertexArrayObject&&!e.disableVertexArrayObjects,this._scene=r,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new st.h(e,this._vertexData,!0,this._vertexBufferSize);const n=this._buffer.createVertexBuffer(st.R.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),o=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing);let a,l=6;if(this._useInstancing){const t=new Float32Array([this._epsilon,this._epsilon,1-this._epsilon,this._epsilon,this._epsilon,1-this._epsilon,1-this._epsilon,1-this._epsilon]);this._spriteBuffer=new st.h(e,t,!1,2),a=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else a=this._buffer.createVertexBuffer("offsets",l,2,this._vertexBufferSize,this._useInstancing),l+=2;const h=this._buffer.createVertexBuffer("inverts",l,2,this._vertexBufferSize,this._useInstancing),c=this._buffer.createVertexBuffer("cellInfo",l+2,4,this._vertexBufferSize,this._useInstancing),u=this._buffer.createVertexBuffer(st.R.ColorKind,l+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[st.R.PositionKind]=n,this._vertexBuffers.options=o,this._vertexBuffers.offsets=a,this._vertexBuffers.inverts=h,this._vertexBuffers.cellInfo=c,this._vertexBuffers[st.R.ColorKind]=u,this._initShaderSourceAsync()}async _initShaderSourceAsync(){this._engine.isWebGPU&&!Zx.ForceGLSL?(this._shaderLanguage=1,await Promise.all([Promise.resolve().then(i.bind(i,56029)),Promise.resolve().then(i.bind(i,25151))])):await Promise.all([Promise.resolve().then(i.bind(i,3290)),Promise.resolve().then(i.bind(i,3916))]),this._shadersLoaded=!0,this._createEffects()}_createEffects(){if(this._isDisposed||!this._shadersLoaded)return;this._drawWrapperBase?.dispose(),this._drawWrapperDepth?.dispose(),this._drawWrapperBase=new gt.E(this._engine),this._drawWrapperDepth=new gt.E(this._engine,!1),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing);let e="";this._pixelPerfect&&(e+="#define PIXEL_PERFECT\n"),this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode&&this._fogEnabled&&(e+="#define FOG\n"),this._useLogarithmicDepth&&(e+="#define LOGARITHMICDEPTH\n"),this._drawWrapperBase.effect=this._engine.createEffect("sprites",[st.R.PositionKind,"options","offsets","inverts","cellInfo",st.R.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor","logarithmicDepthConstant"],["diffuseSampler"],e,void 0,void 0,void 0,void 0,this._shaderLanguage),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext}render(e,t,i,r,s=null){if(!(this._shadersLoaded&&this.texture&&this.texture.isReady()&&e.length))return;const n=this._drawWrapperBase,o=this._drawWrapperDepth,a=this.fogEnabled&&this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode,l=n.effect;if(!l.isReady())return;const h=this._engine,c=!(!this._scene||!this._scene.useRightHandedSystem),u=Math.min(this._capacity,e.length);let d=0,f=!0;for(let i=0;i{e.cellRef||(e.cellIndex=0);const i=e.cellIndex;"number"==typeof i&&isFinite(i)&&Math.floor(i)===i&&(e.cellRef=this._spriteMap[e.cellIndex]),e._xOffset=this._cellData[e.cellRef].frame.x/t.width,e._yOffset=this._cellData[e.cellRef].frame.y/t.height,e._xSize=this._cellData[e.cellRef].frame.w,e._ySize=this._cellData[e.cellRef].frame.h},s||(s=he.q.LastCreatedScene),s._getComponent(Ut.v.NAME_SPRITE)||s._addComponent(new Qx(s)),this._fromPacked=a,this._scene=s;const c=this._scene.getEngine();if(this._spriteRenderer=new Zx(c,i,n,s,h?.spriteRendererOptions),r.width&&r.height)this.cellWidth=r.width,this.cellHeight=r.height;else{if(void 0===r)return void(this._spriteRenderer=null);this.cellWidth=r,this.cellHeight=r}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new vi.g(t,s,!0,!1,o)),this._fromPacked&&this._makePacked(t,l)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(null!==t)try{let e;if(e="string"==typeof t?JSON.parse(t):t,e.frames.length){const t={};for(let i=0;i0);const r=e.substring(0,i-1)+".json",s=()=>{Z.V.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1},n=e=>{try{const t=JSON.parse(e),i=Reflect.ownKeys(t.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=t.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON format. Please check documentation for format specifications.")}};Ue.S0.LoadFile(r,n,void 0,void 0,!1,s)}}_checkTextureAlpha(e,t,i,r,s){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.AA.Vector3[0];o.copyFrom(t.direction),o.normalize(),o.scaleInPlace(i),o.addInPlace(t.origin);const a=(o.x-r.x)/(s.x-r.x),l=1-(o.y-r.y)/(s.y-r.y),h=e._xOffset*n.width+a*e._xSize|0,c=e._yOffset*n.height+l*e._ySize|0;return this._textureContent[4*(h+c*n.width)+3]>.5}intersects(e,t,i,r){const s=Math.min(this.capacity,this.sprites.length),n=W.Pq.Zero(),o=W.Pq.Zero();let a=Number.MAX_VALUE,l=null;const h=W.AA.Vector3[0],c=W.AA.Vector3[1],u=t.getViewMatrix();let d=e,f=e;for(let t=0;te){if(!this._checkTextureAlpha(s,d,e,n,o))continue;if(f=d,a=e,l=s,r)break}}}}if(l){const e=new At.G;u.invertToRef(W.AA.Matrix[0]),e.hit=!0,e.pickedSprite=l,e.distance=a;const t=W.AA.Vector3[2];return t.copyFrom(f.direction),t.normalize(),t.scaleInPlace(a),f.origin.addToRef(t,h),e.pickedPoint=W.Pq.TransformCoordinates(h,W.AA.Matrix[0]),e}return null}multiIntersects(e,t,i){const r=Math.min(this.capacity,this.sprites.length),s=W.Pq.Zero(),n=W.Pq.Zero();let o;const a=[],l=W.AA.Vector3[0].copyFromFloats(0,0,0),h=W.AA.Vector3[1].copyFromFloats(0,0,0),c=t.getViewMatrix();for(let t=0;t{const o=new go.u;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),n=Jx.Parse(t,i||he.q.LastCreatedScene,r);e&&(n.name=e),s(n)}else n("Unable to load the sprite manager")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return"_BLANK"===e?Promise.resolve(new Jx("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise(((r,s)=>{const n=new go.u;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const s=JSON.parse(JSON.parse(n.responseText).jsonPayload),o=JSON.parse(s.spriteManager),a=Jx.Parse(o,t||he.q.LastCreatedScene,i);a.snippetId=e,r(a)}else s("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}Jx.SnippetUrl="https://snippet.babylonjs.com",Jx.CreateFromSnippetAsync=Jx.ParseFromSnippetAsync;var eb=!0;class tb{}tb.LoaderInjectedPhysicsEngine=void 0;let ib={},rb={},sb={};const nb=(e,t,i,r)=>{if(!t.materials)return null;for(let s=0,n=t.materials.length;s{for(const r in t)if(e.name===t[r])return i.push(e.id),!0;return void 0!==e.parentId&&-1!==i.indexOf(e.parentId)&&(i.push(e.id),!0)},ab=(e,t)=>e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown"),lb=(e,t)=>{const i=t;if(t._waitingData.lods){if(t._waitingData.lods.ids&&t._waitingData.lods.ids.length>0){const r=t._waitingData.lods.ids,s=i.isEnabled(!1);if(t._waitingData.lods.distances){const n=t._waitingData.lods.distances;if(n.length>=r.length){const t=n.length>r.length?n[n.length-1]:0;i.setEnabled(!1);for(let t=0;t0&&i.addLODLevel(t,null),!0===s&&i.setEnabled(!0)}else Ue.S0.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},hb=(e,t,i)=>{if("number"!=typeof e){const r=i.getLastEntryById(e);return r&&null!=t?r.instances[parseInt(t)]:r}const r=ib[e];return r&&null!=t?r.instances[parseInt(t)]:r},cb=(e,t)=>"number"!=typeof e?t.getLastMaterialById(e,!0):rb[e],ub=(e,t,i,r,s=!1)=>{const n=new ei(e);let o="importScene has failed JSON parse";try{var a=JSON.parse(t);o="";const r=xg.loggingLevel===xg.DETAILED_LOGGING;let s,l;if(void 0!==a.environmentTexture&&null!==a.environmentTexture){const t=void 0===a.isPBR||a.isPBR;if(a.environmentTextureType&&"BABYLON.HDRCubeTexture"===a.environmentTextureType){const r=a.environmentTextureSize?a.environmentTextureSize:128,s=new Vx((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,r,!0,!t,void 0,a.environmentTexturePrefilterOnLoad);a.environmentTextureRotationY&&(s.rotationY=a.environmentTextureRotationY),e.environmentTexture=s}else if("object"==typeof a.environmentTexture){const t=gm.Parse(a.environmentTexture,e,i);e.environmentTexture=t}else if(a.environmentTexture.endsWith(".env")){const t=new gm((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,a.environmentTextureForcedExtension);a.environmentTextureRotationY&&(t.rotationY=a.environmentTextureRotationY),e.environmentTexture=t}else{const t=gm.CreateFromPrefilteredData((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,a.environmentTextureForcedExtension);a.environmentTextureRotationY&&(t.rotationY=a.environmentTextureRotationY),e.environmentTexture=t}if(!0===a.createDefaultSkybox){const i=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,r=a.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,t,i,r)}n.environmentTexture=e.environmentTexture}if(void 0!==a.environmentIntensity&&null!==a.environmentIntensity&&(e.environmentIntensity=a.environmentIntensity),void 0!==a.lights&&null!==a.lights)for(s=0,l=a.lights.length;s{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)})))}if(void 0!==a.multiMaterials&&null!==a.multiMaterials)for(s=0,l=a.multiMaterials.length;s{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)}))}if(void 0!==a.morphTargetManagers&&null!==a.morphTargetManagers)for(const t of a.morphTargetManagers){const i=Gx.Parse(t,e);sb[t.id]=i,n.morphTargetManagers.push(i),i._parentContainer=n}if(void 0!==a.skeletons&&null!==a.skeletons)for(s=0,l=a.skeletons.length;s{e&&(n.geometries.push(e),e._parentContainer=n)}))}if(void 0!==a.transformNodes&&null!==a.transformNodes)for(s=0,l=a.transformNodes.length;s{t._waitingSubMaterialsUniqueIds.forEach((i=>{t.subMaterials.push(cb(i,e))})),t._waitingSubMaterialsUniqueIds=[]})),e.meshes.forEach((t=>{null!==t._waitingMaterialId&&(t.material=cb(t._waitingMaterialId,e),t._waitingMaterialId=null)})),e.meshes.forEach((e=>{null!==e._waitingMorphTargetManagerId&&(e.morphTargetManager=sb[e._waitingMorphTargetManagerId],e._waitingMorphTargetManagerId=null)})),s=0,l=e.skeletons.length;s{if(t._waitingTransformNodeId){const i=e.getLastEntryById(t._waitingTransformNodeId);i&&t.linkTransformNode(i),t._waitingTransformNodeId=null}})),t._hasWaitingData=null)}for(s=0,l=e.meshes.length;s0){for(let i=0;i0){for(let i=0;i{e._loadedUniqueId=""})),pi(a,e,n,i),s=0,l=e.meshes.length;s-1!==e.indexOf("babylon"),importMesh:(e,t,i,r,s,n,o,a)=>{let l="importMesh has failed JSON parse";try{var h=JSON.parse(i);l="";const a=xg.loggingLevel===xg.DETAILED_LOGGING;e?Array.isArray(e)||(e=[e]):e=null;const c=[],u=new Map,d=[];if(void 0!==h.transformNodes&&null!==h.transformNodes)for(let e=0,i=h.transformNodes.length;e{!0!==e&&h.geometries[i]&&Array.isArray(h.geometries[i])&&h.geometries[i].forEach((s=>{s.id===_.geometryId&&("vertexData"===i&&yt.Parse(s,t,r),e=!0)}))})),!1===e&&Z.V.Warn("Geometry not found for mesh "+_.id)}if(_.materialUniqueId||_.materialId){const e=_.materialUniqueId?f:n;let i=-1!==e.indexOf(_.materialUniqueId||_.materialId);if(!1===i&&void 0!==h.multiMaterials&&null!==h.multiMaterials){const s=(i,s)=>{e.push(i);const n=nb(s,h,t,r);n&&n.material&&(rb[n.parsedMaterial.uniqueId||n.parsedMaterial.id]=n.material,l+="\n\tMaterial "+n.material.toString(a))};for(let r=0,n=h.multiMaterials.length;rs(e,(t=>t.uniqueId===e)))):n.materials.forEach((e=>s(e,(t=>t.id===e)))),e.push(n.uniqueId||n.id);const r=kt.ParseMultiMaterial(n,t);rb[n.uniqueId||n.id]=r,r&&(i=!0,l+="\n\tMulti-Material "+r.toString(a));break}}}if(!1===i){e.push(_.materialUniqueId||_.materialId);const i=nb((e=>_.materialUniqueId&&e.uniqueId===_.materialUniqueId||e.id===_.materialId),h,t,r);i&&i.material?(rb[i.parsedMaterial.uniqueId||i.parsedMaterial.id]=i.material,l+="\n\tMaterial "+i.material.toString(a)):Z.V.Warn("Material not found for mesh "+_.id)}}if(null!==_.skeletonId&&void 0!==_.skeletonId&&-1!==h.skeletonId&&void 0!==h.skeletons&&null!==h.skeletons&&!(i.indexOf(_.skeletonId)>-1))for(let e=0,r=h.skeletons.length;e-1&&void 0!==h.morphTargetManagers&&null!==h.morphTargetManagers&&!(p.indexOf(_.morphTargetManagerId)>-1))for(let e=0;e{e._waitingSubMaterialsUniqueIds.forEach((i=>{e.subMaterials.push(cb(i,t))})),e._waitingSubMaterialsUniqueIds=[]})),t.meshes.forEach((e=>{null!==e._waitingMaterialId&&(e.material=cb(e._waitingMaterialId,t),e._waitingMaterialId=null)})),t.meshes.forEach((e=>{null!==e._waitingMorphTargetManagerId&&(e.morphTargetManager=sb[e._waitingMorphTargetManagerId],e._waitingMorphTargetManagerId=null)}));for(let e=0,i=t.transformNodes.length;e{if(e._waitingTransformNodeId){const i=t.getLastEntryById(e._waitingTransformNodeId);i&&e.linkTransformNode(i),e._waitingTransformNodeId=null}})),i._hasWaitingData=null)}for(let e=0,i=t.meshes.length;e{e._loadedUniqueId=""})),!0}catch(e){const t=ab("importMesh",h?h.producer:"Unknown")+l;if(!a)throw Z.V.Log(t),e;a(t,e)}finally{null!==l&&xg.loggingLevel!==xg.NO_LOGGING&&Z.V.Log(ab("importMesh",h?h.producer:"Unknown")+(xg.loggingLevel!==xg.MINIMAL_LOGGING?l:"")),rb={},sb={}}return!1},load:(e,t,i,r)=>{let s="importScene has failed JSON parse";try{var n=JSON.parse(t);switch(s="",void 0!==n.useDelayedTextureLoading&&null!==n.useDelayedTextureLoading&&(e.useDelayedTextureLoading=n.useDelayedTextureLoading&&!xg.ForceFullSceneLoadingForIncremental),void 0!==n.autoClear&&null!==n.autoClear&&(e.autoClear=n.autoClear),void 0!==n.clearColor&&null!==n.clearColor&&(e.clearColor=H.ov.FromArray(n.clearColor)),void 0!==n.ambientColor&&null!==n.ambientColor&&(e.ambientColor=H.v9.FromArray(n.ambientColor)),void 0!==n.gravity&&null!==n.gravity&&(e.gravity=W.Pq.FromArray(n.gravity)),void 0!==n.useRightHandedSystem&&(e.useRightHandedSystem=!!n.useRightHandedSystem),void 0!==n.fogMode&&null!==n.fogMode&&(e.fogMode=n.fogMode),void 0!==n.fogColor&&null!==n.fogColor&&(e.fogColor=H.v9.FromArray(n.fogColor)),void 0!==n.fogStart&&null!==n.fogStart&&(e.fogStart=n.fogStart),void 0!==n.fogEnd&&null!==n.fogEnd&&(e.fogEnd=n.fogEnd),void 0!==n.fogDensity&&null!==n.fogDensity&&(e.fogDensity=n.fogDensity),s+="\tFog mode for scene: ",e.fogMode){case 0:s+="none\n";break;case 1:s+="exp\n";break;case 2:s+="exp2\n";break;case 3:s+="linear\n"}if(n.physicsEnabled){let t;"cannon"===n.physicsEngine||n.physicsEngine===Xx.name?t=new Xx(void 0,void 0,tb.LoaderInjectedPhysicsEngine):"oimo"===n.physicsEngine||n.physicsEngine===qx.name?t=new qx(void 0,tb.LoaderInjectedPhysicsEngine):"ammo"!==n.physicsEngine&&n.physicsEngine!==Yx.name||(t=new Yx(void 0,tb.LoaderInjectedPhysicsEngine,void 0)),s="\tPhysics engine "+(n.physicsEngine?n.physicsEngine:"oimo")+" enabled\n";const i=n.gravity?W.Pq.FromArray(n.gravity):n.physicsGravity?W.Pq.FromArray(n.physicsGravity):null;e.enablePhysics(i,t)}return void 0!==n.metadata&&null!==n.metadata&&(e.metadata=n.metadata),void 0!==n.collisionsEnabled&&null!==n.collisionsEnabled&&(e.collisionsEnabled=n.collisionsEnabled),!!ub(e,t,i,r,!0)&&(n.autoAnimate&&e.beginAnimation(e,n.autoAnimateFrom,n.autoAnimateTo,n.autoAnimateLoop,n.autoAnimateSpeed||1),void 0!==n.activeCameraID&&null!==n.activeCameraID&&e.setActiveCameraById(n.activeCameraID),!0)}catch(e){const t=ab("importScene",n?n.producer:"Unknown")+s;if(!r)throw Z.V.Log(t),e;r(t,e)}finally{null!==s&&xg.loggingLevel!==xg.NO_LOGGING&&Z.V.Log(ab("importScene",n?n.producer:"Unknown")+(xg.loggingLevel!==xg.MINIMAL_LOGGING?s:""))}return!1},loadAssetContainer:(e,t,i,r)=>ub(e,t,i,r)});var db=i(18135),fb=i(61853),pb=i(80723),_b=i(91341),mb=i(87741);class gb{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,Ot.$.MarkAllMaterialsAsDirty(20))}constructor(e={}){this._isEnabled=!0,this.bias=void 0===e.bias?0:e.bias,this.power=void 0===e.power?1:e.power,this.leftColor=e.leftColor||H.v9.White(),this.rightColor=e.rightColor||H.v9.Black(),!1===e.isEnabled&&(this.isEnabled=!1)}clone(){const e=new gb;return ce.r.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 gb({isEnabled:e.isEnabled,leftColor:H.v9.FromArray(e.leftColor),rightColor:H.v9.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}it.p._FresnelParametersParser=gb.Parse;class vb{}vb.BindSceneUniformBuffer=Bt._8,vb.PrepareDefinesForMergedUV=Bt.YT,vb.BindTextureMatrix=Bt.mA,vb.GetFogState=Bt.qL,vb.PrepareDefinesForMisc=Bt.fm,vb.PrepareDefinesForCamera=Bt.Y7,vb.PrepareDefinesForFrameBoundValues=Bt.OR,vb.PrepareDefinesForBones=Bt.IC,vb.PrepareDefinesForMorphTargets=Bt.Jz,vb.PrepareDefinesForBakedVertexAnimation=Bt.wu,vb.PrepareDefinesForAttributes=Bt.qB,vb.PrepareDefinesForMultiview=Bt.VO,vb.PrepareDefinesForOIT=Bt.Nc,vb.PrepareDefinesForPrePass=Bt.N4,vb.PrepareDefinesForLight=Bt.lo,vb.PrepareDefinesForLights=Bt.az,vb.PrepareUniformsAndSamplersForLight=Bt.GD,vb.PrepareUniformsAndSamplersList=Bt.Bb,vb.HandleFallbacksForShadows=Bt.c4,vb.PrepareAttributesForMorphTargetsInfluencers=Bt.MF,vb.PrepareAttributesForMorphTargets=Bt.IF,vb.PrepareAttributesForBakedVertexAnimation=Bt.J2,vb.PrepareAttributesForBones=Bt.ni,vb.PrepareAttributesForInstances=Bt.ER,vb.PushAttributesForInstances=Bt.te,vb.BindLightProperties=Bt.L0,vb.BindLight=Bt.Kd,vb.BindLights=Bt.RL,vb.BindFogParameters=Bt.Yy,vb.BindBonesParameters=Bt.f$,vb.BindMorphTargetParameters=Bt.nR,vb.BindLogDepth=Bt.DL;var xb=i(27683),bb=i(53501);class Sb extends xo{constructor(e,t){super(e,t,"color",{attributes:["position"],uniforms:["world","viewProjection","color"]}),this.disableColorWrite=!0,this.forceDepthWrite=!0,this.setColor4("color",new H.ov(0,0,0,1))}}class Tb extends Gm{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 H.v9(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],Tb.prototype,"maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],Tb.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],Tb.prototype,"environmentTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Tb.prototype,"invertNormalMapX",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Tb.prototype,"invertNormalMapY",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],Tb.prototype,"normalTexture",void 0),(0,je.Cg)([(0,$e.jT)("emissive"),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Tb.prototype,"emissiveColor",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Tb.prototype,"emissiveTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],Tb.prototype,"occlusionStrength",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],Tb.prototype,"occlusionTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],Tb.prototype,"alphaCutOff",void 0),(0,je.Cg)([(0,$e.lK)()],Tb.prototype,"doubleSided",null),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty",null)],Tb.prototype,"lightmapTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Tb.prototype,"useLightmapAsShadowmap",void 0);class Cb extends Tb{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=it.p.Clone((()=>new Cb(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=it.p.Serialize(this);return e.customType="BABYLON.PBRMetallicRoughnessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const r=it.p.Parse((()=>new Cb(e.name,t)),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}(0,je.Cg)([(0,$e.jT)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_albedoColor")],Cb.prototype,"baseColor",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],Cb.prototype,"baseTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Cb.prototype,"metallic",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Cb.prototype,"roughness",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],Cb.prototype,"metallicRoughnessTexture",void 0),(0,X.Y5)("BABYLON.PBRMetallicRoughnessMaterial",Cb);class yb extends Tb{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){const t=it.p.Clone((()=>new yb(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=it.p.Serialize(this);return e.customType="BABYLON.PBRSpecularGlossinessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const r=it.p.Parse((()=>new yb(e.name,t)),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}(0,je.Cg)([(0,$e.jT)("diffuse"),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_albedoColor")],yb.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],yb.prototype,"diffuseTexture",void 0),(0,je.Cg)([(0,$e.jT)("specular"),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],yb.prototype,"specularColor",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_microSurface")],yb.prototype,"glossiness",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],yb.prototype,"specularGlossinessTexture",void 0),(0,X.Y5)("BABYLON.PBRSpecularGlossinessMaterial",yb);var Eb,Pb=i(431),Ab=i(66854),Rb=i(60693),Ib=i(43004);!function(e){e[e.GLSL=0]="GLSL",e[e.WGSL=1]="WGSL"}(Eb||(Eb={}));class Mb extends js.t{constructor(e,t,i=null){if(super(t),e)if(this._textureMatrix=W.uq.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{const e=this.getScene();e&&e.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){const e=this._getEngine();let t;t=e._features.support3DTextures?e.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):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=i=>{if("string"!=typeof i)return;let r,s=null,n=null;const o=i.split("\n");let a=0,l=0,h=0,c=0,u=0;for(let e=0;e0&&(e+1)%4==0)s[e]=255;else{const t=n[e];s[e]=t/u*255}t.is3D?(t.updateSize(a,a,a),e.updateRawTexture3D(t,s,5,!1)):(t.updateSize(a*a,a),e.updateRawTexture(t,s,5,!1)),t.isReady=!0,this._triggerOnLoad()},r=this.getScene();return r?r._loadFile(this.url,i):e._loadFile(this.url,i),this._texture}_loadTexture(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()}clone(){const e=new Mb(this.url,this.getScene()||this._getEngine());return e.level=this.level,e}delayLoad(){4===this.delayLoadState&&(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 Mb(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}}Mb._NoneEmptyLineRegex=/\S+/,(0,X.Y5)("BABYLON.ColorGradingTexture",Mb);var Ob=i(5060);class Db extends js.t{constructor(e,t,i,r=!1,s=!0,n=null,o=null,a=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw new Error("Image url is not set");this._coordinatesMode=vi.g.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=a,this._noMipmap=r,this.gammaSpace=s,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?Ue.S0.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 r=i.getEngine().createRawCubeTexture(null,this._size,4,i.getEngine().getCaps().textureFloat?1:7,!this._noMipmap,!1,3);r.generateMipMaps=!this._noMipmap,i.addPendingData(r),r.url=this.url,r.isReady=!1,i.getEngine()._internalTexturesCache.push(r),this._texture=r,(0,$m.W$)(this.url,(t=>{let i;this._width=t.width,this._height=t.height,(0,ii.Nf)()?(i=document.createElement("canvas"),i.width=this._width,i.height=this._height):i=new OffscreenCanvas(this._width,this._height);const r=i.getContext("2d");r.drawImage(t,0,0);const s=r.getImageData(0,0,t.width,t.height);this._buffer=s.data.buffer,i.remove&&i.remove(),e()}),((e,s)=>{i.removePendingData(r),t&&t(`${this.getClassName()} could not be loaded`,s)}),i?i.offlineProvider:null)}_loadTexture(){const e=this.getScene();if(!e)return;const t=(()=>{const e=this._getFloat32ArrayFromArrayBuffer(this._buffer),t=Ob.D.ConvertPanoramaToCubemap(e,this._width,this._height,this._size,this._supersample),i=[];for(let e=0;e<6;e++){const r=t[Db._FacesMapping[e]];i.push(r)}return i})(),i=this._texture;e.getEngine().updateRawCubeTexture(i,t,i.format,i.type,i.invertY),i.isReady=!0,e.removePendingData(i),i.onLoadedObservable.notifyObservers(i),i.onLoadedObservable.clear(),this._onLoad&&this._onLoad()}_getFloat32ArrayFromArrayBuffer(e){const t=new DataView(e),i=new Float32Array(3*e.byteLength/4);let r=0;for(let s=0;s0&&(this._createInternalTextures(),this._createTextures(n))}_initTypes(e,t,i,r,s,n,o,a,l,h){for(let c=0;c{this.onAfterRenderObservable.notifyObservers(t)}))}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){const e=this._renderTarget?.textures;if(e){for(let t=e.length-1;t>=0;t--)this._textures[t]._texture=null;this._renderTarget?.dispose(),this._renderTarget=null}}}class qb{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}}class Yb{constructor(e,t,i,r){return this.name=e,this.meshes=t,this.scene=r,this.options=i,this.options.map=this.options.map??["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=this.options.uvsIn??st.R.UVKind,this.options.uvsOut=this.options.uvsOut??st.R.UVKind,this.options.layout=this.options.layout??Yb.LAYOUT_STRIP,this.options.layout===Yb.LAYOUT_COLNUM&&(this.options.colnum=this.options.colnum??8),this.options.updateInputMeshes=this.options.updateInputMeshes??!0,this.options.disposeSources=this.options.disposeSources??!0,this._expecting=0,this.options.fillBlanks=this.options.fillBlanks??!0,!0===this.options.fillBlanks&&(this.options.customFillColor=this.options.customFillColor??"black"),this.options.frameSize=this.options.frameSize??256,this.options.paddingRatio=this.options.paddingRatio??.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!=0&&this._paddingValue++,this.options.paddingMode=this.options.paddingMode??Yb.SUBUV_WRAP,this.options.paddingMode===Yb.SUBUV_COLOR&&(this.options.paddingColor=this.options.paddingColor??new H.ov(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){const t=this._calculateSize(),i=new W.I9(1,1).divide(t);let r=0;const s=this._expecting,n=this.meshes.length,o=Object.keys(this.sets);for(let e=0;e{this._calculateMeshUVFrames(a,l,t,i,this.options.updateInputMeshes||!1)};for(let i=0;i{r++,d.update(!1);const i=f.getImageData(0,0,h,h),n=this.sets[m];if(n.getContext().putImageData(i,t.x*p.x,t.y*p.y),d.dispose(),n.update(!1),r==s)return c(),void e()},m=o[u]||"_blank";if(n&&null!==n[m]){const e=n[m],t=new Image;t.src=e instanceof Gn?e.getContext().canvas.toDataURL("image/png"):e.url,Ue.S0.SetCorsBehavior(t.src,t),t.onload=()=>{f.fillStyle="rgba(0,0,0,0)",f.fillRect(0,0,h,h),d.update(!1),f.setTransform(1,0,0,-1,0,0);const e=[0,0,1,0,1,1,0,1,-1,1,-1,0,-2,0,-1,1,-1];switch(this.options.paddingMode){case 0:for(let i=0;i<9;i++)f.drawImage(t,0,0,t.width,t.height,l+a*e[i],l+a*e[i+1]-h,a,a);break;case 1:for(let i=0;i{e.dispose&&e.dispose()};for(let e=0;e{try{if(0===this.meshes.length)return void e();let t=0;const i=i=>{if(t++,this.options.map){for(let e=0;e{i(n)}));else if(t++,t===this.meshes.length)return this._createFrames(e)}}catch(e){return t(e)}}))}dispose(){const e=Object.keys(this.sets);for(let t=0;t{const i={name:this.name,sets:{},options:{},frames:[]},r=Object.keys(this.sets),s=Object.keys(this.options);try{for(let s=0;s{try{this.setFragment(this._texturePath)}catch(e){Z.V.Log("No json or ShaderStore or DOM element found for CustomProceduralTexture")}},i=e+"/config.json",r=new go.u;r.open("GET",i),r.addEventListener("load",(()=>{if(200===r.status||r.responseText&&r.responseText.length>0)try{this._config=JSON.parse(r.response),this.updateShaderUniforms(),this.updateTextures(),this.setFragment(this._texturePath+"/custom"),this._animate=this._config.animate,this.refreshRate=this._config.refreshrate}catch(e){t()}else t()}),!1),r.addEventListener("error",(()=>{t()}),!1);try{r.send()}catch(e){Z.V.Error("CustomProceduralTexture: Error on XHR send request.")}}isReady(){if(!super.isReady())return!1;for(const e in this._textures)if(!this._textures[e].isReady())return!1;return!0}render(e){const t=this.getScene();this._animate&&t&&(this._time+=.03*t.getAnimationRatio(),this.updateShaderUniforms()),super.render(e)}updateTextures(){for(let e=0;e{}))}clone(){return it.p.Clone((()=>{const e=this.getScene(),t=this._texture,i=new $b(e,t._bufferViewArray,t.width,t.format,t.type,t.generateMipMaps,t.invertY,t.samplingMode,t._compression);return 13===t.source&&i.updateRGBDAsync(t._bufferViewArrayArray,t._sphericalPolynomial,t._lodGenerationScale,t._lodGenerationOffset),i}),this)}}class Qb extends vi.g{get width(){return this._texture?this._texture.width:0}get height(){return this._texture?this._texture.height:0}get depth(){return this._texture?this._texture.depth:0}constructor(e,t,i,r,s,n,o=!0,a=!1,l=vi.g.TRILINEAR_SAMPLINGMODE,h=0,c){super(null,n,!o,a),this.format=s,this._texture=n.getEngine().createRawTexture3D(e,t,i,r,s,o,a,l,null,h,c),this.is3D=!0}update(e){this._texture&&this._getEngine().updateRawTexture3D(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)}}class Zb extends ln.${constructor(e,t,i,r){super(e,t,i,r,!0),this.refractionPlane=new Ft.Z(0,1,0,1),this.depth=2,this.onBeforeRenderObservable.add((()=>{this.getScene().clipPlane=this.refractionPlane})),this.onAfterRenderObservable.add((()=>{this.getScene().clipPlane=null}))}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Zb(this.name,t.width,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.refractionPlane=this.refractionPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i.depth=this.depth,i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.refractionPlane.asArray(),e.depth=this.depth,e}}var Jb=i(18310),eS=i(29305);class tS extends eS.D{get renderTarget(){return this._renderTarget}constructor(e,t,i){super(null),this._renderTarget=null,this._engine=e,this._renderTargetOptions=i,this.resize(t)}resize(e){this._renderTarget?.dispose(),this._renderTarget=null,this._texture=null,this._size=e,this._engine&&(this._renderTarget=this._engine.createRenderTargetTexture(this._size,this._renderTargetOptions)),this._texture=this.renderTarget.texture}getInternalTexture(){return this._texture}getClassName(){return"ThinRenderTargetTexture"}dispose(e=!1){this._renderTarget?.dispose(!0),this._renderTarget=null,e||super.dispose()}}var iS,rS=i(63199),sS=i(67402),nS=i(92911),oS=i(77318),aS=i(80424),lS=i(44623),hS=i(17477);!function(e){e[e.Uniform=0]="Uniform",e[e.Attribute=1]="Attribute",e[e.Varying=2]="Varying",e[e.Undefined=3]="Undefined"}(iS||(iS={}));class cS extends Ug{constructor(e,t,i,r,s){super(e,t,i),this._blockType=r,this._blockName=s,this.needDualDirectionValidation=!0}checkCompatibilityState(e){return e instanceof cS&&e._blockName===this._blockName?0:1}createCustomInputBlock(){return[new this._blockType(this._blockName),this.name]}}class uS extends Gg{constructor(e){super(e,Dg.Vertex),this._isUnique=!0,this.registerInput("splatPosition",Og.Vector3,!1,Dg.Vertex),this.registerInput("splatScale",Og.Vector2,!0,Dg.Vertex),this.registerInput("world",Og.Matrix,!1,Dg.Vertex),this.registerInput("view",Og.Matrix,!1,Dg.Vertex),this.registerInput("projection",Og.Matrix,!1,Dg.Vertex),this.registerOutput("splatVertex",Og.Vector4,Dg.Vertex)}getClassName(){return"GaussianSplattingBlock"}get splatPosition(){return this._inputs[0]}get splatScale(){return this._inputs[1]}get world(){return this._inputs[2]}get view(){return this._inputs[3]}get projection(){return this._inputs[4]}get splatVertex(){return this._outputs[0]}initialize(e){e._excludeVariableName("focal"),e._excludeVariableName("invViewport")}_buildBlock(e){if(super._buildBlock(e),e.target===Dg.Fragment)return;const t=`//${this.name}`;e._emitFunctionFromInclude("gaussianSplattingVertexDeclaration",t),e._emitFunctionFromInclude("gaussianSplatting",t),e._emitUniformFromString("focal",Og.Vector2),e._emitUniformFromString("invViewport",Og.Vector2),e.attributes.push(st.R.PositionKind),e.sharedData.nodeMaterial.backFaceCulling=!1;const i=this.splatPosition,r=this.splatScale,s=this.world,n=this.view,o=this.projection,a=this.splatVertex;let l=`vec2${e.fSuffix}(1.,1.)`;r.isConnected&&(l=r.associatedVariableName);let h="position",c="";return 1===e.shaderLanguage&&(h="input.position",c=", uniforms.focal, uniforms.invViewport"),e.compilationString+=`${e._declareOutput(a)} = gaussianSplatting(${h}, ${i.associatedVariableName}, ${l}, covA, covB, ${s.associatedVariableName}, ${n.associatedVariableName}, ${o.associatedVariableName}${c});\n`,this}}(0,X.Y5)("BABYLON.GaussianSplattingBlock",uS);class dS extends Gg{constructor(e){super(e,Dg.Fragment),this._isUnique=!1,this.registerInput("splatColor",Og.Color4,!1,Dg.Fragment),this.registerOutput("rgba",Og.Color4,Dg.Fragment)}getClassName(){return"GaussianBlock"}get splatColor(){return this._inputs[0]}get rgba(){return this._outputs[0]}initialize(e){e._excludeVariableName("vPosition")}_buildBlock(e){if(super._buildBlock(e),e.target===Dg.Vertex)return;const t=`//${this.name}`;e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e._emitFunctionFromInclude("logDepthDeclaration",t),e._emitFunctionFromInclude("fogFragmentDeclaration",t),e._emitFunctionFromInclude("gaussianSplattingFragmentDeclaration",t),e._emitVaryingFromString("vPosition",Og.Vector2);const i=this.splatColor,r=this._outputs[0];return 1===e.shaderLanguage?e.compilationString+=`${e._declareOutput(r)} = gaussianColor(${i.associatedVariableName}, input.vPosition);\n`:e.compilationString+=`${e._declareOutput(r)} = gaussianColor(${i.associatedVariableName});\n`,this}}(0,X.Y5)("BABYLON.GaussianBlock",dS),i(67058),i(21325),i(99407),i(92026);class fS extends xn{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 pS extends bn{constructor(e,t){super(e,t),this.backFaceCulling=!1}get hasRenderTargetTextures(){return!1}needAlphaTesting(){return!1}needAlphaBlending(){return!0}isReadyForSubMesh(e,t){const r=!0,s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===r)return!0;t.materialDefines||(t.materialDefines=new fS);const n=this.getScene(),o=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const a=n.getEngine();if((0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,!1,o),(0,Bt.OR)(n,a,this,o,r,null,!0),(0,Bt.qB)(e,o,!1,!1),o.isDirty){o.markAsProcessed(),n.resetCachedMaterial();const e=[st.R.PositionKind,"splatIndex"];(0,Bt.ER)(e,o);const r=["world","view","projection","vFogInfos","vFogColor","logarithmicDepthConstant","invViewport","dataTextureSize","focal"],s=["covariancesATexture","covariancesBTexture","centersTexture","colorsTexture"],l=["Scene","Mesh"];(0,Bt.Bb)({uniformsNames:r,uniformBuffersNames:l,samplers:s,defines:o}),(0,Ln.TV)(r);const h=o.toString(),c=n.getEngine().createEffect("gaussianSplatting",{attributes:e,uniformsNames:r,uniformBuffersNames:l,samplers:s,defines:h,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{},shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,99407)),Promise.resolve().then(i.bind(i,92026))]):await Promise.all([Promise.resolve().then(i.bind(i,67058)),Promise.resolve().then(i.bind(i,21325))])}},a);t.setEffect(c,o,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(o._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=r,0))}static BindEffect(e,t,i){const r=i.getEngine(),s=i.activeCamera,n=r.getRenderWidth(),o=r.getRenderHeight(),a=s?.rigParent?.rigCameras.length||1;t.setFloat2("invViewport",1/(n/a),1/o);let l=1e3;if(s){const e=s.getProjectionMatrix().m[5];l=s.fovMode==rt.FOVMODE_VERTICAL_FIXED?o*e/2:n*e/2}t.setFloat2("focal",l,l);const h=e;if(h.covariancesATexture){const e=h.covariancesATexture.getSize();t.setFloat2("dataTextureSize",e.width,e.height),t.setTexture("covariancesATexture",h.covariancesATexture),t.setTexture("covariancesBTexture",h.covariancesBTexture),t.setTexture("centersTexture",h.centersTexture),t.setTexture("colorsTexture",h.colorsTexture)}}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e),this._mustRebind(r,n,i,t.visibility)?(this.bindView(n),this.bindViewProjection(n),pS.BindEffect(t,this._activeEffect,r),(0,Ln.gS)(n,this,r)):r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0),(0,Bt.Yy)(r,t,n),this.useLogarithmicDepth&&(0,Bt.DL)(s,n,r),this._afterBind(t,this._activeEffect,i))}clone(e){return it.p.Clone((()=>new pS(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GaussianSplattingMaterial",e}getClassName(){return"GaussianSplattingMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new pS(e.name,t)),e,t,i)}}(0,X.Y5)("BABYLON.GaussianSplattingMaterial",pS);class _S extends Gg{constructor(e){super(e,Dg.Vertex),this._isUnique=!0,this.registerInput("splatIndex",Og.Float,!1,Dg.Vertex),this.registerOutput("splatPosition",Og.Vector3,Dg.Vertex),this.registerOutput("splatColor",Og.Color4,Dg.Vertex)}getClassName(){return"SplatReaderBlock"}get splatIndex(){return this._inputs[0]}get splatPosition(){return this._outputs[0]}get splatColor(){return this._outputs[1]}initialize(e){e._excludeVariableName("covA"),e._excludeVariableName("covB"),e._excludeVariableName("vPosition"),e._excludeVariableName("covariancesATexture"),e._excludeVariableName("covariancesBTexture"),e._excludeVariableName("centersTexture"),e._excludeVariableName("colorsTexture"),e._excludeVariableName("dataTextureSize")}bind(e,t,i){if(!i)return;const r=i.getScene();pS.BindEffect(i,e,r)}_buildBlock(e){if(super._buildBlock(e),e.target===Dg.Fragment)return;e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emit2DSampler("covariancesATexture"),e._emit2DSampler("covariancesBTexture"),e._emit2DSampler("centersTexture"),e._emit2DSampler("colorsTexture"),e._emitFunctionFromInclude("gaussianSplattingVertexDeclaration",t),e._emitFunctionFromInclude("gaussianSplatting",t),e._emitVaryingFromString("vPosition",Og.Vector2),e._emitUniformFromString("dataTextureSize",Og.Vector2);const i=this.splatIndex,r=this.splatPosition,s=this.splatColor,n=e._getFreeVariableName("splat");return 1===e.shaderLanguage?(e.compilationString+=`var ${n}: Splat = readSplat(${i.associatedVariableName}, uniforms.dataTextureSize);\n`,e.compilationString+="var covA: vec3f = splat.covA.xyz; var covB: vec3f = vec3f(splat.covA.w, splat.covB.xy);\n",e.compilationString+="vertexOutputs.vPosition = input.position;\n"):(e.compilationString+=`Splat ${n} = readSplat(${i.associatedVariableName});\n`,e.compilationString+="vec3 covA = splat.covA.xyz; vec3 covB = vec3(splat.covA.w, splat.covB.xy);\n",e.compilationString+="vPosition = position;\n"),e.compilationString+=`${e._declareOutput(r)} = ${n}.center.xyz;\n`,e.compilationString+=`${e._declareOutput(s)} = ${n}.color;\n`,this}}function mS(e){e.clear(),e.editorData=null;const t=new Kg("SplatIndex");t.setAsAttribute("splatIndex");const i=new _S("SplatReader");t.connectTo(i);const r=new uS("GaussianSplatting");i.connectTo(r);const s=new Kg("World");s.setAsSystemValue(Lg.World);const n=new zg("WorldPos");i.connectTo(n),s.connectTo(n),n.connectTo(r,{output:"xyz",input:"splatPosition"});const o=new Kg("view");o.setAsSystemValue(Lg.View);const a=new Kg("Projection");a.setAsSystemValue(Lg.Projection),s.connectTo(r,{input:"world"}),o.connectTo(r,{input:"view"}),a.connectTo(r,{input:"projection"});const l=new dS("Gaussian");i.connectTo(l,{input:"splatColor",output:"splatColor"});const h=new Hg("FragmentOutput");l.connectTo(h);const c=new Wg("VertexOutput");r.connectTo(c),e.addOutputNode(c),e.addOutputNode(h),e._mode=rv.GaussianSplatting}(0,X.Y5)("BABYLON.SplatReaderBlock",_S);class gS extends Gg{constructor(e){super(e,Dg.Vertex),this.registerInput("matricesIndices",Og.Vector4),this.registerInput("matricesWeights",Og.Vector4),this.registerInput("matricesIndicesExtra",Og.Vector4,!0),this.registerInput("matricesWeightsExtra",Og.Vector4,!0),this.registerInput("world",Og.Matrix),this.registerOutput("output",Og.Matrix)}initialize(e){e._excludeVariableName("boneSampler"),e._excludeVariableName("boneTextureWidth"),e._excludeVariableName("mBones"),e._excludeVariableName("BonesPerMesh"),this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,1===e?await Promise.all([Promise.resolve().then(i.bind(i,25589)),Promise.resolve().then(i.bind(i,40903))]):await Promise.all([Promise.resolve().then(i.bind(i,39948)),Promise.resolve().then(i.bind(i,78792))]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}getClassName(){return"BonesBlock"}get matricesIndices(){return this._inputs[0]}get matricesWeights(){return this._inputs[1]}get matricesIndicesExtra(){return this._inputs[2]}get matricesWeightsExtra(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}autoConfigure(e,t=(()=>!0)){if(!this.matricesIndices.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesIndices"===e.name&&t(e)));i||(i=new Kg("matricesIndices"),i.setAsAttribute("matricesIndices")),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesWeights"===e.name&&t(e)));i||(i=new Kg("matricesWeights"),i.setAsAttribute("matricesWeights")),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Lg.World&&t(e)));i||(i=new Kg("world"),i.setAsSystemValue(Lg.World)),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){(0,Bt.f$)(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&(0,Bt.IC)(e,i)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithFallbacks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.uniforms.push("boneTextureWidth"),e.uniforms.push("mBones"),e.samplers.push("boneSampler");const t=`//${this.name}`;e._emitFunctionFromInclude("bonesDeclaration",t,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});const i=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",t,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:i}]});const r=this._outputs[0],s=this.world;return e.compilationString+="#if NUM_BONE_INFLUENCERS>0\n",e.compilationString+=e._declareOutput(r)+` = ${s.associatedVariableName} * ${i};\n`,e.compilationString+="#else\n",e.compilationString+=e._declareOutput(r)+` = ${s.associatedVariableName};\n`,e.compilationString+="#endif\n",this}}(0,X.Y5)("BABYLON.BonesBlock",gS);class vS extends Gg{constructor(e){super(e,Dg.Vertex),this.registerInput("world0",Og.Vector4),this.registerInput("world1",Og.Vector4),this.registerInput("world2",Og.Vector4),this.registerInput("world3",Og.Vector4),this.registerInput("world",Og.Matrix,!0),this.registerOutput("output",Og.Matrix),this.registerOutput("instanceID",Og.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((e=>e.isAttribute&&"world0"===e.name&&t(e)));i||(i=new Kg("world0"),i.setAsAttribute("world0")),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world1"===e.name&&t(e)));i||(i=new Kg("world1"),i.setAsAttribute("world1")),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world2"===e.name&&t(e)));i||(i=new Kg("world2"),i.setAsAttribute("world2")),i.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world3"===e.name&&t(e)));i||(i=new Kg("world3"),i.setAsAttribute("world3")),i.output.connectTo(this.world3)}if(!this.world.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world"===e.name&&t(e)));i||(i=new Kg("world"),i.setAsSystemValue(Lg.World)),i.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,r=!1,s){let n=!1;i.INSTANCES!==r&&(i.setValue("INSTANCES",r),n=!0),s&&i.THIN_INSTANCES!==!!s?.getRenderingMesh().hasThinInstances&&(i.setValue("THIN_INSTANCES",!!s?.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],r=this._outputs[1],s=this.world0,n=this.world1,o=this.world2,a=this.world3;let l="mat4",h="gl_InstanceID",c="float";return 1===e.shaderLanguage&&(l="mat4x4f",h="vertexInputs.instanceIndex",c="f32"),e.compilationString+="#ifdef INSTANCES\n",e.compilationString+=e._declareOutput(i)+` = ${l}(${s.associatedVariableName}, ${n.associatedVariableName}, ${o.associatedVariableName}, ${a.associatedVariableName});\n`,e.compilationString+="#ifdef THIN_INSTANCES\n",e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName};\n`,e.compilationString+="#endif\n",t._caps.canUseGLInstanceID?e.compilationString+=e._declareOutput(r)+` = ${c}(${h});\n`:e.compilationString+=e._declareOutput(r)+" = 0.0;\n",e.compilationString+="#else\n",e.compilationString+=e._declareOutput(i)+` = ${this.world.associatedVariableName};\n`,e.compilationString+=e._declareOutput(r)+" = 0.0;\n",e.compilationString+="#endif\n",this}}(0,X.Y5)("BABYLON.InstancesBlock",vS);class xS extends Gg{constructor(e){super(e,Dg.Vertex),this.registerInput("position",Og.Vector3),this.registerInput("normal",Og.Vector3),this.registerInput("tangent",Og.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(Og.Color4|Og.Vector4|Og.Vector3),this.registerInput("uv",Og.Vector2),this.registerOutput("positionOutput",Og.Vector3),this.registerOutput("normalOutput",Og.Vector3),this.registerOutput("tangentOutput",Og.Vector4),this.registerOutput("uvOutput",Og.Vector2)}getClassName(){return"MorphTargetsBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get tangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get positionOutput(){return this._outputs[0]}get normalOutput(){return this._outputs[1]}get tangentOutput(){return this._outputs[2]}get uvOutput(){return this._outputs[3]}initialize(e){e._excludeVariableName("morphTargetInfluences"),this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,1===e?await Promise.all([Promise.resolve().then(i.bind(i,43610)),Promise.resolve().then(i.bind(i,51148)),Promise.resolve().then(i.bind(i,8573)),Promise.resolve().then(i.bind(i,47381))]):await Promise.all([Promise.resolve().then(i.bind(i,44219)),Promise.resolve().then(i.bind(i,11783)),Promise.resolve().then(i.bind(i,99216)),Promise.resolve().then(i.bind(i,9158))]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}autoConfigure(e,t=(()=>!0)){if(!this.position.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name&&t(e)));i||(i=new Kg("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name&&t(e)));i||(i=new Kg("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name&&t(e)));i||(i=new Kg("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name&&t(e)));i||(i=new Kg("uv"),i.setAsAttribute("uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){const t=e.morphTargetManager;t?.isUsingTextureForTargets&&(t.numMaxInfluencers||t.numInfluencers)!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&(0,Bt.Jz)(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&((0,Bt.nR)(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,r){const s=this.position,n=this.normal,o=this.tangent,a=this.uv,l=this.positionOutput,h=this.normalOutput,c=this.tangentOutput,u=this.uvOutput,d=e,f=r.NUM_MORPH_INFLUENCERS,p=i.morphTargetManager,_=p&&p.supportsNormals&&r.NORMAL,m=p&&p.supportsTangents&&r.TANGENT,g=p&&p.supportsUVs&&r.UV1;let v="";p?.isUsingTextureForTargets&&f>0&&(v+=`${d._declareLocalVar("vertexID",Og.Float)};\n`),v+="#ifdef MORPHTARGETS\n";const x=1===d.shaderLanguage,b=x?"uniforms.":"";if(p?.isUsingTextureForTargets)v+=`for (${x?"var":"int"} i = 0; i < NUM_MORPH_INFLUENCERS; i++) {\n`,v+=`if (i >= ${b}morphTargetCount) { break; }\n`,v+=`vertexID = ${x?"f32(vertexInputs.vertexIndex":"float(gl_VertexID"}) * ${b}morphTargetTextureInfo.x;\n`,v+=`${l.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${s.associatedVariableName}) * ${b}morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",_&&(v+="#ifdef MORPHTARGETS_NORMAL\n",v+=`${h.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${n.associatedVariableName}) * ${b}morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",v+="#endif\n"),g&&(v+="#ifdef MORPHTARGETS_UV\n",v+=`${u.associatedVariableName} += (readVector3FromRawSampler(i, vertexID).xy - ${a.associatedVariableName}) * ${b}morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",v+="#endif\n"),m&&(v+="#ifdef MORPHTARGETS_TANGENT\n",v+=`${c.associatedVariableName}.xyz += (readVector3FromRawSampler(i, vertexID) - ${o.associatedVariableName}.xyz) * ${b}morphTargetInfluences[i];\n`,o.type===Og.Vector4?v+=`${c.associatedVariableName}.w = ${o.associatedVariableName}.w;\n`:v+=`${c.associatedVariableName}.w = 1.;\n`,v+="#endif\n"),v+="}\n";else for(let e=0;e0)for(let e=0;e!0)){if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.isSystemValue&&e.systemValue===Lg.World&&t(e)));i||(i=new Kg("world"),i.setAsSystemValue(Lg.World)),i.output.connectTo(this.world)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name&&t(e)));i||(i=new Kg("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name&&e.type===Og.Vector4&&t(e)));i||(i=new Kg("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){const r=this.normal,s=this.tangent;let n=r.isConnected;r.connectInputBlock?.isAttribute&&!e.isVerticesDataPresent(r.connectInputBlock?.name)&&(n=!1);let o=s.isConnected;s.connectInputBlock?.isAttribute&&!e.isVerticesDataPresent(s.connectInputBlock?.name)&&(o=!1);const a=n&&o;i.setValue("TBNBLOCK",a,!0)}_buildBlock(e){super._buildBlock(e);const t=this.normal,i=this.tangent,r=this.world,s=this.TBN,n=this.row0,o=this.row1,a=this.row2,l=1===e.shaderLanguage,h=l?"mat3x3f":"mat3",c=l?"f":"";return e.target===Dg.Fragment&&(e.compilationString+=`\n // ${this.name}\n ${e._declareLocalVar("tbnNormal",Og.Vector3)} = normalize(${t.associatedVariableName}).xyz;\n ${e._declareLocalVar("tbnTangent",Og.Vector3)} = normalize(${i.associatedVariableName}.xyz);\n ${e._declareLocalVar("tbnBitangent",Og.Vector3)} = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w;\n ${l?"var":"mat3"} ${s.associatedVariableName} = ${h}(${r.associatedVariableName}[0].xyz, ${r.associatedVariableName}[1].xyz, ${r.associatedVariableName}[2].xyz) * ${h}(tbnTangent, tbnBitangent, tbnNormal);\n `,n.hasEndpoints&&(e.compilationString+=e._declareOutput(n)+` = vec3${c}(${s.associatedVariableName}[0][0], ${s.associatedVariableName}[0][1], ${s.associatedVariableName}[0][2]);\n`),o.hasEndpoints&&(e.compilationString+=e._declareOutput(o)+` = vec3${c}(${s.associatedVariableName}[1[0], ${s.associatedVariableName}[1][1], ${s.associatedVariableName}[1][2]);\n`),a.hasEndpoints&&(e.compilationString+=e._declareOutput(a)+` = vec3${c}(${s.associatedVariableName}[2][0], ${s.associatedVariableName}[2][1], ${s.associatedVariableName}[2][2]);\n`),e.sharedData.blocksWithDefines.push(this)),this}}(0,X.Y5)("BABYLON.TBNBlock",NS);class FS extends Gg{constructor(e){super(e,Dg.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",Og.Vector4,!1),this.registerInput("worldNormal",Og.Vector4,!1),this.registerInput("worldTangent",Og.Vector4,!0),this.registerInput("uv",Og.Vector2,!1),this.registerInput("normalMapColor",Og.Color3,!1),this.registerInput("strength",Og.Float,!1),this.registerInput("viewDirection",Og.Vector3,!0),this.registerInput("parallaxScale",Og.Float,!0),this.registerInput("parallaxHeight",Og.Float,!0),this.registerInput("TBN",Og.Object,!0,Dg.VertexAndFragment,new cS("TBN",this,0,NS,"TBNBlock")),this.registerInput("world",Og.Matrix,!0),this.registerOutput("output",Og.Vector4),this.registerOutput("uvOffset",Og.Vector2)}getClassName(){return"PerturbNormalBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get worldTangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get normalMapColor(){return this._inputs[4]}get strength(){return this._inputs[5]}get viewDirection(){return this._inputs[6]}get parallaxScale(){return this._inputs[7]}get parallaxHeight(){return this._inputs[8]}get TBN(){return this._inputs[9]}get world(){return this._inputs[10]}get output(){return this._outputs[0]}get uvOffset(){return this._outputs[1]}initialize(e){this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,1===e?await Promise.all([Promise.resolve().then(i.bind(i,99312)),Promise.resolve().then(i.bind(i,56332)),Promise.resolve().then(i.bind(i,87087))]):await Promise.all([Promise.resolve().then(i.bind(i,90249)),Promise.resolve().then(i.bind(i,82267)),Promise.resolve().then(i.bind(i,29424))]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}prepareDefines(e,t,i){const r=this.normalMapColor.connectedPoint._ownerBlock.samplerName,s=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&r||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",s,!0),i.setValue("PARALLAX_RHS",t.getScene().useRightHandedSystem,!0),i.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0),i.setValue("OBJECTSPACE_NORMALMAP",this.useObjectSpaceNormalMap,!0)}bind(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1),i&&(e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1),this.useObjectSpaceNormalMap&&!this.world.isConnected&&e.setMatrix(this._worldMatrixName,i.getWorldMatrix()))}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name&&t(e)));i||(i=new Kg("uv"),i.setAsAttribute()),i.output.connectTo(this.uv)}if(!this.strength.isConnected){const e=new Kg("strength");e.value=1,e.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`,i=this.uv,r=this.worldPosition,s=this.worldNormal,n=this.worldTangent,o=1===e.shaderLanguage,a=o?"mat3x3f":"mat3",l=o?"f":"",h=o?"uniforms.":"";e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=e._getFreeDefineName("tangentSpaceParameter"),e._emitUniformFromString(this._tangentSpaceParameterName,Og.Vector2),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,Og.Float),this._worldMatrixName=e._getFreeDefineName("perturbNormalWorldMatrix"),e._emitUniformFromString(this._worldMatrixName,Og.Matrix);let c=null;this.normalMapColor.connectedPoint&&(c=this.normalMapColor.connectedPoint._ownerBlock.samplerName);const u=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&c||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),d=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?e._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",f=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?`\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n${e._emitFloat(this.strength.connectInputBlock.value)}`:`\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n${this.strength.associatedVariableName}`;o||e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const p={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},_=this.TBN;_.isConnected?e.compilationString+=`\n #ifdef TBNBLOCK\n ${o?"var":"mat3"} vTBN = ${_.associatedVariableName};\n #endif\n `:n.isConnected&&(e.compilationString+=`${e._declareLocalVar("tbnNormal",Og.Vector3)} = normalize(${s.associatedVariableName}.xyz);\n`,e.compilationString+=`${e._declareLocalVar("tbnTangent",Og.Vector3)} = normalize(${n.associatedVariableName}.xyz);\n`,e.compilationString+=`${e._declareLocalVar("tbnBitangent",Og.Vector3)} = cross(tbnNormal, tbnTangent) * ${o?"uniforms.":""}${this._tangentCorrectionFactorName};\n`,e.compilationString+=`${o?"var":"mat3"} vTBN = ${a}(tbnTangent, tbnBitangent, tbnNormal);\n`);let m=[p,{search:/varying mat3 vTBN;/g,replace:""},{search:/uniform mat4 normalMatrix;/g,replace:""}];o&&(m.push({search:/varying vTBN0: vec3f;/g,replace:""}),m.push({search:/varying vTBN1: vec3f;/g,replace:""}),m.push({search:/varying vTBN2: vec3f;/g,replace:""})),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:m});const g=o?"fn parallaxOcclusion(vViewDirCoT: vec3f, vNormalCoT: vec3f, texCoord: vec2f, parallaxScale:f32, bump: texture_2d, bumpSampler: sampler)":"#define inline\nvec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)",v=o?/fn parallaxOcclusion\(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32\)/g:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,x=o?"fn parallaxOffset(viewDir: vec3f, heightScale: f32, height_: f32)":"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)",b=o?/fn parallaxOffset\(viewDir: vec3f,heightScale: f32\)/g:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g;e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:v,replace:g},{search:b,replace:x},{search:/texture.+?bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});const S=u&&c?`${o?`textureSample(${c}, ${c+"Sampler"}`:`texture2D(${c}`}, ${i.associatedVariableName} + uvOffset).xyz`:this.normalMapColor.associatedVariableName,T=e._getFreeVariableName("tempOutput");return e.compilationString+=e._declareLocalVar(T,Og.Vector3)+` = vec3${l}(0.);\n`,m=[{search:new RegExp(`texture.+?bumpSampler${o?"Sampler,fragmentInputs.":","}vBumpUV\\)`,"g"),replace:`${S}`},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:`${e._declareLocalVar("normalMatrix",Og.Matrix)} = toNormalMatrix(${this.world.isConnected?this.world.associatedVariableName:this._worldMatrixName});`},{search:new RegExp(`perturbNormal\\(TBN,texture.+?bumpSampler${o?"Sampler,fragmentInputs.":","}vBumpUV\\+uvOffset\\).xyz,${o?"uniforms.":""}vBumpInfos.y\\)`,"g"),replace:`perturbNormal(TBN, ${S}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${o?u&&this.useParallaxOcclusion?`${c}, ${c+"Sampler"}`:"bump, bumpSampler":u&&this.useParallaxOcclusion?c:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${u?this.parallaxHeight.associatedVariableName:"0."})`},{search:/vBumpInfos.y/g,replace:f},{search:/vBumpInfos.z/g,replace:d},{search:/normalW=/g,replace:T+" = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:`${a}(normalMatrix) * `+T},{search:/normalW/g,replace:s.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:u?this.viewDirection.associatedVariableName:`vec3${l}(0.)`},p],o?(m.push({search:/fragmentInputs.vBumpUV/g,replace:i.associatedVariableName}),m.push({search:/input.vPositionW/g,replace:r.associatedVariableName+".xyz"}),m.push({search:/uniforms.vTangentSpaceParams/g,replace:h+this._tangentSpaceParameterName}),m.push({search:/var TBN: mat3x3f=mat3x3\(input.vTBN0,input.vTBN1,input.vTBN2\);/g,replace:"var TBN = vTBN;"})):(m.push({search:/vBumpUV/g,replace:i.associatedVariableName}),m.push({search:/vPositionW/g,replace:r.associatedVariableName+".xyz"}),m.push({search:/vTangentSpaceParams/g,replace:h+this._tangentSpaceParameterName})),e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:m}),e.compilationString+=e._declareOutput(this.output)+` = vec4${l}(${T}, 0.);\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX};\n`;return e+=`${this._codeVariableName}.invertY = ${this.invertY};\n`,e+=`${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion};\n`,e+=`${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap};\n`,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}}(0,je.Cg)([t_("Invert X axis",0,"PROPERTIES",{embedded:!0,notifiers:{update:!1}})],FS.prototype,"invertX",void 0),(0,je.Cg)([t_("Invert Y axis",0,"PROPERTIES",{embedded:!0,notifiers:{update:!1}})],FS.prototype,"invertY",void 0),(0,je.Cg)([t_("Use parallax occlusion",0,void 0,{embedded:!0,notifiers:{update:!1}})],FS.prototype,"useParallaxOcclusion",void 0),(0,je.Cg)([t_("Object Space Mode",0,"PROPERTIES",{embedded:!0,notifiers:{update:!1}})],FS.prototype,"useObjectSpaceNormalMap",void 0),(0,X.Y5)("BABYLON.PerturbNormalBlock",FS);class LS extends Gg{constructor(e){super(e,Dg.Fragment,!0),this.registerInput("value",Og.Float,!0),this.registerInput("cutoff",Og.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; }\n`,this}}(0,X.Y5)("BABYLON.DiscardBlock",LS);class BS extends Gg{constructor(e){super(e,Dg.Fragment),this.registerOutput("output",Og.Float,Dg.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===Dg.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary("1.0","0.0",0===e.shaderLanguage?"gl_FrontFacing":"fragmentInputs.frontFacing")};\n`,this}}(0,X.Y5)("BABYLON.FrontFacingBlock",BS);class VS extends Gg{constructor(e){super(e,Dg.Fragment),this.registerInput("input",Og.AutoDetect,!1),this.registerOutput("dx",Og.BasedOnInput),this.registerOutput("dy",Og.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[1]._typeConnectionSource=this._inputs[0]}getClassName(){return"DerivativeBlock"}get input(){return this._inputs[0]}get dx(){return this._outputs[0]}get dy(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._outputs[1];e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let r="dFdx",s="dFdy";return 1===e.shaderLanguage&&(r="dpdx",s="dpdy"),t.hasEndpoints&&(e.compilationString+=e._declareOutput(t)+` = ${r}(${this.input.associatedVariableName});\n`),i.hasEndpoints&&(e.compilationString+=e._declareOutput(i)+` = ${s}(${this.input.associatedVariableName});\n`),this}}(0,X.Y5)("BABYLON.DerivativeBlock",VS);class kS extends Gg{constructor(e){super(e,Dg.Fragment),this.registerOutput("xy",Og.Vector2,Dg.Fragment),this.registerOutput("xyz",Og.Vector3,Dg.Fragment),this.registerOutput("xyzw",Og.Vector4,Dg.Fragment),this.registerOutput("x",Og.Float,Dg.Fragment),this.registerOutput("y",Og.Float,Dg.Fragment),this.registerOutput("z",Og.Float,Dg.Fragment),this.registerOutput("w",Og.Float,Dg.Fragment)}getClassName(){return"FragCoordBlock"}get xy(){return this._outputs[0]}get xyz(){return this._outputs[1]}get xyzw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get output(){return this._outputs[6]}writeOutputs(e){let t="";const i=1===e.shaderLanguage?"fragmentInputs.position":"gl_FragCoord";for(const r of this._outputs)r.hasEndpoints&&(t+=`${e._declareOutput(r)} = ${i}.${r.name};\n`);return t}_buildBlock(e){if(super._buildBlock(e),e.target===Dg.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}}(0,X.Y5)("BABYLON.FragCoordBlock",kS);class US extends Gg{constructor(e){super(e,Dg.Fragment),this.registerOutput("xy",Og.Vector2,Dg.Fragment),this.registerOutput("x",Og.Float,Dg.Fragment),this.registerOutput("y",Og.Float,Dg.Fragment)}getClassName(){return"ScreenSizeBlock"}get xy(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}bind(e){const t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())}writeOutputs(e,t){let i="";for(const r of this._outputs)r.hasEndpoints&&(i+=`${e._declareOutput(r)} = ${t}.${r.name};\n`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===Dg.Vertex)throw"ScreenSizeBlock must only be used in a fragment shader";e.sharedData.bindableBlocks.push(this),this._varName=e._getFreeVariableName("screenSize"),e._emitUniformFromString(this._varName,Og.Vector2);const t=1===e.shaderLanguage?"uniforms.":"";return e.compilationString+=this.writeOutputs(e,t+this._varName),this}}(0,X.Y5)("BABYLON.ScreenSizeBlock",US);class GS extends Gg{constructor(e){super(e,Dg.Fragment),this.registerInput("vector",Og.AutoDetect),this.registerInput("worldViewProjection",Og.Matrix),this.registerOutput("output",Og.Vector2),this.registerOutput("x",Og.Float),this.registerOutput("y",Og.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(Og.Color3|Og.Vector3|Og.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((e=>e.systemValue===Lg.WorldViewProjection&&t(e)));i||(i=new Kg("worldViewProjection"),i.setAsSystemValue(Lg.WorldViewProjection)),i.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;const r=i.associatedVariableName,s=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case Og.Vector3:e.compilationString+=`${e._declareLocalVar(s,Og.Vector4)} = ${r} * vec4${e.fSuffix}(${t.associatedVariableName}, 1.0);\n`;break;case Og.Vector4:e.compilationString+=`${e._declareLocalVar(s,Og.Vector4)} = ${r} * ${t.associatedVariableName};\n`}return e.compilationString+=`${s} = vec4${e.fSuffix}(${s}.xy / ${s}.w, ${s}.zw);`,e.compilationString+=`${s} = vec4${e.fSuffix}(${s}.xy * 0.5 + vec2${e.fSuffix}(0.5, 0.5), ${s}.zw);`,this.output.hasEndpoints&&(e.compilationString+=e._declareOutput(this.output)+` = ${s}.xy;\n`),this.x.hasEndpoints&&(e.compilationString+=e._declareOutput(this.x)+` = ${s}.x;\n`),this.y.hasEndpoints&&(e.compilationString+=e._declareOutput(this.y)+` = ${s}.y;\n`),this}}(0,X.Y5)("BABYLON.ScreenSpaceBlock",GS);class zS extends Gg{constructor(e){super(e,Dg.Fragment),this.registerInput("input",Og.Vector2),this.registerInput("strength",Og.Float),this.registerInput("center",Og.Vector2),this.registerInput("offset",Og.Vector2),this.registerOutput("output",Og.Vector2),this.registerOutput("x",Og.Float),this.registerOutput("y",Og.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 Kg("center");e.value=new W.I9(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){const e=new Kg("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){const e=new Kg("offset");e.value=new W.I9(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);const t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),r=e._getFreeVariableName("x"),s=e._getFreeVariableName("y"),n=e._getFreeVariableName("result");return e.compilationString+=` \n ${e._declareLocalVar(t,Og.Vector2)} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName};\n ${e._declareLocalVar(i,Og.Float)} = ${this.strength.associatedVariableName} * length(${t});\n ${e._declareLocalVar(r,Og.Float)} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y;\n ${e._declareLocalVar(s,Og.Float)} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y;\n ${e._declareLocalVar(n,Og.Vector2)} = vec2(${r} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${s} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y);\n `,this.output.hasEndpoints&&(e.compilationString+=e._declareOutput(this.output)+` = ${n};\n`),this.x.hasEndpoints&&(e.compilationString+=e._declareOutput(this.x)+` = ${n}.x;\n`),this.y.hasEndpoints&&(e.compilationString+=e._declareOutput(this.y)+` = ${n}.y;\n`),this}}(0,X.Y5)("BABYLON.TwirlBlock",zS);class WS extends Gg{constructor(e){super(e,Dg.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",Og.Float),this.registerInput("worldPosition",Og.Vector3),this.registerInput("worldNormal",Og.Vector3),this.registerInput("worldTangent",Og.AutoDetect,!0),this.registerOutput("output",Og.Vector4),this.registerOutput("xyz",Og.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(Og.Color3|Og.Vector3|Og.Vector4)}getClassName(){return"HeightToNormalBlock"}get input(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=1===e.shaderLanguage,r=e.fSuffix;this.generateInWorldSpace||this.worldTangent.isConnected||Z.V.Error(`You must connect the 'worldTangent' input of the ${this.name} block!`);const s=this.generateInWorldSpace?"":"\n vec3 biTangent = cross(norm, tgt);\n mat3 TBN = mat3(tgt, biTangent, norm);\n ",n=this.generateInWorldSpace?"":"\n result = TBN * result;\n result = result * vec3(0.5) + vec3(0.5);\n ";let o=`\n vec4 heightToNormal(float height, vec3 position, vec3 tangent, vec3 normal) {\n vec3 tgt = ${this.automaticNormalizationTangent?"normalize(tangent);":"tangent;"}\n vec3 norm = ${this.automaticNormalizationNormal?"normalize(normal);":"normal;"}\n ${s}\n vec3 worlddX = dFdx(position);\n vec3 worlddY = dFdy(position);\n vec3 crossX = cross(norm, worlddX);\n vec3 crossY = cross(worlddY, norm);\n float d = abs(dot(crossY, worlddX));\n vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d));\n inToNormal.y *= -1.0;\n vec3 result = normalize((d * norm) - inToNormal);\n ${n}\n return vec4(result, 0.);\n }`;return i?o=e._babylonSLtoWGSL(o):e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitFunction("heightToNormal",o,"// heightToNormal"),e.compilationString+=e._declareOutput(t)+` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected?this.worldTangent.associatedVariableName:`vec3${r}(0.)`}.xyz, ${this.worldNormal.associatedVariableName});\n`,this.xyz.hasEndpoints&&(e.compilationString+=e._declareOutput(this.xyz)+` = ${this.output.associatedVariableName}.xyz;\n`),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace};\n`,e+=`${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal};\n`,e+=`${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent};\n`,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}}(0,je.Cg)([t_("Generate in world space instead of tangent space",0,"PROPERTIES",{notifiers:{update:!0}})],WS.prototype,"generateInWorldSpace",void 0),(0,je.Cg)([t_("Force normalization for the worldNormal input",0,"PROPERTIES",{notifiers:{update:!0}})],WS.prototype,"automaticNormalizationNormal",void 0),(0,je.Cg)([t_("Force normalization for the worldTangent input",0,"PROPERTIES",{notifiers:{update:!0}})],WS.prototype,"automaticNormalizationTangent",void 0),(0,X.Y5)("BABYLON.HeightToNormalBlock",WS);class HS extends Gg{constructor(e){super(e,Dg.Fragment,!0),this.registerInput("depth",Og.Float,!0),this.registerInput("worldPos",Og.Vector4,!0),this.registerInput("viewProjection",Og.Matrix,!0)}getClassName(){return"FragDepthBlock"}get depth(){return this._inputs[0]}get worldPos(){return this._inputs[1]}get viewProjection(){return this._inputs[2]}_buildBlock(e){super._buildBlock(e);const t=0===e.shaderLanguage?"gl_FragDepth":"fragmentOutputs.fragDepth";return this.depth.isConnected?e.compilationString+=`${t} = ${this.depth.associatedVariableName};\n`:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=`\n ${e._declareLocalVar("p",Og.Vector4)} = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName};\n ${e._declareLocalVar("v",Og.Float)} = p.z / p.w;\n #ifndef IS_NDC_HALF_ZRANGE\n v = v * 0.5 + 0.5;\n #endif\n ${t} = v;\n \n `:Z.V.Warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}}(0,X.Y5)("BABYLON.FragDepthBlock",HS);class XS extends Gg{constructor(e){super(e,Dg.Fragment),this.registerInput("worldPosition",Og.Vector4,!1),this.registerInput("viewProjection",Og.Matrix,!1),this.registerInput("worldNormal",Og.AutoDetect,!0),this.registerOutput("depth",Og.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(Og.Color3|Og.Vector3|Og.Vector4)}getClassName(){return"ShadowMapBlock"}initialize(e){e._excludeVariableName("vPositionWSM"),e._excludeVariableName("lightDataSM"),e._excludeVariableName("biasAndScaleSM"),e._excludeVariableName("depthValuesSM"),e._excludeVariableName("clipPos"),e._excludeVariableName("worldPos"),e._excludeVariableName("zSM"),this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,1===e?await Promise.all([Promise.resolve().then(i.bind(i,18902)),Promise.resolve().then(i.bind(i,2456)),Promise.resolve().then(i.bind(i,43140))]):await Promise.all([Promise.resolve().then(i.bind(i,94949)),Promise.resolve().then(i.bind(i,72693)),Promise.resolve().then(i.bind(i,73391))]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}get worldPosition(){return this._inputs[0]}get viewProjection(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get depth(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`,i=1===e.shaderLanguage;e._emitUniformFromString("biasAndScaleSM",Og.Vector3),e._emitUniformFromString("lightDataSM",Og.Vector3),e._emitUniformFromString("depthValuesSM",Og.Vector2),e._emitFunctionFromInclude("packingFunctions",t),e.compilationString+=`${e._declareLocalVar("worldPos",Og.Vector4)} = ${this.worldPosition.associatedVariableName};\n`,e.compilationString+=`${e._declareLocalVar("vPositionWSM",Og.Vector3)};\n`,e.compilationString+=`${e._declareLocalVar("vDepthMetricSM",Og.Float)} = 0.0;\n`,e.compilationString+=`${e._declareLocalVar("zSM",Og.Float)};\n`,this.worldNormal.isConnected&&(e.compilationString+=`${e._declareLocalVar("vNormalW",Og.Vector3)} = ${this.worldNormal.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`${e._declareLocalVar("clipPos",Og.Vector4)} = ${this.viewProjection.associatedVariableName} * worldPos;\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"},{search:/vertexOutputs.position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]});const r=i?"fragmentOutputs.fragDepth":"gl_FragDepth";return e.compilationString+=`\n #if SM_DEPTHTEXTURE == 1\n #ifdef IS_NDC_HALF_ZRANGE\n ${r} = (clipPos.z / clipPos.w);\n #else\n ${r} = (clipPos.z / clipPos.w) * 0.5 + 0.5;\n #endif\n #endif\n `,e.compilationString+=`${e._declareOutput(this.depth)} = vec3${e.fSuffix}(depthSM, 1., 1.);\n`,this}}(0,X.Y5)("BABYLON.ShadowMapBlock",XS);class qS extends Gg{constructor(e){super(e,Dg.Fragment,!0),this.registerInput("viewDepth",Og.Float,!0),this.registerInput("screenDepth",Og.Float,!0),this.registerInput("worldPosition",Og.AutoDetect,!0),this.registerInput("localPosition",Og.AutoDetect,!0),this.registerInput("viewNormal",Og.AutoDetect,!0),this.registerInput("worldNormal",Og.AutoDetect,!0),this.registerInput("reflectivity",Og.AutoDetect,!0),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(Og.Vector3|Og.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(Og.Vector3|Og.Vector4),this.inputs[4].addExcludedConnectionPointFromAllowedTypes(Og.Vector3|Og.Vector4),this.inputs[5].addExcludedConnectionPointFromAllowedTypes(Og.Vector3|Og.Vector4),this.inputs[6].addExcludedConnectionPointFromAllowedTypes(Og.Vector3|Og.Vector4|Og.Color3|Og.Color4)}getClassName(){return"PrePassOutputBlock"}get viewDepth(){return this._inputs[0]}get screenDepth(){return this._inputs[1]}get worldPosition(){return this._inputs[2]}get localPosition(){return this._inputs[3]}get viewNormal(){return this._inputs[4]}get worldNormal(){return this._inputs[5]}get reflectivity(){return this._inputs[6]}_getFragData(e,t){return e?`fragmentOutputs.fragData${t}`:`gl_FragData[${t}]`}_buildBlock(e){super._buildBlock(e);const t=this.worldPosition,i=this.localPosition,r=this.viewNormal,s=this.worldNormal,n=this.viewDepth,o=this.reflectivity,a=this.screenDepth;e.sharedData.blocksWithDefines.push(this);const l=`//${this.name}`,h=e._getShaderType(Og.Vector4),c=1===e.shaderLanguage;return e._emitFunctionFromInclude("helperFunctions",l),e.compilationString+="#if defined(PREPASS)\r\n",e.compilationString+=c?"var fragData: array, SCENE_MRT_COUNT>;\r\n":"vec4 fragData[SCENE_MRT_COUNT];\r\n",e.compilationString+="#ifdef PREPASS_DEPTH\r\n",n.connectedPoint?e.compilationString+=` fragData[PREPASS_DEPTH_INDEX] = ${h}(${n.associatedVariableName}, 0.0, 0.0, 1.0);\r\n`:e.compilationString+=` fragData[PREPASS_DEPTH_INDEX] = ${h}(0.0, 0.0, 0.0, 0.0);\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_SCREENSPACE_DEPTH\r\n",a.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_SCREENSPACE_DEPTH_INDEX] = vec4(${a.associatedVariableName}, 0.0, 0.0, 1.0);\r\n`:e.compilationString+=" gl_FragData[PREPASS_SCREENSPACE_DEPTH_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_POSITION\r\n",t.connectedPoint?e.compilationString+=`fragData[PREPASS_POSITION_INDEX] = ${h}(${t.associatedVariableName}.rgb, ${t.connectedPoint.type===Og.Vector4?t.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=` fragData[PREPASS_POSITION_INDEX] = ${h}(0.0, 0.0, 0.0, 0.0);\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_LOCAL_POSITION\r\n",i.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_LOCAL_POSITION_INDEX] = vec4(${i.associatedVariableName}.rgb, ${i.connectedPoint.type===Og.Vector4?i.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_LOCAL_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_NORMAL\r\n",r.connectedPoint?e.compilationString+=` fragData[PREPASS_NORMAL_INDEX] = ${h}(${r.associatedVariableName}.rgb, ${r.connectedPoint.type===Og.Vector4?r.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=` fragData[PREPASS_NORMAL_INDEX] = ${h}(0.0, 0.0, 0.0, 0.0);\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_WORLD_NORMAL\r\n",s.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_WORLD_NORMAL_INDEX] = vec4(${s.associatedVariableName}.rgb, ${s.connectedPoint.type===Og.Vector4?s.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_WORLD_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_REFLECTIVITY\r\n",o.connectedPoint?e.compilationString+=` fragData[PREPASS_REFLECTIVITY_INDEX] = ${h}(${o.associatedVariableName}.rgb, ${o.connectedPoint.type===Og.Vector4?o.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=` fragData[PREPASS_REFLECTIVITY_INDEX] = ${h}(0.0, 0.0, 0.0, 1.0);\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#if SCENE_MRT_COUNT > 1\r\n",e.compilationString+=`${this._getFragData(c,1)} = fragData[1];\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#if SCENE_MRT_COUNT > 2\r\n",e.compilationString+=`${this._getFragData(c,2)} = fragData[2];\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#if SCENE_MRT_COUNT > 3\r\n",e.compilationString+=`${this._getFragData(c,3)} = fragData[3];\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#if SCENE_MRT_COUNT > 4\r\n",e.compilationString+=`${this._getFragData(c,4)} = fragData[4];\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#if SCENE_MRT_COUNT > 5\r\n",e.compilationString+=`${this._getFragData(c,5)} = fragData[5];\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#if SCENE_MRT_COUNT > 6\r\n",e.compilationString+=`${this._getFragData(c,6)} = fragData[6];\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#if SCENE_MRT_COUNT > 7\r\n",e.compilationString+=`${this._getFragData(c,7)} = fragData[7];\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#endif\r\n",this}}(0,X.Y5)("BABYLON.PrePassOutputBlock",qS);var YS=i(33882),KS=i(33731),jS=i(94388),$S=i(75651),QS=i(88658),ZS=i(99312),JS=i(56332),eT=i(87087),tT=i(90249),iT=i(82267),rT=i(29424),sT=i(18902),nT=i(2456),oT=i(43140),aT=i(94949),lT=i(72693),hT=i(73391);class cT extends Gg{constructor(e){super(e,Dg.VertexAndFragment,!1),this.registerInput("worldPosition",Og.Vector4,!1,Dg.Vertex),this.registerInput("view",Og.Matrix,!1,Dg.Vertex),this.registerInput("input",Og.AutoDetect,!1,Dg.Fragment),this.registerInput("fogColor",Og.AutoDetect,!1,Dg.Fragment),this.registerOutput("output",Og.Color3,Dg.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(Og.Color3|Og.Vector3|Og.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(Og.Color3|Og.Vector3|Og.Color4)}getClassName(){return"FogBlock"}get worldPosition(){return this._inputs[0]}get view(){return this._inputs[1]}get input(){return this._inputs[2]}get fogColor(){return this._inputs[3]}get output(){return this._outputs[0]}initialize(e){this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,1===e?await Promise.resolve().then(i.bind(i,10668)):await Promise.resolve().then(i.bind(i,64657)),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}autoConfigure(e,t=(()=>!0)){if(!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Lg.View&&t(e)));i||(i=new Kg("view"),i.setAsSystemValue(Lg.View)),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Lg.FogColor&&t(e)));i||(i=new Kg("fogColor",void 0,Og.Color3),i.setAsSystemValue(Lg.FogColor)),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){const r=e.getScene();i.setValue("FOG",t.fogEnabled&&(0,Bt.qL)(e,r))}bind(e,t,i){if(!i)return;const r=i.getScene();e.setFloat4(this._fogParameters,r.fogMode,r.fogStart,r.fogEnd,r.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===Dg.Fragment){e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);let t=[],i="",r="";1===e.shaderLanguage?(t=[{search:/fn CalcFogFactor\(\)/,replace:"fn CalcFogFactor(vFogDistance: vec3f, vFogInfos: vec4f)"},{search:/uniforms.vFogInfos/g,replace:"vFogInfos"},{search:/fragmentInputs.vFogDistance/g,replace:"vFogDistance"}],i="fragmentInputs.",r="uniforms."):t=[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}],e._emitFunctionFromInclude("fogFragmentDeclaration",`//${this.name}`,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:t});const s=e._getFreeVariableName("fog"),n=this.input,o=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");const a=this._outputs[0];e._emitUniformFromString(this._fogParameters,Og.Vector4),e.compilationString+="#ifdef FOG\n",e.compilationString+=`${e._declareLocalVar(s,Og.Float)} = CalcFogFactor(${i}${this._fogDistanceName}, ${r}${this._fogParameters});\n`,e.compilationString+=e._declareOutput(a)+` = ${s} * ${n.associatedVariableName}.rgb + (1.0 - ${s}) * ${o.associatedVariableName}.rgb;\n`,e.compilationString+=`#else\n${e._declareOutput(a)} = ${n.associatedVariableName}.rgb;\n`,e.compilationString+="#endif\n"}else{const t=this.worldPosition,i=this.view;this._fogDistanceName=e._getFreeVariableName("vFogDistance"),e._emitVaryingFromString(this._fogDistanceName,Og.Vector3);const r=1===e.shaderLanguage?"vertexOutputs.":"";e.compilationString+=`${r}${this._fogDistanceName} = (${i.associatedVariableName} * ${t.associatedVariableName}).xyz;\n`}return this}}(0,X.Y5)("BABYLON.FogBlock",cT);class uT extends Gg{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,Z.V.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?Dg.Fragment:Dg.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?Dg.Fragment:Dg.Vertex}constructor(e){super(e,Dg.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",Og.Vector4,!1,Dg.Vertex),this.registerInput("worldNormal",Og.Vector4,!1,Dg.Fragment),this.registerInput("cameraPosition",Og.Vector3,!1,Dg.Fragment),this.registerInput("glossiness",Og.Float,!0,Dg.Fragment),this.registerInput("glossPower",Og.Float,!0,Dg.Fragment),this.registerInput("diffuseColor",Og.Color3,!0,Dg.Fragment),this.registerInput("specularColor",Og.Color3,!0,Dg.Fragment),this.registerInput("view",Og.Matrix,!0),this.registerOutput("diffuseOutput",Og.Color3,Dg.Fragment),this.registerOutput("specularOutput",Og.Color3,Dg.Fragment),this.registerOutput("shadow",Og.Float,Dg.Fragment)}getClassName(){return"LightBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get cameraPosition(){return this._inputs[2]}get glossiness(){return this._inputs[3]}get glossPower(){return this._inputs[4]}get diffuseColor(){return this._inputs[5]}get specularColor(){return this._inputs[6]}get view(){return this._inputs[7]}get diffuseOutput(){return this._outputs[0]}get specularOutput(){return this._outputs[1]}get shadow(){return this._outputs[2]}initialize(e){this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,1===e?await Promise.all([Promise.resolve().then(i.bind(i,55090)),Promise.resolve().then(i.bind(i,71426)),Promise.resolve().then(i.bind(i,85188)),Promise.resolve().then(i.bind(i,87647)),Promise.resolve().then(i.bind(i,34992)),Promise.resolve().then(i.bind(i,94662)),Promise.resolve().then(i.bind(i,48453))]):await Promise.all([Promise.resolve().then(i.bind(i,23133)),Promise.resolve().then(i.bind(i,81749)),Promise.resolve().then(i.bind(i,58769)),Promise.resolve().then(i.bind(i,19215)),Promise.resolve().then(i.bind(i,96951)),Promise.resolve().then(i.bind(i,94388)),Promise.resolve().then(i.bind(i,97295)),Promise.resolve().then(i.bind(i,34091)),Promise.resolve().then(i.bind(i,2946))]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}autoConfigure(e,t=(()=>!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Lg.CameraPosition&&t(e)));i||(i=new Kg("cameraPosition"),i.setAsSystemValue(Lg.CameraPosition)),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;const r=e.getScene();if(this.light){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};(0,Bt.lo)(r,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else(0,Bt.az)(r,e,i,!0,t.maxSimultaneousLights)}updateUniformsAndSamples(e,t,i,r){for(let s=0;s=0;(0,Bt.GD)(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],r,t)}}bind(e,t,i){if(!i)return;const r=i.getScene();this.light?(0,Bt.Kd)(this.light,this._lightId,r,e,!0):(0,Bt.RL)(r,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const r="v_"+t.associatedVariableName;e._emitVaryingFromString(r,Og.Vector4)&&(e.compilationString+=(1===e.shaderLanguage?"vertexOutputs.":"")+`${r} = ${t.associatedVariableName};\n`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`${e._declareLocalVar("worldPos",Og.Vector4)} = ${t.associatedVariableName};\n`,this.view.isConnected&&(e.compilationString+=`${e._declareLocalVar("view",Og.Matrix)} = ${this.view.associatedVariableName};\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_injectUBODeclaration(e){const t=`//${this.name}`;this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0})}_buildBlock(e){super._buildBlock(e);const t=1===e.shaderLanguage,i=t?"f":"",r=`//${this.name}`;if(e.target!==Dg.Fragment)return void this._injectVertexCode(e);this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const s=t?"fragmentInputs.":"";e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const n=this.worldPosition;let o=n.associatedVariableName;this.generateOnlyFragmentCode?(o=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`${e._declareLocalVar(o,Og.Vector3)};\n`,r),e.compilationString+=`${o} = ${n.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",r,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${n.associatedVariableName}`:void 0})):o=s+"v_"+o+".xyz",e._emitFunctionFromInclude("helperFunctions",r);let a={search:/vPositionW/g,replace:o};if(t&&(a={search:/fragmentInputs\.vPositionW/g,replace:o}),e._emitFunctionFromInclude("lightsFragmentFunctions",r,{replaceStrings:[a]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",r,{replaceStrings:[a]}),this._injectUBODeclaration(e),0===this._lightId&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`${e._declareLocalVar("viewDirectionW",Og.Vector3)} = normalize(${this.cameraPosition.associatedVariableName} - ${o});\n`),e.compilationString+=t?"var info: lightingInfo;\n":"lightingInfo info;\n",e.compilationString+=`${e._declareLocalVar("shadow",Og.Float)} = 1.;\n`,e.compilationString+=`${e._declareLocalVar("aggShadow",Og.Float)} = 0.;\n`,e.compilationString+=`${e._declareLocalVar("numLights",Og.Float)} = 0.;\n`,e.compilationString+=`${e._declareLocalVar("glossiness",Og.Float)} = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"};\n`,e.compilationString+=`${e._declareLocalVar("diffuseBase",Og.Vector3)} = vec3${i}(0., 0., 0.);\n`,e.compilationString+=`${e._declareLocalVar("specularBase",Og.Vector3)} = vec3${i}(0., 0., 0.);\n`,e.compilationString+=`${e._declareLocalVar("normalW",Og.Vector3)} = ${this.worldNormal.associatedVariableName}.xyz;\n`),this.light){let i={search:/vPositionW/g,replace:o+".xyz"};t&&(i={search:/fragmentInputs\.vPositionW/g,replace:o+".xyz"}),e.compilationString+=e._emitCodeFromInclude("lightFragment",r,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},i]})}else{let i=`vPositionW,${o}.xyz`;t&&(i=`fragmentInputs.vPositionW,${o}.xyz`),e.compilationString+=e._emitCodeFromInclude("lightFragment",r,{repeatKey:"maxSimultaneousLights",substitutionVars:i})}0===this._lightId&&(e.compilationString+="aggShadow = aggShadow / numLights;\n");const l=this.diffuseOutput,h=this.specularOutput;return e.compilationString+=e._declareOutput(l)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""};\n`,h.hasEndpoints&&(e.compilationString+=e._declareOutput(h)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""};\n`),this.shadow.hasEndpoints&&(e.compilationString+=e._declareOutput(this.shadow)+" = aggShadow;\n"),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()}}(0,je.Cg)([t_("Generate only fragment code",0,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:uT._OnGenerateOnlyFragmentCodeChanged}})],uT.prototype,"generateOnlyFragmentCode",void 0),(0,X.Y5)("BABYLON.LightBlock",uT);class dT extends Gg{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??he.q.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get samplerName(){return this._samplerName}constructor(e){super(e,Dg.VertexAndFragment),this.registerOutput("source",Og.Object,Dg.VertexAndFragment,new cS("source",this,1,dT,"ImageSourceBlock")),this.registerOutput("dimensions",Og.Vector2)}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]}get dimensions(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),e.target===Dg.Vertex&&(this._samplerName=e._getFreeVariableName(this.name+"Texture"),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this)),this.dimensions.isConnected){let t="";t=1===e.shaderLanguage?`vec2f(textureDimensions(${this._samplerName}, 0).xy)`:`vec2(textureSize(${this._samplerName}, 0).xy)`,e.compilationString+=`${e._declareOutput(this.dimensions)} = ${t};\n`}return 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});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&"VideoTexture"!==this.texture.getClassName()&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i,r){super._deserialize(e,t,i,r),e.texture&&!pv.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(0===e.texture.url.indexOf("data:")?i="":r&&(e.texture.url=r(e.texture.url),e.texture.name=e.texture.url),this.texture=vi.g.Parse(e.texture,t,i))}}(0,X.Y5)("BABYLON.ImageSourceBlock",dT);class fT extends Gg{get texture(){return this.source.isConnected?(this.source.connectedPoint?.ownerBlock).texture:this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??he.q.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}static _IsPrePassTextureBlock(e){return"PrePassTextureBlock"===e?.getClassName()}get _isSourcePrePass(){return fT._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!fT._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 e=this.texture.getScene()??he.q.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=this.texture.getScene()??he.q.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?Dg.Fragment:Dg.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",Og.AutoDetect,!1,Dg.VertexAndFragment),this.registerInput("source",Og.Object,!0,Dg.VertexAndFragment,new cS("source",this,0,dT,"ImageSourceBlock")),this.registerInput("layer",Og.Float,!0),this.registerInput("lod",Og.Float,!0),this.registerOutput("rgba",Og.Color4,Dg.Neutral),this.registerOutput("rgb",Og.Color3,Dg.Neutral),this.registerOutput("r",Og.Float,Dg.Neutral),this.registerOutput("g",Og.Float,Dg.Neutral),this.registerOutput("b",Og.Float,Dg.Neutral),this.registerOutput("a",Og.Float,Dg.Neutral),this.registerOutput("level",Og.Float,Dg.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(Og.Vector2|Og.Vector3|Og.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]}_isTiedToFragment(e){if(e.target===Dg.Fragment)return!0;if(e.target===Dg.Vertex)return!1;if(e.target===Dg.Neutral||e.target===Dg.VertexAndFragment){const t=e.ownerBlock;if(t.target===Dg.Fragment)return!0;for(const e of t.inputs)if(e.isConnected&&this._isTiedToFragment(e.connectedPoint))return!0}return!1}_getEffectiveTarget(){return this._fragmentOnly?Dg.Fragment:this.uv.isConnected?this.uv.sourceBlock.isInput?Dg.VertexAndFragment:this._isTiedToFragment(this.uv.connectedPoint)?Dg.Fragment:Dg.VertexAndFragment:Dg.VertexAndFragment}get target(){return this._getEffectiveTarget()}set target(e){}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected)if(e.mode===rv.PostProcess){const i=e.getBlockByPredicate((e=>"uv"===e.name&&t(e)));i&&i.connectTo(this)}else if(e.mode!==rv.ProceduralTexture){const i=e.mode===rv.Particle?"particle_uv":"uv";let r=e.getInputBlockByPredicate((e=>e.isAttribute&&e.name===i&&t(e)));r||(r=new Kg("uv"),r.setAsAttribute(i)),r.output.connectTo(this.uv)}}initializeDefines(e,t,i){i._areTexturesDirty&&void 0!==this._mainUVDefineName&&i.setValue(this._mainUVDefineName,!1,!0)}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;if(!this.texture||!this.texture.getTextureMatrix)return void(this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)));const r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,s,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),null==i[this._mainUVDefineName]&&i.setValue(this._mainUVDefineName,!1,!0)))}isReady(){return!!this._isSourcePrePass||!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this._isSourcePrePass&&e.setFloat(this._textureInfoName,1),this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),this._imageSource||e.setTexture(this._samplerName,this.texture))}get _isMixed(){return this.target!==Dg.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,Og.Vector2,this._defineName),e._emitVaryingFromString(this._mainUVName,Og.Vector2,this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,Og.Matrix,this._defineName);const i=e._getShaderType(Og.Vector4),r=e._getShaderType(Og.Vector2);e.compilationString+=`#ifdef ${this._defineName}\n`,e.compilationString+=`${e._getVaryingName(this._transformedUVName)} = ${r}(${this._textureTransformName} * ${i}(${t.associatedVariableName}.xy, 1.0, 0.0));\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\n`;let s="";if(1===e.shaderLanguage&&t.isConnectedToInputBlock&&-1===t.associatedVariableName.indexOf("vertexInputs.")&&(s="vertexInputs."),e.compilationString+=`${e._getVaryingName(this._mainUVName)} = ${s}${t.associatedVariableName}.xy;\n`,e.compilationString+="#endif\n",this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name,!0)}}_getUVW(e){let t=e;const i=this._texture?._texture?.is2DArray??!1,r=this._texture?._texture?.is3D??!1;return(i||r)&&(t=`vec3(${e}, ${this.layer.isConnected?this.layer.associatedVariableName:"0"})`),t}_samplerFunc(e){return 1===e.shaderLanguage?e.target===Dg.Vertex?"textureSampleLevel":"textureSample":this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureSample(e,t){if(1===t.shaderLanguage){const i=t.target===Dg.Vertex;return`${this._samplerFunc(t)}(${this.samplerName},${this.samplerName+"Sampler"}, ${this._getUVW(e)}${this._samplerLodSuffix}${i?", 0":""})`}return`${this._samplerFunc(t)}(${this.samplerName}, ${this._getUVW(e)}${this._samplerLodSuffix})`}_generateTextureLookup(e){e.compilationString+=`#ifdef ${this._defineName}\n`,e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = ${this._generateTextureSample(e._getVaryingName(this._transformedUVName),e)};\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\n`,e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = ${this._generateTextureSample(this._mainUVName?e._getVaryingName(this._mainUVName):this.uv.associatedVariableName,e)}${this._samplerLodSuffix};\n`,e.compilationString+="#endif\n"}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===Dg.Fragment)return;this._generateTextureLookup(e)}else this.uv.ownerBlock.target!==Dg.Fragment?this._generateTextureLookup(e):e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = ${this._generateTextureSample(i.associatedVariableName,e)}${this._samplerLodSuffix};\n`}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = ${e._toLinearSpace(t)};\n #endif\n `)}_writeOutput(e,t,i,r=!1){if(r){if(e.target===Dg.Fragment)return;return e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,void this._generateConversionCode(e,t,i)}if(this.uv.ownerBlock.target===Dg.Fragment)return e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,void this._generateConversionCode(e,t,i);let s="";this.disableLevelMultiplication||(s=" * "+(1===e.shaderLanguage?"uniforms.":"")+this._textureInfoName),e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}${s};\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===Dg.Vertex||this._fragmentOnly||e.target===Dg.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),!this._isMixed&&e.target===Dg.Fragment||this._isMixed&&e.target===Dg.Vertex){if(!this._imageSource){const t=e._getFreeVariableName(this.name);this._samplerName=t+"Texture",this._texture?._texture?.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName)}e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this)}if(e.target!==Dg.Fragment)return void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;this._isMixed&&!this._imageSource&&(this._texture?._texture?.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._isMixed&&e._emitUniformFromString(this._textureInfoName,Og.Float),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):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||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i,r){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this._fragmentOnly=!!e.fragmentOnly,this.disableLevelMultiplication=!!e.disableLevelMultiplication,e.texture&&!pv.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(0===e.texture.url.indexOf("data:")?i="":r&&(e.texture.url=r(e.texture.url),e.texture.name=e.texture.url),this.texture=vi.g.Parse(e.texture,t,i))}}(0,X.Y5)("BABYLON.TextureBlock",fT);class pT extends Gg{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??he.q.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?Dg.Fragment:Dg.VertexAndFragment)}constructor(e){super(e,Dg.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}initialize(e){this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,1===e?await Promise.resolve().then(i.bind(i,7769)):await Promise.resolve().then(i.bind(i,51068)),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}autoConfigure(e,t=(()=>!0)){if(!this.position.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name&&t(e)));i||(i=new Kg("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Lg.World&&t(e)));i||(i=new Kg("world"),i.setAsSystemValue(Lg.World)),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Lg.View&&t(e)));i||(i=new Kg("view"),i.setAsSystemValue(Lg.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const r=this._getTexture();r&&r.getTextureMatrix&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLocalCubicName,!!r.boundingBoxSize,!0),i.setValue(this._defineExplicitName,0===r.coordinatesMode,!0),i.setValue(this._defineSkyboxName,5===r.coordinatesMode,!0),i.setValue(this._defineCubicName,3===r.coordinatesMode||6===r.coordinatesMode,!0),i.setValue("INVERTCUBICMAP",6===r.coordinatesMode,!0),i.setValue(this._defineSphericalName,1===r.coordinatesMode,!0),i.setValue(this._definePlanarName,2===r.coordinatesMode,!0),i.setValue(this._defineProjectionName,4===r.coordinatesMode,!0),i.setValue(this._defineEquirectangularName,7===r.coordinatesMode,!0),i.setValue(this._defineEquirectangularFixedName,8===r.coordinatesMode,!0),i.setValue(this._defineMirroredEquirectangularFixedName,9===r.coordinatesMode,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i,r){const s=this._getTexture();if(i&&s&&(e.setMatrix(this._reflectionMatrixName,s.getReflectionTextureMatrix()),s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s),s.boundingBoxSize)){const t=s;e.setVector3(this._reflectionPositionName,t.boundingBoxPosition),e.setVector3(this._reflectionSizeName,t.boundingBoxSize)}}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===Dg.Vertex)return"";const t=1===e.shaderLanguage;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,Og.Matrix);let i="";this._worldPositionNameInFragmentOnlyMode=e._getFreeVariableName("worldPosition");const r=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(r,Og.Vector4))&&(this.generateOnlyFragmentCode?i+=`${e._declareLocalVar(r,Og.Vector4)} = ${this.worldPosition.associatedVariableName};\n`:i+=`${t?"vertexOutputs.":""}${r} = ${this.worldPosition.associatedVariableName};\n`),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,Og.Vector3,this._defineSkyboxName))&&(i+=`#ifdef ${this._defineSkyboxName}\n`,this.generateOnlyFragmentCode?i+=`${e._declareLocalVar(this._positionUVWName,Og.Vector3)} = ${this.position.associatedVariableName}.xyz;\n`:i+=`${t?"vertexOutputs.":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz;\n`,i+="#endif\n"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,Og.Vector3,`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(i+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})\n`,this.generateOnlyFragmentCode?i+=`${e._declareLocalVar(this._directionWName,Og.Vector3)} = normalize(vec3${e.fSuffix}(${this.world.associatedVariableName} * vec4${e.fSuffix}(${this.position.associatedVariableName}.xyz, 0.0)));\n`:i+=`${t?"vertexOutputs.":""}${this._directionWName} = normalize(vec3${e.fSuffix}(${this.world.associatedVariableName} * vec4${e.fSuffix}(${this.position.associatedVariableName}.xyz, 0.0)));\n`,i+="#endif\n"),i}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName}\n`,e._emitCubeSampler(this._cubeSamplerName,"",!0),e._samplerDeclaration+="#else\n",e._emit2DSampler(this._2DSamplerName,"",!0),e._samplerDeclaration+="#endif\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"},{search:/fn computeReflectionCoords\(worldPos: vec4f,worldNormal: vec3f\)->vec3f/g,replace:"fn DUMMYFUNC()"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,Og.Vector3),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,Og.Vector3)}handleFragmentSideCodeReflectionCoords(e,t,i,r=!1,s=!1){i||(i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);const n=(1===e.shaderLanguage?"uniforms.":"")+this._reflectionMatrixName,o=`normalize(${this._directionWName})`,a=`${this._positionUVWName}`,l=`${this.cameraPosition.associatedVariableName}`,h=`${this.view.associatedVariableName}`;t+=".xyz";let c=`\n #ifdef ${this._defineMirroredEquirectangularFixedName}\n ${e._declareLocalVar(this._reflectionVectorName,Og.Vector3)} = computeMirroredFixedEquirectangularCoords(${i}, ${t}, ${o});\n #endif\n\n #ifdef ${this._defineEquirectangularFixedName}\n ${e._declareLocalVar(this._reflectionVectorName,Og.Vector3)} = computeFixedEquirectangularCoords(${i}, ${t}, ${o});\n #endif\n\n #ifdef ${this._defineEquirectangularName}\n ${e._declareLocalVar(this._reflectionVectorName,Og.Vector3)} = computeEquirectangularCoords(${i}, ${t}, ${l}.xyz, ${n});\n #endif\n\n #ifdef ${this._defineSphericalName}\n ${e._declareLocalVar(this._reflectionVectorName,Og.Vector3)} = computeSphericalCoords(${i}, ${t}, ${h}, ${n});\n #endif\n\n #ifdef ${this._definePlanarName}\n ${e._declareLocalVar(this._reflectionVectorName,Og.Vector3)} = computePlanarCoords(${i}, ${t}, ${l}.xyz, ${n});\n #endif\n\n #ifdef ${this._defineCubicName}\n #ifdef ${this._defineLocalCubicName}\n ${e._declareLocalVar(this._reflectionVectorName,Og.Vector3)} = computeCubicLocalCoords(${i}, ${t}, ${l}.xyz, ${n}, ${this._reflectionSizeName}, ${this._reflectionPositionName});\n #else\n ${e._declareLocalVar(this._reflectionVectorName,Og.Vector3)} = computeCubicCoords(${i}, ${t}, ${l}.xyz, ${n});\n #endif\n #endif\n\n #ifdef ${this._defineProjectionName}\n ${e._declareLocalVar(this._reflectionVectorName,Og.Vector3)} = computeProjectionCoords(${i}, ${h}, ${n});\n #endif\n\n #ifdef ${this._defineSkyboxName}\n ${e._declareLocalVar(this._reflectionVectorName,Og.Vector3)} = computeSkyBoxCoords(${a}, ${n});\n #endif\n\n #ifdef ${this._defineExplicitName}\n ${e._declareLocalVar(this._reflectionVectorName,Og.Vector3)} = vec3(0, 0, 0);\n #endif\n`;return s||(c+=`#ifdef ${this._defineOppositeZ}\n ${this._reflectionVectorName}.z *= -1.0;\n #endif\n`),r||(c+=`\n #ifdef ${this._define3DName}\n ${e._declareLocalVar(this._reflectionCoordsName,Og.Vector3)} = ${this._reflectionVectorName};\n #else\n ${e._declareLocalVar(this._reflectionCoordsName,Og.Vector2)} = ${this._reflectionVectorName}.xy;\n #ifdef ${this._defineProjectionName}\n ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z;\n #endif\n ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y;\n #endif\n`),c}handleFragmentSideCodeReflectionColor(e,t,i=".rgb"){let r=Og.Vector4;3===i.length&&(r=Og.Vector3);let s=`${e._declareLocalVar(this._reflectionColorName,r)};\n #ifdef ${this._define3DName}\n`;return s+=t?`${this._reflectionColorName} = ${e._generateTextureSampleCubeLOD(this._reflectionVectorName,this._cubeSamplerName,t)}${i};\n`:`${this._reflectionColorName} = ${e._generateTextureSampleCube(this._reflectionVectorName,this._cubeSamplerName)}${i};\n`,s+="\n #else\n",s+=t?`${this._reflectionColorName} =${e._generateTextureSampleLOD(this._reflectionCoordsName,this._2DSamplerName,t)}${i};\n`:`${this._reflectionColorName} = ${e._generateTextureSample(this._reflectionCoordsName,this._2DSamplerName)}${i};\n`,s+="#endif\n",s}writeOutputs(e,t){let i="";if(e.target===Dg.Fragment)for(const r of this._outputs)r.hasEndpoints&&(i+=`${e._declareOutput(r)} = ${t}.${r.name};\n`);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"});\n`}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null);\n`;return e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,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&&!pv.IgnoreTexturesAtLoadTime&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=gm.Parse(e.texture,t,i):this.texture=vi.g.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}(0,je.Cg)([t_("Generate only fragment code",0,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:pT._OnGenerateOnlyFragmentCodeChanged}})],pT.prototype,"generateOnlyFragmentCode",void 0),(0,X.Y5)("BABYLON.ReflectionTextureBaseBlock",pT);class _T extends pT{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,Z.V.Error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,Z.V.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?Dg.Fragment:Dg.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?Dg.Fragment:Dg.Vertex}constructor(e){super(e),this.registerInput("position",Og.AutoDetect,!1,Dg.Vertex),this.registerInput("worldPosition",Og.Vector4,!1,Dg.Vertex),this.registerInput("worldNormal",Og.Vector4,!1,Dg.Fragment),this.registerInput("world",Og.Matrix,!1,Dg.Vertex),this.registerInput("cameraPosition",Og.Vector3,!1,Dg.Fragment),this.registerInput("view",Og.Matrix,!1,Dg.Fragment),this.registerOutput("rgb",Og.Color3,Dg.Fragment),this.registerOutput("rgba",Og.Color4,Dg.Fragment),this.registerOutput("r",Og.Float,Dg.Fragment),this.registerOutput("g",Og.Float,Dg.Fragment),this.registerOutput("b",Og.Float,Dg.Fragment),this.registerOutput("a",Og.Float,Dg.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(Og.Color3|Og.Vector3|Og.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((e=>e.systemValue===Lg.CameraPosition&&t(e)));i||(i=new Kg("cameraPosition"),i.setAsSystemValue(Lg.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,`vec4${e.fSuffix}(0.)`),this;if(e.target!==Dg.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.generateOnlyFragmentCode&&(e.compilationString+=this.handleVertexSide(e)),this.handleFragmentSideInits(e);const t=e._getFreeVariableName("normalWUnit");return e.compilationString+=`${e._declareLocalVar(t,Og.Vector4)} = normalize(${this.worldNormal.associatedVariableName});\n`,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(e,t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(e,void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}}(0,X.Y5)("BABYLON.ReflectionTextureBlock",_T);class mT extends Gg{constructor(e){super(e,Dg.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",Og.AutoDetect,!1,Dg.VertexAndFragment),this.registerOutput("depth",Og.Float,Dg.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(Og.Vector2|Og.Vector3|Og.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?Dg.VertexAndFragment:Dg.Fragment:Dg.VertexAndFragment}_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===Og.Vector3?Og.Vector3:t.type===Og.Vector4?Og.Vector4:Og.Vector2)),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,Og.Vector2),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r",!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===Dg.Fragment)return;const t=0===e.shaderLanguage?`texture2D(${this._samplerName},`:`textureSampleLevel(${this._samplerName}, ${this._samplerName+"Sampler"},`,r=0===e.shaderLanguage?"":", 0";return void(e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,Og.Vector4)}= ${t} ${i.associatedVariableName}.xy${r});\n`)}const r=0===e.shaderLanguage?`texture2D(${this._samplerName},`:`textureSample(${this._samplerName}, ${this._samplerName+"Sampler"},`;this.uv.ownerBlock.target!==Dg.Fragment?e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = ${r} ${this._mainUVName});\n`:e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = ${r} ${i.associatedVariableName}.xy);\n`}_writeOutput(e,t,i,r=!1){if(r){if(e.target===Dg.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}else this.uv.ownerBlock.target,Dg.Fragment,e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}_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!==Dg.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(this._outputs.some((e=>e.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}}(0,je.Cg)([t_("Use non linear depth",0,"ADVANCED",{embedded:!0,notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let r=!1;return i.useNonLinearDepth&&(i.storeCameraSpaceZ=!1,r=!0),e&&e.disableDepthRenderer(),r}}})],mT.prototype,"useNonLinearDepth",void 0),(0,je.Cg)([t_("Store Camera space Z",0,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let r=!1;return i.storeCameraSpaceZ&&(i.useNonLinearDepth=!1,r=!0),e&&e.disableDepthRenderer(),r}}})],mT.prototype,"storeCameraSpaceZ",void 0),(0,je.Cg)([t_("Force 32 bits float",0,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:e=>e?.disableDepthRenderer()}})],mT.prototype,"force32itsFloat",void 0),(0,X.Y5)("BABYLON.SceneDepthBlock",mT);class gT extends Gg{constructor(e){super(e,Dg.VertexAndFragment,!0),this.registerInput("worldPosition",Og.Vector4,!1)}getClassName(){return"ClipPlanesBlock"}initialize(e){e._excludeVariableName("vClipPlane"),e._excludeVariableName("fClipDistance"),e._excludeVariableName("vClipPlane2"),e._excludeVariableName("fClipDistance2"),e._excludeVariableName("vClipPlane3"),e._excludeVariableName("fClipDistance3"),e._excludeVariableName("vClipPlane4"),e._excludeVariableName("fClipDistance4"),e._excludeVariableName("vClipPlane5"),e._excludeVariableName("fClipDistance5"),e._excludeVariableName("vClipPlane6"),e._excludeVariableName("fClipDistance6"),this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,1===e?await Promise.all([Promise.resolve().then(i.bind(i,76794)),Promise.resolve().then(i.bind(i,96140)),Promise.resolve().then(i.bind(i,57728)),Promise.resolve().then(i.bind(i,30486))]):await Promise.all([Promise.resolve().then(i.bind(i,89797)),Promise.resolve().then(i.bind(i,77165)),Promise.resolve().then(i.bind(i,71471)),Promise.resolve().then(i.bind(i,18355))]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}get worldPosition(){return this._inputs[0]}get target(){return Dg.VertexAndFragment}set target(e){}prepareDefines(e,t,i){const r=e.getScene(),s=!!(t.clipPlane??r.clipPlane),n=!!(t.clipPlane2??r.clipPlane2),o=!!(t.clipPlane3??r.clipPlane3),a=!!(t.clipPlane4??r.clipPlane4),l=!!(t.clipPlane5??r.clipPlane5),h=!!(t.clipPlane6??r.clipPlane6);i.setValue("CLIPPLANE",s,!0),i.setValue("CLIPPLANE2",n,!0),i.setValue("CLIPPLANE3",o,!0),i.setValue("CLIPPLANE4",a,!0),i.setValue("CLIPPLANE5",l,!0),i.setValue("CLIPPLANE6",h,!0)}bind(e,t,i){if(!i)return;const r=i.getScene();(0,Ln.gS)(e,t,r)}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;if(e.target!==Dg.Fragment){const i=this.worldPosition;return 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",Og.Vector4),e._emitUniformFromString("vClipPlane2",Og.Vector4),e._emitUniformFromString("vClipPlane3",Og.Vector4),e._emitUniformFromString("vClipPlane4",Og.Vector4),e._emitUniformFromString("vClipPlane5",Og.Vector4),void e._emitUniformFromString("vClipPlane6",Og.Vector4)}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}}(0,X.Y5)("BABYLON.ClipPlanesBlock",gT);var vT,xT=i(76794),bT=i(96140),ST=i(57728),TT=i(30486),CT=i(89797),yT=i(77165),ET=i(71471),PT=i(18355),AT=i(10668),RT=i(64657),IT=i(55090),MT=i(71426),OT=i(85188),DT=i(34992),wT=i(94662),NT=i(48453),FT=i(23133),LT=i(81749),BT=i(58769),VT=i(19215),kT=i(96951),UT=i(97295),GT=i(34091),zT=i(2946),WT=i(7769),HT=i(51068);class XT extends Gg{get texture(){return null}set texture(e){}constructor(e,t=Dg.VertexAndFragment){super(e,t,!1),this.registerOutput("position",Og.Object,Dg.VertexAndFragment,new cS("position",this,1,dT,"ImageSourceBlock")),this.registerOutput("localPosition",Og.Object,Dg.VertexAndFragment,new cS("localPosition",this,1,dT,"ImageSourceBlock")),this.registerOutput("depth",Og.Object,Dg.VertexAndFragment,new cS("depth",this,1,dT,"ImageSourceBlock")),this.registerOutput("screenDepth",Og.Object,Dg.VertexAndFragment,new cS("screenDepth",this,1,dT,"ImageSourceBlock")),this.registerOutput("normal",Og.Object,Dg.VertexAndFragment,new cS("normal",this,1,dT,"ImageSourceBlock")),this.registerOutput("worldNormal",Og.Object,Dg.VertexAndFragment,new cS("worldNormal",this,1,dT,"ImageSourceBlock"))}getSamplerName(e){return e===this._outputs[0]?this._positionSamplerName:e===this._outputs[1]?this._localPositionSamplerName:e===this._outputs[2]?this._depthSamplerName:e===this._outputs[3]?this._screenSpaceDepthSamplerName:e===this._outputs[4]?this._normalSamplerName:e===this._outputs[5]?this._worldNormalSamplerName:""}get position(){return this._outputs[0]}get localPosition(){return this._outputs[1]}get depth(){return this._outputs[2]}get screenDepth(){return this._outputs[3]}get normal(){return this._outputs[4]}get worldNormal(){return this._outputs[5]}get positionSamplerName(){return this._positionSamplerName}get localPositionSamplerName(){return this._localPositionSamplerName}get normalSamplerName(){return this._normalSamplerName}get worldNormalSamplerName(){return this._worldNormalSamplerName}get depthSamplerName(){return this._depthSamplerName}get linearDepthSamplerName(){return this._screenSpaceDepthSamplerName}getClassName(){return"PrePassTextureBlock"}_buildBlock(e){if(super._buildBlock(e),e.target!==Dg.Vertex)return this._positionSamplerName="prepassPositionSampler",this._depthSamplerName="prepassDepthSampler",this._normalSamplerName="prepassNormalSampler",this._worldNormalSamplerName="prepassWorldNormalSampler",this._localPositionSamplerName="prepassLocalPositionSampler",this._screenSpaceDepthSamplerName="prepassScreenSpaceDepthSampler",e.sharedData.variableNames.prepassPositionSampler=0,e.sharedData.variableNames.prepassDepthSampler=0,e.sharedData.variableNames.prepassNormalSampler=0,e.sharedData.variableNames.prepassWorldNormalSampler=0,e.sharedData.variableNames.prepassLocalPositionSampler=0,e.sharedData.variableNames.prepassScreenSpaceDepthSampler=0,e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this),this.position.isConnected&&e._emit2DSampler(this._positionSamplerName),this.depth.isConnected&&e._emit2DSampler(this._depthSamplerName),this.normal.isConnected&&e._emit2DSampler(this._normalSamplerName),this.worldNormal.isConnected&&e._emit2DSampler(this._worldNormalSamplerName),this.localPosition.isConnected&&e._emit2DSampler(this._localPositionSamplerName),this.screenDepth.isConnected&&e._emit2DSampler(this._screenSpaceDepthSamplerName),this}bind(e,t){const i=t.getScene().enablePrePassRenderer();if(!i)return;const r=i.defaultRT;r.textures&&(this.position.isConnected&&e.setTexture(this._positionSamplerName,r.textures[i.getIndex(1)]),this.localPosition.isConnected&&e.setTexture(this._localPositionSamplerName,r.textures[i.getIndex(9)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,r.textures[i.getIndex(5)]),this.screenDepth.isConnected&&e.setTexture(this._screenSpaceDepthSamplerName,r.textures[i.getIndex(10)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,r.textures[i.getIndex(6)]),this.worldNormal.isConnected&&e.setTexture(this._worldNormalSamplerName,r.textures[i.getIndex(8)]))}}(0,X.Y5)("BABYLON.PrePassTextureBlock",XT);class qT extends Gg{get endpoints(){return this._endpoints}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==Dg.VertexAndFragment)return t.target;if(e.connectedPoint.target!==Dg.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){this._target&e||(this._target=e)}constructor(e){super(e,Dg.Neutral),this._endpoints=[],this.registerInput("input",Og.AutoDetect)}getClassName(){return"NodeMaterialTeleportInBlock"}get input(){return this._inputs[0]}isConnectedInFragmentShader(){return this.endpoints.some((e=>e.output.isConnectedInFragmentShader))}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const r of this.endpoints)-1===t.indexOf(r)&&(i+=r._dumpCode(e,t));return i}isAnAncestorOf(e){for(const t of this.endpoints){if(t===e)return!0;if(t.isAnAncestorOf(e))return!0}return!1}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name,this._outputs=this._endpoints.map((e=>e.output))}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null,this._outputs=this._endpoints.map((e=>e.output)))}dispose(){super.dispose();for(const e of this._endpoints)this.detachFromEndpoint(e);this._endpoints=[]}}(0,X.Y5)("BABYLON.NodeMaterialTeleportInBlock",qT);class YT extends Gg{constructor(e){super(e,Dg.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",Og.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};\n`)}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&&-1===t.indexOf(this.entryPoint)&&(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});\n`),e}serialize(){const e=super.serialize();return e.entryPoint=this.entryPoint?.uniqueId??"",e}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}}(0,X.Y5)("BABYLON.NodeMaterialTeleportOutBlock",YT);class KT extends tv{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};\n`,this}}(0,X.Y5)("BABYLON.AddBlock",KT);class jT extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("input",Og.AutoDetect),this.registerInput("factor",Og.Float),this.registerOutput("output",Og.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};\n`,this}}(0,X.Y5)("BABYLON.ScaleBlock",jT);class $T extends Gg{constructor(e){super(e,Dg.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",Og.AutoDetect),this.registerOutput("output",Og.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=1===e.shaderLanguage?e._getShaderType(this.value.type):"";return e.compilationString+=e._declareOutput(t)+` = clamp(${this.value.associatedVariableName}, ${i}(${this._writeFloat(this.minimum)}), ${i}(${this._writeFloat(this.maximum)}));\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};\n`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};\n`,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}}(0,je.Cg)([t_("Minimum",1,void 0,{embedded:!0})],$T.prototype,"minimum",void 0),(0,je.Cg)([t_("Maximum",1,void 0,{embedded:!0})],$T.prototype,"maximum",void 0),(0,X.Y5)("BABYLON.ClampBlock",$T);class QT extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("left",Og.AutoDetect),this.registerInput("right",Og.AutoDetect),this.registerOutput("output",Og.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Og.Float),this._inputs[0].excludedConnectionPointTypes.push(Og.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Og.Vector2),this._inputs[1].excludedConnectionPointTypes.push(Og.Float),this._inputs[1].excludedConnectionPointTypes.push(Og.Matrix),this._inputs[1].excludedConnectionPointTypes.push(Og.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);\n`,this}}(0,X.Y5)("BABYLON.CrossBlock",QT);class ZT extends Gg{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 s=new RegExp("\\{TYPE_"+r.name+"\\}","gm"),n=e._getGLType(r.type);t=t.replace(s,n),i=i.replace(s,n)})),this._outputs.forEach((r=>{const s=new RegExp("\\{TYPE_"+r.name+"\\}","gm"),n=e._getGLType(r.type);t=t.replace(s,n),i=i.replace(s,n)})),e._emitFunction(i,t,""),this._outputs.forEach((t=>{e.compilationString+=e._declareOutput(t)+";\n"})),e.compilationString+=i+"(";let r=!1;return this._inputs.forEach(((t,i)=>{i>0&&(e.compilationString+=", "),this._inputSamplers&&-1!==this._inputSamplers.indexOf(t.name)?e.compilationString+=t.connectedPoint?.ownerBlock?.samplerName??t.associatedVariableName:e.compilationString+=t.associatedVariableName,r=!0})),this._outputs.forEach(((t,i)=>{(i>0||r)&&(e.compilationString+=", "),e.compilationString+=t.associatedVariableName})),e.compilationString+=");\n",this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.options = ${JSON.stringify(this._options)};\n`,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){this._options=e,this._code=e.code.join("\n")+"\n",this.name=this.name||e.name,this.target=Dg[e.target],e.inParameters?.forEach(((e,t)=>{const i=Og[e.type];"sampler2D"===e.type||"samplerCube"===e.type?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(e.name),this.registerInput(e.name,Og.Object,!0,Dg.VertexAndFragment,new cS(e.name,this,0,dT,"ImageSourceBlock"))):this.registerInput(e.name,i),Object.defineProperty(this,e.name,{get:function(){return this._inputs[t]},enumerable:!0,configurable:!0})})),e.outParameters?.forEach(((e,t)=>{this.registerOutput(e.name,Og[e.type]),Object.defineProperty(this,e.name,{get:function(){return this._outputs[t]},enumerable:!0,configurable:!0}),"BasedOnInput"===e.type&&(this._outputs[t]._typeConnectionSource=this._findInputByName(e.typeFromInput)[0])})),e.inLinkedConnectionTypes?.forEach((e=>{this._linkConnectionTypes(this._findInputByName(e.input1)[1],this._findInputByName(e.input2)[1])}))}_findInputByName(e){if(!e)return null;for(let t=0;t!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Lg.CameraPosition&&t(e)));i||(i=new Kg("cameraPosition"),i.setAsSystemValue(Lg.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);\n`,this}}(0,X.Y5)("BABYLON.ViewDirectionBlock",lC),i(49046);class hC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("worldNormal",Og.Vector4),this.registerInput("viewDirection",Og.Vector3),this.registerInput("bias",Og.Float),this.registerInput("power",Og.Float),this.registerOutput("fresnel",Og.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 lC("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){const e=new Kg("bias");e.value=0,e.output.connectTo(this.bias)}if(!this.power.isConnected){const e=new Kg("power");e.value=1,e.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});\n`,this}}(0,X.Y5)("BABYLON.FresnelBlock",hC);class cC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("left",Og.AutoDetect),this.registerInput("right",Og.AutoDetect),this.registerOutput("output",Og.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});\n`,this}}(0,X.Y5)("BABYLON.MaxBlock",cC);class uC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("left",Og.AutoDetect),this.registerInput("right",Og.AutoDetect),this.registerOutput("output",Og.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});\n`,this}}(0,X.Y5)("BABYLON.MinBlock",uC);class dC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("left",Og.AutoDetect),this.registerInput("right",Og.AutoDetect),this.registerOutput("output",Og.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Og.Float),this._inputs[0].excludedConnectionPointTypes.push(Og.Matrix),this._inputs[1].excludedConnectionPointTypes.push(Og.Float),this._inputs[1].excludedConnectionPointTypes.push(Og.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});\n`,this}}(0,X.Y5)("BABYLON.DistanceBlock",dC);class fC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("value",Og.AutoDetect),this.registerOutput("output",Og.Float),this._inputs[0].excludedConnectionPointTypes.push(Og.Float),this._inputs[0].excludedConnectionPointTypes.push(Og.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});\n`,this}}(0,X.Y5)("BABYLON.LengthBlock",fC);class pC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("value",Og.AutoDetect),this.registerOutput("output",Og.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};\n`,this}}(0,X.Y5)("BABYLON.NegateBlock",pC);class _C extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("value",Og.AutoDetect),this.registerInput("power",Og.AutoDetect),this.registerOutput("output",Og.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(max(${this.value.associatedVariableName}, 0.), ${this.power.associatedVariableName});\n`,this}}(0,X.Y5)("BABYLON.PowBlock",_C);class mC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("seed",Og.AutoDetect),this.registerOutput("output",Og.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(Og.Vector2|Og.Vector3|Og.Vector4|Og.Color3|Og.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);\n`,this}}(0,X.Y5)("BABYLON.RandomNumberBlock",mC);class gC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("x",Og.Float),this.registerInput("y",Og.Float),this.registerOutput("output",Og.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=1===e.shaderLanguage?"atan2":"atan";return e.compilationString+=e._declareOutput(t)+` = ${i}(${this.x.associatedVariableName}, ${this.y.associatedVariableName});\n`,this}}(0,X.Y5)("BABYLON.ArcTan2Block",gC);class vC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("value",Og.AutoDetect),this.registerInput("edge0",Og.Float),this.registerInput("edge1",Og.Float),this.registerOutput("output",Og.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});\n`,this}}(0,X.Y5)("BABYLON.SmoothStepBlock",vC);class xC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("input",Og.AutoDetect),this.registerOutput("output",Og.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===Og.Matrix?e.compilationString+=e._declareOutput(t)+` = inverse(${this.input.associatedVariableName});\n`:e.compilationString+=e._declareOutput(t)+` = 1. / ${this.input.associatedVariableName};\n`,this}}(0,X.Y5)("BABYLON.ReciprocalBlock",xC);class bC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("value",Og.AutoDetect),this.registerInput("reference",Og.AutoDetect),this.registerInput("distance",Og.Float),this.registerInput("replacement",Og.AutoDetect),this.registerOutput("output",Og.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(Og.Float),this._inputs[0].excludedConnectionPointTypes.push(Og.Matrix),this._inputs[1].excludedConnectionPointTypes.push(Og.Float),this._inputs[1].excludedConnectionPointTypes.push(Og.Matrix),this._inputs[3].excludedConnectionPointTypes.push(Og.Float),this._inputs[3].excludedConnectionPointTypes.push(Og.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)+";\n",e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) {\n`,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName};\n`,e.compilationString+="} else {\n",e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName};\n`,e.compilationString+="}\n",this}}(0,X.Y5)("BABYLON.ReplaceColorBlock",bC);class SC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("value",Og.AutoDetect),this.registerInput("steps",Og.AutoDetect),this.registerOutput("output",Og.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Og.Matrix),this._inputs[1].excludedConnectionPointTypes.push(Og.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(Og.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});\n`,this}}(0,X.Y5)("BABYLON.PosterizeBlock",SC),function(e){e[e.SawTooth=0]="SawTooth",e[e.Square=1]="Square",e[e.Triangle=2]="Triangle"}(vT||(vT={}));class TC extends Gg{constructor(e){super(e,Dg.Neutral),this.kind=0,this.registerInput("input",Og.AutoDetect),this.registerOutput("output",Og.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Og.Matrix)}getClassName(){return"WaveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];switch(this.kind){case 0:e.compilationString+=e._declareOutput(t)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName});\n`;break;case 1:e.compilationString+=e._declareOutput(t)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName}));\n`;break;case 2:e.compilationString+=e._declareOutput(t)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0;\n`}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}}(0,je.Cg)([t_("Kind",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"SawTooth",value:0},{label:"Square",value:1},{label:"Triangle",value:2}]})],TC.prototype,"kind",void 0),(0,X.Y5)("BABYLON.WaveBlock",TC);class CC{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 yC extends Gg{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,Dg.Neutral),this.colorSteps=[new CC(0,H.v9.Black()),new CC(1,H.v9.White())],this.onValueChangedObservable=new z.cP,this.registerInput("gradient",Og.AutoDetect),this.registerOutput("output",Og.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(Og.Float|Og.Vector2|Og.Vector3|Og.Vector4|Og.Color3|Og.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(Og.Vector3);if(!this.colorSteps.length||!this.gradient.connectedPoint)return void(e.compilationString+=e._declareOutput(t)+` = ${i}(0., 0., 0.);\n`);const r=e._getFreeVariableName("gradientTempColor"),s=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`${e._declareLocalVar(r,Og.Vector3)} = ${this._writeColorConstant(0,i)};\n`,e.compilationString+=`${e._declareLocalVar(s,Og.Float)};\n`;let n=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==Og.Float&&(n+=".x");for(let t=1;t vec3f {\n ${this.handleFragmentSideCodeReflectionCoords(e,"worldNormal","worldPos",!0,!0)}\n return ${this._reflectionVectorName};\n }\n`:`\n vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) {\n ${this.handleFragmentSideCodeReflectionCoords(e,"worldNormal","worldPos",!0,!0)}\n return ${this._reflectionVectorName};\n }\n`;return e._emitFunction("computeReflectionCoordsPBR",s,`//${this.name}`),this._vReflectionMicrosurfaceInfosName=e._getFreeVariableName("vReflectionMicrosurfaceInfos"),e._emitUniformFromString(this._vReflectionMicrosurfaceInfosName,Og.Vector3),this._vReflectionInfosName=e._getFreeVariableName("vReflectionInfos"),this._vReflectionFilteringInfoName=e._getFreeVariableName("vReflectionFilteringInfo"),e._emitUniformFromString(this._vReflectionFilteringInfoName,Og.Vector2),i+=`#ifdef REFLECTION\n ${e._declareLocalVar(this._vReflectionInfosName,Og.Vector2)} = vec2${e.fSuffix}(1., 0.);\n\n ${r?"var reflectionOut: reflectionOutParams":"reflectionOutParams reflectionOut"};\n\n reflectionOut = reflectionBlock(\n ${this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:(r?"input.":"")+"v_"+this.worldPosition.associatedVariableName}.xyz\n , ${t}\n , alphaG\n , ${(r?"uniforms.":"")+this._vReflectionMicrosurfaceInfosName}\n , ${this._vReflectionInfosName}\n , ${this.reflectionColor}\n #ifdef ANISOTROPIC\n ,anisotropicOut\n #endif\n #if defined(${this._defineLODReflectionAlpha}) && !defined(${this._defineSkyboxName})\n ,NdotVUnclamped\n #endif\n #ifdef ${this._defineLinearSpecularReflection}\n , roughness\n #endif\n #ifdef ${this._define3DName}\n , ${this._cubeSamplerName}\n ${r?`, ${this._cubeSamplerName}Sampler`:""}\n #else\n , ${this._2DSamplerName}\n ${r?`, ${this._2DSamplerName}Sampler`:""}\n #endif\n #if defined(NORMAL) && defined(USESPHERICALINVERTEX)\n , ${r?"input.":""}${this._vEnvironmentIrradianceName}\n #endif\n #ifdef USESPHERICALFROMREFLECTIONMAP\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n , ${this._reflectionMatrixName}\n #endif\n #endif\n #ifdef USEIRRADIANCEMAP\n , irradianceSampler // ** not handled **\n ${r?", irradianceSamplerSampler":""}\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef ${this._define3DName}\n , ${this._cubeSamplerName}\n ${r?`, ${this._cubeSamplerName}Sampler`:""}\n , ${this._cubeSamplerName}\n ${r?`, ${this._cubeSamplerName}Sampler`:""}\n #else\n , ${this._2DSamplerName}\n ${r?`, ${this._2DSamplerName}Sampler`:""}\n , ${this._2DSamplerName} \n ${r?`, ${this._2DSamplerName}Sampler`:""}\n #endif\n #endif\n #ifdef REALTIME_FILTERING\n , ${this._vReflectionFilteringInfoName}\n #endif\n );\n #endif\n`,i}_buildBlock(e){return this._scene=e.sharedData.scene,e.target!==Dg.Fragment&&(this._defineLODReflectionAlpha=e._getFreeDefineName("LODINREFLECTIONALPHA"),this._defineLinearSpecularReflection=e._getFreeDefineName("LINEARSPECULARREFLECTION")),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e+=`${this._codeVariableName}.texture.gammaSpace = ${this.texture.gammaSpace};\n`),e+=`${this._codeVariableName}.useSphericalHarmonics = ${this.useSphericalHarmonics};\n`,e+=`${this._codeVariableName}.forceIrradianceInFragment = ${this.forceIrradianceInFragment};\n`,e}serialize(){const e=super.serialize();return e.useSphericalHarmonics=this.useSphericalHarmonics,e.forceIrradianceInFragment=this.forceIrradianceInFragment,e.gammaSpace=this.texture?.gammaSpace??!0,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.useSphericalHarmonics=e.useSphericalHarmonics,this.forceIrradianceInFragment=e.forceIrradianceInFragment,this.texture&&(this.texture.gammaSpace=e.gammaSpace)}}(0,je.Cg)([t_("Spherical Harmonics",0,"ADVANCED",{embedded:!0,notifiers:{update:!0}})],FC.prototype,"useSphericalHarmonics",void 0),(0,je.Cg)([t_("Force irradiance in fragment",0,"ADVANCED",{embedded:!0,notifiers:{update:!0}})],FC.prototype,"forceIrradianceInFragment",void 0),(0,X.Y5)("BABYLON.ReflectionBlock",FC);class LC extends Gg{constructor(e){super(e,Dg.Fragment),this._tangentCorrectionFactorName="",this.remapF0OnInterfaceChange=!0,this._isUnique=!0,this.registerInput("intensity",Og.Float,!1,Dg.Fragment),this.registerInput("roughness",Og.Float,!0,Dg.Fragment),this.registerInput("indexOfRefraction",Og.Float,!0,Dg.Fragment),this.registerInput("normalMapColor",Og.Color3,!0,Dg.Fragment),this.registerInput("uv",Og.Vector2,!0,Dg.Fragment),this.registerInput("tintColor",Og.Color3,!0,Dg.Fragment),this.registerInput("tintAtDistance",Og.Float,!0,Dg.Fragment),this.registerInput("tintThickness",Og.Float,!0,Dg.Fragment),this.registerInput("worldTangent",Og.Vector4,!0),this.registerInput("worldNormal",Og.AutoDetect,!0),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(Og.Color4|Og.Vector4|Og.Vector3),this.registerInput("TBN",Og.Object,!0,Dg.VertexAndFragment,new cS("TBN",this,0,NS,"TBNBlock")),this.registerOutput("clearcoat",Og.Object,Dg.Fragment,new cS("clearcoat",this,1,LC,"ClearCoatBlock"))}initialize(e){e._excludeVariableName("clearcoatOut"),e._excludeVariableName("vClearCoatParams"),e._excludeVariableName("vClearCoatTintParams"),e._excludeVariableName("vClearCoatRefractionParams"),e._excludeVariableName("vClearCoatTangentSpaceParams"),e._excludeVariableName("vGeometricNormaClearCoatW")}getClassName(){return"ClearCoatBlock"}get intensity(){return this._inputs[0]}get roughness(){return this._inputs[1]}get indexOfRefraction(){return this._inputs[2]}get normalMapColor(){return this._inputs[3]}get uv(){return this._inputs[4]}get tintColor(){return this._inputs[5]}get tintAtDistance(){return this._inputs[6]}get tintThickness(){return this._inputs[7]}get worldTangent(){return this._inputs[8]}get worldNormal(){return this._inputs[9]}get TBN(){return this._inputs[10]}get clearcoat(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){const e=new Kg("ClearCoat intensity",Dg.Fragment,Og.Float);e.value=1,e.output.connectTo(this.intensity)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("CLEARCOAT",!0),i.setValue("CLEARCOAT_TEXTURE",!1,!0),i.setValue("CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),i.setValue("CLEARCOAT_TINT",this.tintColor.isConnected||this.tintThickness.isConnected||this.tintAtDistance.isConnected,!0),i.setValue("CLEARCOAT_BUMP",this.normalMapColor.isConnected,!0),i.setValue("CLEARCOAT_DEFAULTIOR",!this.indexOfRefraction.isConnected||this.indexOfRefraction.connectInputBlock.value===Mm._DefaultIndexOfRefraction,!0),i.setValue("CLEARCOAT_REMAP_F0",this.remapF0OnInterfaceChange,!0)}bind(e,t,i){super.bind(e,t,i);const r=this.indexOfRefraction.connectInputBlock?.value??Mm._DefaultIndexOfRefraction,s=1-r,n=1+r,o=Math.pow(-s/n,2),a=1/r;e.setFloat4("vClearCoatRefractionParams",o,a,s,n);const l=this.clearcoat.hasEndpoints?this.clearcoat.endpoints[0].ownerBlock:null,h=l?.perturbedNormal.isConnected?l.perturbedNormal.connectedPoint.ownerBlock:null;this._scene._mirroredCameraPosition?e.setFloat2("vClearCoatTangentSpaceParams",h?.invertX?1:-1,h?.invertY?1:-1):e.setFloat2("vClearCoatTangentSpaceParams",h?.invertX?-1:1,h?.invertY?-1:1),i&&e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1)}_generateTBNSpace(e,t,i){let r="";const s=`//${this.name}`,n=this.worldTangent,o=1===e.shaderLanguage;o||e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const a={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},l=this.TBN;return l.isConnected?e.compilationString+=`\n #ifdef TBNBLOCK\n ${o?"var TBN":"mat3 TBN"} = ${l.associatedVariableName};\n #endif\n `:n.isConnected&&(r+=`${e._declareLocalVar("tbnNormal",Og.Vector3)} = normalize(${i}.xyz);\n`,r+=`${e._declareLocalVar("tbnTangent",Og.Vector3)} = normalize(${n.associatedVariableName}.xyz);\n`,r+=`${e._declareLocalVar("tbnBitangent",Og.Vector3)} = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\n`,r+=`${o?"var vTBN":"mat3 vTBN"} = ${o?"mat3x3f":"mat3"}(tbnTangent, tbnBitangent, tbnNormal);\n`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",s,{replaceStrings:[a]}),r}static GetCode(e,t,i,r,s,n,o){let a="";const l=t?.intensity.isConnected?t.intensity.associatedVariableName:"1.",h=t?.roughness.isConnected?t.roughness.associatedVariableName:"0.",c=t?.normalMapColor.isConnected?t.normalMapColor.associatedVariableName:`vec3${e.fSuffix}(0.)`,u=t?.uv.isConnected?t.uv.associatedVariableName:`vec2${e.fSuffix}(0.)`,d=t?.tintColor.isConnected?t.tintColor.associatedVariableName:`vec3${e.fSuffix}(1.)`,f=t?.tintThickness.isConnected?t.tintThickness.associatedVariableName:"1.",p=t?.tintAtDistance.isConnected?t.tintAtDistance.associatedVariableName:"1.",_=`vec4${e.fSuffix}(0.)`;if(t){e._emitUniformFromString("vClearCoatRefractionParams",Og.Vector4),e._emitUniformFromString("vClearCoatTangentSpaceParams",Og.Vector2);const i=t.worldNormal;a+=`${e._declareLocalVar("vGeometricNormaClearCoatW",Og.Vector3)} = ${i.isConnected?"normalize("+i.associatedVariableName+".xyz)":"geometricNormalW"};\n`}else a+=`${e._declareLocalVar("vGeometricNormaClearCoatW",Og.Vector3)} = geometricNormalW;\n`;s&&t&&(a+=t._generateTBNSpace(e,r,o),n=t.worldTangent.isConnected);const m=1===e.shaderLanguage;return a+=`${m?"var clearcoatOut: clearcoatOutParams":"clearcoatOutParams clearcoatOut"};\n\n #ifdef CLEARCOAT\n ${e._declareLocalVar("vClearCoatParams",Og.Vector2)} = vec2${e.fSuffix}(${l}, ${h});\n ${e._declareLocalVar("vClearCoatTintParams",Og.Vector4)} = vec4${e.fSuffix}(${d}, ${f});\n\n clearcoatOut = clearcoatBlock(\n ${r}.xyz\n , vGeometricNormaClearCoatW\n , viewDirectionW\n , vClearCoatParams\n , specularEnvironmentR0\n #ifdef CLEARCOAT_TEXTURE\n , vec2${e.fSuffix}(0.)\n #endif\n #ifdef CLEARCOAT_TINT\n , vClearCoatTintParams\n , ${p}\n , ${m?"uniforms.":""}vClearCoatRefractionParams\n #ifdef CLEARCOAT_TINT_TEXTURE\n , ${_}\n #endif\n #endif\n #ifdef CLEARCOAT_BUMP\n , vec2${e.fSuffix}(0., 1.)\n , vec4${e.fSuffix}(${c}, 0.)\n , ${u}\n #if defined(${n?"TANGENT":"IGNORE"}) && defined(NORMAL)\n , vTBN\n #else\n , ${m?"uniforms.":""}vClearCoatTangentSpaceParams\n #endif\n #ifdef OBJECTSPACE_NORMALMAP\n , normalMatrix\n #endif\n #endif\n #if defined(FORCENORMALFORWARD) && defined(NORMAL)\n , faceNormal\n #endif\n #ifdef REFLECTION\n , ${m?"uniforms.":""}${i?._vReflectionMicrosurfaceInfosName}\n , ${i?._vReflectionInfosName}\n , ${i?.reflectionColor}\n , ${m?"uniforms.":""}vLightingIntensity\n #ifdef ${i?._define3DName}\n , ${i?._cubeSamplerName} \n ${m?`, ${i?._cubeSamplerName}Sampler`:""}\n #else\n , ${i?._2DSamplerName} \n ${m?`, ${i?._2DSamplerName}Sampler`:""}\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef ${i?._define3DName}\n , ${i?._cubeSamplerName} \n ${m?`, ${i?._cubeSamplerName}Sampler`:""}\n , ${i?._cubeSamplerName}\n ${m?`, ${i?._cubeSamplerName}Sampler`:""}\n #else\n , ${i?._2DSamplerName}\n ${m?`, ${i?._2DSamplerName}Sampler`:""}\n , ${i?._2DSamplerName}\n ${m?`, ${i?._2DSamplerName}Sampler`:""} \n #endif\n #endif\n #endif\n #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)\n , (${e._generateTernary("1.","-1.",m?"fragmentInputs.frontFacing":"gl_FrontFacing")})\n #endif\n );\n #else\n clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0;\n #endif\n`,a}_buildBlock(e){return this._scene=e.sharedData.scene,e.target===Dg.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,Og.Float)),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.remapF0OnInterfaceChange = ${this.remapF0OnInterfaceChange};\n`,e}serialize(){const e=super.serialize();return e.remapF0OnInterfaceChange=this.remapF0OnInterfaceChange,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.remapF0OnInterfaceChange=e.remapF0OnInterfaceChange??!0}}(0,je.Cg)([t_("Remap F0 on interface change",0,"ADVANCED",{embedded:!0})],LC.prototype,"remapF0OnInterfaceChange",void 0),(0,X.Y5)("BABYLON.ClearCoatBlock",LC);class BC extends Gg{constructor(e){super(e,Dg.Fragment),this._isUnique=!0,this.registerInput("intensity",Og.Float,!0,Dg.Fragment),this.registerInput("indexOfRefraction",Og.Float,!0,Dg.Fragment),this.registerInput("thickness",Og.Float,!0,Dg.Fragment),this.registerOutput("iridescence",Og.Object,Dg.Fragment,new cS("iridescence",this,1,BC,"IridescenceBlock"))}initialize(e){e._excludeVariableName("iridescenceOut"),e._excludeVariableName("vIridescenceParams")}getClassName(){return"IridescenceBlock"}get intensity(){return this._inputs[0]}get indexOfRefraction(){return this._inputs[1]}get thickness(){return this._inputs[2]}get iridescence(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){const e=new Kg("Iridescence intensity",Dg.Fragment,Og.Float);e.value=1,e.output.connectTo(this.intensity);const t=new Kg("Iridescence ior",Dg.Fragment,Og.Float);t.value=1.3,t.output.connectTo(this.indexOfRefraction);const i=new Kg("Iridescence thickness",Dg.Fragment,Og.Float);i.value=400,i.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("IRIDESCENCE",!0,!0),i.setValue("IRIDESCENCE_TEXTURE",!1,!0),i.setValue("IRIDESCENCE_THICKNESS_TEXTURE",!1,!0)}static GetCode(e,t){let i="";const r=e?.intensity.isConnected?e.intensity.associatedVariableName:"1.",s=e?.indexOfRefraction.isConnected?e.indexOfRefraction.associatedVariableName:Dm._DefaultIndexOfRefraction,n=e?.thickness.isConnected?e.thickness.associatedVariableName:Dm._DefaultMaximumThickness;return i+=`${1===t.shaderLanguage?"var iridescenceOut: iridescenceOutParams":"iridescenceOutParams iridescenceOut"};\n\n #ifdef IRIDESCENCE\n iridescenceOut = iridescenceBlock(\n vec4(${r}, ${s}, 1., ${n})\n , NdotV\n , specularEnvironmentR0\n #ifdef CLEARCOAT\n , NdotVUnclamped\n #endif \n );\n\n float iridescenceIntensity = iridescenceOut.iridescenceIntensity;\n specularEnvironmentR0 = iridescenceOut.specularEnvironmentR0;\n #endif\n`,i}_buildBlock(e){return e.target===Dg.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this)),this}serialize(){return super.serialize()}_deserialize(e,t,i){super._deserialize(e,t,i)}}(0,X.Y5)("BABYLON.IridescenceBlock",BC);class VC extends Gg{constructor(e){super(e,Dg.Fragment),this.linkRefractionWithTransparency=!1,this.invertRefractionY=!1,this.useThicknessAsDepth=!1,this._isUnique=!0,this.registerInput("intensity",Og.Float,!1,Dg.Fragment),this.registerInput("tintAtDistance",Og.Float,!0,Dg.Fragment),this.registerInput("volumeIndexOfRefraction",Og.Float,!0,Dg.Fragment),this.registerOutput("refraction",Og.Object,Dg.Fragment,new cS("refraction",this,1,VC,"RefractionBlock"))}initialize(e){e._excludeVariableName("vRefractionPosition"),e._excludeVariableName("vRefractionSize")}getClassName(){return"RefractionBlock"}get intensity(){return this._inputs[0]}get tintAtDistance(){return this._inputs[1]}get volumeIndexOfRefraction(){return this._inputs[2]}get view(){return this.viewConnectionPoint}get refraction(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}autoConfigure(e,t=(()=>!0)){if(!this.intensity.isConnected){const e=new Kg("Refraction intensity",Dg.Fragment,Og.Float);e.value=1,e.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Lg.View&&t(e)));i||(i=new Kg("view"),i.setAsSystemValue(Lg.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const r=this._getTexture(),s=r&&r.getTextureMatrix;i.setValue("SS_REFRACTION",s,!0),s&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLODRefractionAlpha,r.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,r.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&r.isCube?!r.invertZ:r.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",r.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",r.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!r.boundingBoxSize,!0),i.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i){super.bind(e,t,i);const r=this._getTexture();if(!r)return;r.isCube?e.setTexture(this._cubeSamplerName,r):e.setTexture(this._2DSamplerName,r),e.setMatrix(this._refractionMatrixName,r.getRefractionTextureMatrix());let s=1;r.isCube||r.depth&&(s=r.depth);const n=this.volumeIndexOfRefraction.connectInputBlock?.value??this.indexOfRefractionConnectionPoint.connectInputBlock?.value??1.5;e.setFloat4(this._vRefractionInfosName,r.level,1/n,s,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,r.getSize().width,r.lodGenerationScale,r.lodGenerationOffset,1/n);const o=r.getSize().width;if(e.setFloat2(this._vRefractionFilteringInfoName,o,Math.log2(o)),r.boundingBoxSize){const t=r;e.setVector3("vRefractionPosition",t.boundingBoxPosition),e.setVector3("vRefractionSize",t.boundingBoxSize)}}getCode(e){return e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),this._define3DName=e._getFreeDefineName("SS_REFRACTIONMAP_3D"),this._getTexture()&&(e._samplerDeclaration+=`#ifdef ${this._define3DName}\n`,e._emitCubeSampler(this._cubeSamplerName,void 0,!0),e._samplerDeclaration+="#else\n",e._emit2DSampler(this._2DSamplerName,void 0,!0),e._samplerDeclaration+="#endif\n"),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,Og.Matrix),1!==e.shaderLanguage&&(e._emitFunction("sampleRefraction",`\n #ifdef ${this._define3DName}\n #define sampleRefraction(s, c) textureCube(s, c)\n #else\n #define sampleRefraction(s, c) texture2D(s, c)\n #endif\n`,`//${this.name}`),e._emitFunction("sampleRefractionLod",`\n #ifdef ${this._define3DName}\n #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l)\n #else\n #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l)\n #endif\n`,`//${this.name}`)),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,Og.Vector4),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,Og.Vector4),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,Og.Vector2),e._emitUniformFromString("vRefractionPosition",Og.Vector3),e._emitUniformFromString("vRefractionSize",Og.Vector3),""}_buildBlock(e){return this._scene=e.sharedData.scene,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e=this.texture.isCube?`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}");\n`:`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}");\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency};\n`,e+=`${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY};\n`,e+=`${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth};\n`,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=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=gm.Parse(e.texture,t,i):this.texture=vi.g.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}(0,je.Cg)([t_("Link refraction to transparency",0,"ADVANCED",{embedded:!0,notifiers:{update:!0}})],VC.prototype,"linkRefractionWithTransparency",void 0),(0,je.Cg)([t_("Invert refraction Y",0,"ADVANCED",{embedded:!0,notifiers:{update:!0}})],VC.prototype,"invertRefractionY",void 0),(0,je.Cg)([t_("Use thickness as depth",0,"ADVANCED",{embedded:!0,notifiers:{update:!0}})],VC.prototype,"useThicknessAsDepth",void 0),(0,X.Y5)("BABYLON.RefractionBlock",VC);class kC extends Gg{constructor(e){super(e,Dg.Fragment),this._isUnique=!0,this.registerInput("thickness",Og.Float,!1,Dg.Fragment),this.registerInput("tintColor",Og.Color3,!0,Dg.Fragment),this.registerInput("translucencyIntensity",Og.Float,!0,Dg.Fragment),this.registerInput("translucencyDiffusionDist",Og.Color3,!0,Dg.Fragment),this.registerInput("refraction",Og.Object,!0,Dg.Fragment,new cS("refraction",this,0,VC,"RefractionBlock")),this.registerInput("dispersion",Og.Float,!0,Dg.Fragment),this.registerOutput("subsurface",Og.Object,Dg.Fragment,new cS("subsurface",this,1,kC,"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 Kg("SubSurface thickness",Dg.Fragment,Og.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const r=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",r||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",r,!0),i.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),i.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),i.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),i.setValue("SS_USE_GLTF_TEXTURES",!1,!0),i.setValue("SS_DISPERSION",this.dispersion.isConnected,!0)}static GetCode(e,t,i,r){let s="";const n=t?.thickness.isConnected?t.thickness.associatedVariableName:"0.",o=t?.tintColor.isConnected?t.tintColor.associatedVariableName:"vec3(1.)",a=t?.translucencyIntensity.isConnected?t?.translucencyIntensity.associatedVariableName:"1.",l=t?.translucencyDiffusionDist.isConnected?t?.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",h=t?.refraction.isConnected?t?.refraction.connectedPoint?.ownerBlock:null,c=h?.tintAtDistance.isConnected?h.tintAtDistance.associatedVariableName:"1.",u=h?.intensity.isConnected?h.intensity.associatedVariableName:"1.",d=h?.view.isConnected?h.view.associatedVariableName:"",f=t?.dispersion.isConnected?t?.dispersion.associatedVariableName:"0.0",p=1===e.shaderLanguage;return s+=h?.getCode(e)??"",s+=`${p?"var subSurfaceOut: subSurfaceOutParams":"subSurfaceOutParams subSurfaceOut"};\n\n #ifdef SUBSURFACE\n ${e._declareLocalVar("vThicknessParam",Og.Vector2)} = vec2${e.fSuffix}(0., ${n});\n ${e._declareLocalVar("vTintColor",Og.Vector4)} = vec4${e.fSuffix}(${o}, ${c});\n ${e._declareLocalVar("vSubSurfaceIntensity",Og.Vector3)} = vec3(${u}, ${a}, 0.);\n ${e._declareLocalVar("dispersion",Og.Float)} = ${f};\n subSurfaceOut = subSurfaceBlock(\n vSubSurfaceIntensity\n , vThicknessParam\n , vTintColor\n , normalW\n , specularEnvironmentReflectance\n #ifdef SS_THICKNESSANDMASK_TEXTURE\n , vec4${e.fSuffix}(0.)\n #endif\n #ifdef REFLECTION\n #ifdef SS_TRANSLUCENCY\n , ${(p?"uniforms.":"")+i?._reflectionMatrixName}\n #ifdef USESPHERICALFROMREFLECTIONMAP\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n , reflectionOut.irradianceVector\n #endif\n #if defined(REALTIME_FILTERING)\n , ${i?._cubeSamplerName}\n ${p?`, ${i?._cubeSamplerName}Sampler`:""}\n , ${i?._vReflectionFilteringInfoName}\n #endif\n #endif\n #ifdef USEIRRADIANCEMAP\n , irradianceSampler\n ${p?", irradianceSamplerSampler":""}\n #endif\n #endif\n #endif\n #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\n , surfaceAlbedo\n #endif\n #ifdef SS_REFRACTION\n , ${r}.xyz\n , viewDirectionW\n , ${d}\n , ${(p?"uniforms.":"")+h?._vRefractionInfosName??""}\n , ${(p?"uniforms.":"")+h?._refractionMatrixName??""}\n , ${(p?"uniforms.":"")+h?._vRefractionMicrosurfaceInfosName??""}\n , ${p?"uniforms.":""}vLightingIntensity\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n , alpha\n #endif\n #ifdef ${h?._defineLODRefractionAlpha??"IGNORE"}\n , NdotVUnclamped\n #endif\n #ifdef ${h?._defineLinearSpecularRefraction??"IGNORE"}\n , roughness\n #endif\n , alphaG\n #ifdef ${h?._define3DName??"IGNORE"}\n , ${h?._cubeSamplerName??""}\n ${p?`, ${h?._cubeSamplerName}Sampler`:""}\n #else\n , ${h?._2DSamplerName??""}\n ${p?`, ${h?._2DSamplerName}Sampler`:""}\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef ${h?._define3DName??"IGNORE"}\n , ${h?._cubeSamplerName??""} \n ${p?`, ${h?._cubeSamplerName}Sampler`:""}\n , ${h?._cubeSamplerName??""} \n ${p?`, ${h?._cubeSamplerName}Sampler`:""}\n #else\n , ${h?._2DSamplerName??""}\n ${p?`, ${h?._2DSamplerName}Sampler`:""}\n , ${h?._2DSamplerName??""}\n ${p?`, ${h?._2DSamplerName}Sampler`:""}\n #endif\n #endif\n #ifdef ANISOTROPIC\n , anisotropicOut\n #endif\n #ifdef REALTIME_FILTERING\n , ${h?._vRefractionFilteringInfoName??""}\n #endif\n #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n , vRefractionPosition\n , vRefractionSize\n #endif\n #ifdef SS_DISPERSION\n , dispersion\n #endif\n #endif\n #ifdef SS_TRANSLUCENCY\n , ${l}\n , vTintColor\n #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\n , vec4${e.fSuffix}(0.)\n #endif\n #endif \n );\n\n #ifdef SS_REFRACTION\n surfaceAlbedo = subSurfaceOut.surfaceAlbedo;\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha = subSurfaceOut.alpha;\n #endif\n #endif\n #else\n subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance;\n #endif\n`,s}_buildBlock(e){return e.target===Dg.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}(0,X.Y5)("BABYLON.SubSurfaceBlock",kC);const UC={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 GC extends Gg{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,Z.V.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?Dg.Fragment:Dg.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?Dg.Fragment:Dg.Vertex}constructor(e){super(e,Dg.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=H.v9.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",Og.Vector4,!1,Dg.Vertex),this.registerInput("worldNormal",Og.Vector4,!1,Dg.Vertex),this.registerInput("view",Og.Matrix,!1),this.registerInput("cameraPosition",Og.Vector3,!1,Dg.Fragment),this.registerInput("perturbedNormal",Og.Vector4,!0,Dg.Fragment),this.registerInput("baseColor",Og.Color3,!0,Dg.Fragment),this.registerInput("metallic",Og.Float,!1,Dg.Fragment),this.registerInput("roughness",Og.Float,!1,Dg.Fragment),this.registerInput("ambientOcc",Og.Float,!0,Dg.Fragment),this.registerInput("opacity",Og.Float,!0,Dg.Fragment),this.registerInput("indexOfRefraction",Og.Float,!0,Dg.Fragment),this.registerInput("ambientColor",Og.Color3,!0,Dg.Fragment),this.registerInput("reflection",Og.Object,!0,Dg.Fragment,new cS("reflection",this,0,FC,"ReflectionBlock")),this.registerInput("clearcoat",Og.Object,!0,Dg.Fragment,new cS("clearcoat",this,0,LC,"ClearCoatBlock")),this.registerInput("sheen",Og.Object,!0,Dg.Fragment,new cS("sheen",this,0,wC,"SheenBlock")),this.registerInput("subsurface",Og.Object,!0,Dg.Fragment,new cS("subsurface",this,0,kC,"SubSurfaceBlock")),this.registerInput("anisotropy",Og.Object,!0,Dg.Fragment,new cS("anisotropy",this,0,NC,"AnisotropyBlock")),this.registerInput("iridescence",Og.Object,!0,Dg.Fragment,new cS("iridescence",this,0,BC,"IridescenceBlock")),this.registerOutput("ambientClr",Og.Color3,Dg.Fragment),this.registerOutput("diffuseDir",Og.Color3,Dg.Fragment),this.registerOutput("specularDir",Og.Color3,Dg.Fragment),this.registerOutput("clearcoatDir",Og.Color3,Dg.Fragment),this.registerOutput("sheenDir",Og.Color3,Dg.Fragment),this.registerOutput("diffuseInd",Og.Color3,Dg.Fragment),this.registerOutput("specularInd",Og.Color3,Dg.Fragment),this.registerOutput("clearcoatInd",Og.Color3,Dg.Fragment),this.registerOutput("sheenInd",Og.Color3,Dg.Fragment),this.registerOutput("refraction",Og.Color3,Dg.Fragment),this.registerOutput("lighting",Og.Color3,Dg.Fragment),this.registerOutput("shadow",Og.Float,Dg.Fragment),this.registerOutput("alpha",Og.Float,Dg.Fragment)}initialize(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode"),this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,1===e?await Promise.all([Promise.resolve().then(i.bind(i,431)),Promise.resolve().then(i.bind(i,66854))]):await Promise.all([Promise.resolve().then(i.bind(i,60693)),Promise.resolve().then(i.bind(i,43004))]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}getClassName(){return"PBRMetallicRoughnessBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get view(){return this._inputs[2]}get cameraPosition(){return this._inputs[3]}get perturbedNormal(){return this._inputs[4]}get baseColor(){return this._inputs[5]}get metallic(){return this._inputs[6]}get roughness(){return this._inputs[7]}get ambientOcc(){return this._inputs[8]}get opacity(){return this._inputs[9]}get indexOfRefraction(){return this._inputs[10]}get ambientColor(){return this._inputs[11]}get reflection(){return this._inputs[12]}get clearcoat(){return this._inputs[13]}get sheen(){return this._inputs[14]}get subsurface(){return this._inputs[15]}get anisotropy(){return this._inputs[16]}get iridescence(){return this._inputs[17]}get ambientClr(){return this._outputs[0]}get diffuseDir(){return this._outputs[1]}get specularDir(){return this._outputs[2]}get clearcoatDir(){return this._outputs[3]}get sheenDir(){return this._outputs[4]}get diffuseInd(){return this._outputs[5]}get specularInd(){return this._outputs[6]}get clearcoatInd(){return this._outputs[7]}get sheenInd(){return this._outputs[8]}get refraction(){return this._outputs[9]}get lighting(){return this._outputs[10]}get shadow(){return this._outputs[11]}get alpha(){return this._outputs[12]}autoConfigure(e,t=(()=>!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Lg.CameraPosition&&t(e)));i||(i=new Kg("cameraPosition"),i.setAsSystemValue(Lg.CameraPosition)),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Lg.View&&t(e)));i||(i=new Kg("view"),i.setAsSystemValue(Lg.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===Gm.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===Gm.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));const r=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",r.indexOf(".")<0?r+".":r,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);const s=e.getScene();if(s.getEngine()._features.needTypeSuffixInShaderConstants?i.setValue("NUM_SAMPLES",this.realTimeFilteringQuality+"u",!0):i.setValue("NUM_SAMPLES",""+this.realTimeFilteringQuality,!0),i.setValue("BRDF_V_HEIGHT_CORRELATED",!0),i.setValue("MS_BRDF_ENERGY_CONSERVATION",this.useEnergyConservation,!0),i.setValue("RADIANCEOCCLUSION",this.useRadianceOcclusion,!0),i.setValue("HORIZONOCCLUSION",this.useHorizonOcclusion,!0),i.setValue("UNLIT",this.unlit,!0),i.setValue("FORCENORMALFORWARD",this.forceNormalForward,!0),this._environmentBRDFTexture&&Sn.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){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};(0,Bt.lo)(s,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else(0,Bt.az)(s,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,(0,Bt.VO)(s,i)}updateUniformsAndSamples(e,t,i,r){for(let s=0;s=0;(0,Bt.GD)(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],r,t)}}isReady(e,t,i){return!(this._environmentBRDFTexture&&!this._environmentBRDFTexture.isReady()||i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}bind(e,t,i){if(!i)return;const r=i.getScene();this.light?(0,Bt.Kd)(this.light,this._lightId,r,e,!0):(0,Bt.RL)(r,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);const s=this._scene.ambientColor;s&&e.setColor3("ambientFromScene",s);const n=r.useRightHandedSystem===(null!=r._mirroredCameraPosition);e.setFloat(this._invertNormalName,n?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);const o=this.indexOfRefraction.connectInputBlock?.value??1.5,a=Math.pow((o-1)/(o+1),2);this._metallicReflectanceColor.scaleToRef(a*this._metallicF0Factor,H.IG.Color3[0]);const l=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,H.IG.Color3[0],l),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){const t=this.worldPosition,i=this.worldNormal,r=`//${this.name}`,s=1===e.shaderLanguage;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",r,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",r,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const n="v_"+t.associatedVariableName;e._emitVaryingFromString(n,Og.Vector4)&&(e.compilationString+=(s?"vertexOutputs.":"")+`${n} = ${t.associatedVariableName};\n`);const o="v_"+i.associatedVariableName;e._emitVaryingFromString(o,Og.Vector4)&&(e.compilationString+=(s?"vertexOutputs.":"")+`${o} = ${i.associatedVariableName};\n`);const a=this.reflection.isConnected?this.reflection.connectedPoint?.ownerBlock:null;a&&(a.viewConnectionPoint=this.view),e.compilationString+=a?.handleVertexSide(e)??"",e._emitVaryingFromString("vClipSpacePosition",Og.Vector4,"defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+="#if DEBUGMODE > 0\n",e._injectAtEnd+=(s?"vertexOutputs.":"")+`vClipSpacePosition = ${s?"vertexOutputs.position":"gl_Position"};\n`,e._injectAtEnd+="#endif\n"),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",r,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`${e._declareLocalVar("worldPos",Og.Vector4)} = ${t.associatedVariableName};\n`,this.view.isConnected&&(e.compilationString+=`${e._declareLocalVar("view",Og.Matrix)} = ${this.view.associatedVariableName};\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",r,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(e){let t=1===e.shaderLanguage?"var albedoOpacityOut: albedoOpacityOutParams;\n":"albedoOpacityOutParams albedoOpacityOut;\n";const i=this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)",r=this.opacity.isConnected?this.opacity.associatedVariableName:"1.";return t+=`albedoOpacityOut = albedoOpacityBlock(\n vec4${e.fSuffix}(${i}, 1.)\n #ifdef ALBEDO\n ,vec4${e.fSuffix}(1.)\n ,vec2${e.fSuffix}(1., 1.)\n #endif\n #ifdef OPACITY\n ,vec4${e.fSuffix}(${r})\n ,vec2${e.fSuffix}(1., 1.)\n #endif \n );\n\n ${e._declareLocalVar("surfaceAlbedo",Og.Vector3)} = albedoOpacityOut.surfaceAlbedo;\n ${e._declareLocalVar("alpha",Og.Float)} = albedoOpacityOut.alpha;\n`,t}_getAmbientOcclusionCode(e){let t=1===e.shaderLanguage?"var aoOut: ambientOcclusionOutParams;\n":"ambientOcclusionOutParams aoOut;\n";const i=this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1.";return t+=`aoOut = ambientOcclusionBlock(\n #ifdef AMBIENT\n vec3${e.fSuffix}(${i}),\n vec4${e.fSuffix}(0., 1.0, 1.0, 0.)\n #endif\n );\n`,t}_getReflectivityCode(e){const t=1===e.shaderLanguage;let i=t?"var reflectivityOut: reflectivityOutParams;\n":"reflectivityOutParams reflectivityOut;\n";return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,Og.Vector4),i+=`${e._declareLocalVar("baseColor",Og.Vector3)} = surfaceAlbedo;\n\n reflectivityOut = reflectivityBlock(\n vec4${e.fSuffix}(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.)\n #ifdef METALLICWORKFLOW\n , surfaceAlbedo\n , ${(t?"uniforms.":"")+this._vMetallicReflectanceFactorsName}\n #endif\n #ifdef REFLECTIVITY\n , vec3${e.fSuffix}(0., 0., 1.)\n , vec4${e.fSuffix}(1.)\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n , aoOut.ambientOcclusionColor\n #endif\n #ifdef MICROSURFACEMAP\n , microSurfaceTexel <== not handled!\n #endif\n );\n\n ${e._declareLocalVar("microSurface",Og.Float)} = reflectivityOut.microSurface;\n ${e._declareLocalVar("roughness",Og.Float)} = reflectivityOut.roughness;\n\n #ifdef METALLICWORKFLOW\n surfaceAlbedo = reflectivityOut.surfaceAlbedo;\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor;\n #endif\n`,i}_buildBlock(e){super._buildBlock(e),this._scene=e.sharedData.scene;const t=1===e.shaderLanguage;this._environmentBRDFTexture||(this._environmentBRDFTexture=Em(this._scene));const i=this.reflection.isConnected?this.reflection.connectedPoint?.ownerBlock:null;if(i&&(i.worldPositionConnectionPoint=this.worldPosition,i.cameraPositionConnectionPoint=this.cameraPosition,i.worldNormalConnectionPoint=this.worldNormal,i.viewConnectionPoint=this.view),e.target!==Dg.Fragment)return this._injectVertexCode(e),this;e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const r=`//${this.name}`,s=this.perturbedNormal;let n=this.worldPosition.associatedVariableName,o=this.worldNormal.associatedVariableName;this.generateOnlyFragmentCode?(n=e._getFreeVariableName("globalWorldPos"),e.compilationString+=`${n} = ${this.worldPosition.associatedVariableName}.xyz;\n`,o=e._getFreeVariableName("globalWorldNormal"),e.compilationString+=`${o} = ${this.worldNormal.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",r,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+="#if DEBUGMODE > 0\n",e.compilationString+=`${e._declareLocalVar("vClipSpacePosition",Og.Vector4)} = vec4${e.fSuffix}((vec2${e.fSuffix}(${t?"fragmentInputs.position":"gl_FragCoord.xy"}) / vec2${e.fSuffix}(1.0)) * 2.0 - 1.0, 0.0, 1.0);\n`,e.compilationString+="#endif\n"):(n=(t?"input.":"")+"v_"+n,o=(t?"input.":"")+"v_"+o),this._environmentBrdfSamplerName=e._getFreeVariableName("environmentBrdfSampler"),e._emit2DSampler(this._environmentBrdfSamplerName),e.sharedData.hints.needAlphaBlending=e.sharedData.hints.needAlphaBlending||this.useAlphaBlending,e.sharedData.hints.needAlphaTesting=e.sharedData.hints.needAlphaTesting||this.useAlphaTest,e._emitExtension("lod","#extension GL_EXT_shader_texture_lod : enable","defined(LODBASEDMICROSFURACE)"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitUniformFromString("vDebugMode",Og.Vector2,"defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene",Og.Vector3),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity"),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",r,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",r,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",r),e._emitFunctionFromInclude("importanceSampling",r),e._emitFunctionFromInclude("pbrHelperFunctions",r),e._emitFunctionFromInclude("imageProcessingDeclaration",r),e._emitFunctionFromInclude("imageProcessingFunctions",r),e._emitFunctionFromInclude("shadowsFragmentFunctions",r),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",r),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",r),e._emitFunctionFromInclude("pbrBRDFFunctions",r,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:i?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",r),e._emitFunctionFromInclude("pbrDirectLightingFunctions",r),e._emitFunctionFromInclude("pbrIBLFunctions",r),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",r),e._emitFunctionFromInclude("pbrBlockReflectivity",r),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",r),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",r),e._emitFunctionFromInclude("pbrBlockAnisotropic",r),e._emitUniformFromString("vLightingIntensity",Og.Vector4),i?.generateOnlyFragmentCode&&(e.compilationString+=i.handleVertexSide(e)),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+=`${e._declareLocalVar(this._vNormalWName,Og.Vector4)} = normalize(${o});\n`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`${e._declareLocalVar("viewDirectionW",Og.Vector3)} = normalize(${this.cameraPosition.associatedVariableName} - ${n}.xyz);\n`),e.compilationString+=`${e._declareLocalVar("geometricNormalW",Og.Vector3)} = ${this._vNormalWName}.xyz;\n`,e.compilationString+=`${e._declareLocalVar("normalW",Og.Vector3)} = ${s.isConnected?"normalize("+s.associatedVariableName+".xyz)":"geometricNormalW"};\n`,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,Og.Float),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",r,{replaceStrings:[{search:/vPositionW/g,replace:n+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(e),e.compilationString+=e._emitCodeFromInclude("depthPrePass",r),e.compilationString+=this._getAmbientOcclusionCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",r),e.compilationString+=`#ifdef UNLIT\n ${e._declareLocalVar("diffuseBase",Og.Vector3)} = vec3${e.fSuffix}(1., 1., 1.);\n #else\n`,e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",r,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:i?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:i?._define3DName??"REFLECTIONMAP_3D"}]});const a=this.anisotropy.isConnected?this.anisotropy.connectedPoint?.ownerBlock:null;a&&(a.worldPositionConnectionPoint=this.worldPosition,a.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=a.getCode(e,!this.perturbedNormal.isConnected)),i&&i.hasTexture&&(e.compilationString+=i.getCode(e,a?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",r,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:i?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:i?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:i?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:i?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:i?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:i?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:i?._vReflectionFilteringInfoName??"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",r,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:(t?"uniforms.":"")+this._vMetallicReflectanceFactorsName}]});const l=this.sheen.isConnected?this.sheen.connectedPoint?.ownerBlock:null;l&&(e.compilationString+=l.getCode(i,e)),e._emitFunctionFromInclude("pbrBlockSheen",r,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:i?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:i?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:i?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:i?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"}]});const h=this.iridescence.isConnected?this.iridescence.connectedPoint?.ownerBlock:null;e.compilationString+=BC.GetCode(h,e),e._emitFunctionFromInclude("pbrBlockIridescence",r,{replaceStrings:[]});const c=this.clearcoat.isConnected?this.clearcoat.connectedPoint?.ownerBlock:null,u=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,d=this.perturbedNormal.isConnected&&(this.perturbedNormal.connectedPoint?.ownerBlock).worldTangent?.isConnected,f=this.anisotropy.isConnected&&(this.anisotropy.connectedPoint?.ownerBlock).worldTangent.isConnected;let p=d||!this.perturbedNormal.isConnected&&f;e.compilationString+=LC.GetCode(e,c,i,n,u,p,o),u&&(p=c?.worldTangent.isConnected??!1),e._emitFunctionFromInclude("pbrBlockClearcoat",r,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:i?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:i?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:i?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:i?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:i?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:i?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:p?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",r,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:i?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:i?._define3DName??"REFLECTIONMAP_3D"}]});const _=this.subsurface.isConnected?this.subsurface.connectedPoint?.ownerBlock:null,m=this.subsurface.isConnected?(this.subsurface.connectedPoint?.ownerBlock).refraction.connectedPoint?.ownerBlock:null;m&&(m.viewConnectionPoint=this.view,m.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=kC.GetCode(e,_,i,n),e._emitFunctionFromInclude("pbrBlockSubSurface",r,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:i?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:i?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:i?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:m?._define3DName??"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:m?._defineLODRefractionAlpha??"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:m?._defineLinearSpecularRefraction??"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:m?._defineOppositeZ??"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",r),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",r,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:new RegExp((t?"fragmentInputs.":"")+"vPositionW","g"),replace:n+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",r,{repeatKey:"maxSimultaneousLights",substitutionVars:`${t?"fragmentInputs.":""}vPositionW,${n}.xyz`}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",r),e.compilationString+="#endif\n";const g=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:`vec3${e.fSuffix}(0., 0., 0.)`;let v=Gm.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();-1===v.indexOf(".")&&(v+=".");let x=[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:new RegExp((t?"uniforms.":"")+"vAmbientColor","g"),replace:g+` * ${t?"uniforms.":""}ambientFromScene`},{search:new RegExp((t?"uniforms.":"")+"vAmbientInfos.w","g"),replace:v}];t&&(x[0]={search:/var finalEmissive[\s\S]*?finalEmissive\*=uniforms.vLightingIntensity\.y;/g,replace:""}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",r,{replaceStrings:x}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",r,{replaceStrings:[{search:/finalEmissive/g,replace:`vec3${e.fSuffix}(0.)`}]}),x=t?[{search:/mesh.visibility/g,replace:"1."}]:[{search:/visibility/g,replace:"1."}],e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",r,{replaceStrings:x});const b=t?"fragmentOutputs.color":"gl_FragColor";x=[{search:new RegExp((t?"fragmentInputs.":"")+"vNormalW","g"),replace:this._vNormalWName},{search:new RegExp((t?"fragmentInputs.":"")+"vPositionW","g"),replace:n},{search:/albedoTexture\.rgb;/g,replace:`vec3${e.fSuffix}(1.);\n${b}.rgb = toGammaSpace(${b}.rgb);\n`}],e.compilationString+=e._emitCodeFromInclude("pbrDebug",r,{replaceStrings:x});for(const t of this._outputs)if(t.hasEndpoints){const i=UC[t.name];if(i){const[r,s]=i;s&&(e.compilationString+=`#if ${s}\n`),e.compilationString+=`${e._declareOutput(t)} = ${r};\n`,s&&(e.compilationString+="#else\n",e.compilationString+=`${e._declareOutput(t)} = vec3${e.fSuffix}(0.);\n`,e.compilationString+="#endif\n")}else Z.V.Error(`There's no remapping for the ${t.name} end point! No code generated`)}return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.lightFalloff = ${this.lightFalloff};\n`,e+=`${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest};\n`,e+=`${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff};\n`,e+=`${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending};\n`,e+=`${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha};\n`,e+=`${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha};\n`,e+=`${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing};\n`,e+=`${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering};\n`,e+=`${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality};\n`,e+=`${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation};\n`,e+=`${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion};\n`,e+=`${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion};\n`,e+=`${this._codeVariableName}.unlit = ${this.unlit};\n`,e+=`${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward};\n`,e+=`${this._codeVariableName}.debugMode = ${this.debugMode};\n`,e+=`${this._codeVariableName}.debugLimit = ${this.debugLimit};\n`,e+=`${this._codeVariableName}.debugFactor = ${this.debugFactor};\n`,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()}}(0,je.Cg)([t_("Direct lights",1,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],GC.prototype,"directIntensity",void 0),(0,je.Cg)([t_("Environment lights",1,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],GC.prototype,"environmentIntensity",void 0),(0,je.Cg)([t_("Specular highlights",1,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],GC.prototype,"specularIntensity",void 0),(0,je.Cg)([t_("Light falloff",4,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:Gm.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:Gm.LIGHTFALLOFF_GLTF},{label:"Standard",value:Gm.LIGHTFALLOFF_STANDARD}]})],GC.prototype,"lightFalloff",void 0),(0,je.Cg)([t_("Alpha Testing",0,"OPACITY")],GC.prototype,"useAlphaTest",void 0),(0,je.Cg)([t_("Alpha CutOff",1,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],GC.prototype,"alphaTestCutoff",void 0),(0,je.Cg)([t_("Alpha blending",0,"OPACITY")],GC.prototype,"useAlphaBlending",void 0),(0,je.Cg)([t_("Radiance over alpha",0,"RENDERING",{notifiers:{update:!0}})],GC.prototype,"useRadianceOverAlpha",void 0),(0,je.Cg)([t_("Specular over alpha",0,"RENDERING",{notifiers:{update:!0}})],GC.prototype,"useSpecularOverAlpha",void 0),(0,je.Cg)([t_("Specular anti-aliasing",0,"RENDERING",{notifiers:{update:!0}})],GC.prototype,"enableSpecularAntiAliasing",void 0),(0,je.Cg)([t_("Realtime filtering",0,"RENDERING",{notifiers:{update:!0}})],GC.prototype,"realTimeFiltering",void 0),(0,je.Cg)([t_("Realtime filtering quality",4,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],GC.prototype,"realTimeFilteringQuality",void 0),(0,je.Cg)([t_("Energy Conservation",0,"ADVANCED",{notifiers:{update:!0}})],GC.prototype,"useEnergyConservation",void 0),(0,je.Cg)([t_("Radiance occlusion",0,"ADVANCED",{notifiers:{update:!0}})],GC.prototype,"useRadianceOcclusion",void 0),(0,je.Cg)([t_("Horizon occlusion",0,"ADVANCED",{notifiers:{update:!0}})],GC.prototype,"useHorizonOcclusion",void 0),(0,je.Cg)([t_("Unlit",0,"ADVANCED",{notifiers:{update:!0}})],GC.prototype,"unlit",void 0),(0,je.Cg)([t_("Force normal forward",0,"ADVANCED",{notifiers:{update:!0}})],GC.prototype,"forceNormalForward",void 0),(0,je.Cg)([t_("Generate only fragment code",0,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:GC._OnGenerateOnlyFragmentCodeChanged}})],GC.prototype,"generateOnlyFragmentCode",void 0),(0,je.Cg)([t_("Debug mode",4,"DEBUG",{notifiers:{update:!0},options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87},{label:"Albedo color",value:88},{label:"Ambient occlusion color",value:89}]})],GC.prototype,"debugMode",void 0),(0,je.Cg)([t_("Split position",1,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],GC.prototype,"debugLimit",void 0),(0,je.Cg)([t_("Output factor",1,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],GC.prototype,"debugFactor",void 0),(0,X.Y5)("BABYLON.PBRMetallicRoughnessBlock",GC);class zC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("left",Og.AutoDetect),this.registerInput("right",Og.AutoDetect),this.registerOutput("output",Og.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[1].acceptedConnectionPointTypes.push(Og.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 0===e.shaderLanguage?e.compilationString+=e._declareOutput(t)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`:e.compilationString+=e._declareOutput(t)+` = (${this.left.associatedVariableName} % ${this.right.associatedVariableName});\n`,this}}(0,X.Y5)("BABYLON.ModBlock",zC);class WC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("row0",Og.Vector4),this.registerInput("row1",Og.Vector4),this.registerInput("row2",Og.Vector4),this.registerInput("row3",Og.Vector4),this.registerOutput("output",Og.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 Kg("row0");e.value=new W.IU(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){const e=new Kg("row1");e.value=new W.IU(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){const e=new Kg("row2");e.value=new W.IU(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){const e=new Kg("row3");e.value=new W.IU(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.row0,r=this.row1,s=this.row2,n=this.row3,o=1===e.shaderLanguage?"mat4x4f":"mat4";return e.compilationString+=e._declareOutput(t)+` = ${o}(${i.associatedVariableName}, ${r.associatedVariableName}, ${s.associatedVariableName}, ${n.associatedVariableName});\n`,this}}var HC,XC,qC;(0,X.Y5)("BABYLON.MatrixBuilder",WC),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(HC||(HC={}));class YC extends Gg{constructor(e){super(e,Dg.Neutral),this.condition=HC.LessThan,this.registerInput("a",Og.Float),this.registerInput("b",Og.Float),this.registerInput("true",Og.AutoDetect,!0),this.registerInput("false",Og.AutoDetect,!0),this.registerOutput("output",Og.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=Og.Float}getClassName(){return"ConditionalBlock"}get a(){return this._inputs[0]}get b(){return this._inputs[1]}get true(){return this._inputs[2]}get false(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.true.isConnected?this.true.associatedVariableName:"1.0",r=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case HC.Equal:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`${this.a.associatedVariableName} == ${this.b.associatedVariableName}`)};\n`;break;case HC.NotEqual:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`${this.a.associatedVariableName} != ${this.b.associatedVariableName}`)};\n`;break;case HC.LessThan:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`${this.a.associatedVariableName} < ${this.b.associatedVariableName}`)};\n`;break;case HC.LessOrEqual:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`${this.a.associatedVariableName} <= ${this.b.associatedVariableName}`)};\n`;break;case HC.GreaterThan:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`${this.a.associatedVariableName} > ${this.b.associatedVariableName}`)};\n`;break;case HC.GreaterOrEqual:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`${this.a.associatedVariableName} >= ${this.b.associatedVariableName}`)};\n`;break;case HC.Xor:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`(((${this.a.associatedVariableName} + ${this.b.associatedVariableName}) % 2.0) > 0.0)`)};\n`;break;case HC.Or:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`(min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0)`)};\n`;break;case HC.And:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`(${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0)`)};\n`}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.${HC[this.condition]};\n`}}(0,je.Cg)([t_("Condition",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"Equal",value:HC.Equal},{label:"NotEqual",value:HC.NotEqual},{label:"LessThan",value:HC.LessThan},{label:"GreaterThan",value:HC.GreaterThan},{label:"LessOrEqual",value:HC.LessOrEqual},{label:"GreaterOrEqual",value:HC.GreaterOrEqual},{label:"Xor",value:HC.Xor},{label:"And",value:HC.And},{label:"Or",value:HC.Or}]})],YC.prototype,"condition",void 0),(0,X.Y5)("BABYLON.ConditionalBlock",YC);class KC extends Gg{constructor(e){super(e,Dg.Neutral),this.octaves=6,this.registerInput("seed",Og.AutoDetect),this.registerInput("chaos",Og.AutoDetect,!0),this.registerInput("offsetX",Og.Float,!0),this.registerInput("offsetY",Og.Float,!0),this.registerInput("offsetZ",Og.Float,!0),this.registerOutput("output",Og.Float),this._inputs[0].acceptedConnectionPointTypes.push(Og.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(Og.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){if(super._buildBlock(e),!this.seed.isConnected)return;if(!this._outputs[0].hasEndpoints)return;let t="\n\n float cloudRandom(float p) { \n float temp = fract(p * 0.011); \n temp *= temp + 7.5; \n temp *= temp + temp; \n return fract(temp); \n }\n\n // Based on Morgan McGuire @morgan3d\n // https://www.shadertoy.com/view/4dS3Wd\n float cloudNoise2(vec2 x, vec2 chaos) {\n vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.);\n\n vec2 i = floor(x);\n vec2 f = fract(x);\n\n float n = dot(i, step);\n\n vec2 u = f * f * (3.0 - 2.0 * f);\n return mix(\n mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x),\n mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x),\n u.y\n );\n }\n\n float cloudNoise3(vec3 x, vec3 chaos) {\n vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.);\n\n vec3 i = floor(x);\n vec3 f = fract(x);\n\n float n = dot(i, step);\n\n vec3 u = f * f * (3.0 - 2.0 * f);\n return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y),\n mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z);\n }",i="\n float fbm2(vec2 st, vec2 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = .5;\n float frequency = 0.;\n\n // Loop of octaves\n vec2 tempST = st;\n for (int i = 0; i < OCTAVES; i++) {\n value += amplitude * cloudNoise2(tempST, chaos);\n tempST *= 2.0;\n amplitude *= 0.5;\n }\n return value;\n }\n\n float fbm3(vec3 x, vec3 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = 0.5;\n vec3 tempX = x;\n for (int i = 0; i < OCTAVES; i++) {\n value += amplitude * cloudNoise3(tempX, chaos);\n tempX = tempX * 2.0;\n amplitude *= 0.5;\n }\n return value;\n }";1===e.shaderLanguage&&(t=e._babylonSLtoWGSL(t),i=e._babylonSLtoWGSL(i));const r=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode",t,"// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,i.replace(/fbm/gi,r).replace(/OCTAVES/gi,(0|this.octaves).toString()),"// CloudBlockCode FBM");const s=e._getFreeVariableName("st"),n=this.seed.connectedPoint?.type||Og.Vector3;e.compilationString+=`${e._declareLocalVar(s,n)} = ${this.seed.associatedVariableName};\n`,this.offsetX.isConnected&&(e.compilationString+=`${s}.x += 0.1 * ${this.offsetX.associatedVariableName};\n`),this.offsetY.isConnected&&(e.compilationString+=`${s}.y += 0.1 * ${this.offsetY.associatedVariableName};\n`),this.offsetZ.isConnected&&n===Og.Vector3&&(e.compilationString+=`${s}.z += 0.1 * ${this.offsetZ.associatedVariableName};\n`);let o="";if(this.chaos.isConnected)o=this.chaos.associatedVariableName;else{const t=e.fSuffix;o=this.seed.connectedPoint?.type===Og.Vector2?`vec2${t}(0., 0.)`:`vec3${t}(0., 0., 0.)`}return e.compilationString+=e._declareOutput(this._outputs[0])+` = ${r}${this.seed.connectedPoint?.type===Og.Vector2?"2":"3"}(${s}, ${o});\n`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves};\n`}serialize(){const e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}}(0,je.Cg)([t_("Octaves",2,void 0,{embedded:!0})],KC.prototype,"octaves",void 0),(0,X.Y5)("BABYLON.CloudBlock",KC);class jC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("seed",Og.Vector2),this.registerInput("offset",Og.Float),this.registerInput("density",Og.Float),this.registerOutput("output",Og.Float),this.registerOutput("cells",Og.Float)}getClassName(){return"VoronoiNoiseBlock"}get seed(){return this._inputs[0]}get offset(){return this._inputs[1]}get density(){return this._inputs[2]}get output(){return this._outputs[0]}get cells(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;let t="vec2 voronoiRandom(vec2 p){\n p = vec2(dot(p,vec2(127.1,311.7)),dot(p,vec2(269.5,183.3)));\n return fract(sin(p)*18.5453);\n }\n ";1===e.shaderLanguage&&(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){\n vec2 n = floor(seed * density);\n vec2 f = fract(seed * density);\n vec3 m = vec3( 8.0 );\n for( int j=-1; j<=1; j++ ){\n for( int i=-1; i<=1; i++ ){\n vec2 g = vec2( float(i), float(j) );\n vec2 o = voronoiRandom( n + g);\n vec2 r = g - f + (0.5+0.5*sin(offset+6.2831*o));\n float d = dot( r, r );\n if( de.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get textureY(){return this.sourceY.isConnected?(this.sourceY.connectedPoint?.ownerBlock).texture:null}get textureZ(){return this.sourceZ?.isConnected?(this.sourceY.connectedPoint?.ownerBlock).texture:null}_getImageSourceBlock(e){return e?.isConnected?e.connectedPoint.ownerBlock:null}get samplerName(){const e=this._getImageSourceBlock(this.source);return e?e.samplerName:this._samplerName}get samplerYName(){return this._getImageSourceBlock(this.sourceY)?.samplerName??null}get samplerZName(){return this._getImageSourceBlock(this.sourceZ)?.samplerName??null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const e=this.texture.getScene()??he.q.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=this.texture.getScene()??he.q.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,Dg.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",Og.AutoDetect,!1),this.registerInput("normal",Og.AutoDetect,!1),this.registerInput("sharpness",Og.Float,!0),this.registerInput("source",Og.Object,!0,Dg.VertexAndFragment,new cS("source",this,0,dT,"ImageSourceBlock")),this.registerInput("sourceY",Og.Object,!0,Dg.VertexAndFragment,new cS("sourceY",this,0,dT,"ImageSourceBlock")),t||this.registerInput("sourceZ",Og.Object,!0,Dg.VertexAndFragment,new cS("sourceZ",this,0,dT,"ImageSourceBlock")),this.registerOutput("rgba",Og.Color4,Dg.Neutral),this.registerOutput("rgb",Og.Color3,Dg.Neutral),this.registerOutput("r",Og.Float,Dg.Neutral),this.registerOutput("g",Og.Float,Dg.Neutral),this.registerOutput("b",Og.Float,Dg.Neutral),this.registerOutput("a",Og.Float,Dg.Neutral),this.registerOutput("level",Og.Float,Dg.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(Og.Color3|Og.Vector3|Og.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(Og.Color3|Og.Vector3|Og.Vector4)}getClassName(){return"TriPlanarBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get sharpness(){return this._inputs[2]}get source(){return this._inputs[3]}get sourceY(){return this._inputs[4]}get sourceZ(){return this._inputs[5]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,s,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))}_samplerFunc(e){return 1===e.shaderLanguage?"textureSample":"texture2D"}_generateTextureSample(e,t,i){return 1===i.shaderLanguage?`${this._samplerFunc(i)}(${e},${e+"Sampler"}, ${t})`:`${this._samplerFunc(i)}(${e}, ${t})`}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??t,r=this.samplerZName??t,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",n=e._getFreeVariableName("x"),o=e._getFreeVariableName("y"),a=e._getFreeVariableName("z"),l=e._getFreeVariableName("w"),h=e._getFreeVariableName("n"),c=e._getFreeVariableName("uvx"),u=e._getFreeVariableName("uvy"),d=e._getFreeVariableName("uvz");e.compilationString+=`\n ${e._declareLocalVar(h,Og.Vector3)} = ${this.normal.associatedVariableName}.xyz;\n\n ${e._declareLocalVar(c,Og.Vector2)} = ${this.position.associatedVariableName}.yz;\n ${e._declareLocalVar(u,Og.Vector2)} = ${this.position.associatedVariableName}.zx;\n ${e._declareLocalVar(d,Og.Vector2)} = ${this.position.associatedVariableName}.xy;\n `,this.projectAsCube&&(e.compilationString+=`\n ${c}.xy = ${c}.yx;\n\n if (${h}.x >= 0.0) {\n ${c}.x = -${c}.x;\n }\n if (${h}.y < 0.0) {\n ${u}.y = -${u}.y;\n }\n if (${h}.z < 0.0) {\n ${d}.x = -${d}.x;\n }\n `);const f=e.fSuffix;e.compilationString+=`\n ${e._declareLocalVar(n,Og.Vector4)} = ${this._generateTextureSample(t,c,e)};\n ${e._declareLocalVar(o,Og.Vector4)} = ${this._generateTextureSample(i,u,e)};\n ${e._declareLocalVar(a,Og.Vector4)} = ${this._generateTextureSample(r,d,e)};\n \n // blend weights\n ${e._declareLocalVar(l,Og.Vector3)} = pow(abs(${h}), vec3${f}(${s}));\n\n // blend and return\n ${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = (${n}*${l}.x + ${o}*${l}.y + ${a}*${l}.z) / (${l}.x + ${l}.y + ${l}.z); \n `}_generateConversionCode(e,t,i){let r="";1!==e.shaderLanguage||t.type!==Og.Vector3&&t.type!==Og.Color3||(r="Vec3"),"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace${r}(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = toLinearSpace${r}(${t.associatedVariableName});\n #endif\n `)}_writeOutput(e,t,i){let r="";this.disableLevelMultiplication||(r=` * ${1===e.shaderLanguage?"uniforms.":""}${this._textureInfoName}`),e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}${r};\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=(1===e.shaderLanguage?"uniforms.":"")+this._textureInfoName,this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA"),this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Texture"),e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,Og.Float),this._generateTextureLookup(e);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\n`,e+=`${this._codeVariableName}.projectAsCube = ${this.projectAsCube};\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):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||"VideoTexture"===this.texture.getClassName()||(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&&!pv.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=vi.g.Parse(e.texture,t,i))}}(0,je.Cg)([t_("Project as cube",0,"ADVANCED",{embedded:!0,notifiers:{update:!0}})],QC.prototype,"projectAsCube",void 0),(0,X.Y5)("BABYLON.TriPlanarBlock",QC);class ZC extends QC{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_declareLocalVarAsVec3I(e,t){return 1===t.shaderLanguage?`var ${e}: vec3`:`ivec3 ${e}`}_getTextureGrad(e,t){return 1===e.shaderLanguage?`textureSampleGrad(${t},${t+"Sampler"}`:`textureGrad(${t}`}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??this.samplerName,r=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",s=e._getFreeVariableName("dxValue"),n=e._getFreeVariableName("dyValue"),o=e._getFreeVariableName("n"),a=e._getFreeVariableName("ma"),l=e._getFreeVariableName("mi"),h=e._getFreeVariableName("me"),c=e._getFreeVariableName("x"),u=e._getFreeVariableName("y"),d=e._getFreeVariableName("w");let f="ivec3",p="dFdx",_="dFdy";const m=e.fSuffix;1===e.shaderLanguage&&(f="vec3",p="dpdx",_="dpdy"),e.compilationString+=`\n // grab coord derivatives for texturing\n ${e._declareLocalVar(s,Og.Vector3)} = ${p}(${this.position.associatedVariableName}.xyz);\n ${e._declareLocalVar(n,Og.Vector3)} = ${_}(${this.position.associatedVariableName}.xyz);\n ${e._declareLocalVar(o,Og.Vector3)} = abs(${this.normal.associatedVariableName}.xyz);\n \n // determine major axis (in x; yz are following axis)\n ${this._declareLocalVarAsVec3I(a,e)} = ${e._generateTernary(`${f}(0,1,2)`,`${e._generateTernary(`${f}(1,2,0)`,`${f}(2,0,1)`,`(${o}.y>${o}.z)`)}`,`(${o}.x>${o}.y && ${o}.x>${o}.z)`)}; \n\n // determine minor axis (in x; yz are following axis)\n ${this._declareLocalVarAsVec3I(l,e)} = ${e._generateTernary(`${f}(0,1,2)`,`${e._generateTernary(`${f}(1,2,0)`,`${f}(2,0,1)`,`(${o}.y<${o}.z)`)}`,`(${o}.x<${o}.y && ${o}.x<${o}.z)`)}; \n \n // determine median axis (in x; yz are following axis)\n ${this._declareLocalVarAsVec3I(h,e)} = ${f}(3) - ${l} - ${a};\n \n // project+fetch\n ${e._declareLocalVar(c,Og.Vector4)} = ${this._getTextureGrad(e,t)}, vec2${m}(${this.position.associatedVariableName}[${a}.y], ${this.position.associatedVariableName}[${a}.z]), \n vec2${m}(${s}[${a}.y],${s}[${a}.z]), \n vec2${m}(${n}[${a}.y],${n}[${a}.z]));\n ${e._declareLocalVar(u,Og.Vector4)} = ${this._getTextureGrad(e,i)}, vec2${m}(${this.position.associatedVariableName}[${h}.y], ${this.position.associatedVariableName}[${h}.z]), \n vec2${m}(${s}[${h}.y],${s}[${h}.z]),\n vec2${m}(${n}[${h}.y],${n}[${h}.z]));\n \n // blend factors\n ${e._declareLocalVar(d,Og.Vector2)} = vec2${m}(${o}[${a}.x],${o}[${h}.x]);\n // make local support\n ${d} = clamp( (${d}-0.5773)/(1.0-0.5773), vec2${m}(0.0), vec2${m}(1.0) );\n // shape transition\n ${d} = pow( ${d}, vec2${m}(${r}/8.0) );\n // blend and return\n ${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = (${c}*${d}.x + ${u}*${d}.y) / (${d}.x + ${d}.y);\n `}}(0,X.Y5)("BABYLON.BiPlanarBlock",ZC);class JC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("input",Og.Matrix),this.registerOutput("output",Og.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});\n`,this}}(0,X.Y5)("BABYLON.MatrixDeterminantBlock",JC);class ey extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("input",Og.Matrix),this.registerOutput("output",Og.Matrix)}getClassName(){return"MatrixTransposeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=e._declareOutput(t)+` = transpose(${i.associatedVariableName});\n`,this}}(0,X.Y5)("BABYLON.MatrixTransposeBlock",ey),function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Tangent=2]="Tangent",e[e.VertexColor=3]="VertexColor",e[e.UV1=4]="UV1",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6"}(XC||(XC={}));class ty extends Gg{constructor(e){super(e,Dg.Neutral),this.attributeType=0,this.registerInput("input",Og.AutoDetect),this.registerInput("fallback",Og.AutoDetect),this.registerOutput("output",Og.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add((e=>{if(this.attributeType)return;const t=e.ownerBlock;if(t instanceof Kg&&t.isAttribute)switch(t.name){case"color":this.attributeType=3;break;case"normal":this.attributeType=1;break;case"tangent":this.attributeType=2;break;case"uv":this.attributeType=4;break;case"uv2":this.attributeType=5;break;case"uv3":this.attributeType=6;break;case"uv4":this.attributeType=7;break;case"uv5":this.attributeType=8;break;case"uv6":this.attributeType=9}else if(t instanceof xS)switch(this.input.connectedPoint?.name){case"normalOutput":this.attributeType=1;break;case"tangentOutput":this.attributeType=2;break;case"uvOutput":this.attributeType=4}}))}getClassName(){return"MeshAttributeExistsBlock"}get input(){return this._inputs[0]}get fallback(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.attributeType){case 3:t="VERTEXCOLOR_NME";break;case 1:t="NORMAL";break;case 2:t="TANGENT";break;case 4:t="UV1";break;case 5:t="UV2";break;case 6:t="UV3";break;case 7:t="UV4";break;case 8:t="UV5";break;case 9:t="UV6"}const i=e._declareOutput(this.output);return t&&(e.compilationString+=`#ifdef ${t}\n`),e.compilationString+=`${i} = ${this.input.associatedVariableName};\n`,t&&(e.compilationString+="#else\n",e.compilationString+=`${i} = ${this.fallback.associatedVariableName};\n`,e.compilationString+="#endif\n"),this}serialize(){const e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.attributeType=e.attributeType??0}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.attributeType = ${this.attributeType};\n`,e}}(0,je.Cg)([t_("Attribute lookup",4,void 0,{notifiers:{update:!0},embedded:!0,options:[{label:"(None)",value:0},{label:"Normal",value:1},{label:"Tangent",value:2},{label:"Vertex Color",value:3},{label:"UV1",value:4},{label:"UV2",value:5},{label:"UV3",value:6},{label:"UV4",value:7},{label:"UV5",value:8},{label:"UV6",value:9}]})],ty.prototype,"attributeType",void 0),(0,X.Y5)("BABYLON.MeshAttributeExistsBlock",ty),function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(qC||(qC={}));class iy extends Gg{constructor(e){super(e,Dg.Neutral),this.type=qC.EaseInOutSine,this.registerInput("input",Og.AutoDetect),this.registerOutput("output",Og.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Og.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Og.Object),this._inputs[0].excludedConnectionPointTypes.push(Og.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("float"===t||"f32"===t)return this._duplicateEntryDirect(e);const r=parseInt(t.replace("vec",""));let s=i?`\n var ret: vec${r}f = vec${r}f(0.0);\n `:`\n vec${r} ret = vec${r}(0.0);\n `;for(let t=1;t<=r;t++)s+=this._duplicateEntry(e,1===t?"x":2===t?"y":3===t?"z":"w")+";\n";return s+="return ret;\n",s}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="",r="";const s=e._getShaderType(this.input.type),n=1===e.shaderLanguage;switch(r=qC[this.type]+"_"+s.replace("<","").replace(">",""),this.type){case qC.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case qC.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case qC.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case qC.EaseInQuad:i="return v * v";break;case qC.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case qC.EaseInOutQuad:{const t=e._generateTernary("2.0 * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,s,n);break}case qC.EaseInCubic:i="return v * v * v";break;case qC.EaseOutCubic:{const e="1.0 - pow(1.0 - VAL, 3.0)";i=this._duplicateVector(e,s,n);break}case qC.EaseInOutCubic:{const t=e._generateTernary("4.0 * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,s,n);break}case qC.EaseInQuart:i="return v * v * v * v";break;case qC.EaseOutQuart:{const e="1.0 - pow(1.0 - VAL, 4.0)";i=this._duplicateVector(e,s,n);break}case qC.EaseInOutQuart:{const t=e._generateTernary("8.0 * VAL * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,s,n);break}case qC.EaseInQuint:i="return v * v * v * v * v";break;case qC.EaseOutQuint:{const e="1.0 - pow(1.0 - VAL, 5.0)";i=this._duplicateVector(e,s,n);break}case qC.EaseInOutQuint:{const t=e._generateTernary("16.0 * VAL * VAL * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,s,n);break}case qC.EaseInExpo:{const t=e._generateTernary("0.0","pow(2.0, 10.0 * VAL - 10.0)","VAL == 0.0");i=this._duplicateVector(t,s,n);break}case qC.EaseOutExpo:{const t=e._generateTernary("1.0","1.0 - pow(2.0, -10.0 * VAL)","VAL == 1.0");i=this._duplicateVector(t,s,n);break}case qC.EaseInOutExpo:{const t=e._generateTernary("0.0",e._generateTernary("1.0",e._generateTernary("pow(2.0, 20.0 * VAL - 10.0) / 2.0","(2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0","VAL < 0.5"),"VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,s,n);break}case qC.EaseInCirc:{const e="1.0 - sqrt(1.0 - pow(VAL, 2.0))";i=this._duplicateVector(e,s,n);break}case qC.EaseOutCirc:{const e="sqrt(1.0 - pow(VAL - 1.0, 2.0))";i=this._duplicateVector(e,s,n);break}case qC.EaseInOutCirc:{const t=e._generateTernary("(1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0","(sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,s,n);break}case qC.EaseInBack:i="return 2.70158 * v * v * v - 1.70158 * v * v";break;case qC.EaseOutBack:{const e="2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)";i=this._duplicateVector(e,s,n);break}case qC.EaseInOutBack:{const t=e._generateTernary("(pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0","(pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,s,n);break}case qC.EaseInElastic:{const t=e._generateTernary("0.0",e._generateTernary("1.0","-pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))","VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,s,n);break}case qC.EaseOutElastic:{const t=e._generateTernary("0.0",e._generateTernary("1.0","pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0","VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,s,n);break}case qC.EaseInOutElastic:{const t=e._generateTernary("0.0",e._generateTernary("1.0",e._generateTernary("-(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0","(pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0","VAL < 0.5"),"VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,s,n);break}}return n?e._emitFunction(r,`fn ${r}(v: ${s}) -> ${s} {${i};}\n`,""):e._emitFunction(r,`${s} ${r}(${s} v) {${i};}\n`,""),e.compilationString+=e._declareOutput(t)+` = ${r}(${this.input.associatedVariableName});\n`,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.${qC[this.type]};\n`}}(0,je.Cg)([t_("Type",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"EaseInSine",value:qC.EaseInSine},{label:"EaseOutSine",value:qC.EaseOutSine},{label:"EaseInOutSine",value:qC.EaseInOutSine},{label:"EaseInQuad",value:qC.EaseInQuad},{label:"EaseOutQuad",value:qC.EaseOutQuad},{label:"EaseInOutQuad",value:qC.EaseInOutQuad},{label:"EaseInCubic",value:qC.EaseInCubic},{label:"EaseOutCubic",value:qC.EaseOutCubic},{label:"EaseInOutCubic",value:qC.EaseInOutCubic},{label:"EaseInQuart",value:qC.EaseInQuart},{label:"EaseOutQuart",value:qC.EaseOutQuart},{label:"EaseInOutQuart",value:qC.EaseInOutQuart},{label:"EaseInQuint",value:qC.EaseInQuint},{label:"EaseOutQuint",value:qC.EaseOutQuint},{label:"EaseInOutQuint",value:qC.EaseInOutQuint},{label:"EaseInExpo",value:qC.EaseInExpo},{label:"EaseOutExpo",value:qC.EaseOutExpo},{label:"EaseInOutExpo",value:qC.EaseInOutExpo},{label:"EaseInCirc",value:qC.EaseInCirc},{label:"EaseOutCirc",value:qC.EaseOutCirc},{label:"EaseInOutCirc",value:qC.EaseInOutCirc},{label:"EaseInBack",value:qC.EaseInBack},{label:"EaseOutBack",value:qC.EaseOutBack},{label:"EaseInOutBack",value:qC.EaseInOutBack},{label:"EaseInElastic",value:qC.EaseInElastic},{label:"EaseOutElastic",value:qC.EaseOutElastic},{label:"EaseInOutElastic",value:qC.EaseInOutElastic}]})],iy.prototype,"type",void 0),(0,X.Y5)("BABYLON.CurveBlock",iy);class ry extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("rgb ",Og.Color3,!0),this.registerInput("hsl ",Og.Color3,!0),this.registerOutput("rgb",Og.Color3),this.registerOutput("hsl",Og.Color3)}getClassName(){return"ColorConverterBlock"}get rgbIn(){return this._inputs[0]}get hslIn(){return this._inputs[1]}get rgbOut(){return this._outputs[0]}get hslOut(){return this._outputs[1]}_inputRename(e){return"rgb "===e?"rgbIn":"hsl "===e?"hslIn":e}_buildBlock(e){super._buildBlock(e);const t=this.rgbIn,i=this.hslIn,r=this._outputs[0],s=this._outputs[1],n=e._getShaderType(Og.Vector3);let o="\n vec3 rgb2hsl(vec3 color) {\n float r = color.r;\n float g = color.g;\n float b = color.b;\n\n float maxc = max(r, max(g, b));\n float minc = min(r, min(g, b));\n float h = 0.0;\n float s = 0.0;\n float l = (maxc + minc) / 2.0;\n\n if (maxc != minc) {\n float d = maxc - minc;\n if (l > 0.5) {\n s = d / (2.0 - maxc - minc);\n } else {\n s = d / (maxc + minc);\n }\n\n if (maxc == r) {\n float add = 0.0;\n if (g < b) {\n add = 6.0;\n }\n h = (g - b) / d + add;\n } else if (maxc == g) {\n h = (b - r) / d + 2.0;\n } else if (maxc == b) {\n h = (r - g) / d + 4.0;\n }\n h /= 6.0;\n }\n\n return vec3(h, s, l);\n }",a="\n float hue2rgb(float p, float q, float tt) {\n float t = tt;\n if (t < 0.0) {\n t += 1.0;\n }\n if (t > 1.0) {\n t -= 1.0;\n }\n if (t < 1.0/6.0) {\n return p + (q - p) * 6.0 * t;\n }\n if (t < 1.0/2.0) {\n return q;\n }\n if (t < 2.0/3.0) {\n return p + (q - p) * (2.0/3.0 - t) * 6.0;\n }\n return p;\n }",l="\n vec3 hsl2rgb(vec3 hsl) {\n float h = hsl.x;\n float s = hsl.y;\n float l = hsl.z;\n\n float r;\n float g;\n float b;\n\n if (s == 0.0) {\n // Achromatic (grey)\n r = l;\n g = l;\n b = l; \n } else {\n float q;\n \n if (l < 0.5) {\n q = l * (1.0 + s);\n } else {\n q = (l + s - l * s);\n }\n\n float p = 2.0 * l - q;\n\n r = hue2rgb(p, q, h + 1.0/3.0);\n g = hue2rgb(p, q, h);\n b = hue2rgb(p, q, h - 1.0/3.0);\n }\n\n return vec3(r, g, b);\n }";return 1===e.shaderLanguage&&(o=e._babylonSLtoWGSL(o),a=e._babylonSLtoWGSL(a),l=e._babylonSLtoWGSL(l)),e._emitFunction("rgb2hsl",o,""),e._emitFunction("hue2rgb",a,""),e._emitFunction("hsl2rgb",l,""),t.isConnected?(r.hasEndpoints&&(e.compilationString+=e._declareOutput(r)+` = ${t.associatedVariableName};\n`),s.hasEndpoints&&(e.compilationString+=e._declareOutput(s)+` = rgb2hsl(${t.associatedVariableName});\n`)):i.isConnected?(r.hasEndpoints&&(e.compilationString+=e._declareOutput(r)+` = hsl2rgb(${i.associatedVariableName});\n`),s.hasEndpoints&&(e.compilationString+=e._declareOutput(s)+` = ${i.associatedVariableName};\n`)):(r.hasEndpoints&&(e.compilationString+=e._declareOutput(r)+` = ${n}(0.);\n`),s.hasEndpoints&&(e.compilationString+=e._declareOutput(s)+` = ${n}(0.);\n`)),this}}(0,X.Y5)("BABYLON.ColorConverterBlock",ry);class sy extends Gg{constructor(e){super(e,Dg.Neutral),this.iterations=4,this.registerInput("input",Og.AutoDetect),this.registerInput("iterations",Og.Float,!0),this.registerOutput("output",Og.BasedOnInput),this.registerOutput("index",Og.Float,Dg.Fragment),this.registerOutput("loopID",Og.Object,void 0,new cS("loopID",this,1,sy,"LoopBlock")),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[0]._forPostBuild=!0,this._outputs[2]._redirectedSource=this._inputs[0],this._outputs[1]._preventBubbleUp=!0,this._outputs[2]._preventBubbleUp=!0}getClassName(){return"LoopBlock"}get input(){return this._inputs[0]}get iterationsInput(){return this._inputs[1]}get output(){return this._outputs[0]}get index(){return this._outputs[1]}get loopID(){return this._outputs[2]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._outputs[1],r=e._getFreeVariableName("index"),s=1===e.shaderLanguage?"var":"int",n=1===e.shaderLanguage?"f32":"float",o=1===e.shaderLanguage?"i32":"int";e.compilationString+=e._declareOutput(t)+` = ${this.input.associatedVariableName};\n`;const a=this.iterationsInput.isConnected?`${o}(${this.iterationsInput.associatedVariableName})`:this.iterations;return e.compilationString+=`for (${s} ${r} = 0; ${r} < ${a}; ${r}++){\n`,e.compilationString+=`${e._declareOutput(i)} = ${n}(${r});\n`,this}_postBuildBlock(e){return super._postBuildBlock(e),e.compilationString+="}\n",this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.iterations = ${this.iterations};\n`}serialize(){const e=super.serialize();return e.iterations=this.iterations,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.iterations=e.iterations}}(0,je.Cg)([t_("Iterations",2,void 0,{embedded:!0})],sy.prototype,"iterations",void 0),(0,X.Y5)("BABYLON.LoopBlock",sy);class ny extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("loopID",Og.Object,!1,void 0,new cS("loopID",this,0,sy,"LoopBlock")),this.registerOutput("value",Og.AutoDetect),this._outputs[0]._linkedConnectionSource=this._inputs[0]}getClassName(){return"StorageReadBlock"}get loopID(){return this._inputs[0]}get value(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.value;if(!this.loopID.isConnected)return this;const i=this.loopID.connectedPoint.ownerBlock;return e.compilationString+=e._declareOutput(t)+` = ${i.output.associatedVariableName};\n`,this}}(0,X.Y5)("BABYLON.StorageReadBlock",ny);class oy extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("loopID",Og.Object,!1,void 0,new cS("loopID",this,0,sy,"LoopBlock")),this.registerInput("value",Og.AutoDetect),this._linkConnectionTypes(0,1)}getClassName(){return"StorageWriteBlock"}get loopID(){return this._inputs[0]}get value(){return this._inputs[1]}isConnectedInFragmentShader(){return!!this.loopID.isConnected&&this.loopID.connectedPoint.ownerBlock.output.isConnectedInFragmentShader}_buildBlock(e){super._buildBlock(e);const t=this.value;if(!this.loopID.isConnected)return this;const i=this.loopID.connectedPoint.ownerBlock;return e.compilationString+=`${i.output.associatedVariableName} = ${t.associatedVariableName};\n`,this}}(0,X.Y5)("BABYLON.StorageWriteBlock",oy);const ay="gaussianSplattingVertexDeclaration",ly="attribute position: vec2f;\n";Cs.l.IncludesShadersStoreWGSL[ay]=ly;const hy={name:ay,shader:ly};var cy,uy=i(93784);class dy{optimize(e,t){}}class fy{constructor(){this.mm=new Map}get(e,t){const i=this.mm.get(e);if(void 0!==i)return i.get(t)}set(e,t,i){let r=this.mm.get(e);void 0===r&&this.mm.set(e,r=new Map),r.set(t,i)}}class py{get standalone(){return this._options?.standalone??!1}get baseMaterial(){return this._baseMaterial}get doNotInjectCode(){return this._options?.doNotInjectCode??!1}constructor(e,t,i){this._baseMaterial=e,this._scene=t??he.q.LastCreatedScene,this._options=i,this._subMeshToEffect=new Map,this._subMeshToDepthWrapper=new fy,this._meshes=new Map,this._onEffectCreatedObserver=this._baseMaterial.onEffectCreatedObservable.add((e=>{const t=e.subMesh?.getMesh();t&&!this._meshes.has(t)&&this._meshes.set(t,t.onDisposeObservable.add((e=>{const t=this._subMeshToEffect.keys();for(let i=t.next();!0!==i.done;i=t.next()){const t=i.value;t?.getMesh()===e&&(this._subMeshToEffect.delete(t),this._deleteDepthWrapperEffect(t))}}))),this._subMeshToEffect.get(e.subMesh)?.[0]!==e.effect&&(this._subMeshToEffect.set(e.subMesh,[e.effect,this._scene.getEngine().currentRenderPassId]),this._deleteDepthWrapperEffect(e.subMesh))}))}_deleteDepthWrapperEffect(e){const t=this._subMeshToDepthWrapper.mm.get(e);t&&(t.forEach((e=>{e.mainDrawWrapper.effect?.dispose()})),this._subMeshToDepthWrapper.mm.delete(e))}getEffect(e,t,i){const r=this._subMeshToDepthWrapper.mm.get(e)?.get(t);if(!r)return null;let s=r.drawWrapper[i];return s||(s=r.drawWrapper[i]=new gt.E(this._scene.getEngine()),s.setEffect(r.mainDrawWrapper.effect,r.mainDrawWrapper.defines)),s}isReadyForSubMesh(e,t,i,r,s){return!(this.standalone&&!this._baseMaterial.isReadyForSubMesh(e.getMesh(),e,r))&&(this._makeEffect(e,t,i,s)?.isReady()??!1)}dispose(){this._baseMaterial.onEffectCreatedObservable.remove(this._onEffectCreatedObserver),this._onEffectCreatedObserver=null;const e=this._meshes.entries();for(let t=e.next();!0!==t.done;t=e.next()){const[e,i]=t.value;e.onDisposeObservable.remove(i)}}_makeEffect(e,t,i,r){const s=this._scene.getEngine(),n=this._subMeshToEffect.get(e);if(!n)return null;const[o,a]=n;let l=this._subMeshToDepthWrapper.get(e,i);if(!l){const t=new gt.E(s);t.defines=e._getDrawWrapper(a)?.defines??null,l={drawWrapper:[],mainDrawWrapper:t,depthDefines:"",token:(0,Au.z)()},l.drawWrapper[r]=t,this._subMeshToDepthWrapper.set(e,i,l)}const h=t.join("\n");if(l.mainDrawWrapper.effect&&h===l.depthDefines)return l.mainDrawWrapper.effect;l.depthDefines=h;const c=o.getUniformNames().slice();let u=o.vertexSourceCodeBeforeMigration,d=o.fragmentSourceCodeBeforeMigration;if(!this.doNotInjectCode){const e=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",t=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",i=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",r="#include",s="#include";u=0===o.shaderLanguage?u.replace(/void\s+?main/g,`\n${s}\nvoid main`):u.replace(/@vertex/g,`\n${s}\n@vertex`),u=u.replace(/#define SHADOWDEPTH_NORMALBIAS|#define CUSTOM_VERTEX_UPDATE_WORLDPOS/g,e),u=-1!==u.indexOf("#define SHADOWDEPTH_METRIC")?u.replace(/#define SHADOWDEPTH_METRIC/g,t):u.replace(/}\s*$/g,t+"\n}"),u=u.replace(/#define SHADER_NAME.*?\n|out vec4 glFragColor;\n/g,"");const n=d.indexOf("#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW")>=0||d.indexOf("#define CUSTOM_FRAGMENT_BEFORE_FOG")>=0,a=-1!==d.indexOf("#define SHADOWDEPTH_FRAGMENT");let l="";n?d=d.replace(/#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW|#define CUSTOM_FRAGMENT_BEFORE_FOG/g,i):l=i+"\n",d=d.replace(/void\s+?main/g,Cl.M.IncludesShadersStore.shadowMapFragmentExtraDeclaration+"\nvoid main"),a?d=d.replace(/#define SHADOWDEPTH_FRAGMENT/g,r):l+=r+"\n",l&&(d=d.replace(/}\s*$/g,l+"}")),c.push("biasAndScaleSM","depthValuesSM","lightDataSM","softTransparentShadowSM")}l.mainDrawWrapper.effect=s.createEffect({vertexSource:u,fragmentSource:d,vertexToken:l.token,fragmentToken:l.token},{attributes:o.getAttributesNames(),uniformsNames:c,uniformBuffersNames:o.getUniformBuffersNames(),samplers:o.getSamplers(),defines:h+"\n"+o.defines.replace("#define SHADOWS","").replace(/#define SHADOW\d/g,""),indexParameters:o.getIndexParameters(),shaderLanguage:o.shaderLanguage},s);for(let e=0;e0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof W.Pq){const t=[];return e.forEach((e=>{t.push(e.flatMap((e=>[e.x,e.y,e.z])))})),t}if(e instanceof Float32Array){if(t?.floatArrayStride){const i=[],r=3*t.floatArrayStride;for(let t=0;t{t.push(Array.from(e))})),t}return[]}static OmitZeroLengthPredicate(e,t,i){const r=[];return t.subtract(e).lengthSquared()>0&&r.push([e,t]),i.subtract(t).lengthSquared()>0&&r.push([t,i]),e.subtract(i).lengthSquared()>0&&r.push([i,e]),0===r.length?null:r}static OmitDuplicatesPredicate(e,t,i,r){const s=[];return Ey._SearchInPoints(e,t,r)||s.push([e,t]),Ey._SearchInPoints(t,i,r)||s.push([t,i]),Ey._SearchInPoints(i,e,r)||s.push([i,e]),0===s.length?null:s}static _SearchInPoints(e,t,i){for(const r of i)for(let i=0;i{const s=e.getVerticesData(st.R.PositionKind),n=e.getIndices();if(s&&n)for(let o=0,a=0;o[e.x,e.y,e.z]))}static GetPointsCountInfo(e){const t=new Array(e.length);let i=0;for(let r=e.length;r--;)t[r]=e[r].length/3,i+=t[r];return{total:i,counts:t}}static GetLineLength(e){if(0===e.length)return 0;let t;t="number"==typeof e[0]?Ey.ToVector3Array(e):e;const i=W.AA.Vector3[0];let r=0;for(let e=0;e{e.length>t?Ey.SegmentizeSegmentByCount(e.point1,e.point2,Math.ceil(e.length/t)).forEach((e=>{r.push(e)})):(r.push(e.point1),r.push(e.point2))})),r}static SegmentizeLineBySegmentCount(e,t){const i="number"==typeof e[0]?Ey.ToVector3Array(e):e,r=Ey.GetLineLength(i)/t;return Ey.SegmentizeLineBySegmentLength(i,r)}static GetLineSegments(e){const t=[];for(let i=0;ie.length));return{min:t[0].length,max:t[t.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,r=!1){const s=t*i;let n=0,o=0;const a=e.length;for(let t=0;t[e.x,e.y,e.z]))}static GetArrowCap(e,t,i,r,s,n=0,o=0){return{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[r,s,n,o]}}static GetPointsFromText(e,t,i,r,s=0,n=!0){const o=[],a=vl(e,t,i,r);for(const e of a){for(const t of e.paths){const e=[],i=t.getPoints();for(const t of i)e.push(t.x,t.y,s);o.push(e)}if(n)for(const t of e.holes){const e=[],i=t.getPoints();for(const t of i)e.push(t.x,t.y,s);o.push(e)}}return o}static Color3toRGBAUint8(e){const t=new Uint8Array(4*e.length);for(let i=0,r=0;is?s:t.length,o=Math.ceil(t.length/s);o>1&&(t=[...t,...Array(n*o-t.length).fill(t[0])]);const a=Ey.Color3toRGBAUint8(t),l=new xi(a,n,o,an.TEXTUREFORMAT_RGBA,r,!1,!0,i);return l.name=e,l}static PrepareEmptyColorsTexture(e){if(!yy.EmptyColorsTexture){const t=new Uint8Array(4);yy.EmptyColorsTexture=new xi(t,1,1,an.TEXTUREFORMAT_RGBA,e,!1,!1,xi.NEAREST_NEAREST),yy.EmptyColorsTexture.name="grlEmptyColorsTexture"}return yy.EmptyColorsTexture}static DisposeEmptyColorsTexture(){yy.EmptyColorsTexture?.dispose(),yy.EmptyColorsTexture=null}static BooleanToNumber(e){return e?1:0}}class Py extends xn{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 Ay extends Dn{constructor(e,t,i){i=i||{color:yy.DEFAULT_COLOR};const r=new Py;r.GREASED_LINE_HAS_COLOR=!!i.color&&!i.useColors,r.GREASED_LINE_SIZE_ATTENUATION=i.sizeAttenuation??!1,r.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=1===i.colorDistributionType,r.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=(t??e.getScene()).useRightHandedSystem,r.GREASED_LINE_CAMERA_FACING=i.cameraFacing??!0,super(e,Ay.GREASED_LINE_MATERIAL_NAME,200,r),this.colorsTexture=null,this._scene=t??e.getScene(),this._engine=this._scene.getEngine(),this._cameraFacing=i.cameraFacing??!0,this.visibility=i.visibility??1,this.useDash=i.useDash??!1,this.dashRatio=i.dashRatio??.5,this.dashOffset=i.dashOffset??0,this.width=i.width?i.width:i.sizeAttenuation?yy.DEFAULT_WIDTH_ATTENUATED:yy.DEFAULT_WIDTH,this._sizeAttenuation=i.sizeAttenuation??!1,this.colorMode=i.colorMode??0,this._color=i.color??null,this.useColors=i.useColors??!1,this._colorsDistributionType=i.colorDistributionType??0,this.colorsSampling=i.colorsSampling??xi.NEAREST_NEAREST,this._colors=i.colors??null,this.dashCount=i.dashCount??1,this.resolution=i.resolution??new W.I9(this._engine.getRenderWidth(),this._engine.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this._colors?this.colorsTexture=Ey.CreateColorsTexture(`${e.name}-colors-texture`,this._colors,this.colorsSampling,this._scene):(this._color=this._color??yy.DEFAULT_COLOR,Ey.PrepareEmptyColorsTexture(this._scene)),this._engine.onDisposeObservable.add((()=>{Ey.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?"\n uniform vec4 grl_aspect_resolution_lineWidth;\n uniform mat4 grl_projection;\n ":"",fragment:"\n uniform vec4 grl_dashOptions;\n uniform vec2 grl_textureSize;\n uniform vec4 grl_colorMode_visibility_colorsWidth_useColors;\n uniform vec3 grl_singleColor;\n "}}get isEnabled(){return!0}bindForSubMesh(e){if(this._cameraFacing){const t=this._scene.activeCamera;if(!t)throw Error("GreasedLinePluginMaterial requires an active camera.");{const i=t.getProjectionMatrix();e.updateMatrix("grl_projection",i)}const i=W.AA.Vector4[0];i.x=this._aspect,i.y=this._resolution.x,i.z=this._resolution.y,i.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",i)}const t=W.AA.Vector4[0];t.x=Ey.BooleanToNumber(this.useDash),t.y=this._dashArray,t.z=this.dashOffset,t.w=this.dashRatio,e.updateVector4("grl_dashOptions",t);const i=W.AA.Vector4[1];i.x=this.colorMode,i.y=this.visibility,i.z=this.colorsTexture?this.colorsTexture.getSize().width:0,i.w=Ey.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",i),this._color&&e.updateColor3("grl_singleColor",this._color);const r=this.colorsTexture??yy.EmptyColorsTexture;e.setTexture("grl_colors",r),e.updateFloat2("grl_textureSize",r?.getSize().width??1,r?.getSize().height??1)}prepareDefines(e,t,i){e.GREASED_LINE_HAS_COLOR=!!this.color&&!this.useColors,e.GREASED_LINE_SIZE_ATTENUATION=this._sizeAttenuation,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=1===this._colorsDistributionType,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing}getClassName(){return Ay.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){if("vertex"===e){const e={CUSTOM_VERTEX_DEFINITIONS:"\n attribute float grl_widths;\n attribute vec3 grl_offsets;\n attribute float grl_colorPointers;\n varying float grlCounters;\n varying float grlColorPointer;\n\n #ifdef GREASED_LINE_CAMERA_FACING\n attribute vec4 grl_previousAndSide;\n attribute vec4 grl_nextAndCounters;\n\n vec2 grlFix( vec4 i, float aspect ) {\n vec2 res = i.xy / i.w;\n res.x *= aspect;\n return res;\n }\n #else\n attribute vec3 grl_slopes;\n attribute float grl_counters;\n #endif\n ",CUSTOM_VERTEX_UPDATE_POSITION:"\n #ifdef GREASED_LINE_CAMERA_FACING\n vec3 grlPositionOffset = grl_offsets;\n positionUpdated += grlPositionOffset;\n #else\n positionUpdated = (positionUpdated + grl_offsets) + (grl_slopes * grl_widths);\n #endif\n ",CUSTOM_VERTEX_MAIN_END:"\n grlColorPointer = grl_colorPointers;\n\n #ifdef GREASED_LINE_CAMERA_FACING\n\n float grlAspect = grl_aspect_resolution_lineWidth.x;\n float grlBaseWidth = grl_aspect_resolution_lineWidth.w;\n\n\n vec3 grlPrevious = grl_previousAndSide.xyz;\n float grlSide = grl_previousAndSide.w;\n\n vec3 grlNext = grl_nextAndCounters.xyz;\n grlCounters = grl_nextAndCounters.w;\n\n mat4 grlMatrix = viewProjection * finalWorld;\n vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 );\n vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 );\n vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 );\n\n vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect );\n vec2 grlPrevP = grlFix( grlPrevPos, grlAspect );\n vec2 grlNextP = grlFix( grlNextPos, grlAspect );\n\n float grlWidth = grlBaseWidth * grl_widths;\n\n vec2 grlDir;\n if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP );\n else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP );\n else {\n vec2 grlDir1 = normalize( grlCurrentP - grlPrevP );\n vec2 grlDir2 = normalize( grlNextP - grlCurrentP );\n grlDir = normalize( grlDir1 + grlDir2 );\n }\n vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. );\n #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM\n grlNormal.xy *= -.5 * grlWidth;\n #else\n grlNormal.xy *= .5 * grlWidth;\n #endif\n\n grlNormal *= grl_projection;\n\n #ifdef GREASED_LINE_SIZE_ATTENUATION\n grlNormal.xy *= grlFinalPosition.w;\n grlNormal.xy /= ( vec4( grl_aspect_resolution_lineWidth.yz, 0., 1. ) * grl_projection ).xy;\n #endif\n\n grlFinalPosition.xy += grlNormal.xy * grlSide;\n gl_Position = grlFinalPosition;\n\n vPositionW = vec3(grlFinalPosition);\n #else\n grlCounters = grl_counters;\n #endif\n "};return this._cameraFacing&&(e["!gl_Position\\=viewProjection\\*worldPos;"]="//"),e}return"fragment"===e?{CUSTOM_FRAGMENT_DEFINITIONS:"\n varying float grlCounters;\n varying float grlColorPointer;\n uniform sampler2D grl_colors;\n ",CUSTOM_FRAGMENT_MAIN_END:"\n float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x;\n float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y;\n float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z;\n float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w;\n\n float grlUseDash = grl_dashOptions.x;\n float grlDashArray = grl_dashOptions.y;\n float grlDashOffset = grl_dashOptions.z;\n float grlDashRatio = grl_dashOptions.w;\n\n gl_FragColor.a *= step(grlCounters, grlVisibility);\n if( gl_FragColor.a == 0. ) discard;\n\n if(grlUseDash == 1.){\n gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio));\n if (gl_FragColor.a == 0.) discard;\n }\n\n #ifdef GREASED_LINE_HAS_COLOR\n if (grlColorMode == 0.) {\n gl_FragColor.rgb = grl_singleColor;\n } else if (grlColorMode == 1.) {\n gl_FragColor.rgb += grl_singleColor;\n } else if (grlColorMode == 2.) {\n gl_FragColor.rgb *= grl_singleColor;\n }\n #else\n if (grlUseColors == 1.) {\n #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE\n vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.);\n #else\n vec2 lookup = vec2(fract(grlColorPointer / grl_textureSize.x), 1.0 - floor(grlColorPointer / grl_textureSize.x) / max(grl_textureSize.y - 1.0, 1.0));\n vec4 grlColor = texture2D(grl_colors, lookup, 0.0);\n #endif\n if (grlColorMode == 0.) {\n gl_FragColor = grlColor;\n } else if (grlColorMode == 1.) {\n gl_FragColor += grlColor;\n } else if (grlColorMode == 2.) {\n gl_FragColor *= grlColor;\n }\n }\n #endif\n\n "}:null}dispose(){this.colorsTexture?.dispose(),super.dispose()}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){const r=this._colors?.length??0;if(this._colors=e,null!==e&&0!==e.length){if(!t||i)if(this.colorsTexture&&r===e.length&&!i){const t=Ey.Color3toRGBAUint8(e);this.colorsTexture.update(t)}else this.colorsTexture?.dispose(),this.colorsTexture=Ey.CreateColorsTexture(`${this._material.name}-colors-texture`,e,this.colorsSampling,this._scene)}else this.colorsTexture?.dispose()}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){null===this._color&&null!==e||null!==this._color&&null===e?(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){super.parse(e,t,i);const r=e.greasedLineMaterialOptions;this.colorsTexture?.dispose(),r.color&&this.setColor(r.color,!0),r.colorDistributionType&&(this.colorsDistributionType=r.colorDistributionType),r.colors&&(this.colors=r.colors),r.colorsSampling&&(this.colorsSampling=r.colorsSampling),r.colorMode&&(this.colorMode=r.colorMode),r.useColors&&(this.useColors=r.useColors),r.visibility&&(this.visibility=r.visibility),r.useDash&&(this.useDash=r.useDash),r.dashCount&&(this.dashCount=r.dashCount),r.dashRatio&&(this.dashRatio=r.dashRatio),r.dashOffset&&(this.dashOffset=r.dashOffset),r.width&&(this.width=r.width),r.sizeAttenuation&&(this.sizeAttenuation=r.sizeAttenuation),r.resolution&&(this.resolution=r.resolution),this.colors?this.colorsTexture=Ey.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):Ey.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){const t=e;t.colorsTexture?.dispose(),this._colors&&(t.colorsTexture=Ey.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()}}Ay.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial",(0,X.Y5)(`BABYLON.${Ay.GREASED_LINE_MATERIAL_NAME}`,Ay);Cs.l.ShadersStore.greasedLinePixelShader="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;}\nif (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==COLOR_DISTRIBUTION_TYPE_LINE) { \ntextureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);}\nif (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;}}}\n",i(56865),i(18411);Cs.l.ShadersStore.greasedLineVertexShader="precision highp float;\n#include\nattribute 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;\n#ifdef GREASED_LINE_CAMERA_FACING\nattribute 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;}\n#else\nattribute vec3 grl_slopes;attribute float grl_counters;\n#endif\nvoid main() {\n#include\ngrlColorPointer=grl_colorPointers;mat4 grlMatrix=viewProjection*finalWorld ;\n#ifdef GREASED_LINE_CAMERA_FACING\nfloat 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 );}\nvec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. );\n#ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM\ngrlNormal.xy*=-.5*grlWidth;\n#else\ngrlNormal.xy*=.5*grlWidth;\n#endif\ngrlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;}\ngrlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition;\n#else\ngrlCounters=grl_counters;vec4 grlFinalPosition=grlMatrix*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition;\n#endif\n}\n";class Ry extends xo{constructor(e,t,i){const r=["COLOR_DISTRIBUTION_TYPE_LINE 1.","COLOR_DISTRIBUTION_TYPE_SEGMENT 0.","COLOR_MODE_SET 0.","COLOR_MODE_ADD 1.","COLOR_MODE_MULTIPLY 2."],s=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&r.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(r.push("GREASED_LINE_CAMERA_FACING"),s.push("grl_previousAndSide","grl_nextAndCounters")):(s.push("grl_slopes"),s.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:s,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:r}),this._color=H.v9.White(),this._colorsDistributionType=0,this._colorsTexture=null,i=i||{color:yy.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?yy.DEFAULT_WIDTH_ATTENUATED:yy.DEFAULT_WIDTH,this.sizeAttenuation=i.sizeAttenuation??!1,this.color=i.color??H.v9.White(),this.useColors=i.useColors??!1,this.colorsDistributionType=i.colorDistributionType??0,this.colorsSampling=i.colorsSampling??xi.NEAREST_NEAREST,this.colorMode=i.colorMode??0,this._colors=i.colors??null,this._cameraFacing=i.cameraFacing??!0,this.resolution=i.resolution??new W.I9(n.getRenderWidth(),n.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this.colorsTexture=Ey.PrepareEmptyColorsTexture(t),this._colors&&this.useColors&&(this.colorsTexture=Ey.CreateColorsTexture(`${this.name}-colors-texture`,this._colors,this.colorsSampling,t)),n.onDisposeObservable.add((()=>{Ey.DisposeEmptyColorsTexture()}))}dispose(){this._colorsTexture?.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new W.I9(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){const r=this._colors?.length??0;if(this._colors=e,null!==e&&0!==e.length){if(!t||i)if(this._colorsTexture&&r===e.length&&!i){const t=Ey.Color3toRGBAUint8(e);this._colorsTexture.update(t)}else this._colorsTexture?.dispose(),this.colorsTexture=Ey.CreateColorsTexture(`${this.name}-colors-texture`,e,this.colorsSampling,this.getScene())}else this._colorsTexture?.dispose()}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",Ey.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",Ey.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",Ey.BooleanToNumber(e))}get color(){return this._color}set color(e){this.setColor(e)}setColor(e){e=e??yy.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){const r=e.greasedLineMaterialOptions;this._colorsTexture?.dispose(),r.color&&(this.color=r.color),r.colorDistributionType&&(this.colorsDistributionType=r.colorDistributionType),r.colorsSampling&&(this.colorsSampling=r.colorsSampling),r.colorMode&&(this.colorMode=r.colorMode),r.useColors&&(this.useColors=r.useColors),r.visibility&&(this.visibility=r.visibility),r.useDash&&(this.useDash=r.useDash),r.dashCount&&(this.dashCount=r.dashCount),r.dashRatio&&(this.dashRatio=r.dashRatio),r.dashOffset&&(this.dashOffset=r.dashOffset),r.width&&(this.width=r.width),r.sizeAttenuation&&(this.sizeAttenuation=r.sizeAttenuation),r.resolution&&(this.resolution=r.resolution),r.colors?this.colorsTexture=Ey.CreateColorsTexture(`${this.name}-colors-texture`,r.colors,this.colorsSampling,this.getScene()):this.colorsTexture=Ey.PrepareEmptyColorsTexture(t),this._cameraFacing=r.cameraFacing??!0,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}}var Iy,My,Oy;!function(e){e[e.MATERIAL_TYPE_STANDARD=0]="MATERIAL_TYPE_STANDARD",e[e.MATERIAL_TYPE_PBR=1]="MATERIAL_TYPE_PBR",e[e.MATERIAL_TYPE_SIMPLE=2]="MATERIAL_TYPE_SIMPLE"}(Iy||(Iy={})),function(e){e[e.COLOR_MODE_SET=0]="COLOR_MODE_SET",e[e.COLOR_MODE_ADD=1]="COLOR_MODE_ADD",e[e.COLOR_MODE_MULTIPLY=2]="COLOR_MODE_MULTIPLY"}(My||(My={})),function(e){e[e.COLOR_DISTRIBUTION_TYPE_SEGMENT=0]="COLOR_DISTRIBUTION_TYPE_SEGMENT",e[e.COLOR_DISTRIBUTION_TYPE_LINE=1]="COLOR_DISTRIBUTION_TYPE_LINE"}(Oy||(Oy={}));const Dy=[new hc.v9(.98,.26,.38),new hc.v9(.47,.75,.3),new hc.v9(0,.26,.77),new hc.v9(.97,.6,.76),new hc.v9(.19,.63,.78),new hc.v9(.98,.8,.6),new hc.v9(.65,.43,.15),new hc.v9(.15,.47,.22),new hc.v9(.67,.71,.86),new hc.v9(.09,.46,.56),new hc.v9(.8,.98,.02),new hc.v9(.39,.29,.13),new hc.v9(.53,.63,.06),new hc.v9(.95,.96,.41),new hc.v9(1,.72,.94),new hc.v9(.63,.08,.31),new hc.v9(.66,.96,.95),new hc.v9(.22,.14,.19),new hc.v9(.14,.65,.59),new hc.v9(.93,1,.68),new hc.v9(.93,.14,.44),new hc.v9(.47,.86,.67),new hc.v9(.85,.07,.78),new hc.v9(.53,.64,.98),new hc.v9(.43,.37,.56),new hc.v9(.71,.65,.25),new hc.v9(.66,.19,.01),new hc.v9(.94,.53,.12),new hc.v9(.41,.44,.44),new hc.v9(.24,.71,.96),new hc.v9(.57,.28,.56),new hc.v9(.44,.98,.42)];var wy;!function(e){e[e.NONE=0]="NONE",e[e.TRIANGLES=1]="TRIANGLES",e[e.VERTICES=2]="VERTICES",e[e.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",e[e.UV0=4]="UV0",e[e.UV1=5]="UV1",e[e.VERTEXCOLORS=6]="VERTEXCOLORS",e[e.MATERIALIDS=7]="MATERIALIDS"}(wy||(wy={}));class Ny extends xn{constructor(){super(...arguments),this.DBG_MODE=0,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}}class Fy extends Dn{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}isCompatible(e){switch(e){case 0:case 1:return!0;default:return!1}}constructor(e,t={}){const i=new Ny;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 hc.v9(1,1,1),this.shadedSpecularColor=t.shadedSpecularColor??new hc.v9(.8,.8,.8),this.shadedSpecularPower=t.shadedSpecularPower??10,this.wireframeThickness=t.wireframeThickness??.7,this.wireframeTrianglesColor=t.wireframeTrianglesColor??new hc.v9(0,0,0),this.wireframeVerticesColor=t.wireframeVerticesColor??new hc.v9(.8,.8,.8),this.vertexColor=t.vertexColor??new hc.v9(0,0,0),this.vertexRadius=t.vertexRadius??1.2,this.uvScale=t.uvScale??20,this.uvPrimaryColor=t.uvPrimaryColor??new hc.v9(1,1,1),this.uvSecondaryColor=t.uvSecondaryColor??new hc.v9(.5,.5,.5),this._materialColor=Fy.MaterialColors[Fy._PluginCount++%Fy.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&&1==this._material.getScene().getEngine().version)return Z.V.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),void(this._isEnabled=!1);this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){2!=this._mode&&1!=this._mode&&3!=this._mode||i.isVerticesDataPresent("dbg_initialPass")||Z.V.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.",1),e.DBG_MODE=this._mode,e.DBG_MULTIPLY=this._multiply,e.DBG_ENABLED=this._isEnabled}getAttributes(e){e.push("dbg_initialPass")}getUniforms(e=0){return{ubo:[{name:"dbg_shadedDiffuseColor",size:3,type:"vec3"},{name:"dbg_shadedSpecularColorPower",size:4,type:"vec4"},{name:"dbg_thicknessRadiusScale",size:3,type:"vec3"},{name:"dbg_wireframeTrianglesColor",size:3,type:"vec3"},{name:"dbg_wireframeVerticesColor",size:3,type:"vec3"},{name:"dbg_vertexColor",size:3,type:"vec3"},{name:"dbg_uvPrimaryColor",size:3,type:"vec3"},{name:"dbg_uvSecondaryColor",size:3,type:"vec3"},{name:"dbg_materialColor",size:3,type:"vec3"}],fragment:0===e?"#if defined(DBG_ENABLED)\nuniform vec3 dbg_shadedDiffuseColor;\nuniform vec4 dbg_shadedSpecularColorPower;\nuniform vec3 dbg_thicknessRadiusScale;\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n uniform vec3 dbg_vertexColor;\n#endif\n\n#if DBG_MODE == 1\n uniform vec3 dbg_wireframeTrianglesColor;\n#elif DBG_MODE == 3\n uniform vec3 dbg_wireframeVerticesColor;\n#elif DBG_MODE == 4 || DBG_MODE == 5\n uniform vec3 dbg_uvPrimaryColor;\n uniform vec3 dbg_uvSecondaryColor;\n#elif DBG_MODE == 7\n uniform vec3 dbg_materialColor;\n#endif\n#endif":"#if defined(DBG_ENABLED)\nuniform dbg_shadedDiffuseColor: vec3f;\nuniform dbg_shadedSpecularColorPower: vec4f;\nuniform dbg_thicknessRadiusScale: vec3f;\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n uniform dbg_vertexColor: vec3f;\n#endif\n\n#if DBG_MODE == 1\n uniform dbg_wireframeTrianglesColor: vec3f;\n#elif DBG_MODE == 3\n uniform dbg_wireframeVerticesColor: vec3f;\n#elif DBG_MODE == 4 || DBG_MODE == 5\n uniform dbg_uvPrimaryColor: vec3f;\n uniform dbg_uvSecondaryColor: vec3f;\n#elif DBG_MODE == 7\n uniform dbg_materialColor: vec3f;\n#endif\n#endif"}}bindForSubMesh(e){this._isEnabled&&(e.updateFloat3("dbg_shadedDiffuseColor",this.shadedDiffuseColor.r,this.shadedDiffuseColor.g,this.shadedDiffuseColor.b),e.updateFloat4("dbg_shadedSpecularColorPower",this.shadedSpecularColor.r,this.shadedSpecularColor.g,this.shadedSpecularColor.b,this.shadedSpecularPower),e.updateFloat3("dbg_thicknessRadiusScale",this.wireframeThickness,this.vertexRadius,this.uvScale),e.updateColor3("dbg_wireframeTrianglesColor",this.wireframeTrianglesColor),e.updateColor3("dbg_wireframeVerticesColor",this.wireframeVerticesColor),e.updateColor3("dbg_vertexColor",this.vertexColor),e.updateColor3("dbg_uvPrimaryColor",this.uvPrimaryColor),e.updateColor3("dbg_uvSecondaryColor",this.uvSecondaryColor),e.updateColor3("dbg_materialColor",this._materialColor))}getCustomCode(e,t=0){return 1===t?"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:"#if defined(DBG_ENABLED)\nattribute dbg_initialPass: f32;\nvarying dbg_vBarycentric: vec3f;\nvarying dbg_vVertexWorldPos: vec3f;\nvarying dbg_vPass: f32;\n#endif",CUSTOM_VERTEX_MAIN_END:"#if defined(DBG_ENABLED)\nvar dbg_vertexIndex = f32(input.vertexIndex) % 3.;\nif (dbg_vertexIndex == 0.0) { \n vertexOutputs.dbg_vBarycentric = vec3f(1.,0.,0.); \n}\nelse if (dbg_vertexIndex == 1.0) { \n vertexOutputs.dbg_vBarycentric = vec3f(0.,1.,0.); \n}\nelse { \n vertexOutputs.dbg_vBarycentric = vec3f(0.,0.,1.); \n}\n\nvertexOutputs.dbg_vVertexWorldPos = vertexOutputs.vPositionW;\nvertexOutputs.dbg_vPass = input.dbg_initialPass;\n#endif"}:{CUSTOM_FRAGMENT_DEFINITIONS:"#if defined(DBG_ENABLED)\nvarying dbg_vBarycentric: vec3f;\nvarying dbg_vVertexWorldPos: vec3f;\nvarying dbg_vPass: f32;\n\n#if !defined(DBG_MULTIPLY)\n fn dbg_applyShading(color: vec3f) -> vec3f {\n var N = fragmentInputs.vNormalW.xyz;\n var L = normalize(scene.vEyePosition.xyz - fragmentInputs.vPositionW.xyz);\n var H = normalize(L + L);\n var LdotN = clamp(dot(L,N), 0., 1.);\n var HdotN = clamp(dot(H,N), 0., 1.);\n var specTerm = pow(HdotN, uniforms.dbg_shadedSpecularColorPower.w);\n var result = color * (LdotN / PI);\n result += uniforms.dbg_shadedSpecularColorPower.rgb * (specTerm / PI);\n return result;\n }\n#endif\n\n#if DBG_MODE == 1 || DBG_MODE == 3\n fn dbg_edgeFactor() -> f32 {\n var d = fwidth(fragmentInputs.dbg_vBarycentric);\n var a3 = smoothstep(vec3f(0.), d * uniforms.dbg_thicknessRadiusScale.x, fragmentInputs.dbg_vBarycentric);\n return min(min(a3.x, a3.y), a3.z);\n }\n#endif\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n fn dbg_cornerFactor() -> f32 {\n var worldPos = fragmentInputs.vPositionW;\n float dist = length(worldPos - fragmentInputs.dbg_vVertexWorldPos);\n float camDist = length(worldPos - scene.vEyePosition.xyz);\n float d = sqrt(camDist) * .001;\n return smoothstep((uniforms.dbg_thicknessRadiusScale.y * d), ((uniforms.dbg_thicknessRadiusScale.y * 1.01) * d), dist);\n }\n#endif\n\n#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2))\n fn dbg_checkerboardFactor(uv: vec2f) -> f32 {\n var f = fract(uv * uniforms.dbg_thicknessRadiusScale.z);\n f -= .5;\n return (f.x * f.y) > 0. ? 1. : 0.;\n }\n#endif\n#endif",CUSTOM_FRAGMENT_MAIN_END:"#if defined(DBG_ENABLED)\nvar dbg_color = vec3f(1.);\n#if DBG_MODE == 1\n dbg_color = mix(uniforms.dbg_wireframeTrianglesColor, vec3f(1.), dbg_edgeFactor());\n#elif DBG_MODE == 2 || DBG_MODE == 3\n var dbg_cornerFactor = dbg_cornerFactor();\n if (fragmentInputs.dbg_vPass == 0. && dbg_cornerFactor == 1.) discard;\n dbg_color = mix(uniforms.dbg_vertexColor, vec3(1.), dbg_cornerFactor);\n #if DBG_MODE == 3\n dbg_color *= mix(uniforms.dbg_wireframeVerticesColor, vec3f(1.), dbg_edgeFactor());\n #endif\n#elif DBG_MODE == 4 && defined(MAINUV1)\n dbg_color = mix(uniforms.dbg_uvPrimaryColor, uniforms.dbg_uvSecondaryColor, dbg_checkerboardFactor(fragmentInputs.vMainUV1));\n#elif DBG_MODE == 5 && defined(MAINUV2)\n dbg_color = mix(uniforms.dbg_uvPrimaryColor, uniforms.dbg_uvSecondaryColor, dbg_checkerboardFactor(fragmentInputs.vMainUV2));\n#elif DBG_MODE == 6 && defined(VERTEXCOLOR)\n dbg_color = fragmentInputs.vColor.rgb;\n#elif DBG_MODE == 7\n dbg_color = uniforms.dbg_materialColor;\n#endif\n\n#if defined(DBG_MULTIPLY)\n fragmentOutputs.color *= vec4f(dbg_color, 1.);\n#else\n #if DBG_MODE != 6\n fragmentOutputs.color = vec4f(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.);\n #else\n fragmentOutputs.color = vec4f(dbg_color, 1.);\n #endif\n#endif\n#endif"}:"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:"#if defined(DBG_ENABLED)\nattribute float dbg_initialPass;\nvarying vec3 dbg_vBarycentric;\nflat varying vec3 dbg_vVertexWorldPos;\nflat varying float dbg_vPass;\n#endif",CUSTOM_VERTEX_MAIN_END:"#if defined(DBG_ENABLED)\nfloat dbg_vertexIndex = mod(float(gl_VertexID), 3.);\nif (dbg_vertexIndex == 0.0) { \n dbg_vBarycentric = vec3(1.,0.,0.); \n}\nelse if (dbg_vertexIndex == 1.0) { \n dbg_vBarycentric = vec3(0.,1.,0.); \n}\nelse { \n dbg_vBarycentric = vec3(0.,0.,1.); \n}\n\ndbg_vVertexWorldPos = vPositionW;\ndbg_vPass = dbg_initialPass;\n#endif"}:{CUSTOM_FRAGMENT_DEFINITIONS:"#if defined(DBG_ENABLED)\nvarying vec3 dbg_vBarycentric;\nflat varying vec3 dbg_vVertexWorldPos;\nflat varying float dbg_vPass;\n\n#if !defined(DBG_MULTIPLY)\n vec3 dbg_applyShading(vec3 color) {\n vec3 N = vNormalW.xyz;\n vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz);\n vec3 H = normalize(L + L);\n float LdotN = clamp(dot(L,N), 0., 1.);\n float HdotN = clamp(dot(H,N), 0., 1.);\n float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w);\n color *= (LdotN / PI);\n color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI);\n return color;\n }\n#endif\n\n#if DBG_MODE == 1 || DBG_MODE == 3\n float dbg_edgeFactor() {\n vec3 d = fwidth(dbg_vBarycentric);\n vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric);\n return min(min(a3.x, a3.y), a3.z);\n }\n#endif\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n float dbg_cornerFactor() {\n vec3 worldPos = vPositionW;\n float dist = length(worldPos - dbg_vVertexWorldPos);\n float camDist = length(worldPos - vEyePosition.xyz);\n float d = sqrt(camDist) * .001;\n return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist);\n }\n#endif\n\n#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2))\n float dbg_checkerboardFactor(vec2 uv) {\n vec2 f = fract(uv * dbg_thicknessRadiusScale.z);\n f -= .5;\n return (f.x * f.y) > 0. ? 1. : 0.;\n }\n#endif\n#endif",CUSTOM_FRAGMENT_MAIN_END:"#if defined(DBG_ENABLED)\nvec3 dbg_color = vec3(1.);\n#if DBG_MODE == 1\n dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor());\n#elif DBG_MODE == 2 || DBG_MODE == 3\n float dbg_cornerFactor = dbg_cornerFactor();\n if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard;\n dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor);\n #if DBG_MODE == 3\n dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor());\n #endif\n#elif DBG_MODE == 4 && defined(MAINUV1)\n dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1));\n#elif DBG_MODE == 5 && defined(MAINUV2)\n dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2));\n#elif DBG_MODE == 6 && defined(VERTEXCOLOR)\n dbg_color = vColor.rgb;\n#elif DBG_MODE == 7\n dbg_color = dbg_materialColor;\n#endif\n\n#if defined(DBG_MULTIPLY)\n gl_FragColor *= vec4(dbg_color, 1.);\n#else\n #if DBG_MODE != 6\n gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.);\n #else\n gl_FragColor = vec4(dbg_color, 1.);\n #endif\n#endif\n#endif"}}static Reset(){this._PluginCount=0,this.MaterialColors=Dy}static PrepareMeshForTrianglesAndVerticesMode(e,t=!1){let i=()=>{};if(0==e.getTotalIndices())return i;if(t){const t=e.getVerticesDataKinds(),r=e.getIndices(),s={};for(const i of t)s[i]=e.getVerticesData(i);i=function(){e.setIndices(r);for(const i of t){const t=e.getVertexBuffer(i).getStrideSize();e.setVerticesData(i,s[i],void 0,t)}e.removeVerticesData("dbg_initialPass")}}let r=Array.from(e.getIndices());const s=[];for(let e=0;eisNaN(e??Number.NaN))))return!1;if(e.morphTargetManager)for(let t=0;t<3;t++){let i=n[t];for(let n=0;n4,a=o?e.getVerticesData(st.R.MatricesIndicesExtraKind):null,l=o?e.getVerticesData(st.R.MatricesWeightsExtraKind):null,h=e.skeleton.getTransformMatrices(e),c=W.AA.Matrix[0],u=W.AA.Matrix[1];c.reset();const d=4*t;let f,p;for(f=0;f<4;f++)p=s[d+f],p>0&&(W.uq.FromFloat32ArrayToRefScaled(h,Math.floor(16*r[d+f]),p,u),c.addToSelf(u));if(a&&l)for(f=0;f<4;f++)p=l[d+f],p>0&&(W.uq.FromFloat32ArrayToRefScaled(h,Math.floor(16*a[d+f]),p,u),c.addToSelf(u));W.Pq.TransformCoordinatesFromFloatsToRef(n[0],n[1],n[2],c,i)}}return!0}function Ky(e,t,i,r){i.set(0,0,0);for(let r=0;r<3;r++){if(!Yy(e,t.pointIndex[r],W.AA.Vector3[r]))return!1;W.AA.Vector3[r].scaleAndAddToRef(t.barycentric[r],i)}if(W.Pq.TransformCoordinatesToRef(i,e.getWorldMatrix(),i),r){const t=W.AA.Vector3[0],i=W.AA.Vector3[1],s=W.AA.Vector3[2],n=W.AA.Vector3[3],o=W.AA.Vector3[4];n.copyFrom(i),n.subtractInPlace(t),o.copyFrom(s),o.subtractInPlace(t),n.normalize(),o.normalize(),W.Pq.CrossToRef(n,o,r),e.material&&e.material.sideOrientation===(e.getScene().useRightHandedSystem?0:1)&&r.scaleInPlace(-1),W.Pq.TransformNormalToRef(r,e.getWorldMatrix(),r),r.normalize()}return!0}var jy=i(28382);function $y(e,t,i,r,s){let n=null,o=null,a=null;try{let l;n=new e.Decoder,o=new e.DecoderBuffer,o.Init(t,t.byteLength);const h=n.GetEncodedGeometryType(o);switch(h){case e.TRIANGULAR_MESH:{const t=new e.Mesh;if(l=n.DecodeBufferToMesh(o,t),!l.ok()||0===t.ptr)throw new Error(l.error_msg());const i=3*t.num_faces(),s=4*i,h=e._malloc(s);try{n.GetTrianglesUInt32Array(t,s,h);const o=new Uint32Array(i);o.set(new Uint32Array(e.HEAPF32.buffer,h,i)),r(o)}finally{e._free(h)}a=t;break}case e.POINT_CLOUD:{const t=new e.PointCloud;if(l=n.DecodeBufferToPointCloud(o,t),!l.ok()||!t.ptr)throw new Error(l.error_msg());a=t;break}default:throw new Error(`Invalid geometry type ${h}`)}const c=a.num_points(),u=(t,i,r,n)=>{const o=n.data_type(),a=n.num_components(),l=n.normalized(),h=n.byte_stride(),u=n.byte_offset(),d={[e.DT_FLOAT32]:{typedArrayConstructor:Float32Array,heap:e.HEAPF32},[e.DT_INT8]:{typedArrayConstructor:Int8Array,heap:e.HEAP8},[e.DT_INT16]:{typedArrayConstructor:Int16Array,heap:e.HEAP16},[e.DT_INT32]:{typedArrayConstructor:Int32Array,heap:e.HEAP32},[e.DT_UINT8]:{typedArrayConstructor:Uint8Array,heap:e.HEAPU8},[e.DT_UINT16]:{typedArrayConstructor:Uint16Array,heap:e.HEAPU16},[e.DT_UINT32]:{typedArrayConstructor:Uint32Array,heap:e.HEAPU32}}[o];if(!d)throw new Error(`Invalid data type ${o}`);const f=c*a,p=f*d.typedArrayConstructor.BYTES_PER_ELEMENT,_=e._malloc(p);try{t.GetAttributeDataArrayForAllPoints(i,n,o,p,_);const e=new d.typedArrayConstructor(d.heap.buffer,_,f);s(r,e.slice(),a,u,h,l)}finally{e._free(_)}};if(i)for(const e in i){const t=i[e],r=n.GetAttributeByUniqueId(a,t);u(n,a,e,r)}else{const t={position:e.POSITION,normal:e.NORMAL,color:e.COLOR,uv:e.TEX_COORD};for(const e in t){const i=n.GetAttributeId(a,t[e]);if(-1!==i){const t=n.GetAttribute(a,i);u(n,a,e,t)}}}return c}finally{a&&e.destroy(a),o&&e.destroy(o),n&&e.destroy(n)}}function Qy(){let e;onmessage=t=>{const i=t.data;switch(i.id){case"init":{const t=i.decoder;t.url&&importScripts(t.url);const r=t.wasmBinary?{wasmBinary:t.wasmBinary}:{};e=DracoDecoderModule(r),postMessage({id:"initDone"});break}case"decodeMesh":if(!e)throw new Error("Draco decoder module is not available");e.then((e=>{const t=$y(e,i.dataView,i.attributes,(e=>{postMessage({id:"indices",data:e},[e.buffer])}),((e,t,i,r,s,n)=>{postMessage({id:"attribute",kind:e,data:t,size:i,byteOffset:r,byteStride:s,normalized:n},[t.buffer])}));postMessage({id:"decodeMeshDone",totalVertices:t})}))}}}class Zy{static get DecoderAvailable(){const e=Zy.Configuration.decoder;return!!(e.wasmUrl&&e.wasmBinaryUrl&&"object"==typeof WebAssembly||e.fallbackUrl)}static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static get Default(){return Zy._Default||(Zy._Default=new Zy),Zy._Default}static ResetDefault(e){Zy._Default&&(e||Zy._Default.dispose(),Zy._Default=null)}constructor(e=Zy.DefaultNumWorkers){const t=Zy.Configuration.decoder;if(t.workerPool||"object"==typeof e&&e.workerPool)this._workerPoolPromise=Promise.resolve(t.workerPool||e.workerPool);else{const i=t.wasmBinary||"object"==typeof e&&e.wasmBinary,r="number"==typeof e?e:e.numWorkers,s=r&&"function"==typeof Worker&&"function"==typeof URL,n=s||!s&&!t.jsModule,o=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:n?Ue.S0.GetBabylonScriptURL(t.wasmUrl,!0):"",wasmBinaryPromise:i?Promise.resolve(i):Ue.S0.LoadFileAsync(Ue.S0.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:n?Ue.S0.GetBabylonScriptURL(t.fallbackUrl):"",wasmBinaryPromise:Promise.resolve(void 0)};s?this._workerPoolPromise=o.wasmBinaryPromise.then((e=>{const t=`${$y}(${Qy})()`,i=URL.createObjectURL(new Blob([t],{type:"application/javascript"}));return new jy.h(r,(()=>function(e,t,i){return new Promise(((r,s)=>{const n=t=>{e.removeEventListener("error",n),e.removeEventListener("message",o),s(t)},o=t=>{"initDone"===t.data.id&&(e.removeEventListener("error",n),e.removeEventListener("message",o),r(e))};if(e.addEventListener("error",n),e.addEventListener("message",o),t){const r=t.slice(0);e.postMessage({id:"init",decoder:{url:i,wasmBinary:r}},[r])}else e.postMessage({id:"init",decoder:{url:i}})}))}(new Worker(i),e,o.url)))})):this._decoderModulePromise=o.wasmBinaryPromise.then((async e=>{if("undefined"==typeof DracoDecoderModule&&!t.jsModule){if(!o.url)throw new Error("Draco decoder module is not available");await Ue.S0.LoadBabylonScriptAsync(o.url)}return await(i=e,r=t.jsModule,new Promise((e=>{(r||DracoDecoderModule)({wasmBinary:i}).then((t=>{e({module:t})}))})));var i,r}))}}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then((e=>{e.dispose()})),delete this._workerPoolPromise,delete this._decoderModulePromise}async whenReadyAsync(){this._workerPoolPromise?await this._workerPoolPromise:this._decoderModulePromise&&await this._decoderModulePromise}decodeMeshToMeshDataAsync(e,t,i){const r=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength);if(this._workerPoolPromise)return this._workerPoolPromise.then((e=>new Promise(((s,n)=>{e.push(((e,o)=>{let a=null;const l=[],h=t=>{e.removeEventListener("error",h),e.removeEventListener("message",c),n(t),o()},c=t=>{const r=t.data;switch(r.id){case"decodeMeshDone":e.removeEventListener("error",h),e.removeEventListener("message",c),s({indices:a,attributes:l,totalVertices:r.totalVertices}),o();break;case"indices":a=r.data;break;case"attribute":l.push({kind:r.kind,data:r.data,size:r.size,byteOffset:r.byteOffset,byteStride:r.byteStride,normalized:(n=r.kind,u=r.normalized,i&&void 0!==i[n]?(u!==i[n]&&Z.V.Warn(`Normalized flag from Draco data (${u}) does not match normalized flag from glTF accessor (${i[n]}). Using flag from glTF accessor.`),i[n]):u)})}var n,u};e.addEventListener("error",h),e.addEventListener("message",c);const u=r.slice();e.postMessage({id:"decodeMesh",dataView:u,attributes:t},[u.buffer])}))}))));if(this._decoderModulePromise)return this._decoderModulePromise.then((e=>{let i=null;const s=[],n=$y(e.module,r,t,(e=>{i=e}),((e,t,i,r,n,o)=>{s.push({kind:e,data:t,size:i,byteOffset:r,byteStride:n,normalized:o})}));return{indices:i,attributes:s,totalVertices:n}}));throw new Error("Draco decoder module is not available")}async decodeMeshToGeometryAsync(e,t,i,r){const s=await this.decodeMeshToMeshDataAsync(i,r),n=new yt(e,t);s.indices&&n.setIndices(s.indices);for(const e of s.attributes)n.setVerticesBuffer(new st.R(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),s.totalVertices);return n}async _decodeMeshToGeometryForGltfAsync(e,t,i,r,s){const n=await this.decodeMeshToMeshDataAsync(i,r,s),o=new yt(e,t);n.indices&&o.setIndices(n.indices);for(const e of n.attributes)o.setVerticesBuffer(new st.R(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),n.totalVertices);return o}async decodeMeshAsync(e,t){const i=await this.decodeMeshToMeshDataAsync(e,t),r=new bt;i.indices&&(r.indices=i.indices);for(const e of i.attributes){const t=st.R.GetFloatData(e.data,e.size,st.R.GetDataType(e.data),e.byteOffset,e.byteStride,e.normalized,i.totalVertices);r.set(t,e.kind)}return r}}Zy.Configuration={decoder:{wasmUrl:`${Ue.S0._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${Ue.S0._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${Ue.S0._DefaultCdnUrl}/draco_decoder_gltf.js`}},Zy.DefaultNumWorkers=Zy.GetDefaultNumWorkers(),Zy._Default=null;class Jy{static get Default(){return Jy._Default||(Jy._Default=new Jy),Jy._Default}constructor(){const e=Jy.Configuration.decoder;this._decoderModulePromise=Ue.S0.LoadBabylonScriptAsync(e.url).then((()=>MeshoptDecoder.ready))}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,r,s){return this._decoderModulePromise.then((async()=>{MeshoptDecoder.useWorkers(1);const n=await MeshoptDecoder.decodeGltfBufferAsync(t,i,e,r,s);return MeshoptDecoder.useWorkers(0),n}))}}Jy.Configuration={decoder:{url:`${Ue.S0._DefaultCdnUrl}/meshopt_decoder.js`}},Jy._Default=null;let eE=0;class tE{constructor(e,t,i,r){this.pos=e,this.normal=t,this.uv=i,this.vertColor=r}clone(){return new tE(this.pos.clone(),this.normal.clone(),this.uv?.clone(),this.vertColor?.clone())}flip(){this.normal=this.normal.scale(-1)}interpolate(e,t){return new tE(W.Pq.Lerp(this.pos,e.pos,t),W.Pq.Lerp(this.normal,e.normal,t),this.uv&&e.uv?W.I9.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?H.ov.Lerp(this.vertColor,e.vertColor,t):void 0)}}class iE{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){const r=i.subtract(e),s=t.subtract(e);if(0===r.lengthSquared()||0===s.lengthSquared())return null;const n=W.Pq.Normalize(W.Pq.Cross(r,s));return new iE(n,W.Pq.Dot(n,e))}clone(){return new iE(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,r,s){let n=0;const o=[];let a,l;for(a=0;aiE.EPSILON?1:0;n|=t,o.push(t)}switch(n){case 0:(W.Pq.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:r.push(e);break;case 2:s.push(e);break;case 3:{const t=[],i=[];for(a=0;a=3&&(n=new rE(t,e.shared),n.plane&&r.push(n)),i.length>=3&&(n=new rE(i,e.shared),n.plane&&s.push(n));break}}}}iE.EPSILON=1e-5;class rE{constructor(e,t){this.vertices=e,this.shared=t,this.plane=iE.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=this.vertices.map((e=>e.clone()));return new rE(e,this.shared)}flip(){this.vertices.reverse().map((e=>{e.flip()})),this.plane.flip()}}class sE{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=new Array,e&&this.build(e)}clone(){const e=new sE;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((e=>e.clone())),e}invert(){for(let e=0;ee.clone())),e.copyTransformAttributes(this),e}union(e){const t=new sE(this.clone()._polygons),i=new sE(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),nE._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){const t=new sE(this._polygons),i=new sE(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 sE(this.clone()._polygons),i=new sE(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(),nE._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){const t=new sE(this._polygons),i=new sE(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 sE(this.clone()._polygons),i=new sE(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),nE._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){const t=new sE(this._polygons),i=new sE(e._polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}inverse(){const e=this.clone();return e.inverseInPlace(),e}inverseInPlace(){this._polygons.map((e=>{e.flip()}))}copyTransformAttributes(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this}toVertexData(e=null,t=null){const i=this.matrix.clone();i.invert();const r=this._polygons,s=[],n=[],o=[];let a=null,l=null;const h=W.Pq.Zero(),c=W.Pq.Zero(),u=W.I9.Zero(),d=new H.ov(0,0,0,0),f=[0,0,0],p={};let _;for(let m=0,g=r.length;me.shared.meshId===t.shared.meshId?e.shared.subMeshId-t.shared.subMeshId:e.shared.meshId-t.shared.meshId)),this.toVertexData((e=>{o[e.shared.meshId]||(o[e.shared.meshId]={}),o[e.shared.meshId][e.shared.subMeshId]||(o[e.shared.meshId][e.shared.subMeshId]={indexStart:1/0,indexEnd:-1/0,materialIndex:e.shared.materialIndex}),a=o[e.shared.meshId][e.shared.subMeshId]}),(()=>{a.indexStart=Math.min(n,a.indexStart),a.indexEnd=Math.max(n,a.indexEnd),n++})).applyToMesh(r),i){let e,t=0;r.subMeshes=[];for(const i in o){e=-1;for(const s in o[i])a=o[i][s],vt.CreateFromIndices(a.materialIndex+t,a.indexStart,a.indexEnd-a.indexStart+1,r),e=Math.max(a.materialIndex,e);t+=++e}}return r}toMesh(e,t=null,i,r){const s=this.buildMeshGeometry(e,i,r);return s.material=t,s.position.copyFrom(this.position),s.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(s.rotationQuaternion=this.rotationQuaternion.clone()),s.scaling.copyFrom(this.scaling),s.computeWorldMatrix(!0),s}}class oE{static _GetShader(e,t){if(!e._meshUVSpaceRendererShader){const i=new xo("meshUVSpaceRendererShader",e,{vertex:"meshUVSpaceRenderer",fragment:"meshUVSpaceRenderer"},{attributes:["position","normal","uv"],uniforms:["world","projMatrix"],samplers:["textureSampler"],needAlphaBlending:!0,shaderLanguage:t});i.backFaceCulling=!1,i.alphaMode=2,e.onDisposeObservable.add((()=>{e._meshUVSpaceRendererShader?.dispose(),e._meshUVSpaceRendererShader=null})),e._meshUVSpaceRendererShader=i}return e._meshUVSpaceRendererShader}static _GetMaskShader(e,t){if(!e._meshUVSpaceRendererMaskShader){const i=new xo("meshUVSpaceRendererMaskShader",e,{vertex:"meshUVSpaceRendererMasker",fragment:"meshUVSpaceRendererMasker"},{attributes:["position","uv"],uniforms:["worldViewProjection"],shaderLanguage:t});i.backFaceCulling=!1,i.alphaMode=2,e.onDisposeObservable.add((()=>{e._meshUVSpaceRendererMaskShader?.dispose(),e._meshUVSpaceRendererMaskShader=null})),e._meshUVSpaceRendererMaskShader=i}return e._meshUVSpaceRendererMaskShader}static _IsRenderTargetTexture(e){return void 0!==e.renderList}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i){this._textureCreatedInternally=!1,this._configureUserCreatedTexture=!0,this._maskTexture=null,this._finalPostProcess=null,this._shadersLoaded=!1,this._isDisposed=!1,this.clearColor=new H.ov(0,0,0,0),this.texture=null,this._shaderLanguage=0,this._mesh=e,this._scene=t,this._options={width:1024,height:1024,textureType:0,generateMipMaps:!0,optimizeUVAllocation:!0,uvEdgeBlending:!1,...i},this._initShaderSourceAsync()}async _initShaderSourceAsync(){this._scene.getEngine().isWebGPU?(this._shaderLanguage=1,await Promise.all([Promise.resolve().then(i.bind(i,4830)),Promise.resolve().then(i.bind(i,49584)),Promise.resolve().then(i.bind(i,72919)),Promise.resolve().then(i.bind(i,49373)),Promise.resolve().then(i.bind(i,55153)),Promise.resolve().then(i.bind(i,83479))])):await Promise.all([Promise.resolve().then(i.bind(i,82017)),Promise.resolve().then(i.bind(i,33287)),Promise.resolve().then(i.bind(i,96924)),Promise.resolve().then(i.bind(i,99990)),Promise.resolve().then(i.bind(i,13460)),Promise.resolve().then(i.bind(i,33534))]),this._isDisposed||(this._shadersLoaded=!0)}isReady(){if(!this._shadersLoaded)return!1;this.texture?this._configureUserCreatedTexture&&this._configureUserCreatedRTT():this._createDiffuseRTT();const e=oE._IsRenderTargetTexture(this.texture)?this.texture.isReadyForRendering():this.texture.isReady(),t=this._maskTexture?.isReadyForRendering()??!0,i=this._finalPostProcess?.isReady()??!0;return e&&t&&i}renderTexture(e,t,i,r,s=0,n=!0){if(!n||this.isReady()){if(this.texture?this._configureUserCreatedTexture&&this._configureUserCreatedRTT():this._createDiffuseRTT(),oE._IsRenderTargetTexture(this.texture)){const n=this._createProjectionMatrix(t,i,r,s),o=oE._GetShader(this._scene,this._shaderLanguage);o.setTexture("textureSampler",e),o.setMatrix("projMatrix",n),this.texture.render(),o.removeTexture("textureSampler")}}else setTimeout((()=>{this.renderTexture(e,t,i,r,s,n)}),16)}clear(){if(this.texture&&oE._IsRenderTargetTexture(this.texture)&&this.texture.renderTarget){const e=this._scene.getEngine();e.bindFramebuffer(this.texture.renderTarget),e.clear(this.clearColor,!0,!0,!0),e.unBindFramebuffer(this.texture.renderTarget)}if(this._finalPostProcess?.inputTexture){const e=this._scene.getEngine();e.bindFramebuffer(this._finalPostProcess?.inputTexture),e.clear(this.clearColor,!0,!0,!0),e.unBindFramebuffer(this._finalPostProcess?.inputTexture)}}dispose(){this._textureCreatedInternally&&(this.texture?.dispose(),this._textureCreatedInternally=!1),this._configureUserCreatedTexture=!0,this._maskTexture?.dispose(),this._maskTexture=null,this._finalPostProcess?.dispose(),this._finalPostProcess=null,this._isDisposed=!0}_configureUserCreatedRTT(){this._configureUserCreatedTexture=!1,this.texture&&oE._IsRenderTargetTexture(this.texture)&&(this.texture.setMaterialForRendering(this._mesh,oE._GetShader(this._scene,this._shaderLanguage)),this.texture.onClearObservable.add((()=>{})),this.texture.renderList=[this._mesh],this._options.uvEdgeBlending&&(this._createMaskTexture(),this._createPostProcess(),this.texture.addPostProcess(this._finalPostProcess)))}_createDiffuseRTT(){this._textureCreatedInternally=!0;const e=this._createRenderTargetTexture(this._options.width,this._options.height);e.setMaterialForRendering(this._mesh,oE._GetShader(this._scene,this._shaderLanguage)),this.texture=e,this._configureUserCreatedTexture=!1,this._options.uvEdgeBlending&&(this._createMaskTexture(),this._createPostProcess(),e.addPostProcess(this._finalPostProcess))}_createMaskTexture(){this._maskTexture||(this._maskTexture=new ln.$(this._mesh.name+"_maskTexture",{width:this._options.width,height:this._options.height},this._scene,!1,!0,0,!1,2,void 0,void 0,void 0,6),this._maskTexture.clearColor=new H.ov(0,0,0,0),this._maskTexture.renderList.push(this._mesh),this._maskTexture.setMaterialForRendering(this._mesh,oE._GetMaskShader(this._scene,this._shaderLanguage)),this._maskTexture.refreshRate=ln.$.REFRESHRATE_RENDER_ONCE,this._scene.customRenderTargets.push(this._maskTexture))}_createPostProcess(){this._finalPostProcess||(this._finalPostProcess=new ms.w(this._mesh.name+"_fixSeamsPostProcess","meshUVSpaceRendererFinaliser",["textureSize"],["textureSampler","maskTextureSampler"],1,null,1,this._scene.getEngine(),!1,null,this._options.textureType,void 0,void 0,void 0,void 0,this._shaderLanguage),this._finalPostProcess.onApplyObservable.add((e=>{e.setTexture("maskTextureSampler",this._maskTexture),e.setFloat2("textureSize",this._options.width,this._options.height)})))}_createRenderTargetTexture(e,t){const i=new ln.$(this._mesh.name+"_uvspaceTexture",{width:e,height:t},this._scene,this._options.generateMipMaps,!0,this._options.textureType,!1,this._options.generateMipMaps?3:2,!1,!1,!1,5);return i.renderParticles=!1,i.optimizeUVAllocation=!!this._options.optimizeUVAllocation,i.onClearObservable.addOnce((()=>{this._scene.getEngine().clear(this.clearColor,!0,!0,!0),i.onClearObservable.add((()=>{}))})),i.renderList=[this._mesh],i}_createProjectionMatrix(e,t,i,r=0){const s=-Math.atan2(t.z,t.x)-Math.PI/2,n=Math.sqrt(t.x*t.x+t.z*t.z),o=Math.atan2(t.y,n),a=e.add(t.scale(.5*i.z)),l=W.uq.RotationYawPitchRoll(s,o,r).multiply(W.uq.Translation(a.x,a.y,a.z)),h=W.uq.Invert(l),c=W.uq.FromArray([2/i.x,0,0,0,0,2/i.y,0,0,0,0,1/i.z,0,0,0,0,1]),u=W.uq.FromArray([.5,0,0,0,0,.5,0,0,0,0,1,0,.5,.5,0,1]);return h.multiply(c).multiply(u)}}Yt._TrailMeshParser=(e,t)=>aE.Parse(e,t);class aE extends Yt{constructor(e,t,i,r,s=60,n=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._generator=t,"object"==typeof r&&null!==r?(this.diameter=r.diameter||1,this._length=r.length||60,this._segments=r.segments?r.segments>this._length?this._length:r.segments:this._length,this._sectionPolygonPointsCount=r.sections||4,this._doNotTaper=r.doNotTaper||!1,this._autoStart=r.autoStart||!0):(this.diameter=r||1,this._length=s,this._segments=this._length,this._doNotTaper=!1,this._autoStart=n),this._sectionVectors=[],this._sectionNormalVectors=[];for(let e=0;e<=this._sectionPolygonPointsCount;e++)this._sectionVectors[e]=W.Pq.Zero(),this._sectionNormalVectors[e]=W.Pq.Zero();this._createMesh()}getClassName(){return"TrailMesh"}_createMesh(){const e=new bt,t=[],i=[],r=[],s=[];let n=W.Pq.Zero();n=this._generator instanceof Nt&&this._generator.hasBoundingInfo?this._generator.getBoundingInfo().boundingBox.centerWorld:this._generator.absolutePosition;const o=2*Math.PI/this._sectionPolygonPointsCount;for(let e=0;e<=this._sectionPolygonPointsCount;e++){const i=e!==this._sectionPolygonPointsCount?e*o:0;t.push(n.x+Math.cos(i)*this.diameter,n.y+Math.sin(i)*this.diameter,n.z),s.push(e/this._sectionPolygonPointsCount,0)}for(let e=1;e<=this._segments;e++){for(let i=0;i<=this._sectionPolygonPointsCount;i++){const r=i!==this._sectionPolygonPointsCount?i*o:0;t.push(n.x+Math.cos(r)*this.diameter,n.y+Math.sin(r)*this.diameter,n.z),s.push(i/this._sectionPolygonPointsCount,e/this._segments)}const i=t.length/3-2*(this._sectionPolygonPointsCount+1);for(let e=0;e<=this._sectionPolygonPointsCount;e++)r.push(i+e,i+e+this._sectionPolygonPointsCount,i+e+this._sectionPolygonPointsCount+1),r.push(i+e,i+e+this._sectionPolygonPointsCount+1,i+e+1)}bt.ComputeNormals(t,r,i),e.positions=t,e.normals=i,e.indices=r,e.uvs=s,e.applyToMesh(this,!0),this._autoStart&&this.start()}_updateSectionVectors(){const e=this._generator.getWorldMatrix(),t=2*Math.PI/this._sectionPolygonPointsCount;for(let i=0;i<=this._sectionPolygonPointsCount;i++){const r=i!==this._sectionPolygonPointsCount?i*t:0;this._sectionVectors[i].copyFromFloats(Math.cos(r)*this.diameter,Math.sin(r)*this.diameter,0),this._sectionNormalVectors[i].copyFromFloats(Math.cos(r),Math.sin(r),0),W.Pq.TransformCoordinatesToRef(this._sectionVectors[i],e,this._sectionVectors[i]),W.Pq.TransformNormalToRef(this._sectionNormalVectors[i],e,this._sectionNormalVectors[i])}}start(){this._running||(this._running=!0,this._beforeRenderObserver=this.getScene().onBeforeRenderObservable.add((()=>{this.update()})))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){const e=this.getVerticesData(st.R.PositionKind),t=this.getVerticesData(st.R.NormalKind),i=3*(this._sectionPolygonPointsCount+1);if(e&&t){if(this._doNotTaper)for(let t=i;t{this._getSimplifier(e).simplify(t,(i=>{void 0!==t.distance&&e.mesh.addLODLevel(t.distance,i),i.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()}))}));else{const t=this._getSimplifier(e),i=(i,r)=>{t.simplify(i,(t=>{void 0!==i.distance&&e.mesh.addLODLevel(i.distance,t),t.isVisible=!0,r()}))};Ue.LV.Run(e.settings.length,(t=>{i(e.settings[t.index],(()=>{t.executeNext()}))}),(()=>{e.successCallback&&e.successCallback(),this.executeNext()}))}}_getSimplifier(e){return e.simplificationType,new bE(e.mesh)}}var cE,uE,dE,fE,pE,_E;!function(e){e[e.QUADRATIC=0]="QUADRATIC"}(cE||(cE={}));class mE{constructor(e){this._vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class gE{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new vE,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class vE{constructor(e){this.data=new Array(10);for(let t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}det(e,t,i,r,s,n,o,a,l){return this.data[e]*this.data[s]*this.data[l]+this.data[i]*this.data[r]*this.data[a]+this.data[t]*this.data[n]*this.data[o]-this.data[i]*this.data[s]*this.data[o]-this.data[e]*this.data[n]*this.data[a]-this.data[t]*this.data[r]*this.data[l]}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 vE;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,r){return new vE(vE.DataFromNumbers(e,t,i,r))}static DataFromNumbers(e,t,i,r){return[e*e,e*t,e*i,e*r,t*t,t*i,t*r,i*i,i*r,r*r]}}class xE{constructor(e,t){this.vertexId=e,this.triangleId=t}}class bE{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=lt.bH}simplify(e,t){this._initDecimatedMesh(),Ue.LV.Run(this._mesh.subMeshes.length,(t=>{this._initWithMesh(t.index,(()=>{this._runDecimation(e,t.index,(()=>{t.executeNext()}))}),e.optimizeMesh)}),(()=>{setTimeout((()=>{t(this._reconstructedMesh)}),0)}))}_runDecimation(e,t,i){const r=~~(this._triangles.length*e.quality);let s=0;const n=this._triangles.length,o=(e,t)=>{setTimeout((()=>{e%5==0&&this._updateMesh(0===e);for(let e=0;e{const t=~~((this._triangles.length/2+e)%this._triangles.length),r=this._triangles[t];if(r&&!(r.error[3]>i||r.deleted||r.isDirty))for(let e=0;e<3;++e)if(r.error[e]{-1===h.indexOf(e)&&(e.deletePending=!0,h.push(e))})),h.length%2!=0)continue;n.q=o.q.add(n.q),n.updatePosition(a);const c=this._references.length;s=this._updateTriangles(n,n,t,s),s=this._updateTriangles(n,o,i,s);const u=this._references.length-c;if(u<=n.triangleCount){if(u)for(let e=0;en-s<=r))}),0)};Ue.LV.Run(this.decimationIterations,(e=>{n-s<=r?e.breakLoop():o(e.index,(()=>{e.executeNext()}))}),(()=>{setTimeout((()=>{this._reconstructMesh(t),i()}),0)}))}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];const r=this._mesh.getVerticesData(st.R.PositionKind),s=this._mesh.getIndices(),n=this._mesh.subMeshes[e],o=e=>{if(i)for(let t=0;t{if(!r)return;const t=e+n.verticesStart,i=W.Pq.FromArray(r,3*t),s=o(i)||new gE(i,this._vertices.length);s.originalOffsets.push(t),s.id===this._vertices.length&&this._vertices.push(s),a.push(s.id)}),(()=>{Ue.LV.SyncAsyncForLoop(n.indexCount/3,this.syncIterations,(e=>{if(!s)return;const t=3*(n.indexStart/3+e),i=s[t+0],r=s[t+1],o=s[t+2],l=this._vertices[a[i-n.verticesStart]],h=this._vertices[a[r-n.verticesStart]],c=this._vertices[a[o-n.verticesStart]],u=new mE([l,h,c]);u.originalOffset=t,this._triangles.push(u)}),(()=>{this._init(t)}))}))}_init(e){Ue.LV.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];t.normal=W.Pq.Cross(t._vertices[1].position.subtract(t._vertices[0].position),t._vertices[2].position.subtract(t._vertices[0].position)).normalize();for(let e=0;e<3;e++)t._vertices[e].q.addArrayInPlace(vE.DataFromNumbers(t.normal.x,t.normal.y,t.normal.z,-W.Pq.Dot(t.normal,t._vertices[0].position)))}),(()=>{Ue.LV.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];for(let e=0;e<3;++e)t.error[e]=this._calculateError(t._vertices[e],t._vertices[(e+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])}),(()=>{e()}))}))}_reconstructMesh(e){const t=[];let i,r,s;for(i=0;i{n.push(e.position.x),n.push(e.position.y),n.push(e.position.z),h&&h.length&&(o.push(h[3*t]),o.push(h[3*t+1]),o.push(h[3*t+2])),c&&c.length&&(a.push(c[2*t]),a.push(c[2*t+1])),u&&u.length&&(l.push(u[4*t]),l.push(u[4*t+1]),l.push(u[4*t+2]),l.push(u[4*t+3])),++d}))}const f=this._reconstructedMesh.getTotalIndices(),p=this._reconstructedMesh.getTotalVertices(),_=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];const m=this._reconstructedMesh.getIndices(),g=this._mesh.getIndices();for(i=0;i{const t=g[r.originalOffset+e];let i=r._vertices[e].originalOffsets.indexOf(t);i<0&&(i=0),m.push(r._vertices[e].id+i+p)}));this._reconstructedMesh.setIndices(m),this._reconstructedMesh.setVerticesData(st.R.PositionKind,n),o.length>0&&this._reconstructedMesh.setVerticesData(st.R.NormalKind,o),a.length>0&&this._reconstructedMesh.setVerticesData(st.R.UVKind,a),l.length>0&&this._reconstructedMesh.setVerticesData(st.R.ColorKind,l);const v=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],_.forEach((e=>{vt.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())})),vt.AddToMesh(v.materialIndex,p,d,f,3*t.length,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new Yt(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId}_isFlipped(e,t,i,r,s){for(let n=0;n.999)return!0;const d=W.Pq.Cross(c,u).normalize();if(r[n]=!1,W.Pq.Dot(d,o.normal)<.2)return!0}return!1}_updateTriangles(e,t,i,r){let s=r;for(let r=0;rMath.max(e,t.getTotalVertices())),0),a=Array.from({length:o},(()=>new W.Pq)),l=Array.from({length:o},(()=>new W.Pq));for(const t of e){const e=t.getVerticesData(st.R.PositionKind);if(!e)continue;const i=t.getTotalVertices();a.length=Math.max(a.length,i),l.length=Math.max(a.length,i);for(let t=0,s=0;t4,r=e?t.getVerticesData(st.R.MatricesWeightsExtraKind):null,s=e?t.getVerticesData(st.R.MatricesIndicesExtraKind):null,o=n.get(t.uniqueId)||new Map;n.set(t.uniqueId,o);const h=(e,t,i,r)=>{for(let s=t;s0){const t=r[s],i=o.get(t);i?(i.minimum.minimizeInPlace(a[e]),i.maximum.maximizeInPlace(l[e])):o.set(t,{minimum:a[e].clone(),maximum:l[e].clone()})}};for(let e=0,t=0;e{const s=TE(e),n=i[t].getAbsoluteInverseBindMatrix();for(const e of s)W.Pq.TransformCoordinatesToRef(e,n,e);r.set(t,s)}))}}}const u=Array.from({length:e.length},(()=>({minimum:(new W.Pq).setAll(Number.POSITIVE_INFINITY),maximum:(new W.Pq).setAll(Number.NEGATIVE_INFINITY)}))),d=()=>{for(let t=0;t{for(const o of i){const i=e[n].getFinalMatrix().multiplyToRef(s,W.AA.Matrix[0]);W.Pq.TransformCoordinatesToRef(o,i,r),u[t].minimum.minimizeInPlace(r),u[t].maximum.maximizeInPlace(r)}}))}else for(const e of h.get(i.uniqueId))W.Pq.TransformCoordinatesToRef(e,s,r),u[t].minimum.minimizeInPlace(r),u[t].maximum.maximizeInPlace(r)}};if(t&&t.isStarted){const e=t.getCurrentFrame(),r=i/t.getLength(0,1);for(let e=t.from;e<=t.to;e+=r)t.goToFrame(e),d();t.goToFrame(e)}else d();return u}class yE{getClassName(){return"Lattice"}get resolutionX(){return this._resolutionX}get resolutionY(){return this._resolutionY}get resolutionZ(){return this._resolutionZ}get size(){return this._size}get position(){return this._position}get data(){return this._data}get cellSize(){return this._cellSize}get min(){return this._min}get max(){return this._max}constructor(e){this._cellSize=new W.Pq,this._min=new W.Pq(-.5,-.5,-.5),this._max=new W.Pq(.5,.5,.5),this._localPos=new W.Pq,this._tmpVector=new W.Pq,this._lerpVector0=new W.Pq,this._lerpVector1=new W.Pq,this._lerpVector2=new W.Pq,this._lerpVector3=new W.Pq,this._lerpVector4=new W.Pq,this._lerpVector5=new W.Pq;const t={resolutionX:3,resolutionY:3,resolutionZ:3,position:W.Pq.Zero(),size:W.Pq.One(),...e};this._resolutionX=t.resolutionX,this._resolutionY=t.resolutionY,this._resolutionZ=t.resolutionZ,this._position=t.position,this._size=t.autoAdaptToMesh?t.autoAdaptToMesh.getBoundingInfo().boundingBox.extendSize.scale(2):t.size,this._allocateData(),this.update()}_allocateData(){this._data=new Array(this.resolutionX);for(let e=0;eo.x||l.yo.y||l.zo.z){t&&l.toArray(t,a);continue}const h=this._localPos.set((l.x-n.x)/this._cellSize.x,(l.y-n.y)/this._cellSize.y,(l.z-n.z)/this._cellSize.z),c=Math.floor(h.x),u=Math.floor(h.y),d=Math.floor(h.z),f=Math.min(c+1,i-1),p=Math.min(u+1,r-1),_=Math.min(d+1,s-1),m=h.x-c,g=h.y-u,v=h.z-d,x=(0,ar.Clamp)(c,0,i-1),b=(0,ar.Clamp)(u,0,r-1),S=(0,ar.Clamp)(d,0,s-1),T=(0,ar.Clamp)(f,0,i-1),C=(0,ar.Clamp)(p,0,r-1),y=(0,ar.Clamp)(_,0,s-1),E=this._data[x][b][S],P=this._data[T][b][S],A=this._data[x][C][S],R=this._data[T][C][S],I=this._data[x][b][y],M=this._data[T][b][y],O=this._data[x][C][y],D=this._data[T][C][y],w=W.Pq.LerpToRef(E,P,m,this._lerpVector0),N=W.Pq.LerpToRef(I,M,m,this._lerpVector1),F=W.Pq.LerpToRef(A,R,m,this._lerpVector2),L=W.Pq.LerpToRef(O,D,m,this._lerpVector3),B=W.Pq.LerpToRef(w,F,g,this._lerpVector4),V=W.Pq.LerpToRef(N,L,g,this._lerpVector5),k=W.Pq.LerpToRef(B,V,v,this._lerpVector0);k.addInPlace(this.position),k.toArray(t||e,a)}}}class EE extends Dn{constructor(e,t){super(t,"Lattice",200),this._lattice=e,this.refreshData(),this._enable(!0)}getClassName(){return"LatticePluginMaterial"}isCompatible(e){switch(e){case 0:case 1:return!0;default:return!1}}refreshData(){const e=this._lattice.resolutionX*this._lattice.resolutionY*this._lattice.resolutionZ*4;this._latticeData&&this._latticeData.length===e||(this._latticeData=new Float32Array(e));for(let e=0;e;\n ",CUSTOM_VERTEX_UPDATE_POSITION:this._prepareCode(t)}:{CUSTOM_VERTEX_DEFINITIONS:"\n precision highp sampler3D;\n uniform sampler3D latticeData;\n ",CUSTOM_VERTEX_UPDATE_POSITION:this._prepareCode(t)}:null}dispose(){this._latticeDataTexture&&(this._latticeDataTexture.dispose(),this._latticeDataTexture=null)}}!function(e){e[e.POINTS_MODE_POINTS=0]="POINTS_MODE_POINTS",e[e.POINTS_MODE_PATHS=1]="POINTS_MODE_PATHS"}(uE||(uE={})),function(e){e[e.FACES_MODE_SINGLE_SIDED=0]="FACES_MODE_SINGLE_SIDED",e[e.FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING=1]="FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING",e[e.FACES_MODE_DOUBLE_SIDED=2]="FACES_MODE_DOUBLE_SIDED"}(dE||(dE={})),function(e){e[e.AUTO_DIRECTIONS_FROM_FIRST_SEGMENT=0]="AUTO_DIRECTIONS_FROM_FIRST_SEGMENT",e[e.AUTO_DIRECTIONS_FROM_ALL_SEGMENTS=1]="AUTO_DIRECTIONS_FROM_ALL_SEGMENTS",e[e.AUTO_DIRECTIONS_ENHANCED=2]="AUTO_DIRECTIONS_ENHANCED",e[e.AUTO_DIRECTIONS_FACE_TO=3]="AUTO_DIRECTIONS_FACE_TO",e[e.AUTO_DIRECTIONS_NONE=99]="AUTO_DIRECTIONS_NONE"}(fE||(fE={}));class PE extends Yt{constructor(e,t,i){super(e,t,null,null,!1,!1),this.name=e,this._options=i,this._lazy=!1,this._updatable=!1,this._engine=t.getEngine(),this._lazy=i.lazy??!1,this._updatable=i.updatable??!1,this._vertexPositions=[],this._indices=[],this._uvs=[],this._points=[],this._colorPointers=i.colorPointers??[],this._widths=i.widths??new Array(i.points.length).fill(1)}getClassName(){return"GreasedLineMesh"}_updateWidthsWithValue(e){let t=0;for(const e of this._points)t+=e.length;const i=t/3*2-this._widths.length;for(let t=0;tAE.Parse(e,t);class AE extends PE{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(Ey.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+=2*e.length,r+=2*(e.length-3),s+=4*e.length/3,n+=8*e.length/3}));const o=new Float32Array(i),a=i>65535?new Uint32Array(r):new Uint16Array(r),l=new Float32Array(s),h=new Float32Array(n),c=new Float32Array(n);let u=0,d=0,f=0,p=0,_=0;e.forEach((e=>{const i=Ey.GetLineLengthArray(e),r=i[i.length-1];for(let i=0,r=0;r>1]/r;if(this._options.uvs)for(let e=0;eRE.Parse(e,t);class RE extends PE{constructor(e,t,i,r){if(super(e,t,i),this.name=e,!i.ribbonOptions)throw"'GreasedLineMeshOptions.ribbonOptions' is not set.";this._paths=[],this._counters=[],this._slopes=[],this._widths=i.widths??[],this._ribbonWidths=[],this._pathsOptions=r??[],i.points&&this.addPoints(Ey.ConvertPoints(i.points),i,!!r)}addPoints(e,t,i=!1){if(!t.ribbonOptions)throw"addPoints() on GreasedLineRibbonMesh instance requires 'GreasedLineMeshOptions.ribbonOptions'.";i||this._pathsOptions.push({options:t,pathCount:e.length}),super.addPoints(e,t)}getClassName(){return"GreasedLineRibbonMesh"}get isFlatLine(){return this._paths.length<3}get slopes(){return this._slopes}set slopes(e){this._slopes=e}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[];for(let t=0;t{const s=RE._ConvertToRibbonPath(e,n.ribbonOptions,this._scene.useRightHandedSystem,i?i[t]:i);r=this._preprocess(s,r,n)}))}}this._lazy||(this._createVertexBuffers(),!this.doNotSyncBoundingInfo&&this.refreshBoundingInfo())}static _GetDirectionPlanesFromDirectionsOption(e,t){return Array.isArray(t)?t:new Array(e).fill(t)}static _CreateRibbonVertexData(e,t){const i=e.length;if(i<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";const r=[],s=[],n=e[0];for(let t=0;t2)for(let e=0;e0&&(o[0]+=1,o[1]+=1),s.push(o[1]+(e%2!=0?i:0),o[0],o[2]),a&&s.push(o[0],o[1]+(e%2!=0?i:0),o[2])}else for(let e=0;ee.y&&e.x>e.z?i?RE._RightHandedForwardReadOnlyQuaternion:RE._LeftHandedForwardReadOnlyQuaternion:RE._LeftReadOnlyQuaternion),l=e.normalize()}h=l.multiplyByFloats(o,o,o),s.push(c.add(h)),n.push(c.subtract(h))}r||(s.push(a[a.length-1].add(h)),n.push(a[a.length-1].subtract(h)))}return[s,n]}static _GetDirectionFromPoints(e,t,i){return e.x!==t.x||i&&1!==i?.x?e.y===t.y?RE.DIRECTION_XZ:e.z===t.z?RE.DIRECTION_XY:RE.DIRECTION_XZ:RE.DIRECTION_YZ}clone(e=`${this.name}-cloned`,t){const i=this._createLineOptions(),r={},s=[];ce.r.DeepCopy(this._pathsOptions,s,void 0,void 0,!0),ce.r.DeepCopy(i,r,["instance"],void 0,!0);const n=new RE(e,this._scene,r,s);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,r=e.name,s=e.pathOptions;return new RE(r,t,i,s)}_initGreasedLine(){super._initGreasedLine(),this._paths=[],this._counters=[],this._slopes=[],this._ribbonWidths=[]}_calculateSegmentLengths(e){const t=e.length;this._vSegmentLengths=new Array(t),this._vTotalLengths=new Array(t);let i=0;for(let r=0;r0){if(t.length%2!=0&&t.push(r),5===i){const e=Math.floor(t.length/2);for(let i=0,r=0;i0){if(5===i){const e=Math.floor(t.length/2);for(let i=0;ie.kind===st.R.NormalKind)),s=this._manifold.getMesh(t.rebuildNormals&&r?[3,4,5]:void 0);i.indices=s.triVerts.length>65535?new Uint32Array(s.triVerts):new Uint16Array(s.triVerts);for(let e=0;ee.kind===st.R.NormalKind)),o=this._manifold.getMesh(r.rebuildNormals&&n?[3,4,5]:void 0),a=o.vertProperties.length/o.numProp,l=new Yt(e,t);if(s.applyToMesh(l),r.centerMesh){const e=l.getBoundingInfo().boundingSphere.center;l.position.set(-e.x,-e.y,-e.z),l.bakeCurrentTransformIntoVertices()}let h=o.runOriginalID[0],c=o.runIndex[0],u=0;const d=[];t=l.getScene();for(let e=0;e1){const i=new kt(e,t);i.subMaterials=d,l.material=i}else l.material=d[0];return l}dispose(){this._manifold&&(this._manifold.delete(),this._manifold=null)}static _ProcessData(e,t,i,r,s,n){const o=new Float32Array(e*i.reduce(((e,t)=>e+t.stride),0));for(let t=0;te.subMeshes[i].indexStart)),o=e.material||e.getScene().defaultMaterial,a="MultiMaterial"===o.getClassName(),l=[...Array(e.subMeshes.length)].map(((t,i)=>a?LE+o.subMaterials[e.subMeshes[i].materialIndex].uniqueId:LE+o.uniqueId)),h=Array.from(n.keys());h.sort(((e,t)=>n[e]-n[t]));const c=new Uint32Array(h.map((e=>n[e]))),u=new Uint32Array(h.map((e=>l[e]))),d={positions:i,indices:r,normals:e.getVerticesData(st.R.NormalKind),colors:e.getVerticesData(st.R.ColorKind),uvs:e.getVerticesData(st.R.UVKind),uvs2:e.getVerticesData(st.R.UV2Kind),uvs3:e.getVerticesData(st.R.UV3Kind),uvs4:e.getVerticesData(st.R.UV4Kind),uvs5:e.getVerticesData(st.R.UV5Kind),uvs6:e.getVerticesData(st.R.UV6Kind)};return this._Construct(d,t?null:s,c,u)}}function kE(){return void 0!==NE}async function UE(e){const t={manifoldUrl:"https://unpkg.com/manifold-3d@3.0.0",...e};if(t.manifoldInstance)NE=t.manifoldInstance,FE=t.manifoldMeshInstance;else{const e=await(i=`\n import Module from '${t.manifoldUrl}/manifold.js';\n const wasm = await Module();\n wasm.setup();\n const {Manifold, Mesh} = wasm;\n const returnedValue = {Manifold, Mesh};\n `,new Promise(((e,t)=>{let r,s;if((0,ii.BA)())r=window,s="window";else{if("undefined"==typeof self)return void t(new Error("Cannot load script module outside of a window or a worker"));r=self,s="self"}r._LoadScriptModuleResolve||(r._LoadScriptModuleResolve={}),r._LoadScriptModuleResolve[BE]=e,i+=`\n ${s}._LoadScriptModuleResolve[${BE}](returnedValue);\n ${s}._LoadScriptModuleResolve[${BE}] = undefined;\n `,BE++,Ue.S0.LoadScript(i,void 0,((e,i)=>{t(i||new Error(e))}),undefined,!0)})));NE=e.Manifold,FE=e.Mesh}var i;LE=NE.reserveIDs(65536)}var GE,zE,WE,HE,XE,qE,YE,KE,jE,$E,QE,ZE;Yt.prototype.thinInstanceAdd=function(e,t=!0){if(!this.getScene().getEngine().getCaps().instancedArrays)return Z.V.Error("Thin Instances are not supported on this device as Instanced Array extension not supported"),-1;this._thinInstanceUpdateBufferSize("matrix",Array.isArray(e)?e.length:1);const i=this._thinInstanceDataStorage.instancesCount;if(Array.isArray(e))for(let i=0;i=this._thinInstanceDataStorage.instancesCount)return!1;const r=this._thinInstanceDataStorage.matrixData;return t.copyToArray(r,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),i&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},Yt.prototype.thinInstanceSetAttributeAt=function(e,t,i,r=!0){return e===st.R.ColorKind&&(e=st.R.ColorInstanceKind),!(!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[e]||t>=this._thinInstanceDataStorage.instancesCount||(this._thinInstanceUpdateBufferSize(e,0),this._userThinInstanceBuffersStorage.data[e].set(i,t*this._userThinInstanceBuffersStorage.strides[e]),r&&this.thinInstanceBufferUpdated(e),0))},Object.defineProperty(Yt.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){const t=this._thinInstanceDataStorage.matrixData??this.source?._thinInstanceDataStorage.matrixData;e<=(t?t.length/16:0)&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),Yt.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!0){const r=new st.h(this.getEngine(),t,!i,16,!1,!0);for(let t=0;t<4;t++)this.setVerticesBuffer(r.createVertexBuffer(e+t,4*t,4));return r},Yt.prototype.thinInstanceSetBuffer=function(e,t,i=0,r=!0){i=i||16,"matrix"===e?(this._thinInstanceDataStorage.matrixBuffer?.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=t?t.length:32*i,this._thinInstanceDataStorage.matrixData=t,this._thinInstanceDataStorage.worldMatrices=null,null!==t?(this._thinInstanceDataStorage.instancesCount=t.length/i,this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",t,r),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):"previousMatrix"===e?(this._thinInstanceDataStorage.previousMatrixBuffer?.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,r))):(e===st.R.ColorKind&&(e=st.R.ColorInstanceKind),null===t?this._userThinInstanceBuffersStorage?.data[e]&&(this.removeVerticesData(e),delete this._userThinInstanceBuffersStorage.data[e],delete this._userThinInstanceBuffersStorage.strides[e],delete this._userThinInstanceBuffersStorage.sizes[e],delete this._userThinInstanceBuffersStorage.vertexBuffers[e]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[e]=t,this._userThinInstanceBuffersStorage.strides[e]=i,this._userThinInstanceBuffersStorage.sizes[e]=t.length,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new st.R(this.getEngine(),t,e,!r,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},Yt.prototype.thinInstanceBufferUpdated=function(e){"matrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.matrixBuffer&&!this._thinInstanceDataStorage.matrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._thinInstanceDataStorage.matrixBuffer?.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount)):"previousMatrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.previousMatrixBuffer&&!this._thinInstanceDataStorage.previousMatrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._thinInstanceDataStorage.previousMatrixBuffer?.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount)):(e===st.R.ColorKind&&(e=st.R.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&(this.thinInstanceAllowAutomaticStaticBufferRecreation&&!this._userThinInstanceBuffersStorage.vertexBuffers[e].isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0)))},Yt.prototype.thinInstancePartialBufferUpdate=function(e,t,i){"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===st.R.ColorKind&&(e=st.R.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},Yt.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let t=0;te.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){return this.isConnected?this._connectedPoint?._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=GE.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new z.cP,this.onDisconnectionObservable=new z.cP,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 0===this.checkCompatibilityState(e)}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==GE.AutoDetect)return e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)?0:1;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return 1;let r=i,s=t;return 0===this.direction&&(r=t,s=i),r.isAnAncestorOf(s)?2:0}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(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 eP{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)return!0;if(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 t=i.ownerBlock.getDescendantOfPredicate(e);if(t)return t}return null}get _isReadyState(){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 z.cP,this._inputs=new Array,this._outputs=new Array,this._codeVariableName="",this.visibleOnFrame=!1,this._name=e,this.uniqueId=Op.K.UniqueId}registerInput(e,t,i=!1,r,s,n){const o=new JE(e,this,0);return o.type=t,o.isOptional=i,o.defaultValue=r,o.value=r,o.valueMin=s,o.valueMax=n,this._inputs.push(o),this}registerOutput(e,t,i){return(i=i??new JE(e,this,1)).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((e=>e.hasEndpoints))&&!this.isDebug)return!1;this.outputs.forEach((e=>e._resetCounters()))}this._buildId=e.buildId;for(const t of this._inputs){if(!t.connectedPoint){t.isOptional||e.notConnectedNonOptionalInputs.push(t);continue}const i=t.connectedPoint.ownerBlock;i&&i!==this&&i.build(e)}this._customBuildStep(e),e.verbose&&Z.V.Log(`Building ${this.name} [${this.getClassName()}]`);const t=ai.j.Now;return this._buildBlock(e),this._buildExecutionTime=ai.j.Now-t,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((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.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((e=>{const t=this.inputs.find((t=>t.name===e.name));if(t&&(e.displayName&&(t.displayName=e.displayName),e.isExposedOnFrame&&(t.isExposedOnFrame=e.isExposedOnFrame,t.exposedPortPosition=e.exposedPortPosition),void 0!==e.value&&null!==e.value))if("number"===e.valueType)t.value=e.value;else{const i=(0,X.n9)(e.valueType);i&&(t.value=i.FromArray(e.value))}})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}_dumpPropertiesCode(){return`${this._codeVariableName}.visibleOnFrame = ${this.visibleOnFrame};\n`}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e),t+=`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\n`}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}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=i+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let r=`\n// ${this.getClassName()}\n`;this.comments&&(r+=`// ${this.comments}\n`);const s=this.getClassName();if("GeometryInputBlock"===s){const e=this.type;r+=`var ${this._codeVariableName} = new BABYLON.GeometryInputBlock("${this.name}", ${e});\n`}else r+=`var ${this._codeVariableName} = new BABYLON.${s}("${this.name}");\n`;r+=this._dumpPropertiesCode();for(const i of this.inputs){if(!i.isConnected)continue;const s=i.connectedPoint.ownerBlock;-1===t.indexOf(s)&&(r+=s._dumpCode(e,t))}for(const i of this.outputs)if(i.hasEndpoints)for(const s of i.endpoints){const i=s.ownerBlock;i&&-1===t.indexOf(i)&&(r+=i._dumpCode(e,t))}return r}clone(){const e=this.serialize(),t=(0,X.n9)(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()}}(0,je.Cg)([(0,$e.lK)("comment")],eP.prototype,"comments",void 0);class tP extends eP{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",GE.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}}(0,X.Y5)("BABYLON.GeometryOutputBlock",tP),function(e){e[e.None=0]="None",e[e.Positions=1]="Positions",e[e.Normals=2]="Normals",e[e.Tangents=3]="Tangents",e[e.UV=4]="UV",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6",e[e.Colors=10]="Colors",e[e.VertexID=11]="VertexID",e[e.FaceID=12]="FaceID",e[e.GeometryID=13]="GeometryID",e[e.CollectionID=14]="CollectionID",e[e.LoopID=15]="LoopID",e[e.InstanceID=16]="InstanceID",e[e.LatticeID=17]="LatticeID",e[e.LatticeControl=18]="LatticeControl"}(HE||(HE={}));class iP{constructor(){this._rotationMatrix=new W.uq,this._scalingMatrix=new W.uq,this._positionMatrix=new W.uq,this._scalingRotationMatrix=new W.uq,this._transformMatrix=new W.uq,this._tempVector3=new W.Pq,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 HE.Positions:return this.executionContext.getOverridePositionsContextualValue?this.executionContext.getOverridePositionsContextualValue():this.geometryContext&&this.geometryContext.positions?W.Pq.FromArray(this.geometryContext.positions,3*i):W.Pq.Zero();case HE.Normals:return this.executionContext.getOverrideNormalsContextualValue?this.executionContext.getOverrideNormalsContextualValue():this.geometryContext&&this.geometryContext.normals?W.Pq.FromArray(this.geometryContext.normals,3*i):W.Pq.Zero();case HE.Colors:return this.geometryContext&&this.geometryContext.colors?W.IU.FromArray(this.geometryContext.colors,4*i):W.IU.Zero();case HE.Tangents:return this.geometryContext&&this.geometryContext.tangents?W.IU.FromArray(this.geometryContext.tangents,4*i):W.IU.Zero();case HE.UV:return this.executionContext.getOverrideUVs1ContextualValue?this.executionContext.getOverrideUVs1ContextualValue():this.geometryContext&&this.geometryContext.uvs?W.I9.FromArray(this.geometryContext.uvs,2*i):W.I9.Zero();case HE.UV2:return this.geometryContext&&this.geometryContext.uvs2?W.I9.FromArray(this.geometryContext.uvs2,2*i):W.I9.Zero();case HE.UV3:return this.geometryContext&&this.geometryContext.uvs3?W.I9.FromArray(this.geometryContext.uvs3,2*i):W.I9.Zero();case HE.UV4:return this.geometryContext&&this.geometryContext.uvs4?W.I9.FromArray(this.geometryContext.uvs4,2*i):W.I9.Zero();case HE.UV5:return this.geometryContext&&this.geometryContext.uvs5?W.I9.FromArray(this.geometryContext.uvs5,2*i):W.I9.Zero();case HE.UV6:return this.geometryContext&&this.geometryContext.uvs6?W.I9.FromArray(this.geometryContext.uvs6,2*i):W.I9.Zero();case HE.VertexID:return i;case HE.FaceID:return this.executionContext.getExecutionFaceIndex();case HE.LoopID:return this.executionContext.getExecutionLoopIndex();case HE.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case HE.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case HE.CollectionID:return this.geometryContext&&this.geometryContext.metadata&&this.geometryContext.metadata.collectionId||0;case HE.LatticeID:return this.executionContext.getOverridePositionsContextualValue?this.executionContext.getOverridePositionsContextualValue():W.Pq.Zero();case HE.LatticeControl:return this.executionContext.getOverrideNormalsContextualValue?this.executionContext.getOverrideNormalsContextualValue():W.Pq.Zero()}return null}adapt(e,t){const i=e.getConnectedValue(this)||0;if(e.type===t)return i;switch(t){case GE.Vector2:return new W.I9(i,i);case GE.Vector3:return new W.Pq(i,i,i);case GE.Vector4:return new W.IU(i,i,i,i)}return null}adaptInput(e,t,i){if(!e.isConnected)return e.value||i;const r=e.getConnectedValue(this);if(e._connectedPoint?.type===t)return r;switch(t){case GE.Vector2:return new W.I9(r,r);case GE.Vector3:return new W.Pq(r,r,r);case GE.Vector4:return new W.IU(r,r,r,r)}return null}emitErrors(){let e="";for(const t of this.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional.\n`;for(const t of this.noContextualData)e+=`Contextual input ${HE[t]} has no context to pull data from (must be connected to a setXXX block or a instantiateXXX block).\n`;if(e)throw"Build of NodeGeometry failed:\n"+e}_instantiate(e,t,i,r,s){W.uq.ScalingToRef(r.x,r.y,r.z,this._scalingMatrix),W.uq.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),W.uq.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 t=0;te.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.${HE[this._contextualSource]};\n`;const t=[];let i="";switch(this.type){case GE.Float:case GE.Int:i=`${this.value}`;break;case GE.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case GE.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case GE.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`}return t.push(`${e}.value = ${i}`),this.type!==GE.Float&&this.type!==GE.Int||t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}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,null===this._storedValue||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("number"===e.valueType)this._storedValue=e.value;else{const t=(0,X.n9)(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}(0,X.Y5)("BABYLON.GeometryInputBlock",rP);class sP extends eP{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",GE.Float,!0,1),this.registerInput("width",GE.Float,!0,0),this.registerInput("height",GE.Float,!0,0),this.registerInput("depth",GE.Float,!0,0),this.registerInput("subdivisions",GE.Int,!0,1),this.registerInput("subdivisionsX",GE.Int,!0,0),this.registerInput("subdivisionsY",GE.Int,!0,0),this.registerInput("subdivisionsZ",GE.Int,!0,0),this.registerOutput("geometry",GE.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 rP("Size");return e.value=1,void e.output.connectTo(this.size)}if(!this.width.isConnected){const e=new rP("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new rP("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){const e=new rP("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){const t={},i=e=>{t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.depth=this.depth.getConnectedValue(e);const i=this.subdivisions.getConnectedValue(e),r=this.subdivisionsX.getConnectedValue(e),s=this.subdivisionsY.getConnectedValue(e),n=this.subdivisionsZ.getConnectedValue(e);return i&&(t.segments=i),r&&(t.widthSegments=r),s&&(t.heightSegments=s),n&&(t.depthSegments=n),Yo(t)};if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],sP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.BoxBlock",sP);class nP{_getGlobalNodeGeometryEditor(){return"undefined"!=typeof NODEGEOMETRYEDITOR?NODEGEOMETRYEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeGeometryEditor?BABYLON:void 0}get buildExecutionTime(){return this._buildExecutionTime}constructor(e){this._buildId=nP._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new z.cP,this.outputBlock=null,this.name=e}getClassName(){return"NodeGeometry"}get vertexData(){return this._vertexData}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e){if(t)return Ue.S0.Warn("More than one block was found with the name `"+e+"`"),t;t=i}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(),void 0===this.BJSNODEGEOMETRYEDITOR){const i=e&&e.editorURL?e.editorURL:nP.EditorURL;Ue.S0.LoadBabylonScript(i,(()=>{this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),this._createNodeEditor(e?.nodeGeometryEditorConfig),t()}))}else this._createNodeEditor(e?.nodeGeometryEditorConfig),t()}))}_createNodeEditor(e){const t={nodeGeometry:this,...e};this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(t)}build(e=!1,t=!0,i=!1){if(this._buildWasSuccessful=!1,!this.outputBlock)throw"You must define the outputBlock property before building the geometry";const r=ai.j.Now;this._initializeBlock(this.outputBlock,i);const s=[];for(const e of this.attachedBlocks)e._isReadyState&&s.push(e._isReadyState);if(s.length)return void Promise.all(s).then((()=>{this.build(e,t,i)}));const n=new iP;n.buildId=this._buildId,n.verbose=e;try{this.outputBlock.build(n)}finally{t&&(this._buildId=nP._BuildIdGenerator++)}this._buildExecutionTime=ai.j.Now-r,n.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=n.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;const i=new Yt(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)}_initializeBlock(e,t=!0){e.initialize(),t&&e.autoConfigure(),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)&&this.attachedBlocks.push(e);for(const i of e.inputs){const r=i.connectedPoint;if(r){const i=r.ownerBlock;i!==e&&this._initializeBlock(i,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 t of e.blocks){const e=(0,X.n9)(t.customType);if(e){const r=new e;r._deserialize(t),i[t.id]=r,this.attachedBlocks.push(r)}}for(const e of this.attachedBlocks)if(e.isTeleportOut){const t=e,r=t._tempEntryPointUniqueId;if(r){const e=i[r];e&&e.attachToEndpoint(t)}}for(let r=0;re.targetConnectionName))&&!t||this._restoreConnections(n,e,i))}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){const r=e.locations||e.editorData.locations;for(const e of r)i[e.blockId]&&(e.blockId=i[e.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&r.concat(this.editorData.locations),e.locations?this.editorData={locations:r}:(this.editorData=e.editorData,this.editorData.locations=r);const s=[];for(const e in i)s[e]=i[e].uniqueId;this.editorData.map=s}this.comment=e.comment}_restoreConnections(e,t,i){for(const r of e.outputs)for(const s of t.blocks){const n=i[s.id];if(n)for(const o of s.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==r.name);else{const e=n.getInputByName(o.inputName);if(!e||e.isConnected)continue;r.connectTo(e,!0),this._restoreConnections(n,t,i)}}}generateCode(){let e=[];const t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);let r=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}");\n`;for(const s of t)s.isInput&&-1===e.indexOf(s)&&(r+=s._dumpCode(i,e));return this.outputBlock&&(e=[],r+="// Connections\n",r+=this.outputBlock._dumpCodeForOutputConnections(e),r+="// Output nodes\n",r+=`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName};\n`,r+="nodeGeometry.build();\n"),r}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const r=i.connectedPoint;if(r){const i=r.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}setToDefault(){this.clear(),this.editorData=null;const e=new sP("Box");e.autoConfigure();const t=new tP("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){const t=this.serialize(),i=it.p.Clone((()=>new nP(e)),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){const t=e?{}:it.p.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 e of i)t.blocks.push(e.serialize());if(!e)for(const e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.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 nP(e);return t.setToDefault(),t.build(),t}static Parse(e){const t=it.p.Parse((()=>new nP(e.name)),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return"_BLANK"===e?Promise.resolve(nP.CreateDefault("blank")):new Promise(((r,s)=>{const n=new go.u;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const o=JSON.parse(JSON.parse(n.responseText).jsonPayload),a=JSON.parse(o.nodeGeometry);t||(t=it.p.Parse((()=>new nP(e)),a,null)),t.parseSerializedObject(a),t.snippetId=e;try{i||t.build(),r(t)}catch(e){s(e)}}else s("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}nP._BuildIdGenerator=0,nP.EditorURL=`${Ue.S0._DefaultCdnUrl}/v${Ot.$.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`,nP.SnippetUrl="https://snippet.babylonjs.com",(0,je.Cg)([(0,$e.lK)()],nP.prototype,"name",void 0),(0,je.Cg)([(0,$e.lK)("comment")],nP.prototype,"comment",void 0);class oP extends eP{getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}constructor(e){super(e),this.evaluateContext=!0,this.epsilon=lt.bH,this.optimizeFaces=!1,this.registerInput("geometry",GE.Geometry),this.registerInput("selector",GE.Int,!0),this.registerOutput("output",GE.Geometry)}getClassName(){return"GeometryOptimizeBlock"}get geometry(){return this._inputs[0]}get selector(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(!this.geometry.isConnected)return null;const t=this.geometry.getConnectedValue(e),i=[],r={};e.pushExecutionContext(this),e.pushGeometryContext(t);for(let s=0;sr[e])),o=[];if(this.optimizeFaces){for(let e=0;e{t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e);const i=this.subdivisions.getConnectedValue(e),r=this.subdivisionsX.getConnectedValue(e),s=this.subdivisionsY.getConnectedValue(e);i&&(t.subdivisions=i),r&&(t.subdivisionsX=r),s&&(t.subdivisionsY=s);const n=Jn(t);return W.uq.RotationYawPitchRollToRef(-Math.PI/2,0,Math.PI/2,this._rotationMatrix),n.transform(this._rotationMatrix),n};if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],aP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.PlaneBlock",aP);class lP extends eP{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",GE.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)return void(this._cachedVertexData?this.geometry._storedValue=this._cachedVertexData.clone():this.geometry._storedValue=null);const e=bt.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=bt.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=bt.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}}(0,je.Cg)([t_("Serialize cached data",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],lP.prototype,"serializedCachedData",void 0),(0,X.Y5)("BABYLON.MeshBlock",lP);class hP extends eP{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",GE.Float,!0,1),this.registerInput("radiusX",GE.Float,!0,0),this.registerInput("radiusY",GE.Float,!0,0),this.registerInput("radiusZ",GE.Float,!0,0),this.registerInput("subdivisions",GE.Int,!0,4),this.registerOutput("geometry",GE.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 rP("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.radiusX=this.radiusX.getConnectedValue(e),t.radiusY=this.radiusY.getConnectedValue(e),t.radiusZ=this.radiusZ.getConnectedValue(e),$a(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],hP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.IcoSphereBlock",hP);class cP extends eP{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",GE.Int,!0,32),this.registerInput("diameter",GE.Float,!0,1),this.registerInput("diameterX",GE.Float,!0,0),this.registerInput("diameterY",GE.Float,!0,0),this.registerInput("diameterZ",GE.Float,!0,0),this.registerInput("arc",GE.Float,!0,1),this.registerInput("slice",GE.Float,!0,1),this.registerOutput("geometry",GE.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 rP("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=e=>(t.segments=this.segments.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterX=this.diameterX.getConnectedValue(e),t.diameterY=this.diameterY.getConnectedValue(e),t.diameterZ=this.diameterZ.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),t.slice=this.slice.getConnectedValue(e),$o(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],cP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.SphereBlock",cP);class uP extends eP{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",GE.Float,!0,1),this.registerInput("height",GE.Float,!0,1),this.registerInput("subdivisions",GE.Int,!0,1),this.registerInput("subdivisionsX",GE.Int,!0,0),this.registerInput("subdivisionsY",GE.Int,!0,0),this.registerOutput("geometry",GE.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 rP("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new rP("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=e=>(t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.subdivisionsX=this.subdivisionsX.getConnectedValue(e),t.subdivisionsY=this.subdivisionsY.getConnectedValue(e),Jn(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],uP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.GridBlock",uP);class dP extends eP{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",GE.Float,!0,1),this.registerInput("thickness",GE.Float,!0,.5),this.registerInput("tessellation",GE.Int,!0,16),this.registerOutput("geometry",GE.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 rP("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=e=>(t.thickness=this.thickness.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),oo(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],dP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.TorusBlock",dP);class fP extends eP{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",GE.Float,!0,25),this.registerInput("diameter",GE.Float,!0,1),this.registerInput("diameterTop",GE.Float,!0,-1),this.registerInput("diameterBottom",GE.Float,!0,-1),this.registerInput("subdivisions",GE.Int,!0,1),this.registerInput("tessellation",GE.Int,!0,24),this.registerInput("arc",GE.Float,!0,1),this.registerOutput("geometry",GE.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 rP("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){const e=new rP("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=e=>(t.height=this.height.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterTop=this.diameterTop.getConnectedValue(e),t.diameterBottom=this.diameterBottom.getConnectedValue(e),-1===t.diameterTop&&(t.diameterTop=t.diameter),-1===t.diameterBottom&&(t.diameterBottom=t.diameter),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),wo(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],fP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.CylinderBlock",fP);class pP extends eP{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",GE.Float,!0,1),this.registerInput("radius",GE.Float,!0,.25),this.registerInput("tessellation",GE.Int,!0,16),this.registerInput("subdivisions",GE.Int,!0,2),this.registerOutput("geometry",GE.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 rP("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){const e=new rP("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.height=this.height.getConnectedValue(e),t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),na(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],pP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.CapsuleBlock",pP);class _P extends eP{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",GE.Float,!0,.5),this.registerInput("tessellation",GE.Int,!0,64),this.registerInput("arc",GE.Float,!0,1),this.registerOutput("geometry",GE.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 rP("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),ua(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],_P.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.DiscBlock",_P);class mP extends eP{constructor(e){super(e),this.registerOutput("geometry",GE.Geometry),this.registerOutput("vector",GE.Vector3)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}get vector(){return this._outputs[1]}_buildBlock(){this.geometry._storedValue=null,this.vector._storedValue=null}}(0,X.Y5)("BABYLON.NullBlock",mP);class gP extends eP{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",GE.Geometry),this.registerInput("positions",GE.Vector3),this.registerOutput("output",GE.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]}_remapVector3Data(e,t){const i=[];for(let r=0;r{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.positions.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);const t={},i=this._vertexData.positions.length/3,r=[];let s=0,n=!1;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.normals.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.normals||(this._vertexData.normals=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.uvs.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);const t=[],i=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.colors.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.colors||(this._vertexData.colors=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.tangents.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.tangents||(this._vertexData.tangents=[]);const t=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)return this.output._storedFunction=null,void(this.output._storedValue=null);const r=t.type===GE.Float||t.type===GE.Int,s=i.type===GE.Float||i.type===GE.Int,n=r&&s;switch(this.operation){case XE.Add:e=n?e=>t.getConnectedValue(e)+i.getConnectedValue(e):r?e=>e.adapt(t,i.type).add(i.getConnectedValue(e)):e=>t.getConnectedValue(e).add(e.adapt(i,t.type));break;case XE.Subtract:e=n?e=>t.getConnectedValue(e)-i.getConnectedValue(e):r?e=>e.adapt(t,i.type).subtract(i.getConnectedValue(e)):e=>t.getConnectedValue(e).subtract(e.adapt(i,t.type));break;case XE.Multiply:e=n?e=>t.getConnectedValue(e)*i.getConnectedValue(e):r?e=>e.adapt(t,i.type).multiply(i.getConnectedValue(e)):e=>t.getConnectedValue(e).multiply(e.adapt(i,t.type));break;case XE.Divide:e=n?e=>t.getConnectedValue(e)/i.getConnectedValue(e):r?e=>e.adapt(t,i.type).divide(i.getConnectedValue(e)):e=>t.getConnectedValue(e).divide(e.adapt(i,t.type));break;case XE.Min:if(n)e=e=>Math.min(t.getConnectedValue(e),i.getConnectedValue(e));else{const[s,n]=r?[i,t]:[t,i];switch(s.type){case GE.Vector2:e=e=>W.I9.Minimize(s.getConnectedValue(e),e.adapt(n,s.type));break;case GE.Vector3:e=e=>W.Pq.Minimize(s.getConnectedValue(e),e.adapt(n,s.type));break;case GE.Vector4:e=e=>W.IU.Minimize(s.getConnectedValue(e),e.adapt(n,s.type))}}break;case XE.Max:if(!n){const[s,n]=r?[i,t]:[t,i];switch(s.type){case GE.Vector2:e=e=>W.I9.Maximize(s.getConnectedValue(e),e.adapt(n,s.type));break;case GE.Vector3:e=e=>W.Pq.Maximize(s.getConnectedValue(e),e.adapt(n,s.type));break;case GE.Vector4:e=e=>W.IU.Maximize(s.getConnectedValue(e),e.adapt(n,s.type))}break}e=e=>Math.max(t.getConnectedValue(e),i.getConnectedValue(e))}this.output._storedFunction=i=>t.type===GE.Int?0|e(i):e(i)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${XE[this.operation]};\n`}_updateInputOutputTypes(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===GE.Int||this.left.type===GE.Float&&this.right.type!==GE.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=[GE.Int,GE.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),t.type!==GE.Int&&t.type!==GE.Float||e.acceptedConnectionPointTypes.push(GE.Vector2,GE.Vector3,GE.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}}(0,je.Cg)([t_("Operation",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"Add",value:XE.Add},{label:"Subtract",value:XE.Subtract},{label:"Multiply",value:XE.Multiply},{label:"Divide",value:XE.Divide},{label:"Max",value:XE.Max},{label:"Min",value:XE.Min}]})],TP.prototype,"operation",void 0),(0,X.Y5)("BABYLON.MathBlock",TP);class CP extends eP{constructor(e){super(e),this.registerInput("value",GE.AutoDetect),this.registerInput("fromMin",GE.Float,!0,0),this.registerInput("fromMax",GE.Float,!0,1),this.registerInput("toMin",GE.Float,!0,0),this.registerInput("toMax",GE.Float,!0,1),this.registerOutput("output",GE.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(GE.Vector2),this._inputs[0].excludedConnectionPointTypes.push(GE.Vector3),this._inputs[0].excludedConnectionPointTypes.push(GE.Vector4),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.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)return this.output._storedFunction=null,void(this.output._storedValue=null);this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.fromMin.getConnectedValue(e),r=this.fromMax.getConnectedValue(e),s=this.toMin.getConnectedValue(e),n=(t-i)/(r-i)*(this.toMax.getConnectedValue(e)-s)+s;return this.output.type===GE.Int?Math.floor(n):n}}}(0,X.Y5)("BABYLON.MapRangeBlock",CP),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(qE||(qE={}));class yP extends eP{constructor(e){super(e),this.test=qE.Equal,this.registerInput("left",GE.Float),this.registerInput("right",GE.Float,!0,0),this.registerInput("ifTrue",GE.AutoDetect,!0,1),this.registerInput("ifFalse",GE.AutoDetect,!0,0),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=GE.Float,this._inputs[0].acceptedConnectionPointTypes.push(GE.Int),this._inputs[1].acceptedConnectionPointTypes.push(GE.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)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);let r=!1;switch(this.test){case qE.Equal:r=(0,ar.WithinEpsilon)(t,i,lt.bH);break;case qE.NotEqual:r=t!==i;break;case qE.LessThan:r=ti;break;case qE.LessOrEqual:r=t<=i;break;case qE.GreaterOrEqual:r=t>=i;break;case qE.Xor:r=!!t&&!i||!t&&!!i;break;case qE.Or:r=!!t||!!i;break;case qE.And:r=!!t&&!!i}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.${qE[this.test]};\n`}serialize(){const e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}}(0,je.Cg)([t_("Test",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"Equal",value:qE.Equal},{label:"NotEqual",value:qE.NotEqual},{label:"LessThan",value:qE.LessThan},{label:"GreaterThan",value:qE.GreaterThan},{label:"LessOrEqual",value:qE.LessOrEqual},{label:"GreaterOrEqual",value:qE.GreaterOrEqual},{label:"Xor",value:qE.Xor},{label:"Or",value:qE.Or},{label:"And",value:qE.And}]})],yP.prototype,"test",void 0),(0,X.Y5)("BABYLON.ConditionBlock",yP),function(e){e[e.None=0]="None",e[e.LoopID=1]="LoopID",e[e.InstanceID=2]="InstanceID",e[e.Once=3]="Once"}(YE||(YE={}));class EP extends eP{constructor(e){super(e),this._currentLockId=-1,this.lockMode=YE.None,this.registerInput("min",GE.AutoDetect),this.registerInput("max",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.Texture),this._inputs[1].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[1].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[1].excludedConnectionPointTypes.push(GE.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 rP("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){const e=new rP("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case GE.Int:case GE.Float:e=e=>{const t=this.min.getConnectedValue(e)||0,i=this.max.getConnectedValue(e)||0;return t+Math.random()*(i-t)};break;case GE.Vector2:e=e=>{const t=this.min.getConnectedValue(e)||W.I9.Zero(),i=this.max.getConnectedValue(e)||W.I9.Zero();return new W.I9(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y))};break;case GE.Vector3:e=e=>{const t=this.min.getConnectedValue(e)||W.Pq.Zero(),i=this.max.getConnectedValue(e)||W.Pq.Zero();return new W.Pq(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z))};break;case GE.Vector4:e=e=>{const t=this.min.getConnectedValue(e)||W.IU.Zero(),i=this.max.getConnectedValue(e)||W.IU.Zero();return new W.IU(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z),t.w+Math.random()*(i.w-t.w))}}this.lockMode!==YE.None&&e?this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case YE.InstanceID:i=t.getContextualValue(HE.InstanceID,!0)||0;break;case YE.LoopID:i=t.getContextualValue(HE.LoopID,!0)||0;break;case YE.Once:i=t.buildId||0}return this._currentLockId===i&&this.lockMode!==YE.None||(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}:this.output._storedFunction=e}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${YE[this.lockMode]};\n`}serialize(){const e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}}(0,je.Cg)([t_("LockMode",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"None",value:YE.None},{label:"LoopID",value:YE.LoopID},{label:"InstanceID",value:YE.InstanceID},{label:"Once",value:YE.Once}]})],EP.prototype,"lockMode",void 0),(0,X.Y5)("BABYLON.RandomBlock",EP);class PP extends eP{constructor(e){super(e),this.registerInput("offset",GE.Vector3,!0,W.Pq.Zero()),this.registerInput("scale",GE.Float,!0,1),this.registerInput("octaves",GE.Float,!0,2,0,16),this.registerInput("roughness",GE.Float,!0,.5,0,1),this.registerOutput("output",GE.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 0!==t?-e:e}_noiseGrad(e,t,i,r){const s=15&e,n=s<8?t:i,o=s<4?i:12===s||14==s?t:r;return this._negateIf(n,s&n)+this._negateIf(o,2&s)}_fade(e){return e*e*e*(e*(6*e-15)+10)}_hashBitRotate(e,t){return e<>32-t}_hash(e,t,i){let r,s,n;return r=s=n=3735928584,n+=i,s+=t,r+=e,n^=s,n-=this._hashBitRotate(s,14),r^=n,r-=this._hashBitRotate(n,11),s^=r,s-=this._hashBitRotate(r,25),n^=s,n-=this._hashBitRotate(s,16),r^=n,r-=this._hashBitRotate(n,4),s^=r,s-=this._hashBitRotate(r,14),n^=s,n-=this._hashBitRotate(s,24),n}_mix(e,t,i,r,s,n,o,a,l,h,c){const u=1-l,d=1-h;return(1-c)*(d*(e*u+t*l)+h*(i*u+r*l))+c*(d*(s*u+n*l)+h*(o*u+a*l))}_perlinNoise(e){const t=(0|e.x)-(e.x<0?1:0),i=(0|e.y)-(e.y<0?1:0),r=(0|e.z)-(e.z<0?1:0),s=e.x-t,n=e.y-i,o=e.z-r,a=this._fade(s),l=this._fade(n),h=this._fade(o);return this._mix(this._noiseGrad(this._hash(t,i,r),s,n,o),this._noiseGrad(this._hash(t+1,i,r),s-1,n,o),this._noiseGrad(this._hash(t,i+1,r),s,n-1,o),this._noiseGrad(this._hash(t+1,i+1,r),s-1,n-1,o),this._noiseGrad(this._hash(t,i,r+1),s,n,o-1),this._noiseGrad(this._hash(t+1,i,r+1),s-1,n,o-1),this._noiseGrad(this._hash(t,i+1,r+1),s,n-1,o-1),this._noiseGrad(this._hash(t+1,i+1,r+1),s-1,n-1,o-1),a,l,h)}_perlinSigned(e){return.982*this._perlinNoise(e)}_perlin(e){return this._perlinSigned(e)/2+.5}noise(e,t,i,r,s){const n=new W.Pq(i.x*s+r.x,i.y*s+r.y,i.z*s+r.z);let o=1,a=1,l=0,h=0;const c=0|(e=(0,ar.Clamp)(e,0,15));for(let e=0;e<=c;e++)h+=this._perlin(n.scale(o))*a,l+=a,a*=(0,ar.Clamp)(t,0,1),o*=2;const u=e-Math.floor(e);if(0==u)return h/l;let d=h+this._perlin(n.scale(o))*a;return h/=l,d/=l+a,(1-u)*h+u*d}_buildBlock(){this.output._storedFunction=e=>{const t=e.getContextualValue(HE.Positions),i=this.octaves.getConnectedValue(e),r=this.roughness.getConnectedValue(e),s=this.offset.getConnectedValue(e),n=this.scale.getConnectedValue(e);return this.noise(i,r,t,s,n)}}}(0,X.Y5)("BABYLON.NoiseBlock",PP);class AP extends eP{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",GE.Geometry),this.registerInput("geometry1",GE.Geometry,!0),this.registerInput("geometry2",GE.Geometry,!0),this.registerInput("geometry3",GE.Geometry,!0),this.registerInput("geometry4",GE.Geometry,!0),this.registerOutput("output",GE.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=e=>{const t=[];if(this.geometry0.isConnected){const i=this.geometry0.getConnectedValue(e);i&&t.push(i)}if(this.geometry1.isConnected){const i=this.geometry1.getConnectedValue(e);i&&t.push(i)}if(this.geometry2.isConnected){const i=this.geometry2.getConnectedValue(e);i&&t.push(i)}if(this.geometry3.isConnected){const i=this.geometry3.getConnectedValue(e);i&&t.push(i)}if(this.geometry4.isConnected){const i=this.geometry4.getConnectedValue(e);i&&t.push(i)}if(0===t.length)return null;let i=t[0].clone();const r=t.slice(1);return r.length&&i&&(i=i.merge(r,!0,!1,!0,!0)),i};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"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],AP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.MergeGeometryBlock",AP);class RP extends eP{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",GE.Geometry,!0),this.registerInput("geometry1",GE.Geometry,!0),this.registerInput("geometry2",GE.Geometry,!0),this.registerInput("geometry3",GE.Geometry,!0),this.registerInput("geometry4",GE.Geometry,!0),this.registerInput("geometry5",GE.Geometry,!0),this.registerInput("geometry6",GE.Geometry,!0),this.registerInput("geometry7",GE.Geometry,!0),this.registerInput("geometry8",GE.Geometry,!0),this.registerInput("geometry9",GE.Geometry,!0),this.registerOutput("output",GE.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"GeometryCollectionBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get geometry5(){return this._inputs[5]}get geometry6(){return this._inputs[6]}get geometry7(){return this._inputs[7]}get geometry8(){return this._inputs[8]}get geometry9(){return this._inputs[9]}get output(){return this._outputs[0]}_storeGeometry(e,t,i,r){if(e.isConnected){const s=e.getConnectedValue(t);if(!s)return;s.metadata=s.metadata||{},s.metadata.collectionId=i,r.push(s)}}_buildBlock(e){const t=e=>{const t=[];return this._storeGeometry(this.geometry0,e,0,t),this._storeGeometry(this.geometry1,e,1,t),this._storeGeometry(this.geometry2,e,2,t),this._storeGeometry(this.geometry3,e,3,t),this._storeGeometry(this.geometry4,e,4,t),this._storeGeometry(this.geometry5,e,5,t),this._storeGeometry(this.geometry6,e,6,t),this._storeGeometry(this.geometry7,e,7,t),this._storeGeometry(this.geometry8,e,8,t),this._storeGeometry(this.geometry9,e,9,t),t.length?t[Math.round(Math.random()*(t.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"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],RP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.GeometryCollectionBlock",RP);class IP extends eP{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",GE.Geometry),this.registerOutput("output",GE.Geometry)}getClassName(){return"CleanGeometryBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(!this.geometry.isConnected)return null;const t=this.geometry.getConnectedValue(e).clone();if(!t.positions||!t.indices||!t.normals)return t;const i=t.indices,r=t.positions;return(0,mt.Y4)(r,i),t};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"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],IP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.CleanGeometryBlock",IP);class MP extends eP{constructor(e){super(e),this.registerInput("input",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}get buildExecutionTime(){return-1}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=e=>i.getConnectedValue(e)}}(0,X.Y5)("BABYLON.GeometryElbowBlock",MP);class OP extends eP{constructor(e){super(e),this.registerInput("geometry",GE.Geometry),this.registerOutput("output",GE.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=[]),bt.ComputeNormals(t.positions,t.indices,t.normals),t}}}(0,X.Y5)("BABYLON.ComputeNormalsBlock",OP);class DP extends eP{constructor(e){super(e),this.registerInput("xyzw ",GE.Vector4,!0),this.registerInput("xyz ",GE.Vector3,!0),this.registerInput("xy ",GE.Vector2,!0),this.registerInput("zw ",GE.Vector2,!0),this.registerInput("x ",GE.Float,!0),this.registerInput("y ",GE.Float,!0),this.registerInput("z ",GE.Float,!0),this.registerInput("w ",GE.Float,!0),this.registerOutput("xyzw",GE.Vector4),this.registerOutput("xyz",GE.Vector3),this.registerOutput("xy",GE.Vector2),this.registerOutput("zw",GE.Vector2),this.registerOutput("x",GE.Float),this.registerOutput("y",GE.Float),this.registerOutput("z",GE.Float),this.registerOutput("w",GE.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"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":"x "===e?"xIn":"y "===e?"yIn":"z "===e?"zIn":"w "===e?"wIn":e}_outputRename(e){switch(e){case"x":return"xOut";case"y":return"yOut";case"z":return"zOut";case"w":return"wOut";case"xy":return"xyOut";case"zw":return"zwOut";case"xyz":return"xyzOut";case"xyzw":return"xyzwOut";default:return e}}_buildBlock(e){super._buildBlock(e);const t=this.xIn,i=this.yIn,r=this.zIn,s=this.wIn,n=this.xyIn,o=this.zwIn,a=this.xyzIn,l=this.xyzwIn,h=this.xyzwOut,c=this.xyzOut,u=this.xyOut,d=this.zwOut,f=this.xOut,p=this.yOut,_=this.zOut,m=this.wOut,g=e=>{if(l.isConnected)return l.getConnectedValue(e);let h=0,c=0,u=0,d=0;if(t.isConnected&&(h=t.getConnectedValue(e)),i.isConnected&&(c=i.getConnectedValue(e)),r.isConnected&&(u=r.getConnectedValue(e)),s.isConnected&&(d=s.getConnectedValue(e)),n.isConnected){const t=n.getConnectedValue(e);t&&(h=t.x,c=t.y)}if(o.isConnected){const t=o.getConnectedValue(e);t&&(u=t.x,d=t.y)}if(a.isConnected){const t=a.getConnectedValue(e);t&&(h=t.x,c=t.y,u=t.z)}return new W.IU(h,c,u,d)};h._storedFunction=e=>g(e),c._storedFunction=e=>{const t=g(e);return new W.Pq(t.x,t.y,t.z)},u._storedFunction=e=>{const t=g(e);return new W.I9(t.x,t.y)},d._storedFunction=e=>{const t=g(e);return new W.I9(t.z,t.w)},f._storedFunction=e=>g(e).x,p._storedFunction=e=>g(e).y,_._storedFunction=e=>g(e).z,m._storedFunction=e=>g(e).w}}(0,X.Y5)("BABYLON.VectorConverterBlock",DP);class wP extends eP{constructor(e){super(e),this.registerInput("input",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(GE.Float),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.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){super._buildBlock(e),this.output._storedFunction=null,this.input.isConnected?this.output._storedFunction=e=>this.input.getConnectedValue(e).normalize():this.output._storedValue=null}}(0,X.Y5)("BABYLON.NormalizeVectorBlock",wP);class NP extends eP{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",GE.Geometry),this.registerInput("id",GE.Int,!0,0),this.registerOutput("output",GE.Geometry),this.id.acceptedConnectionPointTypes.push(GE.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)return this.output._storedFunction=null,void(this.output._storedValue=null);const t=e=>{const t=this.geometry.getConnectedValue(e);if(!t||!t.indices||!t.positions)return t;const i=new xt;return i.materialIndex=0|this.id.getConnectedValue(e),i.indexStart=0,i.indexCount=t.indices.length,i.verticesStart=0,i.verticesCount=t.positions.length/3,t.materialInfos=[i],t};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"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],NP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.SetMaterialIDBlock",NP);class FP extends eP{constructor(e){super(e),this._indexVector3=new W.Pq,this._currentControl=new W.Pq,this.evaluateContext=!0,this.resolutionX=3,this.resolutionY=3,this.resolutionZ=3,this.registerInput("geometry",GE.Geometry),this.registerInput("controls",GE.Vector3),this.registerOutput("output",GE.Geometry)}getExecutionIndex(){return this._currentIndexX+this.resolutionX*(this._currentIndexY+this.resolutionY*this._currentIndexZ)}getExecutionLoopIndex(){return this.getExecutionIndex()}getExecutionFaceIndex(){return 0}getClassName(){return"LatticeBlock"}get geometry(){return this._inputs[0]}get controls(){return this._inputs[1]}get output(){return this._outputs[0]}getOverridePositionsContextualValue(){return this._indexVector3}getOverrideNormalsContextualValue(){return this._currentControl}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),!this._vertexData||!this._vertexData.positions)return e.restoreExecutionContext(),void(this.output._storedValue=null);const t=this._vertexData.positions,i=(0,mt.b8)(t,0,t.length/3);for(this._lattice=new yE({resolutionX:this.resolutionX,resolutionY:this.resolutionY,resolutionZ:this.resolutionZ,size:i.maximum.subtract(i.minimum)}),this._currentIndexX=0;this._currentIndexXMath.cos(e);break;case KE.Sin:t=e=>Math.sin(e);break;case KE.Abs:t=e=>Math.abs(e);break;case KE.Exp:t=e=>Math.exp(e);break;case KE.Exp2:t=e=>Math.pow(2,e);break;case KE.Round:t=e=>Math.round(e);break;case KE.Floor:t=e=>Math.floor(e);break;case KE.Ceiling:t=e=>Math.ceil(e);break;case KE.Sqrt:t=e=>Math.sqrt(e);break;case KE.Log:t=e=>Math.log(e);break;case KE.Tan:t=e=>Math.tan(e);break;case KE.ArcTan:t=e=>Math.atan(e);break;case KE.ArcCos:t=e=>Math.acos(e);break;case KE.ArcSin:t=e=>Math.asin(e);break;case KE.Sign:t=e=>Math.sign(e);break;case KE.Negate:t=e=>-e;break;case KE.OneMinus:t=e=>1-e;break;case KE.Reciprocal:t=e=>1/e;break;case KE.ToRadians:t=e=>e*Math.PI/180;break;case KE.ToDegrees:t=e=>180*e/Math.PI;break;case KE.Fract:t=e=>e>=0?e-Math.floor(e):e-Math.ceil(e)}if(!t)return this.output._storedFunction=null,void(this.output._storedValue=null);switch(this.input.type){case GE.Int:case GE.Float:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return t(i)};break;case GE.Vector2:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new W.I9(t(i.x),t(i.y))};break;case GE.Vector3:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new W.Pq(t(i.x),t(i.y),t(i.z))};break;case GE.Vector4:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new W.IU(t(i.x),t(i.y),t(i.z),t(i.w))}}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.${KE[this.operation]};\n`}}(0,je.Cg)([t_("Operation",4,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0},options:[{label:"Cos",value:KE.Cos},{label:"Sin",value:KE.Sin},{label:"Abs",value:KE.Abs},{label:"Exp",value:KE.Exp},{label:"Exp2",value:KE.Exp2},{label:"Round",value:KE.Round},{label:"Floor",value:KE.Floor},{label:"Ceiling",value:KE.Ceiling},{label:"Sqrt",value:KE.Sqrt},{label:"Log",value:KE.Log},{label:"Tan",value:KE.Tan},{label:"ArcTan",value:KE.ArcTan},{label:"ArcCos",value:KE.ArcCos},{label:"ArcSin",value:KE.ArcSin},{label:"Sign",value:KE.Sign},{label:"Negate",value:KE.Negate},{label:"OneMinus",value:KE.OneMinus},{label:"Reciprocal",value:KE.Reciprocal},{label:"ToDegrees",value:KE.ToDegrees},{label:"ToRadians",value:KE.ToRadians},{label:"Fract",value:KE.Fract}]})],LP.prototype,"operation",void 0),(0,X.Y5)("BABYLON.GeometryTrigonometryBlock",LP);class BP extends eP{constructor(e){super(e),this._rotationMatrix=new W.uq,this._scalingMatrix=new W.uq,this._translationMatrix=new W.uq,this._scalingRotationMatrix=new W.uq,this._pivotMatrix=new W.uq,this._backPivotMatrix=new W.uq,this._transformMatrix=new W.uq,this.evaluateContext=!0,this.registerInput("value",GE.AutoDetect),this.registerInput("matrix",GE.Matrix,!0),this.registerInput("translation",GE.Vector3,!0,W.Pq.Zero()),this.registerInput("rotation",GE.Vector3,!0,W.Pq.Zero()),this.registerInput("scaling",GE.Vector3,!0,W.Pq.One()),this.registerInput("pivot",GE.Vector3,!0,W.Pq.Zero()),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(GE.Float),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.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 pivot(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const t=e=>{const t=this.value.getConnectedValue(e);if(!t)return null;let i;if(this.matrix.isConnected)i=this.matrix.getConnectedValue(e);else{const t=this.scaling.getConnectedValue(e)||W.Pq.OneReadOnly,r=this.rotation.getConnectedValue(e)||W.Pq.ZeroReadOnly,s=this.translation.getConnectedValue(e)||W.Pq.ZeroReadOnly,n=this.pivot.getConnectedValue(e)||W.Pq.ZeroReadOnly;W.uq.TranslationToRef(-n.x,-n.y,-n.z,this._pivotMatrix),W.uq.ScalingToRef(t.x,t.y,t.z,this._scalingMatrix),W.uq.RotationYawPitchRollToRef(r.y,r.x,r.z,this._rotationMatrix),W.uq.TranslationToRef(s.x+n.x,s.y+n.y,s.z+n.z,this._translationMatrix),this._pivotMatrix.multiplyToRef(this._scalingMatrix,this._backPivotMatrix),this._backPivotMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),i=this._transformMatrix}switch(this.value.type){case GE.Geometry:{const e=t.clone();return e.transform(i),e}case GE.Vector2:return W.I9.Transform(t,i);case GE.Vector3:return W.Pq.TransformCoordinates(t,i);case GE.Vector4:return W.IU.TransformCoordinates(t,i)}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"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],BP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.GeometryTransformBlock",BP);class VP extends eP{constructor(e){super(e),this.registerInput("angle",GE.Float,!1,0),this.registerOutput("matrix",GE.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new rP("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>W.uq.RotationX(this.angle.getConnectedValue(e))}}(0,X.Y5)("BABYLON.RotationXBlock",VP);class kP extends eP{constructor(e){super(e),this.registerInput("angle",GE.Float,!1,0),this.registerOutput("matrix",GE.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new rP("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>W.uq.RotationY(this.angle.getConnectedValue(e))}}(0,X.Y5)("BABYLON.RotationYBlock",kP);class UP extends eP{constructor(e){super(e),this.registerInput("angle",GE.Float,!1,0),this.registerOutput("matrix",GE.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new rP("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>W.uq.RotationZ(this.angle.getConnectedValue(e))}}(0,X.Y5)("BABYLON.RotationZBlock",UP);class GP extends eP{constructor(e){super(e),this.registerInput("scale",GE.Vector3,!1,W.Pq.One()),this.registerOutput("matrix",GE.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){const e=new rP("Scale");e.value=new W.Pq(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.scale.getConnectedValue(e);return W.uq.Scaling(t.x,t.y,t.z)}}}(0,X.Y5)("BABYLON.ScalingBlock",GP);class zP extends eP{constructor(e){super(e),this.registerInput("source",GE.Vector3,!0,W.Pq.Up()),this.registerInput("target",GE.Vector3,!0,W.Pq.Left()),this.registerOutput("matrix",GE.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=e=>{const t=this.source.getConnectedValue(e).clone(),i=this.target.getConnectedValue(e).clone(),r=new W.uq;return t.normalize(),i.normalize(),W.uq.RotationAlignToRef(t,i,r,!0),r}}}(0,X.Y5)("BABYLON.AlignBlock",zP);class WP extends eP{constructor(e){super(e),this.registerInput("translation",GE.Vector3,!1,W.Pq.Zero()),this.registerOutput("matrix",GE.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){const e=new rP("Translation");e.value=new W.Pq(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.translation.getConnectedValue(e);return W.uq.Translation(t.x,t.y,t.z)}}}(0,X.Y5)("BABYLON.TranslationBlock",WP);class HP extends eP{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",GE.Geometry),this.registerInput("instance",GE.Geometry,!0),this.registerInput("density",GE.Float,!0,1,0,1),this.registerInput("matrix",GE.Matrix,!0),this.registerInput("rotation",GE.Vector3,!0,W.Pq.Zero()),this.registerInput("scaling",GE.Vector3,!0,W.Pq.One()),this.scaling.acceptedConnectionPointTypes.push(GE.Float),this.registerOutput("output",GE.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=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.instance.isConnected)return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=this._vertexData.positions.length/3;const i=[],r=new W.Pq,s=[];let n=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndexs)continue;r.fromArray(n,3*this._currentIndex);const o=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(o,r,t,i)}else{const t=e.adaptInput(this.scaling,GE.Vector3,W.Pq.OneReadOnly),s=this.rotation.getConnectedValue(e)||W.Pq.ZeroReadOnly;e._instantiate(o,r,s,t,i)}this._currentLoopIndex++}if(e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),!i.length)return null;if(1===i.length)this._vertexData=i[0];else{const e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}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"};\n`;return e+=`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`,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,void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],HP.prototype,"evaluateContext",void 0),(0,je.Cg)([t_("Remove duplicated positions",0,"ADVANCED",{notifiers:{update:!0}})],HP.prototype,"removeDuplicatedPositions",void 0),(0,X.Y5)("BABYLON.InstantiateOnVerticesBlock",HP);class XP extends eP{constructor(e){super(e),this._currentPosition=new W.Pq,this._currentUV=new W.I9,this._vertex0=new W.Pq,this._vertex1=new W.Pq,this._vertex2=new W.Pq,this._tempVector0=new W.Pq,this._tempVector1=new W.Pq,this._uv0=new W.I9,this._uv1=new W.I9,this._uv2=new W.I9,this.evaluateContext=!0,this.registerInput("geometry",GE.Geometry),this.registerInput("instance",GE.Geometry,!0),this.registerInput("count",GE.Int,!0,256),this.registerInput("matrix",GE.Matrix,!0),this.registerInput("rotation",GE.Vector3,!0,W.Pq.Zero()),this.registerInput("scaling",GE.Vector3,!0,W.Pq.One()),this.scaling.acceptedConnectionPointTypes.push(GE.Float),this.registerOutput("output",GE.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(),W.Pq.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=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!(this._vertexData&&this._vertexData.positions&&this._vertexData.indices&&this.instance.isConnected))return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=null;const i=this.count.getConnectedValue(e),r=this._vertexData.indices.length/3,s=i/r;let n=0;const o=[];let a=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex=i);l++){let i=Math.random(),r=Math.random();if(i>r){const e=i;i=r,r=e}const l=i,h=r-i,c=1-l-h;if(this._currentPosition.set(l*this._vertex0.x+h*this._vertex1.x+c*this._vertex2.x,l*this._vertex0.y+h*this._vertex1.y+c*this._vertex2.y,l*this._vertex0.z+h*this._vertex1.z+c*this._vertex2.z),this._vertexData.uvs&&this._currentUV.set(l*this._uv0.x+h*this._uv1.x+c*this._uv2.x,l*this._uv0.y+h*this._uv1.y+c*this._uv2.y),t=this.instance.getConnectedValue(e),!t||!t.positions||0===t.positions.length){n-=s;continue}const u=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(u,this._currentPosition,t,o)}else{const t=e.adaptInput(this.scaling,GE.Vector3,W.Pq.OneReadOnly),i=this.rotation.getConnectedValue(e)||W.Pq.ZeroReadOnly;e._instantiate(u,this._currentPosition,i,t,o)}a++,this._currentLoopIndex++}}if(o.length)if(1===o.length)this._vertexData=o[0];else{const e=o.splice(0,1)[0];this._vertexData=e.merge(o,!0,!1,!0,!0)}return e.restoreExecutionContext(),e.restoreInstancingContext(),e.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"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],XP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.InstantiateOnFacesBlock",XP);class qP extends eP{constructor(e){super(e),this._currentPosition=new W.Pq,this._vertex0=new W.Pq,this._vertex1=new W.Pq,this._vertex2=new W.Pq,this.evaluateContext=!0,this.gridMode=!1,this.registerInput("geometry",GE.Geometry),this.registerInput("instance",GE.Geometry,!0),this.registerInput("count",GE.Int,!0,256),this.registerInput("matrix",GE.Matrix,!0),this.registerInput("rotation",GE.Vector3,!0,W.Pq.Zero()),this.registerInput("scaling",GE.Vector3,!0,W.Pq.One()),this.registerInput("gridSize",GE.Int,!0,10),this.scaling.acceptedConnectionPointTypes.push(GE.Float),this.registerOutput("output",GE.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return 0}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getClassName(){return"InstantiateOnVolumeBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get gridSize(){return this._inputs[6]}get output(){return this._outputs[0]}_getValueOnGrid(e,t,i,r){const s=(r-i)/t;return i+s/2+e*s}_getIndexinGrid(e,t,i,r){return e+t*r+i*r*r}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!(this._vertexData&&this._vertexData.positions&&this._vertexData.indices&&this.instance.isConnected))return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=null;const i=this.count.getConnectedValue(e),r=[],s=(0,mt.b8)(this._vertexData.positions,0,this._vertexData.positions.length/3),n=s.minimum,o=s.maximum,a=new W.Pq(.5,.8,.2),l=this._vertexData.indices.length/3,h=this.gridSize.getConnectedValue(e);let c;if(this._currentLoopIndex=0,this.gridMode){c=[];for(let e=0;e0&&u++}if(u%2==0){s--;continue}if(t=this.instance.getConnectedValue(e),!t||!t.positions||0===t.positions.length)continue;const d=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(d,this._currentPosition,t,r)}else{const t=e.adaptInput(this.scaling,GE.Vector3,W.Pq.OneReadOnly),i=this.rotation.getConnectedValue(e)||W.Pq.ZeroReadOnly;e._instantiate(d,this._currentPosition,i,t,r)}this._currentLoopIndex++}if(r.length)if(1===r.length)this._vertexData=r[0];else{const e=r.splice(0,1)[0];this._vertexData=e.merge(r,!0,!1,!0,!0)}return e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`;return e+=`${this._codeVariableName}.gridMode = ${this.gridMode?"true":"false"};\n`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.gridMode=this.gridMode,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext),void 0!==e.gridMode&&(this.gridMode=e.gridMode)}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],qP.prototype,"evaluateContext",void 0),(0,je.Cg)([t_("Grid mode",0,"MODES",{notifiers:{rebuild:!0}})],qP.prototype,"gridMode",void 0),(0,X.Y5)("BABYLON.InstantiateOnVolumeBlock",qP);class YP extends eP{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",GE.Geometry,!0),this.registerInput("count",GE.Int,!0,1),this.registerOutput("output",GE.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"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],YP.prototype,"evaluateContext",void 0);class KP extends YP{constructor(e){super(e),this.registerInput("matrix",GE.Matrix,!0),this.registerInput("position",GE.Vector3,!0,W.Pq.Zero()),this.registerInput("rotation",GE.Vector3,!0,W.Pq.Zero()),this.registerInput("scaling",GE.Vector3,!0,W.Pq.One()),this.scaling.acceptedConnectionPointTypes.push(GE.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=e=>{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[];for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[],r=W.uq.Identity(),s=W.Pq.Zero(),n=W.Pq.Zero(),o=W.Pq.Zero();for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[],r=W.uq.Identity(),s=W.uq.Identity(),n=W.uq.Identity(),o=W.Pq.Zero(),a=W.Pq.Zero(),l=W.Pq.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}}(0,X.Y5)("BABYLON.IntFloatConverterBlock",QP);class ZP extends eP{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.Texture)}get buildExecutionTime(){return-1}getClassName(){return"DebugBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.input.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);this.log=[];const t=e=>{const t=this.input.getConnectedValue(e);if(null==t)return this.log.push(["null",""]),t;switch(this.input.type){case GE.Vector2:this.log.push([Hy(t,4),t.toString()]);break;case GE.Vector3:this.log.push([Xy(t,4),t.toString()]);break;case GE.Vector4:this.log.push([qy(t,4),t.toString()]);break;default:this.log.push([t.toString(),t.toString()])}return t};this.output.isConnected?this.output._storedFunction=t:this.output._storedValue=t(e)}}(0,X.Y5)("BABYLON.DebugBlock",ZP);class JP extends eP{constructor(e){super(e),this.registerInput("geometry",GE.Geometry),this.registerOutput("output",GE.Geometry),this.registerOutput("id",GE.Int),this.registerOutput("collectionId",GE.Int),this.registerOutput("verticesCount",GE.Int),this.registerOutput("facesCount",GE.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)return 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,void(this.output._storedFunction=null);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)}}(0,X.Y5)("BABYLON.GeometryInfoBlock",JP),function(e){e[e.Spherical=0]="Spherical",e[e.Cylindrical=1]="Cylindrical",e[e.Cubic=2]="Cubic"}(jE||(jE={}));class eA extends eP{constructor(e){super(e),this.mapping=jE.Spherical,this.registerInput("position",GE.Vector3),this.registerInput("normal",GE.Vector3),this.registerInput("center",GE.Vector3,!0,W.Pq.Zero()),this.registerOutput("uv",GE.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)return this.uv._storedFunction=null,void(this.uv._storedValue=null);const e=W.Pq.Zero(),t=t=>{const i=this.position.getConnectedValue(t)||W.Pq.Zero(),r=this.normal.getConnectedValue(t)||W.Pq.Zero(),s=this.center.getConnectedValue(t),n=W.I9.Zero();switch(this.mapping){case jE.Spherical:{i.subtractToRef(s,e);const t=e.length();t>0&&(n.x=Math.acos(e.y/t)/Math.PI,0===e.x&&0===e.z||(n.y=Math.atan2(e.x,e.z)/(2*Math.PI)));break}case jE.Cylindrical:{i.subtractToRef(s,e);const t=e.length();t>0&&(n.x=Math.atan2(e.x/t,e.z/t)/(2*Math.PI),n.y=(e.y+1)/2);break}case jE.Cubic:{const e=Math.abs(r.x),t=Math.abs(r.y),o=Math.abs(r.z),a=Math.max(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z));let l=0,h=0;e>=t&&e>=o?(l=i.y/a-s.y,h=i.z/a-s.z):t>=e&&t>=o?(l=i.x/a-s.x,h=i.z/a-s.z):(l=i.x/a-s.x,h=i.y/a-s.y),n.x=(l+1)/2,n.y=(h+1)/2}}return n};this.uv._storedFunction=e=>t(e)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.mapping = BABYLON.MappingTypes.${jE[this.mapping]};\n`}serialize(){const e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}}(0,je.Cg)([t_("Mapping",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"Spherical",value:jE.Spherical},{label:"Cylindrical",value:jE.Cylindrical},{label:"Cubic",value:jE.Cubic}]})],eA.prototype,"mapping",void 0),(0,X.Y5)("BABYLON.MappingBlock",eA);class tA extends eP{constructor(e){super(e),this.registerInput("matrix0",GE.Matrix),this.registerInput("matrix1",GE.Matrix),this.registerOutput("output",GE.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?t.multiply(i):null}}}(0,X.Y5)("BABYLON.MatrixComposeBlock",tA);class iA extends eP{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",GE.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const r of this.endpoints)-1===t.indexOf(r)&&(i+=r._dumpCode(e,t));return i}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(const t of this.endpoints)if(t.isAnAncestorOfType(e))return!0;return!1}isAnAncestorOf(e){for(const t of this.endpoints){if(t===e)return!0;if(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);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}_buildBlock(){for(const e of this._endpoints)e.output._storedFunction=e=>this.input.getConnectedValue(e)}}(0,X.Y5)("BABYLON.TeleportInBlock",iA);class rA extends eP{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",GE.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&&-1===t.indexOf(this.entryPoint)&&(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});\n`),e}serialize(){const e=super.serialize();return e.entryPoint=this.entryPoint?.uniqueId??"",e}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}}(0,X.Y5)("BABYLON.TeleportOutBlock",rA);class sA extends eP{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",GE.Texture)}getClassName(){return"GeometryTextureBlock"}get texture(){return this._outputs[0]}_prepareImgToLoadAsync(e){return new Promise(((t,i)=>{const r=new Image,s=document.createElement("canvas"),n=s.getContext("2d");r.onload=()=>{s.width=r.width,s.height=r.height,n.drawImage(r,0,0);const e=n.getImageData(0,0,r.width,r.height).data,i=new Float32Array(e.length);for(let t=0;t{this._data=null,i()},r.src=e}))}cleanData(){this._data=null}loadTextureFromFileAsync(e){return this._prepareImgToLoadAsync(URL.createObjectURL(e))}loadTextureFromUrlAsync(e){return this._prepareImgToLoadAsync(e)}extractFromTextureAsync(e){return new Promise(((t,i)=>{if(!e.isReady())return void e.onLoadObservable.addOnce((()=>this.extractFromTextureAsync(e).then(t).catch(i)));const r=e.getSize();Ac.LO.GetTextureDataAsync(e,r.width,r.height).then((async e=>{const i=new Float32Array(e.length);for(let t=0;t=0?e%1:1-Math.abs(e)%1}_buildBlock(){const e=e=>{const t=this.texture.getConnectedValue(e);if(!t||!t.data)return null;const i=this.coordinates.getConnectedValue(e);if(!i)return null;const r=this.clampCoordinates?Math.max(0,Math.min(i.x,1)):this._repeatClamp(i.x),s=this.clampCoordinates?Math.max(0,Math.min(i.y,1)):this._repeatClamp(i.y),n=Math.floor(r*(t.width-1)),o=Math.floor(s*(t.height-1)),a=n+t.width*o;return W.IU.FromArray(t.data,4*a)};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};\n`}serialize(){const e=super.serialize();return e.clampCoordinates=this.clampCoordinates,e}_deserialize(e){super._deserialize(e),this.clampCoordinates=e.clampCoordinates}}(0,je.Cg)([t_("Clamp Coordinates",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],nA.prototype,"clampCoordinates",void 0),(0,X.Y5)("BABYLON.GeometryTextureFetchBlock",nA);class oA extends eP{constructor(e){super(e),this.registerInput("geometry",GE.Geometry),this.registerOutput("min",GE.Vector3),this.registerOutput("max",GE.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?(0,mt.b8)(t.positions,0,t.positions.length/3).minimum:null},this.max._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?(0,mt.b8)(t.positions,0,t.positions.length/3).maximum:null}}}(0,X.Y5)("BABYLON.BoundingBlock",oA),function(e){e[e.Intersect=0]="Intersect",e[e.Subtract=1]="Subtract",e[e.Union=2]="Union"}($E||($E={}));class aA extends eP{get _isReadyState(){return kE()?null:(this._csg2LoadingPromise||(this._csg2LoadingPromise=UE()),this._csg2LoadingPromise)}constructor(e){super(e),this.evaluateContext=!1,this.operation=$E.Intersect,this.useOldCSGEngine=!1,this.registerInput("geometry0",GE.Geometry),this.registerInput("geometry1",GE.Geometry),this.registerOutput("output",GE.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=e=>{const t=this.geometry0.getConnectedValue(e),i=this.geometry1.getConnectedValue(e);if(!t||!i)return null;const r=t.positions.length/3;let s;if(!t.normals&&i.normals&&(t.normals=new Array(t.positions.length)),!i.normals&&t.normals&&(i.normals=new Array(i.positions.length)),!t.uvs&&i.uvs&&(t.uvs=new Array(2*r)),!i.uvs&&t.uvs&&(i.uvs=new Array(2*r)),!t.colors&&i.colors&&(t.colors=new Array(4*r)),!i.colors&&t.colors&&(i.colors=new Array(4*r)),this.useOldCSGEngine){const e=nE.FromVertexData(t),r=nE.FromVertexData(i);switch(this.operation){case $E.Intersect:s=e.intersect(r);break;case $E.Subtract:s=e.subtract(r);break;case $E.Union:s=e.union(r)}}else{const e=VE.FromVertexData(t),r=VE.FromVertexData(i);switch(this.operation){case $E.Intersect:s=e.intersect(r);break;case $E.Subtract:s=e.subtract(r);break;case $E.Union:s=e.add(r)}}return s.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"};\n`;return e+=`${this._codeVariableName}.operation = BABYLON.BooleanGeometryOperations.${$E[this.operation]};\n`,e+=`${this._codeVariableName}.useOldCSGEngine = ${this.useOldCSGEngine?"true":"false"};\n`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.operation=this.operation,e.useOldCSGEngine=this.useOldCSGEngine,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,e.operation&&(this.operation=e.operation),this.useOldCSGEngine=!!e.useOldCSGEngine}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],aA.prototype,"evaluateContext",void 0),(0,je.Cg)([t_("Operation",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"Intersect",value:$E.Intersect},{label:"Subtract",value:$E.Subtract},{label:"Union",value:$E.Union}]})],aA.prototype,"operation",void 0),(0,je.Cg)([t_("Use old CSG engine",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],aA.prototype,"useOldCSGEngine",void 0),(0,X.Y5)("BABYLON.BooleanGeometryBlock",aA);class lA extends eP{constructor(e){super(e),this.registerInput("x",GE.AutoDetect),this.registerInput("y",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.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)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>Math.atan2(e,t);this.output._storedFunction=t=>{const i=this.x.getConnectedValue(t),r=this.y.getConnectedValue(t);switch(this.x.type){case GE.Int:case GE.Float:return e(i,r);case GE.Vector2:return new W.I9(e(i.x,r.x),e(i.y,r.y));case GE.Vector3:return new W.Pq(e(i.x,r.x),e(i.y,r.y),e(i.z,r.z));case GE.Vector4:return new W.IU(e(i.x,r.x),e(i.y,r.y),e(i.z,r.z),e(i.w,r.w))}return 0}}}(0,X.Y5)("BABYLON.GeometryArcTan2Block",lA);class hA extends eP{constructor(e){super(e),this.registerInput("left",GE.AutoDetect),this.registerInput("right",GE.AutoDetect),this.registerInput("gradient",GE.Float),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.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)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>(1-e)*t+e*i;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),r=this.right.getConnectedValue(t),s=this.gradient.getConnectedValue(t);switch(this.left.type){case GE.Int:case GE.Float:return e(s,i,r);case GE.Vector2:return new W.I9(e(s,i.x,r.x),e(s,i.y,r.y));case GE.Vector3:return new W.Pq(e(s,i.x,r.x),e(s,i.y,r.y),e(s,i.z,r.z));case GE.Vector4:return new W.IU(e(s,i.x,r.x),e(s,i.y,r.y),e(s,i.z,r.z),e(s,i.w,r.w))}return 0},this}}(0,X.Y5)("BABYLON.GeometryLerpBlock",hA);class cA extends eP{constructor(e){super(e),this.registerInput("left",GE.AutoDetect),this.registerInput("right",GE.AutoDetect),this.registerInput("gradient",GE.Float),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.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)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>(1-e)*t+e*i;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),r=this.right.getConnectedValue(t),s=this.gradient.getConnectedValue(t);switch(this.left.type){case GE.Int:case GE.Float:return e(s,i,r);case GE.Vector2:{const t=new W.I9(e(s,i.x,r.x),e(s,i.y,r.y));return t.normalize(),t}case GE.Vector3:{const t=new W.Pq(e(s,i.x,r.x),e(s,i.y,r.y),e(s,i.z,r.z));return t.normalize(),t}case GE.Vector4:{const t=new W.IU(e(s,i.x,r.x),e(s,i.y,r.y),e(s,i.z,r.z),e(s,i.w,r.w));return t.normalize(),t}}return 0},this}}(0,X.Y5)("BABYLON.GeometryNLerpBlock",cA);class uA extends eP{constructor(e){super(e),this.registerInput("value",GE.AutoDetect),this.registerInput("edge",GE.Float),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.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)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>e{const i=this.value.getConnectedValue(t),r=this.edge.getConnectedValue(t);switch(this.value.type){case GE.Int:case GE.Float:return e(i,r);case GE.Vector2:return new W.I9(e(i.x,r),e(i.y,r));case GE.Vector3:return new W.Pq(e(i.x,r),e(i.y,r),e(i.z,r));case GE.Vector4:return new W.IU(e(i.x,r),e(i.y,r),e(i.z,r),e(i.w,r))}return 0},this}}(0,X.Y5)("BABYLON.GeometryStepBlock",uA);class dA extends eP{constructor(e){super(e),this.registerInput("value",GE.AutoDetect),this.registerInput("edge0",GE.Float),this.registerInput("edge1",GE.Float),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.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)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>{const r=Math.max(0,Math.min((e-t)/(i-t),1));return r*r*(3-2*r)};return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),r=this.edge0.getConnectedValue(t),s=this.edge1.getConnectedValue(t);switch(this.value.type){case GE.Int:case GE.Float:return e(i,r,s);case GE.Vector2:return new W.I9(e(i.x,r,s),e(i.y,r,s));case GE.Vector3:return new W.Pq(e(i.x,r,s),e(i.y,r,s),e(i.z,r,s));case GE.Vector4:return new W.IU(e(i.x,r,s),e(i.y,r,s),e(i.z,r,s),e(i.w,r,s))}return 0},this}}(0,X.Y5)("BABYLON.GeometrySmoothStepBlock",dA);class fA extends eP{constructor(e){super(e),this.registerInput("left",GE.AutoDetect),this.registerInput("right",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.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)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>e-Math.floor(e/t)*t;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),r=this.right.getConnectedValue(t);switch(this.left.type){case GE.Int:case GE.Float:return e(i,r);case GE.Vector2:return new W.I9(e(i.x,r.x),e(i.y,r.y));case GE.Vector3:return new W.Pq(e(i.x,r.x),e(i.y,r.y),e(i.z,r.z));case GE.Vector4:return new W.IU(e(i.x,r.x),e(i.y,r.y),e(i.z,r.z),e(i.w,r.w))}return 0},this}}(0,X.Y5)("BABYLON.GeometryModBlock",fA);class pA extends eP{constructor(e){super(e),this.registerInput("value",GE.AutoDetect),this.registerInput("power",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.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)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>Math.pow(e,t);return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),r=this.power.getConnectedValue(t);switch(this.value.type){case GE.Int:case GE.Float:return e(i,r);case GE.Vector2:return new W.I9(e(i.x,r),e(i.y,r));case GE.Vector3:return new W.Pq(e(i.x,r),e(i.y,r),e(i.z,r));case GE.Vector4:return new W.IU(e(i.x,r),e(i.y,r),e(i.z,r),e(i.w,r))}return 0},this}}(0,X.Y5)("BABYLON.GeometryPowBlock",pA);class _A extends eP{constructor(e){super(e),this.minimum=0,this.maximum=1,this.registerInput("value",GE.AutoDetect),this.registerInput("min",GE.Float,!0),this.registerInput("max",GE.Float,!0),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.Texture)}getClassName(){return"GeometryClampBlock"}get value(){return this._inputs[0]}get min(){return this._inputs[1]}get max(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>Math.max(t,Math.min(e,i));return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),r=this.min.isConnected?this.min.getConnectedValue(t):this.minimum,s=this.max.isConnected?this.max.getConnectedValue(t):this.maximum;switch(this.value.type){case GE.Int:case GE.Float:return e(i,r,s);case GE.Vector2:return new W.I9(e(i.x,r,s),e(i.y,r,s));case GE.Vector3:return new W.Pq(e(i.x,r,s),e(i.y,r,s),e(i.z,r,s));case GE.Vector4:return new W.IU(e(i.x,r,s),e(i.y,r,s),e(i.z,r,s),e(i.w,r,s))}return 0},this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};\n`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};\n`,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}}(0,je.Cg)([t_("Minimum",1,void 0,{embedded:!0})],_A.prototype,"minimum",void 0),(0,je.Cg)([t_("Maximum",1,void 0,{embedded:!0})],_A.prototype,"maximum",void 0),(0,X.Y5)("BABYLON.GeometryClampBlock",_A);class mA extends eP{constructor(e){super(e),this.registerInput("left",GE.AutoDetect),this.registerInput("right",GE.AutoDetect),this.registerOutput("output",GE.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(GE.Int),this._inputs[0].excludedConnectionPointTypes.push(GE.Float),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Vector2),this._inputs[1].excludedConnectionPointTypes.push(GE.Int),this._inputs[1].excludedConnectionPointTypes.push(GE.Float),this._inputs[1].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[1].excludedConnectionPointTypes.push(GE.Vector2)}getClassName(){return"GeometryCrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.left.isConnected&&this.right.isConnected?(this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);switch(this.left.type){case GE.Vector3:return W.Pq.Cross(t,i);case GE.Vector4:return W.Pq.Cross(t.toVector3(),i.toVector3())}return 0},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}(0,X.Y5)("BABYLON.GeometryCrossBlock",mA),function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(QE||(QE={}));class gA extends eP{constructor(e){super(e),this.type=QE.EaseInOutSine,this.registerInput("input",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Int)}getClassName(){return"GeometryCurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.input.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);let e;switch(this.type){case QE.EaseInSine:e=e=>1-Math.cos(3.1415*e/2);break;case QE.EaseOutSine:e=e=>Math.sin(3.1415*e/2);break;case QE.EaseInOutSine:e=e=>-(Math.cos(3.1415*e)-1)/2;break;case QE.EaseInQuad:e=e=>e*e;break;case QE.EaseOutQuad:e=e=>(1-e)*(1-e);break;case QE.EaseInOutQuad:e=e=>e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;break;case QE.EaseInCubic:e=e=>e*e*e;break;case QE.EaseOutCubic:e=e=>1-Math.pow(1-e,3);break;case QE.EaseInOutCubic:e=e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;break;case QE.EaseInQuart:e=e=>e*e*e*e;break;case QE.EaseOutQuart:e=e=>1-Math.pow(1-e,4);break;case QE.EaseInOutQuart:e=e=>e<.5?8*e*e*e*e:1-Math.pow(-2*e+2,4)/2;break;case QE.EaseInQuint:e=e=>e*e*e*e*e;break;case QE.EaseOutQuint:e=e=>1-Math.pow(1-e,5);break;case QE.EaseInOutQuint:e=e=>e<.5?16*e*e*e*e*e:1-Math.pow(-2*e+2,5)/2;break;case QE.EaseInExpo:e=e=>0===e?0:Math.pow(2,10*e-10);break;case QE.EaseOutExpo:e=e=>1===e?1:1-Math.pow(2,-10*e);break;case QE.EaseInOutExpo:e=e=>0===e?0:1===e?1:e<.5?Math.pow(2,20*e-10)/2:(2-Math.pow(2,-20*e+10))/2;break;case QE.EaseInCirc:e=e=>1-Math.sqrt(1-Math.pow(e,2));break;case QE.EaseOutCirc:e=e=>Math.sqrt(1-Math.pow(e-1,2));break;case QE.EaseInOutCirc:e=e=>e<.5?(1-Math.sqrt(1-Math.pow(2*e,2)))/2:(Math.sqrt(1-Math.pow(-2*e+2,2))+1)/2;break;case QE.EaseInBack:e=e=>2.70158*e*e*e-1.70158*e*e;break;case QE.EaseOutBack:e=e=>2.70158*Math.pow(e-1,3)+1.70158*Math.pow(e-1,2);break;case QE.EaseInOutBack:e=e=>e<.5?Math.pow(2*e,2)*(7.189819*e-2.5949095)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+3.5949095)+2)/2;break;case QE.EaseInElastic:e=e=>0===e?0:1===e?1:-Math.pow(2,10*e-10)*Math.sin(6.283/3*(10*e-10.75));break;case QE.EaseOutElastic:e=e=>0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin(6.283/3*(10*e-.75))+1;break;case QE.EaseInOutElastic:e=e=>0===e?0:1==e?1:e<.5?-Math.pow(2,20*e-10)*Math.sin(6.283/4.5*(20*e-11.125))/2:Math.pow(2,-20*e+10)*Math.sin(6.283/4.5*(20*e-11.125))/2+1}return this.output._storedFunction=t=>{const i=this.input.getConnectedValue(t);switch(this.input.type){case GE.Float:return e(i);case GE.Vector2:return new W.I9(e(i.x),e(i.y));case GE.Vector3:return new W.Pq(e(i.x),e(i.y),e(i.z));case GE.Vector4:return new W.IU(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.${QE[this.type]};\n`}}(0,je.Cg)([t_("Type",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"EaseInSine",value:QE.EaseInSine},{label:"EaseOutSine",value:QE.EaseOutSine},{label:"EaseInOutSine",value:QE.EaseInOutSine},{label:"EaseInQuad",value:QE.EaseInQuad},{label:"EaseOutQuad",value:QE.EaseOutQuad},{label:"EaseInOutQuad",value:QE.EaseInOutQuad},{label:"EaseInCubic",value:QE.EaseInCubic},{label:"EaseOutCubic",value:QE.EaseOutCubic},{label:"EaseInOutCubic",value:QE.EaseInOutCubic},{label:"EaseInQuart",value:QE.EaseInQuart},{label:"EaseOutQuart",value:QE.EaseOutQuart},{label:"EaseInOutQuart",value:QE.EaseInOutQuart},{label:"EaseInQuint",value:QE.EaseInQuint},{label:"EaseOutQuint",value:QE.EaseOutQuint},{label:"EaseInOutQuint",value:QE.EaseInOutQuint},{label:"EaseInExpo",value:QE.EaseInExpo},{label:"EaseOutExpo",value:QE.EaseOutExpo},{label:"EaseInOutExpo",value:QE.EaseInOutExpo},{label:"EaseInCirc",value:QE.EaseInCirc},{label:"EaseOutCirc",value:QE.EaseOutCirc},{label:"EaseInOutCirc",value:QE.EaseInOutCirc},{label:"EaseInBack",value:QE.EaseInBack},{label:"EaseOutBack",value:QE.EaseOutBack},{label:"EaseInOutBack",value:QE.EaseInOutBack},{label:"EaseInElastic",value:QE.EaseInElastic},{label:"EaseOutElastic",value:QE.EaseOutElastic},{label:"EaseInOutElastic",value:QE.EaseInOutElastic}]})],gA.prototype,"type",void 0),(0,X.Y5)("BABYLON.GeometryCurveBlock",gA);class vA extends eP{constructor(e){super(e),this.registerInput("color",GE.Vector3),this.registerInput("level",GE.Float,!0,0),this.registerOutput("output",GE.Vector3)}getClassName(){return"GeometryDesaturateBlock"}get color(){return this._inputs[0]}get level(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.color.isConnected?(this.output._storedFunction=e=>{const t=this.color.getConnectedValue(e),i=this.level.getConnectedValue(e),r=.5*(Math.min(t.x,t.y,t.z)+Math.max(t.x,t.y,t.z));return new W.Pq(t.x*(1-i)+r*i,t.y*(1-i)+r*i,t.z*(1-i)+r*i)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}(0,X.Y5)("BABYLON.GeometryDesaturateBlock",vA);class xA extends eP{constructor(e){super(e),this.registerInput("value",GE.AutoDetect),this.registerInput("steps",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[1].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(GE.Float)}getClassName(){return"GeometryPosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected&&this.steps.isConnected?(this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.steps.getConnectedValue(e);let r=i;if(this.steps.type===GE.Float)switch(this.value.type){case GE.Vector2:r=new W.I9(i,i);break;case GE.Vector3:r=new W.Pq(i,i,i);break;case GE.Vector4:r=new W.IU(i,i,i,i)}switch(this.value.type){case GE.Vector2:return new W.I9(t.x/(1/r.x)*(1/r.x),t.y/(1/r.y)*(1/r.y));case GE.Vector3:return new W.Pq(t.x/(1/r.x)*(1/r.x),t.y/(1/r.y)*(1/r.y),t.z/(1/r.z)*(1/r.z));case GE.Vector4:return new W.IU(t.x/(1/r.x)*(1/r.x),t.y/(1/r.y)*(1/r.y),t.z/(1/r.z)*(1/r.z),t.w/(1/r.w)*(1/r.w));default:return Math.floor(t/(1/i)*(1/i))}},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}(0,X.Y5)("BABYLON.GeometryPosterizeBlock",xA);class bA extends eP{constructor(e){super(e),this.registerInput("value",GE.AutoDetect),this.registerInput("reference",GE.AutoDetect),this.registerInput("distance",GE.Float),this.registerInput("replacement",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(GE.Float),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[1].excludedConnectionPointTypes.push(GE.Float),this._inputs[1].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[3].excludedConnectionPointTypes.push(GE.Float),this._inputs[3].excludedConnectionPointTypes.push(GE.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(){return this.value.isConnected&&this.reference.isConnected&&this.distance.isConnected&&this.replacement.isConnected?(this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.reference.getConnectedValue(e),r=this.distance.getConnectedValue(e),s=this.replacement.getConnectedValue(e);return t.subtract(i).length(){const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.subtract(i).length()},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}(0,X.Y5)("BABYLON.GeometryDistanceBlock",SA);class TA extends eP{constructor(e){super(e),this.registerInput("left",GE.AutoDetect),this.registerInput("right",GE.AutoDetect),this.registerOutput("output",GE.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(GE.Int),this._inputs[0].excludedConnectionPointTypes.push(GE.Float),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[1].excludedConnectionPointTypes.push(GE.Float),this._inputs[1].excludedConnectionPointTypes.push(GE.Matrix)}getClassName(){return"GeometryDotBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.left.isConnected&&this.right.isConnected?(this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.dot(i)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}(0,X.Y5)("BABYLON.GeometryDotBlock",TA);class CA extends eP{constructor(e){super(e),this.registerInput("value",GE.AutoDetect),this.registerOutput("output",GE.Float),this._inputs[0].excludedConnectionPointTypes.push(GE.Int),this._inputs[0].excludedConnectionPointTypes.push(GE.Float),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix)}getClassName(){return"GeometryLengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected?(this.output._storedFunction=e=>this.value.getConnectedValue(e).length(),this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}(0,X.Y5)("BABYLON.GeometryLengthBlock",CA);class yA extends eP{constructor(e){super(e),this.registerInput("input",GE.Vector2),this.registerInput("angle",GE.Float),this.registerOutput("output",GE.Vector2)}getClassName(){return"GeometryRotate2dBlock"}get input(){return this._inputs[0]}get angle(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.angle.isConnected&&this.input.isConnected?(this.output._storedFunction=e=>{const t=this.input.getConnectedValue(e),i=this.angle.getConnectedValue(e);return new W.I9(Math.cos(i)*t.x-Math.sin(i)*t.y,Math.sin(i)*t.x+Math.cos(i)*t.y)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}(0,X.Y5)("BABYLON.GeometryRotate2dBlock",yA);class EA extends eP{constructor(e){super(e),this.onInterceptionObservable=new z.cP(void 0,!0),this.registerInput("input",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}get buildExecutionTime(){return-1}getClassName(){return"GeometryInterceptorBlock"}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=e=>{let t=i.getConnectedValue(e);return this.customFunction&&(t=this.customFunction(t,e)),this.onInterceptionObservable.notifyObservers(t),t}}}(0,X.Y5)("BABYLON.GeometryInterceptorBlock",EA),function(e){e[e.Max=0]="Max",e[e.Min=1]="Min",e[e.Sum=2]="Sum"}(ZE||(ZE={}));class PA extends eP{constructor(e){super(e),this.aggregation=ZE.Sum,this.evaluateContext=!0,this.registerInput("geometry",GE.Geometry),this.registerInput("source",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[1]}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"AggregatorBlock"}get geometry(){return this._inputs[0]}get source(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.source.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);const t=this._vertexData.positions.length/3,i=[];for(this._currentIndex=0;this._currentIndexMath.max(e,t);break;case ZE.Min:s=(e,t)=>Math.min(e,t);break;case ZE.Sum:s=(e,t)=>e+t}if(!s)return e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedFunction=null,void(this.output._storedValue=null);switch(this.source.type){case GE.Int:case GE.Float:r=i.reduce(s);break;case GE.Vector2:{const e=i.map((e=>e.x)).reduce(s),t=i.map((e=>e.y)).reduce(s);r=new W.I9(e,t);break}case GE.Vector3:{const e=i.map((e=>e.x)).reduce(s),t=i.map((e=>e.y)).reduce(s),n=i.map((e=>e.z)).reduce(s);r=new W.Pq(e,t,n);break}case GE.Vector4:{const e=i.map((e=>e.x)).reduce(s),t=i.map((e=>e.y)).reduce(s),n=i.map((e=>e.z)).reduce(s),o=i.map((e=>e.w)).reduce(s);r=new W.IU(e,t,n,o);break}}return e.restoreGeometryContext(),e.restoreExecutionContext(),r};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"};\n`;return e+=`${this._codeVariableName}.aggregation = BABYLON.Aggregations.${ZE[this.aggregation]};\n`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.aggregation=this.aggregation,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext),void 0!==e.aggregation&&(this.aggregation=e.aggregation)}}(0,je.Cg)([t_("Aggregation",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"Max",value:ZE.Max},{label:"Min",value:ZE.Min},{label:"Sum",value:ZE.Sum}]})],PA.prototype,"aggregation",void 0),(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],PA.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.AggregatorBlock",PA);const AA=(e,t)=>{const i=(1<{t.x=AA(e>>>21,11),t.y=AA(e>>>11,10),t.z=AA(e,11)},IA=(e,t)=>{t[0]=255*AA(e>>>24,8),t[1]=255*AA(e>>>16,8),t[2]=255*AA(e>>>8,8),t[3]=255*AA(e,8)},MA=(e,t)=>{const i=1/(.5*Math.sqrt(2)),r=(AA(e>>>20,10)-.5)*i,s=(AA(e>>>10,10)-.5)*i,n=(AA(e,10)-.5)*i,o=Math.sqrt(1-(r*r+s*s+n*n));switch(e>>>30){case 0:t.set(o,r,s,n);break;case 1:t.set(r,o,s,n);break;case 2:t.set(r,s,o,n);break;case 3:t.set(r,s,n,o)}};var OA,DA;!function(e){e[e.FLOAT=0]="FLOAT",e[e.INT=1]="INT",e[e.UINT=2]="UINT",e[e.DOUBLE=3]="DOUBLE",e[e.UCHAR=4]="UCHAR",e[e.UNDEFINED=5]="UNDEFINED"}(OA||(OA={})),function(e){e[e.MIN_X=0]="MIN_X",e[e.MIN_Y=1]="MIN_Y",e[e.MIN_Z=2]="MIN_Z",e[e.MAX_X=3]="MAX_X",e[e.MAX_Y=4]="MAX_Y",e[e.MAX_Z=5]="MAX_Z",e[e.MIN_SCALE_X=6]="MIN_SCALE_X",e[e.MIN_SCALE_Y=7]="MIN_SCALE_Y",e[e.MIN_SCALE_Z=8]="MIN_SCALE_Z",e[e.MAX_SCALE_X=9]="MAX_SCALE_X",e[e.MAX_SCALE_Y=10]="MAX_SCALE_Y",e[e.MAX_SCALE_Z=11]="MAX_SCALE_Z",e[e.PACKED_POSITION=12]="PACKED_POSITION",e[e.PACKED_ROTATION=13]="PACKED_ROTATION",e[e.PACKED_SCALE=14]="PACKED_SCALE",e[e.PACKED_COLOR=15]="PACKED_COLOR",e[e.X=16]="X",e[e.Y=17]="Y",e[e.Z=18]="Z",e[e.SCALE_0=19]="SCALE_0",e[e.SCALE_1=20]="SCALE_1",e[e.SCALE_2=21]="SCALE_2",e[e.DIFFUSE_RED=22]="DIFFUSE_RED",e[e.DIFFUSE_GREEN=23]="DIFFUSE_GREEN",e[e.DIFFUSE_BLUE=24]="DIFFUSE_BLUE",e[e.OPACITY=25]="OPACITY",e[e.F_DC_0=26]="F_DC_0",e[e.F_DC_1=27]="F_DC_1",e[e.F_DC_2=28]="F_DC_2",e[e.F_DC_3=29]="F_DC_3",e[e.ROT_0=30]="ROT_0",e[e.ROT_1=31]="ROT_1",e[e.ROT_2=32]="ROT_2",e[e.ROT_3=33]="ROT_3",e[e.UNDEFINED=34]="UNDEFINED"}(DA||(DA={}));class wA extends Yt{get covariancesATexture(){return this._covariancesATexture}get covariancesBTexture(){return this._covariancesBTexture}get centersTexture(){return this._centersTexture}get colorsTexture(){return this._colorsTexture}set material(e){this._material=e,this._material.backFaceCulling=!0,this._material.cullBackFaces=!1,e.resetDrawCache()}get material(){return this._material}constructor(e,t=null,i=null,r=!1){super(e,i),this._vertexCount=0,this._worker=null,this._frameIdLastUpdate=-1,this._modelViewMatrix=W.uq.Identity(),this._canPostToWorker=!0,this._readyToDisplay=!1,this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,this._splatPositions=null,this._splatIndex=null,this._covariancesA=null,this._covariancesB=null,this._colors=null,this._keepInRam=!1,this._delayedTextureUpdate=null,this._oldDirection=new W.Pq,this._useRGBACovariants=!1,this._material=null,this._tmpCovariances=[0,0,0,0,0,0],this._sortIsDirty=!1;const s=new bt;s.positions=[-3,-2,0,3,-2,0,0,4,0],s.indices=[0,1,2],s.applyToMesh(this),this.subMeshes=[],new vt(0,0,3,0,3,this),this.setEnabled(!1),this._useRGBACovariants=!this.getEngine().isWebGPU&&1===this.getEngine().version,this._keepInRam=r,t&&this.loadFileAsync(t),this._material=new pS(this.name+"_material",this._scene)}getClassName(){return"GaussianSplattingMesh"}getTotalVertices(){return this._vertexCount}isReady(e=!1){return!(!super.isReady(e,!0)||!this._readyToDisplay&&(this._postToWorker(!0),1))}_postToWorker(e=!1){const t=this.getScene().getFrameId();if((e||t!==this._frameIdLastUpdate)&&this._worker&&this._scene.activeCamera&&this._canPostToWorker){const i=this._scene.activeCamera.getViewMatrix();this.getWorldMatrix().multiplyToRef(i,this._modelViewMatrix),i.invertToRef(W.AA.Matrix[0]),this.getWorldMatrix().multiplyToRef(W.AA.Matrix[0],W.AA.Matrix[1]),W.Pq.TransformNormalToRef(W.Pq.Forward(this._scene.useRightHandedSystem),W.AA.Matrix[1],W.AA.Vector3[2]),W.AA.Vector3[2].normalize();const r=W.Pq.Dot(W.AA.Vector3[2],this._oldDirection);(e||Math.abs(r-1)>=.01)&&(this._oldDirection.copyFrom(W.AA.Vector3[2]),this._frameIdLastUpdate=t,this._canPostToWorker=!1,this._worker.postMessage({view:this._modelViewMatrix.m,depthMix:this._depthMix,useRightHandedSystem:this._scene.useRightHandedSystem},[this._depthMix.buffer]))}}render(e,t,i){return this._postToWorker(),super.render(e,t,i)}static _TypeNameToEnum(e){switch(e){case"float":return 0;case"int":return 1;case"uint":return 2;case"double":return 3;case"uchar":return 4}return 5}static _ValueNameToEnum(e){switch(e){case"min_x":return 0;case"min_y":return 1;case"min_z":return 2;case"max_x":return 3;case"max_y":return 4;case"max_z":return 5;case"min_scale_x":return 6;case"min_scale_y":return 7;case"min_scale_z":return 8;case"max_scale_x":return 9;case"max_scale_y":return 10;case"max_scale_z":return 11;case"packed_position":return 12;case"packed_rotation":return 13;case"packed_scale":return 14;case"packed_color":return 15;case"x":return 16;case"y":return 17;case"z":return 18;case"scale_0":return 19;case"scale_1":return 20;case"scale_2":return 21;case"diffuse_red":case"red":return 22;case"diffuse_green":case"green":return 23;case"diffuse_blue":case"blue":return 24;case"f_dc_0":return 26;case"f_dc_1":return 27;case"f_dc_2":return 28;case"f_dc_3":return 29;case"opacity":return 25;case"rot_0":return 30;case"rot_1":return 31;case"rot_2":return 32;case"rot_3":return 33}return 34}static ParseHeader(e){const t=new Uint8Array(e),i=(new TextDecoder).decode(t.slice(0,10240)),r=i.indexOf("end_header\n");if(r<0||!i)return null;const s=parseInt(/element vertex (\d+)\n/.exec(i)[1]),n=/element chunk (\d+)\n/.exec(i);let o=0;n&&(o=parseInt(n[1]));let a=0,l=0;const h={double:8,int:4,uint:4,float:4,short:2,ushort:2,uchar:1,list:0};let c;!function(e){e[e.Vertex=0]="Vertex",e[e.Chunk=1]="Chunk"}(c||(c={}));let u=1;const d=[],f=[],p=i.slice(0,r).split("\n");for(const e of p)if(e.startsWith("property ")){const[,t,i]=e.split(" "),r=wA._ValueNameToEnum(i),s=wA._TypeNameToEnum(t);1==u?(f.push({value:r,type:s,offset:l}),l+=h[t]):0==u&&(d.push({value:r,type:s,offset:a}),a+=h[t]),h[t]||Z.V.Warn(`Unsupported property type: ${t}.`)}else if(e.startsWith("element ")){const[,t]=e.split(" ");"chunk"==t?u=1:"vertex"==t&&(u=0)}return{vertexCount:s,chunkCount:o,rowVertexLength:a,rowChunkLength:l,vertexProperties:d,chunkProperties:f,dataView:new DataView(e,r+11),buffer:new ArrayBuffer(wA._RowOutputLength*s)}}static _GetCompressedChunks(e,t){if(!e.chunkCount)return null;const i=e.dataView,r=new Array(e.chunkCount);for(let s=0;s>8;let p=255,_=0,m=0,g=0;for(let t=0;t{wA.ConvertPLYToSplatAsync(e).then((e=>{this.updateDataAsync(e)}))}))}dispose(e){this._covariancesATexture?.dispose(),this._covariancesBTexture?.dispose(),this._centersTexture?.dispose(),this._colorsTexture?.dispose(),this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,this._worker?.terminate(),this._worker=null,super.dispose(e,!0)}_copyTextures(e){this._covariancesATexture=e.covariancesATexture?.clone(),this._covariancesBTexture=e.covariancesBTexture?.clone(),this._centersTexture=e.centersTexture?.clone(),this._colorsTexture=e.colorsTexture?.clone()}clone(e=""){const t=new wA(e,void 0,this.getScene());t._copySource(this),t.makeGeometryUnique(),t._vertexCount=this._vertexCount,t._copyTextures(this),t._modelViewMatrix=W.uq.Identity(),t._splatPositions=this._splatPositions,t._readyToDisplay=!1,t._instanciateWorker();const i=this.getBoundingInfo();return t.getBoundingInfo().reConstruct(i.minimum,i.maximum,this.getWorldMatrix()),t.forcedInstanceCount=t._vertexCount,t.setEnabled(!0),t}_makeSplat(e,t,i,r,s,n,o,a,l){const h=W.AA.Matrix[0],c=W.AA.Matrix[1],u=W.AA.Quaternion[0],d=this._useRGBACovariants?4:2,f=i[8*e+0],p=-i[8*e+1],_=i[8*e+2];this._splatPositions[4*e+0]=f,this._splatPositions[4*e+1]=p,this._splatPositions[4*e+2]=_,a.minimizeInPlaceFromFloats(f,p,_),l.maximizeInPlaceFromFloats(f,p,_),u.set((r[32*e+28+1]-128)/128,(r[32*e+28+2]-128)/128,(r[32*e+28+3]-128)/128,-(r[32*e+28+0]-128)/128),u.toRotationMatrix(h),W.uq.ScalingToRef(2*i[8*e+3+0],2*i[8*e+3+1],2*i[8*e+3+2],c);const m=h.multiplyToRef(c,W.AA.Matrix[0]).m,g=this._tmpCovariances;g[0]=m[0]*m[0]+m[1]*m[1]+m[2]*m[2],g[1]=m[0]*m[4]+m[1]*m[5]+m[2]*m[6],g[2]=m[0]*m[8]+m[1]*m[9]+m[2]*m[10],g[3]=m[4]*m[4]+m[5]*m[5]+m[6]*m[6],g[4]=m[4]*m[8]+m[5]*m[9]+m[6]*m[10],g[5]=m[8]*m[8]+m[9]*m[9]+m[10]*m[10];let v=-1e4;for(let e=0;e<6;e++)v=Math.max(v,Math.abs(g[e]));this._splatPositions[4*e+3]=v;const x=v;s[4*t+0]=(0,Ac.LZ)(g[0]/x),s[4*t+1]=(0,Ac.LZ)(g[1]/x),s[4*t+2]=(0,Ac.LZ)(g[2]/x),s[4*t+3]=(0,Ac.LZ)(g[3]/x),n[t*d+0]=(0,Ac.LZ)(g[4]/x),n[t*d+1]=(0,Ac.LZ)(g[5]/x),o[4*t+0]=r[32*e+24+0],o[4*t+1]=r[32*e+24+1],o[4*t+2]=r[32*e+24+2],o[4*t+3]=r[32*e+24+3]}_updateTextures(e,t,i){const r=this._getTextureSize(this._vertexCount),s=(e,t,i,r)=>new xi(e,t,i,r,this._scene,!1,!1,2,2);if(this._keepInRam&&(this._covariancesA=e,this._covariancesB=t,this._colors=i),this._covariancesATexture){this._delayedTextureUpdate={covA:e,covB:t,colors:i,centers:this._splatPositions};const r=Float32Array.from(this._splatPositions),s=this._vertexCount;this._worker.postMessage({positions:r,vertexCount:s},[r.buffer]),this._postToWorker(!0)}else this._covariancesATexture=s(e,r.x,r.y,5),this._covariancesBTexture=s(t,r.x,r.y,this._useRGBACovariants?5:7),this._centersTexture=((e,t,i,r)=>new xi(e,t,i,r,this._scene,!1,!1,2,1))(this._splatPositions,r.x,r.y,5),this._colorsTexture=((e,t,i,r)=>new xi(e,t,i,r,this._scene,!1,!1,2,0))(i,r.x,r.y,5),this._instanciateWorker()}*_updateData(e,t){this._covariancesATexture||(this._readyToDisplay=!1);const i=new Uint8Array(e),r=new Float32Array(i.buffer),s=i.length/wA._RowOutputLength;s!=this._vertexCount&&this._updateSplatIndexBuffer(s),this._vertexCount=s;const n=this._getTextureSize(s),o=n.x*n.y,a=wA.ProgressiveUpdateAmount??n.y,l=n.x*a;this._splatPositions=new Float32Array(4*o);const h=new Uint16Array(4*o),c=new Uint16Array((this._useRGBACovariants?4:2)*o),u=new Uint8Array(4*o),d=new W.Pq(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),f=new W.Pq(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);if(wA.ProgressiveUpdateAmount){this._updateTextures(h,c,u),this.setEnabled(!0);const e=Math.ceil(n.y/a);for(let s=0;sthis._splatIndex.length)&&(this._splatIndex=new Float32Array(e),this.thinInstanceSetBuffer("splatIndex",this._splatIndex,1,!1)),this.forcedInstanceCount=e}_updateSubTextures(e,t,i,r,s,n){const o=(e,t,i,r,s)=>{this.getEngine().updateTextureData(e.getInternalTexture(),t,0,r,i,s,0,0,!1)},a=this._getTextureSize(this._vertexCount),l=this._useRGBACovariants?4:2,h=s*a.x,c=n*a.x,u=new Uint16Array(t.buffer,4*h*Uint16Array.BYTES_PER_ELEMENT,4*c),d=new Uint16Array(i.buffer,h*l*Uint16Array.BYTES_PER_ELEMENT,c*l),f=new Uint8Array(r.buffer,4*h,4*c),p=new Float32Array(e.buffer,4*h*Float32Array.BYTES_PER_ELEMENT,4*c);o(this._covariancesATexture,u,a.x,s,n),o(this._covariancesBTexture,d,a.x,s,n),((e,t,i,r,s)=>{this.getEngine().updateTextureData(e.getInternalTexture(),t,0,r,i,s,0,0,!1)})(this._centersTexture,p,a.x,s,n),((e,t,i,r,s)=>{this.getEngine().updateTextureData(e.getInternalTexture(),t,0,r,i,s,0,0,!1)})(this._colorsTexture,f,a.x,s,n)}_instanciateWorker(){if(!this._vertexCount)return;this._updateSplatIndexBuffer(this._vertexCount),this._worker?.terminate(),this._worker=new Worker(URL.createObjectURL(new Blob(["(",wA._CreateWorker.toString(),")(self)"],{type:"application/javascript"}))),this._depthMix=new BigInt64Array(this._vertexCount);const e=Float32Array.from(this._splatPositions),t=this._vertexCount;this._worker.postMessage({positions:e,vertexCount:t},[e.buffer]),this._worker.onmessage=e=>{this._depthMix=e.data.depthMix;const i=new Uint32Array(e.data.depthMix.buffer);if(this._splatIndex)for(let e=0;ei&&(Z.V.Error("GaussianSplatting texture size: ("+i+", "+r+"), maxTextureSize: "+i),r=i),new W.I9(i,r)}}wA._RowOutputLength=32,wA._SH_C0=.28209479177387814,wA._SplatBatchSize=327680,wA._PlyConversionBatchSize=32768,wA.ProgressiveUpdateAmount=0,wA._CreateWorker=function(e){let t,i,r,s,n=0;e.onmessage=o=>{if(o.data.positions)t=o.data.positions,n=o.data.vertexCount;else{const a=o.data.view;if(!t||!a)throw new Error("positions or view is not defined!");i=o.data.depthMix,r=new Uint32Array(i.buffer),s=new Float32Array(i.buffer);for(let e=0;e{this._onDoneCallback(t,i)}),((e,t)=>{this._onErrorCallback(i,e,t)}))}runTask(e,t,i){throw new Error("runTask is not implemented")}reset(){this._taskState=0}_onErrorCallback(e,t,i){this._taskState=3,this._errorObject={message:t,exception:i},this.onError&&this.onError(this,t,i),e()}_onDoneCallback(e,t){try{this._taskState=2,this._isCompleted=!0,this.onSuccess&&this.onSuccess(this),e()}catch(e){this._onErrorCallback(t,"Task is done, error executing success callback(s)",e)}}}class QA{constructor(e,t,i){this.remainingCount=e,this.totalCount=t,this.task=i}}class ZA extends $A{constructor(e,t,i,r,s){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=r,this.extension=s}runTask(e,t,i){xg.LoadAssetContainer(this.rootUrl,this.sceneFilename,e,(e=>{this.loadedContainer=e,this.loadedMeshes=e.meshes,this.loadedTransformNodes=e.transformNodes,this.loadedParticleSystems=e.particleSystems,this.loadedSkeletons=e.skeletons,this.loadedAnimationGroups=e.animationGroups,t()}),null,((e,t,r)=>{i(t,r)}),this.extension)}}class JA extends $A{constructor(e,t,i,r,s){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=r,this.extension=s}runTask(e,t,i){xg.ImportMesh(this.meshesNames,this.rootUrl,this.sceneFilename,e,((e,i,r,s,n)=>{this.loadedMeshes=e,this.loadedTransformNodes=n,this.loadedParticleSystems=i,this.loadedSkeletons=r,this.loadedAnimationGroups=s,t()}),null,((e,t,r)=>{i(t,r)}),this.extension)}}class eR extends $A{constructor(e,t,i,r,s){super(e),this.name=e,this.rootUrl=t,this.filename=i,this.targetConverter=r,this.extension=s}runTask(e,t,i){const r=e.animatables.length,s=e.animationGroups.length;this.loadedAnimatables=[],this.loadedAnimationGroups=[],xg.ImportAnimations(this.rootUrl,this.filename,e,!1,3,this.targetConverter,(()=>{this.loadedAnimatables=e.animatables.slice(r),this.loadedAnimationGroups=e.animationGroups.slice(s),t()}),null,((e,t,r)=>{i(t,r)}),this.extension)}}class tR extends $A{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,(e=>{this.text=e,t()}),void 0,!1,!1,((e,t)=>{e&&i(e.status+" "+e.statusText,t)}))}}class iR extends $A{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,(e=>{this.data=e,t()}),void 0,!0,!0,((e,t)=>{e&&i(e.status+" "+e.statusText,t)}))}}class rR extends $A{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){const r=new Image;Ue.S0.SetCorsBehavior(this.url,r),r.onload=()=>{this.image=r,t()},r.onerror=e=>{i("Error loading image",e)},r.src=this.url}}class sR extends $A{constructor(e,t,i,r=!0,s=vi.g.TRILINEAR_SAMPLINGMODE){super(e),this.name=e,this.url=t,this.noMipmap=i,this.invertY=r,this.samplingMode=s}runTask(e,t,i){this.texture=new vi.g(this.url,e,this.noMipmap,this.invertY,this.samplingMode,(()=>{t()}),((e,t)=>{i(e,t)}))}}class nR extends $A{constructor(e,t,i,r,s,n){super(e),this.name=e,this.url=t,this.extensions=i,this.noMipmap=r,this.files=s,this.prefiltered=n}runTask(e,t,i){this.texture=new gm(this.url,e,this.extensions,this.noMipmap,this.files,(()=>{t()}),((e,t)=>{i(e,t)}),void 0,this.prefiltered)}}class oR extends $A{constructor(e,t,i,r=!1,s=!0,n=!1,o=!1){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=r,this.generateHarmonics=s,this.gammaSpace=n,this.reserved=o}runTask(e,t,i){this.texture=new Vx(this.url,e,this.size,this.noMipmap,this.generateHarmonics,this.gammaSpace,this.reserved,(()=>{t()}),((e,t)=>{i(e,t)}))}}class aR extends $A{constructor(e,t,i,r=!1,s=!0){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=r,this.gammaSpace=s}runTask(e,t,i){this.texture=new Db(this.url,e,this.size,this.noMipmap,this.gammaSpace,(()=>{t()}),((e,t)=>{i(e,t)}))}}class lR{constructor(e){this._isLoading=!1,this._tasks=new Array,this._waitingTasksCount=0,this._totalTasksCount=0,this.onTaskSuccessObservable=new z.cP,this.onTaskErrorObservable=new z.cP,this.onTasksDoneObservable=new z.cP,this.onProgressObservable=new z.cP,this.useDefaultLoadingScreen=!0,this.autoHideLoadingUI=!0,this._scene=e||he.q.LastCreatedScene}addContainerTask(e,t,i,r,s){const n=new ZA(e,t,i,r,s);return this._tasks.push(n),n}addMeshTask(e,t,i,r,s){const n=new JA(e,t,i,r,s);return this._tasks.push(n),n}addTextFileTask(e,t){const i=new tR(e,t);return this._tasks.push(i),i}addBinaryFileTask(e,t){const i=new iR(e,t);return this._tasks.push(i),i}addImageTask(e,t){const i=new rR(e,t);return this._tasks.push(i),i}addTextureTask(e,t,i,r,s=vi.g.TRILINEAR_SAMPLINGMODE){const n=new sR(e,t,i,r,s);return this._tasks.push(n),n}addCubeTextureTask(e,t,i,r,s,n){const o=new nR(e,t,i,r,s,n);return this._tasks.push(o),o}addHDRCubeTextureTask(e,t,i,r=!1,s=!0,n=!1,o=!1){const a=new oR(e,t,i,r,s,n,o);return this._tasks.push(a),a}addEquiRectangularCubeTextureAssetTask(e,t,i,r=!1,s=!0){const n=new aR(e,t,i,r,s);return this._tasks.push(n),n}removeTask(e){const t=this._tasks.indexOf(e);t>-1&&this._tasks.splice(t,1)}_decreaseWaitingTasksCount(e){this._waitingTasksCount--;try{this.onProgress&&this.onProgress(this._waitingTasksCount,this._totalTasksCount,e),this.onProgressObservable.notifyObservers(new QA(this._waitingTasksCount,this._totalTasksCount,e))}catch(e){Z.V.Error("Error running progress callbacks."),Z.V.Log(e)}if(0===this._waitingTasksCount){try{const e=this._tasks.slice();this.onFinish&&this.onFinish(e);for(const t of e)if(2===t.taskState){const e=this._tasks.indexOf(t);e>-1&&this._tasks.splice(e,1)}this.onTasksDoneObservable.notifyObservers(this._tasks)}catch(e){Z.V.Error("Error running tasks-done callbacks."),Z.V.Log(e)}this._isLoading=!1,this.autoHideLoadingUI&&this._scene.getEngine().hideLoadingUI()}}_runTask(e){const t=(t,i)=>{e._setErrorObject(t,i),this.onTaskError?this.onTaskError(e):e.onError||Z.V.Error(this._formatTaskErrorMessage(e)),this.onTaskErrorObservable.notifyObservers(e),this._decreaseWaitingTasksCount(e)};e.run(this._scene,(()=>{try{this.onTaskSuccess&&this.onTaskSuccess(e),this.onTaskSuccessObservable.notifyObservers(e),this._decreaseWaitingTasksCount(e)}catch(e){t("Error executing task success callbacks",e)}}),t)}_formatTaskErrorMessage(e){let t="Unable to complete task "+e.name;return e.errorObject.message&&(t+=`: ${e.errorObject.message}`),e.errorObject.exception&&(t+=`: ${e.errorObject.exception}`),t}reset(){return this._isLoading=!1,this._tasks=new Array,this}load(){if(this._isLoading)return this;if(this._isLoading=!0,this._waitingTasksCount=this._tasks.length,this._totalTasksCount=this._tasks.length,0===this._waitingTasksCount)return this._isLoading=!1,this.onFinish&&this.onFinish(this._tasks),this.onTasksDoneObservable.notifyObservers(this._tasks),this;this.useDefaultLoadingScreen&&this._scene.getEngine().displayLoadingUI();for(let e=0;e{this._isLoading?e():(this.onTasksDoneObservable.addOnce((i=>{i&&i.length?t(i):e()})),this.load())}))}}var hR=i(68622),cR=i(26589);class uR{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}}class dR{constructor(e,t){this._meshesOrigins=[],this._toCenterVectors=[],this._scaledDirection=new W.Pq(1,1,1),this._newPosition=W.Pq.Zero(),this._centerPosition=W.Pq.Zero(),this._meshes=e.slice(),t?this._centerMesh=t:this._setCenterMesh(),this._centerMesh.computeWorldMatrix(!0);const i=this._meshes.indexOf(this._centerMesh);i>=0&&this._meshes.splice(i,1),this._centerPosition=this._centerMesh.getAbsolutePosition().clone();for(let e=0;e!0,this.displayLoadingUI=!0,this.loadAsync=(e,t)=>this.useAppend?xg.AppendAsync("file:",e,this._currentScene,t):xg.LoadAsync("file:",e,this._engine,t),this._engine=e,this._currentScene=t,this._sceneLoadedCallback=i,this._progressCallback=r,this._additionalRenderLoopLogicCallback=s,this._textureLoadingCallback=n,this._startingProcessingFilesCallback=o,this._onReloadCallback=a,this._errorCallback=l}monitorElementForDragNDrop(e){e&&(this._elementToMonitor=e,this._dragEnterHandler=e=>{this._drag(e)},this._dragOverHandler=e=>{this._drag(e)},this._dropHandler=e=>{this._drop(e)},this._elementToMonitor.addEventListener("dragenter",this._dragEnterHandler,!1),this._elementToMonitor.addEventListener("dragover",this._dragOverHandler,!1),this._elementToMonitor.addEventListener("drop",this._dropHandler,!1))}get filesToLoad(){return this._filesToLoad}dispose(){this._elementToMonitor&&(this._elementToMonitor.removeEventListener("dragenter",this._dragEnterHandler),this._elementToMonitor.removeEventListener("dragover",this._dragOverHandler),this._elementToMonitor.removeEventListener("drop",this._dropHandler))}_renderFunction(){if(this._additionalRenderLoopLogicCallback&&this._additionalRenderLoopLogicCallback(),this._currentScene){if(this._textureLoadingCallback){const e=this._currentScene.getWaitingItemsCount();e>0&&this._textureLoadingCallback(e)}this._currentScene.render()}}_drag(e){e.stopPropagation(),e.preventDefault()}_drop(e){e.stopPropagation(),e.preventDefault(),this.loadFiles(e)}_traverseFolder(e,t,i,r){const s=e.createReader(),n=e.fullPath.replace(/^\//,"").replace(/(.+?)\/?$/,"$1/");s.readEntries((e=>{i.count+=e.length;for(const s of e)s.isFile?s.file((e=>{e.correctName=n+e.name,t.push(e),0==--i.count&&r()})):s.isDirectory&&this._traverseFolder(s,t,i,r);0==--i.count&&r()}))}_processFiles(e){for(let t=0;tthis._sceneFileToLoad=e))&&(xg.IsPluginForExtensionAvailable("."+r)&&(this._sceneFileToLoad=e[t]),pR.FilesToLoad[i]=e[t])}}loadFiles(e){if(e&&e.dataTransfer&&e.dataTransfer.files&&(this._filesToLoad=e.dataTransfer.files),e&&e.target&&e.target.files&&(this._filesToLoad=e.target.files),this._filesToLoad&&0!==this._filesToLoad.length&&(this._startingProcessingFilesCallback&&this._startingProcessingFilesCallback(this._filesToLoad),this._filesToLoad&&this._filesToLoad.length>0)){const t=[],i=[],r=e.dataTransfer?e.dataTransfer.items:null;for(let e=0;e{this._processFiles(t),0===e.count&&this._processReload()}))}}}_processReload(){this._onReloadCallback?this._onReloadCallback(this._sceneFileToLoad):this.reload()}reload(){if(this._sceneFileToLoad)this.useAppend||this._currentScene&&(Z.V.errorsCount>0&&Z.V.ClearLogCache(),this._engine.stopRenderLoop()),xg.ShowLoadingScreen=!1,this.displayLoadingUI&&this._engine.displayLoadingUI(),this.loadAsync(this._sceneFileToLoad,this._progressCallback).then((e=>{this.useAppend?this.displayLoadingUI&&this._engine.hideLoadingUI():(this._currentScene&&this._currentScene.dispose(),this._currentScene=e,this._currentScene.executeWhenReady((()=>{this.displayLoadingUI&&this._engine.hideLoadingUI(),this._engine.runRenderLoop((()=>{this._renderFunction()}))}))),this._sceneLoadedCallback&&this._currentScene&&this._sceneLoadedCallback(this._sceneFileToLoad,this._currentScene)})).catch((e=>{this.displayLoadingUI&&this._engine.hideLoadingUI(),this._errorCallback&&this._errorCallback(this._sceneFileToLoad,this._currentScene,e.message)}));else{if(1===this._filesToLoad.length){const e=this._filesToLoad[0].name.toLowerCase().split(".").pop();if(e)switch(e.toLowerCase()){case"dds":case"env":case"hdr":return}}Z.V.Error("Please provide a valid .babylon file.")}}}var _R=i(52710);class mR{dispose(){if(this._observers&&this._observables)for(let e=0;e{o.skipNextObservers||i._willBeUnregistered||i.mask&t&&(n=i.scope?n.then((t=>(o.lastReturnValue=t,i.callback.apply(i.scope,[e,o])))):n.then((t=>(o.lastReturnValue=t,i.callback(e,o)))),i.unregisterOnNextCall&&this._deferUnregister(i))})),await n,e};class gR{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}}class vR extends gR{getDescription(){return"Reducing render target texture size to "+this.maximumSize}constructor(e=0,t=1024,i=.5){super(e),this.priority=e,this.maximumSize=t,this.step=i}apply(e,t){let i=!0;for(let t=0;tthis.maximumSize&&(r.scale(this.step),i=!1)}return i}}class xR extends gR{getDescription(){return"Setting hardware scaling level to "+this._currentScale}constructor(e=0,t=2,i=.25){super(e),this.priority=e,this.maximumScale=t,this.step=i,this._currentScale=-1,this._directionOffset=1}apply(e,t){return-1===this._currentScale&&(this._currentScale=e.getEngine().getHardwareScalingLevel(),this._currentScale>this.maximumScale&&(this._directionOffset=-1)),this._currentScale+=this._directionOffset*this.step,e.getEngine().setHardwareScalingLevel(this._currentScale),1===this._directionOffset?this._currentScale>=this.maximumScale:this._currentScale<=this.maximumScale}}class bR extends gR{getDescription(){return"Turning shadows on/off"}apply(e,t){return e.shadowsEnabled=t.isInImprovementMode,!0}}class SR extends gR{getDescription(){return"Turning post-processes on/off"}apply(e,t){return e.postProcessesEnabled=t.isInImprovementMode,!0}}class TR extends gR{getDescription(){return"Turning lens flares on/off"}apply(e,t){return e.lensFlaresEnabled=t.isInImprovementMode,!0}}class CR extends gR{getDescription(){return this.onGetDescription?this.onGetDescription():"Running user defined callback"}apply(e,t){return!this.onApply||this.onApply(e,t)}}class yR extends gR{getDescription(){return"Turning particles on/off"}apply(e,t){return e.particlesEnabled=t.isInImprovementMode,!0}}class ER extends gR{getDescription(){return"Turning render targets off"}apply(e,t){return e.renderTargetsEnabled=t.isInImprovementMode,!0}}class PR extends gR{constructor(){super(...arguments),this._canBeMerged=e=>{if(!(e instanceof Yt))return!1;const t=e;return!(t.isDisposed()||!t.isVisible||!t.isEnabled()||t.instances.length>0||t.skeleton||t.hasLODLevels||0===t.getTotalVertices())}}static get UpdateSelectionTree(){return PR._UpdateSelectionTree}static set UpdateSelectionTree(e){PR._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){const r=e.meshes.slice(0);let s=r.length;for(let e=0;e{this._sceneDisposeObserver=null,this.dispose()}))}stop(){this._isRunning=!1}reset(){this._currentPriorityLevel=0}start(){this._isRunning||(this._isRunning=!0,this._scene.executeWhenReady((()=>{setTimeout((()=>{this._checkCurrentState()}),this._trackerDuration)})))}_checkCurrentState(){if(!this._isRunning)return;const e=this._scene,t=this._options;if(this._currentFrameRate=Math.round(e.getEngine().getFps()),this._improvementMode&&this._currentFrameRate<=this._targetFrameRate||!this._improvementMode&&this._currentFrameRate>=this._targetFrameRate)return this._isRunning=!1,void this.onSuccessObservable.notifyObservers(this);let i=!0,r=!0;for(let s=0;s{setTimeout((()=>{this._checkCurrentState()}),this._trackerDuration)}))}dispose(){this.stop(),this.onSuccessObservable.clear(),this.onFailureObservable.clear(),this.onNewOptimizationAppliedObservable.clear(),this._sceneDisposeObserver&&this._scene.onDisposeObservable.remove(this._sceneDisposeObserver)}static OptimizeAsync(e,t,i,r){const s=new RR(e,t||AR.ModerateDegradationAllowed(),!1);return i&&s.onSuccessObservable.add((()=>{i()})),r&&s.onFailureObservable.add((()=>{r()})),s.start(),s}}let IR=[];const MR=(e,t)=>{e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),IR[e.id]=!0)},OR=(e,t)=>{const i={},r=e._geometry;return r&&(e.getScene().getGeometryById(r.id)||MR(r,t.geometries)),e.serialize&&e.serialize(i),i};class DR{static ClearCache(){IR=[]}static Serialize(e){return DR._Serialize(e)}static _Serialize(e,t=!0){const i={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&vi.g.ForceSerializeBuffers&&Z.V.Warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),DR.ClearCache(),i.useDelayedTextureLoading=e.useDelayedTextureLoading,i.autoClear=e.autoClear,i.clearColor=e.clearColor.asArray(),i.ambientColor=e.ambientColor.asArray(),i.gravity=e.gravity.asArray(),i.collisionsEnabled=e.collisionsEnabled,i.useRightHandedSystem=e.useRightHandedSystem,void 0!==e.fogMode&&null!==e.fogMode&&(i.fogMode=e.fogMode),void 0!==e.fogColor&&null!==e.fogColor&&(i.fogColor=e.fogColor.asArray()),void 0!==e.fogStart&&null!==e.fogStart&&(i.fogStart=e.fogStart),void 0!==e.fogEnd&&null!==e.fogEnd&&(i.fogEnd=e.fogEnd),void 0!==e.fogDensity&&null!==e.fogDensity&&(i.fogDensity=e.fogDensity),e.isPhysicsEnabled&&e.isPhysicsEnabled()){const t=e.getPhysicsEngine();t&&(i.physicsEnabled=!0,i.physicsGravity=t.gravity.asArray(),i.physicsEngine=t.getPhysicsPluginName())}e.metadata&&(i.metadata=e.metadata),i.morphTargetManagers=[];for(const t of e.meshes){const e=t.morphTargetManager;e&&i.morphTargetManagers.push(e.serialize())}let r,s,n;for(i.lights=[],r=0;r0){i.animationGroups=[];for(let t=0;t0)for(i.reflectionProbes=[],r=0;rt))}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;ie[i]=t))):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}else if(e instanceof Object)for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const r=e[i];r instanceof Promise?t.push(r.then((t=>e[i]=t))):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}}static SerializeMesh(e,t=!1,i=!1){const r={meshes:[],transformNodes:[],cameras:[],lights:[]};if(DR.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let r=0;r{e.indexOf(t)<0&&!t.doNotSerialize&&e.push(t)})),t&&e[r].parent&&e.indexOf(e[r].parent)<0&&!e[r].parent.doNotSerialize&&e.push(e[r].parent);return e.forEach((e=>{((e,t)=>{if(e._isMesh){const i=e;if(1===i.delayLoadState||0===i.delayLoadState){const e=e=>{t.materials=t.materials||[],i.material&&!t.materials.some((e=>e.id===i.material.id))&&t.materials.push(e.serialize())};if(i.material&&!i.material.doNotSerialize)if(i.material instanceof kt){if(t.multiMaterials=t.multiMaterials||[],!t.multiMaterials.some((e=>e.id===i.material.id))){t.multiMaterials.push(i.material.serialize());for(const t of i.material.subMaterials)t&&e(t)}}else e(i.material);else i.material||e(i.getScene().defaultMaterial);const r=i._geometry;r&&(t.geometries||(t.geometries={},t.geometries.boxes=[],t.geometries.spheres=[],t.geometries.cylinders=[],t.geometries.toruses=[],t.geometries.grounds=[],t.geometries.planes=[],t.geometries.torusKnots=[],t.geometries.vertexData=[]),MR(r,t.geometries)),i.skeleton&&!i.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(i.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(OR(i,t))}}else if("TransformNode"===e.getClassName()){const i=e;t.transformNodes.push(i.serialize())}else if(-1!==e.getClassName().indexOf("Camera")){const i=e;t.cameras.push(i.serialize())}else if(-1!==e.getClassName().indexOf("Light")){const i=e;t.lights.push(i.serialize())}})(e,r)})),r}}var wR=i(47084),NR=i(46143),FR=i(61951),LR=i(58316),BR=i(96172);class VR{static IsSupported(e,t){const i=t??e.getRenderingCanvas();return!!i&&"function"==typeof i.captureStream}get isRecording(){return!!this._canvas&&this._isRecording}constructor(e,t={}){if(!VR.IsSupported(e,t.canvas))throw"Your browser does not support recording so far.";const i=t.canvas??e.getRenderingCanvas();if(!i)throw"The babylon engine must have a canvas to be recorded";this._canvas=i,this._isRecording=!1,this._options={...VR._DefaultOptions,...t};const r=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(const e of this._options.audioTracks)r.addTrack(e);this._mediaRecorder=new MediaRecorder(r,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=e=>this._handleDataAvailable(e),this._mediaRecorder.onerror=e=>this._handleError(e),this._mediaRecorder.onstop=()=>this._handleStop()}stopRecording(){this._canvas&&this._mediaRecorder&&this.isRecording&&(this._isRecording=!1,this._mediaRecorder.stop())}startRecording(e="babylonjs.webm",t=7){if(!this._canvas||!this._mediaRecorder)throw"Recorder has already been disposed";if(this.isRecording)throw"Recording already in progress";return t>0&&setTimeout((()=>{this.stopRecording()}),1e3*t),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}dispose(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null}_handleDataAvailable(e){e.data.size>0&&this._recordedChunks.push(e.data)}_handleError(e){if(this.stopRecording(),!this._reject)throw new e.error;this._reject(e.error)}_handleStop(){this.stopRecording();const e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&Ue.S0.Download(e,this._fileName)}}VR._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};class kR extends ms.w{getClassName(){return"FxaaPostProcess"}constructor(e,t,i=null,r,s,n,o=0){super(e,"fxaa",["texelSize"],null,t,i,r||vi.g.BILINEAR_SAMPLINGMODE,s,n,null,o,"fxaa",void 0,!0);const a=this._getDefines();this.updateEffect(a),this.onApplyObservable.add((e=>{const t=this.texelSize;e.setFloat2("texelSize",t.x,t.y)}))}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,54525)),Promise.resolve().then(i.bind(i,32439))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,75424)),Promise.resolve().then(i.bind(i,84014))])),super._gatherImports(e,t)}_getDefines(){const e=this.getEngine();return e&&e.extractDriverInfo().toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null}static _Parse(e,t,i,r){return it.p.Parse((()=>new kR(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,r)}}(0,X.Y5)("BABYLON.FxaaPostProcess",kR);var UR=i(465);let GR=null;function zR(e,t,i,r,s="image/png",n=!1,o){const{height:a,width:l}=YR(e,t,i);if(!a||!l)return void Z.V.Error("Invalid 'size' parameter !");GR||(GR=document.createElement("canvas")),GR.width=l,GR.height=a;const h=GR.getContext("2d"),c=e.getRenderWidth()/e.getRenderHeight();let u=l,d=u/c;d>a&&(d=a,u=d*c);const f=Math.max(0,l-u)/2,p=Math.max(0,a-d)/2;t.getScene().activeCamera!==t?XR(e,t,i,(e=>{if(n){const t=new Blob([e]);Ue.S0.DownloadBlob(t),r&&r("")}else r&&r(e)}),s,1,e.getCreationOptions().antialias,void 0,void 0,void 0,void 0,o):e.onEndFrameObservable.addOnce((()=>{const t=e.getRenderingCanvas();h&&t&&h.drawImage(t,f,p,u,d),GR&&(n?(Ue.S0.EncodeScreenshotCanvasData(GR,void 0,s,void 0,o),r&&r("")):Ue.S0.EncodeScreenshotCanvasData(GR,r,s,void 0,o))}))}function WR(e,t,i,r="image/png",s){return new Promise(((n,o)=>{zR(e,t,i,(e=>{void 0!==e?n(e):o(new Error("Data is undefined"))}),r,void 0,s)}))}function HR(e,t,i,r,s="image/png",n){return new Promise((o=>{zR(e,t,{width:i,height:r},(()=>{o()}),s,!0,n)}))}function XR(e,t,r,s,n="image/png",o=1,a=!1,l,h=!1,c=!1,u=!0,d,f){const{height:p,width:_,finalWidth:m,finalHeight:g}=YR(e,t,r),v={width:_,height:p};if(!p||!_)return void Z.V.Error("Invalid 'size' parameter !");const x={width:e.getRenderWidth(),height:e.getRenderHeight()};e.setSize(_,p);const b=t.getScene(),S=new ln.$("screenShot",v,b,!1,!1,0,!1,vi.g.BILINEAR_SAMPLINGMODE,void 0,c,void 0,void 0,void 0,o);S.renderList=b.meshes.slice(),S.samples=o,S.renderSprites=h,S.activeCamera=t,S.forceLayerMaskCheck=u,f?.(S);const T=()=>{S.isReadyForRendering()&&t.isReady(!0)?(e.onEndFrameObservable.addOnce((()=>{m===_&&g===p?S.readPixels(void 0,void 0,void 0,!1).then((e=>{(0,UR.DumpData)(_,p,e,s,n,l,!0,void 0,d),S.dispose()})):(e.isWebGPU?Promise.resolve().then(i.bind(i,418)):Promise.resolve().then(i.bind(i,30927))).then((()=>(0,Ac.Qs)("pass",S.getInternalTexture(),b,void 0,void 0,void 0,m,g).then((t=>{e._readTexturePixels(t,m,g,-1,0,null,!0,!1,0,0).then((e=>{(0,UR.DumpData)(m,g,e,s,n,l,!0,void 0,d),t.dispose()}))}))))})),b.incrementRenderId(),b.resetCachedMaterial(),S.render(!0),e.setSize(x.width,x.height),t.getProjectionMatrix(!0)):setTimeout(T,16)},C=()=>{b.incrementRenderId(),b.resetCachedMaterial(),T()};if(a){const e=new kR("antialiasing",1,b.activeCamera);S.addPostProcess(e),e.onEffectCreatedObservable.addOnce((e=>{e.isReady()?C():e.onCompiled=()=>{C()}}))}else C()}function qR(e,t,i,r="image/png",s=1,n=!1,o,a=!1,l=!1,h=!0,c,u){return new Promise(((d,f)=>{XR(e,t,i,(e=>{void 0!==e?d(e):f(new Error("Data is undefined"))}),r,s,n,o,a,l,h,c,u)}))}function YR(e,t,i){let r=0,s=0,n=0,o=0;if("object"==typeof i){const a=i.precision?Math.abs(i.precision):1;i.width&&i.height?(r=i.height*a,s=i.width*a):i.width&&!i.height?(s=i.width*a,r=Math.round(s/e.getAspectRatio(t))):i.height&&!i.width?(r=i.height*a,s=Math.round(r*e.getAspectRatio(t))):(s=Math.round(e.getRenderWidth()*a),r=Math.round(s/e.getAspectRatio(t))),i.finalWidth&&i.finalHeight?(o=i.finalHeight,n=i.finalWidth):i.finalWidth&&!i.finalHeight?(n=i.finalWidth,o=Math.round(n/e.getAspectRatio(t))):i.finalHeight&&!i.finalWidth?(o=i.finalHeight,n=Math.round(o*e.getAspectRatio(t))):(n=s,o=r)}else isNaN(i)||(r=i,s=i,n=i,o=i);return s&&(s=Math.floor(s)),r&&(r=Math.floor(r)),n&&(n=Math.floor(n)),o&&(o=Math.floor(o)),{height:0|r,width:0|s,finalWidth:0|n,finalHeight:0|o}}const KR={CreateScreenshot:zR,CreateScreenshotAsync:WR,CreateScreenshotWithResizeAsync:HR,CreateScreenshotUsingRenderTarget:XR,CreateScreenshotUsingRenderTargetAsync:qR};var jR;Ue.S0.CreateScreenshot=zR,Ue.S0.CreateScreenshotAsync=WR,Ue.S0.CreateScreenshotUsingRenderTarget=XR,Ue.S0.CreateScreenshotUsingRenderTargetAsync=qR,function(e){e[e.Checkbox=0]="Checkbox",e[e.Slider=1]="Slider",e[e.Vector3=2]="Vector3",e[e.Quaternion=3]="Quaternion",e[e.Color3=4]="Color3",e[e.String=5]="String",e[e.Button=6]="Button",e[e.Options=7]="Options",e[e.Tab=8]="Tab",e[e.FileButton=9]="FileButton",e[e.Vector2=10]="Vector2"}(jR||(jR={}));class $R{constructor(e,t,i){this.gradient=e,this.color1=t,this.color2=i}getColorToRef(e){this.color2?H.ov.LerpToRef(this.color1,this.color2,Math.random(),e):e.copyFrom(this.color1)}}class QR{constructor(e,t){this.gradient=e,this.color=t}}class ZR{constructor(e,t,i){this.gradient=e,this.factor1=t,this.factor2=i}getFactor(){return void 0===this.factor2||this.factor2===this.factor1?this.factor1:this.factor1+(this.factor2-this.factor1)*Math.random()}}class JR{static GetCurrentGradient(e,t,i){if(t[0].gradient>e)return void i(t[0],t[0],1);for(let r=0;r=s.gradient&&e<=n.gradient)return void i(s,n,(e-s.gradient)/(n.gradient-s.gradient))}const r=t.length-1;i(t[r],t[r],1)}}var eI=i(56703);class tI{constructor(e){this.byteOffset=0,this.buffer=e}loadAsync(e){return this.buffer.readAsync(this.byteOffset,e).then((e=>{this._dataView=new DataView(e.buffer,e.byteOffset,e.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(0,bi.Tq)(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}class iI{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch{const e={};return{getItem:t=>{const i=e[t];return void 0===i?null:i},setItem:(t,i)=>{e[t]=i}}}}static ReadString(e,t){const i=this._Storage.getItem(e);return null!==i?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){const i=this._Storage.getItem(e);return null!==i?"true"===i:t}static WriteBoolean(e,t){this._Storage.setItem(e,t?"true":"false")}static ReadNumber(e,t){const i=this._Storage.getItem(e);return null!==i?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}}iI._Storage=iI._GetStorage();class rI{constructor(e){this.particleSystem=e,this.position=W.Pq.Zero(),this.direction=W.Pq.Zero(),this.color=new H.ov(0,0,0,0),this.colorStep=new H.ov(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new W.I9(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new H.ov(0,0,0,0),this._currentColor2=new H.ov(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=rI._Count++,this.particleSystem.isAnimationSheetEnabled&&this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e=this.age,t=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===t?(t=1,e=this._randomCellOffset):e+=this._randomCellOffset);const i=this._initialEndSpriteCellID-this._initialStartSpriteCellID+1;let r;r=this._initialSpriteCellLoop?(0,ar.Clamp)(e*t%this.lifeTime/this.lifeTime):(0,ar.Clamp)(e*t/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+r*i|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){const t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){const e=W.AA.Vector3[0];this.direction.normalizeToRef(e),t.setDirection(e,0,Math.PI/2)}}else e.particleSystem.emitter.copyFrom(this.position);this.direction.scaleToRef(e.inheritedVelocityAmount/2,W.AA.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(W.AA.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach((e=>{this._inheritParticleInfoToSubEmitter(e)}))}_reset(){this.age=0,this.id=rI._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 W.IU(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()))}}rI._Count=0;class sI{constructor(){this.direction1=new W.Pq(0,1,0),this.direction2=new W.Pq(0,1,0),this.minEmitBox=new W.Pq(-.5,-.5,-.5),this.maxEmitBox=new W.Pq(.5,.5,.5)}startDirectionFunction(e,t,i,r){const s=(0,ar.RandomRange)(this.direction1.x,this.direction2.x),n=(0,ar.RandomRange)(this.direction1.y,this.direction2.y),o=(0,ar.RandomRange)(this.direction1.z,this.direction2.z);if(r)return t.x=s,t.y=n,void(t.z=o);W.Pq.TransformNormalFromFloatsToRef(s,n,o,e,t)}startPositionFunction(e,t,i,r){const s=(0,ar.RandomRange)(this.minEmitBox.x,this.maxEmitBox.x),n=(0,ar.RandomRange)(this.minEmitBox.y,this.maxEmitBox.y),o=(0,ar.RandomRange)(this.minEmitBox.z,this.maxEmitBox.z);if(r)return t.x=s,t.y=n,void(t.z=o);W.Pq.TransformCoordinatesFromFloatsToRef(s,n,o,e,t)}clone(){const e=new sI;return ce.r.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){W.Pq.FromArrayToRef(e.direction1,0,this.direction1),W.Pq.FromArrayToRef(e.direction2,0,this.direction2),W.Pq.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),W.Pq.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}var nI,oI=i(61923);class aI extends nv{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get useRampGradients(){return this._useRampGradients}set useRampGradients(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())}get particles(){return this._particles}get shaderLanguage(){return this._shaderLanguage}getActiveCount(){return this._particles.length}getClassName(){return"ParticleSystem"}isStopping(){return this._stopped&&this.isAlive()}getCustomEffect(e=0){return this._customWrappers[e]?.effect??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new gt.E(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 z.cP),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,r=null,s=!1,n=.01){super(e),this._emitterInverseWorldMatrix=W.uq.Identity(),this._inheritedVelocityOffset=new W.Pq,this.onDisposeObservable=new z.cP,this.onStoppedObservable=new z.cP,this._particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new H.ov(0,0,0,0),this._colorDiff=new H.ov(0,0,0,0),this._scaledDirection=W.Pq.Zero(),this._scaledGravity=W.Pq.Zero(),this._currentRenderId=-1,this._useInstancing=!1,this._started=!1,this._stopped=!1,this._actualFrame=0,this._currentEmitRate1=0,this._currentEmitRate2=0,this._currentStartSize1=0,this._currentStartSize2=0,this.updateInAnimate=!0,this._rawTextureWidth=256,this._useRampGradients=!1,this.isLocal=!1,this.isGPU=!1,this._shaderLanguage=0,this._onBeforeDrawParticlesObservable=null,this._emitFromParticle=e=>{},this.recycleParticle=e=>{const t=this._particles.pop();t!==e&&t.copyTo(e),this._stockParticles.push(t)},this._createParticle=()=>{let e;return 0!==this._stockParticles.length?(e=this._stockParticles.pop(),e._reset()):e=new rI(this),this._prepareParticle(e),e},this._shadersLoaded=!1,this._capacity=t,this._epsilon=n,this._isAnimationSheetEnabled=s,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=W.uq.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||he.q.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._initShaderSourceAsync(),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new gt.E(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new sI;let o=null;this.updateFunction=e=>{let t=null;this.noiseTexture&&(t=this.noiseTexture.getSize(),this.noiseTexture.getContent()?.then((e=>{o=e})));const i=e===this._particles;for(let r=0;rs.lifeTime){const e=s.age-a;n=(s.lifeTime-a)*n/e,s.age=s.lifeTime}const l=s.age/s.lifeTime;this._colorGradients&&this._colorGradients.length>0?JR.GetCurrentGradient(l,this._colorGradients,((e,t,i)=>{e!==s._currentColorGradient&&(s._currentColor1.copyFrom(s._currentColor2),t.getColorToRef(s._currentColor2),s._currentColorGradient=e),H.ov.LerpToRef(s._currentColor1,s._currentColor2,i,s.color)})):(s.colorStep.scaleToRef(n,this._scaledColorStep),s.color.addInPlace(this._scaledColorStep),s.color.a<0&&(s.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&JR.GetCurrentGradient(l,this._angularSpeedGradients,((e,t,i)=>{e!==s._currentAngularSpeedGradient&&(s._currentAngularSpeed1=s._currentAngularSpeed2,s._currentAngularSpeed2=t.getFactor(),s._currentAngularSpeedGradient=e),s.angularSpeed=(0,ar.Lerp)(s._currentAngularSpeed1,s._currentAngularSpeed2,i)})),s.angle+=s.angularSpeed*n;let h=n;if(this._velocityGradients&&this._velocityGradients.length>0&&JR.GetCurrentGradient(l,this._velocityGradients,((e,t,i)=>{e!==s._currentVelocityGradient&&(s._currentVelocity1=s._currentVelocity2,s._currentVelocity2=t.getFactor(),s._currentVelocityGradient=e),h*=(0,ar.Lerp)(s._currentVelocity1,s._currentVelocity2,i)})),s.direction.scaleToRef(h,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&JR.GetCurrentGradient(l,this._limitVelocityGradients,((e,t,i)=>{e!==s._currentLimitVelocityGradient&&(s._currentLimitVelocity1=s._currentLimitVelocity2,s._currentLimitVelocity2=t.getFactor(),s._currentLimitVelocityGradient=e);const r=(0,ar.Lerp)(s._currentLimitVelocity1,s._currentLimitVelocity2,i);s.direction.length()>r&&s.direction.scaleInPlace(this.limitVelocityDamping)})),this._dragGradients&&this._dragGradients.length>0&&JR.GetCurrentGradient(l,this._dragGradients,((e,t,i)=>{e!==s._currentDragGradient&&(s._currentDrag1=s._currentDrag2,s._currentDrag2=t.getFactor(),s._currentDragGradient=e);const r=(0,ar.Lerp)(s._currentDrag1,s._currentDrag2,i);this._scaledDirection.scaleInPlace(1-r)})),this.isLocal&&s._localPosition?(s._localPosition.addInPlace(this._scaledDirection),W.Pq.TransformCoordinatesToRef(s._localPosition,this._emitterWorldMatrix,s.position)):s.position.addInPlace(this._scaledDirection),o&&t&&s._randomNoiseCoordinates1){const e=this._fetchR(s._randomNoiseCoordinates1.x,s._randomNoiseCoordinates1.y,t.width,t.height,o),i=this._fetchR(s._randomNoiseCoordinates1.z,s._randomNoiseCoordinates2.x,t.width,t.height,o),r=this._fetchR(s._randomNoiseCoordinates2.y,s._randomNoiseCoordinates2.z,t.width,t.height,o),a=W.AA.Vector3[0],l=W.AA.Vector3[1];a.copyFromFloats((2*e-1)*this.noiseStrength.x,(2*i-1)*this.noiseStrength.y,(2*r-1)*this.noiseStrength.z),a.scaleToRef(n,l),s.direction.addInPlace(l)}this.gravity.scaleToRef(n,this._scaledGravity),s.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&JR.GetCurrentGradient(l,this._sizeGradients,((e,t,i)=>{e!==s._currentSizeGradient&&(s._currentSize1=s._currentSize2,s._currentSize2=t.getFactor(),s._currentSizeGradient=e),s.size=(0,ar.Lerp)(s._currentSize1,s._currentSize2,i)})),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&JR.GetCurrentGradient(l,this._colorRemapGradients,((e,t,i)=>{const r=(0,ar.Lerp)(e.factor1,t.factor1,i),n=(0,ar.Lerp)(e.factor2,t.factor2,i);s.remapData.x=r,s.remapData.y=n-r})),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&JR.GetCurrentGradient(l,this._alphaRemapGradients,((e,t,i)=>{const r=(0,ar.Lerp)(e.factor1,t.factor1,i),n=(0,ar.Lerp)(e.factor2,t.factor2,i);s.remapData.z=r,s.remapData.w=n-r}))),this._isAnimationSheetEnabled&&s.updateCellIndex(),s._inheritParticleInfoToSubEmitters(),s.age>=s.lifeTime&&(this._emitFromParticle(s),s._attachedSubEmitters&&(s._attachedSubEmitters.forEach((e=>{e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()})),s._attachedSubEmitters=null),this.recycleParticle(s),i&&r--)}}}serialize(e){throw new Error("Method not implemented.")}clone(e,t,i=!1){throw new Error("Method not implemented.")}_addFactorGradient(e,t,i,r){const s=new ZR(t,i,r);e.push(s),e.sort(((e,t)=>e.gradientt.gradient?1:0))}_removeFactorGradient(e,t){if(!e)return;let i=0;for(const r of e){if(r.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;const e=new Uint8Array(4*this._rawTextureWidth),t=H.IG.Color3[0];for(let i=0;i{H.v9.LerpToRef(r.color,s.color,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255}))}this._rampGradientsTexture=xi.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 QR(e,t);return this._rampGradients.push(i),this._syncRampGradientTexture(),this}removeRampGradient(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this}addColorGradient(e,t,i){this._colorGradients||(this._colorGradients=[]);const r=new $R(e,t,i);return this._colorGradients.push(r),this._colorGradients.sort(((e,t)=>e.gradientt.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?.dispose();this._drawWrappers=[]}_fetchR(e,t,i,r,s){return s[4*(((e=.5*Math.abs(e)+.5)*i%i|0)+((t=.5*Math.abs(t)+.5)*r%r|0)*i)]/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&&8!==this.billboardMode&&9!==this.billboardMode||(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 st.h(e,this._vertexData,!0,t);let i=0;const r=this._vertexBuffer.createVertexBuffer(st.R.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[st.R.PositionKind]=r,i+=3;const s=this._vertexBuffer.createVertexBuffer(st.R.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[st.R.ColorKind]=s,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 e=this._vertexBuffer.createVertexBuffer("cellIndex",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=e,i+=1}if(!this._isBillboardBased||8===this.billboardMode||9===this.billboardMode){const e=this._vertexBuffer.createVertexBuffer("direction",i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=e,i+=3}if(this._useRampGradients){const e=this._vertexBuffer.createVertexBuffer("remapData",i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=e,i+=4}let a;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new st.h(e,t,!1,2),a=this._spriteBuffer.createVertexBuffer("offset",0,2)}else a=this._vertexBuffer.createVertexBuffer("offset",i,2,this._vertexBufferSize,this._useInstancing),i+=2;this._vertexBuffers.offset=a,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing)return void(this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3])));const e=[],t=[];let i=0;for(let r=0;r{this.start(0)}),e);else{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){-1!==this.emitter?.getClassName().indexOf("Mesh")&&this.emitter.computeWorldMatrix(!0);const e=this.noiseTexture;if(e&&e.onGeneratedObservable)e.onGeneratedObservable.addOnce((()=>{setTimeout((()=>{for(let t=0;t0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}}stop(e=!0){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,this._postStop(e))}_postStop(e){}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,r){let s=e*this._vertexBufferSize;if(this._vertexData[s++]=t.position.x+this.worldOffset.x,this._vertexData[s++]=t.position.y+this.worldOffset.y,this._vertexData[s++]=t.position.z+this.worldOffset.z,this._vertexData[s++]=t.color.r,this._vertexData[s++]=t.color.g,this._vertexData[s++]=t.color.b,this._vertexData[s++]=t.color.a,this._vertexData[s++]=t.angle,this._vertexData[s++]=t.scale.x*t.size,this._vertexData[s++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[s++]=t.cellIndex),this._isBillboardBased)8!==this.billboardMode&&9!==this.billboardMode||(this._vertexData[s++]=t.direction.x,this._vertexData[s++]=t.direction.y,this._vertexData[s++]=t.direction.z);else if(t._initialDirection){let e=t._initialDirection;this.isLocal&&(W.Pq.TransformNormalToRef(e,this._emitterWorldMatrix,W.AA.Vector3[0]),e=W.AA.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}else{let e=t.direction;this.isLocal&&(W.Pq.TransformNormalToRef(e,this._emitterWorldMatrix,W.AA.Vector3[0]),e=W.AA.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}this._useRampGradients&&t.remapData&&(this._vertexData[s++]=t.remapData.x,this._vertexData[s++]=t.remapData.y,this._vertexData[s++]=t.remapData.z,this._vertexData[s++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===r?r=this._epsilon:1===r&&(r=1-this._epsilon)),this._vertexData[s++]=i,this._vertexData[s++]=r)}_prepareParticle(e){}_update(e){if(this._alive=this._particles.length>0,this.emitter.position){const e=this.emitter;this._emitterWorldMatrix=e.getWorldMatrix()}else{const e=this.emitter;this._emitterWorldMatrix=W.uq.Translation(e.x,e.y,e.z)}let t;this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(let i=0;i0){const e=(0,ar.Clamp)(this._actualFrame/this.targetStopDuration);JR.GetCurrentGradient(e,this._lifeTimeGradients,((i,r)=>{const s=i,n=r,o=s.getFactor(),a=n.getFactor(),l=(e-s.gradient)/(n.gradient-s.gradient);t.lifeTime=(0,ar.Lerp)(o,a,l)}))}else t.lifeTime=(0,ar.RandomRange)(this.minLifeTime,this.maxLifeTime);const e=(0,ar.RandomRange)(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(),W.Pq.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),0===e?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(e),this._sizeGradients&&0!==this._sizeGradients.length?(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.size=(0,ar.RandomRange)(this.minSize,this.maxSize),t.scale.copyFromFloats((0,ar.RandomRange)(this.minScaleX,this.maxScaleX),(0,ar.RandomRange)(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){const e=this._actualFrame/this.targetStopDuration;JR.GetCurrentGradient(e,this._startSizeGradients,((e,i,r)=>{e!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=i.getFactor(),this._currentStartSizeGradient=e);const s=(0,ar.Lerp)(this._currentStartSize1,this._currentStartSize2,r);t.scale.scaleInPlace(s)}))}if(this._angularSpeedGradients&&0!==this._angularSpeedGradients.length?(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.angularSpeed=(0,ar.RandomRange)(this.minAngularSpeed,this.maxAngularSpeed),t.angle=(0,ar.RandomRange)(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&&0!==this._colorGradients.length)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);else{const e=(0,ar.RandomRange)(0,1);H.ov.LerpToRef(this.color1,this.color2,e,t.color),this.colorDead.subtractToRef(t.color,this._colorDiff),this._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)}this._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=this.startSpriteCellID,t._initialEndSpriteCellID=this.endSpriteCellID,t._initialSpriteCellLoop=this.spriteCellLoop),t.direction.addInPlace(this._inheritedVelocityOffset),this._useRampGradients&&(t.remapData=new W.IU(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 W.Pq(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new W.Pq(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){const r=[st.R.PositionKind,st.R.ColorKind,"angle","offset","size"];return e&&r.push("cellIndex"),t||r.push("direction"),i&&r.push("remapData"),r}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const r=["invView","view","projection","textureMask","translationPivot","eyePosition"];return(0,Ln.TV)(r),e&&r.push("particlesInfos"),t&&r.push("logarithmicDepthConstant"),i&&(r.push("vFogInfos"),r.push("vFogColor")),r}fillDefines(e,t,i=!0){if(this._scene&&((0,Ln.tv)(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&0!==this._scene.fogMode&&e.push("#define FOG")),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===nv.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"),9===this.billboardMode&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case 7:e.push("#define BILLBOARDMODE_ALL")}i&&this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...aI._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&8!==this.billboardMode&&9!==this.billboardMode,this._useRampGradients)),e.push(...aI._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&((0,oI._)(e,this._imageProcessingConfigurationDefines),(0,oI.C)(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t?.effect)return t;const i=[];this.fillDefines(i,e);const r=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0;let s=this._drawWrappers[r];s||(s=this._drawWrappers[r]=[]);let n=s[e];n||(n=new gt.E(this._engine),n.drawContext&&(n.drawContext.useInstancing=this._useInstancing),s[e]=n);const o=i.join("\n");if(n.defines!==o){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),n.setEffect(this._engine.createEffect("particles",e,t,i,o,void 0,void 0,void 0,void 0,this._shaderLanguage),o)}return n}animate(e=!1){if(!this._started)return;if(!e&&this._scene){if(!this.isReady())return;if(this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}let t;if(this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:this._scene?.getAnimationRatio()||1),this.manualEmitCount>-1)t=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{let e=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){const t=this._actualFrame/this.targetStopDuration;JR.GetCurrentGradient(t,this._emitRateGradients,((t,i,r)=>{t!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=i.getFactor(),this._currentEmitRateGradient=t),e=(0,ar.Lerp)(this._currentEmitRate1,this._currentEmitRate2,r)}))}t=e*this._scaledUpdateSpeed|0,this._newPartsExcess+=e*this._scaledUpdateSpeed-t}if(this._newPartsExcess>1&&(t+=0|this._newPartsExcess,this._newPartsExcess-=0|this._newPartsExcess),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 e=0;for(let t=0;t=0&&(s.invertToRef(W.AA.Matrix[0]),i.setMatrix("invView",W.AA.Matrix[0])),void 0!==this._vertexArrayObject?this._scene?.forceWireframe?r.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,i):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,i)),this._engine.bindVertexArrayObject(this._vertexArrayObject,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?r.bindBuffers(this._vertexBuffers,this._scene?.forceWireframe?this._linesIndexBuffer:this._indexBuffer,i):r.bindBuffers(this._vertexBuffers,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:null,i),this.useLogarithmicDepth&&this._scene&&(0,Bt.DL)(n,i,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(i),e){case nv.BLENDMODE_ADD:r.setAlphaMode(1);break;case nv.BLENDMODE_ONEONE:r.setAlphaMode(6);break;case nv.BLENDMODE_STANDARD:r.setAlphaMode(2);break;case nv.BLENDMODE_MULTIPLY:r.setAlphaMode(4)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(i),this._useInstancing?this._scene?.forceWireframe?r.drawElementsType(6,0,10,this._particles.length):r.drawArraysType(7,0,4,this._particles.length):this._scene?.forceWireframe?r.drawElementsType(1,0,10*this._particles.length):r.drawElementsType(0,0,6*this._particles.length),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 t=this.blendMode===nv.BLENDMODE_MULTIPLYADD?this._render(nv.BLENDMODE_MULTIPLY)+this._render(nv.BLENDMODE_ADD):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 e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}}aI.ForceGLSL=!1,function(e){e[e.ATTACHED=0]="ATTACHED",e[e.END=1]="END"}(nI||(nI={}));class lI{constructor(e){if(this.particleSystem=e,this.type=1,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){const t=(0,X.n9)("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;e?e instanceof W.Pq?e=e.clone():-1!==e.getClassName().indexOf("Mesh")&&(e=new((0,X.n9)("BABYLON.Mesh"))("",e.getScene()),e.isVisible=!1):e=new W.Pq;const t=new lI(this.particleSystem.clone(this.particleSystem.name,e));return t.particleSystem.name+="Clone",t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem._disposeEmitterOnDispose=!0,t.particleSystem.disposeOnStop=!0,t}serialize(e=!1){const t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,r=!1){throw(0,Je.n)("ParseParticle")}static Parse(e,t,i){const r=e.particleSystem,s=new lI(lI._ParseParticleSystem(r,t,i,!0));return s.type=e.type,s.inheritDirection=e.inheritDirection,s.inheritedVelocityAmount=e.inheritedVelocityAmount,s.particleSystem._isSubEmitter=!0,s}dispose(){this.particleSystem.dispose()}}class hI{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(st.R.PositionKind),this._normals=e.getVerticesData(st.R.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=W.Pq.Zero(),this._mesh=null,this.direction1=new W.Pq(0,1,0),this.direction2=new W.Pq(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,r){if(this.useMeshNormalsForDirection&&this._normals)return void W.Pq.TransformNormalToRef(this._storedNormal,e,t);const s=(0,ar.RandomRange)(this.direction1.x,this.direction2.x),n=(0,ar.RandomRange)(this.direction1.y,this.direction2.y),o=(0,ar.RandomRange)(this.direction1.z,this.direction2.z);r?t.copyFromFloats(s,n,o):W.Pq.TransformNormalFromFloatsToRef(s,n,o,e,t)}startPositionFunction(e,t,i,r){if(!this._indices||!this._positions)return;const s=3*Math.random()*(this._indices.length/3)|0,n=Math.random(),o=Math.random()*(1-n),a=1-n-o,l=this._indices[s],h=this._indices[s+1],c=this._indices[s+2],u=W.AA.Vector3[0],d=W.AA.Vector3[1],f=W.AA.Vector3[2],p=W.AA.Vector3[3];W.Pq.FromArrayToRef(this._positions,3*l,u),W.Pq.FromArrayToRef(this._positions,3*h,d),W.Pq.FromArrayToRef(this._positions,3*c,f),p.x=n*u.x+o*d.x+a*f.x,p.y=n*u.y+o*d.y+a*f.y,p.z=n*u.z+o*d.z+a*f.z,r?t.copyFromFloats(p.x,p.y,p.z):W.Pq.TransformCoordinatesFromFloatsToRef(p.x,p.y,p.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(W.Pq.FromArrayToRef(this._normals,3*l,u),W.Pq.FromArrayToRef(this._normals,3*h,d),W.Pq.FromArrayToRef(this._normals,3*c,f),this._storedNormal.x=n*u.x+o*d.x+a*f.x,this._storedNormal.y=n*u.y+o*d.y+a*f.y,this._storedNormal.z=n*u.z+o*d.z+a*f.z)}clone(){const e=new hI(this.mesh);return ce.r.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(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.meshId=this.mesh?.id,e.useMeshNormalsForDirection=this.useMeshNormalsForDirection,e}parse(e,t){W.Pq.FromArrayToRef(e.direction1,0,this.direction1),W.Pq.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}class cI{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,r){const s=W.AA.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,s);const e=W.AA.Vector3[1];s.subtractToRef(i.position,e),e.scaleToRef(1/i.lifeTime,s)}else s.set(0,0,0);r?t.copyFrom(s):W.Pq.TransformNormalToRef(s,e,t)}startPositionFunction(e,t,i,r){const s=W.AA.Vector3[0];this.particlePositionGenerator?this.particlePositionGenerator(-1,i,s):s.set(0,0,0),r?t.copyFrom(s):W.Pq.TransformCoordinatesToRef(s,e,t)}clone(){const e=new cI;return ce.r.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 uI{constructor(){this.direction1=new W.Pq(0,1,0),this.direction2=new W.Pq(0,1,0)}startDirectionFunction(e,t,i,r){const s=(0,ar.RandomRange)(this.direction1.x,this.direction2.x),n=(0,ar.RandomRange)(this.direction1.y,this.direction2.y),o=(0,ar.RandomRange)(this.direction1.z,this.direction2.z);r?t.copyFromFloats(s,n,o):W.Pq.TransformNormalFromFloatsToRef(s,n,o,e,t)}startPositionFunction(e,t,i,r){r?t.copyFromFloats(0,0,0):W.Pq.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){const e=new uI;return ce.r.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){W.Pq.FromArrayToRef(e.direction1,0,this.direction1),W.Pq.FromArrayToRef(e.direction2,0,this.direction2)}}class dI{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){const s=i.position.subtract(e.getTranslation()).normalize(),n=(0,ar.RandomRange)(0,this.directionRandomizer),o=(0,ar.RandomRange)(0,this.directionRandomizer),a=(0,ar.RandomRange)(0,this.directionRandomizer);s.x+=n,s.y+=o,s.z+=a,s.normalize(),r?t.copyFrom(s):W.Pq.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,r){const s=this.radius-(0,ar.RandomRange)(0,this.radius*this.radiusRange),n=(0,ar.RandomRange)(0,1),o=(0,ar.RandomRange)(0,2*Math.PI),a=Math.acos(2*n-1),l=s*Math.cos(o)*Math.sin(a),h=s*Math.cos(a),c=s*Math.sin(o)*Math.sin(a);r?t.copyFromFloats(l,Math.abs(h),c):W.Pq.TransformCoordinatesFromFloatsToRef(l,Math.abs(h),c,e,t)}clone(){const e=new dI(this.radius,this.directionRandomizer);return ce.r.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 fI{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){const s=i.position.subtract(e.getTranslation()).normalize(),n=(0,ar.RandomRange)(0,this.directionRandomizer),o=(0,ar.RandomRange)(0,this.directionRandomizer),a=(0,ar.RandomRange)(0,this.directionRandomizer);s.x+=n,s.y+=o,s.z+=a,s.normalize(),r?t.copyFrom(s):W.Pq.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,r){const s=this.radius-(0,ar.RandomRange)(0,this.radius*this.radiusRange),n=(0,ar.RandomRange)(0,1),o=(0,ar.RandomRange)(0,2*Math.PI),a=Math.acos(2*n-1),l=s*Math.cos(o)*Math.sin(a),h=s*Math.cos(a),c=s*Math.sin(o)*Math.sin(a);r?t.copyFromFloats(l,h,c):W.Pq.TransformCoordinatesFromFloatsToRef(l,h,c,e,t)}clone(){const e=new fI(this.radius,this.directionRandomizer);return ce.r.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 pI extends fI{constructor(e=1,t=new W.Pq(0,1,0),i=new W.Pq(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){const i=(0,ar.RandomRange)(this.direction1.x,this.direction2.x),r=(0,ar.RandomRange)(this.direction1.y,this.direction2.y),s=(0,ar.RandomRange)(this.direction1.z,this.direction2.z);W.Pq.TransformNormalFromFloatsToRef(i,r,s,e,t)}clone(){const e=new pI(this.radius,this.direction1,this.direction2);return ce.r.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\n#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 _I{constructor(e=1,t=1,i=1,r=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=r,this._tempVector=W.Pq.Zero()}startDirectionFunction(e,t,i,r,s){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),W.Pq.TransformNormalToRef(this._tempVector,s,this._tempVector);const n=(0,ar.RandomRange)(-this.directionRandomizer/2,this.directionRandomizer/2);let o=Math.atan2(this._tempVector.x,this._tempVector.z);o+=(0,ar.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(),r?t.copyFrom(this._tempVector):W.Pq.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,r){const s=(0,ar.RandomRange)(-this.height/2,this.height/2),n=(0,ar.RandomRange)(0,2*Math.PI),o=(0,ar.RandomRange)((1-this.radiusRange)*(1-this.radiusRange),1),a=Math.sqrt(o)*this.radius,l=a*Math.cos(n),h=a*Math.sin(n);r?t.copyFromFloats(l,s,h):W.Pq.TransformCoordinatesFromFloatsToRef(l,s,h,e,t)}clone(){const e=new _I(this.radius,this.directionRandomizer);return ce.r.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 mI extends _I{constructor(e=1,t=1,i=1,r=new W.Pq(0,1,0),s=new W.Pq(0,1,0)){super(e,t,i),this.direction1=r,this.direction2=s}startDirectionFunction(e,t,i,r){const s=(0,ar.RandomRange)(this.direction1.x,this.direction2.x),n=(0,ar.RandomRange)(this.direction1.y,this.direction2.y),o=(0,ar.RandomRange)(this.direction1.z,this.direction2.z);r?t.copyFromFloats(s,n,o):W.Pq.TransformNormalFromFloatsToRef(s,n,o,e,t)}clone(){const e=new mI(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return ce.r.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\n#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),W.Pq.FromArrayToRef(e.direction1,0,this.direction1),W.Pq.FromArrayToRef(e.direction2,0,this.direction2)}}class gI{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(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,r){r?W.AA.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),W.AA.Vector3[0]).normalize();const s=(0,ar.RandomRange)(0,this.directionRandomizer),n=(0,ar.RandomRange)(0,this.directionRandomizer),o=(0,ar.RandomRange)(0,this.directionRandomizer);t.x=W.AA.Vector3[0].x+s,t.y=W.AA.Vector3[0].y+n,t.z=W.AA.Vector3[0].z+o,t.normalize()}startPositionFunction(e,t,i,r){const s=(0,ar.RandomRange)(0,2*Math.PI);let n;this.emitFromSpawnPointOnly?n=1e-4:(n=(0,ar.RandomRange)(0,this.heightRange),n=1-n*n);let o=this._radius-(0,ar.RandomRange)(0,this._radius*this.radiusRange);o*=n;const a=o*Math.sin(s),l=o*Math.cos(s),h=n*this._height;if(r)return t.x=a,t.y=h,void(t.z=l);W.Pq.TransformCoordinatesFromFloatsToRef(a,h,l,e,t)}clone(){const e=new gI(this._radius,this._angle,this.directionRandomizer);return ce.r.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+="\n#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=void 0!==e.radiusRange?e.radiusRange:1,this.heightRange=void 0!==e.radiusRange?e.heightRange:1,this.emitFromSpawnPointOnly=void 0!==e.emitFromSpawnPointOnly&&e.emitFromSpawnPointOnly}}class vI extends gI{constructor(e=1,t=Math.PI,i=new W.Pq(0,1,0),r=new W.Pq(0,1,0)){super(e,t),this.direction1=i,this.direction2=r}startDirectionFunction(e,t){const i=(0,ar.RandomRange)(this.direction1.x,this.direction2.x),r=(0,ar.RandomRange)(this.direction1.y,this.direction2.y),s=(0,ar.RandomRange)(this.direction1.z,this.direction2.z);W.Pq.TransformNormalFromFloatsToRef(i,r,s,e,t)}clone(){const e=new vI(this.radius,this.angle,this.direction1,this.direction2);return ce.r.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define CONEEMITTER\n#define DIRECTEDCONEEMITTER"}getClassName(){return"ConeDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}function xI(e,t){const i=new uI;return i.direction1=e,i.direction2=t,i}function bI(e=1,t=1){return new dI(e,t)}function SI(e=1,t=1){return new fI(e,t)}function TI(e=1,t=new W.Pq(0,1,0),i=new W.Pq(0,1,0)){return new pI(e,t,i)}function CI(e=1,t=1,i=1,r=0){return new _I(e,t,i,r)}function yI(e=1,t=1,i=1,r=new W.Pq(0,1,0),s=new W.Pq(0,1,0)){return new mI(e,t,i,r,s)}function EI(e=1,t=Math.PI/4){return new gI(e,t)}function PI(e=1,t=Math.PI/4,i=new W.Pq(0,1,0),r=new W.Pq(0,1,0)){return new vI(e,t,i,r)}class AI extends aI{constructor(){super(...arguments),this._disposeEmitterOnDispose=!1,this._emitFromParticle=e=>{if(!this._subEmitters||0===this._subEmitters.length)return;const t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach((t=>{if(1===t.type){const i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}}))}}createPointEmitter(e,t){const i=xI(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=bI(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=SI(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new W.Pq(0,1,0),i=new W.Pq(0,1,0)){const r=TI(e,t,i);return this.particleEmitterType=r,r}createCylinderEmitter(e=1,t=1,i=1,r=0){const s=CI(e,t,i,r);return this.particleEmitterType=s,s}createDirectedCylinderEmitter(e=1,t=1,i=1,r=new W.Pq(0,1,0),s=new W.Pq(0,1,0)){const n=yI(e,t,i,r,s);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=EI(e,t);return this.particleEmitterType=i,i}createDirectedConeEmitter(e=1,t=Math.PI/4,i=new W.Pq(0,1,0),r=new W.Pq(0,1,0)){const s=PI(e,t,i,r);return this.particleEmitterType=s,s}createBoxEmitter(e,t,i,r){const s=new sI;return this.particleEmitterType=s,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=r,s}_prepareSubEmitterInternalArray(){this._subEmitters=new Array,this.subEmitters&&this.subEmitters.forEach((e=>{e instanceof AI?this._subEmitters.push([new lI(e)]):e instanceof lI?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);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_preStart(){this._prepareSubEmitterInternalArray(),this._subEmitters&&0!=this._subEmitters.length&&(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((t=>{if(0===t.type){const i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}}))}}_onDispose(e=!1,t=!1){if(this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),e&&this.particles?.forEach((e=>{if(e._attachedSubEmitters)for(let t=e._attachedSubEmitters.length-1;t>=0;t-=1)e._attachedSubEmitters[t].dispose()})),t&&this.activeSubSystems)for(let e=this.activeSubSystems.length-1;e>=0;e-=1)this.activeSubSystems[e].dispose();if(this._subEmitters&&this._subEmitters.length){for(let e=0;e0?h.shaderOptions.defines.join("\n"):"";l=o.createEffectForParticles(h.shaderPath.fragmentElement,h.shaderOptions.uniforms,h.shaderOptions.samplers,t)}const c=new AI(n,s||e.capacity,t,l,e.isAnimationSheetEnabled);if(c.customShader=h,c._rootUrl=i,e.id&&(c.id=e.id),e.subEmitters){c.subEmitters=[];for(const r of e.subEmitters){const e=[];for(const s of r)e.push(lI.Parse(s,t,i));c.subEmitters.push(e)}}return AI._Parse(e,c,t,i),e.textureMask&&(c.textureMask=H.ov.FromArray(e.textureMask)),e.worldOffset&&(c.worldOffset=W.Pq.FromArray(e.worldOffset)),e.preventAutoStart&&(c.preventAutoStart=e.preventAutoStart),r||c.preventAutoStart||c.start(),c}serialize(e=!1){const t={};if(AI._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,t.worldOffset=this.worldOffset.asArray(),this.subEmitters){t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(const i of this._subEmitters){const r=[];for(const t of i)r.push(t.serialize(e));t.subEmitters.push(r)}}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){const i=t.emitter;e.emitterId=i.id}else{const i=t.emitter;e.emitter=i.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,it.p.AppendSerializedAnimations(t,e),e.beginAnimationOnStart=t.beginAnimationOnStart,e.beginAnimationFrom=t.beginAnimationFrom,e.beginAnimationTo=t.beginAnimationTo,e.beginAnimationLoop=t.beginAnimationLoop,e.startDelay=t.startDelay,e.renderingGroupId=t.renderingGroupId,e.isBillboardBased=t.isBillboardBased,e.billboardMode=t.billboardMode,e.minAngularSpeed=t.minAngularSpeed,e.maxAngularSpeed=t.maxAngularSpeed,e.minSize=t.minSize,e.maxSize=t.maxSize,e.minScaleX=t.minScaleX,e.maxScaleX=t.maxScaleX,e.minScaleY=t.minScaleY,e.maxScaleY=t.maxScaleY,e.minEmitPower=t.minEmitPower,e.maxEmitPower=t.maxEmitPower,e.minLifeTime=t.minLifeTime,e.maxLifeTime=t.maxLifeTime,e.emitRate=t.emitRate,e.gravity=t.gravity.asArray(),e.noiseStrength=t.noiseStrength.asArray(),e.color1=t.color1.asArray(),e.color2=t.color2.asArray(),e.colorDead=t.colorDead.asArray(),e.updateSpeed=t.updateSpeed,e.targetStopDuration=t.targetStopDuration,e.blendMode=t.blendMode,e.preWarmCycles=t.preWarmCycles,e.preWarmStepOffset=t.preWarmStepOffset,e.minInitialRotation=t.minInitialRotation,e.maxInitialRotation=t.maxInitialRotation,e.startSpriteCellID=t.startSpriteCellID,e.spriteCellLoop=t.spriteCellLoop,e.endSpriteCellID=t.endSpriteCellID,e.spriteCellChangeSpeed=t.spriteCellChangeSpeed,e.spriteCellWidth=t.spriteCellWidth,e.spriteCellHeight=t.spriteCellHeight,e.spriteRandomStartCell=t.spriteRandomStartCell,e.isAnimationSheetEnabled=t.isAnimationSheetEnabled,e.useLogarithmicDepth=t.useLogarithmicDepth;const r=t.getColorGradients();if(r){e.colorGradients=[];for(const t of r){const i={gradient:t.gradient,color1:t.color1.asArray()};t.color2?i.color2=t.color2.asArray():i.color2=t.color1.asArray(),e.colorGradients.push(i)}}const s=t.getRampGradients();if(s){e.rampGradients=[];for(const t of s){const i={gradient:t.gradient,color:t.color.asArray()};e.rampGradients.push(i)}e.useRampGradients=t.useRampGradients}const n=t.getColorRemapGradients();if(n){e.colorRemapGradients=[];for(const t of n){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.colorRemapGradients.push(i)}}const o=t.getAlphaRemapGradients();if(o){e.alphaRemapGradients=[];for(const t of o){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.alphaRemapGradients.push(i)}}const a=t.getSizeGradients();if(a){e.sizeGradients=[];for(const t of a){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.sizeGradients.push(i)}}const l=t.getAngularSpeedGradients();if(l){e.angularSpeedGradients=[];for(const t of l){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.angularSpeedGradients.push(i)}}const h=t.getVelocityGradients();if(h){e.velocityGradients=[];for(const t of h){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.velocityGradients.push(i)}}const c=t.getDragGradients();if(c){e.dragGradients=[];for(const t of c){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.dragGradients.push(i)}}const u=t.getEmitRateGradients();if(u){e.emitRateGradients=[];for(const t of u){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.emitRateGradients.push(i)}}const d=t.getStartSizeGradients();if(d){e.startSizeGradients=[];for(const t of d){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.startSizeGradients.push(i)}}const f=t.getLifeTimeGradients();if(f){e.lifeTimeGradients=[];for(const t of f){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.lifeTimeGradients.push(i)}}const p=t.getLimitVelocityGradients();if(p){e.limitVelocityGradients=[];for(const t of p){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.limitVelocityGradients.push(i)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}clone(e,t,i=!1){const r={...this._customWrappers};let s=null;const n=this._engine;if(n.createEffectForParticles&&null!=this.customShader){s=this.customShader;const e=s.shaderOptions.defines.length>0?s.shaderOptions.defines.join("\n"):"",t=n.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e);r[0]?r[0].effect=t:this.setCustomEffect(t,0)}const o=this.serialize(i),a=AI.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=s,a._customWrappers=r,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,this.preventAutoStart||a.start(),a}}AI.BILLBOARDMODE_Y=2,AI.BILLBOARDMODE_ALL=7,AI.BILLBOARDMODE_STRETCHED=8,AI.BILLBOARDMODE_STRETCHED_LOCAL=9,lI._ParseParticleSystem=AI.Parse;class RI{constructor(){this._trackedScene=null}track(e){this._trackedScene=e,it.p.AllowLoadingUniqueId=!0,this._savedJSON=DR.Serialize(e),it.p.AllowLoadingUniqueId=!1}getDelta(){if(!this._trackedScene)return null;const e=vi.g.ForceSerializeBuffers;vi.g.ForceSerializeBuffers=!1,it.p.AllowLoadingUniqueId=!0;const t=DR.Serialize(this._trackedScene);it.p.AllowLoadingUniqueId=!1;const i={};for(const e in t)this._compareCollections(e,this._savedJSON[e],t[e],i);return vi.g.ForceSerializeBuffers=e,i}_compareArray(e,t,i,r){if(0===t.length&&0===i.length)return!0;if(t.length&&!isNaN(t[0])||i.length&&!isNaN(i[0])){if(t.length!==i.length)return!1;if(0===t.length)return!0;for(let s=0;se.uniqueId===a));if(l.length){const t=l[0],i={};this._compareObjects(o,t,i)||(r[e]||(r[e]=[]),i.__state={id:t.id||t.name},r[e].push(i))}else{const t={__state:{deleteId:o.id||o.name}};r[e]||(r[e]=[]),r[e].push(t)}}for(let t=0;te.getShadowGenerators()));for(const e of i)if(e){const i=e.values();for(let e=i.next();!0!==e.done;e=i.next()){const i=e.value;if(i&&i.id===t)return i}}return null}static ApplyDelta(e,t){"string"==typeof e&&(e=JSON.parse(e));const i=t;for(const r in e){const s=e[r],n=i[r];if(Array.isArray(n)||"shadowGenerators"===r)switch(r){case"cameras":this._ApplyDeltaForEntity(s,t,t.getCameraById.bind(t),(e=>rt.Parse(e,t)));break;case"lights":this._ApplyDeltaForEntity(s,t,t.getLightById.bind(t),(e=>$t.Parse(e,t)));break;case"shadowGenerators":this._ApplyDeltaForEntity(s,t,(e=>this.GetShadowGeneratorById(t,e)),(e=>ux.Parse(e,t)));break;case"meshes":this._ApplyDeltaForEntity(s,t,t.getMeshById.bind(t),(e=>Yt.Parse(e,t,"")));break;case"skeletons":this._ApplyDeltaForEntity(s,t,t.getSkeletonById.bind(t),(e=>Ti.Parse(e,t)));break;case"materials":this._ApplyDeltaForEntity(s,t,t.getMaterialById.bind(t),(e=>Vt.Parse(e,t,"")));break;case"multiMaterials":this._ApplyDeltaForEntity(s,t,t.getMaterialById.bind(t),(e=>kt.Parse(e,t,"")));break;case"transformNodes":this._ApplyDeltaForEntity(s,t,t.getTransformNodeById.bind(t),(e=>Pt.Parse(e,t,"")));break;case"particleSystems":this._ApplyDeltaForEntity(s,t,t.getParticleSystemById.bind(t),(e=>AI.Parse(e,t,"")));break;case"morphTargetManagers":this._ApplyDeltaForEntity(s,t,t.getMorphTargetById.bind(t),(e=>Gx.Parse(e,t)));break;case"postProcesses":this._ApplyDeltaForEntity(s,t,t.getPostProcessByName.bind(t),(e=>ms.w.Parse(e,t,"")))}else isNaN(n)?n.fromArray&&n.fromArray(s):i[r]=s}}static _ApplyPropertiesToEntity(e,t){for(const i in e){const r=e[i],s=t[i];void 0!==s&&(!isNaN(s)||Array.isArray(s)?t[i]=r:s.fromArray?s.fromArray(r):"object"==typeof s&&null!==s&&this._ApplyPropertiesToEntity(r,s))}}static _ApplyDeltaForEntity(e,t,i,r){for(const s of e)if(s.__state&&void 0!==s.__state.id){const e=i(s.__state.id);e&&(this._ApplyPropertiesToEntity(s,e),it.p.ParseProperties(s,e,t,null))}else if(s.__state&&void 0!==s.__state.deleteId){const e=i(s.__state.deleteId);e?.dispose()}else r(s)}}var II,MI=i(27606);!function(e){class t{serialize(){const e={},t=new Array(this._characterToIdx.size);return this._characterToIdx.forEach(((e,i)=>{t[e]=i})),e.characters=t,e.insertionCosts=this._insertionCosts,e.deletionCosts=this._deletionCosts,e.substitutionCosts=this._substitutionCosts,JSON.stringify(e)}static Deserialize(e){const i=JSON.parse(e),r=new t(i.characters);return r._insertionCosts=i.insertionCosts,r._deletionCosts=i.deletionCosts,r._substitutionCosts=i.substitutionCosts,r}constructor(e,t=null,i=null,r=null){let s;t=t??(()=>1),i=i??(()=>1),r=r??((e,t)=>e===t?0:1),this._characterToIdx=new Map,this._insertionCosts=new Array(e.length),this._deletionCosts=new Array(e.length),this._substitutionCosts=new Array(e.length);for(let n=0;ni._MAX_SEQUENCE_LENGTH)throw new Error("Sequences longer than "+i._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=t,this._characters=e.map((e=>this._alphabet.getCharacterIdx(e)))}distance(e){return i._Distance(this,e)}static _Distance(e,t){const r=e._alphabet;if(r!==t._alphabet)throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");const s=e._characters,n=t._characters,o=s.length,a=n.length,l=i._CostMatrix;l[0][0]=0;for(let e=0;enew Array(i._MAX_SEQUENCE_LENGTH+1))),e.Sequence=i}(II||(II={}));class OI{serialize(){return JSON.stringify(this)}static Deserialize(e){const t=JSON.parse(e),i=new OI(t._segmentLength);return i._points=t._points.map((e=>new W.Pq(e._x,e._y,e._z))),i}constructor(e=.01){this._points=[],this._segmentLength=e}getLength(){return this._points.length*this._segmentLength}add(e){let t=this._points.length;if(0===t)this._points.push(e.clone());else{const i=()=>this._segmentLength/W.Pq.Distance(this._points[t-1],e);for(let r=i();r<=1;r=i()){const i=this._points[t-1].scale(1-r);e.scaleAndAddToRef(r,i),this._points.push(i),++t}}}resampleAtTargetResolution(e){const t=new OI(this.getLength()/e);return this._points.forEach((e=>{t.add(e)})),t}tokenize(e){const t=[],i=new W.Pq;for(let r=2;r.98||(W.Pq.CrossToRef(OI._ForwardDir,OI._InverseFromVec,OI._UpDir),OI._UpDir.normalize(),W.uq.LookAtLHToRef(e,t,OI._UpDir,OI._LookMatrix),i.subtractToRef(t,OI._FromToVec),OI._FromToVec.normalize(),W.Pq.TransformNormalToRef(OI._FromToVec,OI._LookMatrix,r),0))}static _TokenizeSegment(e,t){OI._BestMatch=0,OI._Score=W.Pq.Dot(e,t[0]),OI._BestScore=OI._Score;for(let i=1;iOI._BestScore&&(OI._BestMatch=i,OI._BestScore=OI._Score);return OI._BestMatch}}OI._ForwardDir=new W.Pq,OI._InverseFromVec=new W.Pq,OI._UpDir=new W.Pq,OI._FromToVec=new W.Pq,OI._LookMatrix=new W.uq;class DI{static Generate(e=64,t=256,i=.1,r=.001,s=[]){const n=new DI(e);for(let t=0;t{n.chars[e].subtractToRef(t,h),a=h.lengthSquared(),a>1e-6&&h.scaleAndAddToRef(1/(h.lengthSquared()*a),l)})),l.scaleInPlace(o),n.chars[e].addInPlace(l),n.chars[e].normalize()}var c;return n}serialize(){return JSON.stringify(this.chars)}static Deserialize(e){const t=JSON.parse(e),i=new DI(t.length);for(let e=0;ee.serialize())))}static Deserialize(e,t){const i=new wI;return i._sequences=JSON.parse(e).map((e=>II.Sequence.Deserialize(e,t))),i}static CreateFromTrajectory(e,t,i){return wI.CreateFromTokenizationPyramid(wI._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){const i=new wI;return i._sequences=e.map((e=>new II.Sequence(e,t))),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=wI._FINEST_DESCRIPTOR_RESOLUTION){const r=[];for(let s=i;s>4;s=Math.floor(s/2))r.push(e.resampleAtTargetResolution(s).tokenize(t.chars));return r}distance(e){let t,i=0;for(let r=0;re.serialize())),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){const i=JSON.parse(e),r=new NI;return r._descriptors=i.descriptors.map((e=>wI.Deserialize(e,t))),r._centroidIdx=i.centroidIdx,r._averageDistance=i.averageDistance,r}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map((t=>t.distance(e))))}_refreshDescription(){let e;this._centroidIdx=-1;const t=this._descriptors.map((t=>(e=0,this._descriptors.forEach((i=>{e+=t.distance(i)})),e)));for(let e=0;e{this._averageDistance+=e.distance(this._descriptors[this._centroidIdx])})),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,NI._MIN_AVERAGE_DISTANCE))}}NI._MIN_AVERAGE_DISTANCE=1;class FI{serialize(){const e={};return e.maximumAllowableMatchCost=this._maximumAllowableMatchCost,e.vector3Alphabet=this._vector3Alphabet.serialize(),e.levenshteinAlphabet=this._levenshteinAlphabet.serialize(),e.nameToDescribedTrajectory=[],this._nameToDescribedTrajectory.forEach(((t,i)=>{e.nameToDescribedTrajectory.push(i),e.nameToDescribedTrajectory.push(t.serialize())})),JSON.stringify(e)}static Deserialize(e){const t=JSON.parse(e),i=new FI;i._maximumAllowableMatchCost=t.maximumAllowableMatchCost,i._vector3Alphabet=DI.Deserialize(t.vector3Alphabet),i._levenshteinAlphabet=II.Alphabet.Deserialize(t.levenshteinAlphabet);for(let e=0;e0===e?0:1),(e=>0===e?0:1),((t,i)=>Math.min(1-W.Pq.Dot(e.chars[t],e.chars[i]),1))),r=new FI;return r._vector3Alphabet=e,r._levenshteinAlphabet=i,r}constructor(){this._maximumAllowableMatchCost=4,this._nameToDescribedTrajectory=new Map}addTrajectoryToClassification(e,t){this._nameToDescribedTrajectory.has(t)||this._nameToDescribedTrajectory.set(t,new NI),this._nameToDescribedTrajectory.get(t).add(wI.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet))}deleteClassification(e){return this._nameToDescribedTrajectory.delete(e)}classifyTrajectory(e){const t=wI.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet),i=[];if(this._nameToDescribedTrajectory.forEach(((e,r)=>{e.getMatchCost(t){const t=e.data;if(t.startsWith(BI._SERVER_PREFIX)){const e=t.substring(BI._SERVER_PREFIX.length);return Z.V.Log(`[Reflector] Received server message: ${e.substring(0,64)}`),void this._handleServerMessage(e)}Z.V.Log(`[Reflector] Received client message: ${t.substring(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=e=>{Z.V.Log(`[Reflector] Disconnected ${e.code} ${e.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){"connected"===e&&DR.SerializeAsync(this._scene).then((e=>{this._webSocket.send(`load|${JSON.stringify(e)}`)}))}_handleClientMessage(){}}BI._SERVER_PREFIX="$$";class VI{constructor(e){this._observer=null,this._currentState=[],this.onPressureChanged=new z.cP,VI.IsAvailable&&(this._observer=new PressureObserver((e=>{this._currentState=e,this.onPressureChanged.notifyObservers(e)}),e))}static get IsAvailable(){return"undefined"!=typeof PressureObserver&&PressureObserver.knownSources&&PressureObserver.knownSources.includes("cpu")}observe(e){try{this._observer?.observe(e),this.onPressureChanged.notifyObservers(this._currentState)}catch{}}unobserve(e){try{this._observer?.unobserve(e)}catch{}}dispose(){this._observer?.disconnect(),this._observer=null,this.onPressureChanged.clear()}}class kI{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(1.5*this._view.length),t=new Float32Array(e);t.set(this._view),this._view=t}}const UI=1800,GI="timestamp",zI="numPoints",WI=/\r/g;class HI{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{const e=ai.j.Now-this._startingTimestamp,t=this.datasets.ids.length,i=this.datasets.startingIndices.itemLength;let r=0;if(i>0){const e=this.datasets.startingIndices.at(i-1);r=e+this.datasets.data.at(e+HI.NumberOfPointsOffset)+HI.SliceDataOffset}if(this.datasets.startingIndices.push(r),this.datasets.data.push(e),this.datasets.data.push(t),this.datasets.ids.forEach((e=>{const t=this._strategies.get(e);t&&this.datasets.data.push(t.getData())})),this.datasetObservable.hasObservers()){const i=[e,t];for(let e=0;ee.callback(this._datasetMeta,new z.qO(0)))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){if(this._strategies.has(e)&&!t)return;this._strategies.has(e)&&t&&(this._strategies.get(e)?.dispose(),this._strategies.delete(e));const r={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:t=>{let i=0,r=0;const s=t.onAfterRenderObservable.add((()=>{r=i,i=0})),n=this._customEventObservable.add((t=>{e===t.name&&(void 0!==t.value?i=t.value:i++)}));return{id:e,getData:()=>r,dispose:()=>{t.onAfterRenderObservable.remove(s),this._customEventObservable.remove(n)}}},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:r}of e){const e=t(this._scene);this._strategies.has(e.id)?e.dispose():(this.datasets.ids.push(e.id),i&&(i=i.replace(new RegExp("@","g"),"")),this._datasetMeta.set(e.id,{color:this._getHexColorFromId(e.id),category:i,hidden:r}),this._strategies.set(e.id,e))}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let i=0;i>e&255).toString(16);i+=r.substring(r.length-2)}return i}getCurrentSlice(){const e=[ai.j.Now-this._startingTimestamp,this.datasets.ids.length];this.datasets.ids.forEach((t=>{const i=this._strategies.get(t);i&&this.datasetObservable.hasObservers()&&e.push(i.getData())})),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(e)}updateMetadata(e,t,i){const r=this._datasetMeta.get(e);r&&(r[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new kI(UI),this.datasets.ids.length=0,this.datasets.startingIndices=new kI(UI),this._datasetMeta.clear(),this._strategies.forEach((e=>e.dispose())),this._strategies.clear(),e||this._eventRestoreSet.clear(),this._hasLoadedData=!1}get hasLoadedData(){return this._hasLoadedData}loadFromFileData(e,t){const i=e.replace(WI,"").split("\n").map((e=>e.split(",").filter((e=>e.length>0)))).filter((e=>e.length>0)),r=HI.NumberOfPointsOffset;if(i.length<2)return!1;const s={ids:[],data:new kI(UI),startingIndices:new kI(UI)},[n,...o]=i;if(n.length<2||n[0]!==GI||n[r]!==zI)return!1;const a=new Map;for(let e=HI.SliceDataOffset;ee.dispose())),this._strategies.clear(),!t)for(const e of this.datasets.ids){const t=a.get(e);this._datasetMeta.set(e,{category:t,color:this._getHexColorFromId(e)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${GI},${zI}`;for(let t=0;t{e.dispose()})),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}const XI=()=>{};class qI{static FpsStrategy(){return e=>{const t=e.getEngine();return{id:"FPS",getData:()=>t.getFps(),dispose:XI}}}static ThermalStrategy(){return this._PressureStrategy("Thermal utilization","thermal")}static PowerSupplyStrategy(){return this._PressureStrategy("Power supply utilization","power-supply")}static PressureStrategy(){return this._PressureStrategy("Pressure")}static _PressureStrategy(e,t=null){return()=>{let i=0;const r=new VI;return r.observe("cpu"),r.onPressureChanged.add((e=>{for(const r of e)if(t&&r.factors.includes(t)||!t&&0===(r.factors?.length??0))switch(r.state){case"nominal":i=0;break;case"fair":i=.25;break;case"serious":i=.5;break;case"critical":i=1}})),{id:e,getData:()=>i,dispose:()=>r.dispose()}}}static TotalMeshesStrategy(){return e=>({id:"Total meshes",getData:()=>e.meshes.length,dispose:XI})}static ActiveMeshesStrategy(){return e=>({id:"Active meshes",getData:()=>e.getActiveMeshes().length,dispose:XI})}static ActiveIndicesStrategy(){return e=>({id:"Active indices",getData:()=>e.getActiveIndices(),dispose:XI})}static ActiveFacesStrategy(){return e=>({id:"Active faces",getData:()=>e.getActiveIndices()/3,dispose:XI})}static ActiveBonesStrategy(){return e=>({id:"Active bones",getData:()=>e.getActiveBones(),dispose:XI})}static ActiveParticlesStrategy(){return e=>({id:"Active particles",getData:()=>e.getActiveParticles(),dispose:XI})}static DrawCallsStrategy(){return e=>{let t=0;const i=e.onBeforeAnimationsObservable.add((()=>{e.getEngine()._drawCalls.fetchNewFrame()})),r=e.onAfterRenderObservable.add((()=>{t=e.getEngine()._drawCalls.current}));return{id:"Draw calls",getData:()=>t,dispose:()=>{e.onBeforeAnimationsObservable.remove(i),e.onAfterRenderObservable.remove(r)}}}}static TotalLightsStrategy(){return e=>({id:"Total lights",getData:()=>e.lights.length,dispose:XI})}static TotalVerticesStrategy(){return e=>({id:"Total vertices",getData:()=>e.getTotalVertices(),dispose:XI})}static TotalMaterialsStrategy(){return e=>({id:"Total materials",getData:()=>e.materials.length,dispose:XI})}static TotalTexturesStrategy(){return e=>({id:"Total textures",getData:()=>e.textures.length,dispose:XI})}static AbsoluteFpsStrategy(){return e=>{const t=new Fv(e);return t.captureFrameTime=!0,{id:"Absolute FPS",getData:()=>1e3/t.frameTimeCounter.lastSecAverage,dispose:XI}}}static MeshesSelectionStrategy(){return e=>{let t=ai.j.Now,i=0;const r=e.onBeforeActiveMeshesEvaluationObservable.add((()=>{t=ai.j.Now})),s=e.onAfterActiveMeshesEvaluationObservable.add((()=>{i=ai.j.Now-t}));return{id:"Meshes Selection",getData:()=>i,dispose:()=>{e.onBeforeActiveMeshesEvaluationObservable.remove(r),e.onAfterActiveMeshesEvaluationObservable.remove(s)}}}}static RenderTargetsStrategy(){return e=>{let t=ai.j.Now,i=0;const r=e.onBeforeRenderTargetsRenderObservable.add((()=>{t=ai.j.Now})),s=e.onAfterRenderTargetsRenderObservable.add((()=>{i=ai.j.Now-t}));return{id:"Render Targets",getData:()=>i,dispose:()=>{e.onBeforeRenderTargetsRenderObservable.remove(r),e.onAfterRenderTargetsRenderObservable.remove(s)}}}}static ParticlesStrategy(){return e=>{let t=ai.j.Now,i=0;const r=e.onBeforeParticlesRenderingObservable.add((()=>{t=ai.j.Now})),s=e.onAfterParticlesRenderingObservable.add((()=>{i=ai.j.Now-t}));return{id:"Particles",getData:()=>i,dispose:()=>{e.onBeforeParticlesRenderingObservable.remove(r),e.onAfterParticlesRenderingObservable.remove(s)}}}}static SpritesStrategy(){return e=>{let t=ai.j.Now,i=0;const r=e.onBeforeSpritesRenderingObservable?.add((()=>{t=ai.j.Now})),s=e.onAfterSpritesRenderingObservable?.add((()=>{i=ai.j.Now-t}));return{id:"Sprites",getData:()=>i,dispose:()=>{e.onBeforeSpritesRenderingObservable?.remove(r),e.onAfterSpritesRenderingObservable?.remove(s)}}}}static AnimationsStrategy(){return e=>{let t=ai.j.Now,i=0;const r=e.onBeforeAnimationsObservable.add((()=>{t=ai.j.Now})),s=e.onAfterAnimationsObservable.add((()=>{i=ai.j.Now-t}));return{id:"Animations",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(r),e.onAfterAnimationsObservable.remove(s)}}}}static PhysicsStrategy(){return e=>{let t=ai.j.Now,i=0;const r=e.onBeforePhysicsObservable?.add((()=>{t=ai.j.Now})),s=e.onAfterPhysicsObservable?.add((()=>{i=ai.j.Now-t}));return{id:"Physics",getData:()=>i,dispose:()=>{e.onBeforePhysicsObservable?.remove(r),e.onAfterPhysicsObservable?.remove(s)}}}}static RenderStrategy(){return e=>{let t=ai.j.Now,i=0;const r=e.onBeforeDrawPhaseObservable.add((()=>{t=ai.j.Now})),s=e.onAfterDrawPhaseObservable.add((()=>{i=ai.j.Now-t}));return{id:"Render",getData:()=>i,dispose:()=>{e.onBeforeDrawPhaseObservable.remove(r),e.onAfterDrawPhaseObservable.remove(s)}}}}static FrameTotalStrategy(){return e=>{let t=ai.j.Now,i=0;const r=e.onBeforeAnimationsObservable.add((()=>{t=ai.j.Now})),s=e.onAfterRenderObservable.add((()=>{i=ai.j.Now-t}));return{id:"Frame Total",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(r),e.onAfterRenderObservable.remove(s)}}}}static InterFrameStrategy(){return e=>{let t=ai.j.Now,i=0;const r=e.onBeforeAnimationsObservable.add((()=>{i=ai.j.Now-t})),s=e.onAfterRenderObservable.add((()=>{t=ai.j.Now}));return{id:"Inter-frame",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(r),e.onAfterRenderObservable.remove(s)}}}}static GpuFrameTimeStrategy(){return e=>{const t=new Nv(e.getEngine());return t.captureGPUFrameTime=!0,{id:"GPU frame time",getData:()=>Math.max(1e-6*t.gpuFrameTimeCounter.current,0),dispose:()=>{t.dispose()}}}}}oi.Z.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new HI(this)),this._perfCollector};class YI{constructor(e,t){this._disableRenderingRefCount=0,this._currentPerformancePriorityMode=0,this._scene=e,this._engine=e.getEngine(),this._engine.isWebGPU&&(this._options={morphTargetsNumMaxInfluences:20,...t},this._engine.snapshotRenderingMode=1,this.fixMeshes(),this._onResizeObserver=this._engine.onResizeObservable.add((()=>{this.disableSnapshotRendering(),this.enableSnapshotRendering()})),this._scene.onBeforeRenderObservable.add((()=>{if(this._fastSnapshotRenderingEnabled){e.skeletons.forEach((e=>e.prepare(!0)));for(const t of e.meshes)if(t.infiniteDistance&&t.transferToEffect(t.computeWorldMatrix(!0)),t.skeleton&&t.transferToEffect(t.computeWorldMatrix(!0)),t.morphTargetManager&&t.subMeshes)for(const e of t.subMeshes){const i=e._drawWrapper,r=i.effect;if(r){const e=i.drawContext.buffers.LeftOver,s=r._pipelineContext?.uniformBuffer;e&&s&&s.setDataBuffer(e)&&(t.morphTargetManager._bind(r),(0,Bt.nR)(t,r),s.update())}}}})))}enableSnapshotRendering(){this._engine.isWebGPU&&(--this._disableRenderingRefCount>0||(this._disableRenderingRefCount=0,this._currentPerformancePriorityMode=this._pendingCurrentPerformancePriorityMode??this._scene.performancePriority,this._pendingCurrentPerformancePriorityMode=void 0,this._scene.performancePriority=0,this._scene.executeWhenReady((()=>{this._disableRenderingRefCount>0||this._executeAtFrame(this._engine.frameId+2,(()=>{this._engine.snapshotRendering=!0}))}))))}disableSnapshotRendering(){this._engine.isWebGPU&&(0===this._disableRenderingRefCount&&(this._scene.performancePriority=0,0!==this._currentPerformancePriorityMode&&(this._pendingCurrentPerformancePriorityMode=this._currentPerformancePriorityMode,this._scene.executeWhenReady((()=>{this._executeAtFrame(this._engine.frameId+2,(()=>{this._disableRenderingRefCount>0&&void 0!==this._pendingCurrentPerformancePriorityMode&&(this._scene.performancePriority=this._pendingCurrentPerformancePriorityMode),this._pendingCurrentPerformancePriorityMode=void 0}),!0)})))),this._engine.snapshotRendering=!1,this._disableRenderingRefCount++)}fixMeshes(e){if(this._engine.isWebGPU){e=e||this._scene.meshes;for(const t of e)t.ignoreCameraMaxZ=!1,t.morphTargetManager&&(t.morphTargetManager.numMaxInfluencers=Math.min(t.morphTargetManager.numTargets,this._options.morphTargetsNumMaxInfluences))}}updateMesh(e){if(this._fastSnapshotRenderingEnabled)if(Array.isArray(e))for(const t of e)t.transferToEffect(t.computeWorldMatrix(!0));else e.transferToEffect(e.computeWorldMatrix(!0))}updateMeshesForEffectLayer(e,t=!0){if(!this._engine.isWebGPU)return;const i=e.mainTexture.renderPassId;t?this._onBeforeRenderObserverUpdateLayer=this._scene.onBeforeRenderObservable.add((()=>{this._updateMeshMatricesForRenderPassId(i)})):this._updateMeshMatricesForRenderPassId(i)}dispose(){this._engine.isWebGPU&&(this._scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserverUpdateLayer),this._engine.onResizeObservable.remove(this._onResizeObserver))}get _fastSnapshotRenderingEnabled(){return this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode}_updateMeshMatricesForRenderPassId(e){if(!this._fastSnapshotRenderingEnabled)return;const t=this._scene.getTransformMatrix();for(let i=0;i{this._disableRenderingRefCount>0&&!i||0===this._disableRenderingRefCount&&i?this._engine.onEndFrameObservable.remove(r):this._engine.frameId>=e&&(this._engine.onEndFrameObservable.remove(r),t())}))}}z.cP.prototype.runCoroutineAsync=function(e){if(!this._coroutineScheduler){const e=function(e){const t=new Array,i=new Array,r=new Array,s=e.add((()=>{const e=t.length;for(let s=0;s{t.push(e),i.push(s),r.push(n)},dispose:()=>{e.remove(s)}}}(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return qe(e,this._coroutineScheduler)},z.cP.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};async function KI(e,t){const i=t.probe??new Kx("tempProbe",t.size,e),r=!!t.probe;r||(t.position?i.position=t.position.clone():e.activeCamera&&(i.position=e.activeCamera.position.clone()));const s=t.meshesFilter?e.meshes.filter(t.meshesFilter):e.meshes;i.renderList?.push(...s),i.refreshRate=ln.$.REFRESHRATE_RENDER_ONCE,i.cubeTexture.render();const n=new Kb("tempProceduralTexture","equirectangularPanorama",{width:2*t.size,height:t.size},e);return n.setTexture("cubeMap",i.cubeTexture),new Promise(((e,s)=>{n.onGeneratedObservable.addOnce((()=>{const o=n.readPixels();if(!o)return s(new Error("No Pixel Data found on procedural texture")),n.dispose(),void(r||i.dispose());o.then((s=>{n.dispose(),r||i.dispose(),t.filename?((0,UR.DumpData)(2*t.size,t.size,s,void 0,"image/png",t.filename),e(null)):e(s)}))}))}))}Cs.l.ShadersStore.equirectangularPanoramaPixelShader="#ifdef GL_ES\nprecision highp float;\n#endif\n#define M_PI 3.1415926535897932384626433832795\nvarying 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(\n- sin( longitude )*sin( latitude ),\ncos( latitude ),\n- cos( longitude )*sin( latitude )\n);normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}";class jI{constructor(){this._currentOperation=Promise.resolve()}lockAsync(e,t){t?.throwIfAborted();const i=t?()=>(t.throwIfAborted(),e()):e,r=this._currentOperation.then(i);return this._currentOperation=new Promise((e=>r.then((()=>e()),e))),r}static async LockAsync(e,t,i){if(i?.throwIfAborted(),0===t.length)return await e();const r=new uR;let s=0;return t.forEach((n=>n.lockAsync((async()=>(s++,s===t.length&&r.resolve(await e()),r.promise)),i).catch((e=>r.reject(e))))),r.promise}}var $I=i(64849),QI=i(32957),ZI=i(79388),JI=i(41572),eM=i(92224),tM=i(89517);class iM{constructor(e=Recast){this.bjsRECAST={},this.name="RecastJSPlugin",this._maximumSubStepCount=10,this._timeStep=1/60,this._timeFactor=1,this._worker=null,"function"==typeof e?Z.V.Error("RecastJS is not ready. Please make sure you await Recast() before using the plugin."):this.bjsRECAST=e,this.isSupported()?(this.setTimeStep(),this._tempVec1=new this.bjsRECAST.Vec3,this._tempVec2=new this.bjsRECAST.Vec3):Z.V.Error("RecastJS is not available. Please make sure you included the js file.")}setWorkerURL(e){return!(!window||!window.Worker||(this._worker=new Worker(e),0))}setTimeStep(e=1/60){this._timeStep=e}getTimeStep(){return this._timeStep}setMaximumSubStepCount(e=10){this._maximumSubStepCount=e}getMaximumSubStepCount(){return this._maximumSubStepCount}set timeFactor(e){this._timeFactor=Math.max(e,0)}get timeFactor(){return this._timeFactor}createNavMesh(e,t,i){let r,s,n;this._worker&&!i?Z.V.Warn("A worker is avaible but no completion callback. Defaulting to blocking navmesh creation"):!this._worker&&i&&Z.V.Warn("A completion callback is avaible but no worker. Defaulting to blocking navmesh creation"),this.navMesh=new this.bjsRECAST.NavMesh;const o=[],a=[];let l=0;for(r=0;r{this.update(.001*r.getEngine().getDeltaTime()*e.timeFactor)}))}addAgent(e,t,i){const r=new this.bjsRECASTPlugin.bjsRECAST.dtCrowdAgentParams;r.radius=t.radius,r.height=t.height,r.maxAcceleration=t.maxAcceleration,r.maxSpeed=t.maxSpeed,r.collisionQueryRange=t.collisionQueryRange,r.pathOptimizationRange=t.pathOptimizationRange,r.separationWeight=t.separationWeight,r.updateFlags=7,r.obstacleAvoidanceType=0,r.queryFilterType=0,r.userData=0;const s=this.recastCrowd.addAgent(new this.bjsRECASTPlugin.bjsRECAST.Vec3(e.x,e.y,e.z),r);return this.transforms.push(i),this.agents.push(s),this.reachRadii.push(t.reachRadius?t.reachRadius:t.radius),this._agentDestinationArmed.push(!1),this._agentDestination.push(new hc.Pq(0,0,0)),s}getAgentPosition(e){const t=this.recastCrowd.getAgentPosition(e);return new hc.Pq(t.x,t.y,t.z)}getAgentPositionToRef(e,t){const i=this.recastCrowd.getAgentPosition(e);t.set(i.x,i.y,i.z)}getAgentVelocity(e){const t=this.recastCrowd.getAgentVelocity(e);return new hc.Pq(t.x,t.y,t.z)}getAgentVelocityToRef(e,t){const i=this.recastCrowd.getAgentVelocity(e);t.set(i.x,i.y,i.z)}getAgentNextTargetPath(e){const t=this.recastCrowd.getAgentNextTargetPath(e);return new hc.Pq(t.x,t.y,t.z)}getAgentNextTargetPathToRef(e,t){const i=this.recastCrowd.getAgentNextTargetPath(e);t.set(i.x,i.y,i.z)}getAgentState(e){return this.recastCrowd.getAgentState(e)}overOffmeshConnection(e){return this.recastCrowd.overOffmeshConnection(e)}agentGoto(e,t){this.recastCrowd.agentGoto(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z));const i=this.agents.indexOf(e);i>-1&&(this._agentDestinationArmed[i]=!0,this._agentDestination[i].set(t.x,t.y,t.z))}agentTeleport(e,t){this.recastCrowd.agentTeleport(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z))}updateAgentParameters(e,t){const i=this.recastCrowd.getAgentParameters(e);void 0!==t.radius&&(i.radius=t.radius),void 0!==t.height&&(i.height=t.height),void 0!==t.maxAcceleration&&(i.maxAcceleration=t.maxAcceleration),void 0!==t.maxSpeed&&(i.maxSpeed=t.maxSpeed),void 0!==t.collisionQueryRange&&(i.collisionQueryRange=t.collisionQueryRange),void 0!==t.pathOptimizationRange&&(i.pathOptimizationRange=t.pathOptimizationRange),void 0!==t.separationWeight&&(i.separationWeight=t.separationWeight),this.recastCrowd.setAgentParameters(e,i)}removeAgent(e){this.recastCrowd.removeAgent(e);const t=this.agents.indexOf(e);t>-1&&(this.agents.splice(t,1),this.transforms.splice(t,1),this.reachRadii.splice(t,1),this._agentDestinationArmed.splice(t,1),this._agentDestination.splice(t,1))}getAgents(){return this.agents}update(e){if(this.bjsRECASTPlugin.navMesh.update(),e<=hc.bH)return;const t=this.bjsRECASTPlugin.getTimeStep(),i=this.bjsRECASTPlugin.getMaximumSubStepCount();if(t<=hc.bH)this.recastCrowd.update(e);else{let r=Math.floor(e/t);i&&r>i&&(r=i),r<1&&(r=1);const s=e/r;for(let e=0;eo&&i.ynew sM(e,t,i);class sM{get enableSceneOffline(){return this._enableSceneOffline}get enableTexturesOffline(){return this._enableTexturesOffline}constructor(e,t,i=!1){this._idbFactory="undefined"!=typeof indexedDB?indexedDB:void 0,this._currentSceneUrl=sM._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,sM.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,Ue.S0.SetImmediate((()=>{t(!0)}))):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){const t=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},i=()=>{try{if("function"==typeof URL&&0===this._currentSceneUrl.indexOf("http")){const e=new URL(this._currentSceneUrl);return e.pathname+=".manifest",e.toString()}}catch(e){}return`${this._currentSceneUrl}.manifest`};let r=!1,s=i();const n=new go.u;navigator.onLine&&(r=!0,s=s+(null==s.match(/\?/)?"?":"&")+Date.now()),n.open("GET",s),n.addEventListener("load",(()=>{if(200===n.status||sM._ValidateXHRData(n,1))try{const t=JSON.parse(n.response);this._enableSceneOffline=t.enableSceneOffline,this._enableTexturesOffline=t.enableTexturesOffline&&sM._IsUASupportingBlobStorage,t.version&&!isNaN(parseInt(t.version))&&(this._manifestVersionFound=t.version),e(!0)}catch(e){t()}else t()}),!1),n.addEventListener("error",(()=>{if(r){r=!1;const e=i();n.open("GET",e),n.send()}else t()}),!1);try{n.send()}catch(t){Z.V.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))if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;const t=this._idbFactory.open("babylonjs",1);t.onerror=()=>{i()},t.onblocked=()=>{Z.V.Error("IDB request blocked. Please reload the page."),i()},t.onsuccess=()=>{this._db=t.result,e()},t.onupgradeneeded=e=>{if(this._db=e.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(e){Z.V.Error("Error while creating object stores. Exception: "+e.message),i()}}}else this._isSupported=!1,t&&t()}loadImage(e,t){const i=sM._ReturnFullUrlLocation(e),r=()=>{this._hasReachedQuota||null===this._db?t.src=e:this._saveImageIntoDBAsync(i,t)};this._mustUpdateRessources?r():this._loadImageFromDBAsync(i,t,r)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&null!==this._db){let r;const s=this._db.transaction(["textures"]);s.onabort=()=>{t.src=e},s.oncomplete=()=>{let s;r&&"function"==typeof URL?(s=URL.createObjectURL(r.data),t.onerror=()=>{Z.V.Error("Error loading image from blob URL: "+s+" switching back to web url: "+e),t.src=e},t.src=s):i()};const n=s.objectStore("textures").get(e);n.onsuccess=e=>{r=e.target.result},n.onerror=()=>{Z.V.Error("Error loading texture "+e+" from DB."),t.src=e}}else Z.V.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t.src=e}_saveImageIntoDBAsync(e,t){let i;if(this._isSupported){const r=()=>{let e;if(i&&"function"==typeof URL)try{e=URL.createObjectURL(i)}catch(t){e=URL.createObjectURL(i)}e&&(t.src=e)};if(sM._IsUASupportingBlobStorage){const s=new go.u;s.open("GET",e),s.responseType="blob",s.addEventListener("load",(()=>{if(200===s.status&&this._db){i=s.response;const n=this._db.transaction(["textures"],"readwrite");n.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}r()},n.oncomplete=()=>{r()};const o={textureUrl:e,data:i};try{const e=n.objectStore("textures").put(o);e.onsuccess=()=>{},e.onerror=()=>{r()}}catch(i){25===i.code&&(sM._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e}),!1),s.addEventListener("error",(()=>{Z.V.Error("Error in XHR request in BABYLON.Database."),t.src=e}),!1),s.send()}else t.src=e}else Z.V.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t.src=e}_checkVersionFromDB(e,t){this._loadVersionFromDBAsync(e,t,(()=>{this._saveVersionIntoDBAsync(e,t)}))}_loadVersionFromDBAsync(e,t,i){if(this._isSupported&&this._db){let r;try{const s=this._db.transaction(["versions"]);s.oncomplete=()=>{r?this._manifestVersionFound!==r.data?(this._mustUpdateRessources=!0,i()):t(r.data):(this._mustUpdateRessources=!0,i())},s.onabort=()=>{t(-1)};const n=s.objectStore("versions").get(e);n.onsuccess=e=>{r=e.target.result},n.onerror=()=>{Z.V.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(e){Z.V.Error("Error while accessing 'versions' object store (READ OP). Exception: "+e.message),t(-1)}}else Z.V.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=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};const r={sceneUrl:e,data:this._manifestVersionFound},s=i.objectStore("versions").put(r);s.onsuccess=()=>{},s.onerror=()=>{Z.V.Error("Error in DB add version request in BABYLON.Database.")}}catch(e){Z.V.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+e.message),t(-1)}else t(-1)}loadFile(e,t,i,r,s){const n=sM._ReturnFullUrlLocation(e),o=()=>{this._saveFileAsync(n,t,i,s,r)};this._checkVersionFromDB(n,(e=>{-1!==e?this._mustUpdateRessources?this._saveFileAsync(n,t,i,s,r):this._loadFileAsync(n,t,o,i):r&&r()}))}_loadFileAsync(e,t,i,r){if(this._isSupported&&this._db){let s,n;s=-1!==e.indexOf(".babylon")?"scenes":"textures";const o=this._db.transaction([s]);o.oncomplete=()=>{if(n){if(r){const e=n.data?.byteLength||0;r({total:e,loaded:e,lengthComputable:!0})}t(n.data)}else i()},o.onabort=()=>{i()};const a=o.objectStore(s).get(e);a.onsuccess=e=>{n=e.target.result},a.onerror=()=>{Z.V.Error("Error loading file "+e+" from DB."),i()}}else Z.V.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,r,s){if(this._isSupported){let n;n=-1!==e.indexOf(".babylon")?"scenes":"textures";const o=new go.u;let a;o.open("GET",e+(null==e.match(/\?/)?"?":"&")+Date.now()),r&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",(()=>{if(200===o.status||o.status<400&&sM._ValidateXHRData(o,r?6:1))if(a=r?o.response:o.responseText,!this._hasReachedQuota&&this._db){const i=this._db.transaction([n],"readwrite");let r;i.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(a)},i.oncomplete=()=>{t(a)},r="scenes"===n?{sceneUrl:e,data:a,version:this._manifestVersionFound}:{textureUrl:e,data:a};try{const e=i.objectStore(n).put(r);e.onsuccess=()=>{},e.onerror=()=>{Z.V.Error("Error in DB add file request in BABYLON.Database.")}}catch(e){t(a)}}else t(a);else o.status>=400&&s?s(o):t()}),!1),o.addEventListener("error",(()=>{Z.V.Error("error on XHR request."),s&&s()}),!1),o.send()}else Z.V.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),s&&s()}static _ValidateXHRData(e,t=7){try{if(1&t){if(e.responseText&&e.responseText.length>0)return!0;if(1===t)return!1}if(2&t){const i=(0,BR.O_)(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){const t=new Uint8Array(e.response,0,3);return 68===t[0]&&68===t[1]&&83===t[2]}}catch(e){}return!1}}sM._IsUASupportingBlobStorage=!0,sM.IDBStorageEnabled=!1,sM._ParseURL=e=>{document.createElement("a").href=e;const t=e.substring(0,e.lastIndexOf("#")),i=e.substring(t.lastIndexOf("/")+1,e.length);return e.substring(0,e.indexOf(i,0))},sM._ReturnFullUrlLocation=e=>-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")&&"undefined"!=typeof window?sM._ParseURL(window.location.href)+e:e;class nM{_isUbo(e){return void 0!==e.addUniform}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))}}Cs.l.ShadersStore.gpuUpdateParticlesPixelShader="#version 300 es\nvoid main() {discard;}\n";Cs.l.ShadersStore.gpuUpdateParticlesVertexShader="#version 300 es\n#define PI 3.14159\nuniform float currentCount;uniform float timeDelta;uniform float stopFactor;\n#ifndef LOCAL\nuniform mat4 emitterWM;\n#endif\nuniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;uniform vec4 color2;\n#endif\nuniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;uniform float radiusRange;uniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;uniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;uniform float height;uniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;uniform float coneAngle;uniform vec2 height;\n#ifdef DIRECTEDCONEEMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\nin vec3 position;\n#ifdef CUSTOMEMITTER\nin vec3 initialPosition;\n#endif\nin float age;in float life;in vec4 seed;in vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;in vec3 noiseCoordinates2;\n#endif\nout vec3 outPosition;\n#ifdef CUSTOMEMITTER\nout vec3 outInitialPosition;\n#endif\nout float outAge;out float outLife;out vec4 outSeed;out vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;uniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec4 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;}\nvec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));}\nvoid main() {float newAge=age+timeDelta; \nif (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;\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 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; \n#elif defined(SPHEREEMITTER)\nvec3 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);\n#ifdef DIRECTEDSPHEREEMITTER\nnewDirection=normalize(direction1+(direction2-direction1)*randoms3);\n#else\nnewDirection=normalize(newPosition+directionRandomizer*randoms3);\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 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);\n#ifdef DIRECTEDCYLINDEREMITTER\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#else\nangle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.0001;\n#else\nfloat h=randoms2.y*height.y;h=1.-h*h; \n#endif\nfloat 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); \nvec3 randoms3=getRandomVec3(seed.z);\n#ifdef DIRECTEDCONEEMITTER\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#else\nif (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {newDirection=normalize(newPosition+directionRandomizer*randoms3); }\n#endif\n#elif defined(CUSTOMEMITTER)\nnewPosition=initialPosition;outInitialPosition=initialPosition;\n#else \nnewPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\n#ifdef LOCAL\noutPosition=newPosition;\n#else\noutPosition=(emitterWM*vec4(newPosition,1.)).xyz;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#ifndef BILLBOARD \noutInitialDirection=direction;\n#endif\n#else\n#ifdef LOCAL\nvec3 initial=newDirection;\n#else \nvec3 initial=(emitterWM*vec4(newDirection,0.)).xyz;\n#endif\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#if defined(CUSTOMEMITTER)\noutPosition=position+(direction-position)*ageGradient; \noutInitialPosition=initialPosition;\n#else\noutPosition=position+direction*directionScale;\n#endif\noutLife=life;outSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#else\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nfloat 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;\n#endif \n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;float dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset;\n#else\nfloat cellStartOffset=0.;\n#endif \nfloat ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);}\nelse {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);}\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}}";class oM{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(){return this._updateEffect?.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 cI&&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 Cl.M("gpuUpdateParticles",this._updateEffectOptions,this._engine),new nM(this._updateEffect)}createVertexBuffers(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null),this._renderVertexBuffers=t}createParticleBuffer(e){return e}bindDrawBuffers(e,t,i){i?this._engine.bindBuffers(this._renderVertexBuffers,i,t):this._engine.bindVertexArrayObject(this._renderVAO[e],null)}preUpdateParticleBuffer(){const e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw new Error("GPU particles cannot work without a full Engine. ThinEngine is not supported")}updateParticleBuffer(e,t,i){this._updateEffect.setTexture("randomSampler",this._parent._randomTexture),this._updateEffect.setTexture("randomSampler2",this._parent._randomTexture2),this._parent._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateEffect.setTexture("limitVelocityGradientSampler",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateEffect.setTexture("dragGradientSampler",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateEffect.setTexture("noiseSampler",this._parent.noiseTexture),this._engine.bindVertexArrayObject(this._updateVAO[e],null);const r=this._engine;r.bindTransformFeedbackBuffer(t.getBuffer()),r.setRasterizerState(!1),r.beginTransformFeedback(!0),r.drawArraysType(3,0,i),r.endTransformFeedback(),r.setRasterizerState(!0),r.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;e{this.start(0)}),e):(this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop))}stop(){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0)}reset(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0}getClassName(){return"GPUParticleSystem"}getCustomEffect(e=0){return this._customWrappers[e]?.effect??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new gt.E(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new z.cP),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"gpuRenderParticles"}get vertexBuffers(){return this._renderVertexBuffers[1^this._targetIndex]}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 $R(e,t);return this._colorGradients.push(i),this._refreshColorGradient(!0),this._releaseBuffers(),this}_refreshColorGradient(e=!1){this._colorGradients&&(e&&this._colorGradients.sort(((e,t)=>e.gradientt.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(){for(const e in this._drawWrappers){const t=this._drawWrappers[e];t.drawContext?.reset()}}_addFactorGradient(e,t,i){const r=new ZR(t,i);e.push(r),this._releaseBuffers()}addSizeGradient(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this}removeSizeGradient(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this}_refreshFactorGradient(e,t,i=!1){if(!e)return;i&&e.sort(((e,t)=>e.gradientt.gradient?1:0));const r=this;r[t]&&(r[t].dispose(),r[t]=null)}addAngularSpeedGradient(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this}removeAngularSpeedGradient(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this}addVelocityGradient(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this}removeVelocityGradient(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this}addLimitVelocityGradient(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this}removeLimitVelocityGradient(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this}addDragGradient(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this}removeDragGradient(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this}addEmitRateGradient(){return this}removeEmitRateGradient(){return this}addStartSizeGradient(){return this}removeStartSizeGradient(){return this}addColorRemapGradient(){return this}removeColorRemapGradient(){return this}addAlphaRemapGradient(){return this}removeAlphaRemapGradient(){return this}addRampGradient(){return this}removeRampGradient(){return this}getRampGradients(){return null}get useRampGradients(){return!1}set useRampGradients(e){}addLifeTimeGradient(){return this}removeLifeTimeGradient(){return this}constructor(e,t,i,r=null,s=!1){if(super(e),this.layerMask=268435455,this._accumulatedCount=0,this._renderVertexBuffers=[],this._targetIndex=0,this._currentRenderId=-1,this._currentRenderingCameraUniqueId=-1,this._started=!1,this._stopped=!1,this._timeDelta=0,this.updateInAnimate=!1,this._actualFrame=0,this._rawTextureWidth=256,this._rebuildingAfterContextLost=!1,this.onDisposeObservable=new z.cP,this.onStoppedObservable=new z.cP,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=W.uq.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||he.q.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().supportComputeShaders){if(!(0,X.n9)("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new((0,X.n9)("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!(0,X.n9)("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new((0,X.n9)("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new gt.E(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers={0:new gt.E(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._createIndexBuffer(),this._attachImageProcessingConfiguration(null),(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=s,this.particleEmitterType=new sI;const a=Math.min(this._engine.getCaps().maxTextureSize,n.randomTextureSize);let l=[];for(let e=0;e0;)i.push(0)}const o=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),a=this._platform.createParticleBuffer(i),l=this._platform.createParticleBuffer(i);this._buffer0=new st.h(t,a,!1,this._attributesStrideSize),this._buffer1=new st.h(t,l,!1,this._attributesStrideSize),this._spriteBuffer=new st.h(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+="\n#define BILLBOARD"),this._colorGradientsTexture&&(e+="\n#define COLORGRADIENTS"),this._sizeGradientsTexture&&(e+="\n#define SIZEGRADIENTS"),this._angularSpeedGradientsTexture&&(e+="\n#define ANGULARSPEEDGRADIENTS"),this._velocityGradientsTexture&&(e+="\n#define VELOCITYGRADIENTS"),this._limitVelocityGradientsTexture&&(e+="\n#define LIMITVELOCITYGRADIENTS"),this._dragGradientsTexture&&(e+="\n#define DRAGGRADIENTS"),this.isAnimationSheetEnabled&&(e+="\n#define ANIMATESHEET",this.spriteRandomStartCell&&(e+="\n#define ANIMATESHEETRANDOMSTART")),this.noiseTexture&&(e+="\n#define NOISE"),this.isLocal&&(e+="\n#define LOCAL"),this._platform.isUpdateBufferCreated()&&this._cachedUpdateDefines===e||(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e)),this._platform.isUpdateBufferReady()}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t?.effect)return t;const i=[];this.fillDefines(i,e);let r=this._drawWrappers[e];r||(r=new gt.E(this._engine),r.drawContext&&(r.drawContext.useInstancing=!0),this._drawWrappers[e]=r);const s=i.join("\n");if(r.defines!==s){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),r.setEffect(this._engine.createEffect("gpuRenderParticles",e,t,i,s),s)}return r}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,r=!1){const s=[st.R.PositionKind,"age","life","size","angle"];return e||s.push(st.R.ColorKind),t&&s.push("cellIndex"),i||s.push("initialDirection"),r&&s.push("direction"),s.push("offset",st.R.UVKind),s}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const r=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return(0,Ln.TV)(r),e&&r.push("sheetInfos"),t&&r.push("logarithmicDepthConstant"),i&&(r.push("vFogInfos"),r.push("vFogColor")),r}fillDefines(e,t=0,i=!0){if(this._scene&&((0,Ln.tv)(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&this._scene.fogMode!==oi.Z.FOGMODE_NONE&&e.push("#define FOG")),t===AI.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 AI.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case AI.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case AI.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._colorGradientsTexture&&e.push("#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),i&&this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(""+this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...lM._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===AI.BILLBOARDMODE_STRETCHED)),e.push(...lM._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(gn.p.PrepareUniforms(e,this._imageProcessingConfigurationDefines),gn.p.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:this._scene?.getAnimationRatio()||1),this._actualFrame+=this._timeDelta,this._stopped||this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop(),this.updateInAnimate&&this._update()}_createFactorGradientTexture(e,t){const i=this[t];if(!e||!e.length||i)return;const r=new Float32Array(this._rawTextureWidth);for(let t=0;t{r[t]=(0,ar.Lerp)(e.factor1,i.factor1,s)}))}this[t]=xi.CreateRTexture(r,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1),this[t].name=t.substring(1)}_createSizeGradientTexture(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")}_createAngularSpeedGradientTexture(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")}_createVelocityGradientTexture(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")}_createLimitVelocityGradientTexture(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")}_createDragGradientTexture(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")}_createColorGradientTexture(){if(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)return;const e=new Uint8Array(4*this._rawTextureWidth),t=H.IG.Color4[0];for(let i=0;i{H.ov.LerpToRef(r.color1,s.color1,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255*t.a}))}this._colorGradientsTexture=xi.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){const i=this._getWrapper(e),r=i.effect;this._engine.enableEffect(i);const s=this._scene?.getViewMatrix()||W.uq.IdentityReadOnly;if(r.setMatrix("view",s),r.setMatrix("projection",this.defaultProjectionMatrix??this._scene.getProjectionMatrix()),r.setTexture("diffuseSampler",this.particleTexture),r.setVector2("translationPivot",this.translationPivot),r.setVector3("worldOffset",this.worldOffset),this.isLocal&&r.setMatrix("emitterWM",t),this._colorGradientsTexture?r.setTexture("colorGradientSampler",this._colorGradientsTexture):r.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){const e=this.particleTexture.getBaseSize();r.setFloat3("sheetInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,e.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){const e=this._scene.activeCamera;r.setVector3("eyePosition",e.globalPosition)}const n=r.defines;if(this._scene&&((0,Ln.gS)(r,this,this._scene),this.applyFog&&(0,Bt.Yy)(this._scene,void 0,r)),n.indexOf("#define BILLBOARDMODE_ALL")>=0){const e=s.clone();e.invert(),r.setMatrix("invView",e)}switch(this.useLogarithmicDepth&&this._scene&&(0,Bt.DL)(n,r,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(r),e){case AI.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case AI.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case AI.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case AI.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4)}return this._platform.bindDrawBuffers(this._targetIndex,r,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(r),this._scene?.forceWireframe?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),this._scene?.forceWireframe&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer)return;if(!this._recreateUpdateEffect()||this._rebuildingAfterContextLost)return;if(!e)if(this.emitter.position)e=this.emitter.getWorldMatrix();else{const t=this.emitter;e=W.AA.Matrix[0],W.uq.TranslationToRef(t.x,t.y,t.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++,2===this._targetIndex&&(this._targetIndex=0);const t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){if(!this._started)return 0;if(!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let e=0;e1){const e=0|this._accumulatedCount;this._accumulatedCount-=e,this._currentActiveCount+=e}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 e=this.emitter;i=W.AA.Matrix[0],W.uq.TranslationToRef(e.x,e.y,e.z,i)}const r=this._engine;this.updateInAnimate||this._update(i);let s=0;return e||t||(r.setState(!1),this.forceDepthWrite&&r.setDepthWrite(!0),s=this.blendMode===AI.BLENDMODE_MULTIPLYADD?this._render(AI.BLENDMODE_MULTIPLY,i)+this._render(AI.BLENDMODE_ADD,i):this._render(this.blendMode,i),this._engine.setAlphaMode(0)),s}rebuild(){const e=()=>{this._recreateUpdateEffect()&&this._platform.isUpdateBufferReady()?(this._initialize(!0),this._rebuildingAfterContextLost=!1):setTimeout(e,10)};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 e in this._drawWrappers)this._drawWrappers[e].dispose();if(this._drawWrappers={},this._scene){const e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let e=0;e0?s.shaderOptions.defines.join("\n"):"";r[0]=n.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e,void 0,void 0,void 0,this)}const o=this.serialize(i),a=lM.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=s,a._customWrappers=r,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,a}serialize(e=!1){const t={};return AI._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,r=!1,s){const n=e.name;let o,a;t instanceof Ot.$?o=t:(a=t,o=a.getEngine());const l=new lM(n,{capacity:s||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(l._rootUrl=i,e.customShader&&o.createEffectForParticles){const t=e.customShader,i=t.shaderOptions.defines.length>0?t.shaderOptions.defines.join("\n"):"",r=o.createEffectForParticles(t.shaderPath.fragmentElement,t.shaderOptions.uniforms,t.shaderOptions.samplers,i,void 0,void 0,void 0,l);l.setCustomEffect(r,0),l.customShader=t}return e.id&&(l.id=e.id),e.activeParticleCount&&(l.activeParticleCount=e.activeParticleCount),AI._Parse(e,l,t,i),e.preventAutoStart&&(l.preventAutoStart=e.preventAutoStart),r||l.preventAutoStart||l.start(),l}}class hM{constructor(){this._emitterNodeIsOwned=!0,this.systems=[]}get emitterNode(){return this._emitterNode}set emitterNode(e){this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1);for(const t of this.systems)t.emitter=e;this._emitterNode=e}setEmitterAsSphere(e,t,i){this._emitterNodeIsOwned&&this._emitterNode&&this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!0,this._emitterCreationOptions={kind:"Sphere",options:e,renderingGroupId:t};const r=Qo("emitterSphere",{diameter:e.diameter,segments:e.segments},i);r.renderingGroupId=t;const s=new Un("emitterSphereMaterial",i);s.emissiveColor=e.color,r.material=s;for(const e of this.systems)e.emitter=r;this._emitterNode=r}start(e){for(const t of this.systems)e&&(t.emitter=e),t.start()}dispose(){for(const e of this.systems)e.dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)}serialize(e=!1){const t={systems:[]};for(const i of this.systems)t.systems.push(i.serialize(e));return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t}static Parse(e,t,i=!1,r){const s=new hM,n=this.BaseAssetsUrl+"/textures/";t=t||he.q.LastCreatedScene;for(const o of e.systems)s.systems.push(i?lM.Parse(o,t,n,!0,r):AI.Parse(o,t,n,!0,r));if(e.emitter){const i=e.emitter.options;"Sphere"===e.emitter.kind&&s.setEmitterAsSphere({diameter:i.diameter,segments:i.segments,color:H.v9.FromArray(i.color)},e.emitter.renderingGroupId,t)}return s}}hM.BaseAssetsUrl="https://assets.babylonjs.com/particles";class cM{static CreateDefault(e,t=500,i,r=!1){let s;return s=r?new lM("default system",{capacity:t},i):new AI("default system",t,i),s.emitter=e,s.particleTexture=new vi.g("https://assets.babylonjs.com/textures/flare.png",s.getScene()),s.createConeEmitter(.1,Math.PI/4),s.color1=new H.ov(1,1,1,1),s.color2=new H.ov(1,1,1,1),s.colorDead=new H.ov(1,1,1,0),s.minSize=.1,s.maxSize=.1,s.minEmitPower=2,s.maxEmitPower=2,s.updateSpeed=1/60,s.emitRate=30,s}static CreateAsync(e,t,i=!1,r){t||(t=he.q.LastCreatedScene);const s={};return t.addPendingData(s),new Promise(((n,o)=>{if(i&&!lM.IsSupported)return t.removePendingData(s),o("Particle system with GPU is not supported.");Ue.S0.LoadFile(`${cM.BaseAssetsUrl}/systems/${e}.json`,(e=>{t.removePendingData(s);const o=JSON.parse(e.toString());return n(hM.Parse(o,t,i,r))}),void 0,void 0,void 0,(()=>(t.removePendingData(s),o(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`))))}))}static ExportSet(e){const t=new hM;for(const i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,r=!1,s="",n){return new Promise(((o,a)=>{const l=new go.u;l.addEventListener("readystatechange",(()=>{if(4==l.readyState)if(200==l.status){const t=JSON.parse(l.responseText);let a;a=r?lM.Parse(t,i,s,!1,n):AI.Parse(t,i,s,!1,n),e&&(a.name=e),o(a)}else a("Unable to load the particle system")})),l.open("GET",t),l.send()}))}static ParseFromSnippetAsync(e,t,i=!1,r="",s){if("_BLANK"===e){const e=this.CreateDefault(null);return e.start(),Promise.resolve(e)}return new Promise(((n,o)=>{const a=new go.u;a.addEventListener("readystatechange",(()=>{if(4==a.readyState)if(200==a.status){const o=JSON.parse(JSON.parse(a.responseText).jsonPayload),l=JSON.parse(o.particleSystem);let h;h=i?lM.Parse(l,t,r,!1,s):AI.Parse(l,t,r,!1,s),h.snippetId=e,n(h)}else o("Unable to load the snippet "+e)})),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()}))}}cM.BaseAssetsUrl=hM.BaseAssetsUrl,cM.SnippetUrl="https://snippet.babylonjs.com",cM.CreateFromSnippetAsync=cM.ParseFromSnippetAsync,ci(Ut.v.NAME_PARTICLESYSTEM,((e,t,i,r)=>{const s=fi(Ut.v.NAME_PARTICLESYSTEM);if(s&&void 0!==e.particleSystems&&null!==e.particleSystems)for(let n=0,o=e.particleSystems.length;ne.activeParticleCount?lM.Parse(e,t,i):AI.Parse(e,t,i))),Ot.$.prototype.createEffectForParticles=function(e,t=[],r=[],s="",n,o,a,l,h=0){let c=[],u=[];const d=[];return l?l.fillUniformsAttributesAndSamplerNames(u,c,d):(c=AI._GetAttributeNamesOrOptions(),u=AI._GetEffectCreationOptions()),-1===s.indexOf(" BILLBOARD")&&(s+="\n#define BILLBOARD\n"),l?.isAnimationSheetEnabled&&-1===s.indexOf(" ANIMATESHEET")&&(s+="\n#define ANIMATESHEET\n"),-1===r.indexOf("diffuseSampler")&&r.push("diffuseSampler"),this.createEffect({vertex:l?.vertexShaderName??"particles",fragmentElement:e},c,u.concat(t),d.concat(r),s,n,o,a,void 0,h,(async()=>{0===h?await Promise.resolve().then(i.bind(i,70917)):await Promise.resolve().then(i.bind(i,25806))}))},Yt.prototype.getEmittedParticleSystems=function(){const e=[];for(let t=0;tt.sqDistance-e.sqDistance,this._materialSortFunction=(e,t)=>e.materialIndex-t.materialIndex,this._autoUpdateSubMeshes=!1,this._recomputeInvisibles=!1,this.name=e,this._scene=t||he.q.LastCreatedScene,this._camera=t.activeCamera,this._pickable=!!i&&i.isPickable,this._depthSort=!!i&&i.enableDepthSort,this._multimaterialEnabled=!!i&&i.enableMultiMaterial,this._useModelMaterial=!!i&&i.useModelMaterial,this._multimaterialEnabled=!!this._useModelMaterial||this._multimaterialEnabled,this._expandable=!!i&&i.expandable,this._particlesIntersect=!!i&&i.particleIntersection,this._bSphereOnly=!!i&&i.boundingSphereOnly,this._bSphereRadiusFactor=i&&i.bSphereRadiusFactor?i.bSphereRadiusFactor:1,this._computeBoundingBox=!!i?.computeBoundingBox&&i.computeBoundingBox,this._autoFixFaceOrientation=!!i?.autoFixFaceOrientation&&i.autoFixFaceOrientation,i&&void 0!==i.updatable?this._updatable=i.updatable:this._updatable=!0,this._pickable&&(this.pickedBySubMesh=[[]],this.pickedParticles=this.pickedBySubMesh[0]),(this._depthSort||this._multimaterialEnabled)&&(this.depthSortedParticles=[]),this._multimaterialEnabled&&(this._multimaterial=new kt(this.name+"MultiMaterial",this._scene),this._materials=[],this._materialIndexesById={}),this._tmpVertex=new pM}buildMesh(){if(!this._isNotBuilt&&this.mesh)return this.mesh;if(0===this.nbParticles&&!this.mesh){const e=da("",{radius:1,tessellation:3},this._scene);this.addShape(e,1),e.dispose()}if(this._indices32=this._needs32Bits?new Uint32Array(this._indices):new Uint16Array(this._indices),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors),!this.mesh){const e=new Yt(this.name,this._scene);this.mesh=e}!this._updatable&&this._multimaterialEnabled&&this._sortParticlesByMaterial(),this.recomputeNormals&&bt.ComputeNormals(this._positions32,this._indices32,this._normals),this._normals32=new Float32Array(this._normals),this._fixedNormal32=new Float32Array(this._normals),this._mustUnrotateFixedNormals&&this._unrotateFixedNormals();const e=new bt;if(e.indices=this._depthSort?this._indices:this._indices32,e.set(this._positions32,st.R.PositionKind),e.set(this._normals32,st.R.NormalKind),this._uvs32.length>0&&e.set(this._uvs32,st.R.UVKind),this._colors32.length>0&&e.set(this._colors32,st.R.ColorKind),e.applyToMesh(this.mesh,this._updatable),this.mesh.isPickable=this._pickable,this._pickable){let e=0;for(let t=0;td?d:r,i=Math.round(d/r),s=0):i=i>d?d:i;const f=[],p=[],_=[],m=[],g=[],v=W.Pq.Zero(),x=i;for(;ud-i&&(i=d-u),f.length=0,p.length=0,_.length=0,m.length=0,g.length=0;let t=0;for(let e=3*u;e<3*(u+i);e++){_.push(t);const i=o[e],r=3*i;if(f.push(n[r],n[r+1],n[r+2]),p.push(h[r],h[r+1],h[r+2]),a){const e=2*i;m.push(a[e],a[e+1])}if(l){const e=4*i;g.push(l[e],l[e+1],l[e+2],l[e+3])}t++}let r=this.nbParticles;const b=this._posToShape(f),S=this._uvsToShapeUV(m),T=_.slice(),C=g.slice(),y=p.slice();let E;for(v.copyFromFloats(0,0,0),E=0;E65535&&(this._needs32Bits=!0)}if(this._depthSort||this._multimaterialEnabled){const e=null!==b.materialIndex?b.materialIndex:0;this.depthSortedParticles.push(new fM(d,t,s.length,e))}return b}_posToShape(e){const t=[];for(let i=0;i=this.nbParticles||!this._updatable)return[];const r=this.particles,s=this.nbParticles;if(t=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(0!=e||t!=this.nbParticles-1)){const e=this.mesh.getBoundingInfo();e&&(v.copyFrom(e.minimum),x.copyFrom(e.maximum))}P=this.particles[e]._pos;const D=P/3|0;R=4*D,M=2*D;for(let i=e;i<=t;i++){const e=this.particles[i];this.updateParticle(e);const t=e._model._shape,s=e._model._shapeUV,c=e._rotationMatrix,u=e.position,D=e.rotation,w=e.scaling,N=e._globalPosition;if(f){const t=this.depthSortedParticles[i];t.idx=e.idx,t.ind=e._ind,t.indicesLength=e._model._indicesLength,t.sqDistance=W.Pq.DistanceSquared(e.position,b)}if(e.alive&&(!e._stillInvisible||e.isVisible||this._recomputeInvisibles)){if(e.isVisible){e._stillInvisible=!1;const i=p[12];if(e.pivot.multiplyToRef(w,i),this.billboard&&(D.x=0,D.y=0),(this._computeParticleRotation||this.billboard)&&e.getRotationMatrix(r),null!==e.parentId){const t=this.getParticleById(e.parentId);if(t){const e=t._rotationMatrix,i=t._globalPosition,s=u.x*e[1]+u.y*e[4]+u.z*e[7],n=u.x*e[0]+u.y*e[3]+u.z*e[6],o=u.x*e[2]+u.y*e[5]+u.z*e[8];if(N.x=i.x+n,N.y=i.y+s,N.z=i.z+o,this._computeParticleRotation||this.billboard){const t=r.m;c[0]=t[0]*e[0]+t[1]*e[3]+t[2]*e[6],c[1]=t[0]*e[1]+t[1]*e[4]+t[2]*e[7],c[2]=t[0]*e[2]+t[1]*e[5]+t[2]*e[8],c[3]=t[4]*e[0]+t[5]*e[3]+t[6]*e[6],c[4]=t[4]*e[1]+t[5]*e[4]+t[6]*e[7],c[5]=t[4]*e[2]+t[5]*e[5]+t[6]*e[8],c[6]=t[8]*e[0]+t[9]*e[3]+t[10]*e[6],c[7]=t[8]*e[1]+t[9]*e[4]+t[10]*e[7],c[8]=t[8]*e[2]+t[9]*e[5]+t[10]*e[8]}}else e.parentId=null}else if(N.x=u.x,N.y=u.y,N.z=u.z,this._computeParticleRotation||this.billboard){const e=r.m;c[0]=e[0],c[1]=e[1],c[2]=e[2],c[3]=e[4],c[4]=e[5],c[5]=e[6],c[6]=e[8],c[7]=e[9],c[8]=e[10]}const n=p[11];for(e.translateFromPivot?n.setAll(0):n.copyFrom(i),O=0;O0)for(let t=0;t(this._isReady=!0,this._buildMesh(e))))}_buildMesh(e){0===this.nbParticles&&this.addPoints(1),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors);const t=new bt;t.set(this._positions32,st.R.PositionKind),this._uvs32.length>0&&t.set(this._uvs32,st.R.UVKind);let i=0;this._colors32.length>0&&(i=1,t.set(this._colors32,st.R.ColorKind));const r=new Yt(this.name,this._scene);t.applyToMesh(r,this._updatable),this.mesh=r,this._positions=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0);let s=e;return s||(s=new Un("point cloud material",this._scene),s.emissiveColor=new hc.v9(i,i,i),s.disableLighting=!0,s.pointsCloud=!0,s.pointSize=this._size),r.material=s,new Promise((e=>e(r)))}_addParticle(e,t,i,r){const s=new mM(e,t,i,r,this);return this.particles.push(s),s}_randomUnitVector(e){e.position=new W.Pq(Math.random(),Math.random(),Math.random()),e.color=new hc.ov(1,1,1,1)}_getColorIndicesForCoord(e,t,i,r){const s=e._groupImageData,n=i*(4*r)+4*t,o=[n,n+1,n+2,n+3],a=o[1],l=o[2],h=o[3],c=s[o[0]],u=s[a],d=s[l],f=s[h];return new hc.ov(c/255,u/255,d/255,f)}_setPointsColorOrUV(e,t,i,r,s,n,o,a){a=a??0,i&&e.updateFacetData();const l=2*e.getBoundingInfo().boundingSphere.radius;let h=e.getVerticesData(st.R.PositionKind);const c=e.getIndices(),u=e.getVerticesData(st.R.UVKind+(a?a+1:"")),d=e.getVerticesData(st.R.ColorKind),f=W.Pq.Zero();e.computeWorldMatrix();const p=e.getWorldMatrix();if(!p.isIdentity()){h=h.slice(0);for(let e=0;e1&&(Pe=1),Ae<0&&(Ae=0),Ae>1&&(Ae=1),hc.v9.HSVtoRGBToRef(Ee,Pe,Ae,Me),de.set(Me.r,Me.g,Me.b,1)):de=re.set(Math.random(),Math.random(),Math.random(),1),De.color=new hc.ov(de.x,de.y,de.z,de.w),this._colors.push(de.x,de.y,de.z,de.w))}}_colorFromTexture(e,t,i){if(null===e.material)return Z.V.Warn(e.name+"has no material."),t._groupImageData=null,void this._setPointsColorOrUV(e,t,i,!0,!1);const r=e.material.getActiveTextures();if(0===r.length)return Z.V.Warn(e.name+"has no usable texture."),t._groupImageData=null,void this._setPointsColorOrUV(e,t,i,!0,!1);const s=e.clone();s.setEnabled(!1),this._promises.push(new Promise((e=>{js.t.WhenAllReady(r,(()=>{let n=t._textureNb;n<0&&(n=0),n>r.length-1&&(n=r.length-1);const o=()=>{t._groupImgWidth=r[n].getSize().width,t._groupImgHeight=r[n].getSize().height,this._setPointsColorOrUV(s,t,i,!0,!0,void 0,void 0,r[n].coordinatesIndex),s.dispose(),e()};t._groupImageData=null;const a=r[n].readPixels();a?a.then((e=>{t._groupImageData=e,o()})):o()}))})))}_calculateDensity(e,t,i){let r,s,n,o,a,l,h,c,u,d,f,p;const _=W.Pq.Zero(),m=W.Pq.Zero(),g=W.Pq.Zero(),v=W.Pq.Zero(),x=W.Pq.Zero(),b=W.Pq.Zero();let S;const T=[];let C=0;const y=i.length/3;for(let e=0;e0;e--){const t=T[e];if(0===t)E[e]=0;else{const i=(t-T[e-1])/t*P,r=Math.floor(i),s=i-r,n=r+Number(Math.random()3)&&(n=0);const o=e.getVerticesData(st.R.PositionKind),a=e.getIndices();this._groups.push(this._groupCounter);const l=new gM(this._groupCounter,null);switch(l._groupDensity=this._calculateDensity(t,o,a),2===n?l._textureNb=r||0:r=r||new hc.ov(1,1,1,1),n){case 2:this._colorFromTexture(e,l,!1);break;case 1:this._setPointsColorOrUV(e,l,!1,!1,!1);break;case 0:this._setPointsColorOrUV(e,l,!1);break;case 3:this._setPointsColorOrUV(e,l,!1,void 0,void 0,r,s)}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}addVolumePoints(e,t,i,r,s){let n=i||0;(isNaN(n)||n<0||n>3)&&(n=0);const o=e.getVerticesData(st.R.PositionKind),a=e.getIndices();this._groups.push(this._groupCounter);const l=new gM(this._groupCounter,null);switch(l._groupDensity=this._calculateDensity(t,o,a),2===n?l._textureNb=r||0:r=r||new hc.ov(1,1,1,1),n){case 2:this._colorFromTexture(e,l,!0);break;case 1:this._setPointsColorOrUV(e,l,!0,!1,!1);break;case 0:this._setPointsColorOrUV(e,l,!0);break;case 3:this._setPointsColorOrUV(e,l,!0,void 0,void 0,r,s)}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}setParticles(e=0,t=this.nbParticles-1,i=!0){if(!this._updatable||!this._isReady)return this;this.beforeUpdateParticles(e,t,i);const r=W.AA.Matrix[0],s=this.mesh,n=this._colors32,o=this._positions32,a=this._uvs32,l=W.AA.Vector3,h=l[5].copyFromFloats(1,0,0),c=l[6].copyFromFloats(0,1,0),u=l[7].copyFromFloats(0,0,1),d=l[8].setAll(Number.MAX_VALUE),f=l[9].setAll(-Number.MAX_VALUE);W.uq.IdentityToRef(r);let p=0;if(this.mesh?.isFacetDataEnabled&&(this._computeBoundingBox=!0),t=t>=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(0!=e||t!=this.nbParticles-1)){const e=this.mesh?.getBoundingInfo();e&&(d.copyFrom(e.minimum),f.copyFrom(e.maximum))}p=0;let _=0,m=0,g=0;for(let i=e;i<=t;i++){const e=this.particles[i];p=e.idx,_=3*p,m=4*p,g=2*p,this.updateParticle(e);const t=e._rotationMatrix,s=e.position,n=e._globalPosition;if(this._computeParticleRotation&&e.getRotationMatrix(r),null!==e.parentId){const i=this.particles[e.parentId],o=i._rotationMatrix,a=i._globalPosition,l=s.x*o[1]+s.y*o[4]+s.z*o[7],h=s.x*o[0]+s.y*o[3]+s.z*o[6],c=s.x*o[2]+s.y*o[5]+s.z*o[8];if(n.x=a.x+h,n.y=a.y+l,n.z=a.z+c,this._computeParticleRotation){const e=r.m;t[0]=e[0]*o[0]+e[1]*o[3]+e[2]*o[6],t[1]=e[0]*o[1]+e[1]*o[4]+e[2]*o[7],t[2]=e[0]*o[2]+e[1]*o[5]+e[2]*o[8],t[3]=e[4]*o[0]+e[5]*o[3]+e[6]*o[6],t[4]=e[4]*o[1]+e[5]*o[4]+e[6]*o[7],t[5]=e[4]*o[2]+e[5]*o[5]+e[6]*o[8],t[6]=e[8]*o[0]+e[9]*o[3]+e[10]*o[6],t[7]=e[8]*o[1]+e[9]*o[4]+e[10]*o[7],t[8]=e[8]*o[2]+e[9]*o[5]+e[10]*o[8]}}else if(n.x=0,n.y=0,n.z=0,this._computeParticleRotation){const e=r.m;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[4],t[4]=e[5],t[5]=e[6],t[6]=e[8],t[7]=e[9],t[8]=e[10]}const a=l[11];e.translateFromPivot?a.setAll(0):a.copyFrom(e.pivot);const v=l[0];v.copyFrom(e.position);const x=v.x-e.pivot.x,b=v.y-e.pivot.y,S=v.z-e.pivot.z;let T=x*t[0]+b*t[3]+S*t[6],C=x*t[1]+b*t[4]+S*t[7],y=x*t[2]+b*t[5]+S*t[8];T+=a.x,C+=a.y,y+=a.z;const E=o[_]=n.x+h.x*T+c.x*C+u.x*y,P=o[_+1]=n.y+h.y*T+c.y*C+u.y*y,A=o[_+2]=n.z+h.z*T+c.z*C+u.z*y;if(this._computeBoundingBox&&(d.minimizeInPlaceFromFloats(E,P,A),f.maximizeInPlaceFromFloats(E,P,A)),this._computeParticleColor&&e.color){const t=e.color,i=this._colors32;i[m]=t.r,i[m+1]=t.g,i[m+2]=t.b,i[m+3]=t.a}if(this._computeParticleTexture&&e.uv){const t=e.uv,i=this._uvs32;i[g]=t.x,i[g+1]=t.y}}return s&&(i&&(this._computeParticleColor&&s.updateVerticesData(st.R.ColorKind,n,!1,!1),this._computeParticleTexture&&s.updateVerticesData(st.R.UVKind,a,!1,!1),s.updateVerticesData(st.R.PositionKind,o,!1,!1)),this._computeBoundingBox&&(s.hasBoundingInfo?s.getBoundingInfo().reConstruct(d,f,s._worldMatrix):s.buildBoundingInfo(d,f,s._worldMatrix))),this.afterUpdateParticles(e,t,i),this}dispose(){this.mesh?.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(){return this._isVisibilityBoxLocked||this.mesh?.refreshBoundingInfo(),this}setVisibilityBox(e){if(!this.mesh)return;const t=e/2;this.mesh.buildBoundingInfo(new W.Pq(-t,-t,-t),new W.Pq(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){}}var bM,SM,TM,CM,yM,EM,PM,AM,RM,IM,MM,OM,DM,wM=i(50619),NM=i(70917),FM=i(86144),LM=i(25806);Object.defineProperty(Nt.prototype,"physicsImpostor",{get:function(){return this._physicsImpostor},set:function(e){this._physicsImpostor!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsImpostor=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add((()=>{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)}))))},enumerable:!0,configurable:!0}),Nt.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},Nt.prototype.applyImpulse=function(e,t){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(e,t),this):this},Nt.prototype.setPhysicsLinkWith=function(e,t,i,r){return this.physicsImpostor&&e.physicsImpostor?(this.physicsImpostor.createJoint(e.physicsImpostor,Jo.HingeJoint,{mainPivot:t,connectedPivot:i,nativeParams:r}),this):this};class BM{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw(0,Je.n)("")}constructor(e,t=BM.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new W.Pq(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}setVelocityLimits(e,t){this._physicsPlugin.setVelocityLimits(e,t)}getMaxLinearVelocity(){return this._physicsPlugin.getMaxLinearVelocity()}getMaxAngularVelocity(){return this._physicsPlugin.getMaxAngularVelocity()}_step(e){e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._physicsBodies)}addBody(e){this._physicsBodies.push(e)}removeBody(e){const t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)}getBodies(){return this._physicsBodies}getPhysicsPlugin(){return this._physicsPlugin}raycastToRef(e,t,i,r){this._physicsPlugin.raycast(e,t,i,r)}raycast(e,t,i){const r=new Wx;return this._physicsPlugin.raycast(e,t,r,i),r}}!function(e){e[e.FREE=0]="FREE",e[e.LIMITED=1]="LIMITED",e[e.LOCKED=2]="LOCKED"}(bM||(bM={})),function(e){e[e.LINEAR_X=0]="LINEAR_X",e[e.LINEAR_Y=1]="LINEAR_Y",e[e.LINEAR_Z=2]="LINEAR_Z",e[e.ANGULAR_X=3]="ANGULAR_X",e[e.ANGULAR_Y=4]="ANGULAR_Y",e[e.ANGULAR_Z=5]="ANGULAR_Z",e[e.LINEAR_DISTANCE=6]="LINEAR_DISTANCE"}(SM||(SM={})),function(e){e[e.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",e[e.DISTANCE=2]="DISTANCE",e[e.HINGE=3]="HINGE",e[e.SLIDER=4]="SLIDER",e[e.LOCK=5]="LOCK",e[e.PRISMATIC=6]="PRISMATIC",e[e.SIX_DOF=7]="SIX_DOF"}(TM||(TM={})),function(e){e[e.SPHERE=0]="SPHERE",e[e.CAPSULE=1]="CAPSULE",e[e.CYLINDER=2]="CYLINDER",e[e.BOX=3]="BOX",e[e.CONVEX_HULL=4]="CONVEX_HULL",e[e.CONTAINER=5]="CONTAINER",e[e.MESH=6]="MESH",e[e.HEIGHTFIELD=7]="HEIGHTFIELD"}(CM||(CM={})),function(e){e[e.NONE=0]="NONE",e[e.VELOCITY=1]="VELOCITY",e[e.POSITION=2]="POSITION"}(yM||(yM={})),function(e){e.COLLISION_STARTED="COLLISION_STARTED",e.COLLISION_CONTINUED="COLLISION_CONTINUED",e.COLLISION_FINISHED="COLLISION_FINISHED",e.TRIGGER_ENTERED="TRIGGER_ENTERED",e.TRIGGER_EXITED="TRIGGER_EXITED"}(EM||(EM={})),function(e){e[e.STATIC=0]="STATIC",e[e.ANIMATED=1]="ANIMATED",e[e.DYNAMIC=2]="DYNAMIC"}(PM||(PM={})),function(e){e[e.DISABLED=0]="DISABLED",e[e.TELEPORT=1]="TELEPORT",e[e.ACTION=2]="ACTION"}(AM||(AM={})),function(e){e[e.SIMULATION_CONTROLLED=0]="SIMULATION_CONTROLLED",e[e.ALWAYS_ACTIVE=1]="ALWAYS_ACTIVE",e[e.ALWAYS_INACTIVE=2]="ALWAYS_INACTIVE"}(RM||(RM={}));class VM{get disablePreStep(){return this._prestepType==AM.DISABLED}set disablePreStep(e){this._prestepType=e?AM.DISABLED:AM.TELEPORT}constructor(e,t,i,r){if(this._pluginData=void 0,this._pluginDataInstances=[],this._collisionCBEnabled=!1,this._collisionEndedCBEnabled=!1,this.disableSync=!1,this._isDisposed=!1,this._shape=null,this._prestepType=AM.DISABLED,!r)return;const s=r.getPhysicsEngine();if(!s)throw new Error("No Physics Engine available.");if(this._physicsEngine=s,2!=s.getPluginVersion())throw new Error("Plugin version is incorrect. Expected version 2.");const n=s.getPhysicsPlugin();if(!n)throw new Error("No Physics Plugin available.");this._physicsPlugin=n,e.rotationQuaternion||(e.rotationQuaternion=W.PT.FromEulerAngles(e.rotation.x,e.rotation.y,e.rotation.z)),this.startAsleep=i,this._motionType=t,this.disableSync=0==t;const o=e;o.hasThinInstances?this._physicsPlugin.initBodyInstances(this,t,o):(e.parent&&e.computeWorldMatrix(!0),this._physicsPlugin.initBody(this,t,e.absolutePosition,e.absoluteRotationQuaternion)),this.transformNode=e,e.physicsBody=this,s.addBody(this),this._nodeDisposeObserver=e.onDisposeObservable.add((()=>{this.dispose()}))}getClassName(){return"PhysicsBody"}clone(e){const t=new VM(e,this.getMotionType(),this.startAsleep,this.transformNode.getScene());return t.shape=this.shape,t.setMassProperties(this.getMassProperties()),t.setLinearDamping(this.getLinearDamping()),t.setAngularDamping(this.getAngularDamping()),t}updateBodyInstances(){const e=this.transformNode;e.hasThinInstances&&this._physicsPlugin.updateBodyInstances(this,e)}get numInstances(){return this._pluginDataInstances.length}get motionType(){return this._motionType}set shape(e){this._shape=e,e&&this._physicsPlugin.setShape(this,e)}get shape(){return this._shape}getBoundingBox(){return this._physicsPlugin.getBodyBoundingBox(this)}setEventMask(e,t){this._physicsPlugin.setEventMask(this,e,t)}getEventMask(e){return this._physicsPlugin.getEventMask(this,e)}setMotionType(e,t){this.disableSync=0==e,this._physicsPlugin.setMotionType(this,e,t)}getMotionType(e){return this._physicsPlugin.getMotionType(this,e)}setPrestepType(e){this._prestepType=e}getPrestepType(){return this._prestepType}computeMassProperties(e){return this._physicsPlugin.computeMassProperties(this,e)}setMassProperties(e,t){this._physicsPlugin.setMassProperties(this,e,t)}getMassProperties(e){return this._physicsPlugin.getMassProperties(this,e)}setLinearDamping(e,t){this._physicsPlugin.setLinearDamping(this,e,t)}getLinearDamping(e){return this._physicsPlugin.getLinearDamping(this,e)}setAngularDamping(e,t){this._physicsPlugin.setAngularDamping(this,e,t)}getAngularDamping(e){return this._physicsPlugin.getAngularDamping(this,e)}setLinearVelocity(e,t){this._physicsPlugin.setLinearVelocity(this,e,t)}getLinearVelocityToRef(e,t){this._physicsPlugin.getLinearVelocityToRef(this,e,t)}getLinearVelocity(e){const t=new W.Pq;return this.getLinearVelocityToRef(t,e),t}setAngularVelocity(e,t){this._physicsPlugin.setAngularVelocity(this,e,t)}getAngularVelocityToRef(e,t){this._physicsPlugin.getAngularVelocityToRef(this,e,t)}getAngularVelocity(e){const t=new W.Pq;return this.getAngularVelocityToRef(t,e),t}applyImpulse(e,t,i){this._physicsPlugin.applyImpulse(this,e,t,i)}applyAngularImpulse(e,t){this._physicsPlugin.applyAngularImpulse(this,e,t)}applyForce(e,t,i){this._physicsPlugin.applyForce(this,e,t,i)}getGeometry(){return this._physicsPlugin.getBodyGeometry(this)}getCollisionObservable(){return this._physicsPlugin.getCollisionObservable(this)}getCollisionEndedObservable(){return this._physicsPlugin.getCollisionEndedObservable(this)}setCollisionCallbackEnabled(e){this._collisionCBEnabled=e,this._physicsPlugin.setCollisionCallbackEnabled(this,e)}setCollisionEndedCallbackEnabled(e){this._collisionEndedCBEnabled=e,this._physicsPlugin.setCollisionEndedCallbackEnabled(this,e)}getObjectCenterWorld(e){const t=new W.Pq;return this.getObjectCenterWorldToRef(t,e)}getObjectCenterWorldToRef(e,t){if(this._pluginDataInstances?.length>0){const i=t||0,r=this.transformNode._thinInstanceDataStorage.matrixData;r&&e.set(r[16*i+12],r[16*i+13],r[16*i+14])}else e.copyFrom(this.transformNode.position);return e}addConstraint(e,t,i,r){this._physicsPlugin.addConstraint(this,e,t,i,r)}syncWithBone(e,t,i,r,s,n){const o=this.transformNode;if(o.rotationQuaternion)if(s){const i=W.AA.Quaternion[0];e.getRotationQuaternionToRef(1,t,i),i.multiplyToRef(s,o.rotationQuaternion)}else e.getRotationQuaternionToRef(1,t,o.rotationQuaternion);const a=W.AA.Vector3[0],l=W.AA.Vector3[1];n||((n=W.AA.Vector3[2]).x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,l),e.getAbsolutePositionToRef(t,a),null==r&&i&&(r=i.length()),null!=r&&(a.x+=l.x*r,a.y+=l.y*r,a.z+=l.z*r),o.setAbsolutePosition(a)}iterateOverAllInstances(e){if(this._pluginDataInstances?.length>0)for(let t=0;t{this.dispose()}))}_getObjectBoundingBox(){return this.transformNode.getRawBoundingInfo?this.transformNode.getRawBoundingInfo().boundingBox:new ht(new W.Pq(-.5,-.5,-.5),new W.Pq(.5,.5,.5))}_hasVertices(e){return e?.getTotalVertices()>0}_addSizeOptions(){this.transformNode.computeWorldMatrix(!0);const e=this._getObjectBoundingBox(),t=W.AA.Vector3[0];t.copyFrom(e.extendSize),t.scaleInPlace(2),t.multiplyInPlace(this.transformNode.absoluteScaling),t.x=Math.abs(t.x),t.y=Math.abs(t.y),t.z=Math.abs(t.z);const i=W.AA.Vector3[1];if(i.copyFrom(e.minimum),i.multiplyInPlace(this.transformNode.absoluteScaling),!this._options.center){const t=new W.Pq;t.copyFrom(e.center),t.multiplyInPlace(this.transformNode.absoluteScaling),this._options.center=t}switch(this.type){case 0:!this._options.radius&&(0,ar.WithinEpsilon)(t.x,t.y,1e-4)&&(0,ar.WithinEpsilon)(t.x,t.z,1e-4)?this._options.radius=t.x/2:this._options.radius||(Z.V.Warn("Non uniform scaling is unsupported for sphere shapes. Setting the radius to the biggest bounding box extent."),this._options.radius=Math.max(t.x,t.y,t.z)/2);break;case 1:{const e=t.x/2;this._options.radius=this._options.radius??e,this._options.pointA=this._options.pointA??new W.Pq(0,i.y+e,0),this._options.pointB=this._options.pointB??new W.Pq(0,i.y+t.y-e,0)}break;case 2:{const e=t.x/2;this._options.radius=this._options.radius??e,this._options.pointA=this._options.pointA??new W.Pq(0,i.y,0),this._options.pointB=this._options.pointB??new W.Pq(0,i.y+t.y,0)}break;case 6:case 4:case 7:if(!this._options.mesh&&this._hasVertices(this.transformNode))this._options.mesh=this.transformNode;else if(!this._options.mesh||!this._hasVertices(this._options.mesh))throw new Error("No valid mesh was provided for mesh or convex hull shape parameter. Please provide a mesh with valid geometry (number of vertices greater than 0).");break;case 3:this._options.extents=this._options.extents??new W.Pq(t.x,t.y,t.z),this._options.rotation=this._options.rotation??W.PT.Identity()}}dispose(){this._nodeDisposeObserver&&(this.body.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver),this._nodeDisposeObserver=null),this.body.dispose(),this._disposeShapeWhenDisposed&&this.shape.dispose()}}class oO{}class aO{constructor(e,t,i){this._boxConfigs=new Array,this._joints=new Array,this._bones=new Array,this._initialRotation=new Array,this._initialRotation2=new Array,this._boneNames=[],this._transforms=new Array,this._aggregates=new Array,this._ragdollMode=!1,this._rootBoneName="",this._rootBoneIndex=-1,this._mass=10,this._restitution=0,this.pauseSync=!1,this._defaultJoint=3,this._defaultJointMin=-90,this._defaultJointMax=90,this._skeleton=e,this._scene=e.getScene(),this._rootTransformNode=t,this._config=i,this._boxConfigs=[],this._putBoxesInBoneCenter=!1,this._defaultJoint=3,this._init()}getAggregate(e){return e<0||e>=this._aggregates.length?this._aggregates[this._rootBoneIndex]:this._aggregates[e]}_createColliders(){this._rootTransformNode.computeWorldMatrix(),this._skeleton.computeAbsoluteMatrices(!0),this._skeleton.prepare(!0);const e=this._config;for(let t=0;t{this._syncBonesAndBoxes()})),this._syncBonesToPhysics())}ragdoll(){this._ragdollMode=!0,this._skeleton.bones.forEach((e=>{e.linkTransformNode(null)}));for(let e=0;e{e.dispose()}))}}class lO{constructor(e,t,i){this._vertices=[],this._indices=[],this._isRightHanded=i.useRightHandedSystem,this._collectIndices=t}addNodeMeshes(e,t){e.computeWorldMatrix(!0);const i=W.AA.Matrix[0];if(W.uq.ScalingToRef(e.absoluteScaling.x,e.absoluteScaling.y,e.absoluteScaling.z,i),e instanceof Yt?this._addMesh(e,i):e instanceof Kt&&this._addMesh(e.sourceMesh,i),t){const t=W.AA.Matrix[1];e.computeWorldMatrix().invertToRef(t);const r=W.AA.Matrix[2];t.multiplyToRef(i,r),e.getChildMeshes(!1).filter((e=>!e.physicsBody)).forEach((e=>{const t=e.computeWorldMatrix(),i=W.AA.Matrix[3];t.multiplyToRef(r,i),e instanceof Yt?this._addMesh(e,i):e instanceof Kt&&this._addMesh(e.sourceMesh,i)}))}}_addMesh(e,t){const i=e.getVerticesData(st.R.PositionKind)||[],r=i.length/3,s=this._vertices.length;for(let e=0;e0)for(const t of e._pluginDataInstances)this._bodyCollisionObservable.delete(t.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,t.hpBodyId),this._bodies.delete(t.hpBodyId[0]);e._pluginData&&(this._bodyCollisionObservable.delete(e._pluginData.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,e._pluginData.hpBodyId),this._bodies.delete(e._pluginData.hpBodyId[0]))}initBodyInstances(e,t,i){const r=i._thinInstanceDataStorage?.instancesCount??0,s=i._thinInstanceDataStorage.matrixData;s&&(this._createOrUpdateBodyInstances(e,t,s,0,r,!1),e._pluginDataInstances.forEach(((t,i)=>{this._bodies.set(t.hpBodyId[0],{body:e,index:i})})))}_createOrUpdateBodyInstances(e,t,i,r,s,n){const o=W.AA.Quaternion[0],a=W.uq.Identity();for(let l=r;ls){this._createOrUpdateBodyInstances(e,n,r,s,i,!1);const t=this._hknp.HP_Body_GetShape(e._pluginDataInstances[0].hpBodyId)[1];t[0]||(t[0]=e.shape?._pluginData[0]);for(let r=s;r{this._hknp.HP_Body_SetEventMask(e.hpBodyId,t)}),i)}getEventMask(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetEventMask(i.hpBodyId)[1]}_fromMassPropertiesTuple(e){return{centerOfMass:W.Pq.FromArray(e[0]),mass:e[1],inertia:W.Pq.FromArray(e[2]),inertiaOrientation:W.PT.FromArray(e[3])}}_internalUpdateMassProperties(e){const t=this._internalComputeMassProperties(e),i=e.userMassProps;i.centerOfMass&&(t[0]=i.centerOfMass.asArray()),null!=i.mass&&(t[1]=i.mass),i.inertia&&(t[2]=i.inertia.asArray()),i.inertiaOrientation&&(t[3]=i.inertiaOrientation.asArray()),this._hknp.HP_Body_SetMassProperties(e.hpBodyId,t)}_internalSetMotionType(e,t){switch(t){case 0:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.STATIC);break;case 1:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.KINEMATIC);break;case 2:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.DYNAMIC)}}setMotionType(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._internalSetMotionType(e,t)}),i)}getMotionType(e,t){const i=this._getPluginReference(e,t),r=this._hknp.HP_Body_GetMotionType(i.hpBodyId)[1];switch(r){case this._hknp.MotionType.STATIC:return 0;case this._hknp.MotionType.KINEMATIC:return 1;case this._hknp.MotionType.DYNAMIC:return 2}throw new Error("Unknown motion type: "+r)}setActivationControl(e,t){switch(t){case 1:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.ALWAYS_ACTIVE);break;case 2:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.ALWAYS_INACTIVE);break;case 0:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.SIMULATION_CONTROLLED)}}_internalComputeMassProperties(e){const t=this._hknp.HP_Body_GetShape(e.hpBodyId);if(t[0]==this._hknp.Result.RESULT_OK){const e=this._hknp.HP_Shape_BuildMassProperties(t[1]);if(e[0]==this._hknp.Result.RESULT_OK)return e[1]}return[[0,0,0],1,[1,1,1],[0,0,0,1]]}computeMassProperties(e,t){const i=this._getPluginReference(e,t),r=this._internalComputeMassProperties(i);return this._fromMassPropertiesTuple(r)}setMassProperties(e,t,i){this._applyToBodyOrInstances(e,(e=>{e.userMassProps=t,this._internalUpdateMassProperties(e)}),i)}getMassProperties(e,t){const i=this._getPluginReference(e,t),r=this._hknp.HP_Body_GetMassProperties(i.hpBodyId)[1];return this._fromMassPropertiesTuple(r)}setLinearDamping(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetLinearDamping(e.hpBodyId,t)}),i)}getLinearDamping(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetLinearDamping(i.hpBodyId)[1]}setAngularDamping(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetAngularDamping(e.hpBodyId,t)}),i)}getAngularDamping(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetAngularDamping(i.hpBodyId)[1]}setLinearVelocity(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetLinearVelocity(e.hpBodyId,this._bVecToV3(t))}),i)}getLinearVelocityToRef(e,t,i){const r=this._getPluginReference(e,i),s=this._hknp.HP_Body_GetLinearVelocity(r.hpBodyId)[1];this._v3ToBvecRef(s,t)}_applyToBodyOrInstances(e,t,i){if(e._pluginDataInstances?.length>0&&void 0===i)for(let i=0;i{this._hknp.HP_Body_ApplyImpulse(e.hpBodyId,this._bVecToV3(i),this._bVecToV3(t))}),r)}applyAngularImpulse(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_ApplyAngularImpulse(e.hpBodyId,this._bVecToV3(t))}),i)}applyForce(e,t,i,r){t.scaleToRef(this.getTimeStep(),this._tmpVec3[0]),this.applyImpulse(e,this._tmpVec3[0],i,r)}setAngularVelocity(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetAngularVelocity(e.hpBodyId,this._bVecToV3(t))}),i)}getAngularVelocityToRef(e,t,i){const r=this._getPluginReference(e,i),s=this._hknp.HP_Body_GetAngularVelocity(r.hpBodyId)[1];this._v3ToBvecRef(s,t)}setPhysicsBodyTransformation(e,t){if(e.getPrestepType()==AM.TELEPORT){const i=e.transformNode;if(e.numInstances>0){const t=i._thinInstanceDataStorage.matrixData;if(!t)return;const r=e.numInstances;this._createOrUpdateBodyInstances(e,e.getMotionType(),t,0,r,!0)}else this._hknp.HP_Body_SetQTransform(e._pluginData.hpBodyId,this._getTransformInfos(t))}else e.getPrestepType()==AM.ACTION?this.setTargetTransform(e,t.absolutePosition,t.absoluteRotationQuaternion):e.getPrestepType()==AM.DISABLED?Z.V.Warn("Prestep type is set to DISABLED. Unable to set physics body transformation."):Z.V.Warn("Invalid prestep type set to physics body.")}setTargetTransform(e,t,i,r){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetTargetQTransform(e.hpBodyId,[this._bVecToV3(t),this._bQuatToV4(i)])}),r)}setGravityFactor(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetGravityFactor(e.hpBodyId,t)}),i)}getGravityFactor(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetGravityFactor(i.hpBodyId)[1]}disposeBody(e){if(e._pluginDataInstances&&e._pluginDataInstances.length>0)for(const t of e._pluginDataInstances)this._hknp.HP_Body_Release(t.hpBodyId),t.hpBodyId=void 0;e._pluginData&&(this._hknp.HP_Body_Release(e._pluginData.hpBodyId),e._pluginData.hpBodyId=void 0)}_createOptionsFromGroundMesh(e){const t=e.groundMesh;if(!t)return;let i=t.getVerticesData(st.R.PositionKind);const r=t.computeWorldMatrix(!0),s=[];let n;for(n=0;n0?e._pluginDataInstances[0]:e._pluginData,i=this._hknp.HP_Body_GetShape(t.hpBodyId)[1],r=this._hknp.HP_Shape_CreateDebugDisplayGeometry(i);if(r[0]!=this._hknp.Result.RESULT_OK)return{positions:[],indices:[]};const s=this._hknp.HP_DebugGeometry_GetInfo(r[1])[1],n=new Float32Array(this._hknp.HEAPU8.buffer,s[0],3*s[1]),o=new Uint32Array(this._hknp.HEAPU8.buffer,s[2],3*s[3]),a=n.slice(0),l=o.slice(0);return this._hknp.HP_DebugGeometry_Release(r[1]),{positions:a,indices:l}}disposeShape(e){this._hknp.HP_Shape_Release(e._pluginData),e._pluginData=void 0}initConstraint(e,t,i,r,s){const n=e.type,o=e.options;if(!n||!o)return void Z.V.Warn("No constraint type or options. Constraint is invalid.");if(t._pluginDataInstances.length>0&&void 0===r||i._pluginDataInstances.length>0&&void 0===s)return void Z.V.Warn("Body is instanced but no instance index was specified. Constraint will not be applied.");e._pluginData=e._pluginData??[];const a=this._hknp.HP_Constraint_Create()[1];e._pluginData.push(a);const l=this._getPluginReference(t,r).hpBodyId,h=this._getPluginReference(i,s).hpBodyId;this._hknp.HP_Constraint_SetParentBody(a,l),this._hknp.HP_Constraint_SetChildBody(a,h),this._constraintToBodyIdPair.set(a[0],[l[0],h[0]]);const c=o.pivotA?this._bVecToV3(o.pivotA):this._bVecToV3(W.Pq.Zero()),u=o.axisA??new W.Pq(1,0,0),d=this._tmpVec3[0];o.perpAxisA?d.copyFrom(o.perpAxisA):u.getNormalToRef(d),this._hknp.HP_Constraint_SetAnchorInParent(a,c,this._bVecToV3(u),this._bVecToV3(d));const f=o.pivotB?this._bVecToV3(o.pivotB):this._bVecToV3(W.Pq.Zero()),p=o.axisB??new W.Pq(1,0,0),_=this._tmpVec3[0];if(o.perpAxisB?_.copyFrom(o.perpAxisB):p.getNormalToRef(_),this._hknp.HP_Constraint_SetAnchorInChild(a,f,this._bVecToV3(p),this._bVecToV3(_)),e._initOptions||(e._initOptions={axisA:u.clone(),axisB:p.clone(),perpAxisA:d.clone(),perpAxisB:_.clone(),pivotA:new W.Pq(c[0],c[1],c[2]),pivotB:new W.Pq(f[0],f[1],f[2])}),5==n)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(2==n){const e=o.maxDistance||0,t=this._hknp.ConstraintAxis.LINEAR_DISTANCE;this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(a,t,e),this._hknp.HP_Constraint_SetAxisMaxLimit(a,t,e)}else if(3==n)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(6==n)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(4==n)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(1==n)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else{if(7!=n)throw new Error("Unsupported Constraint Type.");{const t=e;for(const e of t.limits){const t=this._constraintAxisToNative(e.axis);0==(e.minLimit??-1)&&0==(e.maxLimit??-1)?this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LOCKED):(null!=e.minLimit&&(this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(a,t,e.minLimit)),null!=e.maxLimit&&(this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMaxLimit(a,t,e.maxLimit))),e.stiffness&&this._hknp.HP_Constraint_SetAxisStiffness(a,t,e.stiffness),e.damping&&this._hknp.HP_Constraint_SetAxisDamping(a,t,e.damping)}}}const m=!!o.collision;this._hknp.HP_Constraint_SetCollisionsEnabled(a,m),this._hknp.HP_Constraint_SetEnabled(a,!0)}getBodiesUsingConstraint(e){const t=[];for(const i of e._pluginData){const e=this._constraintToBodyIdPair.get(i[0]);if(e){const i=this._bodies.get(e[0]),r=this._bodies.get(e[1]);i&&r&&t.push({parentBody:i.body,parentBodyIndex:i.index,childBody:r.body,childBodyIndex:r.index})}}return t}addConstraint(e,t,i,r,s){this.initConstraint(i,e,t,r,s)}setEnabled(e,t){for(const i of e._pluginData)this._hknp.HP_Constraint_SetEnabled(i,t)}getEnabled(e){const t=e._pluginData&&e._pluginData[0];return!!t&&this._hknp.HP_Constraint_GetEnabled(t)[1]}setCollisionsEnabled(e,t){for(const i of e._pluginData)this._hknp.HP_Constraint_SetCollisionsEnabled(i,t)}getCollisionsEnabled(e){const t=e._pluginData&&e._pluginData[0];return!!t&&this._hknp.HP_Constraint_GetCollisionsEnabled(t)[1]}setAxisFriction(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisFriction(r,this._constraintAxisToNative(t),i)}getAxisFriction(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisFriction(i,this._constraintAxisToNative(t))[1]:null}setAxisMode(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMode(r,this._constraintAxisToNative(t),this._limitModeToNative(i))}getAxisMode(e,t){const i=e._pluginData&&e._pluginData[0];if(i){const e=this._hknp.HP_Constraint_GetAxisMode(i,this._constraintAxisToNative(t))[1];return this._nativeToLimitMode(e)}return null}setAxisMinLimit(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMinLimit(r,this._constraintAxisToNative(t),i)}getAxisMinLimit(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMinLimit(i,this._constraintAxisToNative(t))[1]:null}setAxisMaxLimit(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMaxLimit(r,this._constraintAxisToNative(t),i)}getAxisMaxLimit(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMaxLimit(i,this._constraintAxisToNative(t))[1]:null}setAxisMotorType(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorType(r,this._constraintAxisToNative(t),this._constraintMotorTypeToNative(i))}getAxisMotorType(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._nativeToMotorType(this._hknp.HP_Constraint_GetAxisMotorType(i,this._constraintAxisToNative(t))[1]):null}setAxisMotorTarget(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorTarget(r,this._constraintAxisToNative(t),i)}getAxisMotorTarget(e,t){return e._pluginData&&e._pluginData[0]?this._hknp.HP_Constraint_GetAxisMotorTarget(e._pluginData,this._constraintAxisToNative(t))[1]:null}setAxisMotorMaxForce(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorMaxForce(r,this._constraintAxisToNative(t),i)}getAxisMotorMaxForce(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMotorMaxForce(i,this._constraintAxisToNative(t))[1]:null}disposeConstraint(e){for(const t of e._pluginData)this._hknp.HP_Constraint_SetEnabled(t,!1),this._hknp.HP_Constraint_Release(t);e._pluginData.length=0}_populateHitData(e,t){const i=this._bodies.get(e[0][0]);t.body=i?.body,t.bodyIndex=i?.index;const r=this._shapes.get(e[1][0]);t.shape=r;const s=e[3],n=e[4],o=e[5];t.setHitData({x:n[0],y:n[1],z:n[2]},{x:s[0],y:s[1],z:s[2]},o)}raycast(e,t,i,r){const s=r?.membership??-1,n=r?.collideWith??-1,o=r?.shouldHitTriggers??!1;i.reset(e,t);const a=[BigInt(0)],l=[this._bVecToV3(e),this._bVecToV3(t),[s,n],o,a];if(this._hknp.HP_World_CastRayWithCollector(this.world,this._queryCollector,l),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[,e]=this._hknp.HP_QueryCollector_GetCastRayResult(this._queryCollector,0)[1];this._populateHitData(e,i),i.calculateHitDistance()}}pointProximity(e,t){const i=e?.collisionFilter?.membership??-1,r=e?.collisionFilter?.collideWith??-1;t.reset();const s=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],n=[this._bVecToV3(e.position),e.maxDistance,[i,r],e.shouldHitTriggers,s];if(this._hknp.HP_World_PointProximityWithCollector(this.world,this._queryCollector,n),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[e,i]=this._hknp.HP_QueryCollector_GetPointProximityResult(this._queryCollector,0)[1];this._populateHitData(i,t),t.setHitDistance(e)}}shapeProximity(e,t,i){t.reset(),i.reset();const r=e.shape._pluginData,s=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],n=[r,this._bVecToV3(e.position),this._bQuatToV4(e.rotation),e.maxDistance,e.shouldHitTriggers,s];if(this._hknp.HP_World_ShapeProximityWithCollector(this.world,this._queryCollector,n),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[e,r,s]=this._hknp.HP_QueryCollector_GetShapeProximityResult(this._queryCollector,0)[1];this._populateHitData(r,t),this._populateHitData(s,i),t.setHitDistance(e),i.setHitDistance(e)}}shapeCast(e,t,i){t.reset(),i.reset();const r=e.shape._pluginData,s=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],n=[r,this._bQuatToV4(e.rotation),this._bVecToV3(e.startPosition),this._bVecToV3(e.endPosition),e.shouldHitTriggers,s];if(this._hknp.HP_World_ShapeCastWithCollector(this.world,this._queryCollector,n),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[e,r,s]=this._hknp.HP_QueryCollector_GetShapeCastResult(this._queryCollector,0)[1];this._populateHitData(r,t),this._populateHitData(s,i),t.setHitFraction(e),i.setHitFraction(e)}}getCollisionObservable(e){const t=e._pluginData.hpBodyId[0];let i=this._bodyCollisionObservable.get(t);return i||(i=new z.cP,this._bodyCollisionObservable.set(t,i)),i}getCollisionEndedObservable(e){const t=e._pluginData.hpBodyId[0];let i=this._bodyCollisionEndedObservable.get(t);return i||(i=new z.cP,this._bodyCollisionEndedObservable.set(t,i)),i}setCollisionCallbackEnabled(e,t){const i=this._hknp.EventType.COLLISION_STARTED.value|this._hknp.EventType.COLLISION_CONTINUED.value|this._hknp.EventType.COLLISION_FINISHED.value;e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach((e=>{this._hknp.HP_Body_SetEventMask(e.hpBodyId,t?i:0)})):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,t?i:0)}setCollisionEndedCallbackEnabled(e,t){const i=this._getPluginReference(e);let r=this._hknp.HP_Body_GetEventMask(i.hpBodyId)[1];r=t?r|this._hknp.EventType.COLLISION_FINISHED.value:r&~this._hknp.EventType.COLLISION_FINISHED.value,e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach((e=>{this._hknp.HP_Body_SetEventMask(e.hpBodyId,r)})):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,r)}_notifyTriggers(){let e=this._hknp.HP_World_GetTriggerEvents(this.world)[1];const t=new dO;for(;e;){dO.readToRef(this._hknp.HEAPU8.buffer,e,t);const i=this._bodies.get(t.bodyIdA),r=this._bodies.get(t.bodyIdB);if(i&&r){const e={collider:i.body,colliderIndex:i.index,collidedAgainst:r.body,collidedAgainstIndex:r.index,type:this._nativeTriggerCollisionValueToCollisionType(t.type)};this.onTriggerCollisionObservable.notifyObservers(e)}e=this._hknp.HP_World_GetNextTriggerEvent(this.world,e)}}_notifyCollisions(){let e=this._hknp.HP_World_GetCollisionEvents(this.world)[1];const t=new uO,i=Number(this.world);for(;e;){uO.readToRef(this._hknp.HEAPU8.buffer,e,t);const r=this._bodies.get(t.contactOnA.bodyId),s=this._bodies.get(t.contactOnB.bodyId);if(r&&s){const e={collider:r.body,colliderIndex:r.index,collidedAgainst:s.body,collidedAgainstIndex:s.index,type:this._nativeCollisionValueToCollisionType(t.type)};if("COLLISION_FINISHED"===e.type)this.onCollisionEndedObservable.notifyObservers(e);else{t.contactOnB.position.subtractToRef(t.contactOnA.position,this._tmpVec3[0]);const i=W.Pq.Dot(this._tmpVec3[0],t.contactOnA.normal);e.point=t.contactOnA.position,e.distance=i,e.impulse=t.impulseApplied,e.normal=t.contactOnA.normal,this.onCollisionObservable.notifyObservers(e)}if(this._bodyCollisionObservable.size&&"COLLISION_FINISHED"!==e.type){const i=this._bodyCollisionObservable.get(t.contactOnA.bodyId),n=this._bodyCollisionObservable.get(t.contactOnB.bodyId);t.contactOnA.position.subtractToRef(t.contactOnB.position,this._tmpVec3[0]);const o=W.Pq.Dot(this._tmpVec3[0],t.contactOnB.normal);if(i&&i.notifyObservers(e),n){const e={collider:s.body,colliderIndex:s.index,collidedAgainst:r.body,collidedAgainstIndex:r.index,point:t.contactOnB.position,distance:o,impulse:t.impulseApplied,normal:t.contactOnB.normal,type:this._nativeCollisionValueToCollisionType(t.type)};n.notifyObservers(e)}}else if(this._bodyCollisionEndedObservable.size){const i=this._bodyCollisionEndedObservable.get(t.contactOnA.bodyId),n=this._bodyCollisionEndedObservable.get(t.contactOnB.bodyId);t.contactOnA.position.subtractToRef(t.contactOnB.position,this._tmpVec3[0]);const o=W.Pq.Dot(this._tmpVec3[0],t.contactOnB.normal);if(i&&i.notifyObservers(e),n){const e={collider:s.body,colliderIndex:s.index,collidedAgainst:r.body,collidedAgainstIndex:r.index,point:t.contactOnB.position,distance:o,impulse:t.impulseApplied,normal:t.contactOnB.normal,type:this._nativeCollisionValueToCollisionType(t.type)};n.notifyObservers(e)}}}e=this._hknp.HP_World_GetNextCollisionEvent(i,e)}}get numBodies(){return this._hknp.HP_World_GetNumBodies(this.world)[1]}dispose(){this._queryCollector&&(this._hknp.HP_QueryCollector_Release(this._queryCollector),this._queryCollector=void 0),this.world&&(this._hknp.HP_World_Release(this.world),this.world=void 0)}_v3ToBvecRef(e,t){t.set(e[0],e[1],e[2])}_bVecToV3(e){return[e._x,e._y,e._z]}_bQuatToV4(e){return[e._x,e._y,e._z,e._w]}_constraintMotorTypeToNative(e){switch(e){case 2:return this._hknp.ConstraintMotorType.POSITION;case 1:return this._hknp.ConstraintMotorType.VELOCITY}return this._hknp.ConstraintMotorType.NONE}_nativeToMotorType(e){switch(e){case this._hknp.ConstraintMotorType.POSITION:return 2;case this._hknp.ConstraintMotorType.VELOCITY:return 1}return 0}_materialCombineToNative(e){switch(e){case 0:return this._hknp.MaterialCombine.GEOMETRIC_MEAN;case 1:return this._hknp.MaterialCombine.MINIMUM;case 2:return this._hknp.MaterialCombine.MAXIMUM;case 3:return this._hknp.MaterialCombine.ARITHMETIC_MEAN;case 4:return this._hknp.MaterialCombine.MULTIPLY}}_nativeToMaterialCombine(e){switch(e){case this._hknp.MaterialCombine.GEOMETRIC_MEAN:return 0;case this._hknp.MaterialCombine.MINIMUM:return 1;case this._hknp.MaterialCombine.MAXIMUM:return 2;case this._hknp.MaterialCombine.ARITHMETIC_MEAN:return 3;case this._hknp.MaterialCombine.MULTIPLY:return 4;default:return}}_constraintAxisToNative(e){switch(e){case 0:return this._hknp.ConstraintAxis.LINEAR_X;case 1:return this._hknp.ConstraintAxis.LINEAR_Y;case 2:return this._hknp.ConstraintAxis.LINEAR_Z;case 3:return this._hknp.ConstraintAxis.ANGULAR_X;case 4:return this._hknp.ConstraintAxis.ANGULAR_Y;case 5:return this._hknp.ConstraintAxis.ANGULAR_Z;case 6:return this._hknp.ConstraintAxis.LINEAR_DISTANCE}}_nativeToLimitMode(e){switch(e){case this._hknp.ConstraintAxisLimitMode.FREE:return 0;case this._hknp.ConstraintAxisLimitMode.LIMITED:return 1;case this._hknp.ConstraintAxisLimitMode.LOCKED:return 2}return 0}_limitModeToNative(e){switch(e){case 0:return this._hknp.ConstraintAxisLimitMode.FREE;case 1:return this._hknp.ConstraintAxisLimitMode.LIMITED;case 2:return this._hknp.ConstraintAxisLimitMode.LOCKED}}_nativeCollisionValueToCollisionType(e){switch(e){case this._hknp.EventType.COLLISION_STARTED.value:return"COLLISION_STARTED";case this._hknp.EventType.COLLISION_FINISHED.value:return"COLLISION_FINISHED";case this._hknp.EventType.COLLISION_CONTINUED.value:return"COLLISION_CONTINUED"}return"COLLISION_STARTED"}_nativeTriggerCollisionValueToCollisionType(e){switch(e){case 8:return"TRIGGER_ENTERED";case 16:return"TRIGGER_EXITED"}return"TRIGGER_ENTERED"}}oi.Z.prototype.getPhysicsEngine=function(){return this._physicsEngine},oi.Z.prototype.enablePhysics=function(e=null,t){if(this._physicsEngine)return!0;let i=this._getComponent(Ut.v.NAME_PHYSICSENGINE);i||(i=new pO(this),this._addComponent(i));try{if(t&&1!==t?.getPluginVersion()){if(2!==t?.getPluginVersion())throw new Error("Unsupported Physics plugin version.");this._physicsEngine=new BM(e,t)}else this._physicsEngine=new Hx(e,t);return this._physicsTimeAccumulator=0,!0}catch(e){return Z.V.Error(e.message),!1}},oi.Z.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},oi.Z.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},oi.Z.prototype.deleteCompoundImpostor=function(e){const t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},oi.Z.prototype._advancePhysicsEngineStep=function(e){if(this._physicsEngine){const t=this._physicsEngine.getSubTimeStep();if(t>0)for(this._physicsTimeAccumulator+=e;this._physicsTimeAccumulator>t;)this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(t/1e3),this.onAfterPhysicsObservable.notifyObservers(this),this._physicsTimeAccumulator-=t;else this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(e/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class pO{constructor(e){this.name=Ut.v.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new z.cP,this.scene.onAfterPhysicsObservable=new z.cP,this.scene.getDeterministicFrameTime=()=>this.scene._physicsEngine?1e3*this.scene._physicsEngine.getTimeStep():1e3/60}register(){}rebuild(){}dispose(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()}}Object.defineProperty(Pt.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(e){this._physicsBody!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add((()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)}))))},enumerable:!0,configurable:!0}),Pt.prototype.getPhysicsBody=function(){return this.physicsBody},Pt.prototype.applyImpulse=function(e,t){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(e,t),this},Pt.prototype.applyAngularImpulse=function(e){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyAngularImpulse(e),this};class _O{static GetContactPointToRef(e,t,i,r,s){const n=e.getScene().getPhysicsEngine(),o=n?.getPluginVersion();if(1===o){const s=new wi(t,i).intersectsMesh(e);if(s.hit&&s.pickedPoint)return r.copyFrom(s.pickedPoint),!0}else if(2===o)return e.physicsBody.getObjectCenterWorldToRef(r,s),!0;return!1}static HasAppliedForces(e,t){return 0===e.getMotionType(t)||0===(e.getMassProperties(t)?.mass??0)||0===e.transformNode?.getTotalVertices()}static IsInsideCylinder(e,t,i,r){const s=W.AA.Vector3[0];return e.subtractToRef(t,s),Math.abs(s.x)<=i&&Math.abs(s.z)<=i&&s.y>=0&&s.y<=r}}class mO{constructor(e){this._hitData={force:new W.Pq,contactPoint:new W.Pq,distanceFromOrigin:0},this._scene=e,this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine||Z.V.Warn("Physics engine not enabled. Please enable the physics before you can use the methods.")}applyRadialExplosionImpulse(e,t,i,r){if(!this._physicsEngine)return Z.V.Warn("Physics engine not enabled. Please enable the physics before you call this method."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;let s=!1;if("number"==typeof t){const e=t;(t=new SO).radius=e,t.strength=i??t.strength,t.falloff=r??t.falloff}else s=!(!t.affectedImpostorsCallback&&!t.affectedBodiesCallback);const n=new gO(this._scene,t),o=this._hitData;if(1===this._physicsEngine.getPluginVersion()){const t=Array();this._physicsEngine.getImpostors().forEach((i=>{n.getImpostorHitData(i,e,o)&&(i.applyImpulse(o.force,o.contactPoint),s&&t.push({impostor:i,hitData:this._copyPhysicsHitData(o)}))})),n.triggerAffectedImpostorsCallback(t)}else this._applicationForBodies(n,e,o,s,((e,t)=>{e.applyImpulse(t.force,t.contactPoint,t.instanceIndex)}));return n.dispose(!1),n}applyRadialExplosionForce(e,t,i,r){if(!this._physicsEngine)return Z.V.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;let s=!1;if("number"==typeof t){const e=t;(t=new SO).radius=e,t.strength=i??t.strength,t.falloff=r??t.falloff}else s=!(!t.affectedImpostorsCallback&&!t.affectedBodiesCallback);const n=new gO(this._scene,t),o=this._hitData;if(1===this._physicsEngine.getPluginVersion()){const t=Array();this._physicsEngine.getImpostors().forEach((i=>{n.getImpostorHitData(i,e,o)&&(i.applyForce(o.force,o.contactPoint),s&&t.push({impostor:i,hitData:this._copyPhysicsHitData(o)}))})),n.triggerAffectedImpostorsCallback(t)}else this._applicationForBodies(n,e,o,s,((e,t)=>{e.applyForce(t.force,t.contactPoint,t.instanceIndex)}));return n.dispose(!1),n}_applicationForBodies(e,t,i,r,s){const n=Array(),o=this._physicsEngine.getBodies();for(const a of o)a.iterateOverAllInstances(((o,a)=>{e.getBodyHitData(o,t,i,a)&&(s(o,i),r&&n.push({body:o,hitData:this._copyPhysicsHitData(i)}))}));e.triggerAffectedBodiesCallback(n)}gravitationalField(e,t,i,r){if(!this._physicsEngine)return Z.V.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new SO).radius=e,t.strength=i??t.strength,t.falloff=r??t.falloff}const s=new vO(this,this._scene,e,t);return s.dispose(!1),s}updraft(e,t,i,r,s){if(!this._physicsEngine)return Z.V.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new TO).radius=e,t.strength=i??t.strength,t.height=r??t.height,t.updraftMode=s??t.updraftMode}const n=new xO(this._scene,e,t);return n.dispose(!1),n}vortex(e,t,i,r){if(!this._physicsEngine)return Z.V.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new CO).radius=e,t.strength=i??t.strength,t.height=r??t.height}const s=new bO(this._scene,e,t);return s.dispose(!1),s}_copyPhysicsHitData(e){return{force:e.force.clone(),contactPoint:e.contactPoint.clone(),distanceFromOrigin:e.distanceFromOrigin,instanceIndex:e.instanceIndex}}}class gO{constructor(e,t){this._scene=e,this._options=t,this._dataFetched=!1,this._options={...new SO,...this._options}}getData(){return this._dataFetched=!0,{sphere:this._sphere}}_getHitData(e,t,i,r){const s=W.AA.Vector3[0];s.copyFrom(t).subtractInPlace(i);const n=W.AA.Vector3[1];if(!_O.GetContactPointToRef(e,i,s,n,r.instanceIndex))return!1;const o=W.Pq.Distance(i,n);if(o>this._options.radius)return!1;const a=0===this._options.falloff?this._options.strength:this._options.strength*(1-o/this._options.radius);return s.scaleInPlace(a),r.force.copyFrom(s),r.contactPoint.copyFrom(n),r.distanceFromOrigin=o,!0}getBodyHitData(e,t,i,r){if(_O.HasAppliedForces(e,r))return!1;const s=e.transformNode,n=e.getObjectCenterWorld(r);return i.instanceIndex=r,this._getHitData(s,n,t,i)}getImpostorHitData(e,t,i){if(0===e.mass)return!1;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;const r=e.object;if(!this._intersectsWithSphere(r,t,this._options.radius))return!1;const s=e.getObjectCenter();return this._getHitData(r,s,t,i),!0}triggerAffectedImpostorsCallback(e){this._options.affectedImpostorsCallback&&this._options.affectedImpostorsCallback(e)}triggerAffectedBodiesCallback(e){this._options.affectedBodiesCallback&&this._options.affectedBodiesCallback(e)}dispose(e=!0){this._sphere&&(e?this._sphere.dispose():setTimeout((()=>{this._dataFetched||this._sphere.dispose()}),0))}_prepareSphere(){this._sphere||(this._sphere=Qo("radialExplosionEventSphere",this._options.sphere,this._scene),this._sphere.isVisible=!1)}_intersectsWithSphere(e,t,i){return this._prepareSphere(),this._sphere.position=t,this._sphere.scaling.setAll(2*i),this._sphere._updateBoundingInfo(),this._sphere.computeWorldMatrix(!0),this._sphere.intersectsMesh(e,!0)}}class vO{constructor(e,t,i,r){this._physicsHelper=e,this._scene=t,this._origin=i,this._options=r,this._dataFetched=!1,this._options={...new SO,...this._options},this._tickCallback=()=>this._tick(),this._options.strength=-1*this._options.strength}getData(){return this._dataFetched=!0,{sphere:this._sphere}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._sphere&&(e?this._sphere.dispose():setTimeout((()=>{this._dataFetched||this._sphere.dispose()}),0))}_tick(){if(this._sphere)this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);else{const e=this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);e&&(this._sphere=e.getData().sphere?.clone("radialExplosionEventSphereClone"))}}}class xO{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=W.Pq.Zero(),this._originDirection=W.Pq.Zero(),this._cylinderPosition=W.Pq.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new TO,...this._options},this._origin.addToRef(new W.Pq(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new W.Pq(0,this._options.height,0),this._originTop),1===this._options.updraftMode&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?(this._cylinder.dispose(),this._cylinder=void 0):setTimeout((()=>{!this._dataFetched&&this._cylinder&&(this._cylinder.dispose(),this._cylinder=void 0)}),0))}_getHitData(e,t){let i;i=1===this._options.updraftMode?this._originDirection:e.subtract(this._originTop);const r=W.Pq.Distance(this._origin,e),s=-1*this._options.strength,n=i.multiplyByFloats(s,s,s);t.force.copyFrom(n),t.contactPoint.copyFrom(e),t.distanceFromOrigin=r}_getBodyHitData(e,t,i){if(_O.HasAppliedForces(e))return!1;const r=e.getObjectCenterWorld(i);return!!_O.IsInsideCylinder(r,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(r,t),!0)}_getImpostorHitData(e,t){if(0===e.mass)return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const r=e.getObjectCenter();return this._getHitData(r,t),!0}_tick(){const e=xO._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=No("updraftEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return!!this._cylinder&&(this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0))}}xO._HitData={force:new W.Pq,contactPoint:new W.Pq,distanceFromOrigin:0};class bO{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=W.Pq.Zero(),this._cylinderPosition=W.Pq.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new CO,...this._options},this._origin.addToRef(new W.Pq(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new W.Pq(0,this._options.height,0),this._originTop),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?this._cylinder.dispose():setTimeout((()=>{this._dataFetched||this._cylinder.dispose()}),0))}_getHitData(e,t,i){const r=bO._OriginOnPlane;r.set(this._origin.x,t.y,this._origin.z);const s=W.AA.Vector3[0];t.subtractToRef(r,s);const n=W.AA.Vector3[1];if(!_O.GetContactPointToRef(e,r,s,n,i.instanceIndex))return!1;const o=W.Pq.Distance(n,r)/this._options.radius,a=W.AA.Vector3[2];let l,h,c;if(n.normalizeToRef(a),o>this._options.centripetalForceThreshold&&a.negateInPlace(),o>this._options.centripetalForceThreshold)l=a.x*this._options.centripetalForceMultiplier,h=a.y*this._options.updraftForceMultiplier,c=a.z*this._options.centripetalForceMultiplier;else{const e=W.Pq.Cross(r,t).normalize();l=(e.x+a.x)*this._options.centrifugalForceMultiplier,h=this._originTop.y*this._options.updraftForceMultiplier,c=(e.z+a.z)*this._options.centrifugalForceMultiplier}const u=W.AA.Vector3[3];return u.set(l,h,c),u.scaleInPlace(this._options.strength),i.force.copyFrom(u),i.contactPoint.copyFrom(t),i.distanceFromOrigin=o,!0}_getBodyHitData(e,t,i){if(_O.HasAppliedForces(e,i))return!1;const r=e.transformNode,s=e.getObjectCenterWorld(i);return!!_O.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(r,s,t))}_getImpostorHitData(e,t){if(0===e.mass)return!1;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const r=e.getObjectCenter();return this._getHitData(i,r,t),!0}_tick(){const e=bO._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=No("vortexEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)}}bO._OriginOnPlane=W.Pq.Zero(),bO._HitData={force:new W.Pq,contactPoint:new W.Pq,distanceFromOrigin:0};class SO{constructor(){this.radius=5,this.strength=10,this.falloff=0,this.sphere={segments:32,diameter:1}}}class TO{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=0}}class CO{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}}!function(e){e[e.Constant=0]="Constant",e[e.Linear=1]="Linear"}(MM||(MM={})),function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"}(OM||(OM={}));class yO extends zx{constructor(){super(...arguments),this._hitDistance=0}get hitDistance(){return this._hitDistance}setHitDistance(e){this._hitDistance=e}reset(){super.reset(),this._hitDistance=0}}class EO extends zx{constructor(){super(...arguments),this._hitFraction=0}get hitFraction(){return this._hitFraction}setHitFraction(e){this._hitFraction=e}}class PO extends ms.w{get degree(){return this._effectWrapper.degree}set degree(e){this._effectWrapper.degree=e}getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i=null,r,s,n){const o={uniforms:l_.Uniforms,size:"number"==typeof t?t:void 0,camera:i,samplingMode:r,engine:s,reusable:n,...t};super(e,l_.FragmentUrl,{effectWrapper:"number"!=typeof t&&t.effectWrapper?void 0:new l_(e,s,o),...o})}static _Parse(e,t,i,r){return it.p.Parse((()=>new PO(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,r)}}(0,je.Cg)([(0,$e.lK)()],PO.prototype,"degree",null),(0,X.Y5)("BABYLON.BlackAndWhitePostProcess",PO);class AO{constructor(e,t,i,r){this._name=t,this._singleInstance=r||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(const e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){const t=this._postProcesses[e];for(let e=0;e{const t=r.attachPostProcess(e);this._indicesForCamera[s].push(t)})),this._cameras[s]||(this._cameras[s]=r)}}_detachCameras(e){const t=Ue.S0.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)})),this._cameras[r]&&(this._cameras[r]=null),delete this._indicesForCamera[r]}}_enable(e){const t=Ue.S0.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)}))}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}class RO extends ms.w{get threshold(){return this._effectWrapper.threshold}set threshold(e){this._effectWrapper.threshold=e}get _exposure(){return this._effectWrapper._exposure}set _exposure(e){this._effectWrapper._exposure=e}getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i=null,r,s,n,o=0,a=!1){const l={uniforms:__.Uniforms,size:"number"==typeof t?t:void 0,camera:i,samplingMode:r,engine:s,reusable:n,textureType:o,blockCompilation:a,...t};super(e,__.FragmentUrl,{effectWrapper:"number"!=typeof t&&t.effectWrapper?void 0:new __(e,s,l),...l}),this._inputPostProcess=null,this.onApplyObservable.add((e=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&e.setTextureFromPostProcess("textureSampler",this._inputPostProcess)}))}}(0,je.Cg)([(0,$e.lK)()],RO.prototype,"threshold",null),(0,X.Y5)("BABYLON.ExtractHighlightsPostProcess",RO);class IO extends ms.w{get weight(){return this._effectWrapper.weight}set weight(e){this._effectWrapper.weight=e}getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,r,s,n=null,o,a,l,h=0,c=!1){const u="number"==typeof s?c:!!s.blockCompilation,d={uniforms:d_.Uniforms,samplers:d_.Samplers,size:"number"==typeof s?s:void 0,camera:n,samplingMode:o,engine:a,reusable:l,textureType:h,...s,blockCompilation:!0};super(e,d_.FragmentUrl,{effectWrapper:"number"!=typeof s&&s.effectWrapper?void 0:new d_(e,a,d),...d}),this.weight=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("bloomBlur",i)})),u||this.updateEffect()}}(0,je.Cg)([(0,$e.lK)()],IO.prototype,"weight",null),(0,X.Y5)("BABYLON.BloomMergePostProcess",IO);class MO extends AO{get threshold(){return this._thinBloomEffect.threshold}set threshold(e){this._thinBloomEffect.threshold=e}get weight(){return this._thinBloomEffect.weight}set weight(e){this._thinBloomEffect.weight=e}get kernel(){return this._thinBloomEffect.kernel}set kernel(e){this._thinBloomEffect.kernel=e}get bloomScale(){return this._thinBloomEffect.scale}constructor(e,t,i,r,s=0,n=!1){const o=e._renderForCamera?e.getEngine():e;super(o,"bloom",(()=>this._effects),!0),this._effects=[],this._thinBloomEffect=new m_("bloom",o,t,n),this._downscale=new RO("highlights",{size:1,samplingMode:vi.g.BILINEAR_SAMPLINGMODE,engine:o,textureType:s,blockCompilation:n,effectWrapper:this._thinBloomEffect._downscale}),this._blurX=new _m("horizontal blur",this._thinBloomEffect._blurX.direction,this._thinBloomEffect._blurX.kernel,{size:t,samplingMode:vi.g.BILINEAR_SAMPLINGMODE,engine:o,textureType:s,blockCompilation:n,effectWrapper:this._thinBloomEffect._blurX}),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new _m("vertical blur",this._thinBloomEffect._blurY.direction,this._thinBloomEffect._blurY.kernel,{size:t,samplingMode:vi.g.BILINEAR_SAMPLINGMODE,engine:o,textureType:s,blockCompilation:n,effectWrapper:this._thinBloomEffect._blurY}),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=r,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new IO("bloomMerge",this._downscale,this._blurY,i,{size:t,samplingMode:vi.g.BILINEAR_SAMPLINGMODE,engine:o,textureType:s,blockCompilation:n,effectWrapper:this._thinBloomEffect._merge}),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t{e.setFloat("chromatic_aberration",this.aberrationAmount),e.setFloat("screen_width",t),e.setFloat("screen_height",i),e.setFloat("radialIntensity",this.radialIntensity),e.setFloat2("direction",this.direction.x,this.direction.y),e.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)}))}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,44134))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,76437))])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return it.p.Parse((()=>new OO(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,r)}}(0,je.Cg)([(0,$e.lK)()],OO.prototype,"aberrationAmount",void 0),(0,je.Cg)([(0,$e.lK)()],OO.prototype,"radialIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],OO.prototype,"direction",void 0),(0,je.Cg)([(0,$e.lK)()],OO.prototype,"centerPosition",void 0),(0,je.Cg)([(0,$e.lK)()],OO.prototype,"screenWidth",void 0),(0,je.Cg)([(0,$e.lK)()],OO.prototype,"screenHeight",void 0),(0,X.Y5)("BABYLON.ChromaticAberrationPostProcess",OO);class DO extends ms.w{get lensSize(){return this._effectWrapper.lensSize}set lensSize(e){this._effectWrapper.lensSize=e}get fStop(){return this._effectWrapper.fStop}set fStop(e){this._effectWrapper.fStop=e}get focusDistance(){return this._effectWrapper.focusDistance}set focusDistance(e){this._effectWrapper.focusDistance=e}get focalLength(){return this._effectWrapper.focalLength}set focalLength(e){this._effectWrapper.focalLength=e}getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,r,s,n,o,a=0,l=!1){const h={uniforms:T_.Uniforms,samplers:T_.Samplers,defines:"object"==typeof i&&i.depthNotNormalized?T_.DefinesDepthNotNormalized:void 0,size:"number"==typeof i?i:void 0,camera:r,samplingMode:s,engine:n,reusable:o,textureType:a,blockCompilation:l,...i};super(e,T_.FragmentUrl,{effectWrapper:"number"!=typeof i&&i.effectWrapper?void 0:new T_(e,n,h),...h}),this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add((e=>{this._depthTexture?(e.setTexture("depthSampler",this._depthTexture),this._effectWrapper.camera=this._depthTexture.activeCamera):Z.V.Warn("No depth texture set on CircleOfConfusionPostProcess")}))}set depthTexture(e){this._depthTexture=e}}(0,je.Cg)([(0,$e.lK)()],DO.prototype,"lensSize",null),(0,je.Cg)([(0,$e.lK)()],DO.prototype,"fStop",null),(0,je.Cg)([(0,$e.lK)()],DO.prototype,"focusDistance",null),(0,je.Cg)([(0,$e.lK)()],DO.prototype,"focalLength",null),(0,X.Y5)("BABYLON.CircleOfConfusionPostProcess",DO);class wO extends ms.w{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,r,s,n,o){super(e,"colorCorrection",null,["colorTable"],i,r,s,n,o);const a=r?.getScene()||null;this._colorTableTexture=new vi.g(t,a,!0,!1,vi.g.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=vi.g.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=vi.g.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=e=>{e.setTexture("colorTable",this._colorTableTexture)}}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,82308))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,42711))])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return it.p.Parse((()=>new wO(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,r)}}(0,je.Cg)([(0,$e.lK)()],wO.prototype,"colorTableUrl",void 0),(0,X.Y5)("BABYLON.ColorCorrectionPostProcess",wO);class NO extends ms.w{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,r,s,n,o,a=0){super(e,"convolution",["kernel","screenSize"],null,i,r,s,n,o,null,a),this.kernel=t,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setArray("kernel",this.kernel)}}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,79799))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,59188))])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return it.p.Parse((()=>new NO(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType)),e,i,r)}}NO.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],NO.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],NO.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],NO.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],NO.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],NO.GaussianKernel=[0,1,0,1,1,1,0,1,0],(0,je.Cg)([(0,$e.lK)()],NO.prototype,"kernel",void 0),(0,X.Y5)("BABYLON.ConvolutionPostProcess",NO);class FO extends _m{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,r,s,n,o,a=null,l=vi.g.BILINEAR_SAMPLINGMODE,h,c,u=0,d=!1,f=5){super(e,i,r,{camera:n,engine:h,reusable:c,textureType:u,defines:"#define DOF 1\n",blockCompilation:d,textureFormat:f,...s,samplingMode:2}),this.externalTextureSamplerBinding=!!a,this.onApplyObservable.add((e=>{null!=a&&e.setTextureFromPostProcess("textureSampler",a),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",o)}))}}(0,X.Y5)("BABYLON.DepthOfFieldBlurPostProcess",FO);class LO extends ms.w{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,r,s,n,o,a,l,h=0,c=!1){const u="number"==typeof s?c:!!s.blockCompilation,d={samplers:E_.Samplers,size:"number"==typeof s?s:void 0,camera:n,samplingMode:o,engine:a,reusable:l,textureType:h,...s,blockCompilation:!0};super(e,E_.FragmentUrl,{effectWrapper:"number"!=typeof s&&s.effectWrapper?void 0:new E_(e,a,d),...d}),this._blurSteps=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),r.forEach(((t,i)=>{e.setTextureFromPostProcessOutput("blurStep"+(r.length-i-1),t)}))})),u||this.updateEffect()}updateEffect(e=null,t=null,i=null,r,s,n){e||(e="",e+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),super.updateEffect(e,t,i,r,s,n)}}!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(DM||(DM={}));class BO extends AO{set focalLength(e){this._thinDepthOfFieldEffect.focalLength=e}get focalLength(){return this._thinDepthOfFieldEffect.focalLength}set fStop(e){this._thinDepthOfFieldEffect.fStop=e}get fStop(){return this._thinDepthOfFieldEffect.fStop}set focusDistance(e){this._thinDepthOfFieldEffect.focusDistance=e}get focusDistance(){return this._thinDepthOfFieldEffect.focusDistance}set lensSize(e){this._thinDepthOfFieldEffect.lensSize=e}get lensSize(){return this._thinDepthOfFieldEffect.lensSize}constructor(e,t,i=0,r=0,s=!1,n=!1){const o=e._renderForCamera?e.getEngine():e;super(o,"depth of field",(()=>this._effects),!0),this._effects=[],this._thinDepthOfFieldEffect=new I_("Depth of Field",o,i,!1,s);const a=o.isWebGPU||o.version>1?6:5;this._circleOfConfusion=new DO("circleOfConfusion",t,{size:1,samplingMode:vi.g.BILINEAR_SAMPLINGMODE,engine:o,textureType:r,blockCompilation:s,depthNotNormalized:n,effectWrapper:this._thinDepthOfFieldEffect._circleOfConfusion},null),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];const l=this._thinDepthOfFieldEffect._depthOfFieldBlurX.length;for(let e=0;enew VO(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,r)}}(0,X.Y5)("BABYLON.DisplayPassPostProcess",VO);class kO extends ms.w{getClassName(){return"FilterPostProcess"}constructor(e,t,i,r,s,n,o){super(e,"filter",["kernelMatrix"],null,i,r,s,n,o),this.kernelMatrix=t,this.onApply=e=>{e.setMatrix("kernelMatrix",this.kernelMatrix)}}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,26879))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,88770))])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return it.p.Parse((()=>new kO(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,r)}}(0,je.Cg)([(0,$e.GG)()],kO.prototype,"kernelMatrix",void 0),(0,X.Y5)("BABYLON.FilterPostProcess",kO);class UO extends ms.w{getClassName(){return"GrainPostProcess"}constructor(e,t,i,r,s,n,o=0,a=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,r,s,n,null,o,void 0,null,a),this.intensity=30,this.animated=!1,this.onApplyObservable.add((e=>{e.setFloat("intensity",this.intensity),e.setFloat("animatedSeed",this.animated?Math.random()+1:1)}))}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,35624))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,55099))])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return it.p.Parse((()=>new UO(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,r)}}(0,je.Cg)([(0,$e.lK)()],UO.prototype,"intensity",void 0),(0,je.Cg)([(0,$e.lK)()],UO.prototype,"animated",void 0),(0,X.Y5)("BABYLON.GrainPostProcess",UO);class GO extends ms.w{getClassName(){return"HighlightsPostProcess"}constructor(e,t,i,r,s,n,o=0){super(e,"highlights",null,null,t,i,r,s,n,null,o)}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,28162))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,13079))])),super._gatherImports(e,t)}}class zO extends ms.w{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 e=null;const t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){const i=t.scenes;e=i[i.length-1]}else e=he.q.LastCreatedScene;this._imageProcessingConfiguration=e?e.imageProcessingConfiguration:new gn.p}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateParameters()}))),t||this._updateParameters()}}get isSupported(){const e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,r,s,n,o=0,a){super(e,"imageProcessing",[],[],t,i,r,s,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},a?(a.applyByPostProcess=!0,this._attachImageProcessingConfiguration(a,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=e=>{this.imageProcessingConfiguration.bind(e,this.aspectRatio)}}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(i.bind(i,41123)))):t.push(Promise.resolve().then(i.bind(i,27220))),super._gatherImports(e,t)}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(const t in this._defines){const i=this._defines[t];switch(typeof i){case"number":case"string":e+=`#define ${t} ${i};\n`;break;default:i&&(e+=`#define ${t};\n`)}}const t=["textureSampler"],i=["scale"];gn.p&&(gn.p.PrepareSamplers(t,this._defines),gn.p.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)}}(0,je.Cg)([(0,$e.lK)()],zO.prototype,"_fromLinearSpace",void 0);var WO=i(2146),HO=i(24077);const XO=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureWidth"];(0,Ln.TV)(XO);class qO{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._enableDepth=!0,this._enableNormal=!0,this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._enableVelocityLinear=!1,this._enableScreenspaceDepth=!1,this._attachmentsFromPrePass=[]}_forceTextureType(e,t){e===qO.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===qO.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===qO.VELOCITY_LINEAR_TEXTURE_TYPE?(this._velocityLinearIndex=t,this._enableVelocityLinear=!0):e===qO.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===qO.DEPTH_TEXTURE_TYPE?(this._depthIndex=t,this._enableDepth=!0):e===qO.NORMAL_TEXTURE_TYPE?(this._normalIndex=t,this._enableNormal=!0):e===qO.SCREENSPACE_DEPTH_TEXTURE_TYPE&&(this._screenspaceDepthIndex=t,this._enableScreenspaceDepth=!0)}_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 qO.POSITION_TEXTURE_TYPE:return this._positionIndex;case qO.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case qO.VELOCITY_LINEAR_TEXTURE_TYPE:return this._velocityLinearIndex;case qO.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case qO.DEPTH_TEXTURE_TYPE:return this._depthIndex;case qO.NORMAL_TEXTURE_TYPE:return this._normalIndex;case qO.SCREENSPACE_DEPTH_TEXTURE_TYPE:return this._screenspaceDepthIndex;default:return-1}}get enableDepth(){return this._enableDepth}set enableDepth(e){this._enableDepth=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableNormal(){return this._enableNormal}set enableNormal(e){this._enableNormal=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}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 enableVelocityLinear(){return this._enableVelocityLinear}set enableVelocityLinear(e){this._enableVelocityLinear=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableScreenspaceDepth(){return this._enableScreenspaceDepth}set enableScreenspaceDepth(e){this._enableScreenspaceDepth=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return"object"==typeof this._ratioOrDimensions?1:this._ratioOrDimensions}get shaderLanguage(){return this._shaderLanguage}constructor(e,t=1,i=15,r){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._normalsAreUnsigned=!1,this._resizeObserver=null,this._enableDepth=!0,this._enableNormal=!0,this._enablePosition=!1,this._enableVelocity=!1,this._enableVelocityLinear=!1,this._enableReflectivity=!1,this._enableScreenspaceDepth=!1,this._clearColor=new H.ov(0,0,0,0),this._clearDepthColor=new H.ov(1e8,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._velocityLinearIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._screenspaceDepthIndex=-1,this._linkedWithPrePass=!1,this.useSpecificClearForDepthTexture=!1,this._shaderLanguage=0,this._shadersLoaded=!1,this._scene=e,this._ratioOrDimensions=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,this._textureTypesAndFormats=r||{},this._initShaderSourceAsync(),qO._SceneComponentInitialization(this._scene),this._createRenderTargets()}async _initShaderSourceAsync(){this._scene.getEngine().isWebGPU&&!qO.ForceGLSL?(this._shaderLanguage=1,await Promise.all([Promise.resolve().then(i.bind(i,20267)),Promise.resolve().then(i.bind(i,55745))])):await Promise.all([Promise.resolve().then(i.bind(i,24077)),Promise.resolve().then(i.bind(i,2146))]),this._shadersLoaded=!0}isReady(e,t){if(!this._shadersLoaded)return!1;const i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;const r=[],s=[st.R.PositionKind,st.R.NormalKind],n=e.getMesh();if(i){let e=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(r.push("#define ALPHATEST"),r.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),e=!0),(i.bumpTexture||i.normalTexture)&&Sn.BumpTextureEnabled){const t=i.bumpTexture||i.normalTexture;r.push("#define BUMP"),r.push(`#define BUMP_UV${t.coordinatesIndex+1}`),e=!0}if(this._enableReflectivity){let t=!1;"PBRMetallicRoughnessMaterial"===i.getClassName()?(i.metallicRoughnessTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!=i.metallic&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),t=!0),null!=i.roughness&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),t=!0),t&&(i.baseTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),e=!0),i.baseColor&&r.push("#define ALBEDOCOLOR"))):"PBRSpecularGlossinessMaterial"===i.getClassName()?(i.specularGlossinessTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),e=!0,i.specularGlossinessTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE")):i.specularColor&&r.push("#define REFLECTIVITYCOLOR"),null!=i.glossiness&&r.push("#define GLOSSINESS")):"PBRMaterial"===i.getClassName()?(i.metallicTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!=i.metallic&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),t=!0),null!=i.roughness&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),t=!0),t?(i.albedoTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),e=!0),i.albedoColor&&r.push("#define ALBEDOCOLOR")):(i.reflectivityTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0):i.reflectivityColor&&r.push("#define REFLECTIVITYCOLOR"),null!=i.microSurface&&r.push("#define GLOSSINESS"))):"StandardMaterial"===i.getClassName()&&(i.specularTexture&&(r.push("#define REFLECTIVITYTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0),i.specularColor&&r.push("#define REFLECTIVITYCOLOR"))}e&&(r.push("#define NEED_UV"),n.isVerticesDataPresent(st.R.UVKind)&&(s.push(st.R.UVKind),r.push("#define UV1")),n.isVerticesDataPresent(st.R.UV2Kind)&&(s.push(st.R.UV2Kind),r.push("#define UV2")))}this._enableDepth&&(r.push("#define DEPTH"),r.push("#define DEPTH_INDEX "+this._depthIndex)),this._enableNormal&&(r.push("#define NORMAL"),r.push("#define NORMAL_INDEX "+this._normalIndex)),this._enablePosition&&(r.push("#define POSITION"),r.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(r.push("#define VELOCITY"),r.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(n)&&r.push("#define BONES_VELOCITY_ENABLED")),this._enableVelocityLinear&&(r.push("#define VELOCITY_LINEAR"),r.push("#define VELOCITY_LINEAR_INDEX "+this._velocityLinearIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(n)&&r.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(r.push("#define REFLECTIVITY"),r.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this._enableScreenspaceDepth&&-1!==this._screenspaceDepthIndex&&(r.push("#define SCREENSPACE_DEPTH_INDEX "+this._screenspaceDepthIndex),r.push("#define SCREENSPACE_DEPTH")),this.generateNormalsInWorldSpace&&r.push("#define NORMAL_WORLDSPACE"),this._normalsAreUnsigned&&r.push("#define ENCODE_NORMAL"),n.useBones&&n.computeBonesUsingShaders&&n.skeleton?(s.push(st.R.MatricesIndicesKind),s.push(st.R.MatricesWeightsKind),n.numBoneInfluencers>4&&(s.push(st.R.MatricesIndicesExtraKind),s.push(st.R.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),r.push("#define BONETEXTURE "+n.skeleton.isUsingTextureForMatrices),r.push("#define BonesPerMesh "+(n.skeleton.bones.length+1))):(r.push("#define NUM_BONE_INFLUENCERS 0"),r.push("#define BONETEXTURE false"),r.push("#define BonesPerMesh 0"));const o=n.morphTargetManager;let a=0;o&&(a=o.numMaxInfluencers||o.numInfluencers,a>0&&(r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+a),o.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),(0,Bt.MF)(s,n,a))),t&&(r.push("#define INSTANCES"),(0,Bt.te)(s,this._enableVelocity||this._enableVelocityLinear),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES")),this._linkedWithPrePass?r.push("#define SCENE_MRT_COUNT "+this._attachmentsFromPrePass.length):r.push("#define SCENE_MRT_COUNT "+this._multiRenderTarget.textures.length),(0,Ln.tv)(i,this._scene,r);const l=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),c=h.defines,u=r.join("\n");return c!==u&&h.setEffect(l.createEffect("geometry",{attributes:s,uniformsNames:XO,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets","boneSampler"],defines:u,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:a},shaderLanguage:this.shaderLanguage},l),u),h.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=0;return this._enableDepth&&(this._depthIndex=i,i++,e.push("gBuffer_Depth"),t.push(this._textureTypesAndFormats[qO.DEPTH_TEXTURE_TYPE])),this._enableNormal&&(this._normalIndex=i,i++,e.push("gBuffer_Normal"),t.push(this._textureTypesAndFormats[qO.NORMAL_TEXTURE_TYPE])),this._enablePosition&&(this._positionIndex=i,i++,e.push("gBuffer_Position"),t.push(this._textureTypesAndFormats[qO.POSITION_TEXTURE_TYPE])),this._enableVelocity&&(this._velocityIndex=i,i++,e.push("gBuffer_Velocity"),t.push(this._textureTypesAndFormats[qO.VELOCITY_TEXTURE_TYPE])),this._enableVelocityLinear&&(this._velocityLinearIndex=i,i++,e.push("gBuffer_VelocityLinear"),t.push(this._textureTypesAndFormats[qO.VELOCITY_LINEAR_TEXTURE_TYPE])),this._enableReflectivity&&(this._reflectivityIndex=i,i++,e.push("gBuffer_Reflectivity"),t.push(this._textureTypesAndFormats[qO.REFLECTIVITY_TEXTURE_TYPE])),this._enableScreenspaceDepth&&(this._screenspaceDepthIndex=i,i++,e.push("gBuffer_ScreenspaceDepth"),t.push(this._textureTypesAndFormats[qO.SCREENSPACE_DEPTH_TEXTURE_TYPE])),[i,e,t]}_createRenderTargets(){const e=this._scene.getEngine(),[t,i,r]=this._assignRenderTargetIndices();let s=0;e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?s=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(s=2);const n=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions},o=[],a=[];for(const e of r)e?(o.push(e.textureType),a.push(e.textureFormat)):(o.push(s),a.push(5));if(this._normalsAreUnsigned=11===o[qO.NORMAL_TEXTURE_TYPE]||13===o[qO.NORMAL_TEXTURE_TYPE],this._multiRenderTarget=new Xb("gBuffer",n,t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,types:o,formats:a,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=vi.g.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=vi.g.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;const l=[!0],h=[!1],c=[!0];for(let e=1;e{e.bindAttachments(this.useSpecificClearForDepthTexture?d:u),e.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(e.bindAttachments(f),e.clear(this._clearDepthColor,!0,!0,!0)),e.bindAttachments(u)})),this._resizeObserver=e.onResizeObservable.add((()=>{if(this._multiRenderTarget){const t=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};this._multiRenderTarget.resize(t)}}));const p=e=>{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),r=this._scene,s=r.getEngine(),n=e.getMaterial();if(!n)return;if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,(this._enableVelocity||this._enableVelocityLinear)&&!this._previousTransformationMatrices[i.uniqueId]&&(this._previousTransformationMatrices[i.uniqueId]={world:W.uq.Identity(),viewProjection:r.getTransformMatrix()},t.skeleton)){const e=t.skeleton.getTransformMatrices(t);this._previousBonesTransformationMatrices[t.uniqueId]=this._copyBonesTransformationMatrices(e,new Float32Array(e.length))}const o=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;const a=s.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||t.hasThinInstances),l=i.getWorldMatrix();if(this.isReady(e,a)){const h=e._getDrawWrapper();if(!h)return;const c=h.effect;let u;s.enableEffect(h),a||t._bind(e,c,n.fillMode),this._useUbo?((0,Bt._8)(c,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(c.setMatrix("viewProjection",r.getTransformMatrix()),c.setMatrix("view",r.getViewMatrix()));const d=t._instanceDataStorage;if(d.isFrozen||!n.backFaceCulling&&null===n.sideOrientation)u=d.sideOrientation;else{const e=i._getWorldMatrixDeterminant();u=n._getEffectiveOrientation(t),e<0&&(u=u===Vt.ClockWiseSideOrientation?Vt.CounterClockWiseSideOrientation:Vt.ClockWiseSideOrientation)}if(n._preBind(h,u),n.needAlphaTesting()){const e=n.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if((n.bumpTexture||n.normalTexture)&&r.getEngine().getCaps().standardDerivatives&&Sn.BumpTextureEnabled){const e=n.bumpTexture||n.normalTexture;c.setFloat3("vBumpInfos",e.coordinatesIndex,1/e.level,n.parallaxScaleBias),c.setMatrix("bumpMatrix",e.getTextureMatrix()),c.setTexture("bumpSampler",e),c.setFloat2("vTangentSpaceParams",n.invertNormalMapX?-1:1,n.invertNormalMapY?-1:1)}if(this._enableReflectivity&&("PBRMetallicRoughnessMaterial"===n.getClassName()?(null!==n.metallicRoughnessTexture&&(c.setTexture("reflectivitySampler",n.metallicRoughnessTexture),c.setMatrix("reflectivityMatrix",n.metallicRoughnessTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.baseTexture&&(c.setTexture("albedoSampler",n.baseTexture),c.setMatrix("albedoMatrix",n.baseTexture.getTextureMatrix())),null!==n.baseColor&&c.setColor3("albedoColor",n.baseColor)):"PBRSpecularGlossinessMaterial"===n.getClassName()?(null!==n.specularGlossinessTexture?(c.setTexture("reflectivitySampler",n.specularGlossinessTexture),c.setMatrix("reflectivityMatrix",n.specularGlossinessTexture.getTextureMatrix())):null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor),null!==n.glossiness&&c.setFloat("glossiness",n.glossiness)):"PBRMaterial"===n.getClassName()?(null!==n.metallicTexture&&(c.setTexture("reflectivitySampler",n.metallicTexture),c.setMatrix("reflectivityMatrix",n.metallicTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.roughness||null!==n.metallic||null!==n.metallicTexture?(null!==n.albedoTexture&&(c.setTexture("albedoSampler",n.albedoTexture),c.setMatrix("albedoMatrix",n.albedoTexture.getTextureMatrix())),null!==n.albedoColor&&c.setColor3("albedoColor",n.albedoColor)):(null!==n.reflectivityTexture?(c.setTexture("reflectivitySampler",n.reflectivityTexture),c.setMatrix("reflectivityMatrix",n.reflectivityTexture.getTextureMatrix())):null!==n.reflectivityColor&&c.setColor3("reflectivityColor",n.reflectivityColor),null!==n.microSurface&&c.setFloat("glossiness",n.microSurface))):"StandardMaterial"===n.getClassName()&&(null!==n.specularTexture&&(c.setTexture("reflectivitySampler",n.specularTexture),c.setMatrix("reflectivityMatrix",n.specularTexture.getTextureMatrix())),null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor))),(0,Ln.gS)(c,n,this._scene),t.useBones&&t.computeBonesUsingShaders&&t.skeleton){const e=t.skeleton;if(e.isUsingTextureForMatrices&&c.getUniformIndex("boneTextureWidth")>-1){const i=e.getTransformMatrixTexture(t);c.setTexture("boneSampler",i),c.setFloat("boneTextureWidth",4*(e.bones.length+1))}else c.setMatrices("mBones",t.skeleton.getTransformMatrices(t));(this._enableVelocity||this._enableVelocityLinear)&&c.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[t.uniqueId])}(0,Bt.nR)(t,c),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(c),(this._enableVelocity||this._enableVelocityLinear)&&(c.setMatrix("previousWorld",this._previousTransformationMatrices[i.uniqueId].world),c.setMatrix("previousViewProjection",this._previousTransformationMatrices[i.uniqueId].viewProjection)),a&&t.hasThinInstances&&c.setMatrix("world",l),t._processRendering(i,e,c,n.fillMode,o,a,((e,t)=>{e||c.setMatrix("world",t)}))}(this._enableVelocity||this._enableVelocityLinear)&&(this._previousTransformationMatrices[i.uniqueId].world=l.clone(),this._previousTransformationMatrices[i.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),t.skeleton&&this._copyBonesTransformationMatrices(t.skeleton.getTransformMatrices(t),this._previousBonesTransformationMatrices[i.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(t,i,r)=>{if((r||0===i)&&t.subMeshes)for(let i=0;i{let n;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(s.length){for(e.setColorWrite(!1),n=0;n{throw(0,Je.n)("GeometryBufferRendererSceneComponent")};class YO{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(oi.Z.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(e){e&&e.isSupported&&(this._geometryBufferRenderer=e)},enumerable:!0,configurable:!0}),oi.Z.prototype.enableGeometryBufferRenderer=function(e=1,t=15,i){return this._geometryBufferRenderer||(this._geometryBufferRenderer=new qO(this,e,t,i),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null)),this._geometryBufferRenderer},oi.Z.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class KO{constructor(e){this.name=Ut.v.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(Ut.v.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}qO._SceneComponentInitialization=e=>{let t=e._getComponent(Ut.v.NAME_GEOMETRYBUFFERRENDERER);t||(t=new KO(e),e._addComponent(t))};class jO extends ms.w{get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this._motionBlurSamples=e,this._updateEffect()}get isObjectBased(){return this._isObjectBased}set isObjectBased(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"MotionBlurPostProcess"}constructor(e,t,i,r,s,n,o,a=0,l=!1,h=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,r,s,n,o,"#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED",a,void 0,null,l),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=h,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new YO)),this._applyMode()}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,95400))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,28377))])),super._gatherImports(e,t)}excludeSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}t.push(e)}}removeExcludedSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}const i=t.indexOf(e);-1!==i&&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 Z.V.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=W.uq.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 W.I9(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(qO.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.AA.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 W.I9(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(qO.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[t])}}_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("\n"))}}static _Parse(e,t,i,r){return it.p.Parse((()=>new jO(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,r)}}(0,je.Cg)([(0,$e.lK)()],jO.prototype,"motionStrength",void 0),(0,je.Cg)([(0,$e.lK)()],jO.prototype,"motionBlurSamples",null),(0,je.Cg)([(0,$e.lK)()],jO.prototype,"isObjectBased",null),(0,X.Y5)("BABYLON.MotionBlurPostProcess",jO);Cs.l.ShadersStore.refractionPixelShader="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);}";class $O extends ms.w{get refractionTexture(){return this._refTexture}set refractionTexture(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1}getClassName(){return"RefractionPostProcess"}constructor(e,t,i,r,s,n,o,a,l,h){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],n,o,a,l,h),this._ownRefractionTexture=!0,this.color=i,this.depth=r,this.colorLevel=s,this.refractionTextureUrl=t,this.onActivateObservable.add((e=>{this._refTexture=this._refTexture||new vi.g(t,e.getScene())})),this.onApplyObservable.add((e=>{e.setColor3("baseColor",this.color),e.setFloat("depth",this.depth),e.setFloat("colorLevel",this.colorLevel),e.setTexture("refractionSampler",this._refTexture)}))}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,r){return it.p.Parse((()=>new $O(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,r)}}(0,je.Cg)([(0,$e.lK)()],$O.prototype,"color",void 0),(0,je.Cg)([(0,$e.lK)()],$O.prototype,"depth",void 0),(0,je.Cg)([(0,$e.lK)()],$O.prototype,"colorLevel",void 0),(0,je.Cg)([(0,$e.lK)()],$O.prototype,"refractionTextureUrl",void 0),(0,X.Y5)("BABYLON.RefractionPostProcess",$O);var QO=i(3367);class ZO extends ms.w{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,r,s,n,o=0,a=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,r,s,n,null,o,void 0,null,a),this.colorAmount=1,this.edgeAmount=.3,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,68820))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,3367))])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return it.p.Parse((()=>new ZO(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,r)}}(0,je.Cg)([(0,$e.lK)()],ZO.prototype,"colorAmount",void 0),(0,je.Cg)([(0,$e.lK)()],ZO.prototype,"edgeAmount",void 0),(0,X.Y5)("BABYLON.SharpenPostProcess",ZO);class JO{get name(){return this._name}get cameras(){return this._cameras}get engine(){return this._engine}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(Ue.S0.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(Ue.S0.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=Ue.S0.MakeArray(e||this._cameras);if(!i)return;const r=[];let s;for(s=0;s0){const i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}_adaptPostProcessesToViewPort(){const e=Object.keys(this._renderEffects);for(const t of e){const e=this._renderEffects[t].getPostProcesses();if(e)for(const t of e)t.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}}(0,je.Cg)([(0,$e.lK)()],JO.prototype,"_name",void 0);class eD{constructor(){this._renderPipelines={}}get supportedPipelines(){const e=[];for(const t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){const i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e}addPipeline(e){this._renderPipelines[e._name]=e}removePipeline(e){delete this._renderPipelines[e]}attachCamerasToRenderPipeline(e,t,i=!1){const r=this._renderPipelines[e];r&&r._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){const i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){const r=this._renderPipelines[e];r&&r._enableEffect(t,i)}disableEffectInPipeline(e,t,i){const r=this._renderPipelines[e];r&&r._disableEffect(t,i)}update(){for(const e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){const t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e]._rebuild()}dispose(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e].dispose()}}Object.defineProperty(oi.Z.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let e=this._getComponent(Ut.v.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new tD(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new eD}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class tD{constructor(e){this.name=Ut.v.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(Ut.v.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 iD extends JO{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 MO(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 BO(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 MO(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new OO("ChromaticAberration",o.getRenderWidth(),o.getRenderHeight(),1,null,vi.g.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new AO(o,this.ChromaticAberrationPostProcessId,(()=>this.chromaticAberration),!0),this.grain=new UO("Grain",1,null,vi.g.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new AO(o,this.GrainPostProcessId,(()=>this.grain),!0);let a=!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,a?Ue.S0.SetImmediate((()=>{this._buildPipeline()})):this._buildPipeline())})),this._buildPipeline(),a=!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(),null!==this._cameras&&(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 e of this._cameras)this._scene.enableDepthRenderer(e).useOnlyInActiveCamera=!0;this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add((e=>{this._cameras.indexOf(e.activeCamera)>-1&&(this.depthOfField.depthTexture=e.enableDepthRenderer(e.activeCamera).getDepthMap())}))}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);const e=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=e.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 zO("imageProcessing",1,null,vi.g.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new AO(e,this.ImageProcessingPostProcessId,(()=>this.imageProcessing),!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._cameras&&0!==this._cameras.length||(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 kR("fxaa",1,null,vi.g.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new AO(e,this.FxaaPostProcessId,(()=>this.fxaa),!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera))&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add((()=>{this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera)&&(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&&Z.V.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 iD(e._name,e._name._hdr,t)),e,t,i)}}(0,je.Cg)([(0,$e.lK)()],iD.prototype,"sharpenEnabled",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"bloomKernel",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"_bloomWeight",void 0),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"_bloomThreshold",void 0),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"_hdr",void 0),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"bloomWeight",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"bloomThreshold",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"bloomScale",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"bloomEnabled",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"depthOfFieldEnabled",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"depthOfFieldBlurLevel",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"fxaaEnabled",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"samples",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"imageProcessingEnabled",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"glowLayerEnabled",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"chromaticAberrationEnabled",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"grainEnabled",null),(0,X.Y5)("BABYLON.DefaultRenderingPipeline",iD);var rD=i(76437);Cs.l.ShadersStore.lensHighlightsPixelShader="uniform sampler2D textureSampler; \nuniform 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; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;}\nfloat 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);\n#ifdef PENTAGON\nblurred+=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)));\n#else\nblurred+=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)));\n#endif\nblurred/=39.0;gl_FragColor=blurred;}";Cs.l.ShadersStore.depthOfFieldPixelShader="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; \nuniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV;\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \nvec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co)\n{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);}\nvec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; }\nvec2 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;}\nfloat 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;}\nfloat getBlurLevel(float size) {return min(3.0,ceil(size/1.0));}\nvec4 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);}\nif (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);}\ncol/=total_weight; \nif (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);}\nreturn col;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{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); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; }\nfloat 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;}\nfloat blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);}\nelse {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;}\nif (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;}}\nif (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;}}\n";class sD extends JO{constructor(e,t,i,r=1,s){super(i.getEngine(),e),this.LensChromaticAberrationEffect="LensChromaticAberrationEffect",this.HighlightsEnhancingEffect="HighlightsEnhancingEffect",this.LensDepthOfFieldEffect="LensDepthOfFieldEffect",this._pentagonBokehIsEnabled=!1,this._scene=i,this._depthTexture=i.enableDepthRenderer().getDepthMap(),t.grain_texture?this._grainTexture=t.grain_texture:this._createGrainTexture(),this._edgeBlur=t.edge_blur?t.edge_blur:0,this._grainAmount=t.grain_amount?t.grain_amount:0,this._chromaticAberration=t.chromatic_aberration?t.chromatic_aberration:0,this._distortion=t.distortion?t.distortion:0,this._highlightsGain=void 0!==t.dof_gain?t.dof_gain:-1,this._highlightsThreshold=t.dof_threshold?t.dof_threshold:1,this._dofDistance=void 0!==t.dof_focus_distance?t.dof_focus_distance:-1,this._dofAperture=t.dof_aperture?t.dof_aperture:1,this._dofDarken=t.dof_darken?t.dof_darken:0,this._dofPentagon=void 0===t.dof_pentagon||t.dof_pentagon,this._blurNoise=void 0===t.blur_noise||t.blur_noise,this._createChromaticAberrationPostProcess(r),this._createHighlightsPostProcess(r),this._createDepthOfFieldPostProcess(r/4),this.addEffect(new AO(i.getEngine(),this.LensChromaticAberrationEffect,(()=>this._chromaticAberrationPostProcess),!0)),this.addEffect(new AO(i.getEngine(),this.HighlightsEnhancingEffect,(()=>this._highlightsPostProcess),!0)),this.addEffect(new AO(i.getEngine(),this.LensDepthOfFieldEffect,(()=>this._depthOfFieldPostProcess),!0)),-1===this._highlightsGain&&this._disableEffect(this.HighlightsEnhancingEffect,null),i.postProcessRenderPipelineManager.addPipeline(this),s&&i.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}getClassName(){return"LensRenderingPipeline"}get scene(){return this._scene}get edgeBlur(){return this._edgeBlur}set edgeBlur(e){this.setEdgeBlur(e)}get grainAmount(){return this._grainAmount}set grainAmount(e){this.setGrainAmount(e)}get chromaticAberration(){return this._chromaticAberration}set chromaticAberration(e){this.setChromaticAberration(e)}get dofAperture(){return this._dofAperture}set dofAperture(e){this.setAperture(e)}get edgeDistortion(){return this._distortion}set edgeDistortion(e){this.setEdgeDistortion(e)}get dofDistortion(){return this._dofDistance}set dofDistortion(e){this.setFocusDistance(e)}get darkenOutOfFocus(){return this._dofDarken}set darkenOutOfFocus(e){this.setDarkenOutOfFocus(e)}get blurNoise(){return this._blurNoise}set blurNoise(e){this._blurNoise=e}get pentagonBokeh(){return this._pentagonBokehIsEnabled}set pentagonBokeh(e){e?this.enablePentagonBokeh():this.disablePentagonBokeh()}get highlightsGain(){return this._highlightsGain}set highlightsGain(e){this.setHighlightsGain(e)}get highlightsThreshold(){return this._highlightsThreshold}set highlightsThreshold(e){this.setHighlightsThreshold(e)}setEdgeBlur(e){this._edgeBlur=e}disableEdgeBlur(){this._edgeBlur=0}setGrainAmount(e){this._grainAmount=e}disableGrain(){this._grainAmount=0}setChromaticAberration(e){this._chromaticAberration=e}disableChromaticAberration(){this._chromaticAberration=0}setEdgeDistortion(e){this._distortion=e}disableEdgeDistortion(){this._distortion=0}setFocusDistance(e){this._dofDistance=e}disableDepthOfField(){this._dofDistance=-1}setAperture(e){this._dofAperture=e}setDarkenOutOfFocus(e){this._dofDarken=e}enablePentagonBokeh(){this._highlightsPostProcess.updateEffect("#define PENTAGON\n"),this._pentagonBokehIsEnabled=!0}disablePentagonBokeh(){this._pentagonBokehIsEnabled=!1,this._highlightsPostProcess.updateEffect()}enableNoiseBlur(){this._blurNoise=!0}disableNoiseBlur(){this._blurNoise=!1}setHighlightsGain(e){this._highlightsGain=e}setHighlightsThreshold(e){-1===this._highlightsGain&&(this._highlightsGain=1),this._highlightsThreshold=e}disableHighlights(){this._highlightsGain=-1}dispose(e=!1){this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),this._chromaticAberrationPostProcess=null,this._highlightsPostProcess=null,this._depthOfFieldPostProcess=null,this._grainTexture.dispose(),e&&this._scene.disableDepthRenderer()}_createChromaticAberrationPostProcess(e){this._chromaticAberrationPostProcess=new ms.w("LensChromaticAberration","chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],e,null,vi.g.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._chromaticAberrationPostProcess.onApply=e=>{e.setFloat("chromatic_aberration",this._chromaticAberration),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight()),e.setFloat("radialIntensity",1),e.setFloat2("direction",17,17),e.setFloat2("centerPosition",.5,.5)}}_createHighlightsPostProcess(e){this._highlightsPostProcess=new ms.w("LensHighlights","lensHighlights",["gain","threshold","screen_width","screen_height"],[],e,null,vi.g.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,this._dofPentagon?"#define PENTAGON\n":""),this._highlightsPostProcess.externalTextureSamplerBinding=!0,this._highlightsPostProcess.onApply=e=>{e.setFloat("gain",this._highlightsGain),e.setFloat("threshold",this._highlightsThreshold),e.setTextureFromPostProcess("textureSampler",this._chromaticAberrationPostProcess),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight())}}_createDepthOfFieldPostProcess(e){this._depthOfFieldPostProcess=new ms.w("LensDepthOfField","depthOfField",["grain_amount","blur_noise","screen_width","screen_height","distortion","dof_enabled","screen_distance","aperture","darken","edge_blur","highlights","near","far"],["depthSampler","grainSampler","highlightsSampler"],e,null,vi.g.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._depthOfFieldPostProcess.externalTextureSamplerBinding=!0,this._depthOfFieldPostProcess.onApply=e=>{e.setTexture("depthSampler",this._depthTexture),e.setTexture("grainSampler",this._grainTexture),e.setTextureFromPostProcess("textureSampler",this._highlightsPostProcess),e.setTextureFromPostProcess("highlightsSampler",this._depthOfFieldPostProcess),e.setFloat("grain_amount",this._grainAmount),e.setBool("blur_noise",this._blurNoise),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight()),e.setFloat("distortion",this._distortion),e.setBool("dof_enabled",-1!==this._dofDistance),e.setFloat("screen_distance",1/(.1-1/this._dofDistance)),e.setFloat("aperture",this._dofAperture),e.setFloat("darken",this._dofDarken),e.setFloat("edge_blur",this._edgeBlur),e.setBool("highlights",-1!==this._highlightsGain),this._scene.activeCamera&&(e.setFloat("near",this._scene.activeCamera.minZ),e.setFloat("far",this._scene.activeCamera.maxZ))}}_createGrainTexture(){const e=new Uint8Array(1048576);for(let t=0;tthis._originalColorPostProcess),!0)),this.addEffect(new AO(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new AO(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new AO(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new AO(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let e=0;e{e?t.push(Promise.resolve().then(i.bind(i,20661))):t.push(Promise.resolve().then(i.bind(i,33258)))}));return a.onApply=e=>{if(!this._scene.activeCamera)return;const t=o?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,i=o?this._originalColorPostProcess.width:this._originalColorPostProcess.height;e.setFloat("outSize",t>0?t:i),e.setInt("samples",this.bilateralSamples),e.setFloat("soften",this.bilateralSoften),e.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)])},a.samples=this.textureSamples,a.autoClear=!1,a}_radicalInverse_VdC(e){return this._bits[0]=e,this._bits[0]=(this._bits[0]<<16|this._bits[0]>>16)>>>0,this._bits[0]=(1431655765&this._bits[0])<<1|(2863311530&this._bits[0])>>>1>>>0,this._bits[0]=(858993459&this._bits[0])<<2|(3435973836&this._bits[0])>>>2>>>0,this._bits[0]=(252645135&this._bits[0])<<4|(4042322160&this._bits[0])>>>4>>>0,this._bits[0]=(16711935&this._bits[0])<<8|(4278255360&this._bits[0])>>>8>>>0,2.3283064365386963e-10*this._bits[0]}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){const i=2*t*Math.PI,r=1-.85*e,s=Math.sqrt(1-r*r);return new W.Pq(Math.cos(i)*s,Math.sin(i)*s,r)}_generateHemisphere(){const e=this.samples,t=[];let i,r=0;for(;r{e?t.push(Promise.resolve().then(i.bind(i,20661))):t.push(Promise.resolve().then(i.bind(i,33258)))})),this._ssaoPostProcess.autoClear=!1,this._ssaoPostProcess.onApply=e=>{if(this._scene.activeCamera){if(e.setArray3("sampleSphere",this._sampleSphere),e.setFloat("randTextureTiles",32),e.setFloat("samplesFactor",1/this.samples),e.setFloat("totalStrength",this.totalStrength),e.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),e.setFloat("radius",this.radius),e.setFloat("maxZ",this.maxZ),e.setFloat("minZAspect",this.minZAspect),e.setFloat("base",this.base),e.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===rt.PERSPECTIVE_CAMERA)e.setMatrix3x3("depthProjection",oD.PERSPECTIVE_DEPTH_PROJECTION),e.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),e.setFloat("yViewport",Math.tan(this._scene.activeCamera.fov/2));else{const t=this._scene.getEngine().getRenderWidth()/2,i=this._scene.getEngine().getRenderHeight()/2,r=this._scene.activeCamera.orthoLeft??-t,s=this._scene.activeCamera.orthoRight??t,n=this._scene.activeCamera.orthoBottom??-i,o=this._scene.activeCamera.orthoTop??i;e.setMatrix3x3("depthProjection",oD.ORTHO_DEPTH_PROJECTION),e.setFloat("xViewport",.5*(s-r)),e.setFloat("yViewport",.5*(o-n))}e.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),e.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),e.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),e.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new nD)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new ms.w("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t,void 0,void 0,void 0,void 0,this._scene.getEngine().isWebGPU?1:0,((e,t)=>{e?t.push(Promise.resolve().then(i.bind(i,93640))):t.push(Promise.resolve().then(i.bind(i,85387)))})),this._ssaoCombinePostProcess.onApply=e=>{const t=this._scene.activeCamera.viewport;e.setVector4("viewport",W.AA.Vector4[0].copyFromFloats(t.x,t.y,t.width,t.height)),e.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.autoClear=!1,this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){const e=new Uint8Array(65536),t=W.I9.Zero();for(let i=0;inew oD(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType)),e,t,i)}}oD.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1],oD.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1],(0,je.Cg)([(0,$e.lK)()],oD.prototype,"totalStrength",void 0),(0,je.Cg)([(0,$e.lK)()],oD.prototype,"maxZ",void 0),(0,je.Cg)([(0,$e.lK)()],oD.prototype,"minZAspect",void 0),(0,je.Cg)([(0,$e.lK)("epsilon")],oD.prototype,"_epsilon",void 0),(0,je.Cg)([(0,$e.lK)("samples")],oD.prototype,"_samples",void 0),(0,je.Cg)([(0,$e.lK)("textureSamples")],oD.prototype,"_textureSamples",void 0),(0,je.Cg)([(0,$e.lK)()],oD.prototype,"_forceGeometryBuffer",void 0),(0,je.Cg)([(0,$e.lK)()],oD.prototype,"_ratio",void 0),(0,je.Cg)([(0,$e.lK)()],oD.prototype,"_textureType",void 0),(0,je.Cg)([(0,$e.lK)()],oD.prototype,"radius",void 0),(0,je.Cg)([(0,$e.lK)()],oD.prototype,"base",void 0),(0,je.Cg)([(0,$e.lK)("bypassBlur")],oD.prototype,"_bypassBlur",void 0),(0,je.Cg)([(0,$e.lK)("expensiveBlur")],oD.prototype,"_expensiveBlur",void 0),(0,je.Cg)([(0,$e.lK)()],oD.prototype,"bilateralSamples",void 0),(0,je.Cg)([(0,$e.lK)()],oD.prototype,"bilateralSoften",void 0),(0,je.Cg)([(0,$e.lK)()],oD.prototype,"bilateralTolerance",void 0),(0,X.Y5)("BABYLON.SSAO2RenderingPipeline",oD);Cs.l.ShadersStore.ssaoPixelShader="uniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSAO\nuniform 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)\n{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);}\nvoid main()\n{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 AO(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new AO(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new AO(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new AO(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}_attachCameras(e,t){super._attachCameras(e,t);for(const e of this._cameras)this._scene.enableDepthRenderer(e).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let e=0;e{const e=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*e})),this._blurVPostProcess.onActivateObservable.add((()=>{const e=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*e}))}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){const t=[.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];this._ssaoPostProcess=new ms.w("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define SAMPLES 16\n#define SSAO"),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=e=>{this._firstUpdate&&(e.setArray3("sampleSphere",t),e.setFloat("samplesFactor",.0625),e.setFloat("randTextureTiles",4)),e.setFloat("totalStrength",this.totalStrength),e.setFloat("radius",this.radius),e.setFloat("area",this.area),e.setFloat("fallOff",this.fallOff),e.setFloat("base",this.base),e.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),e.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new ms.w("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=e=>{e.setVector4("viewport",W.AA.Vector4[0].copyFromFloats(0,0,1,1)),e.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){const e=new Uint8Array(1048576);for(let t=0;t0.0)\nhitCoord-=dir;else\nhitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;}\nprojectedCoord=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;}\n/**\n* Tests the given world position (hitCoord) according to the given reflection vector (dir)\n* until it finds a collision (means that depth is enough close to say \"it's the pixel to sample!\").\n*/\nReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord)\n{ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i{const i=this._geometryBufferRenderer,r=this._prePassRenderer;if(!r&&!i)return;if(i){const t=i.getTextureIndex(qO.POSITION_TEXTURE_TYPE),r=i.getTextureIndex(qO.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("positionSampler",i.getGBuffer().textures[t]),e.setTexture("reflectivitySampler",i.getGBuffer().textures[r])}else if(r){const t=r.getIndex(1),i=r.getIndex(3),s=r.getIndex(6);e.setTexture("normalSampler",r.getRenderTarget().textures[s]),e.setTexture("positionSampler",r.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",r.getRenderTarget().textures[i])}const s=t.activeCamera;if(!s)return;const n=s.getViewMatrix(!0),o=s.getProjectionMatrix(!0);e.setMatrix("projection",o),e.setMatrix("view",n),e.setFloat("threshold",this.threshold),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.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 "+(0|this._reflectionSamples)),e.push("#define SMOOTH_STEPS "+(0|this._smoothSteps)),this.updateEffect(e.join("\n"))}static _Parse(e,t,i,r){return it.p.Parse((()=>new cD(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,r)}}(0,je.Cg)([(0,$e.lK)()],cD.prototype,"threshold",void 0),(0,je.Cg)([(0,$e.lK)()],cD.prototype,"strength",void 0),(0,je.Cg)([(0,$e.lK)()],cD.prototype,"reflectionSpecularFalloffExponent",void 0),(0,je.Cg)([(0,$e.lK)()],cD.prototype,"step",void 0),(0,je.Cg)([(0,$e.lK)()],cD.prototype,"roughnessFactor",void 0),(0,je.Cg)([(0,$e.lK)()],cD.prototype,"enableSmoothReflections",null),(0,je.Cg)([(0,$e.lK)()],cD.prototype,"reflectionSamples",null),(0,je.Cg)([(0,$e.lK)()],cD.prototype,"smoothSteps",null),(0,X.Y5)("BABYLON.ScreenSpaceReflectionPostProcess",cD);Cs.l.ShadersStore.standardPixelShader="uniform sampler2D textureSampler;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];void main(void)\n{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;}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void)\n{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)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;}\naccumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;void main(void)\n{gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];void main()\n{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++)\n{color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));}\naverage=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];uniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\n#include\n#endif\nvoid main()\n{vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++)\n{color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;uniform float averageLuminance;void main()\n{vec4 color=texture2D(textureAdderSampler,vUV);\n#ifndef AUTO_EXPOSURE\nvec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0;\n#endif\ngl_FragColor=color;}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p)\n{float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);}\nfloat noise(in vec2 p)\n{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)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);}\nfloat fbm(vec2 p)\n{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;}\nvec3 pattern(vec2 uv)\n{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);}\nfloat luminance(vec3 color)\n{return dot(color.rgb,vec3(0.2126,0.7152,0.0722));}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{return vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);}\nvoid main(void)\n{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)\nbreak;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);}\ngl_FragColor=result/float(nSamples);}\n#endif\n";class uD extends JO{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("\n"))}}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())return void Z.V.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");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\n#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\n#define MAX_MOTION_SAMPLES "+e.toFixed(1))),this._motionBlurSamples=e}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}constructor(e,t,i,r=null,s){super(t.getEngine(),e),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.blurHPostProcesses=[],this.blurVPostProcesses=[],this.textureAdderPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.luminancePostProcess=null,this.luminanceDownSamplePostProcesses=[],this.hdrPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlareFinalPostProcess=null,this.hdrFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.motionBlurPostProcess=null,this.depthOfFieldPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.brightThreshold=1,this.blurWidth=512,this.horizontalBlur=!1,this.lensTexture=null,this.volumetricLightCoefficient=.2,this.volumetricLightPower=4,this.volumetricLightBlurScale=64,this.sourceLight=null,this.hdrMinimumLuminance=1,this.hdrDecreaseRate=.5,this.hdrIncreaseRate=.5,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensFlareBlurWidth=512,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.depthOfFieldBlurWidth=64,this.animations=[],this._currentDepthOfFieldSource=null,this._fixedExposure=1,this._currentExposure=1,this._hdrAutoExposure=!1,this._hdrCurrentLuminance=1,this._motionStrength=1,this._isObjectBasedMotionBlur=!1,this._camerasToBeAttached=[],this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._vlsEnabled=!1,this._lensFlareEnabled=!1,this._hdrEnabled=!1,this._motionBlurEnabled=!1,this._fxaaEnabled=!1,this._screenSpaceReflectionsEnabled=!1,this._motionBlurSamples=64,this._volumetricLightStepsCount=50,this._samples=1,this._cameras=s||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=r,this._ratio=i,this._floatTextureType=t.getEngine().getCaps().textureFloatRender?1:2,t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline()}_buildPipeline(){const e=this._ratio,t=this._scene;this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new cD("HDRPass",t,e,null,vi.g.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add((()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess})),this.addEffect(new AO(t.getEngine(),"HDRScreenSpaceReflections",(()=>this.screenSpaceReflectionPostProcess),!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new ms.w("HDRPass","standard",[],[],e,null,vi.g.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 AO(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 ms.w("HDRDepthOfFieldSource","standard",[],[],e,null,vi.g.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new AO(t.getEngine(),"HDRBaseDepthOfFieldSource",(()=>this.textureAdderFinalPostProcess),!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new ms.w("HDRVLSFinal","standard",[],[],e,null,vi.g.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new AO(t.getEngine(),"HDRVLSFinal",(()=>this.volumetricLightFinalPostProcess),!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new ms.w("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,vi.g.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new AO(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",(()=>this.lensFlareFinalPostProcess),!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new ms.w("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,vi.g.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new AO(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 kR("fxaa",1,null,vi.g.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new AO(t.getEngine(),"HDRFxaa",(()=>this.fxaaPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&Z.V.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 ms.w("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=e=>{let t=0;const r=this.downSampleX4PostProcess.width,s=this.downSampleX4PostProcess.height;for(let e=-2;e<2;e++)for(let n=-2;n<2;n++)i[t]=(e+.5)*(1/r),i[t+1]=(n+.5)*(1/s),t+=2;e.setArray2("dsOffsets",i)},this.addEffect(new AO(e.getEngine(),"HDRDownSampleX4",(()=>this.downSampleX4PostProcess),!0))}_createBrightPassPostProcess(e,t){const i=new Array(8);this.brightPassPostProcess=new ms.w("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=e=>{const t=1/this.brightPassPostProcess.width,r=1/this.brightPassPostProcess.height;i[0]=-.5*t,i[1]=.5*r,i[2]=.5*t,i[3]=.5*r,i[4]=-.5*t,i[5]=-.5*r,i[6]=.5*t,i[7]=-.5*r,e.setArray2("dsOffsets",i),e.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new AO(e.getEngine(),"HDRBrightPass",(()=>this.brightPassPostProcess),!0))}_createBlurPostProcesses(e,t,i,r="blurWidth"){const s=e.getEngine(),n=new _m("HDRBlurH_"+i,new W.I9(1,0),this[r],t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),o=new _m("HDRBlurV_"+i,new W.I9(0,1),this[r],t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);n.onActivateObservable.add((()=>{const e=n.width/s.getRenderWidth();n.kernel=this[r]*e})),o.onActivateObservable.add((()=>{const e=o.height/s.getRenderHeight();o.kernel=this.horizontalBlur?64*e:this[r]*e})),this.addEffect(new AO(e.getEngine(),"HDRBlurH"+i,(()=>n),!0)),this.addEffect(new AO(e.getEngine(),"HDRBlurV"+i,(()=>o),!0)),this.blurHPostProcesses.push(n),this.blurVPostProcesses.push(o)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new ms.w("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._vlsEnabled?this._currentDepthOfFieldSource:this.originalPostProcess),e.setTexture("lensSampler",this.lensTexture),e.setFloat("exposure",this._currentExposure),this._currentDepthOfFieldSource=this.textureAdderFinalPostProcess},this.addEffect(new AO(e.getEngine(),"HDRTextureAdder",(()=>this.textureAdderPostProcess),!0))}_createVolumetricLightPostProcess(e,t){const i=e.enableGeometryBufferRenderer();i.enablePosition=!0;const r=i.getGBuffer();this.volumetricLightPostProcess=new ms.w("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));const s=W.I9.Zero();this.volumetricLightPostProcess.onApply=e=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){const t=this.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",r.textures[2]),e.setColor3("sunColor",this.sourceLight.diffuse),e.setVector3("sunDirection",this.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),e.setFloat("scatteringPower",this.volumetricLightPower),s.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),s.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),e.setVector2("depthValues",s)}},this.addEffect(new AO(e.getEngine(),"HDRVLS",(()=>this.volumetricLightPostProcess),!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new ms.w("HDRVLSMerge","standard",[],["originalSampler"],t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=e=>{e.setTextureFromPostProcess("originalSampler",this._bloomEnabled?this.textureAdderFinalPostProcess:this.originalPostProcess),this._currentDepthOfFieldSource=this.volumetricLightFinalPostProcess},this.addEffect(new AO(e.getEngine(),"HDRVLSMerge",(()=>this.volumetricLightMergePostProces),!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,uD.LuminanceSteps);this.luminancePostProcess=new ms.w("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);const r=[];this.luminancePostProcess.onApply=e=>{const t=1/this.luminancePostProcess.width,i=1/this.luminancePostProcess.height;r[0]=-.5*t,r[1]=.5*i,r[2]=.5*t,r[3]=.5*i,r[4]=-.5*t,r[5]=-.5*i,r[6]=.5*t,r[7]=-.5*i,e.setArray2("lumOffsets",r)},this.addEffect(new AO(e.getEngine(),"HDRLuminance",(()=>this.luminancePostProcess),!0));for(let r=uD.LuminanceSteps-1;r>=0;r--){i=Math.pow(3,r);let s="#define LUMINANCE_DOWN_SAMPLE\n";0===r&&(s+="#define FINAL_DOWN_SAMPLER");const n=new ms.w("HDRLuminanceDownSample"+r,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,t);this.luminanceDownSamplePostProcesses.push(n)}let s=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach(((t,i)=>{const r=new Array(18);t.onApply=e=>{if(!s)return;let n=0;for(let e=-1;e<2;e++)for(let t=-1;t<2;t++)r[n]=e/s.width,r[n+1]=t/s.height,n+=2;e.setArray2("dsOffsets",r),e.setFloat("halfDestPixelSize",.5/s.width),s=i===this.luminanceDownSamplePostProcesses.length-1?this.luminancePostProcess:t},i===this.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=()=>{const t=e.getEngine().readPixels(0,0,1,1),i=new W.IU(1/16581375,1/65025,1/255,1);t.then((e=>{const t=new Uint8Array(e.buffer);this._hdrCurrentLuminance=(t[0]*i.x+t[1]*i.y+t[2]*i.z+t[3]*i.w)/100}))}),this.addEffect(new AO(e.getEngine(),"HDRLuminanceDownSample"+i,(()=>t),!0))}))}_createHdrPostProcess(e,t){const i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new ms.w("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join("\n"),0);let r=1,s=0,n=0;this.hdrPostProcess.onApply=t=>{if(t.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),s+=e.getEngine().getDeltaTime(),r<0)r=this._hdrCurrentLuminance;else{const e=(n-s)/1e3;this._hdrCurrentLuminancer-this.hdrIncreaseRate*e?r-=this.hdrIncreaseRate*e:r=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/r:(r=(0,ar.Clamp)(r,this.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",r)),n=s,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new AO(e.getEngine(),"HDR",(()=>this.hdrPostProcess),!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new ms.w("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new AO(e.getEngine(),"HDRLensFlare",(()=>this.lensFlarePostProcess),!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new ms.w("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new AO(e.getEngine(),"HDRLensFlareCompose",(()=>this.lensFlareComposePostProcess),!0));const i=new W.I9(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=e=>{e.setTextureFromPostProcess("textureSampler",this._bloomEnabled?this.blurHPostProcesses[0]:this.originalPostProcess),e.setTexture("lensColorSampler",this.lensColorTexture),e.setFloat("strength",this.lensFlareStrength),e.setFloat("ghostDispersal",this.lensFlareGhostDispersal),e.setFloat("haloWidth",this.lensFlareHaloWidth),i.x=this.lensFlarePostProcess.width,i.y=this.lensFlarePostProcess.height,e.setVector2("resolution",i),e.setFloat("distortionStrength",this.lensFlareDistortionStrength)};const r=W.uq.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=W.uq.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=e=>{if(!this._scene.activeCamera)return;e.setTextureFromPostProcess("otherSampler",this.lensFlarePostProcess),e.setTexture("lensDirtSampler",this.lensFlareDirtTexture),e.setTexture("lensStarSampler",this.lensStarTexture);const t=this._scene.activeCamera.getViewMatrix().getRow(0),i=this._scene.activeCamera.getViewMatrix().getRow(2);let n=W.Pq.Dot(t.toVector3(),new W.Pq(1,0,0))+W.Pq.Dot(i.toVector3(),new W.Pq(0,0,1));n*=4;const o=W.uq.FromValues(.5*Math.cos(n),-Math.sin(n),0,0,Math.sin(n),.5*Math.cos(n),0,0,0,0,1,0,0,0,0,1),a=s.multiply(o).multiply(r);e.setMatrix("lensStarMatrix",a),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new ms.w("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",0),this.depthOfFieldPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._currentDepthOfFieldSource),e.setTexture("depthSampler",this._getDepthTexture()),e.setFloat("distance",this.depthOfFieldDistance)},this.addEffect(new AO(e.getEngine(),"HDRDepthOfField",(()=>this.depthOfFieldPostProcess),!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){const i=new jO("HDRMotionBlur",e,t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new ms.w("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),0);let i=0,r=W.uq.Identity();const s=W.uq.Identity();let n=W.uq.Identity();const o=W.I9.Zero();this.motionBlurPostProcess.onApply=t=>{n=e.getProjectionMatrix().multiply(e.getViewMatrix()),n.invertToRef(s),t.setMatrix("inverseViewProjection",s),t.setMatrix("prevViewProjection",r),r=n,o.x=this.motionBlurPostProcess.width,o.y=this.motionBlurPostProcess.height,t.setVector2("screenSize",o),i=e.getEngine().getFps()/60,t.setFloat("motionScale",i),t.setFloat("motionStrength",this.motionStrength),t.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new AO(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 uD(e._name,t,e._ratio)),e,t,i);return e.sourceLightId&&(r.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&it.p.Parse((()=>r.screenSpaceReflectionPostProcess),e.screenSpaceReflectionPostProcess,t,i),r}}uD.LuminanceSteps=6,(0,je.Cg)([(0,$e.lK)()],uD.prototype,"brightThreshold",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"blurWidth",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"horizontalBlur",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"exposure",null),(0,je.Cg)([(0,$e.uM)("lensTexture")],uD.prototype,"lensTexture",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"volumetricLightCoefficient",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"volumetricLightPower",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"volumetricLightBlurScale",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"hdrMinimumLuminance",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"hdrDecreaseRate",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"hdrIncreaseRate",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"hdrAutoExposure",null),(0,je.Cg)([(0,$e.uM)("lensColorTexture")],uD.prototype,"lensColorTexture",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"lensFlareStrength",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"lensFlareGhostDispersal",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"lensFlareHaloWidth",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"lensFlareDistortionStrength",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"lensFlareBlurWidth",void 0),(0,je.Cg)([(0,$e.uM)("lensStarTexture")],uD.prototype,"lensStarTexture",void 0),(0,je.Cg)([(0,$e.uM)("lensFlareDirtTexture")],uD.prototype,"lensFlareDirtTexture",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"depthOfFieldDistance",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"depthOfFieldBlurWidth",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"motionStrength",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"objectBasedMotionBlur",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"_ratio",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"BloomEnabled",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"DepthOfFieldEnabled",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"LensFlareEnabled",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"HDREnabled",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"VLSEnabled",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"MotionBlurEnabled",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"fxaaEnabled",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"screenSpaceReflectionsEnabled",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"volumetricLightStepsCount",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"motionBlurSamples",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"samples",null),(0,X.Y5)("BABYLON.StandardRenderingPipeline",uD);class dD{constructor(e=!1){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3],this.texturesRequired.push(e?10:5)}}const fD=W.uq.Compose(new W.Pq(.5,.5,.5),W.PT.Identity(),new W.Pq(.5,.5,.5)),pD=W.uq.Compose(new W.Pq(.5,.5,1),W.PT.Identity(),new W.Pq(.5,.5,0));class _D extends JO{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&&(0===e&&0!==this._reflectivityThreshold||0!==e&&0===this._reflectivityThreshold?(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=0===e&&0!==this._blurDispersionStrength||0!==e&&0===this._blurDispersionStrength;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():null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get inputTextureColorIsInGammaSpace(){return this._inputTextureColorIsInGammaSpace}set inputTextureColorIsInGammaSpace(e){this._inputTextureColorIsInGammaSpace!==e&&(this._inputTextureColorIsInGammaSpace=e,this._buildPipeline())}get generateOutputInGammaSpace(){return this._generateOutputInGammaSpace}set generateOutputInGammaSpace(e){this._generateOutputInGammaSpace!==e&&(this._generateOutputInGammaSpace=e,this._buildPipeline())}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._buildPipeline())}getScene(){return this._scene}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}get scene(){return this._scene}get isSupported(){const e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch}constructor(e,t,i,r=!1,s=0,n=!1){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._useScreenspaceDepth=!1,this._environmentTextureIsProbe=!1,this._attenuateScreenBorders=!0,this._attenuateIntersectionDistance=!0,this._attenuateIntersectionIterations=!0,this._attenuateFacingCamera=!1,this._attenuateBackfaceReflection=!1,this._clipToFrustum=!0,this._useFresnel=!1,this._enableAutomaticThicknessComputation=!1,this._backfaceDepthTextureDownsample=0,this._backfaceForceDepthWriteTransparentMeshes=!0,this._isEnabled=!0,this._inputTextureColorIsInGammaSpace=!0,this._generateOutputInGammaSpace=!0,this._debug=!1,this._forceGeometryBuffer=!1,this._isDirty=!1,this._camerasToBeAttached=[],this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=s,this._forceGeometryBuffer=r,this._useScreenspaceDepth=n,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){const e=t.enableGeometryBufferRenderer();e&&(e.enableReflectivity=!0,e.useSpecificClearForDepthTexture=!0,e.enableScreenspaceDepth=this._useScreenspaceDepth,e.enableDepth=!this._useScreenspaceDepth)}else{const e=t.enablePrePassRenderer();e&&(e.useSpecificClearForDepthTexture=!0,e.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(){const e=this._scene.getEngine(),t=this._prePassRenderer;let i={width:e.getRenderWidth(),height:e.getRenderHeight()};if(t&&this._scene.activeCamera?._getFirstPostProcess()===this._ssrPostProcess){const e=t.getRenderTarget();e&&e.textures&&(i=e.textures[t.getIndex(4)].getSize())}else this._ssrPostProcess?.inputTexture&&(i.width=this._ssrPostProcess.inputTexture.width,i.height=this._ssrPostProcess.inputTexture.height);return i}_updateEffectDefines(){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._useScreenspaceDepth&&e.push("#define SSRAYTRACE_SCREENSPACE_DEPTH"),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"),0===this._reflectivityThreshold&&e.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),(this._geometryBufferRenderer?.generateNormalsInWorldSpace??this._prePassRenderer?.generateNormalsInWorldSpace)&&e.push("#define SSR_NORMAL_IS_IN_WORLDSPACE"),this._geometryBufferRenderer?.normalsAreUnsigned&&e.push("#define SSR_DECODE_NORMAL");const t=this._cameras?.[0];t&&1===t.mode&&e.push("#define ORTHOGRAPHIC_CAMERA"),this._ssrPostProcess?.updateEffect(e.join("\n"))}_buildPipeline(){if(!this.isSupported)return;if(!this._isEnabled)return void(this._isDirty=!0);this._isDirty=!1;const e=this._scene.getEngine();if(this._disposeDepthRenderer(),this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._enableAutomaticThicknessComputation){const e=this._cameras?.[0];e&&(this._depthRendererCamera=e,this._depthRenderer=new px(this._scene,void 0,void 0,this._useScreenspaceDepth,1,!this._useScreenspaceDepth,"SSRBackDepth"),this._useScreenspaceDepth||(this._depthRenderer.clearColor.r=1e8),this._depthRenderer.reverseCulling=!0,this._depthRenderer.forceDepthWriteTransparentMeshes=this._backfaceForceDepthWriteTransparentMeshes,this._resizeDepthRenderer(),e.customRenderTargets.push(this._depthRenderer.getDepthMap()))}this._createSSRPostProcess(),this.addEffect(new AO(e,this.SSRRenderEffect,(()=>this._ssrPostProcess),!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new AO(e,this.SSRBlurRenderEffect,(()=>[this._blurPostProcessX,this._blurPostProcessY]),!0)),this.addEffect(new AO(e,this.SSRCombineRenderEffect,(()=>this._blurCombinerPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_resizeDepthRenderer(){if(!this._depthRenderer)return;const e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),r=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));t.width===i&&t.height===r||this._depthRenderer.getDepthMap().resize({width:i,height:r})}_disposeDepthRenderer(){if(this._depthRenderer){if(this._depthRendererCamera){const e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap())??-1;-1!==e&&this._depthRendererCamera.customRenderTargets.splice(e,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){for(let e=0;e{e?t.push(Promise.resolve().then(i.bind(i,98e3))):t.push(Promise.resolve().then(i.bind(i,87193)))})),this._updateEffectDefines(),this._ssrPostProcess.onApply=e=>{this._resizeDepthRenderer();const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){const i=t.getTextureIndex(qO.REFLECTIVITY_TEXTURE_TYPE),r=t.getTextureIndex(qO.NORMAL_TEXTURE_TYPE);if(e.setTexture("normalSampler",t.getGBuffer().textures[r]),e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),this._useScreenspaceDepth){const i=t.getTextureIndex(qO.SCREENSPACE_DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",t.getGBuffer().textures[i])}else{const i=t.getTextureIndex(qO.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",t.getGBuffer().textures[i])}}else if(i){const t=i.getIndex(this._useScreenspaceDepth?10:5),r=i.getIndex(3),s=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[s]),e.setTexture("depthSampler",i.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[r])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));const r=this._scene.activeCamera;if(!r)return;const s=r.getViewMatrix(),n=r.getProjectionMatrix();n.invertToRef(W.AA.Matrix[0]),s.invertToRef(W.AA.Matrix[1]),e.setMatrix("projection",n),e.setMatrix("view",s),e.setMatrix("invView",W.AA.Matrix[1]),e.setMatrix("invProjectionMatrix",W.AA.Matrix[0]),e.setFloat("thickness",this.thickness),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("maxSteps",this.maxSteps),e.setFloat("roughnessFactor",this.roughnessFactor),e.setFloat("nearPlaneZ",r.minZ),e.setFloat("farPlaneZ",r.maxZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);const o=this._getTextureSize();W.uq.ScalingToRef(o.width,o.height,1,W.AA.Matrix[2]),n.multiplyToRef(this._scene.getEngine().isWebGPU?pD:fD,W.AA.Matrix[3]),W.AA.Matrix[3].multiplyToRef(W.AA.Matrix[2],W.AA.Matrix[4]),e.setMatrix("projectionPixel",W.AA.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 dD(this._useScreenspaceDepth))}_createBlurAndCombinerPostProcesses(){const e=this._scene.getEngine();this._blurPostProcessX=new ms.w("SSRblurX","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._ssrDownsample+1):1,null,2,e,!1,"",this._textureType,void 0,void 0,void 0,void 0,this._scene.getEngine().isWebGPU?1:0,((e,t)=>{e?t.push(Promise.resolve().then(i.bind(i,86763))):t.push(Promise.resolve().then(i.bind(i,83514)))})),this._blurPostProcessX.autoClear=!1,this._blurPostProcessX.onApplyObservable.add((e=>{const t=this._blurPostProcessX?.inputTexture.width??this._scene.getEngine().getRenderWidth();e.setFloat2("texelOffsetScale",this._blurDispersionStrength/t,0)})),this._blurPostProcessY=new ms.w("SSRblurY","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._blurDownsample+1):1,null,2,e,!1,"",this._textureType,void 0,void 0,void 0,void 0,this._scene.getEngine().isWebGPU?1:0,((e,t)=>{e?t.push(Promise.resolve().then(i.bind(i,86763))):t.push(Promise.resolve().then(i.bind(i,83514)))})),this._blurPostProcessY.autoClear=!1,this._blurPostProcessY.onApplyObservable.add((e=>{const t=this._blurPostProcessY?.inputTexture.height??this._scene.getEngine().getRenderHeight();e.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/t)}));const t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],r=["textureSampler","mainSampler","reflectivitySampler"];let s="";this._debug&&(s+="#define SSRAYTRACE_DEBUG\n"),this._inputTextureColorIsInGammaSpace&&(s+="#define SSR_INPUT_IS_GAMMA_SPACE\n"),this._generateOutputInGammaSpace&&(s+="#define SSR_OUTPUT_IS_GAMMA_SPACE\n"),this.useFresnel&&(s+="#define SSR_BLEND_WITH_FRESNEL\n",t.push("projection","invProjectionMatrix","nearPlaneZ","farPlaneZ"),r.push("depthSampler","normalSampler")),this._useScreenspaceDepth&&(s+="#define SSRAYTRACE_SCREENSPACE_DEPTH"),0===this._reflectivityThreshold&&(s+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new ms.w("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,r,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,s,this._textureType,void 0,void 0,void 0,void 0,this._scene.getEngine().isWebGPU?1:0,((e,t)=>{e?t.push(Promise.resolve().then(i.bind(i,20136))):t.push(Promise.resolve().then(i.bind(i,36253)))})),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add((e=>{const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(i||t){if(i&&this._scene.activeCamera?._getFirstPostProcess()===this._ssrPostProcess){const t=i.getRenderTarget();t&&t.textures&&e.setTexture("mainSampler",t.textures[i.getIndex(4)])}else e.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(t){const i=t.getTextureIndex(qO.REFLECTIVITY_TEXTURE_TYPE);if(e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),this.useFresnel){const i=this._scene.activeCamera;if(i&&this._useScreenspaceDepth&&(e.setFloat("nearPlaneZ",i.minZ),e.setFloat("farPlaneZ",i.maxZ)),e.setTexture("normalSampler",t.getGBuffer().textures[1]),this._useScreenspaceDepth){const i=t.getTextureIndex(qO.SCREENSPACE_DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",t.getGBuffer().textures[i])}else e.setTexture("depthSampler",t.getGBuffer().textures[0])}}else if(i){const t=i.getIndex(3);if(e.setTexture("reflectivitySampler",i.getRenderTarget().textures[t]),this.useFresnel){const t=this._scene.activeCamera;t&&this._useScreenspaceDepth&&(e.setFloat("nearPlaneZ",t.minZ),e.setFloat("farPlaneZ",t.maxZ));const r=i.getIndex(this._useScreenspaceDepth?10:5),s=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[s]),e.setTexture("depthSampler",i.getRenderTarget().textures[r])}}if(e.setFloat("strength",this.strength),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){const t=this._scene.activeCamera;if(t){const i=t.getProjectionMatrix();i.invertToRef(W.AA.Matrix[0]),e.setMatrix("projection",i),e.setMatrix("invProjectionMatrix",W.AA.Matrix[0])}}}}))}serialize(){const e=it.p.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return it.p.Parse((()=>new _D(e._name,t,e._ratio)),e,t,i)}}(0,je.Cg)([(0,$e.lK)()],_D.prototype,"samples",null),(0,je.Cg)([(0,$e.lK)()],_D.prototype,"maxDistance",void 0),(0,je.Cg)([(0,$e.lK)()],_D.prototype,"step",void 0),(0,je.Cg)([(0,$e.lK)()],_D.prototype,"thickness",void 0),(0,je.Cg)([(0,$e.lK)()],_D.prototype,"strength",void 0),(0,je.Cg)([(0,$e.lK)()],_D.prototype,"reflectionSpecularFalloffExponent",void 0),(0,je.Cg)([(0,$e.lK)()],_D.prototype,"maxSteps",void 0),(0,je.Cg)([(0,$e.lK)()],_D.prototype,"roughnessFactor",void 0),(0,je.Cg)([(0,$e.lK)()],_D.prototype,"selfCollisionNumSkip",void 0),(0,je.Cg)([(0,$e.lK)()],_D.prototype,"_reflectivityThreshold",void 0),(0,je.Cg)([(0,$e.lK)("_ssrDownsample")],_D.prototype,"_ssrDownsample",void 0),(0,je.Cg)([(0,$e.lK)()],_D.prototype,"ssrDownsample",null),(0,je.Cg)([(0,$e.lK)("blurDispersionStrength")],_D.prototype,"_blurDispersionStrength",void 0),(0,je.Cg)([(0,$e.lK)("blurDownsample")],_D.prototype,"_blurDownsample",void 0),(0,je.Cg)([(0,$e.lK)("enableSmoothReflections")],_D.prototype,"_enableSmoothReflections",void 0),(0,je.Cg)([(0,$e.lK)("environmentTexture")],_D.prototype,"_environmentTexture",void 0),(0,je.Cg)([(0,$e.lK)("environmentTextureIsProbe")],_D.prototype,"_environmentTextureIsProbe",void 0),(0,je.Cg)([(0,$e.lK)("attenuateScreenBorders")],_D.prototype,"_attenuateScreenBorders",void 0),(0,je.Cg)([(0,$e.lK)("attenuateIntersectionDistance")],_D.prototype,"_attenuateIntersectionDistance",void 0),(0,je.Cg)([(0,$e.lK)("attenuateIntersectionIterations")],_D.prototype,"_attenuateIntersectionIterations",void 0),(0,je.Cg)([(0,$e.lK)("attenuateFacingCamera")],_D.prototype,"_attenuateFacingCamera",void 0),(0,je.Cg)([(0,$e.lK)("attenuateBackfaceReflection")],_D.prototype,"_attenuateBackfaceReflection",void 0),(0,je.Cg)([(0,$e.lK)("clipToFrustum")],_D.prototype,"_clipToFrustum",void 0),(0,je.Cg)([(0,$e.lK)("useFresnel")],_D.prototype,"_useFresnel",void 0),(0,je.Cg)([(0,$e.lK)("enableAutomaticThicknessComputation")],_D.prototype,"_enableAutomaticThicknessComputation",void 0),(0,je.Cg)([(0,$e.lK)("backfaceDepthTextureDownsample")],_D.prototype,"_backfaceDepthTextureDownsample",void 0),(0,je.Cg)([(0,$e.lK)("backfaceForceDepthWriteTransparentMeshes")],_D.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0),(0,je.Cg)([(0,$e.lK)("isEnabled")],_D.prototype,"_isEnabled",void 0),(0,je.Cg)([(0,$e.lK)("inputTextureColorIsInGammaSpace")],_D.prototype,"_inputTextureColorIsInGammaSpace",void 0),(0,je.Cg)([(0,$e.lK)("generateOutputInGammaSpace")],_D.prototype,"_generateOutputInGammaSpace",void 0),(0,je.Cg)([(0,$e.lK)("debug")],_D.prototype,"_debug",void 0),(0,X.Y5)("BABYLON.SSRRenderingPipeline",_D);class mD extends JO{set samples(e){this._taaThinPostProcess.samples=e}get samples(){return this._taaThinPostProcess.samples}set msaaSamples(e){this._msaaSamples!==e&&(this._msaaSamples=e,this._taaPostProcess&&(this._taaPostProcess.samples=e))}get msaaSamples(){return this._msaaSamples}get factor(){return this._taaThinPostProcess.factor}set factor(e){this._taaThinPostProcess.factor=e}get disableOnCameraMove(){return this._taaThinPostProcess.disableOnCameraMove}set disableOnCameraMove(e){this._taaThinPostProcess.disableOnCameraMove=e}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&(this._taaThinPostProcess._reset(),this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras))):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get scene(){return this._scene}get isSupported(){return this._scene.getEngine().getCaps().texelFetch}constructor(e,t,i,r=0){const s=t.getEngine();super(s,e),this.TAARenderEffect="TAARenderEffect",this.TAAPassEffect="TAAPassEffect",this._msaaSamples=1,this._isEnabled=!0,this._isDirty=!1,this._camerasToBeAttached=[],this._pingpong=0,this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=r,this._taaThinPostProcess=new W_("TAA",this._scene.getEngine()),this.isSupported&&(this._createPingPongTextures(s.getRenderWidth(),s.getRenderHeight()),t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline())}getClassName(){return"TAARenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(){this._disposePostProcesses(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._ping.dispose(),this._pong.dispose(),super.dispose()}_createPingPongTextures(e,t){const i=this._scene.getEngine();this._ping?.dispose(),this._pong?.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._taaThinPostProcess.textureWidth=e,this._taaThinPostProcess.textureHeight=t}_buildPipeline(){if(!this.isSupported)return;if(!this._isEnabled)return void(this._isDirty=!0);this._isDirty=!1;const e=this._scene.getEngine();this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._createTAAPostProcess(),this.addEffect(new AO(e,this.TAARenderEffect,(()=>this._taaPostProcess),!0)),this._createPassPostProcess(),this.addEffect(new AO(e,this.TAAPassEffect,(()=>this._passPostProcess),!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_disposePostProcesses(){for(let e=0;e{if(this._taaThinPostProcess.camera=this._scene.activeCamera,this._taaPostProcess?.width!==this._ping.width||this._taaPostProcess?.height!==this._ping.height){const e=this._scene.getEngine();this._createPingPongTextures(e.getRenderWidth(),e.getRenderHeight())}this._taaThinPostProcess.updateProjectionMatrix(),this._passPostProcess&&(this._passPostProcess.inputTexture=this._pingpong?this._ping:this._pong),this._pingpong=1^this._pingpong})),this._taaPostProcess.onApplyObservable.add((e=>{e._bindTexture("historySampler",this._pingpong?this._ping.texture:this._pong.texture)}))}_createPassPostProcess(){const e=this._scene.getEngine();this._passPostProcess=new _s.v("TAAPass",1,null,1,e),this._passPostProcess.inputTexture=this._ping,this._passPostProcess.autoClear=!1}serialize(){const e=it.p.Serialize(this);return e.customType="TAARenderingPipeline",e}static Parse(e,t,i){return it.p.Parse((()=>new mD(e._name,t,e._ratio)),e,t,i)}}(0,je.Cg)([(0,$e.lK)("samples")],mD.prototype,"samples",null),(0,je.Cg)([(0,$e.lK)("msaaSamples")],mD.prototype,"_msaaSamples",void 0),(0,je.Cg)([(0,$e.lK)()],mD.prototype,"factor",null),(0,je.Cg)([(0,$e.lK)()],mD.prototype,"disableOnCameraMove",null),(0,je.Cg)([(0,$e.lK)("isEnabled")],mD.prototype,"_isEnabled",void 0),(0,X.Y5)("BABYLON.TAARenderingPipeline",mD);var gD,vD=i(33258),xD=i(20661),bD=i(93640),SD=i(87193),TD=i(83514),CD=i(36253),yD=i(98e3),ED=i(86763),PD=i(20136);i(7672),i(88559),function(e){e[e.Hable=0]="Hable",e[e.Reinhard=1]="Reinhard",e[e.HejiDawson=2]="HejiDawson",e[e.Photographic=3]="Photographic"}(gD||(gD={}));class AD extends ms.w{getClassName(){return"TonemapPostProcess"}constructor(e,t,i,r,s=2,n,o=0,a){super(e,"tonemap",["_ExposureAdjustment"],null,1,r,s,n,a,null,o),this._operator=t,this.exposureAdjustment=i;let l="#define ";0===this._operator?l+="HABLE_TONEMAPPING":1===this._operator?l+="REINHARD_TONEMAPPING":2===this._operator?l+="OPTIMIZED_HEJIDAWSON_TONEMAPPING":3===this._operator&&(l+="PHOTOGRAPHIC_TONEMAPPING"),this.updateEffect(l),this.onApply=e=>{e.setFloat("_ExposureAdjustment",this.exposureAdjustment)}}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,41739))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,47088))])),super._gatherImports(e,t)}}Cs.l.ShadersStore.volumetricLightScatteringPixelShader="uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec2 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{this.isSupported||this.dispose(e),this.onActivate=null},this.onApplyObservable.add((e=>{this._updateMeshScreenCoordinates(l),e.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),e.setFloat("exposure",this.exposure),e.setFloat("decay",this.decay),e.setFloat("weight",this.weight),e.setFloat("density",this.density),e.setVector2("meshPositionOnScreen",this._screenCoordinates)}))}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){const i=e.getMesh();if(i===this.mesh&&i.material)return i.material.isReady(i);const r=i._internalAbstractMeshDataInfo._materialForRenderPass?.[this._scene.getEngine().currentRenderPassId];if(r)return r.isReadyForSubMesh(i,e,t);const s=[],n=[st.R.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&s.push("#define ALPHATEST"),i.isVerticesDataPresent(st.R.UVKind)&&(n.push(st.R.UVKind),s.push("#define UV1")),i.isVerticesDataPresent(st.R.UV2Kind)&&(n.push(st.R.UV2Kind),s.push("#define UV2")));const a=new Tn;if(i.useBones&&i.computeBonesUsingShaders&&i.skeleton){n.push(st.R.MatricesIndicesKind),n.push(st.R.MatricesWeightsKind),i.numBoneInfluencers>4&&(n.push(st.R.MatricesIndicesExtraKind),n.push(st.R.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+i.numBoneInfluencers),i.numBoneInfluencers>0&&a.addCPUSkinningFallback(0,i);const e=i.skeleton;e.isUsingTextureForMatrices?s.push("#define BONETEXTURE"):s.push("#define BonesPerMesh "+(e.bones.length+1))}else s.push("#define NUM_BONE_INFLUENCERS 0");const l=i.morphTargetManager;let h=0;l&&(h=l.numMaxInfluencers||l.numInfluencers,h>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+h),l.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),(0,Bt.MF)(n,i,h))),t&&(s.push("#define INSTANCES"),(0,Bt.te)(n),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES"));const c=i.bakedVertexAnimationManager;c&&c.isEnabled&&(s.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&n.push("bakedVertexAnimationSettingsInstanced"));const u=e._getDrawWrapper(void 0,!0),d=u.defines,f=s.join("\n");if(d!==f){const e=["world","mBones","boneTextureWidth","viewProjection","diffuseMatrix","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],t=["diffuseSampler","morphTargets","boneSampler","bakedVertexAnimationTexture"];u.setEffect(i.getScene().getEngine().createEffect("volumetricLightScatteringPass",{attributes:n,uniformsNames:e,uniformBuffersNames:[],samplers:t,defines:f,fallbacks:a,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:h}},i.getScene().getEngine()),f)}return u.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){const t=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==t&&e.getScene().customRenderTargets.splice(t,1),this._volumetricLightScatteringRTT.dispose(),super.dispose(e)}getPass(){return this._volumetricLightScatteringRTT}_meshExcluded(e){return this.includedMeshes.length>0&&-1===this.includedMeshes.indexOf(e)||this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)}_createPass(e,t){const i=e.getEngine();this._volumetricLightScatteringRTT=new ln.$("volumetricLightScatteringMap",{width:i.getRenderWidth()*t,height:i.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=vi.g.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=vi.g.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;const r=this.getCamera();r?r.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);const s=e=>{const t=e.getRenderingMesh(),i=e.getEffectiveMesh();if(this._meshExcluded(t))return;i._internalAbstractMeshDataInfo._isActiveIntermediate=!1;const r=e.getMaterial();if(!r)return;const s=t.getScene(),n=s.getEngine();n.setState(r.backFaceCulling,void 0,void 0,void 0,r.cullBackFaces);const o=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;const a=n.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||t.hasThinInstances);if(this._isReady(e,a)){const l=i._internalAbstractMeshDataInfo._materialForRenderPass?.[n.currentRenderPassId];let h=e._getDrawWrapper();if(t!==this.mesh||h||(h=r._getDrawWrapper()),!h)return;const c=h.effect;if(n.enableEffect(h),a||t._bind(e,c,r.fillMode),t===this.mesh)r.bind(i.getWorldMatrix(),t);else if(l)l.bindForSubMesh(i.getWorldMatrix(),i,e);else{if(c.setMatrix("viewProjection",s.getTransformMatrix()),r.needAlphaTesting()){const e=r.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}(0,Bt.f$)(t,c),(0,Bt.nR)(t,c),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(c);const i=e.getMesh().bakedVertexAnimationManager;i&&i.isEnabled&&i.bind(c,a)}a&&t.hasThinInstances&&c.setMatrix("world",i.getWorldMatrix()),t._processRendering(i,e,c,Vt.TriangleFillMode,o,a,((e,t)=>{e||c.setMatrix("world",t)}))}};let n;const o=new H.ov(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((()=>{n=e.clearColor,e.clearColor=o})),this._volumetricLightScatteringRTT.onAfterRenderObservable.add((()=>{e.clearColor=n})),this._volumetricLightScatteringRTT.customIsReadyFunction=(e,t,r)=>{if((r||0===t)&&e.subMeshes)for(let t=0;t{const o=e.getEngine();let a;if(n.length){for(o.setColorWrite(!1),a=0;ae._alphaIndex>t._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0)),o.setAlphaMode(2),a=0;a{e.setFloat("curvature_ridge",.5/Math.max(this.ridge*this.ridge,1e-4)),e.setFloat("curvature_valley",.7/Math.max(this.valley*this.valley,1e-4));const t=this._geometryBufferRenderer.getGBuffer().textures[1];e.setTexture("normalSampler",t)}):Z.V.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){const e=he.q.LastCreatedEngine;return!!e&&e.getCaps().drawBuffersExtension}static _Parse(e,t,i,r){return it.p.Parse((()=>new ID(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,r)}}(0,je.Cg)([(0,$e.lK)()],ID.prototype,"ridge",void 0),(0,je.Cg)([(0,$e.lK)()],ID.prototype,"valley",void 0),(0,X.Y5)("BABYLON.ScreenSpaceCurvaturePostProcess",ID);var MD=i(18013),OD=i(45010),DD=i(45245),wD=i(95527),ND=i(56558),FD=i(42876),LD=i(30927),BD=i(88412),VD=i(418),kD=i(12253),UD=i(44341),GD=i(79132),zD=i(41123),WD=i(27220),HD=i(68820),XD=i(55099),qD=i(35624),YD=i(44134),KD=i(95610),jD=i(41289),$D=i(29743),QD=i(89328),ZD=i(94811),JD=i(63186),ew=i(83062),tw=i(9574),iw=i(75424),rw=i(84014),sw=i(54525),nw=i(32439),ow=i(27897),aw=i(31162),lw=i(20692),hw=i(2153),cw=i(59188),uw=i(79799),dw=i(42711),fw=i(82308),pw=i(28377),_w=i(95400),mw=i(88770),gw=i(26879),vw=i(13079),xw=i(28162),bw=i(17239),Sw=i(63788),Tw=i(47088),Cw=i(41739);Object.defineProperty(oi.Z.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(e){this._forceShowBoundingBoxes=e,e&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),oi.Z.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new yw(this)),this._boundingBoxRenderer},Object.defineProperty(Nt.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(e){this._showBoundingBox=e,e&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class yw{get shaderLanguage(){return this._shaderLanguage}constructor(e){this.name=Ut.v.NAME_BOUNDINGBOXRENDERER,this.frontColor=new H.v9(1,1,1),this.backColor=new H.v9(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new z.cP,this.onAfterBoxRenderingObservable=new z.cP,this.onResourcesReadyObservable=new z.cP,this.enabled=!0,this._shaderLanguage=0,this.renderList=new Qe.L(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,this.scene.getEngine().isWebGPU&&(this._shaderLanguage=1),e._addComponent(this),this._uniformBufferFront=new Rt.D(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!0),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new Rt.D(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!0),this._buildUniformLayout(this._uniformBufferBack)}_buildUniformLayout(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()}register(){this.scene._beforeEvaluateActiveMeshStage.registerStep(Ut.v.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(Ut.v.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(Ut.v.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(Ut.v.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){const i=t.getBoundingInfo();null!=i&&(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 xo("colorShader",this.scene,"boundingBoxRenderer",{attributes:[st.R.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,10737)),Promise.resolve().then(i.bind(i,83063))]):await Promise.all([Promise.resolve().then(i.bind(i,81473)),Promise.resolve().then(i.bind(i,16400))])}},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new xo("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[st.R.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,10737)),Promise.resolve().then(i.bind(i,83063))]):await Promise.all([Promise.resolve().then(i.bind(i,81473)),Promise.resolve().then(i.bind(i,16400))])}},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};const e=this.scene.getEngine(),t=qo({size:1});this._vertexBuffers[st.R.PositionKind]=new st.R(e,t.positions,st.R.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[st.R.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){if(0===this.renderList.length||!this.enabled)return;if(this._prepareResources(),!this._colorShader.isReady())return;const t=this.scene.getEngine();t.setDepthWrite(!1);const i=this.scene.getTransformMatrix();for(let r=0;r{let t=e._getComponent(Ut.v.NAME_DEPTHRENDERER);t||(t=new Ew(e),e._addComponent(t))};class Pw{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class Aw{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){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}get shaderLanguage(){return this._shaderLanguage}constructor(e,t=5){if(this._thinTextures=[],this._currentPingPongState=0,this._layoutCacheFormat=[[!0],[!0,!0],[!0,!0,!0]],this._layoutCache=[],this._candidateSubMeshes=new Qe.L(10),this._excludedSubMeshes=new Qe.L(10),this._excludedMeshes=[],this._colorCache=[new H.ov(Aw._DEPTH_CLEAR_VALUE,Aw._DEPTH_CLEAR_VALUE,0,0),new H.ov(-Aw._MIN_DEPTH,Aw._MAX_DEPTH,0,0),new H.ov(0,0,0,0)],this._shaderLanguage=0,this._scene=e,this._engine=e.getEngine(),this._passCount=t,e.enablePrePassRenderer()){for(let e=0;e{1===this._shaderLanguage?await Promise.resolve().then(i.bind(i,29551)):await Promise.resolve().then(i.bind(i,17738))}}),this._blendBackEffectWrapperPingPong=new Yp.$({fragmentShader:"oitBackBlend",useShaderStore:!0,engine:this._engine,samplerNames:["uBackColor"],uniformNames:[],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await Promise.resolve().then(i.bind(i,29551)):await Promise.resolve().then(i.bind(i,17738))}}),this._finalEffectWrapper=new Yp.$({fragmentShader:"oitFinal",useShaderStore:!0,engine:this._engine,samplerNames:["uFrontColor","uBackColor"],uniformNames:[],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await Promise.resolve().then(i.bind(i,21937)):await Promise.resolve().then(i.bind(i,4172))}}),this._effectRenderer=new Yp.J(this._engine)}setPrePassRenderer(e){e.addEffectConfiguration(this._prePassEffectConfiguration)}bind(e){e.setTexture("oitDepthSampler",this._thinTextures[3*this._currentPingPongState]),e.setTexture("oitFrontColorSampler",this._thinTextures[3*this._currentPingPongState+1])}_renderSubMeshes(e){let t;this._useRenderPasses&&(t={});for(let i=0;i{1===t?await Promise.all([Promise.resolve().then(i.bind(i,7217)),Promise.resolve().then(i.bind(i,27127))]):await Promise.all([Promise.resolve().then(i.bind(i,42644)),Promise.resolve().then(i.bind(i,85550))])}},!1);r.disableDepthWrite=!0,r.backFaceCulling=!1,r.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=r}return e._edgeRenderLineShader}get shaderLanguage(){return this._shaderLanguage}constructor(e,t=.95,i=!1,r=!0,s){this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new Qe.L(32),this._shaderLanguage=0,this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=s??null,this._epsilon=t;const n=this._source.getScene().getEngine();n.isWebGPU&&(this._drawWrapper=new gt.E(n),this._shaderLanguage=1),this._prepareRessources(),r&&(s?.useAlternateEdgeFinder??1?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=Mw._GetShader(this._source.getScene(),this._shaderLanguage))}_rebuild(){let e=this._buffers[st.R.PositionKind];e&&e._rebuild(),e=this._buffers[st.R.NormalKind],e&&e._rebuild();const t=this._source.getScene().getEngine();this._ib=t.createIndexBuffer(this._linesIndices)}dispose(){this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let e=this._buffers[st.R.PositionKind];e&&(e.dispose(),this._buffers[st.R.PositionKind]=null),e=this._buffers[st.R.NormalKind],e&&(e.dispose(),this._buffers[st.R.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),this._drawWrapper?.dispose()}_processEdgeForAdjacencies(e,t,i,r,s){return e===i&&t===r||e===r&&t===i?0:e===r&&t===s||e===s&&t===r?1:e===s&&t===i||e===i&&t===s?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,r,s){const n=1e-10;return e.equalsWithEpsilon(i,n)&&t.equalsWithEpsilon(r,n)||e.equalsWithEpsilon(r,n)&&t.equalsWithEpsilon(i,n)?0:e.equalsWithEpsilon(r,n)&&t.equalsWithEpsilon(s,n)||e.equalsWithEpsilon(s,n)&&t.equalsWithEpsilon(r,n)?1:e.equalsWithEpsilon(s,n)&&t.equalsWithEpsilon(i,n)||e.equalsWithEpsilon(i,n)&&t.equalsWithEpsilon(s,n)?2:-1}_checkEdge(e,t,i,r,s){let n;n=void 0===t||W.Pq.Dot(i[e],i[t]){i>=0&&t.push(i);for(let i=0;i=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 t=0;t<3;++t)t===n?e[t].sort(((e,t)=>e[1]t[1]?1:0)):e[t].sort(((e,t)=>e[1]>t[1]?-1:e[1]=n+1;--o)s(e[o%3],a,o!==n+2?r[i[t+(o+1)%3]]:-1);const h=a.length;i.push(r[i[t+n]],o[0],a[0]),i.push(r[i[t+(n+1)%3]],a[h-1],o[l-1]);const c=l<=h,u=c?l:h,d=c?h:l,f=c?l-1:h-1,p=c?0:1;let _=l+h-2,m=0,g=0;const v=c?o:a,x=c?a:o;let b=0;for(;_-- >0;){let e;p?i.push(v[m],x[g]):i.push(x[g],v[m]),b+=u,b>=d&&ml){const e=a;a=l,l=e}const c=a+"_"+l,u=o[c];u?u.done||(W.Pq.Dot(r,u.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)return void this._lineShader._setDrawWrapper(t);const i=this._source.hasInstances&&this.customInstances.length>0,r=i||this._source.hasThinInstances;let s=0;if(r)if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){const e=this._source._instanceDataStorage;if(s=this.customInstances.length,!e.instancesData)return void(this._source.getScene()._activeMeshesFrozen||this.customInstances.reset());if(!e.isFrozen){let t=0;for(let i=0;i{this._isVoxelGrid3D?e?t.push(Promise.resolve().then(i.bind(i,20008))):t.push(Promise.resolve().then(i.bind(i,95171))):e?t.push(Promise.resolve().then(i.bind(i,7426))):t.push(Promise.resolve().then(i.bind(i,68859)))}};this._voxelDebugPass=new ms.w(this.debugPassName,this._isVoxelGrid3D?"iblVoxelGrid3dDebug":"iblVoxelGrid2dArrayDebug",t),this._voxelDebugPass.onApplyObservable.add((e=>{0===this._voxelDebugAxis?e.setTexture("voxelTexture",this._voxelGridXaxis):1===this._voxelDebugAxis?e.setTexture("voxelTexture",this._voxelGridYaxis):2===this._voxelDebugAxis?e.setTexture("voxelTexture",this._voxelGridZaxis):e.setTexture("voxelTexture",this.getVoxelGrid()),e.setTexture("voxelSlabTexture",this._voxelSlabDebugRT),e.setVector4("sizeParams",this._debugSizeParams),e.setFloat("mipNumber",this._debugMipNumber)}))}}constructor(e,t,r=6,s=!0){this._voxelMrtsXaxis=[],this._voxelMrtsYaxis=[],this._voxelMrtsZaxis=[],this._isVoxelGrid3D=!0,this._renderTargets=[],this._triPlanarVoxelization=!0,this._voxelizationInProgress=!1,this._invWorldScaleMatrix=W.uq.Identity(),this._voxelResolution=64,this._voxelResolutionExp=6,this._mipArray=[],this._voxelDebugEnabled=!1,this._voxelDebugAxis=-1,this._debugSizeParams=new W.IU(0,0,0,0),this._includedMeshes=[],this._debugMipNumber=0,this._debugPassName="Voxelization Debug Pass",this._scene=e,this._engine=e.getEngine(),this._triPlanarVoxelization=s,this._engine.getCaps().drawBuffersExtension||Z.V.Error("Can't do voxel rendering without the draw buffers extension.");const n=this._engine.isWebGPU;this._maxDrawBuffers=this._engine.getCaps().maxDrawBuffers||0,this._copyMipEffectRenderer=new Yp.J(this._engine),this._copyMipEffectWrapper=new Yp.$({engine:this._engine,fragmentShader:"copyTexture3DLayerToTexture",useShaderStore:!0,uniformNames:["layerNum"],samplerNames:["textureSampler"],shaderLanguage:n?1:0,extraInitializationsAsync:async()=>{n?await Promise.resolve().then(i.bind(i,4357)):await Promise.resolve().then(i.bind(i,76978))}}),this.voxelResolutionExp=r}_generateMipMaps(){const e=Math.ceil(Math.log2(this._voxelResolution));for(let t=1;t{e?await Promise.resolve().then(i.bind(i,48016)):await Promise.resolve().then(i.bind(i,17897))}};this._triPlanarVoxelization?(this._voxelGridXaxis=new ln.$("voxelGridXaxis",t,this._scene,r),this._voxelGridYaxis=new ln.$("voxelGridYaxis",t,this._scene,r),this._voxelGridZaxis=new ln.$("voxelGridZaxis",t,this._scene,r),this._voxelMrtsXaxis=this._createVoxelMRTs("x_axis_",this._voxelGridXaxis,s),this._voxelMrtsYaxis=this._createVoxelMRTs("y_axis_",this._voxelGridYaxis,s),this._voxelMrtsZaxis=this._createVoxelMRTs("z_axis_",this._voxelGridZaxis,s),this._voxelGridRT=new cv("combinedVoxelGrid",t,"iblCombineVoxelGrids",this._scene,n,!1),this._scene.proceduralTextures.splice(this._scene.proceduralTextures.indexOf(this._voxelGridRT),1),this._voxelGridRT.setFloat("layer",0),this._voxelGridRT.setTexture("voxelXaxisSampler",this._voxelGridXaxis),this._voxelGridRT.setTexture("voxelYaxisSampler",this._voxelGridYaxis),this._voxelGridRT.setTexture("voxelZaxisSampler",this._voxelGridZaxis),this._voxelGridRT.autoClear=!1,this._voxelGridRT.wrapU=vi.g.CLAMP_ADDRESSMODE,this._voxelGridRT.wrapV=vi.g.CLAMP_ADDRESSMODE):(this._voxelGridZaxis=new ln.$("voxelGridZaxis",t,this._scene,n),this._voxelMrtsZaxis=this._createVoxelMRTs("z_axis_",this._voxelGridZaxis,s));const o={generateDepthBuffer:!1,generateMipMaps:!1,type:0,format:6,samplingMode:1,shaderLanguage:e?1:0,extraInitializationsAsync:async()=>{e?await Promise.resolve().then(i.bind(i,88789)):await Promise.resolve().then(i.bind(i,99638))}};this._mipArray=new Array(Math.ceil(Math.log2(this._voxelResolution)));for(let e=1;e<=this._mipArray.length;e++){const t=this._voxelResolution>>e,i={width:t,height:t,depth:t};this._mipArray[e-1]=new cv("voxelMip"+e,i,"iblGenerateVoxelMip",this._scene,o,!1),this._scene.proceduralTextures.splice(this._scene.proceduralTextures.indexOf(this._mipArray[e-1]),1);const r=this._mipArray[e-1];r.autoClear=!1,r.wrapU=vi.g.CLAMP_ADDRESSMODE,r.wrapV=vi.g.CLAMP_ADDRESSMODE,r.setTexture("srcMip",e>1?this._mipArray[e-2]:this.getVoxelGrid()),r.setInt("layerNum",0)}this._createVoxelMaterials()}_createVoxelMRTs(e,t,i){t.wrapU=vi.g.CLAMP_ADDRESSMODE,t.wrapV=vi.g.CLAMP_ADDRESSMODE,t.noPrePassRenderer=!0;const r=[],s=new Array(this._maxDrawBuffers).fill(this._isVoxelGrid3D?32879:35866);for(let n=0;nn*this._maxDrawBuffers+t));let o=new Array(this._maxDrawBuffers).fill("");o=o.map(((t,i)=>"voxel_grid_"+e+(n*this._maxDrawBuffers+i)));const a=new Xb("mrt_"+e+n,{width:this._voxelResolution,height:this._voxelResolution,depth:this._isVoxelGrid3D?this._voxelResolution:void 0},this._maxDrawBuffers,this._scene,{types:new Array(this._maxDrawBuffers).fill(0),samplingModes:new Array(this._maxDrawBuffers).fill(3),generateMipMaps:!1,targetTypes:s,formats:new Array(this._maxDrawBuffers).fill(6),faceIndex:new Array(this._maxDrawBuffers).fill(0),layerIndex:i,layerCounts:new Array(this._maxDrawBuffers).fill(this._voxelResolution),generateDepthBuffer:!1,generateStencilBuffer:!1},o);a.clearColor=new H.ov(0,0,0,1),a.noPrePassRenderer=!0;for(let e=0;e{e.dispose()})),this._voxelMaterial?.dispose(),this._voxelSlabDebugMaterial?.dispose(),this._mipArray=[],this._voxelMrtsXaxis=[],this._voxelMrtsYaxis=[],this._voxelMrtsZaxis=[]}_createVoxelMaterials(){const e=this._engine.isWebGPU;this._voxelMaterial=new xo("voxelization",this._scene,"iblVoxelGrid",{uniforms:["world","viewMatrix","invWorldScale","nearPlane","farPlane","stepSize"],defines:["MAX_DRAW_BUFFERS "+this._maxDrawBuffers],shaderLanguage:e?1:0,extraInitializationsAsync:async()=>{e?await Promise.all([Promise.resolve().then(i.bind(i,75904)),Promise.resolve().then(i.bind(i,79214))]):await Promise.all([Promise.resolve().then(i.bind(i,83145)),Promise.resolve().then(i.bind(i,19395))])}}),this._voxelMaterial.cullBackFaces=!1,this._voxelMaterial.backFaceCulling=!1,this._voxelMaterial.depthFunction=an.ALWAYS,this._voxelSlabDebugMaterial=new xo("voxelSlabDebug",this._scene,"iblVoxelSlabDebug",{uniforms:["world","viewMatrix","cameraViewMatrix","projection","invWorldScale","nearPlane","farPlane","stepSize"],defines:["MAX_DRAW_BUFFERS "+this._maxDrawBuffers],shaderLanguage:e?1:0,extraInitializationsAsync:async()=>{e?await Promise.all([Promise.resolve().then(i.bind(i,16615)),Promise.resolve().then(i.bind(i,94369))]):await Promise.all([Promise.resolve().then(i.bind(i,81284)),Promise.resolve().then(i.bind(i,71650))])}})}_setDebugBindings(){this._voxelSlabDebugMaterial.setMatrix("projection",this._scene.activeCamera.getProjectionMatrix()),this._voxelSlabDebugMaterial.setMatrix("cameraViewMatrix",this._scene.activeCamera.getViewMatrix())}isReady(){let e=this.getVoxelGrid().isReady();for(let t=0;tt===e[0]));if(t>=0)this._renderTargets.splice(t,e.length);else{const t=this._scene.customRenderTargets.findIndex((t=>t===e[0]));t>=0&&this._scene.customRenderTargets.splice(t,e.length)}}updateVoxelGrid(e){this._stopVoxelization(),this._includedMeshes=e,this._voxelizationInProgress=!0,this._triPlanarVoxelization?(this._addRTsForRender(this._voxelMrtsXaxis,e,0),this._addRTsForRender(this._voxelMrtsYaxis,e,1),this._addRTsForRender(this._voxelMrtsZaxis,e,2)):this._addRTsForRender(this._voxelMrtsZaxis,e,2),this._voxelDebugEnabled&&this._addRTsForRender([this._voxelSlabDebugRT],e,this._voxelDebugAxis,1,!0),this._renderVoxelGridBound=this._renderVoxelGrid.bind(this),this._scene.onAfterRenderObservable.add(this._renderVoxelGridBound)}_renderVoxelGrid(){if(this._voxelizationInProgress){let e=this.getVoxelGrid().isReady();for(let t=0;t{e.render()})),this._stopVoxelization(),this._triPlanarVoxelization&&this._voxelGridRT.render(),this._generateMipMaps(),this._copyMipMaps(),this._scene.onAfterRenderObservable.removeCallback(this._renderVoxelGridBound),this._voxelizationInProgress=!1)}}_addRTsForRender(e,t,i,r=0,s=!1){const n=1/this._computeNumberOfSlabs();let o;o=0===r?this._voxelMaterial:this._voxelSlabDebugMaterial,e.forEach(((e,r)=>{e.renderList=[];const s=r*n,a=(r+1)*n,l=n/this._maxDrawBuffers,h=new W.Pq(0,0,0);let c=new W.Pq(0,0,1);0===i?c=new W.Pq(1,0,0):1===i&&(c=new W.Pq(0,1,0));let u=new W.Pq(0,1,0);1===i&&(u=new W.Pq(1,0,0)),e.onBeforeRenderObservable.add((()=>{o.setMatrix("viewMatrix",W.uq.LookAtLH(h,c,u)),o.setMatrix("invWorldScale",this._invWorldScaleMatrix),o.setFloat("nearPlane",s),o.setFloat("farPlane",a),o.setFloat("stepSize",l)})),0!==t.length&&t.forEach((t=>{t&&(t.subMeshes&&t.subMeshes.length>0&&(e.renderList?.push(t),e.setMaterialForRendering(t,o)),t.getChildMeshes().forEach((t=>{t.subMeshes&&t.subMeshes.length>0&&(e.renderList?.push(t),e.setMaterialForRendering(t,o))})))}))})),s?e.forEach((e=>{-1===this._scene.customRenderTargets.indexOf(e)&&this._scene.customRenderTargets.push(e)})):this._renderTargets=this._renderTargets.concat(e)}resize(){this._voxelSlabDebugRT?.resize({width:this._scene.getEngine().getRenderWidth(),height:this._scene.getEngine().getRenderHeight()})}dispose(){this._disposeVoxelTextures(),this._voxelSlabDebugRT&&(this._removeVoxelRTs([this._voxelSlabDebugRT]),this._voxelSlabDebugRT.dispose()),this._voxelDebugPass&&this._voxelDebugPass.dispose()}}class ww{get voxelShadowOpacity(){return this._voxelShadowOpacity}set voxelShadowOpacity(e){this._voxelShadowOpacity=e}get ssShadowOpacity(){return this._ssShadowOpacity}set ssShadowOpacity(e){this._ssShadowOpacity=e}get sssSamples(){return this._sssSamples}set sssSamples(e){this._sssSamples=e}get sssStride(){return this._sssStride}set sssStride(e){this._sssStride=e}get sssMaxDist(){return this._sssMaxDist}set sssMaxDist(e){this._sssMaxDist=e}get sssThickness(){return this._sssThickness}set sssThickness(e){this._sssThickness=e}get voxelNormalBias(){return this._voxelNormalBias}set voxelNormalBias(e){this._voxelNormalBias=e}get voxelDirectionBias(){return this._voxelDirectionBias}set voxelDirectionBias(e){this._voxelDirectionBias=e}get sampleDirections(){return this._sampleDirections}set sampleDirections(e){this._sampleDirections=e}get envRotation(){return this._envRotation}set envRotation(e){this._envRotation=e}getOutputTexture(){return this._outputTexture}getDebugPassPP(){return this._debugPassPP||this._createDebugPass(),this._debugPassPP}get debugPassName(){return this._debugPassName}setWorldScaleMatrix(e){this._invWorldScaleMatrix=e}setDebugDisplayParams(e,t,i,r){this._debugSizeParams.set(e,t,i,r)}_createDebugPass(){const e=this._engine.isWebGPU;if(!this._debugPassPP){const t={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight(),uniforms:["sizeParams"],samplers:["debugSampler"],engine:this._engine,reusable:!1,shaderLanguage:e?1:0,extraInitializations:(e,t)=>{e?t.push(Promise.resolve().then(i.bind(i,65461))):t.push(Promise.resolve().then(i.bind(i,73588)))}};this._debugPassPP=new ms.w(this.debugPassName,"iblShadowDebug",t),this._debugPassPP.autoClear=!1,this._debugPassPP.onApplyObservable.add((e=>{e.setTexture("debugSampler",this._outputTexture),e.setVector4("sizeParams",this._debugSizeParams)}))}}constructor(e,t){this._voxelShadowOpacity=1,this._sssSamples=16,this._sssStride=8,this._sssMaxDist=.05,this._sssThickness=.5,this._ssShadowOpacity=1,this._cameraInvView=W.uq.Identity(),this._cameraInvProj=W.uq.Identity(),this._invWorldScaleMatrix=W.uq.Identity(),this._frameId=0,this._sampleDirections=4,this._shadowParameters=new W.IU(0,0,0,0),this._sssParameters=new W.IU(0,0,0,0),this._opacityParameters=new W.IU(0,0,0,0),this._voxelBiasParameters=new W.IU(0,0,0,0),this._voxelNormalBias=1.4,this._voxelDirectionBias=1.75,this.enabled=!0,this.debugEnabled=!1,this._debugPassName="Voxel Tracing Debug Pass",this._envRotation=0,this._debugVoxelMarchEnabled=!1,this._debugSizeParams=new W.IU(0,0,0,0),this._scene=e,this._engine=e.getEngine(),this._renderPipeline=t,this._createTextures()}_createTextures(){let e="";this._scene.useRightHandedSystem&&(e+="#define RIGHT_HANDED\n"),this._debugVoxelMarchEnabled&&(e+="#define VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION 1u\n");const t=this._engine.isWebGPU,r={type:0,format:5,samplingMode:1,generateDepthBuffer:!1,shaderLanguage:t?1:0,extraInitializationsAsync:async()=>{t?await Promise.all([Promise.resolve().then(i.bind(i,35680))]):await Promise.all([Promise.resolve().then(i.bind(i,74747))])}};this._outputTexture=new cv("voxelTracingPass",{width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},"iblShadowVoxelTracing",this._scene,r),this._outputTexture.refreshRate=-1,this._outputTexture.autoClear=!1,this._outputTexture.defines=e,this._setBindings(this._scene.activeCamera);let s=0;this._scene.onBeforeRenderObservable.add((()=>{s=0})),this._scene.onAfterRenderTargetsRenderObservable.add((()=>{2==++s&&this.enabled&&this._outputTexture.isReady()&&(this._setBindings(this._scene.activeCamera),this._outputTexture.render())}))}_setBindings(e){this._scene.useRightHandedSystem&&(this._outputTexture.defines="#define RIGHT_HANDED\n"),this._outputTexture.setMatrix("viewMtx",e.getViewMatrix()),this._outputTexture.setMatrix("projMtx",e.getProjectionMatrix()),e.getProjectionMatrix().invertToRef(this._cameraInvProj),e.getViewMatrix().invertToRef(this._cameraInvView),this._outputTexture.setMatrix("invProjMtx",this._cameraInvProj),this._outputTexture.setMatrix("invViewMtx",this._cameraInvView),this._outputTexture.setMatrix("wsNormalizationMtx",this._invWorldScaleMatrix),this._frameId++;let t=this._scene.useRightHandedSystem?-(this._envRotation+.5*Math.PI):this._envRotation-.5*Math.PI;t%=2*Math.PI,this._shadowParameters.set(this._sampleDirections,this._frameId,1,t),this._outputTexture.setVector4("shadowParameters",this._shadowParameters);const i=this._renderPipeline._getVoxelGridTexture(),r=Math.floor(Math.log2(i.getSize().width));this._voxelBiasParameters.set(this._voxelNormalBias,this._voxelDirectionBias,r,0),this._outputTexture.setVector4("voxelBiasParameters",this._voxelBiasParameters),this._sssParameters.set(this._sssSamples,this._sssStride,this._sssMaxDist,this._sssThickness),this._outputTexture.setVector4("sssParameters",this._sssParameters),this._opacityParameters.set(this._voxelShadowOpacity,this._ssShadowOpacity,0,0),this._outputTexture.setVector4("shadowOpacity",this._opacityParameters),this._outputTexture.setTexture("voxelGridSampler",i),this._outputTexture.setTexture("blueNoiseSampler",this._renderPipeline._getNoiseTexture()),this._outputTexture.setTexture("icdfySampler",this._renderPipeline._getIcdfyTexture()),this._outputTexture.setTexture("icdfxSampler",this._renderPipeline._getIcdfxTexture()),this._debugVoxelMarchEnabled&&(this._outputTexture.defines+="#define VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION 1u\n");const s=this._scene.geometryBufferRenderer;if(!s)return;const n=s.getTextureIndex(qO.SCREENSPACE_DEPTH_TEXTURE_TYPE);this._outputTexture.setTexture("depthSampler",s.getGBuffer().textures[n]);const o=s.getTextureIndex(qO.NORMAL_TEXTURE_TYPE);this._outputTexture.setTexture("worldNormalSampler",s.getGBuffer().textures[o])}resize(e=1){const t={width:Math.max(1,Math.floor(this._engine.getRenderWidth()*e)),height:Math.max(1,Math.floor(this._engine.getRenderHeight()*e))};this._outputTexture.resize(t,!1)}isReady(){return this._outputTexture.isReady()&&!(this._debugPassPP&&!this._debugPassPP.isReady())&&this._renderPipeline._getIcdfyTexture().isReady()&&this._renderPipeline._getIcdfxTexture().isReady()&&this._renderPipeline._getVoxelGridTexture().isReady()}dispose(){this._outputTexture.dispose(),this._debugPassPP&&this._debugPassPP.dispose()}}class Nw{get iblSource(){return this._iblSource}set iblSource(e){this._iblSource!==e&&(this._disposeTextures(),this._iblSource=e,e.isCube,e.isReadyOrNotBlocking()?this._recreateAssetsFromNewIbl(e):e.onLoadObservable.addOnce(this._recreateAssetsFromNewIbl.bind(this,e)))}_recreateAssetsFromNewIbl(e){this._debugPass&&this._debugPass.dispose(),this._createTextures(),this._debugPass&&this._createDebugPass(),this._icdfxPT.onGeneratedObservable.addOnce((()=>{this.onReadyObservable.notifyObservers()}))}getIcdfyTexture(){return this._icdfyPT}getIcdfxTexture(){return this._icdfxPT}setDebugDisplayParams(e,t,i,r){this._debugSizeParams.set(e,t,i,r)}get debugPassName(){return this._debugPassName}getDebugPassPP(){return this._debugPass||this._createDebugPass(),this._debugPass}constructor(e){this.debugEnabled=!1,this._debugSizeParams=new W.IU(0,0,0,0),this._debugPassName="Importance Sample Debug",this.onReadyObservable=new z.cP,this._scene=e,this._engine=e.getEngine()}_createTextures(){const e=this._iblSource?this._iblSource.getSize():{width:1,height:1};this._iblSource||(this._iblSource=xi.CreateRTexture(new Uint8Array([255]),1,1,this._scene,!1,!1,1,0),this._iblSource.name="Placeholder IBL Source"),this._iblSource.isCube&&(e.width*=4,e.height*=2);const t=this._engine.isWebGPU,r={generateDepthBuffer:!1,generateMipMaps:!1,format:6,type:1,samplingMode:1,shaderLanguage:t?1:0,extraInitializationsAsync:async()=>{t?await Promise.all([Promise.resolve().then(i.bind(i,43572)),Promise.resolve().then(i.bind(i,85917))]):await Promise.all([Promise.resolve().then(i.bind(i,47473)),Promise.resolve().then(i.bind(i,98824))])}},s={generateDepthBuffer:!1,generateMipMaps:!1,format:6,type:2,samplingMode:1,shaderLanguage:t?1:0,extraInitializationsAsync:async()=>{t?await Promise.all([Promise.resolve().then(i.bind(i,38957)),Promise.resolve().then(i.bind(i,27844))]):await Promise.all([Promise.resolve().then(i.bind(i,8970)),Promise.resolve().then(i.bind(i,7683))])}};this._cdfyPT=new cv("cdfyTexture",{width:e.width,height:e.height+1},"iblShadowsCdfy",this._scene,r,!1,!1),this._cdfyPT.autoClear=!1,this._cdfyPT.setTexture("iblSource",this._iblSource),this._cdfyPT.setInt("iblHeight",e.height),this._iblSource.isCube&&(this._cdfyPT.defines="#define IBL_USE_CUBE_MAP\n"),this._cdfyPT.refreshRate=0,this._icdfyPT=new cv("icdfyTexture",{width:e.width,height:e.height},"iblShadowsIcdfy",this._scene,s,!1,!1),this._icdfyPT.autoClear=!1,this._icdfyPT.setTexture("cdfy",this._cdfyPT),this._icdfyPT.refreshRate=0,this._cdfxPT=new cv("cdfxTexture",{width:e.width+1,height:1},"iblShadowsCdfx",this._scene,r,!1,!1),this._cdfxPT.autoClear=!1,this._cdfxPT.setTexture("cdfy",this._cdfyPT),this._cdfxPT.refreshRate=0,this._icdfxPT=new cv("icdfxTexture",{width:e.width,height:1},"iblShadowsIcdfx",this._scene,s,!1,!1),this._icdfxPT.autoClear=!1,this._icdfxPT.setTexture("cdfx",this._cdfxPT),this._icdfxPT.refreshRate=0}_disposeTextures(){this._cdfyPT?.dispose(),this._icdfyPT?.dispose(),this._cdfxPT?.dispose(),this._icdfxPT?.dispose()}_createDebugPass(){this._debugPass&&this._debugPass.dispose();const e=this._engine.isWebGPU,t={width:this._scene.getEngine().getRenderWidth(),height:this._scene.getEngine().getRenderHeight(),samplingMode:vi.g.BILINEAR_SAMPLINGMODE,engine:this._engine,textureType:0,uniforms:["sizeParams"],samplers:["cdfy","icdfy","cdfx","icdfx","iblSource"],defines:this._iblSource?.isCube?"#define IBL_USE_CUBE_MAP\n":"",shaderLanguage:e?1:0,extraInitializations:(e,t)=>{e?t.push(Promise.resolve().then(i.bind(i,78685))):t.push(Promise.resolve().then(i.bind(i,87382)))}};this._debugPass=new ms.w(this._debugPassName,"iblShadowsImportanceSamplingDebug",t);const r=this._debugPass.getEffect();r&&(r.defines=this._iblSource?.isCube?"#define IBL_USE_CUBE_MAP\n":""),this._iblSource?.isCube&&this._debugPass.updateEffect("#define IBL_USE_CUBE_MAP\n"),this._debugPass.onApplyObservable.add((e=>{e.setTexture("cdfy",this._cdfyPT),e.setTexture("icdfy",this._icdfyPT),e.setTexture("cdfx",this._cdfxPT),e.setTexture("icdfx",this._icdfxPT),e.setTexture("iblSource",this._iblSource),e.setFloat4("sizeParams",this._debugSizeParams.x,this._debugSizeParams.y,this._debugSizeParams.z,this._debugSizeParams.w)}))}isReady(){return this._iblSource&&"Placeholder IBL Source"!==this._iblSource.name&&this._iblSource.isReady()&&this._cdfyPT&&this._cdfyPT.isReady()&&this._icdfyPT&&this._icdfyPT.isReady()&&this._cdfxPT&&this._cdfxPT.isReady()&&this._icdfxPT&&this._icdfxPT.isReady()}dispose(){this._disposeTextures(),this._debugPass&&this._debugPass.dispose(),this.onReadyObservable.clear()}}class Fw{getOutputTexture(){return this._outputTexture}getDebugPassPP(){return this._debugPassPP||this._createDebugPass(),this._debugPassPP}get debugPassName(){return this._debugPassName}setWorldScale(e){this._worldScale=e}setDebugDisplayParams(e,t,i,r){this._debugSizeParams.set(e,t,i,r)}_createDebugPass(){if(!this._debugPassPP){const e=this._engine.isWebGPU,t={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight(),textureFormat:6,textureType:0,samplingMode:1,uniforms:["sizeParams"],samplers:["debugSampler"],engine:this._engine,reusable:!1,shaderLanguage:e?1:0,extraInitializations:(e,t)=>{e?t.push(Promise.resolve().then(i.bind(i,65461))):t.push(Promise.resolve().then(i.bind(i,73588)))}};this._debugPassPP=new ms.w(this.debugPassName,"iblShadowDebug",t),this._debugPassPP.autoClear=!1,this._debugPassPP.onApplyObservable.add((e=>{e.setTexture("debugSampler",this._outputTexture),e.setVector4("sizeParams",this._debugSizeParams)}))}}constructor(e,t){this._worldScale=1,this._blurParameters=new W.IU(0,0,0,0),this.enabled=!0,this._debugPassName="Spatial Blur Debug Pass",this.debugEnabled=!1,this._debugSizeParams=new W.IU(0,0,0,0),this._scene=e,this._engine=e.getEngine(),this._renderPipeline=t,this._createTextures()}_createTextures(){const e=this._engine.isWebGPU,t={type:0,format:5,samplingMode:1,generateDepthBuffer:!1,generateMipMaps:!1,shaderLanguage:e?1:0,extraInitializationsAsync:async()=>{e?await Promise.all([Promise.resolve().then(i.bind(i,45647))]):await Promise.all([Promise.resolve().then(i.bind(i,80018))])}};this._outputTexture=new cv("spatialBlurPass",{width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},"iblShadowSpatialBlur",this._scene,t,!1,!1,0),this._outputTexture.refreshRate=-1,this._outputTexture.autoClear=!1,this._setBindings();let r=0;this._scene.onBeforeRenderObservable.add((()=>{r=0})),this._scene.onAfterRenderTargetsRenderObservable.add((()=>{2==++r&&this.enabled&&this._outputTexture.isReady()&&(this._setBindings(),this._outputTexture.render())}))}_setBindings(){this._outputTexture.setTexture("voxelTracingSampler",this._renderPipeline._getVoxelTracingTexture()),this._blurParameters.set(1,this._worldScale,0,0),this._outputTexture.setVector4("blurParameters",this._blurParameters);const e=this._scene.geometryBufferRenderer;if(!e)return;const t=e.getTextureIndex(qO.SCREENSPACE_DEPTH_TEXTURE_TYPE);this._outputTexture.setTexture("depthSampler",e.getGBuffer().textures[t]);const i=e.getTextureIndex(qO.NORMAL_TEXTURE_TYPE);this._outputTexture.setTexture("worldNormalSampler",e.getGBuffer().textures[i])}resize(e=1){const t={width:Math.max(1,Math.floor(this._engine.getRenderWidth()*e)),height:Math.max(1,Math.floor(this._engine.getRenderHeight()*e))};this._outputTexture.resize(t,!1)}isReady(){return this._outputTexture.isReady()&&!(this._debugPassPP&&!this._debugPassPP.isReady())}dispose(){this._outputTexture.dispose(),this._debugPassPP&&this._debugPassPP.dispose()}}class Lw{getOutputTexture(){return this._outputTexture}getDebugPassPP(){return this._debugPassPP||this._createDebugPass(),this._debugPassPP}get debugPassName(){return this._debugPassName}get remanence(){return this._remanence}set remanence(e){this._remanence=e}get reset(){return this._reset}set reset(e){this._reset=e}set isMoving(e){this._isMoving=e}setDebugDisplayParams(e,t,i,r){this._debugSizeParams.set(e,t,i,r)}_createDebugPass(){if(!this._debugPassPP){const e=this._engine.isWebGPU,t={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight(),textureFormat:5,textureType:0,samplingMode:1,uniforms:["sizeParams"],samplers:["debugSampler"],engine:this._engine,reusable:!1,shaderLanguage:e?1:0,extraInitializations:(e,t)=>{e?t.push(Promise.resolve().then(i.bind(i,65461))):t.push(Promise.resolve().then(i.bind(i,73588)))}};this._debugPassPP=new ms.w(this.debugPassName,"iblShadowDebug",t),this._debugPassPP.autoClear=!1,this._debugPassPP.onApplyObservable.add((e=>{e.setTexture("debugSampler",this._outputTexture),e.setVector4("sizeParams",this._debugSizeParams)}))}}constructor(e,t){this._accumulationParams=new W.IU(0,0,0,0),this.debugEnabled=!1,this.enabled=!0,this.onReadyObservable=new z.cP,this._debugPassName="Shadow Accumulation Debug Pass",this._remanence=.9,this._reset=!0,this._isMoving=!1,this._debugSizeParams=new W.IU(0,0,0,0),this._scene=e,this._engine=e.getEngine(),this._renderPipeline=t,this._createTextures()}_createTextures(){const e=this._engine.isWebGPU,t={type:2,format:5,samplingMode:1,generateDepthBuffer:!1,generateMipMaps:!1,shaderLanguage:e?1:0,extraInitializationsAsync:async()=>{e?await Promise.all([Promise.resolve().then(i.bind(i,41115))]):await Promise.all([Promise.resolve().then(i.bind(i,17864))])}};this._outputTexture=new cv("shadowAccumulationPass",{width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},"iblShadowAccumulation",this._scene,t),this._outputTexture.refreshRate=-1,this._outputTexture.autoClear=!1,this._outputTexture.onGeneratedObservable.addOnce((()=>{this.onReadyObservable.notifyObservers()})),this._setOutputTextureBindings();let r=0;this._scene.onBeforeRenderObservable.add((()=>{r=0})),this._scene.onAfterRenderTargetsRenderObservable.add((()=>{2==++r&&this.enabled&&this._outputTexture.isReady()&&(this._setOutputTextureBindings(),this._outputTexture.render())}));const s={type:2,format:5,samplingMode:1,generateDepthBuffer:!1,generateMipMaps:!1,shaderLanguage:e?1:0,extraInitializationsAsync:async()=>{e?await Promise.all([Promise.resolve().then(i.bind(i,418))]):await Promise.all([Promise.resolve().then(i.bind(i,30927))])}};this._oldAccumulationCopy=new cv("oldAccumulationRT",{width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},"pass",this._scene,s,!1),this._oldAccumulationCopy.autoClear=!1,this._oldAccumulationCopy.refreshRate=1,this._oldAccumulationCopy.onBeforeGenerationObservable.add(this._setAccumulationCopyBindings.bind(this)),this._setAccumulationCopyBindings();const n={type:2,format:5,samplingMode:1,generateDepthBuffer:!1,generateMipMaps:!1,shaderLanguage:e?1:0,extraInitializationsAsync:async()=>{e?await Promise.all([Promise.resolve().then(i.bind(i,418))]):await Promise.all([Promise.resolve().then(i.bind(i,30927))])}};this._oldPositionCopy=new cv("oldLocalPositionRT",{width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},"pass",this._scene,n,!1),this._updatePositionCopy(),this._oldPositionCopy.autoClear=!1,this._oldPositionCopy.refreshRate=1,this._oldPositionCopy.onBeforeGenerationObservable.add(this._updatePositionCopy.bind(this))}_setOutputTextureBindings(){const e=this._isMoving?this.remanence:.99;this._accumulationParams.set(e,this.reset?1:0,this._renderPipeline.voxelGridSize,0),this._outputTexture.setTexture("spatialBlurSampler",this._renderPipeline._getSpatialBlurTexture()),this._outputTexture.setVector4("accumulationParameters",this._accumulationParams),this._outputTexture.setTexture("oldAccumulationSampler",this._oldAccumulationCopy?this._oldAccumulationCopy:this._renderPipeline._dummyTexture2d),this._outputTexture.setTexture("prevPositionSampler",this._oldPositionCopy?this._oldPositionCopy:this._renderPipeline._dummyTexture2d);const t=this._scene.geometryBufferRenderer;if(!t)return;const i=t.getTextureIndex(qO.VELOCITY_LINEAR_TEXTURE_TYPE);this._outputTexture.setTexture("motionSampler",t.getGBuffer().textures[i]);const r=t.getTextureIndex(qO.POSITION_TEXTURE_TYPE);this._outputTexture.setTexture("positionSampler",t.getGBuffer().textures[r]),this.reset=!1,this._isMoving=!1}_updatePositionCopy(){const e=this._scene.geometryBufferRenderer,t=e.getTextureIndex(qO.POSITION_TEXTURE_TYPE);this._oldPositionCopy.setTexture("textureSampler",e.getGBuffer().textures[t])}_setAccumulationCopyBindings(){this._oldAccumulationCopy.setTexture("textureSampler",this._outputTexture)}resize(e=1){const t={width:Math.max(1,Math.floor(this._engine.getRenderWidth()*e)),height:Math.max(1,Math.floor(this._engine.getRenderHeight()*e))};this._outputTexture.resize(t,!1),this._oldAccumulationCopy.resize(t,!1),this._oldPositionCopy.resize({width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},!1),this.reset=!0}_disposeTextures(){this._oldAccumulationCopy.dispose(),this._oldPositionCopy.dispose(),this._outputTexture.dispose()}isReady(){return this._oldAccumulationCopy&&this._oldAccumulationCopy.isReady()&&this._oldPositionCopy&&this._oldPositionCopy.isReady()&&this._outputTexture.isReady()&&!(this._debugPassPP&&!this._debugPassPP.isReady())}dispose(){this._disposeTextures(),this._debugPassPP&&this._debugPassPP.dispose(),this.onReadyObservable.clear()}}class Bw extends xn{constructor(){super(...arguments),this.RENDER_WITH_IBL_SHADOWS=!1}}class Vw extends Dn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e){super(e,Vw.Name,310,new Bw),this.shadowOpacity=1,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}prepareDefines(e){e.RENDER_WITH_IBL_SHADOWS=this._isEnabled}getClassName(){return"IBLShadowsPluginMaterial"}getUniforms(){return{ubo:[{name:"renderTargetSize",size:2,type:"vec2"},{name:"shadowOpacity",size:1,type:"float"}],fragment:"#ifdef RENDER_WITH_IBL_SHADOWS\n uniform vec2 renderTargetSize;\n uniform float shadowOpacity;\n #endif"}}getSamplers(e){e.push("iblShadowsTexture")}bindForSubMesh(e){this._isEnabled&&(e.bindTexture("iblShadowsTexture",this.iblShadowsTexture),e.updateFloat2("renderTargetSize",this._material.getScene().getEngine().getRenderWidth(),this._material.getScene().getEngine().getRenderHeight()),e.updateFloat("shadowOpacity",this.shadowOpacity))}getCustomCode(e,t){let i;return 1===t?(i={CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RENDER_WITH_IBL_SHADOWS\n var iblShadowsTextureSampler: sampler;\n var iblShadowsTexture: texture_2d;\n\n fn computeIndirectShadow() -> vec2f {\n var uv = fragmentInputs.position.xy / uniforms.renderTargetSize;\n var shadowValue: vec2f = textureSample(iblShadowsTexture, iblShadowsTextureSampler, uv).rg;\n return mix(shadowValue, vec2f(1.0), 1.0 - uniforms.shadowOpacity);\n }\n #endif\n "},this._material instanceof Gm?i.CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION="\n #ifdef RENDER_WITH_IBL_SHADOWS\n #ifdef REFLECTION\n var shadowValue: vec2f = computeIndirectShadow();\n finalIrradiance *= vec3f(shadowValue.x);\n finalRadianceScaled *= vec3f(mix(pow(shadowValue.y, 4.0), shadowValue.x, roughness));\n #endif\n #endif\n ":i.CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR="\n #ifdef RENDER_WITH_IBL_SHADOWS\n var shadowValue: vec2f = computeIndirectShadow();\n color *= toGammaSpace(vec4f(shadowValue.x, shadowValue.x, shadowValue.x, 1.0f));\n #endif\n "):(i={CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RENDER_WITH_IBL_SHADOWS\n uniform sampler2D iblShadowsTexture;\n\n vec2 computeIndirectShadow() {\n vec2 uv = gl_FragCoord.xy / renderTargetSize;\n vec2 shadowValue = texture2D(iblShadowsTexture, uv).rg;\n return mix(shadowValue.rg, vec2(1.0), 1.0 - shadowOpacity);\n }\n #endif\n "},this._material instanceof Gm?i.CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION="\n #ifdef RENDER_WITH_IBL_SHADOWS\n #ifdef REFLECTION\n vec2 shadowValue = computeIndirectShadow();\n finalIrradiance *= shadowValue.x;\n finalRadianceScaled *= mix(pow(shadowValue.y, 4.0), shadowValue.x, roughness);\n #endif\n #endif\n ":i.CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR="\n #ifdef RENDER_WITH_IBL_SHADOWS\n vec2 shadowValue = computeIndirectShadow();\n color.rgb *= toGammaSpace(shadowValue.x);\n #endif\n "),"vertex"===e?null:i}}Vw.Name="IBLShadowsPluginMaterial",(0,je.Cg)([(0,$e.lK)()],Vw.prototype,"iblShadowsTexture",void 0),(0,je.Cg)([(0,$e.lK)()],Vw.prototype,"shadowOpacity",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vw.prototype,"isEnabled",void 0),(0,X.Y5)("BABYLON.IBLShadowsPluginMaterial",Vw);class kw extends JO{resetAccumulation(){this._accumulationPass.reset=!0}get shadowOpacity(){return this._shadowOpacity}set shadowOpacity(e){this._shadowOpacity=e,this._setPluginParameters()}get shadowRenderSizeFactor(){return this._renderSizeFactor}set shadowRenderSizeFactor(e){this._renderSizeFactor=Math.max(Math.min(e,1),0),this._voxelTracingPass.resize(e),this._spatialBlurPass.resize(e),this._accumulationPass.resize(e),this._setPluginParameters()}get voxelShadowOpacity(){return this._voxelTracingPass?.voxelShadowOpacity}set voxelShadowOpacity(e){this._voxelTracingPass&&(this._voxelTracingPass.voxelShadowOpacity=e)}get ssShadowOpacity(){return this._voxelTracingPass?.ssShadowOpacity}set ssShadowOpacity(e){this._voxelTracingPass&&(this._voxelTracingPass.ssShadowOpacity=e)}get ssShadowSampleCount(){return this._voxelTracingPass?.sssSamples}set ssShadowSampleCount(e){this._voxelTracingPass&&(this._voxelTracingPass.sssSamples=e)}get ssShadowStride(){return this._voxelTracingPass?.sssStride}set ssShadowStride(e){this._voxelTracingPass&&(this._voxelTracingPass.sssStride=e)}get ssShadowDistanceScale(){return this._sssMaxDistScale}set ssShadowDistanceScale(e){this._sssMaxDistScale=e,this._updateSSShadowParams()}get ssShadowThicknessScale(){return this._sssThicknessScale}set ssShadowThicknessScale(e){this._sssThicknessScale=e,this._updateSSShadowParams()}setIblTexture(e){this._importanceSamplingRenderer&&(this._importanceSamplingRenderer.iblSource=e)}_getVoxelGridTexture(){const e=this._voxelRenderer?.getVoxelGrid();return e&&e.isReady()?e:this._dummyTexture3d}_getIcdfyTexture(){const e=this._importanceSamplingRenderer.getIcdfyTexture();return e&&e.isReady()?e:this._dummyTexture2d}_getIcdfxTexture(){const e=this._importanceSamplingRenderer.getIcdfxTexture();return e&&e.isReady()?e:this._dummyTexture2d}_getNoiseTexture(){const e=this._noiseTexture;return e&&e.isReady()?e:this._dummyTexture2d}_getVoxelTracingTexture(){const e=this._voxelTracingPass?.getOutputTexture();return e&&e.isReady()?e:this._dummyTexture2d}_getSpatialBlurTexture(){const e=this._spatialBlurPass.getOutputTexture();return e&&e.isReady()?e:this._dummyTexture2d}_getAccumulatedTexture(){const e=this._accumulationPass?.getOutputTexture();return e&&e.isReady()?e:this._dummyTexture2d}get gbufferDebugEnabled(){return this._gbufferDebugEnabled}set gbufferDebugEnabled(e){!e||this.allowDebugPasses?(this._gbufferDebugEnabled=e,e?this._enableEffect(this._getGBufferDebugPass().name,this.cameras):this._disableEffect(this._getGBufferDebugPass().name,this.cameras)):Z.V.Warn("Can't enable G-Buffer debug view without setting allowDebugPasses to true.")}get importanceSamplingDebugEnabled(){return this._importanceSamplingRenderer?.debugEnabled}set importanceSamplingDebugEnabled(e){this._importanceSamplingRenderer&&(!e||this.allowDebugPasses?e!==this._importanceSamplingRenderer.debugEnabled&&(this._importanceSamplingRenderer.debugEnabled=e,e?this._enableEffect(this._importanceSamplingRenderer.debugPassName,this.cameras):this._disableEffect(this._importanceSamplingRenderer.debugPassName,this.cameras)):Z.V.Warn("Can't enable importance sampling debug view without setting allowDebugPasses to true."))}get voxelDebugEnabled(){return this._voxelRenderer?.voxelDebugEnabled}set voxelDebugEnabled(e){this._voxelRenderer&&(!e||this.allowDebugPasses?(this._voxelRenderer.voxelDebugEnabled=e,e?this._enableEffect(this._voxelRenderer.debugPassName,this.cameras):this._disableEffect(this._voxelRenderer.debugPassName,this.cameras)):Z.V.Warn("Can't enable voxel debug view without setting allowDebugPasses to true."))}get voxelDebugAxis(){return this._voxelRenderer?.voxelDebugAxis}set voxelDebugAxis(e){this._voxelRenderer&&(this._voxelRenderer.voxelDebugAxis=e)}set voxelDebugDisplayMip(e){this._voxelRenderer&&this._voxelRenderer.setDebugMipNumber(e)}get voxelTracingDebugEnabled(){return this._voxelTracingPass?.debugEnabled}set voxelTracingDebugEnabled(e){this._voxelTracingPass&&(!e||this.allowDebugPasses?e!==this._voxelTracingPass.debugEnabled&&(this._voxelTracingPass.debugEnabled=e,e?this._enableEffect(this._voxelTracingPass.debugPassName,this.cameras):this._disableEffect(this._voxelTracingPass.debugPassName,this.cameras)):Z.V.Warn("Can't enable voxel tracing debug view without setting allowDebugPasses to true."))}get spatialBlurPassDebugEnabled(){return this._spatialBlurPass.debugEnabled}set spatialBlurPassDebugEnabled(e){this._spatialBlurPass&&(!e||this.allowDebugPasses?e!==this._spatialBlurPass.debugEnabled&&(this._spatialBlurPass.debugEnabled=e,e?this._enableEffect(this._spatialBlurPass.debugPassName,this.cameras):this._disableEffect(this._spatialBlurPass.debugPassName,this.cameras)):Z.V.Warn("Can't enable spatial blur debug view without setting allowDebugPasses to true."))}get accumulationPassDebugEnabled(){return this._accumulationPass?.debugEnabled}set accumulationPassDebugEnabled(e){this._accumulationPass&&(!e||this.allowDebugPasses?e!==this._accumulationPass.debugEnabled&&(this._accumulationPass.debugEnabled=e,e?this._enableEffect(this._accumulationPass.debugPassName,this.cameras):this._disableEffect(this._accumulationPass.debugPassName,this.cameras)):Z.V.Warn("Can't enable accumulation pass debug view without setting allowDebugPasses to true."))}addShadowCastingMesh(e){if(Array.isArray(e))for(const t of e)t&&-1===this._shadowCastingMeshes.indexOf(t)&&this._shadowCastingMeshes.push(t);else e&&-1===this._shadowCastingMeshes.indexOf(e)&&this._shadowCastingMeshes.push(e)}removeShadowCastingMesh(e){if(Array.isArray(e))for(const t of e){const e=this._shadowCastingMeshes.indexOf(t);-1!==e&&this._shadowCastingMeshes.splice(e,1)}else{const t=this._shadowCastingMeshes.indexOf(e);-1!==t&&this._shadowCastingMeshes.splice(t,1)}}get resolutionExp(){return this._voxelRenderer.voxelResolutionExp}set resolutionExp(e){e!==this._voxelRenderer.voxelResolutionExp&&(this._voxelRenderer.isVoxelizationInProgress()?Z.V.Warn("Can't change the resolution of the voxel grid while voxelization is in progress."):(this._voxelRenderer.voxelResolutionExp=Math.max(1,Math.min(e,8)),this._accumulationPass.reset=!0))}get sampleDirections(){return this._voxelTracingPass?.sampleDirections}set sampleDirections(e){this._voxelTracingPass&&(this._voxelTracingPass.sampleDirections=e)}get shadowRemanence(){return this._accumulationPass?.remanence}set shadowRemanence(e){this._accumulationPass&&(this._accumulationPass.remanence=e)}get envRotation(){return this._voxelTracingPass?.envRotation}set envRotation(e){this._voxelTracingPass&&(this._voxelTracingPass.envRotation=e,this._accumulationPass.reset=!0)}get allowDebugPasses(){return this._allowDebugPasses}set allowDebugPasses(e){this._allowDebugPasses!==e&&(this._allowDebugPasses=e,e?this._importanceSamplingRenderer.isReady()?this._createDebugPasses():this._importanceSamplingRenderer.onReadyObservable.addOnce((()=>{this._createDebugPasses()})):this._disposeDebugPasses())}static get IsSupported(){const e=he.q.LastCreatedEngine;return!!e&&e._features.supportIBLShadows}toggleShadow(e){this._enabled=e,this._voxelTracingPass.enabled=e,this._spatialBlurPass.enabled=e,this._accumulationPass.enabled=e,this._materialsWithRenderPlugin.forEach((t=>{t.pluginManager&&(t.pluginManager.getPlugin(Vw.Name).isEnabled=e)})),this._setPluginParameters()}updateVoxelization(){0!==this._shadowCastingMeshes.length?(this._voxelRenderer.updateVoxelGrid(this._shadowCastingMeshes),this._updateSSShadowParams()):Z.V.Warn("IBL Shadows: updateVoxelization called with no shadow-casting meshes to voxelize.")}updateSceneBounds(){const e={min:new W.Pq(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),max:new W.Pq(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE)};this._shadowCastingMeshes.forEach((t=>{const i=t.getHierarchyBoundingVectors(!0);e.min=W.Pq.Minimize(e.min,i.min),e.max=W.Pq.Maximize(e.max,i.max)}));const t=e.max.subtract(e.min);if(this.voxelGridSize=Math.max(t.x,t.y,t.z),0===this._shadowCastingMeshes.length||!isFinite(this.voxelGridSize)||0===this.voxelGridSize)return Z.V.Warn("IBL Shadows: Scene size is invalid. Can't update bounds."),void(this.voxelGridSize=1);const i=this.voxelGridSize/2,r=e.max.add(e.min).multiplyByFloats(-.5,-.5,-.5),s=W.uq.Compose(new W.Pq(1/i,1/i,1/i),new W.PT,new W.Pq(0,0,0));W.uq.Compose(new W.Pq(1,1,1),new W.PT,r).multiplyToRef(s,s),this._voxelTracingPass.setWorldScaleMatrix(s),this._voxelRenderer.setWorldScaleMatrix(s),this._spatialBlurPass.setWorldScale(2*i),this._updateSSShadowParams()}constructor(e,t,i={},r){super(t.getEngine(),e),this._allowDebugPasses=!1,this._debugPasses=[],this._shadowCastingMeshes=[],this._shadowOpacity=.8,this._enabled=!0,this._materialsWithRenderPlugin=[],this.onShadowTextureReadyObservable=new z.cP,this.onNewIblReadyObservable=new z.cP,this.voxelGridSize=1,this._renderSizeFactor=1,this._gbufferDebugEnabled=!1,this._gBufferDebugSizeParams=new W.IU(0,0,0,0),this.scene=t,this._cameras=r||[t.activeCamera];const s=new Uint8Array([0,0,0,255]);this._dummyTexture2d=new xi(s,1,1,an.TEXTUREFORMAT_RGBA,t,!1),this._dummyTexture3d=new Qb(s,1,1,1,an.TEXTUREFORMAT_RGBA,t,!1);const n={};n[qO.SCREENSPACE_DEPTH_TEXTURE_TYPE]={textureFormat:6,textureType:1},n[qO.VELOCITY_LINEAR_TEXTURE_TYPE]={textureFormat:7,textureType:2},n[qO.POSITION_TEXTURE_TYPE]={textureFormat:5,textureType:2},n[qO.NORMAL_TEXTURE_TYPE]={textureFormat:5,textureType:2};const o=t.enableGeometryBufferRenderer(void 0,14,n);o?(this._geometryBufferRenderer=o,this._geometryBufferRenderer.enableScreenspaceDepth=!0,this._geometryBufferRenderer.enableVelocityLinear=!0,this._geometryBufferRenderer.enablePosition=!0,this._geometryBufferRenderer.enableNormal=!0,this._geometryBufferRenderer.generateNormalsInWorldSpace=!0,this.shadowOpacity=i.shadowOpacity||.8,this._voxelRenderer=new Dw(this.scene,this,i?i.resolutionExp:6,void 0===i.triPlanarVoxelization||i.triPlanarVoxelization),this._importanceSamplingRenderer=new Nw(this.scene),this._voxelTracingPass=new ww(this.scene,this),this._spatialBlurPass=new Fw(this.scene,this),this._accumulationPass=new Lw(this.scene,this),this._accumulationPass.onReadyObservable.addOnce((()=>{this.onShadowTextureReadyObservable.notifyObservers()})),this.sampleDirections=i.sampleDirections||2,this.voxelShadowOpacity=i.voxelShadowOpacity??1,this.envRotation=i.envRotation??0,this.shadowRenderSizeFactor=i.shadowRenderSizeFactor||1,this.ssShadowOpacity=void 0===i.ssShadowsEnabled||i.ssShadowsEnabled?1:0,this.ssShadowDistanceScale=i.ssShadowDistanceScale||1.25,this.ssShadowSampleCount=i.ssShadowSampleCount||16,this.ssShadowStride=i.ssShadowStride||8,this.ssShadowThicknessScale=i.ssShadowThicknessScale||1,this.shadowRemanence=i.shadowRemanence??.75,this._noiseTexture=new vi.g("https://assets.babylonjs.com/textures/blue_noise/blue_noise_rgb.png",this.scene,!1,!0,1),this.scene.environmentTexture&&(this._importanceSamplingRenderer.iblSource=this.scene.environmentTexture),t.postProcessRenderPipelineManager.addPipeline(this),this.scene.onActiveCameraChanged.add(this._listenForCameraChanges.bind(this)),this.scene.onBeforeRenderObservable.add(this._updateBeforeRender.bind(this)),this._listenForCameraChanges(),this.scene.getEngine().onResizeObservable.add(this._handleResize.bind(this)),this._importanceSamplingRenderer.onReadyObservable.add((()=>{this._setPluginParameters(),this.onNewIblReadyObservable.notifyObservers()}))):Z.V.Error("Geometry buffer renderer is required for IBL shadows to work.")}_handleResize(){this._voxelRenderer.resize(),this._voxelTracingPass.resize(this.shadowRenderSizeFactor),this._spatialBlurPass.resize(this.shadowRenderSizeFactor),this._accumulationPass.resize(this.shadowRenderSizeFactor),this._setPluginParameters()}_getGBufferDebugPass(){if(this._gbufferDebugPass)return this._gbufferDebugPass;const e=this.engine.isWebGPU,t={width:this.scene.getEngine().getRenderWidth(),height:this.scene.getEngine().getRenderHeight(),samplingMode:1,engine:this.scene.getEngine(),textureType:0,textureFormat:5,uniforms:["sizeParams"],samplers:["depthSampler","normalSampler","positionSampler","velocitySampler"],reusable:!1,shaderLanguage:e?1:0,extraInitializations:(e,t)=>{e?t.push(Promise.resolve().then(i.bind(i,23008))):t.push(Promise.resolve().then(i.bind(i,64367)))}};return this._gbufferDebugPass=new ms.w("iblShadowGBufferDebug","iblShadowGBufferDebug",t),this._gbufferDebugPass.autoClear=!1,this._gbufferDebugPass.onApplyObservable.add((e=>{const t=this._geometryBufferRenderer.getTextureIndex(qO.SCREENSPACE_DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[t]);const i=this._geometryBufferRenderer.getTextureIndex(qO.NORMAL_TEXTURE_TYPE);e.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[i]);const r=this._geometryBufferRenderer.getTextureIndex(qO.POSITION_TEXTURE_TYPE);e.setTexture("positionSampler",this._geometryBufferRenderer.getGBuffer().textures[r]);const s=this._geometryBufferRenderer.getTextureIndex(qO.VELOCITY_LINEAR_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[s]),e.setVector4("sizeParams",this._gBufferDebugSizeParams),this.scene.activeCamera&&e.setFloat("maxDepth",this.scene.activeCamera.maxZ)})),this._gbufferDebugPass}_createDebugPasses(){this._debugPasses=[{pass:this._importanceSamplingRenderer.getDebugPassPP(),enabled:this.importanceSamplingDebugEnabled},{pass:this._voxelRenderer.getDebugPassPP(),enabled:this.voxelDebugEnabled},{pass:this._voxelTracingPass.getDebugPassPP(),enabled:this.voxelTracingDebugEnabled},{pass:this._spatialBlurPass.getDebugPassPP(),enabled:this.spatialBlurPassDebugEnabled},{pass:this._accumulationPass.getDebugPassPP(),enabled:this.accumulationPassDebugEnabled},{pass:this._getGBufferDebugPass(),enabled:this.gbufferDebugEnabled}];for(let e=0;ethis._debugPasses[e].pass),!0));const e=this.cameras.slice();this.scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this.name,this.cameras),this.scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this.name,e);for(let e=0;e{this._addShadowSupportToMaterial(e)})):this._addShadowSupportToMaterial(e):this.scene.materials.forEach((e=>{this._addShadowSupportToMaterial(e)}))}removeShadowReceivingMaterial(e){if(Array.isArray(e))e.forEach((e=>{const t=this._materialsWithRenderPlugin.indexOf(e);if(-1!==t){this._materialsWithRenderPlugin.splice(t,1);const i=e.pluginManager?.getPlugin(Vw.Name);i.isEnabled=!1}}));else{const t=this._materialsWithRenderPlugin.indexOf(e);-1!==t&&(this._materialsWithRenderPlugin.splice(t,1),e.pluginManager.getPlugin(Vw.Name).isEnabled=!1)}}_addShadowSupportToMaterial(e){if(!(e instanceof Gm||e instanceof Un))return;let t=e.pluginManager?.getPlugin(Vw.Name);t||(t=new Vw(e)),-1===this._materialsWithRenderPlugin.indexOf(e)&&(this._enabled&&(t.iblShadowsTexture=this._getAccumulatedTexture().getInternalTexture(),t.shadowOpacity=this.shadowOpacity),t.isEnabled=this._enabled,this._materialsWithRenderPlugin.push(e))}_setPluginParameters(){this._enabled&&this._materialsWithRenderPlugin.forEach((e=>{if(e.pluginManager){const t=e.pluginManager.getPlugin(Vw.Name);t.iblShadowsTexture=this._getAccumulatedTexture().getInternalTexture(),t.shadowOpacity=this.shadowOpacity}}))}_updateBeforeRender(){this._updateDebugPasses()}_listenForCameraChanges(){this.scene.activeCamera?.onViewMatrixChangedObservable.add((()=>{this._accumulationPass.isMoving=!0}))}isReady(){return this._noiseTexture.isReady()&&this._voxelRenderer.isReady()&&this._importanceSamplingRenderer.isReady()&&(!this._voxelTracingPass||this._voxelTracingPass.isReady())&&(!this._spatialBlurPass||this._spatialBlurPass.isReady())&&(!this._accumulationPass||this._accumulationPass.isReady())}getClassName(){return"IBLShadowsRenderPipeline"}dispose(){this._materialsWithRenderPlugin.splice(0).forEach((e=>{this.removeShadowReceivingMaterial(e)})),this._disposeEffectPasses(),this._noiseTexture.dispose(),this._voxelRenderer.dispose(),this._importanceSamplingRenderer.dispose(),this._voxelTracingPass.dispose(),this._spatialBlurPass.dispose(),this._accumulationPass.dispose(),this._dummyTexture2d.dispose(),this._dummyTexture3d.dispose(),this.onNewIblReadyObservable.clear(),this.onShadowTextureReadyObservable.clear(),super.dispose()}}class Uw extends Xb{constructor(e,t,i,r,s,n){super(e,i,r,s,n),this._beforeCompositionPostProcesses=[],this._internalTextureDirty=!1,this.enabled=!1,this.renderTargetTexture=null,this.renderTargetTexture=t}_createCompositionEffect(){this.imageProcessingPostProcess=new zO("prePassComposition",1,null,void 0,this._engine),this.imageProcessingPostProcess._updateParameters()}_checkSize(){const e=this._engine.getRenderWidth(!0),t=this._engine.getRenderHeight(!0),i=this.getRenderWidth(),r=this.getRenderHeight();i===e&&r===t||(this.resize({width:e,height:t}),this._internalTextureDirty=!0)}updateCount(e,t,i){super.updateCount(e,t,i),this._internalTextureDirty=!0}_resetPostProcessChain(){this._beforeCompositionPostProcesses.length=0}dispose(){const e=this._scene;if(super.dispose(),e&&e.prePassRenderer){const t=e.prePassRenderer.renderTargets.indexOf(this);-1!==t&&e.prePassRenderer.renderTargets.splice(t,1)}this.imageProcessingPostProcess&&this.imageProcessingPostProcess.dispose(),this.renderTargetTexture&&(this.renderTargetTexture._prePassRenderTarget=null),this._outputPostProcess&&(this._outputPostProcess.autoClear=!0,this._outputPostProcess.restoreDefaultInputTexture())}}class Gw{get generateNormalsInWorldSpace(){return this._generateNormalsInWorldSpace}set generateNormalsInWorldSpace(e){this._generateNormalsInWorldSpace!==e&&(this._generateNormalsInWorldSpace=e,this._markAllMaterialsAsPrePassDirty())}getIndex(e){return this._textureIndices[e]}get samples(){return this.defaultRT.samples}set samples(e){this.defaultRT.samples=e}get useSpecificClearForDepthTexture(){return this._useSpecificClearForDepthTexture}set useSpecificClearForDepthTexture(e){this._useSpecificClearForDepthTexture!==e&&(this._useSpecificClearForDepthTexture=e,this._isDirty=!0)}getRenderTarget(){return this._currentTarget}_setRenderTarget(e){e?this._currentTarget=e:(this._currentTarget=this.defaultRT,this._engine.currentRenderPassId=this._scene.activeCamera?.renderPassId??this._currentTarget.renderPassId)}get currentRTisSceneRT(){return this._currentTarget===this.defaultRT}_refreshGeometryBufferRendererLink(){if(this.doNotUseGeometryRendererFallback)this._geometryBuffer&&this._geometryBuffer._unlinkPrePassRenderer(),this._geometryBuffer=null,this._scene.disableGeometryBufferRenderer();else{if(this._geometryBuffer=this._scene.enableGeometryBufferRenderer(),!this._geometryBuffer)return void(this.doNotUseGeometryRendererFallback=!0);this._geometryBuffer._linkPrePassRenderer(this)}}get enabled(){return this._enabled}constructor(e){this.excludedSkinnedMesh=[],this.excludedMaterials=[],this.mrtCount=0,this._mrtTypes=[],this._mrtFormats=[],this._mrtLayout=[],this._mrtNames=[],this._textureIndices=[],this._generateNormalsInWorldSpace=!1,this._useSpecificClearForDepthTexture=!1,this._isDirty=!0,this._effectConfigurations=[],this.doNotUseGeometryRendererFallback=!0,this.renderTargets=[],this._clearColor=new H.ov(0,0,0,0),this._clearDepthColor=new H.ov(1e8,0,0,1),this._enabled=!1,this._needsCompositionForThisPass=!1,this.disableGammaTransform=!1,this._scene=e,this._engine=e.getEngine();let t=0;this._engine._caps.textureFloat&&this._engine._caps.textureFloatLinearFiltering?t=1:this._engine._caps.textureHalfFloat&&this._engine._caps.textureHalfFloatLinearFiltering&&(t=2);for(let e=0;e0&&(this._useSpecificClearForDepthTexture&&5===this._mrtLayout[s]?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),r.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(r)}_resetLayout(){for(let e=0;enull!=e)),this._scene.autoClear=!0;const r=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!r&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;const s=this._getFirstPostProcess(this._postProcessesSourceForThisPass),n=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0];let o=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||r,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),n?o=n:this._needsCompositionForThisPass?o=e.imageProcessingPostProcess:s&&(o=s),this._bindFrameBuffer(),this._linkInternalTexture(e,o)}_linkInternalTexture(e,t){t&&(t.autoClear=!1,t.inputTexture=e.renderTarget),e._outputPostProcess!==t&&(e._outputPostProcess&&this._unlinkInternalTexture(e),e._outputPostProcess=t),e._internalTextureDirty&&(this._updateGeometryBufferLayout(),e._internalTextureDirty=!1)}_unlinkInternalTexture(e){e._outputPostProcess&&(e._outputPostProcess.autoClear=!0,e._outputPostProcess.restoreDefaultInputTexture(),e._outputPostProcess=null)}_needsImageProcessing(){for(let e=0;enull!=e)),e)){for(let r=0;r=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw(0,Je.n)("PrePassRendererSceneComponent")},Gw.TextureFormats=[{purpose:0,type:2,format:5,name:"prePass_Irradiance"},{purpose:1,type:2,format:5,name:"prePass_Position"},{purpose:2,type:0,format:5,name:"prePass_Velocity"},{purpose:3,type:0,format:5,name:"prePass_Reflectivity"},{purpose:4,type:2,format:5,name:"prePass_Color"},{purpose:5,type:1,format:6,name:"prePass_Depth"},{purpose:6,type:2,format:5,name:"prePass_Normal"},{purpose:7,type:0,format:5,name:"prePass_Albedo"},{purpose:8,type:0,format:5,name:"prePass_WorldNormal"},{purpose:9,type:2,format:5,name:"prePass_LocalPosition"},{purpose:10,type:1,format:6,name:"prePass_ScreenDepth"},{purpose:11,type:2,format:5,name:"prePass_VelocityLinear"}],Object.defineProperty(oi.Z.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(e){e&&e.isSupported&&(this._prePassRenderer=e)},enumerable:!0,configurable:!0}),oi.Z.prototype.enablePrePassRenderer=function(){return this._prePassRenderer||(this._prePassRenderer=new Gw(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,Z.V.Error("PrePassRenderer needs WebGL 2 support.\nMaybe you tried to use the following features that need the PrePassRenderer :\n + Subsurface Scattering"))),this._prePassRenderer},oi.Z.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class zw{constructor(e){this.name=Ut.v.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(Ut.v.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(Ut.v.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(Ut.v.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(Ut.v.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(Ut.v.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(Ut.v.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(Ut.v.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(Ut.v.STEP_AFTERRENDERINGMESH_PREPASS,this,this._afterRenderingMeshStage)}_beforeRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._beforeDraw(void 0,t,i))}_afterRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&this.scene.prePassRenderer._afterDraw(t,i)}_beforeRenderTargetClearStage(e){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(e._prePassRenderTarget||(e._prePassRenderTarget=this.scene.prePassRenderer._createRenderTarget(e.name+"_prePassRTT",e)),this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._clear())}_beforeCameraDraw(e){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._beforeDraw(e))}_afterCameraDraw(){this.scene.prePassRenderer&&this.scene.prePassRenderer._afterDraw()}_beforeClearStage(){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._clear())}_beforeRenderingMeshStage(e,t,i,r){if(!r)return;const s=e.getScene();s.prePassRenderer&&s.prePassRenderer.bindAttachmentsForEffect(r,t)}_afterRenderingMeshStage(e){const t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){}dispose(){this.scene.disablePrePassRenderer()}}Gw._SceneComponentInitialization=e=>{let t=e._getComponent(Ut.v.NAME_PREPASSRENDERER);t||(t=new zw(e),e._addComponent(t))};Cs.l.IncludesShadersStore.fibonacci="#define rcp(x) 1./x\n#define GOLDEN_RATIO 1.618033988749895\n#define TWO_PI 6.2831855\nvec2 Golden2dSeq(int i,float n)\n{return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));}\nvec2 SampleDiskGolden(int i,int sampleCount)\n{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}",i(34001);Cs.l.IncludesShadersStore.diffusionProfile="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";Cs.l.ShadersStore.subSurfaceScatteringPixelShader="#include\n#include\n#include\n#include\nvarying 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;\n#define rcp(x) 1./x\n#define Sq(x) x*x\n#define SSS_BILATERAL_FILTER true\nvec3 EvalBurleyDiffusionProfile(float r,vec3 S)\n{vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); \nvec3 expSum=exp_13*(1.+exp_13*exp_13); \nreturn (S*rcp(8.*PI))*expSum; }\nvec2 SampleBurleyDiffusionProfile(float u,float rcpS)\n{u=1.-u; \nfloat g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); \nfloat p=(g*n)*n; \nfloat c=1.+p+n; \nfloat d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); \nfloat x=(3./LOG2_E)*log2(c)-d; \nfloat rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; \nreturn vec2(r,rcpPdf);}\nvec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf)\n{\n#ifndef SSS_BILATERAL_FILTER\nz=0.;\n#endif\nfloat r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf;\n#if SSS_CLAMP_ARTIFACT\nreturn clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0);\n#else\nreturn EvalBurleyDiffusionProfile(r,S)*area;\n#endif\n}\nvoid EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm,\nfloat phase,inout vec3 totalIrradiance,inout vec3 totalWeight)\n{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; \nfloat cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; \nvec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; \nfloat 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))\n{float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;}\nelse\n{}}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{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)\n{centerDepth=texture2D(depthSampler,vUV).r;}\nif (!passedStencilTest) { \ngl_FragColor=inputColor;return;}\nfloat 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; \nvec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; \nfloat 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)\n{\n#ifdef DEBUG_SSS_SAMPLES\nvec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return;\n#endif\ngl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;}\n#ifdef DEBUG_SSS_SAMPLES\nvec3 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;\n#endif\nfloat phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); \nvec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i{if(!t.prePassRenderer||!t.subSurfaceConfiguration)return void Z.V.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");const i=this.texelSize;e.setFloat("metersPerUnit",t.subSurfaceConfiguration.metersPerUnit),e.setFloat2("texelSize",i.x,i.y),e.setTexture("irradianceSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(0)]),e.setTexture("depthSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(5)]),e.setTexture("albedoSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(7)]),e.setFloat2("viewportSize",Math.tan(t.activeCamera.fov/2)*t.getEngine().getAspectRatio(t.activeCamera,!0),Math.tan(t.activeCamera.fov/2)),e.setArray3("diffusionS",t.subSurfaceConfiguration.ssDiffusionS),e.setArray("diffusionD",t.subSurfaceConfiguration.ssDiffusionD),e.setArray("filterRadii",t.subSurfaceConfiguration.ssFilterRadii)}))}}class Hw{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=Ut.v.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new H.v9(1,1,1)),this._scene=e,Hw._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return Z.V.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw(0,Je.n)("SubSurfaceSceneComponent")},ci(Ut.v.NAME_SUBSURFACE,((e,t)=>{if(void 0!==e.ssDiffusionProfileColors&&null!==e.ssDiffusionProfileColors&&(t.enableSubSurfaceForPrePass(),t.subSurfaceConfiguration))for(let i=0,r=e.ssDiffusionProfileColors.length;i{let t=e._getComponent(Ut.v.NAME_SUBSURFACE);t||(t=new Xw(e),e._addComponent(t))},oi.Z.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new qw(this)),this._outlineRenderer},Object.defineProperty(Yt.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(Yt.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});class qw{get shaderLanguage(){return this._shaderLanguage}constructor(e){this.name=Ut.v.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this._shaderLanguage=0,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let e=0;e<4;++e)this._passIdForDrawWrapper[e]=this._engine.createRenderPassId(`Outline Renderer (${e})`);this._engine.isWebGPU&&(this._shaderLanguage=1)}register(){this.scene._beforeRenderingMeshStage.registerStep(Ut.v.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(Ut.v.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e{f.setMatrix("world",t)})),n.setZOffset(0),n.setZOffsetUnits(0)}isReady(e,t,r){r=r??this._passIdForDrawWrapper[0];const s=[],n=[st.R.PositionKind,st.R.NormalKind],o=e.getMesh(),a=e.getMaterial();if(!a)return!1;const l=o.getScene();a.needAlphaTesting()&&(s.push("#define ALPHATEST"),o.isVerticesDataPresent(st.R.UVKind)&&(n.push(st.R.UVKind),s.push("#define UV1")),o.isVerticesDataPresent(st.R.UV2Kind)&&(n.push(st.R.UV2Kind),s.push("#define UV2"))),a.useLogarithmicDepth&&s.push("#define LOGARITHMICDEPTH"),(0,Ln.tv)(a,l,s);const h=new Tn;if(o.useBones&&o.computeBonesUsingShaders&&o.skeleton){n.push(st.R.MatricesIndicesKind),n.push(st.R.MatricesWeightsKind),o.numBoneInfluencers>4&&(n.push(st.R.MatricesIndicesExtraKind),n.push(st.R.MatricesWeightsExtraKind));const e=o.skeleton;s.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers),o.numBoneInfluencers>0&&h.addCPUSkinningFallback(0,o),e.isUsingTextureForMatrices?s.push("#define BONETEXTURE"):s.push("#define BonesPerMesh "+(e.bones.length+1))}else s.push("#define NUM_BONE_INFLUENCERS 0");const c=o.morphTargetManager;let u=0;c&&(u=c.numMaxInfluencers||c.numInfluencers,u>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+u),c.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),(0,Bt.MF)(n,o,u))),t&&(s.push("#define INSTANCES"),(0,Bt.te)(n),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES"));const d=o.bakedVertexAnimationManager;d&&d.isEnabled&&(s.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&n.push("bakedVertexAnimationSettingsInstanced"));const f=e._getDrawWrapper(r,!0),p=f.defines,_=s.join("\n");if(p!==_){const e=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","boneTextureWidth","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],t=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"];(0,Ln.TV)(e),f.setEffect(this.scene.getEngine().createEffect("outline",{attributes:n,uniformsNames:e,uniformBuffersNames:[],samplers:t,defines:_,fallbacks:h,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:u},shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,55515)),Promise.resolve().then(i.bind(i,18789))]):await Promise.all([Promise.resolve().then(i.bind(i,32192)),Promise.resolve().then(i.bind(i,65038))])}},this.scene.getEngine()),_)}return f.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){const r=t.getMaterial();r&&r.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(qw._StencilReference),this._engine.setStencilFunctionReference(qw._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),r&&r.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){const e=this._engine.getAlphaMode(),r=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(e),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))}}qw._StencilReference=4;var Yw,Kw=i(20005);class jw{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(){return!!this.vertexBuffers?.velocity}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}get shaderLanguage(){return this._shaderLanguage}constructor(e,t){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new z.cP,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._shaderLanguage=0,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null,this._shaderLanguage=t??(this._engine.isWebGPU?1:0)}_createEffects(){const e=["view","projection","particleRadius","size"],t=["position","offset"],r=[];this._effectsAreDirty=!1,this.useVelocity&&(t.push("velocity"),r.push("#define FLUIDRENDERING_VELOCITY")),this._scene.useRightHandedSystem&&r.push("#define FLUIDRENDERING_RHS"),this._depthEffectWrapper=new Yp.$({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:r,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,27014)),Promise.resolve().then(i.bind(i,40264))]):await Promise.all([Promise.resolve().then(i.bind(i,49377)),Promise.resolve().then(i.bind(i,21959))])}}),e.push("particleAlpha"),this._thicknessEffectWrapper=new Yp.$({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleThickness",fragmentShader:"fluidRenderingParticleThickness",attributeNames:["position","offset"],uniformNames:e,samplerNames:[],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,64615)),Promise.resolve().then(i.bind(i,45261))]):await Promise.all([Promise.resolve().then(i.bind(i,3420)),Promise.resolve().then(i.bind(i,28566))])}})}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||0===e)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||0===e)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(){this._depthEffectWrapper?.dispose(!1),this._thicknessEffectWrapper?.dispose(!1),this.onParticleSizeChanged.clear()}}class $w extends jw{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,i){super(e,i),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 Qw{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,null!==this._blurPostProcesses)){const e=this._blurPostProcesses[0],t=this._blurPostProcesses[1];this._blurPostProcesses=[];for(let i=0;i<2*this._blurNumIterations;++i)this._blurPostProcesses[i]=1&i?t:e}}get renderTarget(){return this._rt}get renderTargetBlur(){return this._rtBlur}get texture(){return this._texture}get textureBlur(){return this._textureBlurred}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,r,s,n,o=1,a=6,l=1,h=6,c=!1,u=null,d=!0,f=1,p){this.enableBlur=!0,this.blurSizeDivisor=1,this.blurFilterSize=7,this._blurNumIterations=3,this.blurMaxFilterSize=100,this.blurDepthScale=10,this.particleSize=.02,this.onDisposeObservable=new z.cP,this._shaderLanguage=0,this._name=e,this._scene=t,this._camera=u,this._engine=t.getEngine(),this._width=i,this._height=r,this._blurTextureSizeX=s,this._blurTextureSizeY=n,this._textureType=o,this._textureFormat=a,this._blurTextureType=l,this._blurTextureFormat=h,this._useStandardBlur=c,this._generateDepthBuffer=d,this._samples=f,this._postProcessRunningIndex=0,this.enableBlur=0!==s&&0!==n,this._rt=null,this._texture=null,this._rtBlur=null,this._textureBlurred=null,this._blurPostProcesses=null,this._shaderLanguage=p??(this._engine.isWebGPU?1:0)}initialize(){if(this.dispose(),this._createRenderTarget(),this.enableBlur&&this._texture){const[e,t,i]=this._createBlurPostProcesses(this._texture,this._blurTextureType,this._blurTextureFormat,this.blurSizeDivisor,this._name,this._useStandardBlur);this._rtBlur=e,this._textureBlurred=t,this._blurPostProcesses=i}}applyBlurPostProcesses(){this.enableBlur&&this._blurPostProcesses&&(this._postProcessRunningIndex=0,this._scene.postProcessManager.directRender(this._blurPostProcesses,this._rtBlur,!0),this._engine.unBindFramebuffer(this._rtBlur))}_createRenderTarget(){this._rt=this._engine.createRenderTargetTexture({width:this._width,height:this._height},{generateMipMaps:!1,type:this._textureType,format:this._textureFormat,samplingMode:1,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTT-${this._name}`});const e=this._rt.texture;e.incrementReferences(),this._texture=new vi.g(null,this._scene),this._texture.name="rtt"+this._name,this._texture._texture=e,this._texture.wrapU=vi.g.CLAMP_ADDRESSMODE,this._texture.wrapV=vi.g.CLAMP_ADDRESSMODE,this._texture.anisotropicFilteringLevel=1}_createBlurPostProcesses(e,t,r,s,n,o=!1){const a=this._scene.getEngine(),l=new W.I9(Math.floor(this._blurTextureSizeX/s),Math.floor(this._blurTextureSizeY/s)),h=1===t&&a.getCaps().textureFloatLinearFiltering||2===t&&a.getCaps().textureHalfFloatLinearFiltering,c=this._engine.createRenderTargetTexture({width:l.x,height:l.y},{generateMipMaps:!1,type:t,format:r,samplingMode:h?2:1,generateDepthBuffer:!1,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTTBlur-${n}`}),u=c.texture;u.incrementReferences();const d=new vi.g(null,this._scene);if(d.name="rttBlurred"+n,d._texture=u,d.wrapU=vi.g.CLAMP_ADDRESSMODE,d.wrapV=vi.g.CLAMP_ADDRESSMODE,d.anisotropicFilteringLevel=1,o){const s=new ms.w("BilateralBlurX","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,a,!0,null,t,void 0,void 0,void 0,r,this._shaderLanguage,(async()=>{1===this.shaderLanguage?await Promise.resolve().then(i.bind(i,5769)):await Promise.resolve().then(i.bind(i,53360))}));s.samples=this._samples,s.externalTextureSamplerBinding=!0,s.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",s.inputTexture.texture),t.setInt("filterSize",this.blurFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++})),s.onSizeChangedObservable.add((()=>{s._textures.forEach((e=>{e.texture.wrapU=vi.g.CLAMP_ADDRESSMODE,e.texture.wrapV=vi.g.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(s);const n=new ms.w("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,a,!0,null,t,void 0,void 0,void 0,r,this._shaderLanguage,(async()=>{1===this.shaderLanguage?await Promise.resolve().then(i.bind(i,5769)):await Promise.resolve().then(i.bind(i,53360))}));n.samples=this._samples,n.onApplyObservable.add((e=>{e.setInt("filterSize",this.blurFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++})),n.onSizeChangedObservable.add((()=>{n._textures.forEach((e=>{e.texture.wrapU=vi.g.CLAMP_ADDRESSMODE,e.texture.wrapV=vi.g.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(n),s.autoClear=!1,n.autoClear=!1;const o=[];for(let e=0;e<2*this._blurNumIterations;++e)o[e]=1&e?n:s;return[c,d,o]}{const s=["maxFilterSize","blurDir","projectedParticleConstant","depthThreshold"],n=new ms.w("BilateralBlurX","fluidRenderingBilateralBlur",s,null,1,null,1,a,!0,null,t,void 0,void 0,void 0,r,this._shaderLanguage,(async()=>{1===this.shaderLanguage?await Promise.resolve().then(i.bind(i,92862)):await Promise.resolve().then(i.bind(i,93705))}));n.samples=this._samples,n.externalTextureSamplerBinding=!0,n.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",n.inputTexture.texture),t.setInt("maxFilterSize",this.blurMaxFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),t.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),t.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++})),n.onSizeChangedObservable.add((()=>{n._textures.forEach((e=>{e.texture.wrapU=vi.g.CLAMP_ADDRESSMODE,e.texture.wrapV=vi.g.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(n);const o=new ms.w("BilateralBlurY","fluidRenderingBilateralBlur",s,null,1,null,1,a,!0,null,t,void 0,void 0,void 0,r,this._shaderLanguage,(async()=>{1===this.shaderLanguage?await Promise.resolve().then(i.bind(i,92862)):await Promise.resolve().then(i.bind(i,93705))}));o.samples=this._samples,o.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++})),o.onSizeChangedObservable.add((()=>{o._textures.forEach((e=>{e.texture.wrapU=vi.g.CLAMP_ADDRESSMODE,e.texture.wrapV=vi.g.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(o),n.autoClear=!1,o.autoClear=!1;const l=[];for(let e=0;e<2*this._blurNumIterations;++e)l[e]=1&e?o:n;return[c,d,l]}}_fixReusablePostProcess(e){e.isReusable()&&(e.onActivateObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})),e.onApplyObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})))}_getProjectedParticleConstant(){return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan((this._camera?.fov??45*Math.PI/180)/2)}_getDepthThreshold(){return this.particleSize/2*this.blurDepthScale}dispose(){this.onDisposeObservable.hasObservers()&&this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._rt?.dispose(),this._rt=null,this._texture?.dispose(),this._texture=null,this._rtBlur?.dispose(),this._rtBlur=null,this._textureBlurred?.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}!function(e){e[e.DepthTexture=0]="DepthTexture",e[e.DepthBlurredTexture=1]="DepthBlurredTexture",e[e.ThicknessTexture=2]="ThicknessTexture",e[e.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",e[e.DiffuseTexture=4]="DiffuseTexture",e[e.Normals=5]="Normals",e[e.DiffuseRendering=6]="DiffuseRendering"}(Yw||(Yw={}));class Zw{get needInitialization(){return this._needInitialization}get generateDiffuseTexture(){return this._generateDiffuseTexture}set generateDiffuseTexture(e){this._generateDiffuseTexture!==e&&(this._generateDiffuseTexture=e,this._needInitialization=!0)}get debugFeature(){return this._debugFeature}set debugFeature(e){this._debugFeature!==e&&(this._needInitialization=!0,this._debugFeature=e)}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._needInitialization=!0)}get environmentMap(){return this._environmentMap}set environmentMap(e){this._environmentMap!==e&&(this._needInitialization=!0,this._environmentMap=e)}get enableBlurDepth(){return this._enableBlurDepth}set enableBlurDepth(e){this._enableBlurDepth!==e&&(this._enableBlurDepth=e,this._needInitialization=!0)}get blurDepthSizeDivisor(){return this._blurDepthSizeDivisor}set blurDepthSizeDivisor(e){this._blurDepthSizeDivisor!==e&&(this._blurDepthSizeDivisor=e,this._needInitialization=!0)}get blurDepthFilterSize(){return this._blurDepthFilterSize}set blurDepthFilterSize(e){this._blurDepthFilterSize!==e&&(this._blurDepthFilterSize=e,this._setBlurParameters())}get blurDepthNumIterations(){return this._blurDepthNumIterations}set blurDepthNumIterations(e){this._blurDepthNumIterations!==e&&(this._blurDepthNumIterations=e,this._setBlurParameters())}get blurDepthMaxFilterSize(){return this._blurDepthMaxFilterSize}set blurDepthMaxFilterSize(e){this._blurDepthMaxFilterSize!==e&&(this._blurDepthMaxFilterSize=e,this._setBlurParameters())}get blurDepthDepthScale(){return this._blurDepthDepthScale}set blurDepthDepthScale(e){this._blurDepthDepthScale!==e&&(this._blurDepthDepthScale=e,this._setBlurParameters())}get enableBlurThickness(){return this._enableBlurThickness}set enableBlurThickness(e){this._enableBlurThickness!==e&&(this._enableBlurThickness=e,this._needInitialization=!0)}get blurThicknessSizeDivisor(){return this._blurThicknessSizeDivisor}set blurThicknessSizeDivisor(e){this._blurThicknessSizeDivisor!==e&&(this._blurThicknessSizeDivisor=e,this._needInitialization=!0)}get blurThicknessFilterSize(){return this._blurThicknessFilterSize}set blurThicknessFilterSize(e){this._blurThicknessFilterSize!==e&&(this._blurThicknessFilterSize=e,this._setBlurParameters())}get blurThicknessNumIterations(){return this._blurThicknessNumIterations}set blurThicknessNumIterations(e){this._blurThicknessNumIterations!==e&&(this._blurThicknessNumIterations=e,this._setBlurParameters())}get useFixedThickness(){return this._useFixedThickness}set useFixedThickness(e){this._useFixedThickness!==e&&(this._useFixedThickness=e,this._needInitialization=!0)}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&(this._useVelocity=e,this._needInitialization=!0,this._onUseVelocityChanged.notifyObservers(this))}get depthMapSize(){return this._depthMapSize}set depthMapSize(e){this._depthMapSize!==e&&(this._depthMapSize=e,this._needInitialization=!0)}get thicknessMapSize(){return this._thicknessMapSize}set thicknessMapSize(e){this._thicknessMapSize!==e&&(this._thicknessMapSize=e,this._needInitialization=!0)}get diffuseMapSize(){return this._diffuseMapSize}set diffuseMapSize(e){this._diffuseMapSize!==e&&(this._diffuseMapSize=e,this._needInitialization=!0)}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._needInitialization=!0)}get compositeMode(){return this._compositeMode}set compositeMode(e){this._compositeMode!==e&&(this._compositeMode=e,this._needInitialization=!0)}get camera(){return this._camera}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i){this._generateDiffuseTexture=!1,this.fluidColor=new H.v9(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new W.Pq(-2,-1,1).normalize(),this._debugFeature=1,this._debug=!1,this._enableBlurDepth=!0,this._blurDepthSizeDivisor=1,this._blurDepthFilterSize=7,this._blurDepthNumIterations=3,this._blurDepthMaxFilterSize=100,this._blurDepthDepthScale=10,this._enableBlurThickness=!0,this._blurThicknessSizeDivisor=1,this._blurThicknessFilterSize=5,this._blurThicknessNumIterations=1,this._useFixedThickness=!1,this._onUseVelocityChanged=new z.cP,this._useVelocity=!1,this._depthMapSize=null,this._thicknessMapSize=null,this._diffuseMapSize=null,this._samples=1,this._compositeMode=!1,this._shaderLanguage=0,this._scene=e,this._engine=e.getEngine(),this._camera=t??e.activeCamera,this._needInitialization=!0,this._bgDepthTexture=null,this._invProjectionMatrix=new W.uq,this._depthClearColor=new H.ov(1e6,1e6,1e6,1),this._thicknessClearColor=new H.ov(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null,this._shaderLanguage=i??(this._engine.isWebGPU?1:0)}_initialize(){this.dispose(),this._needInitialization=!1;const e=this._depthMapSize??this._engine.getRenderWidth(),t=null!==this._depthMapSize?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new Qw("Depth",this._scene,e,t,e,t,1,7,1,7,!1,this._camera,!0,this._samples,this._shaderLanguage),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){const e=this._diffuseMapSize??this._engine.getRenderWidth(),t=null!==this._diffuseMapSize?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new Qw("Diffuse",this._scene,e,t,0,0,0,5,0,5,!0,this._camera,!0,this._samples,this._shaderLanguage),this._initializeRenderTarget(this._diffuseRenderTarget)}const i=this._thicknessMapSize??this._engine.getRenderWidth(),r=null!==this._thicknessMapSize?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new Qw("Thickness",this._scene,i,r,i,r,2,6,2,6,!0,this._camera,!1,this._samples,this._shaderLanguage),this._initializeRenderTarget(this._thicknessRenderTarget)),this._createLiquidRenderingPostProcess()}_setBlurParameters(e=null){null!==e&&e!==this._depthRenderTarget||this._setBlurDepthParameters(),null!==e&&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"],r=["depthSampler"],s=[];if(this.dispose(!0),!this._camera)return;const n=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,o=new W.I9(1/n.getSize().width,1/n.getSize().height);this._scene.useRightHandedSystem&&s.push("#define FLUIDRENDERING_RHS"),null!==this._environmentMap&&(this._environmentMap??this._scene.environmentTexture)&&(r.push("reflectionSampler"),s.push("#define FLUIDRENDERING_ENVIRONMENT")),this._diffuseRenderTarget?(r.push("diffuseSampler"),s.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):t.push("diffuseColor"),this._useVelocity&&(r.push("velocitySampler"),s.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(t.push("thickness"),r.push("bgDepthSampler"),s.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(t.push("minimumThickness"),r.push("thicknessSampler")),this._compositeMode&&s.push("#define FLUIDRENDERING_COMPOSITE_MODE"),this._debug&&(s.push("#define FLUIDRENDERING_DEBUG"),5===this._debugFeature?s.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):6===this._debugFeature?s.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(s.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),r.push("debugSampler"),0!==this._debugFeature&&1!==this._debugFeature||s.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new ms.w("FluidRendering","fluidRenderingRender",t,r,1,null,2,e,!1,null,0,void 0,void 0,!0,void 0,this._shaderLanguage,(async()=>{1===this._shaderLanguage?await Promise.resolve().then(i.bind(i,37009)):await Promise.resolve().then(i.bind(i,35116))})),this._renderPostProcess.updateEffect(s.join("\n")),this._renderPostProcess.samples=this._samples;const a=e,l=a.setTextureSampler;this._renderPostProcess.onApplyObservable.add((e=>{if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),l&&l.call(a,"textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(e.setTexture("depthSampler",this._depthRenderTarget.textureBlur),l&&l.call(a,"depthSamplerSampler",this._depthRenderTarget.textureBlur?.getInternalTexture()??null)):(e.setTexture("depthSampler",this._depthRenderTarget.texture),l&&l.call(a,"depthSamplerSampler",this._depthRenderTarget.texture?.getInternalTexture()??null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(e.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),l&&l.call(a,"diffuseSamplerSampler",this._diffuseRenderTarget.textureBlur?.getInternalTexture()??null)):(e.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),l&&l.call(a,"diffuseSamplerSampler",this._diffuseRenderTarget.texture?.getInternalTexture()??null)):e.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(e.setFloat("thickness",this.minimumThickness),e._bindTexture("bgDepthSampler",this._bgDepthTexture),l&&l.call(a,"bgDepthSamplerSampler",this._bgDepthTexture??null)):(this._thicknessRenderTarget.enableBlur?(e.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),l&&l.call(a,"thicknessSamplerSampler",this._thicknessRenderTarget.textureBlur?.getInternalTexture()??null)):(e.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),l&&l.call(a,"thicknessSamplerSampler",this._thicknessRenderTarget.texture?.getInternalTexture()??null)),e.setFloat("minimumThickness",this.minimumThickness)),null!==this._environmentMap){const t=this._environmentMap??this._scene.environmentTexture;t&&(e.setTexture("reflectionSampler",t),l&&l.call(a,"reflectionSamplerSampler",t?.getInternalTexture()??null))}if(e.setMatrix("viewMatrix",this._scene.getViewMatrix()),e.setMatrix("invProjectionMatrix",this._invProjectionMatrix),e.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),e.setVector2("texelSize",o),e.setFloat("density",this.density),e.setFloat("refractionStrength",this.refractionStrength),e.setFloat("fresnelClamp",this.fresnelClamp),e.setFloat("specularPower",this.specularPower),e.setVector3("dirLight",this.dirLight),e.setFloat("cameraFar",this._camera.maxZ),this._debug){let t=null;switch(this._debugFeature){case 0:t=this._depthRenderTarget.texture;break;case 1:t=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case 2:t=this._thicknessRenderTarget?.texture??null;break;case 3:t=this._thicknessRenderTarget?.enableBlur?this._thicknessRenderTarget?.textureBlur??null:this._thicknessRenderTarget?.texture??null;break;case 4:this._diffuseRenderTarget&&(t=this._diffuseRenderTarget.texture)}5!==this._debugFeature&&(e.setTexture("debugSampler",t),l&&l.call(a,"debugSamplerSampler",t?.getInternalTexture()??null))}}))}_clearTargets(){this._depthRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),this._engine.clear(this._depthClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),this._diffuseRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),this._thicknessRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!1,!1),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget))}_render(e){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),this._depthRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),this._diffuseRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),this._thicknessRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),this._depthRenderTarget?.applyBlurPostProcesses(),this._diffuseRenderTarget?.applyBlurPostProcesses(),this._thicknessRenderTarget?.applyBlurPostProcesses(),t&&this._engine.bindFramebuffer(t)}dispose(e=!1){e||(this._depthRenderTarget?.dispose(),this._depthRenderTarget=null,this._diffuseRenderTarget?.dispose(),this._diffuseRenderTarget=null,this._thicknessRenderTarget?.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),this._renderPostProcess?.dispose(),this._renderPostProcess=null,this._onUseVelocityChanged.clear(),this._needInitialization=!1}}class Jw extends jw{getClassName(){return"FluidRenderingObjectCustomParticles"}get vertexBuffers(){return this._vertexBuffers}constructor(e,t,i,r){super(e,r),this._numParticles=i,this._diffuseEffectWrapper=null,this._vertexBuffers={},this.addBuffers(t)}addBuffers(e){for(const t in e){let i,r=!0;switch(t){case"velocity":i=3;break;case"offset":r=!1}this._vertexBuffers[t]=new st.R(this._engine,e[t],t,!0,!1,i,r)}}_createEffects(){super._createEffects(),this._diffuseEffectWrapper=new Yp.$({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:["position","offset","color"],uniformNames:["view","projection","size"],samplerNames:[],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await Promise.resolve().then(i.bind(i,89753)):await Promise.resolve().then(i.bind(i,76558))}})}isReady(){return this._vertexBuffers.offset||(this._vertexBuffers.offset=new st.R(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&(this._diffuseEffectWrapper?.effect.isReady()??!1)}get numParticles(){return this._numParticles}setNumParticles(e){this._numParticles=e}renderDiffuseTexture(){const e=this.numParticles;if(!this._diffuseEffectWrapper||0===e)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()),null!==this._particleSize&&i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}dispose(){super.dispose(),this._diffuseEffectWrapper?.dispose();for(const e in this._vertexBuffers)this._vertexBuffers[e].dispose();this._vertexBuffers={}}}class eN{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,r=1){this._engine=e,this._copyTextureToTexture=new Kp(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:r,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"}),this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil").label=`FluidDepthTextureCopy${t}x${i}x${r}`}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}}function tN(e){return!!e.particleSystem}function iN(e){return!!e.addBuffers}Object.defineProperty(oi.Z.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(e){this._fluidRenderer=e},enumerable:!0,configurable:!0}),oi.Z.prototype.enableFluidRenderer=function(){return this._fluidRenderer||(this._fluidRenderer=new sN(this)),this._fluidRenderer},oi.Z.prototype.disableFluidRenderer=function(){this._fluidRenderer?.dispose(),this._fluidRenderer=null};class rN{constructor(e){this.name=Ut.v.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(Ut.v.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(Ut.v.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)}_gatherActiveCameraRenderTargets(e){this.scene.fluidRenderer?._prepareRendering()}_afterCameraDraw(e){this.scene.fluidRenderer?._render(e)}rebuild(){const e=this.scene.fluidRenderer;if(!e)return;const t=new Set;for(let i=0;i{e._rebuild()}))}dispose(){this.scene.disableFluidRenderer()}}class sN{static _SceneComponentInitialization(e){let t=e._getComponent(Ut.v.NAME_FLUIDRENDERER);t||(t=new rN(e),e._addComponent(t))}get shaderLanguage(){return this._shaderLanguage}constructor(e){this._shaderLanguage=0,this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,sN._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add((()=>{this._initialize()})),this._engine.isWebGPU&&(this._shaderLanguage=1)}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){const t=this._getParticleSystemIndex(e);return-1!==t?this.renderObjects[t]:null}addParticleSystem(e,t,i,r){const s=new $w(this._scene,e,this._shaderLanguage);s.onParticleSizeChanged.add((()=>this._setParticleSizeForRenderTargets())),i||(i=new Zw(this._scene,r,this._shaderLanguage),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add((()=>this._setUseVelocityForRenderObject())),void 0!==t&&(i.generateDiffuseTexture=t);const n={object:s,targetRenderer:i};return this.renderObjects.push(n),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),n}addCustomParticles(e,t,i,r,s){const n=new Jw(this._scene,e,t,this._shaderLanguage);n.onParticleSizeChanged.add((()=>this._setParticleSizeForRenderTargets())),r||(r=new Zw(this._scene,s,this._shaderLanguage),this.targetRenderers.push(r)),r._onUseVelocityChanged.hasObservers()||r._onUseVelocityChanged.add((()=>this._setUseVelocityForRenderObject())),void 0!==i&&(r.generateDiffuseTexture=i);const o={object:n,targetRenderer:r};return this.renderObjects.push(o),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),o}removeRenderObject(e,t=!0){const i=this.renderObjects.indexOf(e);return-1!==i&&(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 t=0;t{s.inputTexture.depthStencilTexture||s.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,n[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${s.name}`);for(const e of n){const t=e._thicknessRenderTarget?.renderTarget,i=t?.texture;if(t&&i){const e=i.width+"_"+i.height;let r=o[e];r||(r=o[e]=new eN(this._engine,i.width,i.height)),r.depthRTWrapper.shareDepth(t)}}}))}t=this._cameras.keys();for(let i=t.next();!0!==i.done;i=t.next()){const t=i.value,r=this._cameras.get(t)[1],s=e.get(t);if(s)for(const e in r)s[1][e]||r[e].dispose();else for(const e in r)r[e].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){const e=new Map;for(let t=0;t{t._depthRenderTarget&&(t._depthRenderTarget.particleSize=e)}))}_setUseVelocityForRenderObject(){for(const e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(const e of this.targetRenderers)if(e.needInitialization)return void this._initialize()}_render(e){for(let t=0;t{const t=e[1];for(const e in t)t[e].dispose()})),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}var nN=i(49377),oN=i(21959),aN=i(3420),lN=i(28566);const hN="fluidRenderingParticleDiffuseVertexShader",cN="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;}\n";Cs.l.ShadersStore[hN]=cN;const uN={name:hN,shader:cN};var dN=i(76558),fN=i(93705),pN=i(53360),_N=i(35116),mN=i(27014),gN=i(40264),vN=i(64615),xN=i(45261);const bN="fluidRenderingParticleDiffuseVertexShader",SN="attribute position: vec3f;attribute offset: vec2f;attribute color: vec4f;uniform view: mat4x4f;uniform projection: mat4x4f;uniform size: vec2f;varying uv: vec2f;varying diffuseColor: vec3f;@vertex\nfn main(input: VertexInputs)->FragmentInputs {var cornerPos: vec3f=vec3f(\nvec2f(input.offset.x-0.5,input.offset.y-0.5)*uniforms.size,\n0.0\n);var viewPos: vec3f=(uniforms.view*vec4f(input.position,1.0)).xyz+cornerPos;vertexOutputs.position=uniforms.projection*vec4f(viewPos,1.0);vertexOutputs.uv=input.offset;vertexOutputs.diffuseColor=input.color.rgb;}\n";Cs.l.ShadersStoreWGSL[bN]=SN;const TN={name:bN,shader:SN};var CN=i(89753),yN=i(92862),EN=i(5769),PN=i(37009);class AN{get enable(){return this._enable}set enable(e){this._enable!==e&&(this._enable=e,this._customRenderTarget(e))}get positionWorldTexture(){return this._mrt.textures[0]}get normalWorldTexture(){return this._mrt.textures[1]}get fluxTexture(){return this._mrt.textures[2]}get renderList(){return this._mrt.renderList}get light(){return this._light}constructor(e,t,i={width:512,height:512}){this._lightTransformMatrix=W.uq.Identity(),this._enable=!1,this.forceUpdateLightParameters=!1,this._scene=e,this._light=t,this._textureDimensions=i,this._regularMatToMatWithPlugin=new Map,this._counters=[{name:"RSM Generation "+t.name,value:0}],this._createMultiRenderTarget(),this._recomputeLightTransformationMatrix(),this.enable=!0}setTextureDimensions(e){const t=this._mrt.renderList;this._textureDimensions=e,this._disposeMultiRenderTarget(),this._createMultiRenderTarget(),t?.forEach((e=>{this._addMeshToMRT(e)}))}addMesh(e){e?this._addMeshToMRT(e):this._scene.meshes.forEach((e=>{this._addMeshToMRT(e)})),this._recomputeLightTransformationMatrix()}updateLightParameters(){this._recomputeLightTransformationMatrix()}get lightTransformationMatrix(){return this.forceUpdateLightParameters&&this.updateLightParameters(),this._lightTransformMatrix}get countersGPU(){return this._counters}dispose(){this._disposeMultiRenderTarget()}_createMultiRenderTarget(){const e=this._light.name,t=this._scene.getEngine().getCaps(),i=t.rg11b10ufColorRenderable?13:2,r=t.rg11b10ufColorRenderable?4:5;let s,n;this._mrt=new Xb("RSMmrt_"+e,this._textureDimensions,3,this._scene,{types:[2,11,i],samplingModes:[2,2,2],generateMipMaps:!1,targetTypes:[3553,3553,3553],formats:[5,5,r]},["RSMPosition_"+e,"RSMNormal_"+e,"RSMFlux_"+e]),this._mrt.renderList=[],this._mrt.clearColor=new H.ov(0,0,0,1),this._mrt.noPrePassRenderer=!0;const o=this._scene.getEngine().supportsUniformBuffers;let a;o&&(s=this._scene.createSceneUniformBuffer(`Scene for RSM (light "${e}")`)),this._mrt.onBeforeBindObservable.add((()=>{n=this._scene.getSceneUniformBuffer(),a=this._light.shadowEnabled,this._light.shadowEnabled=!1})),this._mrt.onBeforeRenderObservable.add((e=>{s&&this._scene.setSceneUniformBuffer(s);const t=this._light.getViewMatrix(e),i=this._light.getProjectionMatrix(t||void 0,this._mrt.renderList||void 0);t&&i&&this._scene.setTransformMatrix(t,i),o&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._mrt.onAfterUnbindObservable.add((()=>{s&&this._scene.setSceneUniformBuffer(n),this._scene.updateTransformMatrix(),this._light.shadowEnabled=a,this._counters[0].value=this._mrt.renderTarget.gpuTimeInFrame?.counter.lastSecAverage??0})),this._customRenderTarget(!0)}_customRenderTarget(e){const t=this._scene.customRenderTargets.indexOf(this._mrt);e?-1===t&&this._scene.customRenderTargets.push(this._mrt):-1!==t&&this._scene.customRenderTargets.splice(t,1)}_recomputeLightTransformationMatrix(){const e=this._light.getViewMatrix(),t=this._light.getProjectionMatrix(e||void 0,this._mrt.renderList||void 0);e&&t&&e.multiplyToRef(t,this._lightTransformMatrix)}_addMeshToMRT(e){this._mrt.renderList?.push(e);const t=e.material;if(0===e.getTotalVertices()||!t)return;let i=this._regularMatToMatWithPlugin.get(t);if(!i&&(i=t.clone("RSMCreate_"+t.name)||void 0,i)){Object.defineProperty(i,"canRenderToMRT",{get:function(){return!1},enumerable:!0,configurable:!0}),i.disableLighting=!0;const e=new IN(i);e.isEnabled=!0,e.light=this._light,this._regularMatToMatWithPlugin.set(t,i)}this._mrt.setMaterialForRendering(e,i)}_disposeMultiRenderTarget(){this._customRenderTarget(!1),this._mrt.dispose()}}class RN extends xn{constructor(){super(...arguments),this.RSMCREATE=!1,this.RSMCREATE_PROJTEXTURE=!1,this.RSMCREATE_LIGHT_IS_SPOT=!1}}class IN extends Dn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e){super(e,IN.Name,300,new RN),this._lightColor=new H.v9,this._hasProjectionTexture=!1,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._varAlbedoName=e instanceof Gm?"surfaceAlbedo":"baseColor.rgb"}prepareDefines(e){e.RSMCREATE=this._isEnabled,this._hasProjectionTexture=!1;const t=this.light.getTypeID()===$t.LIGHTTYPEID_SPOTLIGHT;if(t){const e=this.light;this._hasProjectionTexture=!!e.projectionTexture&&e.projectionTexture.isReady()}e.RSMCREATE_PROJTEXTURE=this._hasProjectionTexture,e.RSMCREATE_LIGHT_IS_SPOT=t,e.SCENE_MRT_COUNT=3}getClassName(){return"RSMCreatePluginMaterial"}getUniforms(){return{ubo:[{name:"rsmTextureProjectionMatrix",size:16,type:"mat4"},{name:"rsmSpotInfo",size:4,type:"vec4"},{name:"rsmLightColor",size:3,type:"vec3"},{name:"rsmLightPosition",size:3,type:"vec3"}],fragment:"#ifdef RSMCREATE\n uniform mat4 rsmTextureProjectionMatrix;\n uniform vec4 rsmSpotInfo;\n uniform vec3 rsmLightColor;\n uniform vec3 rsmLightPosition;\n #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()===$t.LIGHTTYPEID_SPOTLIGHT)){const t=this.light;this._hasProjectionTexture&&(e.updateMatrix("rsmTextureProjectionMatrix",t.projectionTextureMatrix),e.setTexture("rsmTextureProjectionSampler",t.projectionTexture));const i=W.AA.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(.5*t.angle))}}getCustomCode(e,t){return"vertex"===e?null:1===t?{CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RSMCREATE\n #ifdef RSMCREATE_PROJTEXTURE\n var rsmTextureProjectionSamplerSampler: sampler;\n var rsmTextureProjectionSampler: texture_2d;\n #endif\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:`\n #ifdef RSMCREATE\n var rsmColor = ${this._varAlbedoName} * uniforms.rsmLightColor;\n #ifdef RSMCREATE_PROJTEXTURE\n {\n var strq = uniforms.rsmTextureProjectionMatrix * vec4f(fragmentInputs.vPositionW, 1.0);\n strq /= strq.w;\n rsmColor *= textureSample(rsmTextureProjectionSampler, rsmTextureProjectionSamplerSampler, strq.xy).rgb;\n }\n #endif\n #ifdef RSMCREATE_LIGHT_IS_SPOT\n {\n var cosAngle = max(0., dot(uniforms.rsmSpotInfo.xyz, normalize(fragmentInputs.vPositionW - uniforms.rsmLightPosition)));\n rsmColor = sign(cosAngle - uniforms.rsmSpotInfo.w) * rsmColor;\n }\n #endif\n\n #define MRT_AND_COLOR\n fragmentOutputs.fragData0 = vec4f(fragmentInputs.vPositionW, 1.);\n fragmentOutputs.fragData1 = vec4f(normalize(normalW) * 0.5 + 0.5, 1.);\n fragmentOutputs.fragData2 = vec4f(rsmColor, 1.);\n #endif\n `}:{CUSTOM_FRAGMENT_BEGIN:"\n #ifdef RSMCREATE\n #extension GL_EXT_draw_buffers : require\n #endif\n ",CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RSMCREATE\n #ifdef RSMCREATE_PROJTEXTURE\n uniform highp sampler2D rsmTextureProjectionSampler; \n #endif\n layout(location = 0) out highp vec4 glFragData[3];\n vec4 glFragColor;\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:`\n #ifdef RSMCREATE\n vec3 rsmColor = ${this._varAlbedoName} * rsmLightColor;\n #ifdef RSMCREATE_PROJTEXTURE\n {\n vec4 strq = rsmTextureProjectionMatrix * vec4(vPositionW, 1.0);\n strq /= strq.w;\n rsmColor *= texture2D(rsmTextureProjectionSampler, strq.xy).rgb;\n }\n #endif\n #ifdef RSMCREATE_LIGHT_IS_SPOT\n {\n float cosAngle = max(0., dot(rsmSpotInfo.xyz, normalize(vPositionW - rsmLightPosition)));\n rsmColor = sign(cosAngle - rsmSpotInfo.w) * rsmColor;\n }\n #endif\n glFragData[0] = vec4(vPositionW, 1.);\n glFragData[1] = vec4(normalize(normalW) * 0.5 + 0.5, 1.);\n glFragData[2] = vec4(rsmColor, 1.);\n #endif\n `}}}IN.Name="RSMCreate",(0,je.Cg)([(0,$e.lK)()],IN.prototype,"light",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],IN.prototype,"isEnabled",void 0),(0,X.Y5)("BABYLON.RSMCreatePluginMaterial",IN);class MN{constructor(e){this.numSamples=400,this.radius=.1,this.intensity=.1,this.edgeArtifactCorrection=.1,this.rotateSample=!0,this.noiseFactor=100,this.useFullTexture=!1,this.rsm=e}dispose(){this.rsm.dispose()}}class ON{get enable(){return this._enable}set enable(e){0===this._giRSM.length&&(e=!1),e!==this._enable&&(this._enable=e,this._debugLayer.isEnabled=this._showOnlyGI&&e,this._materialsWithRenderPlugin.forEach((t=>{t.pluginManager&&(t.pluginManager.getPlugin(wN.Name).isEnabled=e)})),this.recreateResources(!e))}get enableBlur(){return this._enableBlur}set enableBlur(e){e!==this._enableBlur&&(this._enableBlur=e,this.recreateResources())}get useQualityBlur(){return this._useQualityBlur}set useQualityBlur(e){e!==this._useQualityBlur&&(this._useQualityBlur=e,this.recreateResources())}get fullSizeBlur(){return this._forceFullSizeBlur}set fullSizeBlur(e){this._forceFullSizeBlur!==e&&(this._forceFullSizeBlur=e,this.recreateResources())}get useQualityUpsampling(){return this._useQualityUpsampling}set useQualityUpsampling(e){e!==this._useQualityUpsampling&&(this._useQualityUpsampling=e,this.recreateResources())}get showOnlyGI(){return this._showOnlyGI}set showOnlyGI(e){this._showOnlyGI!==e&&(this._showOnlyGI=e,this._debugLayer.isEnabled=e)}get use32BitsDepthBuffer(){return this._use32BitsDepthBuffer}set use32BitsDepthBuffer(e){this._use32BitsDepthBuffer!==e&&(this._use32BitsDepthBuffer=e,this.recreateResources())}setOutputDimensions(e){this._outputDimensions=e,this.recreateResources()}setGITextureDimensions(e){this._giTextureDimensions=e,this.recreateResources()}get giTextureType(){return this._giTextureType}set giTextureType(e){this._giTextureType!==e&&(this._giTextureType=e,this.recreateResources())}get shaderLanguage(){return this._shaderLanguage}get giRSM(){return this._giRSM}addGIRSM(e){Array.isArray(e)?this._giRSM.push(...e):this._giRSM.push(e),this.recreateResources()}removeGIRSM(e){if(Array.isArray(e))for(let t=0;t{e.getTotalVertices()>0&&e.isEnabled()&&e.material&&this._addGISupportToMaterial(e.material)}))}get countersGPU(){return this._counters}recreateResources(e=!1){this._shadersLoaded?(this._disposePostProcesses(e),this._createPostProcesses(),this._setPluginParameters()):this._onShaderLoadedObservable.addOnce((()=>{this.recreateResources(e)}))}generateSampleTexture(e){this._sampleTexture?.dispose(),this._maxSamples=e;const t=new Float32Array(4*this._maxSamples);for(let e=0;e{const e=this._engine._currentRenderTarget;let t=!1;if(this._enable){this.pause||(this._scene.postProcessManager.directRender(this._ppGlobalIllumination,this._ppGlobalIllumination[0].inputTexture),this._engine.unBindFramebuffer(this._ppGlobalIllumination[0].inputTexture,!0),this._engine.setAlphaMode(0),t=!0,this.enableBlur&&this._blurPostProcesses&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,this._blurRTT.renderTarget,!0),this._engine.unBindFramebuffer(this._blurRTT.renderTarget,!0)));for(let e=0;e{if(e.pluginManager){const t=e.pluginManager.getPlugin(wN.Name);t.textureGIContrib=this.enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture,t.outputTextureWidth=this._outputDimensions.width,t.outputTextureHeight=this._outputDimensions.height}}))}_createPostProcesses(){if(!this._enable)return;const e=13===this._giTextureType?4:5;this._firstActivation&&(this._firstActivation=!1,this._geomBufferEnabled=!!this._scene.geometryBufferRenderer,this._geomBufferEnablePosition=this._scene.geometryBufferRenderer?.enablePosition??!1),this._geomBufferEnabled||this._scene.disableGeometryBufferRenderer();const t=this._scene.enableGeometryBufferRenderer(this._enableBlur?this._outputDimensions:this._giTextureDimensions,this._use32BitsDepthBuffer?14:15,ON.GeometryBufferTextureTypesAndFormats);if(!t)throw new Error("Geometry buffer renderer is not supported but is required for GIRSMManager.");t.enablePosition=!0,this._geomBufferEnabled||(t.generateNormalsInWorldSpace=!0);const i=t.normalsAreUnsigned,r=t.generateNormalsInWorldSpace;this._counters.push({name:"Geometry buffer renderer",value:0}),this._countersRTW.push([this._scene.geometryBufferRenderer.getGBuffer().renderTarget]);let s="";i&&(s+="#define DECODE_NORMAL\n"),r||(s+="#define TRANSFORM_NORMAL\n");for(let i=0;i{e.setTexture("textureSampler",t.getGBuffer().textures[t.getTextureIndex(qO.POSITION_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(qO.NORMAL_TEXTURE_TYPE)]),e.setTexture("rsmPositionW",o.positionWorldTexture),e.setTexture("rsmNormalW",o.normalWorldTexture),e.setTexture("rsmFlux",o.fluxTexture),e.setMatrix("rsmLightMatrix",o.lightTransformationMatrix),n.useFullTexture?e.setFloat4("rsmInfo",o.fluxTexture.getInternalTexture().width,o.fluxTexture.getInternalTexture().height,n.intensity,n.edgeArtifactCorrection):(e.setTexture("rsmSamples",this._sampleTexture),e.setFloat4("rsmInfo",n.numSamples,n.radius,n.intensity,n.edgeArtifactCorrection),e.setFloat4("rsmInfo2",n.noiseFactor,n.rotateSample?1:0,o.fluxTexture.getInternalTexture().width,o.fluxTexture.getInternalTexture().height)),r||(this._tempMatrix.copyFrom(this._scene.activeCamera.getViewMatrix()),this._tempMatrix.invert(),e.setMatrix("invView",this._tempMatrix))}))}for(const e of this._ppGlobalIllumination)e.inputTexture||e.resize(this._giTextureDimensions.width,this._giTextureDimensions.height);if(this._counters.push({name:"GI generation",value:0}),this._countersRTW.push([this._ppGlobalIllumination[0].inputTexture]),this._enableBlur){const r=this._forceFullSizeBlur?this._outputDimensions:this._giTextureDimensions;this._blurRTT=new ln.$("GIRSMContribution",this._outputDimensions,this._scene,{type:this._giTextureType,format:e,generateDepthBuffer:!1}),this._blurRTT.wrapU=0,this._blurRTT.wrapV=0,this._blurRTT.updateSamplingMode(1),this._blurRTT.skipInitialClear=!0;const s=[];if(this._counters.push({name:"GI blur",value:0}),this._countersRTW.push(s),this._blurXPostprocess=new ms.w(this._useQualityBlur?"BilateralBlur":"BilateralBlurX",this._useQualityBlur?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:r,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e,shaderLanguage:this._shaderLanguage}),this._blurXPostprocess.onApplyObservable.add((e=>{e._bindTexture("textureSampler",this._ppGlobalIllumination[0].inputTexture.texture),e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(qO.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(qO.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.blurKernel),e.setFloat2("blurDir",1/this._giTextureDimensions.width,this._useQualityBlur?1/this._giTextureDimensions.height:0),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._blurXPostprocess.externalTextureSamplerBinding=!0,this._blurXPostprocess.autoClear=!1,this._useQualityBlur||(this._blurYPostprocess=new ms.w("BilateralBlurY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:r,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e,shaderLanguage:this._shaderLanguage}),this._blurYPostprocess.autoClear=!1,this._blurYPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(qO.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(qO.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.blurKernel),e.setFloat2("blurDir",0,1/this._giTextureDimensions.height),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._blurYPostprocess.resize(r.width,r.height),s.push(this._blurYPostprocess.inputTexture)),this._blurPostProcesses=[this._blurXPostprocess],this._blurYPostprocess&&this._blurPostProcesses.push(this._blurYPostprocess),this._giTextureDimensions.width>=this._outputDimensions.width&&this._giTextureDimensions.height>=this._outputDimensions.height||this._forceFullSizeBlur)s.push(this._blurRTT.renderTarget);else{const n=[];this._counters.push({name:"GI upsampling",value:0}),this._countersRTW.push(n),this._upsamplingXPostprocess=new ms.w(this._useQualityUpsampling?"BilateralUpsampling":"BilateralUpsamplingX",this._useQualityUpsampling?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:r,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e,shaderLanguage:this._shaderLanguage}),this._upsamplingXPostprocess.autoClear=!1,this._upsamplingXPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(qO.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(qO.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.upsamplerKernel),e.setFloat2("blurDir",1/this._outputDimensions.width,this._useQualityUpsampling?1/this._outputDimensions.height:0),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._upsamplingXPostprocess.resize(r.width,r.height),s.push(this._upsamplingXPostprocess.inputTexture),this.useQualityUpsampling||(this._upsamplingYPostprocess=new ms.w("BilateralUpsamplingY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:this._outputDimensions,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e,shaderLanguage:this._shaderLanguage}),this._upsamplingYPostprocess.autoClear=!1,this._upsamplingYPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(qO.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(qO.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.upsamplerKernel),e.setFloat2("blurDir",0,1/this._outputDimensions.height),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._upsamplingYPostprocess.resize(this._outputDimensions.width,this._outputDimensions.height),n.push(this._upsamplingYPostprocess.inputTexture)),n.push(this._blurRTT.renderTarget),this._blurPostProcesses.push(this._upsamplingXPostprocess),this._upsamplingYPostprocess&&this._blurPostProcesses.push(this._upsamplingYPostprocess)}}this._debugLayer.texture?.dispose(),this._debugLayer.texture=new js.t(this._scene,this._enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture)}_addGISupportToMaterial(e){if(e.pluginManager?.getPlugin(wN.Name))return;const t=new wN(e);this._enable&&this._ppGlobalIllumination.length>0&&(t.textureGIContrib=this._ppGlobalIllumination[0].inputTexture.texture,t.outputTextureWidth=this._outputDimensions.width,t.outputTextureHeight=this._outputDimensions.height),t.isEnabled=this._enable,this._materialsWithRenderPlugin.push(e)}}ON.GeometryBufferTextureTypesAndFormats={0:{textureType:2,textureFormat:6},1:{textureType:11,textureFormat:5},2:{textureType:2,textureFormat:5}};class DN extends xn{constructor(){super(...arguments),this.RENDER_WITH_GIRSM=!1,this.RSMCREATE_PROJTEXTURE=!1}}class wN extends Dn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e){super(e,wN.Name,310,new DN),this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._isPBR=e instanceof Gm}prepareDefines(e){e.RENDER_WITH_GIRSM=this._isEnabled}getClassName(){return"GIRSMRenderPluginMaterial"}getUniforms(){return{ubo:[{name:"girsmTextureOutputSize",size:2,type:"vec2"}],fragment:"#ifdef RENDER_WITH_GIRSM\n uniform vec2 girsmTextureOutputSize;\n #endif"}}getSamplers(e){e.push("girsmTextureGIContrib")}bindForSubMesh(e){this._isEnabled&&(e.bindTexture("girsmTextureGIContrib",this.textureGIContrib),e.updateFloat2("girsmTextureOutputSize",this.outputTextureWidth,this.outputTextureHeight))}getCustomCode(e,t){let i;return 1===t?(i={CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RENDER_WITH_GIRSM\n var girsmTextureGIContribSampler: sampler;\n var girsmTextureGIContrib: texture_2d;\n\n fn computeIndirect() -> vec3f {\n var uv = fragmentInputs.position.xy / uniforms.girsmTextureOutputSize;\n return textureSample(girsmTextureGIContrib, girsmTextureGIContribSampler, uv).rgb;\n }\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:"\n #ifdef RENDER_WITH_GIRSM\n finalDiffuse += computeIndirect() * surfaceAlbedo.rgb;\n #endif\n "},this._isPBR||(i.CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR="\n #ifdef RENDER_WITH_GIRSM\n color = vec4f(color.rgb + computeIndirect() * baseColor.rgb, color.a);\n #endif\n ")):(i={CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RENDER_WITH_GIRSM\n uniform sampler2D girsmTextureGIContrib;\n\n vec3 computeIndirect() {\n vec2 uv = gl_FragCoord.xy / girsmTextureOutputSize;\n return texture2D(girsmTextureGIContrib, uv).rgb;\n }\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:"\n #ifdef RENDER_WITH_GIRSM\n finalDiffuse += computeIndirect() * surfaceAlbedo.rgb;\n #endif\n "},this._isPBR||(i.CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR="\n #ifdef RENDER_WITH_GIRSM\n color.rgb += computeIndirect() * baseColor.rgb;\n #endif\n ")),"vertex"===e?null:i}}wN.Name="GIRSMRender",(0,je.Cg)([(0,$e.lK)()],wN.prototype,"textureGIContrib",void 0),(0,je.Cg)([(0,$e.lK)()],wN.prototype,"outputTextureWidth",void 0),(0,je.Cg)([(0,$e.lK)()],wN.prototype,"outputTextureHeight",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],wN.prototype,"isEnabled",void 0),(0,X.Y5)("BABYLON.GIRSMRenderPluginMaterial",wN);var NN=i(41341),FN=i(47318),LN=i(58500),BN=i(69319),VN=i(84910),kN=i(46563),UN=i(31583),GN=i(91944),zN=i(66246),WN=i(61420),HN=i(55745),XN=i(20267),qN=i(16400),YN=i(81473),KN=i(83063),jN=i(10737),$N=i(85550),QN=i(42644),ZN=i(27127),JN=i(7217),eF=i(32192),tF=i(65038),iF=i(55515),rF=i(18789),sF=i(76978),nF=i(4357),oF=i(74747),aF=i(35680),lF=i(73588),hF=i(65461),cF=i(45647),uF=i(80018),dF=i(41115),fF=i(17864);const pF="iblShadowsCombinePixelShader",_F="precision highp float;varying vec2 vUV;uniform sampler2D shadowSampler;uniform sampler2D textureSampler;uniform float shadowOpacity;void main(void)\n{vec3 shadow=texture(shadowSampler,vUV).rgb;vec3 sceneColor=texture(textureSampler,vUV).rgb;float shadowValue=mix(1.0,shadow.x,shadowOpacity);gl_FragColor=vec4(sceneColor*shadowValue,1.0);}";Cs.l.ShadersStore[pF]=_F;const mF={name:pF,shader:_F},gF="iblShadowsCombinePixelShader",vF="varying vUV: vec2f;var shadowSamplerSampler : sampler;var shadowSampler : texture_2d;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform shadowOpacity: f32;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var shadow\n: vec3f =\ntextureSample(shadowSampler,shadowSamplerSampler,input.vUV).rgb;var color\n: vec3f =\ntextureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var shadowValue: f32=mix(1.0,shadow.x,uniforms.shadowOpacity);fragmentOutputs.color=vec4f(color*shadowValue,1.0);}";Cs.l.ShadersStoreWGSL[gF]=vF;const xF={name:gF,shader:vF};var bF=i(48016),SF=i(17897),TF=i(99638),CF=i(88789),yF=i(64367),EF=i(23008),PF=i(43572),AF=i(47473),RF=i(85917),IF=i(98824),MF=i(38957),OF=i(8970),DF=i(27844),wF=i(7683),NF=i(78685),FF=i(87382),LF=i(68859),BF=i(7426),VF=i(83145),kF=i(19395),UF=i(75904),GF=i(79214),zF=i(95171),WF=i(20008),HF=i(71650),XF=i(81284),qF=i(94369),YF=i(16615),KF=i(17738),jF=i(4172),$F=i(29551),QF=i(21937);Cs.l.ShadersStore.spriteMapPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nprecision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;\n#include\n#include\nfloat mt;const float fdStep=1.0*0.25;const float aFrameSteps=MAX_ANIMATION_FRAMES==0.0 ? 0.0 : 1.0/MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID) {float fX=frameID/spriteCount;return mat4(\nTEXTUREFUNC(frameMap,vec2(fX,0.0),0.0),\nTEXTUREFUNC(frameMap,vec2(fX,fdStep*1.0),0.0),\nTEXTUREFUNC(frameMap,vec2(fX,fdStep*2.0),0.0),\nvec4(0.0)\n);}\nvoid main() {vec4 color=vec4(0.0);vec2 tileUV=fract(tUV);vec2 tileID=floor(tUV);vec2 sheetUnits=1.0/spriteMapSize;float spriteUnits=1.0/spriteCount;vec2 stageUnits=1.0/stageSize;for(int i=0; i0.0) {mt=mod(time*animationData.z,1.0);for(float f=0.0; fmt) {frameID=animationData.x;break;}\nanimationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.0);}}\nmat4 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;\n#ifdef FR_CW\nif (frameData[2].z==1.0) {tileUV.xy=tileUV.yx;} else {tileUV.xy=fract(tUV).xy;}\n#ifdef FLIPU\ntileUV.y=1.0-tileUV.y;\n#endif\n#else\nif (frameData[2].z==1.0) {\n#ifdef FLIPU\ntileUV.y=1.0-tileUV.y;\n#endif\ntileUV.xy=tileUV.yx;} else {tileUV.xy=fract(tUV).xy;\n#ifdef FLIPU\ntileUV.y=1.0-tileUV.y;\n#endif\n}\n#endif\nvec4 nc=TEXTUREFUNC(spriteSheet,tileUV*frameSize+offset,0.0);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);}}\ncolor.xyz*=colorMul;\n#include\n#include\ngl_FragColor=color;}";var ZF;Cs.l.ShadersStore.spriteMapVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform mat4 world;uniform mat4 view;uniform mat4 projection;uniform vec2 stageSize;uniform float stageScale;\n#include\n#include\nvoid main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; \nvec3 viewPos=(view*world*p).xyz; \ngl_Position=projection*vec4(viewPos,1.0); \n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n#include\n}",function(e){e[e.CCW=0]="CCW",e[e.CW=1]="CW"}(ZF||(ZF={}));class JF{get spriteCount(){return this.sprites.length}get position(){return this._output.position}set position(e){this._output.position=e}get rotation(){return this._output.rotation}set rotation(e){this._output.rotation=e}get animationMap(){return this._animationMap}set animationMap(e){const t=e._texture._bufferView,i=this._createTileAnimationBuffer(t);this._animationMap.dispose(),this._animationMap=i,this._material.setTexture("animationMap",this._animationMap)}get fogEnabled(){return this._material.fogEnabled}set fogEnabled(e){this._material.fogEnabled=e}get useLogarithmicDepth(){return this._material.useLogarithmicDepth}set useLogarithmicDepth(e){this._material.useLogarithmicDepth=e}constructor(e,t,i,r,s){this.name=e,this.sprites=[],this.atlasJSON=t,this.sprites=this.atlasJSON.frames,this.spriteSheet=i,this.options=r,r.stageSize=r.stageSize||new W.I9(1,1),r.outputSize=r.outputSize||r.stageSize,r.outputPosition=r.outputPosition||W.Pq.Zero(),r.outputRotation=r.outputRotation||W.Pq.Zero(),r.layerCount=r.layerCount||1,r.maxAnimationFrames=r.maxAnimationFrames||0,r.baseTile=r.baseTile||0,r.flipU=r.flipU||!1,r.colorMultiply=r.colorMultiply||new W.Pq(1,1,1),this._scene=s,this._frameMap=this._createFrameBuffer(),this._tileMaps=new Array;for(let e=0;e{this.spriteSheet&&this.spriteSheet.isReady()&&this.spriteSheet._texture?this._material.setVector2("spriteMapSize",new W.I9(this.spriteSheet._texture.baseWidth||1,this.spriteSheet._texture.baseHeight||1)):l<100&&setTimeout((()=>{l++,h()}),100)};h(),this._material.setVector3("colorMul",r.colorMultiply),this._material.setTexture("frameMap",this._frameMap),this._material.setTextureArray("tileMaps",this._tileMaps),this._material.setTexture("animationMap",this._animationMap),this._material.setFloat("time",this._time),this._output=Qi(e+":output",{size:1,updatable:!0},s),this._output.scaling.x=r.outputSize.x,this._output.scaling.y=r.outputSize.y,this.position=r.outputPosition,this.rotation=r.outputRotation,this._scene.onBeforeRenderObservable.add((()=>{this._time+=this._scene.getEngine().getDeltaTime(),this._material.setFloat("time",this._time)})),this._output.material=this._material}getTileIdxByName(e){return this.atlasJSON.frames.findIndex((t=>t.filename===e))}getTileID(){const e=this.getMousePosition();return e.multiplyInPlace(this.options.stageSize||W.I9.Zero()),e.x=Math.floor(e.x),e.y=Math.floor(e.y),e}getMousePosition(){const e=this._output,t=this._scene.pick(this._scene.pointerX,this._scene.pointerY,(t=>t===e));if(!t||!t.hit||!t.getTextureCoordinates)return new W.I9(-1,-1);return t.getTextureCoordinates()||new W.I9(-1,-1)}_createFrameBuffer(){const e=[];for(let t=0;t0&&(e+="\n\r"),e+=this._tileMaps[t]._texture._bufferView.toString();const t=document.createElement("a");t.href="data:octet/stream;charset=utf-8,"+encodeURI(e),t.target="_blank",t.download=this.name+".tilemaps",t.click(),t.remove()}loadTileMaps(e){const t=new XMLHttpRequest;t.open("GET",e);const i=this.options.layerCount||0;t.onload=()=>{const e=t.response.split("\n\r");for(let t=0;t{e.dispose()})),this._frameMap.dispose()}}class eL extends Jx{constructor(e,t,i,r,s=null,n=.01,o=vi.g.TRILINEAR_SAMPLINGMODE,a){super(e,t,i,64,r,n,o,!0,s,a),this.name=e}}var tL,iL,rL=i(3916),sL=i(3290),nL=i(25151),oL=i(56029),aL=i(94895),lL=i(69905);!function(e){e[e.ENTERING_XR=0]="ENTERING_XR",e[e.EXITING_XR=1]="EXITING_XR",e[e.IN_XR=2]="IN_XR",e[e.NOT_IN_XR=3]="NOT_IN_XR"}(tL||(tL={})),function(e){e[e.NOT_TRACKING=0]="NOT_TRACKING",e[e.TRACKING_LOST=1]="TRACKING_LOST",e[e.TRACKING=2]="TRACKING"}(iL||(iL={}));class hL extends Ig{constructor(e,t={}){super(e),this.options=t,this._direction=new W.Pq(0,0,-1),this._mat=new W.uq,this._onSelectEnabled=!1,this._origin=new W.Pq(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new z.cP,this._onHitTestResults=e=>{const t=e.map((e=>{const t=W.uq.FromArray(e.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||t.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&t.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),t),{xrHitResult:e,transformationMatrix:t}}));this.lastNativeXRHitResults=e,this.onHitTestResultObservable.notifyObservers(t)},this._onSelect=e=>{this._onSelectEnabled&&hL.XRHitTestWithSelectEvent(e,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",Ue.S0.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,r){return e.requestHitTest(t,i).then((e=>{const t=r||(e=>!!e.hitMatrix);return e.filter(t)}))}static XRHitTestWithSelectEvent(e,t){const i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);const r=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,r,t)}attach(){return!!super.attach()&&(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)}detach(){return!!super.detach()&&(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)}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;W.uq.FromArrayToRef(t.transform.matrix,0,this._mat),W.Pq.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),W.Pq.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});hL.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}hL.Name=hr.HIT_TEST,hL.Version=1,cr.AddWebXRFeature(hL.Name,((e,t)=>()=>new hL(e,t)),hL.Version,!1);let cL=0;class uL extends Ig{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 z.cP,this.onAnchorRemovedObservable=new z.cP,this.onAnchorUpdatedObservable=new z.cP,this._tmpVector=new W.Pq,this._tmpQuaternion=new W.PT,this.xrNativeFeatureName="anchors",this._options.clearAnchorsOnSessionInit&&this._xrSessionManager.onXRSessionInit.add((()=>{this._trackedAnchors.length=0,this._futureAnchors.length=0,this._lastFrameDetected.clear()}))}_populateTmpTransformation(e,t){return this._tmpVector.copyFrom(e),this._tmpQuaternion.copyFrom(t),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpVector.z*=-1,this._tmpQuaternion.z*=-1,this._tmpQuaternion.w*=-1),{position:this._tmpVector,rotationQuaternion:this._tmpQuaternion}}async addAnchorPointUsingHitTestResultAsync(e,t=new W.Pq,i=new W.PT){this._populateTmpTransformation(t,i);const r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w});if(!e.xrHitResult.createAnchor)throw this.detach(),new Error("Anchors not enabled in this environment/browser");try{const t=await e.xrHitResult.createAnchor(r);return new Promise(((e,i)=>{this._futureAnchors.push({nativeAnchor:t,resolved:!1,submitted:!0,xrTransformation:r,resolve:e,reject:i})}))}catch(e){throw new Error(e)}}async addAnchorAtPositionAndRotationAsync(e,t=new W.PT,i=!1){this._populateTmpTransformation(e,t);const r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),s=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(r,this._xrSessionManager.currentFrame):void 0;return new Promise(((e,t)=>{this._futureAnchors.push({nativeAnchor:s,resolved:!1,submitted:!1,xrTransformation:r,resolve:e,reject:t})}))}get anchors(){return this._trackedAnchors}detach(){if(!super.detach())return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){const e=this._trackedAnchors.pop();e&&this.onAnchorRemovedObservable.notifyObservers(e)}return!0}dispose(){this._futureAnchors.length=0,super.dispose(),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()}_onXRFrame(e){if(!this.attached||!e)return;const t=e.trackedAnchors;if(t){const i=this._trackedAnchors.filter((e=>!t.has(e.xrAnchor))).map((e=>this._trackedAnchors.indexOf(e)));let r=0;i.forEach((e=>{const t=this._trackedAnchors.splice(e-r,1)[0];this.onAnchorRemovedObservable.notifyObservers(t),r++})),t.forEach((t=>{if(this._lastFrameDetected.has(t)){const i=this._findIndexInAnchorArray(t),r=this._trackedAnchors[i];try{this._updateAnchorWithXRFrame(t,r,e),r.attachedNode&&(r.attachedNode.rotationQuaternion=r.attachedNode.rotationQuaternion||new W.PT,r.transformationMatrix.decompose(r.attachedNode.scaling,r.attachedNode.rotationQuaternion,r.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(r)}catch(e){Ue.S0.Warn("Anchor could not be updated")}}else{const i={id:cL++,xrAnchor:t,remove:()=>t.delete()},r=this._updateAnchorWithXRFrame(t,i,e);this._trackedAnchors.push(r),this.onAnchorAddedObservable.notifyObservers(r);const s=this._futureAnchors.filter((e=>e.nativeAnchor===t))[0];s&&(s.resolve(r),s.resolved=!0)}})),this._lastFrameDetected=t}this._futureAnchors.forEach((t=>{t.resolved||t.submitted||(this._createAnchorAtTransformation(t.xrTransformation,e).then((e=>{t.nativeAnchor=e}),(e=>{t.resolved=!0,t.reject(e)})),t.submitted=!0)}))}_findIndexInAnchorArray(e){for(let t=0;t()=>new uL(e,t)),uL.Version);let dL=0;class fL extends Ig{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new z.cP,this.onPlaneRemovedObservable=new z.cP,this.onPlaneUpdatedObservable=new z.cP,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"undefined"!=typeof XRPlane}async initiateRoomCapture(){return this._xrSessionManager.session.initiateRoomCapture?this._xrSessionManager.session.initiateRoomCapture():Promise.reject("initiateRoomCapture is not supported on this session")}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;const t=e.detectedPlanes||e.worldInformation?.detectedPlanes;if(t){for(let e=0;e{if(this._lastFrameDetected.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._findIndexInPlaneArray(t),r=this._detectedPlanes[i];this._updatePlaneWithXRPlane(t,r,e),this.onPlaneUpdatedObservable.notifyObservers(r)}}else{const i={id:dL++,xrPlane:t,polygonDefinition:[]},r=this._updatePlaneWithXRPlane(t,i,e);this._detectedPlanes.push(r),this.onPlaneAddedObservable.notifyObservers(r)}})),this._lastFrameDetected=t}}_init(){const e=()=>{this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes.length=0)};this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),this._xrSessionManager.session.updateWorldTrackingState?(this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),e()):e()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map((e=>{const t=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new W.Pq(e.x,e.y,e.z*t)}));const r=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(r){const e=t.transformationMatrix||new W.uq;W.uq.FromArrayToRef(r.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}_findIndexInPlaneArray(e){for(let t=0;t()=>new fL(e,t)),fL.Version);class pL extends Ig{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new z.cP}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((t=>t.setEnabled(e))),this.onBackgroundStateChangedObservable.notifyObservers(e)}}pL.Name=hr.BACKGROUND_REMOVER,pL.Version=1,cr.AddWebXRFeature(pL.Name,((e,t)=>()=>new pL(e,t)),pL.Version,!0);class _L{}class mL extends Ig{_createPhysicsImpostor(e){const t=this._options.physicsProperties.impostorType||sa.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,r=Qo("impostor-mesh-"+e.uniqueId,{diameterX:"number"==typeof i?i:i.width,diameterY:"number"==typeof i?i:i.height,diameterZ:"number"==typeof i?i:i.depth});r.isVisible=this._debugMode,r.isPickable=!1,r.rotationQuaternion=new W.PT;const s=e.grip||e.pointer;r.position.copyFrom(s.position),r.rotationQuaternion.copyFrom(s.rotationQuaternion);const n=new sa(r,t,{mass:0,...this._options.physicsProperties});this._controllers[e.uniqueId]={xrController:e,impostor:n,impostorMesh:r}}constructor(e,t){super(e),this._options=t,this._attachController=e=>{this._controllers[e.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||Z.V.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&e.inputSource.gamepad?e.onMotionControllerInitObservable.addOnce((t=>{t._doNotLoadControllerMesh?this._createPhysicsImpostor(e):t.onModelLoadedObservable.addOnce((()=>{const i=new sa(t.rootMesh,sa.MeshImpostor,{mass:0,...this._options.physicsProperties}),r=e.grip||e.pointer;this._controllers[e.uniqueId]={xrController:e,impostor:i,oldPos:r.position.clone(),oldRotation:r.rotationQuaternion.clone()}}))})):this._createPhysicsImpostor(e))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new W.PT,this._tmpVector=new W.Pq,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:sa.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=Qo("headset-mesh",{diameterX:"number"==typeof t?t:t.width,diameterY:"number"==typeof t?t:t.height,diameterZ:"number"==typeof t?t:t.depth}),this._headsetMesh.rotationQuaternion=new W.PT,this._headsetMesh.isVisible=!1,this._headsetImpostor=new sa(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)}getHeadsetImpostor(){return this._headsetImpostor}getImpostorForController(e){const t="string"==typeof e?e:e.uniqueId;return this._controllers[t]?this._controllers[t].impostor:null}setPhysicsProperties(e){this._options.physicsProperties={...this._options.physicsProperties,...e}}_onXRFrame(e){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),this._options.xrInput.xrCamera._lastXRViewerPose?.linearVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if(this._options.xrInput.xrCamera._lastXRViewerPose?.angularVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach((e=>{const t=this._controllers[e],i=t.xrController.grip||t.xrController.pointer,r=t.oldPos||t.impostorMesh.position;if(t.xrController._lastXRPose?.linearVelocity){const e=t.xrController._lastXRPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),t.impostor.setLinearVelocity(this._tmpVector)}else i.position.subtractToRef(r,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),t.impostor.setLinearVelocity(this._tmpVector);r.copyFrom(i.position),this._debugMode&&Z.V.Log([this._tmpVector,"linear"]);const s=t.oldRotation||t.impostorMesh.rotationQuaternion;if(t.xrController._lastXRPose?.angularVelocity){const e=t.xrController._lastXRPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),t.impostor.setAngularVelocity(this._tmpVector)}else if(!s.equalsWithEpsilon(i.rotationQuaternion)){s.conjugateInPlace().multiplyToRef(i.rotationQuaternion,this._tmpQuaternion);const e=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),e<.001)this._tmpVector.scaleInPlace(2);else{const t=2*Math.atan2(e,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(t/(e*(this._delta/1e3)))}t.impostor.setAngularVelocity(this._tmpVector)}s.copyFrom(i.rotationQuaternion),this._debugMode&&Z.V.Log([this._tmpVector,this._tmpQuaternion,"angular"])}))}_detachController(e){const t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}mL.Name=hr.PHYSICS_CONTROLLERS,mL.Version=1,cr.AddWebXRFeature(mL.Name,((e,t)=>()=>new mL(e,t)),mL.Version,!0);class gL extends Ig{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new W.uq,this._tmpPos=new W.Pq,this._tmpQuat=new W.PT,this._initHitTestSource=e=>{if(!e)return;const t=new XRRay(this.options.offsetRay||{}),i={space:this.options.useReferenceSpace?e:this._xrSessionManager.viewerReferenceSpace,offsetRay:t};this.options.entityTypes&&(i.entityTypes=this.options.entityTypes),i.space?this._xrSessionManager.session.requestHitTestSource(i).then((e=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=e})):Ue.S0.Warn("waiting for viewer reference space to initialize")},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new z.cP,this.paused=!1,this.xrNativeFeatureName="hit-test",Ue.S0.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach())return!1;if(!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((e=>{this._transientXrHitTestSource=e}))}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)}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((e=>{this._processWebXRHitTestResult(e.results,e.inputSource)}))}}_processWebXRHitTestResult(e,t){const i=[];e.forEach((e=>{const r=e.getPose(this._xrSessionManager.referenceSpace);if(!r)return;const s=r.transform.position,n=r.transform.orientation;this._tmpPos.set(s.x,s.y,s.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._tmpQuat.set(n.x,n.y,n.z,n.w),W.uq.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 o={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:e};i.push(o)})),this.onHitTestResultObservable.notifyObservers(i)}}gL.Name=hr.HIT_TEST,gL.Version=2,cr.AddWebXRFeature(gL.Name,((e,t)=>()=>new gL(e,t)),gL.Version,!1);class vL extends Ig{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new z.cP,this.onFeaturePointsUpdatedObservable=new z.cP,this.xrNativeFeatureName="bjsfeature-points",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){return!!super.detach()&&(this.featurePointCloud.length=0,!0)}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&&0!==t.length){if(t.length%5!=0)throw new Error("Received malformed feature point cloud of length: "+t.length);const e=t.length/5,i=[],r=[];for(let s=0;s0&&this.onFeaturePointsAddedObservable.notifyObservers(r),i.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(i)}}_init(){this._xrSessionManager.session.trySetFeaturePointCloudEnabled&&this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)&&(this._enabled=!0)}}vL.Name=hr.FEATURE_POINTS,vL.Version=1,cr.AddWebXRFeature(vL.Name,(e=>()=>new vL(e)),vL.Version);let xL=0;class bL extends Ig{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new z.cP,this.onMeshRemovedObservable=new z.cP,this.onMeshUpdatedObservable=new z.cP,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)}dispose(){super.dispose(),this.onMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onMeshUpdatedObservable.clear()}_onXRFrame(e){try{if(!this.attached||!e)return;const t=e.detectedMeshes||e.worldInformation?.detectedMeshes;if(t){const i=new Set;this._detectedMeshes.forEach(((e,r)=>{t.has(r)||i.add(r)})),i.forEach((e=>{const t=this._detectedMeshes.get(e);t&&(this.onMeshRemovedObservable.notifyObservers(t),this._detectedMeshes.delete(e))})),t.forEach((t=>{if(this._detectedMeshes.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._detectedMeshes.get(t);i&&(this._updateVertexDataWithXRMesh(t,i,e),this.onMeshUpdatedObservable.notifyObservers(i))}}else{const i={id:xL++,xrMesh:t},r=this._updateVertexDataWithXRMesh(t,i,e);this._detectedMeshes.set(t,r),this.onMeshAddedObservable.notifyObservers(r)}}))}}catch(e){Z.V.Log(e.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){t.xrMesh=e,t.worldParentNode=this._options.worldParentNode;const r=e.vertices||e.positions;if(this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=r,t.normals=e.normals;else{t.positions=new Float32Array(r.length);for(let e=0;e()=>new bL(e,t)),bL.Version,!1),function(e){e[e.NotReceived=0]="NotReceived",e[e.Waiting=1]="Waiting",e[e.Received=2]="Received"}(SL||(SL={}));class TL extends Ig{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new z.cP,this.onTrackableImageFoundObservable=new z.cP,this.onTrackedImageUpdatedObservable=new z.cP,this._trackableScoreStatus=SL.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((e=>"string"==typeof e.src?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(e.src):Promise.resolve(e.src)));try{const t=await Promise.all(e);return this._originalTrackingRequest=t.map(((e,t)=>({image:e,widthInMeters:this.options.images[t].estimatedRealWorldWidth}))),{trackedImages:this._originalTrackingRequest}}catch(e){return Ue.S0.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===SL.Waiting)return;if(this._trackableScoreStatus===SL.NotReceived)return void this._checkScoresAsync();const t=e.getImageTrackingResults();for(const i of t){let t=!1;const r=i.index,s=this._trackedImages[r];if(!s)continue;s.xrTrackingResult=i,s.realWorldWidth!==i.measuredWidthInMeters&&(s.realWorldWidth=i.measuredWidthInMeters,t=!0);const n=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(n){const e=s.transformationMatrix;W.uq.FromArrayToRef(n.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t=!0}const o="emulated"===i.trackingState;s.emulated!==o&&(s.emulated=o,t=!0),t&&this.onTrackedImageUpdatedObservable.notifyObservers(s)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==SL.NotReceived)return;this._trackableScoreStatus=SL.Waiting;const e=await this._xrSessionManager.session.getTrackedImageScores();if(e&&0!==e.length){for(let t=0;t0?SL.Received:SL.NotReceived}else this._trackableScoreStatus=SL.NotReceived}}TL.Name=hr.IMAGE_TRACKING,TL.Version=1,cr.AddWebXRFeature(TL.Name,((e,t)=>()=>new TL(e,t)),TL.Version,!1);class CL extends Ig{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",Ue.S0.Warn("dom-overlay is an experimental and unstable feature.")}attach(){return!(!super.attach()||!this._xrSessionManager.session.domOverlayState||null===this._xrSessionManager.session.domOverlayState.type||(this._domOverlayType=this._xrSessionManager.session.domOverlayState.type,null!==this._element&&!0===this.options.supressXRSelectEvents&&(this._beforeXRSelectListener=e=>{e.preventDefault()},this._element.addEventListener("beforexrselect",this._beforeXRSelectListener)),0))}get domOverlayType(){return this._domOverlayType}dispose(){super.dispose(),null!==this._element&&this._beforeXRSelectListener&&this._element.removeEventListener("beforexrselect",this._beforeXRSelectListener)}_onXRFrame(e){}async getXRSessionInitExtension(){if(void 0===this.options.element)return Ue.S0.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if("string"==typeof this.options.element){const e=document.querySelector(this.options.element);if(null===e)return Ue.S0.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}}}}CL.Name=hr.DOM_OVERLAY,CL.Version=1,cr.AddWebXRFeature(CL.Name,((e,t)=>()=>new CL(e,t)),CL.Version,!1);class yL extends Ig{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){super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new W.PT,this._tmpRotationMatrix=W.uq.Identity(),this._tmpTranslationDirection=new W.Pq,this._tmpMovementTranslation=new W.Pq,this._tempCacheQuaternion=new W.PT,this._attachController=e=>{if(this._controllers[e.uniqueId])return;this._controllers[e.uniqueId]={xrController:e,registeredComponents:[]};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController)for(const i of this._currentRegistrationConfigurations){let r=null;if(i.allowedComponentTypes)for(const t of i.allowedComponentTypes){const i=e.motionController.getComponentOfType(t);if(null!==i){r=i;break}}if(i.mainComponentOnly){const t=e.motionController.getMainComponent();if(null===t)continue;r=t}if("function"==typeof i.componentSelectionPredicate&&(r=i.componentSelectionPredicate(e)),r&&i.forceHandedness&&e.inputSource.handedness!==i.forceHandedness)continue;if(null===r)continue;const s={registrationConfiguration:i,component:r};t.registeredComponents.push(s),"axisChangedHandler"in i&&(s.onAxisChangedObserver=r.onAxisValueChangedObservable.add((e=>{i.axisChangedHandler(e,this._movementState,this._featureContext,this._xrInput)}))),"buttonChangedHandler"in i&&(s.onButtonChangedObserver=r.onButtonStateChangedObservable.add((e=>{e.changes.pressed&&i.buttonChangedHandler(e.changes.pressed,this._movementState,this._featureContext,this._xrInput)})))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}},t&&void 0!==t.xrInput?(Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=yL.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:t.movementOrientationFollowsViewerPose??!0,movementOrientationFollowsController:t.movementOrientationFollowsController??!1,orientationPreferredHandedness:t.orientationPreferredHandedness,movementSpeed:t.movementSpeed??1,movementThreshold:t.movementThreshold??.25,rotationEnabled:t.rotationEnabled??!0,rotationSpeed:t.rotationSpeed??1,rotationThreshold:t.rotationThreshold??.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput):Ue.S0.Error('WebXRControllerMovement feature requires "xrInput" option.')}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)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._controllers={},!0)}_onXRFrame(e){if(this.attached){if(0!==this._movementState.rotateX&&this._featureContext.rotationEnabled){const e=.001*this._xrSessionManager.scene.getEngine().getDeltaTime()*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);if(this._featureContext.movementOrientationFollowsViewerPose)this._xrInput.xrCamera.cameraRotation.y+=e,W.PT.RotationYawPitchRollToRef(e,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection);else if(this._featureContext.movementOrientationFollowsController){this._xrInput.xrCamera.cameraRotation.y+=e;const t=this._featureContext.orientationPreferredHandedness||"right",i=Object.keys(this._controllers).find((e=>this._controllers[e]?.xrController?.inputSource.handedness===t))||Object.keys(this._controllers)[0],r=this._controllers[i];W.PT.RotationYawPitchRollToRef(e,0,0,this._tempCacheQuaternion),(r?.xrController.pointer.rotationQuaternion||W.PT.Identity()).multiplyToRef(this._tempCacheQuaternion,this._movementDirection)}else W.PT.RotationYawPitchRollToRef(3*e,0,0,this._tempCacheQuaternion),this._movementDirection.multiplyInPlace(this._tempCacheQuaternion)}else if(this._featureContext.movementOrientationFollowsViewerPose)this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);else if(this._featureContext.movementOrientationFollowsController){const e=this._featureContext.orientationPreferredHandedness||"right",t=Object.keys(this._controllers).find((t=>this._controllers[t]?.xrController.inputSource.handedness===e))||Object.keys(this._controllers)[0],i=this._controllers[t];this._movementDirection.copyFrom(i?.xrController.pointer.rotationQuaternion||W.PT.Identity())}(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(W.uq.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),W.Pq.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 e of t.registeredComponents)e.onAxisChangedObserver&&e.component.onAxisValueChangedObservable.remove(e.onAxisChangedObserver),e.onButtonChangedObserver&&e.component.onButtonStateChangedObservable.remove(e.onButtonChangedObserver);delete this._controllers[e]}}}yL.Name=hr.MOVEMENT,yL.REGISTRATIONS={default:[{allowedComponentTypes:[Km.THUMBSTICK_TYPE,Km.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(e,t,i)=>{t.rotateX=Math.abs(e.x)>i.rotationThreshold?e.x:0,t.rotateY=Math.abs(e.y)>i.rotationThreshold?e.y:0}},{allowedComponentTypes:[Km.THUMBSTICK_TYPE,Km.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(e,t,i)=>{t.moveX=Math.abs(e.x)>i.movementThreshold?e.x:0,t.moveY=Math.abs(e.y)>i.movementThreshold?e.y:0}}]},yL.Version=1,cr.AddWebXRFeature(yL.Name,((e,t)=>()=>new yL(e,t)),yL.Version,!0);class EL extends Ig{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=W.Pq.Up().negateInPlace(),this._lightColor=H.v9.White(),this._intensity=1,this._sphericalHarmonics=new Ks.O,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new z.cP,this._updateReflectionCubeMap=()=>{if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){const e=Date.now();if(e-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 hm("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new W.Pq(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=jt.c.FALLOFF_GLTF),this._hdrFilter=new Bx(this._xrSessionManager.scene.getEngine()),Ue.S0.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 null===this._canvasContext&&(this._canvasContext=this._xrSessionManager.scene.getEngine()._gl),this._canvasContext}_getXRGLBinding(){if(null===this._xrWebGLBinding){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((e=>{this._xrLightProbe=e,this.options.disableCubeMapReflection||(this._reflectionCubeMap||(this._reflectionCubeMap=new js.t(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 null===this._xrLightProbe||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),null!==this._reflectionCubeMap&&(this._reflectionCubeMap._texture&&this._reflectionCubeMap._texture.dispose(),this._reflectionCubeMap.dispose(),this._reflectionCubeMap=null)}_onXRFrame(e){if(null!==this._xrLightProbe){if(this.options.lightEstimationPollInterval){const e=Date.now();if(e-this._lightEstimationPollTime()=>new EL(e,t)),EL.Version,!1);class PL extends Ig{constructor(e){super(e),this.onEyeTrackingStartedObservable=new z.cP,this.onEyeTrackingEndedObservable=new z.cP,this.onEyeTrackingFrameUpdateObservable=new z.cP,this._eyeTrackingStartListener=e=>{this._latestEyeSpace=e.gazeSpace,this._gazeRay=new wi(W.Pq.Zero(),W.Pq.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 e=t.transform.orientation;W.AA.Quaternion[0].set(e.x,e.y,e.z,e.w),this._xrSessionManager.scene.useRightHandedSystem?W.Pq.RightHandedForwardReadOnly.rotateByQuaternionToRef(W.AA.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,W.AA.Quaternion[0].z*=-1,W.AA.Quaternion[0].w*=-1,W.Pq.LeftHandedForwardReadOnly.rotateByQuaternionToRef(W.AA.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))}}PL.Name=hr.EYE_TRACKING,PL.Version=1,cr.AddWebXRFeature(PL.Name,(e=>()=>new PL(e)),PL.Version,!1);class AL{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 RL{constructor(){this._samples=new AL(20),this._entropy=0,this.onFirstStepDetected=new z.cP}update(e,t,i,r){this._samples.push(e,t);const s=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=W.I9.Distance(s,this._samples.at(1)),this._entropy>this._entropyThreshold)return;let n;for(n=this._samePointCheckStartIdx;no&&(a=t,o=e);if(on*this._squaredProjectionDistanceThreshold)return;const p=W.AA.Vector3[0];p.set(i,r,0);const _=W.AA.Vector3[1];_.set(h.x,h.y,0);const m=W.Pq.Cross(p,_).z>0,g=s.clone(),v=s.clone();l.subtractToRef(s,h),m?(h.scaleAndAddToRef(this._axisToApexShrinkFactor,g),h.scaleAndAddToRef(this._axisToApexExtendFactor,v)):(h.scaleAndAddToRef(this._axisToApexExtendFactor,g),h.scaleAndAddToRef(this._axisToApexShrinkFactor,v)),this.onFirstStepDetected.notifyObservers({leftApex:g,rightApex:v,currentPosition:s,currentStepDirection:m?"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 ML{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new RL,this._walker=null,this._movement=new W.I9,this._millisecondsSinceLastUpdate=ML._MillisecondsPerUpdate,this.movementThisFrame=W.Pq.Zero(),this._engine=e,this._detector.onFirstStepDetected.add((e=>{this._walker||(this._walker=new IL(e.leftApex,e.rightApex,e.currentPosition,e.currentStepDirection),this._walker.onFootfall.add((()=>{Z.V.Log("Footfall!")})),this._walker.onMovement.add((e=>{this._walker.forward.scaleAndAddToRef(.024*e.deltaT,this._movement)})))}))}update(e,t){t.y=0,t.normalize(),this._millisecondsSinceLastUpdate+=this._engine.getDeltaTime(),this._millisecondsSinceLastUpdate>=ML._MillisecondsPerUpdate&&(this._millisecondsSinceLastUpdate-=ML._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 OL extends Ig{static get Name(){return hr.WALKING_LOCOMOTION}static get Version(){return 1}get locomotionTarget(){return this._locomotionTarget}set locomotionTarget(e){this._locomotionTarget=e,this._isLocomotionTargetWebXRCamera="WebXRCamera"===this._locomotionTarget.getClassName()}constructor(e,t){super(e),this._up=new W.Pq,this._forward=new W.Pq,this._position=new W.Pq,this._movement=new W.Pq,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&Z.V.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 void 0===this._sessionManager.sessionMode||"immersive-vr"===this._sessionManager.sessionMode}attach(){return!(!this.isCompatible||!super.attach()||(this._walker=new ML(this._sessionManager.scene.getEngine()),0))}detach(){return!!super.detach()&&(this._walker=null,!0)}_onXRFrame(e){const t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;const i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,r=t.transform.matrix;this._up.copyFromFloats(r[4],r[5],i*r[6]),this._forward.copyFromFloats(r[8],r[9],i*r[10]),this._position.copyFromFloats(r[12],r[13],i*r[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||W.Pq.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}cr.AddWebXRFeature(OL.Name,((e,t)=>()=>new OL(e,t)),OL.Version,!1);class DL extends zn{constructor(e,t,i,r,s,n,o=null){super(e,t,i,r,n),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this.isMultiview=s,this.createRTTProvider=n,this._originalInternalTexture=o}}class wL extends Wn{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this.onRenderTargetTextureCreatedObservable=new z.cP,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t="none"){const i=this._lastSubImages.get(t),r="right"==t?1:0,s=e.colorTextureWidth??e.textureWidth,n=e.colorTextureHeight??e.textureHeight;if(!this._renderTargetTextures[r]||i?.textureWidth!==s||i?.textureHeight!==n){let i;const o=e.depthStencilTextureWidth??s,a=e.depthStencilTextureHeight??n;s!==o&&n!==a||(i=e.depthStencilTexture),this._renderTargetTextures[r]=this._createRenderTargetTexture(s,n,null,e.colorTexture,i,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:s,framebufferHeight:n},this.onRenderTargetTextureCreatedObservable.notifyObservers({texture:this._renderTargetTextures[r],eye:t})}return this._lastSubImages.set(t,e),this._renderTargetTextures[r]}_getSubImageForEye(e){const t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null}getRenderTargetTextureForEye(e){const t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e?.eye)}_setViewportForSubImage(e,t){const i=t.colorTextureWidth??t.textureWidth,r=t.colorTextureHeight??t.textureHeight,s=t.viewport;e.x=s.x/i,e.y=s.y/r,e.width=s.width/i,e.height=s.height/r}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return!!i&&(this._setViewportForSubImage(e,i),!0)}}class NL extends DL{constructor(e,t,i){super((()=>e.textureWidth),(()=>e.textureHeight),e,"XRProjectionLayer",t,(e=>new FL(e,i,this))),this.layer=e}}class FL extends wL{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)}}const LL={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1,clearOnAccess:!1},BL={};class VL extends Ig{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={...LL,...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)}createXRWebGLLayer(e=BL){const t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new Hn(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&&"texture-array"!==e.textureType)throw new Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'.");if(!t&&"texture-array"===e.textureType)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=LL,t=this._isMultiviewEnabled){this._extendXRLayerInit(e,t),this._validateLayerInit(e,t);const i=this._xrWebGLBinding.createProjectionLayer(e),r=new NL(i,t,this._xrWebGLBinding);return this.addXRSessionLayer(r),r}_createQuadLayer(e={params:{}},t){this._extendXRLayerInit(e.params,!1);const i=this._existingLayers[0].layer.textureWidth,r=this._existingLayers[0].layer.textureHeight,s={space:this._xrSessionManager.referenceSpace,viewPixelWidth:i,viewPixelHeight:r,clearOnAccess:!0,...e.params};this._validateLayerInit(s,!1);const n=this._xrWebGLBinding.createQuadLayer(s);n.width=this._isMultiviewEnabled?1:2,n.height=1;const o=new DL((()=>n.width),(()=>n.height),n,"XRQuadLayer",!1,(e=>new wL(e,this._xrWebGLBinding,o)));t&&this._compositionLayerTextureMapping.set(n,t);const a=o.createRenderTargetTextureProvider(this._xrSessionManager);return this._layerToRTTProviderMapping.set(n,a),this.addXRSessionLayer(o),o}addFullscreenAdvancedDynamicTexture(e,t={distanceFromHeadset:1.5}){const i=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}},e),r=i.layer,s={x:0,y:0,z:-Math.max(.1,t.distanceFromHeadset)};r.transform=new XRRigidTransform(s,{x:0,y:0,z:0,w:1});const n=this._layerToRTTProviderMapping.get(r);if(!n)throw new Error("Could not find the RTT provider for the layer");const o=this._xrSessionManager.scene.layers.find((t=>t.texture===e));if(!o)throw new Error("Could not find the babylon layer for the texture");return n.onRenderTargetTextureCreatedObservable.add((e=>{e.eye&&"right"===e.eye||(e.texture.clearColor=new H.ov(0,0,0,0),o.renderTargetTextures.push(e.texture),o.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.scene.onBeforeRenderObservable.add((()=>{e.texture.render()})),o.renderTargetTextures.push(e.texture),o.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.onXRSessionEnded.addOnce((()=>{o.renderTargetTextures.splice(o.renderTargetTextures.indexOf(e.texture),1),o.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;i.transform=new XRRigidTransform({x:0,y:0,z:-10},{x:0,y:0,z:0,w:1});const r=this._layerToRTTProviderMapping.get(i);if(!r)throw new Error("Could not find the RTT provider for the layer");return r.onRenderTargetTextureCreatedObservable.add((t=>{t.texture.clearColor=new H.ov(0,0,0,0),t.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((e=>e.layer)),this._xrSessionManager.updateRenderState(t),this._projectionLayerInitialized||this._xrSessionManager._setBaseLayerWrapper(e.length>0?e.at(0):null)}isCompatible(){return!this._xrSessionManager.isNative&&"undefined"!=typeof XRWebGLBinding&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){const t=this._existingLayers;for(let i=0;i()=>new VL(e,t)),VL.Version,!1);class kL extends Ig{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 Fs.h(e,0);return t.isCube=!1,t.invertY=!1,t._useSRGBBuffer=!1,t.format="ushort"===this.depthDataFormat?2:5,t.generateMipMaps=!1,t.type="ushort"===this.depthDataFormat?5:1,t.samplingMode=7,t.width=this.width??0,t.height=this.height??0,t._cachedWrapU=1,t._cachedWrapV=1,t._hardwareTexture=new Us.d(this._cachedWebGLTexture,e._gl),t}get latestDepthBuffer(){return this._cachedDepthBuffer?"ushort"===this.depthDataFormat?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 z.cP,this.xrNativeFeatureName="depth-sensing",Ue.S0.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){return!!super.attach(e)&&(null!=this._xrSessionManager.session.depthDataFormat&&null!=this._xrSessionManager.session.depthUsage&&(this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._xrSessionManager.scene.getEngine()._gl),!0))}dispose(){this._cachedDepthImageTexture?.dispose(),this.onGetDepthInMetersAvailable.clear()}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(null!=i)for(const t of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,t,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,t,this.depthDataFormat);break;default:Ue.S0.Error("Unknown depth usage"),this.detach()}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){const r=e.getDepthInformation(t);if(null===r)return;const{data:s,width:n,height:o,rawValueToMeters:a,getDepthInMeters:l}=r;switch(this._width=n,this._height=o,this._rawValueToMeters=a,this._cachedDepthBuffer=s,this.onGetDepthInMetersAvailable.notifyObservers(l.bind(r)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=xi.CreateRTexture(null,n,o,this._xrSessionManager.scene,!1,!0,vi.g.NEAREST_SAMPLINGMODE,1)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(s)).map((e=>e*a)));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(s).map((e=>e*a)))}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){const r=e.getDepthInformation(t);if(null===r)return;const{texture:s,width:n,height:o}=r;this._width=n,this._height=o,this._cachedWebGLTexture=s;const a=this._xrSessionManager.scene,l=a.getEngine().wrapWebGLTexture(s);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=xi.CreateRTexture(null,n,o,a,!1,!0,vi.g.NEAREST_SAMPLINGMODE,"ushort"===i?0:1)),this._cachedDepthImageTexture._texture=l}getXRSessionInitExtension(){const e=null!=this.options.usagePreference&&0!==this.options.usagePreference.length,t=null!=this.options.dataFormatPreference&&0!==this.options.dataFormatPreference.length;return new Promise((i=>{i(e&&t?{depthSensing:{usagePreference:this.options.usagePreference.map((e=>{switch(e){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}})),dataFormatPreference:this.options.dataFormatPreference.map((e=>{switch(e){case"ushort":return"luminance-alpha";case"float":return"float32"}}))}}:{})}))}}kL.Name=hr.DEPTH_SENSING,kL.Version=1,cr.AddWebXRFeature(kL.Name,((e,t)=>()=>new kL(e,t)),kL.Version,!1);Cs.l.ShadersStore.velocityPixelShader="precision highp float;\n#define CUSTOM_FRAGMENT_BEGIN\nvarying vec4 clipPos;varying vec4 previousClipPos;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nhighp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Cs.l.ShadersStore.velocityVertexShader="#define CUSTOM_VERTEX_BEGIN\n#define VELOCITY\nattribute vec3 position;\n#include\nuniform mat4 viewProjection;uniform mat4 previousViewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR;\n#endif\nvarying vec4 clipPos;varying vec4 previousClipPos;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;}\n#elif\nclipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";class UL extends ln.${constructor(e,t,i,r=512){super("spacewarp rtt",r,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[W.uq.Identity(),W.uq.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 xo("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add((e=>{this._previousWorldMatrices[e.uniqueId]=this._previousWorldMatrices[e.uniqueId]||e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[e.uniqueId]),this._previousWorldMatrices[e.uniqueId]=e.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((e=>{this._originalPairing.push([e,e.material]),e.material=this._velocityMaterial})),super.render(e,t),this._originalPairing.forEach((e=>{e[0].material=e[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 GL{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("XRProjectionLayer"!==t.layerType)throw new Error('For Space Warp, the base layer type should "XRProjectionLayer".');const i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,r,s){if(!this._engine)throw new Error("Engine is disposed");const n={width:e,height:t},o=new UL(r,s,this._scene,n),a=o.renderTarget;return i&&(a._framebuffer=i),a._colorTextureArray=r,a._depthStencilTextureArray=s,o.disableRescaling(),o.renderListPredicate=()=>!0,o}_getRenderTargetForSubImage(e,t){const i=this._lastSubImages.get(t);let r=this._renderTargetTextures.get(t.eye);const s=e.motionVectorTextureWidth,n=e.motionVectorTextureHeight;return r&&i?.textureWidth===s&&i?.textureHeight==n||(r=this._createRenderTargetTexture(s,n,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,r),this._framebufferDimensions={framebufferWidth:s,framebufferHeight:n}),this._lastSubImages.set(t,e),r}trySetViewportForView(e,t){const i=this._lastSubImages.get(t)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}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 zL extends Ig{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[hr.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 GL(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)}}zL.Name=hr.SPACE_WARP,zL.Version=1,cr.AddWebXRFeature(zL.Name,(e=>()=>new zL(e)),zL.Version,!1);class WL extends Ig{constructor(e,t={}){super(e),this.options=t,this._cachedInternalTextures=[],this.texturesData=[],this.viewIndex=[],this.cameraIntrinsics=[],this.onTexturesUpdatedObservable=new z.cP,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)}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)}dispose(){super.dispose(),this.onTexturesUpdatedObservable.clear()}_updateCameraIntrinsics(e,t){const i={width:e.camera.width,height:e.camera.height,x:0,y:0},r=e.projectionMatrix,s=(1-r[8])*i.width/2+i.x,n=(1-r[9])*i.height/2+i.y,o=i.width/2*r[0],a=i.height/2*r[5],l=i.width/2*r[4];this.cameraIntrinsics[t]={u0:s,v0:n,ax:o,ay:a,gamma:l,width:i.width,height:i.height,viewportX:i.x,viewportY:i.y}}_updateInternalTextures(e,t=0){if(!e.camera)return!1;this.viewIndex[t]=e.eye;const i=this._glBinding?.getCameraImage(e.camera);if(this._cachedInternalTextures[t])this._cachedInternalTextures[t]._hardwareTexture?.set(i);else{const r=new Fs.h(this._xrSessionManager.scene.getEngine(),0,!0);r.invertY=!1,r.format=5,r.generateMipMaps=!0,r.type=0,r.samplingMode=3,r.width=e.camera.width,r.height=e.camera.height,r._cachedWrapU=1,r._cachedWrapV=1,r._hardwareTexture=new Us.d(i,this._glContext),this._cachedInternalTextures[t]=r;const s=new js.t(this._xrSessionManager.scene);s.name=`WebXR Raw Camera Access (${t})`,s._texture=this._cachedInternalTextures[t],this.texturesData[t]=s,this._updateCameraIntrinsics(e,t)}return this._cachedInternalTextures[t].isReady=!0,!0}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(!i||!i.views)return;let r=!0;i.views.forEach(((e,t)=>{r=r&&this._updateInternalTextures(e,t)})),r&&this.onTexturesUpdatedObservable.notifyObservers(this.texturesData)}}WL.Name=hr.RAW_CAMERA_ACCESS,WL.Version=1,cr.AddWebXRFeature(WL.Name,((e,t)=>()=>new WL(e,t)),WL.Version,!1);class HL extends bg{constructor(e,t,i){super(e,XL[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(){}}Eg.RegisterController("generic-hand-select-grasp",((e,t)=>new HL(t,e.gamepad,e.handedness)));const XL={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 qL extends bg{constructor(e,t,i){super(e,YL["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="";return e="left"===this.handedness?qL.MODEL_LEFT_FILENAME:qL.MODEL_RIGHT_FILENAME,{filename:e,path:qL.MODEL_BASE_URL+"default/"}}_getModelLoadingConstraints(){const e=xg.IsPluginForExtensionAvailable(".glb");return e||Z.V.Warn("glTF / glb loaded was not registered, using generic controller instead"),e}_processLoadedModel(e){this.rootMesh&&(this.getComponentIds().forEach(((e,t)=>{if(!this.disableAnimation&&e&&this.rootMesh){const i=this._mapping.buttons[e],r=i.rootNodeName;if(!r)return void Z.V.Log("Skipping unknown button at index: "+t+" with mapped name: "+e);const s=this._getChildByName(this.rootMesh,r);if(!s)return void Z.V.Warn("Missing button mesh with name: "+r);if(i.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.valueNodeName),i.pressedMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.pressedNodeName),i.unpressedMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.unpressedNodeName),i.valueMesh&&i.pressedMesh&&i.unpressedMesh){const t=this.getComponent(e);t&&t.onButtonStateChangedObservable.add((e=>{this._lerpTransform(i,e.value)}),void 0,!0)}else Z.V.Warn("Missing button submesh under mesh with name: "+r)}})),this.getComponentIds().forEach((e=>{const t=this.getComponent(e);t.isAxes()&&["x-axis","y-axis"].forEach((i=>{if(!this.rootMesh)return;const r=this._mapping.axes[e][i],s=this._getChildByName(this.rootMesh,r.rootNodeName);s?(r.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.valueNodeName),r.minMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.minNodeName),r.maxMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.maxNodeName),r.valueMesh&&r.minMesh&&r.maxMesh?t&&t.onAxisValueChangedObservable.add((e=>{const t="x-axis"===i?e.x:e.y;this._lerpTransform(r,t,!0)}),void 0,!0):Z.V.Warn("Missing axis submesh under mesh with name: "+r.rootNodeName)):Z.V.Warn("Missing axis mesh with name: "+r.rootNodeName)}))})))}_setRootMesh(e){let t;this.rootMesh=new Yt(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;inew qL(t,e.gamepad,e.handedness)));const YL={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 KL extends bg{constructor(e,t,i,r=!1,s=!1){super(e,jL[i],t,i),this._forceLegacyControllers=s,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";return e="left"===this.handedness?KL.MODEL_LEFT_FILENAME:KL.MODEL_RIGHT_FILENAME,{filename:e,path:this._isQuest()?KL.QUEST_MODEL_BASE_URL:KL.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){const t=this._isQuest(),i="right"===this.handedness?-1:1;this.getComponentIds().forEach((e=>{const r=e&&this.getComponent(e);r&&r.onButtonStateChangedObservable.add((r=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(t||(this._modelRootNode.getChildren()[3].rotation.x=.2*-r.value,this._modelRootNode.getChildren()[3].position.y=.005*-r.value,this._modelRootNode.getChildren()[3].position.z=.005*-r.value));case"xr-standard-squeeze":return void(t||(this._modelRootNode.getChildren()[4].position.x=i*r.value*.0035));case"xr-standard-thumbstick":return;case"a-button":case"x-button":return void(t||(r.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0));case"b-button":case"y-button":return void(t||(r.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0))}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new Yt(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=W.PT.FromEulerAngles(0,Math.PI,0)),e.forEach((e=>{e.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}}KL.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",KL.MODEL_LEFT_FILENAME="left.babylon",KL.MODEL_RIGHT_FILENAME="right.babylon",KL.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",Eg.RegisterController("oculus-touch",((e,t)=>new KL(t,e.gamepad,e.handedness))),Eg.RegisterController("oculus-touch-legacy",((e,t)=>new KL(t,e.gamepad,e.handedness,!0)));const jL={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 $L extends bg{constructor(e,t,i){super(e,QL[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){return{filename:$L.MODEL_FILENAME,path:$L.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=e&&this.getComponent(e);t&&t.onButtonStateChangedObservable.add((t=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(this._modelRootNode.getChildren()[6].rotation.x=.15*-t.value);case"xr-standard-touchpad":case"xr-standard-squeeze":return}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new Yt(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1})),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=W.PT.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}$L.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",$L.MODEL_FILENAME="wand.babylon",Eg.RegisterController("htc-vive",((e,t)=>new $L(t,e.gamepad,e.handedness)));const QL={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 ZL{get session(){return this._nativeImpl.session}constructor(e){this._nativeImpl=e,this._xrTransform=new XRRigidTransform,this._xrPose={transform:this._xrTransform,emulatedPosition:!1},this._xrPoseVectorData=new Float32Array(8),this.fillPoses=this._nativeImpl.fillPoses.bind(this._nativeImpl),this.getViewerPose=this._nativeImpl.getViewerPose.bind(this._nativeImpl),this.getHitTestResults=this._nativeImpl.getHitTestResults.bind(this._nativeImpl),this.getHitTestResultsForTransientInput=()=>{throw new Error("XRFrame.getHitTestResultsForTransientInput not supported on native.")},this.createAnchor=this._nativeImpl.createAnchor.bind(this._nativeImpl),this.getJointPose=this._nativeImpl.getJointPose.bind(this._nativeImpl),this.fillJointRadii=this._nativeImpl.fillJointRadii.bind(this._nativeImpl),this.getLightEstimate=()=>{throw new Error("XRFrame.getLightEstimate not supported on native.")},this.getImageTrackingResults=()=>this._nativeImpl._imageTrackingResults??[]}getPose(e,t){if(!this._nativeImpl.getPoseData(e,t,this._xrPoseVectorData.buffer,this._xrTransform.matrix.buffer))return;const i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];const r=this._xrTransform.orientation;return r.x=this._xrPoseVectorData[4],r.y=this._xrPoseVectorData[5],r.z=this._xrPoseVectorData[6],r.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw new Error("This function is not available in Babylon Native")}}fh("NativeXRFrame",ZL);class JL{constructor(e,t=JL.UNITMODE_PIXEL,i=!0){this.negativeValueAllowed=i,this._value=1,this._unit=JL.UNITMODE_PIXEL,this.ignoreAdaptiveScaling=!1,this.onChangedObservable=new z.cP,this._value=e,this._unit=t,this._originalUnit=t}get isPercentage(){return this._unit===JL.UNITMODE_PERCENTAGE}get isPixel(){return this._unit===JL.UNITMODE_PIXEL}get internalValue(){return this._value}get value(){return this._value}set value(e){e!==this._value&&(this._value=e,this.onChangedObservable.notifyObservers())}get unit(){return this._unit}set unit(e){e!==this._unit&&(this._unit=e,this.onChangedObservable.notifyObservers())}getValueInPixel(e,t){return this.isPixel?this.getValue(e):this.getValue(e)*t}updateInPlace(e,t=JL.UNITMODE_PIXEL){return this.value===e&&this.unit===t||(this._value=e,this._unit=t,this.onChangedObservable.notifyObservers()),this}getValue(e){if(e&&!this.ignoreAdaptiveScaling&&this.unit!==JL.UNITMODE_PERCENTAGE){let t=0,i=0;if(e.idealWidth&&(t=Math.ceil(this._value*e.getSize().width/e.idealWidth)),e.idealHeight&&(i=Math.ceil(this._value*e.getSize().height/e.idealHeight)),e.useSmallestIdeal&&e.idealWidth&&e.idealHeight)return window.innerWidth{this._markAsDirty(),this._resetFontCache()}))),this._markAsDirty(),this._resetFontCache()}get _isFontSizeInPercentage(){return this._fontSize.isPercentage}get fontSizeInPixels(){const e=this._style?this._style._fontSize:this._fontSize;return e.isPixel?e.getValue(this._host):e.getValueInPixel(this._host,this._tempParentMeasure.height||this._cachedParentMeasure.height)}set fontSizeInPixels(e){isNaN(e)||(this.fontSize=e+"px")}get fontSize(){return this._fontSize.toString(this._host)}set fontSize(e){this._fontSize.toString(this._host)!==e&&this._fontSize.fromString(e)&&(this._markAsDirty(),this._resetFontCache())}get color(){return this._color}set color(e){this._color!==e&&(this._color=e,this._markAsDirty())}get gradient(){return this._gradient}set gradient(e){this._gradient!==e&&(this._gradient=e,this._markAsDirty())}get zIndex(){return this._zIndex}set zIndex(e){this.zIndex!==e&&(this._zIndex=e,this.parent&&this.parent._reOrderControl(this))}get notRenderable(){return this._doNotRender}set notRenderable(e){this._doNotRender!==e&&(this._doNotRender=e,this._markAsDirty())}get isVisible(){return this._isVisible}set isVisible(e){this._isVisible!==e&&(this._isVisible=e,this._markAsDirty(!0),this.onIsVisibleChangedObservable.notifyObservers(e))}get isDirty(){return this._isDirty}get linkedMesh(){return this._linkedMesh}get descendantsOnlyPadding(){return this._descendantsOnlyPadding}set descendantsOnlyPadding(e){this._descendantsOnlyPadding!==e&&(this._descendantsOnlyPadding=e,this._markAsDirty())}get paddingLeft(){return this._paddingLeft.toString(this._host)}set paddingLeft(e){this._paddingLeft.fromString(e)&&this._markAsDirty()}get paddingLeftInPixels(){return this._paddingLeft.getValueInPixel(this._host,this._cachedParentMeasure.width)}set paddingLeftInPixels(e){isNaN(e)||(this.paddingLeft=e+"px")}get _paddingLeftInPixels(){return this._descendantsOnlyPadding?0:this.paddingLeftInPixels}get paddingRight(){return this._paddingRight.toString(this._host)}set paddingRight(e){this._paddingRight.fromString(e)&&this._markAsDirty()}get paddingRightInPixels(){return this._paddingRight.getValueInPixel(this._host,this._cachedParentMeasure.width)}set paddingRightInPixels(e){isNaN(e)||(this.paddingRight=e+"px")}get _paddingRightInPixels(){return this._descendantsOnlyPadding?0:this.paddingRightInPixels}get paddingTop(){return this._paddingTop.toString(this._host)}set paddingTop(e){this._paddingTop.fromString(e)&&this._markAsDirty()}get paddingTopInPixels(){return this._paddingTop.getValueInPixel(this._host,this._cachedParentMeasure.height)}set paddingTopInPixels(e){isNaN(e)||(this.paddingTop=e+"px")}get _paddingTopInPixels(){return this._descendantsOnlyPadding?0:this.paddingTopInPixels}get paddingBottom(){return this._paddingBottom.toString(this._host)}set paddingBottom(e){this._paddingBottom.fromString(e)&&this._markAsDirty()}get paddingBottomInPixels(){return this._paddingBottom.getValueInPixel(this._host,this._cachedParentMeasure.height)}set paddingBottomInPixels(e){isNaN(e)||(this.paddingBottom=e+"px")}get _paddingBottomInPixels(){return this._descendantsOnlyPadding?0:this.paddingBottomInPixels}get left(){return this._left.toString(this._host)}set left(e){this._left.fromString(e)&&this._markAsDirty()}get leftInPixels(){return this._left.getValueInPixel(this._host,this._cachedParentMeasure.width)}set leftInPixels(e){isNaN(e)||(this.left=e+"px")}get top(){return this._top.toString(this._host)}set top(e){this._top.fromString(e)&&this._markAsDirty()}get topInPixels(){return this._top.getValueInPixel(this._host,this._cachedParentMeasure.height)}set topInPixels(e){isNaN(e)||(this.top=e+"px")}get linkOffsetX(){return this._linkOffsetX.toString(this._host)}set linkOffsetX(e){this._linkOffsetX.fromString(e)&&this._markAsDirty()}get linkOffsetXInPixels(){return this._linkOffsetX.getValueInPixel(this._host,this._cachedParentMeasure.width)}set linkOffsetXInPixels(e){isNaN(e)||(this.linkOffsetX=e+"px")}get linkOffsetY(){return this._linkOffsetY.toString(this._host)}set linkOffsetY(e){this._linkOffsetY.fromString(e)&&this._markAsDirty()}get linkOffsetYInPixels(){return this._linkOffsetY.getValueInPixel(this._host,this._cachedParentMeasure.height)}set linkOffsetYInPixels(e){isNaN(e)||(this.linkOffsetY=e+"px")}get centerX(){return this._currentMeasure.left+this._currentMeasure.width/2}get centerY(){return this._currentMeasure.top+this._currentMeasure.height/2}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled===e)return;this._isEnabled=e,this._markAsDirty();const t=e=>{if(e.host){for(const t in e.host._lastControlOver)e===this.host._lastControlOver[t]&&(e._onPointerOut(e,null,!0),delete e.host._lastControlOver[t]);void 0!==e.children&&e.children.forEach(t)}};t(this),this.onEnabledStateChangedObservable.notifyObservers(e)}get disabledColor(){return this._disabledColor}set disabledColor(e){this._disabledColor!==e&&(this._disabledColor=e,this._markAsDirty())}get disabledColorItem(){return this._disabledColorItem}set disabledColorItem(e){this._disabledColorItem!==e&&(this._disabledColorItem=e,this._markAsDirty())}get focusedColor(){return this._focusedColor}set focusedColor(e){this._focusedColor=e}onBlur(){this._isFocused&&(this._isFocused=!1,this.focusedColor&&null!=this._unfocusedColor&&(this.color=this._unfocusedColor),this.onBlurObservable.notifyObservers(this))}onFocus(){this._isFocused=!0,this.focusedColor&&(this._unfocusedColor=this.color,this.color=this.focusedColor),this.onFocusObservable.notifyObservers(this)}keepsFocusWith(){return null}focus(){this._host.moveFocusToControl(this)}blur(){this._host.focusedControl=null}processKeyboard(e){"Enter"===e.key&&this.onEnterPressedObservable.notifyObservers(this),this.onKeyboardEventProcessedObservable.notifyObservers(e,-1,this)}constructor(e){this.name=e,this._alpha=1,this._alphaSet=!1,this._zIndex=0,this._currentMeasure=sB.Empty(),this._tempPaddingMeasure=sB.Empty(),this._fontFamily="",this._fontStyle="",this._fontWeight="",this._fontSize=new JL(18,JL.UNITMODE_PIXEL,!1),this._width=new JL(1,JL.UNITMODE_PERCENTAGE,!1),this._height=new JL(1,JL.UNITMODE_PERCENTAGE,!1),this._color="",this._style=null,this._horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_CENTER,this._verticalAlignment=lB.VERTICAL_ALIGNMENT_CENTER,this._isDirty=!0,this._wasDirty=!1,this._tempParentMeasure=sB.Empty(),this._prevCurrentMeasureTransformedIntoGlobalSpace=sB.Empty(),this._cachedParentMeasure=sB.Empty(),this._descendantsOnlyPadding=!1,this._paddingLeft=new JL(0),this._paddingRight=new JL(0),this._paddingTop=new JL(0),this._paddingBottom=new JL(0),this._left=new JL(0),this._top=new JL(0),this._scaleX=1,this._scaleY=1,this._rotation=0,this._transformCenterX=.5,this._transformCenterY=.5,this._transformMatrix=oB.Identity(),this._invertTransformMatrix=oB.Identity(),this._transformedPosition=W.I9.Zero(),this._isMatrixDirty=!0,this._isVisible=!0,this._isHighlighted=!1,this._highlightColor="#4affff",this._highlightLineWidth=2,this._fontSet=!1,this._dummyVector2=W.I9.Zero(),this._downCount=0,this._enterCount=-1,this._doNotRender=!1,this._downPointerIds={},this._evaluatedMeasure=new sB(0,0,0,0),this._evaluatedParentMeasure=new sB(0,0,0,0),this._isEnabled=!0,this._disabledColor="#9a9a9a",this._disabledColorItem="#6a6a6a",this._isReadOnly=!1,this._gradient=null,this._rebuildLayout=!1,this.onEnabledStateChangedObservable=new z.cP,this._customData={},this._isClipped=!1,this._automaticSize=!1,this.metadata=null,this.isHitTestVisible=!0,this.isPointerBlocker=!1,this.isFocusInvisible=!1,this._clipChildren=!0,this._clipContent=!0,this.useBitmapCache=!1,this._shadowOffsetX=0,this._shadowOffsetY=0,this._shadowBlur=0,this._previousShadowBlur=0,this._shadowColor="black",this.hoverCursor="",this._linkOffsetX=new JL(0),this._linkOffsetY=new JL(0),this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new z.cP,this.onWheelObservable=new z.cP,this.onPointerMoveObservable=new z.cP,this.onPointerOutObservable=new z.cP,this.onPointerDownObservable=new z.cP,this.onPointerUpObservable=new z.cP,this.onPointerClickObservable=new z.cP,this.onEnterPressedObservable=new z.cP,this.onPointerEnterObservable=new z.cP,this.onDirtyObservable=new z.cP,this.onBeforeDrawObservable=new z.cP,this.onAfterDrawObservable=new z.cP,this.onDisposeObservable=new z.cP,this.onIsVisibleChangedObservable=new z.cP,this.isSerializable=!0,this._fixedRatio=0,this._fixedRatioMasterIsWidth=!0,this.animations=null,this._focusedColor=null,this.tabIndex=-1,this._isFocused=!1,this._unfocusedColor=null,this.onFocusObservable=new z.cP,this.onBlurObservable=new z.cP,this.onKeyboardEventProcessedObservable=new z.cP,this._tmpMeasureA=new sB(0,0,0,0)}_getTypeName(){return"Control"}getAscendantOfClass(e){return this.parent?this.parent.getClassName()===e?this.parent:this.parent.getAscendantOfClass(e):null}markAsDirty(e=!1){this._markAsDirty(e)}markAllAsDirty(){this._markAllAsDirty()}_resetFontCache(){this._fontSet=!0,this._markAsDirty()}isAscendant(e){return!!this.parent&&(this.parent===e||this.parent.isAscendant(e))}getLocalCoordinates(e){const t=W.I9.Zero();return this.getLocalCoordinatesToRef(e,t),t}getLocalCoordinatesToRef(e,t){return t.x=e.x-this._currentMeasure.left,t.y=e.y-this._currentMeasure.top,this}getParentLocalCoordinates(e){const t=W.I9.Zero();return t.x=e.x-this._cachedParentMeasure.left,t.y=e.y-this._cachedParentMeasure.top,t}moveToVector3(e,t){if(!this._host||this.parent!==this._host._rootContainer)return void Ue.S0.Error("Cannot move a control to a vector3 if the control is not at root level");this.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,this.verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP;const i=this._host._getGlobalViewport(),r=W.Pq.Project(e,W.uq.IdentityReadOnly,t.getTransformMatrix(),i);this._moveToProjectedPosition(r),r.z<0||r.z>1?this.notRenderable=!0:this.notRenderable=!1}getDescendantsToRef(e,t=!1,i){}getDescendants(e,t){const i=[];return this.getDescendantsToRef(i,e,t),i}linkWithMesh(e){if(!this._host||this.parent&&this.parent!==this._host._rootContainer)return void(e&&Ue.S0.Error("Cannot link a control to a mesh if the control is not at root level"));const t=this._host._linkedControls.indexOf(this);if(-1!==t)return this._linkedMesh=e,void(e||this._host._linkedControls.splice(t,1));e&&(this.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,this.verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP,this._linkedMesh=e,this._host._linkedControls.push(this))}setPadding(e,t,i,r){const s=e,n=t??s,o=i??s,a=r??n;this.paddingTop=s,this.paddingRight=n,this.paddingBottom=o,this.paddingLeft=a}setPaddingInPixels(e,t,i,r){const s=e,n=t??s,o=i??s,a=r??n;this.paddingTopInPixels=s,this.paddingRightInPixels=n,this.paddingBottomInPixels=o,this.paddingLeftInPixels=a}_moveToProjectedPosition(e){const t=this._left.getValue(this._host),i=this._top.getValue(this._host),r=this.parent?._currentMeasure;r&&this._processMeasures(r,this._host.getContext());let s=e.x+this._linkOffsetX.getValue(this._host)-this._currentMeasure.width/2,n=e.y+this._linkOffsetY.getValue(this._host)-this._currentMeasure.height/2;const o=this._left.ignoreAdaptiveScaling&&this._top.ignoreAdaptiveScaling;o&&(Math.abs(s-t)<.5&&(s=t),Math.abs(n-i)<.5&&(n=i)),(o||t!==s||i!==n)&&(this.left=s+"px",this.top=n+"px",this._left.ignoreAdaptiveScaling=!0,this._top.ignoreAdaptiveScaling=!0,this._markAsDirty())}_offsetLeft(e){this._isDirty=!0,this._currentMeasure.left+=e}_offsetTop(e){this._isDirty=!0,this._currentMeasure.top+=e}_markMatrixAsDirty(){this._isMatrixDirty=!0,this._flagDescendantsAsMatrixDirty()}_flagDescendantsAsMatrixDirty(){}_intersectsRect(e,t){return this._transform(t),!(this._evaluatedMeasure.left>=e.left+e.width||this._evaluatedMeasure.top>=e.top+e.height||this._evaluatedMeasure.left+this._evaluatedMeasure.width<=e.left||this._evaluatedMeasure.top+this._evaluatedMeasure.height<=e.top)}_computeAdditionalOffsetX(){return 0}_computeAdditionalOffsetY(){return 0}invalidateRect(){if(this._transform(),this.host&&this.host.useInvalidateRectOptimization){this._currentMeasure.transformToRef(this._transformMatrix,this._tmpMeasureA),sB.CombineToRef(this._tmpMeasureA,this._prevCurrentMeasureTransformedIntoGlobalSpace,this._tmpMeasureA);const e=this.shadowOffsetX,t=this.shadowOffsetY,i=Math.max(this._previousShadowBlur,this.shadowBlur),r=Math.min(Math.min(e,0)-2*i,0),s=Math.max(Math.max(e,0)+2*i,0),n=Math.min(Math.min(t,0)-2*i,0),o=Math.max(Math.max(t,0)+2*i,0),a=this._computeAdditionalOffsetX(),l=this._computeAdditionalOffsetY();this.host.invalidateRect(Math.floor(this._tmpMeasureA.left+r-a),Math.floor(this._tmpMeasureA.top+n-l),Math.ceil(this._tmpMeasureA.left+this._tmpMeasureA.width+s+a),Math.ceil(this._tmpMeasureA.top+this._tmpMeasureA.height+o+l))}}_markAsDirty(e=!1){(this._isVisible||e)&&(this._isDirty=!0,this._markMatrixAsDirty(),this._host&&this._host.markAsDirty())}_markAllAsDirty(){this._markAsDirty(),this._font&&this._prepareFont()}_link(e){this._host=e,this._host&&(this.uniqueId=this._host.getScene().getUniqueId())}_transform(e){if(!this._isMatrixDirty&&1===this._scaleX&&1===this._scaleY&&0===this._rotation)return;const t=this._currentMeasure.width*this._transformCenterX+this._currentMeasure.left,i=this._currentMeasure.height*this._transformCenterY+this._currentMeasure.top;e&&(e.translate(t,i),e.rotate(this._rotation),e.scale(this._scaleX,this._scaleY),e.translate(-t,-i)),(this._isMatrixDirty||this._cachedOffsetX!==t||this._cachedOffsetY!==i)&&(this._cachedOffsetX=t,this._cachedOffsetY=i,this._isMatrixDirty=!1,this._flagDescendantsAsMatrixDirty(),oB.ComposeToRef(-t,-i,this._rotation,this._scaleX,this._scaleY,this.parent?this.parent._transformMatrix:null,this._transformMatrix),this._transformMatrix.invertToRef(this._invertTransformMatrix),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure))}_renderHighlight(e){this.isHighlighted&&(e.save(),e.strokeStyle=this._highlightColor,e.lineWidth=this._highlightLineWidth,this._renderHighlightSpecific(e),e.restore())}_renderHighlightSpecific(e){e.strokeRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)}_getColor(e){return this.gradient?this.gradient.getCanvasGradient(e):this.color}_applyStates(e){this._isFontSizeInPercentage&&(this._fontSet=!0),this._host&&this._host.useSmallestIdeal&&!this._font&&(this._fontSet=!0),this._fontSet&&(this._prepareFont(),this._fontSet=!1),this._font&&(e.font=this._font),(this._color||this.gradient)&&(e.fillStyle=this._getColor(e)),lB.AllowAlphaInheritance?e.globalAlpha*=this._alpha:this._alphaSet&&(e.globalAlpha=this.parent&&!this.parent.renderToIntermediateTexture?this.parent.alpha*this._alpha:this._alpha)}_layout(e,t){if(!this.isDirty&&(!this.isVisible||this.notRenderable))return!1;if(this._isDirty||!this._cachedParentMeasure.isEqualsTo(e)){this.host._numLayoutCalls++,this._currentMeasure.addAndTransformToRef(this._transformMatrix,0|-this._paddingLeftInPixels,0|-this._paddingTopInPixels,0|this._paddingRightInPixels,0|this._paddingBottomInPixels,this._prevCurrentMeasureTransformedIntoGlobalSpace),t.save(),this._applyStates(t);let i=0;do{this._rebuildLayout=!1,this._processMeasures(e,t),i++}while(this._rebuildLayout&&i<3);i>=3&&Z.V.Error(`Layout cycle detected in GUI (Control name=${this.name}, uniqueId=${this.uniqueId})`),t.restore(),this.invalidateRect(),this._evaluateClippingState(e)}return this._wasDirty=this._isDirty,this._isDirty=!1,!0}_processMeasures(e,t){this._tempPaddingMeasure.copyFrom(e),this.parent&&this.parent.descendantsOnlyPadding&&(this._tempPaddingMeasure.left+=this.parent.paddingLeftInPixels,this._tempPaddingMeasure.top+=this.parent.paddingTopInPixels,this._tempPaddingMeasure.width-=this.parent.paddingLeftInPixels+this.parent.paddingRightInPixels,this._tempPaddingMeasure.height-=this.parent.paddingTopInPixels+this.parent.paddingBottomInPixels),this._currentMeasure.copyFrom(this._tempPaddingMeasure),this._preMeasure(this._tempPaddingMeasure,t),this._measure(),this._postMeasure(this._tempPaddingMeasure,t),this._computeAlignment(this._tempPaddingMeasure,t),this._currentMeasure.left=0|this._currentMeasure.left,this._currentMeasure.top=0|this._currentMeasure.top,this._currentMeasure.width=0|this._currentMeasure.width,this._currentMeasure.height=0|this._currentMeasure.height,this._additionalProcessing(this._tempPaddingMeasure,t),this._cachedParentMeasure.copyFrom(this._tempPaddingMeasure),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure),this.onDirtyObservable.hasObservers()&&this.onDirtyObservable.notifyObservers(this)}_evaluateClippingState(e){if(this._transform(),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure),this.parent&&this.parent.clipChildren){if(e.transformToRef(this.parent._transformMatrix,this._evaluatedParentMeasure),this._evaluatedMeasure.left>this._evaluatedParentMeasure.left+this._evaluatedParentMeasure.width)return void(this._isClipped=!0);if(this._evaluatedMeasure.left+this._evaluatedMeasure.widththis._evaluatedParentMeasure.top+this._evaluatedParentMeasure.height)return void(this._isClipped=!0);if(this._evaluatedMeasure.top+this._evaluatedMeasure.heightthis._currentMeasure.left+this._currentMeasure.width||tthis._currentMeasure.top+this._currentMeasure.height||(this.isPointerBlocker&&(this._host._shouldBlockPointer=!0),0))}_processPicking(e,t,i,r,s,n,o,a){return!(!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this._doNotRender||!this.contains(e,t)||(this._processObservables(r,e,t,i,s,n,o,a),0))}_onPointerMove(e,t,i,r){this.onPointerMoveObservable.notifyObservers(t,-1,e,this,r)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerMove(e,t,i,r)}_onPointerEnter(e,t){return!!this._isEnabled&&(!(this._enterCount>0)&&(-1===this._enterCount&&(this._enterCount=0),this._enterCount++,this.onPointerEnterObservable.notifyObservers(this,-1,e,this,t)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerEnter(e,t),!0))}_onPointerOut(e,t,i=!1){if(!i&&!this._isEnabled)return;this._enterCount=0;let r=!0;e.isAscendant(this)||(r=this.onPointerOutObservable.notifyObservers(this,-1,e,this,t)),r&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerOut(e,t,i)}_onPointerDown(e,t,i,r,s){return this._onPointerEnter(this,s),-1!==this.tabIndex&&(this.host.focusedControl=this),0===this._downCount&&(this._downCount++,this._downPointerIds[i]=!0,this.onPointerDownObservable.notifyObservers(new nB(t,r),-1,e,this,s)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerDown(e,t,i,r,s),s&&this.uniqueId!==this._host.rootContainer.uniqueId&&this._host._capturedPointerIds.add(s.event.pointerId),!0)}_onPointerUp(e,t,i,r,s,n){if(!this._isEnabled)return;this._downCount=0,delete this._downPointerIds[i];let o=s;s&&(this._enterCount>0||-1===this._enterCount)&&(this._host.usePointerTapForClickEvent||(o=this.onPointerClickObservable.notifyObservers(new nB(t,r),-1,e,this,n))),this.onPointerUpObservable.notifyObservers(new nB(t,r),-1,e,this,n)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerUp(e,t,i,r,o,n),n&&this.uniqueId!==this._host.rootContainer.uniqueId&&this._host._capturedPointerIds.delete(n.event.pointerId),this._host.usePointerTapForClickEvent&&this.isPointerBlocker&&(this._host._shouldBlockPointer=!1)}_onPointerPick(e,t,i,r,s,n){if(!this._host.usePointerTapForClickEvent)return!1;let o=s;return s&&(this._enterCount>0||-1===this._enterCount)&&(o=this.onPointerClickObservable.notifyObservers(new nB(t,r),-1,e,this,n)),this.onPointerUpObservable.notifyObservers(new nB(t,r),-1,e,this,n)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerPick(e,t,i,r,o,n),this._host.usePointerTapForClickEvent&&this.isPointerBlocker&&(this._host._shouldBlockPointer=!0),!0}_forcePointerUp(e=null){if(null!==e)this._onPointerUp(this,W.I9.Zero(),e,0,!0);else for(const e in this._downPointerIds)this._onPointerUp(this,W.I9.Zero(),+e,0,!0)}_onWheelScroll(e,t){this._isEnabled&&this.onWheelObservable.notifyObservers(new W.I9(e,t))&&null!=this.parent&&this.parent._onWheelScroll(e,t)}_onCanvasBlur(){}_processObservables(e,t,i,r,s,n,o,a){if(!this._isEnabled)return!1;if(this._dummyVector2.copyFromFloats(t,i),e===yi.Zp.POINTERMOVE){this._onPointerMove(this,this._dummyVector2,s,r);const e=this._host._lastControlOver[s];return e&&e!==this&&e._onPointerOut(this,r),e!==this&&this._onPointerEnter(this,r),this._host._lastControlOver[s]=this,!0}if(e===yi.Zp.POINTERDOWN)return this._onPointerDown(this,this._dummyVector2,s,n,r),this._host._registerLastControlDown(this,s),this._host._lastPickedControl=this,!0;if(e===yi.Zp.POINTERUP)return this._host._lastControlDown[s]&&this._host._lastControlDown[s]._onPointerUp(this,this._dummyVector2,s,n,!0,r),this._host.usePointerTapForClickEvent||delete this._host._lastControlDown[s],!0;if(e===yi.Zp.POINTERWHEEL){if(this._host._lastControlOver[s])return this._host._lastControlOver[s]._onWheelScroll(o,a),!0}else if(e===yi.Zp.POINTERTAP)return this._host._lastControlDown[s]&&this._host._lastControlDown[s]._onPointerPick(this,this._dummyVector2,s,n,!0,r),delete this._host._lastControlDown[s],!0;return!1}_getStyleProperty(e,t){const i=(this._style&&this._style[e])??this[e];return!i&&this.parent?this.parent._getStyleProperty(e,t):this.parent?i:t}_prepareFont(){(this._font||this._fontSet)&&(this._font=this._getStyleProperty("fontStyle","")+" "+this._getStyleProperty("fontWeight","")+" "+this.fontSizeInPixels+"px "+this._getStyleProperty("fontFamily","Arial"),this._fontOffset=lB._GetFontOffset(this._font,this._host?.getScene()?.getEngine()),this.getDescendants().forEach((e=>e._markAllAsDirty())))}isDimensionFullyDefined(e){return this.getDimension(e).isPixel}getDimension(e){return"width"===e?this._width:this._height}clone(e){const t={};this.serialize(t,!0);const i=new(Ue.S0.Instantiate("BABYLON.GUI."+t.className));return i.parse(t,e),i}parse(e,t,i){return this._urlRewriter=i,it.p.Parse((()=>this),e,null),this.name=e.name,this._parseFromContent(e,t??this._host),this}serialize(e,t=!1,i=!0){(this.isSerializable||t)&&(it.p.Serialize(this,e),e.name=this.name,e.className=this.getClassName(),i&&this._prepareFont(),this._fontFamily&&(e.fontFamily=this._fontFamily),this.fontSize&&(e.fontSize=this.fontSize),this.fontWeight&&(e.fontWeight=this.fontWeight),this.fontStyle&&(e.fontStyle=this.fontStyle),this._gradient&&(e.gradient={},this._gradient.serialize(e.gradient)),it.p.AppendSerializedAnimations(this,e))}_parseFromContent(e,t,i){if(e.fontFamily&&(this.fontFamily=e.fontFamily),e.fontSize&&(this.fontSize=e.fontSize),e.fontWeight&&(this.fontWeight=e.fontWeight),e.fontStyle&&(this.fontStyle=e.fontStyle),e.gradient){const t=Ue.S0.Instantiate("BABYLON.GUI."+e.gradient.className);this._gradient=new t,this._gradient?.parse(e.gradient)}if(e.animations){this.animations=[];for(let t=0;t-1&&this.linkWithMesh(null),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}static get HORIZONTAL_ALIGNMENT_LEFT(){return lB._HORIZONTAL_ALIGNMENT_LEFT}static get HORIZONTAL_ALIGNMENT_RIGHT(){return lB._HORIZONTAL_ALIGNMENT_RIGHT}static get HORIZONTAL_ALIGNMENT_CENTER(){return lB._HORIZONTAL_ALIGNMENT_CENTER}static get VERTICAL_ALIGNMENT_TOP(){return lB._VERTICAL_ALIGNMENT_TOP}static get VERTICAL_ALIGNMENT_BOTTOM(){return lB._VERTICAL_ALIGNMENT_BOTTOM}static get VERTICAL_ALIGNMENT_CENTER(){return lB._VERTICAL_ALIGNMENT_CENTER}static _GetFontOffset(e,t){if(lB._FontHeightSizes[e])return lB._FontHeightSizes[e];const i=t||he.q.LastCreatedEngine;if(!i)throw new Error("Invalid engine. Unable to create a canvas.");const r=i.getFontOffset(e);return lB._FontHeightSizes[e]=r,r}static Parse(e,t,i){const r=Ue.S0.Instantiate("BABYLON.GUI."+e.className),s=it.p.Parse((()=>{const e=new r;return e._urlRewriter=i,e}),e,null);return s.name=e.name,s._parseFromContent(e,t,i),s}static drawEllipse(e,t,i,r,s,n){n.translate(e,t),n.scale(i,r),n.beginPath(),n.arc(0,0,1,0,2*Math.PI*s,s<0),s>=1&&n.closePath(),n.scale(1/i,1/r),n.translate(-e,-t)}isReady(){return!0}}lB.AllowAlphaInheritance=!1,lB._ClipMeasure=new sB(0,0,0,0),lB._HORIZONTAL_ALIGNMENT_LEFT=0,lB._HORIZONTAL_ALIGNMENT_RIGHT=1,lB._HORIZONTAL_ALIGNMENT_CENTER=2,lB._VERTICAL_ALIGNMENT_TOP=0,lB._VERTICAL_ALIGNMENT_BOTTOM=1,lB._VERTICAL_ALIGNMENT_CENTER=2,lB._FontHeightSizes={},lB.AddHeader=()=>{},(0,je.Cg)([(0,$e.lK)()],lB.prototype,"metadata",void 0),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"isHitTestVisible",void 0),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"isPointerBlocker",void 0),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"isFocusInvisible",void 0),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"clipChildren",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"clipContent",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"useBitmapCache",void 0),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"shadowOffsetX",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"shadowOffsetY",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"shadowBlur",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"shadowColor",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"hoverCursor",void 0),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"fontOffset",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"alpha",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"isSerializable",void 0),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"scaleX",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"scaleY",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"rotation",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"transformCenterY",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"transformCenterX",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"horizontalAlignment",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"verticalAlignment",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"fixedRatio",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"fixedRatioMasterIsWidth",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"width",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"height",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"style",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"color",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"gradient",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"zIndex",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"notRenderable",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"isVisible",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"descendantsOnlyPadding",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"paddingLeft",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"paddingRight",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"paddingTop",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"paddingBottom",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"left",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"top",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"linkOffsetX",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"linkOffsetY",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"isEnabled",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"disabledColor",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"disabledColorItem",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"overlapGroup",void 0),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"overlapDeltaMultiplier",void 0),(0,X.Y5)("BABYLON.GUI.Control",lB);class hB extends lB{get renderToIntermediateTexture(){return this._renderToIntermediateTexture}set renderToIntermediateTexture(e){this._renderToIntermediateTexture!==e&&(this._renderToIntermediateTexture=e,this._markAsDirty())}get adaptHeightToChildren(){return this._adaptHeightToChildren}set adaptHeightToChildren(e){this._adaptHeightToChildren!==e&&(this._adaptHeightToChildren=e,e&&(this.height="100%"),this._markAsDirty())}get adaptWidthToChildren(){return this._adaptWidthToChildren}set adaptWidthToChildren(e){this._adaptWidthToChildren!==e&&(this._adaptWidthToChildren=e,e&&(this.width="100%"),this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get backgroundGradient(){return this._backgroundGradient}set backgroundGradient(e){this._backgroundGradient!==e&&(this._backgroundGradient=e,this._markAsDirty())}get children(){return this._children}get isReadOnly(){return this._isReadOnly}set isReadOnly(e){this._isReadOnly=e;for(const t of this._children)t.isReadOnly=e}constructor(e){super(e),this.name=e,this._children=new Array,this._measureForChildren=sB.Empty(),this._background="",this._backgroundGradient=null,this._adaptWidthToChildren=!1,this._adaptHeightToChildren=!1,this._renderToIntermediateTexture=!1,this._intermediateTexture=null,this.delegatePickingToChildren=!1,this.logLayoutCycleErrors=!1,this.maxLayoutCycle=3,this.onControlAddedObservable=new z.cP,this.onControlRemovedObservable=new z.cP,this._inverseTransformMatrix=oB.Identity(),this._inverseMeasure=new sB(0,0,0,0)}_getTypeName(){return"Container"}_flagDescendantsAsMatrixDirty(){for(const e of this.children)e._isClipped=!1,e._markMatrixAsDirty()}getChildByName(e){for(const t of this.children)if(t.name===e)return t;return null}getChildByType(e,t){for(const e of this.children)if(e.typeName===t)return e;return null}containsControl(e){return-1!==this.children.indexOf(e)}addControl(e){return e?(-1!==this._children.indexOf(e)||(e._link(this._host),e._markAllAsDirty(),this._reOrderControl(e),this._markAsDirty(),this.onControlAddedObservable.notifyObservers(e)),this):this}clearControls(){const e=this.children.slice();for(const t of e)this.removeControl(t);return this}removeControl(e){const t=this._children.indexOf(e);return-1!==t&&(this._children.splice(t,1),e.parent=null),e.linkWithMesh(null),this._host&&this._host._cleanControlAfterRemoval(e),this._markAsDirty(),this.onControlRemovedObservable.notifyObservers(e),this}_reOrderControl(e){const t=e.linkedMesh;this.removeControl(e);let i=!1;for(let t=0;te.zIndex){this._children.splice(t,0,e),i=!0;break}i||this._children.push(e),e.parent=this,t&&e.linkWithMesh(t),this._markAsDirty()}_offsetLeft(e){super._offsetLeft(e);for(const t of this._children)t._offsetLeft(e)}_offsetTop(e){super._offsetTop(e);for(const t of this._children)t._offsetTop(e)}_markAllAsDirty(){super._markAllAsDirty();for(let e=0;e=0&&(r+=this.paddingLeftInPixels+this.paddingRightInPixels,this.width!==r+"px"&&(this.parent?._markAsDirty(),this.width=r+"px",this._width.ignoreAdaptiveScaling=!0,this._rebuildLayout=!0)),this.adaptHeightToChildren&&s>=0&&(s+=this.paddingTopInPixels+this.paddingBottomInPixels,this.height!==s+"px"&&(this.parent?._markAsDirty(),this.height=s+"px",this._height.ignoreAdaptiveScaling=!0,this._rebuildLayout=!0)),this._postMeasure()}i++}while(this._rebuildLayout&&i=3&&this.logLayoutCycleErrors&&Z.V.Error(`Layout cycle detected in GUI (Container name=${this.name}, uniqueId=${this.uniqueId})`),t.restore(),this._isDirty&&(this.invalidateRect(),this._isDirty=!1),!0}_postMeasure(){}_draw(e,t){const i=this._renderToIntermediateTexture&&this._intermediateTexture,r=i?this._intermediateTexture.getContext():e;i&&(r.save(),r.translate(-this._currentMeasure.left,-this._currentMeasure.top),t?(this._transformMatrix.invertToRef(this._inverseTransformMatrix),t.transformToRef(this._inverseTransformMatrix,this._inverseMeasure),r.clearRect(this._inverseMeasure.left,this._inverseMeasure.top,this._inverseMeasure.width,this._inverseMeasure.height)):r.clearRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),this._localDraw(r),e.save(),this.clipChildren&&this._clipForChildren(r);for(const e of this._children)t&&!e._intersectsRect(t)||e._render(r,t);i&&(r.restore(),e.save(),e.globalAlpha=this.alpha,e.drawImage(r.canvas,this._currentMeasure.left,this._currentMeasure.top),e.restore()),e.restore()}getDescendantsToRef(e,t=!1,i){if(this.children)for(let r=0;r=0;r--){const s=this._children[r];if(s.isEnabled&&s.isHitTestVisible&&s.isVisible&&!s.notRenderable&&s.contains(e,t)){i=!0;break}}if(!i)return!1}for(let l=this._children.length-1;l>=0;l--){const h=this._children[l];if(h._processPicking(e,t,i,r,s,n,o,a))return h.hoverCursor&&this._host._changeCursor(h.hoverCursor),!0}return!!l&&!!this.isHitTestVisible&&this._processObservables(r,e,t,i,s,n,o,a)}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.copyFrom(this._currentMeasure)}_getAdaptDimTo(e){return"width"===e?this.adaptWidthToChildren:this.adaptHeightToChildren}isDimensionFullyDefined(e){if(this._getAdaptDimTo(e)){for(const t of this.children)if(!t.isDimensionFullyDefined(e))return!1;return!0}return super.isDimensionFullyDefined(e)}serialize(e,t=!1,i=!0){if(super.serialize(e,t,i),(this.isSerializable||t)&&(this.backgroundGradient&&(e.backgroundGradient={},this.backgroundGradient.serialize(e.backgroundGradient)),this.children.length)){e.children=[];for(const r of this.children)if(r.isSerializable||t){const s={};r.serialize(s,t,i),e.children.push(s)}}}dispose(){super.dispose();for(let e=this.children.length-1;e>=0;e--)this.children[e].dispose();this._intermediateTexture?.dispose()}_parseFromContent(e,t,i){if(super._parseFromContent(e,t,i),this._link(t),e.backgroundGradient){const t=Ue.S0.Instantiate("BABYLON.GUI."+e.backgroundGradient.className);this._backgroundGradient=new t,this._backgroundGradient?.parse(e.backgroundGradient)}if(e.children)for(const r of e.children)this.addControl(lB.Parse(r,t,i))}isReady(){for(const e of this.children)if(!e.isReady())return!1;return!0}}(0,je.Cg)([(0,$e.lK)()],hB.prototype,"delegatePickingToChildren",void 0),(0,je.Cg)([(0,$e.lK)()],hB.prototype,"renderToIntermediateTexture",null),(0,je.Cg)([(0,$e.lK)()],hB.prototype,"maxLayoutCycle",void 0),(0,je.Cg)([(0,$e.lK)()],hB.prototype,"adaptHeightToChildren",null),(0,je.Cg)([(0,$e.lK)()],hB.prototype,"adaptWidthToChildren",null),(0,je.Cg)([(0,$e.lK)()],hB.prototype,"background",null),(0,je.Cg)([(0,$e.lK)()],hB.prototype,"backgroundGradient",null),(0,X.Y5)("BABYLON.GUI.Container",hB);class cB extends hB{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}get cornerRadius(){return this._cornerRadius[0]}set cornerRadius(e){e<0&&(e=0),this._cornerRadius[0]===e&&this._cornerRadius[1]===e&&this._cornerRadius[2]===e&&this._cornerRadius[3]===e||(this._cornerRadius[0]=this._cornerRadius[1]=this._cornerRadius[2]=this._cornerRadius[3]=e,this._markAsDirty())}get cornerRadiusX(){return this._cornerRadius[0]}set cornerRadiusX(e){this._cornerRadius[0]!==e&&(this._cornerRadius[0]=e)}get cornerRadiusY(){return this._cornerRadius[1]}set cornerRadiusY(e){this._cornerRadius[1]!==e&&(this._cornerRadius[1]=e)}get cornerRadiusZ(){return this._cornerRadius[2]}set cornerRadiusZ(e){this._cornerRadius[2]!==e&&(this._cornerRadius[2]=e)}get cornerRadiusW(){return this._cornerRadius[3]}set cornerRadiusW(e){this._cornerRadius[3]!==e&&(this._cornerRadius[3]=e)}constructor(e){super(e),this.name=e,this._thickness=1,this._cornerRadius=[0,0,0,0],this._cachedRadius=[0,0,0,0]}_getTypeName(){return"Rectangle"}_computeAdditionalOffsetX(){let e=0;return 0===this._cornerRadius[0]&&0===this._cornerRadius[1]&&0===this._cornerRadius[2]&&0===this._cornerRadius[3]||(e+=1),this.thickness&&(e+=this.thickness/2),e}_computeAdditionalOffsetY(){let e=0;return 0===this._cornerRadius[0]&&0===this._cornerRadius[1]&&0===this._cornerRadius[2]&&0===this._cornerRadius[3]||(e+=1),this.thickness&&(e+=this.thickness/2),e}_getRectangleFill(e){return this._getBackgroundColor(e)}_localDraw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),(this._background||this._backgroundGradient)&&(e.fillStyle=this._getRectangleFill(e),0!==this._cornerRadius[0]||0!==this._cornerRadius[1]||0!==this._cornerRadius[2]||0!==this._cornerRadius[3]?(this._drawRoundedRect(e,this._thickness/2),e.fill()):e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),this._thickness&&((this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),(this.color||this.gradient)&&(e.strokeStyle=this.gradient?this.gradient.getCanvasGradient(e):this.color),e.lineWidth=this._thickness,0!==this._cornerRadius[0]||0!==this._cornerRadius[1]||0!==this._cornerRadius[2]||0!==this._cornerRadius[3]?(this._drawRoundedRect(e,this._thickness/2),e.stroke()):e.strokeRect(this._currentMeasure.left+this._thickness/2,this._currentMeasure.top+this._thickness/2,this._currentMeasure.width-this._thickness,this._currentMeasure.height-this._thickness)),e.restore()}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.width-=2*this._thickness,this._measureForChildren.height-=2*this._thickness,this._measureForChildren.left+=this._thickness,this._measureForChildren.top+=this._thickness}_drawRoundedRect(e,t=0){const i=this._currentMeasure.left+t,r=this._currentMeasure.top+t,s=this._currentMeasure.width-2*t,n=this._currentMeasure.height-2*t;for(let e=0;ei&&(i=t.width)}if(this._resizeToFit){if(0===this._textWrapping||this._forceResizeWidth){const e=Math.ceil(this._paddingLeftInPixels)+Math.ceil(this._paddingRightInPixels)+Math.ceil(i);e!==this._width.getValueInPixel(this._host,this._tempParentMeasure.width)&&(this._width.updateInPlace(e,JL.UNITMODE_PIXEL),this._rebuildLayout=!0)}let e=this._paddingTopInPixels+this._paddingBottomInPixels+this._fontOffset.height*this._lines.length|0;if(this._lines.length>0&&0!==this._lineSpacing.internalValue){let t=0;t=this._lineSpacing.isPixel?this._lineSpacing.getValue(this._host):this._lineSpacing.getValue(this._host)*this._height.getValueInPixel(this._host,this._cachedParentMeasure.height),e+=(this._lines.length-1)*t}e!==this._height.internalValue&&(this._height.updateInPlace(e,JL.UNITMODE_PIXEL),this._rebuildLayout=!0)}}_drawText(e,t,i,r){const s=this._currentMeasure.width;let n=0;switch(this._textHorizontalAlignment){case lB.HORIZONTAL_ALIGNMENT_LEFT:n=0;break;case lB.HORIZONTAL_ALIGNMENT_RIGHT:n=s-t;break;case lB.HORIZONTAL_ALIGNMENT_CENTER:n=(s-t)/2}(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(r.shadowColor=this.shadowColor,r.shadowBlur=this.shadowBlur,r.shadowOffsetX=this.shadowOffsetX,r.shadowOffsetY=this.shadowOffsetY),this.outlineWidth&&r.strokeText(e,this._currentMeasure.left+n,i),r.fillText(e,this._currentMeasure.left+n,i),this._underline&&this._drawLine(this._currentMeasure.left+n,i+3,this._currentMeasure.left+n+t,i+3,r),this._lineThrough&&this._drawLine(this._currentMeasure.left+n,i-this.fontSizeInPixels/3,this._currentMeasure.left+n+t,i-this.fontSizeInPixels/3,r)}_drawLine(e,t,i,r,s){if(s.beginPath(),s.lineWidth=Math.round(.05*this.fontSizeInPixels),s.moveTo(e,t),s.lineTo(i,r),this.outlineWidth&&this.applyOutlineToUnderline)s.stroke(),s.fill();else{const e=s.strokeStyle;s.strokeStyle=s.fillStyle,s.stroke(),s.strokeStyle=e}s.closePath()}_draw(e){e.save(),this._applyStates(e),this._renderLines(e),e.restore()}_applyStates(e){super._applyStates(e),this.outlineWidth&&(e.lineWidth=this.outlineWidth,e.strokeStyle=this.outlineColor,e.lineJoin="miter",e.miterLimit=2)}_breakLines(e,t,i){this._linesTemp.length=0;const r=4===this._textWrapping?this._parseHTMLText(e,t,i):this.text.split("\n");switch(this._textWrapping){case 1:for(const t of r)this._linesTemp.push(...this._parseLineWordWrap(t,e,i));break;case 2:for(const t of r)this._linesTemp.push(this._parseLineEllipsis(t,e,i));break;case 3:for(const s of r)this._linesTemp.push(...this._parseLineWordWrapEllipsis(s,e,t,i));break;default:for(const e of r)this._linesTemp.push(this._parseLine(e,i))}return this._linesTemp}_parseHTMLText(e,t,i){const r=[];this._htmlElement||(this._htmlElement=document.createElement("div"),document.body.appendChild(this._htmlElement));const s=this._htmlElement;s.textContent=this.text,s.style.font=i.font,s.style.position="absolute",s.style.visibility="hidden",s.style.top="-1000px",s.style.left="-1000px",this.adjustWordWrappingHTMLElement?.(s),s.style.width=e+"px",s.style.height=t+"px";const n=s.textContent;if(!n)return r;const o=s.childNodes[0],a=document.createRange();let l=0;for(const e of n){a.setStart(o,0),a.setEnd(o,l+1);const t=a.getClientRects().length-1;r[t]=(r[t]||"")+e,l++}return this.reuseHTMLForWordWrapping||(s.remove(),this._htmlElement=null),r}_parseLine(e="",t){return{text:e,width:this._getTextMetricsWidth(t.measureText(e))}}_getCharsToRemove(e,t,i){const r=e>t?e-t:0,s=e/i;return Math.max(Math.floor(r/s),1)}_parseLineEllipsis(e="",t,i){let r=this._getTextMetricsWidth(i.measureText(e)),s=this._getCharsToRemove(r,t,e.length);const n=Array.from&&Array.from(e);if(n)for(;n.length&&r>t;)n.splice(n.length-s,s),e=`${n.join("")}…`,r=this._getTextMetricsWidth(i.measureText(e)),s=this._getCharsToRemove(r,t,e.length);else{for(;e.length>2&&r>t;)e=e.slice(0,-s),r=this._getTextMetricsWidth(i.measureText(e+"…")),s=this._getCharsToRemove(r,t,e.length);e+="…"}return{text:e,width:r}}_getTextMetricsWidth(e){return void 0!==e.actualBoundingBoxLeft?Math.abs(e.actualBoundingBoxLeft)+Math.abs(e.actualBoundingBoxRight):e.width}_parseLineWordWrap(e="",t,i){const r=[],s=this.wordSplittingFunction?this.wordSplittingFunction(e):e.split(this._wordDivider);let n=this._getTextMetricsWidth(i.measureText(e));for(let o=0;o0?e+this._wordDivider+s[o]:s[0],l=this._getTextMetricsWidth(i.measureText(a));l>t&&o>0?(r.push({text:e,width:n}),e=s[o],n=this._getTextMetricsWidth(i.measureText(e))):(n=l,e=a)}return r.push({text:e,width:n}),r}_parseLineWordWrapEllipsis(e="",t,i,r){const s=this._parseLineWordWrap(e,t,r);for(let e=1;e<=s.length;e++)if(this._computeHeightForLinesOf(e)>i&&e>1){const i=s[e-2],n=s[e-1];s[e-2]=this._parseLineEllipsis(i.text+this._wordDivider+n.text,t,r);const o=s.length-e+1;for(let e=0;e0&&0!==this._lineSpacing.internalValue){let i=0;i=this._lineSpacing.isPixel?this._lineSpacing.getValue(this._host):this._lineSpacing.getValue(this._host)*this._height.getValueInPixel(this._host,this._cachedParentMeasure.height),t+=(e-1)*i}return t}isDimensionFullyDefined(e){return!!this.resizeToFit||super.isDimensionFullyDefined(e)}computeExpectedHeight(){if(this.text&&this.widthInPixels){const e=he.q.LastCreatedEngine?.createCanvas(0,0).getContext("2d");if(e){this._applyStates(e),this._fontOffset||(this._fontOffset=lB._GetFontOffset(e.font,this._host.getScene()?.getEngine()));const t=this._lines?this._lines:this._breakLines(this.widthInPixels-this._paddingLeftInPixels-this._paddingRightInPixels,this.heightInPixels-this._paddingTopInPixels-this._paddingBottomInPixels,e);return this._computeHeightForLinesOf(t.length)}}return 0}dispose(){super.dispose(),this.onTextChangedObservable.clear(),this._htmlElement?.remove(),this._htmlElement=null}}(0,je.Cg)([(0,$e.lK)()],dB.prototype,"resizeToFit",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"textWrapping",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"text",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"textHorizontalAlignment",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"textVerticalAlignment",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"lineSpacing",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"outlineWidth",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"underline",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"lineThrough",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"applyOutlineToUnderline",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"outlineColor",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"wordDivider",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"forceResizeWidth",null),(0,X.Y5)("BABYLON.GUI.TextBlock",dB);class fB extends lB{get isLoaded(){return this._loaded}isReady(){return this.isLoaded}get detectPointerOnOpaqueOnly(){return this._detectPointerOnOpaqueOnly}set detectPointerOnOpaqueOnly(e){this._detectPointerOnOpaqueOnly!==e&&(this._detectPointerOnOpaqueOnly=e)}get sliceLeft(){return this._sliceLeft}set sliceLeft(e){this._sliceLeft!==e&&(this._sliceLeft=e,this._markAsDirty())}get sliceRight(){return this._sliceRight}set sliceRight(e){this._sliceRight!==e&&(this._sliceRight=e,this._markAsDirty())}get sliceTop(){return this._sliceTop}set sliceTop(e){this._sliceTop!==e&&(this._sliceTop=e,this._markAsDirty())}get sliceBottom(){return this._sliceBottom}set sliceBottom(e){this._sliceBottom!==e&&(this._sliceBottom=e,this._markAsDirty())}get sourceLeft(){return this._sourceLeft}set sourceLeft(e){this._sourceLeft!==e&&(this._sourceLeft=e,this._markAsDirty())}get sourceTop(){return this._sourceTop}set sourceTop(e){this._sourceTop!==e&&(this._sourceTop=e,this._markAsDirty())}get sourceWidth(){return this._sourceWidth}set sourceWidth(e){this._sourceWidth!==e&&(this._sourceWidth=e,this._markAsDirty())}get sourceHeight(){return this._sourceHeight}set sourceHeight(e){this._sourceHeight!==e&&(this._sourceHeight=e,this._markAsDirty())}get imageWidth(){return this._imageWidth}get imageHeight(){return this._imageHeight}get populateNinePatchSlicesFromImage(){return this._populateNinePatchSlicesFromImage}set populateNinePatchSlicesFromImage(e){this._populateNinePatchSlicesFromImage!==e&&(this._populateNinePatchSlicesFromImage=e,this._populateNinePatchSlicesFromImage&&this._loaded&&this._extractNinePatchSliceDataFromImage())}get isSVG(){return this._isSVG}get svgAttributesComputationCompleted(){return this._svgAttributesComputationCompleted}get autoScale(){return this._autoScale}set autoScale(e){this._autoScale!==e&&(this._autoScale=e,e&&this._loaded&&this.synchronizeSizeWithContent())}get stretch(){return this._stretch}set stretch(e){this._stretch!==e&&(this._stretch=e,this._markAsDirty())}_rotate90(e,t=!1){const i=this._domImage.width,r=this._domImage.height,s=this._host?.getScene()?.getEngine()||he.q.LastCreatedEngine;if(!s)throw new Error("Invalid engine. Unable to create a canvas.");const n=s.createCanvas(r,i),o=n.getContext("2d");o.translate(n.width/2,n.height/2),o.rotate(e*Math.PI/2),o.drawImage(this._domImage,0,0,i,r,-i/2,-r/2,i,r);const a=n.toDataURL("image/jpg"),l=new fB(this.name+"rotated",a);return t&&(l._stretch=this._stretch,l._autoScale=this._autoScale,l._cellId=this._cellId,l._cellWidth=e%1?this._cellHeight:this._cellWidth,l._cellHeight=e%1?this._cellWidth:this._cellHeight),this._handleRotationForSVGImage(this,l,e),this._imageDataCache.data=null,l}_handleRotationForSVGImage(e,t,i){e._isSVG&&(e._svgAttributesComputationCompleted?(this._rotate90SourceProperties(e,t,i),this._markAsDirty()):e.onSVGAttributesComputedObservable.addOnce((()=>{this._rotate90SourceProperties(e,t,i),this._markAsDirty()})))}_rotate90SourceProperties(e,t,i){let r=e.sourceLeft,s=e.sourceTop,n=e.domImage.width,o=e.domImage.height,a=r,l=s,h=e.sourceWidth,c=e.sourceHeight;if(0!=i){const e=i<0?-1:1;i%=4;for(let t=0;t127&&-1===this._sliceLeft)this._sliceLeft=t;else if(e<127&&this._sliceLeft>-1){this._sliceRight=t;break}}this._sliceTop=-1,this._sliceBottom=-1;for(let i=0;i127&&-1===this._sliceTop)this._sliceTop=i;else if(t<127&&this._sliceTop>-1){this._sliceBottom=i;break}}}set domImage(e){this._domImage=e,this._loaded=!1,this._imageDataCache.data=null,this._domImage.width?this._onImageLoaded():this._domImage.onload=()=>{this._onImageLoaded()}}get domImage(){return this._domImage}_onImageLoaded(){this._imageDataCache.data=null,this._imageWidth=this._domImage.width,this._imageHeight=this._domImage.height,this._loaded=!0,this._populateNinePatchSlicesFromImage&&this._extractNinePatchSliceDataFromImage(),this._autoScale&&this.synchronizeSizeWithContent(),this.onImageLoadedObservable.notifyObservers(this),this._markAsDirty()}get source(){return this._source}static ResetImageCache(){fB.SourceImgCache.clear()}_removeCacheUsage(e){const t=e&&fB.SourceImgCache.get(e);if(t){t.timesUsed-=1;const i=t.img;i.parentNode&&i.parentNode.removeChild(i),0===t.timesUsed&&fB.SourceImgCache.delete(e)}}set source(e){if(this._urlRewriter&&e&&(e=this._urlRewriter(e)),this._source===e)return;this._removeCacheUsage(this._source),this._loaded=!1,this._source=e,this._imageDataCache.data=null,e&&(e=this._svgCheck(e));const t=this._host?.getScene()?.getEngine()||he.q.LastCreatedEngine;if(!t)throw new Error("Invalid engine. Unable to create a canvas.");if(e&&fB.SourceImgCache.has(e)){const t=fB.SourceImgCache.get(e);return this._domImage=t.img,t.timesUsed+=1,void(t.loaded?this._onImageLoaded():t.waitingForLoadCallback.push(this._onImageLoaded.bind(this)))}this._domImage=t.createCanvasImage();const i=this._domImage;let r=!1;i.style&&this._source?.endsWith(".svg")&&(i.style.visibility="hidden",i.style.position="absolute",i.style.top="0",t.getRenderingCanvas()?.parentNode?.appendChild(i),r=!0),e&&fB.SourceImgCache.set(e,{img:this._domImage,timesUsed:1,loaded:!1,waitingForLoadCallback:[this._onImageLoaded.bind(this)]}),this._domImage.onload=()=>{if(e){const t=fB.SourceImgCache.get(e);if(t){t.loaded=!0;for(const e of t.waitingForLoadCallback)e();return t.waitingForLoadCallback.length=0,void(r&&i.remove())}}this._onImageLoaded(),r&&i.remove()},e&&(Ue.S0.SetCorsBehavior(e,this._domImage),Ue.S0.SetReferrerPolicyBehavior(this.referrerPolicy,this._domImage),this._domImage.src=e)}_svgCheck(e){if(window.SVGSVGElement&&-1!==e.search(/(\.svg|\.svg?[?|#].*)$/gi)&&e.indexOf("#")===e.lastIndexOf("#")){this._isSVG=!0;const t=e.split("#")[0],i=e.split("#")[1],r=document.body.querySelector('object[data="'+t+'"]');if(r){const t=r.contentDocument;if(t&&t.documentElement){const s=t.documentElement.getAttribute("viewBox"),n=Number(t.documentElement.getAttribute("width")),o=Number(t.documentElement.getAttribute("height"));if(t.getElementById(i)&&s&&n&&o)return this._getSVGAttribs(r,i),e}r.addEventListener("load",(()=>{this._getSVGAttribs(r,i)}))}else{const e=document.createElement("object");e.data=t,e.type="image/svg+xml",e.width="0%",e.height="0%",document.body.appendChild(e),e.onload=()=>{const e=document.body.querySelector('object[data="'+t+'"]');e&&this._getSVGAttribs(e,i)}}return t}return e}_getSVGAttribs(e,t){const i=e.contentDocument;if(i&&i.documentElement){const e=i.documentElement.getAttribute("viewBox"),r=Number(i.documentElement.getAttribute("width")),s=Number(i.documentElement.getAttribute("height")),n=i.getElementById(t);if(e&&r&&s&&n){const t=Number(e.split(" ")[2]),i=Number(e.split(" ")[3]),o=n.getBBox();let a=1,l=1,h=0,c=0;const u=n.transform.baseVal.consolidate().matrix;n.transform&&n.transform.baseVal.consolidate()&&(a=u.a,l=u.d,h=u.e,c=u.f),this.sourceLeft=(a*o.x+h)*r/t,this.sourceTop=(l*o.y+c)*s/i,this.sourceWidth=o.width*a*(r/t),this.sourceHeight=o.height*l*(s/i),this._svgAttributesComputationCompleted=!0,this.onSVGAttributesComputedObservable.notifyObservers(this)}}}get cellWidth(){return this._cellWidth}set cellWidth(e){this._cellWidth!==e&&(this._cellWidth=e,this._markAsDirty())}get cellHeight(){return this._cellHeight}set cellHeight(e){this._cellHeight!==e&&(this._cellHeight=e,this._markAsDirty())}get cellId(){return this._cellId}set cellId(e){this._cellId!==e&&(this._cellId=e,this._markAsDirty())}constructor(e,t=null){super(e),this.name=e,this._workingCanvas=null,this._loaded=!1,this._stretch=fB.STRETCH_FILL,this._source=null,this._autoScale=!1,this._sourceLeft=0,this._sourceTop=0,this._sourceWidth=0,this._sourceHeight=0,this._svgAttributesComputationCompleted=!1,this._isSVG=!1,this._cellWidth=0,this._cellHeight=0,this._cellId=-1,this._populateNinePatchSlicesFromImage=!1,this._imageDataCache={data:null,key:""},this.onImageLoadedObservable=new z.cP,this.onSVGAttributesComputedObservable=new z.cP,this.source=t}contains(e,t){if(!super.contains(e,t))return!1;if(!this._detectPointerOnOpaqueOnly||!this._workingCanvas)return!0;const i=0|this._currentMeasure.width,r=0|this._currentMeasure.height,s=i+"_"+r;let n=this._imageDataCache.data;if(!n||this._imageDataCache.key!==s){const e=this._workingCanvas.getContext("2d");this._imageDataCache.data=n=e.getImageData(0,0,i,r).data,this._imageDataCache.key=s}return n[4*((e=e-this._currentMeasure.left|0)+(t=t-this._currentMeasure.top|0)*i)+3]>0}_getTypeName(){return"Image"}synchronizeSizeWithContent(){this._loaded&&(this.width=this._domImage.width+"px",this.height=this._domImage.height+"px")}_processMeasures(e,t){if(this._loaded)switch(this._stretch){case fB.STRETCH_NONE:case fB.STRETCH_FILL:case fB.STRETCH_UNIFORM:case fB.STRETCH_NINE_PATCH:break;case fB.STRETCH_EXTEND:this._autoScale&&this.synchronizeSizeWithContent(),this.parent&&this.parent.parent&&(this.parent.adaptWidthToChildren=!0,this.parent.adaptHeightToChildren=!0)}super._processMeasures(e,t)}_prepareWorkingCanvasForOpaqueDetection(){if(!this._detectPointerOnOpaqueOnly)return;const e=this._currentMeasure.width,t=this._currentMeasure.height;if(!this._workingCanvas){const i=this._host?.getScene()?.getEngine()||he.q.LastCreatedEngine;if(!i)throw new Error("Invalid engine. Unable to create a canvas.");this._workingCanvas=i.createCanvas(e,t)}this._workingCanvas.getContext("2d").clearRect(0,0,e,t)}_drawImage(e,t,i,r,s,n,o,a,l){if(e.drawImage(this._domImage,t,i,r,s,n,o,a,l),!this._detectPointerOnOpaqueOnly)return;const h=e.getTransform(),c=this._workingCanvas.getContext("2d");c.save();const u=n-this._currentMeasure.left,d=o-this._currentMeasure.top;c.setTransform(h.a,h.b,h.c,h.d,(u+a)/2,(d+l)/2),c.translate(-(u+a)/2,-(d+l)/2),c.drawImage(this._domImage,t,i,r,s,u,d,a,l),c.restore()}_draw(e){let t,i,r,s;if(e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),-1==this.cellId)t=this._sourceLeft,i=this._sourceTop,r=this._sourceWidth?this._sourceWidth:this._imageWidth,s=this._sourceHeight?this._sourceHeight:this._imageHeight;else{const e=this._domImage.naturalWidth/this.cellWidth,n=this.cellId/e|0,o=this.cellId%e;t=this.cellWidth*o,i=this.cellHeight*n,r=this.cellWidth,s=this.cellHeight}if(this._prepareWorkingCanvasForOpaqueDetection(),this._applyStates(e),this._loaded)switch(this._stretch){case fB.STRETCH_NONE:case fB.STRETCH_FILL:this._drawImage(e,t,i,r,s,this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height);break;case fB.STRETCH_UNIFORM:{const n=this._currentMeasure.width/r,o=this._currentMeasure.height/s,a=Math.min(n,o),l=(this._currentMeasure.width-r*a)/2,h=(this._currentMeasure.height-s*a)/2;this._drawImage(e,t,i,r,s,this._currentMeasure.left+l,this._currentMeasure.top+h,r*a,s*a);break}case fB.STRETCH_EXTEND:this._drawImage(e,t,i,r,s,this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height);break;case fB.STRETCH_NINE_PATCH:this._renderNinePatch(e,t,i,r,s)}e.restore()}_renderNinePatch(e,t,i,r,s){const n=this.host.idealWidth?this._width.getValue(this.host)/this.host.idealWidth:this.host.idealHeight?this._height.getValue(this.host)/this.host.idealHeight:1,o=this._sliceLeft,a=this._sliceTop,l=s-this._sliceBottom,h=r-this._sliceRight,c=this._sliceRight-this._sliceLeft,u=this._sliceBottom-this._sliceTop,d=Math.round(o*n),f=Math.round(a*n),p=Math.round(l*n),_=Math.round(h*n),m=Math.round(this._currentMeasure.width)-_-d+2,g=Math.round(this._currentMeasure.height)-p-f+2,v=Math.round(this._currentMeasure.left)+d-1,x=Math.round(this._currentMeasure.top)+f-1,b=Math.round(this._currentMeasure.left+this._currentMeasure.width)-_,S=Math.round(this._currentMeasure.top+this._currentMeasure.height)-p;this._drawImage(e,t,i,o,a,this._currentMeasure.left,this._currentMeasure.top,d,f),this._drawImage(e,t+this._sliceLeft,i,c,a,v+1,this._currentMeasure.top,m-2,f),this._drawImage(e,t+this._sliceRight,i,h,a,b,this._currentMeasure.top,_,f),this._drawImage(e,t,i+this._sliceTop,o,u,this._currentMeasure.left,x+1,d,g-2),this._drawImage(e,t+this._sliceLeft,i+this._sliceTop,c,u,v+1,x+1,m-2,g-2),this._drawImage(e,t+this._sliceRight,i+this._sliceTop,h,u,b,x+1,_,g-2),this._drawImage(e,t,i+this._sliceBottom,o,l,this._currentMeasure.left,S,d,p),this._drawImage(e,t+this.sliceLeft,i+this._sliceBottom,c,l,v+1,S,m-2,p),this._drawImage(e,t+this._sliceRight,i+this._sliceBottom,h,l,b,S,_,p)}dispose(){super.dispose(),this.onImageLoadedObservable.clear(),this.onSVGAttributesComputedObservable.clear(),this._removeCacheUsage(this._source)}}fB.SourceImgCache=new Map,fB.STRETCH_NONE=0,fB.STRETCH_FILL=1,fB.STRETCH_UNIFORM=2,fB.STRETCH_EXTEND=3,fB.STRETCH_NINE_PATCH=4,(0,je.Cg)([(0,$e.lK)()],fB.prototype,"detectPointerOnOpaqueOnly",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"sliceLeft",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"sliceRight",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"sliceTop",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"sliceBottom",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"sourceLeft",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"sourceTop",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"sourceWidth",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"sourceHeight",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"populateNinePatchSlicesFromImage",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"autoScale",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"stretch",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"source",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"cellWidth",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"cellHeight",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"cellId",null),(0,X.Y5)("BABYLON.GUI.Image",fB);class pB extends cB{get image(){return this._image}get textBlock(){return this._textBlock}constructor(e){super(e),this.name=e,this.thickness=1,this.isPointerBlocker=!0;let t=null;this.pointerEnterAnimation=()=>{t=this.alpha,this.alpha-=.1},this.pointerOutAnimation=()=>{null!==t&&(this.alpha=t)},this.pointerDownAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05}}_getTypeName(){return"Button"}_processPicking(e,t,i,r,s,n,o,a){if(!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this.notRenderable)return!1;if(!super.contains(e,t))return!1;if(this.delegatePickingToChildren){let i=!1;for(let r=this._children.length-1;r>=0;r--){const s=this._children[r];if(s.isEnabled&&s.isHitTestVisible&&s.isVisible&&!s.notRenderable&&s.contains(e,t)){i=!0;break}}if(!i)return!1}return this._processObservables(r,e,t,i,s,n,o,a),!0}_onPointerEnter(e,t){return!!super._onPointerEnter(e,t)&&(!this.isReadOnly&&this.pointerEnterAnimation&&this.pointerEnterAnimation(),!0)}_onPointerOut(e,t,i=!1){!this.isReadOnly&&this.pointerOutAnimation&&this.pointerOutAnimation(),super._onPointerOut(e,t,i)}_onPointerDown(e,t,i,r,s){return!!super._onPointerDown(e,t,i,r,s)&&(!this.isReadOnly&&this.pointerDownAnimation&&this.pointerDownAnimation(),!0)}_getRectangleFill(e){return this.isEnabled?this._getBackgroundColor(e):this._disabledColor}_onPointerUp(e,t,i,r,s,n){!this.isReadOnly&&this.pointerUpAnimation&&this.pointerUpAnimation(),super._onPointerUp(e,t,i,r,s,n)}serialize(e,t){super.serialize(e,t),(this.isSerializable||t)&&(this._textBlock&&(e.textBlockName=this._textBlock.name),this._image&&(e.imageName=this._image.name))}_parseFromContent(e,t){super._parseFromContent(e,t),e.textBlockName&&(this._textBlock=this.getChildByName(e.textBlockName)),e.imageName&&(this._image=this.getChildByName(e.imageName))}static CreateImageButton(e,t,i){const r=new this(e),s=new dB(e+"_button",t);s.textWrapping=!0,s.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_CENTER,s.paddingLeft="20%",r.addControl(s);const n=new fB(e+"_icon",i);return n.width="20%",n.stretch=fB.STRETCH_UNIFORM,n.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,r.addControl(n),r._image=n,r._textBlock=s,r}static CreateImageOnlyButton(e,t){const i=new this(e),r=new fB(e+"_icon",t);return r.stretch=fB.STRETCH_FILL,r.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,i.addControl(r),i._image=r,i}static CreateSimpleButton(e,t){const i=new this(e),r=new dB(e+"_button",t);return r.textWrapping=!0,r.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_CENTER,i.addControl(r),i._textBlock=r,i}static CreateImageWithCenterTextButton(e,t,i){const r=new this(e),s=new fB(e+"_icon",i);s.stretch=fB.STRETCH_FILL,r.addControl(s);const n=new dB(e+"_button",t);return n.textWrapping=!0,n.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_CENTER,r.addControl(n),r._image=s,r._textBlock=n,r}}(0,X.Y5)("BABYLON.GUI.Button",pB);class _B extends hB{get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,this._markAsDirty())}get spacing(){return this._spacing}set spacing(e){this._spacing!==e&&(this._spacing=e,this._markAsDirty())}set width(e){this._doNotTrackManualChanges||(this._manualWidth=!0),this._width.toString(this._host)!==e&&this._width.fromString(e)&&this._markAsDirty()}get width(){return this._width.toString(this._host)}set height(e){this._doNotTrackManualChanges||(this._manualHeight=!0),this._height.toString(this._host)!==e&&this._height.fromString(e)&&this._markAsDirty()}get height(){return this._height.toString(this._host)}constructor(e){super(e),this.name=e,this._isVertical=!0,this._manualWidth=!1,this._manualHeight=!1,this._doNotTrackManualChanges=!1,this._spacing=0,this.ignoreLayoutWarnings=!1}_getTypeName(){return"StackPanel"}_preMeasure(e,t){for(const e of this._children)this._isVertical?e.verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP:e.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT;super._preMeasure(e,t)}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.copyFrom(e),this._measureForChildren.left=this._currentMeasure.left,this._measureForChildren.top=this._currentMeasure.top,this.isVertical&&!this._manualWidth||(this._measureForChildren.width=this._currentMeasure.width),(this.isVertical||this._manualHeight)&&(this._measureForChildren.height=this._currentMeasure.height)}_postMeasure(){let e=0,t=0;const i=this._children.length;for(let r=0;r=0?Math.min(e,this._characters.length):this._characters.length+Math.max(e,-this._characters.length),void 0===t?t=this._characters.length-e:(isNaN(t)||t<0)&&(t=0);const i=[];for(;--t>=0;)i[t]=this._characters[e+t];return i.join("")}return this._text.substring(e,t?t+e:void 0)}substring(e,t){if(this._characters){isNaN(e)?e=0:e>this._characters.length?e=this._characters.length:e<0&&(e=0),void 0===t?t=this._characters.length:isNaN(t)?t=0:t>this._characters.length?t=this._characters.length:t<0&&(t=0);const i=[];let r=0;for(;e{switch(e.type){case yu.COPY:this._onCopyText(e.event),this.onTextCopyObservable.notifyObservers(this);break;case yu.CUT:this._onCutText(e.event),this.onTextCutObservable.notifyObservers(this);break;case yu.PASTE:this._onPasteText(e.event),this.onTextPasteObservable.notifyObservers(this);break;default:return}}));const e=this._host.getScene();e&&(this._onPointerDblTapObserver=e.onPointerObservable.add((e=>{this._isFocused&&e.type===yi.Zp.POINTERDOUBLETAP&&this._processDblClick(e)}))),this._onFocusSelectAll&&this.selectAllText()}_getTypeName(){return"InputText"}keepsFocusWith(){return this._connectedVirtualKeyboard?[this._connectedVirtualKeyboard]:null}processKey(e,t,i){if(!this.isReadOnly&&(!i||!i.ctrlKey&&!i.metaKey||67!==e&&86!==e&&88!==e)){if(i&&(i.ctrlKey||i.metaKey)&&65===e)return this.selectAllText(),void i.preventDefault();switch(e){case 32:t=" ";break;case 191:i&&i.preventDefault();break;case 8:if(this._textWrapper.text&&this._textWrapper.length>0){if(this.isTextHighlightOn)return this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this._blinkIsEven=!1,void(i&&i.preventDefault());if(0===this._cursorOffset)this.text=this._textWrapper.substring(0,this._textWrapper.length-1);else{const e=this._textWrapper.length-this._cursorOffset;e>0&&(this._textWrapper.removePart(e-1,e),this._textHasChanged())}}return void(i&&i.preventDefault());case 46:if(this.isTextHighlightOn)return this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,void(i&&i.preventDefault());if(this._textWrapper.text&&this._textWrapper.length>0&&this._cursorOffset>0){const e=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(e,e+1),this._textHasChanged(),this._cursorOffset--}return void(i&&i.preventDefault());case 13:return this._host.focusedControl=null,void(this.isTextHighlightOn=!1);case 35:return this._cursorOffset=0,this._blinkIsEven=!1,this.isTextHighlightOn=!1,void this._markAsDirty();case 36:return this._cursorOffset=this._textWrapper.length,this._blinkIsEven=!1,this.isTextHighlightOn=!1,void this._markAsDirty();case 37:if(this._cursorOffset++,this._cursorOffset>this._textWrapper.length&&(this._cursorOffset=this._textWrapper.length),i&&i.shiftKey){if(this._blinkIsEven=!1,i.ctrlKey||i.metaKey){if(!this.isTextHighlightOn){if(this._textWrapper.length===this._cursorOffset)return;this._endHighlightIndex=this._textWrapper.length-this._cursorOffset+1}return this._startHighlightIndex=0,this._cursorIndex=this._textWrapper.length-this._endHighlightIndex,this._cursorOffset=this._textWrapper.length,this.isTextHighlightOn=!0,void this._markAsDirty()}return this.isTextHighlightOn?-1===this._cursorIndex&&(this._cursorIndex=this._textWrapper.length-this._endHighlightIndex,this._cursorOffset=0===this._startHighlightIndex?this._textWrapper.length:this._textWrapper.length-this._startHighlightIndex+1):(this.isTextHighlightOn=!0,this._cursorIndex=this._cursorOffset>=this._textWrapper.length?this._textWrapper.length:this._cursorOffset-1),this._cursorIndexthis._cursorOffset?(this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex):this.isTextHighlightOn=!1,void this._markAsDirty()}return this.isTextHighlightOn&&(this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this.isTextHighlightOn=!1),i&&(i.ctrlKey||i.metaKey)&&(this._cursorOffset=this._textWrapper.length,i.preventDefault()),this._blinkIsEven=!1,this.isTextHighlightOn=!1,this._cursorIndex=-1,void this._markAsDirty();case 39:if(this._cursorOffset--,this._cursorOffset<0&&(this._cursorOffset=0),i&&i.shiftKey){if(this._blinkIsEven=!1,i.ctrlKey||i.metaKey){if(!this.isTextHighlightOn){if(0===this._cursorOffset)return;this._startHighlightIndex=this._textWrapper.length-this._cursorOffset-1}return this._endHighlightIndex=this._textWrapper.length,this.isTextHighlightOn=!0,this._cursorIndex=this._textWrapper.length-this._startHighlightIndex,this._cursorOffset=0,void this._markAsDirty()}return this.isTextHighlightOn?-1===this._cursorIndex&&(this._cursorIndex=this._textWrapper.length-this._startHighlightIndex,this._cursorOffset=this._textWrapper.length===this._endHighlightIndex?0:this._textWrapper.length-this._endHighlightIndex-1):(this.isTextHighlightOn=!0,this._cursorIndex=this._cursorOffset<=0?0:this._cursorOffset+1),this._cursorIndexthis._cursorOffset?(this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex):this.isTextHighlightOn=!1,void this._markAsDirty()}return this.isTextHighlightOn&&(this._cursorOffset=this._textWrapper.length-this._endHighlightIndex,this.isTextHighlightOn=!1),i&&(i.ctrlKey||i.metaKey)&&(this._cursorOffset=0,i.preventDefault()),this._blinkIsEven=!1,this.isTextHighlightOn=!1,this._cursorIndex=-1,void this._markAsDirty()}if(32===e&&(t=i?.key??" "),this._deadKey="Dead"===t,t&&(-1===e||32===e||34===e||39===e||e>47&&e<64||e>64&&e<91||e>159&&e<193||e>218&&e<223||e>95&&e<112)&&(this._currentKey=t,this.onBeforeKeyAddObservable.notifyObservers(this),t=this._currentKey,this._addKey&&!this._deadKey))if(this.isTextHighlightOn)this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex,t),this._textHasChanged(),this._cursorOffset=this._textWrapper.length-(this._startHighlightIndex+1),this.isTextHighlightOn=!1,this._blinkIsEven=!1,this._markAsDirty();else if(0===this._cursorOffset)this.text+=this._deadKey&&i?.key?i.key:t;else{const e=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(e,e,t),this._textHasChanged()}}}_updateValueFromCursorIndex(e){if(this._blinkIsEven=!1,-1===this._cursorIndex)this._cursorIndex=e;else if(this._cursorIndexthis._cursorOffset))return this.isTextHighlightOn=!1,void this._markAsDirty();this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex}this.isTextHighlightOn=!0,this._markAsDirty()}_processDblClick(e){let t,i;this._startHighlightIndex=this._textWrapper.length-this._cursorOffset,this._endHighlightIndex=this._startHighlightIndex;do{i=this._endHighlightIndex0&&this._textWrapper.isWord(this._startHighlightIndex-1)?--this._startHighlightIndex:0}while(t||i);this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this.isTextHighlightOn=!0,this._clickedCoordinate=null,this._blinkIsEven=!0,this._cursorIndex=-1,this._markAsDirty()}selectAllText(){this._blinkIsEven=!0,this.isTextHighlightOn=!0,this._startHighlightIndex=0,this._endHighlightIndex=this._textWrapper.length,this._cursorOffset=this._textWrapper.length,this._cursorIndex=-1,this._markAsDirty()}processKeyboard(e){this.processKey(e.keyCode,e.key,e),super.processKeyboard(e)}_onCopyText(e){this.isTextHighlightOn=!1;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText}_onCutText(e){if(this._highlightedText){this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText,this._highlightedText=""}}_onPasteText(e){let t="";t=e.clipboardData&&-1!==e.clipboardData.types.indexOf("text/plain")?e.clipboardData.getData("text/plain"):this._host.clipboardData;const i=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(i,i,t),this._textHasChanged()}_draw(e){e.save(),this._applyStates(e),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._isFocused?this._focusedBackground&&(e.fillStyle=this._isEnabled?this._focusedBackground:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)):this._background&&(e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._fontOffset&&!this._wasDirty||(this._fontOffset=lB._GetFontOffset(e.font,this._host.getScene()?.getEngine()));const t=this._currentMeasure.left+this._margin.getValueInPixel(this._host,this._tempParentMeasure.width);this.color&&(e.fillStyle=this.color);let i=this._beforeRenderText(this._textWrapper);this._isFocused||this._textWrapper.text||!this._placeholderText||(i=new gB,i.text=this._placeholderText,this._placeholderColor&&(e.fillStyle=this._placeholderColor)),this._textWidth=e.measureText(i.text).width;const r=2*this._margin.getValueInPixel(this._host,this._tempParentMeasure.width);this._autoStretchWidth&&(this.width=Math.min(this._maxWidth.getValueInPixel(this._host,this._tempParentMeasure.width),this._textWidth+r)+"px",this._autoStretchWidth=!0);const s=this._fontOffset.ascent+(this._currentMeasure.height-this._fontOffset.height)/2,n=this._width.getValueInPixel(this._host,this._tempParentMeasure.width)-r;if(e.save(),e.beginPath(),e.rect(t,this._currentMeasure.top+(this._currentMeasure.height-this._fontOffset.height)/2,n+2,this._currentMeasure.height),e.clip(),this._isFocused&&this._textWidth>n){const e=t-this._textWidth+n;this._scrollLeft||(this._scrollLeft=e)}else this._scrollLeft=t;if(this.outlineWidth&&e.strokeText(i.text,this._scrollLeft,this._currentMeasure.top+s),e.fillText(i.text,this._scrollLeft,this._currentMeasure.top+s),this._isFocused){if(this._clickedCoordinate){const t=this._scrollLeft+this._textWidth-this._clickedCoordinate;let r=0;this._cursorOffset=0;let s=0;do{this._cursorOffset&&(s=Math.abs(t-r)),this._cursorOffset++,r=e.measureText(i.substr(i.length-this._cursorOffset,this._cursorOffset)).width}while(r=this._cursorOffset);Math.abs(t-r)>s&&this._cursorOffset--,this._blinkIsEven=!1,this._clickedCoordinate=null}if(!this._blinkIsEven){const r=i.substr(i.length-this._cursorOffset),s=e.measureText(r).width;let o=this._scrollLeft+this._textWidth-s;ot+n&&(this._scrollLeft+=t+n-o,o=t+n,this._markAsDirty()),this.isTextHighlightOn||e.fillRect(o,this._currentMeasure.top+(this._currentMeasure.height-this._fontOffset.height)/2,2,this._fontOffset.height)}if(clearTimeout(this._blinkTimeout),this._blinkTimeout=setTimeout((()=>{this._blinkIsEven=!this._blinkIsEven,this._markAsDirty()}),500),this.isTextHighlightOn){clearTimeout(this._blinkTimeout);const r=e.measureText(i.substring(this._startHighlightIndex)).width;let s=this._scrollLeft+this._textWidth-r;this._highlightedText=i.substring(this._startHighlightIndex,this._endHighlightIndex);let n=e.measureText(i.substring(this._startHighlightIndex,this._endHighlightIndex)).width;s=this._rowDefinitions.length?null:this._rowDefinitions[e]}getColumnDefinition(e){return e<0||e>=this._columnDefinitions.length?null:this._columnDefinitions[e]}addRowDefinition(e,t=!1){return this._rowDefinitions.push(new JL(e,t?JL.UNITMODE_PIXEL:JL.UNITMODE_PERCENTAGE)),this._rowDefinitionObservers.push(this._rowDefinitions[this.rowCount-1].onChangedObservable.add((()=>this._markAsDirty()))),this._markAsDirty(),this}addColumnDefinition(e,t=!1){return this._columnDefinitions.push(new JL(e,t?JL.UNITMODE_PIXEL:JL.UNITMODE_PERCENTAGE)),this._columnDefinitionObservers.push(this._columnDefinitions[this.columnCount-1].onChangedObservable.add((()=>this._markAsDirty()))),this._markAsDirty(),this}setRowDefinition(e,t,i=!1){if(e<0||e>=this._rowDefinitions.length)return this;const r=this._rowDefinitions[e];return r&&r.isPixel===i&&r.value===t||(this._rowDefinitions[e].onChangedObservable.remove(this._rowDefinitionObservers[e]),this._rowDefinitions[e]=new JL(t,i?JL.UNITMODE_PIXEL:JL.UNITMODE_PERCENTAGE),this._rowDefinitionObservers[e]=this._rowDefinitions[e].onChangedObservable.add((()=>this._markAsDirty())),this._markAsDirty()),this}setColumnDefinition(e,t,i=!1){if(e<0||e>=this._columnDefinitions.length)return this;const r=this._columnDefinitions[e];return r&&r.isPixel===i&&r.value===t||(this._columnDefinitions[e].onChangedObservable.remove(this._columnDefinitionObservers[e]),this._columnDefinitions[e]=new JL(t,i?JL.UNITMODE_PIXEL:JL.UNITMODE_PERCENTAGE),this._columnDefinitionObservers[e]=this._columnDefinitions[e].onChangedObservable.add((()=>this._markAsDirty())),this._markAsDirty()),this}getChildrenAt(e,t){const i=this._cells[`${e}:${t}`];return i?i.children:null}getChildCellInfo(e){return e._tag}_removeCell(e,t){if(e){super.removeControl(e);for(const t of e.children){const e=this._childControls.indexOf(t);-1!==e&&this._childControls.splice(e,1)}delete this._cells[t]}}_offsetCell(e,t){if(this._cells[t]){this._cells[e]=this._cells[t];for(const t of this._cells[e].children)t._tag=e;delete this._cells[t]}}removeColumnDefinition(e){if(e<0||e>=this._columnDefinitions.length)return this;for(let t=0;t=this._rowDefinitions.length)return this;for(let t=0;t{for(const s in this._cells){if(!Object.prototype.hasOwnProperty.call(this._cells,s))continue;const n=s.split(":"),o=parseInt(n[0]),a=parseInt(n[1]),l=this._cells[s];l.leftInPixels=e[a],l.topInPixels=t[o],l.widthInPixels=i[a],l.heightInPixels=r[o],l._left.ignoreAdaptiveScaling=!0,l._top.ignoreAdaptiveScaling=!0,l._width.ignoreAdaptiveScaling=!0,l._height.ignoreAdaptiveScaling=!0}})),super._additionalProcessing(e,t)}_flagDescendantsAsMatrixDirty(){for(const e in this._cells)Object.prototype.hasOwnProperty.call(this._cells,e)&&this._cells[e]._markMatrixAsDirty()}_renderHighlightSpecific(e){super._renderHighlightSpecific(e),this._getGridDefinitions(((t,i,r,s)=>{for(let i=0;i{e.tags.push(t._tag)}))}}_parseFromContent(e,t){super._parseFromContent(e,t);const i=[];this.children.forEach((e=>{i.push(e)})),this.removeRowDefinition(0),this.removeColumnDefinition(0);for(let t=0;t=1-bB._Epsilon&&(this._value.r=1),this._value.g>=1-bB._Epsilon&&(this._value.g=1),this._value.b>=1-bB._Epsilon&&(this._value.b=1),this.onValueChangedObservable.notifyObservers(this._value))}get width(){return this._width.toString(this._host)}set width(e){this._width.toString(this._host)!==e&&this._width.fromString(e)&&(0===this._width.getValue(this._host)&&(e="1px",this._width.fromString(e)),this._height.fromString(e),this._markAsDirty())}get height(){return this._height.toString(this._host)}set height(e){this._height.toString(this._host)!==e&&this._height.fromString(e)&&(0===this._height.getValue(this._host)&&(e="1px",this._height.fromString(e)),this._width.fromString(e),this._markAsDirty())}get size(){return this.width}set size(e){this.width=e}constructor(e){super(e),this.name=e,this._value=H.v9.Red(),this._tmpColor=new H.v9,this._pointerStartedOnSquare=!1,this._pointerStartedOnWheel=!1,this._squareLeft=0,this._squareTop=0,this._squareSize=0,this._h=360,this._s=1,this._v=1,this._lastPointerDownId=-1,this.onValueChangedObservable=new z.cP,this._pointerIsDown=!1,this.value=new H.v9(.88,.1,.1),this.size="200px",this.isPointerBlocker=!0}_getTypeName(){return"ColorPicker"}_preMeasure(e){e.widthl||rg?_:(_-p)*(e-m)/(g-m)+p,d=(s-h)/(e-h),o[u+3]=d1-f?255*(1-(d-(1-f))/f):255}return s.putImageData(n,0,0),r}_draw(e){e.save(),this._applyStates(e);const t=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),i=.2*t,r=this._currentMeasure.left,s=this._currentMeasure.top;this._colorWheelCanvas&&this._colorWheelCanvas.width==2*t||(this._colorWheelCanvas=this._createColorWheelCanvas(t,i)),this._updateSquareProps(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY,e.fillRect(this._squareLeft,this._squareTop,this._squareSize,this._squareSize)),e.drawImage(this._colorWheelCanvas,r,s),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._drawGradientSquare(this._h,this._squareLeft,this._squareTop,this._squareSize,this._squareSize,e);let n=this._squareLeft+this._squareSize*this._s,o=this._squareTop+this._squareSize*(1-this._v);this._drawCircle(n,o,.04*t,e);const a=t-.5*i;n=r+t+Math.cos((this._h-180)*Math.PI/180)*a,o=s+t+Math.sin((this._h-180)*Math.PI/180)*a,this._drawCircle(n,o,.35*i,e),e.restore()}_updateValueFromPointer(e,t){if(this._pointerStartedOnWheel){const i=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),r=i+this._currentMeasure.left,s=i+this._currentMeasure.top;this._h=180*Math.atan2(t-s,e-r)/Math.PI+180}else this._pointerStartedOnSquare&&(this._updateSquareProps(),this._s=(e-this._squareLeft)/this._squareSize,this._v=1-(t-this._squareTop)/this._squareSize,this._s=Math.min(this._s,1),this._s=Math.max(this._s,bB._Epsilon),this._v=Math.min(this._v,1),this._v=Math.max(this._v,bB._Epsilon));H.v9.HSVtoRGBToRef(this._h,this._s,this._v,this._tmpColor),this.value=this._tmpColor}_isPointOnSquare(e,t){this._updateSquareProps();const i=this._squareLeft,r=this._squareTop,s=this._squareSize;return e>=i&&e<=i+s&&t>=r&&t<=r+s}_isPointOnWheel(e,t){const i=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),r=i-.2*i,s=e-(i+this._currentMeasure.left),n=t-(i+this._currentMeasure.top),o=s*s+n*n;return o<=i*i&&o>=r*r}_onPointerDown(e,t,i,r,s){if(!super._onPointerDown(e,t,i,r,s))return!1;if(this.isReadOnly)return!0;this._pointerIsDown=!0,this._pointerStartedOnSquare=!1,this._pointerStartedOnWheel=!1,this._invertTransformMatrix.transformCoordinates(t.x,t.y,this._transformedPosition);const n=this._transformedPosition.x,o=this._transformedPosition.y;return this._isPointOnSquare(n,o)?this._pointerStartedOnSquare=!0:this._isPointOnWheel(n,o)&&(this._pointerStartedOnWheel=!0),this._updateValueFromPointer(n,o),this._host._capturingControl[i]=this,this._lastPointerDownId=i,!0}_onPointerMove(e,t,i,r){if(i==this._lastPointerDownId){if(!this.isReadOnly){this._invertTransformMatrix.transformCoordinates(t.x,t.y,this._transformedPosition);const e=this._transformedPosition.x,i=this._transformedPosition.y;this._pointerIsDown&&this._updateValueFromPointer(e,i)}super._onPointerMove(e,t,i,r)}}_onPointerUp(e,t,i,r,s,n){this._pointerIsDown=!1,delete this._host._capturingControl[i],super._onPointerUp(e,t,i,r,s,n)}_onCanvasBlur(){this._forcePointerUp(),super._onCanvasBlur()}static ShowPickerDialogAsync(e,t){return new Promise((i=>{t.pickerWidth=t.pickerWidth||"640px",t.pickerHeight=t.pickerHeight||"400px",t.headerHeight=t.headerHeight||"35px",t.lastColor=t.lastColor||"#000000",t.swatchLimit=t.swatchLimit||20,t.numSwatchesPerLine=t.numSwatchesPerLine||10;const r=t.swatchLimit/t.numSwatchesPerLine,s=parseFloat(t.pickerWidth)/t.numSwatchesPerLine,n=Math.floor(.25*s),o=n*(t.numSwatchesPerLine+1),a=Math.floor((parseFloat(t.pickerWidth)-o)/t.numSwatchesPerLine),l=a*r+n*(r+1),h=(parseInt(t.pickerHeight)+l+Math.floor(.25*a)).toString()+"px",c="#c0c0c0",u="#535353",d="#414141",f="515151",p="#555555",_="#454545",m=H.v9.FromHexString("#dddddd"),g=m.r+m.g+m.b,v="#aaaaaa",x="#ffffff";let b,S;const T=["R","G","B"],C="#454545",y="#f0f0f0";let E,P,A,R,I,M=!1;const O=new xB;if(O.name="Dialog Container",O.width=t.pickerWidth,t.savedColors){O.height=h;const e=parseInt(t.pickerHeight)/parseInt(h);O.addRowDefinition(e,!1),O.addRowDefinition(1-e,!1)}else O.height=t.pickerHeight,O.addRowDefinition(1,!1);if(e.addControl(O),t.savedColors){P=new xB,P.name="Swatch Drawer",P.verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP,P.background=u,P.width=t.pickerWidth;const e=t.savedColors.length/t.numSwatchesPerLine;let i;i=0==e?0:e+1,P.height=(a*e+i*n).toString()+"px",P.top=Math.floor(.25*a).toString()+"px";for(let e=0;e<2*Math.ceil(t.savedColors.length/t.numSwatchesPerLine)+1;e++)e%2!=0?P.addRowDefinition(a,!0):P.addRowDefinition(n,!0);for(let e=0;e<2*t.numSwatchesPerLine+1;e++)e%2!=0?P.addColumnDefinition(a,!0):P.addColumnDefinition(n,!0);O.addControl(P,1,0)}const D=new xB;D.name="Picker Panel",D.height=t.pickerHeight;const w=parseInt(t.headerHeight)/parseInt(t.pickerHeight),N=[w,1-w];D.addRowDefinition(N[0],!1),D.addRowDefinition(N[1],!1),O.addControl(D,0,0);const F=new cB;F.name="Dialogue Header Bar",F.background="#cccccc",F.thickness=0,D.addControl(F,0,0);const L=pB.CreateSimpleButton("closeButton","a");L.fontFamily="coreglyphs";const B=H.v9.FromHexString(F.background),V=new H.v9(1-B.r,1-B.g,1-B.b);L.color=V.toHexString(),L.fontSize=Math.floor(.6*parseInt(t.headerHeight)),L.textBlock.textVerticalAlignment=lB.VERTICAL_ALIGNMENT_CENTER,L.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_RIGHT,L.height=L.width=t.headerHeight,L.background=F.background,L.thickness=0,L.pointerDownAnimation=()=>{},L.pointerUpAnimation=()=>{L.background=F.background},L.pointerEnterAnimation=()=>{L.color=F.background,L.background="red"},L.pointerOutAnimation=()=>{L.color=V.toHexString(),L.background=F.background},L.onPointerClickObservable.add((()=>{De(ie.background)})),D.addControl(L,0,0);const k=new xB;k.name="Dialogue Body",k.background=u;const U=[.4375,.5625];k.addRowDefinition(1,!1),k.addColumnDefinition(U[0],!1),k.addColumnDefinition(U[1],!1),D.addControl(k,1,0);const G=new xB;G.name="Picker Grid",G.addRowDefinition(.85,!1),G.addRowDefinition(.15,!1),k.addControl(G,0,0);const z=new bB;z.name="GUI Color Picker",t.pickerHeight{I=z.name,R="",Re(!1)})),z.onValueChangedObservable.add((function(e){I==z.name&&ye(e,z.name)})),G.addControl(z,0,0);const W=new xB;W.name="Dialogue Right Half",W.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT;const X=[.514,.486];W.addRowDefinition(X[0],!1),W.addRowDefinition(X[1],!1),k.addControl(W,1,1);const q=new xB;q.name="Swatches and Buttons";const Y=[.417,.583];q.addRowDefinition(1,!1),q.addColumnDefinition(Y[0],!1),q.addColumnDefinition(Y[1],!1),W.addControl(q,0,0);const K=new xB;K.name="New and Current Swatches";const j=[.04,.16,.64,.16];K.addRowDefinition(j[0],!1),K.addRowDefinition(j[1],!1),K.addRowDefinition(j[2],!1),K.addRowDefinition(j[3],!1),q.addControl(K,0,0);const $=new xB;$.name="Active Swatches",$.width=.67,$.addRowDefinition(.5,!1),$.addRowDefinition(.5,!1),K.addControl($,2,0);const Q=Math.floor(parseInt(t.pickerWidth)*U[1]*Y[0]*.11),Z=Math.floor(parseInt(t.pickerHeight)*N[1]*X[0]*j[1]*.5);let J;J=t.pickerWidth>t.pickerHeight?Z:Q;const ee=new dB;ee.text="new",ee.name="New Color Label",ee.color=c,ee.fontSize=J,K.addControl(ee,1,0);const te=new cB;te.name="New Color Swatch",te.background=t.lastColor,te.thickness=0,$.addControl(te,0,0);const ie=pB.CreateSimpleButton("currentSwatch","");ie.background=t.lastColor,ie.thickness=0,ie.onPointerClickObservable.add((()=>{ye(H.v9.FromHexString(ie.background),ie.name),Re(!1)})),ie.pointerDownAnimation=()=>{},ie.pointerUpAnimation=()=>{},ie.pointerEnterAnimation=()=>{},ie.pointerOutAnimation=()=>{},$.addControl(ie,1,0);const re=new cB;re.name="Swatch Outline",re.width=.67,re.thickness=2,re.color="#404040",re.isHitTestVisible=!1,K.addControl(re,2,0);const se=new dB;se.name="Current Color Label",se.text="current",se.color=c,se.fontSize=J,K.addControl(se,3,0);const ne=new xB;ne.name="Button Grid",ne.height=.8;const oe=1/3;ne.addRowDefinition(oe,!1),ne.addRowDefinition(oe,!1),ne.addRowDefinition(oe,!1),q.addControl(ne,0,1);const ae=Math.floor(parseInt(t.pickerWidth)*U[1]*Y[1]*.67).toString()+"px",le=Math.floor(parseInt(t.pickerHeight)*N[1]*X[0]*(parseFloat(ne.height.toString())/100)*oe*.7).toString()+"px";b=parseFloat(ae)>parseFloat(le)?Math.floor(.45*parseFloat(le)):Math.floor(.11*parseFloat(ae));const he=pB.CreateSimpleButton("butOK","OK");he.width=ae,he.height=le,he.verticalAlignment=lB.VERTICAL_ALIGNMENT_CENTER,he.thickness=2,he.color=c,he.fontSize=b,he.background=u,he.onPointerEnterObservable.add((()=>{he.background=d})),he.onPointerOutObservable.add((()=>{he.background=u})),he.pointerDownAnimation=()=>{he.background=f},he.pointerUpAnimation=()=>{he.background=d},he.onPointerClickObservable.add((()=>{Re(!1),De(te.background)})),ne.addControl(he,0,0);const ce=pB.CreateSimpleButton("butCancel","Cancel");ce.width=ae,ce.height=le,ce.verticalAlignment=lB.VERTICAL_ALIGNMENT_CENTER,ce.thickness=2,ce.color=c,ce.fontSize=b,ce.background=u,ce.onPointerEnterObservable.add((()=>{ce.background=d})),ce.onPointerOutObservable.add((()=>{ce.background=u})),ce.pointerDownAnimation=()=>{ce.background=f},ce.pointerUpAnimation=()=>{ce.background=d},ce.onPointerClickObservable.add((()=>{Re(!1),De(ie.background)})),ne.addControl(ce,1,0),t.savedColors&&(A=pB.CreateSimpleButton("butSave","Save"),A.width=ae,A.height=le,A.verticalAlignment=lB.VERTICAL_ALIGNMENT_CENTER,A.thickness=2,A.fontSize=b,t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&(0==t.savedColors.length&&Me(!0),t.savedColors.length0&&Me(!0),ne.addControl(A,2,0));const ue=new xB;ue.name="Dialog Lower Right",ue.addRowDefinition(.02,!1),ue.addRowDefinition(.63,!1),ue.addRowDefinition(.21,!1),ue.addRowDefinition(.14,!1),W.addControl(ue,1,0);const de=H.v9.FromHexString(t.lastColor),fe=new xB;fe.name="RGB Values",fe.width=.82,fe.verticalAlignment=lB.VERTICAL_ALIGNMENT_CENTER,fe.addRowDefinition(1/3,!1),fe.addRowDefinition(1/3,!1),fe.addRowDefinition(1/3,!1),fe.addColumnDefinition(.1,!1),fe.addColumnDefinition(.2,!1),fe.addColumnDefinition(.7,!1),ue.addControl(fe,1,0);for(let e=0;e{I=pe.name,R=pe.text,Re(!1)})),pe.onBlurObservable.add((()=>{""==pe.text&&(pe.text="0"),Ee(pe,"r"),I==pe.name&&(I="")})),pe.onTextChangedObservable.add((()=>{I==pe.name&&Ee(pe,"r")})),fe.addControl(pe,0,1);const _e=new vB;_e.width=.83,_e.height=.72,_e.name="gIntField",_e.fontSize=b,_e.text=(255*de.g).toString(),_e.color=y,_e.background=C,_e.onFocusObservable.add((()=>{I=_e.name,R=_e.text,Re(!1)})),_e.onBlurObservable.add((()=>{""==_e.text&&(_e.text="0"),Ee(_e,"g"),I==_e.name&&(I="")})),_e.onTextChangedObservable.add((()=>{I==_e.name&&Ee(_e,"g")})),fe.addControl(_e,1,1);const me=new vB;me.width=.83,me.height=.72,me.name="bIntField",me.fontSize=b,me.text=(255*de.b).toString(),me.color=y,me.background=C,me.onFocusObservable.add((()=>{I=me.name,R=me.text,Re(!1)})),me.onBlurObservable.add((()=>{""==me.text&&(me.text="0"),Ee(me,"b"),I==me.name&&(I="")})),me.onTextChangedObservable.add((()=>{I==me.name&&Ee(me,"b")})),fe.addControl(me,2,1);const ge=new vB;ge.width=.95,ge.height=.72,ge.name="rDecField",ge.fontSize=b,ge.text=de.r.toString(),ge.color=y,ge.background=C,ge.onFocusObservable.add((()=>{I=ge.name,R=ge.text,Re(!1)})),ge.onBlurObservable.add((()=>{0!=parseFloat(ge.text)&&""!=ge.text||(ge.text="0",Pe(ge,"r")),I==ge.name&&(I="")})),ge.onTextChangedObservable.add((()=>{I==ge.name&&Pe(ge,"r")})),fe.addControl(ge,0,2);const ve=new vB;ve.width=.95,ve.height=.72,ve.name="gDecField",ve.fontSize=b,ve.text=de.g.toString(),ve.color=y,ve.background=C,ve.onFocusObservable.add((()=>{I=ve.name,R=ve.text,Re(!1)})),ve.onBlurObservable.add((()=>{0!=parseFloat(ve.text)&&""!=ve.text||(ve.text="0",Pe(ve,"g")),I==ve.name&&(I="")})),ve.onTextChangedObservable.add((()=>{I==ve.name&&Pe(ve,"g")})),fe.addControl(ve,1,2);const xe=new vB;xe.width=.95,xe.height=.72,xe.name="bDecField",xe.fontSize=b,xe.text=de.b.toString(),xe.color=y,xe.background=C,xe.onFocusObservable.add((()=>{I=xe.name,R=xe.text,Re(!1)})),xe.onBlurObservable.add((()=>{0!=parseFloat(xe.text)&&""!=xe.text||(xe.text="0",Pe(xe,"b")),I==xe.name&&(I="")})),xe.onTextChangedObservable.add((()=>{I==xe.name&&Pe(xe,"b")})),fe.addControl(xe,2,2);const be=new xB;be.name="Hex Value",be.width=.82,be.addRowDefinition(1,!1),be.addColumnDefinition(.1,!1),be.addColumnDefinition(.9,!1),ue.addControl(be,2,0);const Se=new dB;Se.text="#",Se.color=c,Se.fontSize=b,be.addControl(Se,0,0);const Te=new vB;Te.width=.96,Te.height=.72,Te.name="hexField",Te.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_CENTER,Te.fontSize=b;const Ce=t.lastColor.split("#");function ye(e,t){I=t;const i=e.toHexString();if(te.background=i,pe.name!=I&&(pe.text=Math.floor(255*e.r).toString()),_e.name!=I&&(_e.text=Math.floor(255*e.g).toString()),me.name!=I&&(me.text=Math.floor(255*e.b).toString()),ge.name!=I&&(ge.text=e.r.toString()),ve.name!=I&&(ve.text=e.g.toString()),xe.name!=I&&(xe.text=e.b.toString()),Te.name!=I){const e=i.split("#");Te.text=e[1]}z.name!=I&&(z.value=e)}function Ee(e,t){let i=e.text;if(/[^0-9]/g.test(i))e.text=R;else if(""!=i&&(Math.floor(parseInt(i))<0?i="0":Math.floor(parseInt(i))>255?i="255":isNaN(parseInt(i))&&(i="0")),I==e.name&&(R=i),""!=i){i=parseInt(i).toString(),e.text=i;const r=H.v9.FromHexString(te.background);I==e.name&&ye("r"==t?new H.v9(parseInt(i)/255,r.g,r.b):"g"==t?new H.v9(r.r,parseInt(i)/255,r.b):new H.v9(r.r,r.g,parseInt(i)/255),e.name)}}function Pe(e,t){let i=e.text;if(/[^0-9.]/g.test(i))return void(e.text=R);""!=i&&"."!=i&&0!=parseFloat(i)&&(parseFloat(i)<0?i="0.0":parseFloat(i)>1?i="1.0":isNaN(parseFloat(i))&&(i="0.0")),I==e.name&&(R=i),""!=i&&"."!=i&&0!=parseFloat(i)?(i=parseFloat(i).toString(),e.text=i):i="0.0";const r=H.v9.FromHexString(te.background);I==e.name&&ye("r"==t?new H.v9(parseFloat(i),r.g,r.b):"g"==t?new H.v9(r.r,parseFloat(i),r.b):new H.v9(r.r,r.g,parseFloat(i)),e.name)}function Ae(){if(t.savedColors&&t.savedColors[E]){let e;e=M?"b":"";const i=pB.CreateSimpleButton("Swatch_"+E,e);i.fontFamily="coreglyphs";const r=H.v9.FromHexString(t.savedColors[E]),s=r.r+r.g+r.b;i.color=s>g?v:x,i.fontSize=Math.floor(.7*a),i.textBlock.verticalAlignment=lB.VERTICAL_ALIGNMENT_CENTER,i.height=i.width=a.toString()+"px",i.background=t.savedColors[E],i.thickness=2;const n=E;return i.pointerDownAnimation=()=>{i.thickness=4},i.pointerUpAnimation=()=>{i.thickness=3},i.pointerEnterAnimation=()=>{i.thickness=3},i.pointerOutAnimation=()=>{i.thickness=2},i.onPointerClickObservable.add((()=>{M?(function(e){t.savedColors&&t.savedColors.splice(e,1),t.savedColors&&0==t.savedColors.length&&(Me(!1),M=!1)}(n),Ie("",A)):t.savedColors&&ye(H.v9.FromHexString(t.savedColors[n]),i.name)})),i}return null}function Re(e){let t;if(void 0!==e&&(M=e),M){for(let e=0;ei*t.numSwatchesPerLine?t.numSwatchesPerLine:t.savedColors.length-(i-1)*t.numSwatchesPerLine;const s=Math.min(Math.max(r,0),t.numSwatchesPerLine);for(let i=0,r=1;it.numSwatchesPerLine)continue;const s=Ae();null!=s&&(P.addControl(s,e,r),r+=2,E++)}}t.savedColors.length>=t.swatchLimit?Oe(i,!0):Oe(i,!1)}}function Me(e){e?(S=pB.CreateSimpleButton("butEdit","Edit"),S.width=ae,S.height=le,S.left=Math.floor(.1*parseInt(ae)).toString()+"px",S.top=(-1*parseFloat(S.left)).toString()+"px",S.verticalAlignment=lB.VERTICAL_ALIGNMENT_BOTTOM,S.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,S.thickness=2,S.color=c,S.fontSize=b,S.background=u,S.onPointerEnterObservable.add((()=>{S.background=d})),S.onPointerOutObservable.add((()=>{S.background=u})),S.pointerDownAnimation=()=>{S.background=f},S.pointerUpAnimation=()=>{S.background=d},S.onPointerClickObservable.add((()=>{M=!M,Re()})),G.addControl(S,1,0)):G.removeControl(S)}function Oe(e,t){t?(e.color=p,e.background=_):(e.color=c,e.background=u)}function De(r){t.savedColors&&t.savedColors.length>0?i({savedColors:t.savedColors,pickedColor:r}):i({pickedColor:r}),e.removeControl(O)}Te.text=Ce[1],Te.color=y,Te.background=C,Te.onFocusObservable.add((()=>{I=Te.name,R=Te.text,Re(!1)})),Te.onBlurObservable.add((()=>{if(3==Te.text.length){const e=Te.text.split("");Te.text=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]}""==Te.text&&(Te.text="000000",ye(H.v9.FromHexString(Te.text),"b")),I==Te.name&&(I="")})),Te.onTextChangedObservable.add((()=>{let e=Te.text;const t=/[^0-9A-F]/i.test(e);if((Te.text.length>6||t)&&I==Te.name)Te.text=R;else{if(Te.text.length<6){const t=6-Te.text.length;for(let i=0;i0&&Ie("",A)}))}}bB._Epsilon=1e-6,(0,je.Cg)([(0,$e.lK)()],bB.prototype,"value",null),(0,je.Cg)([(0,$e.lK)()],bB.prototype,"width",null),(0,je.Cg)([(0,$e.lK)()],bB.prototype,"height",null),(0,je.Cg)([(0,$e.lK)()],bB.prototype,"size",null),(0,X.Y5)("BABYLON.GUI.ColorPicker",bB);class SB extends hB{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}get arc(){return this._arc}set arc(e){this._arc!==e&&(this._arc=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thickness=1,this._arc=1}_getTypeName(){return"Ellipse"}_localDraw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),lB.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._thickness/2,this._currentMeasure.height/2-this._thickness/2,this._arc,e),(this._backgroundGradient||this._background)&&(e.fillStyle=this._getBackgroundColor(e),e.fill()),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._thickness&&(this.color&&(e.strokeStyle=this.color),e.lineWidth=this._thickness,e.stroke()),e.restore()}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.width-=2*this._thickness,this._measureForChildren.height-=2*this._thickness,this._measureForChildren.left+=this._thickness,this._measureForChildren.top+=this._thickness}_clipForChildren(e){lB.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2,this._currentMeasure.height/2,this._arc,e),e.clip()}_renderHighlightSpecific(e){lB.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._highlightLineWidth/2,this._currentMeasure.height/2-this._highlightLineWidth/2,this._arc,e),e.stroke()}}(0,je.Cg)([(0,$e.lK)()],SB.prototype,"thickness",null),(0,je.Cg)([(0,$e.lK)()],SB.prototype,"arc",null),(0,X.Y5)("BABYLON.GUI.Ellipse",SB);class TB extends pB{constructor(e){super(e),this.name=e,this._unfocusedColor=this.color}_onPointerDown(e,t,i,r,s){return this.isReadOnly||this.focus(),super._onPointerDown(e,t,i,r,s)}}(0,X.Y5)("BABYLON.GUI.FocusableButton",TB);class CB extends vB{get autoStretchHeight(){return this._autoStretchHeight}set autoStretchHeight(e){this._autoStretchHeight!==e&&(this._autoStretchHeight=e,this._markAsDirty())}set height(e){this.fixedRatioMasterIsWidth=!1,this._height.toString(this._host)!==e&&(this._height.fromString(e)&&this._markAsDirty(),this._autoStretchHeight=!1)}get maxHeight(){return this._maxHeight.toString(this._host)}get maxHeightInPixels(){return this._maxHeight.getValueInPixel(this._host,this._cachedParentMeasure.height)}set maxHeight(e){this._maxHeight.toString(this._host)!==e&&this._maxHeight.fromString(e)&&this._markAsDirty()}constructor(e,t=""){super(e),this.name=e,this._textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,this._textVerticalAlignment=lB.VERTICAL_ALIGNMENT_TOP,this._prevText=this.text,this._lineSpacing=new JL(0),this._maxHeight=new JL(1,JL.UNITMODE_PERCENTAGE,!1),this.onLinesReadyObservable=new z.cP,this.text=t,this.isPointerBlocker=!0,this.onLinesReadyObservable.add((()=>this._updateCursorPosition())),this._highlightCursorInfo={initialStartIndex:-1,initialRelativeStartIndex:-1,initialLineIndex:-1},this._cursorInfo={globalStartIndex:0,globalEndIndex:0,relativeEndIndex:0,relativeStartIndex:0,currentLineIndex:0}}_getTypeName(){return"InputTextArea"}processKeyboard(e){this.isReadOnly||(this.alternativeProcessKey(e.code,e.key,e),this.onKeyboardEventProcessedObservable.notifyObservers(e))}alternativeProcessKey(e,t,i){if(!i||!i.ctrlKey&&!i.metaKey||"c"!==t&&"v"!==t&&"x"!==t){switch(e){case"Period":i&&i.shiftKey&&i.preventDefault();break;case"Backspace":!this._isTextHighlightOn&&this._cursorInfo.globalStartIndex>0&&(this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex--),this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,i&&i.preventDefault(),this._blinkIsEven=!1,this._isTextHighlightOn=!1,this._textHasChanged();break;case"Delete":!this._isTextHighlightOn&&this._cursorInfo.globalEndIndexthis._highlightCursorInfo.initialStartIndex?this._cursorInfo.globalEndIndex--:this._cursorInfo.globalStartIndex--:(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex--,this._isTextHighlightOn=!0),this._blinkIsEven=!0,void i.preventDefault()):(this._isTextHighlightOn?this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex:i&&(i.ctrlKey||i.metaKey)?(this._cursorInfo.globalStartIndex-=this._cursorInfo.relativeStartIndex,i.preventDefault()):this._cursorInfo.globalStartIndex>0&&this._cursorInfo.globalStartIndex--,this._blinkIsEven=!1,void(this._isTextHighlightOn=!1));case"ArrowRight":if(this._markAsDirty(),i&&i.shiftKey){if(i.ctrlKey||i.metaKey){const e=this._lines[this._cursorInfo.currentLineIndex].text.length-this._cursorInfo.relativeEndIndex-1;this._cursorInfo.globalEndIndex+=e,this._cursorInfo.globalStartIndex=this._highlightCursorInfo.initialStartIndex}return this._isTextHighlightOn?this._cursorInfo.globalStartIndexa&&l>0&&i--,this._isTextHighlightOn?this._cursorInfo.currentLineIndex<=this._highlightCursorInfo.initialLineIndex?(this._cursorInfo.globalStartIndex=i,this._cursorInfo.globalEndIndex=this._highlightCursorInfo.initialStartIndex,this._cursorInfo.relativeEndIndex=this._highlightCursorInfo.initialRelativeStartIndex):this._cursorInfo.globalEndIndex=i:this._cursorInfo.globalStartIndex=i}return void this._markAsDirty();case"ArrowDown":if(this._blinkIsEven=!1,i&&(i.shiftKey?(this._isTextHighlightOn||(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex),this._isTextHighlightOn=!0,this._blinkIsEven=!0):this._isTextHighlightOn=!1,i.preventDefault()),this._cursorInfo.currentLineIndex===this._lines.length-1)this._cursorInfo.globalStartIndex=this.text.length;else{const e=this._lines[this._cursorInfo.currentLineIndex],t=this._lines[this._cursorInfo.currentLineIndex+1];let i=0,r=0;!this._isTextHighlightOn||this._cursorInfo.currentLineIndexa&&l>0&&i--,this._isTextHighlightOn?this._cursorInfo.currentLineIndexthis._cursorInfo.globalEndIndex&&(this._cursorInfo.globalEndIndex+=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex=this._cursorInfo.globalEndIndex-this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex-=this._cursorInfo.globalStartIndex)):(this._cursorInfo.globalEndIndex=i,this._cursorInfo.globalStartIndex=this._highlightCursorInfo.initialStartIndex):this._cursorInfo.globalStartIndex=i}return void this._markAsDirty()}if("a"===t&&i&&(i.ctrlKey||i.metaKey))return this.selectAllText(),void i.preventDefault();1===t?.length&&(i?.preventDefault(),this._currentKey=t,this.onBeforeKeyAddObservable.notifyObservers(this),t=this._currentKey,this._addKey&&(this._isTextHighlightOn=!1,this._blinkIsEven=!1,this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex,t),this._cursorInfo.globalStartIndex+=t.length,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._textHasChanged()))}}_parseLineWordWrap(e="",t,i){const r=[],s=e.split(" ");let n=0;for(let o=0;o0?e+" "+s[o]:s[0],l=i.measureText(a).width;if(l>t){o>0&&(n=i.measureText(e).width,r.push({text:e,width:n,lineEnding:" "})),e=s[o];let a="";e.split("").map((e=>{i.measureText(a+e).width>t&&(r.push({text:a,width:i.measureText(a).width,lineEnding:""}),a=""),a+=e})),e=a,n=i.measureText(e).width}else n=l,e=a}return r.push({text:e,width:n,lineEnding:" "}),r}_breakLines(e,t){const i=[],r=(this.text||this.placeholderText).split("\n");if(this.clipContent)for(const s of r)i.push(...this._parseLineWordWrap(s,e,t));else for(const e of r)i.push(this._parseLine(e,t));return i[i.length-1].lineEnding="\n",i}_parseLine(e="",t){return{text:e,width:t.measureText(e).width,lineEnding:" "}}_preMeasure(e,t){this._fontOffset&&!this._wasDirty||(this._fontOffset=lB._GetFontOffset(t.font,this._host.getScene()?.getEngine()));let i=this._beforeRenderText(this._textWrapper).text;!this.text&&this._placeholderText&&(i=this._placeholderText),this._textWidth=t.measureText(i).width;const r=2*this._margin.getValueInPixel(this._host,e.width);if(this._autoStretchWidth){const s=i.split("\n").reduce(((e,i)=>t.measureText(i).width>t.measureText(e).width?i:e),""),n=t.measureText(s).width;this.width=Math.min(this._maxWidth.getValueInPixel(this._host,e.width),n+r)+"px",this.autoStretchWidth=!0}if(this._availableWidth=this._width.getValueInPixel(this._host,e.width)-r,this._lines=this._breakLines(this._availableWidth,t),this._contextForBreakLines=t,this._autoStretchHeight){const t=this._lines.length*this._fontOffset.height+2*this._margin.getValueInPixel(this._host,e.height);this.height=Math.min(this._maxHeight.getValueInPixel(this._host,e.height),t)+"px",this._autoStretchHeight=!0}if(this._availableHeight=this._height.getValueInPixel(this._host,e.height)-r,this._isFocused){this._cursorInfo.currentLineIndex=0;let e=this._lines[this._cursorInfo.currentLineIndex].text.length+this._lines[this._cursorInfo.currentLineIndex].lineEnding.length,t=0;for(;t+e<=this._cursorInfo.globalStartIndex;)t+=e,this._cursorInfo.currentLineIndexthis._availableWidth){const e=this._clipTextLeft-this._lines[this._cursorInfo.currentLineIndex].width+this._availableWidth;this._scrollLeft||(this._scrollLeft=e)}else this._scrollLeft=this._clipTextLeft;if(this._isFocused){const e=(this._cursorInfo.currentLineIndex+1)*this._fontOffset.height,t=this._clipTextTop-e;this._scrollTop||(this._scrollTop=t)}else this._scrollTop=this._clipTextTop}_additionalProcessing(){this.highlightedText="",this.onLinesReadyObservable.notifyObservers(this)}_drawText(e,t,i,r){const s=this._currentMeasure.width;let n=this._scrollLeft;switch(this._textHorizontalAlignment){case lB.HORIZONTAL_ALIGNMENT_LEFT:n+=0;break;case lB.HORIZONTAL_ALIGNMENT_RIGHT:n+=s-t;break;case lB.HORIZONTAL_ALIGNMENT_CENTER:n+=(s-t)/2}(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(r.shadowColor=this.shadowColor,r.shadowBlur=this.shadowBlur,r.shadowOffsetX=this.shadowOffsetX,r.shadowOffsetY=this.shadowOffsetY),this.outlineWidth&&r.strokeText(e,this._currentMeasure.left+n,i),r.fillText(e,n,i)}_onCopyText(e){this._isTextHighlightOn=!1;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText}_onCutText(e){if(this._highlightedText){try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText,this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),this._textHasChanged()}}_onPasteText(e){let t="";t=e.clipboardData&&-1!==e.clipboardData.types.indexOf("text/plain")?e.clipboardData.getData("text/plain"):this._host.clipboardData,this._isTextHighlightOn=!1,this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex,t);const i=t.length-(this._cursorInfo.globalEndIndex-this._cursorInfo.globalStartIndex);this._cursorInfo.globalStartIndex+=i,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._clickedCoordinateX=null,this._clickedCoordinateY=null,super._textHasChanged()}_draw(e){this._computeScroll(),this._scrollLeft=this._scrollLeft??0,this._scrollTop=this._scrollTop??0,e.save(),this._applyStates(e),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._isFocused?this._focusedBackground&&(e.fillStyle=this._isEnabled?this._focusedBackground:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)):this._background&&(e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this.color&&(e.fillStyle=this.color);const t=this._currentMeasure.height,i=this._currentMeasure.width;let r=0;switch(this._textVerticalAlignment){case lB.VERTICAL_ALIGNMENT_TOP:r=this._fontOffset.ascent;break;case lB.VERTICAL_ALIGNMENT_BOTTOM:r=t-this._fontOffset.height*(this._lines.length-1)-this._fontOffset.descent;break;case lB.VERTICAL_ALIGNMENT_CENTER:r=this._fontOffset.ascent+(t-this._fontOffset.height*this._lines.length)/2}e.save(),e.beginPath(),e.fillStyle=this.fontStyle,!this._textWrapper.text&&this.placeholderText&&(e.fillStyle=this._placeholderColor),e.rect(this._clipTextLeft,this._clipTextTop,this._availableWidth+2,this._availableHeight+2),e.clip(),r+=this._scrollTop;for(let t=0;tthis._clipTextLeft+this._availableWidth&&(this._scrollLeft+=this._clipTextLeft+this._availableWidth-t,t=this._clipTextLeft+this._availableWidth,this._markAsDirty());let i=this._scrollTop+this._cursorInfo.currentLineIndex*this._fontOffset.height;ithis._clipTextTop+this._availableHeight&&this._availableHeight>this._fontOffset.height&&(this._scrollTop+=this._clipTextTop+this._availableHeight-i-this._fontOffset.height,i=this._clipTextTop+this._availableHeight-this._fontOffset.height,this._markAsDirty()),this._isTextHighlightOn||e.fillRect(t,i,2,this._fontOffset.height)}if(this._resetBlinking(),this._isTextHighlightOn){clearTimeout(this._blinkTimeout),this._highlightedText=this.text.substring(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),e.globalAlpha=this._highligherOpacity,e.fillStyle=this._textHighlightColor;const t=Math.min(this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialLineIndex),r=Math.max(this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialLineIndex);let s=this._scrollTop+t*this._fontOffset.height;for(let n=t;n<=r;n++){const o=this._lines[n];let a=this._scrollLeft;switch(this._textHorizontalAlignment){case lB.HORIZONTAL_ALIGNMENT_LEFT:a+=0;break;case lB.HORIZONTAL_ALIGNMENT_RIGHT:a+=i-o.width;break;case lB.HORIZONTAL_ALIGNMENT_CENTER:a+=(i-o.width)/2}const l=n===t?this._cursorInfo.relativeStartIndex:0,h=n===r?this._cursorInfo.relativeEndIndex:o.text.length,c=e.measureText(o.text.substring(0,l)).width,u=o.text.substring(l,h),d=e.measureText(u).width;e.fillRect(a+c,s,d,this._fontOffset.height),s+=this._fontOffset.height}this._cursorInfo.globalEndIndex===this._cursorInfo.globalStartIndex&&this._resetBlinking()}}e.restore(),this._thickness&&(this._isFocused?this.focusedColor&&(e.strokeStyle=this.focusedColor):this.color&&(e.strokeStyle=this.color),e.lineWidth=this._thickness,e.strokeRect(this._currentMeasure.left+this._thickness/2,this._currentMeasure.top+this._thickness/2,this._currentMeasure.width-this._thickness,this._currentMeasure.height-this._thickness))}_resetBlinking(){clearTimeout(this._blinkTimeout),this._blinkTimeout=setTimeout((()=>{this._blinkIsEven=!this._blinkIsEven,this._markAsDirty()}),500)}_onPointerDown(e,t,i,r,s){return!(!super._onPointerDown(e,t,i,r,s)||!this.isReadOnly&&(this._clickedCoordinateX=t.x,this._clickedCoordinateY=t.y,this._isTextHighlightOn=!1,this._highlightedText="",this._isPointerDown=!0,this._host._capturingControl[i]=this,this._host.focusedControl===this?(clearTimeout(this._blinkTimeout),this._markAsDirty(),0):!this._isEnabled||(this._host.focusedControl=this,0)))}_onPointerMove(e,t,i,r){0===r.event.movementX&&0===r.event.movementY||(this._host.focusedControl===this&&this._isPointerDown&&!this.isReadOnly&&(this._clickedCoordinateX=t.x,this._clickedCoordinateY=t.y,this._isTextHighlightOn||(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex,this._isTextHighlightOn=!0),this._markAsDirty()),super._onPointerMove(e,t,i,r))}_updateCursorPosition(){if(this._isFocused)if(!this._textWrapper.text&&this.placeholderText)this._cursorInfo.currentLineIndex=0,this._cursorInfo.globalStartIndex=0,this._cursorInfo.globalEndIndex=0,this._cursorInfo.relativeStartIndex=0,this._cursorInfo.relativeEndIndex=0;else if(this._clickedCoordinateX&&this._clickedCoordinateY){this._isTextHighlightOn||(this._cursorInfo={globalStartIndex:0,globalEndIndex:0,relativeStartIndex:0,relativeEndIndex:0,currentLineIndex:0});let e=0,t=0;const i=this._clickedCoordinateY-this._scrollTop,r=Math.floor(i/this._fontOffset.height);this._cursorInfo.currentLineIndex=Math.min(Math.max(r,0),this._lines.length-1);let s=0;const n=this._clickedCoordinateX-(this._scrollLeft??0);let o=0;for(let t=0;tt;)t++,o=Math.abs(n-s),s=this._contextForBreakLines.measureText(this._lines[this._cursorInfo.currentLineIndex].text.substring(0,t)).width;Math.abs(n-s)>o&&t>0&&t--,e+=t,this._isTextHighlightOn?e=this._highlightCursorInfo.initialStartIndex){for(;t+e<=this._cursorInfo.globalEndIndex;)t+=e,this._cursorInfo.currentLineIndex0&&this._textWrapper.isWord(this._cursorInfo.globalStartIndex-1)?--this._cursorInfo.globalStartIndex:0,i=this._cursorInfo.globalEndIndexthis._markAsDirty()))),this._connectedControl=e,this._markAsDirty())}get x1(){return this._x1.toString(this._host)}set x1(e){this._x1.toString(this._host)!==e&&this._x1.fromString(e)&&this._markAsDirty()}get y1(){return this._y1.toString(this._host)}set y1(e){this._y1.toString(this._host)!==e&&this._y1.fromString(e)&&this._markAsDirty()}get x2(){return this._x2.toString(this._host)}set x2(e){this._x2.toString(this._host)!==e&&this._x2.fromString(e)&&this._markAsDirty()}get y2(){return this._y2.toString(this._host)}set y2(e){this._y2.toString(this._host)!==e&&this._y2.fromString(e)&&this._markAsDirty()}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth!==e&&(this._lineWidth=e,this._markAsDirty())}set horizontalAlignment(e){}set verticalAlignment(e){}get _effectiveX2(){return(this._connectedControl?this._connectedControl.centerX:0)+this._x2.getValue(this._host)}get _effectiveY2(){return(this._connectedControl?this._connectedControl.centerY:0)+this._y2.getValue(this._host)}constructor(e){super(e),this.name=e,this._lineWidth=1,this._x1=new JL(0),this._y1=new JL(0),this._x2=new JL(0),this._y2=new JL(0),this._dash=new Array,this._automaticSize=!0,this.isHitTestVisible=!1,this._horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,this._verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP}_getTypeName(){return"Line"}_draw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._applyStates(e),e.strokeStyle=this._getColor(e),e.lineWidth=this._lineWidth,e.setLineDash(this._dash),e.beginPath(),e.moveTo(this._cachedParentMeasure.left+this._x1.getValue(this._host),this._cachedParentMeasure.top+this._y1.getValue(this._host)),e.lineTo(this._cachedParentMeasure.left+this._effectiveX2,this._cachedParentMeasure.top+this._effectiveY2),e.stroke(),e.restore()}_measure(){this._currentMeasure.width=Math.abs(this._x1.getValue(this._host)-this._effectiveX2)+this._lineWidth,this._currentMeasure.height=Math.abs(this._y1.getValue(this._host)-this._effectiveY2)+this._lineWidth}_computeAlignment(e){this._currentMeasure.left=e.left+Math.min(this._x1.getValue(this._host),this._effectiveX2)-this._lineWidth/2,this._currentMeasure.top=e.top+Math.min(this._y1.getValue(this._host),this._effectiveY2)-this._lineWidth/2}moveToVector3(e,t,i=!1){if(!this._host||this.parent!==this._host._rootContainer)return void Ue.S0.Error("Cannot move a control to a vector3 if the control is not at root level");const r=this._host._getGlobalViewport(),s=W.Pq.Project(e,W.uq.IdentityReadOnly,t.getTransformMatrix(),r);this._moveToProjectedPosition(s,i),s.z<0||s.z>1?this.notRenderable=!0:this.notRenderable=!1}_moveToProjectedPosition(e,t=!1){const i=e.x+this._linkOffsetX.getValue(this._host)+"px",r=e.y+this._linkOffsetY.getValue(this._host)+"px";t?(this.x2=i,this.y2=r,this._x2.ignoreAdaptiveScaling=!0,this._y2.ignoreAdaptiveScaling=!0):(this.x1=i,this.y1=r,this._x1.ignoreAdaptiveScaling=!0,this._y1.ignoreAdaptiveScaling=!0)}}(0,je.Cg)([(0,$e.lK)()],EB.prototype,"dash",null),(0,je.Cg)([(0,$e.lK)()],EB.prototype,"x1",null),(0,je.Cg)([(0,$e.lK)()],EB.prototype,"y1",null),(0,je.Cg)([(0,$e.lK)()],EB.prototype,"x2",null),(0,je.Cg)([(0,$e.lK)()],EB.prototype,"y2",null),(0,je.Cg)([(0,$e.lK)()],EB.prototype,"lineWidth",null),(0,X.Y5)("BABYLON.GUI.Line",EB);class PB{constructor(e){this._multiLine=e,this._x=new JL(0),this._y=new JL(0),this._point=new W.Pq(0,0,0)}get x(){return this._x.toString(this._multiLine._host)}set x(e){this._x.toString(this._multiLine._host)!==e&&this._x.fromString(e)&&this._multiLine._markAsDirty()}get y(){return this._y.toString(this._multiLine._host)}set y(e){this._y.toString(this._multiLine._host)!==e&&this._y.fromString(e)&&this._multiLine._markAsDirty()}get control(){return this._control}set control(e){this._control!==e&&(this._control&&this._controlObserver&&(this._control.onDirtyObservable.remove(this._controlObserver),this._controlObserver=null),this._control=e,this._control&&(this._controlObserver=this._control.onDirtyObservable.add(this._multiLine.onPointUpdate)),this._multiLine._markAsDirty())}get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh&&this._meshObserver&&this._mesh.getScene().onAfterCameraRenderObservable.remove(this._meshObserver),this._mesh=e,this._mesh&&(this._meshObserver=this._mesh.getScene().onAfterCameraRenderObservable.add(this._multiLine.onPointUpdate)),this._multiLine._markAsDirty())}resetLinks(){this.control=null,this.mesh=null}translate(){return this._point=this._translatePoint(),this._point}_translatePoint(){if(null!=this._mesh)return this._multiLine._host.getProjectedPositionWithZ(this._mesh.getBoundingInfo().boundingSphere.center,this._mesh.getWorldMatrix());if(null!=this._control)return new W.Pq(this._control.centerX,this._control.centerY,1-lt.bH);{const e=this._multiLine._host,t=this._x.getValueInPixel(e,Number(e._canvas.width)),i=this._y.getValueInPixel(e,Number(e._canvas.height));return new W.Pq(t,i,1-lt.bH)}}dispose(){this.resetLinks()}}class AB extends lB{constructor(e){super(e),this.name=e,this._lineWidth=1,this.onPointUpdate=()=>{this._markAsDirty()},this._automaticSize=!0,this.isHitTestVisible=!1,this._horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,this._verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP,this._dash=[],this._points=[]}get dash(){return this._dash}set dash(e){this._dash!==e&&(this._dash=e,this._markAsDirty())}getAt(e){return this._points[e]||(this._points[e]=new PB(this)),this._points[e]}add(...e){return e.map((e=>this.push(e)))}push(e){const t=this.getAt(this._points.length);return null==e||(e instanceof Nt?t.mesh=e:e instanceof lB?t.control=e:null!=e.x&&null!=e.y&&(t.x=e.x,t.y=e.y)),t}remove(e){let t;if(e instanceof PB){if(t=this._points.indexOf(e),-1===t)return}else t=e;const i=this._points[t];i&&(i.dispose(),this._points.splice(t,1))}reset(){for(;this._points.length>0;)this.remove(this._points.length-1)}resetLinks(){this._points.forEach((e=>{null!=e&&e.resetLinks()}))}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth!==e&&(this._lineWidth=e,this._markAsDirty())}set horizontalAlignment(e){}set verticalAlignment(e){}_getTypeName(){return"MultiLine"}_draw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._applyStates(e),e.strokeStyle=this.color,e.lineWidth=this._lineWidth,e.setLineDash(this._dash),e.beginPath();let t,i=!0;this._points.forEach((r=>{r&&(i?(e.moveTo(r._point.x,r._point.y),i=!1):r._point.z<1&&t.z<1?e.lineTo(r._point.x,r._point.y):e.moveTo(r._point.x,r._point.y),t=r._point)})),e.stroke(),e.restore()}_additionalProcessing(){this._minX=null,this._minY=null,this._maxX=null,this._maxY=null,this._points.forEach((e=>{e&&(e.translate(),(null==this._minX||e._point.xthis._maxX)&&(this._maxX=e._point.x),(null==this._maxY||e._point.y>this._maxY)&&(this._maxY=e._point.y))})),null==this._minX&&(this._minX=0),null==this._minY&&(this._minY=0),null==this._maxX&&(this._maxX=0),null==this._maxY&&(this._maxY=0)}_measure(){null!=this._minX&&null!=this._maxX&&null!=this._minY&&null!=this._maxY&&(this._currentMeasure.width=Math.abs(this._maxX-this._minX)+this._lineWidth,this._currentMeasure.height=Math.abs(this._maxY-this._minY)+this._lineWidth)}_computeAlignment(){null!=this._minX&&null!=this._minY&&(this._currentMeasure.left=this._minX-this._lineWidth/2,this._currentMeasure.top=this._minY-this._lineWidth/2)}dispose(){this.reset(),super.dispose()}}(0,je.Cg)([(0,$e.lK)()],AB.prototype,"dash",null),(0,X.Y5)("BABYLON.GUI.MultiLine",AB);class RB extends lB{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}get checkSizeRatio(){return this._checkSizeRatio}set checkSizeRatio(e){e=Math.max(Math.min(1,e),0),this._checkSizeRatio!==e&&(this._checkSizeRatio=e,this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get isChecked(){return this._isChecked}set isChecked(e){this._isChecked!==e&&(this._isChecked=e,this._markAsDirty(),this.onIsCheckedChangedObservable.notifyObservers(e),this._isChecked&&this._host&&this._host.executeOnAllControls((e=>{if(e===this)return;if(void 0===e.group)return;const t=e;t.group===this.group&&(t.isChecked=!1)})))}constructor(e){super(e),this.name=e,this._isChecked=!1,this._background="black",this._checkSizeRatio=.8,this._thickness=1,this.group="",this.onIsCheckedChangedObservable=new z.cP,this.isPointerBlocker=!0}_getTypeName(){return"RadioButton"}_draw(e){e.save(),this._applyStates(e);const t=this._currentMeasure.width-this._thickness,i=this._currentMeasure.height-this._thickness;if((this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),lB.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._thickness/2,this._currentMeasure.height/2-this._thickness/2,1,e),e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fill(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),e.strokeStyle=this.color,e.lineWidth=this._thickness,e.stroke(),this._isChecked){e.fillStyle=this._isEnabled?this.color:this._disabledColor;const r=t*this._checkSizeRatio,s=i*this._checkSizeRatio;lB.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,r/2-this._thickness/2,s/2-this._thickness/2,1,e),e.fill()}e.restore()}_onPointerDown(e,t,i,r,s){return!!super._onPointerDown(e,t,i,r,s)&&(this.isReadOnly||this.isChecked||(this.isChecked=!0),!0)}static AddRadioButtonWithHeader(e,t,i,r){const s=new _B;s.isVertical=!1,s.height="30px";const n=new RB;n.width="20px",n.height="20px",n.isChecked=i,n.color="green",n.group=t,n.onIsCheckedChangedObservable.add((e=>r(n,e))),s.addControl(n);const o=new dB;return o.text=e,o.width="180px",o.paddingLeft="5px",o.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,o.color="white",s.addControl(o),s}}(0,je.Cg)([(0,$e.lK)()],RB.prototype,"thickness",null),(0,je.Cg)([(0,$e.lK)()],RB.prototype,"group",void 0),(0,je.Cg)([(0,$e.lK)()],RB.prototype,"checkSizeRatio",null),(0,je.Cg)([(0,$e.lK)()],RB.prototype,"background",null),(0,je.Cg)([(0,$e.lK)()],RB.prototype,"isChecked",null),(0,X.Y5)("BABYLON.GUI.RadioButton",RB);class IB extends lB{get displayThumb(){return this._displayThumb}set displayThumb(e){this._displayThumb!==e&&(this._displayThumb=e,this._markAsDirty())}get step(){return this._step}set step(e){this._step!==e&&(this._step=e,this._markAsDirty())}get barOffset(){return this._barOffset.toString(this._host)}get barOffsetInPixels(){return this._barOffset.getValueInPixel(this._host,this._cachedParentMeasure.width)}set barOffset(e){this._barOffset.toString(this._host)!==e&&this._barOffset.fromString(e)&&this._markAsDirty()}get thumbWidth(){return this._thumbWidth.toString(this._host)}get thumbWidthInPixels(){return this._thumbWidth.getValueInPixel(this._host,this._cachedParentMeasure.width)}set thumbWidth(e){this._thumbWidth.toString(this._host)!==e&&this._thumbWidth.fromString(e)&&this._markAsDirty()}get minimum(){return this._minimum}set minimum(e){this._minimum!==e&&(this._minimum=e,this._markAsDirty(),this.value=Math.max(Math.min(this.value,this._maximum),this._minimum))}get maximum(){return this._maximum}set maximum(e){this._maximum!==e&&(this._maximum=e,this._markAsDirty(),this.value=Math.max(Math.min(this.value,this._maximum),this._minimum))}get value(){return this._value}set value(e){e=Math.max(Math.min(e,this._maximum),this._minimum),this._value!==e&&(this._value=e,this._markAsDirty(),this.onValueChangedObservable.notifyObservers(this._value))}get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,this._markAsDirty())}get isThumbClamped(){return this._isThumbClamped}set isThumbClamped(e){this._isThumbClamped!==e&&(this._isThumbClamped=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thumbWidth=new JL(20,JL.UNITMODE_PIXEL,!1),this._minimum=0,this._maximum=100,this._value=50,this._isVertical=!1,this._barOffset=new JL(5,JL.UNITMODE_PIXEL,!1),this._isThumbClamped=!1,this._displayThumb=!0,this._step=0,this._lastPointerDownId=-1,this._effectiveBarOffset=0,this.onValueChangedObservable=new z.cP,this._pointerIsDown=!1,this.isPointerBlocker=!0}_getTypeName(){return"BaseSlider"}_getThumbPosition(){return this.isVertical?(this.maximum-this.value)/(this.maximum-this.minimum)*this._backgroundBoxLength:(this.value-this.minimum)/(this.maximum-this.minimum)*this._backgroundBoxLength}_getThumbThickness(e){let t=0;switch(e){case"circle":t=this._thumbWidth.isPixel?Math.max(this._thumbWidth.getValue(this._host),this._backgroundBoxThickness):this._backgroundBoxThickness*this._thumbWidth.getValue(this._host);break;case"rectangle":t=this._thumbWidth.isPixel?Math.min(this._thumbWidth.getValue(this._host),this._backgroundBoxThickness):this._backgroundBoxThickness*this._thumbWidth.getValue(this._host)}return t}_prepareRenderingData(e){this._effectiveBarOffset=0,this._renderLeft=this._currentMeasure.left,this._renderTop=this._currentMeasure.top,this._renderWidth=this._currentMeasure.width,this._renderHeight=this._currentMeasure.height,this._backgroundBoxLength=Math.max(this._currentMeasure.width,this._currentMeasure.height),this._backgroundBoxThickness=Math.min(this._currentMeasure.width,this._currentMeasure.height),this._effectiveThumbThickness=this._getThumbThickness(e),this.displayThumb&&(this._backgroundBoxLength-=this._effectiveThumbThickness),this.isVertical&&this._currentMeasure.height=this._selectors.length))return this._selectors[e]}removeSelector(e){e<0||e>=this._selectors.length||(this._groupPanel.removeControl(this._selectors[e]),this._selectors.splice(e,1))}}class DB extends OB{addCheckbox(e,t=(e=>{}),i=!1){i=i||!1;const r=new mB;r.width="20px",r.height="20px",r.color="#364249",r.background="#CCCCCC",r.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,r.onIsCheckedChangedObservable.add((function(e){t(e)}));const s=lB.AddHeader(r,e,"200px",{isHorizontal:!0,controlFirst:!0});s.height="30px",s.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,s.left="4px",this.groupPanel.addControl(s),this.selectors.push(s),r.isChecked=i,this.groupPanel.parent&&this.groupPanel.parent.parent&&(r.color=this.groupPanel.parent.parent.buttonColor,r.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[1].text=t}_setSelectorLabelColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[0].background=t}}class wB extends OB{constructor(){super(...arguments),this._selectNb=0}addRadio(e,t=(e=>{}),i=!1){const r=this._selectNb++,s=new RB;s.name=e,s.width="20px",s.height="20px",s.color="#364249",s.background="#CCCCCC",s.group=this.name,s.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,s.onIsCheckedChangedObservable.add((function(e){e&&t(r)}));const n=lB.AddHeader(s,e,"200px",{isHorizontal:!0,controlFirst:!0});n.height="30px",n.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,n.left="4px",this.groupPanel.addControl(n),this.selectors.push(n),s.isChecked=i,this.groupPanel.parent&&this.groupPanel.parent.parent&&(s.color=this.groupPanel.parent.parent.buttonColor,s.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[1].text=t}_setSelectorLabelColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[0].background=t}}class NB extends OB{addSlider(e,t=(e=>{}),i="Units",r=0,s=0,n=0,o=(e=>0|e)){const a=new MB;a.name=i,a.value=n,a.minimum=r,a.maximum=s,a.width=.9,a.height="20px",a.color="#364249",a.background="#CCCCCC",a.borderColor="black",a.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,a.left="4px",a.paddingBottom="4px",a.onValueChangedObservable.add((function(e){a.parent.children[0].text=a.parent.children[0].name+": "+o(e)+" "+a.name,t(e)}));const l=lB.AddHeader(a,e+": "+o(n)+" "+i,"30px",{isHorizontal:!1,controlFirst:!1});l.height="60px",l.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,l.left="4px",l.children[0].name=e,this.groupPanel.addControl(l),this.selectors.push(l),this.groupPanel.parent&&this.groupPanel.parent.parent&&(a.color=this.groupPanel.parent.parent.buttonColor,a.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[0].name=t,this.selectors[e].children[0].text=t+": "+this.selectors[e].children[1].value+" "+this.selectors[e].children[1].name}_setSelectorLabelColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[1].background=t}}class FB extends cB{constructor(e,t=[]){if(super(e),this.name=e,this.groups=t,this._buttonColor="#364249",this._buttonBackground="#CCCCCC",this._headerColor="black",this._barColor="white",this._barHeight="2px",this._spacerHeight="20px",this._bars=new Array,this._groups=t,this.thickness=2,this._panel=new _B,this._panel.verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP,this._panel.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,this._panel.top=5,this._panel.left=5,this._panel.width=.95,t.length>0){for(let e=0;e0&&this._addSpacer(),this._panel.addControl(e.groupPanel),this._groups.push(e),e.groupPanel.children[0].color=this._headerColor;for(let t=0;t=this._groups.length)return;const t=this._groups[e];this._panel.removeControl(t.groupPanel),this._groups.splice(e,1),e=this._groups.length||(this._groups[t].groupPanel.children[0].text=e)}relabel(e,t,i){if(t<0||t>=this._groups.length)return;const r=this._groups[t];i<0||i>=r.selectors.length||r._setSelectorLabel(i,e)}removeFromGroupSelector(e,t){if(e<0||e>=this._groups.length)return;const i=this._groups[e];t<0||t>=i.selectors.length||i.removeSelector(t)}addToGroupCheckbox(e,t,i=(()=>{}),r=!1){e<0||e>=this._groups.length||this._groups[e].addCheckbox(t,i,r)}addToGroupRadio(e,t,i=(()=>{}),r=!1){e<0||e>=this._groups.length||this._groups[e].addRadio(t,i,r)}addToGroupSlider(e,t,i=(()=>{}),r="Units",s=0,n=0,o=0,a=(e=>0|e)){e<0||e>=this._groups.length||this._groups[e].addSlider(t,i,r,s,n,o,a)}}class LB extends hB{get freezeControls(){return this._freezeControls}set freezeControls(e){if(this._freezeControls===e)return;e||this._restoreMeasures(),this._freezeControls=!1;const t=this.host.getSize(),i=t.width,r=t.height,s=this.host.getContext(),n=new sB(0,0,i,r);this.host._numLayoutCalls=0,this.host._rootContainer._layout(n,s),e&&(this._updateMeasures(),this._useBuckets()&&this._makeBuckets()),this._freezeControls=e,this.host.markAsDirty()}get bucketWidth(){return this._bucketWidth}get bucketHeight(){return this._bucketHeight}setBucketSizes(e,t){this._bucketWidth=e,this._bucketHeight=t,this._useBuckets()?this._freezeControls&&this._makeBuckets():this._buckets={}}_useBuckets(){return this._bucketWidth>0&&this._bucketHeight>0}_makeBuckets(){this._buckets={},this._bucketLen=Math.ceil(this.widthInPixels/this._bucketWidth),this._dispatchInBuckets(this._children),this._oldLeft=null,this._oldTop=null}_dispatchInBuckets(e){for(let t=0;t0&&this._dispatchInBuckets(i._children)}}_updateMeasures(){const e=0|this.leftInPixels,t=0|this.topInPixels;this._measureForChildren.left-=e,this._measureForChildren.top-=t,this._currentMeasure.left-=e,this._currentMeasure.top-=t,this._customData.origLeftForChildren=this._measureForChildren.left,this._customData.origTopForChildren=this._measureForChildren.top,this._customData.origLeft=this._currentMeasure.left,this._customData.origTop=this._currentMeasure.top,this._updateChildrenMeasures(this._children,e,t)}_updateChildrenMeasures(e,t,i){for(let r=0;r0&&this._updateChildrenMeasures(s._children,t,i)}}_restoreMeasures(){const e=0|this.leftInPixels,t=0|this.topInPixels;this._measureForChildren.left=this._customData.origLeftForChildren+e,this._measureForChildren.top=this._customData.origTopForChildren+t,this._currentMeasure.left=this._customData.origLeft+e,this._currentMeasure.top=this._customData.origTop+t}constructor(e){super(e),this._freezeControls=!1,this._bucketWidth=0,this._bucketHeight=0,this._buckets={}}_getTypeName(){return"ScrollViewerWindow"}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._parentMeasure=e,this._measureForChildren.left=this._currentMeasure.left,this._measureForChildren.top=this._currentMeasure.top,this._measureForChildren.width=e.width,this._measureForChildren.height=e.height}_layout(e,t){return this._freezeControls?(this.invalidateRect(),!1):super._layout(e,t)}_scrollChildren(e,t,i){for(let r=0;r0&&this._scrollChildren(s._children,t,i)}}_scrollChildrenWithBuckets(e,t,i,r){const s=Math.max(0,Math.floor(-e/this._bucketWidth)),n=Math.floor((-e+this._parentMeasure.width-1)/this._bucketWidth),o=Math.floor((-t+this._parentMeasure.height-1)/this._bucketHeight);let a=Math.max(0,Math.floor(-t/this._bucketHeight));for(;a<=o;){for(let e=s;e<=n;++e){const t=a*this._bucketLen+e,s=this._buckets[t];if(s)for(let e=0;ethis._tempMeasure.left+this._tempMeasure.width||tthis._tempMeasure.top+this._tempMeasure.height)&&(this.isVertical?this.value=this.minimum+(1-(t-this._currentMeasure.top)/this._currentMeasure.height)*(this.maximum-this.minimum):this.value=this.minimum+(e-this._currentMeasure.left)/this._currentMeasure.width*(this.maximum-this.minimum)));let r=0;r=this.isVertical?-(t-this._originY)/(this._currentMeasure.height-this._effectiveThumbThickness):(e-this._originX)/(this._currentMeasure.width-this._effectiveThumbThickness),this.value+=i*r*(this.maximum-this.minimum),this._originX=e,this._originY=t}_onPointerDown(e,t,i,r,s){return this._first=!0,super._onPointerDown(e,t,i,r,s)}serialize(e){super.serialize(e),this.backgroundGradient&&(e.backgroundGradient={},this.backgroundGradient.serialize(e.backgroundGradient))}_parseFromContent(e,t){if(super._parseFromContent(e,t),e.backgroundGradient){const t=Ue.S0.Instantiate("BABYLON.GUI."+e.backgroundGradient.className);this.backgroundGradient=new t,this.backgroundGradient.parse(e.backgroundGradient)}}}(0,je.Cg)([(0,$e.lK)()],BB.prototype,"borderColor",null),(0,je.Cg)([(0,$e.lK)()],BB.prototype,"background",null),(0,je.Cg)([(0,$e.lK)()],BB.prototype,"invertScrollDirection",null),(0,X.Y5)("BABYLON.GUI.Scrollbar",BB);class VB extends IB{get invertScrollDirection(){return this._invertScrollDirection}set invertScrollDirection(e){this._invertScrollDirection=e}get backgroundImage(){return this._backgroundBaseImage}set backgroundImage(e){this._backgroundBaseImage!==e&&(this._backgroundBaseImage=e,this.isVertical&&0!==this.num90RotationInVerticalMode?e.isLoaded?(this._backgroundImage=e._rotate90(this.num90RotationInVerticalMode,!0),this._markAsDirty()):e.onImageLoadedObservable.addOnce((()=>{const t=e._rotate90(this.num90RotationInVerticalMode,!0);this._backgroundImage=t,t.isLoaded||t.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()})):(this._backgroundImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()))}get thumbImage(){return this._thumbBaseImage}set thumbImage(e){this._thumbBaseImage!==e&&(this._thumbBaseImage=e,this.isVertical&&0!==this.num90RotationInVerticalMode?e.isLoaded?(this._thumbImage=e._rotate90(-this.num90RotationInVerticalMode,!0),this._markAsDirty()):e.onImageLoadedObservable.addOnce((()=>{const t=e._rotate90(-this.num90RotationInVerticalMode,!0);this._thumbImage=t,t.isLoaded||t.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()})):(this._thumbImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()))}get thumbLength(){return this._thumbLength}set thumbLength(e){this._thumbLength!==e&&(this._thumbLength=e,this._markAsDirty())}get thumbHeight(){return this._thumbHeight}set thumbHeight(e){this._thumbLength!==e&&(this._thumbHeight=e,this._markAsDirty())}get barImageHeight(){return this._barImageHeight}set barImageHeight(e){this._barImageHeight!==e&&(this._barImageHeight=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thumbLength=.5,this._thumbHeight=1,this._barImageHeight=1,this._tempMeasure=new sB(0,0,0,0),this._invertScrollDirection=!1,this.num90RotationInVerticalMode=1}_getTypeName(){return"ImageScrollBar"}_getThumbThickness(){let e=0;return e=this._thumbWidth.isPixel?this._thumbWidth.getValue(this._host):this._backgroundBoxThickness*this._thumbWidth.getValue(this._host),e}_draw(e){e.save(),this._applyStates(e),this._prepareRenderingData("rectangle");const t=this._getThumbPosition(),i=this._renderLeft,r=this._renderTop,s=this._renderWidth,n=this._renderHeight;this._backgroundImage&&(this._tempMeasure.copyFromFloats(i,r,s,n),this.isVertical?(this._tempMeasure.copyFromFloats(i+s*(1-this._barImageHeight)*.5,this._currentMeasure.top,s*this._barImageHeight,n),this._tempMeasure.height+=this._effectiveThumbThickness,this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure)):(this._tempMeasure.copyFromFloats(this._currentMeasure.left,r+n*(1-this._barImageHeight)*.5,s,n*this._barImageHeight),this._tempMeasure.width+=this._effectiveThumbThickness,this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure)),this._backgroundImage._draw(e)),this.isVertical?this._tempMeasure.copyFromFloats(i-this._effectiveBarOffset+this._currentMeasure.width*(1-this._thumbHeight)*.5,this._currentMeasure.top+t,this._currentMeasure.width*this._thumbHeight,this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(this._currentMeasure.left+t,this._currentMeasure.top+this._currentMeasure.height*(1-this._thumbHeight)*.5,this._effectiveThumbThickness,this._currentMeasure.height*this._thumbHeight),this._thumbImage&&(this._thumbImage._currentMeasure.copyFrom(this._tempMeasure),this._thumbImage._draw(e)),e.restore()}_updateValueFromPointer(e,t){0!=this.rotation&&(this._invertTransformMatrix.transformCoordinates(e,t,this._transformedPosition),e=this._transformedPosition.x,t=this._transformedPosition.y);const i=this._invertScrollDirection?-1:1;this._first&&(this._first=!1,this._originX=e,this._originY=t,(ethis._tempMeasure.left+this._tempMeasure.width||tthis._tempMeasure.top+this._tempMeasure.height)&&(this.isVertical?this.value=this.minimum+(1-(t-this._currentMeasure.top)/this._currentMeasure.height)*(this.maximum-this.minimum):this.value=this.minimum+(e-this._currentMeasure.left)/this._currentMeasure.width*(this.maximum-this.minimum)));let r=0;r=this.isVertical?-(t-this._originY)/(this._currentMeasure.height-this._effectiveThumbThickness):(e-this._originX)/(this._currentMeasure.width-this._effectiveThumbThickness),this.value+=i*r*(this.maximum-this.minimum),this._originX=e,this._originY=t}_onPointerDown(e,t,i,r,s){return this._first=!0,super._onPointerDown(e,t,i,r,s)}}(0,je.Cg)([(0,$e.lK)()],VB.prototype,"num90RotationInVerticalMode",void 0),(0,je.Cg)([(0,$e.lK)()],VB.prototype,"invertScrollDirection",null);class kB extends cB{get horizontalBar(){return this._horizontalBar}get verticalBar(){return this._verticalBar}addControl(e){return e?(this._window.addControl(e),this):this}removeControl(e){return this._window.removeControl(e),this}get children(){return this._window.children}_flagDescendantsAsMatrixDirty(){for(const e of this._children)e._markMatrixAsDirty()}get freezeControls(){return this._window.freezeControls}set freezeControls(e){this._window.freezeControls=e}get bucketWidth(){return this._window.bucketWidth}get bucketHeight(){return this._window.bucketHeight}setBucketSizes(e,t){this._window.setBucketSizes(e,t)}get forceHorizontalBar(){return this._forceHorizontalBar}set forceHorizontalBar(e){this._grid.setRowDefinition(1,e?this._barSize:0,!0),this._horizontalBar.isVisible=e,this._forceHorizontalBar=e}get forceVerticalBar(){return this._forceVerticalBar}set forceVerticalBar(e){this._grid.setColumnDefinition(1,e?this._barSize:0,!0),this._verticalBar.isVisible=e,this._forceVerticalBar=e}constructor(e,t){super(e),this._barSize=20,this._pointerIsOver=!1,this._wheelPrecision=.05,this._thumbLength=.5,this._thumbHeight=1,this._barImageHeight=1,this._horizontalBarImageHeight=1,this._verticalBarImageHeight=1,this._oldWindowContentsWidth=0,this._oldWindowContentsHeight=0,this._forceHorizontalBar=!1,this._forceVerticalBar=!1,this._useImageBar=t||!1,this.onDirtyObservable.add((()=>{this._horizontalBarSpace.color=this.color,this._verticalBarSpace.color=this.color,this._dragSpace.color=this.color})),this.onPointerEnterObservable.add((()=>{this._pointerIsOver=!0})),this.onPointerOutObservable.add((()=>{this._pointerIsOver=!1})),this._grid=new xB,this._useImageBar?(this._horizontalBar=new VB,this._verticalBar=new VB):(this._horizontalBar=new BB,this._verticalBar=new BB),this._window=new LB("scrollViewer_window"),this._window.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,this._window.verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP,this._grid.addColumnDefinition(1),this._grid.addColumnDefinition(0,!0),this._grid.addRowDefinition(1),this._grid.addRowDefinition(0,!0),super.addControl(this._grid),this._grid.addControl(this._window,0,0),this._verticalBarSpace=new cB,this._verticalBarSpace.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,this._verticalBarSpace.verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP,this._verticalBarSpace.thickness=1,this._grid.addControl(this._verticalBarSpace,0,1),this._addBar(this._verticalBar,this._verticalBarSpace,!0,Math.PI),this._horizontalBarSpace=new cB,this._horizontalBarSpace.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,this._horizontalBarSpace.verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP,this._horizontalBarSpace.thickness=1,this._grid.addControl(this._horizontalBarSpace,1,0),this._addBar(this._horizontalBar,this._horizontalBarSpace,!1,0),this._dragSpace=new cB,this._dragSpace.thickness=1,this._grid.addControl(this._dragSpace,1,1),this._grid.clipChildren=!1,this._useImageBar||(this.barColor="grey",this.barBackground="transparent")}resetWindow(){this._window.width="100%",this._window.height="100%"}_getTypeName(){return"ScrollViewer"}_buildClientSizes(){const e=this.host.idealRatio;this._window.parentClientWidth=this._currentMeasure.width-(this._verticalBar.isVisible||this.forceVerticalBar?this._barSize*e:0)-2*this.thickness,this._window.parentClientHeight=this._currentMeasure.height-(this._horizontalBar.isVisible||this.forceHorizontalBar?this._barSize*e:0)-2*this.thickness,this._clientWidth=this._window.parentClientWidth,this._clientHeight=this._window.parentClientHeight}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._buildClientSizes()}_postMeasure(){super._postMeasure(),this._updateScroller(),this._setWindowPosition(!1)}get wheelPrecision(){return this._wheelPrecision}set wheelPrecision(e){this._wheelPrecision!==e&&(e<0&&(e=0),e>1&&(e=1),this._wheelPrecision=e)}get scrollBackground(){return this._horizontalBarSpace.background}set scrollBackground(e){this._horizontalBarSpace.background!==e&&(this._horizontalBarSpace.background=e,this._verticalBarSpace.background=e)}get barColor(){return this._barColor}set barColor(e){this._barColor!==e&&(this._barColor=e,this._horizontalBar.color=e,this._verticalBar.color=e)}get thumbImage(){return this._barImage}set thumbImage(e){if(this._barImage===e)return;this._barImage=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbImage=e,i.thumbImage=e}get horizontalThumbImage(){return this._horizontalBarImage}set horizontalThumbImage(e){this._horizontalBarImage!==e&&(this._horizontalBarImage=e,this._horizontalBar.thumbImage=e)}get verticalThumbImage(){return this._verticalBarImage}set verticalThumbImage(e){this._verticalBarImage!==e&&(this._verticalBarImage=e,this._verticalBar.thumbImage=e)}get barSize(){return this._barSize}set barSize(e){this._barSize!==e&&(this._barSize=e,this._markAsDirty(),this._horizontalBar.isVisible&&this._grid.setRowDefinition(1,this._barSize,!0),this._verticalBar.isVisible&&this._grid.setColumnDefinition(1,this._barSize,!0))}get thumbLength(){return this._thumbLength}set thumbLength(e){if(this._thumbLength===e)return;e<=0&&(e=.1),e>1&&(e=1),this._thumbLength=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbLength=e,i.thumbLength=e,this._markAsDirty()}get thumbHeight(){return this._thumbHeight}set thumbHeight(e){if(this._thumbHeight===e)return;e<=0&&(e=.1),e>1&&(e=1),this._thumbHeight=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbHeight=e,i.thumbHeight=e,this._markAsDirty()}get barImageHeight(){return this._barImageHeight}set barImageHeight(e){if(this._barImageHeight===e)return;e<=0&&(e=.1),e>1&&(e=1),this._barImageHeight=e;const t=this._horizontalBar,i=this._verticalBar;t.barImageHeight=e,i.barImageHeight=e,this._markAsDirty()}get horizontalBarImageHeight(){return this._horizontalBarImageHeight}set horizontalBarImageHeight(e){this._horizontalBarImageHeight!==e&&(e<=0&&(e=.1),e>1&&(e=1),this._horizontalBarImageHeight=e,this._horizontalBar.barImageHeight=e,this._markAsDirty())}get verticalBarImageHeight(){return this._verticalBarImageHeight}set verticalBarImageHeight(e){this._verticalBarImageHeight!==e&&(e<=0&&(e=.1),e>1&&(e=1),this._verticalBarImageHeight=e,this._verticalBar.barImageHeight=e,this._markAsDirty())}get barBackground(){return this._barBackground}set barBackground(e){if(this._barBackground===e)return;this._barBackground=e;const t=this._horizontalBar,i=this._verticalBar;t.background=e,i.background=e,this._dragSpace.background=e}get barImage(){return this._barBackgroundImage}set barImage(e){this._barBackgroundImage=e;const t=this._horizontalBar,i=this._verticalBar;t.backgroundImage=e,i.backgroundImage=e}get horizontalBarImage(){return this._horizontalBarBackgroundImage}set horizontalBarImage(e){this._horizontalBarBackgroundImage=e,this._horizontalBar.backgroundImage=e}get verticalBarImage(){return this._verticalBarBackgroundImage}set verticalBarImage(e){this._verticalBarBackgroundImage=e,this._verticalBar.backgroundImage=e}_setWindowPosition(e=!0){const t=this.host.idealRatio,i=this._window._currentMeasure.width,r=this._window._currentMeasure.height;if(!e&&this._oldWindowContentsWidth===i&&this._oldWindowContentsHeight===r)return;this._oldWindowContentsWidth=i,this._oldWindowContentsHeight=r;const s=this._clientWidth-i,n=this._clientHeight-r,o=this._horizontalBar.value/t*s+"px",a=this._verticalBar.value/t*n+"px";o!==this._window.left&&(this._window.left=o,this.freezeControls||(this._rebuildLayout=!0)),a!==this._window.top&&(this._window.top=a,this.freezeControls||(this._rebuildLayout=!0))}_updateScroller(){const e=this._window._currentMeasure.width,t=this._window._currentMeasure.height;this._horizontalBar.isVisible&&e<=this._clientWidth&&!this.forceHorizontalBar?(this._grid.setRowDefinition(1,0,!0),this._horizontalBar.isVisible=!1,this._horizontalBar.value=0,this._rebuildLayout=!0):!this._horizontalBar.isVisible&&(e>this._clientWidth||this.forceHorizontalBar)&&(this._grid.setRowDefinition(1,this._barSize,!0),this._horizontalBar.isVisible=!0,this._rebuildLayout=!0),this._verticalBar.isVisible&&t<=this._clientHeight&&!this.forceVerticalBar?(this._grid.setColumnDefinition(1,0,!0),this._verticalBar.isVisible=!1,this._verticalBar.value=0,this._rebuildLayout=!0):!this._verticalBar.isVisible&&(t>this._clientHeight||this.forceVerticalBar)&&(this._grid.setColumnDefinition(1,this._barSize,!0),this._verticalBar.isVisible=!0,this._rebuildLayout=!0),this._buildClientSizes();const i=this.host.idealRatio;this._horizontalBar.thumbWidth=.9*this._thumbLength*(this._clientWidth/i)+"px",this._verticalBar.thumbWidth=.9*this._thumbLength*(this._clientHeight/i)+"px"}_link(e){super._link(e),this._attachWheel()}_addBar(e,t,i,r){e.paddingLeft=0,e.width="100%",e.height="100%",e.barOffset=0,e.value=0,e.maximum=1,e.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_CENTER,e.verticalAlignment=lB.VERTICAL_ALIGNMENT_CENTER,e.isVertical=i,e.rotation=r,e.isVisible=!1,t.addControl(e),e.onValueChangedObservable.add((()=>{this._setWindowPosition()}))}_attachWheel(){this._host&&!this._onWheelObserver&&(this._onWheelObserver=this.onWheelObservable.add((e=>{this._pointerIsOver&&!this.isReadOnly&&(1==this._verticalBar.isVisible&&(e.y<0&&this._verticalBar.value>0?this._verticalBar.value-=this._wheelPrecision:e.y>0&&this._verticalBar.value0&&this._horizontalBar.value>0&&(this._horizontalBar.value-=this._wheelPrecision)))})))}_renderHighlightSpecific(e){this.isHighlighted&&(super._renderHighlightSpecific(e),this._grid._renderHighlightSpecific(e),e.restore())}dispose(){this.onWheelObservable.remove(this._onWheelObserver),this._onWheelObserver=null,super.dispose()}}(0,je.Cg)([(0,$e.lK)()],kB.prototype,"wheelPrecision",null),(0,je.Cg)([(0,$e.lK)()],kB.prototype,"scrollBackground",null),(0,je.Cg)([(0,$e.lK)()],kB.prototype,"barColor",null),(0,je.Cg)([(0,$e.lK)()],kB.prototype,"barSize",null),(0,je.Cg)([(0,$e.lK)()],kB.prototype,"barBackground",null),(0,X.Y5)("BABYLON.GUI.ScrollViewer",kB);class UB extends cB{get group(){return this._group}set group(e){this._group!==e&&(this._group=e)}get isActive(){return this._isActive}set isActive(e){this._isActive!==e&&(this._isActive=e,this._isActive?this.toActiveAnimation?.():this.toInactiveAnimation?.(),this._markAsDirty(),this.onIsActiveChangedObservable.notifyObservers(e),this._isActive&&this._host&&this._group&&this._host.executeOnAllControls((e=>{if("ToggleButton"===e.typeName){if(e===this)return;const t=e;t.group===this.group&&(t.isActive=!1)}})))}constructor(e,t){super(e),this.name=e,this.onIsActiveChangedObservable=new z.cP,this.delegatePickingToChildren=!1,this._isActive=!1,this.group=t??"",this.thickness=0,this.isPointerBlocker=!0;let i=null;this.toActiveAnimation=()=>{this.thickness=1},this.toInactiveAnimation=()=>{this.thickness=0},this.pointerEnterActiveAnimation=()=>{i=this.alpha,this.alpha-=.1},this.pointerOutActiveAnimation=()=>{null!==i&&(this.alpha=i)},this.pointerDownActiveAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpActiveAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05},this.pointerEnterInactiveAnimation=()=>{i=this.alpha,this.alpha-=.1},this.pointerOutInactiveAnimation=()=>{null!==i&&(this.alpha=i)},this.pointerDownInactiveAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpInactiveAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05}}_getTypeName(){return"ToggleButton"}_processPicking(e,t,i,r,s,n,o,a){if(!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this.notRenderable)return!1;if(!super.contains(e,t))return!1;if(this.delegatePickingToChildren){let i=!1;for(let r=this._children.length-1;r>=0;r--){const s=this._children[r];if(s.isEnabled&&s.isHitTestVisible&&s.isVisible&&!s.notRenderable&&s.contains(e,t)){i=!0;break}}if(!i)return!1}return this._processObservables(r,e,t,i,s,n,o,a),!0}_onPointerEnter(e,t){return!!super._onPointerEnter(e,t)&&(this.isReadOnly||(this._isActive?this.pointerEnterActiveAnimation&&this.pointerEnterActiveAnimation():this.pointerEnterInactiveAnimation&&this.pointerEnterInactiveAnimation()),!0)}_onPointerOut(e,t,i=!1){this.isReadOnly||(this._isActive?this.pointerOutActiveAnimation&&this.pointerOutActiveAnimation():this.pointerOutInactiveAnimation&&this.pointerOutInactiveAnimation()),super._onPointerOut(e,t,i)}_onPointerDown(e,t,i,r,s){return!!super._onPointerDown(e,t,i,r,s)&&(this.isReadOnly||(this._isActive?this.pointerDownActiveAnimation&&this.pointerDownActiveAnimation():this.pointerDownInactiveAnimation&&this.pointerDownInactiveAnimation()),!0)}_onPointerUp(e,t,i,r,s,n){this.isReadOnly||(this._isActive?this.pointerUpActiveAnimation&&this.pointerUpActiveAnimation():this.pointerUpInactiveAnimation&&this.pointerUpInactiveAnimation()),super._onPointerUp(e,t,i,r,s,n)}}(0,X.Y5)("BABYLON.GUI.ToggleButton",UB);class GB{}class zB extends _B{constructor(){super(...arguments),this.onKeyPressObservable=new z.cP,this.defaultButtonWidth="40px",this.defaultButtonHeight="40px",this.defaultButtonPaddingLeft="2px",this.defaultButtonPaddingRight="2px",this.defaultButtonPaddingTop="2px",this.defaultButtonPaddingBottom="2px",this.defaultButtonColor="#DDD",this.defaultButtonBackground="#070707",this.shiftButtonColor="#7799FF",this.selectedShiftThickness=1,this.shiftState=0,this._currentlyConnectedInputText=null,this._connectedInputTexts=[],this._onKeyPressObserver=null}_getTypeName(){return"VirtualKeyboard"}_createKey(e,t){const i=pB.CreateSimpleButton(e,e);return i.width=t&&t.width?t.width:this.defaultButtonWidth,i.height=t&&t.height?t.height:this.defaultButtonHeight,i.color=t&&t.color?t.color:this.defaultButtonColor,i.background=t&&t.background?t.background:this.defaultButtonBackground,i.paddingLeft=t&&t.paddingLeft?t.paddingLeft:this.defaultButtonPaddingLeft,i.paddingRight=t&&t.paddingRight?t.paddingRight:this.defaultButtonPaddingRight,i.paddingTop=t&&t.paddingTop?t.paddingTop:this.defaultButtonPaddingTop,i.paddingBottom=t&&t.paddingBottom?t.paddingBottom:this.defaultButtonPaddingBottom,i.thickness=0,i.isFocusInvisible=!0,i.shadowColor=this.shadowColor,i.shadowBlur=this.shadowBlur,i.shadowOffsetX=this.shadowOffsetX,i.shadowOffsetY=this.shadowOffsetY,i.onPointerUpObservable.add((()=>{this.onKeyPressObservable.notifyObservers(e)})),i}addKeysRow(e,t){const i=new _B;i.isVertical=!1,i.isFocusInvisible=!0;let r=null;for(let s=0;sr.heightInPixels)&&(r=o),i.addControl(o)}i.height=r?r.height:this.defaultButtonHeight,this.addControl(i)}applyShiftState(e){if(this.children)for(let t=0;t1?this.selectedShiftThickness:0),s.text=e>0?s.text.toUpperCase():s.text.toLowerCase()}}}get connectedInputText(){return this._currentlyConnectedInputText}connect(e){if(this._connectedInputTexts.some((t=>t.input===e)))return;null===this._onKeyPressObserver&&(this._onKeyPressObserver=this.onKeyPressObservable.add((e=>{if(this._currentlyConnectedInputText){switch(this._currentlyConnectedInputText._host.focusedControl=this._currentlyConnectedInputText,e){case"⇧":return this.shiftState++,this.shiftState>2&&(this.shiftState=0),void this.applyShiftState(this.shiftState);case"←":return void(this._currentlyConnectedInputText instanceof CB?this._currentlyConnectedInputText.alternativeProcessKey("Backspace"):this._currentlyConnectedInputText.processKey(8));case"↵":return void(this._currentlyConnectedInputText instanceof CB?this._currentlyConnectedInputText.alternativeProcessKey("Enter"):this._currentlyConnectedInputText.processKey(13))}this._currentlyConnectedInputText instanceof CB?this._currentlyConnectedInputText.alternativeProcessKey("",this.shiftState?e.toUpperCase():e):this._currentlyConnectedInputText.processKey(-1,this.shiftState?e.toUpperCase():e),1===this.shiftState&&(this.shiftState=0,this.applyShiftState(this.shiftState))}}))),this.isVisible=!1,this._currentlyConnectedInputText=e,e._connectedVirtualKeyboard=this;const t=e.onFocusObservable.add((()=>{this._currentlyConnectedInputText=e,e._connectedVirtualKeyboard=this,this.isVisible=!0})),i=e.onBlurObservable.add((()=>{e._connectedVirtualKeyboard=null,this._currentlyConnectedInputText=null,this.isVisible=!1}));this._connectedInputTexts.push({input:e,onBlurObserver:i,onFocusObserver:t})}disconnect(e){if(e){const t=this._connectedInputTexts.filter((t=>t.input===e));1===t.length&&(this._removeConnectedInputObservables(t[0]),this._connectedInputTexts=this._connectedInputTexts.filter((t=>t.input!==e)),this._currentlyConnectedInputText===e&&(this._currentlyConnectedInputText=null))}else this._connectedInputTexts.forEach((e=>{this._removeConnectedInputObservables(e)})),this._connectedInputTexts.length=0;0===this._connectedInputTexts.length&&(this._currentlyConnectedInputText=null,this.onKeyPressObservable.remove(this._onKeyPressObserver),this._onKeyPressObserver=null)}_removeConnectedInputObservables(e){e.input._connectedVirtualKeyboard=null,e.input.onFocusObservable.remove(e.onFocusObserver),e.input.onBlurObservable.remove(e.onBlurObserver)}dispose(){super.dispose(),this.disconnect()}static CreateDefaultLayout(e){const t=new zB(e);return t.addKeysRow(["1","2","3","4","5","6","7","8","9","0","←"]),t.addKeysRow(["q","w","e","r","t","y","u","i","o","p"]),t.addKeysRow(["a","s","d","f","g","h","j","k","l",";","'","↵"]),t.addKeysRow(["⇧","z","x","c","v","b","n","m",",",".","/"]),t.addKeysRow([" "],[{width:"200px"}]),t}_parseFromContent(e,t){super._parseFromContent(e,t);for(const e of this.children)if("StackPanel"===e.getClassName()){const t=e;for(const e of t.children)"Button"===e.getClassName()&&e.name&&e.onPointerUpObservable.add((()=>{this.onKeyPressObservable.notifyObservers(e.name)}))}}}(0,X.Y5)("BABYLON.GUI.VirtualKeyboard",zB);class WB extends lB{get displayMinorLines(){return this._displayMinorLines}set displayMinorLines(e){this._displayMinorLines!==e&&(this._displayMinorLines=e,this._markAsDirty())}get displayMajorLines(){return this._displayMajorLines}set displayMajorLines(e){this._displayMajorLines!==e&&(this._displayMajorLines=e,this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get cellWidth(){return this._cellWidth}set cellWidth(e){this._cellWidth=e,this._markAsDirty()}get cellHeight(){return this._cellHeight}set cellHeight(e){this._cellHeight=e,this._markAsDirty()}get minorLineTickness(){return this._minorLineTickness}set minorLineTickness(e){this._minorLineTickness=e,this._markAsDirty()}get minorLineColor(){return this._minorLineColor}set minorLineColor(e){this._minorLineColor=e,this._markAsDirty()}get majorLineTickness(){return this._majorLineTickness}set majorLineTickness(e){this._majorLineTickness=e,this._markAsDirty()}get majorLineColor(){return this._majorLineColor}set majorLineColor(e){this._majorLineColor=e,this._markAsDirty()}get majorLineFrequency(){return this._majorLineFrequency}set majorLineFrequency(e){this._majorLineFrequency=e,this._markAsDirty()}constructor(e){super(e),this.name=e,this._cellWidth=20,this._cellHeight=20,this._minorLineTickness=1,this._minorLineColor="DarkGray",this._majorLineTickness=2,this._majorLineColor="White",this._majorLineFrequency=5,this._background="Black",this._displayMajorLines=!0,this._displayMinorLines=!0}_draw(e){if(e.save(),this._applyStates(e),this._isEnabled){this._background&&(e.fillStyle=this._background,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height));const t=this._currentMeasure.width/this._cellWidth,i=this._currentMeasure.height/this._cellHeight,r=this._currentMeasure.left+this._currentMeasure.width/2,s=this._currentMeasure.top+this._currentMeasure.height/2;if(this._displayMinorLines){e.strokeStyle=this._minorLineColor,e.lineWidth=this._minorLineTickness;for(let i=-t/2+1;ithis._markAsDirty())),this._markAsDirty())}get valueBarImage(){return this._valueBarImage}set valueBarImage(e){this._valueBarImage!==e&&(this._valueBarImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>this._markAsDirty())),this._markAsDirty())}get thumbImage(){return this._thumbImage}set thumbImage(e){this._thumbImage!==e&&(this._thumbImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>this._markAsDirty())),this._markAsDirty())}constructor(e){super(e),this.name=e,this._tempMeasure=new sB(0,0,0,0)}_getTypeName(){return"ImageBasedSlider"}_draw(e){e.save(),this._applyStates(e),this._prepareRenderingData("rectangle");const t=this._getThumbPosition(),i=this._renderLeft,r=this._renderTop,s=this._renderWidth,n=this._renderHeight;this._backgroundImage&&(this._tempMeasure.copyFromFloats(i,r,s,n),this.isThumbClamped&&this.displayThumb&&(this.isVertical?this._tempMeasure.height+=this._effectiveThumbThickness:this._tempMeasure.width+=this._effectiveThumbThickness),this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure),this._backgroundImage._draw(e)),this._valueBarImage&&(this.isVertical?this.isThumbClamped&&this.displayThumb?this._tempMeasure.copyFromFloats(i,r+t,s,n-t+this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(i,r+t,s,n-t):this.isThumbClamped&&this.displayThumb?this._tempMeasure.copyFromFloats(i,r,t+this._effectiveThumbThickness/2,n):this._tempMeasure.copyFromFloats(i,r,t,n),this._valueBarImage._currentMeasure.copyFrom(this._tempMeasure),this._valueBarImage._draw(e)),this.displayThumb&&(this.isVertical?this._tempMeasure.copyFromFloats(i-this._effectiveBarOffset,this._currentMeasure.top+t,this._currentMeasure.width,this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(this._currentMeasure.left+t,this._currentMeasure.top,this._effectiveThumbThickness,this._currentMeasure.height),this._thumbImage._currentMeasure.copyFrom(this._tempMeasure),this._thumbImage._draw(e)),e.restore()}serialize(e){super.serialize(e);const t={},i={},r={};this.backgroundImage.serialize(t),this.thumbImage.serialize(i),this.valueBarImage.serialize(r),e.backgroundImage=t,e.thumbImage=i,e.valueBarImage=r}_parseFromContent(e,t){super._parseFromContent(e,t),this.backgroundImage=fB.Parse(e.backgroundImage,t),this.thumbImage=fB.Parse(e.thumbImage,t),this.valueBarImage=fB.Parse(e.valueBarImage,t)}}(0,je.Cg)([(0,$e.lK)()],HB.prototype,"displayThumb",null),(0,X.Y5)("BABYLON.GUI.ImageBasedSlider",HB);const XB="Statics";lB.AddHeader=function(e,t,i,r){const s=new _B("panel"),n=!r||r.isHorizontal,o=!r||r.controlFirst;s.isVertical=!n;const a=new dB("header");return a.text=t,a.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,n?a.width=i:a.height=i,o?(s.addControl(e),s.addControl(a),a.paddingLeft="5px"):(s.addControl(a),s.addControl(e),a.paddingRight="5px"),a.shadowBlur=e.shadowBlur,a.shadowColor=e.shadowColor,a.shadowOffsetX=e.shadowOffsetX,a.shadowOffsetY=e.shadowOffsetY,s};class qB{constructor(){this._colorStops=[],this._gradientDirty=!0}_addColorStopsToCanvasGradient(){for(const e of this._colorStops)this._canvasGradient.addColorStop(e.offset,e.color)}getCanvasGradient(e){return(this._gradientDirty||this._context!==e)&&(this._context=e,this._canvasGradient=this._createCanvasGradient(e),this._addColorStopsToCanvasGradient(),this._gradientDirty=!1),this._canvasGradient}addColorStop(e,t){this._colorStops.push({offset:e,color:t}),this._gradientDirty=!0}removeColorStop(e){this._colorStops=this._colorStops.filter((t=>t.offset!==e)),this._gradientDirty=!0}clearColorStops(){this._colorStops=[],this._gradientDirty=!0}get colorStops(){return this._colorStops}getClassName(){return"BaseGradient"}serialize(e){e.colorStops=this._colorStops,e.className=this.getClassName()}parse(e){this._colorStops=e.colorStops}}class YB extends qB{constructor(e,t,i,r){super(),this._x0=e??0,this._y0=t??0,this._x1=i??0,this._y1=r??0}_createCanvasGradient(e){return e.createLinearGradient(this._x0,this._y0,this._x1,this._y1)}get x0(){return this._x0}get x1(){return this._x1}get y0(){return this._y0}get y1(){return this._y1}getClassName(){return"LinearGradient"}serialize(e){super.serialize(e),e.x0=this._x0,e.y0=this._y0,e.x1=this._x1,e.y1=this._y1}parse(e){super.parse(e),this._x0=e.x0,this._y0=e.y0,this._x1=e.x1,this._y1=e.y1}}(0,X.Y5)("BABYLON.GUI.LinearGradient",YB);class KB extends qB{constructor(e,t,i,r,s,n){super(),this._x0=e??0,this._y0=t??0,this._r0=i??0,this._x1=r??0,this._y1=s??0,this._r1=n??0}_createCanvasGradient(e){return e.createRadialGradient(this._x0,this._y0,this._r0,this._x1,this._y1,this._r1)}get x0(){return this._x0}get x1(){return this._x1}get y0(){return this._y0}get y1(){return this._y1}get r0(){return this._r0}get r1(){return this._r1}getClassName(){return"RadialGradient"}serialize(e){super.serialize(e),e.x0=this._x0,e.y0=this._y0,e.r0=this._r0,e.x1=this._x1,e.y1=this._y1,e.r1=this._r1}parse(e){super.parse(e),this._x0=e.x0,this._y0=e.y0,this._r0=e.r0,this._x1=e.x1,this._y1=e.y1,this._r1=e.r1}}(0,X.Y5)("BABYLON.GUI.RadialGradient",KB);class jB{constructor(e){this._fontFamily="Arial",this._fontStyle="",this._fontWeight="",this._fontSize=new JL(18,JL.UNITMODE_PIXEL,!1),this.onChangedObservable=new z.cP,this._host=e}get fontSize(){return this._fontSize.toString(this._host)}set fontSize(e){this._fontSize.toString(this._host)!==e&&this._fontSize.fromString(e)&&this.onChangedObservable.notifyObservers(this)}get fontFamily(){return this._fontFamily}set fontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.onChangedObservable.notifyObservers(this))}get fontStyle(){return this._fontStyle}set fontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.onChangedObservable.notifyObservers(this))}get fontWeight(){return this._fontWeight}set fontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.onChangedObservable.notifyObservers(this))}dispose(){this.onChangedObservable.clear()}}class $B extends Gn{get numLayoutCalls(){return this._numLayoutCalls}get numRenderCalls(){return this._numRenderCalls}get renderScale(){return this._renderScale}set renderScale(e){e!==this._renderScale&&(this._renderScale=e,this._onResize())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this.markAsDirty())}get idealWidth(){return this._idealWidth}set idealWidth(e){this._idealWidth!==e&&(this._idealWidth=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get idealHeight(){return this._idealHeight}set idealHeight(e){this._idealHeight!==e&&(this._idealHeight=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get useSmallestIdeal(){return this._useSmallestIdeal}set useSmallestIdeal(e){this._useSmallestIdeal!==e&&(this._useSmallestIdeal=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get renderAtIdealSize(){return this._renderAtIdealSize}set renderAtIdealSize(e){this._renderAtIdealSize!==e&&(this._renderAtIdealSize=e,this._onResize())}get idealRatio(){let e=0,t=0;return this._idealWidth&&(e=this.getSize().width/this._idealWidth),this._idealHeight&&(t=this.getSize().height/this._idealHeight),this._useSmallestIdeal&&this._idealWidth&&this._idealHeight?window.innerWidtht.typeName===e))}getControlByName(e){return this._getControlByKey("name",e)}_getControlByKey(e,t){return this._rootContainer.getDescendants().find((i=>i[e]===t))||null}get focusedControl(){return this._focusedControl}set focusedControl(e){this._focusedControl!=e&&(this._focusedControl&&this._focusedControl.onBlur(),e&&e.onFocus(),this._focusedControl=e)}get isForeground(){return!this.layer||!this.layer.isBackground}set isForeground(e){this.layer&&this.layer.isBackground!==!e&&(this.layer.isBackground=!e)}get clipboardData(){return this._clipboardData}set clipboardData(e){this._clipboardData=e}constructor(e,t,i=0,r,s=!1,n=vi.g.NEAREST_SAMPLINGMODE,o=!0){const a="object"==typeof(t=t??0)&&void 0!==t?t.width??0:t??0,l="object"==typeof t&&void 0!==t?t.height??0:i;if(super(e,{width:a,height:l},"object"==typeof t&&void 0!==t?t:r,s,n,Il.TEXTUREFORMAT_RGBA,o),this.useStandalone=!1,this.onGuiReadyObservable=new z.cP,this._isDirty=!1,this._rootContainer=new hB("root"),this._lastControlOver={},this._lastControlDown={},this._capturingControl={},this._linkedControls=new Array,this._isFullscreen=!1,this._fullscreenViewport=new et.L(0,0,1,1),this._idealWidth=0,this._idealHeight=0,this._useSmallestIdeal=!1,this._renderAtIdealSize=!1,this._blockNextFocusCheck=!1,this._renderScale=1,this._cursorChanged=!1,this._defaultMousePointerId=0,this._rootChildrenHaveChanged=!1,this._capturedPointerIds=new Set,this._numLayoutCalls=0,this._numRenderCalls=0,this._clipboardData="",this.onClipboardObservable=new z.cP,this.onControlPickedObservable=new z.cP,this.onBeginLayoutObservable=new z.cP,this.onEndLayoutObservable=new z.cP,this.onBeginRenderObservable=new z.cP,this.onEndRenderObservable=new z.cP,this.premulAlpha=!1,this.applyYInversionOnUpdate=!0,this.disableTabNavigation=!1,this.disablePicking=!1,this.usePointerTapForClickEvent=!1,this.skipBlockEvents=0,this.checkPointerEveryFrame=!1,this._useInvalidateRectOptimization=!0,this._invalidatedRectangle=null,this._clearMeasure=new sB(0,0,0,0),this._focusProperties={index:0,total:-1},this._onClipboardCopy=e=>{const t=e,i=new Eu(yu.COPY,t);this.onClipboardObservable.notifyObservers(i),t.preventDefault()},this._onClipboardCut=e=>{const t=e,i=new Eu(yu.CUT,t);this.onClipboardObservable.notifyObservers(i),t.preventDefault()},this._onClipboardPaste=e=>{const t=e,i=new Eu(yu.PASTE,t);this.onClipboardObservable.notifyObservers(i),t.preventDefault()},this.parseContent=this.parseSerializedObject,!(r=this.getScene())||!this._texture)return;this.applyYInversionOnUpdate=o,this._rootElement=r.getEngine().getInputElement();const h=t;this.useStandalone=!!h?.useStandalone,this.useStandalone||(this._renderObserver=r.onBeforeCameraRenderObservable.add((e=>this._checkUpdate(e)))),this._controlAddedObserver=this._rootContainer.onControlAddedObservable.add((e=>{e&&(this._rootChildrenHaveChanged=!0)})),this._controlRemovedObserver=this._rootContainer.onControlRemovedObservable.add((e=>{e&&(this._rootChildrenHaveChanged=!0)})),this._preKeyboardObserver=r.onPreKeyboardObservable.add((e=>{if(!this.disableTabNavigation&&e.type===Ar.TB.KEYDOWN&&"Tab"===e.event.code){const t=!e.event.shiftKey;return t&&this._focusProperties.index===this._focusProperties.total-1||!t&&0===this._focusProperties.index&&this._focusProperties.total>0?(this.focusedControl=null,this._focusProperties.index=0,void(this._focusProperties.total=-1)):(this._focusNextElement(t),void e.event.preventDefault())}this._focusedControl&&(e.type===Ar.TB.KEYDOWN&&this._focusedControl.processKeyboard(e.event),e.skipOnPointerObservable=!0)})),this._rootContainer._link(this),this.hasAlpha=!0,a&&l||(this._resizeObserver=r.getEngine().onResizeObservable.add((()=>this._onResize())),this._onResize()),this._texture.isReady=!0}getClassName(){return"AdvancedDynamicTexture"}executeOnAllControls(e,t){t||(t=this._rootContainer),e(t);for(const i of t.children)i.children?this.executeOnAllControls(e,i):e(i)}get useInvalidateRectOptimization(){return this._useInvalidateRectOptimization}set useInvalidateRectOptimization(e){this._useInvalidateRectOptimization=e}invalidateRect(e,t,i,r){if(this._useInvalidateRectOptimization)if(this._invalidatedRectangle){const s=Math.ceil(Math.max(this._invalidatedRectangle.left+this._invalidatedRectangle.width-1,i)),n=Math.ceil(Math.max(this._invalidatedRectangle.top+this._invalidatedRectangle.height-1,r));this._invalidatedRectangle.left=Math.floor(Math.min(this._invalidatedRectangle.left,e)),this._invalidatedRectangle.top=Math.floor(Math.min(this._invalidatedRectangle.top,t)),this._invalidatedRectangle.width=s-this._invalidatedRectangle.left+1,this._invalidatedRectangle.height=n-this._invalidatedRectangle.top+1}else this._invalidatedRectangle=new sB(e,t,i-e+1,r-t+1)}markAsDirty(){this._isDirty=!0}createStyle(){return new jB(this)}addControl(e){return this._rootContainer.addControl(e),this}removeControl(e){return this._rootContainer.removeControl(e),this}moveToNonOverlappedPosition(e,t=1,i=1){let r;if(Array.isArray(e))r=e;else{const t=this.getDescendants(!0);r=void 0===e?t.filter((e=>void 0!==e.overlapGroup)):t.filter((t=>t.overlapGroup===e))}r.forEach((e=>{let s=W.I9.Zero();const n=new W.I9(e.centerX,e.centerY);r.forEach((t=>{if(e!==t&&$B._Overlaps(e,t)){const e=n.subtract(new W.I9(t.centerX,t.centerY)),r=e.length();r>0&&(s=s.add(e.normalize().scale(i/r)))}})),s.length()>0&&(s=s.normalize().scale(t*(e.overlapDeltaMultiplier??1)),e.linkOffsetXInPixels+=s.x,e.linkOffsetYInPixels+=s.y)}))}dispose(){const e=this.getScene();e&&(this._rootElement=null,e.onBeforeCameraRenderObservable.remove(this._renderObserver),this._resizeObserver&&e.getEngine().onResizeObservable.remove(this._resizeObserver),this._prePointerObserver&&e.onPrePointerObservable.remove(this._prePointerObserver),this._sceneRenderObserver&&e.onBeforeRenderObservable.remove(this._sceneRenderObserver),this._pointerObserver&&e.onPointerObservable.remove(this._pointerObserver),this._preKeyboardObserver&&e.onPreKeyboardObservable.remove(this._preKeyboardObserver),this._canvasPointerOutObserver&&e.getEngine().onCanvasPointerOutObservable.remove(this._canvasPointerOutObserver),this._canvasBlurObserver&&e.getEngine().onCanvasBlurObservable.remove(this._canvasBlurObserver),this._controlAddedObserver&&this._rootContainer.onControlAddedObservable.remove(this._controlAddedObserver),this._controlRemovedObserver&&this._rootContainer.onControlRemovedObservable.remove(this._controlRemovedObserver),this._layerToDispose&&(this._layerToDispose.texture=null,this._layerToDispose.dispose(),this._layerToDispose=null),this._rootContainer.dispose(),this.onClipboardObservable.clear(),this.onControlPickedObservable.clear(),this.onBeginRenderObservable.clear(),this.onEndRenderObservable.clear(),this.onBeginLayoutObservable.clear(),this.onEndLayoutObservable.clear(),this.onGuiReadyObservable.clear(),super.dispose())}_onResize(){const e=this.getScene();if(!e)return;const t=e.getEngine(),i=this.getSize();let r=t.getRenderWidth()*this._renderScale,s=t.getRenderHeight()*this._renderScale;this._renderAtIdealSize&&(this._idealWidth?(s=s*this._idealWidth/r,r=this._idealWidth):this._idealHeight&&(r=r*this._idealHeight/s,s=this._idealHeight)),i.width===r&&i.height===s||(this.scaleTo(r,s),this.markAsDirty(),(this._idealWidth||this._idealHeight)&&this._rootContainer._markAllAsDirty()),this.invalidateRect(0,0,i.width-1,i.height-1)}_getGlobalViewport(){const e=this.getSize(),t=this._fullscreenViewport.toGlobal(e.width,e.height),i=Math.round(t.width*(1/this.rootContainer.scaleX)),r=Math.round(t.height*(1/this.rootContainer.scaleY));return t.x+=(t.width-i)/2,t.y+=(t.height-r)/2,t.width=i,t.height=r,t}getProjectedPosition(e,t){const i=this.getProjectedPositionWithZ(e,t);return new W.I9(i.x,i.y)}getProjectedPositionWithZ(e,t){const i=this.getScene();if(!i)return W.Pq.Zero();const r=this._getGlobalViewport(),s=W.Pq.Project(e,t,i.getTransformMatrix(),r);return new W.Pq(s.x,s.y,s.z)}_checkUpdate(e,t){if(!this._layerToDispose||!e||e.layerMask&this._layerToDispose.layerMask){if(this._isFullscreen&&this._linkedControls.length){const e=this.getScene();if(!e)return;const t=this._getGlobalViewport();for(const i of this._linkedControls){if(!i.isVisible)continue;const r=i._linkedMesh;if(!r||r.isDisposed()){Ue.S0.SetImmediate((()=>{i.linkWithMesh(null)}));continue}const s=r.getBoundingInfo?r.getBoundingInfo().boundingSphere.center:W.Pq.ZeroReadOnly,n=W.Pq.Project(s,r.getWorldMatrix(),e.getTransformMatrix(),t);n.z<0||n.z>1?i.notRenderable=!0:(i.notRenderable=!1,this.useInvalidateRectOptimization&&i.invalidateRect(),i._moveToProjectedPosition(n))}}(this._isDirty||this._rootContainer.isDirty)&&(this._isDirty=!1,this._render(t),t||this.update(this.applyYInversionOnUpdate,this.premulAlpha,$B.AllowGPUOptimizations))}}_render(e){const t=this.getSize(),i=t.width,r=t.height,s=this.getContext();if(s.font="18px Arial",s.strokeStyle="white",this.onGuiReadyObservable.hasObservers()&&this._checkGuiIsReady(),this._rootChildrenHaveChanged){const e=this.getScene()?.activeCamera;e&&(this._rootChildrenHaveChanged=!1,this._checkUpdate(e,!0))}this.onBeginLayoutObservable.notifyObservers(this);const n=new sB(0,0,i,r);this._numLayoutCalls=0,this._rootContainer._layout(n,s),this.onEndLayoutObservable.notifyObservers(this),this._isDirty=!1,e||(this._invalidatedRectangle?this._clearMeasure.copyFrom(this._invalidatedRectangle):this._clearMeasure.copyFromFloats(0,0,i,r),s.clearRect(this._clearMeasure.left,this._clearMeasure.top,this._clearMeasure.width,this._clearMeasure.height),this._background&&(s.save(),s.fillStyle=this._background,s.fillRect(this._clearMeasure.left,this._clearMeasure.top,this._clearMeasure.width,this._clearMeasure.height),s.restore()),this.onBeginRenderObservable.notifyObservers(this),this._numRenderCalls=0,this._rootContainer._render(s,this._invalidatedRectangle),this.onEndRenderObservable.notifyObservers(this),this._invalidatedRectangle=null)}_changeCursor(e){this._rootElement&&(this._rootElement.style.cursor=e,this._cursorChanged=!0)}_registerLastControlDown(e,t){this._lastControlDown[t]=e,this.onControlPickedObservable.notifyObservers(e)}_doPicking(e,t,i,r,s,n,o,a){const l=this.getScene();if(!l||this.disablePicking)return;const h=l.getEngine(),c=this.getSize();if(this._isFullscreen){const i=l.cameraToUseForPointers||l.activeCamera;if(!i)return;const r=i.viewport;e*=c.width/(h.getRenderWidth()*r.width),t*=c.height/(h.getRenderHeight()*r.height)}if(this._capturingControl[s])return this._capturingControl[s].isPointerBlocker&&(this._shouldBlockPointer=!0),void this._capturingControl[s]._processObservables(r,e,t,i,s,n);this._cursorChanged=!1,this._rootContainer._processPicking(e,t,i,r,s,n,o,a)||(l.doNotHandleCursors||this._changeCursor(""),r===yi.Zp.POINTERMOVE&&this._lastControlOver[s]&&(this._lastControlOver[s]._onPointerOut(this._lastControlOver[s],i),delete this._lastControlOver[s])),this._cursorChanged||l.doNotHandleCursors||this._changeCursor(""),this._manageFocus()}_cleanControlAfterRemovalFromList(e,t){for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&e[i]===t&&delete e[i]}_cleanControlAfterRemoval(e){this._cleanControlAfterRemovalFromList(this._lastControlDown,e),this._cleanControlAfterRemovalFromList(this._lastControlOver,e)}pick(e,t,i=null){this._isFullscreen&&this._scene&&this._translateToPicking(this._scene,new et.L(0,0,0,0),i,e,t)}_translateToPicking(e,t,i,r=e.pointerX,s=e.pointerY){const n=e.cameraToUseForPointers||e.activeCamera,o=e.getEngine(),a=e.cameraToUseForPointers;if(n)if(n.rigCameras.length){const i=new et.L(0,0,1,1);n.rigCameras.forEach((n=>{n.viewport.toGlobalToRef(o.getRenderWidth(),o.getRenderHeight(),i);const a=r/o.getHardwareScalingLevel()-i.x,l=s/o.getHardwareScalingLevel()-(o.getRenderHeight()-i.y-i.height);a<0||l<0||r>i.width||s>i.height||(e.cameraToUseForPointers=n,t.x=i.x,t.y=i.y,t.width=i.width,t.height=i.height)}))}else n.viewport.toGlobalToRef(o.getRenderWidth(),o.getRenderHeight(),t);else t.x=0,t.y=0,t.width=o.getRenderWidth(),t.height=o.getRenderHeight();const l=r/o.getHardwareScalingLevel()-t.x,h=s/o.getHardwareScalingLevel()-(o.getRenderHeight()-t.y-t.height);if(this._shouldBlockPointer=!1,i){const e=i.event.pointerId||this._defaultMousePointerId;this._doPicking(l,h,i,i.type,e,i.event.button,i.event.deltaX,i.event.deltaY),(this._shouldBlockPointer&&!(i.type&this.skipBlockEvents)||this._capturingControl[e])&&(i.skipOnPointerObservable=!0)}else this._doPicking(l,h,null,yi.Zp.POINTERMOVE,this._defaultMousePointerId,0);e.cameraToUseForPointers=a}attach(){const e=this.getScene();if(!e)return;const t=new et.L(0,0,0,0);this._prePointerObserver=e.onPrePointerObservable.add((i=>{if((!e.isPointerCaptured(i.event.pointerId)||i.type!==yi.Zp.POINTERUP||this._capturedPointerIds.has(i.event.pointerId))&&(i.type===yi.Zp.POINTERMOVE||i.type===yi.Zp.POINTERUP||i.type===yi.Zp.POINTERDOWN||i.type===yi.Zp.POINTERWHEEL||i.type===yi.Zp.POINTERTAP)){if(i.type===yi.Zp.POINTERMOVE){if(e.isPointerCaptured(i.event.pointerId))return;i.event.pointerId&&(this._defaultMousePointerId=i.event.pointerId)}this._translateToPicking(e,t,i)}})),this._attachPickingToSceneRender(e,(()=>this._translateToPicking(e,t,null)),!1),this._attachToOnPointerOut(e),this._attachToOnBlur(e)}_focusNextElement(e=!0){const t=[];if(this.executeOnAllControls((e=>{e.isFocusInvisible||!e.isVisible||e.tabIndex<0||t.push(e)})),0===t.length)return;t.sort(((e,t)=>0===e.tabIndex?1:0===t.tabIndex?-1:e.tabIndex-t.tabIndex)),this._focusProperties.total=t.length;let i=-1;this._focusedControl?(i=t.indexOf(this._focusedControl)+(e?1:-1),i<0?i=t.length-1:i>=t.length&&(i=0)):i=e?0:t.length-1,t[i].focus(),this._focusProperties.index=i}registerClipboardEvents(){self.addEventListener("copy",this._onClipboardCopy,!1),self.addEventListener("cut",this._onClipboardCut,!1),self.addEventListener("paste",this._onClipboardPaste,!1)}unRegisterClipboardEvents(){self.removeEventListener("copy",this._onClipboardCopy),self.removeEventListener("cut",this._onClipboardCut),self.removeEventListener("paste",this._onClipboardPaste)}_transformUvs(e){const t=this.getTextureMatrix();let i;if(t.isIdentityAs3x2())i=e;else{const r=W.AA.Matrix[0];t.getRowToRef(0,W.AA.Vector4[0]),t.getRowToRef(1,W.AA.Vector4[1]),t.getRowToRef(2,W.AA.Vector4[2]);const s=W.AA.Vector4[0],n=W.AA.Vector4[1],o=W.AA.Vector4[2];r.setRowFromFloats(0,s.x,s.y,0,0),r.setRowFromFloats(1,n.x,n.y,0,0),r.setRowFromFloats(2,0,0,1,0),r.setRowFromFloats(3,o.x,o.y,0,1),i=W.AA.Vector2[0],W.I9.TransformToRef(e,r,i)}if((this.wrapU===vi.g.WRAP_ADDRESSMODE||this.wrapU===vi.g.MIRROR_ADDRESSMODE)&&i.x>1){let e=i.x-Math.trunc(i.x);this.wrapU===vi.g.MIRROR_ADDRESSMODE&&Math.trunc(i.x)%2==1&&(e=1-e),i.x=e}if((this.wrapV===vi.g.WRAP_ADDRESSMODE||this.wrapV===vi.g.MIRROR_ADDRESSMODE)&&i.y>1){let e=i.y-Math.trunc(i.y);this.wrapV===vi.g.MIRROR_ADDRESSMODE&&Math.trunc(i.x)%2==1&&(e=1-e),i.y=e}return i}attachToMesh(e,t=!0){const i=this.getScene();i&&(this._pointerObserver&&i.onPointerObservable.remove(this._pointerObserver),this._pointerObserver=i.onPointerObservable.add((t=>{if(t.type!==yi.Zp.POINTERMOVE&&t.type!==yi.Zp.POINTERUP&&t.type!==yi.Zp.POINTERDOWN&&t.type!==yi.Zp.POINTERWHEEL)return;t.type===yi.Zp.POINTERMOVE&&t.event.pointerId&&(this._defaultMousePointerId=t.event.pointerId);const i=t.event.pointerId||this._defaultMousePointerId;if(t.pickInfo&&t.pickInfo.hit&&t.pickInfo.pickedMesh===e){let e=t.pickInfo.getTextureCoordinates();if(e){e=this._transformUvs(e);const r=this.getSize();this._doPicking(e.x*r.width,(this.applyYInversionOnUpdate?1-e.y:e.y)*r.height,t,t.type,i,t.event.button,t.event.deltaX,t.event.deltaY)}}else if(t.type===yi.Zp.POINTERUP){if(this._lastControlDown[i]&&this._lastControlDown[i]._forcePointerUp(i),delete this._lastControlDown[i],this.focusedControl){const e=this.focusedControl.keepsFocusWith();let t=!0;if(e)for(const r of e){if(this===r._host)continue;const e=r._host;if(e._lastControlOver[i]&&e._lastControlOver[i].isAscendant(r)){t=!1;break}}t&&(this.focusedControl=null)}}else t.type===yi.Zp.POINTERMOVE&&(this._lastControlOver[i]&&this._lastControlOver[i]._onPointerOut(this._lastControlOver[i],t,!0),delete this._lastControlOver[i])})),e.enablePointerMoveEvents=t,this._attachPickingToSceneRender(i,(()=>{const t=this._defaultMousePointerId,r=i?.pick(i.pointerX,i.pointerY);if(r&&r.hit&&r.pickedMesh===e){let e=r.getTextureCoordinates();if(e){e=this._transformUvs(e);const i=this.getSize();this._doPicking(e.x*i.width,(this.applyYInversionOnUpdate?1-e.y:e.y)*i.height,null,yi.Zp.POINTERMOVE,t,0)}}else this._lastControlOver[t]&&this._lastControlOver[t]._onPointerOut(this._lastControlOver[t],null,!0),delete this._lastControlOver[t]}),!0),this._attachToOnPointerOut(i),this._attachToOnBlur(i))}moveFocusToControl(e){this.focusedControl=e,this._lastPickedControl=e,this._blockNextFocusCheck=!0}_manageFocus(){if(this._blockNextFocusCheck)return this._blockNextFocusCheck=!1,void(this._lastPickedControl=this._focusedControl);if(this._focusedControl&&this._focusedControl!==this._lastPickedControl){if(this._lastPickedControl.isFocusInvisible)return;this.focusedControl=null}}_attachPickingToSceneRender(e,t,i){this._sceneRenderObserver=e.onBeforeRenderObservable.add((()=>{this.checkPointerEveryFrame&&(this._linkedControls.length>0||i)&&t()}))}_attachToOnPointerOut(e){this._canvasPointerOutObserver=e.getEngine().onCanvasPointerOutObservable.add((e=>{this._lastControlOver[e.pointerId]&&this._lastControlOver[e.pointerId]._onPointerOut(this._lastControlOver[e.pointerId],null),delete this._lastControlOver[e.pointerId],this._lastControlDown[e.pointerId]&&this._lastControlDown[e.pointerId]!==this._capturingControl[e.pointerId]&&(this._lastControlDown[e.pointerId]._forcePointerUp(e.pointerId),delete this._lastControlDown[e.pointerId])}))}_attachToOnBlur(e){this._canvasBlurObserver=e.getEngine().onCanvasBlurObservable.add((()=>{Object.entries(this._lastControlDown).forEach((([,e])=>{e._onCanvasBlur()})),this.focusedControl=null,this._lastControlDown={}}))}serializeContent(){const e=this.getSize(),t={root:{},width:e.width,height:e.height};return this._rootContainer.serialize(t.root),t}parseSerializedObject(e,t,i){if(this._rootContainer=lB.Parse(e.root,this,i),t){const t=e.width,i=e.height;"number"==typeof t&&"number"==typeof i&&t>=0&&i>=0?this.scaleTo(t,i):this.scaleTo(1920,1080)}}clone(e,t){const i=this.getScene();if(!i)return this;const r=this.getSize(),s=this.serializeContent();let n;return n=this._isFullscreen?$B.CreateFullscreenUI(e??"Clone of "+this.name):t?$B.CreateForMesh(t,r.width,r.height):new $B(e??"Clone of "+this.name,r.width,r.height,i,!this.noMipmap,this.samplingMode),n.parseSerializedObject(s),n}static async ParseFromSnippetAsync(e,t,i,r){const s=i??$B.CreateFullscreenUI("ADT from snippet");if("_BLANK"===e)return s;const n=await $B._LoadURLContentAsync($B.SnippetUrl+"/"+e.replace(/#/g,"/"),!0);return s.parseSerializedObject(n,t,r),s}parseFromSnippetAsync(e,t,i){return $B.ParseFromSnippetAsync(e,t,this,i)}static async ParseFromFileAsync(e,t,i,r){const s=i??$B.CreateFullscreenUI("ADT from URL"),n=await $B._LoadURLContentAsync(e);return s.parseSerializedObject(n,t,r),s}parseFromURLAsync(e,t,i){return $B.ParseFromFileAsync(e,t,this,i)}static _LoadURLContentAsync(e,t=!1){return""===e?Promise.reject("No URL provided"):new Promise(((i,r)=>{const s=new go.u;s.addEventListener("readystatechange",(()=>{if(4==s.readyState)if(200==s.status){let e;if(t){const t=JSON.parse(JSON.parse(s.responseText).jsonPayload);e=t.encodedGui?new TextDecoder("utf-8").decode((0,bi.yS)(t.encodedGui)):t.gui}else e=s.responseText;const r=JSON.parse(e);i(r)}else r("Unable to load")})),s.open("GET",e),s.send()}))}static _Overlaps(e,t){return!(e.centerX>t.centerX+t.widthInPixels||e.centerX+e.widthInPixelst.centerY+t.heightInPixels)}static CreateForMesh(e,t=1024,i=1024,r=!0,s=!1,n,o=this._CreateMaterial,a=vi.g.TRILINEAR_SAMPLINGMODE){const l=(0,Au.z)(),h=new $B(`AdvancedDynamicTexture for ${e.name} [${l}]`,t,i,e.getScene(),!0,a,n);return o(e,l,h,s),h.attachToMesh(e,r),h}static _CreateMaterial(e,t,i,r){const s=(0,X.n9)("BABYLON.StandardMaterial");if(!s)throw"StandardMaterial needs to be imported before as it contains a side-effect required by your code.";const n=new s(`AdvancedDynamicTextureMaterial for ${e.name} [${t}]`,e.getScene());n.backFaceCulling=!1,n.diffuseColor=H.v9.Black(),n.specularColor=H.v9.Black(),r?(n.diffuseTexture=i,n.emissiveTexture=i,i.hasAlpha=!0):(n.emissiveTexture=i,n.opacityTexture=i),e.material=n}static CreateForMeshTexture(e,t=1024,i=1024,r=!0,s,n=vi.g.TRILINEAR_SAMPLINGMODE){const o=new $B(e.name+" AdvancedDynamicTexture",t,i,e.getScene(),!0,n,s);return o.attachToMesh(e,r),o}static CreateFullscreenUI(e,t=!0,i=null,r=vi.g.BILINEAR_SAMPLINGMODE,s=!1){const n=!i||i._isScene?new $B(e,0,0,i,!1,r):new $B(e,i),o=n.getScene(),a=new zv(e+"_layer",null,o,!t);if(a.texture=n,n._layerToDispose=a,n._isFullscreen=!0,n.useStandalone&&(a.layerMask=0),s&&o){const e=1/o.getEngine().getHardwareScalingLevel();n._rootContainer.scaleX=e,n._rootContainer.scaleY=e}return n.attach(),n}scale(e){super.scale(e),this.markAsDirty()}scaleTo(e,t){super.scaleTo(e,t),this.markAsDirty()}_checkGuiIsReady(){this.guiIsReady()&&(this.onGuiReadyObservable.notifyObservers(this),this.onGuiReadyObservable.clear())}guiIsReady(){return this._rootContainer.isReady()}}$B.SnippetUrl=Il.SnippetUrl,$B.AllowGPUOptimizations=!0;class QB{get renderTimeCounter(){return this._renderTime}get layoutTimeCounter(){return this._layoutTime}get captureRenderTime(){return this._captureRenderTime}set captureRenderTime(e){e!==this._captureRenderTime&&(this._captureRenderTime=e,e?(this._onBeginRenderObserver=this.texture.onBeginRenderObservable.add((()=>{this._renderTime.beginMonitoring()})),this._onEndRenderObserver=this.texture.onEndRenderObservable.add((()=>{this._renderTime.endMonitoring(!0)}))):(this.texture.onBeginRenderObservable.remove(this._onBeginRenderObserver),this._onBeginRenderObserver=null,this.texture.onEndRenderObservable.remove(this._onEndRenderObserver),this._onEndRenderObserver=null))}get captureLayoutTime(){return this._captureLayoutTime}set captureLayoutTime(e){e!==this._captureLayoutTime&&(this._captureLayoutTime=e,e?(this._onBeginLayoutObserver=this.texture.onBeginLayoutObservable.add((()=>{this._layoutTime.beginMonitoring()})),this._onEndLayoutObserver=this.texture.onEndLayoutObservable.add((()=>{this._layoutTime.endMonitoring(!0)}))):(this.texture.onBeginLayoutObservable.remove(this._onBeginLayoutObserver),this._onBeginLayoutObserver=null,this.texture.onEndLayoutObservable.remove(this._onEndLayoutObserver),this._onEndLayoutObserver=null))}constructor(e){this.texture=e,this._captureRenderTime=!1,this._renderTime=new on.A,this._captureLayoutTime=!1,this._layoutTime=new on.A,this._onBeginRenderObserver=null,this._onEndRenderObserver=null,this._onBeginLayoutObserver=null,this._onEndLayoutObserver=null}dispose(){this.texture.onBeginRenderObservable.remove(this._onBeginRenderObserver),this._onBeginRenderObserver=null,this.texture.onEndRenderObservable.remove(this._onEndRenderObserver),this._onEndRenderObserver=null,this.texture.onBeginLayoutObservable.remove(this._onBeginLayoutObserver),this._onBeginLayoutObserver=null,this.texture.onEndLayoutObservable.remove(this._onEndLayoutObserver),this._onEndLayoutObserver=null,this.texture=null}}class ZB extends kp{get disabled(){return this._disabled}set disabled(e){this._disabled=e,this._adt.disablePicking=e}get gui(){return this._adt}constructor(e,t,i){if(super(e,t),i){if(!i.useStandalone)throw new Error(`AdvancedDynamicTexture "${e}": the texture must have been created with the useStandalone property set to true`)}else i=$B.CreateFullscreenUI(e,void 0,{useStandalone:!0});this._adt=i,this.outputTexture=this._frameGraph.createDanglingHandle()}isReady(){return this._adt.guiIsReady()&&this._adt._layerToDispose.isReady()}record(){if(void 0===this.destinationTexture)throw new Error("FrameGraphGUITask: destinationTexture is required");this._frameGraph.resolveDanglingHandle(this.outputTexture,this.destinationTexture);const e=this._frameGraph.addRenderPass(this.name);e.setRenderTarget(this.outputTexture),e.setExecuteFunc((e=>{this._adt._checkUpdate(null),e.render(this._adt._layerToDispose)}));const t=this._frameGraph.addRenderPass(this.name+"_disabled",!0);t.setRenderTarget(this.outputTexture),t.setExecuteFunc((e=>{}))}dispose(){this._adt.dispose(),super.dispose()}}class JB extends wp{get task(){return this._frameGraphTask}get gui(){return this._frameGraphTask.gui}constructor(e,t,i){super(e,t,i),this.registerInput("destination",Rp.Texture),this.registerOutput("output",Rp.BasedOnInput),this.destination.addAcceptedConnectionPointTypes(Rp.TextureAll),this.output._typeConnectionSource=this.destination,this._gui=$B.CreateFullscreenUI(this.name,void 0,{useStandalone:!0}),this._frameGraphTask=new ZB(this.name,t,this._gui)}getClassName(){return"GUI.NodeRenderGraphGUIBlock"}get destination(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this.output.value=this._frameGraphTask.outputTexture;const t=this.destination.connectedPoint;t&&(this._frameGraphTask.destinationTexture=t.value)}}(0,X.Y5)("BABYLON.GUI.NodeRenderGraphGUIBlock",JB);const eV="XmlLoader Exception : XML file is malformed or corrupted.";class tV{constructor(e=null){this._nodes={},this._nodeTypes={element:1,attribute:2,text:3},this._isLoaded=!1,this._objectAttributes={textHorizontalAlignment:1,textVerticalAlignment:2,horizontalAlignment:3,verticalAlignment:4,stretch:5},e&&(this._parentClass=e)}_getChainElement(e){let t=window;this._parentClass&&(t=this._parentClass);let i=e;i=i.split(".");for(let e=0;e0&&u>d)throw"XmlLoader Exception : In the Grid element, the number of columns is defined in the first row, do not add more columns in the subsequent rows.";if(0==c){if(!n[e].attributes.getNamedItem("width"))throw"XmlLoader Exception : Width must be defined for all the grid columns in the first row";r=Number(n[e].attributes.getNamedItem("width").nodeValue),h=!!n[e].attributes.getNamedItem("isPixel")&&JSON.parse(n[e].attributes.getNamedItem("isPixel").nodeValue),t.addColumnDefinition(r,h)}a=n[e].children;for(let e=0;e{if(4===s.readyState&&200===s.status){if(!s.responseXML){if(r)return void r(eV);throw eV}const e=s.responseXML.documentElement;this._parseXml(e.firstChild,t),this._isLoaded=!0,i&&i()}},s.onerror=function(){r&&r("an error occurred during loading the layout")},s.open("GET",e,!0),s.send()}async loadLayoutAsync(e,t){return new Promise(((i,r)=>{this.loadLayout(e,t,i,r)}))}}class iV extends W.Pq{constructor(e,t=0){super(e.x,e.y,e.z),this.buttonIndex=t}}class rV{get position(){return this._node?this._node.position:(this._position=this._position||W.Pq.Zero(),this._position)}set position(e){this._position=e,this._node&&(this._node.position=this._position)}get scaling(){return this._node?this._node.scaling:(this._scaling=this.scaling||new W.Pq(1,1,1),this._scaling)}set scaling(e){this._scaling=e,this._node&&(this._isScaledByManager=!1,this._node.scaling=this._scaling)}get behaviors(){return this._behaviors}addBehavior(e){if(-1!==this._behaviors.indexOf(e))return this;e.init();const t=this._host.scene;return t.isLoading?t.onDataLoadedObservable.addOnce((()=>{e.attach(this)})):e.attach(this),this._behaviors.push(e),this}removeBehavior(e){const t=this._behaviors.indexOf(e);return-1===t||(this._behaviors[t].detach(),this._behaviors.splice(t,1)),this}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}get isVisible(){return this._isVisible}set isVisible(e){if(this._isVisible===e)return;this._isVisible=e;const t=this.mesh;t&&t.setEnabled(e)}constructor(e){this.name=e,this._downCount=0,this._enterCount=-1,this._downPointerIds={},this._isVisible=!0,this._isScaledByManager=!1,this.onPointerMoveObservable=new z.cP,this.onPointerOutObservable=new z.cP,this.onPointerDownObservable=new z.cP,this.onPointerUpObservable=new z.cP,this.onPointerClickObservable=new z.cP,this.onPointerEnterObservable=new z.cP,this._behaviors=new Array}get typeName(){return this._getTypeName()}getClassName(){return this._getTypeName()}_getTypeName(){return"Control3D"}get node(){return this._node}get mesh(){return this._node instanceof Nt?this._node:null}linkToTransformNode(e){return this._node&&(this._node.parent=e),this}_prepareNode(e){if(!this._node){if(this._node=this._createNode(e),!this.node)return;this._position&&(this.node.position=this._position),this._scaling&&(this.node.scaling=this._scaling),this._injectGUI3DReservedDataStore(this.node).control=this;const t=this.mesh;t&&(t.isPickable=!0,this._affectMaterial(t))}}_injectGUI3DReservedDataStore(e){return e.reservedDataStore=e.reservedDataStore??{},e.reservedDataStore.GUI3D=e.reservedDataStore.GUI3D??{},e.reservedDataStore.GUI3D}_createNode(e){return null}_affectMaterial(e){e.material=null}_isTouchButton3D(e){return void 0!==e._generatePointerEventType}_onPointerMove(e,t){this.onPointerMoveObservable.notifyObservers(t,-1,e,this)}_onPointerEnter(e){return-1===this._enterCount&&(this._enterCount=0),this._enterCount++,!(this._enterCount>1||(this.onPointerEnterObservable.notifyObservers(this,-1,e,this),this.pointerEnterAnimation&&this.pointerEnterAnimation(),0))}_onPointerOut(e){this._enterCount--,this._enterCount>0||(this._enterCount=0,this.onPointerOutObservable.notifyObservers(this,-1,e,this),this.pointerOutAnimation&&this.pointerOutAnimation())}_onPointerDown(e,t,i,r){return this._downCount++,this._downPointerIds[i]=this._downPointerIds[i]+1||1,1===this._downCount&&(this.onPointerDownObservable.notifyObservers(new iV(t,r),-1,e,this),this.pointerDownAnimation&&this.pointerDownAnimation(),!0)}_onPointerUp(e,t,i,r,s){this._downCount--,this._downPointerIds[i]--,this._downPointerIds[i]<=0&&delete this._downPointerIds[i],this._downCount<0?this._downCount=0:0==this._downCount&&(s&&(this._enterCount>0||-1===this._enterCount)&&this.onPointerClickObservable.notifyObservers(new iV(t,r),-1,e,this),this.onPointerUpObservable.notifyObservers(new iV(t,r),-1,e,this),this.pointerUpAnimation&&this.pointerUpAnimation())}forcePointerUp(e=null){if(null!==e)this._onPointerUp(this,W.Pq.Zero(),e,0,!0);else{for(const e in this._downPointerIds)this._onPointerUp(this,W.Pq.Zero(),+e,0,!0);this._downCount>0&&(this._downCount=1,this._onPointerUp(this,W.Pq.Zero(),0,0,!0))}}_processObservables(e,t,i,r,s){if(this._isTouchButton3D(this)&&i&&(e=this._generatePointerEventType(e,i,this._downCount)),e===yi.Zp.POINTERMOVE){this._onPointerMove(this,t);const e=this._host._lastControlOver[r];return e&&e!==this&&e._onPointerOut(this),e!==this&&this._onPointerEnter(this),this._host._lastControlOver[r]=this,!0}return e===yi.Zp.POINTERDOWN?(this._onPointerDown(this,t,r,s),this._host._lastControlDown[r]=this,this._host._lastPickedControl=this,!0):(e===yi.Zp.POINTERUP||e===yi.Zp.POINTERDOUBLETAP)&&(this._host._lastControlDown[r]&&this._host._lastControlDown[r]._onPointerUp(this,t,r,s,!0),delete this._host._lastControlDown[r],!0)}_disposeNode(){this._node&&(this._node.dispose(),this._node=null)}dispose(){this.onPointerDownObservable.clear(),this.onPointerEnterObservable.clear(),this.onPointerMoveObservable.clear(),this.onPointerOutObservable.clear(),this.onPointerUpObservable.clear(),this.onPointerClickObservable.clear(),this._disposeNode();for(const e of this._behaviors)e.detach()}}class sV extends rV{constructor(){super(...arguments),this._contentResolution=512,this._contentScaleRatio=2}get content(){return this._content}set content(e){if(this._content=e,e&&this._host&&this._host.utilityLayer){if(this._facadeTexture)this._facadeTexture.rootContainer.clearControls();else{const e="number"==typeof this._contentResolution?this._contentResolution:this._contentResolution.width,t="number"==typeof this._contentResolution?this._contentResolution:this._contentResolution.height;this._facadeTexture=new $B("Facade",e,t,this._host.utilityLayer.utilityLayerScene,!0,vi.g.TRILINEAR_SAMPLINGMODE),this._setFacadeTextureScaling(),this._facadeTexture.premulAlpha=!0}this._facadeTexture.addControl(e),this._applyFacade(this._facadeTexture)}}_setFacadeTextureScaling(){this._facadeTexture&&("number"!=typeof this._contentResolution&&(this._contentScaleRatioY=this._contentResolution.height/this._contentResolution.width*this._contentScaleRatio),this._facadeTexture.rootContainer.scaleX=this._contentScaleRatio,this._facadeTexture.rootContainer.scaleY=this._contentScaleRatioY??this._contentScaleRatio)}get contentResolution(){return this._contentResolution}set contentResolution(e){const t="number"==typeof e?e:e.width,i="number"==typeof e?e:e.height,r="number"==typeof this._contentResolution?this._contentResolution:this._contentResolution.width,s="number"==typeof this._contentResolution?this._contentResolution:this._contentResolution.height;t===r&&i===s||(this._contentResolution=e,this._resetContent())}_disposeFacadeTexture(){this._facadeTexture&&(this._facadeTexture.dispose(),this._facadeTexture=null)}_resetContent(){this._disposeFacadeTexture(),this.content=this._content}_applyFacade(e){}}class nV extends sV{constructor(e){super(e)}_getTypeName(){return"AbstractButton3D"}_createNode(e){return new Pt("button"+this.name,e)}}class oV extends nV{constructor(e,t){super(e),this._options={width:1,height:1,depth:.08,...t},this.pointerEnterAnimation=()=>{this.mesh&&(this._currentMaterial.emissiveColor=H.v9.Red())},this.pointerOutAnimation=()=>{this._currentMaterial.emissiveColor=H.v9.Black()},this.pointerDownAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/.95)}}_applyFacade(e){this._currentMaterial.emissiveTexture=e}_getTypeName(){return"Button3D"}_createNode(e){const t=new Array(6);for(let e=0;e<6;e++)t[e]=new W.IU(0,0,0,0);e.useRightHandedSystem?t[0].copyFromFloats(1,0,0,1):t[1].copyFromFloats(0,0,1,1);const i=Ko(this.name+"_rootMesh",{width:this._options.width,height:this._options.height,depth:this._options.depth,faceUV:t,wrap:!0},e);return this._contentScaleRatioY=this._contentScaleRatio*this._options.width/this._options.height,this._setFacadeTextureScaling(),i}_affectMaterial(e){const t=new Un(this.name+"Material",e.getScene());t.specularColor=H.v9.Black(),e.material=t,this._currentMaterial=t,this._resetContent()}dispose(){super.dispose(),this._disposeFacadeTexture(),this._currentMaterial&&this._currentMaterial.dispose()}}class aV extends rV{get children(){return this._children}get blockLayout(){return this._blockLayout}set blockLayout(e){this._blockLayout!==e&&(this._blockLayout=e,this._blockLayout||this._arrangeChildren())}constructor(e){super(e),this._blockLayout=!1,this._children=new Array}updateLayout(){return this._arrangeChildren(),this}containsControl(e){return-1!==this._children.indexOf(e)}addControl(e){return-1!==this._children.indexOf(e)||(e.parent=this,e._host=this._host,this._children.push(e),this._host.utilityLayer&&(e._prepareNode(this._host.utilityLayer.utilityLayerScene),e.node&&(e.node.parent=this.node),this.blockLayout||this._arrangeChildren())),this}_arrangeChildren(){}_createNode(e){return new Pt("ContainerNode",e)}removeControl(e){const t=this._children.indexOf(e);return-1!==t&&(this._children.splice(t,1),e.parent=null,e._disposeNode()),this}_getTypeName(){return"Container3D"}dispose(){for(const e of this._children)e.dispose();this._children.length=0,super.dispose()}}aV.UNSET_ORIENTATION=0,aV.FACEORIGIN_ORIENTATION=1,aV.FACEORIGINREVERSED_ORIENTATION=2,aV.FACEFORWARD_ORIENTATION=3,aV.FACEFORWARDREVERSED_ORIENTATION=4;class lV extends aV{get orientation(){return this._orientation}set orientation(e){this._orientation!==e&&(this._orientation=e,Ue.S0.SetImmediate((()=>{this._arrangeChildren()})))}get columns(){return this._columns}set columns(e){this._columns!==e&&(this._columns=e,this._rowThenColum=!0,Ue.S0.SetImmediate((()=>{this._arrangeChildren()})))}get rows(){return this._rows}set rows(e){this._rows!==e&&(this._rows=e,this._rowThenColum=!1,Ue.S0.SetImmediate((()=>{this._arrangeChildren()})))}constructor(e){super(e),this._columns=10,this._rows=0,this._rowThenColum=!0,this._orientation=aV.FACEORIGIN_ORIENTATION,this.margin=0}_arrangeChildren(){this._cellWidth=0,this._cellHeight=0;let e=0,t=0,i=0;for(const e of this._children){if(!e.mesh)continue;i++,e.mesh.computeWorldMatrix(!0);const t=e.mesh.getBoundingInfo().boundingBox.extendSize,r=e.mesh.getDescendants(!1);for(const e of r){e.computeWorldMatrix(!0);const i=e;if("function"==typeof i.getBoundingInfo){const e=i.getBoundingInfo().boundingBox.extendSize;t.x=Math.max(t.x,e.x),t.y=Math.max(t.y,e.y),t.z=Math.max(t.z,e.z)}}this._cellWidth=Math.max(this._cellWidth,2*t.x),this._cellHeight=Math.max(this._cellHeight,2*t.y)}this._cellWidth+=2*this.margin,this._cellHeight+=2*this.margin,this._rowThenColum?(t=this._columns,e=Math.ceil(i/this._columns)):(e=this._rows,t=Math.ceil(i/this._rows));const r=.5*t*this._cellWidth,s=.5*e*this._cellHeight,n=[];let o=0;if(this._rowThenColum)for(let a=0;ai));e++);else for(let a=0;ai));t++);o=0;for(const e of this._children)e.mesh&&(this._mapGridNode(e,n[o]),o++);this._finalProcessing()}_finalProcessing(){}}class hV extends lV{constructor(){super(...arguments),this._radius=5}get radius(){return this._radius}set radius(e){this._radius!==e&&(this._radius=e,Ue.S0.SetImmediate((()=>{this._arrangeChildren()})))}_mapGridNode(e,t){const i=e.mesh;if(!i)return;const r=this._cylindricalMapping(t);switch(e.position=r,this.orientation){case aV.FACEORIGIN_ORIENTATION:i.lookAt(new W.Pq(2*r.x,r.y,2*r.z));break;case aV.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new W.Pq(-r.x,r.y,-r.z));break;case aV.FACEFORWARD_ORIENTATION:break;case aV.FACEFORWARDREVERSED_ORIENTATION:i.rotate(Mt._0.Y,Math.PI,0)}}_cylindricalMapping(e){const t=new W.Pq(0,e.y,this._radius),i=e.x/this._radius;return W.uq.RotationYawPitchRollToRef(i,0,0,W.AA.Matrix[0]),W.Pq.TransformNormal(t,W.AA.Matrix[0])}}Cs.l.ShadersStore.fluentVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 world;uniform mat4 viewProjection;varying vec2 vUV;\n#ifdef BORDER\nvarying vec2 scaleInfo;uniform float borderWidth;uniform vec3 scaleFactor;\n#endif\n#ifdef HOVERLIGHT\nvarying vec3 worldPosition;\n#endif\nvoid main(void) {vUV=uv;\n#ifdef BORDER\nvec3 scale=scaleFactor;float minScale=min(min(scale.x,scale.y),scale.z);float maxScale=max(max(scale.x,scale.y),scale.z);float minOverMiddleScale=minScale/(scale.x+scale.y+scale.z-minScale-maxScale);float areaYZ=scale.y*scale.z;float areaXZ=scale.x*scale.z;float areaXY=scale.x*scale.y;float scaledBorderWidth=borderWidth; \nif (abs(normal.x)==1.0) \n{scale.x=scale.y;scale.y=scale.z;if (areaYZ>areaXZ && areaYZ>areaXY)\n{scaledBorderWidth*=minOverMiddleScale;}}\nelse if (abs(normal.y)==1.0) \n{scale.x=scale.z;if (areaXZ>areaXY && areaXZ>areaYZ)\n{scaledBorderWidth*=minOverMiddleScale;}}\nelse \n{if (areaXY>areaYZ && areaXY>areaXZ)\n{scaledBorderWidth*=minOverMiddleScale;}}\nfloat scaleRatio=min(scale.x,scale.y)/max(scale.x,scale.y);if (scale.x>scale.y)\n{scaleInfo.x=1.0-(scaledBorderWidth*scaleRatio);scaleInfo.y=1.0-scaledBorderWidth;}\nelse\n{scaleInfo.x=1.0-scaledBorderWidth;scaleInfo.y=1.0-(scaledBorderWidth*scaleRatio);} \n#endif \nvec4 worldPos=world*vec4(position,1.0);\n#ifdef HOVERLIGHT\nworldPosition=worldPos.xyz;\n#endif\ngl_Position=viewProjection*worldPos;}\n";Cs.l.ShadersStore.fluentPixelShader="precision highp float;varying vec2 vUV;uniform vec4 albedoColor;\n#ifdef INNERGLOW\nuniform vec4 innerGlowColor;\n#endif\n#ifdef BORDER\nvarying vec2 scaleInfo;uniform float edgeSmoothingValue;uniform float borderMinValue;\n#endif\n#ifdef HOVERLIGHT\nvarying vec3 worldPosition;uniform vec3 hoverPosition;uniform vec4 hoverColor;uniform float hoverRadius;\n#endif\n#ifdef TEXTURE\nuniform sampler2D albedoSampler;uniform mat4 textureMatrix;vec2 finalUV;\n#endif\nvoid main(void) {vec3 albedo=albedoColor.rgb;float alpha=albedoColor.a;\n#ifdef TEXTURE\nfinalUV=vec2(textureMatrix*vec4(vUV,1.0,0.0));albedo=texture2D(albedoSampler,finalUV).rgb;\n#endif\n#ifdef HOVERLIGHT\nfloat pointToHover=(1.0-clamp(length(hoverPosition-worldPosition)/hoverRadius,0.,1.))*hoverColor.a;albedo=clamp(albedo+hoverColor.rgb*pointToHover,0.,1.);\n#else\nfloat pointToHover=1.0;\n#endif\n#ifdef BORDER \nfloat borderPower=10.0;float inverseBorderPower=1.0/borderPower;vec3 borderColor=albedo*borderPower;vec2 distanceToEdge;distanceToEdge.x=abs(vUV.x-0.5)*2.0;distanceToEdge.y=abs(vUV.y-0.5)*2.0;float borderValue=max(smoothstep(scaleInfo.x-edgeSmoothingValue,scaleInfo.x+edgeSmoothingValue,distanceToEdge.x),\nsmoothstep(scaleInfo.y-edgeSmoothingValue,scaleInfo.y+edgeSmoothingValue,distanceToEdge.y));borderColor=borderColor*borderValue*max(borderMinValue*inverseBorderPower,pointToHover); \nalbedo+=borderColor;alpha=max(alpha,borderValue);\n#endif\n#ifdef INNERGLOW\nvec2 uvGlow=(vUV-vec2(0.5,0.5))*(innerGlowColor.a*2.0);uvGlow=uvGlow*uvGlow;uvGlow=uvGlow*uvGlow;albedo+=mix(vec3(0.0,0.0,0.0),innerGlowColor.rgb,uvGlow.x+uvGlow.y); \n#endif\ngl_FragColor=vec4(albedo,alpha);}";class cV extends xn{constructor(){super(),this.INNERGLOW=!1,this.BORDER=!1,this.HOVERLIGHT=!1,this.TEXTURE=!1,this.rebuild()}}class uV extends bn{constructor(e,t){super(e,t),this.innerGlowColorIntensity=.5,this.innerGlowColor=new H.v9(1,1,1),this.albedoColor=new H.v9(.3,.35,.4),this.renderBorders=!1,this.borderWidth=.5,this.edgeSmoothingValue=.02,this.borderMinValue=.1,this.renderHoverLight=!1,this.hoverRadius=.01,this.hoverColor=new H.ov(.3,.3,.3,1),this.hoverPosition=W.Pq.Zero()}needAlphaBlending(){return 1!==this.alpha}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new cV);const r=this.getScene(),s=t.materialDefines;if(!this.checkReadyOnEveryCall&&t.effect&&s._renderId===r.getRenderId())return!0;if(s._areTexturesDirty)if(s.INNERGLOW=this.innerGlowColorIntensity>0,s.BORDER=this.renderBorders,s.HOVERLIGHT=this.renderHoverLight,this._albedoTexture){if(!this._albedoTexture.isReadyOrNotBlocking())return!1;s.TEXTURE=!0}else s.TEXTURE=!1;const n=r.getEngine();if(s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=[st.R.PositionKind];e.push(st.R.NormalKind),e.push(st.R.UVKind);const i="fluent",o=["world","viewProjection","innerGlowColor","albedoColor","borderWidth","edgeSmoothingValue","scaleFactor","borderMinValue","hoverColor","hoverPosition","hoverRadius","textureMatrix"],a=["albedoSampler"],l=[];(0,Bt.Bb)({uniformsNames:o,uniformBuffersNames:l,samplers:a,defines:s,maxSimultaneousLights:4});const h=s.toString();t.setEffect(r.getEngine().createEffect(i,{attributes:e,uniformsNames:o,uniformBuffersNames:l,samplers:a,defines:h,fallbacks:null,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;if(n){if(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),this._mustRebind(r,n,i)&&(this._activeEffect.setColor4("albedoColor",this.albedoColor,this.alpha),s.INNERGLOW&&this._activeEffect.setColor4("innerGlowColor",this.innerGlowColor,this.innerGlowColorIntensity),s.BORDER&&(this._activeEffect.setFloat("borderWidth",this.borderWidth),this._activeEffect.setFloat("edgeSmoothingValue",this.edgeSmoothingValue),this._activeEffect.setFloat("borderMinValue",this.borderMinValue),t.getBoundingInfo().boundingBox.extendSize.multiplyToRef(t.scaling,W.AA.Vector3[0]),this._activeEffect.setVector3("scaleFactor",W.AA.Vector3[0])),s.HOVERLIGHT&&(this._activeEffect.setDirectColor4("hoverColor",this.hoverColor),this._activeEffect.setFloat("hoverRadius",this.hoverRadius),this._activeEffect.setVector3("hoverPosition",this.hoverPosition)),s.TEXTURE&&this._albedoTexture)){this._activeEffect.setTexture("albedoSampler",this._albedoTexture);const e=this._albedoTexture.getTextureMatrix();this._activeEffect.setMatrix("textureMatrix",e)}this._afterBind(t,this._activeEffect,i)}}getActiveTextures(){return super.getActiveTextures()}hasTexture(e){return!!super.hasTexture(e)}dispose(e){super.dispose(e)}clone(e){return it.p.Clone((()=>new uV(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GUI.FluentMaterial",e}getClassName(){return"FluentMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new uV(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],uV.prototype,"innerGlowColorIntensity",void 0),(0,je.Cg)([(0,$e.jT)()],uV.prototype,"innerGlowColor",void 0),(0,je.Cg)([(0,$e.jT)()],uV.prototype,"albedoColor",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],uV.prototype,"renderBorders",void 0),(0,je.Cg)([(0,$e.lK)()],uV.prototype,"borderWidth",void 0),(0,je.Cg)([(0,$e.lK)()],uV.prototype,"edgeSmoothingValue",void 0),(0,je.Cg)([(0,$e.lK)()],uV.prototype,"borderMinValue",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],uV.prototype,"renderHoverLight",void 0),(0,je.Cg)([(0,$e.lK)()],uV.prototype,"hoverRadius",void 0),(0,je.Cg)([(0,$e.qK)()],uV.prototype,"hoverColor",void 0),(0,je.Cg)([(0,$e.P_)()],uV.prototype,"hoverPosition",void 0),(0,je.Cg)([(0,$e.uM)("albedoTexture")],uV.prototype,"_albedoTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesAndMiscDirty")],uV.prototype,"albedoTexture",void 0),(0,X.Y5)("BABYLON.GUI.FluentMaterial",uV);class dV extends lV{get backPlateMargin(){return this._backPlateMargin}set backPlateMargin(e){this._backPlateMargin=e,this._children.length>=1&&(this.children.forEach((e=>{this._updateCurrentMinMax(e.position)})),this._updateMargins())}_createNode(e){const t=new Yt(`menu_${this.name}`,e);return this._backPlate=Ko("backPlate"+this.name,{size:1},e),this._backPlate.parent=t,t}_affectMaterial(e){this._backPlateMaterial=new uV(this.name+"backPlateMaterial",e.getScene()),this._backPlateMaterial.albedoColor=new H.v9(.08,.15,.55),this._backPlateMaterial.renderBorders=!0,this._backPlateMaterial.renderHoverLight=!0,this._pickedPointObserver=this._host.onPickedPointChangedObservable.add((e=>{e?(this._backPlateMaterial.hoverPosition=e,this._backPlateMaterial.hoverColor.a=1):this._backPlateMaterial.hoverColor.a=0})),this._backPlate.material=this._backPlateMaterial}_mapGridNode(e,t){e.mesh&&(e.position=t.clone(),this._updateCurrentMinMax(t))}_finalProcessing(){this._updateMargins()}_updateCurrentMinMax(e){this._currentMin||(this._currentMin=e.clone(),this._currentMax=e.clone()),this._currentMin.minimizeInPlace(e),this._currentMax.maximizeInPlace(e)}_updateMargins(){if(this._children.length>0){this._currentMin.addInPlaceFromFloats(-this._cellWidth/2,-this._cellHeight/2,0),this._currentMax.addInPlaceFromFloats(this._cellWidth/2,this._cellHeight/2,0);const e=this._currentMax.subtract(this._currentMin);this._backPlate.scaling.x=e.x+this._cellWidth*this.backPlateMargin,this._backPlate.scaling.y=e.y+this._cellHeight*this.backPlateMargin,this._backPlate.scaling.z=.001;for(let t=0;t0.0 ? g : 1.0;Gradient2=Position_Object.z>0.0 ? 1.0 : g;} else {Gradient1=g+(1.0-g)*(Radial_Gradient);Gradient2=1.0;}}\nvoid Pick_Radius_B144(\nfloat Radius,\nfloat Radius_Top_Left,\nfloat Radius_Top_Right,\nfloat Radius_Bottom_Left,\nfloat Radius_Bottom_Right,\nvec3 Position,\nout float Result)\n{bool whichY=Position.y>0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid main()\n{vec3 Nrm_World_Q128;Nrm_World_Q128=normalize((world*vec4(normal,0.0)).xyz);vec3 Tangent_World_Q131;vec3 Tangent_World_N_Q131;float Tangent_Length_Q131;Tangent_World_Q131=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q131=length(Tangent_World_Q131);Tangent_World_N_Q131=Tangent_World_Q131/Tangent_Length_Q131;vec3 Binormal_World_Q132;vec3 Binormal_World_N_Q132;float Binormal_Length_Q132;Object_To_World_Dir_B132(vec3(0,1,0),Binormal_World_Q132,Binormal_World_N_Q132,Binormal_Length_Q132);float Anisotropy_Q133=Tangent_Length_Q131/Binormal_Length_Q132;vec3 Result_Q177;Result_Q177=mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(_Use_Global_Left_Index_));vec3 Result_Q178;Result_Q178=mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(_Use_Global_Right_Index_));float Result_Q144;Pick_Radius_B144(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q144);vec3 Dir_Q140;PickDir_B140(_Angle_,Tangent_World_N_Q131,Binormal_World_N_Q132,Dir_Q140);float Radius_Q147;float Line_Width_Q147;RelativeOrAbsoluteDetail_B147(Result_Q144,_Line_Width_,_Absolute_Sizes_,Binormal_Length_Q132,Radius_Q147,Line_Width_Q147);vec4 Out_Color_Q145=vec4(Radius_Q147,Line_Width_Q147,0,1);vec3 New_P_Q129;vec2 New_UV_Q129;float Radial_Gradient_Q129;vec3 Radial_Dir_Q129;Move_Verts_B129(Anisotropy_Q133,position,Radius_Q147,New_P_Q129,New_UV_Q129,Radial_Gradient_Q129,Radial_Dir_Q129);vec3 Pos_World_Q115;Object_To_World_Pos_B115(New_P_Q129,Pos_World_Q115);vec4 Blob_Info_Q180;\n#if BLOB_ENABLE\nBlob_Vertex_B180(Pos_World_Q115,Nrm_World_Q128,Tangent_World_N_Q131,Binormal_World_N_Q132,Result_Q177,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q180);\n#else\nBlob_Info_Q180=vec4(0,0,0,0);\n#endif\nvec4 Blob_Info_Q181;\n#if BLOB_ENABLE_2\nBlob_Vertex_B180(Pos_World_Q115,Nrm_World_Q128,Tangent_World_N_Q131,Binormal_World_N_Q132,Result_Q178,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q181);\n#else\nBlob_Info_Q181=vec4(0,0,0,0);\n#endif\nfloat Gradient1_Q130;float Gradient2_Q130;\n#if SMOOTH_EDGES\nEdge_AA_Vertex_B130(Pos_World_Q115,position,normal,cameraPosition,Radial_Gradient_Q129,Radial_Dir_Q129,tangent,Gradient1_Q130,Gradient2_Q130);\n#else\nGradient1_Q130=1.0;Gradient2_Q130=1.0;\n#endif\nvec2 Rect_UV_Q139;vec4 Rect_Parms_Q139;vec2 Scale_XY_Q139;vec2 Line_UV_Q139;Round_Rect_Vertex_B139(New_UV_Q129,Radius_Q147,0.0,Anisotropy_Q133,Gradient1_Q130,Gradient2_Q130,Rect_UV_Q139,Rect_Parms_Q139,Scale_XY_Q139,Line_UV_Q139);vec3 Line_Vertex_Q135;Line_Vertex_B135(Scale_XY_Q139,Line_UV_Q139,0.0,_Rate_,_Highlight_Transform_,Line_Vertex_Q135);vec3 Position=Pos_World_Q115;vec3 Normal=Dir_Q140;vec2 UV=Rect_UV_Q139;vec3 Tangent=Line_Vertex_Q135;vec3 Binormal=Nrm_World_Q128;vec4 Color=Out_Color_Q145;vec4 Extra1=Rect_Parms_Q139;vec4 Extra2=Blob_Info_Q180;vec4 Extra3=Blob_Info_Q181;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class pV extends xn{constructor(){super(),this.BLOB_ENABLE=!0,this.BLOB_ENABLE_2=!0,this.SMOOTH_EDGES=!0,this.IRIDESCENT_MAP_ENABLE=!0,this._needNormals=!0,this.rebuild()}}class _V extends bn{constructor(e,t){super(e,t),this.radius=.03,this.lineWidth=.01,this.absoluteSizes=!1,this._filterWidth=1,this.baseColor=new H.ov(.0392157,.0666667,.207843,1),this.lineColor=new H.ov(.14902,.133333,.384314,1),this.blobIntensity=.98,this.blobFarSize=.04,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.08,this.blobNearSize=.22,this.blobPulse=0,this.blobFade=0,this.blobNearSize2=.22,this.blobPulse2=0,this.blobFade2=0,this._rate=.135,this.highlightColor=new H.ov(.98,.98,.98,1),this.highlightWidth=.25,this._highlightTransform=new W.IU(1,1,0,0),this._highlight=1,this.iridescenceIntensity=0,this.iridescenceEdgeIntensity=1,this._angle=-45,this.fadeOut=1,this._reflected=!0,this._frequency=1,this._verticalOffset=0,this.globalLeftIndexTipPosition=W.Pq.Zero(),this._globalLeftIndexTipPosition4=W.IU.Zero(),this.globalRightIndexTipPosition=W.Pq.Zero(),this._globalRightIndexTipPosition4=W.IU.Zero(),this.alphaMode=Il.ALPHA_DISABLE,this.backFaceCulling=!1,this._blobTexture=new vi.g(_V.BLOB_TEXTURE_URL,this.getScene(),!0,!1,vi.g.NEAREST_SAMPLINGMODE),this._iridescentMap=new vi.g(_V.IM_TEXTURE_URL,this.getScene(),!0,!1,vi.g.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new pV);const r=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if((0,Bt.qB)(e,r,!1,!1),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=new Tn;r.FOG&&e.addFallback(1,"FOG"),(0,Bt.c4)(r,e),r.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const i=[st.R.PositionKind];r.NORMAL&&i.push(st.R.NormalKind),r.UV1&&i.push(st.R.UVKind),r.UV2&&i.push(st.R.UV2Kind),r.VERTEXCOLOR&&i.push(st.R.ColorKind),r.TANGENT&&i.push(st.R.TangentKind),(0,Bt.ER)(i,r);const o="fluentBackplate",a=r.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Absolute_Sizes_","_Filter_Width_","_Base_Color_","_Line_Color_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Rate_","_Highlight_Color_","_Highlight_Width_","_Highlight_Transform_","_Highlight_","_Iridescence_Intensity_","_Iridescence_Edge_Intensity_","_Angle_","_Fade_Out_","_Reflected_","_Frequency_","_Vertical_Offset_","_Iridescent_Map_","_Use_Global_Left_Index_","_Use_Global_Right_Index_","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position"],h=["_Blob_Texture_","_Iridescent_Map_"],c=[];(0,Bt.Bb)({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:r,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera?.position??W.Pq.ZeroReadOnly),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Base_Color_",this.baseColor),this._activeEffect.setDirectColor4("_Line_Color_",this.lineColor),this._activeEffect.setFloat("_Radius_Top_Left_",1),this._activeEffect.setFloat("_Radius_Top_Right_",1),this._activeEffect.setFloat("_Radius_Bottom_Left_",1),this._activeEffect.setFloat("_Radius_Bottom_Right_",1),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setFloat("_Rate_",this._rate),this._activeEffect.setDirectColor4("_Highlight_Color_",this.highlightColor),this._activeEffect.setFloat("_Highlight_Width_",this.highlightWidth),this._activeEffect.setVector4("_Highlight_Transform_",this._highlightTransform),this._activeEffect.setFloat("_Highlight_",this._highlight),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setFloat("_Iridescence_Edge_Intensity_",this.iridescenceEdgeIntensity),this._activeEffect.setFloat("_Angle_",this._angle),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._activeEffect.setFloat("_Reflected_",this._reflected?1:0),this._activeEffect.setFloat("_Frequency_",this._frequency),this._activeEffect.setFloat("_Vertical_Offset_",this._verticalOffset),this._activeEffect.setTexture("_Iridescent_Map_",this._iridescentMap),this._activeEffect.setFloat("_Use_Global_Left_Index_",1),this._activeEffect.setFloat("_Use_Global_Right_Index_",1),this._globalLeftIndexTipPosition4.set(this.globalLeftIndexTipPosition.x,this.globalLeftIndexTipPosition.y,this.globalLeftIndexTipPosition.z,1),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this._globalLeftIndexTipPosition4),this._globalRightIndexTipPosition4.set(this.globalRightIndexTipPosition.x,this.globalRightIndexTipPosition.y,this.globalRightIndexTipPosition.z,1),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this._globalRightIndexTipPosition4),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._blobTexture.dispose(),this._iridescentMap.dispose()}clone(e){return it.p.Clone((()=>new _V(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FluentBackplateMaterial",e}getClassName(){return"FluentBackplateMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new _V(e.name,t)),e,t,i)}}_V.BLOB_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-backplate-blob.png",_V.IM_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-backplate-iridescence.png",(0,je.Cg)([(0,$e.lK)()],_V.prototype,"radius",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"lineWidth",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"absoluteSizes",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"baseColor",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"lineColor",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobFarSize",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobNearDistance",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobFarDistance",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobFadeLength",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobNearSize",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobPulse",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobFade",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobNearSize2",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobPulse2",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobFade2",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"highlightColor",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"highlightWidth",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"iridescenceIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"iridescenceEdgeIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"fadeOut",void 0),(0,je.Cg)([(0,$e.P_)()],_V.prototype,"globalLeftIndexTipPosition",void 0),(0,je.Cg)([(0,$e.P_)()],_V.prototype,"globalRightIndexTipPosition",void 0),(0,X.Y5)("BABYLON.GUI.FluentBackplateMaterial",_V);class mV extends rV{set renderingGroupId(e){this._model.renderingGroupId=e}get renderingGroupId(){return this._model.renderingGroupId}get material(){return this._material}get shareMaterials(){return this._shareMaterials}constructor(e,t=!0){super(e),this._shareMaterials=t}_getTypeName(){return"HolographicBackplate"}_createNode(e){const t=Ko((this.name??"HolographicBackplate")+"_CollisionMesh",{width:1,height:1,depth:1},e);return t.isPickable=!0,t.visibility=0,xg.ImportMeshAsync(void 0,mV.MODEL_BASE_URL,mV.MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.name=`${this.name}_frontPlate`,i.isPickable=!1,i.parent=t,this._material&&(i.material=this._material),this._model=i})),t}_createMaterial(e){this._material=new _V(this.name+" Material",e.getScene())}_affectMaterial(e){this._shareMaterials?this._host._touchSharedMaterials.fluentBackplateMaterial?this._material=this._host._touchSharedMaterials.fluentBackplateMaterial:(this._createMaterial(e),this._host._touchSharedMaterials.fluentBackplateMaterial=this._material):this._createMaterial(e)}dispose(){super.dispose(),this.shareMaterials||this._material.dispose(),this._model.dispose()}}mV.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",mV.MODEL_FILENAME="mrtk-fluent-backplate.glb";class gV extends oV{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}set tooltipText(e){if(e){if(!this._tooltipFade){const e=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=Qi("",{size:1},this._backPlate._scene);const t=Qi("",{size:1,sideOrientation:Yt.DOUBLESIDE},this._backPlate._scene),i=new Un("",this._backPlate._scene);i.diffuseColor=H.v9.FromHexString("#212121"),t.material=i,t.isPickable=!1,this._tooltipMesh.addChild(t),t.position=W.Pq.Forward(e).scale(.05),this._tooltipMesh.scaling.y=1/3,this._tooltipMesh.position=W.Pq.Up().scale(.7).add(W.Pq.Forward(e).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._backPlate,this._tooltipTexture=$B.CreateForMesh(this._tooltipMesh),this._tooltipTextBlock=new dB,this._tooltipTextBlock.scaleY=3,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=130,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new Mi,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)})),this._tooltipOutObserver=this.onPointerOutObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)}))}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}else this._disposeTooltip()}get tooltipText(){return this._tooltipTextBlock?this._tooltipTextBlock.text:null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}constructor(e,t=!0){super(e),this._shareMaterials=!0,this._shareMaterials=t,this.pointerEnterAnimation=()=>{this.mesh&&this._frontPlate.setEnabled(!0)},this.pointerOutAnimation=()=>{this.mesh&&this._frontPlate.setEnabled(!1)}}_getTypeName(){return"HolographicButton"}_rebuildContent(){this._disposeFacadeTexture();const e=new _B;if(e.isVertical=!0,(0,ii.Nf)()&&document.createElement&&this._imageUrl){const t=new fB;t.source=this._imageUrl,t.paddingTop="40px",t.height="180px",t.width="100px",t.paddingBottom="40px",e.addControl(t)}if(this._text){const t=new dB;t.text=this._text,t.color="white",t.height="30px",t.fontSize=24,e.addControl(t)}this._frontPlate&&(this.content=e)}_createNode(e){return this._backPlate=Ko(this.name+"BackMesh",{width:1,height:1,depth:.08},e),this._frontPlate=Ko(this.name+"FrontMesh",{width:1,height:1,depth:.08},e),this._frontPlate.parent=this._backPlate,this._frontPlate.position=W.Pq.Forward(e.useRightHandedSystem).scale(-.08),this._frontPlate.isPickable=!1,this._frontPlate.setEnabled(!1),this._textPlate=super._createNode(e),this._textPlate.parent=this._backPlate,this._textPlate.position=W.Pq.Forward(e.useRightHandedSystem).scale(-.08),this._textPlate.isPickable=!1,this._backPlate}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e}_createBackMaterial(e){this._backMaterial=new uV(this.name+"Back Material",e.getScene()),this._backMaterial.renderHoverLight=!0,this._pickedPointObserver=this._host.onPickedPointChangedObservable.add((e=>{e?(this._backMaterial.hoverPosition=e,this._backMaterial.hoverColor.a=1):this._backMaterial.hoverColor.a=0}))}_createFrontMaterial(e){this._frontMaterial=new uV(this.name+"Front Material",e.getScene()),this._frontMaterial.innerGlowColorIntensity=0,this._frontMaterial.alpha=.5,this._frontMaterial.renderBorders=!0}_createPlateMaterial(e){this._plateMaterial=new Un(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=H.v9.Black()}_affectMaterial(e){this._shareMaterials?(this._host._sharedMaterials.backFluentMaterial?this._backMaterial=this._host._sharedMaterials.backFluentMaterial:(this._createBackMaterial(e),this._host._sharedMaterials.backFluentMaterial=this._backMaterial),this._host._sharedMaterials.frontFluentMaterial?this._frontMaterial=this._host._sharedMaterials.frontFluentMaterial:(this._createFrontMaterial(e),this._host._sharedMaterials.frontFluentMaterial=this._frontMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._frontPlate.material=this._frontMaterial,this._textPlate.material=this._plateMaterial,this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}Cs.l.ShadersStore.fluentButtonPixelShader="uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;uniform float _Edge_Width_;uniform vec4 _Edge_Color_;uniform bool _Relative_Width_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Active_Face_Dir_;uniform vec3 _Active_Face_Up_;uniform bool Enable_Fade;uniform float _Fade_Width_;uniform bool _Smooth_Active_Face_;uniform bool _Show_Frame_;uniform bool _Use_Blob_Texture_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;void Holo_Edge_Fragment_B35(\nvec4 Edges,\nfloat Edge_Width,\nout float NotEdge)\n{vec2 c=vec2(min(Edges.r,Edges.g),min(Edges.b,Edges.a));vec2 df=fwidth(c)*Edge_Width;vec2 g=clamp(c/df,0.0,1.0);NotEdge=g.x*g.y;}\nvoid Blob_Fragment_B39(\nvec2 UV,\nvec3 Blob_Info,\nsampler2D Blob_Texture,\nout vec4 Blob_Color)\n{float k=dot(UV,UV);Blob_Color=Blob_Info.y*texture(Blob_Texture,vec2(vec2(sqrt(k),Blob_Info.x).x,1.0-vec2(sqrt(k),Blob_Info.x).y))*(1.0-clamp(k,0.0,1.0));}\nvec2 FilterStep(vec2 Edge,vec2 X)\n{vec2 dX=max(fwidth(X),vec2(0.00001,0.00001));return clamp( (X+dX-max(Edge,X-dX))/(dX*2.0),0.0,1.0);}\nvoid Wireframe_Fragment_B59(\nvec3 Widths,\nvec2 UV,\nfloat Proximity,\nvec4 Edge_Color,\nout vec4 Wireframe)\n{vec2 c=min(UV,vec2(1.0,1.0)-UV);vec2 g=FilterStep(Widths.xy*0.5,c); \nWireframe=(1.0-min(g.x,g.y))*Proximity*Edge_Color;}\nvoid Proximity_B53(\nvec3 Proximity_Center,\nvec3 Proximity_Center_2,\nfloat Proximity_Max_Intensity,\nfloat Proximity_Near_Radius,\nvec3 Position,\nvec3 Show_Selection,\nvec4 Extra1,\nfloat Dist_To_Face,\nfloat Intensity,\nout float Proximity)\n{vec2 delta1=Extra1.xy;vec2 delta2=Extra1.zw;float d2=sqrt(min(dot(delta1,delta1),dot(delta2,delta2))+Dist_To_Face*Dist_To_Face);Proximity=Intensity*Proximity_Max_Intensity*(1.0-clamp(d2/Proximity_Near_Radius,0.0,1.0))*(1.0-Show_Selection.x)+Show_Selection.x;}\nvoid To_XYZ_B46(\nvec3 Vec3,\nout float X,\nout float Y,\nout float Z)\n{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;}\nvoid main()\n{float NotEdge_Q35;\n#if ENABLE_FADE\nHolo_Edge_Fragment_B35(vColor,_Fade_Width_,NotEdge_Q35);\n#else\nNotEdge_Q35=1.0;\n#endif\nvec4 Blob_Color_Q39;float k=dot(vUV,vUV);vec2 blobTextureCoord=vec2(vec2(sqrt(k),vTangent.x).x,1.0-vec2(sqrt(k),vTangent.x).y);vec4 blobColor=mix(vec4(1.0,1.0,1.0,1.0)*step(1.0-vTangent.x,clamp(sqrt(k)+0.1,0.0,1.0)),texture(_Blob_Texture_,blobTextureCoord),float(_Use_Blob_Texture_));Blob_Color_Q39=vTangent.y*blobColor*(1.0-clamp(k,0.0,1.0));float Is_Quad_Q24;Is_Quad_Q24=vNormal.z;vec3 Blob_Position_Q41= mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(Use_Global_Left_Index));vec3 Blob_Position_Q42= mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(Use_Global_Right_Index));float X_Q46;float Y_Q46;float Z_Q46;To_XYZ_B46(vBinormal,X_Q46,Y_Q46,Z_Q46);float Proximity_Q53;Proximity_B53(Blob_Position_Q41,Blob_Position_Q42,_Proximity_Max_Intensity_,_Proximity_Near_Radius_,vPosition,vBinormal,vExtra1,Y_Q46,Z_Q46,Proximity_Q53);vec4 Wireframe_Q59;Wireframe_Fragment_B59(vNormal,vUV,Proximity_Q53,_Edge_Color_,Wireframe_Q59);vec4 Wire_Or_Blob_Q23=mix(Wireframe_Q59,Blob_Color_Q39,Is_Quad_Q24);vec4 Result_Q22;Result_Q22=mix(Wire_Or_Blob_Q23,vec4(0.3,0.3,0.3,0.3),float(_Show_Frame_));vec4 Final_Color_Q37=NotEdge_Q35*Result_Q22;vec4 Out_Color=Final_Color_Q37;float Clip_Threshold=0.0;bool To_sRGB=false;gl_FragColor=Out_Color;}";Cs.l.ShadersStore.fluentButtonVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform float _Edge_Width_;uniform vec4 _Edge_Color_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Active_Face_Dir_;uniform vec3 _Active_Face_Up_;uniform bool _Enable_Fade_;uniform float _Fade_Width_;uniform bool _Smooth_Active_Face_;uniform bool _Show_Frame_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;void Blob_Vertex_B47(\nvec3 Position,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nvec3 Blob_Position,\nfloat Intensity,\nfloat Blob_Near_Size,\nfloat Blob_Far_Size,\nfloat Blob_Near_Distance,\nfloat Blob_Far_Distance,\nvec4 Vx_Color,\nvec2 UV,\nvec3 Face_Center,\nvec2 Face_Size,\nvec2 In_UV,\nfloat Blob_Fade_Length,\nfloat Selection_Fade,\nfloat Selection_Fade_Size,\nfloat Inner_Fade,\nvec3 Active_Face_Center,\nfloat Blob_Pulse,\nfloat Blob_Fade,\nfloat Blob_Enabled,\nout vec3 Out_Position,\nout vec2 Out_UV,\nout vec3 Blob_Info)\n{float blobSize,fadeIn;vec3 Hit_Position;Blob_Info=vec3(0.0,0.0,0.0);float Hit_Distance=dot(Blob_Position-Face_Center,Normal);Hit_Position=Blob_Position-Hit_Distance*Normal;float absD=abs(Hit_Distance);float lerpVal=clamp((absD-Blob_Near_Distance)/(Blob_Far_Distance-Blob_Near_Distance),0.0,1.0);fadeIn=1.0-clamp((absD-Blob_Far_Distance)/Blob_Fade_Length,0.0,1.0);float innerFade=1.0-clamp(-Hit_Distance/Inner_Fade,0.0,1.0);float farClip=clamp(1.0-step(Blob_Far_Distance+Blob_Fade_Length,absD),0.0,1.0);float size=mix(Blob_Near_Size,Blob_Far_Size,lerpVal)*farClip;blobSize=mix(size,Selection_Fade_Size,Selection_Fade)*innerFade*Blob_Enabled;Blob_Info.x=lerpVal*0.5+0.5;Blob_Info.y=fadeIn*Intensity*(1.0-Selection_Fade)*Blob_Fade;Blob_Info.x*=(1.0-Blob_Pulse);vec3 delta=Hit_Position-Face_Center;vec2 blobCenterXY=vec2(dot(delta,Tangent),dot(delta,Bitangent));vec2 quadUVin=2.0*UV-1.0; \nvec2 blobXY=blobCenterXY+quadUVin*blobSize;vec2 blobClipped=clamp(blobXY,-Face_Size*0.5,Face_Size*0.5);vec2 blobUV=(blobClipped-blobCenterXY)/max(blobSize,0.0001)*2.0;vec3 blobCorner=Face_Center+blobClipped.x*Tangent+blobClipped.y*Bitangent;Out_Position=mix(Position,blobCorner,Vx_Color.rrr);Out_UV=mix(In_UV,blobUV,Vx_Color.rr);}\nvec2 ProjectProximity(\nvec3 blobPosition,\nvec3 position,\nvec3 center,\nvec3 dir,\nvec3 xdir,\nvec3 ydir,\nout float vdistance\n)\n{vec3 delta=blobPosition-position;vec2 xy=vec2(dot(delta,xdir),dot(delta,ydir));vdistance=abs(dot(delta,dir));return xy;}\nvoid Proximity_Vertex_B66(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Active_Face_Center,\nvec3 Active_Face_Dir,\nvec3 Position,\nfloat Proximity_Far_Distance,\nfloat Relative_Scale,\nfloat Proximity_Anisotropy,\nvec3 Up,\nout vec4 Extra1,\nout float Distance_To_Face,\nout float Intensity)\n{vec3 Active_Face_Dir_X=normalize(cross(Active_Face_Dir,Up));vec3 Active_Face_Dir_Y=cross(Active_Face_Dir,Active_Face_Dir_X);float distz1,distz2;Extra1.xy=ProjectProximity(Blob_Position,Position,Active_Face_Center,Active_Face_Dir,Active_Face_Dir_X*Proximity_Anisotropy,Active_Face_Dir_Y,distz1)/Relative_Scale;Extra1.zw=ProjectProximity(Blob_Position_2,Position,Active_Face_Center,Active_Face_Dir,Active_Face_Dir_X*Proximity_Anisotropy,Active_Face_Dir_Y,distz2)/Relative_Scale;Distance_To_Face=dot(Active_Face_Dir,Position-Active_Face_Center);Intensity=1.0-clamp(min(distz1,distz2)/Proximity_Far_Distance,0.0,1.0);}\nvoid Holo_Edge_Vertex_B44(\nvec3 Incident,\nvec3 Normal,\nvec2 UV,\nvec3 Tangent,\nvec3 Bitangent,\nbool Smooth_Active_Face,\nfloat Active,\nout vec4 Holo_Edges)\n{float NdotI=dot(Incident,Normal);vec2 flip=(UV-vec2(0.5,0.5));float udot=dot(Incident,Tangent)*flip.x*NdotI;float uval=1.0-float(udot>0.0);float vdot=-dot(Incident,Bitangent)*flip.y*NdotI;float vval=1.0-float(vdot>0.0);float Smooth_And_Active=step(1.0,float(Smooth_Active_Face && Active>0.0));uval=mix(uval,max(1.0,uval),Smooth_And_Active); \nvval=mix(vval,max(1.0,vval),Smooth_And_Active);Holo_Edges=vec4(1.0,1.0,1.0,1.0)-vec4(uval*UV.x,uval*(1.0-UV.x),vval*UV.y,vval*(1.0-UV.y));}\nvoid Object_To_World_Pos_B13(\nvec3 Pos_Object,\nout vec3 Pos_World)\n{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;}\nvoid Choose_Blob_B38(\nvec4 Vx_Color,\nvec3 Position1,\nvec3 Position2,\nbool Blob_Enable_1,\nbool Blob_Enable_2,\nfloat Near_Size_1,\nfloat Near_Size_2,\nfloat Blob_Inner_Fade_1,\nfloat Blob_Inner_Fade_2,\nfloat Blob_Pulse_1,\nfloat Blob_Pulse_2,\nfloat Blob_Fade_1,\nfloat Blob_Fade_2,\nout vec3 Position,\nout float Near_Size,\nout float Inner_Fade,\nout float Blob_Enable,\nout float Fade,\nout float Pulse)\n{Position=Position1*(1.0-Vx_Color.g)+Vx_Color.g*Position2;float b1=float(Blob_Enable_1);float b2=float(Blob_Enable_2);Blob_Enable=b1+(b2-b1)*Vx_Color.g;Pulse=Blob_Pulse_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Pulse_2;Fade=Blob_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Fade_2;Near_Size=Near_Size_1*(1.0-Vx_Color.g)+Vx_Color.g*Near_Size_2;Inner_Fade=Blob_Inner_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Inner_Fade_2;}\nvoid Wireframe_Vertex_B51(\nvec3 Position,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nfloat Edge_Width,\nvec2 Face_Size,\nout vec3 Wire_Vx_Pos,\nout vec2 UV,\nout vec2 Widths)\n{Widths.xy=Edge_Width/Face_Size;float x=dot(Position,Tangent);float y=dot(Position,Bitangent);float dx=0.5-abs(x);float newx=(0.5-dx*Widths.x*2.0)*sign(x);float dy=0.5-abs(y);float newy=(0.5-dy*Widths.y*2.0)*sign(y);Wire_Vx_Pos=Normal*0.5+newx*Tangent+newy*Bitangent;UV.x=dot(Wire_Vx_Pos,Tangent)+0.5;UV.y=dot(Wire_Vx_Pos,Bitangent)+0.5;}\nvec2 ramp2(vec2 start,vec2 end,vec2 x)\n{return clamp((x-start)/(end-start),vec2(0.0,0.0),vec2(1.0,1.0));}\nfloat computeSelection(\nvec3 blobPosition,\nvec3 normal,\nvec3 tangent,\nvec3 bitangent,\nvec3 faceCenter,\nvec2 faceSize,\nfloat selectionFuzz,\nfloat farDistance,\nfloat fadeLength\n)\n{vec3 delta=blobPosition-faceCenter;float absD=abs(dot(delta,normal));float fadeIn=1.0-clamp((absD-farDistance)/fadeLength,0.0,1.0);vec2 blobCenterXY=vec2(dot(delta,tangent),dot(delta,bitangent));vec2 innerFace=faceSize*(1.0-selectionFuzz)*0.5;vec2 selectPulse=ramp2(-faceSize*0.5,-innerFace,blobCenterXY)-ramp2(innerFace,faceSize*0.5,blobCenterXY);return selectPulse.x*selectPulse.y*fadeIn;}\nvoid Selection_Vertex_B48(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Face_Center,\nvec2 Face_Size,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nfloat Selection_Fuzz,\nfloat Selected,\nfloat Far_Distance,\nfloat Fade_Length,\nvec3 Active_Face_Dir,\nout float Show_Selection)\n{float select1=computeSelection(Blob_Position,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float select2=computeSelection(Blob_Position_2,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float Active=max(0.0,dot(Active_Face_Dir,Normal));Show_Selection=mix(max(select1,select2),1.0,Selected)*Active;}\nvoid Proximity_Visibility_B54(\nfloat Selection,\nvec3 Proximity_Center,\nvec3 Proximity_Center_2,\nfloat Input_Width,\nfloat Proximity_Far_Distance,\nfloat Proximity_Radius,\nvec3 Active_Face_Center,\nvec3 Active_Face_Dir,\nout float Width)\n{vec3 boxEdges=(world*vec4(vec3(0.5,0.5,0.5),0.0)).xyz;float boxMaxSize=length(boxEdges);float d1=dot(Proximity_Center-Active_Face_Center,Active_Face_Dir);vec3 blob1=Proximity_Center-d1*Active_Face_Dir;float d2=dot(Proximity_Center_2-Active_Face_Center,Active_Face_Dir);vec3 blob2=Proximity_Center_2-d2*Active_Face_Dir;vec3 delta1=blob1-Active_Face_Center;vec3 delta2=blob2-Active_Face_Center;float dist1=dot(delta1,delta1);float dist2=dot(delta2,delta2);float nearestProxDist=sqrt(min(dist1,dist2));Width=Input_Width*(1.0-step(boxMaxSize+Proximity_Radius,nearestProxDist))*(1.0-step(Proximity_Far_Distance,min(d1,d2))*(1.0-step(0.0001,Selection)));}\nvoid Object_To_World_Dir_B67(\nvec3 Dir_Object,\nout vec3 Dir_World)\n{Dir_World=(world*vec4(Dir_Object,0.0)).xyz;}\nvoid main()\n{vec3 Active_Face_Center_Q49;Active_Face_Center_Q49=(world*vec4(_Active_Face_Dir_*0.5,1.0)).xyz;vec3 Blob_Position_Q41= mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(Use_Global_Left_Index));vec3 Blob_Position_Q42= mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(Use_Global_Right_Index));vec3 Active_Face_Dir_Q64=normalize((world*vec4(_Active_Face_Dir_,0.0)).xyz);float Relative_Scale_Q57;\n#if RELATIVE_WIDTH\nRelative_Scale_Q57=length((world*vec4(vec3(0,1,0),0.0)).xyz);\n#else\nRelative_Scale_Q57=1.0;\n#endif\nvec3 Tangent_World_Q30;Tangent_World_Q30=(world*vec4(tangent,0.0)).xyz;vec3 Binormal_World_Q31;Binormal_World_Q31=(world*vec4((cross(normal,tangent)),0.0)).xyz;vec3 Normal_World_Q60;Normal_World_Q60=(world*vec4(normal,0.0)).xyz;vec3 Result_Q18=0.5*normal;vec3 Dir_World_Q67;Object_To_World_Dir_B67(_Active_Face_Up_,Dir_World_Q67);float Product_Q56=_Edge_Width_*Relative_Scale_Q57;vec3 Normal_World_N_Q29=normalize(Normal_World_Q60);vec3 Tangent_World_N_Q28=normalize(Tangent_World_Q30);vec3 Binormal_World_N_Q32=normalize(Binormal_World_Q31);vec3 Position_Q38;float Near_Size_Q38;float Inner_Fade_Q38;float Blob_Enable_Q38;float Fade_Q38;float Pulse_Q38;Choose_Blob_B38(color,Blob_Position_Q41,Blob_Position_Q42,_Blob_Enable_,_Blob_Enable_2_,_Blob_Near_Size_,_Blob_Near_Size_2_,_Blob_Inner_Fade_,_Blob_Inner_Fade_2_,_Blob_Pulse_,_Blob_Pulse_2_,_Blob_Fade_,_Blob_Fade_2_,Position_Q38,Near_Size_Q38,Inner_Fade_Q38,Blob_Enable_Q38,Fade_Q38,Pulse_Q38);vec3 Face_Center_Q33;Face_Center_Q33=(world*vec4(Result_Q18,1.0)).xyz;vec2 Face_Size_Q50=vec2(length(Tangent_World_Q30),length(Binormal_World_Q31));float Show_Selection_Q48;Selection_Vertex_B48(Blob_Position_Q41,Blob_Position_Q42,Face_Center_Q33,Face_Size_Q50,Normal_World_N_Q29,Tangent_World_N_Q28,Binormal_World_N_Q32,_Selection_Fuzz_,_Selected_,_Selected_Distance_,_Selected_Fade_Length_,Active_Face_Dir_Q64,Show_Selection_Q48);vec3 Normalized_Q72=normalize(Dir_World_Q67);float Active_Q34=max(0.0,dot(Active_Face_Dir_Q64,Normal_World_N_Q29));float Width_Q54;Proximity_Visibility_B54(Show_Selection_Q48,Blob_Position_Q41,Blob_Position_Q42,Product_Q56,_Proximity_Far_Distance_,_Proximity_Near_Radius_,Active_Face_Center_Q49,Active_Face_Dir_Q64,Width_Q54);vec3 Wire_Vx_Pos_Q51;vec2 UV_Q51;vec2 Widths_Q51;Wireframe_Vertex_B51(position,normal,tangent,(cross(normal,tangent)),Width_Q54,Face_Size_Q50,Wire_Vx_Pos_Q51,UV_Q51,Widths_Q51);vec3 Vec3_Q27=vec3(Widths_Q51.x,Widths_Q51.y,color.r);vec3 Pos_World_Q13;Object_To_World_Pos_B13(Wire_Vx_Pos_Q51,Pos_World_Q13);vec3 Incident_Q36=normalize(Pos_World_Q13-cameraPosition);vec3 Out_Position_Q47;vec2 Out_UV_Q47;vec3 Blob_Info_Q47;Blob_Vertex_B47(Pos_World_Q13,Normal_World_N_Q29,Tangent_World_N_Q28,Binormal_World_N_Q32,Position_Q38,_Blob_Intensity_,Near_Size_Q38,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,color,uv,Face_Center_Q33,Face_Size_Q50,UV_Q51,_Blob_Fade_Length_,_Selection_Fade_,_Selection_Fade_Size_,Inner_Fade_Q38,Active_Face_Center_Q49,Pulse_Q38,Fade_Q38,Blob_Enable_Q38,Out_Position_Q47,Out_UV_Q47,Blob_Info_Q47);vec4 Extra1_Q66;float Distance_To_Face_Q66;float Intensity_Q66;Proximity_Vertex_B66(Blob_Position_Q41,Blob_Position_Q42,Active_Face_Center_Q49,Active_Face_Dir_Q64,Pos_World_Q13,_Proximity_Far_Distance_,Relative_Scale_Q57,_Proximity_Anisotropy_,Normalized_Q72,Extra1_Q66,Distance_To_Face_Q66,Intensity_Q66);vec4 Holo_Edges_Q44;Holo_Edge_Vertex_B44(Incident_Q36,Normal_World_N_Q29,uv,Tangent_World_Q30,Binormal_World_Q31,_Smooth_Active_Face_,Active_Q34,Holo_Edges_Q44);vec3 Vec3_Q19=vec3(Show_Selection_Q48,Distance_To_Face_Q66,Intensity_Q66);vec3 Position=Out_Position_Q47;vec2 UV=Out_UV_Q47;vec3 Tangent=Blob_Info_Q47;vec3 Binormal=Vec3_Q19;vec3 Normal=Vec3_Q27;vec4 Extra1=Extra1_Q66;vec4 Color=Holo_Edges_Q44;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;}";class vV extends xn{constructor(){super(),this.RELATIVE_WIDTH=!0,this.ENABLE_FADE=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class xV extends bn{constructor(e,t){super(e,t),this.edgeWidth=.04,this.edgeColor=new H.ov(.592157,.592157,.592157,1),this.proximityMaxIntensity=.45,this.proximityFarDistance=.16,this.proximityNearRadius=1.5,this.proximityAnisotropy=1,this.selectionFuzz=.5,this.selected=0,this.selectionFade=0,this.selectionFadeSize=.3,this.selectedDistance=.08,this.selectedFadeLength=.08,this.blobIntensity=.5,this.blobFarSize=.05,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.08,this.leftBlobEnable=!0,this.leftBlobNearSize=.025,this.leftBlobPulse=0,this.leftBlobFade=1,this.leftBlobInnerFade=.01,this.rightBlobEnable=!0,this.rightBlobNearSize=.025,this.rightBlobPulse=0,this.rightBlobFade=1,this.rightBlobInnerFade=.01,this.activeFaceDir=new W.Pq(0,0,-1),this.activeFaceUp=new W.Pq(0,1,0),this.enableFade=!0,this.fadeWidth=1.5,this.smoothActiveFace=!0,this.showFrame=!1,this.useBlobTexture=!0,this.globalLeftIndexTipPosition=W.Pq.Zero(),this.globalRightIndexTipPosition=W.Pq.Zero(),this.alphaMode=Il.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1,this._blobTexture=new vi.g(xV.BLOB_TEXTURE_URL,this.getScene(),!0,!1,vi.g.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!0}needAlphaTesting(){return!0}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new vV);const r=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if((0,Bt.qB)(e,r,!0,!1),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=new Tn;r.FOG&&e.addFallback(1,"FOG"),(0,Bt.c4)(r,e),r.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const i=[st.R.PositionKind];r.NORMAL&&i.push(st.R.NormalKind),r.UV1&&i.push(st.R.UVKind),r.UV2&&i.push(st.R.UV2Kind),r.VERTEXCOLOR&&i.push(st.R.ColorKind),r.TANGENT&&i.push(st.R.TangentKind),(0,Bt.ER)(i,r);const o="fluentButton",a=r.toString(),l=["world","viewProjection","cameraPosition","_Edge_Width_","_Edge_Color_","_Relative_Width_","_Proximity_Max_Intensity_","_Proximity_Far_Distance_","_Proximity_Near_Radius_","_Proximity_Anisotropy_","_Selection_Fuzz_","_Selected_","_Selection_Fade_","_Selection_Fade_Size_","_Selected_Distance_","_Selected_Fade_Length_","_Blob_Enable_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Inner_Fade_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Enable_2_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Inner_Fade_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Active_Face_Dir_","_Active_Face_Up_","_Enable_Fade_","_Fade_Width_","_Smooth_Active_Face_","_Show_Frame_","_Use_Blob_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],h=["_Blob_Texture_"],c=[];(0,Bt.Bb)({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:r,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const r=this.getScene();if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",r.activeCamera.position),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Edge_Width_",this.edgeWidth),this._activeEffect.setColor4("_Edge_Color_",new H.v9(this.edgeColor.r,this.edgeColor.g,this.edgeColor.b),this.edgeColor.a),this._activeEffect.setFloat("_Proximity_Max_Intensity_",this.proximityMaxIntensity),this._activeEffect.setFloat("_Proximity_Far_Distance_",this.proximityFarDistance),this._activeEffect.setFloat("_Proximity_Near_Radius_",this.proximityNearRadius),this._activeEffect.setFloat("_Proximity_Anisotropy_",this.proximityAnisotropy),this._activeEffect.setFloat("_Selection_Fuzz_",this.selectionFuzz),this._activeEffect.setFloat("_Selected_",this.selected),this._activeEffect.setFloat("_Selection_Fade_",this.selectionFade),this._activeEffect.setFloat("_Selection_Fade_Size_",this.selectionFadeSize),this._activeEffect.setFloat("_Selected_Distance_",this.selectedDistance),this._activeEffect.setFloat("_Selected_Fade_Length_",this.selectedFadeLength),this._activeEffect.setFloat("_Blob_Enable_",this.leftBlobEnable?1:0),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.leftBlobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Inner_Fade_",this.leftBlobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_",this.leftBlobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.leftBlobFade),this._activeEffect.setFloat("_Blob_Enable_2_",this.rightBlobEnable?1:0),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.rightBlobNearSize),this._activeEffect.setFloat("_Blob_Inner_Fade_2_",this.rightBlobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_2_",this.rightBlobPulse),this._activeEffect.setFloat("_Blob_Fade_2_",this.rightBlobFade),this._activeEffect.setVector3("_Active_Face_Dir_",this.activeFaceDir),this._activeEffect.setVector3("_Active_Face_Up_",this.activeFaceUp),this._activeEffect.setFloat("_Fade_Width_",this.fadeWidth),this._activeEffect.setFloat("_Smooth_Active_Face_",this.smoothActiveFace?1:0),this._activeEffect.setFloat("_Show_Frame_",this.showFrame?1:0),this._activeEffect.setFloat("_Use_Blob_Texture_",this.useBlobTexture?1:0),this._activeEffect.setFloat("Use_Global_Left_Index",1),this._activeEffect.setFloat("Use_Global_Right_Index",1),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",new W.IU(this.globalLeftIndexTipPosition.x,this.globalLeftIndexTipPosition.y,this.globalLeftIndexTipPosition.z,1)),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",new W.IU(this.globalRightIndexTipPosition.x,this.globalRightIndexTipPosition.y,this.globalRightIndexTipPosition.z,1)),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return it.p.Clone((()=>new xV(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FluentButtonMaterial",e}getClassName(){return"FluentButtonMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new xV(e.name,t)),e,t,i)}}xV.BLOB_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-button-blob.png",(0,je.Cg)([(0,$e.lK)()],xV.prototype,"edgeWidth",void 0),(0,je.Cg)([(0,$e.qK)()],xV.prototype,"edgeColor",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"proximityMaxIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"proximityFarDistance",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"proximityNearRadius",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"proximityAnisotropy",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"selectionFuzz",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"selected",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"selectionFade",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"selectionFadeSize",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"selectedDistance",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"selectedFadeLength",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"blobIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"blobFarSize",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"blobNearDistance",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"blobFarDistance",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"blobFadeLength",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"leftBlobEnable",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"leftBlobNearSize",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"leftBlobPulse",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"leftBlobFade",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"leftBlobInnerFade",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"rightBlobEnable",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"rightBlobNearSize",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"rightBlobPulse",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"rightBlobFade",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"rightBlobInnerFade",void 0),(0,je.Cg)([(0,$e.P_)()],xV.prototype,"activeFaceDir",void 0),(0,je.Cg)([(0,$e.P_)()],xV.prototype,"activeFaceUp",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"enableFade",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"fadeWidth",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"smoothActiveFace",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"showFrame",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"useBlobTexture",void 0),(0,je.Cg)([(0,$e.P_)()],xV.prototype,"globalLeftIndexTipPosition",void 0),(0,je.Cg)([(0,$e.P_)()],xV.prototype,"globalRightIndexTipPosition",void 0),(0,X.Y5)("BABYLON.GUI.FluentButtonMaterial",xV);class bV extends oV{constructor(e,t){super(e),this._isNearPressed=!1,this._interactionSurfaceHeight=0,this._isToggleButton=!1,this._toggleState=!1,this._toggleButtonCallback=()=>{this._onToggle(!this._toggleState)},this.onToggleObservable=new z.cP,this.collidableFrontDirection=W.Pq.Zero(),t&&(this.collisionMesh=t)}get isActiveNearInteraction(){return this._isNearPressed}set collidableFrontDirection(e){if(this._collidableFrontDirection=e.normalize(),this._collisionMesh){const e=W.AA.Matrix[0];e.copyFrom(this._collisionMesh.getWorldMatrix()),e.invert(),W.Pq.TransformNormalToRef(this._collidableFrontDirection,e,this._collidableFrontDirection),this._collidableFrontDirection.normalize()}}get collidableFrontDirection(){if(this._collisionMesh){const e=W.AA.Vector3[0];return W.Pq.TransformNormalToRef(this._collidableFrontDirection,this._collisionMesh.getWorldMatrix(),e),e.normalize()}return this._collidableFrontDirection}set collisionMesh(e){this._collisionMesh&&(this._collisionMesh.isNearPickable=!1,this._collisionMesh.reservedDataStore?.GUI3D&&(this._collisionMesh.reservedDataStore.GUI3D={}),this._collisionMesh.getChildMeshes().forEach((e=>{e.isNearPickable=!1,e.reservedDataStore?.GUI3D&&(e.reservedDataStore.GUI3D={})}))),this._collisionMesh=e,this._injectGUI3DReservedDataStore(this._collisionMesh).control=this,this._collisionMesh.isNearPickable=!0,this._collisionMesh.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this,e.isNearPickable=!0})),this.collidableFrontDirection=e.forward}set isToggleButton(e){e!==this._isToggleButton&&(this._isToggleButton=e,e?this.onPointerUpObservable.add(this._toggleButtonCallback):(this.onPointerUpObservable.removeCallback(this._toggleButtonCallback),this._toggleState&&this._onToggle(!1)))}get isToggleButton(){return this._isToggleButton}set isToggled(e){this._isToggleButton&&this._toggleState!==e&&this._onToggle(e)}get isToggled(){return this._toggleState}_onToggle(e){this._toggleState=e,this.onToggleObservable.notifyObservers(e)}_isInteractionInFrontOfButton(e){return this._getInteractionHeight(e,this._collisionMesh.getAbsolutePosition())>0}getPressDepth(e){if(!this._isNearPressed)return 0;const t=this._getInteractionHeight(e,this._collisionMesh.getAbsolutePosition());return this._interactionSurfaceHeight-t}_getInteractionHeight(e,t){const i=this.collidableFrontDirection;if(0===i.length())return W.Pq.Distance(e,t);const r=W.Pq.Dot(t,i);return W.Pq.Dot(e,i)-r}_generatePointerEventType(e,t,i){if(e===yi.Zp.POINTERDOWN||e===yi.Zp.POINTERMOVE){if(!this._isInteractionInFrontOfButton(t))return yi.Zp.POINTERMOVE;this._isNearPressed=!0,this._interactionSurfaceHeight=this._getInteractionHeight(t,this._collisionMesh.getAbsolutePosition())}if(e===yi.Zp.POINTERUP){if(0==i)return yi.Zp.POINTERMOVE;this._isNearPressed=!1}return e}_getTypeName(){return"TouchButton3D"}_createNode(e){return super._createNode(e)}dispose(){super.dispose(),this.onPointerUpObservable.removeCallback(this._toggleButtonCallback),this.onToggleObservable.clear(),this._collisionMesh&&this._collisionMesh.dispose()}}class SV extends bV{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}get mesh(){return this._backPlate}set tooltipText(e){if(e){if(!this._tooltipFade){const e=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=Qi("",{size:1},this._backPlate._scene);const t=Qi("",{size:1,sideOrientation:Yt.DOUBLESIDE},this._backPlate._scene),i=new Un("",this._backPlate._scene);i.diffuseColor=H.v9.FromHexString("#212121"),t.material=i,t.isPickable=!1,this._tooltipMesh.addChild(t),t.position=W.Pq.Forward(e).scale(.05),this._tooltipMesh.scaling.y=1/3,this._tooltipMesh.position=W.Pq.Up().scale(.7).add(W.Pq.Forward(e).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._backPlate,this._tooltipTexture=$B.CreateForMesh(this._tooltipMesh),this._tooltipTextBlock=new dB,this._tooltipTextBlock.scaleY=3,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=130,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new Mi,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)})),this._tooltipOutObserver=this.onPointerOutObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)}))}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}else this._disposeTooltip()}get tooltipText(){return this._tooltipTextBlock?this._tooltipTextBlock.text:null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}set isBackplateVisible(e){this.mesh&&this._backMaterial&&(e&&!this._isBackplateVisible?this._backPlate.visibility=1:!e&&this._isBackplateVisible&&(this._backPlate.visibility=0)),this._isBackplateVisible=e}constructor(e,t=!0){super(e),this._shareMaterials=!0,this._isBackplateVisible=!0,this._frontPlateDepth=.5,this._backPlateDepth=.04,this._backplateColor=new H.v9(.08,.15,.55),this._backplateToggledColor=new H.v9(.25,.4,.95),this._shareMaterials=t,this.pointerEnterAnimation=()=>{this._frontMaterial.leftBlobEnable=!0,this._frontMaterial.rightBlobEnable=!0},this.pointerOutAnimation=()=>{this._frontMaterial.leftBlobEnable=!1,this._frontMaterial.rightBlobEnable=!1},this.pointerDownAnimation=()=>{this._frontPlate&&!this.isActiveNearInteraction&&(this._frontPlate.scaling.z=.2*this._frontPlateDepth,this._frontPlate.position=W.Pq.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-.2*this._frontPlateDepth)/2),this._textPlate.position=W.Pq.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+.2*this._frontPlateDepth)/2))},this.pointerUpAnimation=()=>{this._frontPlate&&(this._frontPlate.scaling.z=this._frontPlateDepth,this._frontPlate.position=W.Pq.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-this._frontPlateDepth)/2),this._textPlate.position=W.Pq.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+this._frontPlateDepth)/2))},this.onPointerMoveObservable.add((e=>{if(this._frontPlate&&this.isActiveNearInteraction){const t=W.Pq.Zero();if(this._backPlate.getWorldMatrix().decompose(t,void 0,void 0)){let i=this._getInteractionHeight(e,this._backPlate.getAbsolutePosition())/t.z;i=Gy.Clamp(i-this._backPlateDepth/2,.2*this._frontPlateDepth,this._frontPlateDepth),this._frontPlate.scaling.z=i,this._frontPlate.position=W.Pq.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-i)/2),this._textPlate.position=W.Pq.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+i)/2)}}})),this._pointerHoverObserver=this.onPointerMoveObservable.add((e=>{this._frontMaterial.globalLeftIndexTipPosition=e}))}_getTypeName(){return"TouchHolographicButton"}_rebuildContent(){this._disposeFacadeTexture();const e=new _B;if(e.isVertical=!0,(0,ii.Nf)()&&document.createElement&&this._imageUrl){const t=new fB;t.source=this._imageUrl,t.paddingTop="40px",t.height="180px",t.width="100px",t.paddingBottom="40px",e.addControl(t)}if(this._text){const t=new dB;t.text=this._text,t.color="white",t.height="30px",t.fontSize=24,e.addControl(t)}this.content=e}_createNode(e){this.name=this.name??"TouchHolographicButton";const t=Ko(`${this.name}_collisionMesh`,{width:1,height:1,depth:this._frontPlateDepth},e);t.isPickable=!0,t.isNearPickable=!0,t.visibility=0,t.position=W.Pq.Forward(e.useRightHandedSystem).scale(-this._frontPlateDepth/2),xg.ImportMeshAsync(void 0,SV.MODEL_BASE_URL,SV.MODEL_FILENAME,e).then((i=>{const r=Ko("${this.name}_alphaMesh",{width:1,height:1,depth:1},e);r.isPickable=!1,r.material=new Un("${this.name}_alphaMesh_material",e),r.material.alpha=.15;const s=i.meshes[1];s.name=`${this.name}_frontPlate`,s.isPickable=!1,s.scaling.z=this._frontPlateDepth,r.parent=s,s.parent=t,this._frontMaterial&&(s.material=this._frontMaterial),this._frontPlate=s})),this._backPlate=Ko(`${this.name}_backPlate`,{width:1,height:1,depth:this._backPlateDepth},e),this._backPlate.position=W.Pq.Forward(e.useRightHandedSystem).scale(this._backPlateDepth/2),this._backPlate.isPickable=!1,this._textPlate=super._createNode(e),this._textPlate.name=`${this.name}_textPlate`,this._textPlate.isPickable=!1,this._textPlate.position=W.Pq.Forward(e.useRightHandedSystem).scale(-this._frontPlateDepth/2),this._backPlate.addChild(t),this._backPlate.addChild(this._textPlate);const i=new Pt("{this.name}_root",e);return this._backPlate.setParent(i),this.collisionMesh=t,this.collidableFrontDirection=this._backPlate.forward.negate(),i}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e,this._plateMaterial.diffuseColor=new H.v9(.4,.4,.4)}_createBackMaterial(e){this._backMaterial=new uV(this.name+"backPlateMaterial",e.getScene()),this._backMaterial.albedoColor=this._backplateColor,this._backMaterial.renderBorders=!0,this._backMaterial.renderHoverLight=!1}_createFrontMaterial(e){this._frontMaterial=new xV(this.name+"Front Material",e.getScene())}_createPlateMaterial(e){this._plateMaterial=new Un(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=H.v9.Black()}_onToggle(e){this._backMaterial&&(this._backMaterial.albedoColor=e?this._backplateToggledColor:this._backplateColor),super._onToggle(e)}_affectMaterial(e){this._shareMaterials?(this._host._touchSharedMaterials.backFluentMaterial?this._backMaterial=this._host._touchSharedMaterials.backFluentMaterial:(this._createBackMaterial(e),this._host._touchSharedMaterials.backFluentMaterial=this._backMaterial),this._host._touchSharedMaterials.frontFluentMaterial?this._frontMaterial=this._host._touchSharedMaterials.frontFluentMaterial:(this._createFrontMaterial(e),this._host._touchSharedMaterials.frontFluentMaterial=this._frontMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._textPlate.material=this._plateMaterial,this._isBackplateVisible||(this._backPlate.visibility=0),this._frontPlate&&(this._frontPlate.material=this._frontMaterial),this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.onPointerMoveObservable.remove(this._pointerHoverObserver),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}SV.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",SV.MODEL_FILENAME="mrtk-fluent-button.glb";class TV{constructor(){this.followBehaviorEnabled=!1,this.sixDofDragBehaviorEnabled=!0,this.surfaceMagnetismBehaviorEnabled=!0,this._followBehavior=new lr,this._sixDofDragBehavior=new ir,this._surfaceMagnetismBehavior=new rr}get name(){return"Default"}get followBehavior(){return this._followBehavior}get sixDofDragBehavior(){return this._sixDofDragBehavior}get surfaceMagnetismBehavior(){return this._surfaceMagnetismBehavior}init(){}attach(e,t,i){this._scene=e.getScene(),this.attachedNode=e,this._addObservables(),this._followBehavior.attach(e),this._sixDofDragBehavior.attach(e),this._sixDofDragBehavior.draggableMeshes=t||null,this._sixDofDragBehavior.faceCameraOnDragStart=!0,this._surfaceMagnetismBehavior.attach(e,this._scene),i&&(this._surfaceMagnetismBehavior.meshes=i),this._surfaceMagnetismBehavior.enabled=!1}detach(){this.attachedNode=null,this._removeObservables(),this._followBehavior.detach(),this._sixDofDragBehavior.detach(),this._surfaceMagnetismBehavior.detach()}_addObservables(){this._onBeforeRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{this._followBehavior._enabled=!this._sixDofDragBehavior.isMoving&&this.followBehaviorEnabled})),this._onDragObserver=this._sixDofDragBehavior.onDragObservable.add((e=>{this._sixDofDragBehavior.disableMovement=this._surfaceMagnetismBehavior.findAndUpdateTarget(e.pickInfo)}))}_removeObservables(){this._scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._sixDofDragBehavior.onDragObservable.remove(this._onDragObserver)}}Cs.l.ShadersStore.handleVertexShader="precision highp float;attribute vec3 position;uniform vec3 positionOffset;uniform mat4 worldViewProjection;uniform float scale;void main(void) {vec4 vPos=vec4((vec3(position)+positionOffset)*scale,1.0);gl_Position=worldViewProjection*vPos;}";Cs.l.ShadersStore.handlePixelShader="uniform vec3 color;void main(void) {gl_FragColor=vec4(color,1.0);}";class CV extends xo{get hover(){return this._hover}set hover(e){this._hover=e,this._updateInterpolationTarget()}get drag(){return this._drag}set drag(e){this._drag=e,this._updateInterpolationTarget()}constructor(e,t){super(e,t,"handle",{attributes:["position"],uniforms:["worldViewProjection","color","scale","positionOffset"],needAlphaBlending:!1,needAlphaTesting:!1}),this._hover=!1,this._drag=!1,this._color=new H.v9,this._scale=1,this._lastTick=-1,this.animationLength=100,this.hoverColor=new H.v9(0,.467,.84),this.baseColor=new H.v9(1,1,1),this.hoverScale=.75,this.baseScale=.35,this.dragScale=.55,this._positionOffset=W.Pq.Zero(),this._updateInterpolationTarget(),this._lastTick=Date.now(),this._onBeforeRender=this.getScene().onBeforeRenderObservable.add((()=>{const e=Date.now(),t=e-this._lastTick,i=this._targetScale-this._scale,r=H.IG.Color3[0].copyFrom(this._targetColor).subtractToRef(this._color,H.IG.Color3[0]);this._scale=this._scale+i*t/this.animationLength,r.scaleToRef(t/this.animationLength,r),this._color.addToRef(r,this._color),this.setColor3("color",this._color),this.setFloat("scale",this._scale),this.setVector3("positionOffset",this._positionOffset),this._lastTick=e}))}_updateInterpolationTarget(){this.drag?(this._targetColor=this.hoverColor,this._targetScale=this.dragScale):this.hover?(this._targetColor=this.hoverColor,this._targetScale=this.hoverScale):(this._targetColor=this.baseColor,this._targetScale=this.baseScale)}dispose(){super.dispose(),this.getScene().onBeforeRenderObservable.remove(this._onBeforeRender)}}var yV;!function(e){e[e.IDLE=0]="IDLE",e[e.HOVER=1]="HOVER",e[e.DRAG=2]="DRAG"}(yV||(yV={}));class EV{get state(){return this._state}get gizmo(){return this._gizmo}set hover(e){e?this._state|=1:this._state&=-2,this._updateMaterial()}set drag(e){e?this._state|=2:this._state&=-3,this._updateMaterial()}constructor(e,t){this._state=0,this._materials=[],this._scene=t,this._gizmo=e,this.node=this.createNode(),this.node.reservedDataStore={handle:this}}_createMaterial(e){const t=new CV("handle",this._scene);return e&&(t._positionOffset=e),t}_updateMaterial(){const e=this._state;for(const e of this._materials)e.hover=!1,e.drag=!1;if(2&e)for(const e of this._materials)e.drag=!0;else if(1&e)for(const e of this._materials)e.hover=!0}setDragBehavior(e,t,i){const r=new tr;this._dragBehavior=r,this._dragStartObserver=r.onDragStartObservable.add(e),this._draggingObserver=r.onDragObservable.add(t),this._dragEndObserver=r.onDragEndObservable.add(i),this._dragBehavior.attach(this.node)}dispose(){this._dragBehavior.onDragStartObservable.remove(this._dragStartObserver),this._dragBehavior.onDragObservable.remove(this._draggingObserver),this._dragBehavior.onDragEndObservable.remove(this._dragEndObserver),this._dragBehavior.detach();for(const e of this._materials)e.dispose();this.node.dispose()}}class PV extends EV{createNode(){const e=Ko("sideVert",{width:1,height:10,depth:.1},this._scene),t=new Pt("side",this._scene);e.parent=t;const i=this._createMaterial();return e.material=i,e.isNearGrabbable=!0,this._materials.push(i),t}}class AV extends EV{createNode(){const e=Ko("angleHor",{width:3,height:1,depth:.1},this._scene),t=Ko("angleVert",{width:1,height:3,depth:.1},this._scene),i=new Pt("angle",this._scene);return e.parent=i,t.parent=i,e.material=this._createMaterial(new W.Pq(1,0,0)),t.material=this._createMaterial(new W.Pq(0,1,0)),t.isNearGrabbable=!0,e.isNearGrabbable=!0,this._materials.push(e.material),this._materials.push(t.material),i}}class RV extends Go{set attachedSlate(e){e?(this.attachedMesh=e.mesh,this.updateBoundingBox(),this._pickedPointObserver=e._host.onPickingObservable.add((e=>{if(!this._handleHovered||e&&e.parent===this._handleHovered.node||(this._handleHovered.hover=!1,this._handleHovered=null),e&&e.parent&&e.parent.reservedDataStore&&e.parent.reservedDataStore.handle){const t=e.parent.reservedDataStore.handle;t.gizmo===this&&(this._handleHovered=t,this._handleHovered.hover=!0)}}))):this._attachedSlate&&this._attachedSlate._host.onPickingObservable.remove(this._pickedPointObserver),this._attachedSlate=e}get attachedSlate(){return this._attachedSlate}constructor(e){super(e),this._boundingDimensions=new W.Pq(0,0,0),this._renderObserver=null,this._tmpQuaternion=new W.PT,this._tmpVector=new W.Pq(0,0,0),this._corners=[],this._sides=[],this._boundingBoxGizmo={min:new W.Pq,max:new W.Pq},this._margin=.35,this._handleSize=.075,this._attachedSlate=null,this._existingSlateScale=new W.Pq,this.fixedScreenSize=!1,this.fixedScreenSizeDistanceFactor=10,this._createNode(),this.updateScale=!1,this._renderObserver=this.gizmoLayer.originalScene.onBeforeRenderObservable.add((()=>{this.attachedMesh&&!this._existingSlateScale.equals(this.attachedMesh.scaling)&&this.updateBoundingBox()}))}_createNode(){this._handlesParent=new Pt("handlesParent",this.gizmoLayer.utilityLayerScene),this._handlesParent.rotationQuaternion=W.PT.Identity();const e=[{dimensions:new W.Pq(-1,-1,0),origin:new W.Pq(1,0,0)},{dimensions:new W.Pq(1,-1,0),origin:new W.Pq(0,0,0)},{dimensions:new W.Pq(1,1,0),origin:new W.Pq(0,1,0)},{dimensions:new W.Pq(-1,1,0),origin:new W.Pq(1,1,0)}];for(let t=0;t<4;t++){const i=new AV(this,this.gizmoLayer.utilityLayerScene);this._corners.push(i),i.node.rotation.z=Math.PI/2*t,i.node.parent=this._handlesParent,this._assignDragBehaviorCorners(i,((e,t,i,r)=>this._moveHandle(e,t,i,r,!0)),e[t])}for(let e=0;e<4;e++){const t=new PV(this,this.gizmoLayer.utilityLayerScene);this._sides.push(t),t.node.rotation.z=Math.PI/2*e,t.node.parent=this._handlesParent,this._assignDragBehaviorSides(t,e%2==0?new W.Pq(0,1,0):new W.Pq(1,0,0))}this._handlesParent.parent=this._rootMesh}_keepAspectRatio(e,t,i=!1){const r=W.AA.Vector3[0];r.copyFromFloats(t,1,0).normalize(),i&&(r.y*=-1);const s=W.Pq.Dot(e,r);e.copyFrom(r).scaleInPlace(s)}_clampDimensions(e,t,i,r=!1){const s=W.AA.Vector3[0];s.copyFrom(e).multiplyInPlace(i);const n=W.AA.Vector3[1];if(n.copyFromFloats(Math.max(this._attachedSlate.minDimensions.x,s.x+t.x),Math.max(this._attachedSlate.minDimensions.y,s.y+t.y),0),r){const e=t.x/t.y;n.x=Math.max(n.x,n.y*e),n.y=Math.max(n.y,n.x/e)}s.copyFrom(n).subtractInPlace(t),e.x=Math.sign(e.x)*Math.abs(s.x),e.y=Math.sign(e.y)*Math.abs(s.y)}_moveHandle(e,t,i,r,s){if(!this._attachedSlate)return;if(s){const e=t.x/t.y;this._keepAspectRatio(i,e,r.dimensions.x*r.dimensions.y<0)}this._clampDimensions(i,t,r.dimensions,s);const n=W.AA.Vector3[0],o=W.AA.Vector3[1];n.copyFrom(i).multiplyInPlace(r.origin),o.copyFrom(i).multiplyInPlace(r.dimensions),this._attachedSlate.origin.copyFrom(e).addInPlace(n),this._attachedSlate.dimensions.set(t.x+o.x,t.y+o.y)}_assignDragBehaviorCorners(e,t,i){const r=new W.Pq,s=new W.Pq,n=new W.Pq,o=new W.uq,a=new W.Pq;e.setDragBehavior((e=>{this.attachedSlate&&this.attachedMesh&&(r.set(this.attachedSlate.dimensions.x,this.attachedSlate.dimensions.y,lt.bH),s.copyFrom(this.attachedSlate.origin),n.copyFrom(e.position),o.copyFrom(this.attachedMesh.computeWorldMatrix(!0)),o.invert(),this.attachedSlate._followButton.isToggled=!1,W.Pq.TransformNormalToRef(W.Pq.Forward(),this.attachedMesh.getWorldMatrix(),a),a.normalize(),this._handleHovered&&(this._handleDragged=this._handleHovered,this._handleDragged.drag=!0))}),(e=>{this.attachedSlate&&this.attachedMesh&&(((e,t,i,r)=>{e.subtractToRef(i,W.AA.Vector3[0]);const s=W.Pq.Dot(W.AA.Vector3[0],t);W.AA.Vector3[1].copyFrom(t).scaleInPlace(s),W.AA.Vector3[0].subtractInPlace(W.AA.Vector3[1]),W.AA.Vector3[0].addToRef(i,r)})(e.position,a,n,this._tmpVector),this._tmpVector.subtractInPlace(n),W.Pq.TransformNormalToRef(this._tmpVector,o,this._tmpVector),t(s,r,this._tmpVector,i),this.attachedSlate._positionElements(),this.updateBoundingBox())}),(()=>{this.attachedSlate&&this.attachedNode&&(this.attachedSlate._updatePivot(),this._handleDragged&&(this._handleDragged.drag=!1,this._handleDragged=null))}))}_assignDragBehaviorSides(e,t){const i=new W.PT,r=new W.Pq,s=new W.Pq,n=new W.Pq,o=new W.Pq;e.setDragBehavior((e=>{this.attachedSlate&&this.attachedMesh&&(i.copyFrom(this.attachedMesh.rotationQuaternion),r.copyFrom(e.position),n.copyFrom(this.attachedMesh.getAbsolutePivotPoint()),s.copyFrom(r).subtractInPlace(n).normalize(),this.attachedSlate._followButton.isToggled=!1,W.Pq.TransformNormalToRef(t,this.attachedMesh.getWorldMatrix(),o),o.normalize(),this._handleHovered&&(this._handleDragged=this._handleHovered,this._handleDragged.drag=!0))}),(e=>{if(this.attachedSlate&&this.attachedMesh){this._tmpVector.copyFrom(e.position),this._tmpVector.subtractInPlace(n),this._tmpVector.normalize();const r=-W.Pq.GetAngleBetweenVectorsOnPlane(this._tmpVector,s,o);W.PT.RotationAxisToRef(t,r,this._tmpQuaternion),i.multiplyToRef(this._tmpQuaternion,this.attachedMesh.rotationQuaternion)}}),(()=>{this.attachedSlate&&this.attachedNode&&(this.attachedSlate._updatePivot(),this._handleDragged&&(this._handleDragged.drag=!1,this._handleDragged=null))}))}_attachedNodeChanged(e){e&&this.updateBoundingBox()}updateBoundingBox(){if(this.attachedMesh){ji._RemoveAndStorePivotPoint(this.attachedMesh);const e=this.attachedMesh.parent;this.attachedMesh.setParent(null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=W.PT.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);const t=this.attachedMesh.getHierarchyBoundingVectors();t.max.subtractToRef(t.min,this._boundingDimensions),this._boundingBoxGizmo.min=t.min,this._boundingBoxGizmo.max=t.max,this._updateHandlesPosition(),this._updateHandlesScaling(),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),ji._RestorePivotPoint(this.attachedMesh),this.attachedMesh.setParent(e),this.attachedMesh.computeWorldMatrix(!0),this._existingSlateScale.copyFrom(this.attachedMesh.scaling)}}_updateHandlesPosition(){const e=this._boundingBoxGizmo.min.clone(),t=this._boundingBoxGizmo.max.clone(),i=this._corners[0].node.scaling.length();e.x-=this._margin*i,e.y-=this._margin*i,t.x+=this._margin*i,t.y+=this._margin*i;const r=e.add(t).scaleInPlace(.5);this._corners[0].node.position.copyFromFloats(e.x,e.y,0),this._corners[1].node.position.copyFromFloats(t.x,e.y,0),this._corners[2].node.position.copyFromFloats(t.x,t.y,0),this._corners[3].node.position.copyFromFloats(e.x,t.y,0),this._sides[0].node.position.copyFromFloats(e.x,r.y,0),this._sides[1].node.position.copyFromFloats(r.x,e.y,0),this._sides[2].node.position.copyFromFloats(t.x,r.y,0),this._sides[3].node.position.copyFromFloats(r.x,t.y,0)}_updateHandlesScaling(){if(this._attachedSlate&&this._attachedSlate.mesh){const e=this._attachedSlate.mesh.scaling.x*this._attachedSlate.dimensions.x,t=this._attachedSlate.mesh.scaling.y*this._attachedSlate.dimensions.y,i=Math.min(e,t)*this._handleSize;for(let e=0;ei?this.minDimensions.x/e.x:this.minDimensions.y/e.y}this._dimensions.copyFrom(e).scaleInPlace(t),this._updatePivot(),this._positionElements()}get titleBarHeight(){return this._titleBarHeight}set titleBarHeight(e){this._titleBarHeight=e}set renderingGroupId(e){this._titleBar.renderingGroupId=e,this._titleBarTitle.renderingGroupId=e,this._contentPlate.renderingGroupId=e,this._backPlate.renderingGroupId=e}get renderingGroupId(){return this._titleBar.renderingGroupId}set title(e){this._titleText=e,this._titleTextComponent&&(this._titleTextComponent.text=e)}get title(){return this._titleText}constructor(e){super(e),this.titleBarMargin=.005,this.origin=new W.Pq(0,0,0),this._dimensions=new W.I9(21.875,12.5),this._titleBarHeight=.625,this._titleText="",this.fitContentToDimensions=!1,this._contentScaleRatio=1,this.minDimensions=new W.I9(15.625,6.25),this.defaultDimensions=this._dimensions.clone(),this._followButton=new SV("followButton"+this.name),this._followButton.isToggleButton=!0,this._closeButton=new SV("closeButton"+this.name),this._contentViewport=new et.L(0,0,1,1),this._contentDragBehavior=new Ji({dragPlaneNormal:new W.Pq(0,0,-1)})}_applyFacade(e){this._contentMaterial.albedoTexture=e,this._resetContentPositionAndZoom(),this._applyContentViewport(),e.attachToMesh(this._contentPlate,!0)}_addControl(e){e._host=this._host,this._host.utilityLayer&&e._prepareNode(this._host.utilityLayer.utilityLayerScene)}_getTypeName(){return"HolographicSlate"}_positionElements(){const e=this._followButton,t=this._closeButton,i=this._titleBar,r=this._titleBarTitle,s=this._contentPlate,n=this._backPlate;if(e&&t&&i){t.scaling.setAll(this.titleBarHeight),e.scaling.setAll(this.titleBarHeight),t.position.copyFromFloats(this.dimensions.x-this.titleBarHeight/2,-this.titleBarHeight/2,0).addInPlace(this.origin),e.position.copyFromFloats(this.dimensions.x-3*this.titleBarHeight/2,-this.titleBarHeight/2,0).addInPlace(this.origin);const o=this.dimensions.y-this.titleBarHeight-this.titleBarMargin,a=s.getScene().useRightHandedSystem;i.scaling.set(this.dimensions.x,this.titleBarHeight,lt.bH),r.scaling.set(this.dimensions.x-2*this.titleBarHeight,this.titleBarHeight,lt.bH),s.scaling.copyFromFloats(this.dimensions.x,o,lt.bH),n.scaling.copyFromFloats(this.dimensions.x,o,lt.bH),i.position.copyFromFloats(this.dimensions.x/2,-this.titleBarHeight/2,0).addInPlace(this.origin),r.position.copyFromFloats(this.dimensions.x/2-this.titleBarHeight,-this.titleBarHeight/2,a?lt.bH:-lt.bH).addInPlace(this.origin),s.position.copyFromFloats(this.dimensions.x/2,-(this.titleBarHeight+this.titleBarMargin+o/2),0).addInPlace(this.origin),n.position.copyFromFloats(this.dimensions.x/2,-(this.titleBarHeight+this.titleBarMargin+o/2),a?-lt.bH:lt.bH).addInPlace(this.origin),this._titleTextComponent.host.scaleTo(IV._DEFAULT_TEXT_RESOLUTION_Y*r.scaling.x/r.scaling.y,IV._DEFAULT_TEXT_RESOLUTION_Y);const l=this.dimensions.x/o;this._contentViewport.width=this._contentScaleRatio,this._contentViewport.height=this._contentScaleRatio/l,this._applyContentViewport(),this._gizmo&&this._gizmo.updateBoundingBox()}}_applyContentViewport(){if(this._contentPlate?.material&&this._contentPlate.material.albedoTexture){const e=this._contentPlate.material.albedoTexture;e.uScale=this._contentScaleRatio,e.vScale=this.fitContentToDimensions?this._contentScaleRatio:this._contentScaleRatio/this._contentViewport.width*this._contentViewport.height,e.uOffset=this._contentViewport.x,e.vOffset=this._contentViewport.y}}_resetContentPositionAndZoom(){this._contentViewport.x=0,this._contentViewport.y=0,this._contentScaleRatio=1}_updatePivot(){if(!this.mesh)return;const e=new W.Pq(.5*this.dimensions.x,.5*-this.dimensions.y,lt.bH);e.addInPlace(this.origin),e.z=0;const t=new W.Pq(0,0,0);W.Pq.TransformCoordinatesToRef(t,this.mesh.computeWorldMatrix(!0),t),this.mesh.setPivotPoint(e);const i=new W.Pq(0,0,0);W.Pq.TransformCoordinatesToRef(i,this.mesh.computeWorldMatrix(!0),i),this.mesh.position.addInPlace(t).subtractInPlace(i)}_createNode(e){const t=new Yt("slate_"+this.name,e);this._titleBar=Ko("titleBar_"+this.name,{size:1},e),this._titleBarTitle=Qi("titleText_"+this.name,{size:1},e),this._titleBarTitle.parent=t,this._titleBarTitle.isPickable=!1;const i=$B.CreateForMesh(this._titleBarTitle);if(this._titleTextComponent=new dB("titleText_"+this.name,this._titleText),this._titleTextComponent.textWrapping=2,this._titleTextComponent.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,this._titleTextComponent.color="white",this._titleTextComponent.fontSize=IV._DEFAULT_TEXT_RESOLUTION_Y/2,this._titleTextComponent.paddingLeft=IV._DEFAULT_TEXT_RESOLUTION_Y/4,i.addControl(this._titleTextComponent),e.useRightHandedSystem){const t=new hc.IU(0,0,1,1);this._contentPlate=Qi("contentPlate_"+this.name,{size:1,sideOrientation:bt.BACKSIDE,frontUVs:t},e),this._backPlate=Qi("backPlate_"+this.name,{size:1,sideOrientation:bt.FRONTSIDE},e)}else{const t=new hc.IU(0,0,1,1);this._contentPlate=Qi("contentPlate_"+this.name,{size:1,sideOrientation:bt.FRONTSIDE,frontUVs:t},e),this._backPlate=Qi("backPlate_"+this.name,{size:1,sideOrientation:bt.BACKSIDE},e)}this._titleBar.parent=t,this._titleBar.isNearGrabbable=!0,this._contentPlate.parent=t,this._backPlate.parent=t,this._attachContentPlateBehavior(),this._addControl(this._followButton),this._addControl(this._closeButton);const r=this._followButton,s=this._closeButton;return r.node.parent=t,s.node.parent=t,this._positionElements(),this._followButton.imageUrl=IV.ASSETS_BASE_URL+IV.FOLLOW_ICON_FILENAME,this._closeButton.imageUrl=IV.ASSETS_BASE_URL+IV.CLOSE_ICON_FILENAME,this._followButton.isBackplateVisible=!1,this._closeButton.isBackplateVisible=!1,this._followButton.onToggleObservable.add((e=>{this._defaultBehavior.followBehaviorEnabled=e,this._defaultBehavior.followBehaviorEnabled&&this._defaultBehavior.followBehavior.recenter()})),this._closeButton.onPointerClickObservable.add((()=>{this.dispose()})),t.rotationQuaternion=W.PT.Identity(),t.isVisible=!1,t}_attachContentPlateBehavior(){this._contentDragBehavior.attach(this._contentPlate),this._contentDragBehavior.moveAttached=!1,this._contentDragBehavior.useObjectOrientationForDragging=!0,this._contentDragBehavior.updateDragPlane=!1;const e=new W.Pq,t=new W.Pq,i=new W.Pq,r=new W.Pq,s=new W.I9;let n,o;this._contentDragBehavior.onDragStartObservable.add((s=>{this.node&&(n=this._contentViewport.clone(),o=this.node.computeWorldMatrix(!0),e.copyFrom(s.dragPlanePoint),t.set(this.dimensions.x,this.dimensions.y,lt.bH),t.y-=this.titleBarHeight+this.titleBarMargin,W.Pq.TransformNormalToRef(t,o,t),i.copyFromFloats(0,1,0),W.Pq.TransformNormalToRef(i,o,i),r.copyFromFloats(1,0,0),W.Pq.TransformNormalToRef(r,o,r),i.normalize(),i.scaleInPlace(1/W.Pq.Dot(i,t)),r.normalize(),r.scaleInPlace(1/W.Pq.Dot(r,t)))}));const a=new W.Pq;this._contentDragBehavior.onDragObservable.add((t=>{this.fitContentToDimensions||(a.copyFrom(t.dragPlanePoint),a.subtractInPlace(e),s.copyFromFloats(W.Pq.Dot(a,r),W.Pq.Dot(a,i)),this._contentViewport.x=Gy.Clamp(n.x-a.x,0,1-this._contentViewport.width*this._contentScaleRatio),this._contentViewport.y=Gy.Clamp(n.y-a.y,0,1-this._contentViewport.height*this._contentScaleRatio),this._applyContentViewport())}))}_affectMaterial(e){this._titleBarMaterial=new _V(`${this.name} plateMaterial`,e.getScene()),this._contentMaterial=new uV(`${this.name} contentMaterial`,e.getScene()),this._contentMaterial.renderBorders=!0,this._backMaterial=new _V(`${this.name} backPlate`,e.getScene()),this._backMaterial.lineWidth=lt.bH,this._backMaterial.radius=.005,this._backMaterial.backFaceCulling=!0,this._titleBar.material=this._titleBarMaterial,this._contentPlate.material=this._contentMaterial,this._backPlate.material=this._backMaterial,this._resetContent(),this._applyContentViewport()}_prepareNode(e){super._prepareNode(e),this._gizmo=new RV(this._host.utilityLayer),this._gizmo.attachedSlate=this,this._defaultBehavior=new TV,this._defaultBehavior.attach(this.node,[this._titleBar]),this._defaultBehavior.sixDofDragBehavior.onDragStartObservable.add((()=>{this._followButton.isToggled=!1})),this._positionChangedObserver=this._defaultBehavior.sixDofDragBehavior.onPositionChangedObservable.add((()=>{this._gizmo.updateBoundingBox()})),this._updatePivot(),this.resetDefaultAspectAndPose(!1)}resetDefaultAspectAndPose(e=!0){if(!this._host||!this._host.utilityLayer||!this.node)return;const t=this._host.utilityLayer.utilityLayerScene,i=t.activeCamera;if(i){const r=i.getWorldMatrix(),s=W.Pq.TransformNormal(W.Pq.Backward(t.useRightHandedSystem),r);this.origin.setAll(0),this._gizmo.updateBoundingBox();const n=this.node.getAbsolutePivotPoint();this.node.position.equalsToFloats(0,0,0)&&this.node.position.copyFrom(i.position).subtractInPlace(s).subtractInPlace(n),this.node.rotationQuaternion=W.PT.FromLookDirectionLH(s,new W.Pq(0,1,0)),e&&(this.dimensions=this.defaultDimensions)}}dispose(){super.dispose(),this._titleBarMaterial.dispose(),this._contentMaterial.dispose(),this._titleBar.dispose(),this._titleBarTitle.dispose(),this._contentPlate.dispose(),this._backPlate.dispose(),this._followButton.dispose(),this._closeButton.dispose(),this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._defaultBehavior.sixDofDragBehavior.onPositionChangedObservable.remove(this._positionChangedObserver),this._defaultBehavior.detach(),this._gizmo.dispose(),this._contentDragBehavior.detach()}}IV.ASSETS_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",IV.CLOSE_ICON_FILENAME="IconClose.png",IV.FOLLOW_ICON_FILENAME="IconFollowMe.png",IV._DEFAULT_TEXT_RESOLUTION_Y=102.4;class MV extends oV{constructor(e,t){super(t),this._currentMesh=e,this.pointerEnterAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1.1)},this.pointerOutAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/1.1)},this.pointerDownAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/.95)}}_getTypeName(){return"MeshButton3D"}_createNode(e){return this._currentMesh.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this})),this._currentMesh}_affectMaterial(e){}}class OV extends dV{get defaultBehavior(){return this._defaultBehavior}get isPinned(){return this._isPinned}set isPinned(e){this._pinButton.isToggled===e?(this._isPinned=e,this._defaultBehavior.followBehaviorEnabled=!e):this._pinButton.isToggled=e}_createPinButton(e){const t=new SV("pin"+this.name,!1);return t.imageUrl=OV._ASSETS_BASE_URL+OV._PIN_ICON_FILENAME,t.parent=this,t._host=this._host,t.isToggleButton=!0,t.onToggleObservable.add((e=>{this.isPinned=e})),this._host.utilityLayer&&(t._prepareNode(this._host.utilityLayer.utilityLayerScene),t.scaling.scaleInPlace(dV.MENU_BUTTON_SCALE),t.node&&(t.node.parent=e)),t}_createNode(e){const t=super._createNode(e);return this._pinButton=this._createPinButton(t),this.isPinned=!1,this._defaultBehavior.attach(t,[this._backPlate]),this._defaultBehavior.followBehavior.ignoreCameraPitchAndRoll=!0,this._defaultBehavior.followBehavior.pitchOffset=-15,this._defaultBehavior.followBehavior.minimumDistance=.3,this._defaultBehavior.followBehavior.defaultDistance=.4,this._defaultBehavior.followBehavior.maximumDistance=.6,this._backPlate.isNearGrabbable=!0,t.isVisible=!1,t}_finalProcessing(){super._finalProcessing(),this._pinButton.position.copyFromFloats((this._backPlate.scaling.x+dV.MENU_BUTTON_SCALE)/2,this._backPlate.scaling.y/2,0)}constructor(e){super(e),this._isPinned=!1,this._defaultBehavior=new TV,this._dragObserver=this._defaultBehavior.sixDofDragBehavior.onDragObservable.add((()=>{this.isPinned=!0})),this.backPlateMargin=1}dispose(){super.dispose(),this._defaultBehavior.sixDofDragBehavior.onDragObservable.remove(this._dragObserver),this._defaultBehavior.detach()}}OV._ASSETS_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",OV._PIN_ICON_FILENAME="IconPin.png";class DV extends lV{_mapGridNode(e,t){const i=e.mesh;if(!i)return;e.position=t.clone();const r=W.AA.Vector3[0];switch(r.copyFrom(t),this.orientation){case aV.FACEORIGIN_ORIENTATION:case aV.FACEFORWARD_ORIENTATION:r.addInPlace(new W.Pq(0,0,1)),i.lookAt(r);break;case aV.FACEFORWARDREVERSED_ORIENTATION:case aV.FACEORIGINREVERSED_ORIENTATION:r.addInPlace(new W.Pq(0,0,-1)),i.lookAt(r)}}}class wV extends lV{constructor(){super(...arguments),this._iteration=100}get iteration(){return this._iteration}set iteration(e){this._iteration!==e&&(this._iteration=e,Ue.S0.SetImmediate((()=>{this._arrangeChildren()})))}_mapGridNode(e,t){const i=e.mesh,r=this._scatterMapping(t);if(i){switch(this.orientation){case aV.FACEORIGIN_ORIENTATION:case aV.FACEFORWARD_ORIENTATION:i.lookAt(new W.Pq(0,0,1));break;case aV.FACEFORWARDREVERSED_ORIENTATION:case aV.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new W.Pq(0,0,-1))}e.position=r}}_scatterMapping(e){return e.x=(1-2*Math.random())*this._cellWidth,e.y=(1-2*Math.random())*this._cellHeight,e}_finalProcessing(){const e=[];for(const t of this._children)t.mesh&&e.push(t.mesh);for(let t=0;t{const i=e.position.lengthSquared(),r=t.position.lengthSquared();return ir?-1:0}));const t=Math.pow(this.margin,2),i=Math.max(this._cellWidth,this._cellHeight),r=W.AA.Vector2[0],s=W.AA.Vector3[0];for(let n=0;n0.0) {C=mix(H,S,k);} else {C=mix(H,G,k); }\nreturn C;}\nvoid Sky_Environment_B50(\nvec3 Normal,\nvec3 Reflected,\nvec4 Sky_Color,\nvec4 Horizon_Color,\nvec4 Ground_Color,\nfloat Horizon_Power,\nout vec4 Reflected_Color,\nout vec4 Indirect_Color)\n{Reflected_Color=SampleEnv_Bid50(Reflected,Sky_Color,Horizon_Color,Ground_Color,Horizon_Power);Indirect_Color=mix(Ground_Color,Sky_Color,Normal.y*0.5+0.5);}\nvoid Min_Segment_Distance_B65(\nvec3 P0,\nvec3 P1,\nvec3 Q0,\nvec3 Q1,\nout vec3 NearP,\nout vec3 NearQ,\nout float Distance)\n{vec3 u=P1-P0;vec3 v=Q1-Q0;vec3 w=P0-Q0;float a=dot(u,u);float b=dot(u,v);float c=dot(v,v);float d=dot(u,w);float e=dot(v,w);float D=a*c-b*b;float sD=D;float tD=D;float sc,sN,tc,tN;if (D<0.00001) {sN=0.0;sD=1.0;tN=e;tD=c;} else {sN=(b*e-c*d);tN=(a*e-b*d);if (sN<0.0) {sN=0.0;tN=e;tD=c;} else if (sN>sD) {sN=sD;tN=e+b;tD=c;}}\nif (tN<0.0) {tN=0.0;if (-d<0.0) {sN=0.0;} else if (-d>a) {sN=sD;} else {sN=-d;sD=a;}} else if (tN>tD) {tN=tD;if ((-d+b)<0.0) {sN=0.0;} else if ((-d+b)>a) {sN=sD;} else {sN=(-d+b);sD=a;}}\nsc=abs(sN)<0.000001 ? 0.0 : sN/sD;tc=abs(tN)<0.000001 ? 0.0 : tN/tD;NearP=P0+sc*u;NearQ=Q0+tc*v;Distance=distance(NearP,NearQ);}\nvoid To_XYZ_B74(\nvec3 Vec3,\nout float X,\nout float Y,\nout float Z)\n{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;}\nvoid Finger_Positions_B64(\nvec3 Left_Index_Pos,\nvec3 Right_Index_Pos,\nvec3 Left_Index_Middle_Pos,\nvec3 Right_Index_Middle_Pos,\nout vec3 Left_Index,\nout vec3 Right_Index,\nout vec3 Left_Index_Middle,\nout vec3 Right_Index_Middle)\n{Left_Index= (Use_Global_Left_Index ? Global_Left_Index_Tip_Position.xyz : Left_Index_Pos);Right_Index= (Use_Global_Right_Index ? Global_Right_Index_Tip_Position.xyz : Right_Index_Pos);Left_Index_Middle= (Use_Global_Left_Index ? Global_Left_Index_Middle_Position.xyz : Left_Index_Middle_Pos);Right_Index_Middle= (Use_Global_Right_Index ? Global_Right_Index_Middle_Position.xyz : Right_Index_Middle_Pos);}\nvoid VaryHSV_B108(\nvec3 HSV_In,\nfloat Hue_Shift,\nfloat Saturation_Shift,\nfloat Value_Shift,\nout vec3 HSV_Out)\n{HSV_Out=vec3(fract(HSV_In.x+Hue_Shift),clamp(HSV_In.y+Saturation_Shift,0.0,1.0),clamp(HSV_In.z+Value_Shift,0.0,1.0));}\nvoid Remap_Range_B114(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid To_HSV_B75(\nvec4 Color,\nout float Hue,\nout float Saturation,\nout float Value,\nout float Alpha,\nout vec3 HSV)\n{vec4 K=vec4(0.0,-1.0/3.0,2.0/3.0,-1.0);vec4 p=Color.g0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid Conditional_Float_B36(\nbool Which,\nfloat If_True,\nfloat If_False,\nout float Result)\n{Result=Which ? If_True : If_False;}\nvoid Greater_Than_B37(\nfloat Left,\nfloat Right,\nout bool Not_Greater_Than,\nout bool Greater_Than)\n{Greater_Than=Left>Right;Not_Greater_Than=!Greater_Than;}\nvoid Remap_Range_B105(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid main()\n{vec2 XY_Q85;XY_Q85=(uv-vec2(0.5,0.5))*_Decal_Scale_XY_+vec2(0.5,0.5);vec3 Tangent_World_Q27;vec3 Tangent_World_N_Q27;float Tangent_Length_Q27;Tangent_World_Q27=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q27=length(Tangent_World_Q27);Tangent_World_N_Q27=Tangent_World_Q27/Tangent_Length_Q27;vec3 Normal_World_Q60;vec3 Normal_World_N_Q60;float Normal_Length_Q60;Object_To_World_Dir_B60(vec3(0,0,1),Normal_World_Q60,Normal_World_N_Q60,Normal_Length_Q60);float X_Q78;float Y_Q78;float Z_Q78;To_XYZ_B78(position,X_Q78,Y_Q78,Z_Q78);vec3 Nrm_World_Q26;Nrm_World_Q26=normalize((world*vec4(normal,0.0)).xyz);vec3 Binormal_World_Q28;vec3 Binormal_World_N_Q28;float Binormal_Length_Q28;Object_To_World_Dir_B28(vec3(0,1,0),Binormal_World_Q28,Binormal_World_N_Q28,Binormal_Length_Q28);float Anisotropy_Q29=Tangent_Length_Q27/Binormal_Length_Q28;float Result_Q69;Pick_Radius_B69(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q69);float Anisotropy_Q53=Binormal_Length_Q28/Normal_Length_Q60;bool Not_Greater_Than_Q37;bool Greater_Than_Q37;Greater_Than_B37(Z_Q78,0.0,Not_Greater_Than_Q37,Greater_Than_Q37);vec4 Linear_Q101;Linear_Q101.rgb=clamp(_Left_Color_.rgb*_Left_Color_.rgb,0.0,1.0);Linear_Q101.a=_Left_Color_.a;vec4 Linear_Q102;Linear_Q102.rgb=clamp(_Right_Color_.rgb*_Right_Color_.rgb,0.0,1.0);Linear_Q102.a=_Right_Color_.a;vec3 Difference_Q61=vec3(0,0,0)-Normal_World_N_Q60;vec4 Out_Color_Q34=vec4(X_Q78,Y_Q78,Z_Q78,1);float Result_Q36;Conditional_Float_B36(Greater_Than_Q37,_Bevel_Back_,_Bevel_Front_,Result_Q36);float Result_Q94;Conditional_Float_B36(Greater_Than_Q37,_Bevel_Back_Stretch_,_Bevel_Front_Stretch_,Result_Q94);vec3 New_P_Q130;vec2 New_UV_Q130;float Radial_Gradient_Q130;vec3 Radial_Dir_Q130;vec3 New_Normal_Q130;Move_Verts_B130(Anisotropy_Q29,position,Result_Q69,Result_Q36,normal,Anisotropy_Q53,Result_Q94,New_P_Q130,New_UV_Q130,Radial_Gradient_Q130,Radial_Dir_Q130,New_Normal_Q130);float X_Q98;float Y_Q98;X_Q98=New_UV_Q130.x;Y_Q98=New_UV_Q130.y;vec3 Pos_World_Q12;Object_To_World_Pos_B12(New_P_Q130,Pos_World_Q12);vec3 Nrm_World_Q32;Object_To_World_Normal_B32(New_Normal_Q130,Nrm_World_Q32);vec4 Blob_Info_Q23;\n#if BLOB_ENABLE\nBlob_Vertex_B23(Pos_World_Q12,Nrm_World_Q26,Tangent_World_N_Q27,Binormal_World_N_Q28,_Blob_Position_,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q23);\n#else\nBlob_Info_Q23=vec4(0,0,0,0);\n#endif\nvec4 Blob_Info_Q24;\n#if BLOB_ENABLE_2\nBlob_Vertex_B24(Pos_World_Q12,Nrm_World_Q26,Tangent_World_N_Q27,Binormal_World_N_Q28,_Blob_Position_2_,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q24);\n#else\nBlob_Info_Q24=vec4(0,0,0,0);\n#endif\nfloat Out_Q105;Remap_Range_B105(0.0,1.0,0.0,1.0,X_Q98,Out_Q105);float X_Q86;float Y_Q86;float Z_Q86;To_XYZ_B78(Nrm_World_Q32,X_Q86,Y_Q86,Z_Q86);vec4 Color_At_T_Q97=mix(Linear_Q101,Linear_Q102,Out_Q105);float Minus_F_Q87=-Z_Q86;float R_Q99;float G_Q99;float B_Q99;float A_Q99;R_Q99=Color_At_T_Q97.r; G_Q99=Color_At_T_Q97.g; B_Q99=Color_At_T_Q97.b; A_Q99=Color_At_T_Q97.a;float ClampF_Q88=clamp(0.0,Minus_F_Q87,1.0);float Result_Q93;Conditional_Float_B93(_Decal_Front_Only_,ClampF_Q88,1.0,Result_Q93);vec4 Vec4_Q89=vec4(Result_Q93,Radial_Gradient_Q130,G_Q99,B_Q99);vec3 Position=Pos_World_Q12;vec3 Normal=Nrm_World_Q32;vec2 UV=XY_Q85;vec3 Tangent=Tangent_World_N_Q27;vec3 Binormal=Difference_Q61;vec4 Color=Out_Color_Q34;vec4 Extra1=Vec4_Q89;vec4 Extra2=Blob_Info_Q23;vec4 Extra3=Blob_Info_Q24;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class NV extends xn{constructor(){super(),this.SKY_ENABLED=!0,this.BLOB_ENABLE_2=!0,this.IRIDESCENCE_ENABLED=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class FV extends bn{constructor(e,t){super(e,t),this.radius=.6,this.bevelFront=.6,this.bevelFrontStretch=.077,this.bevelBack=0,this.bevelBackStretch=0,this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this.bulgeEnabled=!1,this.bulgeHeight=-.323,this.bulgeRadius=.73,this.sunIntensity=1.102,this.sunTheta=.76,this.sunPhi=.526,this.indirectDiffuse=.658,this.albedo=new H.ov(.0117647,.505882,.996078,1),this.specular=0,this.shininess=10,this.sharpness=0,this.subsurface=0,this.leftGradientColor=new H.ov(.0117647,.505882,.996078,1),this.rightGradientColor=new H.ov(.0117647,.505882,.996078,1),this.reflection=.749,this.frontReflect=0,this.edgeReflect=.09,this.power=8.13,this.skyColor=new H.ov(.0117647,.964706,.996078,1),this.horizonColor=new H.ov(.0117647,.333333,.996078,1),this.groundColor=new H.ov(0,.254902,.996078,1),this.horizonPower=1,this.width=.02,this.fuzz=.5,this.minFuzz=.001,this.clipFade=.01,this.hueShift=0,this.saturationShift=0,this.valueShift=0,this.blobPosition=new W.Pq(0,0,.1),this.blobIntensity=.5,this.blobNearSize=.01,this.blobFarSize=.03,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.576,this.blobPulse=0,this.blobFade=1,this.blobPosition2=new W.Pq(.2,0,.1),this.blobNearSize2=.01,this.blobPulse2=0,this.blobFade2=1,this.blobTexture=new vi.g("",this.getScene()),this.leftIndexPosition=new W.Pq(0,0,1),this.rightIndexPosition=new W.Pq(-1,-1,-1),this.leftIndexMiddlePosition=new W.Pq(0,0,0),this.rightIndexMiddlePosition=new W.Pq(0,0,0),this.decalScaleXY=new W.I9(1.5,1.5),this.decalFrontOnly=!0,this.rimIntensity=.287,this.rimHueShift=0,this.rimSaturationShift=0,this.rimValueShift=-1,this.iridescenceIntensity=0,this.useGlobalLeftIndex=1,this.useGlobalRightIndex=1,this.globalLeftIndexTipProximity=0,this.globalRightIndexTipProximity=0,this.globalLeftIndexTipPosition=new W.IU(.5,0,-.55,1),this.globaRightIndexTipPosition=new W.IU(0,0,0,1),this.globalLeftThumbTipPosition=new W.IU(.5,0,-.55,1),this.globalRightThumbTipPosition=new W.IU(0,0,0,1),this.globalLeftIndexMiddlePosition=new W.IU(.5,0,-.55,1),this.globalRightIndexMiddlePosition=new W.IU(0,0,0,1),this.alphaMode=Il.ALPHA_DISABLE,this.backFaceCulling=!1,this._blueGradientTexture=new vi.g(FV.BLUE_GRADIENT_TEXTURE_URL,this.getScene(),!0,!1,vi.g.NEAREST_SAMPLINGMODE),this._decalTexture=new vi.g("",this.getScene()),this._reflectionMapTexture=new vi.g("",this.getScene()),this._indirectEnvTexture=new vi.g("",this.getScene())}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new NV);const r=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if((0,Bt.qB)(e,r,!1,!1),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=new Tn;r.FOG&&e.addFallback(1,"FOG"),(0,Bt.c4)(r,e),r.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const i=[st.R.PositionKind];r.NORMAL&&i.push(st.R.NormalKind),r.UV1&&i.push(st.R.UVKind),r.UV2&&i.push(st.R.UV2Kind),r.VERTEXCOLOR&&i.push(st.R.ColorKind),r.TANGENT&&i.push(st.R.TangentKind),(0,Bt.ER)(i,r);const o="mrdlSliderBar",a=r.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Bevel_Front_","_Bevel_Front_Stretch_","_Bevel_Back_","_Bevel_Back_Stretch_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Bulge_Enabled_","_Bulge_Height_","_Bulge_Radius_","_Sun_Intensity_","_Sun_Theta_","_Sun_Phi_","_Indirect_Diffuse_","_Albedo_","_Specular_","_Shininess_","_Sharpness_","_Subsurface_","_Left_Color_","_Right_Color_","_Reflection_","_Front_Reflect_","_Edge_Reflect_","_Power_","_Sky_Color_","_Horizon_Color_","_Ground_Color_","_Horizon_Power_","_Reflection_Map_","_Indirect_Environment_","_Width_","_Fuzz_","_Min_Fuzz_","_Clip_Fade_","_Hue_Shift_","_Saturation_Shift_","_Value_Shift_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Left_Index_Pos_","_Right_Index_Pos_","_Left_Index_Middle_Pos_","_Right_Index_Middle_Pos_","_Decal_","_Decal_Scale_XY_","_Decal_Front_Only_","_Rim_Intensity_","_Rim_Texture_","_Rim_Hue_Shift_","_Rim_Saturation_Shift_","_Rim_Value_Shift_","_Iridescence_Intensity_","_Iridescence_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Middle_Position;","Global_Right_Index_Middle_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],h=["_Rim_Texture_","_Iridescence_Texture_"],c=[];(0,Bt.Bb)({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:r,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Bevel_Front_",this.bevelFront),this._activeEffect.setFloat("_Bevel_Front_Stretch_",this.bevelFrontStretch),this._activeEffect.setFloat("_Bevel_Back_",this.bevelBack),this._activeEffect.setFloat("_Bevel_Back_Stretch_",this.bevelBackStretch),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Bulge_Enabled_",this.bulgeEnabled?1:0),this._activeEffect.setFloat("_Bulge_Height_",this.bulgeHeight),this._activeEffect.setFloat("_Bulge_Radius_",this.bulgeRadius),this._activeEffect.setFloat("_Sun_Intensity_",this.sunIntensity),this._activeEffect.setFloat("_Sun_Theta_",this.sunTheta),this._activeEffect.setFloat("_Sun_Phi_",this.sunPhi),this._activeEffect.setFloat("_Indirect_Diffuse_",this.indirectDiffuse),this._activeEffect.setDirectColor4("_Albedo_",this.albedo),this._activeEffect.setFloat("_Specular_",this.specular),this._activeEffect.setFloat("_Shininess_",this.shininess),this._activeEffect.setFloat("_Sharpness_",this.sharpness),this._activeEffect.setFloat("_Subsurface_",this.subsurface),this._activeEffect.setDirectColor4("_Left_Color_",this.leftGradientColor),this._activeEffect.setDirectColor4("_Right_Color_",this.rightGradientColor),this._activeEffect.setFloat("_Reflection_",this.reflection),this._activeEffect.setFloat("_Front_Reflect_",this.frontReflect),this._activeEffect.setFloat("_Edge_Reflect_",this.edgeReflect),this._activeEffect.setFloat("_Power_",this.power),this._activeEffect.setDirectColor4("_Sky_Color_",this.skyColor),this._activeEffect.setDirectColor4("_Horizon_Color_",this.horizonColor),this._activeEffect.setDirectColor4("_Ground_Color_",this.groundColor),this._activeEffect.setFloat("_Horizon_Power_",this.horizonPower),this._activeEffect.setTexture("_Reflection_Map_",this._reflectionMapTexture),this._activeEffect.setTexture("_Indirect_Environment_",this._indirectEnvTexture),this._activeEffect.setFloat("_Width_",this.width),this._activeEffect.setFloat("_Fuzz_",this.fuzz),this._activeEffect.setFloat("_Min_Fuzz_",this.minFuzz),this._activeEffect.setFloat("_Clip_Fade_",this.clipFade),this._activeEffect.setFloat("_Hue_Shift_",this.hueShift),this._activeEffect.setFloat("_Saturation_Shift_",this.saturationShift),this._activeEffect.setFloat("_Value_Shift_",this.valueShift),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this.blobTexture),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setVector3("_Left_Index_Pos_",this.leftIndexPosition),this._activeEffect.setVector3("_Right_Index_Pos_",this.rightIndexPosition),this._activeEffect.setVector3("_Left_Index_Middle_Pos_",this.leftIndexMiddlePosition),this._activeEffect.setVector3("_Right_Index_Middle_Pos_",this.rightIndexMiddlePosition),this._activeEffect.setTexture("_Decal_",this._decalTexture),this._activeEffect.setVector2("_Decal_Scale_XY_",this.decalScaleXY),this._activeEffect.setFloat("_Decal_Front_Only_",this.decalFrontOnly?1:0),this._activeEffect.setFloat("_Rim_Intensity_",this.rimIntensity),this._activeEffect.setTexture("_Rim_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("_Rim_Hue_Shift_",this.rimHueShift),this._activeEffect.setFloat("_Rim_Saturation_Shift_",this.rimSaturationShift),this._activeEffect.setFloat("_Rim_Value_Shift_",this.rimValueShift),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setTexture("_Iridescence_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("Use_Global_Left_Index",this.useGlobalLeftIndex),this._activeEffect.setFloat("Use_Global_Right_Index",this.useGlobalRightIndex),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this.globalLeftIndexTipPosition),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this.globaRightIndexTipPosition),this._activeEffect.setVector4("Global_Left_Thumb_Tip_Position",this.globalLeftThumbTipPosition),this._activeEffect.setVector4("Global_Right_Thumb_Tip_Position",this.globalRightThumbTipPosition),this._activeEffect.setVector4("Global_Left_Index_Middle_Position",this.globalLeftIndexMiddlePosition),this._activeEffect.setVector4("Global_Right_Index_Middle_Position",this.globalRightIndexMiddlePosition),this._activeEffect.setFloat("Global_Left_Index_Tip_Proximity",this.globalLeftIndexTipProximity),this._activeEffect.setFloat("Global_Right_Index_Tip_Proximity",this.globalRightIndexTipProximity),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._reflectionMapTexture.dispose(),this._indirectEnvTexture.dispose(),this._blueGradientTexture.dispose(),this._decalTexture.dispose()}clone(e){return it.p.Clone((()=>new FV(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLSliderBarMaterial",e}getClassName(){return"MRDLSliderBarMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new FV(e.name,t)),e,t,i)}}FV.BLUE_GRADIENT_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-blue-gradient.png",(0,je.Cg)([(0,$e.lK)()],FV.prototype,"radius",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"bevelFront",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"bevelFrontStretch",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"bevelBack",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"bevelBackStretch",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"radiusTopLeft",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"radiusTopRight",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"radiusBottomLeft",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"radiusBottomRight",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"bulgeEnabled",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"bulgeHeight",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"bulgeRadius",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"sunIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"sunTheta",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"sunPhi",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"indirectDiffuse",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"albedo",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"specular",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"shininess",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"sharpness",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"subsurface",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"leftGradientColor",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"rightGradientColor",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"reflection",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"frontReflect",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"edgeReflect",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"power",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"skyColor",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"horizonColor",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"groundColor",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"horizonPower",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"width",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"fuzz",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"minFuzz",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"clipFade",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"hueShift",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"saturationShift",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"valueShift",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobPosition",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobNearSize",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobFarSize",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobNearDistance",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobFarDistance",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobFadeLength",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobPulse",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobFade",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobPosition2",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobNearSize2",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobPulse2",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobFade2",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobTexture",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"leftIndexPosition",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"rightIndexPosition",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"leftIndexMiddlePosition",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"rightIndexMiddlePosition",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"decalScaleXY",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"decalFrontOnly",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"rimIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"rimHueShift",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"rimSaturationShift",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"rimValueShift",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"iridescenceIntensity",void 0),(0,X.Y5)("BABYLON.GUI.MRDLSliderBarMaterial",FV);Cs.l.ShadersStore.mrdlSliderThumbPixelShader="uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;uniform float _Radius_;uniform float _Bevel_Front_;uniform float _Bevel_Front_Stretch_;uniform float _Bevel_Back_;uniform float _Bevel_Back_Stretch_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform bool _Bulge_Enabled_;uniform float _Bulge_Height_;uniform float _Bulge_Radius_;uniform float _Sun_Intensity_;uniform float _Sun_Theta_;uniform float _Sun_Phi_;uniform float _Indirect_Diffuse_;uniform vec4 _Albedo_;uniform float _Specular_;uniform float _Shininess_;uniform float _Sharpness_;uniform float _Subsurface_;uniform vec4 _Left_Color_;uniform vec4 _Right_Color_;uniform float _Reflection_;uniform float _Front_Reflect_;uniform float _Edge_Reflect_;uniform float _Power_;uniform vec4 _Sky_Color_;uniform vec4 _Horizon_Color_;uniform vec4 _Ground_Color_;uniform float _Horizon_Power_;uniform sampler2D _Reflection_Map_;uniform sampler2D _Indirect_Environment_;uniform float _Width_;uniform float _Fuzz_;uniform float _Min_Fuzz_;uniform float _Clip_Fade_;uniform float _Hue_Shift_;uniform float _Saturation_Shift_;uniform float _Value_Shift_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Left_Index_Pos_;uniform vec3 _Right_Index_Pos_;uniform vec3 _Left_Index_Middle_Pos_;uniform vec3 _Right_Index_Middle_Pos_;uniform sampler2D _Decal_;uniform vec2 _Decal_Scale_XY_;uniform bool _Decal_Front_Only_;uniform float _Rim_Intensity_;uniform sampler2D _Rim_Texture_;uniform float _Rim_Hue_Shift_;uniform float _Rim_Saturation_Shift_;uniform float _Rim_Value_Shift_;uniform float _Iridescence_Intensity_;uniform sampler2D _Iridescence_Texture_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform vec4 Global_Left_Index_Middle_Position;uniform vec4 Global_Right_Index_Middle_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;void Blob_Fragment_B180(\nsampler2D Blob_Texture,\nvec4 Blob_Info1,\nvec4 Blob_Info2,\nout vec4 Blob_Color)\n{float k1=dot(Blob_Info1.xy,Blob_Info1.xy);float k2=dot(Blob_Info2.xy,Blob_Info2.xy);vec3 closer=k10.0) {C=mix(H,S,k);} else {C=mix(H,G,k); }\nreturn C;}\nvoid Sky_Environment_B200(\nvec3 Normal,\nvec3 Reflected,\nvec4 Sky_Color,\nvec4 Horizon_Color,\nvec4 Ground_Color,\nfloat Horizon_Power,\nout vec4 Reflected_Color,\nout vec4 Indirect_Color)\n{Reflected_Color=SampleEnv_Bid200(Reflected,Sky_Color,Horizon_Color,Ground_Color,Horizon_Power);Indirect_Color=mix(Ground_Color,Sky_Color,Normal.y*0.5+0.5);}\nvoid Min_Segment_Distance_B215(\nvec3 P0,\nvec3 P1,\nvec3 Q0,\nvec3 Q1,\nout vec3 NearP,\nout vec3 NearQ,\nout float Distance)\n{vec3 u=P1-P0;vec3 v=Q1-Q0;vec3 w=P0-Q0;float a=dot(u,u);float b=dot(u,v);float c=dot(v,v);float d=dot(u,w);float e=dot(v,w);float D=a*c-b*b;float sD=D;float tD=D;float sc,sN,tc,tN;if (D<0.00001) {sN=0.0;sD=1.0;tN=e;tD=c;} else {sN=(b*e-c*d);tN=(a*e-b*d);if (sN<0.0) {sN=0.0;tN=e;tD=c;} else if (sN>sD) {sN=sD;tN=e+b;tD=c;}}\nif (tN<0.0) {tN=0.0;if (-d<0.0) {sN=0.0;} else if (-d>a) {sN=sD;} else {sN=-d;sD=a;}} else if (tN>tD) {tN=tD;if ((-d+b)<0.0) {sN=0.0;} else if ((-d+b)>a) {sN=sD;} else {sN=(-d+b);sD=a;}}\nsc=abs(sN)<0.000001 ? 0.0 : sN/sD;tc=abs(tN)<0.000001 ? 0.0 : tN/tD;NearP=P0+sc*u;NearQ=Q0+tc*v;Distance=distance(NearP,NearQ);}\nvoid To_XYZ_B224(\nvec3 Vec3,\nout float X,\nout float Y,\nout float Z)\n{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;}\nvoid Finger_Positions_B214(\nvec3 Left_Index_Pos,\nvec3 Right_Index_Pos,\nvec3 Left_Index_Middle_Pos,\nvec3 Right_Index_Middle_Pos,\nout vec3 Left_Index,\nout vec3 Right_Index,\nout vec3 Left_Index_Middle,\nout vec3 Right_Index_Middle)\n{Left_Index= (Use_Global_Left_Index ? Global_Left_Index_Tip_Position.xyz : Left_Index_Pos);Right_Index= (Use_Global_Right_Index ? Global_Right_Index_Tip_Position.xyz : Right_Index_Pos);Left_Index_Middle= (Use_Global_Left_Index ? Global_Left_Index_Middle_Position.xyz : Left_Index_Middle_Pos);Right_Index_Middle= (Use_Global_Right_Index ? Global_Right_Index_Middle_Position.xyz : Right_Index_Middle_Pos);}\nvoid VaryHSV_B258(\nvec3 HSV_In,\nfloat Hue_Shift,\nfloat Saturation_Shift,\nfloat Value_Shift,\nout vec3 HSV_Out)\n{HSV_Out=vec3(fract(HSV_In.x+Hue_Shift),clamp(HSV_In.y+Saturation_Shift,0.0,1.0),clamp(HSV_In.z+Value_Shift,0.0,1.0));}\nvoid Remap_Range_B264(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid To_HSV_B225(\nvec4 Color,\nout float Hue,\nout float Saturation,\nout float Value,\nout float Alpha,\nout vec3 HSV)\n{vec4 K=vec4(0.0,-1.0/3.0,2.0/3.0,-1.0);vec4 p=Color.g0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid Conditional_Float_B186(\nbool Which,\nfloat If_True,\nfloat If_False,\nout float Result)\n{Result=Which ? If_True : If_False;}\nvoid Greater_Than_B187(\nfloat Left,\nfloat Right,\nout bool Not_Greater_Than,\nout bool Greater_Than)\n{Greater_Than=Left>Right;Not_Greater_Than=!Greater_Than;}\nvoid Remap_Range_B255(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid main()\n{vec2 XY_Q235;XY_Q235=(uv-vec2(0.5,0.5))*_Decal_Scale_XY_+vec2(0.5,0.5);vec3 Tangent_World_Q177;vec3 Tangent_World_N_Q177;float Tangent_Length_Q177;Tangent_World_Q177=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q177=length(Tangent_World_Q177);Tangent_World_N_Q177=Tangent_World_Q177/Tangent_Length_Q177;vec3 Normal_World_Q210;vec3 Normal_World_N_Q210;float Normal_Length_Q210;Object_To_World_Dir_B210(vec3(0,0,1),Normal_World_Q210,Normal_World_N_Q210,Normal_Length_Q210);float X_Q228;float Y_Q228;float Z_Q228;To_XYZ_B228(position,X_Q228,Y_Q228,Z_Q228);vec3 Nrm_World_Q176;Nrm_World_Q176=normalize((world*vec4(normal,0.0)).xyz);vec3 Binormal_World_Q178;vec3 Binormal_World_N_Q178;float Binormal_Length_Q178;Object_To_World_Dir_B178(vec3(0,1,0),Binormal_World_Q178,Binormal_World_N_Q178,Binormal_Length_Q178);float Anisotropy_Q179=Tangent_Length_Q177/Binormal_Length_Q178;float Result_Q219;Pick_Radius_B219(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q219);float Anisotropy_Q203=Binormal_Length_Q178/Normal_Length_Q210;bool Not_Greater_Than_Q187;bool Greater_Than_Q187;Greater_Than_B187(Z_Q228,0.0,Not_Greater_Than_Q187,Greater_Than_Q187);vec4 Linear_Q251;Linear_Q251.rgb=clamp(_Left_Color_.rgb*_Left_Color_.rgb,0.0,1.0);Linear_Q251.a=_Left_Color_.a;vec4 Linear_Q252;Linear_Q252.rgb=clamp(_Right_Color_.rgb*_Right_Color_.rgb,0.0,1.0);Linear_Q252.a=_Right_Color_.a;vec3 Difference_Q211=vec3(0,0,0)-Normal_World_N_Q210;vec4 Out_Color_Q184=vec4(X_Q228,Y_Q228,Z_Q228,1);float Result_Q186;Conditional_Float_B186(Greater_Than_Q187,_Bevel_Back_,_Bevel_Front_,Result_Q186);float Result_Q244;Conditional_Float_B186(Greater_Than_Q187,_Bevel_Back_Stretch_,_Bevel_Front_Stretch_,Result_Q244);vec3 New_P_Q280;vec2 New_UV_Q280;float Radial_Gradient_Q280;vec3 Radial_Dir_Q280;vec3 New_Normal_Q280;Move_Verts_B280(Anisotropy_Q179,position,Result_Q219,Result_Q186,normal,Anisotropy_Q203,Result_Q244,New_P_Q280,New_UV_Q280,Radial_Gradient_Q280,Radial_Dir_Q280,New_Normal_Q280);float X_Q248;float Y_Q248;X_Q248=New_UV_Q280.x;Y_Q248=New_UV_Q280.y;vec3 Pos_World_Q162;Object_To_World_Pos_B162(New_P_Q280,Pos_World_Q162);vec3 Nrm_World_Q182;Object_To_World_Normal_B182(New_Normal_Q280,Nrm_World_Q182);vec4 Blob_Info_Q173;\n#if BLOB_ENABLE\nBlob_Vertex_B173(Pos_World_Q162,Nrm_World_Q176,Tangent_World_N_Q177,Binormal_World_N_Q178,_Blob_Position_,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q173);\n#else\nBlob_Info_Q173=vec4(0,0,0,0);\n#endif\nvec4 Blob_Info_Q174;\n#if BLOB_ENABLE_2\nBlob_Vertex_B174(Pos_World_Q162,Nrm_World_Q176,Tangent_World_N_Q177,Binormal_World_N_Q178,_Blob_Position_2_,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q174);\n#else\nBlob_Info_Q174=vec4(0,0,0,0);\n#endif\nfloat Out_Q255;Remap_Range_B255(0.0,1.0,0.0,1.0,X_Q248,Out_Q255);float X_Q236;float Y_Q236;float Z_Q236;To_XYZ_B228(Nrm_World_Q182,X_Q236,Y_Q236,Z_Q236);vec4 Color_At_T_Q247=mix(Linear_Q251,Linear_Q252,Out_Q255);float Minus_F_Q237=-Z_Q236;float R_Q249;float G_Q249;float B_Q249;float A_Q249;R_Q249=Color_At_T_Q247.r; G_Q249=Color_At_T_Q247.g; B_Q249=Color_At_T_Q247.b; A_Q249=Color_At_T_Q247.a;float ClampF_Q238=clamp(0.0,Minus_F_Q237,1.0);float Result_Q243;Conditional_Float_B243(_Decal_Front_Only_,ClampF_Q238,1.0,Result_Q243);vec4 Vec4_Q239=vec4(Result_Q243,Radial_Gradient_Q280,G_Q249,B_Q249);vec3 Position=Pos_World_Q162;vec3 Normal=Nrm_World_Q182;vec2 UV=XY_Q235;vec3 Tangent=Tangent_World_N_Q177;vec3 Binormal=Difference_Q211;vec4 Color=Out_Color_Q184;vec4 Extra1=Vec4_Q239;vec4 Extra2=Blob_Info_Q173;vec4 Extra3=Blob_Info_Q174;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class LV extends xn{constructor(){super(),this.SKY_ENABLED=!0,this.BLOB_ENABLE_2=!0,this.IRIDESCENCE_ENABLED=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class BV extends bn{constructor(e,t){super(e,t),this.radius=.157,this.bevelFront=.065,this.bevelFrontStretch=.077,this.bevelBack=.031,this.bevelBackStretch=0,this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this.bulgeEnabled=!1,this.bulgeHeight=-.323,this.bulgeRadius=.73,this.sunIntensity=2,this.sunTheta=.937,this.sunPhi=.555,this.indirectDiffuse=1,this.albedo=new H.ov(.0117647,.505882,.996078,1),this.specular=0,this.shininess=10,this.sharpness=0,this.subsurface=.31,this.leftGradientColor=new H.ov(.0117647,.505882,.996078,1),this.rightGradientColor=new H.ov(.0117647,.505882,.996078,1),this.reflection=.749,this.frontReflect=0,this.edgeReflect=.09,this.power=8.1,this.skyColor=new H.ov(.0117647,.960784,.996078,1),this.horizonColor=new H.ov(.0117647,.333333,.996078,1),this.groundColor=new H.ov(0,.254902,.996078,1),this.horizonPower=1,this.width=.02,this.fuzz=.5,this.minFuzz=.001,this.clipFade=.01,this.hueShift=0,this.saturationShift=0,this.valueShift=0,this.blobPosition=new W.Pq(0,0,.1),this.blobIntensity=.5,this.blobNearSize=.01,this.blobFarSize=.03,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.576,this.blobPulse=0,this.blobFade=1,this.blobPosition2=new W.Pq(.2,0,.1),this.blobNearSize2=.01,this.blobPulse2=0,this.blobFade2=1,this.blobTexture=new vi.g("",this.getScene()),this.leftIndexPosition=new W.Pq(0,0,1),this.rightIndexPosition=new W.Pq(-1,-1,-1),this.leftIndexMiddlePosition=new W.Pq(0,0,0),this.rightIndexMiddlePosition=new W.Pq(0,0,0),this.decalScaleXY=new W.I9(1.5,1.5),this.decalFrontOnly=!0,this.rimIntensity=.287,this.rimHueShift=0,this.rimSaturationShift=0,this.rimValueShift=-1,this.iridescenceIntensity=0,this.useGlobalLeftIndex=1,this.useGlobalRightIndex=1,this.globalLeftIndexTipProximity=0,this.globalRightIndexTipProximity=0,this.globalLeftIndexTipPosition=new W.IU(.5,0,-.55,1),this.globaRightIndexTipPosition=new W.IU(0,0,0,1),this.globalLeftThumbTipPosition=new W.IU(.5,0,-.55,1),this.globalRightThumbTipPosition=new W.IU(0,0,0,1),this.globalLeftIndexMiddlePosition=new W.IU(.5,0,-.55,1),this.globalRightIndexMiddlePosition=new W.IU(0,0,0,1),this.alphaMode=Il.ALPHA_DISABLE,this.backFaceCulling=!1,this._blueGradientTexture=new vi.g(BV.BLUE_GRADIENT_TEXTURE_URL,t,!0,!1,vi.g.NEAREST_SAMPLINGMODE),this._decalTexture=new vi.g("",this.getScene()),this._reflectionMapTexture=new vi.g("",this.getScene()),this._indirectEnvTexture=new vi.g("",this.getScene())}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new LV);const r=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if((0,Bt.qB)(e,r,!1,!1),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=new Tn;r.FOG&&e.addFallback(1,"FOG"),(0,Bt.c4)(r,e),r.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const i=[st.R.PositionKind];r.NORMAL&&i.push(st.R.NormalKind),r.UV1&&i.push(st.R.UVKind),r.UV2&&i.push(st.R.UV2Kind),r.VERTEXCOLOR&&i.push(st.R.ColorKind),r.TANGENT&&i.push(st.R.TangentKind),(0,Bt.ER)(i,r);const o="mrdlSliderThumb",a=r.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Bevel_Front_","_Bevel_Front_Stretch_","_Bevel_Back_","_Bevel_Back_Stretch_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Bulge_Enabled_","_Bulge_Height_","_Bulge_Radius_","_Sun_Intensity_","_Sun_Theta_","_Sun_Phi_","_Indirect_Diffuse_","_Albedo_","_Specular_","_Shininess_","_Sharpness_","_Subsurface_","_Left_Color_","_Right_Color_","_Reflection_","_Front_Reflect_","_Edge_Reflect_","_Power_","_Sky_Color_","_Horizon_Color_","_Ground_Color_","_Horizon_Power_","_Reflection_Map_","_Indirect_Environment_","_Width_","_Fuzz_","_Min_Fuzz_","_Clip_Fade_","_Hue_Shift_","_Saturation_Shift_","_Value_Shift_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Left_Index_Pos_","_Right_Index_Pos_","_Left_Index_Middle_Pos_","_Right_Index_Middle_Pos_","_Decal_","_Decal_Scale_XY_","_Decal_Front_Only_","_Rim_Intensity_","_Rim_Texture_","_Rim_Hue_Shift_","_Rim_Saturation_Shift_","_Rim_Value_Shift_","_Iridescence_Intensity_","_Iridescence_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Middle_Position;","Global_Right_Index_Middle_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],h=["_Rim_Texture_","_Iridescence_Texture_"],c=[];(0,Bt.Bb)({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:r,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),r)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Bevel_Front_",this.bevelFront),this._activeEffect.setFloat("_Bevel_Front_Stretch_",this.bevelFrontStretch),this._activeEffect.setFloat("_Bevel_Back_",this.bevelBack),this._activeEffect.setFloat("_Bevel_Back_Stretch_",this.bevelBackStretch),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Bulge_Enabled_",this.bulgeEnabled?1:0),this._activeEffect.setFloat("_Bulge_Height_",this.bulgeHeight),this._activeEffect.setFloat("_Bulge_Radius_",this.bulgeRadius),this._activeEffect.setFloat("_Sun_Intensity_",this.sunIntensity),this._activeEffect.setFloat("_Sun_Theta_",this.sunTheta),this._activeEffect.setFloat("_Sun_Phi_",this.sunPhi),this._activeEffect.setFloat("_Indirect_Diffuse_",this.indirectDiffuse),this._activeEffect.setDirectColor4("_Albedo_",this.albedo),this._activeEffect.setFloat("_Specular_",this.specular),this._activeEffect.setFloat("_Shininess_",this.shininess),this._activeEffect.setFloat("_Sharpness_",this.sharpness),this._activeEffect.setFloat("_Subsurface_",this.subsurface),this._activeEffect.setDirectColor4("_Left_Color_",this.leftGradientColor),this._activeEffect.setDirectColor4("_Right_Color_",this.rightGradientColor),this._activeEffect.setFloat("_Reflection_",this.reflection),this._activeEffect.setFloat("_Front_Reflect_",this.frontReflect),this._activeEffect.setFloat("_Edge_Reflect_",this.edgeReflect),this._activeEffect.setFloat("_Power_",this.power),this._activeEffect.setDirectColor4("_Sky_Color_",this.skyColor),this._activeEffect.setDirectColor4("_Horizon_Color_",this.horizonColor),this._activeEffect.setDirectColor4("_Ground_Color_",this.groundColor),this._activeEffect.setFloat("_Horizon_Power_",this.horizonPower),this._activeEffect.setTexture("_Reflection_Map_",this._reflectionMapTexture),this._activeEffect.setTexture("_Indirect_Environment_",this._indirectEnvTexture),this._activeEffect.setFloat("_Width_",this.width),this._activeEffect.setFloat("_Fuzz_",this.fuzz),this._activeEffect.setFloat("_Min_Fuzz_",this.minFuzz),this._activeEffect.setFloat("_Clip_Fade_",this.clipFade),this._activeEffect.setFloat("_Hue_Shift_",this.hueShift),this._activeEffect.setFloat("_Saturation_Shift_",this.saturationShift),this._activeEffect.setFloat("_Value_Shift_",this.valueShift),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this.blobTexture),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setVector3("_Left_Index_Pos_",this.leftIndexPosition),this._activeEffect.setVector3("_Right_Index_Pos_",this.rightIndexPosition),this._activeEffect.setVector3("_Left_Index_Middle_Pos_",this.leftIndexMiddlePosition),this._activeEffect.setVector3("_Right_Index_Middle_Pos_",this.rightIndexMiddlePosition),this._activeEffect.setTexture("_Decal_",this._decalTexture),this._activeEffect.setVector2("_Decal_Scale_XY_",this.decalScaleXY),this._activeEffect.setFloat("_Decal_Front_Only_",this.decalFrontOnly?1:0),this._activeEffect.setFloat("_Rim_Intensity_",this.rimIntensity),this._activeEffect.setTexture("_Rim_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("_Rim_Hue_Shift_",this.rimHueShift),this._activeEffect.setFloat("_Rim_Saturation_Shift_",this.rimSaturationShift),this._activeEffect.setFloat("_Rim_Value_Shift_",this.rimValueShift),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setTexture("_Iridescence_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("Use_Global_Left_Index",this.useGlobalLeftIndex),this._activeEffect.setFloat("Use_Global_Right_Index",this.useGlobalRightIndex),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this.globalLeftIndexTipPosition),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this.globaRightIndexTipPosition),this._activeEffect.setVector4("Global_Left_Thumb_Tip_Position",this.globalLeftThumbTipPosition),this._activeEffect.setVector4("Global_Right_Thumb_Tip_Position",this.globalRightThumbTipPosition),this._activeEffect.setVector4("Global_Left_Index_Middle_Position",this.globalLeftIndexMiddlePosition),this._activeEffect.setVector4("Global_Right_Index_Middle_Position",this.globalRightIndexMiddlePosition),this._activeEffect.setFloat("Global_Left_Index_Tip_Proximity",this.globalLeftIndexTipProximity),this._activeEffect.setFloat("Global_Right_Index_Tip_Proximity",this.globalRightIndexTipProximity),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._reflectionMapTexture.dispose(),this._indirectEnvTexture.dispose(),this._blueGradientTexture.dispose(),this._decalTexture.dispose()}clone(e){return it.p.Clone((()=>new BV(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLSliderThumbMaterial",e}getClassName(){return"MRDLSliderThumbMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new BV(e.name,t)),e,t,i)}}BV.BLUE_GRADIENT_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-blue-gradient.png",(0,je.Cg)([(0,$e.lK)()],BV.prototype,"radius",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"bevelFront",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"bevelFrontStretch",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"bevelBack",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"bevelBackStretch",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"radiusTopLeft",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"radiusTopRight",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"radiusBottomLeft",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"radiusBottomRight",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"bulgeEnabled",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"bulgeHeight",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"bulgeRadius",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"sunIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"sunTheta",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"sunPhi",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"indirectDiffuse",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"albedo",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"specular",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"shininess",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"sharpness",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"subsurface",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"leftGradientColor",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"rightGradientColor",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"reflection",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"frontReflect",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"edgeReflect",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"power",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"skyColor",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"horizonColor",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"groundColor",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"horizonPower",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"width",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"fuzz",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"minFuzz",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"clipFade",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"hueShift",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"saturationShift",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"valueShift",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobPosition",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobNearSize",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobFarSize",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobNearDistance",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobFarDistance",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobFadeLength",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobPulse",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobFade",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobPosition2",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobNearSize2",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobPulse2",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobFade2",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobTexture",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"leftIndexPosition",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"rightIndexPosition",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"leftIndexMiddlePosition",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"rightIndexMiddlePosition",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"decalScaleXY",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"decalFrontOnly",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"rimIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"rimHueShift",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"rimSaturationShift",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"rimValueShift",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"iridescenceIntensity",void 0),(0,X.Y5)("BABYLON.GUI.MRDLSliderThumbMaterial",BV);Cs.l.ShadersStore.mrdlBackplatePixelShader="uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vExtra1;varying vec4 vExtra2;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Filter_Width_;uniform vec4 _Base_Color_;uniform vec4 _Line_Color_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform float _Rate_;uniform vec4 _Highlight_Color_;uniform float _Highlight_Width_;uniform vec4 _Highlight_Transform_;uniform float _Highlight_;uniform float _Iridescence_Intensity_;uniform float _Iridescence_Edge_Intensity_;uniform vec4 _Iridescence_Tint_;uniform sampler2D _Iridescent_Map_;uniform float _Angle_;uniform bool _Reflected_;uniform float _Frequency_;uniform float _Vertical_Offset_;uniform vec4 _Gradient_Color_;uniform vec4 _Top_Left_;uniform vec4 _Top_Right_;uniform vec4 _Bottom_Left_;uniform vec4 _Bottom_Right_;uniform float _Edge_Width_;uniform float _Edge_Power_;uniform float _Line_Gradient_Blend_;uniform float _Fade_Out_;void FastLinearTosRGB_B353(\nvec4 Linear,\nout vec4 sRGB)\n{sRGB.rgb=sqrt(clamp(Linear.rgb,0.0,1.0));sRGB.a=Linear.a;}\nvoid Round_Rect_Fragment_B332(\nfloat Radius,\nfloat Line_Width,\nvec4 Line_Color,\nfloat Filter_Width,\nvec2 UV,\nfloat Line_Visibility,\nvec4 Rect_Parms,\nvec4 Fill_Color,\nout vec4 Color)\n{float d=length(max(abs(UV)-Rect_Parms.xy,0.0));float dx=max(fwidth(d)*Filter_Width,0.00001);float g=min(Rect_Parms.z,Rect_Parms.w);float dgrad=max(fwidth(g)*Filter_Width,0.00001);float Inside_Rect=clamp(g/dgrad,0.0,1.0);float inner=clamp((d+dx*0.5-max(Radius-Line_Width,d-dx*0.5))/dx,0.0,1.0);Color=clamp(mix(Fill_Color,Line_Color,inner),0.0,1.0)*Inside_Rect;}\nvoid Iridescence_B343(\nvec3 Position,\nvec3 Normal,\nvec2 UV,\nvec3 Axis,\nvec3 Eye,\nvec4 Tint,\nsampler2D Texture,\nbool Reflected,\nfloat Frequency,\nfloat Vertical_Offset,\nout vec4 Color)\n{vec3 i=normalize(Position-Eye);vec3 r=reflect(i,Normal);float idota=dot(i,Axis);float idotr=dot(i,r);float x=Reflected ? idotr : idota;vec2 xy;xy.x=fract((x*Frequency+1.0)*0.5+UV.y*Vertical_Offset);xy.y=0.5;Color=texture(Texture,xy);Color.rgb*=Tint.rgb;}\nvoid Scale_RGB_B346(\nvec4 Color,\nfloat Scalar,\nout vec4 Result)\n{Result=vec4(Scalar,Scalar,Scalar,1)*Color;}\nvoid Scale_RGB_B344(\nfloat Scalar,\nvec4 Color,\nout vec4 Result)\n{Result=vec4(Scalar,Scalar,Scalar,1)*Color;}\nvoid Line_Fragment_B362(\nvec4 Base_Color,\nvec4 Highlight_Color,\nfloat Highlight_Width,\nvec3 Line_Vertex,\nfloat Highlight,\nout vec4 Line_Color)\n{float k2=1.0-clamp(abs(Line_Vertex.y/Highlight_Width),0.0,1.0);Line_Color=mix(Base_Color,Highlight_Color,Highlight*k2);}\nvoid Edge_B356(\nvec4 RectParms,\nfloat Radius,\nfloat Line_Width,\nvec2 UV,\nfloat Edge_Width,\nfloat Edge_Power,\nout float Result)\n{float d=length(max(abs(UV)-RectParms.xy,0.0));float edge=1.0-clamp((1.0-d/(Radius-Line_Width))/Edge_Width,0.0,1.0);Result=pow(edge,Edge_Power);}\nvoid Gradient_B355(\nvec4 Gradient_Color,\nvec4 Top_Left,\nvec4 Top_Right,\nvec4 Bottom_Left,\nvec4 Bottom_Right,\nvec2 UV,\nout vec4 Result)\n{vec3 top=Top_Left.rgb+(Top_Right.rgb-Top_Left.rgb)*UV.x;vec3 bottom=Bottom_Left.rgb+(Bottom_Right.rgb-Bottom_Left.rgb)*UV.x;Result.rgb=Gradient_Color.rgb*(bottom+(top-bottom)*UV.y);Result.a=1.0;}\nvoid main()\n{float X_Q338;float Y_Q338;float Z_Q338;float W_Q338;X_Q338=vExtra2.x;Y_Q338=vExtra2.y;Z_Q338=vExtra2.z;W_Q338=vExtra2.w;vec4 Color_Q343;\n#if IRIDESCENCE_ENABLE\nIridescence_B343(vPosition,vNormal,vUV,vBinormal,cameraPosition,_Iridescence_Tint_,_Iridescent_Map_,_Reflected_,_Frequency_,_Vertical_Offset_,Color_Q343);\n#else\nColor_Q343=vec4(0,0,0,0);\n#endif\nvec4 Result_Q344;Scale_RGB_B344(_Iridescence_Intensity_,Color_Q343,Result_Q344);vec4 Line_Color_Q362;Line_Fragment_B362(_Line_Color_,_Highlight_Color_,_Highlight_Width_,vTangent,_Highlight_,Line_Color_Q362);float Result_Q356;\n#if EDGE_ONLY\nEdge_B356(vExtra1,Z_Q338,W_Q338,vUV,_Edge_Width_,_Edge_Power_,Result_Q356);\n#else\nResult_Q356=1.0;\n#endif\nvec2 Vec2_Q339=vec2(X_Q338,Y_Q338);vec4 Result_Q355;Gradient_B355(_Gradient_Color_,_Top_Left_,_Top_Right_,_Bottom_Left_,_Bottom_Right_,Vec2_Q339,Result_Q355);vec4 Linear_Q348;Linear_Q348.rgb=clamp(Result_Q355.rgb*Result_Q355.rgb,0.0,1.0);Linear_Q348.a=Result_Q355.a;vec4 Result_Q346;Scale_RGB_B346(Linear_Q348,Result_Q356,Result_Q346);vec4 Sum_Q345=Result_Q346+Result_Q344;vec4 Color_At_T_Q347=mix(Line_Color_Q362,Result_Q346,_Line_Gradient_Blend_);vec4 Base_And_Iridescent_Q350;Base_And_Iridescent_Q350=_Base_Color_+vec4(Sum_Q345.rgb,0.0);vec4 Sum_Q349=Color_At_T_Q347+_Iridescence_Edge_Intensity_*Color_Q343;vec4 Result_Q351=Sum_Q349; Result_Q351.a=1.0;vec4 Color_Q332;Round_Rect_Fragment_B332(Z_Q338,W_Q338,Result_Q351,_Filter_Width_,vUV,1.0,vExtra1,Base_And_Iridescent_Q350,Color_Q332);vec4 Result_Q354=_Fade_Out_*Color_Q332;vec4 sRGB_Q353;FastLinearTosRGB_B353(Result_Q354,sRGB_Q353);vec4 Out_Color=sRGB_Q353;float Clip_Threshold=0.001;bool To_sRGB=false;gl_FragColor=Out_Color;}";Cs.l.ShadersStore.mrdlBackplateVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec3 tangent;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Filter_Width_;uniform vec4 _Base_Color_;uniform vec4 _Line_Color_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform float _Rate_;uniform vec4 _Highlight_Color_;uniform float _Highlight_Width_;uniform vec4 _Highlight_Transform_;uniform float _Highlight_;uniform float _Iridescence_Intensity_;uniform float _Iridescence_Edge_Intensity_;uniform vec4 _Iridescence_Tint_;uniform sampler2D _Iridescent_Map_;uniform float _Angle_;uniform bool _Reflected_;uniform float _Frequency_;uniform float _Vertical_Offset_;uniform vec4 _Gradient_Color_;uniform vec4 _Top_Left_;uniform vec4 _Top_Right_;uniform vec4 _Bottom_Left_;uniform vec4 _Bottom_Right_;uniform float _Edge_Width_;uniform float _Edge_Power_;uniform float _Line_Gradient_Blend_;uniform float _Fade_Out_;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vExtra1;varying vec4 vExtra2;void Object_To_World_Pos_B314(\nvec3 Pos_Object,\nout vec3 Pos_World)\n{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;}\nvoid Round_Rect_Vertex_B357(\nvec2 UV,\nfloat Radius,\nfloat Margin,\nfloat Anisotropy,\nfloat Gradient1,\nfloat Gradient2,\nvec3 Normal,\nvec4 Color_Scale_Translate,\nout vec2 Rect_UV,\nout vec4 Rect_Parms,\nout vec2 Scale_XY,\nout vec2 Line_UV,\nout vec2 Color_UV_Info)\n{Scale_XY=vec2(Anisotropy,1.0);Line_UV=(UV-vec2(0.5,0.5));Rect_UV=Line_UV*Scale_XY;Rect_Parms.xy=Scale_XY*0.5-vec2(Radius,Radius)-vec2(Margin,Margin);Rect_Parms.z=Gradient1; \nRect_Parms.w=Gradient2;Color_UV_Info=(Line_UV+vec2(0.5,0.5))*Color_Scale_Translate.xy+Color_Scale_Translate.zw;}\nvoid Line_Vertex_B333(\nvec2 Scale_XY,\nvec2 UV,\nfloat Time,\nfloat Rate,\nvec4 Highlight_Transform,\nout vec3 Line_Vertex)\n{float angle2=(Rate*Time)*2.0*3.1416;float sinAngle2=sin(angle2);float cosAngle2=cos(angle2);vec2 xformUV=UV*Highlight_Transform.xy+Highlight_Transform.zw;Line_Vertex.x=0.0;Line_Vertex.y=cosAngle2*xformUV.x-sinAngle2*xformUV.y;Line_Vertex.z=0.0; }\nvoid PickDir_B334(\nfloat Degrees,\nvec3 DirX,\nvec3 DirY,\nout vec3 Dir)\n{float a=Degrees*3.14159/180.0;Dir=cos(a)*DirX+sin(a)*DirY;}\nvoid Move_Verts_B327(\nfloat Anisotropy,\nvec3 P,\nfloat Radius,\nout vec3 New_P,\nout vec2 New_UV,\nout float Radial_Gradient,\nout vec3 Radial_Dir)\n{vec2 UV=P.xy*2.0+0.5;vec2 center=clamp(UV,0.0,1.0);vec2 delta=UV-center;vec2 r2=2.0*vec2(Radius/Anisotropy,Radius);New_UV=center+r2*(UV-2.0*center+0.5);New_P=vec3(New_UV-0.5,P.z);Radial_Gradient=1.0-length(delta)*2.0;Radial_Dir=vec3(delta*r2,0.0);}\nvoid Pick_Radius_B336(\nfloat Radius,\nfloat Radius_Top_Left,\nfloat Radius_Top_Right,\nfloat Radius_Bottom_Left,\nfloat Radius_Bottom_Right,\nvec3 Position,\nout float Result)\n{bool whichY=Position.y>0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid Edge_AA_Vertex_B328(\nvec3 Position_World,\nvec3 Position_Object,\nvec3 Normal_Object,\nvec3 Eye,\nfloat Radial_Gradient,\nvec3 Radial_Dir,\nvec3 Tangent,\nout float Gradient1,\nout float Gradient2)\n{vec3 I=(Eye-Position_World);vec3 T=(vec4(Tangent,0.0)).xyz;float g=(dot(T,I)<0.0) ? 0.0 : 1.0;if (Normal_Object.z==0.0) { \nGradient1=Position_Object.z>0.0 ? g : 1.0;Gradient2=Position_Object.z>0.0 ? 1.0 : g;} else {Gradient1=g+(1.0-g)*(Radial_Gradient);Gradient2=1.0;}}\nvoid Object_To_World_Dir_B330(\nvec3 Dir_Object,\nout vec3 Binormal_World,\nout vec3 Binormal_World_N,\nout float Binormal_Length)\n{Binormal_World=(world*vec4(Dir_Object,0.0)).xyz;Binormal_Length=length(Binormal_World);Binormal_World_N=Binormal_World/Binormal_Length;}\nvoid RelativeOrAbsoluteDetail_B341(\nfloat Nominal_Radius,\nfloat Nominal_LineWidth,\nbool Absolute_Measurements,\nfloat Height,\nout float Radius,\nout float Line_Width)\n{float scale=Absolute_Measurements ? 1.0/Height : 1.0;Radius=Nominal_Radius*scale;Line_Width=Nominal_LineWidth*scale;}\nvoid main()\n{vec3 Nrm_World_Q326;Nrm_World_Q326=normalize((world*vec4(normal,0.0)).xyz);vec3 Tangent_World_Q329;vec3 Tangent_World_N_Q329;float Tangent_Length_Q329;Tangent_World_Q329=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q329=length(Tangent_World_Q329);Tangent_World_N_Q329=Tangent_World_Q329/Tangent_Length_Q329;vec3 Binormal_World_Q330;vec3 Binormal_World_N_Q330;float Binormal_Length_Q330;Object_To_World_Dir_B330(vec3(0,1,0),Binormal_World_Q330,Binormal_World_N_Q330,Binormal_Length_Q330);float Radius_Q341;float Line_Width_Q341;RelativeOrAbsoluteDetail_B341(_Radius_,_Line_Width_,_Absolute_Sizes_,Binormal_Length_Q330,Radius_Q341,Line_Width_Q341);vec3 Dir_Q334;PickDir_B334(_Angle_,Tangent_World_N_Q329,Binormal_World_N_Q330,Dir_Q334);float Result_Q336;Pick_Radius_B336(Radius_Q341,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q336);float Anisotropy_Q331=Tangent_Length_Q329/Binormal_Length_Q330;vec4 Out_Color_Q337=vec4(Result_Q336,Line_Width_Q341,0,1);vec3 New_P_Q327;vec2 New_UV_Q327;float Radial_Gradient_Q327;vec3 Radial_Dir_Q327;Move_Verts_B327(Anisotropy_Q331,position,Result_Q336,New_P_Q327,New_UV_Q327,Radial_Gradient_Q327,Radial_Dir_Q327);vec3 Pos_World_Q314;Object_To_World_Pos_B314(New_P_Q327,Pos_World_Q314);float Gradient1_Q328;float Gradient2_Q328;\n#if SMOOTH_EDGES\nEdge_AA_Vertex_B328(Pos_World_Q314,position,normal,cameraPosition,Radial_Gradient_Q327,Radial_Dir_Q327,tangent,Gradient1_Q328,Gradient2_Q328);\n#else\nGradient1_Q328=1.0;Gradient2_Q328=1.0;\n#endif\nvec2 Rect_UV_Q357;vec4 Rect_Parms_Q357;vec2 Scale_XY_Q357;vec2 Line_UV_Q357;vec2 Color_UV_Info_Q357;Round_Rect_Vertex_B357(New_UV_Q327,Result_Q336,0.0,Anisotropy_Q331,Gradient1_Q328,Gradient2_Q328,normal,vec4(1,1,0,0),Rect_UV_Q357,Rect_Parms_Q357,Scale_XY_Q357,Line_UV_Q357,Color_UV_Info_Q357);vec3 Line_Vertex_Q333;Line_Vertex_B333(Scale_XY_Q357,Line_UV_Q357,(20.0),_Rate_,_Highlight_Transform_,Line_Vertex_Q333);float X_Q359;float Y_Q359;X_Q359=Color_UV_Info_Q357.x;Y_Q359=Color_UV_Info_Q357.y;vec4 Vec4_Q358=vec4(X_Q359,Y_Q359,Result_Q336,Line_Width_Q341);vec3 Position=Pos_World_Q314;vec3 Normal=Nrm_World_Q326;vec2 UV=Rect_UV_Q357;vec3 Tangent=Line_Vertex_Q333;vec3 Binormal=Dir_Q334;vec4 Color=Out_Color_Q337;vec4 Extra1=Rect_Parms_Q357;vec4 Extra2=Vec4_Q358;vec4 Extra3=vec4(0,0,0,0);gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vExtra1=Extra1;vExtra2=Extra2;}";class VV extends xn{constructor(){super(),this.IRIDESCENCE_ENABLE=!0,this.SMOOTH_EDGES=!0,this._needNormals=!0,this.rebuild()}}class kV extends bn{constructor(e,t){super(e,t),this.radius=.3,this.lineWidth=.003,this.absoluteSizes=!1,this._filterWidth=1,this.baseColor=new H.ov(0,0,0,1),this.lineColor=new H.ov(.2,.262745,.4,1),this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this._rate=0,this.highlightColor=new H.ov(.239216,.435294,.827451,1),this.highlightWidth=0,this._highlightTransform=new W.IU(1,1,0,0),this._highlight=1,this.iridescenceIntensity=.45,this.iridescenceEdgeIntensity=1,this.iridescenceTint=new H.ov(1,1,1,1),this._angle=-45,this.fadeOut=1,this._reflected=!0,this._frequency=1,this._verticalOffset=0,this.gradientColor=new H.ov(.74902,.74902,.74902,1),this.topLeftGradientColor=new H.ov(.00784314,.294118,.580392,1),this.topRightGradientColor=new H.ov(.305882,0,1,1),this.bottomLeftGradientColor=new H.ov(.133333,.258824,.992157,1),this.bottomRightGradientColor=new H.ov(.176471,.176471,.619608,1),this.edgeWidth=.5,this.edgePower=1,this.edgeLineGradientBlend=.5,this.alphaMode=Il.ALPHA_DISABLE,this.backFaceCulling=!1,this._iridescentMapTexture=new vi.g(kV.IRIDESCENT_MAP_TEXTURE_URL,this.getScene(),!0,!1,vi.g.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new VV);const r=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if((0,Bt.qB)(e,r,!1,!1),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=new Tn;r.FOG&&e.addFallback(1,"FOG"),(0,Bt.c4)(r,e),r.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const i=[st.R.PositionKind];r.NORMAL&&i.push(st.R.NormalKind),r.UV1&&i.push(st.R.UVKind),r.UV2&&i.push(st.R.UV2Kind),r.VERTEXCOLOR&&i.push(st.R.ColorKind),r.TANGENT&&i.push(st.R.TangentKind),(0,Bt.ER)(i,r);const o="mrdlBackplate",a=r.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Absolute_Sizes_","_Filter_Width_","_Base_Color_","_Line_Color_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Rate_","_Highlight_Color_","_Highlight_Width_","_Highlight_Transform_","_Highlight_","_Iridescence_Intensity_","_Iridescence_Edge_Intensity_","_Iridescence_Tint_","_Iridescent_Map_","_Angle_","_Reflected_","_Frequency_","_Vertical_Offset_","_Gradient_Color_","_Top_Left_","_Top_Right_","_Bottom_Left_","_Bottom_Right_","_Edge_Width_","_Edge_Power_","_Line_Gradient_Blend_","_Fade_Out_"],h=["_Iridescent_Map_"],c=[];(0,Bt.Bb)({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:r,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),r)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Base_Color_",this.baseColor),this._activeEffect.setDirectColor4("_Line_Color_",this.lineColor),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Rate_",this._rate),this._activeEffect.setDirectColor4("_Highlight_Color_",this.highlightColor),this._activeEffect.setFloat("_Highlight_Width_",this.highlightWidth),this._activeEffect.setVector4("_Highlight_Transform_",this._highlightTransform),this._activeEffect.setFloat("_Highlight_",this._highlight),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setFloat("_Iridescence_Edge_Intensity_",this.iridescenceEdgeIntensity),this._activeEffect.setDirectColor4("_Iridescence_Tint_",this.iridescenceTint),this._activeEffect.setTexture("_Iridescent_Map_",this._iridescentMapTexture),this._activeEffect.setFloat("_Angle_",this._angle),this._activeEffect.setFloat("_Reflected_",this._reflected?1:0),this._activeEffect.setFloat("_Frequency_",this._frequency),this._activeEffect.setFloat("_Vertical_Offset_",this._verticalOffset),this._activeEffect.setDirectColor4("_Gradient_Color_",this.gradientColor),this._activeEffect.setDirectColor4("_Top_Left_",this.topLeftGradientColor),this._activeEffect.setDirectColor4("_Top_Right_",this.topRightGradientColor),this._activeEffect.setDirectColor4("_Bottom_Left_",this.bottomLeftGradientColor),this._activeEffect.setDirectColor4("_Bottom_Right_",this.bottomRightGradientColor),this._activeEffect.setFloat("_Edge_Width_",this.edgeWidth),this._activeEffect.setFloat("_Edge_Power_",this.edgePower),this._activeEffect.setFloat("_Line_Gradient_Blend_",this.edgeLineGradientBlend),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return it.p.Clone((()=>new kV(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLBackplateMaterial",e}getClassName(){return"MRDLBackplateMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new kV(e.name,t)),e,t,i)}}kV.IRIDESCENT_MAP_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-backplate-iridescence.png",(0,je.Cg)([(0,$e.lK)()],kV.prototype,"radius",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"lineWidth",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"absoluteSizes",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"baseColor",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"lineColor",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"radiusTopLeft",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"radiusTopRight",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"radiusBottomLeft",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"radiusBottomRight",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"highlightColor",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"highlightWidth",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"iridescenceIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"iridescenceEdgeIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"iridescenceTint",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"fadeOut",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"gradientColor",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"topLeftGradientColor",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"topRightGradientColor",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"bottomLeftGradientColor",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"bottomRightGradientColor",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"edgeWidth",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"edgePower",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"edgeLineGradientBlend",void 0),(0,X.Y5)("BABYLON.GUI.MRDLBackplateMaterial",kV);class UV extends rV{constructor(e,t){super(e),this.onValueChangedObservable=new z.cP,this._sliderBackplateVisible=t||!1,this._minimum=0,this._maximum=100,this._step=0,this._value=50}get mesh(){return this.node?this._sliderThumb:null}get minimum(){return this._minimum}set minimum(e){this._minimum!==e&&(this._minimum=Math.max(e,0),this._value=Math.max(Math.min(this._value,this._maximum),this._minimum))}get maximum(){return this._maximum}set maximum(e){this._maximum!==e&&(this._maximum=Math.max(e,this._minimum),this._value=Math.max(Math.min(this._value,this._maximum),this._minimum))}get step(){return this._step}set step(e){this._step!==e&&(this._step=Math.max(Math.min(e,this._maximum-this._minimum),0))}get value(){return this._value}set value(e){this._value!==e&&(this._value=Math.max(Math.min(e,this._maximum),this._minimum),this._sliderThumb&&(this._sliderThumb.position.x=this._convertToPosition(this.value)),this.onValueChangedObservable.notifyObservers(this._value))}get start(){return this.node?this._sliderBar.position.x-this._sliderBar.scaling.x/2:-.5}get end(){return this.node?this._sliderBar.position.x+this._sliderBar.scaling.x/2:.5}get sliderBarMaterial(){return this._sliderBarMaterial}get sliderThumbMaterial(){return this._sliderThumbMaterial}get sliderBackplateMaterial(){return this._sliderBackplateMaterial}get sliderBar(){return this._sliderBar}get sliderThumb(){return this._sliderThumb}get sliderBackplate(){return this._sliderBackplate}set isVisible(e){this._isVisible!==e&&(this._isVisible=e,this.node?.setEnabled(e))}_createNode(e){const t=Ko(`${this.name}_sliderbackplate`,{width:1,height:1,depth:1},e);return t.isPickable=!1,t.visibility=0,t.scaling=new W.Pq(1,.5,.8),xg.ImportMeshAsync(void 0,UV.MODEL_BASE_URL,UV.MODEL_FILENAME,e).then((e=>{e.meshes.forEach((e=>{e.isPickable=!1}));const i=e.meshes[1],r=e.meshes[1].clone(`${this.name}_sliderbar`,t),s=e.meshes[1].clone(`${this.name}_sliderthumb`,t);i.visibility=0,this._sliderBackplateVisible&&(i.visibility=1,i.name=`${this.name}_sliderbackplate`,i.scaling.x=1,i.scaling.z=.2,i.parent=t,this._sliderBackplateMaterial&&(i.material=this._sliderBackplateMaterial),this._sliderBackplate=i),r&&(r.parent=t,r.position.z=-.1,r.scaling=new W.Pq(.8,.04,.3),this._sliderBarMaterial&&(r.material=this._sliderBarMaterial),this._sliderBar=r),s&&(s.parent=t,s.isPickable=!0,s.position.z=-.115,s.scaling=new W.Pq(.025,.3,.6),s.position.x=this._convertToPosition(this.value),s.addBehavior(this._createBehavior()),this._sliderThumbMaterial&&(s.material=this._sliderThumbMaterial),this._sliderThumb=s),this._injectGUI3DReservedDataStore(t).control=this,t.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this}))})),this._affectMaterial(t),t}_affectMaterial(e){this._sliderBackplateMaterial=this._sliderBackplateMaterial??new kV(`${this.name}_sliderbackplate_material`,e.getScene()),this._sliderBarMaterial=this._sliderBarMaterial??new FV(`${this.name}_sliderbar_material`,e.getScene()),this._sliderThumbMaterial=this._sliderThumbMaterial??new BV(`${this.name}_sliderthumb_material`,e.getScene())}_createBehavior(){const e=new Ji({dragAxis:W.Pq.Right()});return e.moveAttached=!1,e.onDragStartObservable.add((()=>{this._draggedPosition=this._sliderThumb.position.x})),e.onDragObservable.add((e=>{this._draggedPosition+=e.dragDistance/this.scaling.x,this.value=this._convertToValue(this._draggedPosition)})),e}_convertToPosition(e){const t=(e-this.minimum)/(this.maximum-this.minimum)*(this.end-this.start)+this.start;return Math.min(Math.max(t,this.start),this.end)}_convertToValue(e){let t=(e-this.start)/(this.end-this.start)*(this.maximum-this.minimum);return t=this.step?Math.round(t/this.step)*this.step:t,Math.max(Math.min(this.minimum+t,this._maximum),this._minimum)}dispose(){super.dispose(),this._sliderBar?.dispose(),this._sliderThumb?.dispose(),this._sliderBarMaterial?.dispose(),this._sliderThumbMaterial?.dispose(),this._sliderBackplate?.dispose(),this._sliderBackplateMaterial?.dispose()}}UV.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",UV.MODEL_FILENAME="mrtk-fluent-backplate.glb";class GV extends lV{constructor(){super(...arguments),this._radius=5}get radius(){return this._radius}set radius(e){this._radius!==e&&(this._radius=e,Ue.S0.SetImmediate((()=>{this._arrangeChildren()})))}_mapGridNode(e,t){const i=e.mesh;if(!i)return;const r=this._sphericalMapping(t);switch(e.position=r,this.orientation){case aV.FACEORIGIN_ORIENTATION:i.lookAt(new W.Pq(2*r.x,2*r.y,2*r.z));break;case aV.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new W.Pq(-r.x,-r.y,-r.z));break;case aV.FACEFORWARD_ORIENTATION:break;case aV.FACEFORWARDREVERSED_ORIENTATION:i.rotate(Mt._0.Y,Math.PI,0)}}_sphericalMapping(e){const t=new W.Pq(0,0,this._radius),i=e.y/this._radius,r=-e.x/this._radius;return W.uq.RotationYawPitchRollToRef(r,i,0,W.AA.Matrix[0]),W.Pq.TransformNormal(t,W.AA.Matrix[0])}}class zV extends aV{get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,Ue.S0.SetImmediate((()=>{this._arrangeChildren()})))}constructor(e=!1){super(),this._isVertical=!1,this.margin=.1,this._isVertical=e}_arrangeChildren(){let e=0,t=0,i=0;const r=[],s=W.uq.Invert(this.node.computeWorldMatrix(!0));for(const n of this._children){if(!n.mesh)continue;i++,n.mesh.computeWorldMatrix(!0),n.mesh.getWorldMatrix().multiplyToRef(s,W.AA.Matrix[0]);const o=n.mesh.getBoundingInfo().boundingBox,a=W.Pq.TransformNormal(o.extendSize,W.AA.Matrix[0]);r.push(a),this._isVertical?t+=a.y:e+=a.x}let n;this._isVertical?t+=(i-1)*this.margin/2:e+=(i-1)*this.margin/2,n=this._isVertical?-t:-e;let o=0;for(const e of this._children){if(!e.mesh)continue;i--;const t=r[o++];this._isVertical?(e.position.y=n+t.y,e.position.x=0,n+=2*t.y):(e.position.x=n+t.x,e.position.y=0,n+=2*t.x),n+=i>0?this.margin:0}}}class WV extends bV{constructor(e,t){super(t,e),this._currentMesh=e,this.pointerEnterAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1.1)},this.pointerOutAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/1.1)},this.pointerDownAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/.95)}}_getTypeName(){return"TouchMeshButton3D"}_createNode(){return this._currentMesh.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this})),this._currentMesh}_affectMaterial(e){}}Cs.l.ShadersStore.mrdlBackglowPixelShader="uniform vec3 cameraPosition;varying vec3 vNormal;varying vec2 vUV;uniform float _Bevel_Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Tuning_Motion_;uniform float _Motion_;uniform float _Max_Intensity_;uniform float _Intensity_Fade_In_Exponent_;uniform float _Outer_Fuzz_Start_;uniform float _Outer_Fuzz_End_;uniform vec4 _Color_;uniform vec4 _Inner_Color_;uniform float _Blend_Exponent_;uniform float _Falloff_;uniform float _Bias_;float BiasFunc(float b,float v) {return pow(v,log(clamp(b,0.001,0.999))/log(0.5));}\nvoid Fuzzy_Round_Rect_B33(\nfloat Size_X,\nfloat Size_Y,\nfloat Radius_X,\nfloat Radius_Y,\nfloat Line_Width,\nvec2 UV,\nfloat Outer_Fuzz,\nfloat Max_Outer_Fuzz,\nout float Rect_Distance,\nout float Inner_Distance)\n{vec2 halfSize=vec2(Size_X,Size_Y)*0.5;vec2 r=max(min(vec2(Radius_X,Radius_Y),halfSize),vec2(0.001,0.001));float radius=min(r.x,r.y)-Max_Outer_Fuzz;vec2 v=abs(UV);vec2 nearestp=min(v,halfSize-r);float d=distance(nearestp,v);Inner_Distance=clamp(1.0-(radius-d)/Line_Width,0.0,1.0);Rect_Distance=clamp(1.0-(d-radius)/Outer_Fuzz,0.0,1.0)*Inner_Distance;}\nvoid main()\n{float X_Q42;float Y_Q42;X_Q42=vNormal.x;Y_Q42=vNormal.y;float MaxAB_Q24=max(_Tuning_Motion_,_Motion_);float Sqrt_F_Q27=sqrt(MaxAB_Q24);float Power_Q43=pow(MaxAB_Q24,_Intensity_Fade_In_Exponent_);float Value_At_T_Q26=mix(_Outer_Fuzz_Start_,_Outer_Fuzz_End_,Sqrt_F_Q27);float Product_Q23=_Max_Intensity_*Power_Q43;float Rect_Distance_Q33;float Inner_Distance_Q33;Fuzzy_Round_Rect_B33(X_Q42,Y_Q42,_Bevel_Radius_,_Bevel_Radius_,_Line_Width_,vUV,Value_At_T_Q26,_Outer_Fuzz_Start_,Rect_Distance_Q33,Inner_Distance_Q33);float Power_Q44=pow(Inner_Distance_Q33,_Blend_Exponent_);float Result_Q45=pow(BiasFunc(_Bias_,Rect_Distance_Q33),_Falloff_);vec4 Color_At_T_Q25=mix(_Inner_Color_,_Color_,Power_Q44);float Product_Q22=Result_Q45*Product_Q23;vec4 Result_Q28=Product_Q22*Color_At_T_Q25;vec4 Out_Color=Result_Q28;float Clip_Threshold=0.0;gl_FragColor=Out_Color;}";Cs.l.ShadersStore.mrdlBackglowVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;uniform float _Bevel_Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Tuning_Motion_;uniform float _Motion_;uniform float _Max_Intensity_;uniform float _Intensity_Fade_In_Exponent_;uniform float _Outer_Fuzz_Start_;uniform float _Outer_Fuzz_End_;uniform vec4 _Color_;uniform vec4 _Inner_Color_;uniform float _Blend_Exponent_;uniform float _Falloff_;uniform float _Bias_;varying vec3 vNormal;varying vec2 vUV;void main()\n{vec3 Dir_World_Q41=(world*vec4(tangent,0.0)).xyz;vec3 Dir_World_Q40=(world*vec4((cross(normal,tangent)),0.0)).xyz;float MaxAB_Q24=max(_Tuning_Motion_,_Motion_);float Length_Q16=length(Dir_World_Q41);float Length_Q17=length(Dir_World_Q40);bool Greater_Than_Q37=MaxAB_Q24>0.0;vec3 Sizes_Q35;vec2 XY_Q35;Sizes_Q35=(_Absolute_Sizes_ ? vec3(Length_Q16,Length_Q17,0) : vec3(Length_Q16/Length_Q17,1,0));XY_Q35=(uv-vec2(0.5,0.5))*Sizes_Q35.xy;vec3 Result_Q38=Greater_Than_Q37 ? position : vec3(0,0,0);vec3 Pos_World_Q39=(world*vec4(Result_Q38,1.0)).xyz;vec3 Position=Pos_World_Q39;vec3 Normal=Sizes_Q35;vec2 UV=XY_Q35;vec3 Tangent=vec3(0,0,0);vec3 Binormal=vec3(0,0,0);vec4 Color=vec4(1,1,1,1);gl_Position=viewProjection*vec4(Position,1);vNormal=Normal;vUV=UV;}";class HV extends xn{constructor(){super(),this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class XV extends bn{constructor(e,t){super(e,t),this.bevelRadius=.16,this.lineWidth=.16,this.absoluteSizes=!1,this.tuningMotion=0,this.motion=1,this.maxIntensity=.7,this.intensityFadeInExponent=2,this.outerFuzzStart=.04,this.outerFuzzEnd=.04,this.color=new H.ov(.682353,.698039,1,1),this.innerColor=new H.ov(.356863,.392157,.796078,1),this.blendExponent=1.5,this.falloff=2,this.bias=.5,this.alphaMode=Il.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new HV);const r=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if((0,Bt.qB)(e,r,!1,!1),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=new Tn;r.FOG&&e.addFallback(1,"FOG"),(0,Bt.c4)(r,e),r.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const i=[st.R.PositionKind];r.NORMAL&&i.push(st.R.NormalKind),r.UV1&&i.push(st.R.UVKind),r.UV2&&i.push(st.R.UV2Kind),r.VERTEXCOLOR&&i.push(st.R.ColorKind),r.TANGENT&&i.push(st.R.TangentKind),(0,Bt.ER)(i,r);const o="mrdlBackglow",a=r.toString(),l=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Bevel_Radius_","_Line_Width_","_Absolute_Sizes_","_Tuning_Motion_","_Motion_","_Max_Intensity_","_Intensity_Fade_In_Exponent_","_Outer_Fuzz_Start_","_Outer_Fuzz_End_","_Color_","_Inner_Color_","_Blend_Exponent_","_Falloff_","_Bias_"],h=[],c=[];(0,Bt.Bb)({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:r,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),r)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const r=this.getScene();if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",r.activeCamera.position),this._activeEffect.setFloat("_Bevel_Radius_",this.bevelRadius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Tuning_Motion_",this.tuningMotion),this._activeEffect.setFloat("_Motion_",this.motion),this._activeEffect.setFloat("_Max_Intensity_",this.maxIntensity),this._activeEffect.setFloat("_Intensity_Fade_In_Exponent_",this.intensityFadeInExponent),this._activeEffect.setFloat("_Outer_Fuzz_Start_",this.outerFuzzStart),this._activeEffect.setFloat("_Outer_Fuzz_End_",this.outerFuzzEnd),this._activeEffect.setDirectColor4("_Color_",this.color),this._activeEffect.setDirectColor4("_Inner_Color_",this.innerColor),this._activeEffect.setFloat("_Blend_Exponent_",this.blendExponent),this._activeEffect.setFloat("_Falloff_",this.falloff),this._activeEffect.setFloat("_Bias_",this.bias),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return it.p.Clone((()=>new XV(e,this.getScene())),this)}serialize(){const e=it.p.Serialize(this);return e.customType="BABYLON.MRDLBackglowMaterial",e}getClassName(){return"MRDLBackglowMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new XV(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.lK)()],XV.prototype,"bevelRadius",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"lineWidth",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"absoluteSizes",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"tuningMotion",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"motion",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"maxIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"intensityFadeInExponent",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"outerFuzzStart",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"outerFuzzEnd",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"color",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"innerColor",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"blendExponent",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"falloff",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"bias",void 0),(0,X.Y5)("BABYLON.GUI.MRDLBackglowMaterial",XV);Cs.l.ShadersStore.mrdlFrontplatePixelShader="uniform vec3 cameraPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Relative_To_Height_;uniform float _Filter_Width_;uniform vec4 _Edge_Color_;uniform float _Fade_Out_;uniform bool _Smooth_Edges_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform float _Blob_Pulse_Max_Size_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform float _Gaze_Intensity_;uniform float _Gaze_Focus_;uniform sampler2D _Blob_Texture_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform bool _Use_Global_Left_Index_;uniform bool _Use_Global_Right_Index_;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;void Scale_Color_B54(\nvec4 Color,\nfloat Scalar,\nout vec4 Result)\n{Result=Scalar*Color;}\nvoid Scale_RGB_B50(\nvec4 Color,\nfloat Scalar,\nout vec4 Result)\n{Result=vec4(Scalar,Scalar,Scalar,1)*Color;}\nvoid Proximity_Fragment_B51(\nfloat Proximity_Max_Intensity,\nfloat Proximity_Near_Radius,\nvec4 Deltas,\nfloat Show_Selection,\nfloat Distance_Fade1,\nfloat Distance_Fade2,\nfloat Strength,\nout float Proximity)\n{float proximity1=(1.0-clamp(length(Deltas.xy)/Proximity_Near_Radius,0.0,1.0))*Distance_Fade1;float proximity2=(1.0-clamp(length(Deltas.zw)/Proximity_Near_Radius,0.0,1.0))*Distance_Fade2;Proximity=Strength*(Proximity_Max_Intensity*max(proximity1,proximity2) *(1.0-Show_Selection)+Show_Selection);}\nvoid Blob_Fragment_B56(\nvec2 UV,\nvec3 Blob_Info,\nsampler2D Blob_Texture,\nout vec4 Blob_Color)\n{float k=dot(UV,UV);Blob_Color=Blob_Info.y*texture(Blob_Texture,vec2(vec2(sqrt(k),Blob_Info.x).x,1.0-vec2(sqrt(k),Blob_Info.x).y))*(1.0-clamp(k,0.0,1.0));}\nvoid Round_Rect_Fragment_B61(\nfloat Radius,\nvec4 Line_Color,\nfloat Filter_Width,\nfloat Line_Visibility,\nvec4 Fill_Color,\nbool Smooth_Edges,\nvec4 Rect_Parms,\nout float Inside_Rect)\n{float d=length(max(abs(Rect_Parms.zw)-Rect_Parms.xy,0.0));float dx=max(fwidth(d)*Filter_Width,0.00001);Inside_Rect=Smooth_Edges ? clamp((Radius-d)/dx,0.0,1.0) : 1.0-step(Radius,d);}\nvoid main()\n{float Is_Quad_Q53;Is_Quad_Q53=vNormal.z;vec4 Blob_Color_Q56;Blob_Fragment_B56(vUV,vTangent,_Blob_Texture_,Blob_Color_Q56);float X_Q52;float Y_Q52;float Z_Q52;float W_Q52;X_Q52=vExtra3.x;Y_Q52=vExtra3.y;Z_Q52=vExtra3.z;W_Q52=vExtra3.w;float Proximity_Q51;Proximity_Fragment_B51(_Proximity_Max_Intensity_,_Proximity_Near_Radius_,vExtra2,X_Q52,Y_Q52,Z_Q52,1.0,Proximity_Q51);float Inside_Rect_Q61;Round_Rect_Fragment_B61(W_Q52,vec4(1,1,1,1),_Filter_Width_,1.0,vec4(0,0,0,0),_Smooth_Edges_,vExtra1,Inside_Rect_Q61);vec4 Result_Q50;Scale_RGB_B50(_Edge_Color_,Proximity_Q51,Result_Q50);vec4 Result_Q47=Inside_Rect_Q61*Blob_Color_Q56;vec4 Color_At_T_Q48=mix(Result_Q50,Result_Q47,Is_Quad_Q53);vec4 Result_Q54;Scale_Color_B54(Color_At_T_Q48,_Fade_Out_,Result_Q54);vec4 Out_Color=Result_Q54;float Clip_Threshold=0.001;bool To_sRGB=false;gl_FragColor=Out_Color;}";Cs.l.ShadersStore.mrdlFrontplateVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Relative_To_Height_;uniform float _Filter_Width_;uniform vec4 _Edge_Color_;uniform float _Fade_Out_;uniform bool _Smooth_Edges_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform float _Blob_Pulse_Max_Size_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform float _Gaze_Intensity_;uniform float _Gaze_Focus_;uniform sampler2D _Blob_Texture_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform bool _Use_Global_Left_Index_;uniform bool _Use_Global_Right_Index_;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;void Blob_Vertex_B40(\nvec3 Position,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nvec3 Blob_Position,\nfloat Intensity,\nfloat Blob_Near_Size,\nfloat Blob_Far_Size,\nfloat Blob_Near_Distance,\nfloat Blob_Far_Distance,\nvec4 Vx_Color,\nvec2 UV,\nvec3 Face_Center,\nvec2 Face_Size,\nvec2 In_UV,\nfloat Blob_Fade_Length,\nfloat Selection_Fade,\nfloat Selection_Fade_Size,\nfloat Inner_Fade,\nfloat Blob_Pulse,\nfloat Blob_Fade,\nfloat Blob_Enabled,\nfloat DistanceOffset,\nout vec3 Out_Position,\nout vec2 Out_UV,\nout vec3 Blob_Info,\nout vec2 Blob_Relative_UV)\n{float blobSize,fadeIn;vec3 Hit_Position;Blob_Info=vec3(0.0,0.0,0.0);float Hit_Distance=dot(Blob_Position-Face_Center,Normal)+DistanceOffset*Blob_Far_Distance;Hit_Position=Blob_Position-Hit_Distance*Normal;float absD=abs(Hit_Distance);float lerpVal=clamp((absD-Blob_Near_Distance)/(Blob_Far_Distance-Blob_Near_Distance),0.0,1.0);fadeIn=1.0-clamp((absD-Blob_Far_Distance)/Blob_Fade_Length,0.0,1.0);float innerFade=1.0-clamp(-Hit_Distance/Inner_Fade,0.0,1.0);float farClip=clamp(1.0-step(Blob_Far_Distance+Blob_Fade_Length,absD),0.0,1.0);float size=mix(Blob_Near_Size,Blob_Far_Size,lerpVal)*farClip;blobSize=mix(size,Selection_Fade_Size,Selection_Fade)*innerFade*Blob_Enabled;Blob_Info.x=lerpVal*0.5+0.5;Blob_Info.y=fadeIn*Intensity*(1.0-Selection_Fade)*Blob_Fade;Blob_Info.x*=(1.0-Blob_Pulse);vec3 delta=Hit_Position-Face_Center;vec2 blobCenterXY=vec2(dot(delta,Tangent),dot(delta,Bitangent));vec2 quadUVin=2.0*UV-1.0; \nvec2 blobXY=blobCenterXY+quadUVin*blobSize;vec2 blobClipped=clamp(blobXY,-Face_Size*0.5,Face_Size*0.5);vec2 blobUV=(blobClipped-blobCenterXY)/max(blobSize,0.0001)*2.0;vec3 blobCorner=Face_Center+blobClipped.x*Tangent+blobClipped.y*Bitangent;Out_Position=mix(Position,blobCorner,Vx_Color.rrr);Out_UV=mix(In_UV,blobUV,Vx_Color.rr);Blob_Relative_UV=blobClipped/Face_Size.y;}\nvoid Round_Rect_Vertex_B36(\nvec2 UV,\nvec3 Tangent,\nvec3 Binormal,\nfloat Radius,\nfloat Anisotropy,\nvec2 Blob_Center_UV,\nout vec2 Rect_UV,\nout vec2 Scale_XY,\nout vec4 Rect_Parms)\n{Scale_XY=vec2(Anisotropy,1.0);Rect_UV=(UV-vec2(0.5,0.5))*Scale_XY;Rect_Parms.xy=Scale_XY*0.5-vec2(Radius,Radius);Rect_Parms.zw=Blob_Center_UV;}\nvec2 ProjectProximity(\nvec3 blobPosition,\nvec3 position,\nvec3 center,\nvec3 dir,\nvec3 xdir,\nvec3 ydir,\nout float vdistance\n)\n{vec3 delta=blobPosition-position;vec2 xy=vec2(dot(delta,xdir),dot(delta,ydir));vdistance=abs(dot(delta,dir));return xy;}\nvoid Proximity_Vertex_B33(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Face_Center,\nvec3 Position,\nfloat Proximity_Far_Distance,\nfloat Relative_Scale,\nfloat Proximity_Anisotropy,\nvec3 Normal,\nvec3 Tangent,\nvec3 Binormal,\nout vec4 Extra,\nout float Distance_To_Face,\nout float Distance_Fade1,\nout float Distance_Fade2)\n{float distz1,distz2;Extra.xy=ProjectProximity(Blob_Position,Position,Face_Center,Normal,Tangent*Proximity_Anisotropy,Binormal,distz1)/Relative_Scale;Extra.zw=ProjectProximity(Blob_Position_2,Position,Face_Center,Normal,Tangent*Proximity_Anisotropy,Binormal,distz2)/Relative_Scale;Distance_To_Face=dot(Normal,Position-Face_Center);Distance_Fade1=1.0-clamp(distz1/Proximity_Far_Distance,0.0,1.0);Distance_Fade2=1.0-clamp(distz2/Proximity_Far_Distance,0.0,1.0);}\nvoid Object_To_World_Pos_B12(\nvec3 Pos_Object,\nout vec3 Pos_World)\n{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;}\nvoid Choose_Blob_B27(\nvec4 Vx_Color,\nvec3 Position1,\nvec3 Position2,\nbool Blob_Enable_1,\nbool Blob_Enable_2,\nfloat Near_Size_1,\nfloat Near_Size_2,\nfloat Blob_Inner_Fade_1,\nfloat Blob_Inner_Fade_2,\nfloat Blob_Pulse_1,\nfloat Blob_Pulse_2,\nfloat Blob_Fade_1,\nfloat Blob_Fade_2,\nout vec3 Position,\nout float Near_Size,\nout float Inner_Fade,\nout float Blob_Enable,\nout float Fade,\nout float Pulse)\n{Position=Position1*(1.0-Vx_Color.g)+Vx_Color.g*Position2;float b1=Blob_Enable_1 ? 1.0 : 0.0;float b2=Blob_Enable_2 ? 1.0 : 0.0;Blob_Enable=b1+(b2-b1)*Vx_Color.g;Pulse=Blob_Pulse_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Pulse_2;Fade=Blob_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Fade_2;Near_Size=Near_Size_1*(1.0-Vx_Color.g)+Vx_Color.g*Near_Size_2;Inner_Fade=Blob_Inner_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Inner_Fade_2;}\nvoid Move_Verts_B32(\nvec2 UV,\nfloat Radius,\nfloat Anisotropy,\nfloat Line_Width,\nfloat Visible,\nout vec3 New_P,\nout vec2 New_UV)\n{vec2 xy=2.0*UV-vec2(0.5,0.5);vec2 center=clamp(xy,0.0,1.0);vec2 delta=2.0*(xy-center);float deltaLength=length(delta);vec2 aniso=vec2(1.0/Anisotropy,1.0);center=(center-vec2(0.5,0.5))*(1.0-2.0*Radius*aniso);New_UV=vec2((2.0-2.0*deltaLength)*Visible,0.0);float deltaRadius= (Radius-Line_Width*New_UV.x);New_P.xy=(center+deltaRadius/deltaLength *aniso*delta);New_P.z=0.0;}\nvoid Object_To_World_Dir_B14(\nvec3 Dir_Object,\nout vec3 Binormal_World)\n{Binormal_World=(world*vec4(Dir_Object,0.0)).xyz;}\nvoid Proximity_Visibility_B55(\nfloat Selection,\nvec3 Proximity_Center,\nvec3 Proximity_Center_2,\nfloat Proximity_Far_Distance,\nfloat Proximity_Radius,\nvec3 Face_Center,\nvec3 Normal,\nvec2 Face_Size,\nfloat Gaze,\nout float Width)\n{float boxMaxSize=length(Face_Size)*0.5;float d1=dot(Proximity_Center-Face_Center,Normal);vec3 blob1=Proximity_Center-d1*Normal;float d2=dot(Proximity_Center_2-Face_Center,Normal);vec3 blob2=Proximity_Center_2-d2*Normal;vec3 delta1=blob1-Face_Center;vec3 delta2=blob2-Face_Center;float dist1=dot(delta1,delta1);float dist2=dot(delta2,delta2);float nearestProxDist=sqrt(min(dist1,dist2));Width=(1.0-step(boxMaxSize+Proximity_Radius,nearestProxDist))*(1.0-step(Proximity_Far_Distance,min(d1,d2))*(1.0-step(0.0001,Selection)));Width=max(Gaze,Width);}\nvec2 ramp2(vec2 start,vec2 end,vec2 x)\n{return clamp((x-start)/(end-start),vec2(0.0,0.0),vec2(1.0,1.0));}\nfloat computeSelection(\nvec3 blobPosition,\nvec3 normal,\nvec3 tangent,\nvec3 bitangent,\nvec3 faceCenter,\nvec2 faceSize,\nfloat selectionFuzz,\nfloat farDistance,\nfloat fadeLength\n)\n{vec3 delta=blobPosition-faceCenter;float absD=abs(dot(delta,normal));float fadeIn=1.0-clamp((absD-farDistance)/fadeLength,0.0,1.0);vec2 blobCenterXY=vec2(dot(delta,tangent),dot(delta,bitangent));vec2 innerFace=faceSize*(1.0-selectionFuzz)*0.5;vec2 selectPulse=ramp2(-faceSize*0.5,-innerFace,blobCenterXY)-ramp2(innerFace,faceSize*0.5,blobCenterXY);return selectPulse.x*selectPulse.y*fadeIn;}\nvoid Selection_Vertex_B31(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Face_Center,\nvec2 Face_Size,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nfloat Selection_Fuzz,\nfloat Selected,\nfloat Far_Distance,\nfloat Fade_Length,\nvec3 Active_Face_Dir,\nout float Show_Selection)\n{float select1=computeSelection(Blob_Position,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float select2=computeSelection(Blob_Position_2,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);Show_Selection=mix(max(select1,select2),1.0,Selected);}\nvoid main()\n{vec3 Vec3_Q29=vec3(vec2(0,0).x,vec2(0,0).y,color.r);vec3 Nrm_World_Q24;Nrm_World_Q24=normalize((world*vec4(normal,0.0)).xyz);vec3 Face_Center_Q30;Face_Center_Q30=(world*vec4(vec3(0,0,0),1.0)).xyz;vec3 Tangent_World_Q13;Tangent_World_Q13=(world*vec4(tangent,0.0)).xyz;vec3 Result_Q42;Result_Q42=_Use_Global_Left_Index_ ? Global_Left_Index_Tip_Position.xyz : _Blob_Position_;vec3 Result_Q43;Result_Q43=_Use_Global_Right_Index_ ? Global_Right_Index_Tip_Position.xyz : _Blob_Position_2_;float Value_At_T_Q58=mix(_Blob_Near_Size_,_Blob_Pulse_Max_Size_,_Blob_Pulse_);float Value_At_T_Q59=mix(_Blob_Near_Size_2_,_Blob_Pulse_Max_Size_,_Blob_Pulse_2_);vec3 Cross_Q70=cross(normal,tangent);float Product_Q45=_Gaze_Intensity_*_Gaze_Focus_;float Step_Q46=step(0.0001,Product_Q45);vec3 Tangent_World_N_Q15=normalize(Tangent_World_Q13);vec3 Position_Q27;float Near_Size_Q27;float Inner_Fade_Q27;float Blob_Enable_Q27;float Fade_Q27;float Pulse_Q27;Choose_Blob_B27(color,Result_Q42,Result_Q43,_Blob_Enable_,_Blob_Enable_2_,Value_At_T_Q58,Value_At_T_Q59,_Blob_Inner_Fade_,_Blob_Inner_Fade_2_,_Blob_Pulse_,_Blob_Pulse_2_,_Blob_Fade_,_Blob_Fade_2_,Position_Q27,Near_Size_Q27,Inner_Fade_Q27,Blob_Enable_Q27,Fade_Q27,Pulse_Q27);vec3 Binormal_World_Q14;Object_To_World_Dir_B14(Cross_Q70,Binormal_World_Q14);float Anisotropy_Q21=length(Tangent_World_Q13)/length(Binormal_World_Q14);vec3 Binormal_World_N_Q16=normalize(Binormal_World_Q14);vec2 Face_Size_Q35;float ScaleY_Q35;Face_Size_Q35=vec2(length(Tangent_World_Q13),length(Binormal_World_Q14));ScaleY_Q35=Face_Size_Q35.y;float Out_Radius_Q38;float Out_Line_Width_Q38;Out_Radius_Q38=_Relative_To_Height_ ? _Radius_ : _Radius_/ScaleY_Q35;Out_Line_Width_Q38=_Relative_To_Height_ ? _Line_Width_ : _Line_Width_/ScaleY_Q35;float Show_Selection_Q31;Selection_Vertex_B31(Result_Q42,Result_Q43,Face_Center_Q30,Face_Size_Q35,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,_Selection_Fuzz_,_Selected_,_Selected_Distance_,_Selected_Fade_Length_,vec3(0,0,-1),Show_Selection_Q31);float MaxAB_Q41=max(Show_Selection_Q31,Product_Q45);float Width_Q55;Proximity_Visibility_B55(Show_Selection_Q31,Result_Q42,Result_Q43,_Proximity_Far_Distance_,_Proximity_Near_Radius_,Face_Center_Q30,Nrm_World_Q24,Face_Size_Q35,Step_Q46,Width_Q55);vec3 New_P_Q32;vec2 New_UV_Q32;Move_Verts_B32(uv,Out_Radius_Q38,Anisotropy_Q21,Out_Line_Width_Q38,Width_Q55,New_P_Q32,New_UV_Q32);vec3 Pos_World_Q12;Object_To_World_Pos_B12(New_P_Q32,Pos_World_Q12);vec3 Out_Position_Q40;vec2 Out_UV_Q40;vec3 Blob_Info_Q40;vec2 Blob_Relative_UV_Q40;Blob_Vertex_B40(Pos_World_Q12,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,Position_Q27,_Blob_Intensity_,Near_Size_Q27,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,color,uv,Face_Center_Q30,Face_Size_Q35,New_UV_Q32,_Blob_Fade_Length_,_Selection_Fade_,_Selection_Fade_Size_,Inner_Fade_Q27,Pulse_Q27,Fade_Q27,Blob_Enable_Q27,0.0,Out_Position_Q40,Out_UV_Q40,Blob_Info_Q40,Blob_Relative_UV_Q40);vec2 Rect_UV_Q36;vec2 Scale_XY_Q36;vec4 Rect_Parms_Q36;Round_Rect_Vertex_B36(New_UV_Q32,Tangent_World_Q13,Binormal_World_Q14,Out_Radius_Q38,Anisotropy_Q21,Blob_Relative_UV_Q40,Rect_UV_Q36,Scale_XY_Q36,Rect_Parms_Q36);vec4 Extra_Q33;float Distance_To_Face_Q33;float Distance_Fade1_Q33;float Distance_Fade2_Q33;Proximity_Vertex_B33(Result_Q42,Result_Q43,Face_Center_Q30,Pos_World_Q12,_Proximity_Far_Distance_,1.0,_Proximity_Anisotropy_,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,Extra_Q33,Distance_To_Face_Q33,Distance_Fade1_Q33,Distance_Fade2_Q33);vec4 Vec4_Q37=vec4(MaxAB_Q41,Distance_Fade1_Q33,Distance_Fade2_Q33,Out_Radius_Q38);vec3 Position=Out_Position_Q40;vec3 Normal=Vec3_Q29;vec2 UV=Out_UV_Q40;vec3 Tangent=Blob_Info_Q40;vec3 Binormal=vec3(0,0,0);vec4 Color=vec4(1,1,1,1);vec4 Extra1=Rect_Parms_Q36;vec4 Extra2=Extra_Q33;vec4 Extra3=Vec4_Q37;gl_Position=viewProjection*vec4(Position,1);vNormal=Normal;vUV=UV;vTangent=Tangent;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class qV extends xn{constructor(){super(),this.SMOOTH_EDGES=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class YV extends bn{constructor(e,t){super(e,t),this.radius=.12,this.lineWidth=.01,this.relativeToHeight=!1,this._filterWidth=1,this.edgeColor=new H.ov(.53,.53,.53,1),this.blobEnable=!0,this.blobPosition=new W.Pq(100,100,100),this.blobIntensity=.5,this.blobNearSize=.032,this.blobFarSize=.048,this.blobNearDistance=.008,this.blobFarDistance=.064,this.blobFadeLength=.04,this.blobInnerFade=.01,this.blobPulse=0,this.blobFade=1,this.blobPulseMaxSize=.05,this.blobEnable2=!0,this.blobPosition2=new W.Pq(10,10.1,-.6),this.blobNearSize2=.008,this.blobInnerFade2=.1,this.blobPulse2=0,this.blobFade2=1,this.gazeIntensity=.8,this.gazeFocus=0,this.selectionFuzz=.5,this.selected=1,this.selectionFade=.2,this.selectionFadeSize=0,this.selectedDistance=.08,this.selectedFadeLength=.08,this.proximityMaxIntensity=.45,this.proximityFarDistance=.16,this.proximityNearRadius=.016,this.proximityAnisotropy=1,this.useGlobalLeftIndex=!0,this.useGlobalRightIndex=!0,this.fadeOut=1,this.alphaMode=Il.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1,this._blobTexture=new vi.g(YV.BLOB_TEXTURE_URL,t,!0,!1,vi.g.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new qV);const r=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if((0,Bt.qB)(e,r,!1,!1),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=new Tn;r.FOG&&e.addFallback(1,"FOG"),(0,Bt.c4)(r,e),r.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const i=[st.R.PositionKind];r.NORMAL&&i.push(st.R.NormalKind),r.UV1&&i.push(st.R.UVKind),r.UV2&&i.push(st.R.UV2Kind),r.VERTEXCOLOR&&i.push(st.R.ColorKind),r.TANGENT&&i.push(st.R.TangentKind),(0,Bt.ER)(i,r);const o="mrdlFrontplate",a=r.toString(),l=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Relative_To_Height_","_Filter_Width_","_Edge_Color_","_Fade_Out_","_Smooth_Edges_","_Blob_Enable_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Inner_Fade_","_Blob_Pulse_","_Blob_Fade_","_Blob_Pulse_Max_Size_","_Blob_Enable_2_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Inner_Fade_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Gaze_Intensity_","_Gaze_Focus_","_Blob_Texture_","_Selection_Fuzz_","_Selected_","_Selection_Fade_","_Selection_Fade_Size_","_Selected_Distance_","_Selected_Fade_Length_","_Proximity_Max_Intensity_","_Proximity_Far_Distance_","_Proximity_Near_Radius_","_Proximity_Anisotropy_","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","_Use_Global_Left_Index_","_Use_Global_Right_Index_"],h=[],c=[];(0,Bt.Bb)({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:r,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),r)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const r=this.getScene();if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",r.activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Relative_To_Height_",this.relativeToHeight?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Edge_Color_",this.edgeColor),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._activeEffect.setFloat("_Blob_Enable_",this.blobEnable?1:0),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Inner_Fade_",this.blobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setFloat("_Blob_Pulse_Max_Size_",this.blobPulseMaxSize),this._activeEffect.setFloat("_Blob_Enable_2_",this.blobEnable2?1:0),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Inner_Fade_2_",this.blobInnerFade2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setFloat("_Gaze_Intensity_",this.gazeIntensity),this._activeEffect.setFloat("_Gaze_Focus_",this.gazeFocus),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Selection_Fuzz_",this.selectionFuzz),this._activeEffect.setFloat("_Selected_",this.selected),this._activeEffect.setFloat("_Selection_Fade_",this.selectionFade),this._activeEffect.setFloat("_Selection_Fade_Size_",this.selectionFadeSize),this._activeEffect.setFloat("_Selected_Distance_",this.selectedDistance),this._activeEffect.setFloat("_Selected_Fade_Length_",this.selectedFadeLength),this._activeEffect.setFloat("_Proximity_Max_Intensity_",this.proximityMaxIntensity),this._activeEffect.setFloat("_Proximity_Far_Distance_",this.proximityFarDistance),this._activeEffect.setFloat("_Proximity_Near_Radius_",this.proximityNearRadius),this._activeEffect.setFloat("_Proximity_Anisotropy_",this.proximityAnisotropy),this._activeEffect.setFloat("_Use_Global_Left_Index_",this.useGlobalLeftIndex?1:0),this._activeEffect.setFloat("_Use_Global_Right_Index_",this.useGlobalRightIndex?1:0),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return it.p.Clone((()=>new YV(e,this.getScene())),this)}serialize(){const e=it.p.Serialize(this);return e.customType="BABYLON.MRDLFrontplateMaterial",e}getClassName(){return"MRDLFrontplateMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new YV(e.name,t)),e,t,i)}}YV.BLOB_TEXTURE_URL="",(0,je.Cg)([(0,$e.lK)()],YV.prototype,"radius",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"lineWidth",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"relativeToHeight",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"edgeColor",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobEnable",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobPosition",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobNearSize",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobFarSize",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobNearDistance",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobFarDistance",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobFadeLength",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobInnerFade",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobPulse",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobFade",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobPulseMaxSize",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobEnable2",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobPosition2",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobNearSize2",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobInnerFade2",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobPulse2",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobFade2",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"gazeIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"gazeFocus",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"selectionFuzz",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"selected",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"selectionFade",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"selectionFadeSize",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"selectedDistance",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"selectedFadeLength",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"proximityMaxIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"proximityFarDistance",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"proximityNearRadius",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"proximityAnisotropy",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"useGlobalLeftIndex",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"useGlobalRightIndex",void 0),(0,X.Y5)("BABYLON.GUI.MRDLFrontplateMaterial",YV);Cs.l.ShadersStore.mrdlInnerquadPixelShader="uniform vec3 cameraPosition;varying vec2 vUV;varying vec3 vTangent;uniform vec4 _Color_;uniform float _Radius_;uniform bool _Fixed_Radius_;uniform float _Filter_Width_;uniform float _Glow_Fraction_;uniform float _Glow_Max_;uniform float _Glow_Falloff_;float FilterStep_Bid194(float edge,float x,float filterWidth)\n{float dx=max(1.0E-5,fwidth(x)*filterWidth);return max((x+dx*0.5-max(edge,x-dx*0.5))/dx,0.0);}\nvoid Round_Rect_B194(\nfloat Size_X,\nfloat Size_Y,\nfloat Radius,\nvec4 Rect_Color,\nfloat Filter_Width,\nvec2 UV,\nfloat Glow_Fraction,\nfloat Glow_Max,\nfloat Glow_Falloff,\nout vec4 Color)\n{vec2 halfSize=vec2(Size_X,Size_Y)*0.5;vec2 r=max(min(vec2(Radius,Radius),halfSize),vec2(0.01,0.01));vec2 v=abs(UV);vec2 nearestp=min(v,halfSize-r);vec2 delta=(v-nearestp)/max(vec2(0.01,0.01),r);float Distance=length(delta);float insideRect=1.0-FilterStep_Bid194(1.0-Glow_Fraction,Distance,Filter_Width);float glow=clamp((1.0-Distance)/Glow_Fraction,0.0,1.0);glow=pow(glow,Glow_Falloff);Color=Rect_Color*max(insideRect,glow*Glow_Max);}\nvoid main()\n{float X_Q192;float Y_Q192;float Z_Q192;X_Q192=vTangent.x;Y_Q192=vTangent.y;Z_Q192=vTangent.z;vec4 Color_Q194;Round_Rect_B194(X_Q192,1.0,Y_Q192,_Color_,_Filter_Width_,vUV,_Glow_Fraction_,_Glow_Max_,_Glow_Falloff_,Color_Q194);vec4 Out_Color=Color_Q194;float Clip_Threshold=0.0;gl_FragColor=Out_Color;}\n";Cs.l.ShadersStore.mrdlInnerquadVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform vec4 _Color_;uniform float _Radius_;uniform bool _Fixed_Radius_;uniform float _Filter_Width_;uniform float _Glow_Fraction_;uniform float _Glow_Max_;uniform float _Glow_Falloff_;varying vec2 vUV;varying vec3 vTangent;void main()\n{vec3 Pos_World_Q189;Pos_World_Q189=(world*vec4(position,1.0)).xyz;vec3 Dir_World_Q190;Dir_World_Q190=(world*vec4(tangent,0.0)).xyz;vec3 Dir_World_Q191;Dir_World_Q191=(world*vec4((cross(normal,tangent)),0.0)).xyz;float Length_Q180=length(Dir_World_Q190);float Length_Q181=length(Dir_World_Q191);float Quotient_Q184=Length_Q180/Length_Q181;float Quotient_Q195=_Radius_/Length_Q181;vec2 Result_Q193;Result_Q193=vec2((uv.x-0.5)*Length_Q180/Length_Q181,(uv.y-0.5));float Result_Q198=_Fixed_Radius_ ? Quotient_Q195 : _Radius_;vec3 Vec3_Q183=vec3(Quotient_Q184,Result_Q198,0);vec3 Position=Pos_World_Q189;vec3 Normal=vec3(0,0,0);vec2 UV=Result_Q193;vec3 Tangent=Vec3_Q183;vec3 Binormal=vec3(0,0,0);vec4 Color=color;gl_Position=viewProjection*vec4(Position,1);vUV=UV;vTangent=Tangent;}\n";class KV extends xn{constructor(){super(),this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class jV extends bn{constructor(e,t){super(e,t),this.color=new H.ov(1,1,1,.05),this.radius=.12,this.fixedRadius=!0,this._filterWidth=1,this.glowFraction=0,this.glowMax=.5,this.glowFalloff=2,this.alphaMode=Il.ALPHA_COMBINE,this.backFaceCulling=!1}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new KV);const r=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if((0,Bt.qB)(e,r,!0,!1),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=new Tn;r.FOG&&e.addFallback(1,"FOG"),(0,Bt.c4)(r,e),r.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const i=[st.R.PositionKind];r.NORMAL&&i.push(st.R.NormalKind),r.UV1&&i.push(st.R.UVKind),r.UV2&&i.push(st.R.UV2Kind),r.VERTEXCOLOR&&i.push(st.R.ColorKind),r.TANGENT&&i.push(st.R.TangentKind),(0,Bt.ER)(i,r);const o="mrdlInnerquad",a=r.toString(),l=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Color_","_Radius_","_Fixed_Radius_","_Filter_Width_","_Glow_Fraction_","_Glow_Max_","_Glow_Falloff_"],h=[],c=[];(0,Bt.Bb)({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:r,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),r)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const r=this.getScene();if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",r.activeCamera.position),this._activeEffect.setDirectColor4("_Color_",this.color),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Fixed_Radius_",this.fixedRadius?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setFloat("_Glow_Fraction_",this.glowFraction),this._activeEffect.setFloat("_Glow_Max_",this.glowMax),this._activeEffect.setFloat("_Glow_Falloff_",this.glowFalloff),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return it.p.Clone((()=>new jV(e,this.getScene())),this)}serialize(){const e=it.p.Serialize(this);return e.customType="BABYLON.MRDLInnerquadMaterial",e}getClassName(){return"MRDLInnerquadMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new jV(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.lK)()],jV.prototype,"color",void 0),(0,je.Cg)([(0,$e.lK)()],jV.prototype,"radius",void 0),(0,je.Cg)([(0,$e.lK)()],jV.prototype,"fixedRadius",void 0),(0,je.Cg)([(0,$e.lK)()],jV.prototype,"glowFraction",void 0),(0,je.Cg)([(0,$e.lK)()],jV.prototype,"glowMax",void 0),(0,je.Cg)([(0,$e.lK)()],jV.prototype,"glowFalloff",void 0),(0,X.Y5)("BABYLON.GUI.MRDLInnerquadMaterial",jV);class $V extends bV{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._backGlow.renderingGroupId=e,this._innerQuad.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}get mesh(){return this._backPlate}set tooltipText(e){if(e){if(!this._tooltipFade){const e=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=Qi("",{size:1},this._backPlate._scene),this._tooltipMesh.position=W.Pq.Down().scale(.7).add(W.Pq.Forward(e).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._frontPlateCollisionMesh,this._tooltipTexture=$B.CreateForMesh(this._tooltipMesh);const t=new cB;t.height=.25,t.width=.8,t.cornerRadius=25,t.color="#ffffff",t.thickness=20,t.background="#060668",this._tooltipTexture.addControl(t),this._tooltipTextBlock=new dB,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=100,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new Mi,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)})),this._tooltipOutObserver=this.onPointerOutObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)}))}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}else this._disposeTooltip()}get tooltipText(){return this._tooltipTextBlock?.text||null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get subtext(){return this._subtext}set subtext(e){this._subtext!==e&&(this._subtext=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get backGlowMaterial(){return this._backGlowMaterial}get innerQuadMaterial(){return this._innerQuadMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}set isBackplateVisible(e){this.mesh&&this._backMaterial&&(e&&!this._isBackplateVisible?this._backPlate.visibility=1:!e&&this._isBackplateVisible&&(this._backPlate.visibility=0)),this._isBackplateVisible=e}constructor(e,t=!0){super(e),this.width=1,this.height=1,this.radius=.14,this.textSizeInPixels=18,this.imageSizeInPixels=40,this.plateMaterialColor=new H.v9(.4,.4,.4),this.frontPlateDepth=.2,this.backPlateDepth=.04,this.backGlowOffset=.1,this.flatPlaneDepth=.001,this.innerQuadRadius=this.radius-.04,this.innerQuadColor=new H.ov(0,0,0,0),this.innerQuadToggledColor=new H.ov(.5197843,.6485234,.9607843,.6),this.innerQuadHoverColor=new H.ov(1,1,1,.05),this.innerQuadToggledHoverColor=new H.ov(.5197843,.6485234,.9607843,1),this._isBackplateVisible=!0,this._shareMaterials=!0,this._shareMaterials=t,this.pointerEnterAnimation=()=>{this._frontPlate&&this._textPlate&&!this.isToggleButton&&this._performEnterExitAnimation(1),this.isToggleButton&&this._innerQuadMaterial&&(this.isToggled?this._innerQuadMaterial.color=this.innerQuadToggledHoverColor:this._innerQuadMaterial.color=this.innerQuadHoverColor)},this.pointerOutAnimation=()=>{this._frontPlate&&this._textPlate&&!this.isToggleButton&&this._performEnterExitAnimation(-.8),this.isToggleButton&&this._innerQuadMaterial&&this._onToggle(this.isToggled)},this.pointerDownAnimation=()=>{},this.pointerUpAnimation=()=>{},this._pointerClickObserver=this.onPointerClickObservable.add((()=>{this._frontPlate&&this._backGlow&&!this.isActiveNearInteraction&&this._performClickAnimation(),this.isToggleButton&&this._innerQuadMaterial&&this._onToggle(this.isToggled)})),this._pointerEnterObserver=this.onPointerEnterObservable.add((()=>{this.pointerEnterAnimation()})),this._pointerOutObserver=this.onPointerOutObservable.add((()=>{this.pointerOutAnimation()})),this._toggleObserver=this.onToggleObservable.add((e=>{this._innerQuadMaterial.color=e?this.innerQuadToggledColor:this.innerQuadColor}))}_getTypeName(){return"TouchHolographicButton"}_rebuildContent(){let e;e=this._getAspectRatio()<=1?this._alignContentVertically():this._alignContentHorizontally(),this.content=e}_getAspectRatio(){return this.width/this.height}_alignContentVertically(){const e=new _B;if(e.isVertical=!0,(0,ii.Nf)()&&document.createElement&&this._imageUrl){const t=new fB;t.source=this._imageUrl,t.heightInPixels=180,t.widthInPixels=100,t.paddingTopInPixels=40,t.paddingBottomInPixels=40,e.addControl(t)}if(this._text){const t=new dB;t.text=this._text,t.color="white",t.heightInPixels=30,t.fontSize=24,e.addControl(t)}return e}_alignContentHorizontally(){let e=240;const t=15,i=new cB;i.widthInPixels=e,i.heightInPixels=e,i.color="transparent",i.setPaddingInPixels(t,t,t,t),e-=30;const r=new _B;if(r.isVertical=!1,r.scaleY=this._getAspectRatio(),(0,ii.Nf)()&&document.createElement&&this._imageUrl){const t=new cB(`${this.name}_image`);t.widthInPixels=this.imageSizeInPixels,t.heightInPixels=this.imageSizeInPixels,t.color="transparent",e-=this.imageSizeInPixels;const i=new fB;i.source=this._imageUrl,t.addControl(i),r.addControl(t)}if(this._text){const i=new dB(`${this.name}_text`);if(i.text=this._text,i.color="white",i.fontSize=this.textSizeInPixels,i.widthInPixels=e,this._imageUrl&&(i.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,i.paddingLeftInPixels=t),this._subtext){const s=new xB;s.addColumnDefinition(1),s.addRowDefinition(.5),s.addRowDefinition(.5),s.widthInPixels=e,s.heightInPixels=45;const n=new dB(`${this.name}_subtext`);n.text=this._subtext,n.color="#EEEEEEAB",n.fontSize=.75*this.textSizeInPixels,n.fontWeight="600",this._imageUrl&&(n.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,n.paddingLeftInPixels=t),s.addControl(i,0),s.addControl(n,1),r.addControl(s)}else r.addControl(i)}return i.addControl(r),i}_createNode(e){this.name=this.name??"TouchHolographicButton";const t=this._createBackPlate(e),i=this._createFrontPlate(e),r=this._createInnerQuad(e),s=this._createBackGlow(e);this._frontPlateCollisionMesh=i,this._textPlate=super._createNode(e),this._textPlate.name=`${this.name}_textPlate`,this._textPlate.isPickable=!1,this._textPlate.scaling.x=this.width,this._textPlate.parent=i,this._backPlate=t,this._backPlate.position=W.Pq.Forward(e.useRightHandedSystem).scale(this.backPlateDepth/2),this._backPlate.isPickable=!1,this._backPlate.addChild(i),this._backPlate.addChild(r),s&&this._backPlate.addChild(s);const n=new Pt(`${this.name}_root`,e);return this._backPlate.setParent(n),this.collisionMesh=i,this.collidableFrontDirection=this._backPlate.forward.negate(),n}_createBackPlate(e){const t=Ko(`${this.name}_backPlate`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=.2,xg.ImportMeshAsync(void 0,$V.MRTK_ASSET_BASE_URL,$V.BACKPLATE_MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.visibility=0,this._isBackplateVisible&&(i.visibility=1,i.name=`${this.name}_backPlate`,i.isPickable=!1,i.scaling.x=this.width,i.scaling.y=this.height,i.parent=t),this._backMaterial&&(i.material=this._backMaterial),this._backPlate=i})),t}_createFrontPlate(e){const t=Ko(`${this.name}_frontPlate`,{width:this.width,height:this.height,depth:this.frontPlateDepth},e);return t.isPickable=!0,t.isNearPickable=!0,t.visibility=0,t.position=W.Pq.Forward(e.useRightHandedSystem).scale((this.backPlateDepth-this.frontPlateDepth)/2),xg.ImportMeshAsync(void 0,$V.MRTK_ASSET_BASE_URL,$V.FRONTPLATE_MODEL_FILENAME,e).then((i=>{const r=Ko(`${this.name}_collisionPlate`,{width:this.width,height:this.height},e);r.isPickable=!1,r.scaling.z=this.frontPlateDepth,r.visibility=0,r.parent=t,this._collisionPlate=r;const s=i.meshes[1];s.name=`${this.name}_frontPlate`,s.isPickable=!1,s.scaling.x=this.width-this.backGlowOffset,s.scaling.y=this.height-this.backGlowOffset,s.position=W.Pq.Forward(e.useRightHandedSystem).scale(-.5),s.parent=r,this.isToggleButton&&(s.visibility=0),this._frontMaterial&&(s.material=this._frontMaterial),this._textPlate.scaling.x=1,this._textPlate.parent=s,this._frontPlate=s})),t}_createInnerQuad(e){const t=Ko(`${this.name}_innerQuad`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=this.flatPlaneDepth,t.position.z+=this.backPlateDepth/2-this.flatPlaneDepth,xg.ImportMeshAsync(void 0,$V.MRTK_ASSET_BASE_URL,$V.INNERQUAD_MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.name=`${this.name}_innerQuad`,i.isPickable=!1,i.scaling.x=this.width-this.backGlowOffset,i.scaling.y=this.height-this.backGlowOffset,i.parent=t,this._innerQuadMaterial&&(i.material=this._innerQuadMaterial),this._innerQuad=i})),t}_createBackGlow(e){if(this.isToggleButton)return;const t=Ko(`${this.name}_backGlow`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=this.flatPlaneDepth,t.position.z+=this.backPlateDepth/2-2*this.flatPlaneDepth,xg.ImportMeshAsync(void 0,$V.MRTK_ASSET_BASE_URL,$V.BACKGLOW_MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.name=`${this.name}_backGlow`,i.isPickable=!1,i.scaling.x=this.width-this.backGlowOffset,i.scaling.y=this.height-this.backGlowOffset,i.parent=t,this._backGlowMaterial&&(i.material=this._backGlowMaterial),this._backGlow=i})),t}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e,this._plateMaterial.diffuseColor=this.plateMaterialColor}_performClickAnimation(){const e=new Fe.AnimationGroup("Click Animation Group"),t=[{name:"backGlowMotion",mesh:this._backGlow,property:"material.motion",keys:[{frame:0,values:[0,0,0]},{frame:20,values:[1,.0144,.0144]},{frame:40,values:[.0027713229489760476,0,0]},{frame:45,values:[.0027713229489760476]}]},{name:"_collisionPlateZSlide",mesh:this._collisionPlate,property:"position.z",keys:[{frame:0,values:[0,0,0]},{frame:20,values:[W.Pq.Forward(this._collisionPlate._scene.useRightHandedSystem).scale(this.frontPlateDepth/2).z,0,0]},{frame:40,values:[0,.005403332496794331]},{frame:45,values:[0]}]},{name:"_collisionPlateZScale",mesh:this._collisionPlate,property:"scaling.z",keys:[{frame:0,values:[this.frontPlateDepth,0,0]},{frame:20,values:[this.backPlateDepth,0,0]},{frame:40,values:[this.frontPlateDepth,.0054]},{frame:45,values:[this.frontPlateDepth]}]}];for(const i of t){const t=new pe.X5(i.name,i.property,60,pe.X5.ANIMATIONTYPE_FLOAT,pe.X5.ANIMATIONLOOPMODE_CYCLE),r=[];for(const e of i.keys)r.push({frame:e.frame,value:e.values[0],inTangent:e.values[1],outTangent:e.values[2],interpolation:e.values[3]});t.setKeys(r),i.mesh&&e.addTargetedAnimation(t,i.mesh)}e.normalize(0,45),e.speedRatio=1,e.play()}_performEnterExitAnimation(e){const t=new Fe.AnimationGroup("Enter Exit Animation Group"),i=[{name:"frontPlateFadeOut",mesh:this._frontPlate,property:"material.fadeOut",keys:[{frame:0,values:[0,0,.025045314830017686,0]},{frame:40,values:[1.00205599570012,.025045314830017686,0,0]}]},{name:"textPlateZSlide",mesh:this._textPlate,property:"position.z",keys:[{frame:0,values:[0,0,0]},{frame:40,values:[W.Pq.Forward(this._textPlate._scene.useRightHandedSystem).scale(-.15).z,0,0]}]}];for(const e of i){const i=new pe.X5(e.name,e.property,60,pe.X5.ANIMATIONTYPE_FLOAT,pe.X5.ANIMATIONLOOPMODE_CYCLE),r=[];for(const t of e.keys)r.push({frame:t.frame,value:t.values[0],inTangent:t.values[1],outTangent:t.values[2],interpolation:t.values[3]});i.setKeys(r),e.mesh&&t.addTargetedAnimation(i,e.mesh)}t.normalize(0,45),t.speedRatio=e,t.play()}_createBackMaterial(e){this._backMaterial=this._backMaterial??new kV(this.name+"backPlateMaterial",e.getScene()),this._backMaterial.absoluteSizes=!0,this._backMaterial.radius=this.radius,this._backMaterial.lineWidth=.02}_createFrontMaterial(e){this._frontMaterial=this._frontMaterial??new YV(this.name+"Front Material",e.getScene()),this.frontMaterial.radius=this.innerQuadRadius,this.frontMaterial.fadeOut=0}_createBackGlowMaterial(e){const t=this.radius+.04;this._backGlowMaterial=this._backGlowMaterial??new XV(this.name+"Back Glow Material",e.getScene()),this._backGlowMaterial.bevelRadius=t,this._backGlowMaterial.lineWidth=t,this._backGlowMaterial.motion=0}_createInnerQuadMaterial(e){this._innerQuadMaterial=this._innerQuadMaterial??new jV("inner_quad",e.getScene()),this._innerQuadMaterial.radius=this.innerQuadRadius,this.isToggleButton&&(this._innerQuadMaterial.color=this.innerQuadColor)}_createPlateMaterial(e){this._plateMaterial=this._plateMaterial??new Un(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=H.v9.Black()}_onToggle(e){super._onToggle(e)}_affectMaterial(e){this._shareMaterials?(this._host._touchSharedMaterials.mrdlBackplateMaterial?this._backMaterial=this._host._touchSharedMaterials.mrdlBackplateMaterial:(this._createBackMaterial(e),this._host._touchSharedMaterials.mrdlBackplateMaterial=this._backMaterial),this._host._touchSharedMaterials.mrdlFrontplateMaterial?this._frontMaterial=this._host._touchSharedMaterials.mrdlFrontplateMaterial:(this._createFrontMaterial(e),this._host._touchSharedMaterials.mrdlFrontplateMaterial=this._frontMaterial),this._host._touchSharedMaterials.mrdlBackglowMaterial?this._backGlowMaterial=this._host._touchSharedMaterials.mrdlBackglowMaterial:(this._createBackGlowMaterial(e),this._host._touchSharedMaterials.mrdlBackglowMaterial=this._backGlowMaterial),this._host._touchSharedMaterials.mrdlInnerQuadMaterial?this._innerQuadMaterial=this._host._touchSharedMaterials.mrdlInnerQuadMaterial:(this._createInnerQuadMaterial(e),this._host._touchSharedMaterials.mrdlInnerQuadMaterial=this._innerQuadMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e),this._createBackGlowMaterial(e),this._createInnerQuadMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._textPlate.material=this._plateMaterial,this._isBackplateVisible||(this._backPlate.visibility=0),this._frontPlate&&(this._frontPlate.material=this._frontMaterial),this._backGlow&&(this._backGlow.material=this._backGlowMaterial),this._innerQuad&&(this._innerQuad.material=this._innerQuadMaterial),this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.onPointerClickObservable.remove(this._pointerClickObserver),this.onPointerEnterObservable.remove(this._pointerEnterObserver),this.onPointerOutObservable.remove(this._pointerOutObserver),this.onToggleObservable.remove(this._toggleObserver),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._backGlowMaterial.dispose(),this._innerQuadMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}$V.MRTK_ASSET_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",$V.FRONTPLATE_MODEL_FILENAME="mrtk-fluent-frontplate.glb",$V.BACKPLATE_MODEL_FILENAME="mrtk-fluent-backplate.glb",$V.BACKGLOW_MODEL_FILENAME="mrtk-fluent-button.glb",$V.INNERQUAD_MODEL_FILENAME="SlateProximity.glb";class QV{get scene(){return this._scene}get utilityLayer(){return this._utilityLayer}get controlScaling(){return this._customControlScaling}set controlScaling(e){if(this._customControlScaling!==e&&e>0){const t=e/this._customControlScaling;this._customControlScaling=e,this._rootContainer.children.forEach((i=>{i.scaling.scaleInPlace(t),1!==e&&(i._isScaledByManager=!0)}))}}get useRealisticScaling(){return this.controlScaling===QV.MRTK_REALISTIC_SCALING}set useRealisticScaling(e){this.controlScaling=e?QV.MRTK_REALISTIC_SCALING:1}constructor(e){this._customControlScaling=1,this._lastControlOver={},this._lastControlDown={},this.onPickedPointChangedObservable=new z.cP,this.onPickingObservable=new z.cP,this._sharedMaterials={},this._touchSharedMaterials={},this._scene=e||he.q.LastCreatedScene,this._sceneDisposeObserver=this._scene.onDisposeObservable.add((()=>{this._sceneDisposeObserver=null,this._utilityLayer=null,this.dispose()})),this._utilityLayer=Bo._CreateDefaultUtilityLayerFromScene(this._scene),this._utilityLayer.onlyCheckPointerDownEvents=!1,this._utilityLayer.pickUtilitySceneFirst=!1,this._utilityLayer.mainSceneTrackerPredicate=e=>e&&e.reservedDataStore?.GUI3D?.control?._node,this._rootContainer=new aV("RootContainer"),this._rootContainer._host=this;const t=this._utilityLayer.utilityLayerScene;this._pointerOutObserver=this._utilityLayer.onPointerOutObservable.add((e=>{this._handlePointerOut(e,!0)})),this._pointerObserver=t.onPointerObservable.add((e=>{this._doPicking(e)})),this._utilityLayer.utilityLayerScene.autoClear=!1,this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,new Lo("hemi",W.Pq.Up(),this._utilityLayer.utilityLayerScene)}_handlePointerOut(e,t){const i=this._lastControlOver[e];i&&(i._onPointerOut(i),delete this._lastControlOver[e]),t&&this._lastControlDown[e]&&(this._lastControlDown[e].forcePointerUp(),delete this._lastControlDown[e]),this.onPickedPointChangedObservable.notifyObservers(null)}_doPicking(e){if(!this._utilityLayer||!this._utilityLayer.shouldRender||!this._utilityLayer.utilityLayerScene.activeCamera)return!1;const t=e.event,i=t.pointerId||0,r=t.button,s=e.pickInfo;if(s&&this.onPickingObservable.notifyObservers(s.pickedMesh),!s||!s.hit)return this._handlePointerOut(i,e.type===yi.Zp.POINTERUP),!1;s.pickedPoint&&this.onPickedPointChangedObservable.notifyObservers(s.pickedPoint);const n=s.pickedMesh.reservedDataStore?.GUI3D?.control;return n&&!n._processObservables(e.type,s.pickedPoint,s.originMesh?.position||null,i,r)&&e.type===yi.Zp.POINTERMOVE&&(this._lastControlOver[i]&&this._lastControlOver[i]._onPointerOut(this._lastControlOver[i]),delete this._lastControlOver[i]),e.type===yi.Zp.POINTERUP&&(this._lastControlDown[t.pointerId]&&(this._lastControlDown[t.pointerId].forcePointerUp(),delete this._lastControlDown[t.pointerId]),("touch"===t.pointerType||"xr"===t.pointerType&&this._scene.getEngine().hostInformation.isMobile)&&this._handlePointerOut(i,!1)),!0}get rootContainer(){return this._rootContainer}containsControl(e){return this._rootContainer.containsControl(e)}addControl(e){return this._rootContainer.addControl(e),1!==this._customControlScaling&&(e.scaling.scaleInPlace(this._customControlScaling),e._isScaledByManager=!0),this}removeControl(e){return this._rootContainer.removeControl(e),e._isScaledByManager&&(e.scaling.scaleInPlace(1/this._customControlScaling),e._isScaledByManager=!1),this}dispose(){this._rootContainer.dispose();for(const e in this._sharedMaterials)Object.prototype.hasOwnProperty.call(this._sharedMaterials,e)&&this._sharedMaterials[e].dispose();this._sharedMaterials={};for(const e in this._touchSharedMaterials)Object.prototype.hasOwnProperty.call(this._touchSharedMaterials,e)&&this._touchSharedMaterials[e].dispose();this._touchSharedMaterials={},this._pointerOutObserver&&this._utilityLayer&&(this._utilityLayer.onPointerOutObservable.remove(this._pointerOutObserver),this._pointerOutObserver=null),this.onPickedPointChangedObservable.clear(),this.onPickingObservable.clear();const e=this._utilityLayer?this._utilityLayer.utilityLayerScene:null;e&&this._pointerObserver&&(e.onPointerObservable.remove(this._pointerObserver),this._pointerObserver=null),this._scene&&this._sceneDisposeObserver&&(this._scene.onDisposeObservable.remove(this._sceneDisposeObserver),this._sceneDisposeObserver=null),this._utilityLayer&&this._utilityLayer.dispose()}}function ZV(e,t,i,r){const s={externalResourceFunction:r};return i&&(s.uri="file:"===t?i:t+i),ArrayBuffer.isView(e)?GLTFValidator.validateBytes(e,s):GLTFValidator.validateString(e,s)}function JV(){const e=[];onmessage=t=>{const i=t.data;switch(i.id){case"init":importScripts(i.url);break;case"validate":ZV(i.data,i.rootUrl,i.fileName,(t=>new Promise(((i,r)=>{const s=e.length;e.push({resolve:i,reject:r}),postMessage({id:"getExternalResource",index:s,uri:t})})))).then((e=>{postMessage({id:"validate.resolve",value:e})}),(e=>{postMessage({id:"validate.reject",reason:e})}));break;case"getExternalResource.resolve":e[i.index].resolve(i.value);break;case"getExternalResource.reject":e[i.index].reject(i.reason)}}}QV.MRTK_REALISTIC_SCALING=.032;class ek{static ValidateAsync(e,t,i,r){return"function"==typeof Worker?new Promise(((s,n)=>{const o=`${ZV}(${JV})()`,a=URL.createObjectURL(new Blob([o],{type:"application/javascript"})),l=new Worker(a),h=e=>{l.removeEventListener("error",h),l.removeEventListener("message",c),n(e)},c=e=>{const t=e.data;switch(t.id){case"getExternalResource":r(t.uri).then((e=>{l.postMessage({id:"getExternalResource.resolve",index:t.index,value:e},[e.buffer])}),(e=>{l.postMessage({id:"getExternalResource.reject",index:t.index,reason:e})}));break;case"validate.resolve":l.removeEventListener("error",h),l.removeEventListener("message",c),s(t.value),l.terminate();break;case"validate.reject":l.removeEventListener("error",h),l.removeEventListener("message",c),n(t.reason),l.terminate()}};if(l.addEventListener("error",h),l.addEventListener("message",c),l.postMessage({id:"init",url:Ue.S0.GetBabylonScriptURL(this.Configuration.url)}),ArrayBuffer.isView(e)){const r=e.slice();l.postMessage({id:"validate",data:r,rootUrl:t,fileName:i},[r.buffer])}else l.postMessage({id:"validate",data:e,rootUrl:t,fileName:i})})):(this._LoadScriptPromise||(this._LoadScriptPromise=Ue.S0.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then((()=>ZV(e,t,i,r))))}}ek.Configuration={url:`${Ue.S0._DefaultCdnUrl}/gltf_validator.js`};const tk="Z2xURg",ik="gltf",rk={".gltf":{isBinary:!1,mimeType:"model/gltf+json"},".glb":{isBinary:!0,mimeType:"model/gltf-binary"}},sk=e=>-1!==e.indexOf("asset")&&-1!==e.indexOf("version")||e.startsWith("data:base64,"+tk)||e.startsWith("data:;base64,"+tk)||e.startsWith("data:application/octet-stream;base64,"+tk)||e.startsWith("data:model/gltf-binary;base64,"+tk);function nk(e,t,i){try{return Promise.resolve(new Uint8Array(e,t,i))}catch(e){return Promise.reject(e)}}var ok,ak,lk,hk,ck,uk,dk,fk,pk,_k,mk,gk;!function(e){e[e.AUTO=0]="AUTO",e[e.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"}(ok||(ok={})),function(e){e[e.NONE=0]="NONE",e[e.FIRST=1]="FIRST",e[e.ALL=2]="ALL"}(ak||(ak={})),function(e){e[e.LOADING=0]="LOADING",e[e.READY=1]="READY",e[e.COMPLETE=2]="COMPLETE"}(lk||(lk={}));class vk{constructor(){this.coordinateSystemMode=ok.AUTO,this.animationStartMode=ak.FIRST,this.loadNodeAnimations=!0,this.loadSkins=!0,this.loadMorphTargets=!0,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.useGltfTextureNames=!1,this.preprocessUrlAsync=e=>Promise.resolve(e),this.extensionOptions={}}copyFrom(e){e&&(this.onParsed=e.onParsed,this.coordinateSystemMode=e.coordinateSystemMode??this.coordinateSystemMode,this.animationStartMode=e.animationStartMode??this.animationStartMode,this.loadNodeAnimations=e.loadNodeAnimations??this.loadNodeAnimations,this.loadSkins=e.loadSkins??this.loadSkins,this.loadMorphTargets=e.loadMorphTargets??this.loadMorphTargets,this.compileMaterials=e.compileMaterials??this.compileMaterials,this.useClipPlane=e.useClipPlane??this.useClipPlane,this.compileShadowGenerators=e.compileShadowGenerators??this.compileShadowGenerators,this.transparencyAsCoverage=e.transparencyAsCoverage??this.transparencyAsCoverage,this.useRangeRequests=e.useRangeRequests??this.useRangeRequests,this.createInstances=e.createInstances??this.createInstances,this.alwaysComputeBoundingBox=e.alwaysComputeBoundingBox??this.alwaysComputeBoundingBox,this.loadAllMaterials=e.loadAllMaterials??this.loadAllMaterials,this.loadOnlyMaterials=e.loadOnlyMaterials??this.loadOnlyMaterials,this.skipMaterials=e.skipMaterials??this.skipMaterials,this.useSRGBBuffers=e.useSRGBBuffers??this.useSRGBBuffers,this.targetFps=e.targetFps??this.targetFps,this.alwaysComputeSkeletonRootNode=e.alwaysComputeSkeletonRootNode??this.alwaysComputeSkeletonRootNode,this.useGltfTextureNames=e.useGltfTextureNames??this.useGltfTextureNames,this.preprocessUrlAsync=e.preprocessUrlAsync??this.preprocessUrlAsync,this.customRootNode=e.customRootNode,this.onMeshLoaded=e.onMeshLoaded,this.onSkinLoaded=e.onSkinLoaded,this.onTextureLoaded=e.onTextureLoaded,this.onMaterialLoaded=e.onMaterialLoaded,this.onCameraLoaded=e.onCameraLoaded,this.extensionOptions=e.extensionOptions??this.extensionOptions)}}class xk extends vk{constructor(e){super(),this.onParsedObservable=new z.cP,this.onMeshLoadedObservable=new z.cP,this.onSkinLoadedObservable=new z.cP,this.onTextureLoadedObservable=new z.cP,this.onMaterialLoadedObservable=new z.cP,this.onCameraLoadedObservable=new z.cP,this.onCompleteObservable=new z.cP,this.onErrorObservable=new z.cP,this.onDisposeObservable=new z.cP,this.onExtensionLoadedObservable=new z.cP,this.validate=!1,this.onValidatedObservable=new z.cP,this._loader=null,this._state=null,this._requests=new Array,this.name=ik,this.extensions=rk,this.onLoaderStateChangedObservable=new z.cP,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled,this.copyFrom(e)}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),e&&(this._onParsedObserver=this.onParsedObservable.add(e))}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),e&&(this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e))}set onSkinLoaded(e){this._onSkinLoadedObserver&&this.onSkinLoadedObservable.remove(this._onSkinLoadedObserver),e&&(this._onSkinLoadedObserver=this.onSkinLoadedObservable.add((t=>e(t.node,t.skinnedNode))))}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),e&&(this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e))}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),e&&(this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e))}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),e&&(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,r,s,n,o,a){if(ArrayBuffer.isView(t))return this._loadBinary(e,t,i,r,o,a),null;this._progressCallback=s;const l=t.name||Ue.S0.GetFilename(t);if(n){if(this.useRangeRequests){this.validate&&Z.V.Warn("glTF validation is not supported when range requests are enabled");const i={abort:()=>{},onCompleteObservable:new z.cP},s={readAsync:(i,r)=>new Promise(((s,n)=>{this._loadFile(e,t,(e=>{s(new Uint8Array(e))}),!0,(e=>{n(e)}),(e=>{e.setRequestHeader("Range",`bytes=${i}-${i+r-1}`)}))})),byteLength:0};return this._unpackBinaryAsync(new tI(s)).then((e=>{i.onCompleteObservable.notifyObservers(i),r(e)}),o?e=>o(void 0,e):void 0),i}return this._loadFile(e,t,(t=>{this._validate(e,new Uint8Array(t,0,t.byteLength),i,l),this._unpackBinaryAsync(new tI({readAsync:(e,i)=>nk(t,e,i),byteLength:t.byteLength})).then((e=>{r(e)}),o?e=>o(void 0,e):void 0)}),!0,o)}return this._loadFile(e,t,(t=>{try{this._validate(e,t,i,l),r({json:this._parseJson(t)})}catch{o&&o()}}),!1,o)}_loadBinary(e,t,i,r,s,n){this._validate(e,new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i,n),this._unpackBinaryAsync(new tI({readAsync:(e,i)=>function(e,t,i){try{if(t<0||t>=e.byteLength)throw new RangeError("Offset is out of range.");if(t+i>e.byteLength)throw new RangeError("Length is out of range.");return Promise.resolve(new Uint8Array(e.buffer,e.byteOffset+t,i))}catch(e){return Promise.reject(e)}}(t,e,i),byteLength:t.byteLength})).then((e=>{r(e)}),s?e=>s(void 0,e):void 0)}importMeshAsync(e,t,i,r,s,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,r,s,n))))}loadAsync(e,t,i,r,s){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,i,r,s))))}loadAssetContainerAsync(e,t,i,r,s){return Promise.resolve().then((()=>{this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t);const n=new ei(e),o=[];this.onMaterialLoadedObservable.add((e=>{o.push(e)}));const a=[];this.onTextureLoadedObservable.add((e=>{a.push(e)}));const l=[];this.onCameraLoadedObservable.add((e=>{l.push(e)}));const h=[];return this.onMeshLoadedObservable.add((e=>{e.morphTargetManager&&h.push(e.morphTargetManager)})),this._loader.importMeshAsync(null,e,n,t,i,r,s).then((e=>(Array.prototype.push.apply(n.geometries,e.geometries),Array.prototype.push.apply(n.meshes,e.meshes),Array.prototype.push.apply(n.particleSystems,e.particleSystems),Array.prototype.push.apply(n.skeletons,e.skeletons),Array.prototype.push.apply(n.animationGroups,e.animationGroups),Array.prototype.push.apply(n.materials,o),Array.prototype.push.apply(n.textures,a),Array.prototype.push.apply(n.lights,e.lights),Array.prototype.push.apply(n.transformNodes,e.transformNodes),Array.prototype.push.apply(n.cameras,l),Array.prototype.push.apply(n.morphTargetManagers,h),n)))}))}canDirectLoad(e){return sk(e)}directLoad(e,t){if(t.startsWith("base64,"+tk)||t.startsWith(";base64,"+tk)||t.startsWith("application/octet-stream;base64,"+tk)||t.startsWith("model/gltf-binary;base64,"+tk)){const i=(0,$m.rz)(t);return this._validate(e,new Uint8Array(i,0,i.byteLength)),this._unpackBinaryAsync(new tI({readAsync:(e,t)=>nk(i,e,t),byteLength:i.byteLength}))}return this._validate(e,t),Promise.resolve({json:this._parseJson(t)})}createPlugin(e){return new xk(e[ik])}get loaderState(){return this._state}whenCompleteAsync(){return new Promise(((e,t)=>{this.onCompleteObservable.addOnce((()=>{e()})),this.onErrorObservable.addOnce((e=>{t(e)}))}))}_setState(e){this._state!==e&&(this._state=e,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(lk[this._state]))}_loadFile(e,t,i,r,s,n){const o=e._loadFile(t,i,(e=>{this._onProgress(e,o)}),!0,r,s,n);return o.onCompleteObservable.add((()=>{o._lengthComputable=!0,o._total=o._loaded})),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,r=0,s=0;for(const e of this._requests){if(void 0===e._lengthComputable||void 0===e._loaded||void 0===e._total)return;i=i&&e._lengthComputable,r+=e._loaded,s+=e._total}this._progressCallback({lengthComputable:i,loaded:r,total:i?s:0})}_validate(e,t,i="",r=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),ek.ValidateAsync(t,i,r,(t=>this.preprocessUrlAsync(i+t).then((t=>e._loadFileAsync(t,void 0,!0,!0).then((e=>new Uint8Array(e,0,e.byteLength))))))).then((e=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(e),this.onValidatedObservable.clear()}),(e=>{this._endPerformanceCounter("Validate JSON"),Ue.S0.Warn(`Failed to validate: ${e.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=xk._parseVersion(t.version);if(!i)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=xk._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(xk._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const r={1:xk._CreateGLTF1Loader,2:xk._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=e.readUint32();if(1179937895!==t)throw new nt.bu("Unexpected magic: "+t,nt.tG.GLTFLoaderUnexpectedMagicError);const i=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${i}`);const r=e.readUint32();let s;switch(this.useRangeRequests||r===e.buffer.byteLength||Z.V.Warn(`Length in header does not match actual data length: ${r} != ${e.buffer.byteLength}`),i){case 1:s=this._unpackBinaryV1Async(e,r);break;case 2:s=this._unpackBinaryV2Async(e,r);break;default:throw new Error("Unsupported version: "+i)}return this._endPerformanceCounter("Unpack Binary"),s}))}_unpackBinaryV1Async(e,t){const i=e.readUint32(),r=e.readUint32();if(0!==r)throw new Error(`Unexpected content format: ${r}`);const s=t-e.byteOffset,n={json:this._parseJson(e.readString(i)),bin:null};if(0!==s){const t=e.byteOffset;n.bin={readAsync:(i,r)=>e.buffer.readAsync(t+i,r),byteLength:s}}return Promise.resolve(n)}_unpackBinaryV2Async(e,t){const i=1313821514,r=e.readUint32();if(e.readUint32()!==i)throw new Error("First chunk format is not JSON");return e.byteOffset+r===t?e.loadAsync(r).then((()=>({json:this._parseJson(e.readString(r)),bin:null}))):e.loadAsync(r+8).then((()=>{const s={json:this._parseJson(e.readString(r)),bin:null},n=()=>{const r=e.readUint32();switch(e.readUint32()){case i:throw new Error("Unexpected JSON chunk");case 5130562:{const t=e.byteOffset;s.bin={readAsync:(i,r)=>e.buffer.readAsync(t+i,r),byteLength:r},e.skipBytes(r);break}default:e.skipBytes(r)}return e.byteOffset!==t?e.loadAsync(8).then(n):Promise.resolve(s)};return n()}))}static _parseVersion(e){if("1.0"===e||"1.0.1"===e)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,s){case hk.BYTE:return new Int8Array(o,i,r);case hk.UNSIGNED_BYTE:return new Uint8Array(o,i,r);case hk.SHORT:return new Int16Array(o,i,r);case hk.UNSIGNED_SHORT:return new Uint16Array(o,i,r);default:return new Float32Array(o,i,r)}}static GetBufferFromAccessor(e,t){const i=e.bufferViews[t.bufferView],r=t.count*bk.GetByteStrideFromType(t);return bk.GetBufferFromBufferView(e,i,t.byteOffset,r,t.componentType)}static DecodeBufferToText(e){let t="";const i=e.byteLength;for(let r=0;r=this._maxPos}}const Tk=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],Ck=["world","view","projection","worldView","worldViewProjection","mBones"],yk=["translation","rotation","scale"],Ek=["position","rotationQuaternion","scaling"],Pk=(e,t,i)=>{for(const r in e){const s=e[r];i[t][r]=s}},Ak=e=>{if(e)for(let t=0;t{if("NORMAL"===e.semantic)return"normal";if("POSITION"===e.semantic)return"position";if("JOINT"===e.semantic)return"matricesIndices";if("WEIGHT"===e.semantic)return"matricesWeights";if("COLOR"===e.semantic)return"color";if(e.semantic&&-1!==e.semantic.indexOf("TEXCOORD_")){const t=Number(e.semantic.split("_")[1]);return"uv"+(0===t?"":t+1)}return null},Ik=e=>{let t=null;if(e.translation||e.rotation||e.scale){const i=W.Pq.FromArray(e.scale||[1,1,1]),r=W.PT.FromArray(e.rotation||[0,0,0,1]),s=W.Pq.FromArray(e.translation||[0,0,0]);t=W.uq.Compose(i,r,s)}else t=W.uq.FromArray(e.matrix);return t},Mk=(e,t,i,r)=>{for(let e=0;e{for(let i=0;i{const i=e.nodes;let r=i[t];if(r)return{node:r,id:t};for(const e in i)if(r=i[e],r.jointName===t)return{node:r,id:e};return null},wk=(e,t)=>{for(let i=0;i{if(s||(e.scene._blockEntityCollection=!!e.assetContainer,(s=new Yt(t.name||"",e.scene))._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,s.id=r),!t.babylonNode)return s;const n=[];let o=null;const a=[],l=[],h=[],c=[];for(let t=0;t1?(u=new kt("multimat"+r,e.scene),u.subMaterials=n):u=new Un("multimat"+r,e.scene),1===n.length&&(u=n[0]),u._parentContainer=e.assetContainer,s.material||(s.material=u),new yt(r,e.scene,o,!1,s),s.computeWorldMatrix(!0),e.scene._blockEntityCollection=!1,s.subMeshes=[];let d=0;for(let t=0;t{e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=i),e.scaling&&(e.scaling=r)},Lk=(e,t,i)=>{let r=null;if(e.importOnlyMeshes&&(t.skin||t.meshes)&&e.importMeshesNames&&e.importMeshesNames.length>0&&-1===e.importMeshesNames.indexOf(t.name||""))return null;if(t.skin){if(t.meshes){const s=e.skins[t.skin],n=Nk(e,t,t.meshes,i,t.babylonNode);n.skeleton=e.scene.getLastSkeletonById(t.skin),null===n.skeleton&&(n.skeleton=((e,t,i,r)=>{if(r||(r=new Ti(t.name||"","",e.scene)),!t.babylonSkeleton)return r;const s=[],n=[];((e,t,i,r)=>{for(const s in e.nodes){const n=e.nodes[s],o=s;if(!n.jointName||wk(i,n.jointName))continue;const a=Ik(n),l=new Si.$(n.name||"",t,null,a);l.id=o,r.push({bone:l,node:n,id:o})}for(let e=0;e0&&(u=Ok(s,l),u&&-1===n.indexOf(u)&&n.push(u)),new Si.$(a.jointName||"",r,u,d).id=l}const o=r.bones;r.bones=[];for(let i=0;i{if(t.matrix){const i=new W.Pq(0,0,0),r=new W.PT,s=new W.Pq(0,0,0);W.uq.FromArray(t.matrix).decompose(s,r,i),Fk(e,i,r,s)}else t.translation&&t.rotation&&t.scale&&Fk(e,W.Pq.FromArray(t.translation),W.PT.FromArray(t.rotation),W.Pq.FromArray(t.scale));e.computeWorldMatrix(!0)})(r,t);else{const e=t.translation||[0,0,0],i=t.rotation||[0,0,0,1],s=t.scale||[1,1,1];Fk(r,W.Pq.FromArray(e),W.PT.FromArray(i),W.Pq.FromArray(s))}r.updateCache(!0),t.babylonNode=r}return r},Bk=(e,t,i,r=!1)=>{const s=e.nodes[t];let n=null;if(r=!(e.importOnlyMeshes&&!r&&e.importMeshesNames)||-1!==e.importMeshesNames.indexOf(s.name||"")||0===e.importMeshesNames.length,!s.jointName&&r&&(n=Lk(e,s,t),null!==n&&(n.id=t,n.parent=i)),s.children)for(let t=0;t{let t=e.currentScene;if(t)for(let i=0;i{for(const t in e.animations){const i=e.animations[t];if(!i.channels||!i.samplers)continue;let r=null;for(let s=0;s{for(const r in t.uniforms){const s=t.uniforms[r],n=t.parameters[s];if(e.currentIdentifier===r&&n.semantic&&!n.source&&!n.node){const e=Tk.indexOf(n.semantic);if(-1!==e)return delete i[r],Ck[e]}}return e.currentIdentifier},Uk=e=>{for(const t in e.materials)Wk.LoadMaterialAsync(e,t,(()=>{}),(()=>{}))};class Gk{static CreateRuntime(e,t,i){const r={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&&Pk(e.extensions,"extensions",r),e.extensionsUsed&&Pk(e.extensionsUsed,"extensionsUsed",r),e.buffers&&((e,t)=>{for(const i in e){const r=e[i];t.buffers[i]=r,t.buffersCount++}})(e.buffers,r),e.bufferViews&&Pk(e.bufferViews,"bufferViews",r),e.accessors&&Pk(e.accessors,"accessors",r),e.meshes&&Pk(e.meshes,"meshes",r),e.lights&&Pk(e.lights,"lights",r),e.cameras&&Pk(e.cameras,"cameras",r),e.nodes&&Pk(e.nodes,"nodes",r),e.images&&Pk(e.images,"images",r),e.textures&&Pk(e.textures,"textures",r),e.shaders&&((e,t)=>{for(const i in e){const r=e[i];t.shaders[i]=r,t.shaderscount++}})(e.shaders,r),e.programs&&Pk(e.programs,"programs",r),e.samplers&&Pk(e.samplers,"samplers",r),e.techniques&&Pk(e.techniques,"techniques",r),e.materials&&Pk(e.materials,"materials",r),e.animations&&Pk(e.animations,"animations",r),e.skins&&Pk(e.skins,"skins",r),e.scenes&&(r.scenes=e.scenes),e.scene&&e.scenes&&(r.currentScene=e.scenes[e.scene]),r}static LoadBufferAsync(e,t,i,r,s){const n=e.buffers[t];Ue.S0.IsBase64(n.uri)?setTimeout((()=>i(new Uint8Array(Ue.S0.DecodeBase64(n.uri))))):Ue.S0.LoadFile(e.rootUrl+n.uri,(e=>i(new Uint8Array(e))),s,void 0,!0,(e=>{e&&r(e.status+" "+e.statusText)}))}static LoadTextureBufferAsync(e,t,i,r){const s=e.textures[t];if(!s||!s.source)return void r("");if(s.babylonTexture)return void i(null);const n=e.images[s.source];Ue.S0.IsBase64(n.uri)?setTimeout((()=>i(new Uint8Array(Ue.S0.DecodeBase64(n.uri))))):Ue.S0.LoadFile(e.rootUrl+n.uri,(e=>i(new Uint8Array(e))),void 0,void 0,!0,(e=>{e&&r(e.status+" "+e.statusText)}))}static CreateTextureAsync(e,t,i,r){const s=e.textures[t];if(s.babylonTexture)return void r(s.babylonTexture);const n=e.samplers[s.sampler],o=n.minFilter===fk.NEAREST_MIPMAP_NEAREST||n.minFilter===fk.NEAREST_MIPMAP_LINEAR||n.minFilter===fk.LINEAR_MIPMAP_NEAREST||n.minFilter===fk.LINEAR_MIPMAP_LINEAR,a=vi.g.BILINEAR_SAMPLINGMODE,l=null==i?new Blob:new Blob([i]),h=URL.createObjectURL(l),c=()=>URL.revokeObjectURL(h),u=new vi.g(h,e.scene,!o,!0,a,c,c);void 0!==n.wrapS&&(u.wrapU=bk.GetWrapMode(n.wrapS)),void 0!==n.wrapT&&(u.wrapV=bk.GetWrapMode(n.wrapT)),u.name=t,s.babylonTexture=u,r(u)}static LoadShaderStringAsync(e,t,i,r){const s=e.shaders[t];if(Ue.S0.IsBase64(s.uri)){const e=atob(s.uri.split(",")[1]);i&&i(e)}else Ue.S0.LoadFile(e.rootUrl+s.uri,i,void 0,void 0,!1,(e=>{e&&r&&r(e.status+" "+e.statusText)}))}static LoadMaterialAsync(e,t,i,r){const s=e.materials[t];if(!s.technique)return void(r&&r("No technique found."));const n=e.techniques[s.technique];if(!n){e.scene._blockEntityCollection=!!e.assetContainer;const r=new Un(t,e.scene);return r._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,r.diffuseColor=new H.v9(.5,.5,.5),r.sideOrientation=Vt.CounterClockWiseSideOrientation,void i(r)}const o=e.programs[n.program],a=n.states,l=Cl.M.ShadersStore[o.vertexShader+"VertexShader"],h=Cl.M.ShadersStore[o.fragmentShader+"PixelShader"];let c="",u="";const d=new Sk(l),f=new Sk(h),p={},_=[],m=[],g=[];for(const e in n.uniforms){const t=n.uniforms[e],i=n.parameters[t];if(p[e]=i,!i.semantic||i.node||i.source)i.type===uk.SAMPLER_2D?g.push(e):_.push(e);else{const t=Tk.indexOf(i.semantic);-1!==t?(_.push(Ck[t]),delete p[e]):_.push(e)}}for(const e in n.attributes){const t=n.attributes[e],i=n.parameters[t];if(i.semantic){const e=Rk(i);e&&m.push(e)}}for(;!d.isEnd()&&d.getNextToken();){if(d.currentToken!==gk.IDENTIFIER){c+=d.currentString;continue}let e=!1;for(const t in n.attributes){const i=n.attributes[t],r=n.parameters[i];if(d.currentIdentifier===t&&r.semantic){c+=Rk(r),e=!0;break}}e||(c+=kk(d,n,p))}for(;!f.isEnd()&&f.getNextToken();)f.currentToken===gk.IDENTIFIER?u+=kk(f,n,p):u+=f.currentString;const v={vertex:o.vertexShader+t,fragment:o.fragmentShader+t},x={attributes:m,uniforms:_,samplers:g,needAlphaBlending:a&&a.enable&&-1!==a.enable.indexOf(3042)};Cl.M.ShadersStore[o.vertexShader+t+"VertexShader"]=c,Cl.M.ShadersStore[o.fragmentShader+t+"PixelShader"]=u;const b=new xo(t,e.scene,v,x);if(b.onError=((e,t,i)=>(r,s)=>{t.dispose(!0),i("Cannot compile program named "+e.name+". Error: "+s+". Default material will be applied")})(o,b,r),b.onCompiled=((e,t,i,r,s,n)=>o=>{((e,t,i,r,s)=>{const n=r.values||i.parameters,o=i.uniforms;for(const i in s){const a=s[i],l=a.type;let h=n[o[i]];if(void 0===h&&(h=a.value),!h)continue;const c=e=>i=>{a.value&&e&&(t.setTexture(e,i),delete s[e])};l===uk.SAMPLER_2D?Wk.LoadTextureAsync(e,r.values?h:a.value,c(i),(()=>c(null))):a.value&&bk.SetUniform(t,i,r.values?h:a.value,l)&&delete s[i]}})(e,t,i,r,s),t.onBind=o=>{((e,t,i,r,s,n,o)=>{const a=n.values||s.parameters;for(const o in i){const l=i[o],h=l.type;if(h===uk.FLOAT_MAT2||h===uk.FLOAT_MAT3||h===uk.FLOAT_MAT4)if(!l.semantic||l.source||l.node){if(l.semantic&&(l.source||l.node)){let e=t.scene.getNodeByName(l.source||l.node||"");if(null===e&&(e=t.scene.getNodeById(l.source||l.node||"")),null===e)continue;bk.SetMatrix(t.scene,e,l,o,r.getEffect())}}else bk.SetMatrix(t.scene,e,l,o,r.getEffect());else{const e=a[s.uniforms[o]];if(!e)continue;if(h===uk.SAMPLER_2D){const i=t.textures[n.values?e:l.value].babylonTexture;if(null==i)continue;r.getEffect().setTexture(o,i)}else bk.SetUniform(r.getEffect(),o,e,h)}}o(r)})(o,e,s,t,i,r,n)}})(e,b,n,s,p,i),b.sideOrientation=Vt.CounterClockWiseSideOrientation,a&&a.functions){const e=a.functions;e.cullFace&&e.cullFace[0]!==_k.BACK&&(b.backFaceCulling=!1);const t=e.blendFuncSeparate;t&&(t[0]===mk.SRC_ALPHA&&t[1]===mk.ONE_MINUS_SRC_ALPHA&&t[2]===mk.ONE&&t[3]===mk.ONE?b.alphaMode=Il.ALPHA_COMBINE:t[0]===mk.ONE&&t[1]===mk.ONE&&t[2]===mk.ZERO&&t[3]===mk.ONE?b.alphaMode=Il.ALPHA_ONEONE:t[0]===mk.SRC_ALPHA&&t[1]===mk.ONE&&t[2]===mk.ZERO&&t[3]===mk.ONE?b.alphaMode=Il.ALPHA_ADD:t[0]===mk.ZERO&&t[1]===mk.ONE_MINUS_SRC_COLOR&&t[2]===mk.ONE&&t[3]===mk.ONE?b.alphaMode=Il.ALPHA_SUBTRACT:t[0]===mk.DST_COLOR&&t[1]===mk.ZERO&&t[2]===mk.ONE&&t[3]===mk.ONE?b.alphaMode=Il.ALPHA_MULTIPLY:t[0]===mk.SRC_ALPHA&&t[1]===mk.ONE_MINUS_SRC_COLOR&&t[2]===mk.ONE&&t[3]===mk.ONE&&(b.alphaMode=Il.ALPHA_MAXIMIZED))}}}class zk{static RegisterExtension(e){zk.Extensions[e.name]?Ue.S0.Error('Tool with the same name "'+e.name+'" already exists'):zk.Extensions[e.name]=e}dispose(){}_importMeshAsync(e,t,i,r,s,n,o,a){return t.useRightHandedSystem=!0,Wk.LoadRuntimeAsync(t,i,r,(t=>{t.assetContainer=s,t.importOnlyMeshes=!0,""===e?t.importMeshesNames=[]:"string"==typeof e?t.importMeshesNames=[e]:!e||e instanceof Array?(t.importMeshesNames=[],Ue.S0.Warn("Argument meshesNames must be of type string or string[]")):t.importMeshesNames=[e],this._createNodes(t);const i=[],r=[];for(const e in t.nodes){const r=t.nodes[e];r.babylonNode instanceof Nt&&i.push(r.babylonNode)}for(const e in t.skins){const i=t.skins[e];i.babylonSkeleton instanceof Ti&&r.push(i.babylonSkeleton)}this._loadBuffersAsync(t,(()=>{this._loadShadersAsync(t,(()=>{Uk(t),Vk(t),!xk.IncrementalLoading&&n&&n(i,r)}))})),xk.IncrementalLoading&&n&&n(i,r)}),a),!0}importMeshAsync(e,t,i,r,s,n){return new Promise(((o,a)=>{this._importMeshAsync(e,t,r,s,i,((e,t)=>{o({meshes:e,particleSystems:[],skeletons:t,animationGroups:[],lights:[],transformNodes:[],geometries:[],spriteManagers:[]})}),n,(e=>{a(new Error(e))}))}))}_loadAsync(e,t,i,r,s,n){e.useRightHandedSystem=!0,Wk.LoadRuntimeAsync(e,t,i,(e=>{Wk.LoadRuntimeExtensionsAsync(e,(()=>{this._createNodes(e),this._loadBuffersAsync(e,(()=>{this._loadShadersAsync(e,(()=>{Uk(e),Vk(e),xk.IncrementalLoading||r()}))})),xk.IncrementalLoading&&r()}),n)}),n)}loadAsync(e,t,i,r){return new Promise(((s,n)=>{this._loadAsync(e,t,i,(()=>{s()}),r,(e=>{n(new Error(e))}))}))}_loadShadersAsync(e,t){let i=!1;const r=(i,r)=>{Wk.LoadShaderStringAsync(e,i,(s=>{s instanceof ArrayBuffer||(e.loadedShaderCount++,s&&(Cl.M.ShadersStore[i+(r.type===ck.VERTEX?"VertexShader":"PixelShader")]=s),e.loadedShaderCount===e.shaderscount&&t())}),(()=>{Ue.S0.Error("Error when loading shader program named "+i+" located at "+r.uri)}))};for(const t in e.shaders){i=!0;const s=e.shaders[t];s?r.bind(this,t,s)():Ue.S0.Error("No shader named: "+t)}i||t()}_loadBuffersAsync(e,t){let i=!1;const r=(i,r)=>{Wk.LoadBufferAsync(e,i,(s=>{e.loadedBufferCount++,s&&(s.byteLength!=e.buffers[i].byteLength&&Ue.S0.Error("Buffer named "+i+" is length "+s.byteLength+". Expected: "+r.byteLength),e.loadedBufferViews[i]=s),e.loadedBufferCount===e.buffersCount&&t()}),(()=>{Ue.S0.Error("Error when loading buffer named "+i+" located at "+r.uri)}))};for(const t in e.buffers){i=!0;const s=e.buffers[t];s?r.bind(this,t,s)():Ue.S0.Error("No buffer named: "+t)}i||t()}_createNodes(e){let t=e.currentScene;if(t)for(let i=0;in.loadRuntimeAsync(e,t,i,r,s)),(()=>{setTimeout((()=>{r&&r(Gk.CreateRuntime(t.json,e,i))}))}))}static LoadRuntimeExtensionsAsync(e,t,i){Wk._ApplyExtensions((r=>r.loadRuntimeExtensionsAsync(e,t,i)),(()=>{setTimeout((()=>{t()}))}))}static LoadBufferAsync(e,t,i,r,s){Wk._ApplyExtensions((n=>n.loadBufferAsync(e,t,i,r,s)),(()=>{Gk.LoadBufferAsync(e,t,i,r,s)}))}static LoadTextureAsync(e,t,i,r){Wk._LoadTextureBufferAsync(e,t,(s=>{s&&Wk._CreateTextureAsync(e,t,s,i,r)}),r)}static LoadShaderStringAsync(e,t,i,r){Wk._ApplyExtensions((s=>s.loadShaderStringAsync(e,t,i,r)),(()=>{Gk.LoadShaderStringAsync(e,t,i,r)}))}static LoadMaterialAsync(e,t,i,r){Wk._ApplyExtensions((s=>s.loadMaterialAsync(e,t,i,r)),(()=>{Gk.LoadMaterialAsync(e,t,i,r)}))}static _LoadTextureBufferAsync(e,t,i,r){Wk._ApplyExtensions((s=>s.loadTextureBufferAsync(e,t,i,r)),(()=>{Gk.LoadTextureBufferAsync(e,t,i,r)}))}static _CreateTextureAsync(e,t,i,r,s){Wk._ApplyExtensions((n=>n.createTextureAsync(e,t,i,r,s)),(()=>{Gk.CreateTextureAsync(e,t,i,r)}))}static _ApplyExtensions(e,t){for(const t in zk.Extensions)if(e(zk.Extensions[t]))return;t()}}function Hk(e,t,i,r){return W.Pq.FromArray(t,i).scaleInPlace(r)}xk._CreateGLTF1Loader=()=>new zk,zk.RegisterExtension(new class extends Wk{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,i,r){const s=t.json.extensionsUsed;return!(!s||-1===s.indexOf(this.name)||!t.bin||(this._bin=t.bin,r(Gk.CreateRuntime(t.json,e,i)),0))}loadBufferAsync(e,t,i,r){return-1!==e.extensionsUsed.indexOf(this.name)&&"binary_glTF"===t&&(this._bin.readAsync(0,this._bin.byteLength).then(i,(e=>r(e.message))),!0)}loadTextureBufferAsync(e,t,i){const r=e.textures[t],s=e.images[r.source];if(!s.extensions||!(this.name in s.extensions))return!1;const n=s.extensions[this.name],o=e.bufferViews[n.bufferView];return i(bk.GetBufferFromBufferView(e,o,0,o.byteLength,hk.UNSIGNED_BYTE)),!0}loadShaderStringAsync(e,t,i){const r=e.shaders[t];if(!r.extensions||!(this.name in r.extensions))return!1;const s=r.extensions[this.name],n=e.bufferViews[s.bufferView],o=bk.GetBufferFromBufferView(e,n,0,n.byteLength,hk.UNSIGNED_BYTE);return setTimeout((()=>{const e=bk.DecodeBufferToText(o);i(e)})),!0}}),zk.RegisterExtension(new class extends Wk{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 t in i){const r=i[t];switch(r.type){case"ambient":{const t=new Lo(r.name,new W.Pq(0,1,0),e.scene),i=r.ambient;i&&(t.diffuse=H.v9.FromArray(i.color||[1,1,1]));break}case"point":{const t=new wx(r.name,new W.Pq(10,10,10),e.scene),i=r.point;i&&(t.diffuse=H.v9.FromArray(i.color||[1,1,1]));break}case"directional":{const t=new hm(r.name,new W.Pq(0,-1,0),e.scene),i=r.directional;i&&(t.diffuse=H.v9.FromArray(i.color||[1,1,1]));break}case"spot":{const t=r.spot;t&&(new dm(r.name,new W.Pq(0,10,0),new W.Pq(0,-1,0),t.fallOffAngle||Math.PI,t.fallOffExponent||0,e.scene).diffuse=H.v9.FromArray(t.color||[1,1,1]));break}default:Ue.S0.Warn('GLTF Material Common extension: light type "'+r.type+"” not supported")}}return!1}loadMaterialAsync(e,t,i,r){const s=e.materials[t];if(!s||!s.extensions)return!1;const n=s.extensions[this.name];if(!n)return!1;const o=new Un(t,e.scene);return o.sideOrientation=Vt.CounterClockWiseSideOrientation,"CONSTANT"===n.technique&&(o.disableLighting=!0),o.backFaceCulling=void 0!==n.doubleSided&&!n.doubleSided,o.alpha=void 0===n.values.transparency?1:n.values.transparency,o.specularPower=void 0===n.values.shininess?0:n.values.shininess,"string"==typeof n.values.ambient?this._loadTexture(e,n.values.ambient,o,"ambientTexture",r):o.ambientColor=H.v9.FromArray(n.values.ambient||[0,0,0]),"string"==typeof n.values.diffuse?this._loadTexture(e,n.values.diffuse,o,"diffuseTexture",r):o.diffuseColor=H.v9.FromArray(n.values.diffuse||[0,0,0]),"string"==typeof n.values.emission?this._loadTexture(e,n.values.emission,o,"emissiveTexture",r):o.emissiveColor=H.v9.FromArray(n.values.emission||[0,0,0]),"string"==typeof n.values.specular?this._loadTexture(e,n.values.specular,o,"specularTexture",r):o.specularColor=H.v9.FromArray(n.values.specular||[0,0,0]),!0}_loadTexture(e,t,i,r,s){Gk.LoadTextureBufferAsync(e,t,(s=>{Gk.CreateTextureAsync(e,t,s,(e=>i[r]=e))}),s)}});class Xk{constructor(e,t,i,r){this.type=e,this.name=t,this.getValue=i,this.getStride=r}_buildAnimation(e,t,i){const r=new pe.X5(e,this.name,t,this.type);return r.setKeys(i),r}}class qk extends Xk{buildAnimations(e,t,i,r,s){s(e._babylonTransformNode,this._buildAnimation(t,i,r))}}const Yk={translation:[new qk(pe.X5.ANIMATIONTYPE_VECTOR3,"position",Hk,(()=>3))],rotation:[new qk(pe.X5.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",(function(e,t,i,r){return W.PT.FromArray(t,i).scaleInPlace(r)}),(()=>4))],scale:[new qk(pe.X5.ANIMATIONTYPE_VECTOR3,"scaling",Hk,(()=>3))],weights:[new class extends Xk{buildAnimations(e,t,i,r,s){if(e._numMorphTargets)for(let n=0;n({frame:e.frame,inTangent:e.inTangent?e.inTangent[n]:void 0,value:e.value[n],outTangent:e.outTangent?e.outTangent[n]:void 0,interpolation:e.interpolation})))),e._primitiveBabylonMeshes)for(const t of e._primitiveBabylonMeshes)if(t.morphTargetManager){const e=t.morphTargetManager.getTarget(n),i=o.clone();e.animations.push(i),s(e,i)}}}}(pe.X5.ANIMATIONTYPE_FLOAT,"influence",(function(e,t,i,r){const s=new Array(e._numMorphTargets);for(let e=0;ee._numMorphTargets))]},Kk=new Map,jk=Kk;function $k(e,t,i){Qk(e)&&Z.V.Warn(`Extension with the name '${e}' already exists`),Kk.set(e,{isGLTFExtension:t,factory:i})}function Qk(e){return Kk.delete(e)}function Zk(...e){const t=e=>e&&"object"==typeof e;return e.reduce(((e,i)=>(Object.keys(i).forEach((r=>{const s=e[r],n=i[r];Array.isArray(s)&&Array.isArray(n)?e[r]=s.concat(...n):t(s)&&t(n)?e[r]=Zk(s,n):e[r]=n})),e)),{})}class Jk{static Get(e,t,i){if(!t||null==i||!t[i])throw new Error(`${e}: Failed to find index (${i})`);return t[i]}static TryGet(e,t){return e&&null!=t&&e[t]?e[t]:null}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,r,s,n,o=""){return Promise.resolve().then((()=>{this._babylonScene=t,this._assetContainer=i,this._loadData(r);let n=null;if(e){const t={};if(this._gltf.nodes)for(const e of this._gltf.nodes)e.name&&(t[e.name]=e.index);n=(e instanceof Array?e:[e]).map((e=>{const i=t[e];if(void 0===i)throw new Error(`Failed to find node '${e}'`);return i}))}return this._loadAsync(s,o,n,(()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]})))}))}loadAsync(e,t,i,r,s=""){return Promise.resolve().then((()=>(this._babylonScene=e,this._loadData(t),this._loadAsync(i,s,null,(()=>{})))))}_loadAsync(e,t,i,r){return Promise.resolve().then((async()=>{this._rootUrl=e,this._uniqueRootUrl=!e.startsWith("file:")&&t?e:`${e}${Date.now()}/`,this._fileName=t,this._allMaterialsDirtyRequired=!1,await this._loadExtensionsAsync();const s=`${lk[lk.LOADING]} => ${lk[lk.READY]}`,n=`${lk[lk.LOADING]} => ${lk[lk.COMPLETE]}`;this._parent._startPerformanceCounter(s),this._parent._startPerformanceCounter(n),this._parent._setState(lk.LOADING),this._extensionsOnLoading();const o=new Array,a=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials)if(i)o.push(this.loadSceneAsync("/nodes",{nodes:i,index:-1}));else if(null!=this._gltf.scene||this._gltf.scenes&&this._gltf.scenes[0]){const e=Jk.Get("/scene",this._gltf.scenes,this._gltf.scene||0);o.push(this.loadSceneAsync(`/scenes/${e.index}`,e))}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let e=0;e{})))}return this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=a:this._babylonScene._forceBlockMaterialDirtyMechanism(a),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(lk.READY),this._startAnimations(),r()))).then((e=>(this._parent._endPerformanceCounter(s),Ue.S0.SetImmediate((()=>{this._disposed||Promise.all(this._completePromises).then((()=>{this._parent._endPerformanceCounter(n),this._parent._setState(lk.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()}),(e=>{this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()}))})),e)))})).catch((e=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()),e}))}_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)&&Z.V.Warn(`Binary buffer length (${i.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else Z.V.Warn("Unexpected BIN chunk")}}_setupData(){if(Jk.Assign(this._gltf.accessors),Jk.Assign(this._gltf.animations),Jk.Assign(this._gltf.buffers),Jk.Assign(this._gltf.bufferViews),Jk.Assign(this._gltf.cameras),Jk.Assign(this._gltf.images),Jk.Assign(this._gltf.materials),Jk.Assign(this._gltf.meshes),Jk.Assign(this._gltf.nodes),Jk.Assign(this._gltf.samplers),Jk.Assign(this._gltf.scenes),Jk.Assign(this._gltf.skins),Jk.Assign(this._gltf.textures),this._gltf.nodes){const e={};for(const t of this._gltf.nodes)if(t.children)for(const i of t.children)e[i]=t.index;const t=this._createRootNode();for(const i of this._gltf.nodes){const r=e[i.index];i.parent=void 0===r?t:this._gltf.nodes[r]}}}async _loadExtensionsAsync(){const e=[];if(jk.forEach(((t,i)=>{!1===this.parent.extensionOptions[i]?.enabled?t.isGLTFExtension&&this.isExtensionUsed(i)&&Z.V.Warn(`Extension ${i} is used but has been explicitly disabled.`):t.isGLTFExtension&&!this.isExtensionUsed(i)||e.push((async()=>{const e=await t.factory(this);return e.name!==i&&Z.V.Warn(`The name of the glTF loader extension instance does not match the registered name: ${e.name} !== ${i}`),this._parent.onExtensionLoadedObservable.notifyObservers(e),e})())})),this._extensions.push(...await Promise.all(e)),this._extensions.sort(((e,t)=>(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE))),this._parent.onExtensionLoadedObservable.clear(),this._gltf.extensionsRequired)for(const e of this._gltf.extensionsRequired)if(!this._extensions.some((t=>t.name===e&&t.enabled))){if(!1===this.parent.extensionOptions[e]?.enabled)throw new Error(`Required extension ${e} is disabled`);throw new Error(`Required extension ${e} is not available`)}}_createRootNode(){if(void 0!==this._parent.customRootNode)return this._rootBabylonMesh=this._parent.customRootNode,{_babylonTransformNode:null===this._rootBabylonMesh?void 0:this._rootBabylonMesh,index:-1};this._babylonScene._blockEntityCollection=!!this._assetContainer;const e=new Yt("__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 ok.AUTO:this._babylonScene.useRightHandedSystem||(t.rotation=[0,1,0,0],t.scale=[1,1,-1],eU._LoadTransform(t,this._rootBabylonMesh));break;case ok.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 r=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const i of t.nodes){const t=Jk.Get(`${e}/nodes/${i}`,this._gltf.nodes,i);r.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=this._rootBabylonMesh})))}for(const e of this._postSceneLoadActions)e();return r.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(r).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,(t=>{const i=t.geometry;i&&-1===e.indexOf(i)&&e.push(i)}));return e}_getMeshes(){const e=[];this._rootBabylonMesh instanceof Nt&&e.push(this._rootBabylonMesh);const t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,(t=>{e.push(t)}));return e}_getTransformNodes(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)i._babylonTransformNode&&"TransformNode"===i._babylonTransformNode.getClassName()&&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 ak.NONE:break;case ak.FIRST:{const e=this._getAnimationGroups();0!==e.length&&e[0].start(!0);break}case ak.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:return void Z.V.Error(`Invalid animation start mode (${this._parent.animationStartMode})`)}}loadNodeAsync(e,t,i=(()=>{})){const r=this._extensionsLoadNodeAsync(e,t,i);if(r)return r;if(t._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const s=new Array;this.logOpen(`${e} ${t.name||""}`);const n=r=>{if(eU.AddPointerMetadata(r,e),eU._LoadTransform(t,r),null!=t.camera){const i=Jk.Get(`${e}/camera`,this._gltf.cameras,t.camera);s.push(this.loadCameraAsync(`/cameras/${i.index}`,i,(e=>{e.parent=r})))}if(t.children)for(const i of t.children){const t=Jk.Get(`${e}/children/${i}`,this._gltf.nodes,i);s.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=r})))}i(r)},o=null!=t.mesh,a=this._parent.loadSkins&&null!=t.skin;if(!o||a){const e=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new Pt(e,this._babylonScene);i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,null==t.mesh?t._babylonTransformNode=i:t._babylonTransformNodeForSkin=i,n(i)}if(o)if(a){const i=Jk.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);s.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,(i=>{const r=t._babylonTransformNodeForSkin;i.metadata=Zk(r.metadata,i.metadata||{});const n=Jk.Get(`${e}/skin`,this._gltf.skins,t.skin);s.push(this._loadSkinAsync(`/skins/${n.index}`,t,n,(e=>{this._forEachPrimitive(t,(t=>{t.skeleton=e})),this._postSceneLoadActions.push((()=>{if(null!=n.skeleton){const e=Jk.Get(`/skins/${n.index}/skeleton`,this._gltf.nodes,n.skeleton).parent;t.index===e.index?i.parent=r.parent:i.parent=e._babylonTransformNode}else i.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:r,skinnedNode:i})}))})))})))}else{const i=Jk.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);s.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,n))}return this.logClose(),Promise.all(s).then((()=>(this._forEachPrimitive(t,(e=>{e.geometry&&e.geometry.useBoundingInfoFromGeometry?e._updateBoundingInfo():e.refreshBoundingInfo(!0,!0)})),t._babylonTransformNode)))}_loadMeshAsync(e,t,i,r){const s=i.primitives;if(!s||!s.length)throw new Error(`${e}: Primitives are missing`);null==s[0].index&&Jk.Assign(s);const n=new Array;this.logOpen(`${e} ${i.name||""}`);const o=t.name||`node${t.index}`;if(1===s.length){const r=i.primitives[0];n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${r.index}`,o,t,i,r,(e=>{t._babylonTransformNode=e,t._primitiveBabylonMeshes=[e]})))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new Pt(o,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(const r of s)n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${r.index}`,`${o}_primitive${r.index}`,t,i,r,(e=>{e.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(e)})))}return r(t._babylonTransformNode),this.logClose(),Promise.all(n).then((()=>t._babylonTransformNode))}_loadMeshPrimitiveAsync(e,t,i,r,s,n){const o=this._extensionsLoadMeshPrimitiveAsync(e,t,i,r,s,n);if(o)return o;this.logOpen(`${e}`);const a=0===this._disableInstancedMesh&&this._parent.createInstances&&null==i.skin&&!r.primitives[0].targets;let l,h;if(a&&s._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,l=s._instanceData.babylonSourceMesh.createInstance(t),l._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,h=s._instanceData.promise;else{const n=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new Yt(t,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,o.sideOrientation=this._babylonScene.useRightHandedSystem?Vt.CounterClockWiseSideOrientation:Vt.ClockWiseSideOrientation,this._createMorphTargets(e,i,r,s,o),n.push(this._loadVertexDataAsync(e,s,o).then((t=>this._loadMorphTargetsAsync(e,s,o,t).then((()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,t.applyToMesh(o),t._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})))));const c=eU._GetDrawMode(e,s.mode);if(null==s.material){let e=this._defaultBabylonMaterialData[c];e||(e=this._createDefaultMaterial("__GLTFLoader._default",c),this._parent.onMaterialLoadedObservable.notifyObservers(e),this._defaultBabylonMaterialData[c]=e),o.material=e}else if(!this.parent.skipMaterials){const t=Jk.Get(`${e}/material`,this._gltf.materials,s.material);n.push(this._loadMaterialAsync(`/materials/${t.index}`,t,o,c,(e=>{o.material=e})))}h=Promise.all(n),a&&(s._instanceData={babylonSourceMesh:o,promise:h}),l=o}return eU.AddPointerMetadata(l,e),this._parent.onMeshLoadedObservable.notifyObservers(l),n(l),this.logClose(),h.then((()=>l))}_loadVertexDataAsync(e,t,i){const r=this._extensionsLoadVertexDataAsync(e,t,i);if(r)return r;const s=t.attributes;if(!s)throw new Error(`${e}: Attributes are missing`);const n=new Array,o=new yt(i.name,this._babylonScene);if(null==t.indices)i.isUnIndexed=!0;else{const i=Jk.Get(`${e}/indices`,this._gltf.accessors,t.indices);n.push(this._loadIndicesAccessorAsync(`/accessors/${i.index}`,i).then((e=>{o.setIndices(e)})))}const a=(t,r,a)=>{if(null==s[t])return;i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(r)&&i._delayInfo.push(r);const l=Jk.Get(`${e}/attributes/${t}`,this._gltf.accessors,s[t]);n.push(this._loadVertexAccessorAsync(`/accessors/${l.index}`,l,r).then((e=>{if(e.getKind()===st.R.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!i.skeleton&&l.min&&l.max){const e=W.AA.Vector3[0].copyFromFloats(...l.min),t=W.AA.Vector3[1].copyFromFloats(...l.max);if(l.normalized&&5126!==l.componentType){let i=1;switch(l.componentType){case 5120:i=127;break;case 5121:i=255;break;case 5122:i=32767;break;case 5123:i=65535}const r=1/i;e.scaleInPlace(r),t.scaleInPlace(r)}o._boundingInfo=new _t(e,t),o.useBoundingInfoFromGeometry=!0}o.setVerticesBuffer(e,l.count)}))),r==st.R.MatricesIndicesExtraKind&&(i.numBoneInfluencers=8),a&&a(l)};return a("POSITION",st.R.PositionKind),a("NORMAL",st.R.NormalKind),a("TANGENT",st.R.TangentKind),a("TEXCOORD_0",st.R.UVKind),a("TEXCOORD_1",st.R.UV2Kind),a("TEXCOORD_2",st.R.UV3Kind),a("TEXCOORD_3",st.R.UV4Kind),a("TEXCOORD_4",st.R.UV5Kind),a("TEXCOORD_5",st.R.UV6Kind),a("JOINTS_0",st.R.MatricesIndicesKind),a("WEIGHTS_0",st.R.MatricesWeightsKind),a("JOINTS_1",st.R.MatricesIndicesExtraKind),a("WEIGHTS_1",st.R.MatricesWeightsExtraKind),a("COLOR_0",st.R.ColorKind,(e=>{"VEC4"===e.type&&(i.hasVertexAlpha=!0)})),Promise.all(n).then((()=>o))}_createMorphTargets(e,t,i,r,s){if(!r.targets||!this._parent.loadMorphTargets)return;if(null==t._numMorphTargets)t._numMorphTargets=r.targets.length;else if(r.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,s.morphTargetManager=new Gx(this._babylonScene),s.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,s.morphTargetManager.areUpdatesFrozen=!0;for(let e=0;e{n.areUpdatesFrozen=!1}))}_loadMorphTargetVertexDataAsync(e,t,i,r){const s=new Array,n=(r,n,o)=>{if(null==i[r])return;const a=t.getVertexBuffer(n);if(!a)return;const l=Jk.Get(`${e}/${r}`,this._gltf.accessors,i[r]);s.push(this._loadFloatAccessorAsync(`/accessors/${l.index}`,l).then((e=>{o(a,e)})))};return n("POSITION",st.R.PositionKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(t.length,((e,r)=>{i[r]=t[r]+e})),r.setPositions(i)})),n("NORMAL",st.R.NormalKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(i.length,((e,r)=>{i[r]=t[r]+e})),r.setNormals(i)})),n("TANGENT",st.R.TangentKind,((e,t)=>{const i=new Float32Array(t.length/3*4);let s=0;e.forEach(t.length/3*4,((e,r)=>{(r+1)%4!=0&&(i[s]=t[s]+e,s++)})),r.setTangents(i)})),Promise.all(s).then((()=>{}))}static _LoadTransform(e,t){if(null!=e.skin)return;let i=W.Pq.Zero(),r=W.PT.Identity(),s=W.Pq.One();e.matrix?W.uq.FromArray(e.matrix).decompose(s,r,i):(e.translation&&(i=W.Pq.FromArray(e.translation)),e.rotation&&(r=W.PT.FromArray(e.rotation)),e.scale&&(s=W.Pq.FromArray(e.scale))),t.position=i,t.rotationQuaternion=r,t.scaling=s}_loadSkinAsync(e,t,i,r){if(!this._parent.loadSkins)return Promise.resolve();const s=this._extensionsLoadSkinAsync(e,t,i);if(s)return s;if(i._data)return r(i._data.babylonSkeleton),i._data.promise;const n=`skeleton${i.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new Ti(i.name||n,n,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,i,o);const a=this._loadSkinInverseBindMatricesDataAsync(e,i).then((e=>{this._updateBoneMatrices(o,e)}));return i._data={babylonSkeleton:o,promise:a},r(o),a}_loadBones(e,t,i){if(null==t.skeleton||this._parent.alwaysComputeSkeletonRootNode){const i=this._findSkeletonRootNode(`${e}/joints`,t.joints);if(i)if(void 0===t.skeleton)t.skeleton=i.index;else{const r=(e,t)=>{for(;t.parent;t=t.parent)if(t.parent===e)return!0;return!1},s=Jk.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);s===i||r(s,i)||(Z.V.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=i.index)}else Z.V.Warn(`${e}: Failed to find common root`)}const r={};for(const s of t.joints){const n=Jk.Get(`${e}/joints/${s}`,this._gltf.nodes,s);this._loadBone(n,t,i,r)}}_findSkeletonRootNode(e,t){if(0===t.length)return null;const i={};for(const r of t){const t=[];let s=Jk.Get(`${e}/${r}`,this._gltf.nodes,r);for(;-1!==s.index;)t.unshift(s),s=s.parent;i[r]=t}let r=null;for(let e=0;;++e){let s=i[t[0]];if(e>=s.length)return r;const n=s[e];for(let o=1;o=s.length||n!==s[e])return r;r=n}}_loadBone(e,t,i,r){e._isJoint=!0;let s=r[e.index];if(s)return s;let n=null;e.index!==t.skeleton&&(e.parent&&-1!==e.parent.index?n=this._loadBone(e.parent,t,i,r):void 0!==t.skeleton&&Z.V.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));const o=t.joints.indexOf(e.index);return s=new Si.$(e.name||`joint${e.index}`,i,n,this._getNodeMatrix(e),null,null,o),r[e.index]=s,this._postSceneLoadActions.push((()=>{s.linkTransformNode(e._babylonTransformNode)})),s}_loadSkinInverseBindMatricesDataAsync(e,t){if(null==t.inverseBindMatrices)return Promise.resolve(null);const i=Jk.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 e=W.uq.Identity(),r=i._index;t&&-1!==r&&(W.uq.FromArrayToRef(t,16*r,e),e.invertToRef(e));const s=i.getParent();s&&e.multiplyToRef(s.getAbsoluteInverseBindMatrix(),e),i.updateMatrix(e,!1,!1),i._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?W.uq.FromArray(e.matrix):W.uq.Compose(e.scale?W.Pq.FromArray(e.scale):W.Pq.One(),e.rotation?W.PT.FromArray(e.rotation):W.PT.Identity(),e.translation?W.Pq.FromArray(e.translation):W.Pq.Zero())}loadCameraAsync(e,t,i=(()=>{})){const r=this._extensionsLoadCameraAsync(e,t,i);if(r)return r;const s=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const n=new es(t.name||`camera${t.index}`,W.Pq.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 i=t.perspective;if(!i)throw new Error(`${e}: Camera perspective properties are missing`);n.fov=i.yfov,n.minZ=i.znear,n.maxZ=i.zfar||0;break}case"orthographic":if(!t.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);n.mode=rt.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 eU.AddPointerMetadata(n,e),this._parent.onCameraLoadedObservable.notifyObservers(n),i(n),this.logClose(),Promise.all(s).then((()=>n))}_loadAnimationsAsync(){const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let i=0;i{0===e.targetedAnimations.length&&e.dispose()})))}return Promise.all(t).then((()=>{}))}loadAnimationAsync(e,t){return this._extensionsLoadAnimationAsync(e,t)||Promise.resolve().then(i.bind(i,7042)).then((({AnimationGroup:i})=>{this._babylonScene._blockEntityCollection=!!this._assetContainer;const r=new i(t.name||`animation${t.index}`,this._babylonScene);r._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=r;const s=new Array;Jk.Assign(t.channels),Jk.Assign(t.samplers);for(const i of t.channels)s.push(this._loadAnimationChannelAsync(`${e}/channels/${i.index}`,e,t,i,((e,t)=>{e.animations=e.animations||[],e.animations.push(t),r.addTargetedAnimation(t,e)})));return Promise.all(s).then((()=>(r.normalize(0),r)))}))}_loadAnimationChannelAsync(e,t,i,r,s){const n=this._extensionsLoadAnimationChannelAsync(e,t,i,r,s);if(n)return n;if(null==r.target.node)return Promise.resolve();const o=Jk.Get(`${e}/target/node`,this._gltf.nodes,r.target.node),a=r.target.path,l="weights"===a;if(l&&!o._numMorphTargets||!l&&!o._babylonTransformNode)return Promise.resolve();if(!this._parent.loadNodeAnimations&&!l&&!o._isJoint)return Promise.resolve();let h;switch(a){case"translation":h=Yk.translation;break;case"rotation":h=Yk.rotation;break;case"scale":h=Yk.scale;break;case"weights":h=Yk.weights;break;default:throw new Error(`${e}/target/path: Invalid value (${r.target.path})`)}const c={object:o,info:h};return this._loadAnimationChannelFromTargetInfoAsync(e,t,i,r,c,s)}_loadAnimationChannelFromTargetInfoAsync(e,t,i,r,s,n){const o=this.parent.targetFps,a=1/o,l=Jk.Get(`${e}/sampler`,i.samplers,r.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${r.sampler}`,l).then((e=>{let t=0;const l=s.object,h=s.info;for(const s of h){const h=s.getStride(l),c=e.input,u=e.output,d=new Array(c.length);let f=0;switch(e.interpolation){case"STEP":for(let e=0;e0){const e=`${i.name||`animation${i.index}`}_channel${r.index}_${t}`;s.buildAnimations(l,e,o,d,((e,i)=>{++t,n(e,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 r=Jk.Get(`${e}/input`,this._gltf.accessors,t.input),s=Jk.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${r.index}`,r),this._loadFloatAccessorAsync(`/accessors/${s.index}`,s)]).then((([e,t])=>({input:e,interpolation:i,output:t}))),t._data}loadBufferAsync(e,t,i,r){const s=this._extensionsLoadBufferAsync(e,t,i,r);if(s)return s;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((t=>{try{return new Uint8Array(t.buffer,t.byteOffset+i,r)}catch(t){throw new Error(`${e}: ${t.message}`)}}))}loadBufferViewAsync(e,t){const i=this._extensionsLoadBufferViewAsync(e,t);if(i)return i;if(t._data)return t._data;const r=Jk.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${r.index}`,r,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,t,i){if(t._data)return t._data;const r=eU._GetNumComponents(e,t.type),s=r*st.R.GetTypeByteLength(t.componentType),n=r*t.count;if(null==t.bufferView)t._data=Promise.resolve(new i(n));else{const o=Jk.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${o.index}`,o).then((a=>{if(5126!==t.componentType||t.normalized||o.byteStride&&o.byteStride!==s){const e=new i(n);return st.R.ForEach(a,t.byteOffset||0,o.byteStride||s,r,t.componentType,e.length,t.normalized||!1,((t,i)=>{e[i]=t})),e}return eU._GetTypedArray(e,t.componentType,a,t.byteOffset,n)}))}if(t.sparse){const n=t.sparse;t._data=t._data.then((o=>{const a=o,l=Jk.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,n.indices.bufferView),h=Jk.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,n.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${l.index}`,l),this.loadBufferViewAsync(`/bufferViews/${h.index}`,h)]).then((([o,l])=>{const h=eU._GetTypedArray(`${e}/sparse/indices`,n.indices.componentType,o,n.indices.byteOffset,n.count),c=r*n.count;let u;if(5126!==t.componentType||t.normalized){const o=eU._GetTypedArray(`${e}/sparse/values`,t.componentType,l,n.values.byteOffset,c);u=new i(c),st.R.ForEach(o,0,s,r,t.componentType,u.length,t.normalized||!1,((e,t)=>{u[t]=e}))}else u=eU._GetTypedArray(`${e}/sparse/values`,t.componentType,l,n.values.byteOffset,c);let d=0;for(let e=0;eeU._GetTypedArray(e,t.componentType,i,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((e=>new st.h(t,e,!1))),e._babylonBuffer}_loadVertexAccessorAsync(e,t,i){if(t._babylonVertexBuffer?.[i])return t._babylonVertexBuffer[i];t._babylonVertexBuffer||(t._babylonVertexBuffer={});const r=this._babylonScene.getEngine();if(t.sparse||null==t.bufferView)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then((e=>new st.R(r,e,i,!1)));else{const s=Jk.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[i]=this._loadVertexBufferViewAsync(s).then((n=>{const o=eU._GetNumComponents(e,t.type);return new st.R(r,n,i,!1,void 0,s.byteStride,void 0,t.byteOffset,o,t.componentType,t.normalized,!0,void 0,!0)}))}return t._babylonVertexBuffer[i]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const r=new Array;return t&&(t.baseColorFactor?(i.albedoColor=H.v9.FromArray(t.baseColorFactor),i.alpha=t.baseColorFactor[3]):i.albedoColor=H.v9.White(),i.metallic=null==t.metallicFactor?1:t.metallicFactor,i.roughness=null==t.roughnessFactor?1:t.roughnessFactor,t.baseColorTexture&&r.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,t.baseColorTexture,(e=>{e.name=`${i.name} (Base Color)`,i.albedoTexture=e}))),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,t.metallicRoughnessTexture,(e=>{e.name=`${i.name} (Metallic Roughness)`,i.metallicTexture=e}))),i.useMetallnessFromMetallicTextureBlue=!0,i.useRoughnessFromMetallicTextureGreen=!0,i.useRoughnessFromMetallicTextureAlpha=!1)),Promise.all(r).then((()=>{}))}_loadMaterialAsync(e,t,i,r,s=(()=>{})){const n=this._extensionsLoadMaterialAsync(e,t,i,r,s);if(n)return n;t._data=t._data||{};let o=t._data[r];if(!o){this.logOpen(`${e} ${t.name||""}`);const i=this.createMaterial(e,t,r);o={babylonMaterial:i,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,i)},t._data[r]=o,eU.AddPointerMetadata(i,e),this._parent.onMaterialLoadedObservable.notifyObservers(i),this.logClose()}return i&&(o.babylonMeshes.push(i),i.onDisposeObservable.addOnce((()=>{const e=o.babylonMeshes.indexOf(i);-1!==e&&o.babylonMeshes.splice(e,1)}))),s(o.babylonMaterial),o.promise.then((()=>o.babylonMaterial))}_createDefaultMaterial(e,t){this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new zm(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=zm.PBRMATERIAL_OPAQUE,i.metallic=1,i.roughness=1,i}createMaterial(e,t,i){const r=this._extensionsCreateMaterial(e,t,i);if(r)return r;const s=t.name||`material${t.index}`;return this._createDefaultMaterial(s,i)}loadMaterialPropertiesAsync(e,t,i){const r=this._extensionsLoadMaterialPropertiesAsync(e,t,i);if(r)return r;const s=new Array;return s.push(this.loadMaterialBasePropertiesAsync(e,t,i)),t.pbrMetallicRoughness&&s.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,i)),this.loadMaterialAlphaProperties(e,t,i),Promise.all(s).then((()=>{}))}loadMaterialBasePropertiesAsync(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const r=new Array;return i.emissiveColor=t.emissiveFactor?H.v9.FromArray(t.emissiveFactor):new H.v9(0,0,0),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),t.normalTexture&&(t.normalTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/normalTexture`,t.normalTexture,(e=>{e.name=`${i.name} (Normal)`,i.bumpTexture=e}))),i.invertNormalMapX=!this._babylonScene.useRightHandedSystem,i.invertNormalMapY=this._babylonScene.useRightHandedSystem,null!=t.normalTexture.scale&&i.bumpTexture&&(i.bumpTexture.level=t.normalTexture.scale),i.forceIrradianceInFragment=!0),t.occlusionTexture&&(t.occlusionTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,t.occlusionTexture,(e=>{e.name=`${i.name} (Occlusion)`,i.ambientTexture=e}))),i.useAmbientInGrayScale=!0,null!=t.occlusionTexture.strength&&(i.ambientTextureStrength=t.occlusionTexture.strength)),t.emissiveTexture&&r.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,t.emissiveTexture,(e=>{e.name=`${i.name} (Emissive)`,i.emissiveTexture=e}))),Promise.all(r).then((()=>{}))}loadMaterialAlphaProperties(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);switch(t.alphaMode||"OPAQUE"){case"OPAQUE":i.transparencyMode=zm.PBRMATERIAL_OPAQUE,i.alpha=1;break;case"MASK":i.transparencyMode=zm.PBRMATERIAL_ALPHATEST,i.alphaCutOff=null==t.alphaCutoff?.5:t.alphaCutoff,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0);break;case"BLEND":i.transparencyMode=zm.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 r=this._extensionsLoadTextureInfoAsync(e,t,i);if(r)return r;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const s=Jk.Get(`${e}/index`,this._gltf.textures,t.index);s._textureInfo=t;const n=this._loadTextureAsync(`/textures/${t.index}`,s,(r=>{r.coordinatesIndex=t.texCoord||0,eU.AddPointerMetadata(r,e),this._parent.onTextureLoadedObservable.notifyObservers(r),i(r)}));return this.logClose(),n}_loadTextureAsync(e,t,i=(()=>{})){const r=this._extensionsLoadTextureAsync(e,t,i);if(r)return r;this.logOpen(`${e} ${t.name||""}`);const s=null==t.sampler?eU.DefaultSampler:Jk.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),n=Jk.Get(`${e}/source`,this._gltf.images,t.source),o=this._createTextureAsync(e,s,n,i,void 0,!t._textureInfo.nonColorData);return this.logClose(),o}_createTextureAsync(e,t,i,r=(()=>{}),s,n){const o=this._loadSampler(`/samplers/${t.index}`,t),a=new Array,l=new uR;this._babylonScene._blockEntityCollection=!!this._assetContainer;const h={noMipmap:o.noMipMaps,invertY:!1,samplingMode:o.samplingMode,onLoad:()=>{this._disposed||l.resolve()},onError:(t,i)=>{this._disposed||l.reject(new Error(`${e}: ${i&&i.message?i.message:t||"Failed to load texture"}`))},mimeType:i.mimeType,loaderOptions:s,useSRGBBuffer:!!n&&this._parent.useSRGBBuffers},c=new vi.g(null,this._babylonScene,h);return c._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,a.push(l.promise),a.push(this.loadImageAsync(`/images/${i.index}`,i).then((e=>{const t=i.uri||`${this._fileName}#image${i.index}`,r=`data:${this._uniqueRootUrl}${t}`;c.updateURL(r,e);const s=c.getInternalTexture();s&&(s.label=i.name)}))),c.wrapU=o.wrapU,c.wrapV=o.wrapV,r(c),this._parent.useGltfTextureNames&&(c.name=i.name||i.uri||`image${i.index}`),Promise.all(a).then((()=>c))}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:eU._GetTextureSamplingMode(e,t),wrapU:eU._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:eU._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=Jk.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 r=this._extensionsLoadUriAsync(e,t,i);if(r)return r;if(!eU._ValidateUri(i))throw new Error(`${e}: '${i}' is invalid`);if((0,$m.f2)(i)){const t=new Uint8Array((0,$m.rz)(i));return this.log(`${e}: Decoded ${i.substring(0,64)}... (${t.length} bytes)`),Promise.resolve(t)}return this.log(`${e}: Loading ${i}`),this._parent.preprocessUrlAsync(this._rootUrl+i).then((t=>new Promise(((r,s)=>{this._parent._loadFile(this._babylonScene,t,(t=>{this._disposed||(this.log(`${e}: Loaded ${i} (${t.byteLength} bytes)`),r(new Uint8Array(t)))}),!0,(t=>{s(new $m.hX(`${e}: Failed to load '${i}'${t?": "+t.status+" "+t.statusText:""}`,t))}))}))))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};const i=e._internalMetadata=e._internalMetadata||{},r=i.gltf=i.gltf||{};(r.pointers=r.pointers||[]).push(t)}static _GetTextureWrapMode(e,t){switch(t=null==t?10497:t){case 33071:return vi.g.CLAMP_ADDRESSMODE;case 33648:return vi.g.MIRROR_ADDRESSMODE;case 10497:return vi.g.WRAP_ADDRESSMODE;default:return Z.V.Warn(`${e}: Invalid value (${t})`),vi.g.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,t){const i=null==t.magFilter?9729:t.magFilter,r=null==t.minFilter?9987:t.minFilter;if(9729===i)switch(r){case 9728:return vi.g.LINEAR_NEAREST;case 9729:return vi.g.LINEAR_LINEAR;case 9984:return vi.g.LINEAR_NEAREST_MIPNEAREST;case 9985:return vi.g.LINEAR_LINEAR_MIPNEAREST;case 9986:return vi.g.LINEAR_NEAREST_MIPLINEAR;case 9987:return vi.g.LINEAR_LINEAR_MIPLINEAR;default:return Z.V.Warn(`${e}/minFilter: Invalid value (${r})`),vi.g.LINEAR_LINEAR_MIPLINEAR}else switch(9728!==i&&Z.V.Warn(`${e}/magFilter: Invalid value (${i})`),r){case 9728:return vi.g.NEAREST_NEAREST;case 9729:return vi.g.NEAREST_LINEAR;case 9984:return vi.g.NEAREST_NEAREST_MIPNEAREST;case 9985:return vi.g.NEAREST_LINEAR_MIPNEAREST;case 9986:return vi.g.NEAREST_NEAREST_MIPLINEAR;case 9987:return vi.g.NEAREST_LINEAR_MIPLINEAR;default:return Z.V.Warn(`${e}/minFilter: Invalid value (${r})`),vi.g.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,r,s){const n=i.buffer;r=i.byteOffset+(r||0);const o=eU._GetTypedArrayConstructor(`${e}/componentType`,t),a=st.R.GetTypeByteLength(t);return r%a!=0?(Z.V.Warn(`${e}: Copying buffer as byte offset (${r}) is not a multiple of component type byte length (${a})`),new o(n.slice(r,r+s*a),0)):new o(n,r,s)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return Ue.S0.IsBase64(e)||-1===e.indexOf("..")}static _GetDrawMode(e,t){switch(null==t&&(t=4),t){case 0:return Vt.PointListDrawMode;case 1:return Vt.LineListDrawMode;case 2:return Vt.LineLoopDrawMode;case 3:return Vt.LineStripDrawMode;case 4:return Vt.TriangleFillMode;case 5:return Vt.TriangleStripDrawMode;case 6:return Vt.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 r=t._data[i];for(const t of r.babylonMeshes){t.computeWorldMatrix(!0);const i=r.babylonMaterial;e.push(i.forceCompilationAsync(t)),e.push(i.forceCompilationAsync(t,{useInstances:!0})),this._parent.useClipPlane&&(e.push(i.forceCompilationAsync(t,{clipPlane:!0})),e.push(i.forceCompilationAsync(t,{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 t=i.getShadowGenerator();t&&e.push(t.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 r of this._extensions)if(r.enabled){const s=`${r.name}.${t}`,n=e;n._activeLoaderExtensionFunctions=n._activeLoaderExtensionFunctions||{};const o=n._activeLoaderExtensionFunctions;if(!o[s]){o[s]=!0;try{const e=i(r);if(e)return e}finally{delete o[s]}}}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",(r=>r.loadNodeAsync&&r.loadNodeAsync(e,t,i)))}_extensionsLoadCameraAsync(e,t,i){return this._applyExtensions(t,"loadCamera",(r=>r.loadCameraAsync&&r.loadCameraAsync(e,t,i)))}_extensionsLoadVertexDataAsync(e,t,i){return this._applyExtensions(t,"loadVertexData",(r=>r._loadVertexDataAsync&&r._loadVertexDataAsync(e,t,i)))}_extensionsLoadMeshPrimitiveAsync(e,t,i,r,s,n){return this._applyExtensions(s,"loadMeshPrimitive",(o=>o._loadMeshPrimitiveAsync&&o._loadMeshPrimitiveAsync(e,t,i,r,s,n)))}_extensionsLoadMaterialAsync(e,t,i,r,s){return this._applyExtensions(t,"loadMaterial",(n=>n._loadMaterialAsync&&n._loadMaterialAsync(e,t,i,r,s)))}_extensionsCreateMaterial(e,t,i){return this._applyExtensions(t,"createMaterial",(r=>r.createMaterial&&r.createMaterial(e,t,i)))}_extensionsLoadMaterialPropertiesAsync(e,t,i){return this._applyExtensions(t,"loadMaterialProperties",(r=>r.loadMaterialPropertiesAsync&&r.loadMaterialPropertiesAsync(e,t,i)))}_extensionsLoadTextureInfoAsync(e,t,i){return this._applyExtensions(t,"loadTextureInfo",(r=>r.loadTextureInfoAsync&&r.loadTextureInfoAsync(e,t,i)))}_extensionsLoadTextureAsync(e,t,i){return this._applyExtensions(t,"loadTexture",(r=>r._loadTextureAsync&&r._loadTextureAsync(e,t,i)))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",(i=>i.loadAnimationAsync&&i.loadAnimationAsync(e,t)))}_extensionsLoadAnimationChannelAsync(e,t,i,r,s){return this._applyExtensions(i,"loadAnimationChannel",(n=>n._loadAnimationChannelAsync&&n._loadAnimationChannelAsync(e,t,i,r,s)))}_extensionsLoadSkinAsync(e,t,i){return this._applyExtensions(i,"loadSkin",(r=>r._loadSkinAsync&&r._loadSkinAsync(e,t,i)))}_extensionsLoadUriAsync(e,t,i){return this._applyExtensions(t,"loadUri",(r=>r._loadUriAsync&&r._loadUriAsync(e,t,i)))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",(i=>i.loadBufferViewAsync&&i.loadBufferViewAsync(e,t)))}_extensionsLoadBufferAsync(e,t,i,r){return this._applyExtensions(t,"loadBuffer",(s=>s.loadBufferAsync&&s.loadBufferAsync(e,t,i,r)))}static LoadExtensionAsync(e,t,i,r){if(!t.extensions)return null;const s=t.extensions[i];return s?r(`${e}/extensions/${i}`,s):null}static LoadExtraAsync(e,t,i,r){if(!t.extras)return null;const s=t.extras[i];return s?r(`${e}/extras/${i}`,s):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&-1!==this._gltf.extensionsUsed.indexOf(e)}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)}}eU.DefaultSampler={index:-1},xk._CreateGLTF2Loader=e=>new eU(e);const tU="EXT_lights_image_based";class iU{constructor(e){this.name=tU,this._loader=e,this.enabled=this._loader.isExtensionUsed(tU)}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 eU.LoadExtensionAsync(e,t,this.name,((i,r)=>{this._loader._allMaterialsDirtyRequired=!0;const s=new Array;s.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${i}`);const n=Jk.Get(`${i}/light`,this._lights,r.light);return s.push(this._loadLightAsync(`/extensions/${this.name}/lights/${r.light}`,n).then((e=>{this._loader.babylonScene.environmentTexture=e}))),this._loader.logClose(),Promise.all(s).then((()=>{}))}))}_loadLightAsync(e,t){if(!t._loaded){const i=new Array;this._loader.logOpen(`${e}`);const r=new Array(t.specularImages.length);for(let s=0;s{r[s][t]=e}))),this._loader.logClose()}}this._loader.logClose(),t._loaded=Promise.all(i).then((()=>{const i=new $b(this._loader.babylonScene,null,t.specularImageSize);if(i.name=t.name||"environment",t._babylonTexture=i,null!=t.intensity&&(i.level=t.intensity),t.rotation){let e=W.PT.FromArray(t.rotation);this._loader.babylonScene.useRightHandedSystem||(e=W.PT.Inverse(e)),W.uq.FromQuaternionToRef(e,i.getReflectionTextureMatrix())}if(!t.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const s=Ks.O.FromArray(t.irradianceCoefficients);s.scaleInPlace(t.intensity),s.convertIrradianceToLambertianRadiance();const n=Ks.Q.FromHarmonics(s),o=(r.length-1)/Math.log2(t.specularImageSize);return i.updateRGBDAsync(r,n,o)}))}return t._loaded.then((()=>t._babylonTexture))}}Qk(tU),$k(tU,!0,(e=>new iU(e)));const rU="EXT_mesh_gpu_instancing";class sU{constructor(e){this.name=rU,this._loader=e,this.enabled=this._loader.isExtensionUsed(rU)}dispose(){this._loader=null}loadNodeAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((e,r)=>{this._loader._disableInstancedMesh++;const s=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,i);if(this._loader._disableInstancedMesh--,!t._primitiveBabylonMeshes)return s;const n=new Array;let o=0;const a=t=>{if(null==r.attributes[t])return void n.push(Promise.resolve(null));const i=Jk.Get(`${e}/attributes/${t}`,this._loader.gltf.accessors,r.attributes[t]);if(n.push(this._loader._loadFloatAccessorAsync(`/accessors/${i.bufferView}`,i)),0===o)o=i.count;else if(o!==i.count)throw new Error(`${e}/attributes: Instance buffer accessors do not have the same count.`)};return a("TRANSLATION"),a("ROTATION"),a("SCALE"),s.then((e=>Promise.all(n).then((([i,r,s])=>{const n=new Float32Array(16*o);W.AA.Vector3[0].copyFromFloats(0,0,0),W.AA.Quaternion[0].copyFromFloats(0,0,0,1),W.AA.Vector3[1].copyFromFloats(1,1,1);for(let e=0;enew sU(e)));const nU="EXT_meshopt_compression";class oU{constructor(e){this.name=nU,this.enabled=e.isExtensionUsed(nU),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,t){return eU.LoadExtensionAsync(e,t,this.name,((i,r)=>{const s=t;if(s._meshOptData)return s._meshOptData;const n=Jk.Get(`${e}/buffer`,this._loader.gltf.buffers,r.buffer);return s._meshOptData=this._loader.loadBufferAsync(`/buffers/${n.index}`,n,r.byteOffset||0,r.byteLength).then((e=>Jy.Default.decodeGltfBufferAsync(e,r.count,r.byteStride,r.mode,r.filter))),s._meshOptData}))}}Qk(nU),$k(nU,!0,(e=>new oU(e)));const aU="EXT_texture_webp";class lU{constructor(e){this.name=aU,this._loader=e,this.enabled=e.isExtensionUsed(aU)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=null==t.sampler?eU.DefaultSampler:Jk.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=Jk.Get(`${r}/source`,this._loader.gltf.images,s.source);return this._loader._createTextureAsync(e,n,o,(e=>{i(e)}),void 0,!t._textureInfo.nonColorData)}))}}Qk(aU),$k(aU,!0,(e=>new lU(e)));const hU="EXT_texture_avif";class cU{constructor(e){this.name=hU,this._loader=e,this.enabled=e.isExtensionUsed(hU)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=null==t.sampler?eU.DefaultSampler:Jk.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=Jk.Get(`${r}/source`,this._loader.gltf.images,s.source);return this._loader._createTextureAsync(e,n,o,(e=>{i(e)}),void 0,!t._textureInfo.nonColorData)}))}}Qk(hU),$k(hU,!0,(e=>new cU(e)));const uU="KHR_draco_mesh_compression";class dU{constructor(e){this.name=uU,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=Zy.DecoderAvailable&&this._loader.isExtensionUsed(uU)}dispose(){delete this.dracoCompression,this._loader=null}_loadVertexDataAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{if(null!=t.mode&&4!==t.mode&&5!==t.mode)throw new Error(`${e}: Unsupported mode ${t.mode}`);const n={},o={},a=(e,r)=>{const a=s.attributes[e];if(null!=a&&(i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(r)&&i._delayInfo.push(r),n[r]=a,this.useNormalizedFlagFromAccessor)){const i=Jk.TryGet(this._loader.gltf.accessors,t.attributes[e]);i&&(o[r]=i.normalized||!1)}};a("POSITION",st.R.PositionKind),a("NORMAL",st.R.NormalKind),a("TANGENT",st.R.TangentKind),a("TEXCOORD_0",st.R.UVKind),a("TEXCOORD_1",st.R.UV2Kind),a("TEXCOORD_2",st.R.UV3Kind),a("TEXCOORD_3",st.R.UV4Kind),a("TEXCOORD_4",st.R.UV5Kind),a("TEXCOORD_5",st.R.UV6Kind),a("JOINTS_0",st.R.MatricesIndicesKind),a("WEIGHTS_0",st.R.MatricesWeightsKind),a("COLOR_0",st.R.ColorKind);const l=Jk.Get(r,this._loader.gltf.bufferViews,s.bufferView);return l._dracoBabylonGeometry||(l._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${l.index}`,l).then((t=>(this.dracoCompression||Zy.Default)._decodeMeshToGeometryForGltfAsync(i.name,this._loader.babylonScene,t,n,o).catch((t=>{throw new Error(`${e}: ${t.message}`)}))))),l._dracoBabylonGeometry}))}}Qk(uU),$k(uU,!0,(e=>new dU(e)));const fU="KHR_lights_punctual";class pU{constructor(e){this.name=fU,this._loader=e,this.enabled=this._loader.isExtensionUsed(fU)}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,Jk.Assign(this._lights)}}loadNodeAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>(this._loader._allMaterialsDirtyRequired=!0,this._loader.loadNodeAsync(e,t,(e=>{let t;const n=Jk.Get(r,this._lights,s.light),o=n.name||e.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,n.type){case"directional":{const e=new hm(o,W.Pq.Backward(),this._loader.babylonScene);e.position.setAll(0),t=e;break}case"point":t=new wx(o,W.Pq.Zero(),this._loader.babylonScene);break;case"spot":{const e=new dm(o,W.Pq.Zero(),W.Pq.Backward(),0,1,this._loader.babylonScene);e.angle=2*(n.spot&&n.spot.outerConeAngle||Math.PI/4),e.innerAngle=2*(n.spot&&n.spot.innerConeAngle||0),t=e;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${r}: Invalid light type (${n.type})`)}t._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,n._babylonLight=t,t.falloffType=$t.FALLOFF_GLTF,t.diffuse=n.color?H.v9.FromArray(n.color):H.v9.White(),t.intensity=null==n.intensity?1:n.intensity,t.range=null==n.range?Number.MAX_VALUE:n.range,t.parent=e,this._loader._babylonLights.push(t),eU.AddPointerMetadata(t,r),i(e)})))))}}Qk(fU),$k(fU,!0,(e=>new pU(e)));const _U="KHR_materials_pbrSpecularGlossiness";class mU{constructor(e){this.name=_U,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(_U)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loadSpecularGlossinessPropertiesAsync(r,s,i)),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(n).then((()=>{}))}))}_loadSpecularGlossinessPropertiesAsync(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const r=new Array;return i.metallic=null,i.roughness=null,t.diffuseFactor?(i.albedoColor=H.v9.FromArray(t.diffuseFactor),i.alpha=t.diffuseFactor[3]):i.albedoColor=H.v9.White(),i.reflectivityColor=t.specularFactor?H.v9.FromArray(t.specularFactor):H.v9.White(),i.microSurface=null==t.glossinessFactor?1:t.glossinessFactor,t.diffuseTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,t.diffuseTexture,(e=>{e.name=`${i.name} (Diffuse)`,i.albedoTexture=e}))),t.specularGlossinessTexture&&(r.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,t.specularGlossinessTexture,(e=>{e.name=`${i.name} (Specular Glossiness)`,i.reflectivityTexture=e,i.reflectivityTexture.hasAlpha=!0}))),i.useMicroSurfaceFromReflectivityMapAlpha=!0),Promise.all(r).then((()=>{}))}}Qk(_U),$k(_U,!0,(e=>new mU(e)));const gU="KHR_materials_unlit";class vU{constructor(e){this.name=gU,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(gU)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,(()=>this._loadUnlitPropertiesAsync(e,t,i)))}_loadUnlitPropertiesAsync(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const r=new Array;i.unlit=!0;const s=t.pbrMetallicRoughness;return s&&(s.baseColorFactor?(i.albedoColor=H.v9.FromArray(s.baseColorFactor),i.alpha=s.baseColorFactor[3]):i.albedoColor=H.v9.White(),s.baseColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,s.baseColorTexture,(e=>{e.name=`${i.name} (Base Color)`,i.albedoTexture=e})))),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(r).then((()=>{}))}}Qk(gU),$k(gU,!0,(e=>new vU(e)));const xU="KHR_materials_clearcoat";class bU{constructor(e){this.name=xU,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(xU)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadClearCoatPropertiesAsync(r,s,i)),Promise.all(n).then((()=>{}))}))}_loadClearCoatPropertiesAsync(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const r=new Array;return i.clearCoat.isEnabled=!0,i.clearCoat.useRoughnessFromMainTexture=!1,i.clearCoat.remapF0OnInterfaceChange=!1,null!=t.clearcoatFactor?i.clearCoat.intensity=t.clearcoatFactor:i.clearCoat.intensity=0,t.clearcoatTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,(e=>{e.name=`${i.name} (ClearCoat)`,i.clearCoat.texture=e}))),null!=t.clearcoatRoughnessFactor?i.clearCoat.roughness=t.clearcoatRoughnessFactor:i.clearCoat.roughness=0,t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatRoughnessTexture`,t.clearcoatRoughnessTexture,(e=>{e.name=`${i.name} (ClearCoat Roughness)`,i.clearCoat.textureRoughness=e})))),t.clearcoatNormalTexture&&(t.clearcoatNormalTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatNormalTexture`,t.clearcoatNormalTexture,(e=>{e.name=`${i.name} (ClearCoat Normal)`,i.clearCoat.bumpTexture=e}))),i.invertNormalMapX=!i.getScene().useRightHandedSystem,i.invertNormalMapY=i.getScene().useRightHandedSystem,null!=t.clearcoatNormalTexture.scale&&(i.clearCoat.bumpTexture.level=t.clearcoatNormalTexture.scale)),Promise.all(r).then((()=>{}))}}Qk(xU),$k(xU,!0,(e=>new bU(e)));const SU="KHR_materials_iridescence";class TU{constructor(e){this.name=SU,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(SU)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIridescencePropertiesAsync(r,s,i)),Promise.all(n).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const r=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&&r.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,(e=>{e.name=`${i.name} (Iridescence)`,i.iridescence.texture=e}))),t.iridescenceThicknessTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,(e=>{e.name=`${i.name} (Iridescence Thickness)`,i.iridescence.thicknessTexture=e}))),Promise.all(r).then((()=>{}))}}Qk(SU),$k(SU,!0,(e=>new TU(e)));const CU="KHR_materials_anisotropy";class yU{constructor(e){this.name=CU,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(CU)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIridescencePropertiesAsync(r,s,i)),Promise.all(n).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const r=new Array;return i.anisotropy.isEnabled=!0,i.anisotropy.intensity=t.anisotropyStrength??0,i.anisotropy.angle=t.anisotropyRotation??0,t.anisotropyTexture&&(t.anisotropyTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,(e=>{e.name=`${i.name} (Anisotropy Intensity)`,i.anisotropy.texture=e})))),Promise.all(r).then((()=>{}))}}Qk(CU),$k(CU,!0,(e=>new yU(e)));const EU="KHR_materials_emissive_strength";class PU{constructor(e){this.name=EU,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(EU)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>this._loader.loadMaterialPropertiesAsync(e,t,i).then((()=>{this._loadEmissiveProperties(r,s,i)}))))}_loadEmissiveProperties(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);void 0!==t.emissiveStrength&&(i.emissiveIntensity=t.emissiveStrength)}}Qk(EU),$k(EU,!0,(e=>new PU(e)));const AU="KHR_materials_sheen";class RU{constructor(e){this.name=AU,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(AU)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadSheenPropertiesAsync(r,s,i)),Promise.all(n).then((()=>{}))}))}_loadSheenPropertiesAsync(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const r=new Array;return i.sheen.isEnabled=!0,i.sheen.intensity=1,null!=t.sheenColorFactor?i.sheen.color=H.v9.FromArray(t.sheenColorFactor):i.sheen.color=H.v9.Black(),t.sheenColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/sheenColorTexture`,t.sheenColorTexture,(e=>{e.name=`${i.name} (Sheen Color)`,i.sheen.texture=e}))),void 0!==t.sheenRoughnessFactor?i.sheen.roughness=t.sheenRoughnessFactor:i.sheen.roughness=0,t.sheenRoughnessTexture&&(t.sheenRoughnessTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/sheenRoughnessTexture`,t.sheenRoughnessTexture,(e=>{e.name=`${i.name} (Sheen Roughness)`,i.sheen.textureRoughness=e})))),i.sheen.albedoScaling=!0,i.sheen.useRoughnessFromMainTexture=!1,Promise.all(r).then((()=>{}))}}Qk(AU),$k(AU,!0,(e=>new RU(e)));const IU="KHR_materials_specular";class MU{constructor(e){this.name=IU,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(IU)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadSpecularPropertiesAsync(r,s,i)),Promise.all(n).then((()=>{}))}))}_loadSpecularPropertiesAsync(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const r=new Array;return void 0!==t.specularFactor&&(i.metallicF0Factor=t.specularFactor),void 0!==t.specularColorFactor&&(i.metallicReflectanceColor=H.v9.FromArray(t.specularColorFactor)),t.specularTexture&&(t.specularTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,t.specularTexture,(e=>{e.name=`${i.name} (Specular)`,i.metallicReflectanceTexture=e,i.useOnlyMetallicFromMetallicReflectanceTexture=!0})))),t.specularColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,t.specularColorTexture,(e=>{e.name=`${i.name} (Specular Color)`,i.reflectanceTexture=e}))),Promise.all(r).then((()=>{}))}}Qk(IU),$k(IU,!0,(e=>new MU(e)));const OU="KHR_materials_ior";class DU{constructor(e){this.name=OU,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(OU)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIorPropertiesAsync(r,s,i)),Promise.all(n).then((()=>{}))}))}_loadIorPropertiesAsync(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);return void 0!==t.ior?i.indexOfRefraction=t.ior:i.indexOfRefraction=DU._DEFAULT_IOR,Promise.resolve()}}DU._DEFAULT_IOR=1.5,Qk(OU),$k(OU,!0,(e=>new DU(e)));const wU="KHR_materials_variants";class NU{constructor(e){this.name=wU,this._loader=e,this.enabled=this._loader.isExtensionUsed(wU)}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return NU.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 ${wU} extension`);const r=e=>{const t=i.variants[e];if(t)for(const e of t)e.mesh.material=e.material};if(t instanceof Array)for(const e of t)r(e);else r(t);i.lastSelected=t}selectVariant(e,t){NU.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 ${wU} extension`);for(const e of t.original)e.mesh.material=e.material;t.lastSelected=null}reset(e){NU.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 ${wU} extension`);return t.lastSelected}getLastSelectedVariant(e){return NU.GetLastSelectedVariant(e)}static _GetExtensionMetadata(e){return e?._internalMetadata?.gltf?.[wU]||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,r,s,n){return eU.LoadExtensionAsync(e,s,this.name,((o,a)=>{const l=new Array;return l.push(this._loader._loadMeshPrimitiveAsync(e,t,i,r,s,(t=>{if(n(t),t instanceof Yt){const i=eU._GetDrawMode(e,s.mode),r=this._loader.rootBabylonMesh,n=r?r._internalMetadata=r._internalMetadata||{}:{},h=n.gltf=n.gltf||{},c=h[wU]=h[wU]||{lastSelected:null,original:[],variants:{}};c.original.push({mesh:t,material:t.material});for(let e=0;e{for(let i=0;i{const i=e;let s=null,n=i;do{if(n=n.parent,!n)return;s=NU._GetExtensionMetadata(n)}while(null===s);if(r&&s===NU._GetExtensionMetadata(r)){n._internalMetadata={};for(const e in r._internalMetadata)n._internalMetadata[e]=r._internalMetadata[e];n._internalMetadata.gltf=[];for(const e in r._internalMetadata.gltf)n._internalMetadata.gltf[e]=r._internalMetadata.gltf[e];n._internalMetadata.gltf[wU]={lastSelected:null,original:[],variants:{}};for(const e of s.original)n._internalMetadata.gltf[wU].original.push({mesh:e.mesh,material:e.material});for(const e in s.variants)if(Object.prototype.hasOwnProperty.call(s.variants,e)){n._internalMetadata.gltf[wU].variants[e]=[];for(const t of s.variants[e])n._internalMetadata.gltf[wU].variants[e].push({mesh:t.mesh,material:t.material})}s=n._internalMetadata.gltf[wU]}for(const e of s.original)e.mesh===t&&(e.mesh=i);for(const e of s.variants[o.name])e.mesh===t&&(e.mesh=i)}))}})))}}}))),Promise.all(l).then((([e])=>e))}))}}Qk(wU),$k(wU,!0,(e=>new NU(e)));class FU{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:Il.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,t){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._options={...FU._GetDefaultOptions(),...e},this._scene=t,this._scene._transmissionHelper=this,this.onErrorObservable=new z.cP,this._scene.onDisposeObservable.addOnce((()=>{this.dispose()})),this._parseScene(),this._setupRenderTargets()}updateOptions(e){if(!Object.keys(e).filter((t=>this._options[t]!==e[t])).length)return;const t={...this._options,...e},i=this._options;this._options=t,t.renderSize===i.renderSize&&t.renderTargetTextureType===i.renderTargetTextureType&&t.generateMipmaps===i.generateMipmaps&&this._opaqueRenderTarget?(this._opaqueRenderTarget.samples=t.samples,this._opaqueRenderTarget.lodGenerationScale=t.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=t.lodGenerationOffset):this._setupRenderTargets()}getOpaqueTarget(){return this._opaqueRenderTarget}_shouldRenderAsTransmission(e){return!!e&&!!(e instanceof zm&&e.subSurface.isRefractionEnabled)}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),Ue.S0.SetImmediate((()=>{this._shouldRenderAsTransmission(e.material)?(e.material.refractionTexture=this._opaqueRenderTarget,-1===this._transparentMeshesCache.indexOf(e)&&this._transparentMeshesCache.push(e)):-1===this._opaqueMeshesCache.indexOf(e)&&this._opaqueMeshesCache.push(e)}))}_removeMesh(e){e.onMaterialChangedObservable.remove(this._materialObservers[e.uniqueId]),delete this._materialObservers[e.uniqueId];let t=this._transparentMeshesCache.indexOf(e);-1!==t&&this._transparentMeshesCache.splice(t,1),t=this._opaqueMeshesCache.indexOf(e),-1!==t&&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 zm&&(e.material.subSurface.refractionTexture=this._opaqueRenderTarget),-1!==i?(this._opaqueMeshesCache.splice(i,1),this._transparentMeshesCache.push(e)):-1===t&&this._transparentMeshesCache.push(e)):-1!==t?(this._transparentMeshesCache.splice(t,1),this._opaqueMeshesCache.push(e)):-1===i&&this._opaqueMeshesCache.push(e)}_isRenderTargetValid(){return null!==this._opaqueRenderTarget?.getInternalTexture()}_setupRenderTargets(){let e,t;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new ln.$("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=this._options.clearColor?.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,this._opaqueRenderTarget.onBeforeBindObservable.add((i=>{t=this._scene.environmentIntensity,this._scene.environmentIntensity=1,e=this._scene.imageProcessingConfiguration.applyByPostProcess,this._options.clearColor?i.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(i.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((e=>{this._shouldRenderAsTransmission(e.material)&&(e.material.refractionTexture=this._opaqueRenderTarget)}))}dispose(){this._scene._transmissionHelper=void 0,this._opaqueRenderTarget&&(this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=null),this._transparentMeshesCache=[],this._opaqueMeshesCache=[]}}const LU="KHR_materials_transmission";class BU{constructor(e){this.name=LU,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(LU),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadTransparentPropertiesAsync(r,t,i,s)),Promise.all(n).then((()=>{}))}))}_loadTransparentPropertiesAsync(e,t,i,r){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const s=i;if(s.subSurface.isRefractionEnabled=!0,s.subSurface.volumeIndexOfRefraction=1,s.subSurface.useAlbedoToTintRefraction=!0,void 0===r.transmissionFactor)return s.subSurface.refractionIntensity=0,s.subSurface.isRefractionEnabled=!1,Promise.resolve();{s.subSurface.refractionIntensity=r.transmissionFactor;const e=s.getScene();s.subSurface.refractionIntensity&&!e._transmissionHelper?new FU({},s.getScene()):s.subSurface.refractionIntensity&&!e._transmissionHelper?._isRenderTargetValid()&&e._transmissionHelper?._setupRenderTargets()}return s.subSurface.minimumThickness=0,s.subSurface.maximumThickness=0,r.transmissionTexture?(r.transmissionTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,r.transmissionTexture,void 0).then((e=>{e.name=`${i.name} (Transmission)`,s.subSurface.refractionIntensityTexture=e,s.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}Qk(LU),$k(LU,!0,(e=>new BU(e)));const VU="KHR_materials_diffuse_transmission";class kU{constructor(e){this.name=VU,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(VU),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadTranslucentPropertiesAsync(r,t,i,s)),Promise.all(n).then((()=>{}))}))}_loadTranslucentPropertiesAsync(e,t,i,r){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const s=i;if(s.subSurface.isTranslucencyEnabled=!0,s.subSurface.volumeIndexOfRefraction=1,s.subSurface.minimumThickness=0,s.subSurface.maximumThickness=0,s.subSurface.useAlbedoToTintTranslucency=!1,void 0===r.diffuseTransmissionFactor)return s.subSurface.translucencyIntensity=0,s.subSurface.isTranslucencyEnabled=!1,Promise.resolve();s.subSurface.translucencyIntensity=r.diffuseTransmissionFactor;const n=new Array;return s.subSurface.useGltfStyleTextures=!0,r.diffuseTransmissionTexture&&(r.diffuseTransmissionTexture.nonColorData=!0,n.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionTexture`,r.diffuseTransmissionTexture).then((e=>{e.name=`${i.name} (Diffuse Transmission)`,s.subSurface.translucencyIntensityTexture=e})))),void 0!==r.diffuseTransmissionColorFactor?s.subSurface.translucencyColor=H.v9.FromArray(r.diffuseTransmissionColorFactor):s.subSurface.translucencyColor=H.v9.White(),r.diffuseTransmissionColorTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionColorTexture`,r.diffuseTransmissionColorTexture).then((e=>{e.name=`${i.name} (Diffuse Transmission Color)`,s.subSurface.translucencyColorTexture=e}))),Promise.all(n).then((()=>{}))}}Qk(VU),$k(VU,!0,(e=>new kU(e)));const UU="KHR_materials_volume";class GU{constructor(e){this.name=UU,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(UU),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadVolumePropertiesAsync(r,t,i,s)),Promise.all(n).then((()=>{}))}))}_loadVolumePropertiesAsync(e,t,i,r){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);if(!i.subSurface.isRefractionEnabled&&!i.subSurface.isTranslucencyEnabled||!r.thicknessFactor)return Promise.resolve();i.subSurface.volumeIndexOfRefraction=i.indexOfRefraction;const s=void 0!==r.attenuationDistance?r.attenuationDistance:Number.MAX_VALUE;return i.subSurface.tintColorAtDistance=s,void 0!==r.attenuationColor&&3==r.attenuationColor.length&&i.subSurface.tintColor.copyFromFloats(r.attenuationColor[0],r.attenuationColor[1],r.attenuationColor[2]),i.subSurface.minimumThickness=0,i.subSurface.maximumThickness=r.thicknessFactor,i.subSurface.useThicknessAsDepth=!0,r.thicknessTexture?(r.thicknessTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,r.thicknessTexture).then((e=>{e.name=`${i.name} (Thickness)`,i.subSurface.thicknessTexture=e,i.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}Qk(UU),$k(UU,!0,(e=>new GU(e)));const zU="KHR_materials_dispersion";class WU{constructor(e){this.name=zU,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(zU)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadDispersionPropertiesAsync(r,t,i,s)),Promise.all(n).then((()=>{}))}))}_loadDispersionPropertiesAsync(e,t,i,r){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);return i.subSurface.isRefractionEnabled&&r.dispersion?(i.subSurface.isDispersionEnabled=!0,i.subSurface.dispersion=r.dispersion,Promise.resolve()):Promise.resolve()}}Qk(zU),$k(zU,!0,(e=>new WU(e)));const HU="KHR_mesh_quantization";class XU{constructor(e){this.name=HU,this.enabled=e.isExtensionUsed(HU)}dispose(){}}Qk(HU),$k(HU,!0,(e=>new XU(e)));const qU="KHR_texture_basisu";class YU{constructor(e){this.name=qU,this._loader=e,this.enabled=e.isExtensionUsed(qU)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=null==t.sampler?eU.DefaultSampler:Jk.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=Jk.Get(`${r}/source`,this._loader.gltf.images,s.source);return this._loader._createTextureAsync(e,n,o,(e=>{i(e)}),t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)}))}}Qk(qU),$k(qU,!0,(e=>new YU(e)));const KU="KHR_texture_transform";class jU{constructor(e){this.name=KU,this._loader=e,this.enabled=this._loader.isExtensionUsed(KU)}dispose(){this._loader=null}loadTextureInfoAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>this._loader.loadTextureInfoAsync(e,t,(e=>{if(!(e instanceof vi.g))throw new Error(`${r}: Texture type not supported`);s.offset&&(e.uOffset=s.offset[0],e.vOffset=s.offset[1]),e.uRotationCenter=0,e.vRotationCenter=0,s.rotation&&(e.wAng=-s.rotation),s.scale&&(e.uScale=s.scale[0],e.vScale=s.scale[1]),null!=s.texCoord&&(e.coordinatesIndex=s.texCoord),i(e)}))))}}Qk(KU),$k(KU,!0,(e=>new jU(e)));const $U="KHR_xmp_json_ld";class QU{constructor(e){this.name=$U,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed($U)}dispose(){this._loader=null}onLoading(){if(null===this._loader.rootBabylonMesh)return;const e=this._loader.gltf.extensions?.KHR_xmp_json_ld,t=this._loader.gltf.asset?.extensions?.KHR_xmp_json_ld;if(e&&t){const i=+t.packet;e.packets&&i2)),new nG(pe.X5.ANIMATIONTYPE_FLOAT,`${e}.vScale`,tG,(()=>2))],offset:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,JU,(()=>2)),new nG(pe.X5.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,tG,(()=>2))],rotation:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,`${e}.wAng`,eG,(()=>1))]}}Qk($U),$k($U,!0,(e=>new QU(e)));class sG extends Xk{buildAnimations(e,t,i,r,s){s(e._babylonCamera,this._buildAnimation(t,i,r))}}class nG extends Xk{buildAnimations(e,t,i,r,s){for(const n in e._data)s(e._data[n].babylonMaterial,this._buildAnimation(t,i,r))}}class oG extends Xk{buildAnimations(e,t,i,r,s){s(e._babylonLight,this._buildAnimation(t,i,r))}}const aG={__array__:{__target__:!0,...Yk}},lG={__array__:{__target__:!0,orthographic:{xmag:[new sG(pe.X5.ANIMATIONTYPE_FLOAT,"orthoLeft",eG,(()=>1)),new sG(pe.X5.ANIMATIONTYPE_FLOAT,"orthoRight",tG,(()=>1))],ymag:[new sG(pe.X5.ANIMATIONTYPE_FLOAT,"orthoBottom",eG,(()=>1)),new sG(pe.X5.ANIMATIONTYPE_FLOAT,"orthoTop",tG,(()=>1))],zfar:[new sG(pe.X5.ANIMATIONTYPE_FLOAT,"maxZ",JU,(()=>1))],znear:[new sG(pe.X5.ANIMATIONTYPE_FLOAT,"minZ",JU,(()=>1))]},perspective:{yfov:[new sG(pe.X5.ANIMATIONTYPE_FLOAT,"fov",JU,(()=>1))],zfar:[new sG(pe.X5.ANIMATIONTYPE_FLOAT,"maxZ",JU,(()=>1))],znear:[new sG(pe.X5.ANIMATIONTYPE_FLOAT,"minZ",JU,(()=>1))]}}},hG={nodes:aG,materials:{__array__:{__target__:!0,pbrMetallicRoughness:{baseColorFactor:[new nG(pe.X5.ANIMATIONTYPE_COLOR3,"albedoColor",ZU,(()=>4)),new nG(pe.X5.ANIMATIONTYPE_FLOAT,"alpha",(function(e,t,i,r){return t[i+3]*r}),(()=>4))],metallicFactor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"metallic",JU,(()=>1))],roughnessFactor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"roughness",JU,(()=>1))],baseColorTexture:{extensions:{KHR_texture_transform:rG("albedoTexture")}},metallicRoughnessTexture:{extensions:{KHR_texture_transform:rG("metallicTexture")}}},emissiveFactor:[new nG(pe.X5.ANIMATIONTYPE_COLOR3,"emissiveColor",ZU,(()=>3))],normalTexture:{scale:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"bumpTexture.level",JU,(()=>1))],extensions:{KHR_texture_transform:rG("bumpTexture")}},occlusionTexture:{strength:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",JU,(()=>1))],extensions:{KHR_texture_transform:rG("ambientTexture")}},emissiveTexture:{extensions:{KHR_texture_transform:rG("emissiveTexture")}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",JU,(()=>1))],anisotropyRotation:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"anisotropy.angle",JU,(()=>1))],anisotropyTexture:{extensions:{KHR_texture_transform:rG("anisotropy.texture")}}},KHR_materials_clearcoat:{clearcoatFactor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",JU,(()=>1))],clearcoatRoughnessFactor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",JU,(()=>1))],clearcoatTexture:{extensions:{KHR_texture_transform:rG("clearCoat.texture")}},clearcoatNormalTexture:{scale:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",JU,(()=>1))],extensions:{KHR_texture_transform:rG("clearCoat.bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:rG("clearCoat.textureRoughness")}}},KHR_materials_dispersion:{dispersion:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",JU,(()=>1))]},KHR_materials_emissive_strength:{emissiveStrength:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"emissiveIntensity",JU,(()=>1))]},KHR_materials_ior:{ior:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"indexOfRefraction",JU,(()=>1))]},KHR_materials_iridescence:{iridescenceFactor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"iridescence.intensity",JU,(()=>1))],iridescenceIor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",JU,(()=>1))],iridescenceThicknessMinimum:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",JU,(()=>1))],iridescenceThicknessMaximum:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",JU,(()=>1))],iridescenceTexture:{extensions:{KHR_texture_transform:rG("iridescence.texture")}},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:rG("iridescence.thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:[new nG(pe.X5.ANIMATIONTYPE_COLOR3,"sheen.color",ZU,(()=>3))],sheenRoughnessFactor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"sheen.roughness",JU,(()=>1))],sheenColorTexture:{extensions:{KHR_texture_transform:rG("sheen.texture")}},sheenRoughnessTexture:{extensions:{KHR_texture_transform:rG("sheen.textureRoughness")}}},KHR_materials_specular:{specularFactor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"metallicF0Factor",JU,(()=>1))],specularColorFactor:[new nG(pe.X5.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",ZU,(()=>3))],specularTexture:{extensions:{KHR_texture_transform:rG("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:rG("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",JU,(()=>1))],transmissionTexture:{extensions:{KHR_texture_transform:rG("subSurface.refractionIntensityTexture")}}},KHR_materials_volume:{attenuationColor:[new nG(pe.X5.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",ZU,(()=>3))],attenuationDistance:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",JU,(()=>1))],thicknessFactor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",JU,(()=>1))],thicknessTexture:{extensions:{KHR_texture_transform:rG("subSurface.thicknessTexture")}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"subSurface.translucencyIntensity",JU,(()=>1))],diffuseTransmissionTexture:{extensions:{KHR_texture_transform:rG("subSurface.translucencyIntensityTexture")}},diffuseTransmissionColorFactor:[new nG(pe.X5.ANIMATIONTYPE_COLOR3,"subSurface.translucencyColor",ZU,(()=>3))],diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:rG("subSurface.translucencyColorTexture")}}}}}},cameras:lG,extensions:{KHR_lights_punctual:{lights:{__array__:{__target__:!0,color:[new oG(pe.X5.ANIMATIONTYPE_COLOR3,"diffuse",ZU,(()=>3))],intensity:[new oG(pe.X5.ANIMATIONTYPE_FLOAT,"intensity",JU,(()=>1))],range:[new oG(pe.X5.ANIMATIONTYPE_FLOAT,"range",JU,(()=>1))],spot:{innerConeAngle:[new oG(pe.X5.ANIMATIONTYPE_FLOAT,"innerAngle",iG,(()=>1))],outerConeAngle:[new oG(pe.X5.ANIMATIONTYPE_FLOAT,"angle",iG,(()=>1))]}}}}}};class cG{constructor(e,t){this._gltf=e,this._infoTree=t}convert(e){let t,i=this._gltf,r=this._infoTree;if(!e.startsWith("/"))throw new Error("Path must start with a /");const s=e.split("/");s.shift();for(const n of s){if(r.__array__)r=r.__array__;else if(r=r[n],!r)throw new Error(`Path ${e} is invalid`);if(void 0===i)throw new Error(`Path ${e} is invalid`);i=i[n],r.__target__&&(t=i)}return{object:t,info:r}}}const uG="KHR_animation_pointer";class dG extends cG{constructor(e){super(e,hG)}}class fG{constructor(e){this.name=uG,this._loader=e,this._pathToObjectConverter=new dG(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(uG)}dispose(){this._loader=null,delete this._pathToObjectConverter}_loadAnimationChannelAsync(e,t,i,r,s){const n=r.target.extensions?.KHR_animation_pointer;if(!n||!this._pathToObjectConverter)return null;"pointer"!==r.target.path&&Z.V.Warn(`${e}/target/path: Value (${r.target.path}) must be (pointer) when using the ${this.name} extension`),null!=r.target.node&&Z.V.Warn(`${e}/target/node: Value (${r.target.node}) must not be present when using the ${this.name} extension`);const o=`${e}/extensions/${this.name}`,a=n.pointer;if(!a)throw new Error(`${o}: Pointer is missing`);try{const n=this._pathToObjectConverter.convert(a);return this._loader._loadAnimationChannelFromTargetInfoAsync(e,t,i,r,n,s)}catch(e){return Z.V.Warn(`${o}/pointer: Invalid pointer (${a}) skipped`),null}}}Qk(uG),$k(uG,!0,(e=>new fG(e)));const pG="MSFT_audio_emitter";class _G{constructor(e){this.name=pG,this._loader=e,this.enabled=this._loader.isExtensionUsed(pG)}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,Jk.Assign(this._clips),Jk.Assign(this._emitters)}}loadSceneAsync(e,t){return eU.LoadExtensionAsync(e,t,this.name,((i,r)=>{const s=new Array;s.push(this._loader.loadSceneAsync(e,t));for(const e of r.emitters){const t=Jk.Get(`${i}/emitters`,this._emitters,e);if(null!=t.refDistance||null!=t.maxDistance||null!=t.rolloffFactor||null!=t.distanceModel||null!=t.innerAngle||null!=t.outerAngle)throw new Error(`${i}: Direction or Distance properties are not allowed on emitters attached to a scene`);s.push(this._loadEmitterAsync(`${i}/emitters/${t.index}`,t))}return Promise.all(s).then((()=>{}))}))}loadNodeAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((e,r)=>{const s=new Array;return this._loader.loadNodeAsync(e,t,(t=>{for(const i of r.emitters){const r=Jk.Get(`${e}/emitters`,this._emitters,i);s.push(this._loadEmitterAsync(`${e}/emitters/${r.index}`,r).then((()=>{for(const e of r._babylonSounds)e.attachToMesh(t),null==r.innerAngle&&null==r.outerAngle||(e.setLocalDirectionToMesh(W.Pq.Forward()),e.setDirectionalCone(2*Ue.S0.ToDegrees(null==r.innerAngle?Math.PI:r.innerAngle),2*Ue.S0.ToDegrees(null==r.outerAngle?Math.PI:r.outerAngle),0))})))}i(t)})).then((e=>Promise.all(s).then((()=>e))))}))}loadAnimationAsync(e,t){return eU.LoadExtensionAsync(e,t,this.name,((i,r)=>this._loader.loadAnimationAsync(e,t).then((s=>{const n=new Array;Jk.Assign(r.events);for(const o of r.events)n.push(this._loadAnimationEventAsync(`${i}/events/${o.index}`,e,t,o,s));return Promise.all(n).then((()=>s))}))))}_loadClipAsync(e,t){if(t._objectURL)return t._objectURL;let i;if(t.uri)i=this._loader.loadUriAsync(e,t,t.uri);else{const r=Jk.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,t.bufferView);i=this._loader.loadBufferViewAsync(`/bufferViews/${r.index}`,r)}return t._objectURL=i.then((e=>URL.createObjectURL(new Blob([e],{type:t.mimeType})))),t._objectURL}_loadEmitterAsync(e,t){if(t._babylonSounds=t._babylonSounds||[],!t._babylonData){const e=new Array,i=t.name||`emitter${t.index}`,r={loop:!1,autoplay:!1,volume:null==t.volume?1:t.volume};for(let s=0;s{const n=t._babylonSounds[s]=new si(i,e,this._loader.babylonScene,null,r);n.refDistance=t.refDistance||1,n.maxDistance=t.maxDistance||256,n.rolloffFactor=t.rolloffFactor||1,n.distanceModel=t.distanceModel||"exponential"})))}const s=Promise.all(e).then((()=>{const e=t.clips.map((e=>e.weight||1)),i=new mi(t.loop||!1,t._babylonSounds,e);t.innerAngle&&(i.directionalConeInnerAngle=2*Ue.S0.ToDegrees(t.innerAngle)),t.outerAngle&&(i.directionalConeOuterAngle=2*Ue.S0.ToDegrees(t.outerAngle)),t.volume&&(i.volume=t.volume),t._babylonData.sound=i}));t._babylonData={loaded:s}}return t._babylonData.loaded}_getEventAction(e,t,i,r,s){switch(i){case"play":return e=>{const i=(s||0)+(e-r);t.play(i)};case"stop":return()=>{t.stop()};case"pause":return()=>{t.pause()};default:throw new Error(`${e}: Unsupported action ${i}`)}}_loadAnimationEventAsync(e,t,i,r,s){if(0==s.targetedAnimations.length)return Promise.resolve();const n=s.targetedAnimations[0],o=r.emitter,a=Jk.Get(`/extensions/${this.name}/emitters`,this._emitters,o);return this._loadEmitterAsync(e,a).then((()=>{const t=a._babylonData.sound;if(t){const i=new we(r.time,this._getEventAction(e,t,r.action,r.time,r.startOffset));n.animation.addEvent(i),s.onAnimationGroupEndObservable.add((()=>{t.stop()})),s.onAnimationGroupPauseObservable.add((()=>{t.pause()}))}}))}}Qk(pG),$k(pG,!0,(e=>new _G(e)));const mG="MSFT_lod";class gG{constructor(e){this.name=mG,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new z.cP,this.onMaterialLODsLoadedObservable=new z.cP,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.maxLODsToLoad=this._loader.parent.extensionOptions[mG]?.maxLODsToLoad??this.maxLODsToLoad,this.enabled=this._loader.isExtensionUsed(mG)}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{0!==e&&(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{0!==e&&(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 eU.LoadExtensionAsync(e,t,this.name,((e,r)=>{let s;const n=this._getLODs(e,t,this._loader.gltf.nodes,r.ids);this._loader.logOpen(`${e}`);for(let e=0;e{i(e),e.setEnabled(!1)},o=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,r).then((t=>{if(0!==e){const t=n[e-1];t._babylonTransformNode&&(this._disposeTransformNode(t._babylonTransformNode),delete t._babylonTransformNode)}return t.setEnabled(!0),t}));this._nodePromiseLODs[e]=this._nodePromiseLODs[e]||[],0===e?s=o:(this._nodeIndexLOD=null,this._nodePromiseLODs[e].push(o))}return this._loader.logClose(),s}))}_loadMaterialAsync(e,t,i,r,s){return this._nodeIndexLOD?null:eU.LoadExtensionAsync(e,t,this.name,((e,n)=>{let o;const a=this._getLODs(e,t,this._loader.gltf.materials,n.ids);this._loader.logOpen(`${e}`);for(let e=0;e{0===e&&s(t)})).then((t=>{if(0!==e){s(t);const i=a[e-1]._data;i[r]&&(this._disposeMaterials([i[r].babylonMaterial]),delete i[r])}return t}));this._materialPromiseLODs[e]=this._materialPromiseLODs[e]||[],0===e?o=n:(this._materialIndexLOD=null,this._materialPromiseLODs[e].push(n))}return this._loader.logClose(),o}))}_loadUriAsync(e,t,i){if(null!==this._nodeIndexLOD){this._loader.log("deferred");const r=this._nodeIndexLOD-1;return this._nodeSignalLODs[r]=this._nodeSignalLODs[r]||new uR,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then((()=>this._loader.loadUriAsync(e,t,i)))}if(null!==this._materialIndexLOD){this._loader.log("deferred");const r=this._materialIndexLOD-1;return this._materialSignalLODs[r]=this._materialSignalLODs[r]||new uR,this._materialSignalLODs[r].promise.then((()=>this._loader.loadUriAsync(e,t,i)))}return null}loadBufferAsync(e,t,i,r){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 t=(e,t)=>{const s=i,n=s+r-1;let o=e[t];return o?(o.start=Math.min(o.start,s),o.end=Math.max(o.end,n)):(o={start:s,end:n,loaded:new uR},e[t]=o),o.loaded.promise.then((e=>new Uint8Array(e.buffer,e.byteOffset+i-o.start,r)))};return this._loader.log("deferred"),null!==this._nodeIndexLOD?t(this._nodeBufferLODs,this._nodeIndexLOD):null!==this._materialIndexLOD?t(this._materialBufferLODs,this._materialIndexLOD):t(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((e=>{i.loaded.resolve(e)}),(e=>{i.loaded.reject(e)})))}_getLODs(e,t,i,r){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const s=[];for(let t=r.length-1;t>=0;t--)if(s.push(Jk.Get(`${e}/ids/${r[t]}`,i,r[t])),s.length===this.maxLODsToLoad)return s;return s.push(t),s}_disposeTransformNode(e){const t=[],i=e.material;i&&t.push(i);for(const i of e.getChildMeshes())i.material&&t.push(i.material);e.dispose();const r=t.filter((e=>this._loader.babylonScene.meshes.every((t=>t.material!=e))));this._disposeMaterials(r)}_disposeMaterials(e){const t={};for(const i of e){for(const e of i.getActiveTextures())t[e.uniqueId]=e;i.dispose()}for(const e in t)for(const i of this._loader.babylonScene.materials)i.hasTexture(t[e])&&delete t[e];for(const e in t)t[e].dispose()}}Qk(mG),$k(mG,!0,(e=>new gG(e)));const vG="MSFT_minecraftMesh";class xG{constructor(e){this.name=vG,this._loader=e,this.enabled=this._loader.isExtensionUsed(vG)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtraAsync(e,t,this.name,((r,s)=>{if(s){if(!(i instanceof zm))throw new Error(`${r}: Material type not supported`);const s=this._loader.loadMaterialPropertiesAsync(e,t,i);return i.needAlphaBlending()&&(i.forceDepthWrite=!0,i.separateCullingPass=!0),i.backFaceCulling=i.forceDepthWrite,i.twoSidedLighting=!0,s}return null}))}}Qk(vG),$k(vG,!0,(e=>new xG(e)));const bG="MSFT_sRGBFactors";class SG{constructor(e){this.name=bG,this._loader=e,this.enabled=this._loader.isExtensionUsed(bG)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtraAsync(e,t,this.name,((r,s)=>{if(s){if(!(i instanceof zm))throw new Error(`${r}: Material type not supported`);const s=this._loader.loadMaterialPropertiesAsync(e,t,i),n=i.getScene().getEngine().useExactSrgbConversions;return i.albedoTexture||i.albedoColor.toLinearSpaceToRef(i.albedoColor,n),i.reflectivityTexture||i.reflectivityColor.toLinearSpaceToRef(i.reflectivityColor,n),s}return null}))}}Qk(bG),$k(bG,!0,(e=>new SG(e)));const TG={"lifecycle/onStart":Ep.ClassName,"lifecycle/onTick":Ap.ClassName,log:ld.ClassName,"flow/delay":Sd.ClassName,"customEvent/send":fd.ClassName,"customEvent/receive":Pp.ClassName,"flow/sequence":Id.ClassName,"world/get":Bd.ClassName,"world/set":dd.ClassName,"flow/doN":_d.ClassName,"variable/get":Nd.ClassName,"variable/set":hd.ClassName,"flow/whileLoop":Pd.ClassName,"math/random":af.ClassName,"math/e":hf.ClassName,"math/pi":cf.ClassName,"math/inf":uf.ClassName,"math/nan":df.ClassName,"math/abs":pf.ClassName,"math/sign":_f.ClassName,"math/trunc":mf.ClassName,"math/floor":gf.ClassName,"math/ceil":vf.ClassName,"math/fract":xf.ClassName,"math/neg":bf.ClassName,"math/add":rf.ClassName,"math/sub":sf.ClassName,"math/mul":nf.ClassName,"math/div":of.ClassName,"math/rem":Tf.ClassName,"math/min":Cf.ClassName,"math/max":yf.ClassName,"math/clamp":Af.ClassName,"math/saturate":If.ClassName,"math/mix":Mf.ClassName,"math/eq":Of.ClassName,"math/lt":wf.ClassName,"math/le":Nf.ClassName,"math/gt":Ff.ClassName,"math/ge":Lf.ClassName,"math/isnan":Bf.ClassName,"math/isinf":Vf.ClassName,"math/rad":kf.ClassName,"math/deg":Uf.ClassName,"math/sin":Gf.ClassName,"math/cos":zf.ClassName,"math/tan":Wf.ClassName,"math/asin":Hf.ClassName,"math/acos":Xf.ClassName,"math/atan":qf.ClassName,"math/atan2":Yf.ClassName,"math/sinh":Kf.ClassName,"math/cosh":jf.ClassName,"math/tanh":$f.ClassName,"math/asinh":Qf.ClassName,"math/acosh":Zf.ClassName,"math/atanh":Jf.ClassName,"math/exp":ep.ClassName,"math/log":tp.ClassName,"math/log2":ip.ClassName,"math/log10":rp.ClassName,"math/sqrt":sp.ClassName,"math/cbrt":np.ClassName,"math/pow":op.ClassName,"math/length":ap.ClassName,"math/normalize":lp.ClassName,"math/dot":lf.ClassName,"math/cross":hp.ClassName,"math/rotate2d":cp.ClassName,"math/rotate3d":up.ClassName,"math/transpose":dp.ClassName,"math/determinant":fp.ClassName,"math/inverse":pp.ClassName,"math/matmul":_p.ClassName,"math/not":mp.ClassName,"math/and":gp.ClassName,"math/or":vp.ClassName,"math/xor":xp.ClassName,"math/asr":Sp.ClassName,"math/lsl":bp.ClassName,"math/clz":Tp.ClassName,"math/ctz":Cp.ClassName,"math/popcnt":yp.ClassName},CG={float2:"Vector2",float3:"Vector3",float4:"Vector4",float4x4:"Matrix",int:"FlowGraphInteger"};function yG(e,t,i){if(void 0!==e.type){const r=t.types&&t.types[e.type];if(!r)throw new Error(`${i}: Unknown type: ${e.type}`);const s=r.signature;if(!s)throw new Error(`${i}: Type ${e.type} has no signature`);const n=CG[s];return{value:e.value,className:n}}return e.value}function EG(e,t,i){const r=TG[t.type];if(!r)throw new Error(`/extensions/KHR_interactivity/nodes/${e}: Unknown block type: ${t.type}`);const s=e.toString(),n=function(e,t,i){const r={},s=e.configuration??[];for(const e of s)if("customEvent"===e.id){const s=t.customEvents&&t.customEvents[e.value];if(!s)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Unknown custom event: ${e.value}`);r.eventId=s.id,r.eventData=s.values.map((e=>e.id))}else if("variable"===e.id){const s=t.variables&&t.variables[e.value];if(!s)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Unknown variable: ${e.value}`);r.variableName=s.id}else if("path"===e.id){const t=e.value;r.path=t}else r[e.id]=yG(e,t,`/extensions/KHR_interactivity/nodes/${i}`);return r}(t,i,s);return{className:r,config:n,uniqueId:s,metadata:t.metadata,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[]}}class PG extends cG{constructor(e){super(e,AG)}}const AG={nodes:{__array__:{__target__:!0,translation:{type:"Vector3",get:e=>e._babylonTransformNode.position,set:(e,t)=>{t._babylonTransformNode.position=e},getObject:e=>e._babylonTransformNode}}}},RG="KHR_interactivity";class IG{constructor(e){this._loader=e,this.name=RG,this.enabled=this._loader.isExtensionUsed(RG),this._pathConverter=new PG(this._loader.gltf)}dispose(){this._loader=null,delete this._pathConverter}onReady(){if(!this._loader.babylonScene||!this._pathConverter)return;const e=this._loader.babylonScene,t=this._loader.gltf.extensions?.KHR_interactivity,i=function(e){const t={uniqueId:(0,Au.z)(),_userVariables:{},_connectionValues:{}},i=[t],r=[];for(let t=0;te.name===a));h||(h={uniqueId:(0,Au.z)(),name:a,_connectionType:0,connectedPointIds:[]},l.signalInputs.push(h)),h.connectedPointIds.push(s.uniqueId),s.connectedPointIds.push(h.uniqueId)}const a=s.values??[];for(const s of a){const o=s.id,a={uniqueId:(0,Au.z)(),name:o,_connectionType:0,connectedPointIds:[]};if(n.dataInputs.push(a),void 0!==s.value){const r=yG(s,e,`/extensions/KHR_interactivity/nodes/${i}`);t._connectionValues[a.uniqueId]=r}else{if(void 0===s.node||void 0===s.socket)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Invalid socket ${o} in node ${i}`);{const e=s.node,t=s.socket,n=r[e];if(!n)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Could not find node with id ${e} that connects its output with node${i}'s input ${o}`);let l=n.dataOutputs.find((e=>e.name===t));l||(l={uniqueId:(0,Au.z)(),name:t,_connectionType:1,connectedPointIds:[]},n.dataOutputs.push(l)),a.connectedPointIds.push(l.uniqueId),l.connectedPointIds.push(a.uniqueId)}}}}const s=e.variables??[];for(let i=0;inew IG(e)));const MG="KHR_node_visibility";class OG{constructor(e){this.name=MG,this._loader=e,this.enabled=e.isExtensionUsed(MG)}async onReady(){this._loader.gltf.nodes?.forEach((e=>{e._primitiveBabylonMeshes?.forEach((e=>{e.inheritVisibility=!0})),e.extensions?.KHR_node_visibility&&!1===e.extensions?.KHR_node_visibility.visible&&(e._babylonTransformNode&&(e._babylonTransformNode.isVisible=!1),e._primitiveBabylonMeshes?.forEach((e=>{e.isVisible=!1})))}))}dispose(){this._loader=null}}Qk(MG),$k(MG,!0,(e=>new OG(e)));const DG="ExtrasAsMetadata";class wG{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){const i=e.metadata=e.metadata||{};(i.gltf=i.gltf||{}).extras=t.extras}}constructor(e){this.name=DG,this.enabled=!0,this._loader=e}dispose(){this._loader=null}loadNodeAsync(e,t,i){return this._loader.loadNodeAsync(e,t,(e=>{this._assignExtras(e,t),i(e)}))}loadCameraAsync(e,t,i){return this._loader.loadCameraAsync(e,t,(e=>{this._assignExtras(e,t),i(e)}))}createMaterial(e,t,i){const r=this._loader.createMaterial(e,t,i);return this._assignExtras(r,t),r}}Qk(DG),$k(DG,!1,(e=>new wG(e)));class NG{constructor(){this.materials=[]}parseMTL(e,t,i,r){if(t instanceof ArrayBuffer)return;const s=t.split("\n"),n=/\s+/;let o,a=null;for(let t=0;t=0?l.substring(0,h):l;c=c.toLowerCase();const u=h>=0?l.substring(h+1).trim():"";if("newmtl"===c)a&&this.materials.push(a),e._blockEntityCollection=!!r,a=new Un(u,e),a._parentContainer=r,e._blockEntityCollection=!1;else if("kd"===c&&a)o=u.split(n,3).map(parseFloat),a.diffuseColor=H.v9.FromArray(o);else if("ka"===c&&a)o=u.split(n,3).map(parseFloat),a.ambientColor=H.v9.FromArray(o);else if("ks"===c&&a)o=u.split(n,3).map(parseFloat),a.specularColor=H.v9.FromArray(o);else if("ke"===c&&a)o=u.split(n,3).map(parseFloat),a.emissiveColor=H.v9.FromArray(o);else if("ns"===c&&a)a.specularPower=parseFloat(u);else if("d"===c&&a)a.alpha=parseFloat(u);else if("map_ka"===c&&a)a.ambientTexture=NG._GetTexture(i,u,e);else if("map_kd"===c&&a)a.diffuseTexture=NG._GetTexture(i,u,e);else if("map_ks"===c&&a)a.specularTexture=NG._GetTexture(i,u,e);else if("map_ns"===c);else if("map_bump"===c&&a){const t=u.split(n),r=t.indexOf("-bm");let s=null;r>=0&&(s=t[r+1],t.splice(r,2)),a.bumpTexture=NG._GetTexture(i,t.join(" "),e),a.bumpTexture&&null!==s&&(a.bumpTexture.level=parseFloat(s))}else"map_d"===c&&a&&(a.opacityTexture=NG._GetTexture(i,u,e))}a&&this.materials.push(a)}static _GetTexture(e,t,i){if(!t)return null;let r=e;if("file:"===e){let e=t.lastIndexOf("\\");-1===e&&(e=t.lastIndexOf("/")),r+=e>-1?t.substring(e+1):t}else r+=t;return new vi.g(r,i,!1,NG.INVERT_TEXTURE_Y)}}NG.INVERT_TEXTURE_Y=!0;class FG{constructor(e,t,i){this._positions=[],this._normals=[],this._uvs=[],this._colors=[],this._extColors=[],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 H.ov(.5,.5,.5,1),this._hasLineData=!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-1===i?-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 1!=i&&t[2]===e[t[0]].uv[i]?e[t[0]].idx[i]:-1}_setData(e,t,i,r,s,n,o){let a;a=this._loadingOptions.optimizeWithUV?this._isInArrayUV(this._tuplePosNorm,[e,i,t]):this._isInArray(this._tuplePosNorm,[e,i]),-1===a?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(r),s=s??new W.I9(0,0),this._wrappedUvsForBabylon.push(s),this._wrappedNormalsForBabylon.push(n),void 0!==o&&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(a)}_unwrapData(){try{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._handledMesh.hasLines=this._hasLineData,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,this._hasLineData=!1)}_optimizeNormals(e){const t=e.getVerticesData(st.R.PositionKind),i=e.getVerticesData(st.R.NormalKind),r={};if(!t||!i)return;for(let e=0;ethis._triangles.push(e[0],e[t],e[t+1]),this._handednessSign=1):i.useRightHandedSystem?(this._pushTriangle=(e,t)=>this._triangles.push(e[0],e[t+1],e[t]),this._handednessSign=1):(this._pushTriangle=(e,t)=>this._triangles.push(e[0],e[t],e[t+1]),this._handednessSign=-1);const n=t.split("\n"),o=[];let a=[];o.push(a);for(let e=0;e=7){const e=parseFloat(i[4]),t=parseFloat(i[5]),r=parseFloat(i[6]);this._colors.push(new H.ov(e>1?e/255:e,t>1?t/255:t,r>1?r/255:r,7===i.length||void 0===i[7]?1:parseFloat(i[7])))}else this._colors.push(this._grayColor)}else if(null!==(i=FG.NormalPattern.exec(t)))this._normals.push(new W.Pq(parseFloat(i[1]),parseFloat(i[2]),parseFloat(i[3])));else if(null!==(i=FG.UVPattern.exec(t)))this._uvs.push(new W.I9(parseFloat(i[1])*this._loadingOptions.UVScaling.x,parseFloat(i[2])*this._loadingOptions.UVScaling.y));else if(null!==(i=FG.FacePattern3.exec(t)))this._setDataForCurrentFaceWithPattern3(i[1].trim().split(" "),1);else if(null!==(i=FG.FacePattern4.exec(t)))this._setDataForCurrentFaceWithPattern4(i[1].trim().split(" "),1);else if(null!==(i=FG.FacePattern5.exec(t)))this._setDataForCurrentFaceWithPattern5(i[1].trim().split(" "),1);else if(null!==(i=FG.FacePattern2.exec(t)))this._setDataForCurrentFaceWithPattern2(i[1].trim().split(" "),1);else if(null!==(i=FG.FacePattern1.exec(t)))this._setDataForCurrentFaceWithPattern1(i[1].trim().split(" "),1);else if(null!==(i=FG.LinePattern1.exec(t)))this._setDataForCurrentFaceWithPattern1(i[1].trim().split(" "),0),this._hasLineData=!0;else if(null!==(i=FG.LinePattern2.exec(t)))this._setDataForCurrentFaceWithPattern2(i[1].trim().split(" "),0),this._hasLineData=!0;else if(i=FG._GetZbrushMRGB(t,!this._loadingOptions.importVertexColors))i.forEach((e=>{this._extColors.push(e)}));else if(null!==(i=FG.LinePattern3.exec(t)))this._setDataForCurrentFaceWithPattern3(i[1].trim().split(" "),0),this._hasLineData=!0;else if(FG.GroupDescriptor.test(t)||FG.ObjectDescriptor.test(t)){const e={name:t.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:FG.ObjectDescriptor.test(t)};this._addPreviousObjMesh(),this._meshesFromObj.push(e),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(FG.UseMtlDescriptor.test(t)){if(this._materialNameFromObj=t.substring(7).trim(),!this._isFirstMaterial||!this._hasMeshes){this._addPreviousObjMesh();const e={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(e),this._hasMeshes=!0}this._hasMeshes&&this._isFirstMaterial&&(this._meshesFromObj[this._meshesFromObj.length-1].materialName=this._materialNameFromObj,this._isFirstMaterial=!1)}else FG.MtlLibGroupDescriptor.test(t)?s(t.substring(7).trim()):FG.SmoothDescriptor.test(t)||Z.V.Log("Unhandled expression at line : "+t)}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._handledMesh.hasLines=this._hasLineData,this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon)),!this._hasMeshes){let e=null;if(this._indicesForBabylon.length)this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData();else{for(const e of this._positions)this._unwrappedPositionsForBabylon.push(e.x,e.y,e.z);if(this._normals.length)for(const e of this._normals)this._unwrappedNormalsForBabylon.push(e.x,e.y,e.z);if(this._uvs.length)for(const e of this._uvs)this._unwrappedUVForBabylon.push(e.x,e.y);if(this._extColors.length)for(const e of this._extColors)this._unwrappedColorsForBabylon.push(e.r,e.g,e.b,e.a);else if(this._colors.length)for(const e of this._colors)this._unwrappedColorsForBabylon.push(e.r,e.g,e.b,e.a);this._materialNameFromObj||(e=new Un(yt.RandomId(),i),e.pointsCloud=!0,this._materialNameFromObj=e.name,this._normals.length||(e.disableLighting=!0,e.emissiveColor=H.v9.White()))}this._meshesFromObj.push({name:yt.RandomId(),indices:this._indicesForBabylon,positions:this._unwrappedPositionsForBabylon,colors:this._unwrappedColorsForBabylon,normals:this._unwrappedNormalsForBabylon,uvs:this._unwrappedUVForBabylon,materialName:this._materialNameFromObj,directMaterial:e,isObject:!0,hasLines:this._hasLineData})}for(let t=0;t=0;--e)if(this._meshesFromObj[e].isObject&&this._meshesFromObj[e]._babylonMesh){s.parent=this._meshesFromObj[e]._babylonMesh;break}if(this._materialToUse.push(this._meshesFromObj[t].materialName),this._handledMesh.hasLines&&(s._internalMetadata??(s._internalMetadata={}),s._internalMetadata._isLine=!0),0===this._handledMesh.positions?.length){this._babylonMeshesArray.push(s);continue}const n=new bt;if(n.uvs=this._handledMesh.uvs,n.indices=this._handledMesh.indices,n.positions=this._handledMesh.positions,this._loadingOptions.computeNormals){const e=new Array;bt.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,e),n.normals=e}else n.normals=this._handledMesh.normals;this._loadingOptions.importVertexColors&&(n.colors=this._handledMesh.colors),n.applyToMesh(s),this._loadingOptions.invertY&&(s.scaling.y*=-1),this._loadingOptions.optimizeNormals&&this._optimizeNormals(s),this._babylonMeshesArray.push(s),this._handledMesh.directMaterial&&(s.material=this._handledMesh.directMaterial)}}}FG.ObjectDescriptor=/^o/,FG.GroupDescriptor=/^g/,FG.MtlLibGroupDescriptor=/^mtllib /,FG.UseMtlDescriptor=/^usemtl /,FG.SmoothDescriptor=/^s /,FG.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/,FG.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,FG.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,FG.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/,FG.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,FG.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,FG.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,FG.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/,FG.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/,FG.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/,FG.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;class LG{static get INVERT_TEXTURE_Y(){return NG.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){NG.INVERT_TEXTURE_Y=e}constructor(e){this.name="obj",this.extensions=".obj",this._assetContainer=null,this._loadingOptions=e||LG._DefaultLoadingOptions}static get _DefaultLoadingOptions(){return{computeNormals:LG.COMPUTE_NORMALS,optimizeNormals:LG.OPTIMIZE_NORMALS,importVertexColors:LG.IMPORT_VERTEX_COLORS,invertY:LG.INVERT_Y,invertTextureY:LG.INVERT_TEXTURE_Y,UVScaling:LG.UV_SCALING,materialLoadingFailsSilently:LG.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:LG.OPTIMIZE_WITH_UV,skipMaterials:LG.SKIP_MATERIALS,useLegacyBehavior:LG.USE_LEGACY_BEHAVIOR}}_loadMTL(e,t,i,r){const s=t+e;Ue.S0.LoadFile(s,i,void 0,void 0,!1,((e,t)=>{r(s,t)}))}createPlugin(){return new LG(LG._DefaultLoadingOptions)}canDirectLoad(){return!1}importMeshAsync(e,t,i,r){return this._parseSolid(e,t,i,r).then((e=>({meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]})))}loadAsync(e,t,i){return this.importMeshAsync(null,e,t,i).then((()=>{}))}loadAssetContainerAsync(e,t,i){const r=new ei(e);return this._assetContainer=r,this.importMeshAsync(null,e,t,i).then((e=>(e.meshes.forEach((e=>r.meshes.push(e))),e.meshes.forEach((e=>{const t=e.material;t&&-1==r.materials.indexOf(t)&&(r.materials.push(t),t.getActiveTextures().forEach((e=>{-1==r.textures.indexOf(e)&&r.textures.push(e)})))})),this._assetContainer=null,r))).catch((e=>{throw this._assetContainer=null,e}))}_parseSolid(e,t,i,r){let s="";const n=new NG,o=[],a=[];i=i.replace(/#.*$/gm,"").trim(),new FG(o,a,this._loadingOptions).parse(e,i,t,this._assetContainer,(e=>{s=e}));const l=[];return""===s||this._loadingOptions.skipMaterials||l.push(new Promise(((e,i)=>{this._loadMTL(s,r,(l=>{try{n.parseMTL(t,l,r,this._assetContainer);for(let e=0;e-1;)i.push(r),t=r+1;if(-1===r&&0===i.length)n.materials[e].dispose();else for(let t=0;t{Ue.S0.Warn(`Error downloading MTL file: '${s}'`),this._loadingOptions.materialLoadingFailsSilently?e():i(r)}))}))),Promise.all(l).then((()=>{const e=e=>Boolean(e._internalMetadata?._isLine??!1);return a.forEach((i=>{if(e(i)){let r=i.material??new Un(i.name+"_line",t);r.getBindedMeshes().filter((t=>!e(t))).length>0&&(r=r.clone(r.name+"_line")??r),r.wireframe=!0,i.material=r,i._internalMetadata&&(i._internalMetadata._isLine=void 0)}})),a}))}}LG.OPTIMIZE_WITH_UV=!0,LG.INVERT_Y=!1,LG.IMPORT_VERTEX_COLORS=!1,LG.COMPUTE_NORMALS=!1,LG.OPTIMIZE_NORMALS=!1,LG.UV_SCALING=new W.I9(1,1),LG.SKIP_MATERIALS=!1,LG.MATERIAL_LOADING_FAILS_SILENTLY=!0,LG.USE_LEGACY_BEHAVIOR=!1,ng(new LG);const BG={".stl":{isBinary:!0}};class VG{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=BG}importMesh(e,t,i,r,s){let n;if("string"!=typeof i){if(this._isBinary(i)){const e=new Yt("stlmesh",t);return this._parseBinary(e,i),s&&s.push(e),!0}i=(new TextDecoder).decode(new Uint8Array(i))}for(;n=this.solidPattern.exec(i);){let i=n[1];const r=n[3];if(r&&i!=r)return Ue.S0.Error("Error in STL, solid name != endsolid name"),!1;if(e&&i)if(e instanceof Array){if(!e.indexOf(i))continue}else if(i!==e)continue;i=i||"stlmesh";const o=new Yt(i,t);this._parseASCII(o,n[2]),s&&s.push(o)}return!0}load(e,t,i){return this.importMesh(null,e,t,i,null)}loadAssetContainer(e,t,i){const r=new ei(e);return e._blockEntityCollection=!0,this.importMesh(null,e,t,i,r.meshes),e._blockEntityCollection=!1,r}_isBinary(e){const t=new DataView(e);if(t.byteLength<=80)return!1;if(84+50*t.getUint32(80,!0)===t.byteLength)return!0;const i=[115,111,108,105,100];for(let e=0;e<5;e++)if(t.getUint8(e)!==i[e])return!0;return!1}_parseBinary(e,t){const i=new DataView(t),r=i.getUint32(80,!0);let s=0;const n=new Float32Array(3*r*3),o=new Float32Array(3*r*3),a=new Uint32Array(3*r);let l=0;for(let e=0;e({meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]})))}static _BuildPointCloud(e,t){if(!t.byteLength)return!1;const i=new Uint8Array(t),r=new Float32Array(t),s=i.length/32;return e.addPoints(s,(function(e,t){const s=r[8*t+0],n=r[8*t+1],o=r[8*t+2];e.position=new W.Pq(s,n,o);const a=i[32*t+24+0]/255,l=i[32*t+24+1]/255,h=i[32*t+24+2]/255;e.color=new H.ov(a,l,h,1)})),!0}static _BuildMesh(e,t){const i=new Yt("PLYMesh",e),r=new Uint8Array(t.data),s=new Float32Array(t.data),n=r.length/32,o=[],a=new bt;for(let e=0;e{const i=[];switch(e.mode){case 0:{const r=new wA("GaussianSplatting",null,t,this._loadingOptions.keepInRam);r._parentContainer=this._assetContainer,i.push(r),await r.updateDataAsync(e.data)}break;case 1:{const r=new xM("PointCloud",1,t);if(zG._BuildPointCloud(r,e.data))return Promise.all([r.buildMeshAsync()]).then((e=>(i.push(e[0]),i)));r.dispose()}break;case 2:if(!e.faces)throw new Error("PLY mesh doesn't contain face informations.");i.push(zG._BuildMesh(t,e));break;default:throw new Error("Unsupported Splat mode")}return new Promise((e=>{e(i)}))}))}loadAssetContainerAsync(e,t,i){const r=new ei(e);return this._assetContainer=r,this.importMeshAsync(null,e,t,i).then((e=>(e.meshes.forEach((e=>r.meshes.push(e))),this._assetContainer=null,r))).catch((e=>{throw this._assetContainer=null,e}))}loadAsync(e,t,i){return this.importMeshAsync(null,e,t,i).then((()=>{}))}static _ConvertPLYToSplat(e){const t=new Uint8Array(e),i=(new TextDecoder).decode(t.slice(0,10240)),r=i.indexOf("end_header\n");if(r<0||!i)return new Promise((t=>{t({mode:0,data:e})}));const s=parseInt(/element vertex (\d+)\n/.exec(i)[1]),n=/element face (\d+)\n/.exec(i);let o=0;n&&(o=parseInt(n[1]));const a=/element chunk (\d+)\n/.exec(i);let l=0;a&&(l=parseInt(a[1]));let h=0,c=0;const u={double:8,int:4,uint:4,float:4,short:2,ushort:2,uchar:1,list:0};let d;!function(e){e[e.Vertex=0]="Vertex",e[e.Chunk=1]="Chunk"}(d||(d={}));let f=1;const p=[],_=[],m=i.slice(0,r).split("\n");for(const e of m)if(e.startsWith("property ")){const[,t,i]=e.split(" ");1==f?(_.push({name:i,type:t,offset:c}),c+=u[t]):0==f&&(p.push({name:i,type:t,offset:h}),h+=u[t]),u[t]||Z.V.Warn(`Unsupported property type: ${t}.`)}else if(e.startsWith("element ")){const[,t]=e.split(" ");"chunk"==t?f=1:"vertex"==t&&(f=0)}const g=h,v=c;return wA.ConvertPLYToSplatAsync(e).then((t=>{const i=new DataView(e,r+11);let n=v*l+g*s;const a=[];if(o)for(let e=0;e{e({mode:0,data:t,faces:a,hasVertexColors:!1})}));let h=0,c=0;const u=["x","y","z","scale_0","scale_1","scale_2","opacity","rot_0","rot_1","rot_2","rot_3"],d=["red","green","blue","f_dc_0","f_dc_1","f_dc_2"];for(let e=0;e{e({mode:_,data:t,faces:a,hasVertexColors:!!c})}))}))}}zG._DefaultLoadingOptions={keepInRam:!1},ng(new zG);var WG=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class HG{constructor(e){this.occWorkerManager=e}saveShapeSTEP(e){return WG(this,void 0,void 0,(function*(){this.saveSTEP(e)}))}saveShapeSTEPAndReturn(e){return WG(this,void 0,void 0,(function*(){return this.saveSTEP(e)}))}saveShapeStl(e){return WG(this,void 0,void 0,(function*(){this.saveStl(e)}))}saveShapeStlAndReturn(e){return WG(this,void 0,void 0,(function*(){return this.saveStl(e)}))}saveSTEP(e){return this.occWorkerManager.genericCallToWorkerPromise("io.saveShapeSTEP",e).then((t=>{if(e.tryDownload&&document){const i=new Blob([t],{type:"text/plain"}),r=URL.createObjectURL(i),s=e.fileName?e.fileName:"bitbybit-dev.step",n=document.createElement("a");n.href=r,n.target="_self",n.download=s,n.click(),n.remove()}return t}))}saveStl(e){return this.occWorkerManager.genericCallToWorkerPromise("io.saveShapeStl",e).then((t=>{if(e.tryDownload&&document){const i=new Blob([t],{type:"application/stl"}),r=URL.createObjectURL(i),s=e.fileName?e.fileName:"bitbybit-dev.stl",n=document.createElement("a");n.href=r,n.target="_self",n.download=s,n.click(),n.remove()}return t}))}}class XG{constructor(e){this.occWorkerManager=e}makeCompound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.compound.makeCompound",e)}}class qG{constructor(e){this.occWorkerManager=e}line(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.line",e)}arcThroughThreePoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcThroughThreePoints",e)}arcThroughTwoPointsAndTangent(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcThroughTwoPointsAndTangent",e)}arcFromCircleAndTwoPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcFromCircleAndTwoPoints",e)}arcFromCircleAndTwoAngles(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcFromCircleAndTwoAngles",e)}arcFromCirclePointAndAngle(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcFromCirclePointAndAngle",e)}createCircleEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.createCircleEdge",e)}createEllipseEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.createEllipseEdge",e)}removeInternalEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.removeInternalEdges",e)}makeEdgeFromGeom2dCurveAndSurface(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.makeEdgeFromGeom2dCurveAndSurface",e)}getEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdge",e)}getEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdges",e)}getEdgesAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgesAlongWire",e)}getCircularEdgesAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgesAlongWire",e)}getLinearEdgesAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getLinearEdgesAlongWire",e)}getCornerPointsOfEdgesForShape(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCornerPointsOfEdgesForShape",e)}getEdgeLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgeLength",e)}getEdgesLengths(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgesLengths",e)}getEdgeCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgeCenterOfMass",e)}getEdgesCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgesCentersOfMass",e)}getCircularEdgeCenterPoint(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgeCenterPoint",e)}getCircularEdgeRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgeRadius",e)}getCircularEdgePlaneDirection(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgePlaneDirection",e)}pointOnEdgeAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.pointOnEdgeAtParam",e)}edgesToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.edgesToPoints",e)}reversedEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.reversedEdge",e)}tangentOnEdgeAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.tangentOnEdgeAtParam",e)}pointOnEdgeAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.pointOnEdgeAtLength",e)}tangentOnEdgeAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.tangentOnEdgeAtLength",e)}startPointOnEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.startPointOnEdge",e)}endPointOnEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.endPointOnEdge",e)}divideEdgeByParamsToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.divideEdgeByParamsToPoints",e)}divideEdgeByEqualDistanceToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.divideEdgeByEqualDistanceToPoints",e)}constraintTanLinesFromTwoPtsToCircle(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanLinesFromTwoPtsToCircle",e)}constraintTanLinesFromPtToCircle(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanLinesFromPtToCircle",e)}constraintTanLinesOnTwoCircles(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanLinesOnTwoCircles",e)}constraintTanCirclesOnTwoCircles(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanCirclesOnTwoCircles",e)}constraintTanCirclesOnCircleAndPnt(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanCirclesOnCircleAndPnt",e)}}class YG{constructor(e){this.occWorkerManager=e}createFacesFromWiresOnFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFacesFromWiresOnFace",e)}createFaceFromWireOnFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromWireOnFace",e)}createFaceFromWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromWire",e)}createFaceFromWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromWires",e)}createFaceFromWiresOnFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromWiresOnFace",e)}createFacesFromWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFacesFromWires",e)}createFaceFromMultipleCircleTanWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromMultipleCircleTanWires",e)}createFaceFromMultipleCircleTanWireCollections(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromMultipleCircleTanWireCollections",e)}faceFromSurface(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.faceFromSurface",e)}faceFromSurfaceAndWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.faceFromSurfaceAndWire",e)}createPolygonFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createPolygonFace",e)}createCircleFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createCircleFace",e)}createEllipseFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createEllipseFace",e)}createSquareFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createSquareFace",e)}createRectangleFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createRectangleFace",e)}getFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFace",e)}getFaces(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFaces",e)}reversedFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.reversedFace",e)}subdivideToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToPoints",e)}subdivideToWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToWires",e)}subdivideToRectangleWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToRectangleWires",e)}subdivideToRectangleHoles(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToRectangleHoles",e)}subdivideToPointsControlled(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToPointsControlled",e)}subdivideToNormals(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToNormals",e)}subdivideToUV(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToUV",e)}pointOnUV(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.pointOnUV",e)}normalOnUV(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.normalOnUV",e)}pointsOnUVs(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.pointsOnUVs",e)}normalsOnUVs(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.normalsOnUVs",e)}subdivideToPointsOnParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToPointsOnParam",e)}wireAlongParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.wireAlongParam",e)}wiresAlongParams(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.wiresAlongParams",e)}getUMinBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getUMinBound",e)}getUMaxBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getUMaxBound",e)}getVMinBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getVMinBound",e)}getVMaxBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getVMaxBound",e)}getFaceArea(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFaceArea",e)}getFacesAreas(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFacesAreas",e)}getFaceCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFaceCenterOfMass",e)}getFacesCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFacesCentersOfMass",e)}filterFacePoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.filterFacePoints",e)}}class KG{constructor(e){this.occWorkerManager=e}fromClosedShell(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.fromClosedShell",e)}createBox(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createBox",e)}createCube(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCube",e)}createBoxFromCorner(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createBoxFromCorner",e)}createCylinder(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCylinder",e)}createCylindersOnLines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCylindersOnLines",e)}createSphere(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createSphere",e)}createCone(e){return e.angle=e.angle*(Math.PI/180),this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCone",e)}getSolidSurfaceArea(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidSurfaceArea",e)}getSolidVolume(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidVolume",e)}getSolidsVolumes(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidsVolumes",e)}getSolidCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidCenterOfMass",e)}getSolidsCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidsCentersOfMass",e)}getSolids(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolids",e)}filterSolidPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.filterSolidPoints",e)}}class jG{constructor(e){this.occWorkerManager=e}createPolygonWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolygonWire",e)}createPolygons(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolygons",e)}createLineWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createLineWire",e)}createLines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createLines",e)}splitOnPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.splitOnPoints",e)}wiresToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.wiresToPoints",e)}createPolylineWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolylineWire",e)}createZigZagBetweenTwoWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createZigZagBetweenTwoWires",e)}createWireFromTwoCirclesTan(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createWireFromTwoCirclesTan",e)}createPolylines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolylines",e)}createBezier(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBezier",e)}createBezierWeights(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBezierWeights",e)}createBezierWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBezierWires",e)}interpolatePoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.interpolatePoints",e)}interpolateWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.interpolateWires",e)}createBSpline(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBSpline",e)}createBSplines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBSplines",e)}combineEdgesAndWiresIntoAWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.combineEdgesAndWiresIntoAWire",e)}createWireFromEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createWireFromEdge",e)}addEdgesAndWiresToWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.addEdgesAndWiresToWire",e)}divideWireByParamsToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWireByParamsToPoints",e)}divideWiresByParamsToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWiresByParamsToPoints",e)}divideWireByEqualDistanceToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWireByEqualDistanceToPoints",e)}divideWiresByEqualDistanceToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWiresByEqualDistanceToPoints",e)}pointOnWireAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.pointOnWireAtParam",e)}pointOnWireAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.pointOnWireAtLength",e)}pointsOnWireAtLengths(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.pointsOnWireAtLengths",e)}pointsOnWireAtEqualLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.pointsOnWireAtEqualLength",e)}pointsOnWireAtPatternOfLengths(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.pointsOnWireAtPatternOfLengths",e)}tangentOnWireAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.tangentOnWireAtParam",e)}tangentOnWireAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.tangentOnWireAtLength",e)}derivativesOnWireAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.derivativesOnWireAtLength",e)}derivativesOnWireAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.derivativesOnWireAtParam",e)}startPointOnWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.startPointOnWire",e)}endPointOnWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.endPointOnWire",e)}createCircleWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createCircleWire",e)}createSquareWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createSquareWire",e)}createStarWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createStarWire",e)}createChristmasTreeWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createChristmasTreeWire",e)}createNGonWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createNGonWire",e)}createParallelogramWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createParallelogramWire",e)}createHeartWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createHeartWire",e)}createRectangleWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createRectangleWire",e)}createLPolygonWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createLPolygonWire",e)}createEllipseWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createEllipseWire",e)}getWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWire",e)}getWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWires",e)}getWireCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWireCenterOfMass",e)}getWiresCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWiresCentersOfMass",e)}reversedWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.reversedWire",e)}reversedWireFromReversedEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.reversedWireFromReversedEdges",e)}getWireLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWireLength",e)}getWiresLengths(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWiresLengths",e)}placeWireOnFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.placeWireOnFace",e)}placeWiresOnFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.placeWiresOnFace",e)}closeOpenWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.closeOpenWire",e)}project(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.project",e)}projectWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.projectWires",e)}}class $G{constructor(e){this.occWorkerManager=e}sewFaces(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shell.sewFaces",e)}getShellSurfaceArea(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shell.getShellSurfaceArea",e)}}class QG{constructor(e){this.occWorkerManager=e}purgeInternalEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.purgeInternalEdges",e)}unifySameDomain(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.unifySameDomain",e)}isClosed(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isClosed",e)}isConvex(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isConvex",e)}isChecked(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isChecked",e)}isFree(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isFree",e)}isInfinite(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isInfinite",e)}isModified(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isModified",e)}isLocked(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isLocked",e)}isNull(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isNull",e)}isEqual(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isEqual",e)}isNotEqual(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isNotEqual",e)}isPartner(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isPartner",e)}isSame(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isSame",e)}getOrientation(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.getOrientation",e)}getShapeType(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.getShapeType",e)}}class ZG{constructor(e){this.occWorkerManager=e}vertexFromXYZ(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.vertexFromXYZ",e)}vertexFromPoint(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.vertexFromPoint",e)}verticesFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.verticesFromPoints",e)}verticesCompoundFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.verticesCompoundFromPoints",e)}getVertices(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.getVertices",e)}getVerticesAsPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.getVerticesAsPoints",e)}verticesToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.verticesToPoints",e)}vertexToPoint(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.vertexToPoint",e)}projectPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.projectPoints",e)}}class JG{constructor(e){this.vertex=new ZG(e),this.edge=new qG(e),this.wire=new jG(e),this.face=new YG(e),this.shell=new $G(e),this.solid=new KG(e),this.compound=new XG(e),this.shape=new QG(e)}}class ez{constructor(e){this.occWorkerManager=e}transform(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.transform",e)}rotate(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotate",e)}rotateAroundCenter(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotateAroundCenter",e)}align(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.align",e)}alignAndTranslate(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.alignAndTranslate",e)}translate(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.translate",e)}scale(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scale",e)}scale3d(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scale3d",e)}mirror(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirror",e)}mirrorAlongNormal(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirrorAlongNormal",e)}transformShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.transformShapes",e)}rotateShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotateShapes",e)}rotateAroundCenterShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotateAroundCenterShapes",e)}alignShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.alignShapes",e)}alignAndTranslateShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.alignAndTranslateShapes",e)}translateShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.translateShapes",e)}scaleShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scaleShapes",e)}scale3dShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scale3dShapes",e)}mirrorShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirrorShapes",e)}mirrorAlongNormalShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirrorAlongNormalShapes",e)}}class tz{constructor(e){this.occWorkerManager=e}loft(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.loft",e)}loftAdvanced(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.loftAdvanced",e)}closestPointsBetweenTwoShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.closestPointsBetweenTwoShapes",e)}closestPointsOnShapeFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.closestPointsOnShapeFromPoints",e)}closestPointsOnShapesFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.closestPointsOnShapesFromPoints",e)}distancesToShapeFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.distancesToShapeFromPoints",e)}extrude(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.extrude",e)}extrudeShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.extrudeShapes",e)}splitShapeWithShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.splitShapeWithShapes",e)}revolve(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.revolve",e)}rotatedExtrude(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.rotatedExtrude",e)}pipe(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipe",e)}pipePolylineWireNGon(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipePolylineWireNGon",e)}pipeWiresCylindrical(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipeWiresCylindrical",e)}pipeWireCylindrical(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipeWireCylindrical",e)}offset(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.offset",e)}offsetAdv(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.offsetAdv",e)}makeThickSolidSimple(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.makeThickSolidSimple",e)}makeThickSolidByJoin(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.makeThickSolidByJoin",e)}slice(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.slice",e)}sliceInStepPattern(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.sliceInStepPattern",e)}offset3DWire(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.offset3DWire",e)}}class iz{constructor(e){this.occWorkerManager=e}union(e){return this.occWorkerManager.genericCallToWorkerPromise("booleans.union",e)}difference(e){return this.occWorkerManager.genericCallToWorkerPromise("booleans.difference",e)}intersection(e){return this.occWorkerManager.genericCallToWorkerPromise("booleans.intersection",e)}}class rz{constructor(e){this.occWorkerManager=e}geom2dEllipse(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geom2dEllipse",e)}geom2dTrimmedCurve(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geom2dTrimmedCurve",e)}geom2dSegment(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geom2dSegment",e)}get2dPointFrom2dCurveOnParam(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.get2dPointFrom2dCurveOnParam",e)}geomCircleCurve(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geomCircleCurve",e)}geomEllipseCurve(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geomEllipseCurve",e)}}class sz{constructor(e){this.occWorkerManager=e}cylindricalSurface(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.surfaces.cylindricalSurface",e)}surfaceFromFace(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.surfaces.surfaceFromFace",e)}}class nz{constructor(e){this.curves=new rz(e),this.surfaces=new sz(e)}}class oz{constructor(e){this.occWorkerManager=e}filletEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdges",e)}filletEdgesList(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesList",e)}filletEdgesListOneRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesListOneRadius",e)}filletEdgeVariableRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgeVariableRadius",e)}filletEdgesSameVariableRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesSameVariableRadius",e)}filletEdgesVariableRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesVariableRadius",e)}fillet3DWire(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.fillet3DWire",e)}chamferEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdges",e)}chamferEdgesList(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesList",e)}chamferEdgeTwoDistances(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgeTwoDistances",e)}chamferEdgesTwoDistances(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesTwoDistances",e)}chamferEdgesTwoDistancesLists(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesTwoDistancesLists",e)}chamferEdgeDistAngle(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgeDistAngle",e)}chamferEdgesDistAngle(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesDistAngle",e)}chamferEdgesDistsAngles(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesDistsAngles",e)}fillet2d(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.fillet2d",e)}filletTwoEdgesInPlaneIntoAWire(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletTwoEdgesInPlaneIntoAWire",e)}}class az{constructor(e){this.occWorkerManager=e}basicShapeRepair(e){return this.occWorkerManager.genericCallToWorkerPromise("shapeFix.basicShapeRepair",e)}fixSmallEdgeOnWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapeFix.fixSmallEdgeOnWire",e)}fixEdgeOrientationsAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapeFix.fixEdgeOrientationsAlongWire",e)}}var lz=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class hz{constructor(e){this.occWorkerManager=e,this.shapes=new JG(e),this.geom=new nz(e),this.transforms=new ez(e),this.operations=new tz(e),this.booleans=new iz(e),this.fillets=new oz(e),this.shapeFix=new az(e),this.io=new HG(e)}shapeToMesh(e){return lz(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("shapeToMesh",e)}))}shapesToMeshes(e){return lz(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("shapesToMeshes",e)}))}deleteShape(e){return lz(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("deleteShape",e)}))}deleteShapes(e){return lz(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("deleteShapes",e)}))}cleanAllCache(){return lz(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("cleanAllCache",{})}))}}var cz=function(e,t){return cz=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},cz(e,t)};function uz(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}cz(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}function dz(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],r=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function fz(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var r,s,n=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(e){s={error:e}}finally{try{r&&!r.done&&(i=n.return)&&i.call(n)}finally{if(s)throw s.error}}return o}function pz(e,t,i){if(i||2===arguments.length)for(var r,s=0,n=t.length;s0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,i=this,r=i.hasError,s=i.isStopped,n=i.observers;return r||s?bz:(this.currentObservers=null,n.push(e),new xz((function(){t.currentObservers=null,vz(n,e)})))},t.prototype._checkFinalizedStatuses=function(e){var t=this,i=t.hasError,r=t.thrownError,s=t.isStopped;i?e.error(r):s&&e.complete()},t.prototype.asObservable=function(){var e=new Hz;return e.source=this,e},t.create=function(e,t){return new Qz(e,t)},t}(Hz),Qz=function(e){function t(t,i){var r=e.call(this)||this;return r.destination=t,r.source=i,r}return uz(t,e),t.prototype.next=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===i||i.call(t,e)},t.prototype.error=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===i||i.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,i;return null!==(i=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==i?i:bz},t}($z);!function(e){e.loading="loading",e.loaded="loaded",e.initialised="initialised",e.computing="computing"}(qz||(qz={}));class Zz{constructor(){this.occWorkerState$=new $z,this.promisesMade=[]}occWorkerAlreadyInitialised(){return!!this.occWorker}setOccWorker(e){this.occWorker=e,this.occWorker.onmessage=({data:e})=>{if("occ-initialised"===e)this.occWorkerState$.next({state:qz.initialised});else if("busy"===e)this.occWorkerState$.next({state:qz.computing});else{const t=this.promisesMade.find((t=>t.uid===e.uid));t&&void 0!==e.result&&!e.error?t.resolve(e.result):e.error&&(this.errorCallback&&this.errorCallback(e.error),t.reject(e.error)),this.promisesMade=this.promisesMade.filter((t=>t.uid!==e.uid)),0===this.promisesMade.length?this.occWorkerState$.next({state:qz.loaded}):this.occWorkerState$.next({state:qz.computing})}}}cleanPromisesMade(){this.promisesMade=[]}genericCallToWorkerPromise(e,t){const i=`call${Math.random()}${Date.now()}`,r={uid:i},s=new Promise(((e,t)=>{r.resolve=e,r.reject=t}));return r.promise=s,this.promisesMade.push(r),this.occWorker.postMessage({action:{functionName:e,inputs:t},uid:i}),s}startedTheRun(){return this.genericCallToWorkerPromise("startedTheRun",{})}cleanAllCache(){return this.genericCallToWorkerPromise("cleanAllCache",{})}}!function(e){let t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m,g;!function(e){e.arc="arc",e.intersection="intersection",e.tangent="tangent"}(t=e.joinTypeEnum||(e.joinTypeEnum={})),function(e){e.skin="skin",e.pipe="pipe",e.rectoVerso="rectoVerso"}(i=e.bRepOffsetModeEnum||(e.bRepOffsetModeEnum={})),function(e){e.approxChordLength="approxChordLength",e.approxCentripetal="approxCentripetal",e.approxIsoParametric="approxIsoParametric"}(r=e.approxParametrizationTypeEnum||(e.approxParametrizationTypeEnum={})),function(e){e.outside="outside",e.inside="inside",e.middle="middle"}(s=e.directionEnum||(e.directionEnum={})),function(e){e.iges="iges",e.step="step"}(n=e.fileTypeEnum||(e.fileTypeEnum={})),function(e){e.forward="forward",e.reversed="reversed",e.internal="internal",e.external="external"}(o=e.topAbsOrientationEnum||(e.topAbsOrientationEnum={})),function(e){e.in="in",e.out="out",e.on="on",e.unknown="unknown"}(a=e.topAbsStateEnum||(e.topAbsStateEnum={})),function(e){e.unknown="unknown",e.vertex="vertex",e.edge="edge",e.wire="wire",e.face="face",e.shell="shell",e.solid="solid",e.compSolid="compSolid",e.compound="compound",e.shape="shape"}(l=e.shapeTypeEnum||(e.shapeTypeEnum={})),function(e){e.unqualified="unqualified",e.enclosing="enclosing",e.enclosed="enclosed",e.outside="outside",e.noqualifier="noqualifier"}(h=e.gccEntPositionEnum||(e.gccEntPositionEnum={})),function(e){e.keepSide1="keepSide1",e.keepSide2="keepSide2",e.all="all"}(c=e.positionResultEnum||(e.positionResultEnum={})),function(e){e.none="none",e.keepSide1="keepSide1",e.keepSide2="keepSide2"}(u=e.circleInclusionEnum||(e.circleInclusionEnum={})),function(e){e.none="none",e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(d=e.twoCircleInclusionEnum||(e.twoCircleInclusionEnum={})),function(e){e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(f=e.fourSidesStrictEnum||(e.fourSidesStrictEnum={})),function(e){e.outside="outside",e.inside="inside"}(p=e.twoSidesStrictEnum||(e.twoSidesStrictEnum={})),function(e){e.allWithAll="allWithAll",e.inOrder="inOrder",e.inOrderClosed="inOrderClosed"}(_=e.combinationCirclesForFaceEnum||(e.combinationCirclesForFaceEnum={})),function(e){e[e.curve=0]="curve",e[e.edge=1]="edge",e[e.wire=2]="wire",e[e.face=3]="face"}(m=e.typeSpecificityEnum||(e.typeSpecificityEnum={})),function(e){e.all="all",e.closest="closest",e.furthest="furthest",e.closestAndFurthest="closestAndFurthest"}(g=e.pointProjectionTypeEnum||(e.pointProjectionTypeEnum={})),e.DecomposedMeshDto=class{constructor(e,t){void 0!==e&&(this.faceList=e),void 0!==t&&(this.edgeList=t)}},e.DecomposedFaceDto=class{},e.DecomposedEdgeDto=class{},e.ShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.PointDto=class{constructor(e){this.point=[0,0,0],void 0!==e&&(this.point=e)}},e.XYZDto=class{constructor(e,t,i){void 0!==e&&(this.x=e),void 0!==t&&(this.y=t),void 0!==i&&(this.z=i)}},e.PointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.ConstraintTanLinesFromPtToCircleDto=class{constructor(e,t,i,r,s){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==i&&(this.tolerance=i),void 0!==r&&(this.positionResult=r),void 0!==s&&(this.circleRemainder=s)}},e.ConstraintTanLinesFromTwoPtsToCircleDto=class{constructor(e,t,i,r,s,n){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point1=t),void 0!==i&&(this.point1=i),void 0!==r&&(this.tolerance=r),void 0!==s&&(this.positionResult=s),void 0!==n&&(this.circleRemainder=n)}},e.ConstraintTanLinesOnTwoCirclesDto=class{constructor(e,t,i,r,s){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainders=d.none,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.tolerance=i),void 0!==r&&(this.positionResult=r),void 0!==s&&(this.circleRemainders=s)}},e.ConstraintTanCirclesOnTwoCirclesDto=class{constructor(e,t,i,r){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.tolerance=i),void 0!==r&&(this.radius=r)}},e.ConstraintTanCirclesOnCircleAndPntDto=class{constructor(e,t,i,r){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==i&&(this.tolerance=i),void 0!==r&&(this.radius=r)}},e.CurveAndSurfaceDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.surface=t)}},e.FilletTwoEdgesInPlaneDto=class{constructor(e,t,i,r,s,n){this.planeOrigin=[0,0,0],this.planeDirection=[0,1,0],this.radius=.3,this.solution=-1,void 0!==e&&(this.edge1=e),void 0!==t&&(this.edge2=t),void 0!==i&&(this.planeOrigin=i),void 0!==r&&(this.planeDirection=r),void 0!==s&&(this.radius=s),void 0!==n&&(this.solution=n)}},e.ClosestPointsOnShapeFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.SplitWireOnPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.ClosestPointsOnShapesFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shapes=e),void 0!==t&&(this.points=t)}},e.ClosestPointsBetweenTwoShapesDto=class{constructor(e,t){void 0!==e&&(this.shape1=e),void 0!==t&&(this.shape2=t)}},e.FaceFromSurfaceAndWireDto=class{constructor(e,t,i){this.inside=!0,void 0!==e&&(this.surface=e),void 0!==t&&(this.wire=t),void 0!==i&&(this.inside=i)}},e.WireOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wire=e),void 0!==t&&(this.face=t)}},e.DrawShapeDto=class{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m,g,v){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shape=e),void 0!==t&&(this.faceOpacity=t),void 0!==i&&(this.edgeOpacity=i),void 0!==r&&(this.edgeColour=r),void 0!==s&&(this.faceMaterial=s),void 0!==n&&(this.faceColour=n),void 0!==c&&(this.vertexColour=c),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==l&&(this.drawFaces=l),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==f&&(this.drawEdgeIndexes=f),void 0!==p&&(this.edgeIndexHeight=p),void 0!==_&&(this.edgeIndexColour=_),void 0!==m&&(this.drawFaceIndexes=m),void 0!==g&&(this.faceIndexHeight=g),void 0!==v&&(this.faceIndexColour=v)}},e.DrawShapesDto=class{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m,g,v){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shapes=e),void 0!==t&&(this.faceOpacity=t),void 0!==i&&(this.edgeOpacity=i),void 0!==r&&(this.edgeColour=r),void 0!==s&&(this.faceMaterial=s),void 0!==n&&(this.faceColour=n),void 0!==c&&(this.vertexColour=c),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==l&&(this.drawFaces=l),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==f&&(this.drawEdgeIndexes=f),void 0!==p&&(this.edgeIndexHeight=p),void 0!==_&&(this.edgeIndexColour=_),void 0!==m&&(this.drawFaceIndexes=m),void 0!==g&&(this.faceIndexHeight=g),void 0!==v&&(this.faceIndexColour=v)}},e.FaceSubdivisionDto=class{constructor(e,t,i,r,s,n,o,a,l){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepU=!1,this.removeStartEdgeU=!1,this.removeEndEdgeU=!1,this.shiftHalfStepV=!1,this.removeStartEdgeV=!1,this.removeEndEdgeV=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==i&&(this.nrDivisionsV=i),void 0!==r&&(this.shiftHalfStepU=r),void 0!==s&&(this.removeStartEdgeU=s),void 0!==n&&(this.removeEndEdgeU=n),void 0!==o&&(this.shiftHalfStepV=o),void 0!==a&&(this.removeStartEdgeV=a),void 0!==l&&(this.removeEndEdgeV=l)}},e.FaceSubdivisionToWiresDto=class{constructor(e,t,i,r,s,n){this.nrDivisions=10,this.isU=!0,this.shiftHalfStep=!1,this.removeStart=!1,this.removeEnd=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisions=t),void 0!==i&&(this.isU=i),void 0!==r&&(this.shiftHalfStep=r),void 0!==s&&(this.removeStart=s),void 0!==n&&(this.removeEnd=n)}},e.FaceSubdivideToRectangleWiresDto=class{constructor(e,t,i,r,s,n,o,a,l){this.nrRectanglesU=10,this.nrRectanglesV=10,this.offsetFromBorderU=0,this.offsetFromBorderV=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrRectanglesU=t),void 0!==i&&(this.nrRectanglesU=i),void 0!==r&&(this.scalePatternU=r),void 0!==s&&(this.scalePatternV=s),void 0!==n&&(this.filletPattern=n),void 0!==o&&(this.inclusionPattern=o),void 0!==a&&(this.offsetFromBorderU=a),void 0!==l&&(this.offsetFromBorderV=l)}},e.FaceSubdivideToRectangleHolesDto=class{constructor(e,t,i,r,s,n,o,a,l,h){this.nrRectanglesU=10,this.nrRectanglesV=10,this.holesToFaces=!1,this.offsetFromBorderU=0,this.offsetFromBorderV=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrRectanglesU=t),void 0!==i&&(this.nrRectanglesU=i),void 0!==r&&(this.scalePatternU=r),void 0!==s&&(this.scalePatternV=s),void 0!==n&&(this.filletPattern=n),void 0!==o&&(this.inclusionPattern=o),void 0!==a&&(this.holesToFaces=a),void 0!==l&&(this.offsetFromBorderU=l),void 0!==h&&(this.offsetFromBorderV=h)}},e.FaceSubdivisionControlledDto=class{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepNthU=0,this.shiftHalfStepUOffsetN=0,this.removeStartEdgeNthU=0,this.removeStartEdgeUOffsetN=0,this.removeEndEdgeNthU=0,this.removeEndEdgeUOffsetN=0,this.shiftHalfStepNthV=0,this.shiftHalfStepVOffsetN=0,this.removeStartEdgeNthV=0,this.removeStartEdgeVOffsetN=0,this.removeEndEdgeNthV=0,this.removeEndEdgeVOffsetN=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==i&&(this.nrDivisionsV=i),void 0!==r&&(this.shiftHalfStepNthU=r),void 0!==s&&(this.shiftHalfStepUOffsetN=s),void 0!==n&&(this.removeStartEdgeNthU=n),void 0!==o&&(this.removeStartEdgeUOffsetN=o),void 0!==a&&(this.removeEndEdgeNthU=a),void 0!==l&&(this.removeEndEdgeUOffsetN=l),void 0!==h&&(this.shiftHalfStepNthV=h),void 0!==c&&(this.shiftHalfStepVOffsetN=c),void 0!==u&&(this.removeStartEdgeNthV=u),void 0!==d&&(this.removeStartEdgeVOffsetN=d),void 0!==f&&(this.removeEndEdgeNthV=f),void 0!==p&&(this.removeEndEdgeVOffsetN=p)}},e.FaceLinearSubdivisionDto=class{constructor(e,t,i,r,s,n,o){this.isU=!0,this.param=.5,this.nrPoints=10,this.shiftHalfStep=!1,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.isU=t),void 0!==i&&(this.param=i),void 0!==r&&(this.nrPoints=r),void 0!==s&&(this.shiftHalfStep=s),void 0!==n&&(this.removeStartPoint=n),void 0!==o&&(this.removeEndPoint=o)}},e.WireAlongParamDto=class{constructor(e,t,i){this.isU=!0,this.param=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.isU=t),void 0!==i&&(this.param=i)}},e.WiresAlongParamsDto=class{constructor(e,t,i){this.isU=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.isU=t),void 0!==i&&(this.params=i)}},e.DataOnUVDto=class{constructor(e,t,i){this.paramU=.5,this.paramV=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.paramU=t),void 0!==i&&(this.paramV=i)}},e.DataOnUVsDto=class{constructor(e,t){this.paramsUV=[[.5,.5]],void 0!==e&&(this.shape=e),void 0!==t&&(this.paramsUV=t)}},e.PolygonDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolygonsDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polygons=e),void 0!==t&&(this.returnCompound=t)}},e.PolylineDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolylinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polylines=e),void 0!==t&&(this.returnCompound=t)}},e.SquareDto=class{constructor(e,t,i){this.size=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.RectangleDto=class{constructor(e,t,i,r){this.width=1,this.length=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.center=i),void 0!==r&&(this.direction=r)}},e.LPolygonDto=class{constructor(e,t,i,r,n,o,a,l){this.widthFirst=1,this.lengthFirst=2,this.widthSecond=.5,this.lengthSecond=2,this.align=s.outside,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.widthFirst=e),void 0!==t&&(this.lengthFirst=t),void 0!==i&&(this.widthSecond=i),void 0!==r&&(this.lengthSecond=r),void 0!==n&&(this.align=n),void 0!==o&&(this.rotation=o),void 0!==a&&(this.center=a),void 0!==l&&(this.direction=l)}},e.BoxDto=class{constructor(e,t,i,r){this.width=1,this.length=2,this.height=3,this.center=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.height=i),void 0!==r&&(this.center=r)}},e.CubeDto=class{constructor(e,t){this.size=1,this.center=[0,0,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t)}},e.BoxFromCornerDto=class{constructor(e,t,i,r){this.width=1,this.length=2,this.height=3,this.corner=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.height=i),void 0!==r&&(this.corner=r)}},e.SphereDto=class{constructor(e,t){this.radius=1,this.center=[0,0,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t)}},e.ConeDto=class{constructor(e,t,i,r,s,n){this.radius1=2,this.radius2=1,this.height=2,this.angle=360,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius1=e),void 0!==t&&(this.radius2=t),void 0!==i&&(this.height=i),void 0!==r&&(this.angle=r),void 0!==s&&(this.center=s),void 0!==n&&(this.direction=n)}},e.LineDto=class{constructor(e,t){this.start=[0,0,0],this.end=[0,1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.LinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.lines=e),void 0!==t&&(this.returnCompound=t)}},e.ArcEdgeTwoPointsTangentDto=class{constructor(e,t,i){this.start=[0,0,0],this.tangentVec=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.tangentVec=t),void 0!==i&&(this.end=i)}},e.ArcEdgeCircleTwoPointsDto=class{constructor(e,t,i,r){this.start=[0,0,0],this.end=[0,0,1],this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.start=t),void 0!==i&&(this.end=i),void 0!==r&&(this.sense=r)}},e.ArcEdgeCircleTwoAnglesDto=class{constructor(e,t,i,r){this.alphaAngle1=0,this.alphaAngle2=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle1=t),void 0!==i&&(this.alphaAngle2=i),void 0!==r&&(this.sense=r)}},e.ArcEdgeCirclePointAngleDto=class{constructor(e,t,i,r){this.alphaAngle=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle=t),void 0!==r&&(this.sense=r)}},e.ArcEdgeThreePointsDto=class{constructor(e,t,i){this.start=[0,0,0],this.middle=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.middle=t),void 0!==i&&(this.end=i)}},e.CylinderDto=class{constructor(e,t,i,r){this.radius=1,this.height=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.height=t),void 0!==i&&(this.center=i),void 0!==r&&(this.direction=r)}},e.CylindersOnLinesDto=class{constructor(e,t){void 0!==e&&(this.radius=e),void 0!==t&&(this.lines=t)}},e.FilletDto=class{constructor(e,t,i,r){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.radiusList=i),void 0!==r&&(this.indexes=r)}},e.FilletEdgesListDto=class{constructor(e,t,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusList=i)}},e.FilletEdgesListOneRadiusDto=class{constructor(e,t,i){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radius=i)}},e.FilletEdgeVariableRadiusDto=class{constructor(e,t,i,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.radiusList=i),void 0!==r&&(this.paramsU=r)}},e.FilletEdgesVariableRadiusDto=class{constructor(e,t,i,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusLists=i),void 0!==r&&(this.paramsULists=r)}},e.FilletEdgesSameVariableRadiusDto=class{constructor(e,t,i,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusList=i),void 0!==r&&(this.paramsU=r)}},e.Fillet3DWireDto=class{constructor(e,t,i,r,s){this.radius=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.direction=i),void 0!==r&&(this.radiusList=r),void 0!==s&&(this.indexes=s)}},e.ChamferDto=class{constructor(e,t,i,r){this.distance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.distance=t),void 0!==i&&(this.distanceList=i),void 0!==r&&(this.indexes=r)}},e.ChamferEdgesListDto=class{constructor(e,t,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.distanceList=i)}},e.ChamferEdgeDistAngleDto=class{constructor(e,t,i,r,s){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.face=i),void 0!==r&&(this.distance=r),void 0!==s&&(this.angle=s)}},e.ChamferEdgeTwoDistancesDto=class{constructor(e,t,i,r,s){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.face=i),void 0!==r&&(this.distance1=r),void 0!==s&&(this.distance2=s)}},e.ChamferEdgesTwoDistancesListsDto=class{constructor(e,t,i,r,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==r&&(this.distances1=r),void 0!==s&&(this.distances2=s)}},e.ChamferEdgesTwoDistancesDto=class{constructor(e,t,i,r,s){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==r&&(this.distance1=r),void 0!==s&&(this.distance2=s)}},e.ChamferEdgesDistsAnglesDto=class{constructor(e,t,i,r,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==r&&(this.distances=r),void 0!==s&&(this.angles=s)}},e.ChamferEdgesDistAngleDto=class{constructor(e,t,i,r,s){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==r&&(this.distance=r),void 0!==s&&(this.angle=s)}},e.BSplineDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BSplinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bSplines=e),void 0!==t&&(this.returnCompound=t)}},e.WireFromTwoCirclesTanDto=class{constructor(e,t,i,r,s){this.keepLines=p.outside,this.circleRemainders=f.outside,this.tolerance=1e-7,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.keepLines=i),void 0!==r&&(this.circleRemainders=r),void 0!==s&&(this.tolerance=s)}},e.FaceFromMultipleCircleTanWiresDto=class{constructor(e,t,i,r){this.combination=_.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.circles=e),void 0!==t&&(this.combination=t),void 0!==i&&(this.unify=i),void 0!==r&&(this.tolerance=r)}},e.FaceFromMultipleCircleTanWireCollectionsDto=class{constructor(e,t,i,r){this.combination=_.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.listsOfCircles=e),void 0!==t&&(this.combination=t),void 0!==i&&(this.unify=i),void 0!==r&&(this.tolerance=r)}},e.ZigZagBetweenTwoWiresDto=class{constructor(e,t,i,r,s,n){this.nrZigZags=20,this.divideByEqualDistance=!1,this.zigZagsPerEdge=!0,void 0!==e&&(this.wire1=e),void 0!==t&&(this.wire2=t),void 0!==i&&(this.nrZigZags=i),void 0!==r&&(this.inverse=r),void 0!==s&&(this.divideByEqualDistance=s),void 0!==n&&(this.zigZagsPerEdge=n)}},e.InterpolationDto=class{constructor(e,t,i){this.periodic=!1,this.tolerance=1e-7,void 0!==e&&(this.points=e),void 0!==t&&(this.periodic=t),void 0!==i&&(this.tolerance=i)}},e.InterpolateWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.interpolations=e),void 0!==t&&(this.returnCompound=t)}},e.BezierDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BezierWeightsDto=class{constructor(e,t,i){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.weights=t),void 0!==i&&(this.closed=i)}},e.BezierWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bezierWires=e),void 0!==t&&(this.returnCompound=t)}},e.DivideDto=class{constructor(e,t,i,r){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.removeStartPoint=i),void 0!==r&&(this.removeEndPoint=r)}},e.ProjectWireDto=class{constructor(e,t,i){this.direction=[0,1,0],void 0!==e&&(this.wire=e),void 0!==t&&(this.shape=t),void 0!==i&&(this.direction=i)}},e.ProjectPointsOnShapeDto=class{constructor(e,t,i,r){this.direction=[0,10,0],void 0!==e&&(this.points=e),void 0!==t&&(this.shape=t),void 0!==i&&(this.direction=i),void 0!==r&&(this.projectionType=r)}},e.WiresToPointsDto=class{constructor(e,t,i,r,s,n){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==i&&(this.curvatureDeflection=i),void 0!==r&&(this.minimumOfPoints=r),void 0!==s&&(this.uTolerance=s),void 0!==n&&(this.minimumLength=n)}},e.EdgesToPointsDto=class{constructor(e,t,i,r,s,n){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==i&&(this.curvatureDeflection=i),void 0!==r&&(this.minimumOfPoints=r),void 0!==s&&(this.uTolerance=s),void 0!==n&&(this.minimumLength=n)}},e.ProjectWiresDto=class{constructor(e,t,i){this.direction=[0,1,0],void 0!==e&&(this.wires=e),void 0!==t&&(this.shape=t),void 0!==i&&(this.direction=i)}},e.DivideShapesDto=class{constructor(e,t,i,r){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.removeStartPoint=i),void 0!==r&&(this.removeEndPoint=r)}},e.DataOnGeometryAtParamDto=class{constructor(e,t){this.param=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t)}},e.PointInFaceDto=class{constructor(e,t,i,r){this.tEdgeParam=.5,this.distance2DParam=.5,void 0!==e&&(this.face=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.tEdgeParam=i),void 0!==r&&(this.distance2DParam=r)}},e.PointsOnWireAtEqualLengthDto=class{constructor(e,t,i,r,s){this.length=.5,this.tryNext=!1,this.includeFirst=!1,this.includeLast=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.length=t),void 0!==i&&(this.tryNext=i),void 0!==r&&(this.includeFirst=r),void 0!==s&&(this.includeLast=s)}},e.PointsOnWireAtPatternOfLengthsDto=class{constructor(e,t,i,r,s){this.tryNext=!1,this.includeFirst=!1,this.includeLast=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.lengths=t),void 0!==i&&(this.tryNext=i),void 0!==r&&(this.includeLast=r),void 0!==s&&(this.includeLast=s)}},e.DataOnGeometryAtLengthDto=class{constructor(e,t){this.length=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.length=t)}},e.DataOnGeometryAtLengthsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.lengths=t)}},e.CircleDto=class{constructor(e,t,i){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.LoftDto=class{constructor(e,t){this.makeSolid=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t)}},e.LoftAdvancedDto=class{constructor(e,t,i,s,n,o,a,l,h,c,u,d){this.makeSolid=!1,this.closed=!1,this.periodic=!1,this.straight=!1,this.nrPeriodicSections=10,this.useSmoothing=!1,this.maxUDegree=3,this.tolerance=1e-7,this.parType=r.approxCentripetal,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t),void 0!==i&&(this.closed=i),void 0!==s&&(this.periodic=s),void 0!==n&&(this.straight=n),void 0!==o&&(this.nrPeriodicSections=o),void 0!==a&&(this.useSmoothing=a),void 0!==l&&(this.maxUDegree=l),void 0!==h&&(this.tolerance=h),void 0!==c&&(this.parType=c),void 0!==u&&(this.startVertex=u),void 0!==d&&(this.endVertex=d)}},e.OffsetDto=class{constructor(e,t,i,r){this.distance=.2,this.tolerance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.face=t),void 0!==i&&(this.distance=i),void 0!==r&&(this.tolerance=r)}},e.OffsetAdvancedDto=class{constructor(e,i,r,s,n,o){this.distance=.2,this.tolerance=.1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==i&&(this.face=i),void 0!==r&&(this.distance=r),void 0!==s&&(this.tolerance=s),void 0!==n&&(this.joinType=n),void 0!==o&&(this.removeIntEdges=o)}},e.RevolveDto=class{constructor(e,t,i,r){this.angle=360,this.direction=[0,1,0],this.copy=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.direction=i),void 0!==r&&(this.copy=r)}},e.ShapeShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.WiresOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wires=e),void 0!==t&&(this.face=t)}},e.PipeWiresCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.radius=t)}},e.PipeWireCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t)}},e.PipePolygonWireNGonDto=class{constructor(e,t,i){this.radius=.1,this.nrCorners=6,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.nrCorners=i)}},e.ExtrudeDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t)}},e.ExtrudeShapesDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.direction=t)}},e.SplitDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.UnionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.DifferenceDto=class{constructor(e,t,i){this.keepEdges=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t),void 0!==i&&(this.keepEdges=i)}},e.IntersectionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.ShapeDto=class{constructor(e){void 0!==e&&(this.shape=e)}},e.CompareShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.otherShape=t)}},e.FixSmallEdgesInWireDto=class{constructor(e,t,i){this.lockvtx=!1,this.precsmall=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.lockvtx=t),void 0!==i&&(this.precsmall=i)}},e.BasicShapeRepairDto=class{constructor(e,t,i,r){this.precision=.001,this.maxTolerance=.01,this.minTolerance=1e-4,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.maxTolerance=i),void 0!==r&&(this.minTolerance=r)}},e.FixClosedDto=class{constructor(e,t){this.precision=-.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t)}},e.ShapesWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.ShapeWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.tolerance=t)}},e.ShapeIndexDto=class{constructor(e,t){this.index=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.EdgeIndexDto=class{constructor(e,t){this.index=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.RotationExtrudeDto=class{constructor(e,t,i){this.height=1,this.angle=360,void 0!==e&&(this.shape=e),void 0!==t&&(this.height=t),void 0!==i&&(this.angle=i)}},e.ThickSolidByJoinDto=class{constructor(e,i,r,s,n,o,a,l){this.offset=1,this.tolerance=.001,this.intersection=!1,this.selfIntersection=!1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==i&&(this.shapes=i),void 0!==r&&(this.offset=r),void 0!==s&&(this.tolerance=s),void 0!==n&&(this.intersection=n),void 0!==o&&(this.selfIntersection=o),void 0!==a&&(this.joinType=a),void 0!==l&&(this.removeIntEdges=l)}},e.TransformDto=class{constructor(e,t,i,r,s){this.translation=[0,0,0],this.rotationAxis=[0,1,0],this.rotationAngle=0,this.scaleFactor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t),void 0!==i&&(this.rotationAxis=i),void 0!==r&&(this.rotationAngle=r),void 0!==s&&(this.scaleFactor=s)}},e.TransformShapesDto=class{constructor(e,t,i,r,s){this.translations=[[0,0,0]],this.rotationAxes=[[0,1,0]],this.rotationAngles=[0],this.scaleFactors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t),void 0!==i&&(this.rotationAxes=i),void 0!==r&&(this.rotationAngles=r),void 0!==s&&(this.scaleFactors=s)}},e.TranslateDto=class{constructor(e,t){this.translation=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t)}},e.TranslateShapesDto=class{constructor(e,t){this.translations=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t)}},e.AlignDto=class{constructor(e,t,i,r,s){this.fromOrigin=[0,0,0],this.fromDirection=[0,0,1],this.toOrigin=[0,1,0],this.toDirection=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.fromOrigin=t),void 0!==i&&(this.fromDirection=i),void 0!==r&&(this.toOrigin=r),void 0!==s&&(this.toDirection=s)}},e.AlignShapesDto=class{constructor(e,t,i,r,s){this.fromOrigins=[[0,0,0]],this.fromDirections=[[0,0,1]],this.toOrigins=[[0,1,0]],this.toDirections=[[0,1,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.fromOrigins=t),void 0!==i&&(this.fromDirections=i),void 0!==r&&(this.toOrigins=r),void 0!==s&&(this.toDirections=s)}},e.MirrorDto=class{constructor(e,t,i){this.origin=[0,0,0],this.direction=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.direction=i)}},e.MirrorShapesDto=class{constructor(e,t,i){this.origins=[[0,0,0]],this.directions=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==i&&(this.directions=i)}},e.MirrorAlongNormalDto=class{constructor(e,t,i){this.origin=[0,0,0],this.normal=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.normal=i)}},e.MirrorAlongNormalShapesDto=class{constructor(e,t,i){this.origins=[[0,0,0]],this.normals=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==i&&(this.normals=i)}},e.AlignAndTranslateDto=class{constructor(e,t,i){this.direction=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.center=i)}},e.UnifySameDomainDto=class{constructor(e,t,i,r){this.unifyEdges=!0,this.unifyFaces=!0,this.concatBSplines=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.unifyEdges=t),void 0!==i&&(this.unifyFaces=i),void 0!==r&&(this.concatBSplines=r)}},e.FilterFacePointsDto=class{constructor(e,t,i,r,s,n,o,a,l){this.tolerance=1e-4,this.useBndBox=!1,this.gapTolerance=.1,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==i&&(this.tolerance=i),void 0!==r&&(this.useBndBox=r),void 0!==s&&(this.gapTolerance=s),void 0!==n&&(this.keepIn=n),void 0!==o&&(this.keepOn=o),void 0!==a&&(this.keepOut=a),void 0!==l&&(this.keepUnknown=l)}},e.FilterSolidPointsDto=class{constructor(e,t,i,r,s,n,o){this.tolerance=1e-4,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==i&&(this.tolerance=i),void 0!==r&&(this.keepIn=r),void 0!==s&&(this.keepOn=s),void 0!==n&&(this.keepOut=n),void 0!==o&&(this.keepUnknown=o)}},e.AlignAndTranslateShapesDto=class{constructor(e,t,i){this.directions=[[0,1,0]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.directions=t),void 0!==i&&(this.centers=i)}},e.RotateDto=class{constructor(e,t,i){this.axis=[0,0,1],this.angle=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.angle=i)}},e.RotateAroundCenterDto=class{constructor(e,t,i,r){this.angle=0,this.center=[0,0,0],this.axis=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.center=i),void 0!==r&&(this.axis=r)}},e.RotateShapesDto=class{constructor(e,t,i){this.angles=[0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.axes=t),void 0!==i&&(this.angles=i)}},e.RotateAroundCenterShapesDto=class{constructor(e,t,i,r){this.angles=[0],this.centers=[[0,0,0]],this.axes=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.angles=t),void 0!==i&&(this.centers=i),void 0!==r&&(this.axes=r)}},e.ScaleDto=class{constructor(e,t){this.factor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.factor=t)}},e.ScaleShapesDto=class{constructor(e,t){this.factors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.factors=t)}},e.Scale3DDto=class{constructor(e,t,i){this.scale=[1,1,1],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.scale=t),void 0!==i&&(this.center=i)}},e.Scale3DShapesDto=class{constructor(e,t,i){this.scales=[[1,1,1]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.scales=t),void 0!==i&&(this.centers=i)}},e.ShapeToMeshDto=class{constructor(e,t,i){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.adjustYtoZ=i)}},e.ShapesToMeshesDto=class{constructor(e,t,i){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.adjustYtoZ=i)}},e.SaveStepDto=class{constructor(e,t,i,r){this.fileName="shape.step",this.adjustYtoZ=!1,this.tryDownload=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.adjustYtoZ=i),void 0!==r&&(this.tryDownload=r)}},e.SaveStlDto=class{constructor(e,t,i,r,s,n){this.fileName="shape.stl",this.precision=.01,this.adjustYtoZ=!1,this.tryDownload=!0,this.binary=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.precision=i),void 0!==r&&(this.adjustYtoZ=r),void 0!==s&&(this.tryDownload=s),void 0!==n&&(this.binary=n)}},e.ImportStepIgesFromTextDto=class{constructor(e,t,i){this.fileType=n.step,this.adjustZtoY=!0,void 0!==e&&(this.text=e),void 0!==t&&(this.fileType=t),void 0!==i&&(this.adjustZtoY=i)}},e.ImportStepIgesDto=class{constructor(e,t){this.adjustZtoY=!0,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.adjustZtoY=t)}},e.LoadStepOrIgesDto=class{constructor(e,t,i){this.fileName="shape.igs",this.adjustZtoY=!0,void 0!==e&&(this.filetext=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.adjustZtoY=i)}},e.CompoundShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.ThisckSolidSimpleDto=class{constructor(e,t){this.offset=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t)}},e.Offset3DWireDto=class{constructor(e,t,i){this.offset=1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t),void 0!==i&&(this.direction=i)}},e.FaceFromWireDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.planar=t)}},e.FaceFromWireOnFaceDto=class{constructor(e,t,i){this.inside=!0,void 0!==e&&(this.wire=e),void 0!==t&&(this.face=t),void 0!==i&&(this.inside=i)}},e.FacesFromWiresOnFaceDto=class{constructor(e,t,i){this.inside=!0,void 0!==e&&(this.wires=e),void 0!==t&&(this.face=t),void 0!==i&&(this.inside=i)}},e.FaceFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.FacesFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.FaceFromWiresOnFaceDto=class{constructor(e,t,i){this.inside=!0,void 0!==e&&(this.wires=e),void 0!==t&&(this.face=t),void 0!==i&&(this.inside=i)}},e.SewDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.FaceIsoCurveAtParamDto=class{constructor(e,t,i){this.dir="u",void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t),void 0!==i&&(this.dir=i)}},e.DivideFaceToUVPointsDto=class{constructor(e,t,i,r){this.nrOfPointsU=10,this.nrOfPointsV=10,this.flat=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfPointsU=t),void 0!==i&&(this.nrOfPointsV=i),void 0!==r&&(this.flat=r)}},e.Geom2dEllipseDto=class{constructor(e,t,i,r,s){this.center=[0,0],this.direction=[1,0],this.radiusMinor=1,this.radiusMajor=2,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radiusMinor=i),void 0!==r&&(this.radiusMajor=r),void 0!==s&&(this.sense=s)}},e.Geom2dCircleDto=class{constructor(e,t,i,r){this.center=[0,0],this.direction=[1,0],this.radius=1,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radius=i),void 0!==r&&(this.sense=r)}},e.ChristmasTreeDto=class{constructor(e,t,i,r,s,n,o,a,l,h){this.height=6,this.innerDist=1.5,this.outerDist=3,this.nrSkirts=5,this.trunkHeight=1,this.trunkWidth=1,this.half=!1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.innerDist=t),void 0!==i&&(this.outerDist=i),void 0!==r&&(this.nrSkirts=r),void 0!==s&&(this.trunkHeight=s),void 0!==n&&(this.trunkWidth=n),void 0!==o&&(this.half=o),void 0!==a&&(this.rotation=a),void 0!==l&&(this.origin=l),void 0!==h&&(this.direction=h)}},e.StarDto=class{constructor(e,t,i,r,s,n,o){this.center=[0,0,0],this.direction=[0,1,0],this.numRays=7,this.half=!1,void 0!==e&&(this.outerRadius=e),void 0!==t&&(this.innerRadius=t),void 0!==i&&(this.numRays=i),void 0!==r&&(this.center=r),void 0!==s&&(this.direction=s),void 0!==n&&(this.offsetOuterEdges=n),void 0!==o&&(this.half=o)}},e.ParallelogramDto=class{constructor(e,t,i,r,s,n){this.center=[0,0,0],this.direction=[0,1,0],this.aroundCenter=!0,this.width=2,this.height=1,this.angle=15,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.aroundCenter=i),void 0!==r&&(this.width=r),void 0!==s&&(this.height=s),void 0!==n&&(this.angle=n)}},e.Heart2DDto=class{constructor(e,t,i,r){this.center=[0,0,0],this.direction=[0,1,0],this.rotation=0,this.sizeApprox=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.rotation=i),void 0!==r&&(this.sizeApprox=r)}},e.NGonWireDto=class{constructor(e,t,i,r){this.center=[0,0,0],this.direction=[0,1,0],this.nrCorners=6,this.radius=1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.nrCorners=i),void 0!==r&&(this.radius=r)}},e.EllipseDto=class{constructor(e,t,i,r){this.center=[0,0,0],this.direction=[0,1,0],this.radiusMinor=1,this.radiusMajor=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radiusMinor=i),void 0!==r&&(this.radiusMajor=r)}},e.GeomCylindricalSurfaceDto=class{constructor(e,t,i){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.Geom2dTrimmedCurveDto=class{constructor(e,t,i,r,s){this.u1=0,this.u2=1,this.sense=!0,this.adjustPeriodic=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.u1=t),void 0!==i&&(this.u2=i),void 0!==r&&(this.sense=r),void 0!==s&&(this.adjustPeriodic=s)}},e.Geom2dSegmentDto=class{constructor(e,t){this.start=[0,0],this.end=[1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.SliceDto=class{constructor(e,t,i){this.step=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.step=t),void 0!==i&&(this.direction=i)}},e.SliceInStepPatternDto=class{constructor(e,t,i){this.steps=[.1,.2],this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.steps=t),void 0!==i&&(this.direction=i)}}}(Yz||(Yz={})),function(e){let t;!function(e){e.default="default",e.clearSky="clearSky",e.city="city",e.greyGradient="greyGradient"}(t=e.skyboxEnum||(e.skyboxEnum={}))}(Kz||(Kz={})),"undefined"!=typeof document&&document.currentScript&&document.currentScript.src;class Jz{constructor(e){this.context=e}create(e){const t=new hc.Pq(e.target[0],e.target[1],e.target[2]),i=new is(`arcRotateCamera${Math.random()}`,this.getRadians(e.alpha),this.getRadians(e.beta),e.radius,t,this.context.scene);void 0!==e.angularSensibilityX&&(i.angularSensibilityX=e.angularSensibilityX),void 0!==e.angularSensibilityY&&(i.angularSensibilityY=e.angularSensibilityY),void 0!==e.lowerRadiusLimit&&(i.lowerRadiusLimit=e.lowerRadiusLimit),void 0!==e.upperRadiusLimit&&(i.upperRadiusLimit=e.upperRadiusLimit),void 0!==e.lowerAlphaLimit&&(i.lowerAlphaLimit=this.getRadians(e.lowerAlphaLimit)),void 0!==e.upperAlphaLimit&&(i.upperAlphaLimit=this.getRadians(e.upperAlphaLimit)),void 0!==e.lowerBetaLimit&&(i.lowerBetaLimit=this.getRadians(e.lowerBetaLimit)),void 0!==e.upperBetaLimit&&(i.upperBetaLimit=this.getRadians(e.upperBetaLimit)),void 0!==e.panningSensibility&&(i.panningSensibility=e.panningSensibility),void 0!==e.wheelPrecision&&(i.wheelPrecision=e.wheelPrecision),void 0!==e.maxZ&&(i.maxZ=e.maxZ),i.minZ=0;const r=document.getElementById("renderCanvas");return i.attachControl(r,!0),i}getRadians(e){let t=hc.uM.FromDegrees(e).radians();return e<0&&(t=-t),t}}class eW{constructor(e){this.context=e}create(e){const t=new hc.Pq(e.position[0],e.position[1],e.position[2]),i=new es(`freeCamera${Math.random()}`,t,this.context.scene),r=new hc.Pq(e.target[0],e.target[1],e.target[2]);i.setTarget(r);const s=document.getElementById("renderCanvas");return i.attachControl(s,!0),i.minZ=0,i.maxZ=1e3,i}}class tW{constructor(e){this.context=e}create(e){const t=new hc.Pq(e.position[0],e.position[1],e.position[2]),i=new Jr(`freeCamera${Math.random()}`,t,this.context.scene),r=new hc.Pq(e.target[0],e.target[1],e.target[2]);i.setTarget(r);const s=document.getElementById("renderCanvas");return i.attachControl(s,!0),i.minZ=0,i.maxZ=1e3,i}}class iW{constructor(e){this.context=e,this.free=new eW(this.context),this.arcRotate=new Jz(this.context),this.target=new tW(this.context)}freezeProjectionMatrix(e){e.camera.freezeProjectionMatrix()}unfreezeProjectionMatrix(e){e.camera.unfreezeProjectionMatrix()}setPosition(e){const t=new hc.Pq(e.position[0],e.position[1],e.position[2]);e.camera.position=t}getPosition(e){return[e.camera.position.x,e.camera.position.y,e.camera.position.z]}setTarget(e){const t=new hc.Pq(e.target[0],e.target[1],e.target[2]);e.camera.setTarget(t)}getTarget(e){return[e.camera.target.x,e.camera.target.y,e.camera.target.z]}setSpeed(e){e.camera.speed=e.speed}getSpeed(e){return[e.camera.target.x,e.camera.target.y,e.camera.target.z]}setMinZ(e){e.camera.minZ=e.minZ}setMaxZ(e){e.camera.maxZ=e.maxZ}makeCameraOrthographic(e){e.camera.mode=rt.ORTHOGRAPHIC_CAMERA,e.camera.orthoBottom=e.orthoBottom||-1,e.camera.orthoTop=e.orthoTop||1,e.camera.orthoLeft=e.orthoLeft||-1,e.camera.orthoRight=e.orthoRight||1}makeCameraPerspective(e){e.camera.mode=rt.PERSPECTIVE_CAMERA}}class rW{constructor(e,t){this.context=e,this.color=t}create(e){const t=new Cb(e.name,this.context.scene);return t.baseColor=hc.v9.FromHexString(e.baseColor),t.metallic=e.metallic,t.roughness=e.roughness,t.alpha=e.alpha,t.backFaceCulling=e.backFaceCulling,t.zOffset=e.zOffset,t.alphaMode=1,e.emissiveColor&&(t.emissiveColor=hc.v9.FromHexString(e.emissiveColor)),t}setBaseColor(e){e.material.baseColor=hc.v9.FromHexString(e.baseColor)}setMetallic(e){e.material.metallic=e.metallic}setRoughness(e){e.material.roughness=e.roughness}setAlpha(e){e.material.alpha=e.alpha}setBackFaceCulling(e){e.material.backFaceCulling=e.backFaceCulling}setBaseTexture(e){e.material.baseTexture=e.baseTexture}getBaseColor(e){const t=e.material,i=this.context.remap(t.baseColor.r,0,1,0,255),r=this.context.remap(t.baseColor.g,0,1,0,255),s=this.context.remap(t.baseColor.b,0,1,0,255);return this.color.rgbToHex({r:i,g:r,b:s,min:0,max:255})}getMetallic(e){return e.material.metallic}getRoughness(e){return e.material.roughness}getAlpha(e){return e.material.alpha}getBackFaceCulling(e){return e.material.backFaceCulling}getBaseTexture(e){return e.material.baseTexture}}i(51314),i(65343);Cs.l.ShadersStore.cellPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nvec3 computeCustomDiffuseLighting(lightingInfo info,vec3 diffuseBase,float shadow)\n{diffuseBase=info.diffuse*shadow;\n#ifdef CELLBASIC\nfloat level=1.0;if (info.ndl<0.5)\nlevel=0.5;diffuseBase.rgb*vec3(level,level,level);\n#else\nfloat ToonThresholds[4];ToonThresholds[0]=0.95;ToonThresholds[1]=0.5;ToonThresholds[2]=0.2;ToonThresholds[3]=0.03;float ToonBrightnessLevels[5];ToonBrightnessLevels[0]=1.0;ToonBrightnessLevels[1]=0.8;ToonBrightnessLevels[2]=0.6;ToonBrightnessLevels[3]=0.35;ToonBrightnessLevels[4]=0.2;if (info.ndl>ToonThresholds[0])\n{diffuseBase.rgb*=ToonBrightnessLevels[0];}\nelse if (info.ndl>ToonThresholds[1])\n{diffuseBase.rgb*=ToonBrightnessLevels[1];}\nelse if (info.ndl>ToonThresholds[2])\n{diffuseBase.rgb*=ToonBrightnessLevels[2];}\nelse if (info.ndl>ToonThresholds[3])\n{diffuseBase.rgb*=ToonBrightnessLevels[3];}\nelse\n{diffuseBase.rgb*=ToonBrightnessLevels[4];}\n#endif\nreturn max(diffuseBase,vec3(0.2));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nlightingInfo info;vec3 diffuseBase=vec3(0.,0.,0.);float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}",i(61374);Cs.l.ShadersStore.cellVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class sW extends xn{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.NDOTL=!0,this.CUSTOMUSERLIGHTING=!0,this.CELLBASIC=!0,this.DEPTHPREPASS=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class nW extends bn{constructor(e,t){super(e,t),this.diffuseColor=new H.v9(1,1,1),this._computeHighLevel=!1,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r.effect&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new sW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(s._areTexturesDirty&&(s._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&Sn.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;s._needUVs=!0,s.DIFFUSE=!0}if(s.CELLBASIC=!this.computeHighLevel,(0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=(0,Bt.az)(n,e,s,!1,this._maxSimultaneousLights,this._disableLighting),(0,Bt.OR)(n,o,this,s,!!i),(0,Bt.qB)(e,s,!0,!0),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial();const i=new Tn;s.FOG&&i.addFallback(1,"FOG"),(0,Bt.c4)(s,i,this.maxSimultaneousLights),s.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),s.UV1&&r.push(st.R.UVKind),s.UV2&&r.push(st.R.UV2Kind),s.VERTEXCOLOR&&r.push(st.R.ColorKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="cell",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant"],c=["diffuseSampler"],u=[];(0,Ln.TV)(h),(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights-1}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._mustRebind(r,n,i)&&(this._diffuseTexture&&Sn.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),(0,Ln.gS)(this._activeEffect,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s,this._maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),super.dispose(e)}getClassName(){return"CellMaterial"}clone(e){return it.p.Clone((()=>new nW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.CellMaterial",e}static Parse(e,t,i){return it.p.Parse((()=>new nW(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.uM)("diffuseTexture")],nW.prototype,"_diffuseTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],nW.prototype,"diffuseTexture",void 0),(0,je.Cg)([(0,$e.jT)("diffuse")],nW.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.lK)("computeHighLevel")],nW.prototype,"_computeHighLevel",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],nW.prototype,"computeHighLevel",void 0),(0,je.Cg)([(0,$e.lK)("disableLighting")],nW.prototype,"_disableLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],nW.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.lK)("maxSimultaneousLights")],nW.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],nW.prototype,"maxSimultaneousLights",void 0),(0,X.Y5)("BABYLON.CellMaterial",nW);class oW{constructor(){}}class aW extends Un{AttachAfterBind(e,t){if(this._newUniformInstances)for(const e in this._newUniformInstances){const i=e.toString().split("-");"vec2"==i[0]?t.setVector2(i[1],this._newUniformInstances[e]):"vec3"==i[0]?this._newUniformInstances[e]instanceof H.v9?t.setColor3(i[1],this._newUniformInstances[e]):t.setVector3(i[1],this._newUniformInstances[e]):"vec4"==i[0]?(this._newUniformInstances[e]instanceof H.ov?t.setDirectColor4(i[1],this._newUniformInstances[e]):t.setVector4(i[1],this._newUniformInstances[e]),t.setVector4(i[1],this._newUniformInstances[e])):"mat4"==i[0]?t.setMatrix(i[1],this._newUniformInstances[e]):"float"==i[0]&&t.setFloat(i[1],this._newUniformInstances[e])}if(this._newSamplerInstances)for(const e in this._newSamplerInstances){const i=e.toString().split("-");"sampler2D"==i[0]&&this._newSamplerInstances[e].isReady&&this._newSamplerInstances[e].isReady()&&t.setTexture(i[1],this._newSamplerInstances[e])}}ReviewUniform(e,t){if("uniform"==e&&this._newUniforms)for(let e=0;e0&&n.push(...this._customAttributes),this.ReviewUniform("uniform",t),this.ReviewUniform("sampler",r);const o=this._createdShaderName;return Cl.M.ShadersStore[o+"VertexShader"]&&Cl.M.ShadersStore[o+"PixelShader"]||(Cl.M.ShadersStore[o+"VertexShader"]=this._injectCustomCode(this.VertexShader,"vertex"),Cl.M.ShadersStore[o+"PixelShader"]=this._injectCustomCode(this.FragmentShader,"fragment")),o}_injectCustomCode(e,t){const i=this._getCustomCode(t);for(const t in i){const r=i[t];if(r&&r.length>0){const i="#define "+t;e=e.replace(i,"\n"+r+"\n"+i)}}return e}_getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_BEGIN:this.CustomParts.Vertex_Begin,CUSTOM_VERTEX_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Vertex_Definitions||""),CUSTOM_VERTEX_MAIN_BEGIN:this.CustomParts.Vertex_MainBegin,CUSTOM_VERTEX_UPDATE_POSITION:this.CustomParts.Vertex_Before_PositionUpdated,CUSTOM_VERTEX_UPDATE_NORMAL:this.CustomParts.Vertex_Before_NormalUpdated,CUSTOM_VERTEX_MAIN_END:this.CustomParts.Vertex_MainEnd,CUSTOM_VERTEX_UPDATE_WORLDPOS:this.CustomParts.Vertex_After_WorldPosComputed}:{CUSTOM_FRAGMENT_BEGIN:this.CustomParts.Fragment_Begin,CUSTOM_FRAGMENT_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Fragment_Definitions||""),CUSTOM_FRAGMENT_MAIN_BEGIN:this.CustomParts.Fragment_MainBegin,CUSTOM_FRAGMENT_UPDATE_DIFFUSE:this.CustomParts.Fragment_Custom_Diffuse,CUSTOM_FRAGMENT_UPDATE_ALPHA:this.CustomParts.Fragment_Custom_Alpha,CUSTOM_FRAGMENT_BEFORE_LIGHTS:this.CustomParts.Fragment_Before_Lights,CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:this.CustomParts.Fragment_Before_FragColor,CUSTOM_FRAGMENT_MAIN_END:this.CustomParts.Fragment_MainEnd,CUSTOM_FRAGMENT_BEFORE_FOG:this.CustomParts.Fragment_Before_Fog}}constructor(e,t){super(e,t,!0),this.CustomParts=new oW,this.customShaderNameResolve=this.Builder,this.FragmentShader=Cl.M.ShadersStore.defaultPixelShader,this.VertexShader=Cl.M.ShadersStore.defaultVertexShader,aW.ShaderIndexer++,this._createdShaderName="custom_"+aW.ShaderIndexer}_afterBind(e,t=null,i){if(t){this.AttachAfterBind(e,t);try{super._afterBind(e,t,i)}catch(e){}}}AddUniform(e,t,i){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances={},this._newUniformInstances={}),i&&(-1!=t.indexOf("sampler")?this._newSamplerInstances[t+"-"+e]=i:this._newUniformInstances[t+"-"+e]=i),this._customUniform.push("uniform "+t+" "+e+";"),this._newUniforms.push(e),this}AddAttribute(e){return this._customAttributes||(this._customAttributes=[]),this._customAttributes.push(e),this}Fragment_Begin(e){return this.CustomParts.Fragment_Begin=e,this}Fragment_Definitions(e){return this.CustomParts.Fragment_Definitions=e,this}Fragment_MainBegin(e){return this.CustomParts.Fragment_MainBegin=e,this}Fragment_MainEnd(e){return this.CustomParts.Fragment_MainEnd=e,this}Fragment_Custom_Diffuse(e){return this.CustomParts.Fragment_Custom_Diffuse=e.replace("result","diffuseColor"),this}Fragment_Custom_Alpha(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this}Fragment_Before_Lights(e){return this.CustomParts.Fragment_Before_Lights=e,this}Fragment_Before_Fog(e){return this.CustomParts.Fragment_Before_Fog=e,this}Fragment_Before_FragColor(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this}Vertex_Begin(e){return this.CustomParts.Vertex_Begin=e,this}Vertex_Definitions(e){return this.CustomParts.Vertex_Definitions=e,this}Vertex_MainBegin(e){return this.CustomParts.Vertex_MainBegin=e,this}Vertex_Before_PositionUpdated(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this}Vertex_Before_NormalUpdated(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this}Vertex_After_WorldPosComputed(e){return this.CustomParts.Vertex_After_WorldPosComputed=e,this}Vertex_MainEnd(e){return this.CustomParts.Vertex_MainEnd=e,this}}aW.ShaderIndexer=1,(0,X.Y5)("BABYLON.CustomMaterial",aW);class lW{constructor(){}}class hW extends zm{AttachAfterBind(e,t){if(this._newUniformInstances)for(const e in this._newUniformInstances){const i=e.toString().split("-");"vec2"==i[0]?t.setVector2(i[1],this._newUniformInstances[e]):"vec3"==i[0]?this._newUniformInstances[e]instanceof H.v9?t.setColor3(i[1],this._newUniformInstances[e]):t.setVector3(i[1],this._newUniformInstances[e]):"vec4"==i[0]?(this._newUniformInstances[e]instanceof H.ov?t.setDirectColor4(i[1],this._newUniformInstances[e]):t.setVector4(i[1],this._newUniformInstances[e]),t.setVector4(i[1],this._newUniformInstances[e])):"mat4"==i[0]?t.setMatrix(i[1],this._newUniformInstances[e]):"float"==i[0]&&t.setFloat(i[1],this._newUniformInstances[e])}if(this._newSamplerInstances)for(const e in this._newSamplerInstances){const i=e.toString().split("-");"sampler2D"==i[0]&&this._newSamplerInstances[e].isReady&&this._newSamplerInstances[e].isReady()&&t.setTexture(i[1],this._newSamplerInstances[e])}}ReviewUniform(e,t){if("uniform"==e&&this._newUniforms)for(let e=0;e{if("vertex"===t)return e?e(t,i):i;const r=new $l(i);return r.inlineToken="#define pbr_inline",r.processCode(),e?e(t,r.code):r.code}}n&&this._customAttributes&&this._customAttributes.length>0&&n.push(...this._customAttributes),this.ReviewUniform("uniform",t),this.ReviewUniform("sampler",r);const a=this._createdShaderName;return Cl.M.ShadersStore[a+"VertexShader"]&&Cl.M.ShadersStore[a+"PixelShader"]||(Cl.M.ShadersStore[a+"VertexShader"]=this._injectCustomCode(this.VertexShader,"vertex"),Cl.M.ShadersStore[a+"PixelShader"]=this._injectCustomCode(this.FragmentShader,"fragment")),a}_injectCustomCode(e,t){const i=this._getCustomCode(t);for(const t in i){const r=i[t];if(r&&r.length>0){const i="#define "+t;e=e.replace(i,"\n"+r+"\n"+i)}}return e}_getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_BEGIN:this.CustomParts.Vertex_Begin,CUSTOM_VERTEX_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Vertex_Definitions||""),CUSTOM_VERTEX_MAIN_BEGIN:this.CustomParts.Vertex_MainBegin,CUSTOM_VERTEX_UPDATE_POSITION:this.CustomParts.Vertex_Before_PositionUpdated,CUSTOM_VERTEX_UPDATE_NORMAL:this.CustomParts.Vertex_Before_NormalUpdated,CUSTOM_VERTEX_MAIN_END:this.CustomParts.Vertex_MainEnd,CUSTOM_VERTEX_UPDATE_WORLDPOS:this.CustomParts.Vertex_After_WorldPosComputed}:{CUSTOM_FRAGMENT_BEGIN:this.CustomParts.Fragment_Begin,CUSTOM_FRAGMENT_MAIN_BEGIN:this.CustomParts.Fragment_MainBegin,CUSTOM_FRAGMENT_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Fragment_Definitions||""),CUSTOM_FRAGMENT_UPDATE_ALBEDO:this.CustomParts.Fragment_Custom_Albedo,CUSTOM_FRAGMENT_UPDATE_ALPHA:this.CustomParts.Fragment_Custom_Alpha,CUSTOM_FRAGMENT_BEFORE_LIGHTS:this.CustomParts.Fragment_Before_Lights,CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS:this.CustomParts.Fragment_Custom_MetallicRoughness,CUSTOM_FRAGMENT_UPDATE_MICROSURFACE:this.CustomParts.Fragment_Custom_MicroSurface,CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:this.CustomParts.Fragment_Before_FinalColorComposition,CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:this.CustomParts.Fragment_Before_FragColor,CUSTOM_FRAGMENT_MAIN_END:this.CustomParts.Fragment_MainEnd,CUSTOM_FRAGMENT_BEFORE_FOG:this.CustomParts.Fragment_Before_Fog}}constructor(e,t){super(e,t,!0),this.CustomParts=new lW,this.customShaderNameResolve=this.Builder,this.FragmentShader=Cl.M.ShadersStore.pbrPixelShader,this.VertexShader=Cl.M.ShadersStore.pbrVertexShader,this.FragmentShader=this.FragmentShader.replace(/#include/g,Cl.M.IncludesShadersStore.pbrBlockAlbedoOpacity),this.FragmentShader=this.FragmentShader.replace(/#include/g,Cl.M.IncludesShadersStore.pbrBlockReflectivity),this.FragmentShader=this.FragmentShader.replace(/#include/g,Cl.M.IncludesShadersStore.pbrBlockFinalColorComposition),hW.ShaderIndexer++,this._createdShaderName="custompbr_"+hW.ShaderIndexer}_afterBind(e,t=null,i){if(t){this.AttachAfterBind(e,t);try{super._afterBind(e,t,i)}catch(e){}}}AddUniform(e,t,i){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances={},this._newUniformInstances={}),i&&(-1!=t.indexOf("sampler")?this._newSamplerInstances[t+"-"+e]=i:this._newUniformInstances[t+"-"+e]=i),this._customUniform.push("uniform "+t+" "+e+";"),this._newUniforms.push(e),this}AddAttribute(e){return this._customAttributes||(this._customAttributes=[]),this._customAttributes.push(e),this}Fragment_Begin(e){return this.CustomParts.Fragment_Begin=e,this}Fragment_Definitions(e){return this.CustomParts.Fragment_Definitions=e,this}Fragment_MainBegin(e){return this.CustomParts.Fragment_MainBegin=e,this}Fragment_Custom_Albedo(e){return this.CustomParts.Fragment_Custom_Albedo=e.replace("result","surfaceAlbedo"),this}Fragment_Custom_Alpha(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this}Fragment_Before_Lights(e){return this.CustomParts.Fragment_Before_Lights=e,this}Fragment_Custom_MetallicRoughness(e){return this.CustomParts.Fragment_Custom_MetallicRoughness=e,this}Fragment_Custom_MicroSurface(e){return this.CustomParts.Fragment_Custom_MicroSurface=e,this}Fragment_Before_Fog(e){return this.CustomParts.Fragment_Before_Fog=e,this}Fragment_Before_FinalColorComposition(e){return this.CustomParts.Fragment_Before_FinalColorComposition=e,this}Fragment_Before_FragColor(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this}Fragment_MainEnd(e){return this.CustomParts.Fragment_MainEnd=e,this}Vertex_Begin(e){return this.CustomParts.Vertex_Begin=e,this}Vertex_Definitions(e){return this.CustomParts.Vertex_Definitions=e,this}Vertex_MainBegin(e){return this.CustomParts.Vertex_MainBegin=e,this}Vertex_Before_PositionUpdated(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this}Vertex_Before_NormalUpdated(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this}Vertex_After_WorldPosComputed(e){return this.CustomParts.Vertex_After_WorldPosComputed=e,this}Vertex_MainEnd(e){return this.CustomParts.Vertex_MainEnd=e,this}}hW.ShaderIndexer=1,(0,X.Y5)("BABYLON.PBRCustomMaterial",hW);Cs.l.ShadersStore.firePixelShader="precision highp float;uniform vec4 vEyePosition;varying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\nuniform sampler2D distortionSampler;uniform sampler2D opacitySampler;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;varying vec2 vDistortionCoords2;varying vec2 vDistortionCoords3;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nvec4 bx2(vec4 x)\n{return vec4(2.0)*x-vec4(1.0);}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);float alpha=1.0;\n#ifdef DIFFUSE\nconst float distortionAmount0 =0.092;const float distortionAmount1 =0.092;const float distortionAmount2 =0.092;vec2 heightAttenuation=vec2(0.3,0.39);vec4 noise0=texture2D(distortionSampler,vDistortionCoords1);vec4 noise1=texture2D(distortionSampler,vDistortionCoords2);vec4 noise2=texture2D(distortionSampler,vDistortionCoords3);vec4 noiseSum=bx2(noise0)*distortionAmount0+bx2(noise1)*distortionAmount1+bx2(noise2)*distortionAmount2;vec4 perturbedBaseCoords=vec4(vDiffuseUV,0.0,1.0)+noiseSum*(vDiffuseUV.y*heightAttenuation.x+heightAttenuation.y);vec4 opacityColor=texture2D(opacitySampler,perturbedBaseCoords.xy);\n#ifdef ALPHATEST\nif (opacityColor.r<0.1)\ndiscard;\n#endif\n#include\nbaseColor=texture2D(diffuseSampler,perturbedBaseCoords.xy)*2.0;baseColor*=opacityColor;baseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(1.0,1.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec4 color=vec4(baseColor.rgb,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Cs.l.ShadersStore.fireVertexShader="precision highp float;attribute vec3 position;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\nuniform float time;uniform float speed;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;varying vec2 vDistortionCoords2;varying vec2 vDistortionCoords3;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef DIFFUSE\nvDiffuseUV=uv;vDiffuseUV.y-=0.2;\n#endif\n#include\n#include\n#include\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#ifdef DIFFUSE\nvec3 layerSpeed=vec3(-0.2,-0.52,-0.1)*speed;vDistortionCoords1.x=uv.x;vDistortionCoords1.y=uv.y+layerSpeed.x*time/1000.0;vDistortionCoords2.x=uv.x;vDistortionCoords2.y=uv.y+layerSpeed.y*time/1000.0;vDistortionCoords3.x=uv.x;vDistortionCoords3.y=uv.y+layerSpeed.z*time/1000.0;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class cW extends xn{constructor(){super(),this.DIFFUSE=!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.POINTSIZE=!1,this.FOG=!1,this.UV1=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.BonesPerMesh=0,this.NUM_BONE_INFLUENCERS=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class uW extends bn{constructor(e,t){super(e,t),this.diffuseColor=new H.v9(1,1,1),this.speed=1,this._scaledDiffuse=new H.v9,this._lastTime=0}needAlphaBlending(){return!1}needAlphaTesting(){return!0}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new cW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(s._areTexturesDirty&&(s._needUVs=!1,this._diffuseTexture&&Sn.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;s._needUVs=!0,s.DIFFUSE=!0}if(s.ALPHATEST=!!this._opacityTexture,s._areMiscDirty&&(s.POINTSIZE=this.pointsCloud||n.forcePointsCloud,s.FOG=n.fogEnabled&&e.applyFog&&n.fogMode!==oi.Z.FOGMODE_NONE&&this.fogEnabled,s.LOGARITHMICDEPTH=this._useLogarithmicDepth),(0,Bt.OR)(n,o,this,s,!!i),(0,Bt.qB)(e,s,!1,!0),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial();const i=new Tn;s.FOG&&i.addFallback(1,"FOG"),s.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.UV1&&r.push(st.R.UVKind),s.VERTEXCOLOR&&r.push(st.R.ColorKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="fire",l=["world","view","viewProjection","vEyePosition","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant","time","speed"];(0,Ln.TV)(l);const h=s.toString();t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:l,uniformBuffersNames:[],samplers:["diffuseSampler","distortionSampler","opacitySampler"],defines:h,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:null,maxSimultaneousLights:4,transformFeedbackVaryings:null},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._mustRebind(r,n,i)&&(this._diffuseTexture&&Sn.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix()),this._activeEffect.setTexture("distortionSampler",this._distortionTexture),this._activeEffect.setTexture("opacitySampler",this._opacityTexture)),(0,Ln.gS)(this._activeEffect,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._lastTime+=r.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime),this._activeEffect.setFloat("speed",this.speed),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._distortionTexture&&this._distortionTexture.animations&&this._distortionTexture.animations.length>0&&e.push(this._distortionTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._distortionTexture&&e.push(this._distortionTexture),this._opacityTexture&&e.push(this._opacityTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e||this._distortionTexture===e||this._opacityTexture===e}getClassName(){return"FireMaterial"}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),this._distortionTexture&&this._distortionTexture.dispose(),super.dispose(e)}clone(e){return it.p.Clone((()=>new uW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FireMaterial",e.diffuseColor=this.diffuseColor.asArray(),e.speed=this.speed,this._diffuseTexture&&(e._diffuseTexture=this._diffuseTexture.serialize()),this._distortionTexture&&(e._distortionTexture=this._distortionTexture.serialize()),this._opacityTexture&&(e._opacityTexture=this._opacityTexture.serialize()),e}static Parse(e,t,i){const r=new uW(e.name,t);return r.diffuseColor=H.v9.FromArray(e.diffuseColor),r.speed=e.speed,r.alpha=e.alpha,r.id=e.id,Ge.Y.AddTagsTo(r,e.tags),r.backFaceCulling=e.backFaceCulling,r.wireframe=e.wireframe,e._diffuseTexture&&(r._diffuseTexture=vi.g.Parse(e._diffuseTexture,t,i)),e._distortionTexture&&(r._distortionTexture=vi.g.Parse(e._distortionTexture,t,i)),e._opacityTexture&&(r._opacityTexture=vi.g.Parse(e._opacityTexture,t,i)),r}}(0,je.Cg)([(0,$e.uM)("diffuseTexture")],uW.prototype,"_diffuseTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],uW.prototype,"diffuseTexture",void 0),(0,je.Cg)([(0,$e.uM)("distortionTexture")],uW.prototype,"_distortionTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],uW.prototype,"distortionTexture",void 0),(0,je.Cg)([(0,$e.uM)("opacityTexture")],uW.prototype,"_opacityTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],uW.prototype,"opacityTexture",void 0),(0,je.Cg)([(0,$e.jT)("diffuse")],uW.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.lK)()],uW.prototype,"speed",void 0),(0,X.Y5)("BABYLON.FireMaterial",uW);Cs.l.ShadersStore.furPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;uniform vec4 furColor;uniform float furLength;varying vec3 vPositionW;varying float vfur_length;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef HIGHLEVEL\nuniform float furOffset;uniform float furOcclusion;uniform sampler2D furTexture;varying vec2 vFurUV;\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#include\n#include\nfloat Rand(vec3 rv) {float x=dot(rv,vec3(12.9898,78.233,24.65487));return fract(sin(x)*43758.5453);}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=furColor;vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor*=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef HIGHLEVEL\nvec4 furTextureColor=texture2D(furTexture,vec2(vFurUV.x,vFurUV.y));if (furTextureColor.a<=0.0 || furTextureColor.g[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase.rgb*baseColor.rgb,0.0,1.0);\n#ifdef HIGHLEVEL\nvec4 color=vec4(finalDiffuse,alpha);\n#else\nfloat r=vfur_length/furLength*0.5;vec4 color=vec4(finalDiffuse*(0.5+r),alpha);\n#endif\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Cs.l.ShadersStore.furVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\nuniform float furLength;uniform float furAngle;\n#ifdef HIGHLEVEL\nuniform float furOffset;uniform vec3 furGravity;uniform float furTime;uniform float furSpacing;uniform float furDensity;\n#endif\n#ifdef HEIGHTMAP\nuniform sampler2D heightTexture;\n#endif\n#ifdef HIGHLEVEL\nvarying vec2 vFurUV;\n#endif\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\nvarying float vfur_length;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nfloat Rand(vec3 rv) {float x=dot(rv,vec3(12.9898,78.233,24.65487));return fract(sin(x)*43758.5453);}\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nfloat r=Rand(position);\n#ifdef HEIGHTMAP\n#if __VERSION__>100\nvfur_length=furLength*texture(heightTexture,uv).x;\n#else\nvfur_length=furLength*texture2D(heightTexture,uv).r;\n#endif\n#else \nvfur_length=(furLength*r);\n#endif\nvec3 tangent1=vec3(normal.y,-normal.x,0);vec3 tangent2=vec3(-normal.z,0,normal.x);r=Rand(tangent1*r);float J=(2.0+4.0*r);r=Rand(tangent2*r);float K=(2.0+2.0*r);tangent1=tangent1*J+tangent2*K;tangent1=normalize(tangent1);vec3 newPosition=position+normal*vfur_length*cos(furAngle)+tangent1*vfur_length*sin(furAngle);\n#ifdef HIGHLEVEL\nvec3 forceDirection=vec3(0.0,0.0,0.0);forceDirection.x=sin(furTime+position.x*0.05)*0.2;forceDirection.y=cos(furTime*0.7+position.y*0.04)*0.2;forceDirection.z=sin(furTime*0.7+position.z*0.04)*0.2;vec3 displacement=vec3(0.0,0.0,0.0);displacement=furGravity+forceDirection;float displacementFactor=pow(furOffset,3.0);vec3 aNormal=normal;aNormal.xyz+=displacement*displacementFactor;newPosition=vec3(newPosition.x,newPosition.y,newPosition.z)+(normalize(aNormal)*furOffset*furSpacing);\n#endif\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\ngl_Position=viewProjection*finalWorld*vec4(newPosition,1.0);vec4 worldPos=finalWorld*vec4(newPosition,1.0);vPositionW=vec3(worldPos);\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#ifdef HIGHLEVEL\nvFurUV=vDiffuseUV*furDensity;\n#endif\n#else\n#ifdef HIGHLEVEL\nvFurUV=uv*furDensity;\n#endif\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class dW extends xn{constructor(){super(),this.DIFFUSE=!1,this.HEIGHTMAP=!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.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.HIGHLEVEL=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class fW extends bn{constructor(e,t){super(e,t),this.diffuseColor=new H.v9(1,1,1),this.furLength=1,this.furAngle=0,this.furColor=new H.v9(.44,.21,.02),this.furOffset=0,this.furSpacing=12,this.furGravity=new W.Pq(0,0,0),this.furSpeed=100,this.furDensity=20,this.furOcclusion=0,this._disableLighting=!1,this._maxSimultaneousLights=4,this.highLevelFur=!0,this._furTime=0}get furTime(){return this._furTime}set furTime(e){this._furTime=e}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}updateFur(){for(let e=1;e0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),s.UV1&&r.push(st.R.UVKind),s.UV2&&r.push(st.R.UV2Kind),s.VERTEXCOLOR&&r.push(st.R.ColorKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="fur",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant","furLength","furAngle","furColor","furOffset","furGravity","furTime","furSpacing","furDensity","furOcclusion"];(0,Ln.TV)(h);const c=["diffuseSampler","heightTexture","furTexture"],u=[];(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._mustRebind(r,n,i)&&(this._diffuseTexture&&Sn.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),this._heightTexture&&this._activeEffect.setTexture("heightTexture",this._heightTexture),(0,Ln.gS)(this._activeEffect,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._activeEffect.setFloat("furLength",this.furLength),this._activeEffect.setFloat("furAngle",this.furAngle),this._activeEffect.setColor4("furColor",this.furColor,1),this.highLevelFur&&(this._activeEffect.setVector3("furGravity",this.furGravity),this._activeEffect.setFloat("furOffset",this.furOffset),this._activeEffect.setFloat("furSpacing",this.furSpacing),this._activeEffect.setFloat("furDensity",this.furDensity),this._activeEffect.setFloat("furOcclusion",this.furOcclusion),this._furTime+=this.getScene().getEngine().getDeltaTime()/this.furSpeed,this._activeEffect.setFloat("furTime",this._furTime),this._activeEffect.setTexture("furTexture",this.furTexture)),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.heightTexture&&this.heightTexture.animations&&this.heightTexture.animations.length>0&&e.push(this.heightTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._heightTexture&&e.push(this._heightTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e||this._heightTexture===e}dispose(e){if(this.diffuseTexture&&this.diffuseTexture.dispose(),this._meshes)for(let t=1;tnew fW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FurMaterial",this._meshes&&(e.sourceMeshName=this._meshes[0].name,e.quality=this._meshes.length),e}getClassName(){return"FurMaterial"}static Parse(e,t,i){const r=it.p.Parse((()=>new fW(e.name,t)),e,t,i);return e.sourceMeshName&&r.highLevelFur&&t.executeWhenReady((()=>{const i=t.getMeshByName(e.sourceMeshName);if(i){const s=fW.GenerateTexture("Fur Texture",t);r.furTexture=s,fW.FurifyMesh(i,e.quality)}})),r}static GenerateTexture(e,t){const i=new Gn("FurTexture "+e,256,t,!0),r=i.getContext();for(let e=0;e<2e4;++e)r.fillStyle="rgba(255, "+Math.floor(255*Math.random())+", "+Math.floor(255*Math.random())+", 1)",r.fillRect(Math.random()*i.getSize().width,Math.random()*i.getSize().height,2,2);return i.update(!1),i.wrapU=vi.g.WRAP_ADDRESSMODE,i.wrapV=vi.g.WRAP_ADDRESSMODE,i}static FurifyMesh(e,t){const i=[e],r=e.material;let s;if(!(r instanceof fW))throw"The material of the source mesh must be a Fur Material";for(s=1;s0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),s.UV1&&r.push(st.R.UVKind),s.UV2&&r.push(st.R.UV2Kind),s.VERTEXCOLOR&&r.push(st.R.ColorKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="gradient",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","logarithmicDepthConstant","topColor","bottomColor","offset","smoothness","scale"];(0,Ln.TV)(h);const c=[],u=[];(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:4}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,n),this._mustRebind(r,n,i)&&((0,Ln.gS)(n,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),r.lightsEnabled&&!this.disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._activeEffect.setColor4("topColor",this.topColor,this.topColorAlpha),this._activeEffect.setColor4("bottomColor",this.bottomColor,this.bottomColorAlpha),this._activeEffect.setFloat("offset",this.offset),this._activeEffect.setFloat("scale",this.scale),this._activeEffect.setFloat("smoothness",this.smoothness),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return it.p.Clone((()=>new _W(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GradientMaterial",e}getClassName(){return"GradientMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new _W(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.lK)("maxSimultaneousLights")],_W.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],_W.prototype,"maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.jT)()],_W.prototype,"topColor",void 0),(0,je.Cg)([(0,$e.lK)()],_W.prototype,"topColorAlpha",void 0),(0,je.Cg)([(0,$e.jT)()],_W.prototype,"bottomColor",void 0),(0,je.Cg)([(0,$e.lK)()],_W.prototype,"bottomColorAlpha",void 0),(0,je.Cg)([(0,$e.lK)()],_W.prototype,"offset",void 0),(0,je.Cg)([(0,$e.lK)()],_W.prototype,"scale",void 0),(0,je.Cg)([(0,$e.lK)()],_W.prototype,"smoothness",void 0),(0,je.Cg)([(0,$e.lK)("disableLighting")],_W.prototype,"_disableLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],_W.prototype,"disableLighting",void 0),(0,X.Y5)("BABYLON.GradientMaterial",_W);Cs.l.ShadersStore.gridPixelShader="#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;uniform float visibility;uniform vec3 mainColor;uniform vec3 lineColor;uniform vec4 gridControl;uniform vec3 gridOffset;varying vec3 vPosition;varying vec3 vNormal;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#ifdef OPACITY\nvarying vec2 vOpacityUV;uniform sampler2D opacitySampler;uniform vec2 vOpacityInfos;\n#endif\nfloat getDynamicVisibility(float position) {float majorGridFrequency=gridControl.y;if (floor(position+0.5)==floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{return 1.0;}\nreturn gridControl.z;}\nfloat getAnisotropicAttenuation(float differentialLength) {const float maxNumberOfLines=10.0;return clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);}\nfloat isPointOnLine(float position,float differentialLength) {float fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \n#ifdef ANTIALIAS\nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);float result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result;\n#else\nreturn abs(fractionPartOfPosition)\nfloat gridRatio=gridControl.x;vec3 gridPos=(vPosition+gridOffset.xyz)/gridRatio;float x=contributionOnAxis(gridPos.x);float y=contributionOnAxis(gridPos.y);float z=contributionOnAxis(gridPos.z);vec3 normal=normalize(vNormal);x*=normalImpactOnAxis(normal.x);y*=normalImpactOnAxis(normal.y);z*=normalImpactOnAxis(normal.z);\n#ifdef MAX_LINE\nfloat grid=clamp(max(max(x,y),z),0.,1.);\n#else\nfloat grid=clamp(x+y+z,0.,1.);\n#endif\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include\n#endif\nfloat opacity=1.0;\n#ifdef TRANSPARENT\nopacity=clamp(grid,0.08,gridControl.w*grid);\n#endif\n#ifdef OPACITY\nopacity*=texture2D(opacitySampler,vOpacityUV).a;\n#endif\ngl_FragColor=vec4(color.rgb,opacity*visibility);\n#ifdef TRANSPARENT\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Cs.l.ShadersStore.gridVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#include\nuniform mat4 projection;uniform mat4 view;varying vec3 vPosition;varying vec3 vNormal;\n#include\n#include\n#ifdef OPACITY\nvarying vec2 vOpacityUV;uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#include\nvec4 cameraSpacePosition=view*worldPos;gl_Position=projection*cameraSpacePosition;\n#ifdef OPACITY\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\nif (vOpacityInfos.x==0.)\n{vOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));}\nelse\n{vOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));}\n#endif \n#include\n#include\nvPosition=position;vNormal=normal;\n#define CUSTOM_VERTEX_MAIN_END\n}";class mW extends xn{constructor(){super(),this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.OPACITY=!1,this.ANTIALIAS=!1,this.TRANSPARENT=!1,this.FOG=!1,this.PREMULTIPLYALPHA=!1,this.MAX_LINE=!1,this.UV1=!1,this.UV2=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class gW extends bn{constructor(e,t){super(e,t),this.mainColor=H.v9.Black(),this.lineColor=H.v9.Teal(),this.gridRatio=1,this.gridOffset=W.Pq.Zero(),this.majorUnitFrequency=10,this.minorUnitVisibility=.33,this.opacity=1,this.antialias=!0,this.preMultiplyAlpha=!1,this.useMaxLine=!1,this._gridControl=new W.IU(this.gridRatio,this.majorUnitFrequency,this.minorUnitVisibility,this.opacity)}needAlphaBlending(){return this.opacity<1||this._opacityTexture&&this._opacityTexture.isReady()}needAlphaBlendingForMesh(e){return e.visibility<1||this.needAlphaBlending()}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r.effect&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new mW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;if(s.TRANSPARENT!==this.opacity<1&&(s.TRANSPARENT=!s.TRANSPARENT,s.markAsUnprocessed()),s.PREMULTIPLYALPHA!=this.preMultiplyAlpha&&(s.PREMULTIPLYALPHA=!s.PREMULTIPLYALPHA,s.markAsUnprocessed()),s.MAX_LINE!==this.useMaxLine&&(s.MAX_LINE=!s.MAX_LINE,s.markAsUnprocessed()),s.ANTIALIAS!==this.antialias&&(s.ANTIALIAS=!s.ANTIALIAS,s.markAsUnprocessed()),s._areTexturesDirty&&(s._needUVs=!1,n.texturesEnabled&&this._opacityTexture&&Sn.OpacityTextureEnabled)){if(!this._opacityTexture.isReady())return!1;s._needUVs=!0,s.OPACITY=!0}if((0,Bt.fm)(e,n,this._useLogarithmicDepth,!1,this.fogEnabled,!1,s),(0,Bt.OR)(n,n.getEngine(),this,s,!!i),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial(),(0,Bt.qB)(e,s,!1,!1);const i=[st.R.PositionKind,st.R.NormalKind];s.UV1&&i.push(st.R.UVKind),s.UV2&&i.push(st.R.UV2Kind),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess,(0,Bt.ER)(i,s);const r=["projection","mainColor","lineColor","gridControl","gridOffset","vFogInfos","vFogColor","world","view","opacityMatrix","vOpacityInfos","visibility","logarithmicDepthConstant"],o=s.toString();(0,Ln.TV)(r),t.setEffect(n.getEngine().createEffect("grid",i,r,["opacitySampler"],o,void 0,this.onCompiled,this.onError),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,this._activeEffect.setFloat("visibility",t.visibility),s.INSTANCES&&!s.THIN_INSTANCE||this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("view",r.getViewMatrix()),this._activeEffect.setMatrix("projection",r.getProjectionMatrix()),this._mustRebind(r,n,i)&&(this._activeEffect.setColor3("mainColor",this.mainColor),this._activeEffect.setColor3("lineColor",this.lineColor),this._activeEffect.setVector3("gridOffset",this.gridOffset),this._gridControl.x=this.gridRatio,this._gridControl.y=Math.round(this.majorUnitFrequency),this._gridControl.z=this.minorUnitVisibility,this._gridControl.w=this.opacity,this._activeEffect.setVector4("gridControl",this._gridControl),this._opacityTexture&&Sn.OpacityTextureEnabled&&(this._activeEffect.setTexture("opacitySampler",this._opacityTexture),this._activeEffect.setFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),this._activeEffect.setMatrix("opacityMatrix",this._opacityTexture.getTextureMatrix())),(0,Ln.gS)(n,this,r),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r)),(0,Bt.Yy)(r,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}dispose(e){super.dispose(e)}clone(e){return it.p.Clone((()=>new gW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GridMaterial",e}getClassName(){return"GridMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new gW(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.jT)()],gW.prototype,"mainColor",void 0),(0,je.Cg)([(0,$e.jT)()],gW.prototype,"lineColor",void 0),(0,je.Cg)([(0,$e.lK)()],gW.prototype,"gridRatio",void 0),(0,je.Cg)([(0,$e.P_)()],gW.prototype,"gridOffset",void 0),(0,je.Cg)([(0,$e.lK)()],gW.prototype,"majorUnitFrequency",void 0),(0,je.Cg)([(0,$e.lK)()],gW.prototype,"minorUnitVisibility",void 0),(0,je.Cg)([(0,$e.lK)()],gW.prototype,"opacity",void 0),(0,je.Cg)([(0,$e.lK)()],gW.prototype,"antialias",void 0),(0,je.Cg)([(0,$e.lK)()],gW.prototype,"preMultiplyAlpha",void 0),(0,je.Cg)([(0,$e.lK)()],gW.prototype,"useMaxLine",void 0),(0,je.Cg)([(0,$e.uM)("opacityTexture")],gW.prototype,"_opacityTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],gW.prototype,"opacityTexture",void 0),(0,X.Y5)("BABYLON.GridMaterial",gW);Cs.l.ShadersStore.lavaPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;uniform float time;uniform float speed;uniform float movingSpeed;uniform vec3 fogColor;uniform sampler2D noiseTexture;uniform float fogDensity;varying float noise;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include\n#include\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nfloat random( vec3 scale,float seed ){return fract( sin( dot( gl_FragCoord.xyz+seed,scale ) )*43758.5453+seed ) ;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nvec4 noiseTex=texture2D( noiseTexture,vDiffuseUV );vec2 T1=vDiffuseUV+vec2( 1.5,-1.5 )*time *0.02;vec2 T2=vDiffuseUV+vec2( -0.5,2.0 )*time*0.01*speed;T1.x+=noiseTex.x*2.0;T1.y+=noiseTex.y*2.0;T2.x-=noiseTex.y*0.2+time*0.001*movingSpeed;T2.y+=noiseTex.z*0.2+time*0.002*movingSpeed;float p=texture2D( noiseTexture,T1*3.0 ).a;vec4 lavaColor=texture2D( diffuseSampler,T2*4.0);vec4 temp=lavaColor*( vec4( p,p,p,p )*2. )+( lavaColor*lavaColor-0.1 );baseColor=temp;float depth=gl_FragCoord.z*4.0;const float LOG2=1.442695;float fogFactor=exp2(-fogDensity*fogDensity*depth*depth*LOG2 );fogFactor=1.0-clamp( fogFactor,0.0,1.0 );baseColor=mix( baseColor,vec4( fogColor,baseColor.w ),fogFactor );diffuseColor=baseColor.rgb;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#include[0]\n#include[1]\n#include[2]\n#include[3]\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Cs.l.ShadersStore.lavaVertexShader="precision highp float;uniform float time;uniform float lowFrequencySpeed;varying float noise;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n/* NOISE FUNCTIONS */\nvec3 mod289(vec3 x)\n{return x-floor(x*(1.0/289.0))*289.0;}\nvec4 mod289(vec4 x)\n{return x-floor(x*(1.0/289.0))*289.0;}\nvec4 permute(vec4 x)\n{return mod289(((x*34.0)+1.0)*x);}\nvec4 taylorInvSqrt(vec4 r)\n{return 1.79284291400159-0.85373472095314*r;}\nvec3 fade(vec3 t) {return t*t*t*(t*(t*6.0-15.0)+10.0);}\nfloat pnoise(vec3 P,vec3 rep)\n{vec3 Pi0=mod(floor(P),rep); \nvec3 Pi1=mod(Pi0+vec3(1.0),rep); \nPi0=mod289(Pi0);Pi1=mod289(Pi1);vec3 Pf0=fract(P); \nvec3 Pf1=Pf0-vec3(1.0); \nvec4 ix=vec4(Pi0.x,Pi1.x,Pi0.x,Pi1.x);vec4 iy=vec4(Pi0.yy,Pi1.yy);vec4 iz0=Pi0.zzzz;vec4 iz1=Pi1.zzzz;vec4 ixy=permute(permute(ix)+iy);vec4 ixy0=permute(ixy+iz0);vec4 ixy1=permute(ixy+iz1);vec4 gx0=ixy0*(1.0/7.0);vec4 gy0=fract(floor(gx0)*(1.0/7.0))-0.5;gx0=fract(gx0);vec4 gz0=vec4(0.5)-abs(gx0)-abs(gy0);vec4 sz0=step(gz0,vec4(0.0));gx0-=sz0*(step(0.0,gx0)-0.5);gy0-=sz0*(step(0.0,gy0)-0.5);vec4 gx1=ixy1*(1.0/7.0);vec4 gy1=fract(floor(gx1)*(1.0/7.0))-0.5;gx1=fract(gx1);vec4 gz1=vec4(0.5)-abs(gx1)-abs(gy1);vec4 sz1=step(gz1,vec4(0.0));gx1-=sz1*(step(0.0,gx1)-0.5);gy1-=sz1*(step(0.0,gy1)-0.5);vec3 g000=vec3(gx0.x,gy0.x,gz0.x);vec3 g100=vec3(gx0.y,gy0.y,gz0.y);vec3 g010=vec3(gx0.z,gy0.z,gz0.z);vec3 g110=vec3(gx0.w,gy0.w,gz0.w);vec3 g001=vec3(gx1.x,gy1.x,gz1.x);vec3 g101=vec3(gx1.y,gy1.y,gz1.y);vec3 g011=vec3(gx1.z,gy1.z,gz1.z);vec3 g111=vec3(gx1.w,gy1.w,gz1.w);vec4 norm0=taylorInvSqrt(vec4(dot(g000,g000),dot(g010,g010),dot(g100,g100),dot(g110,g110)));g000*=norm0.x;g010*=norm0.y;g100*=norm0.z;g110*=norm0.w;vec4 norm1=taylorInvSqrt(vec4(dot(g001,g001),dot(g011,g011),dot(g101,g101),dot(g111,g111)));g001*=norm1.x;g011*=norm1.y;g101*=norm1.z;g111*=norm1.w;float n000=dot(g000,Pf0);float n100=dot(g100,vec3(Pf1.x,Pf0.yz));float n010=dot(g010,vec3(Pf0.x,Pf1.y,Pf0.z));float n110=dot(g110,vec3(Pf1.xy,Pf0.z));float n001=dot(g001,vec3(Pf0.xy,Pf1.z));float n101=dot(g101,vec3(Pf1.x,Pf0.y,Pf1.z));float n011=dot(g011,vec3(Pf0.x,Pf1.yz));float n111=dot(g111,Pf1);vec3 fade_xyz=fade(Pf0);vec4 n_z=mix(vec4(n000,n100,n010,n110),vec4(n001,n101,n011,n111),fade_xyz.z);vec2 n_yz=mix(n_z.xy,n_z.zw,fade_xyz.y);float n_xyz=mix(n_yz.x,n_yz.y,fade_xyz.x);return 2.2*n_xyz;}\n/* END FUNCTION */\nfloat turbulence( vec3 p ) {float w=100.0;float t=-.5;for (float f=1.0 ; f<=10.0 ; f++ ){float power=pow( 2.0,f );t+=abs( pnoise( vec3( power*p ),vec3( 10.0,10.0,10.0 ) )/power );}\nreturn t;}\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\n#ifdef NORMAL\nnoise=10.0* -.10*turbulence( .5*normal+time*1.15 );float b=lowFrequencySpeed*5.0*pnoise( 0.05*position +vec3(time*1.025),vec3( 100.0 ) );float displacement=- 1.5*noise+b;vec3 newPosition=position+normal*displacement;gl_Position=viewProjection*finalWorld*vec4( newPosition,1.0 );vec4 worldPos=finalWorld*vec4(newPosition,1.0);vPositionW=vec3(worldPos);vNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";class vW extends xn{constructor(){super(),this.DIFFUSE=!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.POINTSIZE=!1,this.FOG=!1,this.LIGHT0=!1,this.LIGHT1=!1,this.LIGHT2=!1,this.LIGHT3=!1,this.SPOTLIGHT0=!1,this.SPOTLIGHT1=!1,this.SPOTLIGHT2=!1,this.SPOTLIGHT3=!1,this.HEMILIGHT0=!1,this.HEMILIGHT1=!1,this.HEMILIGHT2=!1,this.HEMILIGHT3=!1,this.DIRLIGHT0=!1,this.DIRLIGHT1=!1,this.DIRLIGHT2=!1,this.DIRLIGHT3=!1,this.POINTLIGHT0=!1,this.POINTLIGHT1=!1,this.POINTLIGHT2=!1,this.POINTLIGHT3=!1,this.SHADOW0=!1,this.SHADOW1=!1,this.SHADOW2=!1,this.SHADOW3=!1,this.SHADOWS=!1,this.SHADOWESM0=!1,this.SHADOWESM1=!1,this.SHADOWESM2=!1,this.SHADOWESM3=!1,this.SHADOWPOISSON0=!1,this.SHADOWPOISSON1=!1,this.SHADOWPOISSON2=!1,this.SHADOWPOISSON3=!1,this.SHADOWPCF0=!1,this.SHADOWPCF1=!1,this.SHADOWPCF2=!1,this.SHADOWPCF3=!1,this.SHADOWPCSS0=!1,this.SHADOWPCSS1=!1,this.SHADOWPCSS2=!1,this.SHADOWPCSS3=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.UNLIT=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class xW extends bn{constructor(e,t){super(e,t),this.speed=1,this.movingSpeed=1,this.lowFrequencySpeed=1,this.fogDensity=.15,this._lastTime=0,this.diffuseColor=new H.v9(1,1,1),this._disableLighting=!1,this._unlit=!1,this._maxSimultaneousLights=4,this._scaledDiffuse=new H.v9}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r.effect&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new vW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(s._areTexturesDirty&&(s._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&Sn.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;s._needUVs=!0,s.DIFFUSE=!0}if((0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=!0,(0,Bt.az)(n,e,s,!1,this._maxSimultaneousLights,this._disableLighting),(0,Bt.OR)(n,o,this,s,!!i),(0,Bt.qB)(e,s,!0,!0),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial();const i=new Tn;s.FOG&&i.addFallback(1,"FOG"),(0,Bt.c4)(s,i),s.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),s.UV1&&r.push(st.R.UVKind),s.UV2&&r.push(st.R.UV2Kind),s.VERTEXCOLOR&&r.push(st.R.ColorKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="lava",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant","time","speed","movingSpeed","fogColor","fogDensity","lowFrequencySpeed"];(0,Ln.TV)(h);const c=["diffuseSampler","noiseTexture"],u=[];(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,s.UNLIT=this._unlit,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._mustRebind(r,n,i)&&(this.diffuseTexture&&Sn.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),this.noiseTexture&&this._activeEffect.setTexture("noiseTexture",this.noiseTexture),(0,Ln.gS)(n,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._lastTime+=r.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime*this.speed/1e3),this.fogColor||(this.fogColor=H.v9.Black()),this._activeEffect.setColor3("fogColor",this.fogColor),this._activeEffect.setFloat("fogDensity",this.fogDensity),this._activeEffect.setFloat("lowFrequencySpeed",this.lowFrequencySpeed),this._activeEffect.setFloat("movingSpeed",this.movingSpeed),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.noiseTexture&&this.noiseTexture.animations&&this.noiseTexture.animations.length>0&&e.push(this.noiseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this.diffuseTexture&&this.diffuseTexture.dispose(),this.noiseTexture&&this.noiseTexture.dispose(),super.dispose(e)}clone(e){return it.p.Clone((()=>new xW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.LavaMaterial",e}getClassName(){return"LavaMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new xW(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.uM)("diffuseTexture")],xW.prototype,"_diffuseTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xW.prototype,"diffuseTexture",void 0),(0,je.Cg)([(0,$e.uM)()],xW.prototype,"noiseTexture",void 0),(0,je.Cg)([(0,$e.jT)()],xW.prototype,"fogColor",void 0),(0,je.Cg)([(0,$e.lK)()],xW.prototype,"speed",void 0),(0,je.Cg)([(0,$e.lK)()],xW.prototype,"movingSpeed",void 0),(0,je.Cg)([(0,$e.lK)()],xW.prototype,"lowFrequencySpeed",void 0),(0,je.Cg)([(0,$e.lK)()],xW.prototype,"fogDensity",void 0),(0,je.Cg)([(0,$e.jT)()],xW.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.lK)("disableLighting")],xW.prototype,"_disableLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],xW.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.lK)("unlit")],xW.prototype,"_unlit",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],xW.prototype,"unlit",void 0),(0,je.Cg)([(0,$e.lK)("maxSimultaneousLights")],xW.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],xW.prototype,"maxSimultaneousLights",void 0),(0,X.Y5)("BABYLON.LavaMaterial",xW);Cs.l.ShadersStore.mixPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform sampler2D mixMap1Sampler;uniform vec2 vTextureInfos;\n#ifdef MIXMAP2\nuniform sampler2D mixMap2Sampler;\n#endif\nuniform sampler2D diffuse1Sampler;uniform sampler2D diffuse2Sampler;uniform sampler2D diffuse3Sampler;uniform sampler2D diffuse4Sampler;uniform vec2 diffuse1Infos;uniform vec2 diffuse2Infos;uniform vec2 diffuse3Infos;uniform vec2 diffuse4Infos;\n#ifdef MIXMAP2\nuniform sampler2D diffuse5Sampler;uniform sampler2D diffuse6Sampler;uniform sampler2D diffuse7Sampler;uniform sampler2D diffuse8Sampler;uniform vec2 diffuse5Infos;uniform vec2 diffuse6Infos;uniform vec2 diffuse7Infos;uniform vec2 diffuse8Infos;\n#endif\n#endif\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 finalMixColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef MIXMAP2\nvec4 mixColor2=vec4(1.,1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\nfloat alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec4 mixColor=texture2D(mixMap1Sampler,vTextureUV);\n#include\nmixColor.rgb*=vTextureInfos.y;vec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);vec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);vec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);vec4 diffuse4Color=texture2D(diffuse4Sampler,vTextureUV*diffuse4Infos);diffuse1Color.rgb*=mixColor.r;diffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,mixColor.g);diffuse3Color.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,mixColor.b);finalMixColor.rgb=mix(diffuse3Color.rgb,diffuse4Color.rgb,1.0-mixColor.a);\n#ifdef MIXMAP2\nmixColor=texture2D(mixMap2Sampler,vTextureUV);mixColor.rgb*=vTextureInfos.y;vec4 diffuse5Color=texture2D(diffuse5Sampler,vTextureUV*diffuse5Infos);vec4 diffuse6Color=texture2D(diffuse6Sampler,vTextureUV*diffuse6Infos);vec4 diffuse7Color=texture2D(diffuse7Sampler,vTextureUV*diffuse7Infos);vec4 diffuse8Color=texture2D(diffuse8Sampler,vTextureUV*diffuse8Infos);diffuse5Color.rgb=mix(finalMixColor.rgb,diffuse5Color.rgb,mixColor.r);diffuse6Color.rgb=mix(diffuse5Color.rgb,diffuse6Color.rgb,mixColor.g);diffuse7Color.rgb=mix(diffuse6Color.rgb,diffuse7Color.rgb,mixColor.b);finalMixColor.rgb=mix(diffuse7Color.rgb,diffuse8Color.rgb,1.0-mixColor.a);\n#endif\n#endif\n#ifdef VERTEXCOLOR\nfinalMixColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor*finalMixColor.rgb,0.0,1.0);vec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Cs.l.ShadersStore.mixVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform mat4 textureMatrix;uniform vec2 vTextureInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vTextureInfos.x==0.)\n{vTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));}\nelse\n{vTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class bW extends xn{constructor(){super(),this.DIFFUSE=!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.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.MIXMAP2=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class SW extends bn{constructor(e,t){super(e,t),this.diffuseColor=new H.v9(1,1,1),this.specularColor=new H.v9(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r.effect&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new bW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(n.texturesEnabled){if(!this._mixTexture1||!this._mixTexture1.isReady())return!1;if(s._needUVs=!0,Sn.DiffuseTextureEnabled){if(!this._diffuseTexture1||!this._diffuseTexture1.isReady())return!1;if(s.DIFFUSE=!0,!this._diffuseTexture2||!this._diffuseTexture2.isReady())return!1;if(!this._diffuseTexture3||!this._diffuseTexture3.isReady())return!1;if(!this._diffuseTexture4||!this._diffuseTexture4.isReady())return!1;if(this._mixTexture2){if(!this._mixTexture2.isReady())return!1;if(s.MIXMAP2=!0,!this._diffuseTexture5||!this._diffuseTexture5.isReady())return!1;if(!this._diffuseTexture6||!this._diffuseTexture6.isReady())return!1;if(!this._diffuseTexture7||!this._diffuseTexture7.isReady())return!1;if(!this._diffuseTexture8||!this._diffuseTexture8.isReady())return!1}}}if((0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=(0,Bt.az)(n,e,s,!1,this._maxSimultaneousLights,this._disableLighting),(0,Bt.OR)(n,o,this,s,!!i),(0,Bt.qB)(e,s,!0,!0),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial();const i=new Tn;s.FOG&&i.addFallback(1,"FOG"),(0,Bt.c4)(s,i,this.maxSimultaneousLights),s.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),s.UV1&&r.push(st.R.UVKind),s.UV2&&r.push(st.R.UV2Kind),s.VERTEXCOLOR&&r.push(st.R.ColorKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="mix",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","textureMatrix","logarithmicDepthConstant","diffuse1Infos","diffuse2Infos","diffuse3Infos","diffuse4Infos","diffuse5Infos","diffuse6Infos","diffuse7Infos","diffuse8Infos"],c=["mixMap1Sampler","mixMap2Sampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","diffuse4Sampler","diffuse5Sampler","diffuse6Sampler","diffuse7Sampler","diffuse8Sampler"],u=[];(0,Ln.TV)(h),(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._mustRebind(r,n,i)&&(this._mixTexture1&&(this._activeEffect.setTexture("mixMap1Sampler",this._mixTexture1),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture1.coordinatesIndex,this._mixTexture1.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture1.getTextureMatrix()),Sn.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale)),this._diffuseTexture4&&(this._activeEffect.setTexture("diffuse4Sampler",this._diffuseTexture4),this._activeEffect.setFloat2("diffuse4Infos",this._diffuseTexture4.uScale,this._diffuseTexture4.vScale)))),this._mixTexture2&&(this._activeEffect.setTexture("mixMap2Sampler",this._mixTexture2),Sn.DiffuseTextureEnabled&&(this._diffuseTexture5&&(this._activeEffect.setTexture("diffuse5Sampler",this._diffuseTexture5),this._activeEffect.setFloat2("diffuse5Infos",this._diffuseTexture5.uScale,this._diffuseTexture5.vScale)),this._diffuseTexture6&&(this._activeEffect.setTexture("diffuse6Sampler",this._diffuseTexture6),this._activeEffect.setFloat2("diffuse6Infos",this._diffuseTexture6.uScale,this._diffuseTexture6.vScale)),this._diffuseTexture7&&(this._activeEffect.setTexture("diffuse7Sampler",this._diffuseTexture7),this._activeEffect.setFloat2("diffuse7Infos",this._diffuseTexture7.uScale,this._diffuseTexture7.vScale)),this._diffuseTexture8&&(this._activeEffect.setTexture("diffuse8Sampler",this._diffuseTexture8),this._activeEffect.setFloat2("diffuse8Infos",this._diffuseTexture8.uScale,this._diffuseTexture8.vScale)))),(0,Ln.gS)(n,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),r.lightsEnabled&&!this.disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._mixTexture1&&this._mixTexture1.animations&&this._mixTexture1.animations.length>0&&e.push(this._mixTexture1),this._mixTexture2&&this._mixTexture2.animations&&this._mixTexture2.animations.length>0&&e.push(this._mixTexture2),e}getActiveTextures(){const e=super.getActiveTextures();return this._mixTexture1&&e.push(this._mixTexture1),this._diffuseTexture1&&e.push(this._diffuseTexture1),this._diffuseTexture2&&e.push(this._diffuseTexture2),this._diffuseTexture3&&e.push(this._diffuseTexture3),this._diffuseTexture4&&e.push(this._diffuseTexture4),this._mixTexture2&&e.push(this._mixTexture2),this._diffuseTexture5&&e.push(this._diffuseTexture5),this._diffuseTexture6&&e.push(this._diffuseTexture6),this._diffuseTexture7&&e.push(this._diffuseTexture7),this._diffuseTexture8&&e.push(this._diffuseTexture8),e}hasTexture(e){return!!super.hasTexture(e)||this._mixTexture1===e||this._diffuseTexture1===e||this._diffuseTexture2===e||this._diffuseTexture3===e||this._diffuseTexture4===e||this._mixTexture2===e||this._diffuseTexture5===e||this._diffuseTexture6===e||this._diffuseTexture7===e||this._diffuseTexture8===e}dispose(e){this._mixTexture1&&this._mixTexture1.dispose(),super.dispose(e)}clone(e){return it.p.Clone((()=>new SW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MixMaterial",e}getClassName(){return"MixMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new SW(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.uM)("mixTexture1")],SW.prototype,"_mixTexture1",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],SW.prototype,"mixTexture1",void 0),(0,je.Cg)([(0,$e.uM)("mixTexture2")],SW.prototype,"_mixTexture2",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],SW.prototype,"mixTexture2",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture1")],SW.prototype,"_diffuseTexture1",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],SW.prototype,"diffuseTexture1",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture2")],SW.prototype,"_diffuseTexture2",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],SW.prototype,"diffuseTexture2",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture3")],SW.prototype,"_diffuseTexture3",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],SW.prototype,"diffuseTexture3",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture4")],SW.prototype,"_diffuseTexture4",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],SW.prototype,"diffuseTexture4",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture1")],SW.prototype,"_diffuseTexture5",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],SW.prototype,"diffuseTexture5",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture2")],SW.prototype,"_diffuseTexture6",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],SW.prototype,"diffuseTexture6",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture3")],SW.prototype,"_diffuseTexture7",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],SW.prototype,"diffuseTexture7",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture4")],SW.prototype,"_diffuseTexture8",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],SW.prototype,"diffuseTexture8",void 0),(0,je.Cg)([(0,$e.jT)()],SW.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.jT)()],SW.prototype,"specularColor",void 0),(0,je.Cg)([(0,$e.lK)()],SW.prototype,"specularPower",void 0),(0,je.Cg)([(0,$e.lK)("disableLighting")],SW.prototype,"_disableLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],SW.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.lK)("maxSimultaneousLights")],SW.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],SW.prototype,"maxSimultaneousLights",void 0),(0,X.Y5)("BABYLON.MixMaterial",SW);Cs.l.ShadersStore.normalPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef LIGHTING\n#include\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef NORMAL\nbaseColor=mix(baseColor,vec4(vNormalW,1.0),0.5);\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef LIGHTING\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#include[0]\n#include[1]\n#include[2]\n#include[3]\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse= baseColor.rgb;\n#endif\nvec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Cs.l.ShadersStore.normalVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class TW extends xn{constructor(){super(),this.DIFFUSE=!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.POINTSIZE=!1,this.FOG=!1,this.LIGHT0=!1,this.LIGHT1=!1,this.LIGHT2=!1,this.LIGHT3=!1,this.SPOTLIGHT0=!1,this.SPOTLIGHT1=!1,this.SPOTLIGHT2=!1,this.SPOTLIGHT3=!1,this.HEMILIGHT0=!1,this.HEMILIGHT1=!1,this.HEMILIGHT2=!1,this.HEMILIGHT3=!1,this.DIRLIGHT0=!1,this.DIRLIGHT1=!1,this.DIRLIGHT2=!1,this.DIRLIGHT3=!1,this.POINTLIGHT0=!1,this.POINTLIGHT1=!1,this.POINTLIGHT2=!1,this.POINTLIGHT3=!1,this.SHADOW0=!1,this.SHADOW1=!1,this.SHADOW2=!1,this.SHADOW3=!1,this.SHADOWS=!1,this.SHADOWESM0=!1,this.SHADOWESM1=!1,this.SHADOWESM2=!1,this.SHADOWESM3=!1,this.SHADOWPOISSON0=!1,this.SHADOWPOISSON1=!1,this.SHADOWPOISSON2=!1,this.SHADOWPOISSON3=!1,this.SHADOWPCF0=!1,this.SHADOWPCF1=!1,this.SHADOWPCF2=!1,this.SHADOWPCF3=!1,this.SHADOWPCSS0=!1,this.SHADOWPCSS1=!1,this.SHADOWPCSS2=!1,this.SHADOWPCSS3=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.LIGHTING=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class CW extends bn{constructor(e,t){super(e,t),this.diffuseColor=new H.v9(1,1,1),this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaBlendingForMesh(e){return this.needAlphaBlending()||e.visibility<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r.effect&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new TW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(s._areTexturesDirty&&(s._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&Sn.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;s._needUVs=!0,s.DIFFUSE=!0}if((0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=!0,(0,Bt.az)(n,e,s,!1,this._maxSimultaneousLights,this._disableLighting),(0,Bt.OR)(n,o,this,s,!!i),s.LIGHTING=!this._disableLighting,(0,Bt.qB)(e,s,!0,!0),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial();const i=new Tn;s.FOG&&i.addFallback(1,"FOG"),(0,Bt.c4)(s,i),s.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),s.UV1&&r.push(st.R.UVKind),s.UV2&&r.push(st.R.UV2Kind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="normal",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant"],c=["diffuseSampler"],u=[];(0,Ln.TV)(h),(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:4}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._mustRebind(r,n,i)&&(this.diffuseTexture&&Sn.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),(0,Ln.gS)(n,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this.diffuseTexture&&this.diffuseTexture.dispose(),super.dispose(e)}clone(e){return it.p.Clone((()=>new CW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.NormalMaterial",e}getClassName(){return"NormalMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new CW(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.uM)("diffuseTexture")],CW.prototype,"_diffuseTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],CW.prototype,"diffuseTexture",void 0),(0,je.Cg)([(0,$e.jT)()],CW.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.lK)("disableLighting")],CW.prototype,"_disableLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],CW.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.lK)("maxSimultaneousLights")],CW.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],CW.prototype,"maxSimultaneousLights",void 0),(0,X.Y5)("BABYLON.NormalMaterial",CW);Cs.l.ShadersStore.shadowOnlyPixelShader="precision highp float;uniform vec4 vEyePosition;uniform float alpha;uniform vec3 shadowColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#include[0..1]\nvec4 color=vec4(shadowColor,(1.0-clamp(shadow,0.,1.))*alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Cs.l.ShadersStore.shadowOnlyVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class yW extends xn{constructor(){super(),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.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class EW extends bn{constructor(e,t){super(e,t),this._needAlphaBlending=!0,this.shadowColor=H.v9.Black()}needAlphaBlending(){return this._needAlphaBlending}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}get activeLight(){return this._activeLight}set activeLight(e){this._activeLight=e}_getFirstShadowLightForMesh(e){for(const t of e.lightSources)if(t.shadowEnabled)return t;return null}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r.effect&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new yW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(this._activeLight)for(const t of e.lightSources)if(t.shadowEnabled){if(this._activeLight===t)break;const i=e.lightSources.indexOf(this._activeLight);-1!==i&&(e.lightSources.splice(i,1),e.lightSources.splice(0,0,this._activeLight));break}(0,Bt.OR)(n,o,this,s,!!i),(0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=(0,Bt.az)(n,e,s,!1,1);const a=this._getFirstShadowLightForMesh(e)?.getShadowGenerator();if(this._needAlphaBlending=!0,a&&a.getClassName&&"CascadedShadowGenerator"===a.getClassName()){const e=a;this._needAlphaBlending=!e.autoCalcDepthBounds}if((0,Bt.qB)(e,s,!1,!0),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial();const i=new Tn;s.FOG&&i.addFallback(1,"FOG"),(0,Bt.c4)(s,i,1),s.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="shadowOnly",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","alpha","shadowColor","mBones","logarithmicDepthConstant"],c=[],u=[];(0,Ln.TV)(h),(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:1}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:1}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;if(n){if(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._mustRebind(r,n,i)&&((0,Ln.gS)(n,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setFloat("alpha",this.alpha),this._activeEffect.setColor3("shadowColor",this.shadowColor),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),r.lightsEnabled){(0,Bt.RL)(r,t,this._activeEffect,s,1);const e=this._getFirstShadowLightForMesh(t);e&&(e._renderId=-1)}(r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE||s.SHADOWCSM0)&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._afterBind(t,this._activeEffect,i)}}clone(e){return it.p.Clone((()=>new EW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.ShadowOnlyMaterial",e}getClassName(){return"ShadowOnlyMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new EW(e.name,t)),e,t,i)}}(0,X.Y5)("BABYLON.ShadowOnlyMaterial",EW);Cs.l.ShadersStore.simplePixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Cs.l.ShadersStore.simpleVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class PW extends xn{constructor(){super(),this.DIFFUSE=!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.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class AW extends bn{constructor(e,t){super(e,t),this.diffuseColor=new H.v9(1,1,1),this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r.effect&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new PW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(s._areTexturesDirty&&(s._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&Sn.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;s._needUVs=!0,s.DIFFUSE=!0}if((0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=(0,Bt.az)(n,e,s,!1,this._maxSimultaneousLights,this._disableLighting),(0,Bt.OR)(n,o,this,s,!!i),(0,Bt.qB)(e,s,!0,!0),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial();const i=new Tn;s.FOG&&i.addFallback(1,"FOG"),(0,Bt.c4)(s,i,this.maxSimultaneousLights),s.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),s.UV1&&r.push(st.R.UVKind),s.UV2&&r.push(st.R.UV2Kind),s.VERTEXCOLOR&&r.push(st.R.ColorKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="simple",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant"],c=["diffuseSampler"],u=[];(0,Ln.TV)(h),(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights-1}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._mustRebind(r,n,i)&&(this._diffuseTexture&&Sn.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),(0,Ln.gS)(n,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),super.dispose(e)}clone(e){return it.p.Clone((()=>new AW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.SimpleMaterial",e}getClassName(){return"SimpleMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new AW(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.uM)("diffuseTexture")],AW.prototype,"_diffuseTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],AW.prototype,"diffuseTexture",void 0),(0,je.Cg)([(0,$e.jT)("diffuse")],AW.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.lK)("disableLighting")],AW.prototype,"_disableLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],AW.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.lK)("maxSimultaneousLights")],AW.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],AW.prototype,"maxSimultaneousLights",void 0),(0,X.Y5)("BABYLON.SimpleMaterial",AW);Cs.l.ShadersStore.skyPixelShader="precision highp float;varying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\nuniform vec3 cameraPosition;uniform vec3 cameraOffset;uniform vec3 up;uniform float luminance;uniform float turbidity;uniform float rayleigh;uniform float mieCoefficient;uniform float mieDirectionalG;uniform vec3 sunPosition;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nconst float e=2.71828182845904523536028747135266249775724709369995957;const float pi=3.141592653589793238462643383279502884197169;const float n=1.0003;const float N=2.545E25;const float pn=0.035;const vec3 lambda=vec3(680E-9,550E-9,450E-9);const vec3 K=vec3(0.686,0.678,0.666);const float v=4.0;const float rayleighZenithLength=8.4E3;const float mieZenithLength=1.25E3;const float EE=1000.0;const float sunAngularDiameterCos=0.999956676946448443553574619906976478926848692873900859324;const float cutoffAngle=pi/1.95;const float steepness=1.5;vec3 totalRayleigh(vec3 lambda)\n{return (8.0*pow(pi,3.0)*pow(pow(n,2.0)-1.0,2.0)*(6.0+3.0*pn))/(3.0*N*pow(lambda,vec3(4.0))*(6.0-7.0*pn));}\nvec3 simplifiedRayleigh()\n{return 0.0005/vec3(94,40,18);}\nfloat rayleighPhase(float cosTheta)\n{ \nreturn (3.0/(16.0*pi))*(1.0+pow(cosTheta,2.0));}\nvec3 totalMie(vec3 lambda,vec3 K,float T)\n{float c=(0.2*T )*10E-18;return 0.434*c*pi*pow((2.0*pi)/lambda,vec3(v-2.0))*K;}\nfloat hgPhase(float cosTheta,float g)\n{return (1.0/(4.0*pi))*((1.0-pow(g,2.0))/pow(1.0-2.0*g*cosTheta+pow(g,2.0),1.5));}\nfloat sunIntensity(float zenithAngleCos)\n{return EE*max(0.0,1.0-exp((-(cutoffAngle-acos(zenithAngleCos))/steepness)));}\nfloat A=0.15;float B=0.50;float C=0.10;float D=0.20;float EEE=0.02;float F=0.30;float W=1000.0;vec3 Uncharted2Tonemap(vec3 x)\n{return ((x*(A*x+C*B)+D*EEE)/(x*(A*x+B)+D*F))-EEE/F;}\n#if DITHER\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n/**\n*--------------------------------------------------------------------------------------------------\n* Sky Color\n*--------------------------------------------------------------------------------------------------\n*/\nfloat sunfade=1.0-clamp(1.0-exp((sunPosition.y/450000.0)),0.0,1.0);float rayleighCoefficient=rayleigh-(1.0*(1.0-sunfade));vec3 sunDirection=normalize(sunPosition);float sunE=sunIntensity(dot(sunDirection,up));vec3 betaR=simplifiedRayleigh()*rayleighCoefficient;vec3 betaM=totalMie(lambda,K,turbidity)*mieCoefficient;float zenithAngle=acos(max(0.0,dot(up,normalize(vPositionW-cameraPosition+cameraOffset))));float sR=rayleighZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));float sM=mieZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));vec3 Fex=exp(-(betaR*sR+betaM*sM));float cosTheta=dot(normalize(vPositionW-cameraPosition),sunDirection);float rPhase=rayleighPhase(cosTheta*0.5+0.5);vec3 betaRTheta=betaR*rPhase;float mPhase=hgPhase(cosTheta,mieDirectionalG);vec3 betaMTheta=betaM*mPhase;vec3 Lin=pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*(1.0-Fex),vec3(1.5));Lin*=mix(vec3(1.0),pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*Fex,vec3(1.0/2.0)),clamp(pow(1.0-dot(up,sunDirection),5.0),0.0,1.0));vec3 direction=normalize(vPositionW-cameraPosition);float theta=acos(direction.y);float phi=atan(direction.z,direction.x);vec2 uv=vec2(phi,theta)/vec2(2.0*pi,pi)+vec2(0.5,0.0);vec3 L0=vec3(0.1)*Fex;float sundisk=smoothstep(sunAngularDiameterCos,sunAngularDiameterCos+0.00002,cosTheta);L0+=(sunE*19000.0*Fex)*sundisk;vec3 whiteScale=1.0/Uncharted2Tonemap(vec3(W));vec3 texColor=(Lin+L0);texColor*=0.04 ;texColor+=vec3(0.0,0.001,0.0025)*0.3;float g_fMaxLuminance=1.0;float fLumScaled=0.1/luminance; \nfloat fLumCompressed=(fLumScaled*(1.0+(fLumScaled/(g_fMaxLuminance*g_fMaxLuminance))))/(1.0+fLumScaled); \nfloat ExposureBias=fLumCompressed;vec3 curr=Uncharted2Tonemap((log2(2.0/pow(luminance,4.0)))*texColor);vec3 retColor=curr*whiteScale;/**\n*--------------------------------------------------------------------------------------------------\n* Sky Color\n*--------------------------------------------------------------------------------------------------\n*/\nfloat alpha=1.0;\n#ifdef VERTEXCOLOR\nretColor.rgb*=vColor.rgb;\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#if DITHER\nretColor.rgb+=dither(gl_FragCoord.xy,0.5);\n#endif\nvec4 color=clamp(vec4(retColor.rgb,alpha),0.0,1.0);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Cs.l.ShadersStore.skyVertexShader="precision highp float;attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\nuniform mat4 world;uniform mat4 view;uniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\ngl_Position=viewProjection*world*vec4(position,1.0);vec4 worldPos=world*vec4(position,1.0);vPositionW=vec3(worldPos);\n#include\n#include\n#include\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class RW extends xn{constructor(){super(),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.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.DITHER=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class IW extends bn{constructor(e,t){super(e,t),this.luminance=1,this.turbidity=10,this.rayleigh=2,this.mieCoefficient=.005,this.mieDirectionalG=.8,this.distance=500,this.inclination=.49,this.azimuth=.25,this.sunPosition=new W.Pq(0,100,0),this.useSunPosition=!1,this.cameraOffset=W.Pq.Zero(),this.up=W.Pq.Up(),this.dithering=!1,this._cameraPosition=W.Pq.Zero(),this._skyOrientation=new W.PT}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new RW);const r=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;if((0,Bt.fm)(e,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,!1,r),(0,Bt.qB)(e,r,!0,!1),r.IMAGEPROCESSINGPOSTPROCESS!==s.imageProcessingConfiguration.applyByPostProcess&&r.markAsMiscDirty(),r.DITHER!==this.dithering&&r.markAsMiscDirty(),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=new Tn;r.FOG&&e.addFallback(1,"FOG"),r.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess,r.DITHER=this.dithering;const i=[st.R.PositionKind];r.VERTEXCOLOR&&i.push(st.R.ColorKind);const n="sky",o=["world","viewProjection","view","vFogInfos","vFogColor","logarithmicDepthConstant","pointSize","luminance","turbidity","rayleigh","mieCoefficient","mieDirectionalG","sunPosition","cameraPosition","cameraOffset","up"];(0,Ln.TV)(o);const a=r.toString();t.setEffect(s.getEngine().createEffect(n,i,o,[],a,e,this.onCompiled,this.onError),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),this._mustRebind(r,n,i)&&((0,Ln.gS)(n,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r)),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect);const o=r.activeCamera;if(o){const e=o.getWorldMatrix();this._cameraPosition.x=e.m[12],this._cameraPosition.y=e.m[13],this._cameraPosition.z=e.m[14],this._activeEffect.setVector3("cameraPosition",this._cameraPosition)}if(this._activeEffect.setVector3("cameraOffset",this.cameraOffset),this._activeEffect.setVector3("up",this.up),this.luminance>0&&this._activeEffect.setFloat("luminance",this.luminance),this._activeEffect.setFloat("turbidity",this.turbidity),this._activeEffect.setFloat("rayleigh",this.rayleigh),this._activeEffect.setFloat("mieCoefficient",this.mieCoefficient),this._activeEffect.setFloat("mieDirectionalG",this.mieDirectionalG),!this.useSunPosition){const e=Math.PI*(this.inclination-.5),t=2*Math.PI*(this.azimuth-.5);this.sunPosition.x=this.distance*Math.cos(t)*Math.cos(e),this.sunPosition.y=this.distance*Math.sin(-e),this.sunPosition.z=this.distance*Math.sin(t)*Math.cos(e),W.PT.FromUnitVectorsToRef(W.Pq.UpReadOnly,this.up,this._skyOrientation),this.sunPosition.rotateByQuaternionToRef(this._skyOrientation,this.sunPosition)}this._activeEffect.setVector3("sunPosition",this.sunPosition),this._afterBind(t,this._activeEffect,i)}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return it.p.Clone((()=>new IW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.SkyMaterial",e}getClassName(){return"SkyMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new IW(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.lK)()],IW.prototype,"luminance",void 0),(0,je.Cg)([(0,$e.lK)()],IW.prototype,"turbidity",void 0),(0,je.Cg)([(0,$e.lK)()],IW.prototype,"rayleigh",void 0),(0,je.Cg)([(0,$e.lK)()],IW.prototype,"mieCoefficient",void 0),(0,je.Cg)([(0,$e.lK)()],IW.prototype,"mieDirectionalG",void 0),(0,je.Cg)([(0,$e.lK)()],IW.prototype,"distance",void 0),(0,je.Cg)([(0,$e.lK)()],IW.prototype,"inclination",void 0),(0,je.Cg)([(0,$e.lK)()],IW.prototype,"azimuth",void 0),(0,je.Cg)([(0,$e.P_)()],IW.prototype,"sunPosition",void 0),(0,je.Cg)([(0,$e.lK)()],IW.prototype,"useSunPosition",void 0),(0,je.Cg)([(0,$e.P_)()],IW.prototype,"cameraOffset",void 0),(0,je.Cg)([(0,$e.P_)()],IW.prototype,"up",void 0),(0,je.Cg)([(0,$e.lK)()],IW.prototype,"dithering",void 0),(0,X.Y5)("BABYLON.SkyMaterial",IW);Cs.l.ShadersStore.terrainPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform sampler2D textureSampler;uniform vec2 vTextureInfos;uniform sampler2D diffuse1Sampler;uniform sampler2D diffuse2Sampler;uniform sampler2D diffuse3Sampler;uniform vec2 diffuse1Infos;uniform vec2 diffuse2Infos;uniform vec2 diffuse3Infos;\n#endif\n#ifdef BUMP\nuniform sampler2D bump1Sampler;uniform sampler2D bump2Sampler;uniform sampler2D bump3Sampler;\n#endif\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;float invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));return mat3(tangent*invmax,binormal*invmax,normal);}\nvec3 perturbNormal(vec3 viewDir,vec3 mixColor)\n{vec3 bump1Color=texture2D(bump1Sampler,vTextureUV*diffuse1Infos).xyz;vec3 bump2Color=texture2D(bump2Sampler,vTextureUV*diffuse2Infos).xyz;vec3 bump3Color=texture2D(bump3Sampler,vTextureUV*diffuse3Infos).xyz;bump1Color.rgb*=mixColor.r;bump2Color.rgb=mix(bump1Color.rgb,bump2Color.rgb,mixColor.g);vec3 map=mix(bump2Color.rgb,bump3Color.rgb,mixColor.b);map=map*255./127.-128./127.;mat3 TBN=cotangent_frame(vNormalW*vTextureInfos.y,-viewDir,vTextureUV);return normalize(TBN*map);}\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\nfloat alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(textureSampler,vTextureUV);\n#if defined(BUMP) && defined(DIFFUSE)\nnormalW=perturbNormal(viewDirectionW,baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vTextureInfos.y;vec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);vec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);vec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);diffuse1Color.rgb*=baseColor.r;diffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,baseColor.g);baseColor.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,baseColor.b);\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor*baseColor.rgb,0.0,1.0);vec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Cs.l.ShadersStore.terrainVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform mat4 textureMatrix;uniform vec2 vTextureInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vTextureInfos.x==0.)\n{vTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));}\nelse\n{vTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class MW extends xn{constructor(){super(),this.DIFFUSE=!1,this.BUMP=!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.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class OW extends bn{constructor(e,t){super(e,t),this.diffuseColor=new H.v9(1,1,1),this.specularColor=new H.v9(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r.effect&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new MW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(n.texturesEnabled){if(!this.mixTexture||!this.mixTexture.isReady())return!1;if(s._needUVs=!0,Sn.DiffuseTextureEnabled){if(!this.diffuseTexture1||!this.diffuseTexture1.isReady())return!1;if(!this.diffuseTexture2||!this.diffuseTexture2.isReady())return!1;if(!this.diffuseTexture3||!this.diffuseTexture3.isReady())return!1;s.DIFFUSE=!0}if(this.bumpTexture1&&this.bumpTexture2&&this.bumpTexture3&&Sn.BumpTextureEnabled){if(!this.bumpTexture1.isReady())return!1;if(!this.bumpTexture2.isReady())return!1;if(!this.bumpTexture3.isReady())return!1;s._needNormals=!0,s.BUMP=!0}}if((0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=(0,Bt.az)(n,e,s,!1,this._maxSimultaneousLights,this._disableLighting),(0,Bt.OR)(n,o,this,s,!!i),(0,Bt.qB)(e,s,!0,!0),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial();const i=new Tn;s.FOG&&i.addFallback(1,"FOG"),(0,Bt.c4)(s,i,this.maxSimultaneousLights),s.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),s.UV1&&r.push(st.R.UVKind),s.UV2&&r.push(st.R.UV2Kind),s.VERTEXCOLOR&&r.push(st.R.ColorKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="terrain",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","textureMatrix","diffuse1Infos","diffuse2Infos","diffuse3Infos"],c=["textureSampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","bump1Sampler","bump2Sampler","bump3Sampler","logarithmicDepthConstant"],u=[];(0,Ln.TV)(h),(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("view",r.getViewMatrix()),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._mustRebind(r,n,i)&&(this.mixTexture&&(this._activeEffect.setTexture("textureSampler",this._mixTexture),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture.coordinatesIndex,this._mixTexture.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture.getTextureMatrix()),Sn.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale))),Sn.BumpTextureEnabled&&r.getEngine().getCaps().standardDerivatives&&(this._bumpTexture1&&this._activeEffect.setTexture("bump1Sampler",this._bumpTexture1),this._bumpTexture2&&this._activeEffect.setTexture("bump2Sampler",this._bumpTexture2),this._bumpTexture3&&this._activeEffect.setTexture("bump3Sampler",this._bumpTexture3))),(0,Ln.gS)(n,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),r.lightsEnabled&&!this.disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._mixTexture&&e.push(this._mixTexture),this._diffuseTexture1&&e.push(this._diffuseTexture1),this._diffuseTexture2&&e.push(this._diffuseTexture2),this._diffuseTexture3&&e.push(this._diffuseTexture3),this._bumpTexture1&&e.push(this._bumpTexture1),this._bumpTexture2&&e.push(this._bumpTexture2),this._bumpTexture3&&e.push(this._bumpTexture3),e}hasTexture(e){return!!super.hasTexture(e)||this._mixTexture===e||this._diffuseTexture1===e||this._diffuseTexture2===e||this._diffuseTexture3===e||this._bumpTexture1===e||this._bumpTexture2===e||this._bumpTexture3===e}dispose(e){this.mixTexture&&this.mixTexture.dispose(),super.dispose(e)}clone(e){return it.p.Clone((()=>new OW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.TerrainMaterial",e}getClassName(){return"TerrainMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new OW(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.uM)("mixTexture")],OW.prototype,"_mixTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],OW.prototype,"mixTexture",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture1")],OW.prototype,"_diffuseTexture1",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],OW.prototype,"diffuseTexture1",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture2")],OW.prototype,"_diffuseTexture2",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],OW.prototype,"diffuseTexture2",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture3")],OW.prototype,"_diffuseTexture3",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],OW.prototype,"diffuseTexture3",void 0),(0,je.Cg)([(0,$e.uM)("bumpTexture1")],OW.prototype,"_bumpTexture1",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],OW.prototype,"bumpTexture1",void 0),(0,je.Cg)([(0,$e.uM)("bumpTexture2")],OW.prototype,"_bumpTexture2",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],OW.prototype,"bumpTexture2",void 0),(0,je.Cg)([(0,$e.uM)("bumpTexture3")],OW.prototype,"_bumpTexture3",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],OW.prototype,"bumpTexture3",void 0),(0,je.Cg)([(0,$e.jT)()],OW.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.jT)()],OW.prototype,"specularColor",void 0),(0,je.Cg)([(0,$e.lK)()],OW.prototype,"specularPower",void 0),(0,je.Cg)([(0,$e.lK)("disableLighting")],OW.prototype,"_disableLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],OW.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.lK)("maxSimultaneousLights")],OW.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],OW.prototype,"maxSimultaneousLights",void 0),(0,X.Y5)("BABYLON.TerrainMaterial",OW);Cs.l.ShadersStore.triplanarPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;uniform sampler2D diffuseSamplerX;\n#ifdef BUMPX\nuniform sampler2D normalSamplerX;\n#endif\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;uniform sampler2D diffuseSamplerY;\n#ifdef BUMPY\nuniform sampler2D normalSamplerY;\n#endif\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;uniform sampler2D diffuseSamplerZ;\n#ifdef BUMPZ\nuniform sampler2D normalSamplerZ;\n#endif\n#endif\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(0.,0.,0.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=tangentSpace[2];\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec4 baseNormal=vec4(0.0,0.0,0.0,1.0);normalW*=normalW;\n#ifdef DIFFUSEX\nbaseColor+=texture2D(diffuseSamplerX,vTextureUVX)*normalW.x;\n#ifdef BUMPX\nbaseNormal+=texture2D(normalSamplerX,vTextureUVX)*normalW.x;\n#endif\n#endif\n#ifdef DIFFUSEY\nbaseColor+=texture2D(diffuseSamplerY,vTextureUVY)*normalW.y;\n#ifdef BUMPY\nbaseNormal+=texture2D(normalSamplerY,vTextureUVY)*normalW.y;\n#endif\n#endif\n#ifdef DIFFUSEZ\nbaseColor+=texture2D(diffuseSamplerZ,vTextureUVZ)*normalW.z;\n#ifdef BUMPZ\nbaseNormal+=texture2D(normalSamplerZ,vTextureUVZ)*normalW.z;\n#endif\n#endif\n#ifdef NORMAL\nnormalW=normalize((2.0*baseNormal.xyz-1.0)*tangentSpace);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Cs.l.ShadersStore.triplanarVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;\n#endif\nuniform float tileSize;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef DIFFUSEX\nvTextureUVX=worldPos.zy/tileSize;\n#endif\n#ifdef DIFFUSEY\nvTextureUVY=worldPos.xz/tileSize;\n#endif\n#ifdef DIFFUSEZ\nvTextureUVZ=worldPos.xy/tileSize;\n#endif\n#ifdef NORMAL\nvec3 xtan=vec3(0,0,1);vec3 xbin=vec3(0,1,0);vec3 ytan=vec3(1,0,0);vec3 ybin=vec3(0,0,1);vec3 ztan=vec3(1,0,0);vec3 zbin=vec3(0,1,0);vec3 normalizedNormal=normalize(normal);normalizedNormal*=normalizedNormal;vec3 worldBinormal=normalize(xbin*normalizedNormal.x+ybin*normalizedNormal.y+zbin*normalizedNormal.z);vec3 worldTangent=normalize(xtan*normalizedNormal.x+ytan*normalizedNormal.y+ztan*normalizedNormal.z);mat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nworldTangent=normalize((normalWorld*worldTangent).xyz);worldBinormal=normalize((normalWorld*worldBinormal).xyz);vec3 worldNormal=normalize((normalWorld*normalize(normal)).xyz);tangentSpace[0]=worldTangent;tangentSpace[1]=worldBinormal;tangentSpace[2]=worldNormal;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class DW extends xn{constructor(){super(),this.DIFFUSEX=!1,this.DIFFUSEY=!1,this.DIFFUSEZ=!1,this.BUMPX=!1,this.BUMPY=!1,this.BUMPZ=!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.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.NONUNIFORMSCALING=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class wW extends bn{constructor(e,t){super(e,t),this.tileSize=1,this.diffuseColor=new H.v9(1,1,1),this.specularColor=new H.v9(.2,.2,.2),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r.effect&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new DW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(s._areTexturesDirty&&n.texturesEnabled){if(Sn.DiffuseTextureEnabled){const e=[this.diffuseTextureX,this.diffuseTextureY,this.diffuseTextureZ],t=["DIFFUSEX","DIFFUSEY","DIFFUSEZ"];for(let i=0;i0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),s.VERTEXCOLOR&&r.push(st.R.ColorKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="triplanar",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","mBones","tileSize"],c=["diffuseSamplerX","diffuseSamplerY","diffuseSamplerZ","normalSamplerX","normalSamplerY","normalSamplerZ","logarithmicDepthConstant"],u=[];(0,Ln.TV)(h),(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._activeEffect.setFloat("tileSize",this.tileSize),this._mustRebind(r,n,i)&&(this.diffuseTextureX&&this._activeEffect.setTexture("diffuseSamplerX",this.diffuseTextureX),this.diffuseTextureY&&this._activeEffect.setTexture("diffuseSamplerY",this.diffuseTextureY),this.diffuseTextureZ&&this._activeEffect.setTexture("diffuseSamplerZ",this.diffuseTextureZ),this.normalTextureX&&this._activeEffect.setTexture("normalSamplerX",this.normalTextureX),this.normalTextureY&&this._activeEffect.setTexture("normalSamplerY",this.normalTextureY),this.normalTextureZ&&this._activeEffect.setTexture("normalSamplerZ",this.normalTextureZ),(0,Ln.gS)(n,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),r.lightsEnabled&&!this.disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTextureX&&e.push(this._diffuseTextureX),this._diffuseTextureY&&e.push(this._diffuseTextureY),this._diffuseTextureZ&&e.push(this._diffuseTextureZ),this._normalTextureX&&e.push(this._normalTextureX),this._normalTextureY&&e.push(this._normalTextureY),this._normalTextureZ&&e.push(this._normalTextureZ),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTextureX===e||this._diffuseTextureY===e||this._diffuseTextureZ===e||this._normalTextureX===e||this._normalTextureY===e||this._normalTextureZ===e}dispose(e){this.mixTexture&&this.mixTexture.dispose(),super.dispose(e)}clone(e){return it.p.Clone((()=>new wW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.TriPlanarMaterial",e}getClassName(){return"TriPlanarMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new wW(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.uM)()],wW.prototype,"mixTexture",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTextureX")],wW.prototype,"_diffuseTextureX",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],wW.prototype,"diffuseTextureX",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexturY")],wW.prototype,"_diffuseTextureY",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],wW.prototype,"diffuseTextureY",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTextureZ")],wW.prototype,"_diffuseTextureZ",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],wW.prototype,"diffuseTextureZ",void 0),(0,je.Cg)([(0,$e.uM)("normalTextureX")],wW.prototype,"_normalTextureX",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],wW.prototype,"normalTextureX",void 0),(0,je.Cg)([(0,$e.uM)("normalTextureY")],wW.prototype,"_normalTextureY",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],wW.prototype,"normalTextureY",void 0),(0,je.Cg)([(0,$e.uM)("normalTextureZ")],wW.prototype,"_normalTextureZ",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],wW.prototype,"normalTextureZ",void 0),(0,je.Cg)([(0,$e.lK)()],wW.prototype,"tileSize",void 0),(0,je.Cg)([(0,$e.jT)()],wW.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.jT)()],wW.prototype,"specularColor",void 0),(0,je.Cg)([(0,$e.lK)()],wW.prototype,"specularPower",void 0),(0,je.Cg)([(0,$e.lK)("disableLighting")],wW.prototype,"_disableLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],wW.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.lK)("maxSimultaneousLights")],wW.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],wW.prototype,"maxSimultaneousLights",void 0),(0,X.Y5)("BABYLON.TriPlanarMaterial",wW);Cs.l.ShadersStore.waterPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#ifdef BUMP\nvarying vec2 vNormalUV;\n#ifdef BUMPSUPERIMPOSE\nvarying vec2 vNormalUV2;\n#endif\nuniform sampler2D normalSampler;uniform vec2 vNormalInfos;\n#endif\nuniform sampler2D refractionSampler;uniform sampler2D reflectionSampler;const float LOG2=1.442695;uniform vec3 cameraPosition;uniform vec4 waterColor;uniform float colorBlendFactor;uniform vec4 waterColor2;uniform float colorBlendFactor2;uniform float bumpHeight;uniform float time;varying vec3 vRefractionMapTexCoord;varying vec3 vReflectionMapTexCoord;\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef BUMP\n#ifdef BUMPSUPERIMPOSE\nbaseColor=0.6*texture2D(normalSampler,vNormalUV)+0.4*texture2D(normalSampler,vec2(vNormalUV2.x,vNormalUV2.y));\n#else\nbaseColor=texture2D(normalSampler,vNormalUV);\n#endif\nvec3 bumpColor=baseColor.rgb;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vNormalInfos.y;\n#else\nvec3 bumpColor=vec3(1.0);\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec2 perturbation=bumpHeight*(baseColor.rg-0.5);\n#ifdef BUMPAFFECTSREFLECTION\nvec3 normalW=normalize(vNormalW+vec3(perturbation.x*8.0,0.0,perturbation.y*8.0));if (normalW.y<0.0) {normalW.y=-normalW.y;}\n#else\nvec3 normalW=normalize(vNormalW);\n#endif\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);vec2 perturbation=bumpHeight*(vec2(1.0,1.0)-0.5);\n#endif\n#ifdef FRESNELSEPARATE\n#ifdef REFLECTION\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation*0.5,0.0,1.0);vec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\n#ifdef IS_REFRACTION_LINEAR\nrefractiveColor.rgb=toGammaSpace(refractiveColor.rgb);\n#endif\nvec2 projectedReflectionTexCoords=clamp(vec2(\nvReflectionMapTexCoord.x/vReflectionMapTexCoord.z+perturbation.x*0.3,\nvReflectionMapTexCoord.y/vReflectionMapTexCoord.z+perturbation.y\n),0.0,1.0);vec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\n#ifdef IS_REFLECTION_LINEAR\nreflectiveColor.rgb=toGammaSpace(reflectiveColor.rgb);\n#endif\nvec3 upVector=vec3(0.0,1.0,0.0);float fresnelTerm=clamp(abs(pow(dot(viewDirectionW,upVector),3.0)),0.05,0.65);float IfresnelTerm=1.0-fresnelTerm;refractiveColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*refractiveColor;reflectiveColor=IfresnelTerm*colorBlendFactor2*waterColor+(1.0-colorBlendFactor2*IfresnelTerm)*reflectiveColor;vec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*IfresnelTerm;baseColor=combinedColor;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#else \n#ifdef REFLECTION\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation,0.0,1.0);vec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\n#ifdef IS_REFRACTION_LINEAR\nrefractiveColor.rgb=toGammaSpace(refractiveColor.rgb);\n#endif\nvec2 projectedReflectionTexCoords=clamp(vReflectionMapTexCoord.xy/vReflectionMapTexCoord.z+perturbation,0.0,1.0);vec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\n#ifdef IS_REFLECTION_LINEAR\nreflectiveColor.rgb=toGammaSpace(reflectiveColor.rgb);\n#endif\nvec3 upVector=vec3(0.0,1.0,0.0);float fresnelTerm=max(dot(viewDirectionW,upVector),0.0);vec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*(1.0-fresnelTerm);baseColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*combinedColor;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#endif\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#elif defined(IMAGEPROCESSING)\ncolor.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color);\n#endif\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Cs.l.ShadersStore.waterVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef BUMP\nvarying vec2 vNormalUV;\n#ifdef BUMPSUPERIMPOSE\nvarying vec2 vNormalUV2;\n#endif\nuniform mat4 normalMatrix;uniform vec2 vNormalInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\nuniform mat4 reflectionViewProjection;uniform vec2 windDirection;uniform float waveLength;uniform float time;uniform float windForce;uniform float waveHeight;uniform float waveSpeed;uniform float waveCount;varying vec3 vRefractionMapTexCoord;varying vec3 vReflectionMapTexCoord;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef BUMP\nif (vNormalInfos.x==0.)\n{vNormalUV=vec2(normalMatrix*vec4((uv*1.0)/waveLength+time*windForce*windDirection,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv*0.721)/waveLength+time*1.2*windForce*windDirection,1.0,0.0));\n#endif\n}\nelse\n{vNormalUV=vec2(normalMatrix*vec4((uv2*1.0)/waveLength+time*windForce*windDirection ,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv2*0.721)/waveLength+time*1.2*windForce*windDirection ,1.0,0.0));\n#endif\n}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\nfloat finalWaveCount=1.0/(waveCount*0.5);\n#ifdef USE_WORLD_COORDINATES\nvec3 p=worldPos.xyz;\n#else\nvec3 p=position;\n#endif\nfloat newY=(sin(((p.x/finalWaveCount)+time*waveSpeed))*waveHeight*windDirection.x*5.0)\n+ (cos(((p.z/finalWaveCount)+ time*waveSpeed))*waveHeight*windDirection.y*5.0);p.y+=abs(newY);\n#ifdef USE_WORLD_COORDINATES\ngl_Position=viewProjection*vec4(p,1.0);\n#else\ngl_Position=viewProjection*finalWorld*vec4(p,1.0);\n#endif\n#ifdef REFLECTION\nvRefractionMapTexCoord.x=0.5*(gl_Position.w+gl_Position.x);vRefractionMapTexCoord.y=0.5*(gl_Position.w+gl_Position.y);vRefractionMapTexCoord.z=gl_Position.w;worldPos=reflectionViewProjection*finalWorld*vec4(position,1.0);vReflectionMapTexCoord.x=0.5*(worldPos.w+worldPos.x);vReflectionMapTexCoord.y=0.5*(worldPos.w+worldPos.y);vReflectionMapTexCoord.z=worldPos.w;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class NW extends xn{constructor(){super(),this.BUMP=!1,this.REFLECTION=!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.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.SPECULARTERM=!1,this.LOGARITHMICDEPTH=!1,this.USE_REVERSE_DEPTHBUFFER=!1,this.FRESNELSEPARATE=!1,this.BUMPSUPERIMPOSE=!1,this.BUMPAFFECTSREFLECTION=!1,this.USE_WORLD_COORDINATES=!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.rebuild()}}class FW extends bn{get hasRenderTargetTextures(){return!0}constructor(e,t,i=new W.I9(512,512)){super(e,t),this.renderTargetSize=i,this.diffuseColor=new H.v9(1,1,1),this.specularColor=new H.v9(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4,this.windForce=6,this.windDirection=new W.I9(0,1),this.waveHeight=.4,this.bumpHeight=.4,this._bumpSuperimpose=!1,this._fresnelSeparate=!1,this._bumpAffectsReflection=!1,this.waterColor=new H.v9(.1,.1,.6),this.colorBlendFactor=.2,this.waterColor2=new H.v9(.1,.1,.6),this.colorBlendFactor2=.2,this.waveLength=.1,this.waveSpeed=1,this.waveCount=20,this.disableClipPlane=!1,this._useWorldCoordinatesForWaveDeformation=!1,this._renderTargets=new Qe.L(16),this._mesh=null,this._reflectionTransform=W.uq.Zero(),this._lastTime=0,this._lastDeltaTime=0,this._createRenderTargets(this.getScene(),i),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._renderTargets.push(this._reflectionRTT),this._renderTargets.push(this._refractionRTT),this._renderTargets),this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}get refractionTexture(){return this._refractionRTT}get reflectionTexture(){return this._reflectionRTT}addToRenderList(e){this._refractionRTT&&this._refractionRTT.renderList&&this._refractionRTT.renderList.push(e),this._reflectionRTT&&this._reflectionRTT.renderList&&this._reflectionRTT.renderList.push(e)}removeFromRenderList(e){if(this._refractionRTT&&this._refractionRTT.renderList){const t=this._refractionRTT.renderList.indexOf(e);-1!==t&&this._refractionRTT.renderList.splice(t,1)}if(this._reflectionRTT&&this._reflectionRTT.renderList){const t=this._reflectionRTT.renderList.indexOf(e);-1!==t&&this._reflectionRTT.renderList.splice(t,1)}}enableRenderTargets(e){const t=e?1:0;this._refractionRTT&&(this._refractionRTT.refreshRate=t),this._reflectionRTT&&(this._reflectionRTT.refreshRate=t)}getRenderList(){return this._refractionRTT?this._refractionRTT.renderList:[]}get renderTargetsEnabled(){return!(this._refractionRTT&&0===this._refractionRTT.refreshRate)}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r.effect&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new NW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(s._areTexturesDirty&&(s._needUVs=!1,n.texturesEnabled)){if(this.bumpTexture&&Sn.BumpTextureEnabled){if(!this.bumpTexture.isReady())return!1;s._needUVs=!0,s.BUMP=!0}Sn.ReflectionTextureEnabled&&(s.REFLECTION=!0)}if((0,Bt.OR)(n,o,this,s,!!i),(0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._areMiscDirty&&(s.FRESNELSEPARATE=this._fresnelSeparate,s.BUMPSUPERIMPOSE=this._bumpSuperimpose,s.BUMPAFFECTSREFLECTION=this._bumpAffectsReflection,s.USE_WORLD_COORDINATES=this._useWorldCoordinatesForWaveDeformation),s._needNormals=(0,Bt.az)(n,e,s,!0,this._maxSimultaneousLights,this._disableLighting),s._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s),s.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,s.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}if((0,Bt.qB)(e,s,!0,!0),this._mesh=e,this._waitingRenderList){for(let e=0;e0&&i.addCPUSkinningFallback(0,e);const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),s.UV1&&r.push(st.R.UVKind),s.UV2&&r.push(st.R.UV2Kind),s.VERTEXCOLOR&&r.push(st.R.ColorKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="water",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vNormalInfos","mBones","normalMatrix","logarithmicDepthConstant","reflectionViewProjection","windDirection","waveLength","time","windForce","cameraPosition","bumpHeight","waveHeight","waterColor","waterColor2","colorBlendFactor","colorBlendFactor2","waveSpeed","waveCount"],c=["normalSampler","refractionSampler","reflectionSampler"],u=[];gn.p&&(gn.p.PrepareUniforms(h,s),gn.p.PrepareSamplers(c,s)),(0,Ln.TV)(h),(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;if(!n||!this._mesh)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._mustRebind(r,n,i)&&(this.bumpTexture&&Sn.BumpTextureEnabled&&(this._activeEffect.setTexture("normalSampler",this.bumpTexture),this._activeEffect.setFloat2("vNormalInfos",this.bumpTexture.coordinatesIndex,this.bumpTexture.level),this._activeEffect.setMatrix("normalMatrix",this.bumpTexture.getTextureMatrix())),(0,Ln.gS)(n,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),r.lightsEnabled&&!this.disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),(0,Bt.DL)(s,this._activeEffect,r),Sn.ReflectionTextureEnabled&&(this._activeEffect.setTexture("refractionSampler",this._refractionRTT),this._activeEffect.setTexture("reflectionSampler",this._reflectionRTT));const o=this._reflectionTransform.multiply(r.getProjectionMatrix()),a=r.getEngine().getDeltaTime();a!==this._lastDeltaTime&&(this._lastDeltaTime=a,this._lastTime+=this._lastDeltaTime),this._activeEffect.setMatrix("reflectionViewProjection",o),this._activeEffect.setVector2("windDirection",this.windDirection),this._activeEffect.setFloat("waveLength",this.waveLength),this._activeEffect.setFloat("time",this._lastTime/1e5),this._activeEffect.setFloat("windForce",this.windForce),this._activeEffect.setFloat("waveHeight",this.waveHeight),this._activeEffect.setFloat("bumpHeight",this.bumpHeight),this._activeEffect.setColor4("waterColor",this.waterColor,1),this._activeEffect.setFloat("colorBlendFactor",this.colorBlendFactor),this._activeEffect.setColor4("waterColor2",this.waterColor2,1),this._activeEffect.setFloat("colorBlendFactor2",this.colorBlendFactor2),this._activeEffect.setFloat("waveSpeed",this.waveSpeed),this._activeEffect.setFloat("waveCount",this.waveCount),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect),this._afterBind(t,this._activeEffect,i)}_createRenderTargets(e,t){this._refractionRTT=new ln.$(name+"_refraction",{width:t.x,height:t.y},e,!1,!0),this._refractionRTT.wrapU=Il.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.wrapV=Il.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.ignoreCameraViewport=!0;let i,r=!1;this._refractionRTT.onBeforeRenderObservable.add((()=>{r=e.getBoundingBoxRenderer().enabled,e.getBoundingBoxRenderer().enabled=!1})),this._refractionRTT.onAfterRenderObservable.add((()=>{e.getBoundingBoxRenderer().enabled=r})),this._reflectionRTT=new ln.$(name+"_reflection",{width:t.x,height:t.y},e,!1,!0),this._reflectionRTT.wrapU=Il.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.wrapV=Il.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.ignoreCameraViewport=!0;let s,n=null;const o=W.uq.Zero();this._refractionRTT.onBeforeRender=()=>{if(this._mesh&&(i=this._mesh.isVisible,this._mesh.isVisible=!1),!this.disableClipPlane){n=e.clipPlane;const t=this._mesh?this._mesh.absolutePosition.y:0;e.clipPlane=Ft.Z.FromPositionAndNormal(new W.Pq(0,t+.05,0),new W.Pq(0,1,0))}},this._refractionRTT.onAfterRender=()=>{this._mesh&&(this._mesh.isVisible=i),this.disableClipPlane||(e.clipPlane=n)},this._reflectionRTT.onBeforeRender=()=>{if(this._mesh&&(i=this._mesh.isVisible,this._mesh.isVisible=!1),!this.disableClipPlane){n=e.clipPlane;const t=this._mesh?this._mesh.absolutePosition.y:0;e.clipPlane=Ft.Z.FromPositionAndNormal(new W.Pq(0,t-.05,0),new W.Pq(0,-1,0)),W.uq.ReflectionToRef(e.clipPlane,o)}s=e.getViewMatrix(),o.multiplyToRef(s,this._reflectionTransform),e.setTransformMatrix(this._reflectionTransform,e.getProjectionMatrix()),e._mirroredCameraPosition=W.Pq.TransformCoordinates(e.activeCamera.position,o)},this._reflectionRTT.onAfterRender=()=>{this._mesh&&(this._mesh.isVisible=i),e.clipPlane=n,e.setTransformMatrix(s,e.getProjectionMatrix()),e._mirroredCameraPosition=null}}getAnimatables(){const e=[];return this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0&&e.push(this.bumpTexture),this._reflectionRTT&&this._reflectionRTT.animations&&this._reflectionRTT.animations.length>0&&e.push(this._reflectionRTT),this._refractionRTT&&this._refractionRTT.animations&&this._refractionRTT.animations.length>0&&e.push(this._refractionRTT),e}getActiveTextures(){const e=super.getActiveTextures();return this._bumpTexture&&e.push(this._bumpTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._bumpTexture===e}dispose(e){this.bumpTexture&&this.bumpTexture.dispose();let t=this.getScene().customRenderTargets.indexOf(this._refractionRTT);-1!=t&&this.getScene().customRenderTargets.splice(t,1),t=-1,t=this.getScene().customRenderTargets.indexOf(this._reflectionRTT),-1!=t&&this.getScene().customRenderTargets.splice(t,1),this._reflectionRTT&&this._reflectionRTT.dispose(),this._refractionRTT&&this._refractionRTT.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return it.p.Clone((()=>new FW(e,this.getScene())),this)}serialize(){const e=super.serialize();if(e.customType="BABYLON.WaterMaterial",e.renderList=[],this._refractionRTT&&this._refractionRTT.renderList)for(let t=0;tnew FW(e.name,t)),e,t,i);return r._waitingRenderList=e.renderList,r}static CreateDefaultMesh(e,t){return io(e,{width:512,height:512,subdivisions:32,updatable:!1},t)}}(0,je.Cg)([(0,$e.uM)("bumpTexture")],FW.prototype,"_bumpTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],FW.prototype,"bumpTexture",void 0),(0,je.Cg)([(0,$e.jT)()],FW.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.jT)()],FW.prototype,"specularColor",void 0),(0,je.Cg)([(0,$e.lK)()],FW.prototype,"specularPower",void 0),(0,je.Cg)([(0,$e.lK)("disableLighting")],FW.prototype,"_disableLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],FW.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.lK)("maxSimultaneousLights")],FW.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],FW.prototype,"maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.lK)()],FW.prototype,"windForce",void 0),(0,je.Cg)([(0,$e.WM)()],FW.prototype,"windDirection",void 0),(0,je.Cg)([(0,$e.lK)()],FW.prototype,"waveHeight",void 0),(0,je.Cg)([(0,$e.lK)()],FW.prototype,"bumpHeight",void 0),(0,je.Cg)([(0,$e.lK)("bumpSuperimpose")],FW.prototype,"_bumpSuperimpose",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],FW.prototype,"bumpSuperimpose",void 0),(0,je.Cg)([(0,$e.lK)("fresnelSeparate")],FW.prototype,"_fresnelSeparate",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],FW.prototype,"fresnelSeparate",void 0),(0,je.Cg)([(0,$e.lK)("bumpAffectsReflection")],FW.prototype,"_bumpAffectsReflection",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],FW.prototype,"bumpAffectsReflection",void 0),(0,je.Cg)([(0,$e.jT)()],FW.prototype,"waterColor",void 0),(0,je.Cg)([(0,$e.lK)()],FW.prototype,"colorBlendFactor",void 0),(0,je.Cg)([(0,$e.jT)()],FW.prototype,"waterColor2",void 0),(0,je.Cg)([(0,$e.lK)()],FW.prototype,"colorBlendFactor2",void 0),(0,je.Cg)([(0,$e.lK)()],FW.prototype,"waveLength",void 0),(0,je.Cg)([(0,$e.lK)()],FW.prototype,"waveSpeed",void 0),(0,je.Cg)([(0,$e.lK)()],FW.prototype,"waveCount",void 0),(0,je.Cg)([(0,$e.lK)()],FW.prototype,"disableClipPlane",void 0),(0,je.Cg)([(0,$e.lK)("useWorldCoordinatesForWaveDeformation")],FW.prototype,"_useWorldCoordinatesForWaveDeformation",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],FW.prototype,"useWorldCoordinatesForWaveDeformation",void 0),(0,X.Y5)("BABYLON.WaterMaterial",FW);class LW{constructor(e){this.context=e}create(e){const t=new IW("bitbybit-skyMaterial",this.context.scene);return void 0!==e.luminance&&(t.luminance=e.luminance),void 0!==e.turbidity&&(t.turbidity=e.turbidity),void 0!==e.rayleigh&&(t.rayleigh=e.rayleigh),void 0!==e.mieCoefficient&&(t.mieCoefficient=e.mieCoefficient),void 0!==e.mieDirectionalG&&(t.mieDirectionalG=e.mieDirectionalG),void 0!==e.distance&&(t.distance=e.distance),void 0!==e.inclination&&(t.inclination=e.inclination),void 0!==e.azimuth&&(t.azimuth=e.azimuth),void 0!==e.sunPosition&&(t.sunPosition=new hc.Pq(e.sunPosition[0],e.sunPosition[1],e.sunPosition[2])),void 0!==e.useSunPosition&&(t.useSunPosition=e.useSunPosition),void 0!==e.cameraOffset&&(t.cameraOffset=new hc.Pq(e.cameraOffset[0],e.cameraOffset[1],e.cameraOffset[2])),void 0!==e.up&&(t.up=new hc.Pq(e.up[0],e.up[1],e.up[2])),void 0!==e.dithering&&(t.dithering=e.dithering),t}setLuminance(e){e.material.luminance=e.luminance}setTurbidity(e){e.material.turbidity=e.turbidity}setRayleigh(e){e.material.rayleigh=e.rayleigh}setMieCoefficient(e){e.material.mieCoefficient=e.mieCoefficient}setMieDirectionalG(e){e.material.mieDirectionalG=e.mieDirectionalG}setDistance(e){e.material.distance=e.distance}setInclination(e){e.material.inclination=e.inclination}setAzimuth(e){e.material.azimuth=e.azimuth}setSunPosition(e){e.material.sunPosition=new hc.Pq(e.sunPosition[0],e.sunPosition[1],e.sunPosition[2])}setUseSunPosition(e){e.material.useSunPosition=e.useSunPosition}setCameraOffset(e){e.material.cameraOffset=new hc.Pq(e.cameraOffset[0],e.cameraOffset[1],e.cameraOffset[2])}setUp(e){e.material.up=new hc.Pq(e.up[0],e.up[1],e.up[2])}setDithering(e){e.material.dithering=e.dithering}getLuminance(e){return e.skyMaterial.luminance}getTurbidity(e){return e.skyMaterial.turbidity}getRayleigh(e){return e.skyMaterial.rayleigh}getMieCoefficient(e){return e.skyMaterial.mieCoefficient}getMieDirectionalG(e){return e.skyMaterial.mieDirectionalG}getDistance(e){return e.skyMaterial.distance}getInclination(e){return e.skyMaterial.inclination}getAzimuth(e){return e.skyMaterial.azimuth}getSunPosition(e){return e.skyMaterial.sunPosition.asArray()}getUseSunPosition(e){return e.skyMaterial.useSunPosition}getCameraOffset(e){return e.skyMaterial.cameraOffset.asArray()}getUp(e){return e.skyMaterial.up.asArray()}getDithering(e){return e.skyMaterial.dithering}}class BW{constructor(e,t){this.context=e,this.color=t,this.pbrMetallicRoughness=new rW(e,t),this.skyMaterial=new LW(e)}}var VW=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class kW{constructor(e){this.context=e}createImmersiveARExperience(){return VW(this,void 0,void 0,(function*(){if(yield Qn.IsSessionSupportedAsync("immersive-ar"))return yield this.context.scene.createDefaultXRExperienceAsync({uiOptions:{sessionMode:"immersive-ar",referenceSpaceType:"local-floor"},outputCanvasOptions:{canvasOptions:{framebufferScaleFactor:2,antialias:!0}},optionalFeatures:!0});throw new Error("AR is not supported on this device.")}))}createDefaultXRExperienceWithTeleportation(e){return VW(this,void 0,void 0,(function*(){this.createDefaultXRExperienceWithTeleportationReturn(e)}))}createDefaultXRExperienceWithTeleportationReturn(e){return VW(this,void 0,void 0,(function*(){const t=yield this.context.scene.createDefaultXRExperienceAsync();this.context.scene.metadata?this.context.scene.metadata.xr=t:this.context.scene.metadata={xr:t};const i=[];e.groundMeshes.forEach((e=>{e.getChildMeshes&&(null==e||e.getChildMeshes().forEach((e=>{e.isPickable=!0,i.push(e)}))),i.push(e),e.isPickable=!0}));const r=t.baseExperience.featuresManager,s=new Cb("teleportation");s.baseColor=new hc.v9(0,0,1),s.metallic=0,s.roughness=1,r.enableFeature(hr.TELEPORTATION,"stable",{xrInput:t.input,floorMeshes:i,defaultTargetMeshOptions:{torusArrowMaterial:s,disableLighting:!1}});const n=new QV(this.context.scene);this.context.scene.metadata.guiManager=n,n.useRealisticScaling=!0;const o=new OV("near");n.addControl(o);const a=new SV("button1"),l=new dB;return l.text="Exit VR",l.color="white",l.fontSize="48px",a.onPointerClickObservable.add((()=>VW(this,void 0,void 0,(function*(){yield t.baseExperience.exitXRAsync()})))),o.addButton(a),a.content=l,{xr:t,torusMat:s,manager:n,near:o,button:a,text:l,dispose:()=>{t.dispose(),s.dispose(),n.dispose(),o.dispose(),a.dispose(),l.dispose()}}}))}}class UW{constructor(e){this.context=e,this.simple=new kW(e)}}class GW{constructor(e){this.context=e}getEngine(){return this.context.engine}getRenderingCanvas(){return this.context.engine.getRenderingCanvas()}}var zW;class WW{constructor(e){this.context=e}create(e){return t=this,i=void 0,s=function*(){if(void 0!==e.url)return xg.ImportMeshAsync(null,e.url,void 0,this.context.scene,void 0,".ply").then((e=>{const t=e.meshes[0];return t.name=`gaussian-splatting-${Math.random()}`,t}))},new((r=void 0)||(r=Promise))((function(e,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r((function(e){e(i)}))).then(o,a)}l((s=s.apply(t,i||[])).next())}));var t,i,r,s}clone(e){return e.babylonMesh.clone(`gaussian-splatting-${Math.random()}`)}getSplatPositions(e){const t=e.babylonMesh._splatPositions,i=[];for(let e=0;es[e]&&(s[e]=t),++n}}return{min:r,max:s}}static _NormalizeTangentFromRef(e){const t=Math.sqrt(e.x*e.x+e.y*e.y+e.z*e.z);t>0&&(e.x/=t,e.y/=t,e.z/=t)}static _GetDataAccessorElementCount(e){switch(e){case"MAT2":case"VEC4":return 4;case"MAT3":return 9;case"MAT4":return 16;case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3}}}!function(e){e[e.INTANGENT=0]="INTANGENT",e[e.OUTTANGENT=1]="OUTTANGENT"}(zW||(zW={}));class XW{static _IsTransformable(e){return e&&(e instanceof Pt||e instanceof rt||e instanceof $t)}static _CreateNodeAnimation(e,t,i,r,s){if(this._IsTransformable(e)){const n=[],o=[],a=t.getKeys(),l=XW._CalculateMinMaxKeyFrames(a),h=XW._DeduceInterpolation(a,i,r),c=h.interpolationType,u=h.shouldBakeAnimation;if(u?XW._CreateBakedAnimation(e,t,i,l.min,l.max,t.framePerSecond,s,n,o,l,r):"LINEAR"===c||"STEP"===c?XW._CreateLinearOrStepAnimation(e,t,i,n,o,r):"CUBICSPLINE"===c?XW._CreateCubicSplineAnimation(e,t,i,n,o,r):XW._CreateBakedAnimation(e,t,i,l.min,l.max,t.framePerSecond,s,n,o,l,r),n.length&&o.length)return{inputs:n,outputs:o,samplerInterpolation:c,inputsMin:u?l.min:Ue.S0.FloatRound(l.min/t.framePerSecond),inputsMax:u?l.max:Ue.S0.FloatRound(l.max/t.framePerSecond)}}return null}static _DeduceAnimationInfo(e){let t=null,i="VEC3",r=!1;const s=e.targetProperty.split(".");switch(s[0]){case"scaling":t="scale";break;case"position":t="translation";break;case"rotation":i="VEC4",t="rotation";break;case"rotationQuaternion":i="VEC4",r=!0,t="rotation";break;case"influence":i="SCALAR",t="weights";break;default:Ue.S0.Error(`Unsupported animatable property ${s[0]}`)}return t?{animationChannelTargetPath:t,dataAccessorType:i,useQuaternion:r}:(Ue.S0.Error("animation channel target path and data accessor type could be deduced"),null)}static _CreateNodeAnimationFromNodeAnimations(e,t,i,r,s,n,o,a,l,h){let c;if(XW._IsTransformable(e)&&e.animations)for(const s of e.animations){if(h&&!h(s))continue;const u=XW._DeduceAnimationInfo(s);u&&(c={name:s.name,samplers:[],channels:[]},XW._AddAnimation(`${s.name}`,s.hasRunningRuntimeAnimations?t:c,e,s,u.dataAccessorType,u.animationChannelTargetPath,r,n,o,a,u.useQuaternion,l),c.samplers.length&&c.channels.length&&i.push(c))}}static _CreateMorphTargetAnimationFromMorphTargetAnimations(e,t,i,r,s,n,o,a,l,h){let c;if(e instanceof Yt){const s=e.morphTargetManager;if(s)for(let u=0;u{for(let i=0;ie.morphTargetManager===i));r&&(h.has(r)||h.set(r,new Map),h.get(r)?.set(t,_),d.add(r),u.set(r,_))}}}}d.forEach((e=>{const t=e.morphTargetManager;let a=null;const d=[],p=u.get(e).getKeys(),_=p.length;for(let i=0;i<_;++i)for(let r=0;r0;)t=f.inputs.shift(),e%d==0&&i.push(t),e++;f.inputs=i}const r=o[i.uniqueId];let c=4*f.inputs.length;p=HW._CreateBufferView(0,a.getByteOffset(),c,void 0,`${e} keyframe data view`),l.push(p),f.inputs.forEach((function(e){a.setFloat32(e)})),_=HW._CreateAccessor(l.length-1,`${e} keyframes`,"SCALAR",5126,f.inputs.length,null,[f.inputsMin],[f.inputsMax]),h.push(_),m=h.length-1,v=f.outputs.length,c=4*HW._GetDataAccessorElementCount(s)*f.outputs.length,p=HW._CreateBufferView(0,a.getByteOffset(),c,void 0,`${e} data view`),l.push(p),f.outputs.forEach((function(e){e.forEach((function(e){a.setFloat32(e)}))})),_=HW._CreateAccessor(l.length-1,`${e} data`,s,5126,v,null,null,null),h.push(_),g=h.length-1,x={interpolation:f.samplerInterpolation,input:m,output:g},t.samplers.push(x),b={sampler:t.samplers.length-1,target:{node:r,path:n}},t.channels.push(b)}}static _CreateBakedAnimation(e,t,i,r,s,n,o,a,l,h,c){let u;const d=W.PT.Identity();let f,p=null,_=null,m=null,g=null,v=null,x=null;h.min=Ue.S0.FloatRound(r/n);const b=t.getKeys();for(let r=0,h=b.length;r{"StandardMaterial"===e.getClassName()?r.push(this._convertStandardMaterialAsync(e,t,i)):-1!==e.getClassName().indexOf("PBR")?r.push(this._convertPBRMaterialAsync(e,t,i)):Ue.S0.Warn(`Unsupported material type: ${e.name}`)})),Promise.all(r).then((()=>{}))}_stripTexturesFromMaterial(e){const t={};if(e){t.name=e.name,t.doubleSided=e.doubleSided,t.alphaMode=e.alphaMode,t.alphaCutoff=e.alphaCutoff,t.emissiveFactor=e.emissiveFactor;const i=e.pbrMetallicRoughness;i&&(t.pbrMetallicRoughness={},t.pbrMetallicRoughness.baseColorFactor=i.baseColorFactor,t.pbrMetallicRoughness.metallicFactor=i.metallicFactor,t.pbrMetallicRoughness.roughnessFactor=i.roughnessFactor)}return t}_hasTexturesPresent(e){if(e.emissiveTexture||e.normalTexture||e.occlusionTexture)return!0;const t=e.pbrMetallicRoughness;if(t&&(t.baseColorTexture||t.metallicRoughnessTexture))return!0;if(e.extensions)for(const t in e.extensions){const i=e.extensions[t];if(i)return i.hasTextures?.()}return!1}_getTextureInfo(e){if(e){const t=e.uid;if(t in this._textureMap)return this._textureMap[t]}return null}_convertToGLTFPBRMetallicRoughness(e){const t=new W.I9(0,1),i=new W.I9(0,.1),r=new W.I9(0,.1),s=new W.I9(1300,.1),n=e.diffuseColor.toLinearSpace(e.getScene().getEngine().useExactSrgbConversions).scale(.5),o=e.alpha,a=(l=Gy.Clamp(e.specularPower,0,YW._MaxSpecularPower),h=Math.pow(l/s.x,.333333),c=t.y,u=i.y,d=r.y,f=s.y,(1-h)*(1-h)*(1-h)*c+3*(1-h)*(1-h)*h*u+3*(1-h)*h*h*d+h*h*h*f);var l,h,c,u,d,f;return{baseColorFactor:[n.r,n.g,n.b,o],metallicFactor:0,roughnessFactor:a}}static _SolveMetallic(e,t,i){if(t{e&&(o.baseColorTexture=e)})));const i=e.bumpTexture;i&&n.push(this._exportTextureAsync(i,t).then((e=>{e&&(a.normalTexture=e,1!==i.level&&(a.normalTexture.scale=i.level))}))),e.emissiveTexture&&(a.emissiveFactor=[1,1,1],n.push(this._exportTextureAsync(e.emissiveTexture,t).then((e=>{e&&(a.emissiveTexture=e)})))),e.ambientTexture&&n.push(this._exportTextureAsync(e.ambientTexture,t).then((e=>{if(e){const t={index:e.index};a.occlusionTexture=t}})))}return(e.alpha<1||e.opacityTexture)&&(e.alphaMode===Il.ALPHA_COMBINE?a.alphaMode="BLEND":Ue.S0.Warn(e.name+": glTF 2.0 does not support alpha mode: "+e.alphaMode.toString())),e.emissiveColor&&!YW._FuzzyEquals(e.emissiveColor,H.v9.Black(),YW._Epsilon)&&(a.emissiveFactor=e.emissiveColor.asArray()),a.pbrMetallicRoughness=o,YW._SetAlphaMode(a,e),s.push(a),r[e.uniqueId]=s.length-1,this._finishMaterial(n,a,e,t)}_finishMaterial(e,t,i,r){return Promise.all(e).then((()=>{const e=this._exporter._extensionsPostExportMaterialAdditionalTextures("exportMaterial",t,i);let s=null;for(const t of e)s||(s=[]),s.push(this._exportTextureAsync(t,r));return s||(s=[Promise.resolve(null)]),Promise.all(s).then((()=>{const e=this._exporter._extensionsPostExportMaterialAsync("exportMaterial",t,i);return e?e.then((()=>t)):t}))}))}async _getImageDataAsync(e,t,i,r){const s=Il.TEXTURETYPE_UNSIGNED_INT,n=this._exporter._babylonScene,o=n.getEngine(),a=o.createRawTexture(e,t,i,Il.TEXTUREFORMAT_RGBA,!1,!0,vi.g.NEAREST_SAMPLINGMODE,null,s);await Ac.LO.ApplyPostProcess("pass",a,n,s,Il.TEXTURE_NEAREST_SAMPLINGMODE,Il.TEXTUREFORMAT_RGBA);const l=await o._readTexturePixels(a,t,i);return await UR.DumpTools.DumpDataAsync(t,i,l,r,void 0,!0,!0)}_createWhiteTexture(e,t,i){const r=new Uint8Array(e*t*4);for(let e=0;es.width?(o=t&&t instanceof vi.g?Ac.LO.CreateResizedCopy(t,r.width,r.height,!0):this._createWhiteTexture(r.width,r.height,i),n=e):(n=e,o=t),{texture1:n,texture2:o}}_convertPixelArrayToFloat32(e){if(e instanceof Uint8Array){const t=e.length,i=new Float32Array(e.length);for(let r=0;rYW._Epsilon?S.baseColor.r:1,m[i+1]/=S.baseColor.g>YW._Epsilon?S.baseColor.g:1,m[i+2]/=S.baseColor.b>YW._Epsilon?S.baseColor.b:1;const r=H.v9.FromInts(m[i],m[i+1],m[i+2]).toGammaSpace(n.getEngine().useExactSrgbConversions);m[i]=255*r.r,m[i+1]=255*r.g,m[i+2]=255*r.b,YW._FuzzyEquals(r,H.v9.White(),YW._Epsilon)||(C=!0),_[i+1]/=S.roughness>YW._Epsilon?S.roughness:1,_[i+2]/=S.metallic>YW._Epsilon?S.metallic:1;const s=H.v9.FromInts(255,_[i+1],_[i+2]);YW._FuzzyEquals(s,H.v9.White(),YW._Epsilon)||(T=!0)}return T&&s.push(this._getImageDataAsync(_,c,u,r).then((e=>{S.metallicRoughnessTextureData=e}))),C&&s.push(this._getImageDataAsync(m,c,u,r).then((e=>{S.baseColorTextureData=e}))),Promise.all(s).then((()=>S))}return Promise.reject("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!")}_convertSpecularGlossinessToMetallicRoughness(e){const t=this._getPerceivedBrightness(e.diffuseColor),i=this._getPerceivedBrightness(e.specularColor),r=1-this._getMaxComponent(e.specularColor),s=YW._SolveMetallic(t,i,r),n=e.diffuseColor.scale(r/(1-YW._DielectricSpecular.r)/Math.max(1-s,YW._Epsilon)),o=e.specularColor.subtract(YW._DielectricSpecular.scale(1-s)).scale(1/Math.max(s,YW._Epsilon));let a=H.v9.Lerp(n,o,s*s);return a=a.clampToRef(0,1,a),{baseColor:a,metallic:s,roughness:1-e.glossiness}}_getPerceivedBrightness(e){return e?Math.sqrt(.299*e.r*e.r+.587*e.g*e.g+.114*e.b*e.b):0}_getMaxComponent(e){return e?Math.max(e.r,Math.max(e.g,e.b)):0}_convertMetalRoughFactorsToMetallicRoughnessAsync(e,t,i,r){const s=[],n={baseColor:e._albedoColor,metallic:e._metallic,roughness:e._roughness};if(r){e._albedoTexture&&s.push(this._exportTextureAsync(e._albedoTexture,t).then((e=>{e&&(i.baseColorTexture=e)})));const r=e._metallicTexture;r&&s.push(this._exportTextureAsync(r,t).then((e=>{e&&(i.metallicRoughnessTexture=e)})))}return Promise.all(s).then((()=>n))}_getTextureSampler(e){const t={};if(!(e&&e instanceof vi.g))return t;const i=this._getGLTFTextureWrapMode(e.wrapU);10497!==i&&(t.wrapS=i);const r=this._getGLTFTextureWrapMode(e.wrapV);switch(10497!==r&&(t.wrapT=r),e.samplingMode){case vi.g.LINEAR_LINEAR:t.magFilter=9729,t.minFilter=9729;break;case vi.g.LINEAR_NEAREST:t.magFilter=9729,t.minFilter=9728;break;case vi.g.NEAREST_LINEAR:t.magFilter=9728,t.minFilter=9729;break;case vi.g.NEAREST_LINEAR_MIPLINEAR:t.magFilter=9728,t.minFilter=9987;break;case vi.g.NEAREST_NEAREST:t.magFilter=9728,t.minFilter=9728;break;case vi.g.NEAREST_LINEAR_MIPNEAREST:t.magFilter=9728,t.minFilter=9985;break;case vi.g.LINEAR_NEAREST_MIPNEAREST:t.magFilter=9729,t.minFilter=9984;break;case vi.g.LINEAR_NEAREST_MIPLINEAR:t.magFilter=9729,t.minFilter=9986;break;case vi.g.NEAREST_NEAREST_MIPLINEAR:t.magFilter=9728,t.minFilter=9986;break;case vi.g.LINEAR_LINEAR_MIPLINEAR:t.magFilter=9729,t.minFilter=9987;break;case vi.g.LINEAR_LINEAR_MIPNEAREST:t.magFilter=9729,t.minFilter=9985;break;case vi.g.NEAREST_NEAREST_MIPNEAREST:t.magFilter=9728,t.minFilter=9984}return t}_getGLTFTextureWrapMode(e){switch(e){case vi.g.WRAP_ADDRESSMODE:return 10497;case vi.g.CLAMP_ADDRESSMODE:return 33071;case vi.g.MIRROR_ADDRESSMODE:return 33648;default:return Ue.S0.Error(`Unsupported Texture Wrap Mode ${e}!`),10497}}_convertSpecGlossFactorsToMetallicRoughnessAsync(e,t,i,r){return Promise.resolve().then((()=>{const s={diffuseColor:e._albedoColor,specularColor:e._reflectivityColor,glossiness:e._microSurface},n=e._albedoTexture,o=e._reflectivityTexture,a=e._useMicroSurfaceFromReflectivityMapAlpha;if(o&&!a)return Promise.reject("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture are currently not supported");if((n||o)&&r){const e=this._exportTextureSampler(n||o);return this._convertSpecularGlossinessTexturesToMetallicRoughnessAsync(n,o,s,t).then((r=>{const s=this._exporter._textures;if(r.baseColorTextureData){const o=this._exportImage(`baseColor${s.length}`,t,r.baseColorTextureData);i.baseColorTexture=this._exportTextureInfo(o,e,n?.coordinatesIndex)}if(r.metallicRoughnessTextureData){const n=this._exportImage(`metallicRoughness${s.length}`,t,r.metallicRoughnessTextureData);i.metallicRoughnessTexture=this._exportTextureInfo(n,e,o?.coordinatesIndex)}return r}))}return this._convertSpecularGlossinessToMetallicRoughness(s)}))}_convertPBRMaterialAsync(e,t,i){const r={},s={name:e.name};if(e.isMetallicWorkflow()){const n=e._albedoColor,o=e.alpha;return n&&(r.baseColorFactor=[n.r,n.g,n.b,o]),this._convertMetalRoughFactorsToMetallicRoughnessAsync(e,t,r,i).then((n=>this._setMetallicRoughnessPbrMaterial(n,e,s,r,t,i)))}return this._convertSpecGlossFactorsToMetallicRoughnessAsync(e,t,r,i).then((n=>this._setMetallicRoughnessPbrMaterial(n,e,s,r,t,i)))}_setMetallicRoughnessPbrMaterial(e,t,i,r,s,n){const o=this._exporter._materialMap,a=this._exporter._materials,l=[];if(e){if(YW._SetAlphaMode(i,t),YW._FuzzyEquals(e.baseColor,H.v9.White(),YW._Epsilon)&&t.alpha>=YW._Epsilon||(r.baseColorFactor=[e.baseColor.r,e.baseColor.g,e.baseColor.b,t.alpha]),null!=e.metallic&&1!==e.metallic&&(r.metallicFactor=e.metallic),null!=e.roughness&&1!==e.roughness&&(r.roughnessFactor=e.roughness),null==t.backFaceCulling||t.backFaceCulling||(t._twoSidedLighting||Ue.S0.Warn(t.name+": Back-face culling disabled and two-sided lighting disabled is not supported in glTF."),i.doubleSided=!0),n){const e=t._bumpTexture;if(e){const t=this._exportTextureAsync(e,s).then((t=>{t&&(i.normalTexture=t,1!==e.level&&(i.normalTexture.scale=e.level))}));l.push(t)}const r=t._ambientTexture;if(r){const e=this._exportTextureAsync(r,s).then((e=>{if(e){const r={index:e.index,texCoord:e.texCoord,extensions:e.extensions};i.occlusionTexture=r;const s=t._ambientTextureStrength;s&&(r.strength=s)}}));l.push(e)}const n=t._emissiveTexture;if(n){const e=this._exportTextureAsync(n,s).then((e=>{e&&(i.emissiveTexture=e)}));l.push(e)}}const h=t._emissiveColor;YW._FuzzyEquals(h,H.v9.Black(),YW._Epsilon)||(i.emissiveFactor=h.asArray()),i.pbrMetallicRoughness=r,a.push(i),o[t.uniqueId]=a.length-1}return this._finishMaterial(l,i,t,s)}_getPixelsFromTexture(e){return e.textureType,Il.TEXTURETYPE_UNSIGNED_INT,e.readPixels()}_exportTextureAsync(e,t){const i=this._exporter._extensionsPreExportTextureAsync("exporter",e,t);return i?i.then((i=>i?this._exportTextureInfoAsync(i,t):this._exportTextureInfoAsync(e,t))):this._exportTextureInfoAsync(e,t)}async _exportTextureInfoAsync(e,t){const i=e.uid;if(!(i in this._textureMap)){const r=await this._getPixelsFromTexture(e);if(!r)return null;const s=this._exportTextureSampler(e),n=e.mimeType;if(n)switch(n){case"image/jpeg":case"image/png":case"image/webp":t=n;break;default:Ue.S0.Warn(`Unsupported media type: ${n}`)}const o=this._internalTextureToImage,a=e.getInternalTexture().uniqueId;o[a]||(o[a]={});let l=o[a][t];if(void 0===l){const i=e.getSize();l=(async()=>{const s=await this._getImageDataAsync(r,i.width,i.height,t);return this._exportImage(e.name,t,s)})(),o[a][t]=l}const h=this._exportTextureInfo(await l,s,e.coordinatesIndex);this._textureMap[i]=h,this._exporter._extensionsPostExportTextures("exporter",this._textureMap[i],e)}return this._textureMap[i]}_exportImage(e,t,i){const r=this._exporter._imageData,s=e.replace(/\.\/|\/|\.\\|\\/g,"_"),n=function(e){switch(e){case"image/jpeg":return".jpg";case"image/png":return".png";case"image/webp":return".webp";case"image/avif":return".avif"}}(t);let o=s+n;o in r&&(o=`${s}_${Ue.S0.RandomId()}${n}`),r[o]={data:i,mimeType:t};const a=this._exporter._images;return a.push({name:e,uri:o}),a.length-1}_exportTextureInfo(e,t,i){const r=this._exporter._textures;let s=r.findIndex((i=>i.sampler==t&&i.source===e));-1===s&&(s=r.length,r.push({source:e,sampler:t}));const n={index:s};return i&&(n.texCoord=i),n}_exportTextureSampler(e){const t=this._getTextureSampler(e),i=this._exporter._samplers,r=i.findIndex((e=>e.minFilter===t.minFilter&&e.magFilter===t.magFilter&&e.wrapS===t.wrapS&&e.wrapT===t.wrapT));return-1!==r?r:(i.push(t),i.length-1)}}YW._DielectricSpecular=new H.v9(.04,.04,.04),YW._MaxSpecularPower=1024,YW._Epsilon=1e-6;const KW=W.uq.Compose(new W.Pq(-1,1,1),W.PT.Identity(),W.Pq.Zero()),jW=new W.PT(0,1,0,0);function $W(e,t){if(!(e instanceof Pt))return!1;if(t){if(!e.getWorldMatrix().isIdentity())return!1}else if(!e.getWorldMatrix().multiplyToRef(KW,W.AA.Matrix[0]).isIdentity())return!1;return!(e instanceof Yt&&e.geometry||e instanceof Kt&&e.sourceMesh.geometry)}function QW(e){const t=W.Pq.FromArrayToRef(e.translation||[0,0,0],0,W.AA.Vector3[0]),i=W.PT.FromArrayToRef(e.rotation||[0,0,0,1],0,W.AA.Quaternion[0]),r=W.Pq.FromArrayToRef(e.scale||[1,1,1],0,W.AA.Vector3[1]);W.uq.ComposeToRef(r,i,t,W.AA.Matrix[0]).multiplyToRef(KW,W.AA.Matrix[0]).decompose(r,i,t),t.equalsToFloats(0,0,0)?delete e.translation:e.translation=t.asArray(),W.PT.IsIdentity(i)?delete e.rotation:e.rotation=i.asArray(),r.equalsToFloats(1,1,1)?delete e.scale:e.scale=r.asArray()}function ZW(e,t){switch(t){case 5121:return e.setUInt8.bind(e);case 5123:return e.setUInt16.bind(e);case 5125:return e.setUInt32.bind(e);case 5126:return e.setFloat32.bind(e);default:return Ue.S0.Warn("Unsupported Attribute Component kind: "+t),null}}class JW{_applyExtension(e,t,i,r){if(i>=t.length)return Promise.resolve(e);const s=r(t[i],e);return s?s.then((e=>this._applyExtension(e,t,i+1,r))):this._applyExtension(e,t,i+1,r)}_applyExtensions(e,t){const i=[];for(const e of JW._ExtensionNames)i.push(this._extensions[e]);return this._applyExtension(e,i,0,t)}_extensionsPreExportTextureAsync(e,t,i){return this._applyExtensions(t,((t,r)=>t.preExportTextureAsync&&t.preExportTextureAsync(e,r,i)))}_extensionsPostExportMeshPrimitiveAsync(e,t,i,r){return this._applyExtensions(t,((t,s)=>t.postExportMeshPrimitiveAsync&&t.postExportMeshPrimitiveAsync(e,s,i,r)))}_extensionsPostExportNodeAsync(e,t,i,r,s){return this._applyExtensions(t,((t,n)=>t.postExportNodeAsync&&t.postExportNodeAsync(e,n,i,r,s)))}_extensionsPostExportMaterialAsync(e,t,i){return this._applyExtensions(t,((t,r)=>t.postExportMaterialAsync&&t.postExportMaterialAsync(e,r,i)))}_extensionsPostExportMaterialAdditionalTextures(e,t,i){const r=[];for(const s of JW._ExtensionNames){const n=this._extensions[s];n.postExportMaterialAdditionalTextures&&r.push(...n.postExportMaterialAdditionalTextures(e,t,i))}return r}_extensionsPostExportTextures(e,t,i){for(const r of JW._ExtensionNames){const s=this._extensions[r];s.postExportTexture&&s.postExportTexture(e,t,i)}}_forEachExtensions(e){for(const t of JW._ExtensionNames){const i=this._extensions[t];i.enabled&&e(i)}}_extensionsOnExporting(){this._forEachExtensions((e=>{e.wasUsed&&(null==this._glTF.extensionsUsed&&(this._glTF.extensionsUsed=[]),-1===this._glTF.extensionsUsed.indexOf(e.name)&&this._glTF.extensionsUsed.push(e.name),e.required&&(null==this._glTF.extensionsRequired&&(this._glTF.extensionsRequired=[]),-1===this._glTF.extensionsRequired.indexOf(e.name)&&this._glTF.extensionsRequired.push(e.name)),null==this._glTF.extensions&&(this._glTF.extensions={}),e.onExporting&&e.onExporting())}))}_loadExtensions(){for(const e of JW._ExtensionNames){const t=JW._ExtensionFactories[e](this);this._extensions[e]=t}}constructor(e,t){this._extensions={},this._glTF={asset:{generator:`Babylon.js v${an.Version}`,version:"2.0"}},(e=e||he.q.LastCreatedScene)&&(this._babylonScene=e,this._bufferViews=[],this._accessors=[],this._meshes=[],this._scenes=[],this._cameras=[],this._nodes=[],this._images=[],this._materials=[],this._materialMap=[],this._textures=[],this._samplers=[],this._skins=[],this._animations=[],this._imageData={},this._orderedImageData=[],this._options=t||{},this._animationSampleRate=this._options.animationSampleRate||1/60,this._glTFMaterialExporter=new YW(this),this._loadExtensions())}dispose(){for(const e in this._extensions)this._extensions[e].dispose()}get options(){return this._options}static RegisterExtension(e,t){JW.UnregisterExtension(e)&&Ue.S0.Warn(`Extension with the name ${e} already exists`),JW._ExtensionFactories[e]=t,JW._ExtensionNames.push(e)}static UnregisterExtension(e){if(!JW._ExtensionFactories[e])return!1;delete JW._ExtensionFactories[e];const t=JW._ExtensionNames.indexOf(e);return-1!==t&&JW._ExtensionNames.splice(t,1),!0}_reorderIndicesBasedOnPrimitiveMode(e,t,i,r,s){switch(t){case Vt.TriangleFillMode:r||(r=0);for(let t=e.indexStart,i=e.indexStart+e.indexCount;t=n;--t)s.setUInt32(i[t],r),r+=4;break;case Vt.TriangleStripDrawMode:e.indexCount>=3&&(s.setUInt32(i[e.indexStart+2],r+4),s.setUInt32(i[e.indexStart+1],r+8))}}_reorderVertexAttributeDataBasedOnPrimitiveMode(e,t,i,r,s,n){switch(t){case Vt.TriangleFillMode:this._reorderTriangleFillMode(e,i,r,s,n);break;case Vt.TriangleStripDrawMode:this._reorderTriangleStripDrawMode(e,i,r,s,n);break;case Vt.TriangleFanDrawMode:this._reorderTriangleFanMode(e,i,r,s,n)}}_reorderTriangleFillMode(e,t,i,r,s){const n=this._getVertexBufferFromMesh(t,e.getMesh());if(n){const o=n.byteStride/st.R.GetTypeByteLength(n.type);if(e.verticesCount%3!=0)Ue.S0.Error("The submesh vertices for the triangle fill mode is not divisible by 3!");else{const a=[];let l=0;switch(t){case st.R.PositionKind:case st.R.NormalKind:for(let t=e.verticesStart;t=e.verticesStart;--t)l=t*o,a.push(W.IU.FromArray(i,l));break;case st.R.ColorKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,4===n.getSize()?a.push(W.IU.FromArray(i,l)):a.push(W.Pq.FromArray(i,l));break;case st.R.UVKind:case st.R.UV2Kind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(W.I9.FromArray(i,l));break;default:Ue.S0.Error(`Unsupported Vertex Buffer type: ${t}`)}this._writeVertexAttributeData(a,r+12,t,s)}else Ue.S0.Warn(`reorderTriangleStripDrawMode: Vertex buffer kind ${t} not present!`)}_reorderTriangleFanMode(e,t,i,r,s){const n=this._getVertexBufferFromMesh(t,e.getMesh());if(n){const o=n.byteStride/st.R.GetTypeByteLength(n.type),a=[];let l=0;switch(t){case st.R.PositionKind:case st.R.NormalKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(W.Pq.FromArray(i,l));break;case st.R.TangentKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(W.IU.FromArray(i,l));break;case st.R.ColorKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(W.IU.FromArray(i,l)),4===n.getSize()?a.push(W.IU.FromArray(i,l)):a.push(W.Pq.FromArray(i,l));break;case st.R.UVKind:case st.R.UV2Kind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(W.I9.FromArray(i,l));break;default:Ue.S0.Error(`Unsupported Vertex Buffer type: ${t}`)}this._writeVertexAttributeData(a,r,t,s)}else Ue.S0.Warn(`reorderTriangleFanMode: Vertex buffer kind ${t} not present!`)}_writeVertexAttributeData(e,t,i,r){for(const s of e){i===st.R.NormalKind?s.normalize():i===st.R.TangentKind&&s instanceof W.IU&&HW._NormalizeTangentFromRef(s);for(const e of s.asArray())r.setFloat32(e,t),t+=4}}_writeAttributeData(e,t,i,r,s,n){let o,a=[];switch(e){case st.R.PositionKind:for(let e=0,t=i.length/r;e{e.uri&&(n=this._imageData[e.uri],this._orderedImageData.push(n),s=e.uri.split(".")[0]+" image",o=HW._CreateBufferView(0,a,n.data.byteLength,void 0,s),a+=n.data.byteLength,this._bufferViews.push(o),e.bufferView=this._bufferViews.length-1,e.name=s,e.mimeType=n.mimeType,e.uri=void 0,this._glTF.images||(this._glTF.images=[]),this._glTF.images.push(e))})),r.byteLength=a):this._glTF.images=this._images),e||(r.uri=t+".bin"),i?JSON.stringify(this._glTF,null,2):JSON.stringify(this._glTF)}_generateGLTFAsync(e,t=!0){return this._generateBinaryAsync().then((i=>{this._extensionsOnExporting();const r=this._generateJSON(!1,e,!0),s=new Blob([i],{type:"application/octet-stream"}),n=e+".gltf",o=e+".bin",a=new qW;if(a.glTFFiles[n]=r,a.glTFFiles[o]=s,this._imageData)for(const e in this._imageData)a.glTFFiles[e]=new Blob([this._imageData[e].data],{type:this._imageData[e].mimeType});return t&&this.dispose(),a}))}_generateBinaryAsync(){const e=new eH(4);return this._createSceneAsync(e).then((()=>(this._localEngine&&this._localEngine.dispose(),e.getArrayBuffer())))}_getPadding(e){const t=e%4;return 0===t?t:4-t}_generateGLBAsync(e,t=!0){return this._generateBinaryAsync().then((i=>{this._extensionsOnExporting();const r=this._generateJSON(!0),s=e+".glb";let n,o=r.length,a=0;"undefined"!=typeof TextEncoder&&(n=(new TextEncoder).encode(r),o=n.length);for(let e=0;e0){if(d._getEffectiveOrientation(o)===(this._babylonScene.useRightHandedSystem?Vt.ClockWiseSideOrientation:Vt.CounterClockWiseSideOrientation)){let e=null!=l?this._bufferViews[l].byteOffset:null;null==e&&(e=0);let t=null;if(null!=l&&(t=o.getIndices()),t)this._reorderIndicesBasedOnPrimitiveMode(s,h,t,e,i);else for(const e of a){const t=o.getVerticesData(e.kind,void 0,void 0,!0);if(t){const r=this._bufferViews[c[e.kind]].byteOffset||0;this._reorderVertexAttributeDataBasedOnPrimitiveMode(s,h,e.kind,t,r,i)}}}null!=f&&(_.material=f)}if(u){e.extras||(e.extras={}),e.extras.targetNames=[];for(let t=0;t{}))}_createSceneAsync(e){const t={nodes:[]};let i,r,s;const n=[...this._babylonScene.transformNodes,...this._babylonScene.meshes,...this._babylonScene.lights,...this._babylonScene.cameras],o=new Set;if(this._babylonScene.metadata&&(this._options.metadataSelector?t.extras=this._options.metadataSelector(this._babylonScene.metadata):this._babylonScene.metadata.gltf&&(t.extras=this._babylonScene.metadata.gltf.extras)),(this._options.removeNoopRootNodes??1)&&!this._options.includeCoordinateSystemConversionNodes)for(const e of this._babylonScene.rootNodes)$W(e,this._babylonScene.useRightHandedSystem)&&(o.add(e),n.splice(n.indexOf(e),1));const a=new Map;this._babylonScene.cameras.forEach((e=>{if(this._options.shouldExportNode&&!this._options.shouldExportNode(e))return;const t={type:e.mode===rt.PERSPECTIVE_CAMERA?"perspective":"orthographic"};if(e.name&&(t.name=e.name),"perspective"===t.type)t.perspective={aspectRatio:e.getEngine().getAspectRatio(e),yfov:e.fovMode===rt.FOVMODE_VERTICAL_FIXED?e.fov:e.fov*e.getEngine().getAspectRatio(e),znear:e.minZ,zfar:e.maxZ};else if("orthographic"===t.type){const i=e.orthoLeft&&e.orthoRight?.5*(e.orthoRight-e.orthoLeft):.5*e.getEngine().getRenderWidth(),r=e.orthoBottom&&e.orthoTop?.5*(e.orthoTop-e.orthoBottom):.5*e.getEngine().getRenderHeight();t.orthographic={xmag:i,ymag:r,znear:e.minZ,zfar:e.maxZ}}a.set(e,this._cameras.length),this._cameras.push(t)}));const[l,h]=this._getExportNodes(n);return this._glTFMaterialExporter._convertMaterialsToGLTFAsync(h,"image/png",!0).then((()=>this._createNodeMapAndAnimationsAsync(l,e).then((l=>this._createSkinsAsync(l,e).then((h=>{if(this._nodeMap=l,this._totalByteLength=e.getByteOffset(),null==this._totalByteLength)throw new Error("undefined byte length!");for(const e of n)if(i=this._nodeMap[e.uniqueId],void 0!==i&&(r=this._nodes[i],e.metadata&&(this._options.metadataSelector?r.extras=this._options.metadataSelector(e.metadata):e.metadata.gltf&&(r.extras=e.metadata.gltf.extras)),e instanceof rt&&(r.camera=a.get(e)),this._options.shouldExportNode&&!this._options.shouldExportNode(e)?Ue.S0.Log("Omitting "+e.name+" from scene."):(e.parent||this._babylonScene.useRightHandedSystem||QW(r),e.parent&&!o.has(e.parent)||t.nodes.push(i)),e instanceof Yt&&e.skeleton&&(r.skin=h[e.skeleton.uniqueId]),s=e.getDescendants(!0),!r.children&&s&&s.length)){const e=[];for(const t of s)null!=this._nodeMap[t.uniqueId]&&e.push(this._nodeMap[t.uniqueId]);e.length&&(r.children=e)}t.nodes.length&&this._scenes.push(t)}))))))}_getExportNodes(e){const t=[],i=new Set;for(const r of e)if(!this._options.shouldExportNode||this._options.shouldExportNode(r)){t.push(r);const e=r;if(e.subMeshes&&e.subMeshes.length>0){const t=e.material||e.getScene().defaultMaterial;if(t instanceof kt)for(const e of t.subMaterials)e&&i.add(e);else i.add(t)}}else r.name;return[t,i]}_createNodeMapAndAnimationsAsync(e,t){let i=Promise.resolve();const r={};let s;const n={name:"runtime animations",channels:[],samplers:[]},o=[];for(const a of e)i=i.then((()=>this._createNodeAsync(a,t).then((e=>{const i=this._extensionsPostExportNodeAsync("createNodeAsync",e,a,r,t);return null==i?(Ue.S0.Warn(`Not exporting node ${a.name}`),Promise.resolve()):i.then((e=>{e&&(this._nodes.push(e),s=this._nodes.length-1,r[a.uniqueId]=s,this._babylonScene.animationGroups.length||(XW._CreateMorphTargetAnimationFromMorphTargetAnimations(a,n,o,r,this._nodes,t,this._bufferViews,this._accessors,this._animationSampleRate,this._options.shouldExportAnimation),a.animations.length&&XW._CreateNodeAnimationFromNodeAnimations(a,n,o,r,this._nodes,t,this._bufferViews,this._accessors,this._animationSampleRate,this._options.shouldExportAnimation)))}))}))));return i.then((()=>(n.channels.length&&n.samplers.length&&this._animations.push(n),o.forEach((e=>{e.channels.length&&e.samplers.length&&this._animations.push(e)})),this._babylonScene.animationGroups.length&&XW._CreateNodeAndMorphAnimationFromAnimationGroups(this._babylonScene,this._animations,r,t,this._bufferViews,this._accessors,this._animationSampleRate,this._options.shouldExportAnimation),r)))}_createNodeAsync(e,t){return Promise.resolve().then((()=>{const i={},r={primitives:[]};if(e.name&&(i.name=e.name),e instanceof Pt){if(this._setNodeTransformation(i,e),e instanceof Yt){const t=e.morphTargetManager;if(t&&t.numTargets>0){r.weights=[];for(let e=0;e(r.primitives.length&&(this._meshes.push(r),i.mesh=this._meshes.length-1),i)))}return e instanceof rt?(this._setCameraTransformation(i,e),i):i}))}_createSkinsAsync(e,t){const i=Promise.resolve(),r={};for(const i of this._babylonScene.skeletons){if(i.bones.length<=0)continue;const s={joints:[]},n=[],o={};let a=-1;for(let e=0;ea&&(a=r))}for(let t=0;t<=a;++t){const i=o[t];n.push(i.getInvertedAbsoluteTransform());const r=i.getTransformNode();r&&null!==e[r.uniqueId]&&void 0!==e[r.uniqueId]?s.joints.push(e[r.uniqueId]):Ue.S0.Warn("Exporting a bone without a linked transform node is currently unsupported")}if(s.joints.length>0){const e=64,o=n.length*e,a=t.getByteOffset(),l=HW._CreateBufferView(0,a,o,void 0,"InverseBindMatrices - "+i.name);this._bufferViews.push(l);const h=this._bufferViews.length-1,c=HW._CreateAccessor(h,"InverseBindMatrices - "+i.name,"MAT4",5126,n.length,null,null,null),u=this._accessors.push(c)-1;s.inverseBindMatrices=u,this._skins.push(s),r[i.uniqueId]=this._skins.length-1,n.forEach((e=>{e.m.forEach((e=>{t.setFloat32(e)}))}))}}return i.then((()=>r))}}JW._ExtensionNames=new Array,JW._ExtensionFactories={};class eH{constructor(e){this._arrayBuffer=new ArrayBuffer(e),this._dataView=new DataView(this._arrayBuffer),this._byteOffset=0}_resizeBuffer(e){const t=new ArrayBuffer(e),i=Math.min(this._arrayBuffer.byteLength,e),r=new Uint8Array(this._arrayBuffer,0,i);return new Uint8Array(t).set(r,0),this._arrayBuffer=t,this._dataView=new DataView(this._arrayBuffer),t}getArrayBuffer(){return this._resizeBuffer(this.getByteOffset())}getByteOffset(){if(null==this._byteOffset)throw new Error("Byte offset is undefined!");return this._byteOffset}setUInt8(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setUint8(this._byteOffset,e),this._byteOffset+=1)}setUInt16(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setUint16(this._byteOffset,e,!0),this._byteOffset+=2)}getUInt32(e){if(ethis._byteOffset?Ue.S0.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(e.x=this._dataView.getFloat32(t,!0),e.y=this._dataView.getFloat32(t+4,!0),e.z=this._dataView.getFloat32(t+8,!0))}setVector3Float32FromRef(e,t){t+8>this._byteOffset?Ue.S0.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(this._dataView.setFloat32(t,e.x,!0),this._dataView.setFloat32(t+4,e.y,!0),this._dataView.setFloat32(t+8,e.z,!0))}getVector4Float32FromRef(e,t){t+12>this._byteOffset?Ue.S0.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(e.x=this._dataView.getFloat32(t,!0),e.y=this._dataView.getFloat32(t+4,!0),e.z=this._dataView.getFloat32(t+8,!0),e.w=this._dataView.getFloat32(t+12,!0))}setVector4Float32FromRef(e,t){t+12>this._byteOffset?Ue.S0.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(this._dataView.setFloat32(t,e.x,!0),this._dataView.setFloat32(t+4,e.y,!0),this._dataView.setFloat32(t+8,e.z,!0),this._dataView.setFloat32(t+12,e.w,!0))}setFloat32(e,t){isNaN(e)&&Ue.S0.Error("Invalid data being written!"),null!=t&&(tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setFloat32(this._byteOffset,e,!0),this._byteOffset+=4}setUInt32(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setUint32(this._byteOffset,e,!0),this._byteOffset+=4)}setInt16(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setInt16(this._byteOffset,e,!0),this._byteOffset+=2)}setByte(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setInt8(this._byteOffset,e),this._byteOffset++)}}class tH{static GLTFAsync(e,t,i){return e.whenReadyAsync().then((()=>{const r=t.replace(/\.[^/.]+$/,"");return new JW(e,i)._generateGLTFAsync(r)}))}static _PreExportAsync(e,t){return Promise.resolve().then((()=>t&&t.exportWithoutWaitingForScene?Promise.resolve():e.whenReadyAsync()))}static _PostExportAsync(e,t,i){return Promise.resolve().then((()=>(i&&i.exportWithoutWaitingForScene,t)))}static GLBAsync(e,t,i){return this._PreExportAsync(e,i).then((()=>{const r=t.replace(/\.[^/.]+$/,"");return new JW(e,i)._generateGLBAsync(r).then((t=>this._PostExportAsync(e,t,i)))}))}}const iH="KHR_texture_transform";class rH{constructor(){this.name=iH,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}postExportTexture(e,t,i){if(i&&(0===i.uAng&&0===i.wAng&&0===i.vAng||0===i.uRotationCenter&&0===i.vRotationCenter)){const e={};let r=!1;if(0===i.uOffset&&0===i.vOffset||(e.offset=[i.uOffset,i.vOffset],r=!0),1===i.uScale&&1===i.vScale||(e.scale=[i.uScale,i.vScale],r=!0),0!==i.wAng&&(e.rotation=-i.wAng,r=!0),0!==i.coordinatesIndex&&(e.texCoord=i.coordinatesIndex,r=!0),!r)return;this._wasUsed=!0,t.extensions||(t.extensions={}),t.extensions[iH]=e}}preExportTextureAsync(e,t){return new Promise(((i,r)=>{t.getScene()?0!==t.uAng||0!==t.vAng?(Ue.S0.Warn(`${e}: Texture ${t.name} with rotation in the u or v axis is not supported in glTF.`),i(null)):0===t.wAng||0===t.uRotationCenter&&0===t.vRotationCenter?i(t):(Ue.S0.Warn(`${e}: Texture ${t.name} with rotation not centered at the origin cannot be exported with ${iH}`),i(null)):r(`${e}: "scene" is not defined for Babylon texture ${t.name}!`)}))}}JW.RegisterExtension(iH,(()=>new rH));const sH="KHR_lights_punctual";class nH{constructor(e){this.name=sH,this.enabled=!0,this.required=!1,this._exporter=e}dispose(){this._lights=null}get wasUsed(){return!!this._lights}onExporting(){this._exporter._glTF.extensions[sH]=this._lights}postExportNodeAsync(e,t,i,r){return new Promise((s=>{if(t&&i instanceof lm){let n;const o=i.getTypeID()==$t.LIGHTTYPEID_POINTLIGHT?"point":i.getTypeID()==$t.LIGHTTYPEID_DIRECTIONALLIGHT?"directional":i.getTypeID()==$t.LIGHTTYPEID_SPOTLIGHT?"spot":null;if(null==o)Z.V.Warn(`${e}: Light ${i.name} is not supported in ${sH}`);else{if(i.position.equalsToFloats(0,0,0)||(t.translation=i.position.asArray()),"point"!==o){const e=i.direction,r=-Math.atan2(e.z,e.x)+Math.PI/2,s=Math.sqrt(e.x*e.x+e.z*e.z),n=-Math.atan2(e.y,s),o=W.PT.RotationYawPitchRoll(r+Math.PI,n,0);W.PT.IsIdentity(o)||(t.rotation=o.asArray())}if(i.falloffType!==$t.FALLOFF_GLTF&&Z.V.Warn(`${e}: Light falloff for ${i.name} does not match the ${sH} specification!`),n={type:o},i.diffuse.equals(H.v9.White())||(n.color=i.diffuse.asArray()),1!==i.intensity&&(n.intensity=i.intensity),i.range!==Number.MAX_VALUE&&(n.range=i.range),"spot"===o){const e=i;e.angle!==Math.PI/2&&(null==n.spot&&(n.spot={}),n.spot.outerConeAngle=e.angle/2),0!==e.innerAngle&&(null==n.spot&&(n.spot={}),n.spot.innerConeAngle=e.innerAngle/2)}this._lights||(this._lights={lights:[]}),this._lights.lights.push(n);const a={light:this._lights.lights.length-1},l=i.parent;if(l&&1==l.getChildren().length){const e=this._exporter._nodes[r[l.uniqueId]];if(e){const i=W.Pq.FromArrayToRef(e.translation||[0,0,0],0,W.AA.Vector3[0]),r=W.PT.FromArrayToRef(e.rotation||[0,0,0,1],0,W.AA.Quaternion[0]),n=W.Pq.FromArrayToRef(e.scale||[1,1,1],0,W.AA.Vector3[1]),o=W.uq.ComposeToRef(n,r,i,W.AA.Matrix[0]),l=W.Pq.FromArrayToRef(t.translation||[0,0,0],0,W.AA.Vector3[2]),h=W.PT.FromArrayToRef(t.rotation||[0,0,0,1],0,W.AA.Quaternion[1]),c=W.uq.ComposeToRef(W.Pq.OneReadOnly,h,l,W.AA.Matrix[1]);return o.multiplyToRef(c,c),c.decompose(n,r,i),i.equalsToFloats(0,0,0)?delete e.translation:e.translation=i.asArray(),W.PT.IsIdentity(r)?delete e.rotation:e.rotation=r.asArray(),n.equalsToFloats(1,1,1)?delete e.scale:e.scale=n.asArray(),e.extensions||(e.extensions={}),e.extensions[sH]=a,void s(null)}}t.extensions||(t.extensions={}),t.extensions[sH]=a}}s(t)}))}}JW.RegisterExtension(sH,(e=>new nH(e)));const oH="KHR_materials_clearcoat";class aH{constructor(e){this.name=oH,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const r=[];return i instanceof Gm&&i.clearCoat.isEnabled?(i.clearCoat.texture&&r.push(i.clearCoat.texture),!i.clearCoat.useRoughnessFromMainTexture&&i.clearCoat.textureRoughness&&r.push(i.clearCoat.textureRoughness),i.clearCoat.bumpTexture&&r.push(i.clearCoat.bumpTexture),r):[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Gm){if(!i.clearCoat.isEnabled)return void e(t);this._wasUsed=!0,t.extensions=t.extensions||{};const r=this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.texture);let s;s=i.clearCoat.useRoughnessFromMainTexture?this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.texture):this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.textureRoughness),i.clearCoat.isTintEnabled&&Ue.S0.Warn(`Clear Color tint is not supported for glTF export. Ignoring for: ${i.name}`),i.clearCoat.remapF0OnInterfaceChange&&Ue.S0.Warn(`Clear Color F0 remapping is not supported for glTF export. Ignoring for: ${i.name}`);const n=this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.bumpTexture),o={clearcoatFactor:i.clearCoat.intensity,clearcoatTexture:r??void 0,clearcoatRoughnessFactor:i.clearCoat.roughness,clearcoatRoughnessTexture:s??void 0,clearcoatNormalTexture:n??void 0,hasTextures:()=>null!==o.clearcoatTexture||null!==o.clearcoatRoughnessTexture||null!==o.clearcoatRoughnessTexture};t.extensions[oH]=o}e(t)}))}}JW.RegisterExtension(oH,(e=>new aH(e)));const lH="KHR_materials_iridescence";class hH{constructor(e){this.name=lH,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const r=[];return i instanceof Gm&&i.iridescence.isEnabled?(i.iridescence.texture&&r.push(i.iridescence.texture),i.iridescence.thicknessTexture&&i.iridescence.thicknessTexture!==i.iridescence.texture&&r.push(i.iridescence.thicknessTexture),r):[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Gm){if(!i.iridescence.isEnabled)return void e(t);this._wasUsed=!0,t.extensions=t.extensions||{};const r=this._exporter._glTFMaterialExporter._getTextureInfo(i.iridescence.texture),s=this._exporter._glTFMaterialExporter._getTextureInfo(i.iridescence.thicknessTexture),n={iridescenceFactor:i.iridescence.intensity,iridescenceIor:i.iridescence.indexOfRefraction,iridescenceThicknessMinimum:i.iridescence.minimumThickness,iridescenceThicknessMaximum:i.iridescence.maximumThickness,iridescenceTexture:r??void 0,iridescenceThicknessTexture:s??void 0,hasTextures:()=>null!==n.iridescenceTexture||null!==n.iridescenceThicknessTexture};t.extensions[lH]=n}e(t)}))}}JW.RegisterExtension(lH,(e=>new hH(e)));const cH="KHR_materials_anisotropy";class uH{constructor(e){this.name=cH,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const r=[];return i instanceof Gm&&i.anisotropy.isEnabled&&!i.anisotropy.legacy?(i.anisotropy.texture&&r.push(i.anisotropy.texture),r):[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Gm){if(!i.anisotropy.isEnabled||i.anisotropy.legacy)return void e(t);this._wasUsed=!0,t.extensions=t.extensions||{};const r=this._exporter._glTFMaterialExporter._getTextureInfo(i.anisotropy.texture),s={anisotropyStrength:i.anisotropy.intensity,anisotropyRotation:i.anisotropy.angle,anisotropyTexture:r??void 0,hasTextures:()=>null!==s.anisotropyTexture};t.extensions[cH]=s}e(t)}))}}JW.RegisterExtension(cH,(e=>new uH(e)));const dH="KHR_materials_sheen";class fH{constructor(e){this.name=dH,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){return i instanceof zm&&i.sheen.isEnabled&&i.sheen.texture?[i.sheen.texture]:[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zm){if(!i.sheen.isEnabled)return void e(t);this._wasUsed=!0,null==t.extensions&&(t.extensions={});const r={sheenColorFactor:i.sheen.color.asArray(),sheenRoughnessFactor:i.sheen.roughness??0,hasTextures:()=>null!==r.sheenColorTexture||null!==r.sheenRoughnessTexture};i.sheen.texture&&(r.sheenColorTexture=this._exporter._glTFMaterialExporter._getTextureInfo(i.sheen.texture)??void 0),i.sheen.textureRoughness&&!i.sheen.useRoughnessFromMainTexture?r.sheenRoughnessTexture=this._exporter._glTFMaterialExporter._getTextureInfo(i.sheen.textureRoughness)??void 0:i.sheen.texture&&i.sheen.useRoughnessFromMainTexture&&(r.sheenRoughnessTexture=this._exporter._glTFMaterialExporter._getTextureInfo(i.sheen.texture)??void 0),t.extensions[dH]=r}e(t)}))}}JW.RegisterExtension(dH,(e=>new fH(e)));const pH="KHR_materials_unlit";class _H{constructor(){this.name=pH,this.enabled=!0,this.required=!1,this._wasUsed=!1}get wasUsed(){return this._wasUsed}dispose(){}postExportMaterialAsync(e,t,i){return new Promise((e=>{let r=!1;i instanceof zm?r=i.unlit:i instanceof Un&&(r=i.disableLighting),r&&(this._wasUsed=!0,null==t.extensions&&(t.extensions={}),t.extensions[pH]={}),e(t)}))}}JW.RegisterExtension(pH,(()=>new _H));const mH="KHR_materials_ior";class gH{constructor(){this.name=mH,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}_isExtensionEnabled(e){return!e.unlit&&null!=e.indexOfRefraction&&1.5!=e.indexOfRefraction}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zm&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e={ior:i.indexOfRefraction};t.extensions=t.extensions||{},t.extensions[mH]=e}e(t)}))}}JW.RegisterExtension(mH,(e=>new gH));const vH="KHR_materials_specular";class xH{constructor(e){this.name=vH,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const r=[];return i instanceof zm&&this._isExtensionEnabled(i)?(i.metallicReflectanceTexture&&r.push(i.metallicReflectanceTexture),i.reflectanceTexture&&r.push(i.reflectanceTexture),r):r}_isExtensionEnabled(e){return!e.unlit&&(null!=e.metallicF0Factor&&1!=e.metallicF0Factor||null!=e.metallicReflectanceColor&&!e.metallicReflectanceColor.equalsFloats(1,1,1)||this._hasTexturesExtension(e))}_hasTexturesExtension(e){return null!=e.metallicReflectanceTexture||null!=e.reflectanceTexture}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zm&&this._isExtensionEnabled(i)){this._wasUsed=!0,t.extensions=t.extensions||{};const e=this._exporter._glTFMaterialExporter._getTextureInfo(i.metallicReflectanceTexture)??void 0,r=this._exporter._glTFMaterialExporter._getTextureInfo(i.reflectanceTexture)??void 0,s={specularFactor:1==i.metallicF0Factor?void 0:i.metallicF0Factor,specularTexture:e,specularColorFactor:i.metallicReflectanceColor.equalsFloats(1,1,1)?void 0:i.metallicReflectanceColor.asArray(),specularColorTexture:r,hasTextures:()=>this._hasTexturesExtension(i)};t.extensions[vH]=s}e(t)}))}}JW.RegisterExtension(vH,(e=>new xH(e)));const bH="KHR_materials_volume";class SH{constructor(e){this.name=bH,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const r=[];return i instanceof zm&&this._isExtensionEnabled(i)?(i.subSurface.thicknessTexture&&r.push(i.subSurface.thicknessTexture),r):r}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return!(!t.isRefractionEnabled&&!t.isTranslucencyEnabled)&&(null!=t.maximumThickness&&0!=t.maximumThickness||null!=t.tintColorAtDistance&&t.tintColorAtDistance!=Number.POSITIVE_INFINITY||null!=t.tintColor&&t.tintColor!=H.v9.White()||this._hasTexturesExtension(e))}_hasTexturesExtension(e){return null!=e.subSurface.thicknessTexture}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zm&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e=i.subSurface,r={thicknessFactor:0==e.maximumThickness?void 0:e.maximumThickness,thicknessTexture:this._exporter._glTFMaterialExporter._getTextureInfo(e.thicknessTexture)??void 0,attenuationDistance:e.tintColorAtDistance==Number.POSITIVE_INFINITY?void 0:e.tintColorAtDistance,attenuationColor:e.tintColor.equalsFloats(1,1,1)?void 0:e.tintColor.asArray(),hasTextures:()=>this._hasTexturesExtension(i)};t.extensions=t.extensions||{},t.extensions[bH]=r}e(t)}))}}JW.RegisterExtension(bH,(e=>new SH(e)));const TH="KHR_materials_dispersion";class CH{constructor(){this.name=TH,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return!(!t.isRefractionEnabled&&!t.isDispersionEnabled)}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zm&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e={dispersion:i.subSurface.dispersion};t.extensions=t.extensions||{},t.extensions[TH]=e}e(t)}))}}JW.RegisterExtension(TH,(()=>new CH));const yH="KHR_materials_transmission";class EH{constructor(e){this.name=yH,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const r=[];return i instanceof zm&&this._isExtensionEnabled(i)?(i.subSurface.thicknessTexture&&r.push(i.subSurface.thicknessTexture),r):r}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return t.isRefractionEnabled&&null!=t.refractionIntensity&&0!=t.refractionIntensity||this._hasTexturesExtension(e)}_hasTexturesExtension(e){return null!=e.subSurface.refractionIntensityTexture}async postExportMaterialAsync(e,t,i){if(i instanceof zm&&this._isExtensionEnabled(i)){this._wasUsed=!0;const r=i.subSurface,s={transmissionFactor:0===r.refractionIntensity?void 0:r.refractionIntensity,hasTextures:()=>this._hasTexturesExtension(i)};if(r.refractionIntensityTexture)if(r.useGltfStyleTextures){const e=await this._exporter._glTFMaterialExporter._exportTextureInfoAsync(r.refractionIntensityTexture,"image/png");e&&(s.transmissionTexture=e)}else Z.V.Warn(`${e}: Exporting a subsurface refraction intensity texture without \`useGltfStyleTextures\` is not supported`);t.extensions||(t.extensions={}),t.extensions[yH]=s}return t}}JW.RegisterExtension(yH,(e=>new EH(e)));const PH="EXT_mesh_gpu_instancing";class AH{constructor(e){this.name=PH,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportNodeAsync(e,t,i,r,s){return new Promise((e=>{if(t&&i instanceof Yt&&i.hasThinInstances&&s){this._wasUsed=!0;const e=W.Pq.Zero(),r=W.PT.Identity(),n=W.Pq.One(),o=i.thinInstanceGetWorldMatrices(),a=W.AA.Vector3[2],l=W.AA.Quaternion[1],h=W.AA.Vector3[3];let c=!1,u=!1,d=!1;const f=new Float32Array(3*i.thinInstanceCount),p=new Float32Array(4*i.thinInstanceCount),_=new Float32Array(3*i.thinInstanceCount);let m=0;for(const t of o)t.decompose(h,l,a),f.set(a.asArray(),3*m),p.set(l.normalize().asArray(),4*m),_.set(h.asArray(),3*m),c=c||!a.equalsWithEpsilon(e),u=u||!l.equalsWithEpsilon(r),d=d||!h.equalsWithEpsilon(n),m++;const g={attributes:{}};if(c&&(g.attributes.TRANSLATION=this._buildAccessor(f,"VEC3",i.thinInstanceCount,s,5126)),u){const e=5126;g.attributes.ROTATION=this._buildAccessor(p,"VEC4",i.thinInstanceCount,s,e)}d&&(g.attributes.SCALE=this._buildAccessor(_,"VEC3",i.thinInstanceCount,s,5126)),t.extensions=t.extensions||{},t.extensions[PH]=g}e(t)}))}_buildAccessor(e,t,i,r,s){const n=r.getByteOffset();switch(s){case 5126:for(let t=0;t!=e.length;t++)r.setFloat32(e[t]);break;case 5120:for(let t=0;t!=e.length;t++)r.setByte(127*e[t]);break;case 5122:for(let t=0;t!=e.length;t++)r.setInt16(32767*e[t])}const o={buffer:0,byteOffset:n,byteLength:e.length*st.R.GetTypeByteLength(s)},a=this._exporter._bufferViews.length;this._exporter._bufferViews.push(o);const l=this._exporter._accessors.length,h={bufferView:a,componentType:s,count:i,type:t,normalized:5120==s||5122==s};return this._exporter._accessors.push(h),l}}JW.RegisterExtension(PH,(e=>new AH(e)));const RH="KHR_materials_emissive_strength";class IH{constructor(){this.name=RH,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(!(i instanceof zm))return e(t);const r=i.emissiveColor.asArray(),s=Math.max(...r);if(s>1){this._wasUsed=!0,t.extensions||(t.extensions={});const e={emissiveStrength:s},r=i.emissiveColor.scale(1/e.emissiveStrength);t.emissiveFactor=r.asArray(),t.extensions[RH]=e}return e(t)}))}}JW.RegisterExtension(RH,(e=>new IH));const MH="KHR_materials_diffuse_transmission";class OH{constructor(e){this.name=MH,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const r=[];return i instanceof zm&&this._isExtensionEnabled(i)?(i.subSurface.thicknessTexture&&r.push(i.subSurface.thicknessTexture),r):r}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return!!t.isTranslucencyEnabled&&!e.unlit&&!t.useAlbedoToTintTranslucency&&t.useGltfStyleTextures&&1===t.volumeIndexOfRefraction&&0===t.minimumThickness&&0===t.maximumThickness}_hasTexturesExtension(e){return null!=e.subSurface.translucencyIntensityTexture||null!=e.subSurface.translucencyColorTexture}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zm&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e=i.subSurface,r={diffuseTransmissionFactor:1==e.translucencyIntensity?void 0:e.translucencyIntensity,diffuseTransmissionTexture:this._exporter._glTFMaterialExporter._getTextureInfo(e.translucencyIntensityTexture)??void 0,diffuseTransmissionColorFactor:!e.translucencyColor||e.translucencyColor.equalsFloats(1,1,1)?void 0:e.translucencyColor.asArray(),diffuseTransmissionColorTexture:this._exporter._glTFMaterialExporter._getTextureInfo(e.translucencyColorTexture)??void 0,hasTextures:()=>this._hasTexturesExtension(i)};t.extensions=t.extensions||{},t.extensions[MH]=r}e(t)}))}}JW.RegisterExtension(MH,(e=>new OH(e)));class DH{static CreateSTL(e,t=!0,i="stlmesh",r=!1,s=!0,n=!1,o=!1,a=!1){const l=function(e,t,i){const r=[3*e[i],3*e[i+1],3*e[i+2]],s=[new W.Pq(t[r[0]],t[r[0]+2],t[r[0]+1]),new W.Pq(t[r[1]],t[r[1]+2],t[r[1]+1]),new W.Pq(t[r[2]],t[r[2]+2],t[r[2]+1])],n=s[0].subtract(s[1]),o=s[2].subtract(s[1]);return{v:s,n:W.Pq.Cross(o,n).normalize()}},h=function(e,t,i,r){return t=c(e,t,i.x,r),t=c(e,t,i.y,r),c(e,t,i.z,r)},c=function(e,t,i,r){return e.setFloat32(t,i,r),t+4},u=function(e){if(o){let t=e;e instanceof Kt&&(t=e.sourceMesh);const i=t.getVerticesData(st.R.PositionKind,!0,!0);if(!i)return[];const r=W.Pq.Zero();let s;for(s=0;s"bitbybit-hdrSkyBox"!==e.name&&!e.name.includes("bitbybit-ground")}),tH.GLBAsync(this.context.scene,e.fileName,t).then((e=>{e.downloadFiles()}))}exportMeshToStl(e){return aX(this,void 0,void 0,(function*(){const t=e.mesh.getChildMeshes();let i=[];t&&t.length>0&&(i=t.filter((e=>!(e instanceof Ca||e instanceof AE))));let r=[e.mesh,...i];return r=r.filter((e=>e.isVisible)),DH.CreateSTL(r,!0,e.fileName,!0,!0,!0),Promise.resolve({})}))}exportMeshesToStl(e){return aX(this,void 0,void 0,(function*(){let t;return e.meshes.forEach((e=>{const i=e.getChildMeshes();let r=[];i&&i.length>0&&(r=i.filter((e=>!(e instanceof Ca||e instanceof AE)))),t.push(e),r.length>0&&t.push(...r)})),DH.CreateSTL(t,!0,e.fileName,!0,!0,!0),Promise.resolve({})}))}loadAsset(e,t,i,r){return aX(this,void 0,void 0,(function*(){const e=yield xg.ImportMeshAsync("",t,i,this.context.scene),s=this.context.scene.metadata.shadowGenerators,n=new Yt("ImportedMeshContainer"+Math.random(),this.context.scene);return s.length>0&&e.meshes.forEach((e=>{if(e.isPickable=!1,r&&(e.isVisible=!1),e.getChildMeshes().forEach((e=>{e.isPickable=!1,r&&(e.isVisible=!1)})),this.context.scene.metadata.shadowGenerators.length>0){try{e.receiveShadows=!0}catch(e){}s.forEach((t=>{t.addShadowCaster(e)})),e.getChildMeshes().forEach((e=>{try{e.receiveShadows=!0}catch(e){}s.forEach((t=>{t.addShadowCaster(e)}))}))}})),e.meshes.forEach((e=>{e.parent=n})),n}))}}class hX{constructor(e){this.context=e}setDirectionToTarget(e){e.shadowLight.setDirectionToTarget(new hc.Pq(e.target[0],e.target[1],e.target[2]))}setPosition(e){e.shadowLight.position=new hc.Pq(e.position[0],e.position[1],e.position[2])}}class cX{constructor(e){this.context=e,this.shadowLight=new hX(e)}}class uX{constructor(e){this.context=e}createFullScreenUI(e){const t=vi.g.BILINEAR_SAMPLINGMODE;return $B.CreateFullscreenUI(e.name,e.foreground,this.context.scene,t,e.adaptiveScaling)}createForMesh(e){const t=this.context.getSamplingMode(e.sampling);return $B.CreateForMesh(e.mesh,e.width,e.height,e.supportPointerMove,e.onlyAlphaTesting,e.invertY,void 0,t)}}class dX{constructor(e){this.context=e}createStackPanel(e){const t=new _B(e.name);return t.isVertical=e.isVertical,t.spacing=e.spacing,t.onDisposeObservable.add((e=>{e.clearControls()})),void 0!==e.width?t.width=e.width:t.width=1,void 0!==e.height&&(t.height=e.height),void 0!==e.color&&(t.color=e.color),void 0!==e.background&&(t.background=e.background),t}setIsVertical(e){return e.stackPanel.isVertical=e.isVertical,e.stackPanel}setSpacing(e){return e.stackPanel.spacing=e.spacing,e.stackPanel}setWidth(e){return e.stackPanel.width=e.width,e.stackPanel}setHeight(e){return e.stackPanel.height=e.height,e.stackPanel}getIsVertical(e){return e.stackPanel.isVertical}getSpacing(e){return e.stackPanel.spacing}getWidth(e){return e.stackPanel.width}getHeight(e){return e.stackPanel.height}}class fX{constructor(e){this.context=e}addControls(e){return e.clearControlsFirst&&e.container.clearControls&&e.container.clearControls(),e.controls.forEach((t=>e.container.addControl(t))),e.container}setBackground(e){return e.container.background=e.background,e.container}setIsReadonly(e){return e.container.isReadOnly=e.isReadOnly,e.container}getBackground(e){return e.container.background}getIsReadonly(e){return e.container.isReadOnly}}class pX{constructor(e){this.context=e}createSimpleButton(e){const t=pB.CreateSimpleButton(e.name,e.label);return e.width?t.width=e.width:t.width=1,e.height?t.height=e.height:t.height="42px",t.color=e.color,t.fontSize=e.fontSize,t.background=e.background,t}setButtonText(e){return e.button.textBlock.text=e.text,e.button}getButtonText(e){return e.button.textBlock.text}}class _X{constructor(e){this.context=e}changeControlPadding(e){return void 0!==e.paddingLeft&&(e.control.paddingLeft=e.paddingLeft),void 0!==e.paddingRight&&(e.control.paddingRight=e.paddingRight),void 0!==e.paddingTop&&(e.control.paddingTop=e.paddingTop),void 0!==e.paddingBottom&&(e.control.paddingBottom=e.paddingBottom),e.control}changeControlAlignment(e){switch(e.horizontalAlignment){case"left":e.control.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT;break;case"right":e.control.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_RIGHT;break;case"center":e.control.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_CENTER}switch(e.verticalAlignment){case"top":e.control.verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP;break;case"bottom":e.control.verticalAlignment=lB.VERTICAL_ALIGNMENT_BOTTOM;break;case"center":e.control.verticalAlignment=lB.VERTICAL_ALIGNMENT_CENTER}return e.control}cloneControl(e){const t=e.control.clone(e.host);return e.container&&e.container.addControl(t),e.name&&(t.name=e.name),t}createControlObservableSelector(e){return e.selector}getControlByName(e){return e.container.children.find((t=>t.name===e.name))}setIsVisible(e){return e.control.isVisible=e.isVisible,e.control}setIsReadonly(e){return e.control.isReadOnly=e.isReadOnly,e.control}setIsEnabled(e){return e.control.isEnabled=e.isEnabled,e.control}setHeight(e){return e.control.height=e.height,e.control}setWidth(e){return e.control.width=e.width,e.control}setColor(e){return e.control.color=e.color,e.control}setFontSize(e){return e.control.fontSize=e.fontSize,e.control}getHeight(e){return e.control.height}getWidth(e){return e.control.width}getColor(e){return e.control.color}getFontSize(e){return e.control.fontSize}getIsVisible(e){return e.control.isVisible}getIsReadonly(e){return e.control.isReadOnly}getIsEnabled(e){return e.control.isEnabled}}class mX{constructor(e){this.context=e}createSlider(e){const t=new MB(e.name);return t.minimum=e.minimum,t.maximum=e.maximum,t.value=e.value,t.step=e.step,t.isVertical=e.isVertical,t.displayThumb=e.displayThumb,t.thumbColor="white",e.isVertical?(e.height?t.height=e.height:t.height=1,e.width?t.width=e.width:t.width="42px"):(e.width?t.width=e.width:t.width=1,e.height?t.height=e.height:t.height="42px"),t.color=e.color,t.background=e.background,t}changeSliderThumb(e){return e.slider.thumbColor=e.thumbColor,e.slider.isThumbCircle=e.isThumbCircle,e.slider.isThumbClamped=e.isThumbClamped,e.slider.displayThumb=e.displayThumb,e.thumbWidth&&(e.slider.thumbWidth=e.thumbWidth),e.slider}setBorderColor(e){return e.slider.borderColor=e.borderColor,e.slider}setBackgroundColor(e){return e.slider.background=e.backgroundColor,e.slider}setMaximum(e){return e.slider.maximum=e.value,e.slider}setMinimum(e){return e.slider.minimum=e.value,e.slider}setStep(e){return e.slider.step=e.value,e.slider}setValue(e){return e.slider.value=e.value,e.slider}createSliderObservableSelector(e){return e.selector}getBorderColor(e){return e.slider.borderColor}getBackgroundColor(e){return e.slider.background}getMaximum(e){return e.slider.maximum}getMinimum(e){return e.slider.minimum}getStep(e){return e.slider.step}getValue(e){return e.slider.value}getThumbColor(e){return e.slider.thumbColor}getThumbWidth(e){return e.slider.thumbWidth}getIsVertical(e){return e.slider.isVertical}getDisplayThumb(e){return e.slider.displayThumb}getIsThumbCircle(e){return e.slider.isThumbCircle}getIsThumbClamped(e){return e.slider.isThumbClamped}}!function(e){e.ArcRotateCameraDto=class{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f){this.radius=20,this.target=[0,0,0],this.alpha=45,this.beta=70,this.lowerBetaLimit=1,this.upperBetaLimit=179,this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.panningSensibility=1e3,this.wheelPrecision=3,this.maxZ=1e3,void 0!==e&&(this.radius=e),void 0!==t&&(this.alpha=t),void 0!==i&&(this.beta=i),void 0!==r&&(this.lowerRadiusLimit=r),void 0!==s&&(this.upperRadiusLimit=s),void 0!==n&&(this.lowerAlphaLimit=n),void 0!==o&&(this.upperAlphaLimit=o),void 0!==a&&(this.lowerBetaLimit=a),void 0!==l&&(this.upperBetaLimit=l),void 0!==h&&(this.angularSensibilityX=h),void 0!==c&&(this.angularSensibilityY=c),void 0!==u&&(this.panningSensibility=u),void 0!==d&&(this.wheelPrecision=d),void 0!==f&&(this.maxZ=f)}},e.FreeCameraDto=class{constructor(e,t){this.position=[20,20,20],this.target=[0,0,0],void 0!==e&&(this.position=e),void 0!==t&&(this.target=t)}},e.TargetCameraDto=class{constructor(e,t){this.position=[20,20,20],this.target=[0,0,0],void 0!==e&&(this.position=e),void 0!==t&&(this.target=t)}},e.PositionDto=class{constructor(e,t){this.position=[20,20,20],void 0!==e&&(this.camera=e),void 0!==t&&(this.position=t)}},e.SpeedDto=class{constructor(e,t){this.speed=1,void 0!==e&&(this.camera=e),void 0!==t&&(this.speed=t)}},e.TargetDto=class{constructor(e,t){this.target=[0,0,0],void 0!==e&&(this.camera=e),void 0!==t&&(this.target=t)}},e.MinZDto=class{constructor(e,t){this.minZ=0,void 0!==e&&(this.camera=e),void 0!==t&&(this.minZ=t)}},e.MaxZDto=class{constructor(e,t){this.maxZ=1e3,void 0!==e&&(this.camera=e),void 0!==t&&(this.maxZ=t)}},e.OrthographicDto=class{constructor(e,t,i,r,s){this.orthoLeft=-1,this.orthoRight=1,this.orthoBottom=-1,this.orthoTop=1,void 0!==e&&(this.camera=e),void 0!==t&&(this.orthoLeft=t),void 0!==i&&(this.orthoRight=i),void 0!==r&&(this.orthoTop=r),void 0!==s&&(this.orthoBottom=s)}},e.CameraDto=class{constructor(e){void 0!==e&&(this.camera=e)}}}(wH||(wH={})),function(e){e.ExportSceneGlbDto=class{constructor(e,t){this.fileName="bitbybit-scene",this.discardSkyboxAndGrid=!1,void 0!==e&&(this.fileName=e),void 0!==t&&(this.discardSkyboxAndGrid=t)}},e.ExportSceneDto=class{constructor(e){this.fileName="bitbybit-scene",void 0!==e&&(this.fileName=e)}},e.ExportMeshToStlDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.fileName=t)}},e.ExportMeshesToStlDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.fileName=t)}}}(NH||(NH={})),function(e){e.PBRMetallicRoughnessDto=class{constructor(e,t,i,r,s,n,o,a){this.name="Custom Material",this.baseColor="#0000ff",this.emissiveColor="#000000",this.metallic=.6,this.roughness=.5,this.alpha=1,this.backFaceCulling=!1,this.zOffset=0,void 0!==e&&(this.name=e),void 0!==t&&(this.baseColor=t),void 0!==i&&(this.emissiveColor=i),void 0!==r&&(this.metallic=r),void 0!==s&&(this.roughness=s),void 0!==n&&(this.alpha=n),void 0!==o&&(this.backFaceCulling=o),void 0!==a&&(this.zOffset=a)}},e.BaseColorDto=class{constructor(e,t){this.baseColor="#0000ff",void 0!==e&&(this.material=e),void 0!==t&&(this.baseColor=t)}},e.MaterialPropDto=class{constructor(e){void 0!==e&&(this.material=e)}},e.SkyMaterialPropDto=class{constructor(e){void 0!==e&&(this.skyMaterial=e)}},e.MetallicDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.metallic=t)}},e.RoughnessDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.roughness=t)}},e.AlphaDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.alpha=t)}},e.BackFaceCullingDto=class{constructor(e,t){this.backFaceCulling=!0,void 0!==e&&(this.material=e),void 0!==t&&(this.backFaceCulling=t)}},e.BaseTextureDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.baseTexture=t)}},e.SkyMaterialDto=class{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d){this.luminance=1,this.turbidity=10,this.rayleigh=2,this.mieCoefficient=.005,this.mieDirectionalG=.8,this.distance=500,this.inclination=.49,this.azimuth=.25,this.useSunPosition=!1,this.up=[0,1,0],this.dithering=!1,void 0!==e&&(this.luminance=e),void 0!==t&&(this.turbidity=t),void 0!==i&&(this.rayleigh=i),void 0!==r&&(this.mieCoefficient=r),void 0!==s&&(this.mieDirectionalG=s),void 0!==n&&(this.distance=n),void 0!==o&&(this.inclination=o),void 0!==a&&(this.azimuth=a),void 0!==l&&(this.sunPosition=l),void 0!==h&&(this.useSunPosition=h),void 0!==c&&(this.cameraOffset=c),void 0!==u&&(this.up=u),void 0!==d&&(this.dithering=d)}},e.LuminanceDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.luminance=t)}},e.TurbidityDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.turbidity=t)}},e.RayleighDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.rayleigh=t)}},e.MieCoefficientDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.mieCoefficient=t)}},e.MieDirectionalGDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.mieDirectionalG=t)}},e.DistanceDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.distance=t)}},e.InclinationDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.inclination=t)}},e.AzimuthDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.azimuth=t)}},e.SunPositionDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.sunPosition=t)}},e.UseSunPositionDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.useSunPosition=t)}},e.CameraOffsetDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.cameraOffset=t)}},e.UpDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.up=t)}},e.DitheringDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.dithering=t)}}}(FH||(FH={})),function(e){e.ShadowLightDirectionToTargetDto=class{constructor(e,t){void 0!==e&&(this.shadowLight=e),void 0!==t&&(this.target=t)}},e.ShadowLightPositionDto=class{constructor(e,t){void 0!==e&&(this.shadowLight=e),void 0!==t&&(this.position=t)}}}(LH||(LH={})),function(e){let t;!function(e){e.nearest="nearest",e.bilinear="bilinear",e.trilinear="trilinear"}(t=e.samplingModeEnum||(e.samplingModeEnum={})),e.TextureSimpleDto=class{constructor(t,i,r,s,n,o,a,l,h,c){this.name="Custom Texture",this.invertY=!1,this.invertZ=!1,this.wAng=0,this.uScale=1,this.vScale=1,this.uOffset=0,this.vOffset=0,this.samplingMode=e.samplingModeEnum.nearest,void 0!==t&&(this.name=t),void 0!==i&&(this.url=i),void 0!==r&&(this.invertY=r),void 0!==s&&(this.invertZ=s),void 0!==n&&(this.wAng=n),void 0!==o&&(this.uScale=o),void 0!==a&&(this.vScale=a),void 0!==l&&(this.uOffset=l),void 0!==h&&(this.vOffset=h),void 0!==c&&(this.samplingMode=c)}}}(BH||(BH={})),function(e){let t,i,r,s,n,o,a,l,h;!function(e){e.left="left",e.center="center",e.right="right"}(t=e.horizontalAlignmentEnum||(e.horizontalAlignmentEnum={})),function(e){e.top="top",e.center="center",e.bottom="bottom"}(i=e.verticalAlignmentEnum||(e.verticalAlignmentEnum={})),function(e){e.onTextChangedObservable="onTextChangedObservable",e.onBeforeKeyAddObservable="onBeforeKeyAddObservable",e.onTextHighlightObservable="onTextHighlightObservable",e.onTextCopyObservable="onTextCopyObservable",e.onTextCutObservable="onTextCutObservable",e.onTextPasteObservable="onTextPasteObservable"}(r=e.inputTextObservableSelectorEnum||(e.inputTextObservableSelectorEnum={})),function(e){e.onValueChangedObservable="onValueChangedObservable"}(s=e.sliderObservableSelectorEnum||(e.sliderObservableSelectorEnum={})),function(e){e.onValueChangedObservable="onValueChangedObservable"}(n=e.colorPickerObservableSelectorEnum||(e.colorPickerObservableSelectorEnum={})),function(e){e.onTextChangedObservable="onTextChangedObservable"}(o=e.textBlockObservableSelectorEnum||(e.textBlockObservableSelectorEnum={})),function(e){e.onIsCheckedChangedObservable="onIsCheckedChangedObservable"}(a=e.checkboxObservableSelectorEnum||(e.checkboxObservableSelectorEnum={})),function(e){e.onIsCheckedChangedObservable="onIsCheckedChangedObservable"}(l=e.radioButtonObservableSelectorEnum||(e.radioButtonObservableSelectorEnum={})),function(e){e.onFocusObservable="onFocusObservable",e.onBlurObservable="onBlurObservable",e.onAccessibilityTagChangedObservable="onAccessibilityTagChangedObservable",e.onWheelObservable="onWheelObservable",e.onPointerMoveObservable="onPointerMoveObservable",e.onPointerOutObservable="onPointerOutObservable",e.onPointerDownObservable="onPointerDownObservable",e.onPointerUpObservable="onPointerUpObservable",e.onPointerClickObservable="onPointerClickObservable",e.onEnterPressedObservable="onEnterPressedObservable",e.onPointerEnterObservable="onPointerEnterObservable",e.onDirtyObservable="onDirtyObservable",e.onBeforeDrawObservable="onBeforeDrawObservable",e.onAfterDrawObservable="onAfterDrawObservable",e.onDisposeObservable="onDisposeObservable",e.onIsVisibleChangedObservable="onIsVisibleChangedObservable"}(h=e.controlObservableSelectorEnum||(e.controlObservableSelectorEnum={})),e.CreateFullScreenUIDto=class{constructor(e,t,i){this.name="fullscreen",void 0!==e&&(this.name=e),void 0!==t&&(this.foreground=t),void 0!==i&&(this.adaptiveScaling=i)}},e.CreateForMeshDto=class{constructor(e,t,i,r,s,n,o){this.supportPointerMove=!0,this.onlyAlphaTesting=!1,this.invertY=!0,this.sampling=BH.samplingModeEnum.trilinear,void 0!==e&&(this.mesh=e),void 0!==t&&(this.width=t),void 0!==i&&(this.height=i),void 0!==r&&(this.supportPointerMove=r),void 0!==s&&(this.onlyAlphaTesting=s),void 0!==n&&(this.invertY=n),void 0!==o&&(this.sampling=o)}},e.CreateStackPanelDto=class{constructor(e,t,i,r,s,n,o){this.name="stackPanel",this.isVertical=!0,this.spacing=0,this.color="#00000000",this.background="#00000055",void 0!==e&&(this.name=e),void 0!==t&&(this.isVertical=t),void 0!==i&&(this.spacing=i),void 0!==r&&(this.width=r),void 0!==s&&(this.height=s),void 0!==n&&(this.color=n),void 0!==o&&(this.background=o)}},e.SetStackPanelIsVerticalDto=class{constructor(e,t){this.isVertical=!0,void 0!==e&&(this.stackPanel=e),void 0!==t&&(this.isVertical=t)}},e.SetStackPanelSpacingDto=class{constructor(e,t){this.spacing=0,void 0!==e&&(this.stackPanel=e),void 0!==t&&(this.spacing=t)}},e.SetStackPanelWidthDto=class{constructor(e,t){void 0!==e&&(this.stackPanel=e),void 0!==t&&(this.width=t)}},e.SetStackPanelHeightDto=class{constructor(e,t){void 0!==e&&(this.stackPanel=e),void 0!==t&&(this.height=t)}},e.StackPanelDto=class{constructor(e){void 0!==e&&(this.stackPanel=e)}},e.SliderObservableSelectorDto=class{constructor(e){this.selector=e}},e.ColorPickerObservableSelectorDto=class{constructor(e){this.selector=e}},e.InputTextObservableSelectorDto=class{constructor(e){this.selector=e}},e.RadioButtonObservableSelectorDto=class{constructor(e){this.selector=e}},e.CheckboxObservableSelectorDto=class{constructor(e){this.selector=e}},e.ControlObservableSelectorDto=class{constructor(e){this.selector=e}},e.TextBlockObservableSelectorDto=class{constructor(e){this.selector=e}},e.ContainerDto=class{constructor(e){void 0!==e&&(this.container=e)}},e.AddControlsToContainerDto=class{constructor(e,t,i){this.clearControlsFirst=!0,void 0!==e&&(this.container=e),void 0!==t&&(this.controls=t),void 0!==i&&(this.clearControlsFirst=i)}},e.GetControlByNameDto=class{constructor(e,t){this.name="controlName",void 0!==e&&(this.container=e),void 0!==t&&(this.name=t)}},e.SetControlIsVisibleDto=class{constructor(e,t){this.isVisible=!0,void 0!==e&&(this.control=e),void 0!==t&&(this.isVisible=t)}},e.SetControlIsReadonlyDto=class{constructor(e,t){this.isReadOnly=!1,void 0!==e&&(this.control=e),void 0!==t&&(this.isReadOnly=t)}},e.SetControlIsEnabledDto=class{constructor(e,t){this.isEnabled=!0,void 0!==e&&(this.control=e),void 0!==t&&(this.isEnabled=t)}},e.CreateImageDto=class{constructor(e,t,i,r,s){this.name="imageName",this.color="black",void 0!==e&&(this.name=e),void 0!==t&&(this.url=t),void 0!==i&&(this.color=i),void 0!==r&&(this.width=r),void 0!==s&&(this.height=s)}},e.SetImageUrlDto=class{constructor(e,t){void 0!==e&&(this.image=e),void 0!==t&&(this.url=t)}},e.ImageDto=class{constructor(e){void 0!==e&&(this.image=e)}},e.CreateButtonDto=class{constructor(e,t,i,r,s,n,o){this.name="buttonName",this.label="Click me!",this.color="black",this.background="#f0cebb",this.fontSize=24,void 0!==e&&(this.name=e),void 0!==t&&(this.label=t),void 0!==i&&(this.color=i),void 0!==r&&(this.background=r),void 0!==s&&(this.width=s),void 0!==n&&(this.height=n),void 0!==o&&(this.fontSize=o)}},e.SetButtonTextDto=class{constructor(e,t){this.text="Click me!",void 0!==e&&(this.button=e),void 0!==t&&(this.text=t)}},e.ButtonDto=class{constructor(e){void 0!==e&&(this.button=e)}},e.CreateColorPickerDto=class{constructor(e,t,i,r,s,n){this.name="colorPickerName",this.defaultColor="#f0cebb",this.color="#f0cebb",void 0!==e&&(this.name=e),void 0!==this.defaultColor&&(this.defaultColor=t),void 0!==i&&(this.color=i),void 0!==r&&(this.width=r),void 0!==s&&(this.height=s),void 0!==n&&(this.size=n)}},e.SetColorPickerValueDto=class{constructor(e,t){void 0!==e&&(this.colorPicker=e),void 0!==t&&(this.color=t)}},e.SetColorPickerSizeDto=class{constructor(e,t){void 0!==e&&(this.colorPicker=e),void 0!==t&&(this.size=t)}},e.ColorPickerDto=class{constructor(e){void 0!==e&&(this.colorPicker=e)}},e.CreateCheckboxDto=class{constructor(e,t,i,r,s,n,o){this.name="checkboxName",this.isChecked=!1,this.checkSizeRatio=.8,this.color="#f0cebb",this.background="black",void 0!==e&&(this.name=e),void 0!==t&&(this.isChecked=t),void 0!==i&&(this.checkSizeRatio=i),void 0!==r&&(this.color=r),void 0!==s&&(this.background=s),void 0!==n&&(this.width=n),void 0!==o&&(this.height=o)}},e.SetControlFontSizeDto=class{constructor(e,t){this.fontSize=24,void 0!==e&&(this.control=e),void 0!==t&&(this.fontSize=t)}},e.SetControlHeightDto=class{constructor(e,t){void 0!==e&&(this.control=e),void 0!==t&&(this.height=t)}},e.SetControlWidthDto=class{constructor(e,t){void 0!==e&&(this.control=e),void 0!==t&&(this.width=t)}},e.SetControlColorDto=class{constructor(e,t){this.color="#f0cebb",void 0!==e&&(this.control=e),void 0!==t&&(this.color=t)}},e.SetContainerBackgroundDto=class{constructor(e,t){this.background="black",void 0!==e&&(this.container=e),void 0!==t&&(this.background=t)}},e.SetContainerIsReadonlyDto=class{constructor(e,t){this.isReadOnly=!1,void 0!==e&&(this.container=e),void 0!==t&&(this.isReadOnly=t)}},e.SetCheckboxBackgroundDto=class{constructor(e,t){this.background="black",void 0!==e&&(this.checkbox=e),void 0!==t&&(this.background=t)}},e.SetCheckboxCheckSizeRatioDto=class{constructor(e,t){this.checkSizeRatio=.8,void 0!==e&&(this.checkbox=e),void 0!==t&&(this.checkSizeRatio=t)}},e.CheckboxDto=class{constructor(e){void 0!==e&&(this.checkbox=e)}},e.ControlDto=class{constructor(e){void 0!==e&&(this.control=e)}},e.SetCheckboxIsCheckedDto=class{constructor(e,t){this.isChecked=!1,void 0!==e&&(this.checkbox=e),void 0!==t&&(this.isChecked=t)}},e.CreateInputTextDto=class{constructor(e,t,i,r,s){this.name="inputName",this.color="#f0cebb",this.background="black",void 0!==e&&(this.name=e),void 0!==t&&(this.color=t),void 0!==i&&(this.background=i),void 0!==r&&(this.width=r),void 0!==s&&(this.height=s)}},e.SetInputTextBackgroundDto=class{constructor(e,t){this.background="black",void 0!==e&&(this.inputText=e),void 0!==t&&(this.background=t)}},e.SetInputTextTextDto=class{constructor(e,t){void 0!==e&&(this.inputText=e),void 0!==t&&(this.text=t)}},e.SetInputTextPlaceholderDto=class{constructor(e,t){void 0!==e&&(this.inputText=e),void 0!==t&&(this.placeholder=t)}},e.InputTextDto=class{constructor(e){void 0!==e&&(this.inputText=e)}},e.CreateRadioButtonDto=class{constructor(e,t,i,r,s,n,o,a){this.name="radioBtnName",this.isChecked=!1,this.checkSizeRatio=.8,this.color="#f0cebb",this.background="black",void 0!==e&&(this.name=e),void 0!==t&&(this.group=t),void 0!==i&&(this.isChecked=i),void 0!==r&&(this.checkSizeRatio=r),void 0!==s&&(this.color=s),void 0!==n&&(this.background=n),void 0!==o&&(this.width=o),void 0!==a&&(this.height=a)}},e.SetRadioButtonCheckSizeRatioDto=class{constructor(e,t){this.checkSizeRatio=.8,void 0!==e&&(this.radioButton=e),void 0!==t&&(this.checkSizeRatio=t)}},e.SetRadioButtonGroupDto=class{constructor(e,t){void 0!==e&&(this.radioButton=e),void 0!==t&&(this.group=t)}},e.SetRadioButtonBackgroundDto=class{constructor(e,t){this.background="black",void 0!==e&&(this.radioButton=e),void 0!==t&&(this.background=t)}},e.RadioButtonDto=class{constructor(e){void 0!==e&&(this.radioButton=e)}},e.CreateSliderDto=class{constructor(e,t,i,r,s,n,o,a,l,h,c){this.name="sliderName",this.minimum=0,this.maximum=10,this.value=5,this.step=.01,this.isVertical=!1,this.color="#f0cebb",this.background="black",this.displayThumb=!0,void 0!==e&&(this.name=e),void 0!==t&&(this.minimum=t),void 0!==i&&(this.maximum=i),void 0!==r&&(this.value=r),void 0!==s&&(this.step=s),void 0!==n&&(this.isVertical=n),void 0!==o&&(this.color=o),void 0!==a&&(this.background=a),void 0!==l&&(this.width=l),void 0!==h&&(this.height=h),void 0!==c&&(this.displayThumb=c)}},e.CreateTextBlockDto=class{constructor(e,t,i,r,s){this.name="textBlockName",this.text="Hello World!",this.color="#f0cebb",this.fontSize=24,void 0!==e&&(this.name=e),void 0!==t&&(this.text=t),void 0!==i&&(this.color=i),void 0!==r&&(this.width=r),void 0!==s&&(this.height=s)}},e.SetTextBlockTextDto=class{constructor(e,t){void 0!==e&&(this.textBlock=e),void 0!==t&&(this.text=t)}},e.SetTextBlockResizeToFitDto=class{constructor(e,t){this.resizeToFit=!1,void 0!==e&&(this.textBlock=e),void 0!==t&&(this.resizeToFit=t)}},e.SetTextBlockTextWrappingDto=class{constructor(e,t){void 0!==e&&(this.textBlock=e),void 0!==t&&(this.textWrapping=t)}},e.SetTextBlockLineSpacingDto=class{constructor(e,t){void 0!==e&&(this.textBlock=e),void 0!==t&&(this.lineSpacing=t)}},e.TextBlockDto=class{constructor(e){void 0!==e&&(this.textBlock=e)}},e.SliderThumbDto=class{constructor(e,t,i,r,s,n){this.isThumbCircle=!1,this.thumbColor="white",this.isThumbClamped=!1,this.displayThumb=!0,void 0!==e&&(this.slider=e),void 0!==t&&(this.isThumbCircle=t),void 0!==i&&(this.thumbColor=i),void 0!==r&&(this.thumbWidth=r),void 0!==s&&(this.isThumbClamped=s),void 0!==n&&(this.displayThumb=n)}},e.SliderDto=class{constructor(e){void 0!==e&&(this.slider=e)}},e.SliderBorderColorDto=class{constructor(e,t){this.borderColor="white",void 0!==e&&(this.slider=e),void 0!==t&&(this.borderColor=t)}},e.SliderBackgroundColorDto=class{constructor(e,t){this.backgroundColor="black",void 0!==e&&(this.slider=e),void 0!==t&&(this.backgroundColor=t)}},e.SetSliderValueDto=class{constructor(e,t){void 0!==e&&(this.slider=e),void 0!==t&&(this.value=t)}},e.PaddingLeftRightTopBottomDto=class{constructor(e,t,i,r,s){void 0!==e&&(this.control=e),void 0!==t&&(this.paddingLeft=t),void 0!==i&&(this.paddingRight=i),void 0!==r&&(this.paddingTop=r),void 0!==s&&(this.paddingBottom=s)}},e.CloneControlDto=class{constructor(e,t,i,r){this.name="clonedControl",void 0!==e&&(this.control=e),void 0!==t&&(this.container=t),void 0!==i&&(this.name=i),void 0!==r&&(this.host=r)}},e.AlignmentDto=class{constructor(e,t,i){void 0!==e&&(this.control=e),void 0!==t&&(this.horizontalAlignment=t),void 0!==i&&(this.verticalAlignment=i)}},e.SetTextBlockTextOutlineDto=class{constructor(e,t,i){void 0!==e&&(this.textBlock=e),void 0!==t&&(this.outlineWidth=t),void 0!==i&&(this.outlineColor=i)}}}(VH||(VH={})),function(e){e.CreateGaussianSplattingMeshDto=class{constructor(e){void 0!==e&&(this.url=e)}},e.GaussianSplattingMeshDto=class{constructor(e){void 0!==e&&(this.babylonMesh=e)}}}(kH||(kH={})),function(e){let t;!function(e){e.frontside="frontside",e.backside="backside",e.doubleside="doubleside"}(t=e.sideOrientationEnum||(e.sideOrientationEnum={})),e.UpdateDrawnBabylonMesh=class{constructor(e,t,i,r,s){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.position=t),void 0!==i&&(this.rotation=i),void 0!==r&&(this.scaling=r),void 0!==s&&(this.colours=s)}},e.SetParentDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.parentMesh=t)}},e.UpdateDrawnBabylonMeshPositionDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.position=t)}},e.UpdateDrawnBabylonMeshRotationDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.rotation=t)}},e.UpdateDrawnBabylonMeshScaleDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.scale=t)}},e.IntersectsMeshDto=class{constructor(e,t,i,r){this.precise=!1,this.includeDescendants=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.babylonMesh2=t),void 0!==i&&(this.precise=i),void 0!==r&&(this.includeDescendants=r)}},e.IntersectsPointDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.point=t)}},e.BabylonMeshDto=class{constructor(e){void 0!==e&&(this.babylonMesh=e)}},e.CloneToPositionsDto=class{constructor(e,t){this.positions=[],void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.positions=t)}},e.MergeMeshesDto=class{constructor(e,t,i,r,s,n){this.disposeSource=!0,this.allow32BitsIndices=!1,this.subdivideWithSubMeshes=!1,this.multiMultiMaterials=!1,void 0!==e&&(this.arrayOfMeshes=e),void 0!==t&&(this.disposeSource=t),void 0!==i&&(this.allow32BitsIndices=i),void 0!==r&&(this.meshSubclass=r),void 0!==s&&(this.subdivideWithSubMeshes=s),void 0!==n&&(this.multiMultiMaterials=n)}},e.BabylonMeshWithChildrenDto=class{constructor(e){this.includeChildren=!0,void 0!==e&&(this.babylonMesh=e)}},e.ShowHideMeshDto=class{constructor(e,t){this.includeChildren=!0,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.includeChildren=t)}},e.CloneBabylonMeshDto=class{constructor(e){void 0!==e&&(this.babylonMesh=e)}},e.ChildMeshesBabylonMeshDto=class{constructor(e,t){this.directDescendantsOnly=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.directDescendantsOnly=t)}},e.TranslateBabylonMeshDto=class{constructor(e,t){this.distance=0,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.distance=t)}},e.NameBabylonMeshDto=class{constructor(e,t,i){this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.name=t),void 0!==i&&(this.includeChildren=i)}},e.ByNameBabylonMeshDto=class{constructor(e){void 0!==e&&(this.name=e)}},e.MaterialBabylonMeshDto=class{constructor(e,t,i){this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.material=t),void 0!==i&&(this.includeChildren=i)}},e.IdBabylonMeshDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.id=t)}},e.ByIdBabylonMeshDto=class{constructor(e){void 0!==e&&(this.id=e)}},e.UniqueIdBabylonMeshDto=class{constructor(e){void 0!==e&&(this.uniqueId=e)}},e.PickableBabylonMeshDto=class{constructor(e,t,i){this.pickable=!1,this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.pickable=t),void 0!==i&&(this.includeChildren=i)}},e.CheckCollisionsBabylonMeshDto=class{constructor(e,t,i){this.checkCollisions=!1,this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.checkCollisions=t),void 0!==i&&(this.includeChildren=i)}},e.RotateBabylonMeshDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.rotate=t)}},e.SetMeshVisibilityDto=class{constructor(e,t,i){this.visibility=0,this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.visibility=t),void 0!==i&&(this.includeChildren=i)}},e.MeshInstanceAndTransformDto=class{constructor(e,t,i,r){void 0!==e&&(this.mesh=e),void 0!==t&&(this.position=t),void 0!==i&&(this.rotation=i),void 0!==r&&(this.scaling=r)}},e.MeshInstanceDto=class{constructor(e){void 0!==e&&(this.mesh=e)}},e.RotateAroundAxisNodeDto=class{constructor(e,t,i,r){this.position=[0,0,0],this.axis=[0,1,0],this.angle=0,void 0!==e&&(this.mesh=e),void 0!==t&&(this.position=t),void 0!==i&&(this.axis=i),void 0!==r&&(this.angle=r)}}}(UH||(UH={})),function(e){e.RotationCenterAxisDto=class{constructor(e,t,i){this.angle=90,this.axis=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.angle=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.center=i)}},e.TransformBabylonMeshDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.transformation=t)}},e.RotationCenterDto=class{constructor(e,t){this.angle=90,this.center=[0,0,0],void 0!==e&&(this.angle=e),void 0!==t&&(this.center=t)}},e.RotationCenterYawPitchRollDto=class{constructor(e,t,i,r){this.yaw=0,this.pitch=0,this.roll=0,this.center=[0,0,0],void 0!==e&&(this.yaw=e),void 0!==t&&(this.pitch=t),void 0!==i&&(this.roll=i),void 0!==r&&(this.center=r)}},e.ScaleXYZDto=class{constructor(e){this.scaleXyz=[1,1,1],void 0!==e&&(this.scaleXyz=e)}},e.ScaleCenterXYZDto=class{constructor(e,t){this.center=[0,0,0],this.scaleXyz=[1,1,1],void 0!==e&&(this.center=e),void 0!==t&&(this.scaleXyz=t)}},e.UniformScaleDto=class{constructor(e){this.scale=1,void 0!==e&&(this.scale=e)}},e.UniformScaleFromCenterDto=class{constructor(e,t){this.scale=1,this.center=[0,0,0],void 0!==e&&(this.scale=e),void 0!==t&&(this.center=t)}},e.TranslationXYZDto=class{constructor(e){this.translation=[0,0,0],void 0!==e&&(this.translation=e)}},e.TranslationsXYZDto=class{constructor(e){void 0!==e&&(this.translations=e)}}}(GH||(GH={})),function(e){e.RayDto=class{constructor(e){void 0!==e&&(this.ray=e)}},e.PickInfo=class{constructor(e){void 0!==e&&(this.pickInfo=e)}}}(zH||(zH={})),function(e){e.BaseRayDto=class{constructor(e,t,i){void 0!==e&&(this.origin=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.length=i)}},e.RayDto=class{constructor(e){void 0!==e&&(this.ray=e)}},e.FromToDto=class{constructor(e,t){void 0!==e&&(this.from=e),void 0!==t&&(this.to=t)}}}(WH||(WH={})),function(e){e.ScreenshotDto=class{constructor(e,t,i,r,s){this.width=1920,this.height=1080,this.quality=1,void 0!==e&&(this.camera=e),void 0!==r&&(this.mimeType=r),void 0!==s&&(this.quality=s),void 0!==t&&(this.width=t),void 0!==i&&(this.height=i)}}}(HH||(HH={})),function(e){e.CreateBoxDto=class{constructor(e,t,i,r,s){this.width=1,this.depth=1,this.height=1,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.width=e),void 0!==t&&(this.depth=t),void 0!==i&&(this.height=i),void 0!==r&&(this.sideOrientation=r),void 0!==s&&(this.enableShadows=s)}},e.CreateCubeDto=class{constructor(e,t,i){this.size=1,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.size=e),void 0!==t&&(this.sideOrientation=t),void 0!==i&&(this.enableShadows=i)}},e.CreateSquarePlaneDto=class{constructor(e,t,i){this.size=1,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.size=e),void 0!==t&&(this.sideOrientation=t),void 0!==i&&(this.enableShadows=i)}},e.CreateSphereDto=class{constructor(e,t,i,r){this.diameter=1,this.segments=32,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.diameter=e),void 0!==t&&(this.segments=t),void 0!==i&&(this.sideOrientation=i),void 0!==r&&(this.enableShadows=r)}},e.CreateIcoSphereDto=class{constructor(e,t,i,r,s,n,o,a){this.radius=1,this.radiusX=0,this.radiusY=0,this.radiusZ=0,this.flat=!1,this.subdivisions=4,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.radius=e),void 0!==t&&(this.radiusX=t),void 0!==i&&(this.radiusY=i),void 0!==r&&(this.radiusZ=r),void 0!==s&&(this.flat=s),void 0!==n&&(this.subdivisions=n),void 0!==o&&(this.sideOrientation=o),void 0!==a&&(this.enableShadows=a)}},e.CreateDiscDto=class{constructor(e,t,i,r){this.radius=1,this.tessellation=32,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.radius=e),void 0!==t&&(this.tessellation=t),void 0!==i&&(this.sideOrientation=i),void 0!==r&&(this.enableShadows=r)}},e.CreateRibbonDto=class{constructor(e,t,i,r,s,n,o){this.closeArray=!1,this.closePath=!1,this.offset=0,this.updatable=!1,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.pathArray=e),void 0!==t&&(this.closeArray=t),void 0!==i&&(this.closePath=i),void 0!==r&&(this.offset=r),void 0!==s&&(this.updatable=s),void 0!==n&&(this.sideOrientation=n),void 0!==o&&(this.enableShadows=o)}},e.CreateTorusDto=class{constructor(e,t,i,r,s){this.diameter=1,this.thickness=.5,this.tessellation=32,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.diameter=e),void 0!==t&&(this.thickness=t),void 0!==i&&(this.tessellation=i),void 0!==r&&(this.sideOrientation=r),void 0!==s&&(this.enableShadows=s)}},e.CreateTorusKnotDto=class{constructor(e,t,i,r,s,n,o,a){this.radius=2,this.tube=.5,this.radialSegments=128,this.tubularSegments=32,this.p=2,this.q=3,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.radius=e),void 0!==t&&(this.tube=t),void 0!==i&&(this.radialSegments=i),void 0!==r&&(this.tubularSegments=r),void 0!==s&&(this.p=s),void 0!==n&&(this.q=n),void 0!==o&&(this.sideOrientation=o),void 0!==a&&(this.enableShadows=a)}},e.CreatePolygonDto=class{constructor(e,t,i,r,s,n,o){this.depth=0,this.smoothingThreshold=.01,this.sideOrientation=UH.sideOrientationEnum.frontside,this.wrap=!1,this.enableShadows=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.holes=t),void 0!==i&&(this.depth=i),void 0!==r&&(this.smoothingThreshold=r),void 0!==s&&(this.sideOrientation=s),void 0!==n&&(this.wrap=n),void 0!==o&&(this.enableShadows=o)}},e.ExtrudePolygonDto=class{constructor(e,t,i,r,s,n){this.depth=1,this.sideOrientation=UH.sideOrientationEnum.frontside,this.wrap=!1,this.enableShadows=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.holes=t),void 0!==i&&(this.depth=i),void 0!==r&&(this.sideOrientation=r),void 0!==s&&(this.wrap=s),void 0!==n&&(this.enableShadows=n)}},e.CreatePolyhedronDto=class{constructor(e,t,i,r,s,n,o,a,l){this.size=1,this.type=0,this.sizeX=0,this.sizeY=0,this.sizeZ=0,this.flat=!1,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.size=e),void 0!==t&&(this.type=t),void 0!==i&&(this.sizeX=i),void 0!==r&&(this.sizeY=r),void 0!==s&&(this.sizeZ=s),void 0!==n&&(this.custom=n),void 0!==o&&(this.flat=o),void 0!==a&&(this.sideOrientation=a),void 0!==l&&(this.enableShadows=l)}},e.CreateGeodesicDto=class{constructor(e,t,i,r,s,n,o,a,l,h){this.m=4,this.n=4,this.size=1,this.sizeX=0,this.sizeY=0,this.sizeZ=0,this.flat=!1,this.subdivisions=4,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.m=e),void 0!==t&&(this.n=t),void 0!==i&&(this.size=i),void 0!==r&&(this.sizeX=r),void 0!==s&&(this.sizeY=s),void 0!==n&&(this.sizeZ=n),void 0!==o&&(this.flat=o),void 0!==a&&(this.subdivisions=a),void 0!==l&&(this.sideOrientation=l),void 0!==h&&(this.enableShadows=h)}},e.CreateCapsuleDto=class{constructor(e,t,i,r,s,n,o,a,l,h,c,u){this.subdivisions=2,this.tessellation=16,this.height=2,this.radius=1,this.capSubdivisions=6,this.radiusTop=.5,this.radiusBottom=.5,this.topCapSubdivisions=6,this.bottomCapSubdivisions=6,this.sideOrientation=UH.sideOrientationEnum.doubleside,this.enableShadows=!0,void 0!==e&&(this.orientation=e),void 0!==t&&(this.subdivisions=t),void 0!==i&&(this.tessellation=i),void 0!==r&&(this.height=r),void 0!==s&&(this.radius=s),void 0!==n&&(this.capSubdivisions=n),void 0!==o&&(this.radiusTop=o),void 0!==a&&(this.radiusBottom=a),void 0!==l&&(this.topCapSubdivisions=l),void 0!==h&&(this.bottomCapSubdivisions=h),void 0!==c&&(this.sideOrientation=c),void 0!==u&&(this.enableShadows=u)}},e.CreateGoldbergDto=class{constructor(e,t,i,r,s,n,o,a){this.m=4,this.n=4,this.size=1,this.sizeX=0,this.sizeY=0,this.sizeZ=0,this.sideOrientation=UH.sideOrientationEnum.doubleside,this.enableShadows=!0,void 0!==e&&(this.m=e),void 0!==t&&(this.n=t),void 0!==i&&(this.size=i),void 0!==r&&(this.sizeX=r),void 0!==s&&(this.sizeY=s),void 0!==n&&(this.sizeZ=n),void 0!==o&&(this.sideOrientation=o),void 0!==a&&(this.enableShadows=a)}},e.CreateTubeDto=class{constructor(e,t,i,r,s,n,o){this.radius=1,this.tessellation=32,this.cap=0,this.arc=1,this.sideOrientation=UH.sideOrientationEnum.doubleside,this.enableShadows=!0,void 0!==e&&(this.path=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.tessellation=i),void 0!==r&&(this.cap=r),void 0!==s&&(this.arc=s),void 0!==n&&(this.sideOrientation=n),void 0!==o&&(this.enableShadows=o)}},e.CreateExtrudedShapeDto=class{constructor(e,t,i,r,s,n,o){this.scale=1,this.rotation=0,this.closeShape=!1,this.closePath=!1,this.cap=0,this.sideOrientation=UH.sideOrientationEnum.doubleside,this.enableShadows=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.path=t),void 0!==i&&(this.scale=i),void 0!==r&&(this.rotation=r),void 0!==s&&(this.cap=s),void 0!==n&&(this.sideOrientation=n),void 0!==o&&(this.enableShadows=o)}},e.CreateCylinderDto=class{constructor(e,t,i,r,s,n,o){this.height=1,this.diameterTop=1,this.diameterBottom=1,this.tessellation=64,this.subdivisions=1,this.sideOrientation=UH.sideOrientationEnum.doubleside,this.enableShadows=!0,void 0!==e&&(this.height=e),void 0!==t&&(this.diameterTop=t),void 0!==i&&(this.diameterBottom=i),void 0!==r&&(this.tessellation=r),void 0!==s&&(this.subdivisions=s),void 0!==n&&(this.sideOrientation=n),void 0!==o&&(this.enableShadows=o)}},e.CreateLatheDto=class{constructor(e,t,i,r,s,n,o){this.radius=1,this.tessellation=64,this.arc=1,this.closed=!0,this.sideOrientation=UH.sideOrientationEnum.doubleside,this.enableShadows=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.tessellation=i),void 0!==r&&(this.arc=r),void 0!==s&&(this.closed=s),void 0!==n&&(this.sideOrientation=n),void 0!==o&&(this.enableShadows=o)}},e.CreateGroundDto=class{constructor(e,t,i,r,s,n){this.width=10,this.height=10,this.subdivisionsX=1,this.subdivisionsY=1,this.sideOrientation=UH.sideOrientationEnum.doubleside,this.enableShadows=!0,void 0!==e&&(this.width=e),void 0!==t&&(this.height=t),void 0!==i&&(this.subdivisionsX=i),void 0!==r&&(this.subdivisionsY=r),void 0!==s&&(this.sideOrientation=s),void 0!==n&&(this.enableShadows=n)}},e.CreateRectanglePlaneDto=class{constructor(e,t,i,r){this.width=1,this.height=1,this.sideOrientation=UH.sideOrientationEnum.doubleside,this.enableShadows=!0,void 0!==e&&(this.width=e),void 0!==t&&(this.height=t),void 0!==i&&(this.sideOrientation=i),void 0!==r&&(this.enableShadows=r)}}}(XH||(XH={})),function(e){let t,i,r,s;!function(e){e.onDragStartObservable="onDragStartObservable",e.onDragObservable="onDragObservable",e.onDragEndObservable="onDragEndObservable"}(t=e.positionGizmoObservableSelectorEnum||(e.positionGizmoObservableSelectorEnum={})),function(e){e.onDragStartObservable="onDragStartObservable",e.onDragObservable="onDragObservable",e.onDragEndObservable="onDragEndObservable"}(i=e.rotationGizmoObservableSelectorEnum||(e.rotationGizmoObservableSelectorEnum={})),function(e){e.onDragStartObservable="onDragStartObservable",e.onDragObservable="onDragObservable",e.onDragEndObservable="onDragEndObservable"}(r=e.scaleGizmoObservableSelectorEnum||(e.scaleGizmoObservableSelectorEnum={})),function(e){e.onDragStartObservable="onDragStartObservable",e.onScaleBoxDragObservable="onScaleBoxDragObservable",e.onScaleBoxDragEndObservable="onScaleBoxDragEndObservable",e.onRotationSphereDragObservable="onRotationSphereDragObservable",e.onRotationSphereDragEndObservable="onRotationSphereDragEndObservable"}(s=e.boundingBoxGizmoObservableSelectorEnum||(e.boundingBoxGizmoObservableSelectorEnum={})),e.CreateGizmoDto=class{constructor(e,t,i,r,s,n,o,a){this.usePointerToAttachGizmos=!0,this.clearGizmoOnEmptyPointerEvent=!1,this.scaleRatio=1,void 0!==e&&(this.positionGizmoEnabled=e),void 0!==t&&(this.rotationGizmoEnabled=t),void 0!==i&&(this.scaleGizmoEnabled=i),void 0!==r&&(this.boundingBoxGizmoEnabled=r),void 0!==n&&(this.clearGizmoOnEmptyPointerEvent=n),void 0!==o&&(this.scaleRatio=o),void 0!==a&&(this.usePointerToAttachGizmos=a),void 0!==s&&(this.attachableMeshes=s)}},e.GizmoDto=class{constructor(e){void 0!==e&&(this.gizmo=e)}},e.SetGizmoScaleRatioDto=class{constructor(e,t){this.scaleRatio=1,void 0!==e&&(this.gizmo=e),void 0!==t&&(this.scaleRatio=t)}},e.GizmoManagerDto=class{constructor(e){void 0!==e&&(this.gizmoManager=e)}},e.PositionGizmoDto=class{constructor(e){void 0!==e&&(this.positionGizmo=e)}},e.SetPlanarGizmoEnabled=class{constructor(e,t){this.planarGizmoEnabled=!0,void 0!==e&&(this.positionGizmo=e),void 0!==t&&(this.planarGizmoEnabled=t)}},e.SetScaleGizmoSnapDistanceDto=class{constructor(e,t){this.snapDistance=0,void 0!==e&&(this.scaleGizmo=e),void 0!==t&&(this.snapDistance=t)}},e.SetScaleGizmoIncrementalSnapDto=class{constructor(e,t){this.incrementalSnap=!1,void 0!==e&&(this.scaleGizmo=e),void 0!==t&&(this.incrementalSnap=t)}},e.SetScaleGizmoSensitivityDto=class{constructor(e,t){this.sensitivity=1,void 0!==e&&(this.scaleGizmo=e),void 0!==t&&(this.sensitivity=t)}},e.ScaleGizmoDto=class{constructor(e){void 0!==e&&(this.scaleGizmo=e)}},e.BoundingBoxGizmoDto=class{constructor(e){void 0!==e&&(this.boundingBoxGizmo=e)}},e.SetBoundingBoxGizmoRotationSphereSizeDto=class{constructor(e,t){this.rotationSphereSize=.1,void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.rotationSphereSize=t)}},e.SetBoundingBoxGizmoFixedDragMeshScreenSizeDto=class{constructor(e,t){this.fixedDragMeshScreenSize=!1,void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.fixedDragMeshScreenSize=t)}},e.SetBoundingBoxGizmoFixedDragMeshBoundsSizeDto=class{constructor(e,t){this.fixedDragMeshBoundsSize=!1,void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.fixedDragMeshBoundsSize=t)}},e.SetBoundingBoxGizmoFixedDragMeshScreenSizeDistanceFactorDto=class{constructor(e,t){this.fixedDragMeshScreenSizeDistanceFactor=10,void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.fixedDragMeshScreenSizeDistanceFactor=t)}},e.SetBoundingBoxGizmoScalingSnapDistanceDto=class{constructor(e,t){this.scalingSnapDistance=0,void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.scalingSnapDistance=t)}},e.SetBoundingBoxGizmoRotationSnapDistanceDto=class{constructor(e,t){this.rotationSnapDistance=0,void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.rotationSnapDistance=t)}},e.SetBoundingBoxGizmoScaleBoxSizeDto=class{constructor(e,t){this.scaleBoxSize=.1,void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.scaleBoxSize=t)}},e.SetBoundingBoxGizmoIncrementalSnapDto=class{constructor(e,t){this.incrementalSnap=!1,void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.incrementalSnap=t)}},e.SetBoundingBoxGizmoScalePivotDto=class{constructor(e,t){void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.scalePivot=t)}},e.SetBoundingBoxGizmoAxisFactorDto=class{constructor(e,t){void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.axisFactor=t)}},e.SetBoundingBoxGizmoScaleDragSpeedDto=class{constructor(e,t){this.scaleDragSpeed=1,void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.scaleDragSpeed=t)}},e.SetPositionGizmoSnapDistanceDto=class{constructor(e,t){this.snapDistance=0,void 0!==e&&(this.positionGizmo=e),void 0!==t&&(this.snapDistance=t)}},e.SetRotationGizmoSnapDistanceDto=class{constructor(e,t){this.snapDistance=0,void 0!==e&&(this.rotationGizmo=e),void 0!==t&&(this.snapDistance=t)}},e.SetRotationGizmoSensitivityDto=class{constructor(e,t){this.sensitivity=1,void 0!==e&&(this.rotationGizmo=e),void 0!==t&&(this.sensitivity=t)}},e.RotationGizmoDto=class{constructor(e){void 0!==e&&(this.rotationGizmo=e)}},e.AxisScaleGizmoDto=class{constructor(e){void 0!==e&&(this.axisScaleGizmo=e)}},e.SetIsEnabledAxisScaleGizmoDto=class{constructor(e,t){this.isEnabled=!0,void 0!==e&&(this.axisScaleGizmo=e),void 0!==t&&(this.isEnabled=t)}},e.AxisDragGizmoDto=class{constructor(e){void 0!==e&&(this.axisDragGizmo=e)}},e.SetIsEnabledAxisDragGizmoDto=class{constructor(e,t){this.isEnabled=!0,void 0!==e&&(this.axisDragGizmo=e),void 0!==t&&(this.isEnabled=t)}},e.SetIsEnabledPlaneRotationGizmoDto=class{constructor(e,t){this.isEnabled=!0,void 0!==e&&(this.planeRotationGizmo=e),void 0!==t&&(this.isEnabled=t)}},e.SetIsEnabledPlaneDragGizmoDto=class{constructor(e,t){this.isEnabled=!0,void 0!==e&&(this.planeDragGizmo=e),void 0!==t&&(this.isEnabled=t)}},e.PlaneDragGizmoDto=class{constructor(e){void 0!==e&&(this.planeDragGizmo=e)}},e.PlaneRotationGizmoDto=class{constructor(e){void 0!==e&&(this.planeRotationGizmo=e)}},e.AttachToMeshDto=class{constructor(e,t){this.mesh=e,this.gizmoManager=t}},e.PositionGizmoObservableSelectorDto=class{constructor(e){this.selector=e}},e.BoundingBoxGizmoObservableSelectorDto=class{constructor(e){this.selector=e}},e.RotationGizmoObservableSelectorDto=class{constructor(e){this.selector=e}},e.ScaleGizmoObservableSelectorDto=class{constructor(e){this.selector=e}}}(qH||(qH={})),function(e){e.WebXRDefaultExperienceOptions=class{constructor(e){void 0!==e&&(this.disableDefaultUI=e)}},e.DefaultWebXRWithTeleportationDto=class{constructor(e){void 0!==e&&(this.groundMeshes=e)}},e.WebXRDefaultExperienceDto=class{constructor(e){void 0!==e&&(this.webXRDefaultExperience=e)}},e.WebXRExperienceHelperDto=class{constructor(e){void 0!==e&&(this.baseExperience=e)}}}(YH||(YH={})),function(e){let t,i;!function(e){e.default="default",e.clearSky="clearSky",e.city="city",e.greyGradient="greyGradient"}(t=e.skyboxEnum||(e.skyboxEnum={})),function(e){e.none="none",e.exponential="exponential",e.exponentialSquared="exponentialSquared",e.linear="linear"}(i=e.fogModeEnum||(e.fogModeEnum={}))}(KH||(KH={})),function(e){e.SceneBackgroundColourDto=class{constructor(e){this.colour="#ffffff",void 0!==e&&(this.colour=e)}},e.SceneDto=class{constructor(e){void 0!==e&&(this.scene=e)}},e.EnablePhysicsDto=class{constructor(e){this.vector=[0,-9.81,0],void 0!==e&&(this.vector=e)}},e.PointLightDto=class{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f){this.position=[0,0,0],this.intensity=2e3,this.diffuse="#ffffff",this.specular="#ffffff",this.radius=.1,this.shadowGeneratorMapSize=1024,this.enableShadows=!0,this.shadowDarkness=0,this.shadowUsePercentageCloserFiltering=!0,this.shadowContactHardeningLightSizeUVRatio=.2,this.shadowBias=1e-4,this.shadowNormalBias=.002,this.shadowMaxZ=1e3,this.shadowMinZ=0,void 0!==e&&(this.position=e),void 0!==t&&(this.intensity=t),void 0!==i&&(this.diffuse=i),void 0!==r&&(this.specular=r),void 0!==s&&(this.radius=s),void 0!==n&&(this.shadowGeneratorMapSize=n),void 0!==o&&(this.enableShadows=o),void 0!==a&&(this.shadowDarkness=a),void 0!==l&&(this.shadowUsePercentageCloserFiltering=l),void 0!==h&&(this.shadowContactHardeningLightSizeUVRatio=h),void 0!==c&&(this.shadowBias=c),void 0!==u&&(this.shadowNormalBias=u),void 0!==d&&(this.shadowMaxZ=d),void 0!==f&&(this.shadowMinZ=f)}},e.ActiveCameraDto=class{constructor(e){void 0!==e&&(this.camera=e)}},e.UseRightHandedSystemDto=class{constructor(e){this.use=!0,void 0!==e&&(this.use=e)}},e.DirectionalLightDto=class{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d){this.direction=[-100,-100,-100],this.intensity=.5,this.diffuse="#ffffff",this.specular="#ffffff",this.shadowGeneratorMapSize=1024,this.enableShadows=!0,this.shadowDarkness=0,this.shadowUsePercentageCloserFiltering=!0,this.shadowContactHardeningLightSizeUVRatio=.2,this.shadowBias=1e-4,this.shadowNormalBias=.002,this.shadowMaxZ=1e3,this.shadowMinZ=0,void 0!==e&&(this.direction=e),void 0!==t&&(this.intensity=t),void 0!==i&&(this.diffuse=i),void 0!==r&&(this.specular=r),void 0!==s&&(this.shadowGeneratorMapSize=s),void 0!==n&&(this.enableShadows=n),void 0!==o&&(this.shadowDarkness=o),void 0!==a&&(this.shadowUsePercentageCloserFiltering=a),void 0!==l&&(this.shadowContactHardeningLightSizeUVRatio=l),void 0!==h&&(this.shadowBias=h),void 0!==c&&(this.shadowNormalBias=c),void 0!==u&&(this.shadowMaxZ=u),void 0!==d&&(this.shadowMinZ=d)}},e.CameraConfigurationDto=class{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d){this.position=[10,10,10],this.lookAt=[0,0,0],this.lowerBetaLimit=1,this.upperBetaLimit=179,this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.maxZ=1e3,this.panningSensibility=1e3,this.wheelPrecision=3,void 0!==e&&(this.position=e),void 0!==t&&(this.lookAt=t),void 0!==i&&(this.lowerRadiusLimit=i),void 0!==r&&(this.upperRadiusLimit=r),void 0!==s&&(this.lowerAlphaLimit=s),void 0!==n&&(this.upperAlphaLimit=n),void 0!==o&&(this.lowerBetaLimit=o),void 0!==a&&(this.upperBetaLimit=a),void 0!==l&&(this.angularSensibilityX=l),void 0!==h&&(this.angularSensibilityY=h),void 0!==c&&(this.maxZ=c),void 0!==u&&(this.panningSensibility=u),void 0!==d&&(this.wheelPrecision=d)}},e.SkyboxDto=class{constructor(e,t,i,r){this.skybox=KH.skyboxEnum.clearSky,this.size=1e3,this.blur=.1,this.environmentIntensity=.7,void 0!==e&&(this.skybox=e),void 0!==t&&(this.size=t),void 0!==i&&(this.blur=i),void 0!==r&&(this.environmentIntensity=r)}},e.PointerDto=class{},e.FogDto=class{constructor(e,t,i,r,s){this.color="#ffffff",this.density=.1,void 0!==e&&(this.mode=e),void 0!==t&&(this.color=t),void 0!==i&&(this.density=i),void 0!==r&&(this.start=r),void 0!==s&&(this.end=s)}}}(jH||(jH={})),function(e){e.NodeDto=class{constructor(e){void 0!==e&&(this.node=e)}},e.NodeTranslationDto=class{constructor(e,t,i){void 0!==e&&(this.node=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.distance=i)}},e.NodeParentDto=class{constructor(e,t){void 0!==e&&(this.node=e),void 0!==t&&(this.parentNode=t)}},e.NodeDirectionDto=class{constructor(e,t){void 0!==e&&(this.node=e),void 0!==t&&(this.direction=t)}},e.NodePositionDto=class{constructor(e,t){void 0!==e&&(this.node=e),void 0!==t&&(this.position=t)}},e.RotateNodeDto=class{constructor(e,t,i){this.axis=[0,1,0],this.angle=0,void 0!==e&&(this.node=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.angle=i)}},e.RotateAroundAxisNodeDto=class{constructor(e,t,i,r){this.position=[0,0,0],this.axis=[0,1,0],this.angle=0,void 0!==e&&(this.node=e),void 0!==t&&(this.position=t),void 0!==i&&(this.axis=i),void 0!==r&&(this.angle=r)}},e.CreateNodeFromRotationDto=class{constructor(e,t,i){this.origin=[0,0,0],this.rotation=[0,0,0],void 0!==e&&(this.parent=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.rotation=i)}},e.DrawNodeDto=class{constructor(e,t,i,r,s){this.colorX="#ff0000",this.colorY="#00ff00",this.colorZ="#0000ff",this.size=2,void 0!==e&&(this.node=e),void 0!==t&&(this.colorX=t),void 0!==i&&(this.colorY=i),void 0!==r&&(this.colorZ=r),void 0!==s&&(this.size=s)}},e.DrawNodesDto=class{constructor(e,t,i,r,s){this.colorX="#ff0000",this.colorY="#00ff00",this.colorZ="#0000ff",this.size=2,void 0!==e&&(this.nodes=e),void 0!==t&&(this.colorX=t),void 0!==i&&(this.colorY=i),void 0!==r&&(this.colorZ=r),void 0!==s&&(this.size=s)}}}($H||($H={})),function(e){let t;e.DrawAny=class{constructor(e,t,i){void 0!==e&&(this.entity=e),void 0!==t&&(this.options=t),void 0!==i&&(this.babylonMesh=i)}},e.SceneDrawGridMeshDto=class{constructor(e,t,i,r,s,n,o,a,l,h){this.width=400,this.height=400,this.subdivisions=10,this.majorUnitFrequency=10,this.minorUnitVisibility=.45,this.gridRatio=.5,this.opacity=.5,this.backFaceCulling=!1,this.mainColor="#ffffff",this.secondaryColor="#ffffff",void 0!==e&&(this.width=e),void 0!==t&&(this.height=t),void 0!==i&&(this.subdivisions=i),void 0!==r&&(this.majorUnitFrequency=r),void 0!==s&&(this.minorUnitVisibility=s),void 0!==n&&(this.gridRatio=n),void 0!==o&&(this.opacity=o),void 0!==a&&(this.backFaceCulling=a),void 0!==l&&(this.mainColor=l),void 0!==h&&(this.secondaryColor=h)}},e.DrawBasicGeometryOptions=class{constructor(e,t,i,r,s){this.colours="#ff0000",this.size=.1,this.opacity=1,this.updatable=!1,this.hidden=!1,void 0!==e&&(this.colours=e),void 0!==t&&(this.size=t),void 0!==i&&(this.opacity=i),void 0!==r&&(this.updatable=r),void 0!==s&&(this.hidden=s)}},e.DrawNodeOptions=class{constructor(e,t,i,r){this.colorX="#0000ff",this.colorY="#00ff00",this.colorZ="#ff0000",this.size=2,void 0!==e&&(this.colorX=e),void 0!==t&&(this.colorY=t),void 0!==i&&(this.colorZ=i),void 0!==r&&(this.size=r)}},e.DrawManifoldOrCrossSectionOptions=class{constructor(e,t,i,r,s,n,o){this.faceOpacity=1,this.faceColour="#ff0000",this.crossSectionColour="#ff00ff",this.crossSectionWidth=2,this.computeNormals=!1,void 0!==e&&(this.faceOpacity=e),void 0!==t&&(this.faceMaterial=t),void 0!==i&&(this.faceColour=i),void 0!==r&&(this.crossSectionColour=r),void 0!==s&&(this.crossSectionWidth=s),void 0!==n&&(this.crossSectionOpacity=n),void 0!==o&&(this.computeNormals=o)}},e.DrawOcctShapeOptions=class{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m,g){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.vertexColour="#ffaaff",this.edgeWidth=2,this.vertexSize=.03,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.faceOpacity=e),void 0!==t&&(this.edgeOpacity=t),void 0!==i&&(this.edgeColour=i),void 0!==r&&(this.faceMaterial=r),void 0!==s&&(this.faceColour=s),void 0!==h&&(this.vertexColour=h),void 0!==c&&(this.vertexSize=c),void 0!==n&&(this.edgeWidth=n),void 0!==o&&(this.drawEdges=o),void 0!==a&&(this.drawFaces=a),void 0!==l&&(this.drawVertices=l),void 0!==u&&(this.precision=u),void 0!==d&&(this.drawEdgeIndexes=d),void 0!==f&&(this.edgeIndexHeight=f),void 0!==p&&(this.edgeIndexColour=p),void 0!==_&&(this.drawFaceIndexes=_),void 0!==m&&(this.faceIndexHeight=m),void 0!==g&&(this.faceIndexColour=g)}},e.DrawOcctShapeSimpleOptions=class{constructor(e,t,i,r,s,n){this.precision=.01,this.drawFaces=!0,this.faceColour="#ff0000",this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=2,void 0!==e&&(this.precision=e),void 0!==t&&(this.drawFaces=t),void 0!==i&&(this.faceColour=i),void 0!==r&&(this.drawEdges=r),void 0!==s&&(this.edgeColour=s),void 0!==n&&(this.edgeWidth=n)}},e.DrawOcctShapeMaterialOptions=class{constructor(e,t,i,r,s){this.precision=.01,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=2,void 0!==e&&(this.precision=e),void 0!==t&&(this.faceMaterial=t),void 0!==i&&(this.drawEdges=i),void 0!==r&&(this.edgeColour=r),void 0!==s&&(this.edgeWidth=s)}},function(e){e[e.point=0]="point",e[e.points=1]="points",e[e.line=2]="line",e[e.lines=3]="lines",e[e.node=4]="node",e[e.nodes=5]="nodes",e[e.polyline=6]="polyline",e[e.polylines=7]="polylines",e[e.verbCurve=8]="verbCurve",e[e.verbCurves=9]="verbCurves",e[e.verbSurface=10]="verbSurface",e[e.verbSurfaces=11]="verbSurfaces",e[e.jscadMesh=12]="jscadMesh",e[e.jscadMeshes=13]="jscadMeshes",e[e.occt=14]="occt",e[e.manifold=15]="manifold",e[e.tag=16]="tag",e[e.tags=17]="tags"}(t=e.drawingTypes||(e.drawingTypes={}))}(QH||(QH={})),function(e){e.GetAssetDto=class{constructor(e){void 0!==e&&(this.fileName=e)}},e.FetchDto=class{constructor(e){void 0!==e&&(this.url=e)}},e.FileDto=class{constructor(e){void 0!==e&&(this.file=e)}},e.FilesDto=class{constructor(e){void 0!==e&&(this.files=e)}},e.AssetFileDto=class{constructor(e,t){this.hidden=!1,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.hidden=t)}},e.AssetFileByUrlDto=class{constructor(e,t,i){this.hidden=!1,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.rootUrl=t),void 0!==i&&(this.hidden=i)}}}(ZH||(ZH={})),function(e){e.StringifyDto=class{constructor(e){void 0!==e&&(this.json=e)}},e.ParseDto=class{constructor(e){this.text="[0, 0, 0]",void 0!==e&&(this.text=e)}},e.QueryDto=class{constructor(e,t){void 0!==e&&(this.json=e),void 0!==t&&(this.query=t)}},e.SetValueOnPropDto=class{constructor(e,t,i){this.property="propName",void 0!==e&&(this.json=e),void 0!==t&&(this.value=t),void 0!==i&&(this.property=i)}},e.GetJsonFromArrayByFirstPropMatchDto=class{constructor(e,t,i){this.property="propName",void 0!==e&&(this.jsonArray=e),void 0!==t&&(this.property=t),void 0!==i&&(this.match=i)}},e.GetValueOnPropDto=class{constructor(e,t){this.property="propName",void 0!==e&&(this.json=e),void 0!==t&&(this.property=t)}},e.SetValueDto=class{constructor(e,t,i,r){this.path="$.pathToParent",this.prop="propertyName",void 0!==e&&(this.json=e),void 0!==t&&(this.value=t),void 0!==i&&(this.path=i),void 0!==r&&(this.prop=r)}},e.SetValuesOnPathsDto=class{constructor(e,t,i,r){void 0!==e&&(this.json=e),void 0!==t&&(this.values=t),void 0!==i&&(this.paths=i),void 0!==r&&(this.props=r)}},e.PathsDto=class{constructor(e,t){void 0!==e&&(this.json=e),void 0!==t&&(this.query=t)}},e.JsonDto=class{constructor(e){void 0!==e&&(this.json=e)}}}(JH||(JH={})),function(e){e.LinePointsDto=class{constructor(e,t){void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.LineStartEndPointsDto=class{constructor(e,t){void 0!==e&&(this.startPoints=e),void 0!==t&&(this.endPoints=t)}},e.DrawLineDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.line=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==r&&(this.size=r),void 0!==s&&(this.updatable=s),void 0!==n&&(this.lineMesh=n)}},e.DrawLinesDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.lines=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==r&&(this.size=r),void 0!==s&&(this.updatable=s),void 0!==n&&(this.linesMesh=n)}},e.PointsLinesDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.LineDto=class{constructor(e){void 0!==e&&(this.line=e)}},e.LinesDto=class{constructor(e){void 0!==e&&(this.lines=e)}},e.PointOnLineDto=class{constructor(e,t){void 0!==e&&(this.line=e),void 0!==t&&(this.param=t)}},e.TransformLineDto=class{constructor(e,t){void 0!==e&&(this.line=e),void 0!==t&&(this.transformation=t)}},e.TransformsLinesDto=class{constructor(e,t){void 0!==e&&(this.lines=e),void 0!==t&&(this.transformation=t)}},e.TransformLinesDto=class{constructor(e,t){void 0!==e&&(this.lines=e),void 0!==t&&(this.transformation=t)}}}(eX||(eX={})),function(e){e.PolylinePropertiesDto=class{constructor(e,t){this.isClosed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.isClosed=t)}},e.PolylineDto=class{constructor(e){void 0!==e&&(this.polyline=e)}},e.PolylinesDto=class{constructor(e){void 0!==e&&(this.polylines=e)}},e.TransformPolylineDto=class{constructor(e,t){void 0!==e&&(this.polyline=e),void 0!==t&&(this.transformation=t)}},e.DrawPolylineDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.polyline=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==r&&(this.size=r),void 0!==s&&(this.updatable=s),void 0!==n&&(this.polylineMesh=n)}},e.DrawPolylinesDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.polylines=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==r&&(this.size=r),void 0!==s&&(this.updatable=s),void 0!==n&&(this.polylinesMesh=n)}}}(tX||(tX={})),function(e){e.DrawTagDto=class{constructor(e,t,i){this.updatable=!1,void 0!==e&&(this.tag=e),void 0!==t&&(this.updatable=t),void 0!==i&&(this.tagVariable=i)}},e.DrawTagsDto=class{constructor(e,t,i){this.updatable=!1,void 0!==e&&(this.tags=e),void 0!==t&&(this.updatable=t),void 0!==i&&(this.tagsVariable=i)}},e.TagDto=class{constructor(e,t,i,r,s,n,o){this.position=[0,0,0],this.colour="#444444",this.size=12,this.adaptDepth=!1,void 0!==e&&(this.text=e),void 0!==t&&(this.position=t),void 0!==i&&(this.colour=i),void 0!==r&&(this.size=r),void 0!==s&&(this.adaptDepth=s),void 0!==n&&(this.needsUpdate=n),void 0!==o&&(this.id=o)}}}(iX||(iX={})),function(e){e.PostFromIframe=class{constructor(e,t){void 0!==e&&(this.data=e),void 0!==t&&(this.targetOrigin=t)}}}(rX||(rX={})),function(e){e.CurveDto=class{constructor(e){void 0!==e&&(this.curve=e)}},e.CurvesDto=class{constructor(e){void 0!==e&&(this.curves=e)}},e.ClosestPointDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.point=t)}},e.ClosestPointsDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.points=t)}},e.BezierCurveDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.weights=t)}},e.DrawCurveDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.curve=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==r&&(this.size=r),void 0!==s&&(this.updatable=s),void 0!==n&&(this.curveMesh=n)}},e.CurveParameterDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.parameter=t)}},e.CurvesParameterDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.parameter=t)}},e.CurveTransformDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.transformation=t)}},e.CurvesTransformDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.transformation=t)}},e.CurveToleranceDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.tolerance=t)}},e.CurveLengthToleranceDto=class{constructor(e,t,i){void 0!==e&&(this.curve=e),void 0!==t&&(this.length=t),void 0!==i&&(this.tolerance=i)}},e.CurveDerivativesDto=class{constructor(e,t,i){void 0!==e&&(this.curve=e),void 0!==t&&(this.parameter=t),void 0!==i&&(this.numDerivatives=i)}},e.CurveSubdivisionsDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.subdivision=t)}},e.CurvesSubdivisionsDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.subdivision=t)}},e.CurvesDivideLengthDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.length=t)}},e.CurveDivideLengthDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.length=t)}},e.DrawCurvesDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.curves=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==r&&(this.size=r),void 0!==s&&(this.updatable=s),void 0!==n&&(this.curvesMesh=n)}},e.CurveNurbsDataDto=class{constructor(e,t,i,r){void 0!==e&&(this.degree=e),void 0!==t&&(this.weights=t),void 0!==i&&(this.knots=i),void 0!==r&&(this.points=r)}},e.CurvePathDataDto=class{constructor(e,t){void 0!==e&&(this.degree=e),void 0!==t&&(this.points=t)}},e.EllipseDto=class{constructor(e){void 0!==e&&(this.ellipse=e)}},e.CircleDto=class{constructor(e){void 0!==e&&(this.circle=e)}},e.ArcDto=class{constructor(e){void 0!==e&&(this.arc=e)}},e.EllipseParametersDto=class{constructor(e,t,i){void 0!==e&&(this.xAxis=e),void 0!==t&&(this.yAxis=t),void 0!==i&&(this.center=i)}},e.CircleParametersDto=class{constructor(e,t,i,r){void 0!==e&&(this.xAxis=e),void 0!==t&&(this.yAxis=t),void 0!==i&&(this.radius=i),void 0!==r&&(this.center=r)}},e.ArcParametersDto=class{constructor(e,t,i,r,s,n){void 0!==e&&(this.minAngle=e),void 0!==t&&(this.maxAngle=t),void 0!==i&&(this.xAxis=i),void 0!==r&&(this.yAxis=r),void 0!==s&&(this.radius=s),void 0!==n&&(this.center=n)}},e.EllipseArcParametersDto=class{constructor(e,t,i,r,s){void 0!==e&&(this.minAngle=e),void 0!==t&&(this.maxAngle=t),void 0!==i&&(this.xAxis=i),void 0!==r&&(this.yAxis=r),void 0!==s&&(this.center=s)}},e.SurfaceDto=class{constructor(e){void 0!==e&&(this.surface=e)}},e.SurfaceTransformDto=class{constructor(e,t){void 0!==e&&(this.surface=e),void 0!==t&&(this.transformation=t)}},e.SurfaceParameterDto=class{constructor(e,t,i){void 0!==e&&(this.surface=e),void 0!==t&&(this.parameter=t),void 0!==i&&(this.useV=i)}},e.IsocurvesParametersDto=class{constructor(e,t,i){void 0!==e&&(this.surface=e),void 0!==t&&(this.parameters=t),void 0!==i&&(this.useV=i)}},e.IsocurveSubdivisionDto=class{constructor(e,t,i,r,s){this.useV=!1,this.includeLast=!0,this.includeFirst=!0,void 0!==e&&(this.surface=e),void 0!==t&&(this.useV=t),void 0!==i&&(this.includeLast=i),void 0!==r&&(this.includeFirst=r),void 0!==s&&(this.isocurveSegments=s)}},e.DerivativesDto=class{constructor(e,t,i,r){void 0!==e&&(this.surface=e),void 0!==t&&(this.u=t),void 0!==i&&(this.v=i),void 0!==r&&(this.numDerivatives=r)}},e.SurfaceLocationDto=class{constructor(e,t,i){void 0!==e&&(this.surface=e),void 0!==t&&(this.u=t),void 0!==i&&(this.v=i)}},e.CornersDto=class{constructor(e,t,i,r){void 0!==e&&(this.point1=e),void 0!==t&&(this.point2=t),void 0!==i&&(this.point3=i),void 0!==r&&(this.point4=r)}},e.SurfaceParamDto=class{constructor(e,t){void 0!==e&&(this.surface=e),void 0!==t&&(this.point=t)}},e.KnotsControlPointsWeightsDto=class{constructor(e,t,i,r,s,n){void 0!==e&&(this.degreeU=e),void 0!==t&&(this.degreeV=t),void 0!==i&&(this.knotsU=i),void 0!==r&&(this.knotsV=r),void 0!==s&&(this.points=s),void 0!==n&&(this.weights=n)}},e.LoftCurvesDto=class{constructor(e,t){void 0!==e&&(this.degreeV=e),void 0!==t&&(this.curves=t)}},e.DrawSurfaceDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.surface=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==r&&(this.updatable=r),void 0!==s&&(this.hidden=s),void 0!==n&&(this.surfaceMesh=n)}},e.DrawSurfacesDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.surfaces=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==r&&(this.updatable=r),void 0!==s&&(this.hidden=s),void 0!==n&&(this.surfacesMesh=n)}},e.DrawSurfacesColoursDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.updatable=!1,this.hidden=!1,void 0!==e&&(this.surfaces=e),void 0!==t&&(this.colours=t),void 0!==i&&(this.opacity=i),void 0!==r&&(this.updatable=r),void 0!==s&&(this.hidden=s),void 0!==n&&(this.surfacesMesh=n)}},e.ConeAndCylinderParametersDto=class{constructor(e,t,i,r,s){this.axis=[0,1,0],this.xAxis=[1,0,0],this.base=[0,0,0],this.height=2,this.radius=1,void 0!==e&&(this.axis=e),void 0!==t&&(this.xAxis=t),void 0!==i&&(this.base=i),void 0!==r&&(this.height=r),void 0!==s&&(this.radius=s)}},e.ConeDto=class{constructor(e){void 0!==e&&(this.cone=e)}},e.CylinderDto=class{constructor(e){void 0!==e&&(this.cylinder=e)}},e.ExtrusionParametersDto=class{constructor(e,t){void 0!==e&&(this.profile=e),void 0!==t&&(this.direction=t)}},e.ExtrusionDto=class{constructor(e){void 0!==e&&(this.extrusion=e)}},e.SphericalParametersDto=class{constructor(e,t){void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t)}},e.SphereDto=class{constructor(e){void 0!==e&&(this.sphere=e)}},e.RevolutionParametersDto=class{constructor(e,t,i,r){void 0!==e&&(this.profile=e),void 0!==t&&(this.center=t),void 0!==i&&(this.axis=i),void 0!==r&&(this.angle=r)}},e.RevolutionDto=class{constructor(e){void 0!==e&&(this.revolution=e)}},e.SweepParametersDto=class{constructor(e,t){void 0!==e&&(this.profile=e),void 0!==t&&(this.rail=t)}},e.SweepDto=class{constructor(e){void 0!==e&&(this.sweep=e)}},e.CurveCurveDto=class{constructor(e,t,i){void 0!==e&&(this.firstCurve=e),void 0!==t&&(this.secondCurve=t),void 0!==i&&(this.tolerance=i)}},e.CurveSurfaceDto=class{constructor(e,t,i){void 0!==e&&(this.curve=e),void 0!==t&&(this.surface=t),void 0!==i&&(this.tolerance=i)}},e.SurfaceSurfaceDto=class{constructor(e,t,i){void 0!==e&&(this.firstSurface=e),void 0!==t&&(this.secondSurface=t),void 0!==i&&(this.tolerance=i)}},e.CurveCurveIntersectionsDto=class{constructor(e){void 0!==e&&(this.intersections=e)}},e.CurveSurfaceIntersectionsDto=class{constructor(e){void 0!==e&&(this.intersections=e)}}}(sX||(sX={})),function(e){let t,i;e.PolylinePropertiesDto=class{constructor(e,t){this.isClosed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.isClosed=t)}},function(e){e.edge="edge",e.round="round",e.chamfer="chamfer"}(t=e.solidCornerTypeEnum||(e.solidCornerTypeEnum={})),function(e){e.left="left",e.center="center",e.right="right"}(i=e.jscadTextAlignEnum||(e.jscadTextAlignEnum={})),e.DrawSolidMeshDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.mesh=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==r&&(this.updatable=r),void 0!==s&&(this.hidden=s),void 0!==n&&(this.jscadMesh=n)}},e.DrawSolidMeshesDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.meshes=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==r&&(this.updatable=r),void 0!==s&&(this.hidden=s),void 0!==n&&(this.jscadMesh=n)}},e.DrawPathDto=class{constructor(e,t,i,r,s,n){this.colour="#444444",this.opacity=1,this.width=10,this.updatable=!1,void 0!==e&&(this.path=e),void 0!==t&&(this.colour=t),void 0!==i&&(this.opacity=i),void 0!==r&&(this.width=r),void 0!==s&&(this.updatable=s),void 0!==n&&(this.pathMesh=n)}},e.TransformSolidsDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.transformation=t)}},e.TransformSolidDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.transformation=t)}},e.DownloadSolidDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.fileName=t)}},e.DownloadGeometryDto=class{constructor(e,t,i){this.fileName="jscad-geometry",void 0!==e&&(this.geometry=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.options=i)}},e.DownloadSolidsDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.fileName=t)}},e.ColorizeDto=class{constructor(e,t){this.color="#0000ff",void 0!==e&&(this.geometry=e),void 0!==t&&(this.color=t)}},e.BooleanObjectsDto=class{constructor(e){void 0!==e&&(this.meshes=e)}},e.BooleanTwoObjectsDto=class{constructor(e,t){void 0!==e&&(this.first=e),void 0!==t&&(this.second=t)}},e.BooleanObjectsFromDto=class{constructor(e,t){void 0!==e&&(this.from=e),void 0!==t&&(this.meshes=t)}},e.ExpansionDto=class{constructor(e,i,r,s){this.delta=.1,this.corners=t.edge,this.segments=24,void 0!==e&&(this.geometry=e),void 0!==i&&(this.delta=i),void 0!==r&&(this.corners=r),void 0!==s&&(this.segments=s)}},e.OffsetDto=class{constructor(e,i,r,s){this.delta=.1,this.corners=t.edge,this.segments=24,void 0!==e&&(this.geometry=e),void 0!==i&&(this.delta=i),void 0!==r&&(this.corners=r),void 0!==s&&(this.segments=s)}},e.ExtrudeLinearDto=class{constructor(e,t,i,r){this.height=1,this.twistAngle=90,this.twistSteps=15,void 0!==e&&(this.geometry=e),void 0!==t&&(this.height=t),void 0!==i&&(this.twistAngle=i),void 0!==r&&(this.twistSteps=r)}},e.HullDto=class{constructor(e){void 0!==e&&(this.meshes=e)}},e.ExtrudeRectangularDto=class{constructor(e,t,i){this.height=1,this.size=1,void 0!==e&&(this.geometry=e),void 0!==t&&(this.height=t),void 0!==i&&(this.size=i)}},e.ExtrudeRectangularPointsDto=class{constructor(e,t,i){this.height=1,this.size=1,void 0!==e&&(this.points=e),void 0!==t&&(this.height=t),void 0!==i&&(this.size=i)}},e.ExtrudeRotateDto=class{constructor(e,t,i,r){this.angle=90,this.startAngle=0,this.segments=24,void 0!==e&&(this.polygon=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.startAngle=i),void 0!==r&&(this.segments=r)}},e.PolylineDto=class{constructor(e){void 0!==e&&(this.polyline=e)}},e.CurveDto=class{constructor(e){void 0!==e&&(this.curve=e)}},e.PointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PathDto=class{constructor(e){void 0!==e&&(this.path=e)}},e.PathFromPointsDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.PathsFromPointsDto=class{constructor(e){void 0!==e&&(this.pointsLists=e)}},e.PathFromPolylineDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.polyline=e),void 0!==t&&(this.closed=t)}},e.PathAppendCurveDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.path=t)}},e.PathAppendPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.path=t)}},e.PathAppendPolylineDto=class{constructor(e,t){void 0!==e&&(this.polyline=e),void 0!==t&&(this.path=t)}},e.PathAppendArcDto=class{constructor(e,t,i,r,s,n,o,a){this.endPoint=[1,1],this.xAxisRotation=90,this.clockwise=!0,this.large=!1,this.segments=24,this.radiusX=1,this.radiusY=1,void 0!==e&&(this.path=e),void 0!==t&&(this.endPoint=t),void 0!==i&&(this.xAxisRotation=i),void 0!==r&&(this.clockwise=r),void 0!==s&&(this.large=s),void 0!==n&&(this.segments=n),void 0!==o&&(this.radiusX=o),void 0!==a&&(this.radiusY=a)}},e.CircleDto=class{constructor(e,t,i){this.center=[0,0],this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.EllipseDto=class{constructor(e,t,i){this.center=[0,0],this.radius=[1,2],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.SquareDto=class{constructor(e,t){this.center=[0,0],this.size=1,void 0!==e&&(this.center=e),void 0!==t&&(this.size=t)}},e.RectangleDto=class{constructor(e,t,i){this.center=[0,0],this.width=1,this.length=1,void 0!==e&&(this.center=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i)}},e.RoundedRectangleDto=class{constructor(e,t,i,r,s){this.center=[0,0],this.roundRadius=.2,this.segments=24,this.width=1,this.length=1,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.segments=i),void 0!==r&&(this.width=r),void 0!==s&&(this.length=s)}},e.StarDto=class{constructor(e,t,i,r,s,n){this.center=[0,0],this.vertices=10,this.density=1,this.outerRadius=2,this.innerRadius=1,this.startAngle=0,void 0!==e&&(this.center=e),void 0!==t&&(this.vertices=t),void 0!==i&&(this.density=i),void 0!==r&&(this.outerRadius=r),void 0!==s&&(this.innerRadius=s),void 0!==n&&(this.startAngle=n)}},e.CubeDto=class{constructor(e,t){this.center=[0,0,0],this.size=1,void 0!==e&&(this.center=e),void 0!==t&&(this.size=t)}},e.CubeCentersDto=class{constructor(e,t){this.size=1,void 0!==e&&(this.centers=e),void 0!==t&&(this.size=t)}},e.CuboidDto=class{constructor(e,t,i,r){this.center=[0,0,0],this.width=1,this.length=1,this.height=1,void 0!==e&&(this.center=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==r&&(this.height=r)}},e.CuboidCentersDto=class{constructor(e,t,i,r){this.width=1,this.length=1,this.height=1,void 0!==e&&(this.centers=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==r&&(this.height=r)}},e.RoundedCuboidDto=class{constructor(e,t,i,r,s,n){this.center=[0,0,0],this.roundRadius=1,this.width=1,this.length=1,this.height=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.width=i),void 0!==r&&(this.length=r),void 0!==s&&(this.height=s),void 0!==n&&(this.segments=n)}},e.RoundedCuboidCentersDto=class{constructor(e,t,i,r,s,n){this.roundRadius=.1,this.width=1,this.length=1,this.height=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.width=i),void 0!==r&&(this.length=r),void 0!==s&&(this.height=s),void 0!==n&&(this.segments=n)}},e.CylidnerEllipticDto=class{constructor(e,t,i,r,s){this.center=[0,0,0],this.height=1,this.startRadius=[1,2],this.endRadius=[2,3],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.height=t),void 0!==i&&(this.startRadius=i),void 0!==r&&(this.endRadius=r),void 0!==s&&(this.segments=s)}},e.CylidnerCentersEllipticDto=class{constructor(e,t,i,r,s){this.height=1,this.startRadius=[1,2],this.endRadius=[2,3],this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.height=t),void 0!==i&&(this.startRadius=i),void 0!==r&&(this.endRadius=r),void 0!==s&&(this.segments=s)}},e.CylidnerDto=class{constructor(e,t,i,r){this.center=[0,0,0],this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.height=t),void 0!==i&&(this.radius=i),void 0!==r&&(this.segments=r)}},e.RoundedCylidnerDto=class{constructor(e,t,i,r,s){this.center=[0,0,0],this.roundRadius=.1,this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.height=i),void 0!==r&&(this.radius=r),void 0!==s&&(this.segments=s)}},e.EllipsoidDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=[1,2,3],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.EllipsoidCentersDto=class{constructor(e,t,i){this.radius=[1,2,3],this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.GeodesicSphereDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=1,this.frequency=12,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.frequency=i)}},e.GeodesicSphereCentersDto=class{constructor(e,t,i){this.radius=1,this.frequency=12,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.frequency=i)}},e.CylidnerCentersDto=class{constructor(e,t,i,r){this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.height=t),void 0!==i&&(this.radius=i),void 0!==r&&(this.segments=r)}},e.RoundedCylidnerCentersDto=class{constructor(e,t,i,r,s){this.roundRadius=.1,this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.height=i),void 0!==r&&(this.radius=r),void 0!==s&&(this.segments=s)}},e.SphereDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.SphereCentersDto=class{constructor(e,t,i){this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.TorusDto=class{constructor(e,t,i,r,s,n,o,a){this.center=[0,0,0],this.innerRadius=1,this.outerRadius=2,this.innerSegments=24,this.outerSegments=24,this.innerRotation=0,this.outerRotation=360,this.startAngle=0,void 0!==e&&(this.center=e),void 0!==t&&(this.innerRadius=t),void 0!==i&&(this.outerRadius=i),void 0!==r&&(this.innerSegments=r),void 0!==s&&(this.outerSegments=s),void 0!==n&&(this.innerRotation=n),void 0!==o&&(this.outerRotation=o),void 0!==a&&(this.startAngle=a)}},e.TextDto=class{constructor(e,t,r,s,n,o,a,l,h){this.text="Hello World",this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.segments=t),void 0!==r&&(this.xOffset=r),void 0!==s&&(this.yOffset=s),void 0!==n&&(this.height=n),void 0!==o&&(this.lineSpacing=o),void 0!==a&&(this.letterSpacing=a),void 0!==l&&(this.align=l),void 0!==h&&(this.extrudeOffset=h)}},e.CylinderTextDto=class{constructor(e,t,r,s,n,o,a,l,h,c,u){this.text="Hello World",this.extrusionHeight=.5,this.extrusionSize=.1,this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.extrusionHeight=t),void 0!==r&&(this.extrusionSize=r),void 0!==s&&(this.segments=s),void 0!==n&&(this.xOffset=n),void 0!==o&&(this.yOffset=o),void 0!==a&&(this.height=a),void 0!==l&&(this.lineSpacing=l),void 0!==h&&(this.letterSpacing=h),void 0!==c&&(this.align=c),void 0!==u&&(this.extrudeOffset=u)}},e.SphereTextDto=class{constructor(e,t,r,s,n,o,a,l,h,c){this.text="Hello World",this.radius=.1,this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.radius=t),void 0!==r&&(this.segments=r),void 0!==s&&(this.xOffset=s),void 0!==n&&(this.yOffset=n),void 0!==o&&(this.height=o),void 0!==a&&(this.lineSpacing=a),void 0!==l&&(this.letterSpacing=l),void 0!==h&&(this.align=h),void 0!==c&&(this.extrudeOffset=c)}},e.FromPolygonPoints=class{constructor(e){void 0!==e&&(this.polygonPoints=e)}}}(nX||(nX={})),function(e){let t,i;!function(e){e.evenOdd="EvenOdd",e.nonZero="NonZero",e.positive="Positive",e.negative="Negative"}(t=e.fillRuleEnum||(e.fillRuleEnum={})),function(e){e.square="Square",e.round="Round",e.miter="Miter"}(i=e.manifoldJoinTypeEnum||(e.manifoldJoinTypeEnum={})),e.DecomposedManifoldMeshDto=class{},e.DrawManifoldOrCrossSectionDto=class{constructor(e,t,i,r,s,n,o,a){this.faceOpacity=1,this.faceColour="#ff0000",this.crossSectionColour="#ff00ff",this.crossSectionWidth=2,this.crossSectionOpacity=1,this.computeNormals=!1,void 0!==e&&(this.manifoldOrCrossSection=e),void 0!==t&&(this.faceOpacity=t),void 0!==i&&(this.faceMaterial=i),void 0!==r&&(this.faceColour=r),void 0!==s&&(this.crossSectionColour=s),void 0!==n&&(this.crossSectionWidth=n),void 0!==o&&(this.crossSectionOpacity=o),void 0!==a&&(this.computeNormals=a)}},e.DrawManifoldsOrCrossSectionsDto=class{constructor(e,t,i,r,s,n,o,a){this.faceColour="#ff0000",this.faceOpacity=1,this.crossSectionColour="#ff00ff",this.crossSectionWidth=2,this.crossSectionOpacity=1,this.computeNormals=!1,void 0!==e&&(this.manifoldsOrCrossSections=e),void 0!==t&&(this.faceOpacity=t),void 0!==i&&(this.faceMaterial=i),void 0!==r&&(this.faceColour=r),void 0!==s&&(this.crossSectionColour=s),void 0!==n&&(this.crossSectionWidth=n),void 0!==o&&(this.crossSectionOpacity=o),void 0!==a&&(this.computeNormals=a)}},e.CreateFromMeshDto=class{constructor(e){void 0!==e&&(this.mesh=e)}},e.CubeDto=class{constructor(e,t){this.center=!0,this.size=1,void 0!==e&&(this.center=e),void 0!==t&&(this.size=t)}},e.CreateContourSectionDto=class{constructor(e,i){this.fillRule=t.evenOdd,void 0!==e&&(this.polygons=e),void 0!==i&&(this.fillRule=i)}},e.SquareDto=class{constructor(e,t){this.center=!1,this.size=1,void 0!==e&&(this.center=e),void 0!==t&&(this.size=t)}},e.SphereDto=class{constructor(e,t){this.radius=1,void 0!==e&&(this.radius=e),void 0!==t&&(this.circularSegments=t)}},e.CylinderDto=class{constructor(e,t,i,r,s){this.height=1,this.radiusLow=1,this.radiusHigh=1,this.circularSegments=32,this.center=!0,void 0!==e&&(this.height=e),void 0!==t&&(this.radiusLow=t),void 0!==i&&(this.radiusHigh=i),void 0!==r&&(this.circularSegments=r),void 0!==s&&(this.center=s)}},e.CircleDto=class{constructor(e,t){this.radius=1,this.circularSegments=32,void 0!==e&&(this.radius=e),void 0!==t&&(this.circularSegments=t)}},e.RectangleDto=class{constructor(e,t,i){this.length=1,this.height=1,this.center=!1,void 0!==e&&(this.length=e),void 0!==t&&(this.height=t),void 0!==i&&(this.center=i)}},e.ManifoldDto=class{constructor(e){void 0!==e&&(this.manifold=e)}},e.CalculateNormalsDto=class{constructor(e,t,i){this.normalIdx=0,this.minSharpAngle=0,void 0!==e&&(this.manifold=e),void 0!==t&&(this.normalIdx=t),void 0!==i&&(this.minSharpAngle=i)}},e.CalculateCurvatureDto=class{constructor(e){void 0!==e&&(this.manifold=e)}},e.CountDto=class{constructor(e){void 0!==e&&(this.count=e)}},e.ManifoldsMinGapDto=class{constructor(e,t,i){this.searchLength=100,void 0!==e&&(this.manifold1=e),void 0!==t&&(this.manifold2=t),void 0!==i&&(this.searchLength=i)}},e.ManifoldRefineToleranceDto=class{constructor(e,t){this.tolerance=1e-6,void 0!==e&&(this.manifold=e),void 0!==t&&(this.tolerance=t)}},e.ManifoldRefineLengthDto=class{constructor(e,t){this.length=.1,void 0!==e&&(this.manifold=e),void 0!==t&&(this.length=t)}},e.ManifoldRefineDto=class{constructor(e,t){this.number=1,void 0!==e&&(this.manifold=e),void 0!==t&&(this.number=t)}},e.ManifoldSmoothByNormalsDto=class{constructor(e,t){this.normalIdx=0,void 0!==e&&(this.manifold=e),void 0!==t&&(this.normalIdx=t)}},e.ManifoldSmoothOutDto=class{constructor(e,t,i){this.minSharpAngle=60,this.minSmoothness=0,void 0!==e&&(this.manifold=e),void 0!==t&&(this.minSharpAngle=t),void 0!==i&&(this.minSmoothness=i)}},e.HullPointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.SliceDto=class{constructor(e){this.height=.5,void 0!==e&&(this.manifold=e)}},e.MeshDto=class{constructor(e){void 0!==e&&(this.mesh=e)}},e.MeshVertexIndexDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.vertexIndex=t)}},e.MeshTriangleRunIndexDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.triangleRunIndex=t)}},e.MeshHalfEdgeIndexDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.halfEdgeIndex=t)}},e.MeshTriangleIndexDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.triangleIndex=t)}},e.CrossSectionDto=class{constructor(e){void 0!==e&&(this.crossSection=e)}},e.CrossSectionsDto=class{constructor(e){void 0!==e&&(this.crossSections=e)}},e.ExtrudeDto=class{constructor(e){this.height=1,this.nDivisions=1,this.twistDegrees=0,this.scaleTopX=1,this.scaleTopY=1,this.center=!0,void 0!==e&&(this.crossSection=e)}},e.RevolveDto=class{constructor(e,t,i,r){this.matchProfile=!0,this.circularSegments=32,void 0!==e&&(this.crossSection=e),void 0!==t&&(this.revolveDegrees=t),void 0!==i&&(this.matchProfile=i),void 0!==r&&(this.circularSegments=r)}},e.OffsetDto=class{constructor(e,t,r,s,n){this.joinType=i.round,this.miterLimit=2,this.circularSegments=32,void 0!==e&&(this.crossSection=e),void 0!==t&&(this.delta=t),void 0!==r&&(this.joinType=r),void 0!==s&&(this.miterLimit=s),void 0!==n&&(this.circularSegments=n)}},e.SimplifyDto=class{constructor(e,t){this.epsilon=1e-6,void 0!==e&&(this.crossSection=e),void 0!==t&&(this.epsilon=t)}},e.ComposeDto=class{constructor(e){void 0!==e&&(this.polygons=e)}},e.MirrorCrossSectionDto=class{constructor(e,t){this.normal=[1,0],void 0!==e&&(this.crossSection=e),void 0!==t&&(this.normal=t)}},e.Scale2DCrossSectionDto=class{constructor(e,t){this.vector=[2,2],void 0!==e&&(this.crossSection=e),void 0!==t&&(this.vector=t)}},e.TranslateCrossSectionDto=class{constructor(e,t){void 0!==e&&(this.crossSection=e),void 0!==t&&(this.vector=t)}},e.RotateCrossSectionDto=class{constructor(e,t){void 0!==e&&(this.crossSection=e),void 0!==t&&(this.degrees=t)}},e.ScaleCrossSectionDto=class{constructor(e,t){this.factor=2,void 0!==e&&(this.crossSection=e),void 0!==t&&(this.factor=t)}},e.TranslateXYCrossSectionDto=class{constructor(e,t,i){this.x=0,this.y=0,void 0!==e&&(this.crossSection=e),void 0!==t&&(this.x=t),void 0!==i&&(this.y=i)}},e.TransformCrossSectionDto=class{constructor(e,t){void 0!==e&&(this.crossSection=e),void 0!==t&&(this.transform=t)}},e.MirrorDto=class{constructor(e,t){this.normal=[1,0,0],void 0!==e&&(this.manifold=e),void 0!==t&&(this.normal=t)}},e.Scale3DDto=class{constructor(e,t){this.vector=[2,2,2],void 0!==e&&(this.manifold=e),void 0!==t&&(this.vector=t)}},e.TranslateDto=class{constructor(e,t){void 0!==e&&(this.manifold=e),void 0!==t&&(this.vector=t)}},e.TranslateByVectorsDto=class{constructor(e,t){void 0!==e&&(this.manifold=e),void 0!==t&&(this.vectors=t)}},e.RotateDto=class{constructor(e,t){void 0!==e&&(this.manifold=e),void 0!==t&&(this.vector=t)}},e.RotateXYZDto=class{constructor(e,t,i,r){this.x=0,this.y=0,this.z=0,void 0!==e&&(this.manifold=e),void 0!==t&&(this.x=t),void 0!==i&&(this.y=i),void 0!==r&&(this.z=r)}},e.ScaleDto=class{constructor(e,t){this.factor=2,void 0!==e&&(this.manifold=e),void 0!==t&&(this.factor=t)}},e.TranslateXYZDto=class{constructor(e,t,i,r){this.x=0,this.y=0,this.z=0,void 0!==e&&(this.manifold=e),void 0!==t&&(this.x=t),void 0!==i&&(this.y=i),void 0!==r&&(this.z=r)}},e.TransformDto=class{constructor(e,t){void 0!==e&&(this.manifold=e),void 0!==t&&(this.transform=t)}},e.TransformsDto=class{constructor(e,t){void 0!==e&&(this.manifold=e),void 0!==t&&(this.transforms=t)}},e.TwoCrossSectionsDto=class{constructor(e,t){void 0!==e&&(this.crossSection1=e),void 0!==t&&(this.crossSection2=t)}},e.TwoManifoldsDto=class{constructor(e,t){void 0!==e&&(this.manifold1=e),void 0!==t&&(this.manifold2=t)}},e.SplitManifoldsDto=class{constructor(e,t){void 0!==e&&(this.manifoldToSplit=e),void 0!==t&&(this.manifoldCutter=t)}},e.TrimByPlaneDto=class{constructor(e,t,i){this.normal=[1,0,0],this.originOffset=0,void 0!==e&&(this.manifold=e),void 0!==t&&(this.normal=t),void 0!==i&&(this.originOffset=i)}},e.SplitByPlaneDto=class{constructor(e,t,i){this.normal=[1,0,0],this.originOffset=0,void 0!==e&&(this.manifold=e),void 0!==t&&(this.normal=t),void 0!==i&&(this.originOffset=i)}},e.ManifoldsDto=class{constructor(e){void 0!==e&&(this.manifolds=e)}},e.ManifoldToMeshDto=class{constructor(e,t){void 0!==e&&(this.manifold=e),void 0!==t&&(this.normalIdx=t)}},e.ManifoldsToMeshesDto=class{constructor(e,t){void 0!==e&&(this.manifolds=e),void 0!==t&&(this.normalIdx=t)}},e.DecomposeManifoldOrCrossSectionDto=class{constructor(e,t){void 0!==e&&(this.manifoldOrCrossSection=e),void 0!==t&&(this.normalIdx=t)}},e.ManifoldOrCrossSectionDto=class{constructor(e){void 0!==e&&(this.manifoldOrCrossSection=e)}},e.ManifoldsOrCrossSectionsDto=class{constructor(e){void 0!==e&&(this.manifoldsOrCrossSections=e)}},e.DecomposeManifoldsOrCrossSectionsDto=class{constructor(e,t){void 0!==e&&(this.manifoldsOrCrossSections=e),void 0!==t&&(this.normalIdx=t)}}}(oX||(oX={}));class gX{constructor(e){this.context=e}createTextBlock(e){const t=new dB(e.name,e.text);return e.height?t.height=e.height:t.height=1,e.width?t.width=e.width:t.width="42px",e.width?t.width=e.width:t.width=1,e.height?t.height=e.height:t.height="42px",t.fontSize=e.fontSize,t.color=e.color,t}alignText(e){switch(e.horizontalAlignment){case VH.horizontalAlignmentEnum.left:e.control.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT;break;case VH.horizontalAlignmentEnum.right:e.control.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_RIGHT;break;case VH.horizontalAlignmentEnum.center:e.control.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_CENTER}switch(e.verticalAlignment){case VH.verticalAlignmentEnum.top:e.control.textVerticalAlignment=lB.VERTICAL_ALIGNMENT_TOP;break;case VH.verticalAlignmentEnum.bottom:e.control.textVerticalAlignment=lB.VERTICAL_ALIGNMENT_BOTTOM;break;case VH.verticalAlignmentEnum.center:e.control.textVerticalAlignment=lB.VERTICAL_ALIGNMENT_CENTER}return e.control}setTextOutline(e){return e.textBlock.outlineWidth=e.outlineWidth,e.textBlock.outlineColor=e.outlineColor,e.textBlock}setText(e){return e.textBlock.text=e.text,e.textBlock}setRsizeToFit(e){return e.textBlock.resizeToFit=e.resizeToFit,e.textBlock}setTextWrapping(e){return e.textBlock.textWrapping=e.textWrapping,e.textBlock}setLineSpacing(e){return e.textBlock.lineSpacing=e.lineSpacing,e.textBlock}getText(e){return e.textBlock.text}getTextWrapping(e){return e.textBlock.textWrapping}getLineSpacing(e){return e.textBlock.lineSpacing}getOutlineWidth(e){return e.textBlock.outlineWidth}getResizeToFit(e){return e.textBlock.resizeToFit}getTextHorizontalAlignment(e){return e.textBlock.textHorizontalAlignment}getTextVerticalAlignment(e){return e.textBlock.textVerticalAlignment}createTextBlockObservableSelector(e){return e.selector}}class vX{constructor(e){this.context=e}createRadioButton(e){const t=new RB(e.name);return e.height?t.height=e.height:t.height="32px",e.width?t.width=e.width:t.width="32px",t.checkSizeRatio=e.checkSizeRatio,t.group=e.group,t.color=e.color,t.isChecked=e.isChecked,t.background=e.background,t}setCheckSizeRatio(e){return e.radioButton.checkSizeRatio=e.checkSizeRatio,e.radioButton}setGroup(e){return e.radioButton.group=e.group,e.radioButton}setBackground(e){return e.radioButton.background=e.background,e.radioButton}getCheckSizeRatio(e){return e.radioButton.checkSizeRatio}getGroup(e){return e.radioButton.group}getBackground(e){return e.radioButton.background}createRadioButtonObservableSelector(e){return e.selector}}class xX{constructor(e){this.context=e}createCheckbox(e){const t=new mB(e.name);return e.height?t.height=e.height:t.height="32px",e.width?t.width=e.width:t.width="32px",t.checkSizeRatio=e.checkSizeRatio,t.color=e.color,t.isChecked=e.isChecked,t.background=e.background,t}setBackground(e){return e.checkbox.background=e.background,e.checkbox}setCheckSizeRatio(e){return e.checkbox.checkSizeRatio=e.checkSizeRatio,e.checkbox}setIsChecked(e){return e.checkbox.isChecked=e.isChecked,e.checkbox}getCheckSizeRatio(e){return e.checkbox.checkSizeRatio}getIsChecked(e){return e.checkbox.isChecked}getBackground(e){return e.checkbox.background}createCheckboxObservableSelector(e){return e.selector}}class bX{constructor(e){this.context=e}createInputText(e){const t=new vB(e.name);return e.height?t.height=e.height:t.height="56px",e.width?t.width=e.width:t.width=1,t.text=e.text,t.placeholderText=e.placeholder,t.color=e.color,t.background=e.background,t}setBackground(e){return e.inputText.background=e.background,e.inputText}setText(e){return e.inputText.text=e.text,e.inputText}setPlaceholder(e){return e.inputText.placeholderText=e.placeholder,e.inputText}getBackground(e){return e.inputText.background}getText(e){return e.inputText.text}getPlaceholder(e){return e.inputText.placeholderText}createInputTextObservableSelector(e){return e.selector}}class SX{constructor(e){this.context=e}createColorPicker(e){const t=new bB(e.name);return e.height?t.height=e.height:t.height="300px",e.width?t.width=e.width:t.width="300px",e.size&&(t.size=e.size),e.defaultColor&&(t.value=hc.v9.FromHexString(e.defaultColor)),t.color=e.color,t}setColorPickerValue(e){return e.colorPicker.value=hc.v9.FromHexString(e.color),e.colorPicker}setColorPickerSize(e){return e.colorPicker.size=e.size,e.colorPicker}getColorPickerValue(e){return e.colorPicker.value.toHexString()}getColorPickerSize(e){return e.colorPicker.size}createColorPickerObservableSelector(e){return e.selector}}class TX{constructor(e){this.context=e}createImage(e){const t=new fB(e.name,e.url);return e.width?t.width=e.width:t.width="200px",e.height?t.height=e.height:t.height="200px",t.color=e.color,t}setSourceUrl(e){return e.image.source=e.url,e.image}getSourceUrl(e){return e.image.source}}class CX{constructor(e){this.context=e,this.advancedDynamicTexture=new uX(e),this.control=new _X(e),this.container=new fX(e),this.stackPanel=new dX(e),this.button=new pX(e),this.slider=new mX(e),this.textBlock=new gX(e),this.radioButton=new vX(e),this.checkbox=new xX(e),this.inputText=new bX(e),this.colorPicker=new SX(e),this.image=new TX(e)}}class yX{constructor(e){this.context=e}dispose(e){e.babylonMesh&&(e.babylonMesh.getScene().removeMesh(e.babylonMesh,!0),e.babylonMesh.dispose())}updateDrawn(e){const t=e.babylonMesh.metadata.type;e.babylonMesh.position=new hc.Pq(e.position[0],e.position[1],e.position[2]),e.babylonMesh.rotation=new hc.Pq(e.rotation[0],e.rotation[1],e.rotation[2]),e.babylonMesh.scaling=new hc.Pq(e.scaling[0],e.scaling[1],e.scaling[2]);const i=Array.isArray(e.colours);let r;if(e.babylonMesh.getChildMeshes&&(r=e.babylonMesh.getChildMeshes()),r&&r.length>0)i&&e.colours.length===r.length?r.forEach(((t,i)=>{const r=hc.v9.FromHexString(e.colours[i]);this.assignColorToMesh(t,r)})):i?r.forEach((t=>{const i=hc.v9.FromHexString(e.colours[0]);this.assignColorToMesh(t,i)})):r.forEach((t=>{const i=hc.v9.FromHexString(e.colours);this.assignColorToMesh(t,i)}));else{const t=i?hc.v9.FromHexString(e.colours[0]):hc.v9.FromHexString(e.colours);this.assignColorToMesh(e.babylonMesh,t)}if(null!==e.babylonMesh.edgesRenderer){const t=i?hc.v9.FromHexString(e.colours[0]):hc.v9.FromHexString(e.colours);e.babylonMesh.edgesColor=hc.ov.FromColor3(t)}if([QH.drawingTypes.point,QH.drawingTypes.points,QH.drawingTypes.line,QH.drawingTypes.lines,QH.drawingTypes.polyline,QH.drawingTypes.polylines].includes(t)){const t=e.babylonMesh.getVerticesData(st.R.ColorKind).length/4,r=[];if(i&&t===e.colours.length)for(let i=0;i{t.visibility=e.visibility}))}hide(e){e.babylonMesh.isVisible=!1,e.includeChildren&&e.babylonMesh.getChildMeshes&&e.babylonMesh.getChildMeshes().forEach((e=>{e.isVisible=!1}))}show(e){e.babylonMesh.isVisible=!0,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((e=>{e.isVisible=!0}))}setParent(e){e.babylonMesh.parent=e.parentMesh}getParent(e){return e.babylonMesh.parent}setCheckCollisions(e){e.babylonMesh.checkCollisions=e.checkCollisions,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((t=>{t.checkCollisions=e.checkCollisions}))}getCheckCollisions(e){return e.babylonMesh.checkCollisions}setPickable(e){e.babylonMesh.isPickable=e.pickable,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((t=>{t.isPickable=e.pickable}))}enablePointerMoveEvents(e){e.babylonMesh.enablePointerMoveEvents=!0,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((e=>{e.enablePointerMoveEvents=!1}))}disablePointerMoveEvents(e){e.babylonMesh.enablePointerMoveEvents=!1,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((e=>{e.enablePointerMoveEvents=!1}))}getPickable(e){return e.babylonMesh.isPickable}getMeshesWhereNameContains(e){return this.context.scene.meshes.filter((t=>t.name.includes(e.name)))}getChildMeshes(e){return e.babylonMesh.getChildMeshes(e.directDescendantsOnly)}getMeshesOfId(e){return this.context.scene.getMeshesById(e.id)}getMeshOfId(e){return this.context.scene.getMeshById(e.id)}getMeshOfUniqueId(e){return this.context.scene.getMeshByUniqueId(e.uniqueId)}mergeMeshes(e){return Yt.MergeMeshes(e.arrayOfMeshes,e.disposeSource,e.allow32BitsIndices,e.meshSubclass,e.subdivideWithSubMeshes,e.multiMultiMaterials)}convertToFlatShadedMesh(e){return e.babylonMesh.convertToFlatShadedMesh()}clone(e){var t,i;const r=e.babylonMesh.clone();if(!e.babylonMesh.metadata||e.babylonMesh.metadata&&!1!==e.babylonMesh.metadata.shadows){const e=null===(i=null===(t=this.context.scene)||void 0===t?void 0:t.metadata)||void 0===i?void 0:i.shadowGenerators;e.length>0&&(r.getChildMeshes().forEach((t=>{t.receiveShadows=!0,e.forEach((e=>e.addShadowCaster(t)))})),r.receiveShadows=!0,e.forEach((e=>e.addShadowCaster(r))))}return r.metadata=Object.assign({},e.babylonMesh.metadata),r}cloneToPositions(e){const t=[];return e.positions.forEach((i=>{const r=e.babylonMesh.clone();r.position=new hc.Pq(i[0],i[1],i[2]),t.push(r)})),t}setId(e){e.babylonMesh.id=e.id}getId(e){return e.babylonMesh.id}getUniqueId(e){return e.babylonMesh.uniqueId}setName(e){e.babylonMesh.name=e.name,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((t=>{t.name=e.name}))}getVerticesAsPolygonPoints(e){const t=e.babylonMesh.getVerticesData(st.R.PositionKind),i=e.babylonMesh.getIndices(),r=[];for(let e=0;e{t.material=e.material}))}getMaterial(e){return e.babylonMesh.material}getPosition(e){const t=e.babylonMesh;return[t.position.x,t.position.y,t.position.z]}getAbsolutePosition(e){const t=e.babylonMesh;return[t.absolutePosition.x,t.absolutePosition.y,t.absolutePosition.z]}getRotation(e){const t=e.babylonMesh;return[t.rotation.x,t.rotation.y,t.rotation.z]}getScale(e){const t=e.babylonMesh;return[t.scaling.x,t.scaling.y,t.scaling.z]}moveForward(e){const t=e.babylonMesh;t.translate(t.forward,e.distance,hc.$x.WORLD)}moveBackward(e){const t=e.babylonMesh;t.translate(t.forward.negate(),e.distance,hc.$x.WORLD)}moveUp(e){const t=e.babylonMesh;t.translate(t.up,e.distance,hc.$x.WORLD)}moveDown(e){const t=e.babylonMesh;t.translate(t.up.negate(),e.distance,hc.$x.WORLD)}moveRight(e){const t=e.babylonMesh;t.translate(t.right,e.distance,hc.$x.WORLD)}moveLeft(e){const t=e.babylonMesh;t.translate(t.right.negate(),e.distance,hc.$x.WORLD)}yaw(e){const t=e.babylonMesh,i=hc.uM.FromDegrees(e.rotate).radians();t.rotate(hc._0.Y,i,hc.$x.LOCAL)}pitch(e){const t=e.babylonMesh,i=hc.uM.FromDegrees(e.rotate).radians();t.rotate(hc._0.X,i,hc.$x.LOCAL)}roll(e){const t=e.babylonMesh,i=hc.uM.FromDegrees(e.rotate).radians();t.rotate(hc._0.Z,i,hc.$x.LOCAL)}rotateAroundAxisWithPosition(e){e.mesh.rotateAround(new hc.Pq(e.position[0],e.position[1],e.position[2]),new hc.Pq(e.axis[0],e.axis[1],e.axis[2]),hc.uM.FromDegrees(e.angle).radians())}setPosition(e){e.babylonMesh.position=new hc.Pq(e.position[0],e.position[1],e.position[2])}setRotation(e){const t=hc.uM.FromDegrees(e.rotation[0]).radians(),i=hc.uM.FromDegrees(e.rotation[1]).radians(),r=hc.uM.FromDegrees(e.rotation[2]).radians();e.babylonMesh.rotation=new hc.Pq(t,i,r)}setScale(e){e.babylonMesh.scaling=new hc.Pq(e.scale[0],e.scale[1],e.scale[2])}intersectsMesh(e){return e.babylonMesh.intersectsMesh(e.babylonMesh2,e.precise,e.includeDescendants)}intersectsPoint(e){const t=new hc.Pq(e.point[0],e.point[1],e.point[2]);return e.babylonMesh.intersectsPoint(t)}createMeshInstanceAndTransformNoReturn(e){this.createMeshInstanceAndTransform(e)}createMeshInstanceAndTransform(e){var t,i;const r=new Yt("instanceContainer"+Math.random(),this.context.scene),s=null===(i=null===(t=this.context.scene)||void 0===t?void 0:t.metadata)||void 0===i?void 0:i.shadowGenerators;if(e.mesh&&e.mesh.getChildMeshes&&e.mesh.getChildMeshes().length>0)e.mesh.getChildMeshes(!1).forEach((t=>{const i=t.getTotalVertices();if(t.createInstance&&i>0){t.disableEdgesRendering();const i=t.createInstance(`InstanceMesh${Math.random()}`);i.position=new hc.Pq(e.position[0],e.position[1],e.position[2]),i.rotation=new hc.Pq(e.rotation[0],e.rotation[1],e.rotation[2]),i.scaling=new hc.Pq(e.scaling[0],e.scaling[1],e.scaling[2]),(!e.mesh.metadata||e.mesh.metadata&&!1!==e.mesh.metadata.shadows)&&s.length>0&&(s.forEach((e=>{e.addShadowCaster(i)})),i.receiveShadows=!0),r.metadata=e.mesh.metadata,i.parent=r}})),e.mesh.isVisible=!1;else if(e.mesh){e.mesh.isVisible=!1;const t=e.mesh.createInstance(`InstanceMesh${Math.random()}`);t.position=new hc.Pq(e.position[0],e.position[1],e.position[2]),t.rotation=new hc.Pq(hc.uM.FromDegrees(e.rotation[0]).radians(),hc.uM.FromDegrees(e.rotation[1]).radians(),hc.uM.FromDegrees(e.rotation[2]).radians()),t.scaling=new hc.Pq(e.scaling[0],e.scaling[1],e.scaling[2]),t.parent=r,(!e.mesh.metadata||e.mesh.metadata&&!1!==e.mesh.metadata.shadows)&&(s.length>0&&s.forEach((e=>{e.addShadowCaster(t)})),t.receiveShadows=!0),t.metadata=e.mesh.metadata}return r}createMeshInstance(e){let t;if(e.mesh&&e.mesh.getChildMeshes&&e.mesh.getChildMeshes().length>0){e.mesh.setParent(null);const i=new Yt("meshCloneContainer"+Math.random());e.mesh.getChildMeshes(!1).forEach((e=>{e.createInstance&&e.getTotalVertices()>0&&e.getTotalIndices()>0&&(e.createInstance(`InstanceMesh${Math.random()}`).parent=i)})),t=i;const r=this.context.scene.metadata.shadowGenerators;(!e.mesh.metadata||e.mesh.metadata&&!1!==e.mesh.metadata.shadows)&&r.length>0&&(t.getChildMeshes().forEach((e=>{r.forEach((t=>t.addShadowCaster(e))),e.receiveShadows=!0})),r.forEach((e=>e.addShadowCaster(t))),t.receiveShadows=!0)}else if(e.mesh&&(e.mesh.setParent(null),e.mesh.getTotalVertices()>0)){const i=new Yt("meshCloneContainer"+Math.random());e.mesh.createInstance(`InstanceMesh${Math.random()}`).parent=i,t=i}return t}getSideOrientation(e){switch(e){case UH.sideOrientationEnum.frontside:return Yt.FRONTSIDE;case UH.sideOrientationEnum.backside:return Yt.BACKSIDE;case UH.sideOrientationEnum.doubleside:return Yt.DOUBLESIDE;default:return Yt.FRONTSIDE}}assignColorToMesh(e,t){const i=e.material;i instanceof Cb?i.baseColor=t:i instanceof Un&&(i.diffuseColor=t)}}var EX=i(66570);class PX{constructor(e,t){this.context=e,this.mesh=t}createBox(e){const t=bl.CreateBox("BabylonMesh"+Math.random(),{width:e.width,height:e.height,depth:e.depth,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createCube(e){const t=bl.CreateBox("BabylonMesh"+Math.random(),{size:e.size,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createSquarePlane(e){const t=bl.CreatePlane("BabylonMesh"+Math.random(),{size:e.size,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createSphere(e){const t=bl.CreateSphere("BabylonMesh"+Math.random(),{diameter:e.diameter,segments:e.segments,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createIcoSphere(e){const t=bl.CreateIcoSphere("BabylonMesh"+Math.random(),{radius:e.radius,radiusX:e.radiusX,radiusY:e.radiusY,radiusZ:e.radiusZ,flat:e.flat,subdivisions:e.subdivisions,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createDisc(e){const t=bl.CreateDisc("BabylonMesh"+Math.random(),{radius:e.radius,tessellation:e.tessellation,arc:e.arc,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createTorus(e){const t=bl.CreateTorus("BabylonMesh"+Math.random(),{diameter:e.diameter,thickness:e.thickness,tessellation:e.tessellation,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createTorusKnot(e){const t=bl.CreateTorusKnot("BabylonMesh"+Math.random(),{radius:e.radius,tube:e.tube,radialSegments:e.radialSegments,tubularSegments:e.tubularSegments,p:e.p,q:e.q,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createPolygon(e){var t;const i=bl.CreatePolygon("BabylonMesh"+Math.random(),{shape:e.shape.map((e=>new hc.Pq(e[0],e[1],e[2]))),holes:null===(t=e.holes)||void 0===t?void 0:t.map((e=>e.map((e=>new hc.Pq(e[0],e[1],e[2]))))),depth:e.depth,smoothingThreshold:e.smoothingThreshold,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation),wrap:e.wrap},this.context.scene,EX);return e.enableShadows?this.enableShadows(i):i.metadata={shadows:!1},i}extrudePolygon(e){var t;console.log(EX);const i=bl.ExtrudePolygon("BabylonMesh"+Math.random(),{shape:e.shape.map((e=>new hc.Pq(e[0],e[1],e[2]))),holes:null===(t=e.holes)||void 0===t?void 0:t.map((e=>e.map((e=>new hc.Pq(e[0],e[1],e[2]))))),depth:e.depth,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation),wrap:e.wrap},this.context.scene,EX);return e.enableShadows?this.enableShadows(i):i.metadata={shadows:!1},i}createTube(e){const t=e.path.map((e=>new hc.Pq(e[0],e[1],e[2]))),i=bl.CreateTube("BabylonMesh"+Math.random(),{path:t,radius:e.radius,tessellation:e.tessellation,cap:e.cap,arc:e.arc,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(i):i.metadata={shadows:!1},i}createPolyhedron(e){const t=bl.CreatePolyhedron("BabylonMesh"+Math.random(),{type:e.type,size:e.size,sizeX:e.sizeX,sizeY:e.sizeY,sizeZ:e.sizeZ,custom:e.custom,flat:e.flat,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createGeodesic(e){const t=bl.CreateGeodesic("BabylonMesh"+Math.random(),{m:e.m,n:e.n,size:e.size,sizeX:e.sizeX,sizeY:e.sizeY,sizeZ:e.sizeZ,flat:e.flat,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createGoldberg(e){const t=bl.CreateGoldberg("BabylonMesh"+Math.random(),{n:e.n,m:e.m,size:e.size,sizeX:e.sizeX,sizeY:e.sizeY,sizeZ:e.sizeZ,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createCapsule(e){const t=bl.CreateCapsule("BabylonMesh"+Math.random(),{orientation:new hc.Pq(...e.orientation),subdivisions:e.subdivisions,tessellation:e.tessellation,height:e.height,radius:e.radius,capSubdivisions:e.capSubdivisions,radiusTop:e.radiusTop,radiusBottom:e.radiusBottom,topCapSubdivisions:e.topCapSubdivisions,bottomCapSubdivisions:e.bottomCapSubdivisions},this.context.scene);return t.sideOrientation=this.mesh.getSideOrientation(e.sideOrientation),e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createCylinder(e){const t=bl.CreateCylinder("BabylonMesh"+Math.random(),{height:e.height,diameterTop:e.diameterTop,diameterBottom:e.diameterBottom,tessellation:e.tessellation,subdivisions:e.subdivisions,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createExtrudedSahpe(e){const t=e.shape.map((e=>new hc.Pq(e[0],e[1],e[2]))),i=e.path.map((e=>new hc.Pq(e[0],e[1],e[2]))),r=bl.ExtrudeShape("BabylonMesh"+Math.random(),{shape:t,path:i,scale:e.scale,rotation:e.rotation,closeShape:e.closeShape,closePath:e.closePath,cap:e.cap,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(r):r.metadata={shadows:!1},r}createRibbon(e){const t=e.pathArray.map((e=>e.map((e=>new hc.Pq(e[0],e[1],e[2]))))),i=bl.CreateRibbon("BabylonMesh"+Math.random(),{pathArray:t,closeArray:e.closeArray,closePath:e.closePath,offset:e.offset,updatable:e.updatable,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(i):i.metadata={shadows:!1},i}createLathe(e){const t=e.shape.map((e=>new hc.Pq(e[0],e[1],e[2]))),i=bl.CreateLathe("BabylonMesh"+Math.random(),{shape:t,radius:e.radius,tessellation:e.tessellation,arc:e.arc,closed:e.closed,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(i):i.metadata={shadows:!1},i}createGround(e){const t=bl.CreateGround("BabylonMesh"+Math.random(),{width:e.width,height:e.height,subdivisionsX:e.subdivisionsX,subdivisionsY:e.subdivisionsY},this.context.scene);return t.sideOrientation=this.mesh.getSideOrientation(e.sideOrientation),e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createRectanglePlane(e){const t=bl.CreatePlane("BabylonMesh"+Math.random(),{width:e.width,height:e.height,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}enableShadows(e){this.context.scene.metadata.shadowGenerators&&(e.receiveShadows=!0,this.context.scene.metadata.shadowGenerators.forEach((t=>{t.addShadowCaster(e)})))}}class AX{constructor(e,t){this.context=e,this.drawHelper=t}drawNode(e){this.drawHelper.localAxes(e.size,this.context.scene,e.colorX,e.colorY,e.colorZ).parent=e.node}drawNodes(e){e.nodes.forEach((t=>{this.drawHelper.localAxes(e.size,this.context.scene,e.colorX,e.colorY,e.colorZ).parent=t}))}createNodeFromRotation(e){const t=new Pt(`node${Math.random()}`,this.context.scene);return e.parent&&(t.parent=e.parent),t.position=new hc.Pq(e.origin[0],e.origin[1],e.origin[2]),t.rotation=new hc.Pq(hc.uM.FromDegrees(e.rotation[0]).radians(),hc.uM.FromDegrees(e.rotation[1]).radians(),hc.uM.FromDegrees(e.rotation[2]).radians()),t}createWorldNode(){const e=new Pt(`root${Math.random()}`,this.context.scene);return e.parent=this.context.scene.getTransformNodeByID("root"),e}getAbsoluteForwardVector(e){const t=e.node.forward;return[t.x,t.y,t.z]}getAbsoluteRightVector(e){const t=e.node.right;return[t.x,t.y,t.z]}getAbsoluteUpVector(e){const t=e.node.up;return[t.x,t.y,t.z]}getAbsolutePosition(e){const t=e.node.getAbsolutePosition();return[t.x,t.y,t.z]}getAbsoluteRotationTransformation(e){const t=new hc.uq;return e.node.absoluteRotationQuaternion.toRotationMatrix(t),[...t.toArray()]}getRotationTransformation(e){const t=new hc.uq;return e.node.rotationQuaternion.toRotationMatrix(t),[...t.toArray()]}getChildren(e){return e.node.getChildren()}getParent(e){return e.node.parent}getPositionExpressedInLocalSpace(e){const t=e.node.getPositionExpressedInLocalSpace();return[t.x,t.y,t.z]}getRootNode(){return this.context.scene.getTransformNodeByID("root")}getRotation(e){const t=e.node.rotation;return[hc.uM.FromRadians(t.x).degrees(),hc.uM.FromRadians(t.y).degrees(),hc.uM.FromRadians(t.z).degrees()]}rotateAroundAxisWithPosition(e){e.node.rotateAround(new hc.Pq(e.position[0],e.position[1],e.position[2]),new hc.Pq(e.axis[0],e.axis[1],e.axis[2]),hc.uM.FromDegrees(e.angle).radians())}rotate(e){e.node.rotate(new hc.Pq(e.axis[0],e.axis[1],e.axis[2]),hc.uM.FromDegrees(e.angle).radians())}setAbsolutePosition(e){e.node.setAbsolutePosition(new hc.Pq(e.position[0],e.position[1],e.position[2]))}setDirection(e){e.node.setDirection(new hc.Pq(e.direction[0],e.direction[1],e.direction[2]))}setParent(e){e.node.setParent(e.parentNode)}translate(e){e.node.translate(new hc.Pq(e.direction[0],e.direction[1],e.direction[2]),e.distance)}}class RX{constructor(e){this.context=e}pickWithRay(e){return this.context.scene.pickWithRay(e.ray)}pickWithPickingRay(){const e=this.context.scene,t=e.createPickingRay(e.pointerX,e.pointerY,hc.uq.Identity(),this.context.scene.activeCamera,!1);return e.pickWithRay(t)}getDistance(e){return e.pickInfo.distance}getPickedMesh(e){return e.pickInfo.pickedMesh}getPickedPoint(e){const t=e.pickInfo.pickedPoint;return[t.x,t.y,t.z]}hit(e){return e.pickInfo.hit}getSubMeshId(e){return e.pickInfo.subMeshId}getSubMeshFaceId(e){return e.pickInfo.subMeshFaceId}getBU(e){return e.pickInfo.bu}getBV(e){return e.pickInfo.bv}getPickedSprite(e){return e.pickInfo.pickedSprite}}class IX{constructor(e){this.context=e}createPickingRay(){const e=this.context.scene;return e.createPickingRay(e.pointerX,e.pointerY,hc.uq.Identity(),this.context.scene.activeCamera,!1)}createRay(e){const t=new hc.Pq(e.origin[0],e.origin[1],e.origin[2]),i=new hc.Pq(e.direction[0],e.direction[1],e.direction[2]);let r;return 0!==e.length&&(r=e.length),new wi(t,i,r)}createRayFromTo(e){const t=new hc.Pq(e.from[0],e.from[1],e.from[2]),i=new hc.Pq(e.to[0],e.to[1],e.to[2]);return wi.CreateNewFromTo(t,i)}getOrigin(e){const t=e.ray.origin;return[t.x,t.y,t.z]}getDirection(e){const t=e.ray.direction;return[t.x,t.y,t.z]}getLength(e){return e.ray.length}}class MX{constructor(e){this.context=e}getScene(){return this.context.scene}setAndAttachScene(e){return e.scene.metadata={shadowGenerators:[]},new Pt("root",this.context.scene),this.context.scene=e.scene}backgroundColour(e){this.context.scene.clearColor=hc.ov.FromColor3(hc.v9.FromHexString(e.colour))}activateCamera(e){this.context.scene.activeCamera.detachControl(),this.context.scene.activeCamera=e.camera}useRightHandedSystem(e){this.context.scene.useRightHandedSystem=e.use,this.context.scene.activeCamera.getViewMatrix(!0),this.context.scene.activeCamera.getProjectionMatrix(!0)}drawPointLightNoReturn(e){this.drawPointLight(e)}getShadowGenerators(){return this.context.scene.metadata&&this.context.scene.metadata.shadowGenerators?this.context.scene.metadata.shadowGenerators:[]}drawPointLight(e){const t=new hc.Pq(e.position[0],e.position[1],e.position[2]),i=new wx(`pointLight${Math.random()}`,t,this.context.scene);if(e.enableShadows){i.shadowEnabled=!0;const t=new ux(e.shadowGeneratorMapSize,i);t.darkness=e.shadowDarkness,t.usePercentageCloserFiltering=e.shadowUsePercentageCloserFiltering,t.contactHardeningLightSizeUVRatio=e.shadowContactHardeningLightSizeUVRatio,t.bias=e.shadowBias,t.normalBias=e.shadowNormalBias,i.shadowMaxZ=e.shadowMaxZ,i.shadowMinZ=e.shadowMinZ,this.context.scene.metadata.shadowGenerators.push(t),this.context.scene.meshes.forEach((e=>{"bitbybit-hdrSkyBox"===e.name||e.name.includes("bitbybit-ground")||e.metadata&&(!e.metadata||!1===e.metadata.shadows)||(t.addShadowCaster(e,!0),e.receiveShadows=!0)}))}if(i.diffuse=hc.v9.FromHexString(e.diffuse),i.specular=hc.v9.FromHexString(e.specular),i.intensityMode=$t.INTENSITYMODE_LUMINOUSPOWER,i.intensity=e.intensity,e.radius>0){const t=bl.CreateSphere(`PointLightSphere${Math.random()}`,{diameter:2*e.radius},this.context.scene),r=new Un(`LightMaterial${Math.random()}`,this.context.scene);r.diffuseColor=i.diffuse,r.specularColor=i.diffuse,r.emissiveColor=i.diffuse,t.material=r,t.parent=i}return i}drawDirectionalLightNoReturn(e){this.drawDirectionalLight(e)}drawDirectionalLight(e){const t=new hc.Pq(e.direction[0],e.direction[1],e.direction[2]),i=new hm(`directionalLight${Math.random()}`,t,this.context.scene);if(e.enableShadows){i.shadowEnabled=!0;const t=new ux(e.shadowGeneratorMapSize,i);t.darkness=e.shadowDarkness,t.usePercentageCloserFiltering=e.shadowUsePercentageCloserFiltering,t.contactHardeningLightSizeUVRatio=e.shadowContactHardeningLightSizeUVRatio,t.bias=e.shadowBias,t.normalBias=e.shadowNormalBias,i.shadowMaxZ=e.shadowMaxZ,i.shadowMinZ=e.shadowMinZ,this.context.scene.metadata.shadowGenerators.push(t),this.context.scene.meshes.forEach((e=>{"bitbybit-hdrSkyBox"===e.name||e.name.includes("bitbybit-ground")||e.metadata&&(!e.metadata||!1===e.metadata.shadows)||(t.addShadowCaster(e,!0),e.receiveShadows=!0)}))}return i.diffuse=hc.v9.FromHexString(e.diffuse),i.specular=hc.v9.FromHexString(e.specular),i.intensity=e.intensity,i.shadowMaxZ=e.shadowMaxZ,i}getActiveCamera(){return this.context.scene.activeCamera}adjustActiveArcRotateCamera(e){const t=this.context.scene.getCameraByName("Camera");t.position=new hc.Pq(e.position[0],e.position[1],e.position[2]),t.target=new hc.Pq(e.lookAt[0],e.lookAt[1],e.lookAt[2]);const i=hc.Pq.Distance(t.position,t.target);t.radius=i,void 0!==e.lowerRadiusLimit&&(t.lowerRadiusLimit=e.lowerRadiusLimit),void 0!==e.upperRadiusLimit&&(t.upperRadiusLimit=e.upperRadiusLimit),void 0!==e.lowerAlphaLimit&&(t.lowerAlphaLimit=this.getRadians(e.lowerAlphaLimit)),void 0!==e.upperAlphaLimit&&(t.upperAlphaLimit=this.getRadians(e.upperAlphaLimit)),void 0!==e.lowerBetaLimit&&(t.lowerBetaLimit=this.getRadians(e.lowerBetaLimit)),void 0!==e.upperBetaLimit&&(t.upperBetaLimit=this.getRadians(e.upperBetaLimit)),void 0!==e.angularSensibilityX&&(t.angularSensibilityX=e.angularSensibilityX),void 0!==e.angularSensibilityY&&(t.angularSensibilityY=e.angularSensibilityY),void 0!==e.panningSensibility&&(t.panningSensibility=e.panningSensibility),void 0!==e.wheelPrecision&&(t.wheelPrecision=e.wheelPrecision),void 0!==e.maxZ&&(t.maxZ=e.maxZ)}clearAllDrawn(){const e=this.context.scene;if(e&&(e.environmentTexture&&e.environmentTexture.dispose(),e.environmentTexture=null,e.fogMode=oi.Z.FOGMODE_NONE,e.meshes.forEach((e=>e.dispose())),e.meshes=[],e.materials.forEach((e=>e.dispose())),e.textures.forEach((e=>e.dispose())),e.materials=[],e.textures=[],e.useRightHandedSystem=!1,e.geometries.forEach((e=>{e.meshes&&e.meshes.forEach((e=>e.dispose())),e.dispose&&e.dispose()})),e.geometries=[],e.lights.forEach((e=>{"HemiLight"!==e.name&&e.dispose()})),e.lights=e.lights.filter((e=>"HemiLight"===e.name)),e.transformNodes&&e.transformNodes.forEach((e=>{e&&"root"!==e.name&&e.dispose()})),e.metadata&&(e.metadata.shadowGenerators.length>0&&(e.metadata.shadowGenerators.forEach((e=>e.dispose())),e.metadata.shadowGenerators=[]),e.metadata.xr&&e.metadata.xr.dispose(),e.metadata.guiManager&&e.metadata.guiManager.dispose()),e.transformNodes=[e.getTransformNodeByName("root")],e.activeCamera&&"Camera"!==e.activeCamera.name)){e.cameras.forEach((e=>e.dispose()));const t=new is("Camera",0,10,10,new hc.Pq(0,0,0),e);t.lowerRadiusLimit=0,e.setActiveCameraByName(t.name),t.setPosition(new hc.Pq(0,10,20));const i=document.getElementById("renderCanvas");t.attachControl(i,!0),t.minZ=0}}enableSkybox(e){let t;e.skybox===Kz.skyboxEnum.default?t=new gm("https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.19.0-alpha.0/textures/skybox/default_skybox/skybox",this.context.scene):e.skybox===Kz.skyboxEnum.greyGradient?t=new gm("https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.19.0-alpha.0/textures/skybox/grey_gradient/skybox",this.context.scene):e.skybox===Kz.skyboxEnum.clearSky?t=gm.CreateFromPrefilteredData("https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.19.0-alpha.0/textures/skybox/clear_sky/environment.env",this.context.scene,!1,!1):e.skybox===Kz.skyboxEnum.city&&(t=gm.CreateFromPrefilteredData("https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.19.0-alpha.0/textures/skybox/city/environmentSpecular.env",this.context.scene,!1,!1)),this.context.scene.createDefaultSkybox(t,!0,e.size,e.blur,!0).name="bitbybit-hdrSkyBox",this.context.scene.environmentIntensity=e.environmentIntensity}onPointerDown(e){this.context.scene.onPointerDown=e.statement_update}onPointerUp(e){this.context.scene.onPointerUp=e.statement_update}onPointerMove(e){this.context.scene.onPointerMove=e.statement_update}fog(e){switch(e.mode){case KH.fogModeEnum.none:this.context.scene.fogMode=0;break;case KH.fogModeEnum.exponential:this.context.scene.fogMode=1;break;case KH.fogModeEnum.exponentialSquared:this.context.scene.fogMode=2;break;case KH.fogModeEnum.linear:this.context.scene.fogMode=3}this.context.scene.fogDensity=e.density,this.context.scene.fogStart=e.start,this.context.scene.fogEnd=e.end,this.context.scene.fogColor=hc.v9.FromHexString(e.color)}enablePhysics(e){this.context.scene.enablePhysics(new hc.Pq(e.vector[0],e.vector[1],e.vector[2]),this.context.havokPlugin)}getRadians(e){let t=hc.uM.FromDegrees(e).radians();return e<0&&(t=-t),t}}class OX{constructor(e){this.context=e}createSimple(e){const t=new vi.g(e.url,this.context.scene,void 0,e.invertY,this.context.getSamplingMode(e.samplingMode));return t.uScale=e.uScale,t.vScale=e.vScale,t.wAng=e.wAng,t.invertZ=e.invertZ,t.uOffset=e.uOffset,t.vOffset=e.vOffset,t}}var DX=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class wX{constructor(e){this.context=e}createScreenshot(e){return DX(this,void 0,void 0,(function*(){const t=e.camera?e.camera:this.context.scene.activeCamera;return Ue.S0.CreateScreenshotAsync(this.context.engine,t,{width:e.width,height:e.height},e.mimeType,e.quality)}))}createScreenshotAndDownload(e){return DX(this,void 0,void 0,(function*(){return new Promise(((t,i)=>{const r=e.camera?e.camera:this.context.scene.activeCamera;return Ue.S0.CreateScreenshot(this.context.engine,r,{width:e.width,height:e.height},(()=>{t("done")}),e.mimeType,!0,e.quality)}))}))}}class NX{rotationCenterAxis(e){return[[...hc.uq.Translation(-e.center[0],-e.center[1],-e.center[2]).asArray()],[...hc.uq.RotationAxis(new hc.Pq(e.axis[0],e.axis[1],e.axis[2]),hc.uM.FromDegrees(e.angle).radians()).asArray()],[...hc.uq.Translation(e.center[0],e.center[1],e.center[2]).asArray()]]}rotationCenterX(e){return[[...hc.uq.Translation(-e.center[0],-e.center[1],-e.center[2]).asArray()],[...hc.uq.RotationX(hc.uM.FromDegrees(e.angle).radians()).asArray()],[...hc.uq.Translation(e.center[0],e.center[1],e.center[2]).asArray()]]}rotationCenterY(e){return[[...hc.uq.Translation(-e.center[0],-e.center[1],-e.center[2]).asArray()],[...hc.uq.RotationY(hc.uM.FromDegrees(e.angle).radians()).asArray()],[...hc.uq.Translation(e.center[0],e.center[1],e.center[2]).asArray()]]}rotationCenterZ(e){return[[...hc.uq.Translation(-e.center[0],-e.center[1],-e.center[2]).asArray()],[...hc.uq.RotationZ(hc.uM.FromDegrees(e.angle).radians()).asArray()],[...hc.uq.Translation(e.center[0],e.center[1],e.center[2]).asArray()]]}rotationCenterYawPitchRoll(e){return[[...hc.uq.Translation(-e.center[0],-e.center[1],-e.center[2]).asArray()],[...hc.uq.RotationYawPitchRoll(hc.uM.FromDegrees(e.yaw).radians(),hc.uM.FromDegrees(e.pitch).radians(),hc.uM.FromDegrees(e.roll).radians()).asArray()],[...hc.uq.Translation(e.center[0],e.center[1],e.center[2]).asArray()]]}scaleCenterXYZ(e){return[[...hc.uq.Translation(-e.center[0],-e.center[1],-e.center[2]).asArray()],[...hc.uq.Scaling(e.scaleXyz[0],e.scaleXyz[1],e.scaleXyz[2]).asArray()],[...hc.uq.Translation(e.center[0],e.center[1],e.center[2]).asArray()]]}scaleXYZ(e){return[[...hc.uq.Scaling(e.scaleXyz[0],e.scaleXyz[1],e.scaleXyz[2]).asArray()]]}uniformScale(e){return[[...hc.uq.Scaling(e.scale,e.scale,e.scale).asArray()]]}uniformScaleFromCenter(e){return[[...hc.uq.Translation(-e.center[0],-e.center[1],-e.center[2]).asArray()],[...hc.uq.Scaling(e.scale,e.scale,e.scale).asArray()],[...hc.uq.Translation(e.center[0],e.center[1],e.center[2]).asArray()]]}translationXYZ(e){return[[...hc.uq.Translation(e.translation[0],e.translation[1],e.translation[2]).asArray()]]}translationsXYZ(e){return e.translations.map((e=>[[...hc.uq.Translation(e[0],e[1],e[2]).asArray()]]))}}class FX{constructor(e){this.context=e}createGizmoManager(e){const t=new am(this.context.scene);return t.positionGizmoEnabled=e.positionGizmoEnabled,t.rotationGizmoEnabled=e.rotationGizmoEnabled,t.scaleGizmoEnabled=e.scaleGizmoEnabled,t.boundingBoxGizmoEnabled=e.boundingBoxGizmoEnabled,e.attachableMeshes&&e.attachableMeshes.length>0&&(t.attachableMeshes=e.attachableMeshes),t.clearGizmoOnEmptyPointerEvent=e.clearGizmoOnEmptyPointerEvent,t.scaleRatio=e.scaleRatio,t.usePointerToAttachGizmos=e.usePointerToAttachGizmos,t}getPositionGizmo(e){return e.gizmoManager.gizmos.positionGizmo}getRotationGizmo(e){return e.gizmoManager.gizmos.rotationGizmo}getScaleGizmo(e){return e.gizmoManager.gizmos.scaleGizmo}getBoundingBoxGizmo(e){return e.gizmoManager.gizmos.boundingBoxGizmo}attachToMesh(e){return e.gizmoManager.attachToMesh(e.mesh),e.gizmoManager}detachMesh(e){return e.gizmoManager.attachToMesh(null),e.gizmoManager}}class LX{constructor(e){this.context=e}planarGizmoEnabled(e){return e.positionGizmo.planarGizmoEnabled=e.planarGizmoEnabled,e.positionGizmo}snapDistance(e){return e.positionGizmo.snapDistance=e.snapDistance,e.positionGizmo}getAttachedMesh(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.attachedMesh}getAttachedNode(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.attachedNode}getXGizmo(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.xGizmo}getYGizmo(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.yGizmo}getZGizmo(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.zGizmo}getXPlaneGizmo(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.xPlaneGizmo}getYPlaneGizmo(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.yPlaneGizmo}getZPlaneGizmo(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.zPlaneGizmo}getPlanarGizmoEnabled(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.planarGizmoEnabled}getSnapDistance(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.snapDistance}getIsDragging(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.isDragging}createPositionGizmoObservableSelector(e){return e.selector}}class BX{constructor(e){this.context=e}setIsEnabled(e){return e.axisDragGizmo.isEnabled=e.isEnabled,e.axisDragGizmo}getIsEnabled(e){return e.axisDragGizmo.isEnabled}}class VX{constructor(e){this.context=e}setIsEnabled(e){return e.planeDragGizmo.isEnabled=e.isEnabled,e.planeDragGizmo}getIsEnabled(e){return e.planeDragGizmo.isEnabled}}class kX{constructor(e){this.context=e}snapDistance(e){return e.rotationGizmo.snapDistance=e.snapDistance,e.rotationGizmo}sensitivity(e){return e.rotationGizmo.sensitivity=e.sensitivity,e.rotationGizmo}getAttachedMesh(e){var t;return null===(t=e.rotationGizmo)||void 0===t?void 0:t.attachedMesh}getAttachedNode(e){var t;return null===(t=e.rotationGizmo)||void 0===t?void 0:t.attachedNode}getXGizmo(e){var t;return null===(t=e.rotationGizmo)||void 0===t?void 0:t.xGizmo}getYGizmo(e){var t;return null===(t=e.rotationGizmo)||void 0===t?void 0:t.yGizmo}getZGizmo(e){var t;return null===(t=e.rotationGizmo)||void 0===t?void 0:t.zGizmo}getSnapDistance(e){var t;return null===(t=e.rotationGizmo)||void 0===t?void 0:t.snapDistance}getSensitivity(e){var t;return null===(t=e.rotationGizmo)||void 0===t?void 0:t.sensitivity}createRotationGizmoObservableSelector(e){return e.selector}}class UX{constructor(e){this.context=e}getXGizmo(e){var t;return null===(t=e.scaleGizmo)||void 0===t?void 0:t.xGizmo}getYGizmo(e){var t;return null===(t=e.scaleGizmo)||void 0===t?void 0:t.yGizmo}getZGizmo(e){var t;return null===(t=e.scaleGizmo)||void 0===t?void 0:t.zGizmo}snapDistance(e){return e.scaleGizmo.snapDistance=e.snapDistance,e.scaleGizmo}setIncrementalSnap(e){return e.scaleGizmo.incrementalSnap=e.incrementalSnap,e.scaleGizmo}sensitivity(e){return e.scaleGizmo.sensitivity=e.sensitivity,e.scaleGizmo}getIncrementalSnap(e){return e.scaleGizmo.incrementalSnap}getSnapDistance(e){return e.scaleGizmo.snapDistance}getSensitivity(e){return e.scaleGizmo.sensitivity}createScaleGizmoObservableSelector(e){return e.selector}}class GX{constructor(e){this.context=e}setIsEnabled(e){return e.axisScaleGizmo.isEnabled=e.isEnabled,e.axisScaleGizmo}getIsEnabled(e){return e.axisScaleGizmo.isEnabled}}class zX{constructor(e){this.context=e}setRotationSphereSize(e){return e.boundingBoxGizmo.rotationSphereSize=e.rotationSphereSize,e.boundingBoxGizmo}setFixedDragMeshScreenSize(e){return e.boundingBoxGizmo.fixedDragMeshScreenSize=e.fixedDragMeshScreenSize,e.boundingBoxGizmo}setFixedDragMeshBoundsSize(e){return e.boundingBoxGizmo.fixedDragMeshBoundsSize=e.fixedDragMeshBoundsSize,e.boundingBoxGizmo}setFixedDragMeshScreenSizeDistanceFactor(e){return e.boundingBoxGizmo.fixedDragMeshScreenSizeDistanceFactor=e.fixedDragMeshScreenSizeDistanceFactor,e.boundingBoxGizmo}setScalingSnapDistance(e){return e.boundingBoxGizmo.scalingSnapDistance=e.scalingSnapDistance,e.boundingBoxGizmo}setRotationSnapDistance(e){return e.boundingBoxGizmo.rotationSnapDistance=e.rotationSnapDistance,e.boundingBoxGizmo}setScaleBoxSize(e){return e.boundingBoxGizmo.scaleBoxSize=e.scaleBoxSize,e.boundingBoxGizmo}setIncrementalSnap(e){return e.boundingBoxGizmo.incrementalSnap=e.incrementalSnap,e.boundingBoxGizmo}setScalePivot(e){return e.boundingBoxGizmo.scalePivot=new hc.Pq(...e.scalePivot),e.boundingBoxGizmo}setAxisFactor(e){return e.boundingBoxGizmo.axisFactor=new hc.Pq(...e.axisFactor),e.boundingBoxGizmo}setScaleDragSpeed(e){return e.boundingBoxGizmo.scaleDragSpeed=e.scaleDragSpeed,e.boundingBoxGizmo}getRotationSphereSize(e){var t;return null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.rotationSphereSize}getScaleBoxSize(e){var t;return null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.scaleBoxSize}getFixedDragMeshScreenSize(e){var t;return null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.fixedDragMeshScreenSize}getFixedDragMeshBoundsSize(e){var t;return null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.fixedDragMeshBoundsSize}getFixedDragMeshScreenSizeDistanceFactor(e){var t;return null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.fixedDragMeshScreenSizeDistanceFactor}getScalingSnapDistance(e){var t;return null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.scalingSnapDistance}getRotationSnapDistance(e){var t;return null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.rotationSnapDistance}getIncrementalSnap(e){var t;return null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.incrementalSnap}getScalePivot(e){var t,i;return null===(i=null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.scalePivot)||void 0===i?void 0:i.asArray()}getAxisFactor(e){var t,i;return null===(i=null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.axisFactor)||void 0===i?void 0:i.asArray()}getScaleDragSpeed(e){var t;return null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.scaleDragSpeed}createBoundingBoxGizmoObservableSelector(e){return e.selector}}class WX{constructor(e){this.context=e}setIsEnabled(e){return e.planeRotationGizmo.isEnabled=e.isEnabled,e.planeRotationGizmo}getIsEnabled(e){return e.planeRotationGizmo.isEnabled}}class HX{constructor(e){this.context=e}scaleRatio(e){return e.gizmo.scaleRatio=e.scaleRatio,e.gizmo}getScaleRatio(e){var t;return null===(t=e.gizmo)||void 0===t?void 0:t.scaleRatio}}class XX{constructor(e){this.context=e,this.manager=new FX(e),this.base=new HX(e),this.positionGizmo=new LX(e),this.rotationGizmo=new kX(e),this.scaleGizmo=new UX(e),this.boundingBoxGizmo=new zX(e),this.axisDragGizmo=new BX(e),this.axisScaleGizmo=new GX(e),this.planeDragGizmo=new VX(e),this.planeRotationGizmo=new WX(e)}}class qX{constructor(e,t,i){this.mesh=new yX(e),this.camera=new iW(e),this.gaussianSplatting=new WW(e),this.node=new AX(e,t),this.scene=new MX(e),this.webXr=new UW(e),this.gui=new CX(e),this.transforms=new NX,this.io=new lX(e),this.ray=new IX(e),this.pick=new RX(e),this.material=new BW(e,i),this.lights=new cX(e),this.texture=new OX(e),this.meshBuilder=new PX(e,this.mesh),this.tools=new wX(e),this.engine=new GW(e),this.gizmo=new XX(e)}}class YX extends HG{constructor(e,t){super(e),this.occWorkerManager=e,this.context=t}loadSTEPorIGES(e){return this.context.getFile(e.assetFile).then((t=>this.occWorkerManager.genericCallToWorkerPromise("io.loadSTEPorIGES",new Yz.LoadStepOrIgesDto(t,e.assetFile.name,e.adjustZtoY))))}loadSTEPorIGESFromText(e){return this.occWorkerManager.genericCallToWorkerPromise("io.loadSTEPorIGES",new Yz.LoadStepOrIgesDto(e.text,`fake.${e.fileType}`,e.adjustZtoY))}}class KX extends hz{constructor(e,t){super(t),this.context=e,this.occWorkerManager=t,this.io=new YX(t,e)}}class jX{constructor(e,t){this.context=e,this.math=t}createCircle(e){return new this.context.verb.geom.Circle(e.center,e.xAxis,e.yAxis,e.radius)}createArc(e){return new this.context.verb.geom.Arc(e.center,e.xAxis,e.yAxis,e.radius,this.math.degToRad({number:e.minAngle}),this.math.degToRad({number:e.maxAngle}))}center(e){return e.circle.center()}radius(e){return e.circle.radius()}maxAngle(e){return this.math.radToDeg({number:e.circle.maxAngle()})}minAngle(e){return this.math.radToDeg({number:e.circle.minAngle()})}xAxis(e){return e.circle.xaxis()}yAxis(e){return e.circle.yaxis()}}class $X{constructor(e,t){this.context=e,this.math=t}createEllipse(e){return new this.context.verb.geom.Ellipse(e.center,e.xAxis,e.yAxis)}createArc(e){return new this.context.verb.geom.EllipseArc(e.center,e.xAxis,e.yAxis,this.math.degToRad({number:e.minAngle}),this.math.degToRad({number:e.maxAngle}))}center(e){return e.ellipse.center()}maxAngle(e){return this.math.radToDeg({number:e.ellipse.maxAngle()})}minAngle(e){return this.math.radToDeg({number:e.ellipse.minAngle()})}xAxis(e){return e.ellipse.xaxis()}yAxis(e){return e.ellipse.yaxis()}}class QX{constructor(e,t,i){this.context=e,this.geometryHelper=t,this.math=i,this.circle=new jX(e,this.math),this.ellipse=new $X(e,this.math)}createCurveByKnotsControlPointsWeights(e){return this.context.verb.geom.NurbsCurve.byKnotsControlPointsWeights(e.degree,e.knots,e.points,e.weights)}createCurveByPoints(e){return this.context.verb.geom.NurbsCurve.byPoints(e.points,e.degree)}createBezierCurve(e){return new this.context.verb.geom.BezierCurve(e.points,e.weights)}clone(e){return e.curve.clone()}closestParam(e){return e.curve.closestParam(e.point)}closestParams(e){return e.points.map((t=>e.curve.closestParam(t)))}closestPoint(e){return e.curve.closestPoint(e.point)}closestPoints(e){return e.points.map((t=>e.curve.closestPoint(t)))}controlPoints(e){return e.curve.controlPoints()}degree(e){return e.curve.degree()}derivatives(e){return e.curve.derivatives(e.parameter,e.numDerivatives)}divideByEqualArcLengthToParams(e){return e.curve.divideByEqualArcLength(e.subdivision).map((e=>e.u))}divideByEqualArcLengthToPoints(e){return e.curve.divideByEqualArcLength(e.subdivision).map((t=>e.curve.point(t.u)))}divideByArcLengthToParams(e){return e.curve.divideByArcLength(e.length).map((e=>e.u))}divideByArcLengthToPoints(e){return e.curve.divideByArcLength(e.length).map((t=>e.curve.point(t.u)))}divideCurvesByEqualArcLengthToPoints(e){return e.curves.map((t=>this.divideByEqualArcLengthToPoints({curve:t,subdivision:e.subdivision})))}divideCurvesByArcLengthToPoints(e){return e.curves.map((t=>this.divideByArcLengthToPoints({curve:t,length:e.length})))}domain(e){return e.curve.domain()}startPoint(e){return e.curve.point(e.curve.domain().min)}endPoint(e){return e.curve.point(e.curve.domain().max)}startPoints(e){return e.curves.map((e=>this.startPoint({curve:e})))}endPoints(e){return e.curves.map((e=>this.endPoint({curve:e})))}knots(e){return e.curve.knots()}lengthAtParam(e){return e.curve.lengthAtParam(e.parameter)}length(e){return e.curve.length()}paramAtLength(e){return e.curve.paramAtLength(e.length,e.tolerance)}pointAtParam(e){return e.curve.point(e.parameter)}pointsAtParam(e){return e.curves.map((t=>this.pointAtParam({curve:t,parameter:e.parameter})))}reverse(e){return e.curve.reverse()}split(e){return e.curve.split(e.parameter)}tangent(e){return e.curve.tangent(e.parameter)}tessellate(e){return e.curve.tessellate(e.tolerance)}transform(e){const t=e.curve.controlPoints(),i=this.geometryHelper.transformControlPoints(e.transformation,t);return this.context.verb.geom.NurbsCurve.byKnotsControlPointsWeights(e.curve.degree(),e.curve.knots(),i,e.curve.weights())}transformCurves(e){return e.curves.map((t=>this.transform({curve:t,transformation:e.transformation})))}weights(e){return e.curve.weights()}}class ZX{constructor(e,t){this.context=e,this.geometryHelper=t}curves(e){return this.context.verb.geom.Intersect.curves(e.firstCurve,e.secondCurve,e.tolerance)}curveAndSurface(e){return this.context.verb.geom.Intersect.curveAndSurface(e.curve,e.surface,e.tolerance)}surfaces(e){return this.context.verb.geom.Intersect.surfaces(e.firstSurface,e.secondSurface)}curveCurveFirstParams(e){return e.intersections.filter((e=>e.u0>=0&&e.u0<=1)).map((e=>e.u0))}curveCurveSecondParams(e){return e.intersections.filter((e=>e.u1>=0&&e.u1<=1)).map((e=>e.u1))}curveCurveFirstPoints(e){return e.intersections.filter((e=>e.u0>=0&&e.u0<=1)).map((e=>e.point0))}curveCurveSecondPoints(e){return e.intersections.filter((e=>e.u1>=0&&e.u1<=1)).map((e=>e.point1))}curveSurfaceCurveParams(e){return e.intersections.filter((e=>e.u>=0&&e.u<=1)).map((e=>e.u))}curveSurfaceSurfaceParams(e){return e.intersections.map((e=>e.uv))}curveSurfaceCurvePoints(e){return e.intersections.filter((e=>e.u>=0&&e.u<=1)).map((e=>e.curvePoint))}curveSurfaceSurfacePoints(e){return e.intersections.map((e=>e.surfacePoint))}}class JX{constructor(e){this.context=e}create(e){return new this.context.verb.geom.ConicalSurface(e.axis,e.xAxis,e.base,e.height,e.radius)}axis(e){return e.cone.axis()}base(e){return e.cone.base()}height(e){return e.cone.height()}radius(e){return e.cone.radius()}xAxis(e){return e.cone.xaxis()}}class eq{constructor(e){this.context=e}create(e){return new this.context.verb.geom.CylindricalSurface(e.axis,e.xAxis,e.base,e.height,e.radius)}axis(e){return e.cylinder.axis()}base(e){return e.cylinder.base()}height(e){return e.cylinder.height()}radius(e){return e.cylinder.radius()}xAxis(e){return e.cylinder.xaxis()}}class tq{constructor(e){this.context=e}create(e){return new this.context.verb.geom.ExtrudedSurface(e.profile,e.direction)}direction(e){return e.extrusion.direction()}profile(e){return e.extrusion.profile()}}class iq{constructor(e,t){this.context=e,this.math=t}create(e){return new this.context.verb.geom.RevolvedSurface(e.profile,e.center,e.axis,this.math.degToRad({number:e.angle}))}profile(e){return e.revolution.profile()}center(e){return e.revolution.center()}axis(e){return e.revolution.axis()}angle(e){return this.math.radToDeg({number:e.revolution.angle()})}}class rq{constructor(e){this.context=e}create(e){return new this.context.verb.geom.SphericalSurface(e.center,e.radius)}radius(e){return e.sphere.radius()}center(e){return e.sphere.center()}}class sq{constructor(e){this.context=e}create(e){return new this.context.verb.geom.SweptSurface(e.profile,e.rail)}profile(e){return e.sweep.profile()}rail(e){return e.sweep.rail()}}class nq{constructor(e,t,i){this.context=e,this.geometryHelper=t,this.math=i,this.cone=new JX(e),this.cylinder=new eq(e),this.extrusion=new tq(e),this.sphere=new rq(e),this.revolved=new iq(e,i),this.sweep=new sq(e)}boundaries(e){return e.surface.boundaries()}createSurfaceByCorners(e){return this.context.verb.geom.NurbsSurface.byCorners(e.point1,e.point2,e.point3,e.point4)}createSurfaceByKnotsControlPointsWeights(e){return this.context.verb.geom.NurbsSurface.byKnotsControlPointsWeights(e.degreeU,e.degreeV,e.knotsU,e.knotsV,e.points,e.weights)}createSurfaceByLoftingCurves(e){return this.context.verb.geom.NurbsSurface.byLoftingCurves(e.curves,e.degreeV)}clone(e){return e.surface.clone()}closestParam(e){return e.surface.closestParam(e.point)}closestPoint(e){return e.surface.closestPoint(e.point)}controlPoints(e){return e.surface.controlPoints()}degreeU(e){return e.surface.degreeU()}degreeV(e){return e.surface.degreeV()}derivatives(e){return e.surface.derivatives(e.u,e.v,e.numDerivatives)}domainU(e){return e.surface.domainU()}domainV(e){return e.surface.domainV()}isocurve(e){return e.surface.isocurve(e.parameter,e.useV)}isocurvesSubdivision(e){const t=.999999/e.isocurveSegments,i=this.context.verb.core.Vec.span(1e-7,.9999999,t);return e.includeLast||i.pop(),e.includeFirst||i.shift(),i.map((t=>e.surface.isocurve(t,e.useV)))}isocurvesAtParams(e){return e.parameters.map((t=>e.surface.isocurve(t,e.useV)))}knotsU(e){return e.surface.knotsU()}knotsV(e){return e.surface.knotsV()}normal(e){return e.surface.normal(e.u,e.v)}point(e){return e.surface.point(e.u,e.v)}reverse(e){return e.surface.reverse()}split(e){return e.surface.split(e.parameter,e.useV)}transformSurface(e){const t=e.surface.controlPoints(),i=e.transformation,r=[];return t.forEach((e=>{let t=e;t=this.geometryHelper.transformControlPoints(i,t),r.push(t)})),this.context.verb.geom.NurbsSurface.byKnotsControlPointsWeights(e.surface.degreeU(),e.surface.degreeV(),e.surface.knotsU(),e.surface.knotsV(),r,e.surface.weights())}weights(e){return e.surface.weights()}}class oq{constructor(e,t,i){this.math=i,this.curve=new QX(e,t,this.math),this.surface=new nq(e,t,this.math),this.intersect=new ZX(e,t)}}class aq{}var lq,hq=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class cq{constructor(){this.assetManager=new aq}getFile(e){return this.assetManager.getAsset(e.fileName)}getLocalFile(e){return this.assetManager.getLocalAsset(e.fileName)}fetchBlob(e){return hq(this,void 0,void 0,(function*(){return(yield fetch(e.url)).blob()}))}fetchFile(e){return hq(this,void 0,void 0,(function*(){const t=yield fetch(e.url),i=yield t.blob();return new File([i],e.url.split("/").pop().split("?")[0])}))}fetchJSON(e){return hq(this,void 0,void 0,(function*(){return(yield fetch(e.url)).json()}))}fetchText(e){return hq(this,void 0,void 0,(function*(){return(yield fetch(e.url)).text()}))}createObjectURL(e){return URL.createObjectURL(e.file)}createObjectURLs(e){return e.files.map((e=>URL.createObjectURL(e)))}}!function(e){e.IntervalDto=class{constructor(){this.min=0,this.max=1}},e.UVDto=class{constructor(){this.u=0,this.v=0}},e.CurveCurveIntersection=class{},e.CurveSurfaceIntersection=class{},e.SurfaceSurfaceIntersectionPoint=class{}}(lq||(lq={}));class uq{constructor(e){this.context=e}stringify(e){return JSON.stringify(e.json)}parse(e){return JSON.parse(e.text)}query(e){return this.context.jsonpath({path:e.query,json:e.json})}setValueOnProp(e){const t=Object.assign({},structuredClone(e.json));return t[e.property]=e.value,t}getJsonFromArrayByFirstPropMatch(e){return e.jsonArray.find((t=>t[e.property]===e.match))}getValueOnProp(e){try{return Object.assign({},structuredClone(e.json))[e.property]}catch(t){return e.json[e.property]}}setValue(e){if(e.json instanceof Object){const t=Object.assign({},structuredClone(e.json)),i=t=>(t[e.prop]=e.value,t);return this.context.jsonpath({path:e.path,json:t,callback:i}),t}throw new Error("Json must be an object")}setValuesOnPaths(e){let t=Object.assign({},structuredClone(e.json));return e.paths.forEach(((i,r)=>{t=this.setValue({json:t,path:i,value:e.values[r],prop:e.props[r]})})),t}paths(e){return this.context.jsonpath({json:e.json,path:e.query,resultType:"path"})}createEmpty(){return{}}previewAndSaveJson(e){e.json&&this.context.promptPrintSave({text:e.json,isJson:!0,hidden:!1})}previewJson(e){e.json&&this.context.promptPrint({text:e.json,isJson:!0,hidden:!1})}}class dq{constructor(e,t){this.context=e,this.geometryHelper=t}convertToNurbsCurve(e){return new this.context.verb.geom.Line(e.line.start,e.line.end)}convertLinesToNurbsCurves(e){return e.lines.map((e=>new this.context.verb.geom.Line(e.start,e.end)))}getStartPoint(e){return e.line.start}getEndPoint(e){return e.line.end}length(e){return this.context.verb.core.Vec.dist(e.line.start,e.line.end)}reverse(e){return{start:e.line.end,end:e.line.start}}transformLine(e){const t=e.transformation;let i=[e.line.start,e.line.end];return i=this.geometryHelper.transformControlPoints(t,i),{start:i[0],end:i[1]}}transformsForLines(e){return e.lines.map(((t,i)=>{const r=e.transformation[i];let s=[t.start,t.end];return s=this.geometryHelper.transformControlPoints(r,s),{start:s[0],end:s[1]}}))}create(e){return{start:e.start,end:e.end}}createAsync(e){return Promise.resolve({start:e.start,end:e.end})}getPointOnLine(e){const t=e.line.start,i=e.line.end,r=e.param,s=[i[0]-t[0],i[1]-t[1],i[2]-t[2]];return[t[0]+r*s[0],t[1]+r*s[1],t[2]+r*s[2]]}linesBetweenPoints(e){const t=[];for(let i=1;i({start:t,end:e.endPoints[i]}))).filter((e=>0!==this.context.verb.core.Vec.dist(e.start,e.end)))}linesBetweenStartAndEndPointsAsync(e){return Promise.resolve(this.linesBetweenStartAndEndPoints(e))}}class fq{constructor(e,t){this.context=e,this.geometryHelper=t}convertToNurbsCurve(e){return this.context.verb.geom.NurbsCurve.byPoints(e.polyline.points,1)}length(e){let t=0;for(let i=1;it.id===e.tagVariable.id));Object.keys(e.tag).forEach((i=>{t[i]=e.tag[i]})),t.needsUpdate=!0}else{const t=document.createElement("span"),i="_tag"+(new Date).getTime()+this.context.tagBag.length;e.tag.id=i,t.id=i,t.textContent=e.tag.text,document.querySelector("."+this.context.canvasZoneClass).appendChild(t),e.tag.needsUpdate=!0,this.context.tagBag.push(e.tag)}return e.tag}drawTags(e){if(e.tagsVariable&&e.updatable){if(e.tagsVariable.length{const r=this.context.tagBag.find((e=>e.id===t.id)),s=e.tags[i];if(s)Object.keys(s).forEach((e=>{r[e]=s[e]})),r.needsUpdate=!0;else{this.context.tagBag=this.context.tagBag.filter((e=>e.id!==r.id));const e=document.getElementById(r.id);e.parentNode.removeChild(e)}}))}else{const t=[];e.tags.forEach(((i,r)=>{const s=document.createElement("span"),n="_tag"+(new Date).getTime()+this.context.tagBag.length;i.id=n,s.id=n,s.textContent=i.text,document.querySelector("."+this.context.canvasZoneClass).appendChild(s),i.needsUpdate=!0,this.context.tagBag.push(i),t.push(i),e.tagsVariable=t}))}return e.tagsVariable}}class _q{constructor(e){this.context=e}registerRenderFunction(e){this.context.renderLoopBag.push((t=>{e(t)}))}}class mq{constructor(){this.canvasZoneClass="canvasZone",this.tolerance=1e-5,this.snapTolerance=1e-5,this.tagBag=[],this.timeoutBag=[],this.intervalBag=[],this.renderLoopBag=[],this.keyDownBag=[],this.keyUpBag=[],this.keyPressBag=[],this.currentlyPressedKeys=[]}getFile(e){return new Promise(((t,i)=>{if(e){const r=new FileReader;r.readAsText(e,"UTF-8"),r.onload=e=>{const i=e.target.result;t(i)},r.onerror=e=>{i()}}else i()}))}remap(e,t,i,r,s){return(e-t)/(i-t)*(s-r)+r}}class gq{detectPoint(e){return Array.isArray(e)&&3===e.length&&this.checkIfElementsInArrayAreNumbers(e)}detectPoints(e){return Array.isArray(e)&&this.checkIfElementsInArrayAreArrays(e)&&this.arraysInChildrenArraysContainNumbers(e)&&this.arraysInChildrenArraysAreOfLength3(e)}detectLine(e){return e.start&&e.end&&Array.isArray(e.start)&&Array.isArray(e.end)}detectLines(e){return Array.isArray(e)&&!e.some((e=>!this.detectLine(e)))}detectPolyline(e){return e.points&&Array.isArray(e.points)}detectPolylines(e){return Array.isArray(e)&&!e.some((e=>!this.detectPolyline(e)))}detectNode(e){return!Array.isArray(e)&&e.id&&e.id.includes("node")}detectNodes(e){return Array.isArray(e)&&!e.some((e=>!this.detectNode(e)))}detectVerbCurve(e){return!Array.isArray(e)&&e._data&&e._data.controlPoints&&e._data.knots&&e._data.degree}detectVerbSurface(e){return!Array.isArray(e)&&e._data&&e._data.controlPoints&&e._data.degreeU&&e._data.degreeV&&e._data.knotsU&&e._data.knotsV}detectVerbCurves(e){return Array.isArray(e)&&!e.some((e=>!this.detectVerbCurve(e)))}detectVerbSurfaces(e){return Array.isArray(e)&&!e.some((e=>!this.detectVerbSurface(e)))}detectJscadMesh(e){return!Array.isArray(e)&&(e.sides||e.polygons)}detectJscadMeshes(e){return Array.isArray(e)&&!e.some((e=>!this.detectJscadMesh(e)))}detectOcctShape(e){return"occ-shape"===(null==e?void 0:e.type)}detectOcctShapes(e){return Array.isArray(e)&&!e.some((e=>!this.detectOcctShape(e)))}detectManifoldShape(e){return"manifold-shape"===(null==e?void 0:e.type)}detectManifoldShapes(e){return Array.isArray(e)&&!e.some((e=>!this.detectManifoldShape(e)))}detectTag(e){return!Array.isArray(e)&&e.text}detectTags(e){return Array.isArray(e)&&!e.some((e=>!this.detectTag(e)))}checkIfElementsInArrayAreNumbers(e){return!e.some((e=>isNaN(e)))}checkIfElementsInArrayAreArrays(e){return!e.some((e=>!Array.isArray(e)))}arraysInChildrenArraysContainNumbers(e){return!e.some((e=>!this.checkIfElementsInArrayAreNumbers(e)))}arraysInChildrenArraysAreOfLength3(e){return!e.some((e=>3!==e.length))}}class vq{constructor(e){this.vector=e}computeEdgeMiddlePos(e){let t;if(2===e.vertex_coord.length){const i=e.vertex_coord[0],r=e.vertex_coord[1];t=this.vector.lerp({first:i,second:r,fraction:.5})}else if(3===e.vertex_coord.length)t=e.vertex_coord[1];else{const i=e.vertex_coord[Math.floor(e.vertex_coord.length/2)],r=e.vertex_coord[Math.floor(e.vertex_coord.length/2+1)];t=this.vector.lerp({first:i,second:r,fraction:.5})}return t}computeFaceMiddlePos(e){let t=0,i=0,r=0,s=0;return e.forEach((e=>{t+=e[0],i+=e[1],r+=e[2],s++})),[t/s,i/s,r/s]}}var xq,bq,Sq,Tq,Cq,yq,Eq,Pq,Aq=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class Rq extends gq{constructor(e,t,i,r){super(),this.drawHelper=e,this.node=t,this.tag=i,this.context=r,this.defaultBasicOptions=new QH.DrawBasicGeometryOptions,this.defaultPolylineOptions=Object.assign(Object.assign({},new QH.DrawBasicGeometryOptions),{size:2,colours:"#ff00ff"}),this.defaultNodeOptions={colorX:"#ff0000",colorY:"#00ff00",colorZ:"#0000ff",size:2}}drawAnyAsyncNoReturn(e){return Aq(this,void 0,void 0,(function*(){this.drawAnyAsync(e)}))}drawAnyAsync(e){return Aq(this,void 0,void 0,(function*(){const t=e.entity;return void 0===t||Array.isArray(t)&&0===t.length?Promise.resolve(void 0):this.detectJscadMesh(t)?this.handleJscadMesh(e):this.detectOcctShape(t)?this.handleOcctShape(e):this.detectOcctShapes(t)?this.handleOcctShapes(e):this.detectJscadMeshes(t)?this.handleJscadMeshes(e):this.detectManifoldShape(t)?this.handleManifoldShape(e):this.detectManifoldShapes(t)?this.handleManifoldShapes(e):Promise.resolve(this.drawAny(e))}))}updateAny(e){let t;if(e.babylonMesh&&e.babylonMesh.metadata)switch(e.babylonMesh.metadata.type){case QH.drawingTypes.point:t=this.handlePoint(e);break;case QH.drawingTypes.points:t=this.handlePoints(e);break;case QH.drawingTypes.line:t=this.handleLine(e);break;case QH.drawingTypes.lines:t=this.handleLines(e);break;case QH.drawingTypes.polyline:t=this.handlePolyline(e);break;case QH.drawingTypes.polylines:t=this.handlePolylines(e);break;case QH.drawingTypes.verbCurve:t=this.handleVerbCurve(e);break;case QH.drawingTypes.verbCurves:t=this.handleVerbCurves(e);break;case QH.drawingTypes.verbSurface:t=this.handleVerbSurface(e);break;case QH.drawingTypes.verbSurfaces:t=this.handleVerbSurfaces(e);break;case QH.drawingTypes.tag:t=this.handleTag(e);break;case QH.drawingTypes.tags:t=this.handleTags(e);break;case QH.drawingTypes.node:t=this.handleNode(e);break;case QH.drawingTypes.nodes:t=this.handleNodes(e)}return t}drawAnyNoReturn(e){this.drawAny(e)}drawAny(e){let t;const i=e.entity;return e.babylonMesh?t=this.updateAny(e):this.detectLine(i)?t=this.handleLine(e):this.detectPoint(i)?t=this.handlePoint(e):this.detectPolyline(i)?t=this.handlePolyline(e):this.detectNode(i)?t=this.handleNode(e):this.detectVerbCurve(i)?t=this.handleVerbCurve(e):this.detectVerbSurface(i)?t=this.handleVerbSurface(e):this.detectPolylines(i)?t=this.handlePolylines(e):this.detectLines(i)?t=this.handleLines(e):this.detectPoints(i)?t=this.handlePoints(e):this.detectNodes(i)?t=this.handleNodes(e):this.detectVerbCurves(i)?t=this.handleVerbCurves(e):this.detectVerbSurfaces(i)?t=this.handleVerbSurfaces(e):this.detectTag(i)?t=this.handleTag(e):this.detectTags(i)&&(t=this.handleTags(e)),t}drawGridMeshNoReturn(e){this.drawGridMesh(e)}drawGridMesh(e){try{const t=new gW(`groundMaterial${Math.random()}`,this.context.scene);t.majorUnitFrequency=e.majorUnitFrequency,t.minorUnitVisibility=e.minorUnitVisibility,t.gridRatio=e.gridRatio,t.backFaceCulling=e.backFaceCulling,t.mainColor=hc.v9.FromHexString(e.mainColor),t.lineColor=hc.v9.FromHexString(e.secondaryColor),t.opacity=e.opacity;const i=bl.CreateGround(`bitbybit-ground${Math.random()}`,{width:e.width,height:e.height,subdivisions:e.subdivisions,updatable:!1},this.context.scene);return i.material=t,i}catch(e){return console.log("Error happened: ",e),new Yt("error-ground",this.context.scene)}}optionsSimple(e){return e}optionsOcctShape(e){return e}optionsOcctShapeSimple(e){return e}optionsOcctShapeMaterial(e){return e}optionsManifoldShapeMaterial(e){return e}optionsBabylonNode(e){return e}handleTags(e){const t=e.options?e.options:{updatable:!1},i=this.tag.drawTags(Object.assign({tagsVariable:e.babylonMesh,tags:e.entity},t));return i.metadata={type:QH.drawingTypes.tags,options:t},i}handleTag(e){let t=e.options?e.options:{updatable:!1};!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.tag.drawTag(Object.assign({tagVariable:e.babylonMesh,tag:e.entity},t));return i.metadata={type:QH.drawingTypes.tag,options:t},i}handleVerbSurfaces(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.drawHelper.drawSurfacesMultiColour(Object.assign({surfacesMesh:e.babylonMesh,surfaces:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.verbSurfaces,t,i),i}handleVerbCurves(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.drawHelper.drawCurves(Object.assign({curvesMesh:e.babylonMesh,curves:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.verbCurves,t,i),i}handleNodes(e){let t=e.options?e.options:this.defaultNodeOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=e.entity;return this.node.drawNodes(Object.assign({nodes:e.entity},t)),this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.nodes,t,i),i}handlePoints(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.drawHelper.drawPoints(Object.assign({pointsMesh:e.babylonMesh,points:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.points,t,i),i}handleLines(e){let t=e.options?e.options:this.defaultPolylineOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=e.entity,r=this.drawHelper.drawPolylinesWithColours(Object.assign({polylinesMesh:e.babylonMesh,polylines:i.map((e=>({points:[e.start,e.end]})))},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.lines,t,r),r}handlePolylines(e){let t=e.options?e.options:this.defaultPolylineOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.drawHelper.drawPolylinesWithColours(Object.assign({polylinesMesh:e.babylonMesh,polylines:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.polylines,t,i),i}handleVerbSurface(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.drawHelper.drawSurface(Object.assign({surfaceMesh:e.babylonMesh,surface:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.verbSurface,t,i),i}handleVerbCurve(e){let t=e.options?e.options:this.defaultPolylineOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.drawHelper.drawCurve(Object.assign({curveMesh:e.babylonMesh,curve:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.verbCurve,t,i),i}handleNode(e){let t=e.options?e.options:this.defaultNodeOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=e.entity;return this.node.drawNode(Object.assign({node:e.entity},t)),this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.node,t,i),i}handlePolyline(e){let t=e.options?e.options:this.defaultPolylineOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.drawHelper.drawPolylineClose(Object.assign({polylineMesh:e.babylonMesh,polyline:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.polyline,t,i),i}handlePoint(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.drawHelper.drawPoint(Object.assign({pointMesh:e.babylonMesh,point:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.point,t,i),i}handleLine(e){let t=e.options?e.options:this.defaultPolylineOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=e.entity,r=this.drawHelper.drawPolylinesWithColours(Object.assign({polylinesMesh:e.babylonMesh,polylines:[{points:[i.start,i.end]}]},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.line,t,r),r}handleJscadMeshes(e){let t=e.options?e.options:this.defaultPolylineOptions;return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.drawHelper.drawSolidOrPolygonMeshes(Object.assign({jscadMesh:e.babylonMesh,meshes:e.entity},t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.jscadMeshes,t,e),e)))}handleManifoldShape(e){let t=e.options?e.options:new oX.DrawManifoldOrCrossSectionDto(e.entity);return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.drawHelper.drawManifoldOrCrossSection(Object.assign(Object.assign({manifoldOrCrossSection:e.entity},new QH.DrawManifoldOrCrossSectionOptions),t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.manifold,t,e),e)))}handleManifoldShapes(e){let t=e.options?e.options:new oX.DrawManifoldOrCrossSectionDto(e.entity);return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.drawHelper.drawManifoldsOrCrossSections(Object.assign(Object.assign({manifoldsOrCrossSections:e.entity},new oX.DrawManifoldOrCrossSectionDto),t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.manifold,t,e),e)))}handleOcctShape(e){let t=e.options?e.options:new Yz.DrawShapeDto(e.entity);return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.drawHelper.drawShape(Object.assign(Object.assign({shape:e.entity},new QH.DrawOcctShapeOptions),t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.occt,t,e),e)))}handleOcctShapes(e){let t=e.options?e.options:new Yz.DrawShapeDto(e.entity);return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.drawHelper.drawShapes(Object.assign(Object.assign({shapes:e.entity},new QH.DrawOcctShapeOptions),t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.occt,t,e),e)))}handleJscadMesh(e){let t=e.options?e.options:this.defaultBasicOptions;return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.drawHelper.drawSolidOrPolygonMesh(Object.assign({jscadMesh:e.babylonMesh,mesh:e.entity},t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.jscadMesh,t,e),e)))}applyGlobalSettingsAndMetadataAndShadowCasting(e,t,i){const r={type:e,options:t},s=this.context.scene.metadata.shadowGenerators;i.isPickable=!1,i.getChildMeshes().forEach((e=>{e.isPickable=!1}));let n=!0;i.metadata&&!1===i.metadata.shadows&&(n=!1),n&&s.length>0&&(i.receiveShadows=!0,s.forEach((e=>e.addShadowCaster(i))),i.getChildMeshes().forEach((e=>{e.receiveShadows=!0,s.forEach((t=>t.addShadowCaster(e)))}))),i.metadata=i.metadata?Object.assign(Object.assign({},i.metadata),r):r}}class Iq extends mq{getSamplingMode(e){switch(e){case BH.samplingModeEnum.nearest:return vi.g.NEAREST_SAMPLINGMODE;case BH.samplingModeEnum.bilinear:return vi.g.BILINEAR_SAMPLINGMODE;case BH.samplingModeEnum.trilinear:return vi.g.TRILINEAR_SAMPLINGMODE;default:return vi.g.NEAREST_SAMPLINGMODE}}}!function(e){e.HexDto=class{constructor(e){this.color="#0000ff",void 0!==e&&(this.color=e)}},e.InvertHexDto=class{constructor(e){this.color="#0000ff",this.blackAndWhite=!1,void 0!==e&&(this.color=e)}},e.HexDtoMapped=class{constructor(e,t,i){this.color="#0000ff",this.from=0,this.to=255,void 0!==e&&(this.color=e),void 0!==t&&(this.from=t),void 0!==i&&(this.to=i)}},e.RGBObjectMaxDto=class{constructor(e,t){this.min=0,this.max=255,void 0!==e&&(this.rgb=e),void 0!==t&&(this.max=t)}},e.RGBMinMaxDto=class{constructor(e,t,i,r,s){this.r=255,this.g=255,this.b=255,this.min=0,this.max=255,void 0!==e&&(this.r=e),void 0!==t&&(this.g=t),void 0!==i&&(this.b=i),void 0!==r&&(this.min=r),void 0!==s&&(this.max=s)}},e.RGBObjectDto=class{constructor(e){void 0!==e&&(this.rgb=e)}}}(xq||(xq={})),function(e){let t;!function(e){e.first="first",e.last="last"}(t=e.firstLastEnum||(e.firstLastEnum={})),e.ListItemDto=class{constructor(e,t,i){this.index=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.index=t),void 0!==i&&(this.clone=i)}},e.SubListDto=class{constructor(e,t,i,r){this.indexStart=0,this.indexEnd=1,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.indexStart=t),void 0!==i&&(this.indexEnd=i),void 0!==r&&(this.clone=r)}},e.ListCloneDto=class{constructor(e,t){this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.clone=t)}},e.RepeatInPatternDto=class{constructor(e){this.clone=!0,this.lengthLimit=100,void 0!==e&&(this.list=e)}},e.SortDto=class{constructor(e,t,i){this.clone=!0,this.orderAsc=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.clone=t),void 0!==i&&(this.orderAsc=i)}},e.SortJsonDto=class{constructor(e,t,i){this.clone=!0,this.orderAsc=!0,this.property="propName",void 0!==e&&(this.list=e),void 0!==t&&(this.clone=t),void 0!==i&&(this.orderAsc=i)}},e.ListDto=class{constructor(e){void 0!==e&&(this.list=e)}},e.GroupListDto=class{constructor(e,t,i){this.nrElements=2,this.keepRemainder=!1,void 0!==e&&(this.list=e),void 0!==t&&(this.nrElements=t),void 0!==i&&(this.keepRemainder=i)}},e.MultiplyItemDto=class{constructor(e,t){void 0!==e&&(this.item=e),void 0!==t&&(this.times=t)}},e.AddItemAtIndexDto=class{constructor(e,t,i,r){this.index=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.item=t),void 0!==i&&(this.index=i),void 0!==r&&(this.clone=r)}},e.AddItemAtIndexesDto=class{constructor(e,t,i,r){this.indexes=[0],this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.item=t),void 0!==i&&(this.indexes=i),void 0!==r&&(this.clone=r)}},e.AddItemsAtIndexesDto=class{constructor(e,t,i,r){this.indexes=[0],this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.items=t),void 0!==i&&(this.indexes=i),void 0!==r&&(this.clone=r)}},e.RemoveItemAtIndexDto=class{constructor(e,t,i){this.index=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.index=t),void 0!==i&&(this.clone=i)}},e.RemoveItemsAtIndexesDto=class{constructor(e,t,i){this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.indexes=t),void 0!==i&&(this.clone=i)}},e.RemoveNthItemDto=class{constructor(e,t,i,r){this.nth=2,this.offset=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.nth=t),void 0!==i&&(this.offset=i),void 0!==r&&(this.clone=r)}},e.RandomThresholdDto=class{constructor(e,t,i){this.threshold=1,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.threshold=t),void 0!==i&&(this.clone=i)}},e.RemoveDuplicatesDto=class{constructor(e,t){this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.clone=t)}},e.RemoveDuplicatesToleranceDto=class{constructor(e,t,i){this.tolerance=1e-7,this.clone=!0,void 0!==e&&(this.list=e),void 0!==i&&(this.tolerance=i),void 0!==t&&(this.clone=t)}},e.GetByPatternDto=class{constructor(e,t){this.pattern=[!0,!0,!1],void 0!==e&&(this.list=e),void 0!==t&&(this.pattern=t)}},e.GetNthItemDto=class{constructor(e,t,i,r){this.nth=2,this.offset=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.nth=t),void 0!==i&&(this.offset=i),void 0!==r&&(this.clone=r)}},e.GetLongestListLength=class{constructor(e){void 0!==e&&(this.lists=e)}},e.MergeElementsOfLists=class{constructor(e,t){this.level=0,void 0!==e&&(this.lists=e),void 0!==t&&(this.level=t)}},e.AddItemDto=class{constructor(e,t,i){this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.item=t),void 0!==i&&(this.clone=i)}},e.AddItemFirstLastDto=class{constructor(e,i,r,s){this.position=t.last,this.clone=!0,void 0!==e&&(this.list=e),void 0!==i&&(this.item=i),void 0!==r&&(this.position=r),void 0!==s&&(this.clone=s)}}}(bq||(bq={})),function(e){let t;!function(e){e.less="<",e.lessOrEqual="<=",e.greater=">",e.greaterOrEqual=">=",e.tripleEqual="===",e.tripleNotEqual="!==",e.equal="==",e.notEqual="!="}(t=e.BooleanOperatorsEnum||(e.BooleanOperatorsEnum={})),e.ComparisonDto=class{constructor(e,t,i){void 0!==e&&(this.first=e),void 0!==t&&(this.second=t),void 0!==i&&(this.operator=i)}},e.BooleanDto=class{constructor(e){this.boolean=!1,void 0!==e&&(this.boolean=e)}},e.BooleanListDto=class{constructor(e){void 0!==e&&(this.booleans=e)}},e.ValueGateDto=class{constructor(e,t){this.boolean=!1,void 0!==e&&(this.value=e),void 0!==t&&(this.boolean=t)}},e.TwoValueGateDto=class{constructor(e,t){void 0!==e&&(this.value1=e),void 0!==t&&(this.value2=t)}},e.RandomBooleansDto=class{constructor(e){this.length=10,this.trueThreshold=.5,void 0!==e&&(this.length=e)}},e.TwoThresholdRandomGradientDto=class{},e.ThresholdBooleanListDto=class{},e.ThresholdGapsBooleanListDto=class{}}(Sq||(Sq={})),function(e){let t,i,r;!function(e){e.add="add",e.subtract="subtract",e.multiply="multiply",e.divide="divide",e.power="power",e.modulus="modulus"}(t=e.mathTwoNrOperatorEnum||(e.mathTwoNrOperatorEnum={})),function(e){e.absolute="absolute",e.negate="negate",e.ln="ln",e.log10="log10",e.tenPow="tenPow",e.round="round",e.floor="floor",e.ceil="ceil",e.sqrt="sqrt",e.sin="sin",e.cos="cos",e.tan="tan",e.asin="asin",e.acos="acos",e.atan="atan",e.log="log",e.exp="exp",e.radToDeg="radToDeg",e.degToRad="degToRad"}(i=e.mathOneNrOperatorEnum||(e.mathOneNrOperatorEnum={})),function(e){e.easeInSine="easeInSine",e.easeOutSine="easeOutSine",e.easeInOutSine="easeInOutSine",e.easeInQuad="easeInQuad",e.easeOutQuad="easeOutQuad",e.easeInOutQuad="easeInOutQuad",e.easeInCubic="easeInCubic",e.easeOutCubic="easeOutCubic",e.easeInOutCubic="easeInOutCubic",e.easeInQuart="easeInQuart",e.easeOutQuart="easeOutQuart",e.easeInOutQuart="easeInOutQuart",e.easeInQuint="easeInQuint",e.easeOutQuint="easeOutQuint",e.easeInOutQuint="easeInOutQuint",e.easeInExpo="easeInExpo",e.easeOutExpo="easeOutExpo",e.easeInOutExpo="easeInOutExpo",e.easeInCirc="easeInCirc",e.easeOutCirc="easeOutCirc",e.easeInOutCirc="easeInOutCirc",e.easeInElastic="easeInElastic",e.easeOutElastic="easeOutElastic",e.easeInOutElastic="easeInOutElastic",e.easeInBack="easeInBack",e.easeOutBack="easeOutBack",e.easeInOutBack="easeInOutBack",e.easeInBounce="easeInBounce",e.easeOutBounce="easeOutBounce",e.easeInOutBounce="easeInOutBounce"}(r=e.easeEnum||(e.easeEnum={})),e.ModulusDto=class{constructor(e,t){this.number=1,this.modulus=2,void 0!==e&&(this.number=e),void 0!==t&&(this.modulus=t)}},e.NumberDto=class{constructor(e){this.number=1,void 0!==e&&(this.number=e)}},e.EaseDto=class{constructor(e){this.x=.5,this.min=0,this.max=1,void 0!==e&&(this.x=e)}},e.RoundToDecimalsDto=class{constructor(e,t){this.number=1.123456,this.decimalPlaces=2,void 0!==e&&(this.number=e),void 0!==t&&(this.decimalPlaces=t)}},e.ActionOnTwoNumbersDto=class{constructor(e,t,i){this.first=1,this.second=1,void 0!==e&&(this.first=e),void 0!==t&&(this.second=t),void 0!==i&&(this.operation=i)}},e.TwoNumbersDto=class{constructor(e,t){this.first=1,this.second=2,void 0!==e&&(this.first=e),void 0!==t&&(this.second=t)}},e.ActionOnOneNumberDto=class{constructor(e,t){this.number=1,void 0!==e&&(this.number=e),void 0!==t&&(this.operation=t)}},e.RemapNumberDto=class{constructor(e,t,i,r,s){this.number=.5,this.fromLow=0,this.fromHigh=1,this.toLow=1,this.toHigh=2,void 0!==e&&(this.number=e),void 0!==t&&(this.fromLow=t),void 0!==i&&(this.fromHigh=i),void 0!==r&&(this.toLow=r),void 0!==s&&(this.toHigh=s)}},e.RandomNumberDto=class{constructor(e,t){this.low=0,this.high=1,void 0!==e&&(this.low=e),void 0!==t&&(this.high=t)}},e.RandomNumbersDto=class{constructor(e,t,i){this.low=0,this.high=1,this.count=10,void 0!==e&&(this.low=e),void 0!==t&&(this.high=t),void 0!==i&&(this.count=i)}},e.ToFixedDto=class{constructor(e,t){this.decimalPlaces=2,void 0!==e&&(this.number=e),void 0!==t&&(this.decimalPlaces=t)}}}(Tq||(Tq={})),function(e){e.PointDto=class{constructor(e){void 0!==e&&(this.point=e)}},e.PointXYZDto=class{constructor(e,t,i){this.x=0,this.y=0,this.z=0,void 0!==e&&(this.x=e),void 0!==t&&(this.y=t),void 0!==i&&(this.z=i)}},e.PointXYDto=class{constructor(e,t){this.x=0,this.y=0,void 0!==e&&(this.x=e),void 0!==t&&(this.y=t)}},e.PointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.TwoPointsDto=class{constructor(e,t){void 0!==e&&(this.point1=e),void 0!==t&&(this.point2=t)}},e.DrawPointDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.size=3,this.colours="#444444",this.updatable=!1,void 0!==e&&(this.point=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.size=i),void 0!==r&&(this.colours=r),void 0!==s&&(this.updatable=s),void 0!==n&&(this.pointMesh=n)}},e.DrawPointsDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.size=.1,this.colours="#444444",this.updatable=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.size=i),void 0!==r&&(this.colours=r),void 0!==s&&(this.updatable=s),void 0!==n&&(this.pointsMesh=n)}},e.TransformPointDto=class{constructor(e,t){void 0!==e&&(this.point=e),void 0!==t&&(this.transformation=t)}},e.TransformPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.transformation=t)}},e.TranslatePointsWithVectorsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.translations=t)}},e.TranslatePointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.translation=t)}},e.TranslateXYZPointsDto=class{constructor(e,t,i,r){this.x=0,this.y=1,this.z=0,void 0!==e&&(this.points=e),void 0!==t&&(this.x=t),void 0!==i&&(this.y=i),void 0!==r&&(this.z=r)}},e.ScalePointsCenterXYZDto=class{constructor(e,t,i){this.center=[0,0,0],this.scaleXyz=[1,1,1],void 0!==e&&(this.points=e),void 0!==t&&(this.center=t),void 0!==i&&(this.scaleXyz=i)}},e.RotatePointsCenterAxisDto=class{constructor(e,t,i,r){this.angle=90,this.axis=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.points=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.axis=i),void 0!==r&&(this.center=r)}},e.TransformsForPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.transformation=t)}},e.RemoveConsecutiveDuplicatesDto=class{constructor(e,t,i){this.tolerance=1e-7,this.checkFirstAndLast=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.tolerance=t),void 0!==i&&(this.checkFirstAndLast=i)}},e.ClosestPointFromPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.point=t)}},e.StartEndPointsDto=class{constructor(e,t){void 0!==e&&(this.startPoint=e),void 0!==t&&(this.endPoint=t)}},e.StartEndPointsListDto=class{constructor(e,t){void 0!==e&&(this.startPoint=e),void 0!==t&&(this.endPoints=t)}},e.MultiplyPointDto=class{constructor(e,t){void 0!==e&&(this.point=e),void 0!==t&&(this.amountOfPoints=t)}},e.SpiralDto=class{constructor(e,t,i,r,s){this.phi=.9,this.numberPoints=200,this.widening=3,this.radius=6,this.factor=1,void 0!==e&&(this.radius=e),void 0!==t&&(this.numberPoints=t),void 0!==i&&(this.widening=i),void 0!==r&&(this.factor=r),void 0!==s&&(this.phi=s)}},e.HexGridCentersDto=class{constructor(e,t,i,r,s){this.nrHexagonsY=21,this.nrHexagonsX=21,this.orientOnCenter=!1,this.pointsOnGround=!1,void 0!==e&&(this.nrHexagonsX=e),void 0!==t&&(this.nrHexagonsY=t),void 0!==i&&(this.radiusHexagon=i),void 0!==r&&(this.orientOnCenter=r),void 0!==s&&(this.pointsOnGround=s)}}}(Cq||(Cq={})),function(e){e.TextDto=class{constructor(e){this.text="Hello World",void 0!==e&&(this.text=e)}},e.TextSplitDto=class{constructor(e,t){this.text="a,b,c",this.separator=",",void 0!==e&&(this.text=e),void 0!==t&&(this.separator=t)}},e.TextReplaceDto=class{constructor(e,t,i){this.text="a-c",this.search="-",this.replaceWith="b",void 0!==e&&(this.text=e),void 0!==t&&(this.search=t),void 0!==i&&(this.replaceWith=i)}},e.TextJoinDto=class{constructor(e,t){this.separator=",",void 0!==e&&(this.list=e),void 0!==t&&(this.separator=t)}},e.ToStringDto=class{constructor(e){void 0!==e&&(this.item=e)}},e.ToStringEachDto=class{constructor(e){void 0!==e&&(this.list=e)}},e.TextFormatDto=class{constructor(e,t){this.text="Hello {0}",this.values=["World"],void 0!==e&&(this.text=e),void 0!==t&&(this.values=t)}}}(yq||(yq={})),function(e){e.RotationCenterAxisDto=class{constructor(e,t,i){this.angle=90,this.axis=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.angle=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.center=i)}},e.RotationCenterDto=class{constructor(e,t){this.angle=90,this.center=[0,0,0],void 0!==e&&(this.angle=e),void 0!==t&&(this.center=t)}},e.RotationCenterYawPitchRollDto=class{constructor(e,t,i,r){this.yaw=0,this.pitch=0,this.roll=0,this.center=[0,0,0],void 0!==e&&(this.yaw=e),void 0!==t&&(this.pitch=t),void 0!==i&&(this.roll=i),void 0!==r&&(this.center=r)}},e.ScaleXYZDto=class{constructor(e){this.scaleXyz=[1,1,1],void 0!==e&&(this.scaleXyz=e)}},e.ScaleCenterXYZDto=class{constructor(e,t){this.center=[0,0,0],this.scaleXyz=[1,1,1],void 0!==e&&(this.center=e),void 0!==t&&(this.scaleXyz=t)}},e.UniformScaleDto=class{constructor(e){this.scale=1,void 0!==e&&(this.scale=e)}},e.UniformScaleFromCenterDto=class{constructor(e,t){this.scale=1,this.center=[0,0,0],void 0!==e&&(this.scale=e),void 0!==t&&(this.center=t)}},e.TranslationXYZDto=class{constructor(e){this.translation=[0,0,0],void 0!==e&&(this.translation=e)}},e.TranslationsXYZDto=class{constructor(e){void 0!==e&&(this.translations=e)}}}(Eq||(Eq={})),function(e){e.TwoVectorsDto=class{constructor(e,t){void 0!==e&&(this.first=e),void 0!==t&&(this.second=t)}},e.VectorBoolDto=class{constructor(e){void 0!==e&&(this.vector=e)}},e.RemoveAllDuplicateVectorsDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.vectors=e),void 0!==t&&(this.tolerance=t)}},e.RemoveConsecutiveDuplicateVectorsDto=class{constructor(e,t,i){this.checkFirstAndLast=!1,this.tolerance=1e-7,void 0!==e&&(this.vectors=e),void 0!==t&&(this.checkFirstAndLast=t),void 0!==i&&(this.tolerance=i)}},e.VectorDto=class{constructor(e){void 0!==e&&(this.vector=e)}},e.RangeMaxDto=class{constructor(e){void 0!==e&&(this.max=e)}},e.VectorXYZDto=class{constructor(e,t,i){void 0!==e&&(this.x=e),void 0!==t&&(this.y=t),void 0!==i&&(this.z=i)}},e.VectorXYDto=class{constructor(e,t){void 0!==e&&(this.x=e),void 0!==t&&(this.y=t)}},e.SpanDto=class{constructor(e,t,i){this.step=.1,this.min=0,this.max=1,void 0!==e&&(this.step=e),void 0!==t&&(this.min=t),void 0!==i&&(this.max=i)}},e.SpanEaseItemsDto=class{constructor(e,t,i,r){this.nrItems=100,this.min=0,this.max=1,this.ease=Tq.easeEnum.easeInSine,this.intervals=!1,void 0!==e&&(this.nrItems=e),void 0!==t&&(this.min=t),void 0!==i&&(this.max=i),void 0!==r&&(this.ease=r)}},e.SpanLinearItemsDto=class{constructor(e,t,i){this.nrItems=100,this.min=0,this.max=1,void 0!==e&&(this.nrItems=e),void 0!==t&&(this.min=t),void 0!==i&&(this.max=i)}},e.RayPointDto=class{constructor(e,t,i){void 0!==e&&(this.point=e),void 0!==t&&(this.distance=t),void 0!==i&&(this.vector=i)}},e.VectorsDto=class{constructor(e){void 0!==e&&(this.vectors=e)}},e.FractionTwoVectorsDto=class{constructor(e,t,i){this.fraction=.5,void 0!==e&&(this.fraction=e),void 0!==t&&(this.first=t),void 0!==i&&(this.second=i)}},e.VectorScalarDto=class{constructor(e,t){void 0!==e&&(this.scalar=e),void 0!==t&&(this.vector=t)}},e.TwoVectorsReferenceDto=class{constructor(e,t,i){void 0!==e&&(this.reference=e),void 0!==t&&(this.first=t),void 0!==i&&(this.second=i)}}}(Pq||(Pq={}));var Mq=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class Oq extends vq{constructor(e,t,i,r,s,n){super(i),this.context=e,this.solidText=t,this.vector=i,this.jscadWorkerManager=r,this.manifoldWorkerManager=s,this.occWorkerManager=n,this.usedMaterials=[]}createOrUpdateSurfacesMesh(e,t,i,r,s,n){const o=()=>{const r=e.pop(),s=new bt;s.positions=r.positions,s.indices=r.indices,s.normals=r.normals,s.uvs=r.uvs;const n=[];e.forEach((e=>{const t=new bt;t.positions=e.positions,t.indices=e.indices,t.normals=e.normals,e.uvs&&(t.uvs=e.uvs),n.push(t)})),s.merge(n),s.applyToMesh(t,i)};if(t&&i)t.dispose(),o(),t.flipFaces(!1);else{let e=null;s&&(e=this.context.scene),t=new Yt(`surface${Math.random()}`,e),o(),t.flipFaces(!1),r&&(t.material=r)}return r&&(t.material=r),n&&(t.isVisible=!1),t.isPickable=!1,t}edgesRendering(e,t,i,r){e.enableEdgesRendering(),e.edgesWidth=t;const s=Array.isArray(r)?hc.v9.FromHexString(r[0]):hc.v9.FromHexString(r);e.color=s,e.edgesColor=new hc.ov(s.r,s.g,s.b,i)}drawLines(e){const t=[],i=[];return e.lines.forEach(((r,s)=>{let n;t.push([new hc.Pq(r.start[0],r.start[1],r.start[2]),new hc.Pq(r.end[0],r.end[1],r.end[2])]),n=Array.isArray(e.colours)&&e.colours.length===e.lines.length?hc.v9.FromHexString(e.colours[s]):Array.isArray(e.colours)?hc.v9.FromHexString(e.colours[0]):hc.v9.FromHexString(e.colours),i.push([new hc.ov(n.r,n.g,n.b,e.opacity),new hc.ov(n.r,n.g,n.b,e.opacity)])})),e.linesMesh&&e.updatable?e.linesMesh.getTotalVertices()/2===t.length?e.linesMesh=bl.CreateLineSystem(null,{lines:t,instance:e.linesMesh,colors:i,useVertexAlpha:!0,updatable:e.updatable},null):(e.linesMesh.dispose(),e.linesMesh=this.createLineSystemMesh(e.updatable,t,i)):e.linesMesh=this.createLineSystemMesh(e.updatable,t,i),this.edgesRendering(e.linesMesh,e.size,e.opacity,e.colours),e.linesMesh}drawPolylineClose(e){const t=e.polyline.points;return e.polyline.isClosed&&t.push(t[0]),this.drawPolyline(e.polylineMesh,t,e.updatable,e.size,e.opacity,e.colours)}drawCurve(e){const t=e.curve.tessellate();return this.drawPolyline(e.curveMesh,t,e.updatable,e.size,e.opacity,e.colours)}drawSurface(e){const t=e.surface.tessellate(),i={positions:[],indices:[],normals:[]};let r=0;t.faces.forEach((e=>{r=this.parseFaces(e,t,i,r)}));const s=new Cb("pbr"+Math.random(),this.context.scene);return s.baseColor=hc.v9.FromHexString(Array.isArray(e.colours)?e.colours[0]:e.colours),s.metallic=1,s.roughness=.6,s.alpha=e.opacity,s.alphaMode=1,s.backFaceCulling=!1,s.doubleSided=!0,this.createOrUpdateSurfacesMesh([i],e.surfaceMesh,e.updatable,s,!0,e.hidden)}drawSurfaces(e){const t=[];e.surfaces.forEach((e=>{t.push(e.tessellate())}));const i={positions:[],indices:[],normals:[]};let r=0;t.forEach((e=>{e.faces.forEach((t=>{r=this.parseFaces(t,e,i,r)}))}));const s=new Cb("pbr"+Math.random(),this.context.scene);return s.baseColor=hc.v9.FromHexString(Array.isArray(e.colours)?e.colours[0]:e.colours),s.metallic=1,s.roughness=.6,s.alpha=e.opacity,s.alphaMode=1,s.backFaceCulling=!0,s.doubleSided=!1,this.createOrUpdateSurfacesMesh([i],e.surfacesMesh,e.updatable,s,!0,e.hidden)}drawSurfacesMultiColour(e){return e.surfacesMesh&&e.updatable&&e.surfacesMesh.getChildren().forEach((e=>e.dispose())),e.surfacesMesh=new Yt(`ColouredSurfaces${Math.random()}`,this.context.scene),Array.isArray(e.colours)?e.surfaces.forEach(((t,i)=>{const r=this.drawSurface({surface:t,colours:e.colours[i]?e.colours[i]:e.colours[0],updatable:e.updatable,opacity:e.opacity,hidden:e.hidden});e.surfacesMesh.addChild(r)})):e.surfaces.forEach(((t,i)=>{const r=this.drawSurface({surface:t,colours:e.colours,updatable:e.updatable,opacity:e.opacity,hidden:e.hidden});e.surfacesMesh.addChild(r)})),e.surfacesMesh}drawCurves(e){const t=e.curves.map((e=>e.tessellate()));return this.drawPolylines(e.curvesMesh,t,e.updatable,e.size,e.opacity,e.colours)}drawPolyline(e,t,i,r,s,n){return this.drawPolylines(e,[t],i,r,s,n)}drawPolylinesWithColours(e){let t=e.colours;const i=e.polylines.map(((e,i)=>{const r=e.points;return e.isClosed&&r.push(r[0]),e.color&&(Array.isArray(t)||(t=[]),Array.isArray(e.color)?t[i]=hc.v9.FromArray(e.color).toHexString():t[i]=e.color),r}));return this.drawPolylines(e.polylinesMesh,i,e.updatable,e.size,e.opacity,t)}drawPolylines(e,t,i,r,s,n){var o;const a=[];if(t&&t.length>0){t.forEach((e=>{const t=e.map((e=>2===e.length?[e[0],e[1],0]:e));a.push(t.flat())}));const l=r/100,h=Array.isArray(n)?hc.v9.FromHexString(n[0]):hc.v9.FromHexString(n);if(e&&i){if(!(null===(o=null==e?void 0:e.metadata)||void 0===o?void 0:o.linesForRenderLengths.some(((e,t)=>e!==a[t].length))))return e.setPoints(a),e;e.dispose(),(e=this.createGreasedPolylines(i,a,l,h,s)).metadata={linesForRenderLengths:a.map((e=>e.length))}}else(e=this.createGreasedPolylines(i,a,l,h,s)).metadata={linesForRenderLengths:a.map((e=>e.length))};return e}}createGreasedPolylines(e,t,i,r,s){const n=ME(`lineSystem${Math.random()}`,{points:t,updatable:e},{width:i,color:r},this.context.scene);return n.material.alpha=s,n}localAxes(e,t,i,r,s){const n=bl.CreateLines("pilot_local_axisX"+Math.random(),{points:[hc.Pq.Zero(),new hc.Pq(e,0,0),new hc.Pq(.95*e,.05*e,0),new hc.Pq(e,0,0),new hc.Pq(.95*e,-.05*e,0)]},t),o=hc.v9.FromHexString(i);n.color=o;const a=bl.CreateLines("pilot_local_axisY"+Math.random(),{points:[hc.Pq.Zero(),new hc.Pq(0,e,0),new hc.Pq(-.05*e,.95*e,0),new hc.Pq(0,e,0),new hc.Pq(.05*e,.95*e,0)]},t),l=hc.v9.FromHexString(r);a.color=l;const h=bl.CreateLines("pilot_local_axisZ"+Math.random(),{points:[hc.Pq.Zero(),new hc.Pq(0,0,e),new hc.Pq(0,-.05*e,.95*e),new hc.Pq(0,0,e),new hc.Pq(0,.05*e,.95*e)]},t),c=hc.v9.FromHexString(s);h.color=c;const u=new Yt("local_origin"+Math.random(),t);return u.isVisible=!1,n.parent=u,a.parent=u,h.parent=u,u}drawPoint(e){const t=[e.point];let i=[];return i=Array.isArray(e.colours)?e.colours:[e.colours],e.pointMesh&&e.updatable?this.updatePointsInstances(e.pointMesh,t):e.pointMesh=this.createPointSpheresMesh(`poinsMesh${Math.random()}`,t,i,e.opacity,e.size,e.updatable),e.pointMesh}drawPoints(e){const t=e.points;let i=[];return Array.isArray(e.colours)?(i=e.colours,1===i.length&&(i=e.points.map((()=>i[0])))):i=e.points.map((()=>e.colours)),e.pointsMesh&&e.updatable?e.pointsMesh.getChildMeshes().length===t.length?this.updatePointsInstances(e.pointsMesh,t):(e.pointsMesh.dispose(),e.pointsMesh=this.createPointSpheresMesh(`pointsMesh${Math.random()}`,t,i,e.opacity,e.size,e.updatable)):e.pointsMesh=this.createPointSpheresMesh(`pointsMesh${Math.random()}`,t,i,e.opacity,e.size,e.updatable),e.pointsMesh}updatePointsInstances(e,t){const i=e.getChildMeshes(),r={};t.forEach(((e,t)=>{r[t]=new hc.Pq(e[0],e[1],e[2])})),i.forEach((e=>{e.position=r[e.metadata.index]}))}createPointSpheresMesh(e,t,i,r,s,n){const o=t.map(((e,t)=>({position:e,color:i[t],index:t}))),a=Array.from(new Set(i)),l=a.map(((e,t)=>{const i=new Un(`mat${Math.random()}`,this.context.scene);i.disableLighting=!0,i.emissiveColor=hc.v9.FromHexString(e),i.alpha=r;const s=o.filter((t=>t.color===e));return{hex:a,material:i,positions:s}})),h=new Yt(e,this.context.scene);return l.forEach((e=>{const t=e.positions.length>1e3?1:6;let i;i=e.positions.length<1e4?bl.CreateSphere(`point${Math.random()}`,{diameter:s,segments:t,updatable:n},this.context.scene):bl.CreateBox(`point${Math.random()}`,{size:s,updatable:n},this.context.scene),i.material=e.material,i.isVisible=!1,e.positions.forEach(((e,t)=>{const r=i.createInstance(`point-${t}-${Math.random()}`);r.position=new hc.Pq(e.position[0],e.position[1],e.position[2]),r.metadata={index:e.index},r.parent=h,r.isVisible=!0}))})),h}drawSolidOrPolygonMesh(e){return Mq(this,void 0,void 0,(function*(){const t=yield this.jscadWorkerManager.genericCallToWorkerPromise("shapeToMesh",e);let i,r;i=e.jscadMesh&&e.updatable?e.jscadMesh:new Yt(`jscadMesh${Math.random()}`,this.context.scene),r=e.mesh.color&&e.mesh.color.length>0?hc.v9.FromArray(e.mesh.color).toHexString():Array.isArray(e.colours)?e.colours[0]:e.colours;const s=this.makeMesh(Object.assign(Object.assign({},e),{colour:r}),i,t);return e.jscadMesh=s,s}))}makeMesh(e,t,i){this.createMesh(i.positions,i.indices,i.normals,t,i.transforms,e.updatable),t.material=new Cb(`jscadMaterial${Math.random()}`,this.context.scene),t.flipFaces(!1);const r=t.material;return r.baseColor=hc.v9.FromHexString(e.colour),r.metallic=1,r.roughness=.6,r.alpha=e.opacity,r.alphaMode=1,r.backFaceCulling=!0,r.zOffset=0,t.isPickable=!1,e.hidden&&(t.isVisible=!1),t}drawSolidOrPolygonMeshes(e){return Mq(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapesToMeshes",e).then((t=>{let i;e.jscadMesh&&e.updatable?(i=e.jscadMesh,i.getChildMeshes().forEach((e=>{e.dispose(),i.removeChild(e)}))):i=new Yt("local_origin"+Math.random(),this.context.scene),i.isVisible=!1;const r=Array.isArray(e.colours)&&e.colours.length===t.length,s=Array.isArray(e.colours);return t.map(((t,n)=>{const o=new Yt(`jscadMesh${Math.random()}`,this.context.scene);let a;a=t.color?hc.v9.FromArray(t.color).toHexString():r?e.colours[n]:s?e.colours[0]:e.colours,this.makeMesh(Object.assign(Object.assign({},e),{colour:a}),o,t).parent=i})),e.jscadMesh=i,i}))}))}drawPath(e){return Mq(this,void 0,void 0,(function*(){return new Promise((t=>{if(e.path.points&&e.path.isClosed){const t=e.path.points[0];e.path.points.push([t[0],0,t[1]])}let i=e.colour;e.path.color&&(i=hc.v9.FromArray(e.path.color).toHexString()),t(this.drawPolyline(e.pathMesh,e.path.points,e.updatable,e.width,e.opacity,i))}))}))}drawManifoldsOrCrossSections(e){return Mq(this,void 0,void 0,(function*(){const t=(yield this.manifoldWorkerManager.genericCallToWorkerPromise("decomposeManifoldsOrCrossSections",e)).map((t=>this.handleDecomposedManifold(e,t))),i=new Yt("manifoldMeshContainer"+Math.random(),this.context.scene);return t.forEach((e=>{e.parent=i})),i}))}drawManifoldOrCrossSection(e){return Mq(this,void 0,void 0,(function*(){const t=yield this.manifoldWorkerManager.genericCallToWorkerPromise("decomposeManifoldOrCrossSection",e);return this.handleDecomposedManifold(e,t)}))}drawShape(e){return Mq(this,void 0,void 0,(function*(){const t=Object.assign({},e);e.faceMaterial&&delete e.faceMaterial;const i=yield this.occWorkerManager.genericCallToWorkerPromise("shapeToMesh",e);return this.handleDecomposedMesh(e,i,t)}))}drawShapes(e){return Mq(this,void 0,void 0,(function*(){const t=Object.assign({},e);e.faceMaterial&&delete e.faceMaterial;const i=yield this.occWorkerManager.genericCallToWorkerPromise("shapesToMeshes",e),r=yield Promise.all(i.map((i=>Mq(this,void 0,void 0,(function*(){return this.handleDecomposedMesh(e,i,t)}))))),s=new Yt("shapesMeshContainer"+Math.random(),this.context.scene);return r.forEach((e=>{e.parent=s})),s}))}handleDecomposedMesh(e,t,i){return Mq(this,void 0,void 0,(function*(){const r=new Yt("brepMesh"+Math.random(),this.context.scene);let s;if(r.isVisible=!1,e.drawFaces&&t&&t.faceList&&t.faceList.length){let n;if(i.faceMaterial)n=i.faceMaterial;else{const t=Array.isArray(e.faceColour)?e.faceColour[0]:e.faceColour,i=e.faceOpacity,r=e.drawEdges?2:0,s=this.usedMaterials.find((e=>e.sceneId===this.context.scene.uid&&e.hex===t&&e.alpha===i&&e.zOffset===r));if(this.usedMaterials=this.usedMaterials.filter((e=>e.sceneId===this.context.scene.uid)),s)n=s.material;else{const e=new Cb("pbr"+Math.random(),this.context.scene);e.baseColor=hc.v9.FromHexString(t),e.metallic=1,e.roughness=.6,e.alpha=i,e.alphaMode=1,e.backFaceCulling=!0,e.doubleSided=!1,e.zOffset=r,this.usedMaterials.push({sceneId:this.context.scene.uid,hex:t,alpha:i,zOffset:r,material:e}),n=e}}const o=t.faceList.map((e=>({positions:e.vertex_coord,normals:e.normal_coord,indices:e.tri_indexes,uvs:e.uvs})));this.createOrUpdateSurfacesMesh(o,s,!1,n,!0,!1).parent=r}if(e.drawEdges&&t&&t.edgeList&&t.edgeList.length){const i=[];t.edgeList.forEach((e=>{const t=e.vertex_coord.filter((e=>void 0!==e));i.push(t)})),this.drawPolylines(s,i,!1,e.edgeWidth,e.edgeOpacity,e.edgeColour).parent=r}if(e.drawVertices&&t&&t.pointsList&&t.pointsList.length&&(this.drawPoints({pointsMesh:s,points:t.pointsList,opacity:1,size:e.vertexSize,colours:e.vertexColour,updatable:!1}).parent=r),e.drawEdgeIndexes){const i=t.edgeList.map((t=>Mq(this,void 0,void 0,(function*(){let i=t.middle_point;void 0===i&&(i=this.computeEdgeMiddlePos(t));const r=new nX.TextDto;return r.text=`${t.edge_index+1}`,r.height=e.edgeIndexHeight,r.lineSpacing=1.5,(yield this.solidText.createVectorText(r)).map((e=>e.map((e=>[e[0],e[1]+.05,0])).map((e=>this.vector.add({first:e,second:i})))))})))),s=yield Promise.all(i),n=this.drawPolylines(null,s.flat(),!1,.2,1,e.edgeIndexColour);n.parent=r,n.material.zOffset=-2}if(e.drawFaceIndexes){const i=t.faceList.map((t=>Mq(this,void 0,void 0,(function*(){let i=t.center_point;void 0===i&&(i=this.computeFaceMiddlePos(t.vertex_coord_vec));const r=new nX.TextDto;return r.text=`${t.face_index}`,r.height=e.faceIndexHeight,r.lineSpacing=1.5,(yield this.solidText.createVectorText(r)).map((e=>e.map((e=>[e[0],e[1]+.05,0])).map((e=>this.vector.add({first:e,second:i})))))})))),s=yield Promise.all(i),n=this.drawPolylines(null,s.flat(),!1,.2,1,e.faceIndexColour);n.parent=r,e.drawEdges&&(n.material.zOffset=-2)}return r}))}handleDecomposedManifold(e,t){if(t.vertProperties){const i=t,r=new Yt(`manifoldMesh-${Math.random()}`,this.context.scene),s=new bt;s.indices=i.triVerts.length>65535?new Uint32Array(i.triVerts):new Uint16Array(i.triVerts);for(let e=0;e({points:e.map((e=>[e[0],e[1],0])),isClosed:!0})));return this.drawPolylinesWithColours({polylinesMesh:void 0,polylines:r,updatable:!1,size:e.crossSectionWidth,opacity:e.crossSectionOpacity,colours:e.crossSectionColour}).parent=i,i}}createLineSystemMesh(e,t,i){return bl.CreateLineSystem(`lines${Math.random()}`,{lines:t,colors:i,useVertexAlpha:!0,updatable:e},this.context.scene)}createMesh(e,t,i,r,s,n){const o=new bt;o.positions=e,o.indices=t,bt.ComputeNormals(e,t,i,{useRightHandedSystem:!0}),o.normals=i,o.applyToMesh(r,n),r.setPreTransformMatrix(hc.uq.FromArray(s))}parseFaces(e,t,i,r){return e.reverse().forEach((e=>{const s=t.normals[e];i.normals.push(s[0],s[1],s[2]);const n=t.points[e];i.positions.push(n[0],n[1],n[2]),i.indices.push(r),r++})),r}}class Dq{static get version(){return"1.3.9"}static toString(){return"JavaScript Expression Parser (JSEP) v"+Dq.version}static addUnaryOp(e){return Dq.max_unop_len=Math.max(e.length,Dq.max_unop_len),Dq.unary_ops[e]=1,Dq}static addBinaryOp(e,t,i){return Dq.max_binop_len=Math.max(e.length,Dq.max_binop_len),Dq.binary_ops[e]=t,i?Dq.right_associative.add(e):Dq.right_associative.delete(e),Dq}static addIdentifierChar(e){return Dq.additional_identifier_chars.add(e),Dq}static addLiteral(e,t){return Dq.literals[e]=t,Dq}static removeUnaryOp(e){return delete Dq.unary_ops[e],e.length===Dq.max_unop_len&&(Dq.max_unop_len=Dq.getMaxKeyLen(Dq.unary_ops)),Dq}static removeAllUnaryOps(){return Dq.unary_ops={},Dq.max_unop_len=0,Dq}static removeIdentifierChar(e){return Dq.additional_identifier_chars.delete(e),Dq}static removeBinaryOp(e){return delete Dq.binary_ops[e],e.length===Dq.max_binop_len&&(Dq.max_binop_len=Dq.getMaxKeyLen(Dq.binary_ops)),Dq.right_associative.delete(e),Dq}static removeAllBinaryOps(){return Dq.binary_ops={},Dq.max_binop_len=0,Dq}static removeLiteral(e){return delete Dq.literals[e],Dq}static removeAllLiterals(){return Dq.literals={},Dq}get char(){return this.expr.charAt(this.index)}get code(){return this.expr.charCodeAt(this.index)}constructor(e){this.expr=e,this.index=0}static parse(e){return new Dq(e).parse()}static getMaxKeyLen(e){return Math.max(0,...Object.keys(e).map((e=>e.length)))}static isDecimalDigit(e){return e>=48&&e<=57}static binaryPrecedence(e){return Dq.binary_ops[e]||0}static isIdentifierStart(e){return e>=65&&e<=90||e>=97&&e<=122||e>=128&&!Dq.binary_ops[String.fromCharCode(e)]||Dq.additional_identifier_chars.has(String.fromCharCode(e))}static isIdentifierPart(e){return Dq.isIdentifierStart(e)||Dq.isDecimalDigit(e)}throwError(e){const t=new Error(e+" at character "+this.index);throw t.index=this.index,t.description=e,t}runHook(e,t){if(Dq.hooks[e]){const i={context:this,node:t};return Dq.hooks.run(e,i),i.node}return t}searchHook(e){if(Dq.hooks[e]){const t={context:this};return Dq.hooks[e].find((function(e){return e.call(t.context,t),t.node})),t.node}}gobbleSpaces(){let e=this.code;for(;e===Dq.SPACE_CODE||e===Dq.TAB_CODE||e===Dq.LF_CODE||e===Dq.CR_CODE;)e=this.expr.charCodeAt(++this.index);this.runHook("gobble-spaces")}parse(){this.runHook("before-all");const e=this.gobbleExpressions(),t=1===e.length?e[0]:{type:Dq.COMPOUND,body:e};return this.runHook("after-all",t)}gobbleExpressions(e){let t,i,r=[];for(;this.index0;){if(Dq.binary_ops.hasOwnProperty(e)&&(!Dq.isIdentifierStart(this.code)||this.index+e.lengths.right_a&&e.right_a?i>e.prec:i<=e.prec;for(;r.length>2&&a(r[r.length-2]);)o=r.pop(),t=r.pop().value,n=r.pop(),e={type:Dq.BINARY_EXP,operator:t,left:n,right:o},r.push(e);e=this.gobbleToken(),e||this.throwError("Expected expression after "+l),r.push(s,e)}for(a=r.length-1,e=r[a];a>1;)e={type:Dq.BINARY_EXP,operator:r[a-1].value,left:r[a-2],right:e},a-=2;return e}gobbleToken(){let e,t,i,r;if(this.gobbleSpaces(),r=this.searchHook("gobble-token"),r)return this.runHook("after-token",r);if(e=this.code,Dq.isDecimalDigit(e)||e===Dq.PERIOD_CODE)return this.gobbleNumericLiteral();if(e===Dq.SQUOTE_CODE||e===Dq.DQUOTE_CODE)r=this.gobbleStringLiteral();else if(e===Dq.OBRACK_CODE)r=this.gobbleArray();else{for(t=this.expr.substr(this.index,Dq.max_unop_len),i=t.length;i>0;){if(Dq.unary_ops.hasOwnProperty(t)&&(!Dq.isIdentifierStart(this.code)||this.index+t.length=t.length&&this.throwError("Unexpected token "+String.fromCharCode(e));break}if(s===Dq.COMMA_CODE){if(this.index++,r++,r!==t.length)if(e===Dq.CPAREN_CODE)this.throwError("Unexpected token ,");else if(e===Dq.CBRACK_CODE)for(let e=t.length;e{if("object"!=typeof e||!e.name||!e.init)throw new Error("Invalid JSEP plugin format");this.registered[e.name]||(e.init(this.jsep),this.registered[e.name]=e)}))}}(Dq),COMPOUND:"Compound",SEQUENCE_EXP:"SequenceExpression",IDENTIFIER:"Identifier",MEMBER_EXP:"MemberExpression",LITERAL:"Literal",THIS_EXP:"ThisExpression",CALL_EXP:"CallExpression",UNARY_EXP:"UnaryExpression",BINARY_EXP:"BinaryExpression",ARRAY_EXP:"ArrayExpression",TAB_CODE:9,LF_CODE:10,CR_CODE:13,SPACE_CODE:32,PERIOD_CODE:46,COMMA_CODE:44,SQUOTE_CODE:39,DQUOTE_CODE:34,OPAREN_CODE:40,CPAREN_CODE:41,OBRACK_CODE:91,CBRACK_CODE:93,QUMARK_CODE:63,SEMCOL_CODE:59,COLON_CODE:58,unary_ops:{"-":1,"!":1,"~":1,"+":1},binary_ops:{"||":1,"&&":2,"|":3,"^":4,"&":5,"==":6,"!=":6,"===":6,"!==":6,"<":7,">":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":10,"/":10,"%":10},right_associative:new Set,additional_identifier_chars:new Set(["$","_"]),literals:{true:!0,false:!1,null:null},this_str:"this"}),Dq.max_unop_len=Dq.getMaxKeyLen(Dq.unary_ops),Dq.max_binop_len=Dq.getMaxKeyLen(Dq.binary_ops);const Nq=e=>new Dq(e).parse(),Fq=Object.getOwnPropertyNames(class{});Object.getOwnPropertyNames(Dq).filter((e=>!Fq.includes(e)&&void 0===Nq[e])).forEach((e=>{Nq[e]=Dq[e]})),Nq.Jsep=Dq;var Lq={name:"ternary",init(e){e.hooks.add("after-expression",(function(t){if(t.node&&this.code===e.QUMARK_CODE){this.index++;const i=t.node,r=this.gobbleExpression();if(r||this.throwError("Expected expression"),this.gobbleSpaces(),this.code===e.COLON_CODE){this.index++;const s=this.gobbleExpression();if(s||this.throwError("Expected expression"),t.node={type:"ConditionalExpression",test:i,consequent:r,alternate:s},i.operator&&e.binary_ops[i.operator]<=.9){let r=i;for(;r.right.operator&&e.binary_ops[r.right.operator]<=.9;)r=r.right;t.node.test=r.right,r.right=t.node,t.node=i}}else this.throwError("Expected :")}}))}};Nq.plugins.register(Lq);var Bq={name:"regex",init(e){e.hooks.add("gobble-token",(function(t){if(47===this.code){const i=++this.index;let r=!1;for(;this.index=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57))break;n+=this.char}try{s=new RegExp(r,n)}catch(e){this.throwError(e.message)}return t.node={type:e.LITERAL,value:s,raw:this.expr.slice(i-1,this.index)},t.node=this.gobbleTokenProperty(t.node),t.node}this.code===e.OBRACK_CODE?r=!0:r&&this.code===e.CBRACK_CODE&&(r=!1),this.index+=92===this.code?2:1}this.throwError("Unclosed Regex")}}))}};const Vq={name:"assignment",assignmentOperators:new Set(["=","*=","**=","/=","%=","+=","-=","<<=",">>=",">>>=","&=","^=","|="]),updateOperators:[43,45],assignmentPrecedence:.9,init(e){const t=[e.IDENTIFIER,e.MEMBER_EXP];function i(e){Vq.assignmentOperators.has(e.operator)?(e.type="AssignmentExpression",i(e.left),i(e.right)):e.operator||Object.values(e).forEach((e=>{e&&"object"==typeof e&&i(e)}))}Vq.assignmentOperators.forEach((t=>e.addBinaryOp(t,Vq.assignmentPrecedence,!0))),e.hooks.add("gobble-token",(function(e){const i=this.code;Vq.updateOperators.some((e=>e===i&&e===this.expr.charCodeAt(this.index+1)))&&(this.index+=2,e.node={type:"UpdateExpression",operator:43===i?"++":"--",argument:this.gobbleTokenProperty(this.gobbleIdentifier()),prefix:!0},e.node.argument&&t.includes(e.node.argument.type)||this.throwError(`Unexpected ${e.node.operator}`))})),e.hooks.add("after-token",(function(e){if(e.node){const i=this.code;Vq.updateOperators.some((e=>e===i&&e===this.expr.charCodeAt(this.index+1)))&&(t.includes(e.node.type)||this.throwError(`Unexpected ${e.node.operator}`),this.index+=2,e.node={type:"UpdateExpression",operator:43===i?"++":"--",argument:e.node,prefix:!1})}})),e.hooks.add("after-expression",(function(e){e.node&&i(e.node)}))}};Nq.plugins.register(Bq,Vq),Nq.addUnaryOp("typeof"),Nq.addLiteral("null",null),Nq.addLiteral("undefined",void 0);const kq={evalAst(e,t){switch(e.type){case"BinaryExpression":case"LogicalExpression":return kq.evalBinaryExpression(e,t);case"Compound":return kq.evalCompound(e,t);case"ConditionalExpression":return kq.evalConditionalExpression(e,t);case"Identifier":return kq.evalIdentifier(e,t);case"Literal":return kq.evalLiteral(e,t);case"MemberExpression":return kq.evalMemberExpression(e,t);case"UnaryExpression":return kq.evalUnaryExpression(e,t);case"ArrayExpression":return kq.evalArrayExpression(e,t);case"CallExpression":return kq.evalCallExpression(e,t);case"AssignmentExpression":return kq.evalAssignmentExpression(e,t);default:throw SyntaxError("Unexpected expression",e)}},evalBinaryExpression:(e,t)=>({"||":(e,t)=>e||t(),"&&":(e,t)=>e&&t(),"|":(e,t)=>e|t(),"^":(e,t)=>e^t(),"&":(e,t)=>e&t(),"==":(e,t)=>e==t(),"!=":(e,t)=>e!=t(),"===":(e,t)=>e===t(),"!==":(e,t)=>e!==t(),"<":(e,t)=>e":(e,t)=>e>t(),"<=":(e,t)=>e<=t(),">=":(e,t)=>e>=t(),"<<":(e,t)=>e<>":(e,t)=>e>>t(),">>>":(e,t)=>e>>>t(),"+":(e,t)=>e+t(),"-":(e,t)=>e-t(),"*":(e,t)=>e*t(),"/":(e,t)=>e/t(),"%":(e,t)=>e%t()}[e.operator](kq.evalAst(e.left,t),(()=>kq.evalAst(e.right,t)))),evalCompound(e,t){let i;for(let r=0;rkq.evalAst(e.test,t)?kq.evalAst(e.consequent,t):kq.evalAst(e.alternate,t),evalIdentifier(e,t){if(e.name in t)return t[e.name];throw ReferenceError(`${e.name} is not defined`)},evalLiteral:e=>e.value,evalMemberExpression(e,t){if("Identifier"===e.property.type&&"constructor"===e.property.name||"Identifier"===e.object.type&&"constructor"===e.object.name)throw new Error("'constructor' property is disabled");const i=e.computed?kq.evalAst(e.property):e.property.name,r=kq.evalAst(e.object,t),s=r[i];if("function"==typeof s){if(r===Function&&"bind"===i)throw new Error("Function.prototype.bind is disabled");if(r===Function&&("call"===i||"apply"===i))throw new Error("Function.prototype.call and Function.prototype.apply are disabled");return s===Function?s:s.bind(r)}return s},evalUnaryExpression:(e,t)=>({"-":e=>-kq.evalAst(e,t),"!":e=>!kq.evalAst(e,t),"~":e=>~kq.evalAst(e,t),"+":e=>+kq.evalAst(e,t),typeof:e=>typeof kq.evalAst(e,t)}[e.operator](e.argument)),evalArrayExpression:(e,t)=>e.elements.map((e=>kq.evalAst(e,t))),evalCallExpression(e,t){const i=e.arguments.map((e=>kq.evalAst(e,t))),r=kq.evalAst(e.callee,t);if(r===Function)throw new Error("Function constructor is disabled");return r(...i)},evalAssignmentExpression(e,t){if("Identifier"!==e.left.type)throw SyntaxError("Invalid left-hand side in assignment");const i=e.left.name;if("__proto__"===i)throw new Error("Assignment to __proto__ is disabled");const r=kq.evalAst(e.right,t);return t[i]=r,t[i]}};function Uq(e,t){return(e=e.slice()).push(t),e}function Gq(e,t){return(t=t.slice()).unshift(e),t}class zq extends Error{constructor(e){super('JSONPath should not be called with "new" (it prevents return of (unwrapped) scalar values)'),this.avoidNew=!0,this.value=e,this.name="NewError"}}function Wq(e,t,i,r,s){if(!(this instanceof Wq))try{return new Wq(e,t,i,r,s)}catch(e){if(!e.avoidNew)throw e;return e.value}"string"==typeof e&&(s=r,r=i,i=t,t=e,e=null);const n=e&&"object"==typeof e;if(e=e||{},this.json=e.json||i,this.path=e.path||t,this.resultType=e.resultType||"value",this.flatten=e.flatten||!1,this.wrap=!Object.hasOwn(e,"wrap")||e.wrap,this.sandbox=e.sandbox||{},this.eval=void 0===e.eval?"safe":e.eval,this.ignoreEvalErrors=void 0!==e.ignoreEvalErrors&&e.ignoreEvalErrors,this.parent=e.parent||null,this.parentProperty=e.parentProperty||null,this.callback=e.callback||r||null,this.otherTypeCallback=e.otherTypeCallback||s||function(){throw new TypeError("You must supply an otherTypeCallback callback option with the @other() operator.")},!1!==e.autostart){const r={path:n?e.path:t};n?"json"in e&&(r.json=e.json):r.json=i;const s=this.evaluate(r);if(!s||"object"!=typeof s)throw new zq(s);return s}}Wq.prototype.evaluate=function(e,t,i,r){let s=this.parent,n=this.parentProperty,{flatten:o,wrap:a}=this;if(this.currResultType=this.resultType,this.currEval=this.eval,this.currSandbox=this.sandbox,i=i||this.callback,this.currOtherTypeCallback=r||this.otherTypeCallback,t=t||this.json,(e=e||this.path)&&"object"==typeof e&&!Array.isArray(e)){if(!e.path&&""!==e.path)throw new TypeError('You must supply a "path" property when providing an object argument to JSONPath.evaluate().');if(!Object.hasOwn(e,"json"))throw new TypeError('You must supply a "json" property when providing an object argument to JSONPath.evaluate().');({json:t}=e),o=Object.hasOwn(e,"flatten")?e.flatten:o,this.currResultType=Object.hasOwn(e,"resultType")?e.resultType:this.currResultType,this.currSandbox=Object.hasOwn(e,"sandbox")?e.sandbox:this.currSandbox,a=Object.hasOwn(e,"wrap")?e.wrap:a,this.currEval=Object.hasOwn(e,"eval")?e.eval:this.currEval,i=Object.hasOwn(e,"callback")?e.callback:i,this.currOtherTypeCallback=Object.hasOwn(e,"otherTypeCallback")?e.otherTypeCallback:this.currOtherTypeCallback,s=Object.hasOwn(e,"parent")?e.parent:s,n=Object.hasOwn(e,"parentProperty")?e.parentProperty:n,e=e.path}if(s=s||null,n=n||null,Array.isArray(e)&&(e=Wq.toPathString(e)),!e&&""!==e||!t)return;const l=Wq.toPathArray(e);"$"===l[0]&&l.length>1&&l.shift(),this._hasParentSelector=null;const h=this._trace(l,t,["$"],s,n,i).filter((function(e){return e&&!e.isParentSelector}));return h.length?a||1!==h.length||h[0].hasArrExpr?h.reduce(((e,t)=>{const i=this._getPreferredOutput(t);return o&&Array.isArray(i)?e=e.concat(i):e.push(i),e}),[]):this._getPreferredOutput(h[0]):a?[]:void 0},Wq.prototype._getPreferredOutput=function(e){const t=this.currResultType;switch(t){case"all":{const t=Array.isArray(e.path)?e.path:Wq.toPathArray(e.path);return e.pointer=Wq.toPointer(t),e.path="string"==typeof e.path?e.path:Wq.toPathString(e.path),e}case"value":case"parent":case"parentProperty":return e[t];case"path":return Wq.toPathString(e[t]);case"pointer":return Wq.toPointer(e.path);default:throw new TypeError("Unknown result type")}},Wq.prototype._handleCallback=function(e,t,i){if(t){const r=this._getPreferredOutput(e);e.path="string"==typeof e.path?e.path:Wq.toPathString(e.path),t(r,i,e)}},Wq.prototype._trace=function(e,t,i,r,s,n,o,a){let l;if(!e.length)return l={path:i,value:t,parent:r,parentProperty:s,hasArrExpr:o},this._handleCallback(l,n,"value"),l;const h=e[0],c=e.slice(1),u=[];function d(e){Array.isArray(e)?e.forEach((e=>{u.push(e)})):u.push(e)}if(("string"!=typeof h||a)&&t&&Object.hasOwn(t,h))d(this._trace(c,t[h],Uq(i,h),t,h,n,o));else if("*"===h)this._walk(t,(e=>{d(this._trace(c,t[e],Uq(i,e),t,e,n,!0,!0))}));else if(".."===h)d(this._trace(c,t,i,r,s,n,o)),this._walk(t,(r=>{"object"==typeof t[r]&&d(this._trace(e.slice(),t[r],Uq(i,r),t,r,n,!0))}));else{if("^"===h)return this._hasParentSelector=!0,{path:i.slice(0,-1),expr:c,isParentSelector:!0};if("~"===h)return l={path:Uq(i,h),value:s,parent:r,parentProperty:null},this._handleCallback(l,n,"property"),l;if("$"===h)d(this._trace(c,t,i,null,null,n,o));else if(/^(-?\d*):(-?\d*):?(\d*)$/u.test(h))d(this._slice(h,c,t,i,r,s,n));else if(0===h.indexOf("?(")){if(!1===this.currEval)throw new Error("Eval [?(expr)] prevented in JSONPath expression.");const e=h.replace(/^\?\((.*?)\)$/u,"$1"),o=/@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(e);o?this._walk(t,(e=>{const a=[o[2]],l=o[1]?t[e][o[1]]:t[e];this._trace(a,l,i,r,s,n,!0).length>0&&d(this._trace(c,t[e],Uq(i,e),t,e,n,!0))})):this._walk(t,(o=>{this._eval(e,t[o],o,i,r,s)&&d(this._trace(c,t[o],Uq(i,o),t,o,n,!0))}))}else if("("===h[0]){if(!1===this.currEval)throw new Error("Eval [(expr)] prevented in JSONPath expression.");d(this._trace(Gq(this._eval(h,t,i.at(-1),i.slice(0,-1),r,s),c),t,i,r,s,n,o))}else if("@"===h[0]){let e=!1;const o=h.slice(1,-2);switch(o){case"scalar":t&&["object","function"].includes(typeof t)||(e=!0);break;case"boolean":case"string":case"undefined":case"function":typeof t===o&&(e=!0);break;case"integer":!Number.isFinite(t)||t%1||(e=!0);break;case"number":Number.isFinite(t)&&(e=!0);break;case"nonFinite":"number"!=typeof t||Number.isFinite(t)||(e=!0);break;case"object":t&&typeof t===o&&(e=!0);break;case"array":Array.isArray(t)&&(e=!0);break;case"other":e=this.currOtherTypeCallback(t,i,r,s);break;case"null":null===t&&(e=!0);break;default:throw new TypeError("Unknown value type "+o)}if(e)return l={path:i,value:t,parent:r,parentProperty:s},this._handleCallback(l,n,"value"),l}else if("`"===h[0]&&t&&Object.hasOwn(t,h.slice(1))){const e=h.slice(1);d(this._trace(c,t[e],Uq(i,e),t,e,n,o,!0))}else if(h.includes(",")){const e=h.split(",");for(const o of e)d(this._trace(Gq(o,c),t,i,r,s,n,!0))}else!a&&t&&Object.hasOwn(t,h)&&d(this._trace(c,t[h],Uq(i,h),t,h,n,o,!0))}if(this._hasParentSelector)for(let e=0;e{t(e)}))},Wq.prototype._slice=function(e,t,i,r,s,n,o){if(!Array.isArray(i))return;const a=i.length,l=e.split(":"),h=l[2]&&Number.parseInt(l[2])||1;let c=l[0]&&Number.parseInt(l[0])||0,u=l[1]&&Number.parseInt(l[1])||a;c=c<0?Math.max(0,c+a):Math.min(a,c),u=u<0?Math.max(0,u+a):Math.min(a,u);const d=[];for(let e=c;e{d.push(e)}));return d},Wq.prototype._eval=function(e,t,i,r,s,n){this.currSandbox._$_parentProperty=n,this.currSandbox._$_parent=s,this.currSandbox._$_property=i,this.currSandbox._$_root=this.json,this.currSandbox._$_v=t;const o=e.includes("@path");o&&(this.currSandbox._$_path=Wq.toPathString(r.concat([i])));const a=this.currEval+"Script:"+e;if(!Wq.cache[a]){let t=e.replaceAll("@parentProperty","_$_parentProperty").replaceAll("@parent","_$_parent").replaceAll("@property","_$_property").replaceAll("@root","_$_root").replaceAll(/@([.\s)[])/gu,"_$_v$1");if(o&&(t=t.replaceAll("@path","_$_path")),"safe"===this.currEval||!0===this.currEval||void 0===this.currEval)Wq.cache[a]=new this.safeVm.Script(t);else if("native"===this.currEval)Wq.cache[a]=new this.vm.Script(t);else if("function"==typeof this.currEval&&this.currEval.prototype&&Object.hasOwn(this.currEval.prototype,"runInNewContext")){const e=this.currEval;Wq.cache[a]=new e(t)}else{if("function"!=typeof this.currEval)throw new TypeError(`Unknown "eval" property "${this.currEval}"`);Wq.cache[a]={runInNewContext:e=>this.currEval(t,e)}}}try{return Wq.cache[a].runInNewContext(this.currSandbox)}catch(t){if(this.ignoreEvalErrors)return!1;throw new Error("jsonPath: "+t.message+": "+e)}},Wq.cache={},Wq.toPathString=function(e){const t=e,i=t.length;let r="$";for(let e=1;ee[t]));t=r.reduce(((t,i)=>{let r=e[i].toString();return/function/u.test(r)||(r="function "+r),"var "+i+"="+r+";"+t}),"")+t,/(['"])use strict\1/u.test(t)||i.includes("arguments")||(t="var arguments = undefined;"+t),t=t.replace(/;\s*$/u,"");const n=t.lastIndexOf(";"),o=n>-1?t.slice(0,n+1)+" return "+t.slice(n+1):" return "+t;return new Function(...i,o)(...s)}}};class Hq{constructor(e){this.math=e}hexColor(e){return e.color}hexToRgb(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e.color);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:void 0}rgbToHex(e){let t=e.r,i=e.g,r=e.b;return 255!==e.max&&(t=Math.round(this.math.remap({number:t,fromLow:e.min,fromHigh:e.max,toLow:0,toHigh:255})),i=Math.round(this.math.remap({number:i,fromLow:e.min,fromHigh:e.max,toLow:0,toHigh:255})),r=Math.round(this.math.remap({number:r,fromLow:e.min,fromHigh:e.max,toLow:0,toHigh:255}))),`#${Number(16777216+65536*t+256*i+r).toString(16).substring(1,7)}`}rgbObjToHex(e){return this.rgbToHex({r:e.rgb.r,g:e.rgb.g,b:e.rgb.b,min:e.min,max:e.max})}hexToRgbMapped(e){const t=this.hexToRgb(e);return{r:this.math.remap({number:t.r,fromLow:0,fromHigh:255,toLow:e.from,toHigh:e.to}),g:this.math.remap({number:t.g,fromLow:0,fromHigh:255,toLow:e.from,toHigh:e.to}),b:this.math.remap({number:t.b,fromLow:0,fromHigh:255,toLow:e.from,toHigh:e.to})}}getRedParam(e){return this.hexToRgbMapped(e).r}getGreenParam(e){return this.hexToRgbMapped(e).g}getBlueParam(e){return this.hexToRgbMapped(e).b}rgbToRed(e){return e.rgb.r}rgbToGreen(e){return e.rgb.g}rgbToBlue(e){return e.rgb.b}invert(e){const{r:t,g:i,b:r}=this.hexToRgbMapped({color:e.color,from:0,to:255});if(e.blackAndWhite)return.299*t+.587*i+.114*r>186?"#000000":"#ffffff";const s=255-t,n=255-i,o=255-r;return this.rgbToHex({r:s,g:n,b:o,min:0,max:255})}}class Xq{getItem(e){if(e.index<0||e.index>=e.list.length)throw new Error("Index out of bounds");let t;return t=e.clone?structuredClone(e.list[e.index]):e.list[e.index],t}randomGetThreshold(e){let t=e.list;e.clone&&(t=structuredClone(e.list));const i=[];for(let r=0;r=s)t.forEach(((e,t)=>{!0===i[t]&&n.push(e)}));else{const e=[],o=Math.ceil(s/r);for(let t=0;t{!0===e[i]&&n.push(t)}))}return n}mergeElementsOfLists(e){const t=e.lists,i=e.level,r=[],s=[];t.forEach((e=>{const t=e.flat(i);r.push(t)}));const n=this.getLongestListLength({lists:r});for(let e=0;e0&&s.push(t)}let o=[];if(i>0)for(let e=0;e{e.length>t&&(t=e.length)})),t):void 0}reverse(e){let t=e.list;return e.clone&&(t=structuredClone(e.list)),t.reverse()}flipLists(e){if(e.list.length>0){const t=e.list[0].length;let i=!0;if(e.list.forEach((e=>{e.length!==t&&(i=!1)})),i){const i=[];for(let r=0;r{t.push(e[r])})),i.push(t)}return i}throw new Error("Lists are not of the same length")}throw new Error("List is empty")}groupNth(e){return(e=>{const{nrElements:t,list:i,keepRemainder:r}=e,s=t,n=[];let o=[];return i.forEach(((e,t)=>{o.push(e),(t+1)%s==0&&(n.push(o),o=[]),r&&t===i.length-1&&n.push(o)})),n})(e)}getListDepth(e){let t=0,i=!0,r=e.list;for(;i;){let e=!1;for(let t=0;t=0&&e.index<=t.length&&t.splice(e.index,0,e.item),t}addItemAtIndexes(e){let t=e.list;e.clone&&(t=structuredClone(e.list));let i=[...e.indexes];return i=i.filter((e=>e>=0&&e<=t.length)),i.sort(((e,t)=>e-t)),i.forEach(((i,r)=>{i>=0&&i+r<=t.length&&t.splice(i+r,0,e.item)})),t}addItemsAtIndexes(e){if(e.items.length!==e.indexes.length)throw new Error("Items and indexes must have the same length");for(let t=0;t0&&e.indexes[t-1]>e.indexes[t])throw new Error("Indexes must be in ascending order");let t=e.list;return e.clone&&(t=structuredClone(e.list)),[...e.indexes].forEach(((i,r)=>{i>=0&&i+r<=t.length&&t.splice(i+r,0,e.items[r])})),t}removeItemAtIndex(e){let t=e.list;return e.clone&&(t=structuredClone(e.list)),e.index>=0&&e.index<=t.length&&t.splice(e.index,1),t}removeItemsAtIndexes(e){let t=e.list;e.clone&&(t=structuredClone(e.list));const i=[...e.indexes];return i.sort(((e,t)=>t-e)),i.forEach((e=>{e>=0&&ee.threshold&&i.push(t[r]);return i}removeDuplicateNumbers(e){let t=e.list;return e.clone&&(t=structuredClone(e.list)),t.filter(((e,t,i)=>i.indexOf(e)===t))}removeDuplicateNumbersTolerance(e){let t=e.list;return e.clone&&(t=structuredClone(e.list)),t.filter(((t,i,r)=>r.findIndex((i=>Math.abs(i-t)e-t)):t.sort(((e,t)=>t-e))}sortTexts(e){let t=e.list;return e.clone&&(t=structuredClone(e.list)),e.orderAsc?t.sort():t.sort().reverse()}sortByPropValue(e){let t=e.list;return e.clone&&(t=structuredClone(e.list)),e.orderAsc?t.sort(((t,i)=>t[e.property]-i[e.property])):t.sort(((t,i)=>i[e.property]-t[e.property]))}}class qq{boolean(e){return e.boolean}randomBooleans(e){const t=[];for(let i=0;i{if(ie.thresholdTotalFalse)t.push(!1);else{const r=i-e.thresholdTotalTrue,s=(e.thresholdTotalFalse-e.thresholdTotalTrue)/e.nrLevels,n=Math.ceil(r/s)/e.nrLevels;Math.random()>n?t.push(!0):t.push(!1)}})),t}thresholdBooleanList(e){const t=[];return e.numbers.forEach((i=>{i!e)):t}thresholdGapsBooleanList(e){const t=[];return e.numbers.forEach((i=>{let r=!1;e.gapThresholds.forEach((e=>{const s=e[0],n=e[1];i>=s&&i<=n&&(t.push(!0),r=!0)})),r||t.push(!1)})),e.inverse?t.map((e=>!e)):t}not(e){return!e.boolean}notList(e){return e.booleans.map((e=>!e))}compare(e){switch(e.operator){case"==":return e.first==e.second;case"!=":return e.first!=e.second;case"===":return e.first===e.second;case"!==":return e.first!==e.second;case"<":return e.first":return e.first>e.second;case">=":return e.first>=e.second;default:return!1}}valueGate(e){return e.boolean?e.value:void 0}firstDefinedValueGate(e){let t;return t=void 0!==e.value1?e.value1:void 0!==e.value2?e.value2:void 0,t}}class Yq{number(e){return e.number}twoNrOperation(e){let t;switch(e.operation){case Tq.mathTwoNrOperatorEnum.add:t=e.first+e.second;break;case Tq.mathTwoNrOperatorEnum.subtract:t=e.first-e.second;break;case Tq.mathTwoNrOperatorEnum.multiply:t=e.first*e.second;break;case Tq.mathTwoNrOperatorEnum.divide:t=e.first/e.second;break;case Tq.mathTwoNrOperatorEnum.power:t=Math.pow(e.first,e.second);break;case Tq.mathTwoNrOperatorEnum.modulus:t=e.first%e.second}return t}modulus(e){return this.twoNrOperation({first:e.number,second:e.modulus,operation:Tq.mathTwoNrOperatorEnum.modulus})}roundToDecimals(e){return Math.round(e.number*Math.pow(10,e.decimalPlaces))/Math.pow(10,e.decimalPlaces)}oneNrOperation(e){let t;switch(e.operation){case Tq.mathOneNrOperatorEnum.absolute:t=Math.abs(e.number);break;case Tq.mathOneNrOperatorEnum.negate:t=-e.number;break;case Tq.mathOneNrOperatorEnum.ln:t=Math.log(e.number);break;case Tq.mathOneNrOperatorEnum.log10:t=Math.log10(e.number);break;case Tq.mathOneNrOperatorEnum.tenPow:t=Math.pow(10,e.number);break;case Tq.mathOneNrOperatorEnum.round:t=Math.round(e.number);break;case Tq.mathOneNrOperatorEnum.floor:t=Math.floor(e.number);break;case Tq.mathOneNrOperatorEnum.ceil:t=Math.ceil(e.number);break;case Tq.mathOneNrOperatorEnum.sqrt:t=Math.sqrt(e.number);break;case Tq.mathOneNrOperatorEnum.sin:t=Math.sin(e.number);break;case Tq.mathOneNrOperatorEnum.cos:t=Math.cos(e.number);break;case Tq.mathOneNrOperatorEnum.tan:t=Math.tan(e.number);break;case Tq.mathOneNrOperatorEnum.asin:t=Math.asin(e.number);break;case Tq.mathOneNrOperatorEnum.acos:t=Math.acos(e.number);break;case Tq.mathOneNrOperatorEnum.atan:t=Math.atan(e.number);break;case Tq.mathOneNrOperatorEnum.log:t=Math.log(e.number);break;case Tq.mathOneNrOperatorEnum.exp:t=Math.exp(e.number);break;case Tq.mathOneNrOperatorEnum.degToRad:t=e.number*Math.PI/180;break;case Tq.mathOneNrOperatorEnum.radToDeg:t=180*e.number/Math.PI}return t}remap(e){return(e.number-e.fromLow)*(e.toHigh-e.toLow)/(e.fromHigh-e.fromLow)+e.toLow}random(){return Math.random()}randomNumber(e){return Math.random()*(e.high-e.low)+e.low}randomNumbers(e){const t=[];for(let i=0;ithis.geometryHelper.transformControlPoints(e.transformation[i],[t])[0]))}translatePoints(e){const t=this.transforms.translationXYZ({translation:e.translation});return this.geometryHelper.transformControlPoints(t,e.points)}translatePointsWithVectors(e){if(e.points.length!==e.translations.length)throw new Error("You must provide equal nr of points and translations");const t=this.transforms.translationsXYZ({translations:e.translations});return e.points.map(((e,i)=>this.geometryHelper.transformControlPoints(t[i],[e])[0]))}translateXYZPoints(e){const t=this.transforms.translationXYZ({translation:[e.x,e.y,e.z]});return this.geometryHelper.transformControlPoints(t,e.points)}scalePointsCenterXYZ(e){const t=this.transforms.scaleCenterXYZ({center:e.center,scaleXyz:e.scaleXyz});return this.geometryHelper.transformControlPoints(t,e.points)}rotatePointsCenterAxis(e){const t=this.transforms.rotationCenterAxis({center:e.center,axis:e.axis,angle:e.angle});return this.geometryHelper.transformControlPoints(t,e.points)}closestPointFromPointsDistance(e){return this.closestPointFromPointData(e).distance}closestPointFromPointsIndex(e){return this.closestPointFromPointData(e).index}closestPointFromPoints(e){return this.closestPointFromPointData(e).point}distance(e){const t=e.endPoint[0]-e.startPoint[0],i=e.endPoint[1]-e.startPoint[1],r=e.endPoint[2]-e.startPoint[2];return Math.sqrt(t*t+i*i+r*r)}distancesToPoints(e){return e.endPoints.map((t=>this.distance({startPoint:e.startPoint,endPoint:t})))}multiplyPoint(e){const t=[];for(let i=0;i{t.push(e[0]),i.push(e[1]),r.push(e[2])})),[t.reduce(((e,t)=>e+t),0)/e.points.length,i.reduce(((e,t)=>e+t),0)/e.points.length,r.reduce(((e,t)=>e+t),0)/e.points.length]}pointXYZ(e){return[e.x,e.y,e.z]}pointXY(e){return[e.x,e.y]}spiral(e){const t=e.phi,i=Math.log(t)/(Math.PI/e.widening),r=[],s=e.radius/e.numberPoints;for(let t=0;t{i[s]=[r[0]-e,r[1]-t,0]}))}return e.pointsOnGround&&i.forEach(((e,t)=>{i[t]=[e[0],0,e[1]]})),i}removeConsecutiveDuplicates(e){return this.geometryHelper.removeConsecutivePointDuplicates(e.points,e.checkFirstAndLast,e.tolerance)}closestPointFromPointData(e){let t,i,r=Number.MAX_SAFE_INTEGER;for(let s=0;se.toString()))}format(e){return e.text.replace(/{(\d+)}/g,((t,i)=>void 0!==e.values[i]?e.values[i]:t))}}class $q{constructor(e,t){this.math=e,this.geometryHelper=t}removeAllDuplicateVectors(e){return this.geometryHelper.removeAllDuplicateVectors(e.vectors,e.tolerance)}removeConsecutiveDuplicateVectors(e){return this.geometryHelper.removeConsecutiveVectorDuplicates(e.vectors,e.checkFirstAndLast,e.tolerance)}angleBetween(e){return this.math.radToDeg({number:Math.acos(this.dot({first:e.first,second:e.second})/(this.norm({vector:e.first})*this.norm({vector:e.second})))})}angleBetweenNormalized2d(e){const t=e.first[0]*e.second[1]-e.first[1]*e.second[0];return this.math.radToDeg({number:Math.atan2(t,this.dot({first:e.first,second:e.second}))})}positiveAngleBetween(e){const t=this.signedAngleBetween(e);return t<0?360+t:t}addAll(e){const t=[];for(let i=0;ie))}cross(e){const t=[];return t.push(e.first[1]*e.second[2]-e.first[2]*e.second[1]),t.push(e.first[2]*e.second[0]-e.first[0]*e.second[2]),t.push(e.first[0]*e.second[1]-e.first[1]*e.second[0]),t}distSquared(e){let t=0;for(let i=0;iisFinite(e)))}isZero(e){return 0===this.norm({vector:e.vector})}lerp(e){return this.add({first:this.mul({vector:e.first,scalar:e.fraction}),second:this.mul({vector:e.second,scalar:1-e.fraction})})}max(e){return Math.max(...e.vector)}min(e){return Math.min(...e.vector)}mul(e){const t=[];for(let i=0;i0?o:2*Math.PI-o;return this.math.radToDeg({number:a})}span(e){const t=[];for(let i=e.min;i<=e.max;i+=e.step)t.push(i);return t}spanEaseItems(e){const t=[];for(let i=0;i0===t?e:e-i[t-1])):t}spanLinearItems(e){const t=[],i=e.max-e.min;for(let r=0;re+t),0)}}class Qq{constructor(e,t){this.vector=e,this.math=t}rotationCenterAxis(e){return[this.translation(-e.center[0],-e.center[1],-e.center[2]),this.rotationAxis(e.axis,this.math.degToRad({number:e.angle})),this.translation(e.center[0],e.center[1],e.center[2])]}rotationCenterX(e){return[this.translation(-e.center[0],-e.center[1],-e.center[2]),this.rotationX(this.math.degToRad({number:e.angle})),this.translation(e.center[0],e.center[1],e.center[2])]}rotationCenterY(e){return[this.translation(-e.center[0],-e.center[1],-e.center[2]),this.rotationY(this.math.degToRad({number:e.angle})),this.translation(e.center[0],e.center[1],e.center[2])]}rotationCenterZ(e){return[this.translation(-e.center[0],-e.center[1],-e.center[2]),this.rotationZ(this.math.degToRad({number:e.angle})),this.translation(e.center[0],e.center[1],e.center[2])]}rotationCenterYawPitchRoll(e){return[this.translation(-e.center[0],-e.center[1],-e.center[2]),this.rotationYawPitchRoll(this.math.degToRad({number:e.yaw}),this.math.degToRad({number:e.pitch}),this.math.degToRad({number:e.roll})),this.translation(e.center[0],e.center[1],e.center[2])]}scaleCenterXYZ(e){return[this.translation(-e.center[0],-e.center[1],-e.center[2]),this.scaling(e.scaleXyz[0],e.scaleXyz[1],e.scaleXyz[2]),this.translation(e.center[0],e.center[1],e.center[2])]}scaleXYZ(e){return[this.scaling(e.scaleXyz[0],e.scaleXyz[1],e.scaleXyz[2])]}uniformScale(e){return[this.scaling(e.scale,e.scale,e.scale)]}uniformScaleFromCenter(e){return[this.translation(-e.center[0],-e.center[1],-e.center[2]),this.scaling(e.scale,e.scale,e.scale),this.translation(e.center[0],e.center[1],e.center[2])]}translationXYZ(e){return[this.translation(e.translation[0],e.translation[1],e.translation[2])]}translationsXYZ(e){return e.translations.map((e=>[this.translation(e[0],e[1],e[2])]))}translation(e,t,i){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1]}scaling(e,t,i){return[e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1]}identity(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}rotationAxis(e,t){const i=Math.sin(-t),r=Math.cos(-t),s=1-r,n=this.vector.normalized({vector:e}),o=n[0],a=n[1],l=n[2],h=this.identity();return h[0]=o*o*s+r,h[1]=o*a*s-l*i,h[2]=o*l*s+a*i,h[3]=0,h[4]=a*o*s+l*i,h[5]=a*a*s+r,h[6]=a*l*s-o*i,h[7]=0,h[8]=l*o*s-a*i,h[9]=l*a*s+o*i,h[10]=l*l*s+r,h[11]=0,h[12]=0,h[13]=0,h[14]=0,h[15]=1,h}rotationX(e){const t=Math.sin(e),i=Math.cos(e);return[1,0,0,0,0,i,t,0,0,-t,i,0,0,0,0,1]}rotationY(e){const t=Math.sin(e),i=Math.cos(e);return[i,0,-t,0,0,1,0,0,t,0,i,0,0,0,0,1]}rotationZ(e){const t=Math.sin(e),i=Math.cos(e);return[i,t,0,0,-t,i,0,0,0,0,1,0,0,0,0,1]}rotationYawPitchRoll(e,t,i){const r=.5*i,s=.5*t,n=.5*e,o=Math.sin(r),a=Math.cos(r),l=Math.sin(s),h=Math.cos(s),c=Math.sin(n),u=Math.cos(n),d=u*l*a+c*h*o,f=c*h*a-u*l*o,p=u*h*o-c*l*a,_=u*h*a+c*l*o;return this.rotationMatrixFromQuat(d,f,p,_)}rotationMatrixFromQuat(e,t,i,r){const s=e*e,n=t*t,o=i*i,a=e*t,l=i*r,h=i*e,c=t*r,u=t*i,d=e*r,f=this.identity();return f[0]=1-2*(n+o),f[1]=2*(a+l),f[2]=2*(h-c),f[3]=0,f[4]=2*(a-l),f[5]=1-2*(o+s),f[6]=2*(u+d),f[7]=0,f[8]=2*(h+c),f[9]=2*(u-d),f[10]=1-2*(n+s),f[11]=0,f[12]=0,f[13]=0,f[14]=0,f[15]=1,f}}class Zq{constructor(){this.getArrayDepth=e=>Array.isArray(e)?1+Math.max(...e.map(this.getArrayDepth)):0}transformControlPoints(e,t){return this.getFlatTransformations(e).forEach((e=>{t=this.transformPointsByMatrixArray(t,e)})),t}getFlatTransformations(e){let t=[];return 3===this.getArrayDepth(e)?e.forEach((e=>{t.push(...e)})):t=e,t}transformPointsByMatrixArray(e,t){return this.transformPointsCoordinates(e,t)}transformPointsCoordinates(e,t){const i=[];for(const r of e){const e=this.transformCoordinates(r[0],r[1],r[2],t);i.push(e)}return i}removeAllDuplicateVectors(e,t=1e-7){const i=[];return e.forEach((e=>{i.some((i=>this.vectorsTheSame(e,i,t)))||i.push(e)})),i}removeConsecutiveVectorDuplicates(e,t=!0,i=1e-7){const r=[];if(e.length>1){for(let t=1;t1){for(let t=1;t0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,i=this,r=i.hasError,s=i.isStopped,n=i.observers;return r||s?CY:(this.currentObservers=null,n.push(e),new TY((function(){t.currentObservers=null,SY(n,e)})))},t.prototype._checkFinalizedStatuses=function(e){var t=this,i=t.hasError,r=t.thrownError,s=t.isStopped;i?e.error(r):s&&e.complete()},t.prototype.asObservable=function(){var e=new YY;return e.source=this,e},t.create=function(e,t){return new ZY(e,t)},t}(YY),ZY=function(e){function t(t,i){var r=e.call(this)||this;return r.destination=t,r.source=i,r}return uz(t,e),t.prototype.next=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===i||i.call(t,e)},t.prototype.error=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===i||i.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,i;return null!==(i=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==i?i:CY},t}(QY);!function(e){e[e.loading=0]="loading",e[e.loaded=1]="loaded",e[e.initialised=2]="initialised",e[e.computing=3]="computing"}(jY||(jY={}));class JY{constructor(){this.jscadWorkerState$=new QY,this.promisesMade=[]}jscadWorkerAlreadyInitialised(){return!!this.jscadWorker}setJscadWorker(e){this.jscadWorker=e,this.jscadWorker.onmessage=({data:e})=>{if("jscad-initialised"===e)this.jscadWorkerState$.next({state:jY.initialised});else if("busy"===e)this.jscadWorkerState$.next({state:jY.computing});else{const t=this.promisesMade.find((t=>t.uid===e.uid));t&&e.result&&!e.error?t.resolve(e.result):e.error&&(this.errorCallback&&this.errorCallback(e.error),t.reject(e.error)),this.promisesMade=this.promisesMade.filter((t=>t.uid!==e.uid)),0===this.promisesMade.length?this.jscadWorkerState$.next({state:jY.loaded}):this.jscadWorkerState$.next({state:jY.computing})}}}cleanPromisesMade(){this.promisesMade=[]}genericCallToWorkerPromise(e,t){const i=`call${Math.random()}${Date.now()}`,r={uid:i},s=new Promise(((e,t)=>{r.resolve=e,r.reject=t}));return r.promise=s,this.promisesMade.push(r),this.jscadWorker.postMessage({action:{functionName:e,inputs:t},uid:i}),s}startedTheRun(){return this.genericCallToWorkerPromise("startedTheRun",{})}cleanAllCache(){return this.genericCallToWorkerPromise("cleanAllCache",{})}}var eK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class tK{constructor(e){this.manifoldWorkerManager=e}manifoldFromMesh(e){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.shapes.manifoldFromMesh",e)}cube(e){return eK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.shapes.cube",e)}))}sphere(e){return eK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.shapes.sphere",e)}))}tetrahedron(){return eK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.shapes.tetrahedron",{})}))}cylinder(e){return eK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.shapes.cylinder",e)}))}}var iK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class rK{constructor(e){this.manifoldWorkerManager=e}subtract(e){return iK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.subtract",e)}))}add(e){return iK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.add",e)}))}intersect(e){return iK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.intersect",e)}))}differenceTwo(e){return iK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.differenceTwo",e)}))}unionTwo(e){return iK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.unionTwo",e)}))}intersectionTwo(e){return iK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.intersectionTwo",e)}))}difference(e){return iK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.difference",e)}))}union(e){return iK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.union",e)}))}intersection(e){return iK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.intersection",e)}))}split(e){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.split",e)}splitByPlane(e){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.splitByPlane",e)}trimByPlane(e){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.trimByPlane",e)}}var sK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class nK{constructor(e){this.manifoldWorkerManager=e}hull(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.hull",e)}))}hullPoints(e){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.hullPoints",e)}slice(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.slice",e)}))}project(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.project",e)}))}setTolerance(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.setTolerance",e)}))}reserveIds(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.reserveIds",e)}))}asOriginal(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.asOriginal",e)}))}compose(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.compose",e)}))}decompose(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.decompose",e)}))}calculateNormals(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.calculateNormals",e)}))}calculateCurvature(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.calculateCurvature",e)}))}refineToTolerance(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.refineToTolerance",e)}))}refineToLength(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.refineToLength",e)}))}refine(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.refine",e)}))}smoothOut(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.smoothOut",e)}))}smoothByNormals(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.smoothByNormals",e)}))}}var oK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class aK{constructor(e){this.manifoldWorkerManager=e}scale3D(e){return oK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.transforms.scale3D",e)}))}scale(e){return oK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.transforms.scale",e)}))}mirror(e){return oK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.transforms.mirror",e)}))}translate(e){return oK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.transforms.translate",e)}))}translateByVectors(e){return oK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.transforms.translateByVectors",e)}))}translateXYZ(e){return oK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.transforms.translateXYZ",e)}))}rotate(e){return oK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.transforms.rotate",e)}))}rotateXYZ(e){return oK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.transforms.rotateXYZ",e)}))}transform(e){return oK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.transforms.transform",e)}))}transforms(e){return oK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.transforms.transforms",e)}))}}var lK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class hK{constructor(e){this.manifoldWorkerManager=e}surfaceArea(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.surfaceArea",e)}))}volume(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.volume",e)}))}isEmpty(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.isEmpty",e)}))}numVert(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.numVert",e)}))}numTri(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.numTri",e)}))}numEdge(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.numEdge",e)}))}numProp(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.numProp",e)}))}numPropVert(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.numPropVert",e)}))}boundingBox(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.boundingBox",e)}))}tolerance(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.tolerance",e)}))}genus(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.genus",e)}))}minGap(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.minGap",e)}))}originalID(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.originalID",e)}))}}var cK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class uK{constructor(e){this.manifoldWorkerManager=e,this.shapes=new tK(e),this.booleans=new rK(e),this.operations=new nK(e),this.transforms=new aK(e),this.evaluate=new hK(e)}manifoldToMesh(e){return cK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.manifoldToMesh",e)}))}manifoldsToMeshes(e){return cK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.manifoldsToMeshes",e)}))}}var dK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class fK{constructor(e){this.manifoldWorkerManager=e}hull(e){return dK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.operations.hull",e)}))}extrude(e){return dK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.operations.extrude",e)}))}revolve(e){return dK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.operations.revolve",e)}))}offset(e){return dK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.operations.offset",e)}))}simplify(e){return dK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.operations.simplify",e)}))}compose(e){return dK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.operations.compose",e)}))}decompose(e){return dK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.operations.decompose",e)}))}}var pK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class _K{constructor(e){this.manifoldWorkerManager=e}create(e){return pK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.shapes.create",e)}))}square(e){return pK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.shapes.square",e)}))}circle(e){return pK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.shapes.circle",e)}))}rectangle(e){return pK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.shapes.rectangle",e)}))}}var mK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class gK{constructor(e){this.manifoldWorkerManager=e}scale2D(e){return mK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.transforms.scale2D",e)}))}scale(e){return mK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.transforms.scale",e)}))}mirror(e){return mK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.transforms.mirror",e)}))}translate(e){return mK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.transforms.translate",e)}))}translateXY(e){return mK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.transforms.translateXY",e)}))}rotate(e){return mK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.transforms.rotate",e)}))}transform(e){return mK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.transforms.transform",e)}))}}var vK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class xK{constructor(e){this.manifoldWorkerManager=e}subtract(e){return vK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.booleans.subtract",e)}))}add(e){return vK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.booleans.add",e)}))}intersect(e){return vK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.booleans.intersect",e)}))}differenceTwo(e){return vK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.booleans.differenceTwo",e)}))}unionTwo(e){return vK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.booleans.unionTwo",e)}))}intersectionTwo(e){return vK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.booleans.intersectionTwo",e)}))}difference(e){return vK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.booleans.difference",e)}))}union(e){return vK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.booleans.union",e)}))}intersection(e){return vK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.booleans.intersection",e)}))}}var bK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class SK{constructor(e){this.manifoldWorkerManager=e}area(e){return bK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.evaluate.area",e)}))}isEmpty(e){return bK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.evaluate.isEmpty",e)}))}numVert(e){return bK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.evaluate.numVert",e)}))}numContour(e){return bK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.evaluate.numContour",e)}))}bounds(e){return bK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.evaluate.bounds",e)}))}}var TK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class CK{constructor(e){this.manifoldWorkerManager=e,this.shapes=new _K(e),this.operations=new fK(e),this.booleans=new xK(e),this.transforms=new gK(e),this.evaluate=new SK(e)}crossSectionToPolygons(e){return TK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.crossSectionToPolygons",e)}))}crossSectionsToPolygons(e){return TK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.crossSectionsToPolygons",e)}))}}class yK{constructor(e){this.manifoldWorkerManager=e}merge(e){return t=this,i=void 0,s=function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("mesh.operations.merge",e)},new((r=void 0)||(r=Promise))((function(e,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r((function(e){e(i)}))).then(o,a)}l((s=s.apply(t,i||[])).next())}));var t,i,r,s}}var EK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class PK{constructor(e){this.manifoldWorkerManager=e}position(e){return EK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("mesh.evaluate.position",e)}))}verts(e){return EK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("mesh.evaluate.verts",e)}))}tangent(e){return EK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("mesh.evaluate.tangent",e)}))}extras(e){return EK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("mesh.evaluate.extras",e)}))}transform(e){return EK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("mesh.evaluate.transform",e)}))}numProp(e){return EK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("mesh.evaluate.numProp",e)}))}numVert(e){return EK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("mesh.evaluate.numVert",e)}))}numTri(e){return EK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("mesh.evaluate.numTri",e)}))}numRun(e){return EK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("mesh.evaluate.numRun",e)}))}}class AK{constructor(e){this.manifoldWorkerManager=e,this.operations=new yK(e),this.evaluate=new PK(e)}}var RK,IK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class MK{constructor(e){this.manifoldWorkerManager=e,this.manifold=new uK(e),this.crossSection=new CK(e),this.mesh=new AK(e)}manifoldToMeshPointer(e){return IK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifoldToMeshPointer",e)}))}decomposeManifoldOrCrossSection(e){return IK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("decomposeManifoldOrCrossSection",e)}))}decomposeManifoldsOrCrossSections(e){return IK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("decomposeManifoldsOrCrossSections",e)}))}deleteManifoldOrCrossSection(e){return IK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("deleteManifoldOrCrossSection",e)}))}deleteManifoldsOrCrossSections(e){return IK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("deleteManifoldsOrCrossSections",e)}))}}!function(e){e[e.loading=0]="loading",e[e.loaded=1]="loaded",e[e.initialised=2]="initialised",e[e.computing=3]="computing"}(RK||(RK={}));class OK{constructor(){this.manifoldWorkerState$=new QY,this.promisesMade=[]}manifoldWorkerAlreadyInitialised(){return!!this.manifoldWorker}setManifoldWorker(e){this.manifoldWorker=e,this.manifoldWorker.onmessage=({data:e})=>{if("manifold-initialised"===e)this.manifoldWorkerState$.next({state:RK.initialised});else if("busy"===e)this.manifoldWorkerState$.next({state:RK.computing});else{const t=this.promisesMade.find((t=>t.uid===e.uid));t&&void 0!==e.result&&!e.error?t.resolve(e.result):e.error&&(this.errorCallback&&this.errorCallback(e.error),t.reject(e.error)),this.promisesMade=this.promisesMade.filter((t=>t.uid!==e.uid)),0===this.promisesMade.length?this.manifoldWorkerState$.next({state:RK.loaded}):this.manifoldWorkerState$.next({state:RK.computing})}}}cleanPromisesMade(){this.promisesMade=[]}genericCallToWorkerPromise(e,t){const i=`call${Math.random()}${Date.now()}`,r={uid:i},s=new Promise(((e,t)=>{r.resolve=e,r.reject=t}));return r.promise=s,this.promisesMade.push(r),this.manifoldWorker.postMessage({action:{functionName:e,inputs:t},uid:i}),s}startedTheRun(){return this.genericCallToWorkerPromise("startedTheRun",{})}cleanAllCache(){return this.genericCallToWorkerPromise("cleanAllCache",{})}}var DK=i(34258);class wK{constructor(){this.context=new Iq,this.jscadWorkerManager=new JY,this.manifoldWorkerManager=new OK,this.occtWorkerManager=new Zz,this.jscad=new gY(this.jscadWorkerManager),this.manifold=new MK(this.manifoldWorkerManager);const e=new Zq;this.math=new Yq,this.vector=new $q(this.math,e);const t=new Oq(this.context,this.jscad.text,this.vector,this.jscadWorkerManager,this.manifoldWorkerManager,this.occtWorkerManager);this.babylon=new qX(this.context,t,this.color),this.tag=new pq(this.context),this.draw=new Rq(t,this.babylon.node,this.tag,this.context),this.color=new Hq(this.math),this.line=new dq(this.context,e),this.transforms=new Qq(this.vector,this.math),this.point=new Kq(e,this.transforms),this.polyline=new fq(this.context,e),this.verb=new oq(this.context,e,this.math),this.time=new _q(this.context),this.occt=new KX(this.context,this.occtWorkerManager),this.asset=new cq,this.logic=new qq,this.json=new uq(this.context),this.text=new jq,this.lists=new Xq}init(e,t,i,r,s){this.context.scene=e,s&&(this.context.havokPlugin=s);const n={geom:DK.geom,core:DK.core};this.context.verb=n,this.context.jsonpath=Wq,t&&this.occtWorkerManager.setOccWorker(t),i&&this.jscadWorkerManager.setJscadWorker(i),r&&this.manifoldWorkerManager.setManifoldWorker(r)}}const NK="assets/textures";class FK{constructor(e){this.name="",this.scene=void 0,this.wAng=0,this.uScale=1,this.vScale=1,this.color=void 0,this.albedoTextureUrl=void 0,this.microSurfaceTextureUrl=void 0,this.bumpTextureUrl=void 0,this.metallic=.1,this.roughness=.9,this.zOffset=2,Object.keys(this).forEach((t=>this[t]=e[t]))}}class LK{static simpleBlackMaterial(e){const t=new zm("blackMaterial"+Math.random(),e);return t.albedoColor=new hc.v9(0,0,0),t.metallic=0,t.roughness=.7,t.zOffset=2,t}static rock1Material(e,t,i){const r=new FK({name:"wood1",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:LK.textures.rock1.default.albedo,bumpTextureUrl:LK.textures.rock1.microSurfaceTexture,microSurfaceTextureUrl:LK.textures.rock1.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return LK.createMaterial(r)}static wood1Material(e,t,i){const r=new FK({name:"wood1",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:LK.textures.wood1.light.albedo,bumpTextureUrl:LK.textures.wood1.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return LK.createMaterial(r)}static wood2Material(e,t,i){const r=new FK({name:"wood2",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:LK.textures.wood2.light.albedo,microSurfaceTextureUrl:LK.textures.wood2.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return LK.createMaterial(r)}static wood3Material(e,t,i){const r=new FK({name:"wood3",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:LK.textures.wood1.dark.albedo,microSurfaceTextureUrl:LK.textures.wood1.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return LK.createMaterial(r)}static brownPlanks(e,t,i){const r=new FK({name:"brownPlanks",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:LK.textures.brownPlanks.light.albedo,microSurfaceTextureUrl:LK.textures.brownPlanks.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return LK.createMaterial(r)}static woodenPlanks(e,t,i){const r=new FK({name:"woodenPlanks",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:LK.textures.woodenPlanks.light.albedo,microSurfaceTextureUrl:LK.textures.woodenPlanks.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return LK.createMaterial(r)}static glass(e,t){const i=new zm("faceGlassMaterial"+Math.random(),e);return i.albedoColor=hc.v9.FromHexString(t),i.ambientColor=hc.v9.FromHexString("#ffffff"),i.metallic=.8,i.roughness=.1,i.zOffset=1,i.alpha=.5,i}static brushedConcrete(e,t,i){const r=new FK({name:"brushedConcrete",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:LK.textures.brushedConcrete.grey.albedo,microSurfaceTextureUrl:LK.textures.brushedConcrete.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return LK.createMaterial(r)}static metal1(e,t,i){const r=new FK({name:"metal1",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:LK.textures.metal1.light.albedo,microSurfaceTextureUrl:LK.textures.metal1.microSurfaceTexture,bumpTextureUrl:LK.textures.metal1.light.roughness,metallic:.3,roughness:.6,zOffset:2});return LK.createMaterial(r)}static roughPlastic(e,t){const i=new FK({name:"roughPlastic-"+t,color:t,scene:e,metallic:.1,roughness:.9,zOffset:2});return LK.createMaterial(i)}static createMaterial(e){const t=new zm(e.name,e.scene);return e.color&&(t.albedoColor=hc.v9.FromHexString(e.color)),e.albedoTextureUrl&&(t.albedoTexture=LK.createTexture(e.albedoTextureUrl,e)),e.microSurfaceTextureUrl&&(t.microSurfaceTexture=LK.createTexture(e.microSurfaceTextureUrl,e)),e.bumpTextureUrl&&(t.bumpTexture=LK.createTexture(e.bumpTextureUrl,e)),t.metallic=e.metallic,t.roughness=e.roughness,t.zOffset=e.zOffset,t}static createTexture(e,t){const i=new vi.g(e,t.scene);return i.uScale=t.uScale,i.vScale=t.vScale,i.wAng=t.wAng,i}}LK.textures={wood1:{microSurfaceTexture:`${NK}/Wood048_1K/Wood048_1K_NormalGL.jpg`,light:{albedo:`${NK}/Wood048_1K/Wood048_1K_Light.jpg`},dark:{albedo:`${NK}/Wood048_1K/Wood048_1K_Color_Dark.jpg`}},wood2:{microSurfaceTexture:`${NK}/Wood084_1K/Wood084A_1K_NormalGL.jpg`,light:{albedo:`${NK}/Wood084_1K/Wood084A_1K_Color.jpg`}},metal1:{microSurfaceTexture:`${NK}/metal_1/Metal029_1K_Displacement.jpg`,light:{albedo:`${NK}/metal_1/Metal029_1K_Color.jpg`,normalGL:`${NK}/metal_1/Metal029_1K_NormalGL.jpg`,roughness:`${NK}/metal_1/Metal029_1K_Roughness.jpg`,metalness:`${NK}/metal_1/Metal029_1K_Metalness.jpg`}},brownPlanks:{microSurfaceTexture:`${NK}/brown_planks/brown_planks_05_nor_gl_1k.jpg`,light:{albedo:`${NK}/brown_planks/brown_planks_05_diff_1k.jpg`}},woodenPlanks:{microSurfaceTexture:`${NK}/wooden_planks/wooden_planks_nor_gl_1k.jpg`,light:{albedo:`${NK}/wooden_planks/wooden_planks_diff_1k.jpg`}},brushedConcrete:{microSurfaceTexture:`${NK}/brushed_concrete/brushed_concrete_03_nor_gl_1k.jpg`,sand:{albedo:`${NK}/brushed_concrete/brushed_concrete_03_diff_1k.jpg`},grey:{albedo:`${NK}/brushed_concrete/brushed_concrete_03_diff_grey_1k.jpg`}},rock1:{microSurfaceTexture:`${NK}/Rock044_1K/Rock044_1K_NormalGL.jpg`,default:{albedo:`${NK}/Rock044_1K/Rock044_1K_Color.jpg`,roughness:`${NK}/Rock044_1K/Rock044_1K_Roughness.jpg`}}};var BK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class VK{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return BK(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.wingtipVilla",e);if(t){const e=t.shapes.find((e=>e.id===t.data.roof.compound)),i=t.shapes.find((e=>e.id===t.data.walls.compound));return{type:t.data.type,name:t.data.name,compound:t.compound,roof:{compound:e.shape,shapes:t.shapes.filter((e=>t.data.roof.shapes.includes(e.id))).map((e=>e.shape))},walls:{compound:i.shape,shapes:t.shapes.filter((e=>t.data.walls.shapes.includes(e.id))).map((e=>e.shape))},stick:{shape:t.shapes.find((e=>e.id===t.data.stick.shape)).shape},floor:{shape:t.shapes.find((e=>e.id===t.data.floor.shape)).shape},chimney:{shape:t.shapes.find((e=>e.id===t.data.chimney.shape)).shape},basicPoints:t.data.basicPoints}}}))}drawModel(e){return BK(this,void 0,void 0,(function*(){const t=new Yt("brepMesh"+Math.random(),this.context.scene),i=new QH.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#ffffff";const r=yield this.draw.drawAnyAsync({entity:e.roof.compound,options:i}),s=r.getChildMeshes(),n=s[0],o=s[1],a=yield this.draw.drawAnyAsync({entity:e.walls.compound,options:i}),l=a.getChildMeshes(),h=l[0],c=l[1],u=yield this.draw.drawAnyAsync({entity:e.floor.shape,options:i}),d=u.getChildMeshes(),f=d[0],p=d[1],_=yield this.draw.drawAnyAsync({entity:e.stick.shape,options:i}),m=_.getChildMeshes(),g=m[0],v=m[1],x=yield this.draw.drawAnyAsync({entity:e.chimney.shape,options:i}),b=x.getChildMeshes(),S=b[0],T=b[1],C=new vi.g("assets/textures/Wood048_1K/Wood048_1K_Red.jpg",this.context.scene),y=new vi.g("assets/textures/Wood048_1K/Wood048_1K_Color_Dark.jpg",this.context.scene),E=new vi.g("assets/textures/Wood048_1K/Wood048_1K_NormalGL.jpg",this.context.scene);C.uScale=.3,C.vScale=.3,C.wAng=Math.PI/2,y.uScale=.3,y.vScale=.3,y.wAng=Math.PI/2,E.uScale=.3,E.vScale=.3,E.wAng=Math.PI/2;const P=new zm("wood-red",this.context.scene);P.albedoTexture=C,P.microSurfaceTexture=E,P.metallic=0,P.roughness=1,P.zOffset=2;const A=new zm("wood-dark",this.context.scene);return A.albedoTexture=y,A.microSurfaceTexture=E,A.metallic=0,A.roughness=1,A.zOffset=2,n.material=P,h.material=LK.wood1Material(this.context.scene,Math.PI/2,.3),f.material=P,g.material=P,S.material=A,n.parent=t,h.parent=t,f.parent=t,g.parent=t,S.parent=t,o.parent=t,c.parent=t,p.parent=t,v.parent=t,T.parent=t,r.dispose(),u.dispose(),a.dispose(),_.dispose(),x.dispose(),t}))}dispose(e){return BK(this,void 0,void 0,(function*(){const t=[e.compound,e.chimney.shape,e.floor.shape,...e.roof.shapes,...e.walls.shapes,e.stick.shape];yield this.occt.deleteShapes({shapes:t})}))}}var kK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class UK{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}dispose(e){return kK(this,void 0,void 0,(function*(){const t=[e.compound,e.floor.shape,...e.roof.shapes,...e.walls.shapes,e.stick.shape];yield this.occt.deleteShapes({shapes:t})}))}create(e){return kK(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.chirpyChalet",e);if(t){const e=t.shapes.find((e=>e.id===t.data.roof.compound)),i=t.shapes.find((e=>e.id===t.data.walls.compound));return{type:t.data.type,name:t.data.name,compound:t.compound,roof:{compound:e.shape,shapes:t.shapes.filter((e=>t.data.roof.shapes.includes(e.id))).map((e=>e.shape))},walls:{compound:i.shape,shapes:t.shapes.filter((e=>t.data.walls.shapes.includes(e.id))).map((e=>e.shape))},stick:{shape:t.shapes.find((e=>e.id===t.data.stick.shape)).shape},floor:{shape:t.shapes.find((e=>e.id===t.data.floor.shape)).shape},basicPoints:t.data.basicPoints}}}))}drawModel(e){return kK(this,void 0,void 0,(function*(){const t=new Yt("brepMesh"+Math.random(),this.context.scene),i=new QH.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#ffffff";const r=yield this.draw.drawAnyAsync({entity:e.roof.compound,options:i}),s=r.getChildMeshes()[0],n=yield this.draw.drawAnyAsync({entity:e.walls.compound,options:i}),o=n.getChildMeshes()[0],a=yield this.draw.drawAnyAsync({entity:e.floor.shape,options:i}),l=a.getChildMeshes()[0],h=yield this.draw.drawAnyAsync({entity:e.stick.shape,options:i}),c=h.getChildMeshes()[0],u=new vi.g("assets/textures/Wood048_1K/Wood048_1K_Color.jpg",this.context.scene),d=new vi.g("assets/textures/Wood048_1K/Wood048_1K_Light.jpg",this.context.scene),f=new vi.g("assets/textures/Wood048_1K/Wood048_1K_NormalGL.jpg",this.context.scene);d.uScale=.3,d.vScale=.3,d.wAng=Math.PI/2,u.uScale=.3,u.vScale=.3,u.wAng=Math.PI/2,f.uScale=.3,f.vScale=.3,f.wAng=Math.PI/2;const p=new zm("roof",this.context.scene);p.albedoTexture=u,p.microSurfaceTexture=f,p.metallic=0,p.roughness=1,p.zOffset=2;const _=new zm("walls",this.context.scene);return _.albedoTexture=d,_.microSurfaceTexture=f,_.metallic=0,_.roughness=1,_.zOffset=2,s.material=p,o.material=_,l.material=p,c.material=p,r.setParent(t),a.setParent(t),n.setParent(t),h.setParent(t),t}))}}class GK{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.wingtipVilla=new VK(this.occWorkerManager,this.context,this.draw,this.occt),this.chirpyChalet=new UK(this.occWorkerManager,this.context,this.draw,this.occt)}}class zK{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.birdhouses=new GK(this.occWorkerManager,this.context,this.draw,this.occt)}}var WK,XK,qK,YK,KK,jK,$K=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class QK{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return $K(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.serenitySwirl",e);return t?{type:t.data.type,name:t.data.name,compound:t.compound}:void 0}))}drawModel(e,t=.003){return $K(this,void 0,void 0,(function*(){const i=new Yt("brepMesh"+Math.random(),this.context.scene),r=new QH.DrawOcctShapeOptions;r.faceOpacity=0,r.edgeColour="#bc7e5b",r.edgeWidth=.6,r.precision=t;const s=yield this.draw.drawAnyAsync({entity:e.compound,options:r}),n=new zm("brepMaterial"+Math.random(),this.context.scene);return n.albedoColor=new hc.v9(1,1,1),n.ambientColor=hc.v9.FromHexString("#ffffff"),n.metallic=0,n.roughness=.7,n.zOffset=1,s.getChildMeshes()[0].material=n,s.material=n,s.parent=i,i}))}dispose(e){return $K(this,void 0,void 0,(function*(){const t=[e.compound];yield this.occt.deleteShapes({shapes:t})}))}}!function(e){e.low="low",e.middle="middle",e.high="high"}(WK||(WK={}));class ZK{constructor(){this.lod=WK.low}}class JK{}class ej{constructor(e,t,i,r,s,n,o,a,l){this.swirl=.6,this.nrOfDivisions=10,this.addRadiusNarrow=.4,this.addRadiusWide=.2,this.addMiddleHeight=1.6,this.addTopHeight=1.5,this.thickness=1,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.swirl=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.addRadiusNarrow=i),void 0!==r&&(this.addRadiusWide=r),void 0!==s&&(this.addMiddleHeight=s),void 0!==n&&(this.addTopHeight=n),void 0!==o&&(this.thickness=o),void 0!==a&&(this.rotation=a),void 0!==l&&(this.origin=l)}}class tj{constructor(){this.type="parametric-model",this.name="serenitySwirl"}}class ij{}class rj{constructor(e,t,i,r,s,n,o,a,l,h,c,u){this.profilePoints=[[2,0,0],[4,5,0],[1.5,10,0],[3,14,0]],this.nrOfSides=6,this.nrOfVerticalArches=4,this.archCenterThickness=.8,this.edgesThickness=.2,this.thickness=1,this.baseHeight=.4,this.patchHoles=!0,this.lod=WK.high,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],this.scale=[1,1,1],void 0!==e&&(this.nrOfSides=e),void 0!==t&&(this.nrOfVerticalArches=t),void 0!==i&&(this.archCenterThickness=i),void 0!==r&&(this.edgesThickness=r),void 0!==s&&(this.thickness=s),void 0!==n&&(this.baseHeight=n),void 0!==o&&(this.patchHoles=o),void 0!==a&&(this.lod=a),void 0!==l&&(this.rotation=l),void 0!==h&&(this.origin=h),void 0!==c&&(this.direction=c),void 0!==u&&(this.scale=u)}}class sj{constructor(){this.type="parametric-model",this.name="arabicArchway"}}class nj{}class oj{}class aj{}class lj{constructor(e,t,i,r,s,n,o,a){this.textHeading="LOVE YOU",this.textName="NORA",this.fullModel=!0,this.thickness=6,this.decorationThickness=1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.textHeading=e),void 0!==t&&(this.textName=t),void 0!==i&&(this.fullModel=i),void 0!==r&&(this.thickness=r),void 0!==s&&(this.decorationThickness=s),void 0!==n&&(this.rotation=n),void 0!==o&&(this.origin=o),void 0!==a&&(this.direction=a)}}class hj{constructor(){this.type="parametric-model",this.name="eternalLove"}}class cj{}class uj{constructor(e,t,i,r,s,n,o,a,l,h,c,u){this.height=6,this.radiusBottom=4,this.radiusTopOffset=2,this.thickness=.6,this.fillet=.2,this.nrOfHandles=1,this.handleDist=2,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.radiusBottom=t),void 0!==i&&(this.radiusTopOffset=i),void 0!==r&&(this.thickness=r),void 0!==s&&(this.fillet=s),void 0!==n&&(this.nrOfHandles=n),void 0!==o&&(this.handleDist=o),void 0!==a&&(this.precision=a),void 0!==l&&(this.rotation=l),void 0!==h&&(this.scale=h),void 0!==c&&(this.origin=c),void 0!==u&&(this.direction=u)}}class dj{constructor(){this.type="parametric-model",this.name="calmCup"}}class fj{}class pj{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m,g,v,x,b){this.height=8,this.radiusBottom=4,this.radiusTopOffset=2,this.radiusMidOffset=2,this.rotationTopAngle=20,this.rotationMidAngle=20,this.nrSkinCellsVertical=5,this.nrSkinCellsHorizontal=10,this.nrSkinCellDivisionsTop=1,this.nrSkinCellDivisionsBottom=3,this.skinCellOuterHeight=.4,this.skinCellInnerHeight=.3,this.skinCellBottomHeight=.4,this.skinCellTopHeight=.4,this.thickness=.6,this.bottomThickness=1,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.radiusBottom=t),void 0!==i&&(this.radiusTopOffset=i),void 0!==r&&(this.radiusMidOffset=r),void 0!==s&&(this.rotationTopAngle=s),void 0!==n&&(this.rotationMidAngle=n),void 0!==o&&(this.nrSkinCellsVertical=o),void 0!==a&&(this.nrSkinCellsHorizontal=a),void 0!==l&&(this.nrSkinCellDivisionsTop=l),void 0!==h&&(this.nrSkinCellDivisionsBottom=h),void 0!==c&&(this.skinCellOuterHeight=c),void 0!==u&&(this.skinCellInnerHeight=u),void 0!==d&&(this.skinCellBottomHeight=d),void 0!==f&&(this.skinCellTopHeight=f),void 0!==p&&(this.thickness=p),void 0!==_&&(this.bottomThickness=_),void 0!==m&&(this.precision=m),void 0!==g&&(this.rotation=g),void 0!==v&&(this.scale=v),void 0!==x&&(this.origin=x),void 0!==b&&(this.direction=b)}}class _j{constructor(){this.type="parametric-model",this.name="dragonCup"}}class mj{}class gj{}class vj{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m,g){this.heightBottom=5,this.heightTop=16,this.widthBack=25,this.widthFront=10,this.length=16,this.backOffset=6,this.thickness=.4,this.applyOrnaments=!1,this.filletRadius=2,this.phoneHeight=16.8,this.phoneWidth=7.8,this.phoneThickness=.7,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.heightBottom=e),void 0!==t&&(this.heightTop=t),void 0!==i&&(this.widthBack=i),void 0!==r&&(this.widthFront=r),void 0!==s&&(this.length=s),void 0!==n&&(this.backOffset=n),void 0!==o&&(this.thickness=o),void 0!==a&&(this.applyOrnaments=a),void 0!==l&&(this.filletRadius=l),void 0!==h&&(this.phoneHeight=h),void 0!==c&&(this.phoneWidth=c),void 0!==u&&(this.phoneThickness=u),void 0!==d&&(this.precision=d),void 0!==f&&(this.drawEdges=f),void 0!==p&&(this.rotation=p),void 0!==_&&(this.scale=_),void 0!==m&&(this.origin=m),void 0!==g&&(this.direction=g)}}class xj{constructor(){this.type="parametric-model",this.name="phoneNest"}}class bj extends JK{}class Sj{}class Tj extends JK{}class Cj{}class yj{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class Ej{}class Pj{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m,g,v){this.textTop="Pepper",this.textFront="For Your Spicy Needs",this.nrSides=4,this.nrOffsets=1,this.height=6,this.radiusBase=4,this.radiusOffset=2,this.coverHeight=1,this.baseHeight=1,this.thickness=.6,this.ornamentalThickness=.1,this.nrOrnamnetsPerSide=10,this.invertOrnaments=!1,this.fillet=.2,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.textTop=e),void 0!==t&&(this.textFront=t),void 0!==i&&(this.nrSides=i),void 0!==r&&(this.nrOffsets=r),void 0!==s&&(this.height=s),void 0!==n&&(this.coverHeight=n),void 0!==o&&(this.baseHeight=o),void 0!==a&&(this.radiusBase=a),void 0!==l&&(this.radiusOffset=l),void 0!==h&&(this.thickness=h),void 0!==c&&(this.ornamentalThickness=c),void 0!==u&&(this.nrOrnamnetsPerSide=u),void 0!==d&&(this.invertOrnaments=d),void 0!==f&&(this.fillet=f),void 0!==p&&(this.precision=p),void 0!==_&&(this.rotation=_),void 0!==m&&(this.scale=m),void 0!==g&&(this.origin=g),void 0!==v&&(this.direction=v)}}class Aj{constructor(){this.type="parametric-model",this.name="spicyBox"}}class Rj{}class Ij{}class Mj{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m,g,v,x,b,S,T,C,y,E,P,A,R,I){this.widthFirstWing=4,this.lengthFirstWing=10,this.terraceWidth=3,this.widthSecondWing=5,this.lengthSecondWing=10,this.heightWalls=3,this.roofAngleFirstWing=15,this.roofAngleSecondWing=25,this.roofOffset=.5,this.roofInsideOverhang=.5,this.roofMaxDistAttachmentBeams=.8,this.roofAttachmentBeamWidth=.2,this.roofAttachmentBeamHeight=.05,this.roofOutsideOverhang=.5,this.columnSize=.3,this.ceilingBeamHeight=.25,this.ceilingBeamWidth=.1,this.nrCeilingBeamsBetweenColumns=3,this.distBetweenColumns=2,this.floorHeight=.1,this.groundLevel=.6,this.facadePanelThickness=.05,this.windowWidthOffset=.1,this.windowHeightOffset=.2,this.windowFrameThickness=.1,this.windowGlassFrameThickness=.05,this.lod=WK.high,this.skinOpacity=1,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.widthFirstWing=e),void 0!==t&&(this.lengthFirstWing=t),void 0!==i&&(this.terraceWidth=i),void 0!==r&&(this.widthSecondWing=r),void 0!==s&&(this.lengthSecondWing=s),void 0!==n&&(this.heightWalls=n),void 0!==o&&(this.roofAngleFirstWing=o),void 0!==a&&(this.roofAngleSecondWing=a),void 0!==l&&(this.roofOffset=l),void 0!==h&&(this.roofInsideOverhang=h),void 0!==c&&(this.roofMaxDistAttachmentBeams=c),void 0!==u&&(this.roofAttachmentBeamWidth=u),void 0!==d&&(this.roofAttachmentBeamHeight=d),void 0!==f&&(this.roofOutsideOverhang=f),void 0!==p&&(this.columnSize=p),void 0!==_&&(this.ceilingBeamHeight=_),void 0!==m&&(this.ceilingBeamWidth=m),void 0!==g&&(this.nrCeilingBeamsBetweenColumns=g),void 0!==v&&(this.distBetweenColumns=v),void 0!==x&&(this.floorHeight=x),void 0!==b&&(this.groundLevel=b),void 0!==S&&(this.facadePanelThickness=S),void 0!==T&&(this.windowWidthOffset=T),void 0!==C&&(this.windowHeightOffset=C),void 0!==y&&(this.windowFrameThickness=y),void 0!==E&&(this.windowGlassFrameThickness=E),void 0!==P&&(this.lod=P),void 0!==A&&(this.skinOpacity=A),void 0!==R&&(this.rotation=R),void 0!==I&&(this.origin=I)}}class Oj{constructor(){this.type="parametric-model",this.name="zenHideout"}}class Dj{}class wj{}class Nj{constructor(){this.wallThickness=.4,this.facadePanelThickness=.05,this.glassFrameThickness=.02,this.glassThickness=.005,this.frameThckness=.05,this.height=3,this.lengthFirst=1,this.lengthSecond=2,this.rotation=0}}class Fj{constructor(){this.thickness=.3,this.glassFrameThickness=.02,this.glassThickness=.005,this.frameThickness=.05,this.height=3,this.width=1,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0]}}class Lj extends Fj{}class Bj extends Nj{}class Vj{constructor(){this.name="sandwitch-panel",this.createWindow=!0,this.createInnerPanel=!0,this.createExteriorPanel=!0,this.wallWidth=.3,this.exteriorPanelWidth=.4,this.exteriorPanelHeight=3,this.exteriorPanelThickness=.05,this.exteriorPanelBottomOffset=0,this.interiorPanelWidth=.4,this.interiorPanelHeight=3,this.interiorPanelThickness=.05,this.interiorPanelBottomOffset=0,this.windowWidthOffset=0,this.windowHeightOffset=0,this.windowFrameThickness=.1,this.windowGlassFrameThickness=.05}}class kj{constructor(){this.name="sandwitch-panel-flex",this.createInteriorPanel=!0,this.createExteriorPanel=!0,this.wallWidth=.3,this.exteriorPanelThickness=.05,this.interiorPanelThickness=.05,this.interiorPanelPolygonPoints=[],this.exteriorPanelPolygonPoints=[]}}class Uj extends Vj{}class Gj extends kj{}class zj{}class Wj{}class Hj{}class Xj{}class qj{}class Yj{}class Kj{constructor(){this.invert=!1,this.widthFirstLanding=1,this.widthSecondLanding=1,this.lengthFirstWing=2,this.lengthSecondWing=1,this.maxWishedStepHeight=.25,this.stepHeightWidthProportion=1.35,this.totalHeight=1,this.rotation=0,this.origin=[0,0,0]}}class jj extends Kj{}class $j{}class Qj{constructor(){this.name="roof-cover",this.roofAngle=15,this.roofLength=3,this.roofWidth=3,this.roofOutsideOverhang=.5,this.roofInsideOverhang=1,this.roofOverhangFacade=.1,this.roofThickness=.05,this.roofCoverHeight=.3,this.rotation=0,this.lod=WK.high,this.center=[0,0,0],this.direction=[0,1,0]}}class Zj extends Qj{}class Jj{}class e${}class t${constructor(){this.widthFirstWing=1,this.widthSecondWing=2,this.lengthStairFirstWing=2,this.lengthStairSecondWing=1,this.lengthWallFirstWing=2,this.lengthWallSecondWing=1,this.facadePanelThickness=.05,this.wallThickness=3,this.wallHeightExterior=3,this.wallHeightInterior=3,this.windowFrameOffsetTop=.3,this.windowFrameThickness=.1,this.glassFrameThickness=.05,this.doorWidth=1,this.windowWidthOffset=.3,this.stairTotalHeight=1,this.createStair=!1,this.flipDirection=!1,this.rotation=0,this.origin=[0,0,0]}}class i${constructor(e,t,i,r,s,n,o,a,l,h,c,u,d){this.interiorWidth=3,this.interiorLength=3,this.interiorHeight=5,this.thickness=.5,this.holeDiameter=1.5,this.holeDistToBottom=2.5,this.stickLength=1.2,this.stickDiameter=.5,this.baseAttachmentHeight=2,this.roofOverhang=1,this.rotation=0,this.chimneyHeight=1,this.origin=[0,0,0],void 0!==e&&(this.interiorWidth=e),void 0!==t&&(this.interiorLength=t),void 0!==i&&(this.interiorHeight=i),void 0!==r&&(this.thickness=r),void 0!==s&&(this.holeDiameter=s),void 0!==n&&(this.holeDistToBottom=n),void 0!==o&&(this.stickLength=o),void 0!==a&&(this.stickDiameter=a),void 0!==l&&(this.baseAttachmentHeight=l),void 0!==h&&(this.roofOverhang=h),void 0!==c&&(this.rotation=c),void 0!==u&&(this.chimneyHeight=u),void 0!==d&&(this.origin=d)}}class r${constructor(){this.type="parametric-model",this.name="wingtipVilla"}}class s${constructor(e,t,i,r,s,n,o,a,l,h,c,u,d){this.interiorWidth=3,this.interiorLength=3,this.interiorHeight=5,this.thickness=.3,this.holeDiameter=1.2,this.holeDistToBottom=2.5,this.stickLength=.9,this.stickDiameter=.3,this.baseAttachmentHeight=2,this.roofOverhang=.5,this.roofAngle=20,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.interiorWidth=e),void 0!==t&&(this.interiorLength=t),void 0!==i&&(this.interiorHeight=i),void 0!==r&&(this.thickness=r),void 0!==s&&(this.holeDiameter=s),void 0!==n&&(this.holeDistToBottom=n),void 0!==o&&(this.stickLength=o),void 0!==a&&(this.stickDiameter=a),void 0!==l&&(this.baseAttachmentHeight=l),void 0!==h&&(this.roofOverhang=h),void 0!==c&&(this.roofAngle=c),void 0!==u&&(this.rotation=u),void 0!==d&&(this.origin=d)}}class n${constructor(){this.type="parametric-model",this.name="chirpyChalet"}}class o${}class a${constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p){this.sittingHeight=.45,this.backRestOffset=.1,this.backRestHeight=.7,this.width=.45,this.length=.45,this.thickness=.05,this.nrOrnamentPlanks=7,this.ornamentDepth=.01,this.filletRadius=.05,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.sittingHeight=e),void 0!==t&&(this.backRestOffset=t),void 0!==i&&(this.backRestHeight=i),void 0!==r&&(this.width=r),void 0!==s&&(this.length=s),void 0!==n&&(this.thickness=n),void 0!==o&&(this.nrOrnamentPlanks=o),void 0!==a&&(this.ornamentDepth=a),void 0!==l&&(this.filletRadius=l),void 0!==h&&(this.precision=h),void 0!==c&&(this.drawEdges=c),void 0!==u&&(this.rotation=u),void 0!==d&&(this.scale=d),void 0!==f&&(this.origin=f),void 0!==p&&(this.direction=p)}}class l${constructor(){this.type="parametric-model",this.name="snakeChair"}}class h$ extends JK{}class c${}class u$ extends JK{}class d${}class f${constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class p${}class _${constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_){this.height=.74,this.width=1,this.length=2,this.topThickness=.02,this.topOffset=.03,this.bottomThickness=.05,this.minFillet=.2,this.radiusLegTop=.03,this.radiusLegBottom=.01,this.nrLegPairs=2,this.precision=.001,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==r&&(this.topThickness=r),void 0!==s&&(this.topOffset=s),void 0!==n&&(this.bottomThickness=n),void 0!==o&&(this.minFillet=o),void 0!==a&&(this.radiusLegTop=a),void 0!==l&&(this.radiusLegBottom=l),void 0!==h&&(this.nrLegPairs=h),void 0!==c&&(this.precision=c),void 0!==u&&(this.drawEdges=u),void 0!==d&&(this.rotation=d),void 0!==f&&(this.scale=f),void 0!==p&&(this.origin=p),void 0!==_&&(this.direction=_)}}class m${constructor(){this.type="parametric-model",this.name="elegantTable"}}class g$ extends JK{}class v${}class x$ extends JK{}class b$ extends JK{}class S${constructor(){this.index=0}}class T${}class C${constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class y${}class E${constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m,g){this.height=.4,this.width=1,this.length=1.2,this.chamfer=.01,this.topThickness=.05,this.topGlassOffset=.2,this.glassThickness=.005,this.glassHolderLength=.02,this.shelfTopOffset=.15,this.shelfThickness=.03,this.legWidth=.1,this.legDepth=.05,this.precision=.001,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==r&&(this.chamfer=r),void 0!==s&&(this.topThickness=s),void 0!==n&&(this.topGlassOffset=n),void 0!==o&&(this.glassThickness=o),void 0!==a&&(this.glassHolderLength=a),void 0!==l&&(this.shelfTopOffset=l),void 0!==h&&(this.shelfThickness=h),void 0!==c&&(this.legWidth=c),void 0!==u&&(this.legDepth=u),void 0!==d&&(this.precision=d),void 0!==f&&(this.drawEdges=f),void 0!==p&&(this.rotation=p),void 0!==_&&(this.scale=_),void 0!==m&&(this.origin=m),void 0!==g&&(this.direction=g)}}class P${constructor(){this.type="parametric-model",this.name="goodCoffeeTable"}}class A$ extends JK{}class R${}class I$ extends JK{}class M$ extends JK{}class O$ extends JK{}class D${constructor(){this.index=0}}class w${}class N${constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class F${}class L${constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m){this.height=.74,this.width=1,this.length=2,this.supportLength=.5,this.shelfHeight=.2,this.thickness=.05,this.glassThickness=.005,this.glassOffset=0,this.nrOrnamentPlanks=7,this.ornamentDepth=.01,this.filletRadius=.05,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==r&&(this.supportLength=r),void 0!==s&&(this.shelfHeight=s),void 0!==n&&(this.thickness=n),void 0!==o&&(this.glassThickness=o),void 0!==a&&(this.glassOffset=a),void 0!==l&&(this.nrOrnamentPlanks=l),void 0!==h&&(this.ornamentDepth=h),void 0!==c&&(this.filletRadius=c),void 0!==u&&(this.precision=u),void 0!==d&&(this.drawEdges=d),void 0!==f&&(this.rotation=f),void 0!==p&&(this.scale=p),void 0!==_&&(this.origin=_),void 0!==m&&(this.direction=m)}}class B${constructor(){this.type="parametric-model",this.name="snakeTable"}}class V$ extends JK{}class k${}class U$ extends JK{}class G${}class z${constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}!function(e){e.Aboreto="Aboreto",e.Bungee="Bungee",e.IndieFlower="IndieFlower",e.Lugrasimo="Lugrasimo",e.Orbitron="Orbitron",e.Roboto="Roboto",e.RobotoSlab="RobotoSlab",e.Silkscreen="Silkscreen",e.Tektur="Tektur",e.Workbench="Workbench"}(XK||(XK={})),function(e){e.Regular="Regular",e.Black="Black",e.Bold="Bold",e.ExtraBold="ExtraBold",e.Medium="Medium",e.SemiBold="SemiBold",e.BlackItalic="BlackItalic",e.BoldItalic="BoldItalic",e.Italic="Italic",e.Light="Light",e.LightItalic="LightItalic",e.MediumItalic="MediumItalic",e.Thin="Thin",e.ThinItalic="ThinItalic",e.ExtraLight="ExtraLight"}(qK||(qK={})),function(e){e.separatedExtrusion="separatedExtrusion",e.integratedExtrusion="integratedExtrusion",e.cutout="cutout"}(YK||(YK={})),function(e){e.compound="compound",e.cutout="originalCutout",e.cutoutInsideCharacter="cutoutInsideCharacter"}(KK||(KK={})),function(e){e.leftTop="leftTop",e.leftMiddle="leftMiddle",e.leftBottom="leftBottom",e.centerTop="centerTop",e.centerMiddle="centerMiddle",e.centerBottom="centerBottom",e.rightTop="rightTop",e.rightMiddle="rightMiddle",e.rightBottom="rightBottom"}(jK||(jK={}));const W$=[{key:"Aboreto",variants:["Regular"]},{key:"Bungee",variants:["Regular"]},{key:"IndieFlower",variants:["Regular"]},{key:"Lugrasimo",variants:["Regular"]},{key:"Orbitron",variants:["Black","Bold","ExtraBold","Medium","Regular","SemiBold"]},{key:"Roboto",variants:["Black","BlackItalic","Bold","BoldItalic","Italic","Light","LightItalic","Medium","MediumItalic","Regular","Thin","ThinItalic"]},{key:"RobotoSlab",variants:["Black","Bold","ExtraBold","ExtraLight","Light","Medium","Regular","SemiBold","Thin"]},{key:"Silkscreen",variants:["Bold","Regular"]},{key:"Tektur",variants:["Black","Bold","ExtraBold","Medium","Regular","SemiBold"]},{key:"Workbench",variants:["Regular"]}];class H${constructor(e,t,i,r,s,n,o,a,l){this.text="bitbybit.dev",this.fontType=XK.Roboto,this.fontVariant=qK.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.origin=[0,0,0],this.direction=[0,1,0],this.originAlignment=jK.centerMiddle,void 0!==e&&(this.text=e),void 0!==t&&(this.fontType=t),void 0!==i&&(this.fontVariant=i),void 0!==r&&(this.fontSize=r),void 0!==s&&(this.height=s),void 0!==n&&(this.rotation=n),void 0!==o&&(this.origin=o),void 0!==a&&(this.direction=a),void 0!==l&&(this.originAlignment=l)}}class X${constructor(e,t,i,r,s,n,o,a,l,h,c,u){this.facePlanar=!1,this.faceTextVar=YK.separatedExtrusion,this.text="bitbybit.dev",this.fontType=XK.Roboto,this.fontVariant=qK.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.originParamU=.5,this.originParamV=.5,this.originAlignment=jK.centerMiddle,void 0!==e&&(this.face=e),void 0!==t&&(this.facePlanar=t),void 0!==i&&(this.faceTextVar=i),void 0!==r&&(this.text=r),void 0!==s&&(this.fontType=s),void 0!==n&&(this.fontVariant=n),void 0!==o&&(this.fontSize=o),void 0!==a&&(this.height=a),void 0!==l&&(this.rotation=l),void 0!==h&&(this.originParamU=h),void 0!==c&&(this.originParamV=c),void 0!==u&&(this.originAlignment=u)}}class q${constructor(){this.type="parametric-model",this.name="text3d"}}class Y${constructor(){this.index=0}}class K${}class j${}class $${constructor(e,t,i,r,s,n,o,a,l,h){this.faceTextVar=YK.separatedExtrusion,this.text="bitbybit.dev",this.fontType=XK.Roboto,this.fontVariant=qK.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.originParamU=.5,this.originParamV=.5,this.originAlignment=jK.centerMiddle,void 0!==e&&(this.faceTextVar=e),void 0!==t&&(this.text=t),void 0!==i&&(this.fontType=i),void 0!==r&&(this.fontVariant=r),void 0!==s&&(this.fontSize=s),void 0!==n&&(this.height=n),void 0!==o&&(this.rotation=o),void 0!==a&&(this.originParamU=a),void 0!==l&&(this.originParamV=l),void 0!==h&&(this.originAlignment=h)}}class Q${constructor(e,t,i){this.facePlanar=!1,void 0!==e&&(this.face=e),void 0!==t&&(this.facePlanar=t),void 0!==i&&(this.definitions=i)}}class Z${constructor(e,t,i,r){this.uNumber=10,this.vNumber=10,this.height=.2,this.precision=.01,void 0!==e&&(this.faces=e),void 0!==r&&(this.height=r)}}class J${constructor(e,t,i,r,s,n,o){this.uNumber=10,this.vNumber=5,this.defaultHeight=.2,this.affectMinHeight=0,this.affectMaxHeight=1,this.precision=.01,void 0!==e&&(this.faces=e),void 0!==t&&(this.affectorPoints=t),void 0!==i&&(this.uNumber=i),void 0!==r&&(this.vNumber=r),void 0!==s&&(this.affectMinHeight=s),void 0!==n&&(this.affectMaxHeight=n),void 0!==o&&(this.precision=o)}}class eQ{constructor(){this.type="parametric-model",this.name="patternsFacePatternPyramidSimple"}}class tQ{constructor(){this.index=0}}class iQ{}class rQ{}class sQ{}class nQ{}class oQ{constructor(){this.faceIndex=0}}class aQ{constructor(){this.faceIndex=0,this.uIndex=0,this.vIndex=0}}class lQ{constructor(){this.faceIndex=0,this.uIndex=0}}class hQ{constructor(){this.faceIndex=0,this.vIndex=0}}class cQ{}class uQ{}var dQ;!function(e){e.wire="wire",e.face="face",e.solid="solid"}(dQ||(dQ={}));class fQ{static parse(e,t){var i;const r=[e],s=new Set;for(;r.length>0;){const e=r.pop();if("object"==typeof e&&null!==e&&!s.has(e))if(s.add(e),Array.isArray(e))for(let t=0;tt.id===e.shapes[s])))||void 0===i?void 0:i.shape)}for(const t in e)r.push(e[t])}}return e}}var pQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class _Q{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return pQ(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.arabicArchway",e);if(t){const e=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},e),{type:t.data.type,name:t.data.name,compound:t.compound,shapes:t.shapes,originalInputs:t.data.originalInputs})}}))}drawModel(e,t=.003){return pQ(this,void 0,void 0,(function*(){const i=new Yt("brepMesh"+Math.random(),this.context.scene),r=new QH.DrawOcctShapeOptions;this.materials||(this.materials=this.createMaterials(e.originalInputs.lod)),r.faceOpacity=0,r.edgeColour="#bc7e5b",r.edgeWidth=.6,r.precision=t;const s={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?e.originalInputs.lod===WK.high&&"compound"===t?i(void 0):this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:r}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,t)=>{const r=o[t];if(r){if(r.parent=i,void 0!==this.materials[e]){const t=r.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}r.name=e,r.getChildMeshes().forEach((e=>e.isVisible=!0)),s[e]=r}})),i}))}dispose(e){return pQ(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}disposeMaterials(){this.materials&&Object.keys(this.materials).forEach((e=>{const t=this.materials[e];t&&t.dispose()}))}createMaterials(e){const t=new oj;return e===WK.high?t.compound=this.createBaseMaterial():t.compound=this.createOpaqueMaterial(),t.vasePartsCompound=this.createBaseMaterial(),t.glassPartsCompound=this.createGlassMaterial(),t.vaseBaseCompound=this.createBaseMaterial(),t}createOpaqueMaterial(){const e=new zm("opaqueMat"+Math.random(),this.context.scene);return e.albedoColor=new hc.v9(1,1,1),e.ambientColor=hc.v9.FromHexString("#ffffff"),e.metallic=0,e.roughness=.7,e.zOffset=1,e.backFaceCulling=!1,e.alpha=.3,e}createBaseMaterial(){const e=new zm("faceMaterial"+Math.random(),this.context.scene);return e.albedoColor=new hc.v9(1,1,1),e.ambientColor=hc.v9.FromHexString("#ffffff"),e.metallic=0,e.roughness=.7,e.zOffset=1,e}createGlassMaterial(){const e=new zm("faceGlassMaterial"+Math.random(),this.context.scene);return e.albedoColor=new hc.v9(0,0,.05),e.ambientColor=hc.v9.FromHexString("#ffffff"),e.metallic=.8,e.roughness=.1,e.zOffset=1,e.alpha=.5,e}}class mQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.serenitySwirl=new QK(this.occWorkerManager,this.context,this.draw,this.occt),this.arabicArchway=new _Q(this.occWorkerManager,this.context,this.draw,this.occt)}}var gQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class vQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return gQ(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.eternalLove",e);return t?{type:t.data.type,originalInputs:t.data.originalInputs,name:t.data.name,compound:t.compound}:void 0}))}drawModel(e,t=.003){return gQ(this,void 0,void 0,(function*(){const i=new Yt("brepMesh"+Math.random(),this.context.scene),r=new QH.DrawOcctShapeOptions;r.faceOpacity=0,r.edgeColour="#bc7e5b",r.edgeWidth=.6,r.precision=t;const s=yield this.draw.drawAnyAsync({entity:e.compound,options:r}),n=new zm("brepMaterial"+Math.random(),this.context.scene);return n.albedoColor=new hc.v9(1,.9,1),n.ambientColor=hc.v9.FromHexString("#ff00ff"),n.metallic=.8,n.roughness=.7,n.zOffset=1,s.getChildMeshes()[0].material=n,s.material=n,s.parent=i,i}))}dispose(e){return gQ(this,void 0,void 0,(function*(){const t=[e.compound];yield this.occt.deleteShapes({shapes:t})}))}}class xQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.eternalLove=new vQ(this.occWorkerManager,this.context,this.draw,this.occt)}}var bQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class SQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return bQ(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.calmCup",e);return t?{type:t.data.type,originalInputs:t.data.originalInputs,name:t.data.name,compound:t.compound}:void 0}))}drawModel(e){return bQ(this,void 0,void 0,(function*(){const t=new Yt("brepMesh"+Math.random(),this.context.scene),i=new QH.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#bc7e5b",i.edgeWidth=.6*e.originalInputs.scale,i.precision=e.originalInputs.precision*e.originalInputs.scale;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:i}),s=new zm("brepMaterial"+Math.random(),this.context.scene);return s.albedoColor=new hc.v9(1,1,1),s.ambientColor=hc.v9.FromHexString("#ffffff"),s.metallic=.8,s.roughness=.7,s.zOffset=2,r.getChildMeshes()[0].material=s,r.material=s,r.parent=t,t}))}dispose(e){return bQ(this,void 0,void 0,(function*(){const t=[e.compound];yield this.occt.deleteShapes({shapes:t})}))}}var TQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class CQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return TQ(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.dragonCup",e);return t?{type:t.data.type,originalInputs:t.data.originalInputs,name:t.data.name,compound:t.compound}:void 0}))}getCompoundShape(e){return e.model.compound}drawModel(e){return TQ(this,void 0,void 0,(function*(){const t=new Yt("brepMesh"+Math.random(),this.context.scene),i=new QH.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#617bff",i.edgeWidth=.6*e.originalInputs.scale,i.precision=e.originalInputs.precision*e.originalInputs.scale;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:i}),s=new zm("brepMaterial"+Math.random(),this.context.scene);return s.albedoColor=hc.v9.FromHexString("#2b00ff"),s.ambientColor=hc.v9.FromHexString("#ffffff"),s.metallic=.9,s.roughness=.3,s.zOffset=2,r.getChildMeshes()[0].material=s,r.material=s,r.parent=t,t}))}}class yQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.calmCup=new SQ(this.occWorkerManager,this.context,this.draw,this.occt),this.dragonCup=new CQ(this.occWorkerManager,this.context,this.draw,this.occt)}}var EQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class PQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return EQ(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.main.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.phoneNest",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}drawOptions(e){return e}drawModel(e,t){return EQ(this,void 0,void 0,(function*(){const i=new Yt("brepMesh"+Math.random(),this.context.scene),r=new QH.DrawOcctShapeOptions;t?(r.drawEdges=t.drawEdges,r.drawFaces=t.drawFaces,r.edgeColour=t.edgeColour,r.edgeWidth=t.edgeWidth,r.precision=t.precision):(r.faceOpacity=0,r.drawEdges=e.originalInputs.drawEdges,r.edgeColour="#ffffff",r.edgeWidth=.06*e.originalInputs.scale,r.precision=e.originalInputs.precision*e.originalInputs.scale);const s={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?("phone"===t&&(r.edgeColour="#000000"),this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:r}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)}))):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,r)=>{const n=o[r];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),s[e]=n}})),i}))}dispose(e){return EQ(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="phone-nest-",t=new Sj,i=LK.wood3Material(this.context.scene,Math.PI/2,1);i.name=e+i.name,t.main=i;const r=LK.glass(this.context.scene,"#000000");return r.name=e+r.name,t.phone=r,t}}class AQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.phoneNest=new PQ(this.occWorkerManager,this.context,this.draw,this.occt)}}class RQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.vases=new mQ(this.occWorkerManager,this.context,this.draw,this.occt),this.cups=new yQ(this.occWorkerManager,this.context,this.draw,this.occt),this.medals=new xQ(this.occWorkerManager,this.context,this.draw,this.occt),this.desktop=new AQ(this.occWorkerManager,this.context,this.draw,this.occt)}}var IQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class MQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return IQ(this,void 0,void 0,(function*(){void 0===this.materials&&(this.materials=this.createMaterials()),void 0===this.skin&&(this.skin=this.createSkin());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.zenHideout",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}drawModel(e,t=.003){return IQ(this,void 0,void 0,(function*(){const i=new Yt("brepMesh"+Math.random(),this.context.scene),r=new QH.DrawOcctShapeOptions;if(r.faceOpacity=0,r.edgeColour="#bc7e5b",r.edgeWidth=.06,r.precision=t,e.originalInputs.lod===WK.high&&e.drawingPart){const t={},s=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:r}).then((r=>{r.isVisible=!1,r.getChildMeshes().forEach((e=>e.isVisible=!1)),!0===this.skin[t]&&(r.visibility=e.originalInputs.skinOpacity,r.getChildMeshes().forEach((t=>t.visibility=e.originalInputs.skinOpacity))),i(r)}),(()=>{i(void 0)})):i(void 0)})))),n=yield Promise.all(s);Object.keys(e.drawingPart.shapes).forEach(((e,r)=>{const s=n[r];if(s){if(s.parent=i,void 0!==this.materials[e]){const t=s.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}s.name=e,s.isVisible=!0,s.getChildMeshes().forEach((e=>e.isVisible=!0)),t[e]=s}}))}else if(e.originalInputs.lod===WK.middle){const t=new zm("brepMaterial"+Math.random(),this.context.scene);t.albedoColor=new hc.v9(0,0,0),t.metallic=0,t.roughness=.7,t.zOffset=2;const s=yield this.draw.drawAnyAsync({entity:e.compound,options:r});s.getChildMeshes()[0].material=t,s.material=t,s.parent=i}else e.originalInputs.lod===WK.low&&(r.edgeColour="#e89668",r.edgeWidth=10,(yield this.draw.drawAnyAsync({entity:e.compound,options:r})).parent=i);return i}))}dispose(e){return IQ(this,void 0,void 0,(function*(){const t=e.shapes.map((e=>e.shape));yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="zen-hideout-",t=new wj,i=new Cb(e+"windowGlassCompound",this.context.scene);i.alpha=.2,i.metallic=.9,i.roughness=.1,i.baseColor=new hc.v9(.9,.9,1),i.zOffset=2,t.windowGlassCompound=i;const r=new Cb(e+"windowGlassCompound",this.context.scene);r.metallic=.1,r.roughness=.8,r.baseColor=new hc.v9(.05,.05,.05),r.zOffset=2,t.windowFrameCompound=r;const s=new Cb(e+"glassFramesCompound",this.context.scene);s.metallic=.1,s.roughness=.8,s.baseColor=new hc.v9(0,0,0),s.zOffset=2,t.glassFramesCompound=s;const n=LK.metal1(this.context.scene,0,.3);t.roofCoverFirstCompound=n,t.roofCoverSecondCompound=n;const o=LK.wood1Material(this.context.scene,0,1);t.beamsCompound=o,t.columnsCompound=o;const a=LK.woodenPlanks(this.context.scene,0,1);t.firstFloorExteriorPanelsCompound=a;const l=new Cb(e+"firstFloorInteriorPanelsCompound",this.context.scene);l.metallic=.1,l.roughness=.8,l.baseColor=new hc.v9(.1,.1,.1),l.zOffset=2,t.firstFloorInteriorPanelsCompound=l;const h=LK.wood3Material(this.context.scene,Math.PI/2,1);t.roofExteriorPanelsCompound=h;const c=new Cb(e+"roofInteriorPanelsCompound",this.context.scene);c.metallic=.1,c.roughness=.8,c.baseColor=new hc.v9(.3,.3,.3),c.zOffset=2,t.roofInteriorPanelsCompound=c;const u=LK.wood2Material(this.context.scene,0,.5);t.floorCompound=u;const d=new Cb(e+"ceilingCompound",this.context.scene);d.metallic=.3,d.roughness=.7,d.baseColor=new hc.v9(1,1,1),d.zOffset=2,t.ceilingCompound=d;const f=LK.brushedConcrete(this.context.scene,0,1);return t.stairsCompound=f,t}createSkin(){return{windowGlassCompound:!0,glassFramesCompound:!1,windowFrameCompound:!1,beamsCompound:!1,columnsCompound:!1,firstFloorExteriorPanelsCompound:!0,firstFloorInteriorPanelsCompound:!0,roofExteriorPanelsCompound:!0,roofInteriorPanelsCompound:!0,roofCoverFirstCompound:!0,roofCoverSecondCompound:!0,floorCompound:!0,ceilingCompound:!0,stairsCompound:!1}}}class OQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.zenHideout=new MQ(this.occWorkerManager,this.context,this.draw,this.occt)}}class DQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.houses=new OQ(this.occWorkerManager,this.context,this.draw,this.occt)}}class wQ{lodEnum(e){return e.lod}}var NQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class FQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return NQ(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.top.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.elegantTable",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getLegShapes(e){return e.model.legParts.map((e=>e.shapes.leg))}getLegShapeByIndex(e){return e.index>=0&&e.indexe.bottomCenter))}getLegTopPoints(e){return e.model.legParts.map((e=>e.topCenter))}drawOptions(e){return e}drawModel(e,t){return NQ(this,void 0,void 0,(function*(){const i=new Yt("brepMesh"+Math.random(),this.context.scene),r=new QH.DrawOcctShapeOptions;t?(r.drawEdges=t.drawEdges,r.drawFaces=t.drawFaces,r.edgeColour=t.edgeColour,r.edgeWidth=t.edgeWidth,r.precision=t.precision):(r.faceOpacity=0,r.drawEdges=e.originalInputs.drawEdges,r.edgeColour="#bc7e5b",r.edgeWidth=.06*e.originalInputs.scale,r.precision=e.originalInputs.precision*e.originalInputs.scale);const s={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:r}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,r)=>{const n=o[r];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),s[e]=n}})),i}))}dispose(e){return NQ(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="elegant-table-",t=new v$,i=LK.wood3Material(this.context.scene,Math.PI/2,2);i.name=e+i.name,t.top=i;const r=LK.wood1Material(this.context.scene,Math.PI/2,2);r.name=e+i.name,t.topBase=r;const s=LK.wood1Material(this.context.scene,0,1);return s.name=e+i.name,t.legs=s,t}}var LQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class BQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return LQ(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.top.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.goodCoffeeTable",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getLegShapes(e){return e.model.legParts.map((e=>e.shapes.leg))}getLegShapeByIndex(e){return e.index>=0&&e.indexe.bottomCenter))}getLegTopPoints(e){return e.model.legParts.map((e=>e.topCenter))}drawOptions(e){return e}drawModel(e,t){return LQ(this,void 0,void 0,(function*(){const i=new Yt("brepMesh"+Math.random(),this.context.scene),r=new QH.DrawOcctShapeOptions;t?(r.drawEdges=t.drawEdges,r.drawFaces=t.drawFaces,r.edgeColour=t.edgeColour,r.edgeWidth=t.edgeWidth,r.precision=t.precision):(r.faceOpacity=0,r.drawEdges=e.originalInputs.drawEdges,r.edgeColour="#bc7e5b",r.edgeWidth=.06*e.originalInputs.scale,r.precision=e.originalInputs.precision*e.originalInputs.scale);const s={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:r}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,r)=>{const n=o[r];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),s[e]=n}})),i}))}dispose(e){return LQ(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="good-coffee-table-",t=new R$,i=LK.wood3Material(this.context.scene,Math.PI/2,2);i.name=e+i.name,t.top=i,t.legs=i,t.shelf=i;const r=LK.glass(this.context.scene,"#000000");return r.name=e+i.name,t.topGlass=r,t}}var VQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class kQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return VQ(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.main.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.snakeTable",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getGlassShape(e){return e.model.mainPart.shapes.glass}getMainShape(e){return e.model.mainPart.shapes.main}getTopCenterPoint(e){return e.model.mainPart.topCenter}drawOptions(e){return e}drawModel(e,t){return VQ(this,void 0,void 0,(function*(){const i=new Yt("brepMesh"+Math.random(),this.context.scene),r=new QH.DrawOcctShapeOptions;t?(r.drawEdges=t.drawEdges,r.drawFaces=t.drawFaces,r.edgeColour=t.edgeColour,r.edgeWidth=t.edgeWidth,r.precision=t.precision):(r.faceOpacity=0,r.drawEdges=e.originalInputs.drawEdges,r.edgeColour="#000000",r.edgeWidth=.06*e.originalInputs.scale,r.precision=e.originalInputs.precision*e.originalInputs.scale);const s={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:r}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,r)=>{const n=o[r];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),s[e]=n}})),i}))}dispose(e){return VQ(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="snake-table-",t=new k$,i=LK.roughPlastic(this.context.scene,"#ffffff");i.name=e+i.name,t.main=i;const r=LK.glass(this.context.scene,"#000000");return r.name=e+r.name,t.glass=r,t}}class UQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.elegantTable=new FQ(this.occWorkerManager,this.context,this.draw,this.occt),this.goodCoffeeTable=new BQ(this.occWorkerManager,this.context,this.draw,this.occt),this.snakeTable=new kQ(this.occWorkerManager,this.context,this.draw,this.occt)}}var GQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class zQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return GQ(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.main.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.snakeChair",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getSittingWireShape(e){return e.model.mainPart.shapes.sittingWire}getSittingAreaCenterPoint(e){return e.model.mainPart.sittingCenter}drawOptions(e){return e}drawModel(e,t){return GQ(this,void 0,void 0,(function*(){const i=new Yt("brepMesh"+Math.random(),this.context.scene),r=new QH.DrawOcctShapeOptions;t?(r.drawEdges=t.drawEdges,r.drawFaces=t.drawFaces,r.edgeColour=t.edgeColour,r.edgeWidth=t.edgeWidth,r.precision=t.precision):(r.faceOpacity=0,r.drawEdges=e.originalInputs.drawEdges,r.edgeColour="#000000",r.edgeWidth=.06*e.originalInputs.scale,r.precision=e.originalInputs.precision*e.originalInputs.scale);const s={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:r}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,r)=>{const n=o[r];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),s[e]=n}})),i}))}dispose(e){return GQ(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e=new c$,t=LK.roughPlastic(this.context.scene,"#ffffff");return t.name="snake-chair-"+t.name,e.main=t,e}}class WQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.snakeChair=new zQ(this.occWorkerManager,this.context,this.draw,this.occt)}}class HQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.chairs=new WQ(this.occWorkerManager,this.context,this.draw,this.occt),this.tables=new UQ(this.occWorkerManager,this.context,this.draw,this.occt)}}class XQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.kidsCorner=new zK(this.occWorkerManager,this.context,this.draw,this.occt),this.threeDPrinting=new RQ(this.occWorkerManager,this.context,this.draw,this.occt),this.architecture=new DQ(this.occWorkerManager,this.context,this.draw,this.occt),this.furniture=new HQ(this.occWorkerManager,this.context,this.draw,this.occt),this.enums=new wQ}}var qQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class YQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return qQ(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.text3d",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}createTextOnFace(e){return qQ(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.text3dFace",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}createTextsOnFace(e){return qQ(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.texts3dFace",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}definition3dTextOnFace(e){return e}drawModel(e,t=.003){return qQ(this,void 0,void 0,(function*(){const i=new Yt("brepMesh"+Math.random(),this.context.scene),r=new QH.DrawOcctShapeOptions;r.faceOpacity=0,r.edgeColour="#bc7e5b",r.edgeWidth=.6,r.precision=t;const s=yield this.draw.drawAnyAsync({entity:e.compound,options:r}),n=new zm("brepMaterial"+Math.random(),this.context.scene);return n.albedoColor=new hc.v9(1,1,1),n.ambientColor=hc.v9.FromHexString("#ffffff"),n.metallic=0,n.roughness=.7,n.zOffset=1,s.getChildMeshes()[0].material=n,s.material=n,s.parent=i,i}))}getCompoundShape(e){return e.model.compound}getCharacterShape(e){if(e.index<0||e.index>=e.model.characterParts.length)throw new Error("Index is out of bounds.");return e.model.characterParts[e.index].shapes.compound}getCharacterShapes(e){return e.model.characterParts.map((e=>e.shapes.compound))}getCharacterCenterCoordinates(e){return e.model.characterCenterCoordinates}getFaceCutout(e){if(e.model.faceParts){const t=e.model.faceParts.filter((e=>e.type===KK.cutout)).map((e=>e.shapes.face));if(t.length>0)return t[0];throw new Error("No cutout was found.")}throw new Error("It seems this text was not created on the face, so there is no face cutout.")}getAllFacesOfCutout(e){if(e.model.faceParts)return e.model.faceParts.filter((e=>e.type===KK.cutout||e.type===KK.cutoutInsideCharacter)).map((e=>e.shapes.face));throw new Error("It seems this text was not created on the face, so there is no face cutout.")}getCutoutsInsideCharacters(e){if(e.model.faceParts)return e.model.faceParts.filter((e=>e.type===KK.cutoutInsideCharacter)).map((e=>e.shapes.face));throw new Error("It seems this text was not created on the face, so there is no face cutout.")}getAdvanceWidth(e){return e.model.advanceWidth}}var KQ,jQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class $Q{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}createPyramidSimple(e){return jQ(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.pyramidSimple",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}createPyramidSimpleAffectors(e){return jQ(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.pyramidSimpleAffectors",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}drawModel(e){return jQ(this,void 0,void 0,(function*(){const t=new Yt("brepMesh"+Math.random(),this.context.scene),i=new QH.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#bc7e5b",i.edgeWidth=1,i.precision=e.originalInputs.precision;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:i}),s=new zm("brepMaterial"+Math.random(),this.context.scene);return s.albedoColor=new hc.v9(1,1,1),s.ambientColor=hc.v9.FromHexString("#ffffff"),s.metallic=.3,s.roughness=.6,s.zOffset=2,r.getChildMeshes()[0].material=s,r.material=s,r.parent=t,t}))}getCompoundShape(e){return e.model.compound}getCompoundShapeOnFace(e){if(e.model.faceParts&&e.faceIndext.uIndex===e.uIndex&&t.vIndex===e.vIndex));if(t)return t.shapes.compound;throw new Error("Cell does not exist on the face")}throw new Error("Cell u or v index is out of range")}throw new Error("Face index is out of range")}getAllPyramidCells(e){return e.model.faceParts.map((e=>e.cells)).flat()}getAllPyramidCellsOnFace(e){if(e.model.faceParts&&e.faceIndext.uIndex===e.uIndex));throw new Error("Face index is out of range")}getAllPyramidUCellsOnFaceAtV(e){if(e.model.faceParts&&e.faceIndext.vIndex===e.vIndex));throw new Error("Face index is out of range")}getCellOnIndex(e){if(e.model.faceParts&&e.faceIndext.uIndex===e.uIndex&&t.vIndex===e.vIndex));if(t)return t;throw new Error("Cell does not exist on the face")}throw new Error("Cell u or v index is out of range")}throw new Error("Face index is out of range")}getTopPointsOfCells(e){return e.cells.map((e=>e.topPoint))}getCenterPointsOfCells(e){return e.cells.map((e=>e.centerPoint))}getCornerPointsOfCells(e){return e.cells.map((e=>[e.cornerPoint1,e.cornerPoint2,e.cornerPoint3,e.cornerPoint4].filter((e=>void 0!==e))))}getCornerPointOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.cornerPoint1:1===e.index?t.cornerPoint2:2===e.index?t.cornerPoint3:3===e.index?t.cornerPoint4:void 0));throw new Error("Corner index is out of range")}getCornerNormalOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.cornerNormal1:1===e.index?t.cornerNormal2:2===e.index?t.cornerNormal3:3===e.index?t.cornerNormal4:void 0));throw new Error("Corner index is out of range")}getCornerNormalsOfCells(e){return e.cells.map((e=>[e.cornerNormal1,e.cornerNormal2,e.cornerNormal3,e.cornerNormal4].filter((e=>void 0!==e))))}getCompoundShapesOfCells(e){return e.cells.map((e=>e.shapes.compound))}getFaceShapesOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.shapes.face1:1===e.index?t.shapes.face2:2===e.index?t.shapes.face3:3===e.index?t.shapes.face4:void 0));throw new Error("Face index is out of range")}getWireShapesOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.shapes.wire1:1===e.index?t.shapes.wire2:2===e.index?t.shapes.wire3:3===e.index?t.shapes.wire4:void 0));throw new Error("Wire index is out of range")}getStartPolylineWireU(e){if(e.faceIndex>=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]0&&"string"!=typeof t[e])for(var i=function(i){var r=t[e][i];"object"==typeof r&&null!==r&&r.then&&(r.then((function(r){return t[e][i]=r,r})),n.push(t[e][i]))},r=0;r0&&e.startedAsyncTask(i,r,"#eeeeff"),n.length>0?[2,Promise.all(n).then((function(t){return e.finishedAsyncTask(i,r),t}))]:[2,null]}))}))},e.finishedAsyncTask=function(e,t){},e.startedAsyncTask=function(e,t,i){},e.runtimeValidation=function(e,t){},e.validate=function(e,t,i){},e.handleBlockException=function(e,t){},e.errorHappened=function(e,t,i){},e.updateListInputs=function(e){Object.keys(e).forEach((function(t){if(Array.isArray(e[t])){var i=[];e[t].forEach((function(e){if(e&&e.result){var t=e.result;e.transformers&&e.transformers.length&&e.transformers.forEach((function(e){e.type===iZ.flat&&(t=t.flat())})),t instanceof Array?i.push.apply(i,t):i.push(t)}})),e[t]=i}}))},e.executeBasedOnTypeAsync=function(e,t,i){return sZ(this,void 0,void 0,(function(){var r,s,n,o,a,l,h,c,u;return nZ(this,(function(d){switch(d.label){case 0:if(t)return[3,5];l=this.performActionOnAllVariationsSimplified(e,i),d.label=1;case 1:return d.trys.push([1,3,,4]),[4,Promise.all(l)];case 2:return r=d.sent(),[3,4];case 3:throw s=d.sent(),new Error(s);case 4:return[3,9];case 5:if(!t)return[3,9];for(n=Object.keys(e),o=n.map((function(t){return e[t]})),a=this.normalizeListsToEqualLength(o),l=[],h=function(e){var t={};n.forEach((function(i,r){t[i]=o[r][e]})),l.push(i(t,e))},c=0;ct&&(t=e.length)})),t},e.drawNodeMeshes=function(e,t){return sZ(this,void 0,void 0,(function(){var i,r=this;return nZ(this,(function(s){switch(s.label){case 0:return i=e.map((function(e){return sZ(r,void 0,void 0,(function(){var i,r,s;return nZ(this,(function(n){switch(n.label){case 0:return i=e.result,r=[],i instanceof Array&&i.length>0&&i[0]&&i[0].hash?i.forEach((function(e){var i=t.draw.drawAnyAsync({entity:e,options:void 0});r.push(i)})):(s=t.draw.drawAnyAsync({entity:i,options:void 0}),r.push(s)),[4,Promise.all(r)];case 1:return[2,n.sent()]}}))}))})),[4,Promise.all(i)];case 1:return s.sent(),[2]}}))}))},e}(),hZ=function(){function e(e){this.context=e}return e.prototype.handleTags=function(e,t,i,r){var s=this;!t&&this.context.tagBag.length>0&&this.context.tagBag.find((function(e){return e.needsUpdate}))&&(t=!0),t&&this.context.tagBag.length>0&&this.context.tagBag.forEach((function(t){var n=document.querySelector("#"+t.id),o=new hc.Pq(t.position[0],t.position[1],t.position[2]);n.textContent=t.text;var a=i.getRenderWidth()/2,l=i.getRenderHeight()/2,h=hc.Pq.Project(o,hc.uq.IdentityReadOnly,r.getTransformMatrix(),e.viewport.toGlobal(a,l)),c=hc.Pq.Distance(e.position,o),u=t.adaptDepth?Math.ceil(s.context.remap(c,0,100,t.size,3)):t.size;h.x>0&&h.x0&&h.y0&&h.z<1&&u>3?n.style="".concat("position: absolute; transform: translate(-50%, -50%); font-weight: 400;"," font-size: ").concat(u,"px; color: ").concat(t.colour,"; left: ").concat(h.x,"px; top: ").concat(h.y,"px; display: inline;"):n.style="display: none;"}))},e.prototype.removeTagsIfNeeded=function(){this.tagsExist()&&this.context.tagBag.forEach((function(e){var t=document.getElementById(e.id);t.parentNode.removeChild(t)})),this.context.tagBag=[]},e.prototype.tagsExist=function(){return this.context.tagBag.length>0},e}(),cZ=function(){return cZ=Object.assign||function(e){for(var t,i=1,r=arguments.length;i0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]0?JSON.stringify(r):"{}",';\n let bitbybitRunnerResult = {};\n const runContext = "runner";\n const mockBitbybitRunnerInputs = (inputs) => {\n }\n const getBitbybitRunnerInputs = () => {\n return bitbybitRunnerInputs;\n }\n const setBitbybitRunnerResult = (result) => {\n bitbybitRunnerResult = result;\n }\n const setBitbybitRunnerResultValue = (prop, value) => {\n bitbybitRunnerResult[prop] = value;\n }\n \n const bitbybit = this.bitbybit;\n const Bit = this.Bit;\n Bit.mockBitbybitRunnerInputs = mockBitbybitRunnerInputs;\n Bit.getBitbybitRunnerInputs = getBitbybitRunnerInputs;\n Bit.setBitbybitRunnerResult = setBitbybitRunnerResult;\n Bit.setBitbybitRunnerResultValue = setBitbybitRunnerResultValue;\n \n const BitByBit = this.BitByBit;\n const errorHandle = this.errorHandle;\n const BABYLON = this.BABYLON;\n BABYLON.GUI = this.GUI;\n const resolve = this.resolve;\n \n await ').concat(s.script,"\n if(bitbybitRunnerResult !== undefined){\n resolve(bitbybitRunnerResult);\n } else {\n resolve(undefined);\n }\n }\n \n bitbybitRunnerStart();\n "),a={HS:lZ,BitByBitContextHelperService:this.bitbybit.context},l={bitbybit:this.bitbybit,BABYLON:e,GUI:t,Bit:pZ,BitByBit:a,errorHandle:n},[2,new Promise((function(e){return l.resolve=e,new Function(o).apply(l)}))]}))}))},i.prototype.resetRunnerContext=function(){if(this.bitbybit.context.scene.dispose(),this.options.enablePhysics){var e=new fO(!0,this.havok);this.bitbybit.context.havokPlugin=e}var t=document.getElementById(this.options.canvasId),i=this.bitbybit.context.engine;this.initScene(i,t),this.tagService.removeTagsIfNeeded(),this.bitbybit.context.intervalBag.forEach((function(e){return clearInterval(e)})),this.bitbybit.context.timeoutBag.forEach((function(e){return clearTimeout(e)})),this.bitbybit.context.intervalBag.length=0,this.bitbybit.context.timeoutBag.length=0,this.bitbybit.context.renderLoopBag.length=0,this.bitbybit.context.keyPressBag.length=0,this.bitbybit.context.keyDownBag.length=0,this.bitbybit.context.keyUpBag.length=0},i.prototype.cleanOCCTCache=function(){return uZ(this,void 0,void 0,(function(){return dZ(this,(function(e){return[2,this.bitbybit.occtWorkerManager.cleanAllCache()]}))}))},i.prototype.cleanJSCADCache=function(){return uZ(this,void 0,void 0,(function(){return dZ(this,(function(e){return[2,this.bitbybit.jscadWorkerManager.cleanAllCache()]}))}))},i.prototype.cleanManifoldCache=function(){return uZ(this,void 0,void 0,(function(){return dZ(this,(function(e){return[2,this.bitbybit.manifoldWorkerManager.cleanAllCache()]}))}))},i}()})(),r})())); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.bitbybitRunner=t():e.bitbybitRunner=t()}(this,(()=>(()=>{var e={96772:(e,t,i)=>{"use strict";i.d(t,{G:()=>r});class r{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1,this.disposeWhenUnowned=!0}static get HasTriggers(){for(const e in r.Triggers)if(Object.prototype.hasOwnProperty.call(r.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in r.Triggers)if(Object.prototype.hasOwnProperty.call(r.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in r.Triggers)if(Object.prototype.hasOwnProperty.call(r.Triggers,t)&&parseInt(t)===e)return!0;return!1}}r.Triggers={}},89357:(e,t,i)=>{"use strict";i.d(t,{X:()=>r});class r{constructor(e,t,i,r,s,n){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=r,this.sourceEvent=s,this.additionalData=n}static CreateNew(e,t,i){const s=e.getScene();return new r(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new r(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new r(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new r(e,t.x,t.y,null,i,s)}}},66418:(e,t,i)=>{"use strict";i.d(t,{SM:()=>f,rT:()=>h,BT:()=>d});var r=i(87665),s=i(43279),n=i(34493),o=i(54065),a=i(64736),l=i(94212);class h{get syncRoot(){return this._syncRoot}get masterFrame(){return 0===this._runtimeAnimations.length?0:this._runtimeAnimations[0].currentFrame}get weight(){return this._weight}set weight(e){this._weight=-1!==e?Math.min(Math.max(e,0),1):-1}get speedRatio(){return this._speedRatio}set speedRatio(e){for(let t=0;t-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(s)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i-1){const n=this._runtimeAnimations;for(let i=n.length-1;i>=0;i--){const r=n[i];e&&r.animation.name!=e||t&&!t(r.target)||(r.dispose(),n.splice(i,1))}0==n.length&&(i||this._scene._activeAnimatables.splice(s,1),r||this._raiseOnAnimationEnd())}}else{const e=this._scene._activeAnimatables.indexOf(this);if(e>-1){i||this._scene._activeAnimatables.splice(e,1);const t=this._runtimeAnimations;for(let e=0;e{this.onAnimationEndObservable.add((()=>{e(this)}),void 0,void 0,this,!0)}))}_animate(e){if(this._paused)return this.animationStarted=!1,null===this._pausedDelay&&(this._pausedDelay=e),!0;if(null===this._localDelayOffset?(this._localDelayOffset=e,this._pausedDelay=null):null!==this._pausedDelay&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),null!==this._manualJumpDelay&&(this._localDelayOffset+=this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,0===this._weight)return!0;let t=!1;const i=this._runtimeAnimations;let r;for(r=0;r0?h:-h,s),a.scaleAndAddToRef(h,i)}s.normalize()}for(let t=0;t0)s.copyFrom(r);else if(1===e.animations.length){if(l.PT.SlerpToRef(r,i.currentValue,Math.min(1,e.totalWeight),s),0===e.totalAdditiveWeight)return s}else if(e.animations.length>1){let i,n,o=1;if(e.totalWeight<1){const t=1-e.totalWeight;i=[],n=[],i.push(r),n.push(t)}else{if(2===e.animations.length&&(l.PT.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],n=[],o=e.totalWeight}for(let t=0;t=a&&g.frame<=l&&(r?(x=g.value.clone(),f?(v=x.getTranslation(),x.setTranslation(v.scaleInPlace(p))):_&&s?(v=x.getTranslation(),x.setTranslation(v.multiplyInPlace(s))):x=g.value):x=g.value,m.push({frame:g.frame+i,value:x}));return this.animations[0].createRange(t,a+i,l+i),!0}),e&&(e.prototype._animate=function(e){if(!this.animationsEnabled)return;const t=a.j.Now;if(!this._animationTimeLast){if(this._pendingData.length>0)return;this._animationTimeLast=t}this.deltaTime=void 0!==e?e:this.useConstantAnimationDeltaTime?16:(t-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=t;const i=this._activeAnimatables;if(0===i.length)return;this._animationTime+=this.deltaTime;const r=this._animationTime;for(let e=0;ee.playOrder-t.playOrder))},e.prototype.beginWeightedAnimation=function(e,t,i,r=1,s,n=1,o,a,l,h,c=!1){const u=this.beginAnimation(e,t,i,s,n,o,a,!1,l,h,c);return u.weight=r,u},e.prototype.beginAnimation=function(e,t,i,r,s=1,n,o,a=!0,l,c,u=!1){if(s<0){const e=t;t=i,i=e,s=-s}t>i&&(s=-s),a&&this.stopAnimation(e,void 0,l),o||(o=new h(this,e,t,i,r,s,n,void 0,c,u));const d=!l||l(e);if(e.animations&&d&&o.appendAnimations(e,e.animations),e.getAnimatables){const h=e.getAnimatables();for(let e=0;er&&(n=-n),new h(this,e,i,r,s,n,o,t,a,l)},e.prototype.beginDirectHierarchyAnimation=function(e,t,i,r,s,n,o,a,l,h=!1){const c=e.getDescendants(t),u=[];u.push(this.beginDirectAnimation(e,i,r,s,n,o,a,l,h));for(const e of c)u.push(this.beginDirectAnimation(e,i,r,s,n,o,a,l,h));return u},e.prototype.getAnimatableByTarget=function(e){for(let t=0;t{"use strict";i.d(t,{X5:()=>x,eA:()=>m,nl:()=>g,rq:()=>p,s$:()=>d,vF:()=>_,y4:()=>f});var r=i(94212),s=i(11084),n=i(56984),o=i(56225),a=i(888),l=i(14747),h=i(29962),c=i(67313),u=i(89518);const d=Object.freeze(new r.PT(0,0,0,0)),f=Object.freeze(r.Pq.Zero()),p=Object.freeze(r.I9.Zero()),_=Object.freeze(h.o.Zero()),m=Object.freeze(s.v9.Black()),g=Object.freeze(new s.ov(0,0,0,0)),v={key:0,repeatCount:0,loopMode:2};class x{static _PrepareAnimation(e,t,i,n,o,a,l,c){let u;if(!isNaN(parseFloat(o))&&isFinite(o)?u=x.ANIMATIONTYPE_FLOAT:o instanceof r.PT?u=x.ANIMATIONTYPE_QUATERNION:o instanceof r.Pq?u=x.ANIMATIONTYPE_VECTOR3:o instanceof r.I9?u=x.ANIMATIONTYPE_VECTOR2:o instanceof s.v9?u=x.ANIMATIONTYPE_COLOR3:o instanceof s.ov?u=x.ANIMATIONTYPE_COLOR4:o instanceof h.o&&(u=x.ANIMATIONTYPE_SIZE),null==u)return null;const d=new x(e,t,i,u,l),f=[{frame:0,value:o},{frame:n,value:a}];return d.setKeys(f),void 0!==c&&d.setEasingFunction(c),d}static CreateAnimation(e,t,i,r){const s=new x(e+"Animation",e,i,t,x.ANIMATIONLOOPMODE_CONSTANT);return s.setEasingFunction(r),s}static CreateAndStartAnimation(e,t,i,r,s,n,o,a,l,h,c){const u=x._PrepareAnimation(e,i,r,s,n,o,a,l);return u?(t.getScene&&(c=t.getScene()),c?c.beginDirectAnimation(t,[u],0,s,1===u.loopMode,1,h):null):null}static CreateAndStartHierarchyAnimation(e,t,i,r,s,n,o,a,l,h,c){const u=x._PrepareAnimation(e,r,s,n,o,a,l,h);return u?t.getScene().beginDirectHierarchyAnimation(t,i,[u],0,n,1===u.loopMode,1,c):null}static CreateMergeAndStartAnimation(e,t,i,r,s,n,o,a,l,h){const c=x._PrepareAnimation(e,i,r,s,n,o,a,l);return c?(t.animations.push(c),t.getScene().beginAnimation(t,0,s,1===c.loopMode,1,h)):null}static MakeAnimationAdditive(e,t,i,s=!1,n){let o;o="object"==typeof t?t:{referenceFrame:t??0,range:i,cloneOriginalAnimation:s,clonedAnimationName:n};let a=e;if(o.cloneOriginalAnimation&&(a=e.clone(),a.name=o.clonedAnimationName||a.name),!a._keys.length)return a;const l=o.referenceFrame&&o.referenceFrame>=0?o.referenceFrame:0;let h=0;const c=a._keys[0];let u=a._keys.length-1;const d=a._keys[u],f={referenceValue:c.value,referencePosition:r.AA.Vector3[0],referenceQuaternion:r.AA.Quaternion[0],referenceScaling:r.AA.Vector3[1],keyPosition:r.AA.Vector3[2],keyQuaternion:r.AA.Quaternion[1],keyScaling:r.AA.Vector3[3]};let p=c.frame,_=d.frame;if(o.range){const e=a.getRange(o.range);e&&(p=e.from,_=e.to)}else p=o.fromFrame??p,_=o.toFrame??_;if(p!==c.frame&&(h=a.createKeyForFrame(p)),_!==d.frame&&(u=a.createKeyForFrame(_)),1===a._keys.length){const e=a._getKeyValue(a._keys[0]);f.referenceValue=e.clone?e.clone():e}else if(l<=c.frame){const e=a._getKeyValue(c.value);f.referenceValue=e.clone?e.clone():e}else if(l>=d.frame){const e=a._getKeyValue(d.value);f.referenceValue=e.clone?e.clone():e}else{v.key=0;const e=a._interpolate(l,v);f.referenceValue=e.clone?e.clone():e}a.dataType===x.ANIMATIONTYPE_QUATERNION?f.referenceValue.normalize().conjugateInPlace():a.dataType===x.ANIMATIONTYPE_MATRIX&&(f.referenceValue.decompose(f.referenceScaling,f.referenceQuaternion,f.referencePosition),f.referenceQuaternion.normalize().conjugateInPlace());let m=Number.MAX_VALUE;const g=o.clipKeys?[]:null;for(let e=h;e<=u;e++){let t=a._keys[e];if((g||o.cloneOriginalAnimation)&&(t={frame:t.frame,value:t.value.clone?t.value.clone():t.value,inTangent:t.inTangent,outTangent:t.outTangent,interpolation:t.interpolation,lockedTangent:t.lockedTangent},g&&(m===Number.MAX_VALUE&&(m=t.frame),t.frame-=m,g.push(t))),!e||a.dataType===x.ANIMATIONTYPE_FLOAT||t.value!==c.value)switch(a.dataType){case x.ANIMATIONTYPE_MATRIX:t.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),r.uq.ComposeToRef(f.keyScaling,f.keyQuaternion,f.keyPosition,t.value);break;case x.ANIMATIONTYPE_QUATERNION:f.referenceValue.multiplyToRef(t.value,t.value);break;case x.ANIMATIONTYPE_VECTOR2:case x.ANIMATIONTYPE_VECTOR3:case x.ANIMATIONTYPE_COLOR3:case x.ANIMATIONTYPE_COLOR4:t.value.subtractToRef(f.referenceValue,t.value);break;case x.ANIMATIONTYPE_SIZE:t.value.width-=f.referenceValue.width,t.value.height-=f.referenceValue.height;break;default:t.value-=f.referenceValue}}return g&&a.setKeys(g,!0),a}static TransitionTo(e,t,i,r,s,n,o,a=null){if(o<=0)return i[e]=t,a&&a(),null;const l=s*(o/1e3);n.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(n);const h=r.beginAnimation(i,0,l,!1);return h.onAnimationEnd=a,h}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,r,s,n){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=r,this.loopMode=s,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=r,this.loopMode=void 0===s?x.ANIMATIONLOOPMODE_CYCLE:s,this.uniqueId=x._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 e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort(((e,t)=>e.frame-t.frame))}removeEvents(e){for(let t=0;t=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const r=this._keys,s=r.length;let n=t.key;for(;n>=0&&e=r[n+1].frame;)++n;if(t.key=n,n<0)return i?void 0:this._getKeyValue(r[0].value);if(n+1>s-1)return i?void 0:this._getKeyValue(r[s-1].value);const o=r[n],a=r[n+1];if(i&&(e===o.frame||e===a.frame))return;const l=this._getKeyValue(o.value),h=this._getKeyValue(a.value);if(1===o.interpolation)return a.frame>e?l:h;const c=void 0!==o.outTangent&&void 0!==a.inTangent,u=a.frame-o.frame;let v=(e-o.frame)/u;const b=o.easingFunction||this.getEasingFunction();switch(null!==b&&(v=b.ease(v)),this.dataType){case x.ANIMATIONTYPE_FLOAT:{const e=c?this.floatInterpolateFunctionWithTangents(l,o.outTangent*u,h,a.inTangent*u,v):this.floatInterpolateFunction(l,h,v);switch(t.loopMode){case x.ANIMATIONLOOPMODE_CYCLE:case x.ANIMATIONLOOPMODE_CONSTANT:case x.ANIMATIONLOOPMODE_YOYO:return e;case x.ANIMATIONLOOPMODE_RELATIVE:case x.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(t.offsetValue??0)*t.repeatCount+e}break}case x.ANIMATIONTYPE_QUATERNION:{const e=c?this.quaternionInterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),v):this.quaternionInterpolateFunction(l,h,v);switch(t.loopMode){case x.ANIMATIONLOOPMODE_CYCLE:case x.ANIMATIONLOOPMODE_CONSTANT:case x.ANIMATIONLOOPMODE_YOYO:return e;case x.ANIMATIONLOOPMODE_RELATIVE:case x.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.addInPlace((t.offsetValue||d).scale(t.repeatCount))}return e}case x.ANIMATIONTYPE_VECTOR3:{const e=c?this.vector3InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),v):this.vector3InterpolateFunction(l,h,v);switch(t.loopMode){case x.ANIMATIONLOOPMODE_CYCLE:case x.ANIMATIONLOOPMODE_CONSTANT:case x.ANIMATIONLOOPMODE_YOYO:return e;case x.ANIMATIONLOOPMODE_RELATIVE:case x.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||f).scale(t.repeatCount))}break}case x.ANIMATIONTYPE_VECTOR2:{const e=c?this.vector2InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),v):this.vector2InterpolateFunction(l,h,v);switch(t.loopMode){case x.ANIMATIONLOOPMODE_CYCLE:case x.ANIMATIONLOOPMODE_CONSTANT:case x.ANIMATIONLOOPMODE_YOYO:return e;case x.ANIMATIONLOOPMODE_RELATIVE:case x.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||p).scale(t.repeatCount))}break}case x.ANIMATIONTYPE_SIZE:switch(t.loopMode){case x.ANIMATIONLOOPMODE_CYCLE:case x.ANIMATIONLOOPMODE_CONSTANT:case x.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(l,h,v);case x.ANIMATIONLOOPMODE_RELATIVE:case x.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(l,h,v).add((t.offsetValue||_).scale(t.repeatCount))}break;case x.ANIMATIONTYPE_COLOR3:{const e=c?this.color3InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),v):this.color3InterpolateFunction(l,h,v);switch(t.loopMode){case x.ANIMATIONLOOPMODE_CYCLE:case x.ANIMATIONLOOPMODE_CONSTANT:case x.ANIMATIONLOOPMODE_YOYO:return e;case x.ANIMATIONLOOPMODE_RELATIVE:case x.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||m).scale(t.repeatCount))}break}case x.ANIMATIONTYPE_COLOR4:{const e=c?this.color4InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),v):this.color4InterpolateFunction(l,h,v);switch(t.loopMode){case x.ANIMATIONLOOPMODE_CYCLE:case x.ANIMATIONLOOPMODE_CONSTANT:case x.ANIMATIONLOOPMODE_YOYO:return e;case x.ANIMATIONLOOPMODE_RELATIVE:case x.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||g).scale(t.repeatCount))}break}case x.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case x.ANIMATIONLOOPMODE_CYCLE:case x.ANIMATIONLOOPMODE_CONSTANT:case x.ANIMATIONLOOPMODE_YOYO:return x.AllowMatricesInterpolation?this.matrixInterpolateFunction(l,h,v,t.workValue):l;case x.ANIMATIONLOOPMODE_RELATIVE:case x.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return l}}return 0}matrixInterpolateFunction(e,t,i,s){return x.AllowMatrixDecomposeForInterpolation?s?(r.uq.DecomposeLerpToRef(e,t,i,s),s):r.uq.DecomposeLerp(e,t,i):s?(r.uq.LerpToRef(e,t,i,s),s):r.uq.Lerp(e,t,i)}clone(){const e=new x(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){v.key=0;const t=this._interpolate(e,v,!0);if(!t)return this._keys[v.key].frame===e?v.key:v.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(v.key+1,0,i),v.key+1}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const i=this.getKeys();for(let r=0;r=2&&(l=t.values[1]),t.values.length>=3&&(h=t.values[2]),t.values.length>=4&&(c=t.values[3]);break;case x.ANIMATIONTYPE_QUATERNION:if(o=r.PT.FromArray(t.values),t.values.length>=8){const e=r.PT.FromArray(t.values.slice(4,8));e.equals(r.PT.Zero())||(l=e)}if(t.values.length>=12){const e=r.PT.FromArray(t.values.slice(8,12));e.equals(r.PT.Zero())||(h=e)}t.values.length>=13&&(c=t.values[12]);break;case x.ANIMATIONTYPE_MATRIX:o=r.uq.FromArray(t.values),t.values.length>=17&&(c=t.values[16]);break;case x.ANIMATIONTYPE_COLOR3:o=s.v9.FromArray(t.values),t.values[3]&&(l=s.v9.FromArray(t.values[3])),t.values[4]&&(h=s.v9.FromArray(t.values[4])),t.values[5]&&(c=t.values[5]);break;case x.ANIMATIONTYPE_COLOR4:o=s.ov.FromArray(t.values),t.values[4]&&(l=s.ov.FromArray(t.values[4])),t.values[5]&&(h=s.ov.FromArray(t.values[5])),t.values[6]&&(c=s.ov.FromArray(t.values[6]));break;case x.ANIMATIONTYPE_VECTOR3:default:o=r.Pq.FromArray(t.values),t.values[3]&&(l=r.Pq.FromArray(t.values[3])),t.values[4]&&(h=r.Pq.FromArray(t.values[4])),t.values[5]&&(c=t.values[5])}const u={};u.frame=t.frame,u.value=o,null!=l&&(u.inTangent=l),null!=h&&(u.outTangent=h),null!=c&&(u.interpolation=c),n.push(u)}if(t.setKeys(n),e.ranges)for(a=0;a{const s=new c.u;s.addEventListener("readystatechange",(()=>{if(4==s.readyState)if(200==s.status){let t=JSON.parse(s.responseText);if(t.animations&&(t=t.animations),t.length){const e=[];for(const i of t)e.push(this.Parse(i));i(e)}else{const r=this.Parse(t);e&&(r.name=e),i(r)}}else r("Unable to load the animation")})),s.open("GET",t),s.send()}))}static ParseFromSnippetAsync(e){return new Promise(((t,i)=>{const r=new c.u;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){const i=JSON.parse(JSON.parse(r.responseText).jsonPayload);if(i.animations){const r=JSON.parse(i.animations),s=[];for(const t of r.animations){const i=this.Parse(t);i.snippetId=e,s.push(i)}t(s)}else{const r=JSON.parse(i.animation),s=this.Parse(r);s.snippetId=e,t(s)}}else i("Unable to load the snippet "+e)})),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()}))}}x._UniqueIdGenerator=0,x.AllowMatricesInterpolation=!1,x.AllowMatrixDecomposeForInterpolation=!0,x.SnippetUrl="https://snippet.babylonjs.com",x.ANIMATIONTYPE_FLOAT=0,x.ANIMATIONTYPE_VECTOR3=1,x.ANIMATIONTYPE_QUATERNION=2,x.ANIMATIONTYPE_MATRIX=3,x.ANIMATIONTYPE_COLOR3=4,x.ANIMATIONTYPE_COLOR4=7,x.ANIMATIONTYPE_VECTOR2=5,x.ANIMATIONTYPE_SIZE=6,x.ANIMATIONLOOPMODE_RELATIVE=0,x.ANIMATIONLOOPMODE_CYCLE=1,x.ANIMATIONLOOPMODE_CONSTANT=2,x.ANIMATIONLOOPMODE_YOYO=4,x.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5,x.CreateFromSnippetAsync=x.ParseFromSnippetAsync,(0,o.Y5)("BABYLON.Animation",x),l.b._AnimationRangeFactory=(e,t,i)=>new a.K(e,t,i)},7042:(e,t,i)=>{"use strict";i.r(t),i.d(t,{AnimationGroup:()=>l,TargetedAnimation:()=>a});var r=i(54065),s=i(43279),n=i(34268),o=i(84015);i(66418);class a{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class l{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=0;for(let e=0;e0)){for(let e=0;en&&(n=t.to);const o=new l(e[0].name+"_merged",e[0]._scene,r);for(const r of e){i&&r.normalize(s,n);for(const e of r.targetedAnimations)o.addTargetedAnimation(e.animation,e.target);t&&r.dispose()}return o}constructor(e,t=null,i=-1,r=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._shouldStart=!0,this._parentContainer=null,this.onAnimationEndObservable=new s.cP,this.onAnimationLoopObservable=new s.cP,this.onAnimationGroupLoopObservable=new s.cP,this.onAnimationGroupEndObservable=new s.cP,this.onAnimationGroupPauseObservable=new s.cP,this.onAnimationGroupPlayObservable=new s.cP,this.metadata=null,this._mask=null,this._animationLoopFlags=[],this._scene=t||n.q.LastCreatedScene,this._weight=i,this._playOrder=r,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new a;i.animation=e,i.target=t;const r=e.getKeys();return this._from>r[0].frame&&(this._from=r[0].frame),this._to-1;t--)this._targetedAnimations[t].animation===e&&this._targetedAnimations.splice(t,1)}normalize(e=null,t=null){null==e&&(e=this._from),null==t&&(t=this._to);for(let i=0;ie){const t={frame:e,value:s.value,inTangent:s.inTangent,outTangent:s.outTangent,interpolation:s.interpolation};r.splice(0,0,t)}if(n.frame{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._numActiveAnimatables&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,r,s){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._shouldStart=!1,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let n=0;n{this.onAnimationEndObservable.notifyObservers(o),this._checkAnimationGroupEnded(a)},this._processLoop(a,o,n),this._animatables.push(a)}return this.syncWithMask(),this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e0?this._scene._activeAnimatables[i++]=r:e&&this._checkAnimationGroupEnded(r,e)}return this._scene._activeAnimatables.length=i,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){const e=this._parentContainer.animationGroups.indexOf(this);e>-1&&this._parentContainer.animationGroups.splice(e,1),this._parentContainer=null}this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()}_checkAnimationGroupEnded(e,t=!1){const i=this._animatables.indexOf(e);i>-1&&this._animatables.splice(i,1),this._animatables.length===this._targetedAnimations.length-this._numActiveAnimatables&&(this._isStarted=!1,t||this.onAnimationGroupEndObservable.notifyObservers(this),this._animatables.length=0)}clone(e,t,i=!1){const r=new l(e||this.name,this._scene,this._weight,this._playOrder);r._from=this.from,r._to=this.to,r._speedRatio=this.speedRatio,r._loopAnimation=this.loopAnimation,r._isAdditive=this.isAdditive,r._enableBlending=this.enableBlending,r._blendingSpeed=this.blendingSpeed,r.metadata=this.metadata,r.mask=this.mask;for(const e of this._targetedAnimations)r.addTargetedAnimation(i?e.animation.clone():e.animation,t?t(e.target):e.target);return r}serialize(){const e={};e.name=this.name,e.from=this.from,e.to=this.to,e.speedRatio=this.speedRatio,e.loopAnimation=this.loopAnimation,e.isAdditive=this.isAdditive,e.weight=this.weight,e.playOrder=this.playOrder,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,e.targetedAnimations=[];for(let t=0;ts[0].frame&&(e=s[0].frame),t=t&&e<=i||s&&r.frame>=t&&r.frame<=i){const e={frame:r.frame,value:r.value.clone?r.value.clone():r.value,inTangent:r.inTangent,outTangent:r.outTangent,interpolation:r.interpolation,lockedTangent:r.lockedTangent};d===Number.MAX_VALUE&&(d=e.frame),e.frame-=d,u.push(e)}}0!==u.length?(n>u[0].frame&&(n=u[0].frame),o{"use strict";i.d(t,{K:()=>r});class r{constructor(e,t,i){this.name=e,this.from=t,this.to=i}clone(){return new r(this.name,this.from,this.to)}}},34493:(e,t,i)=>{"use strict";i.d(t,{x:()=>n});var r=i(94212),s=i(54065);class n{get currentFrame(){return this._currentFrame}get weight(){return this._weight}get currentValue(){return this._currentValue}get targetPath(){return this._targetPath}get target(){return this._currentActiveTarget}get isAdditive(){return this._host&&this._host.isAdditive}constructor(e,t,i,n){if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._absoluteFrameOffset=0,this._previousElapsedTime=0,this._yoyoDirection=1,this._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=n,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===s.X5.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=r.uq.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,0!==this._minFrame){const e={frame:0,value:this._minValue};this._keys.splice(0,0,e)}if(this._target instanceof Array){let e=0;for(const t of this._target)this._preparePath(t,e),this._getOriginalValues(e),e++;this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];const o=t.getEvents();o&&o.length>0&&o.forEach((e=>{this._events.push(e._clone())})),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}_preparePath(e,t=0){const i=this._animation.targetPropertyPath;if(i.length>1){let r=e;for(let e=0;e-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray)for(let i=0;ii[i.length-1].frame&&(e=i[i.length-1].frame);const r=this._events;if(r.length)for(let t=0;tthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);const c=i-t;let u,d=e*(a.framePerSecond*n)/1e3+this._absoluteFrameOffset,f=0,p=!1;const _=r&&this._animationState.loopMode===s.X5.ANIMATIONLOOPMODE_YOYO;if(_){const e=(d-t)/c,i=Math.sin(e*Math.PI);d=Math.abs(i)*c+t;const r=i>=0?1:-1;this._yoyoDirection!==r&&(p=!0),this._yoyoDirection=r}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=d,!r&&i>=t&&(d>=c&&n>0||d<=0&&n<0))h=!1,f=a._getKeyValue(this._maxValue);else if(!r&&t>=i&&(d<=c&&n<0||d>=0&&n>0))h=!1,f=a._getKeyValue(this._minValue);else if(this._animationState.loopMode!==s.X5.ANIMATIONLOOPMODE_CYCLE){const e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=s.X5.ANIMATIONLOOPMODE_CYCLE;const r=a._interpolate(t,this._animationState),n=a._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),a.dataType){case s.X5.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=n-r;break;case s.X5.ANIMATIONTYPE_QUATERNION:case s.X5.ANIMATIONTYPE_VECTOR3:case s.X5.ANIMATIONTYPE_VECTOR2:case s.X5.ANIMATIONTYPE_SIZE:case s.X5.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=n.subtract(r)}this._highLimitsCache[e]=n}f=this._highLimitsCache[e],u=this._offsetsCache[e]}if(void 0===u)switch(a.dataType){case s.X5.ANIMATIONTYPE_FLOAT:u=0;break;case s.X5.ANIMATIONTYPE_QUATERNION:u=s.s$;break;case s.X5.ANIMATIONTYPE_VECTOR3:u=s.y4;break;case s.X5.ANIMATIONTYPE_VECTOR2:u=s.rq;break;case s.X5.ANIMATIONTYPE_SIZE:u=s.vF;break;case s.X5.ANIMATIONTYPE_COLOR3:u=s.eA;break;case s.X5.ANIMATIONTYPE_COLOR4:u=s.nl}let m;if(this._host&&this._host.syncRoot){const e=this._host.syncRoot;m=t+c*((e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame))}else m=d>0&&t>i||d<0&&t0&&this.currentFrame>m||n<0&&this.currentFrame0?0:a.getKeys().length-1}this._currentFrame=m,this._animationState.repeatCount=0===c?0:d/c|0,this._animationState.highLimitValue=f,this._animationState.offsetValue=u;const v=a._interpolate(m,this._animationState);if(this.setValue(v,o),g.length)for(let e=0;e=0&&m>=g[e].frame&&g[e].frame>=t||c<0&&m<=g[e].frame&&g[e].frame<=t){const t=g[e];t.isDone||(t.onlyOnce&&(g.splice(e,1),e--),t.isDone=!0,t.action(m))}return h||(this._stopped=!0),h}}},87665:(e,t,i)=>{"use strict";i.d(t,{$:()=>o});var r=i(94212),s=i(34130),n=i(14747);class o extends n.b{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,n=null,o=null,a=null){super(e,t.getScene(),!1),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=s?.clone()??r.uq.Identity(),this._restMatrix=n??this._localMatrix.clone(),this._bindMatrix=o??this._localMatrix.clone(),this._index=a,this._absoluteMatrix=new r.uq,this._absoluteBindMatrix=new r.uq,this._absoluteInverseBindMatrix=new r.uq,this._finalMatrix=new r.uq,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 null===this._index?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 e=this.parent.children.indexOf(this);-1!==e&&this.parent.children.splice(e,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=r.AA.Vector3[0],t=r.AA.Quaternion[0],i=r.AA.Vector3[1];this.getRestMatrix().decompose(e,t,i),this._linkedTransformNode.position.copyFrom(i),this._linkedTransformNode.rotationQuaternion=this._linkedTransformNode.rotationQuaternion??r.PT.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=r.Pq.Zero(),this._localRotation=r.PT.Zero(),this._localPosition=r.Pq.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,r.uq.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)):this._needToCompose=!1)}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 e=0;e{"use strict";i.d(t,{R:()=>o,h:()=>n});var r=i(75801),s=i(60590);class n{get isDisposed(){return this._isDisposed}constructor(e,t,i,s=0,n=!1,o=!1,a=!1,l,h){this._isAlreadyOwned=!1,this._isDisposed=!1,e&&e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=o,this._divisor=l||1,this._label=h,t instanceof r.n?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=a?s:s*Float32Array.BYTES_PER_ELEMENT,n||this.create()}createVertexBuffer(e,t,i,r,s,n=!1,a){const l=n?t:t*Float32Array.BYTES_PER_ELEMENT,h=r?n?r:r*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new o(this._engine,this,e,this._updatable,!0,h,void 0===s?this._instanced:s,l,i,void 0,void 0,!0,this._divisor||a)}isUpdatable(){return this._updatable}getData(){return this._data}getBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT}create(e=null){!e&&this._buffer||(e=e||this._data)&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e,this._label),this._data=e):this._buffer=this._engine.createVertexBuffer(e,void 0,this._label))}_rebuild(){if(this._data)this._buffer=null,this.create(this._data);else{if(!this._buffer)return;if(this._buffer.capacity>0)return void(this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label));s.V.Warn(`Missing data for buffer "${this._label}" ${this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":""}. Buffer reconstruction failed.`),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,i,r=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,r?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),this._data=0===t&&void 0===i?e:null)}_increaseReferences(){this._buffer&&(this._isAlreadyOwned?this._buffer.references++:this._isAlreadyOwned=!0)}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}}class o{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=0!=e;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get _maxVerticesCount(){const e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,i,r,s,a,l,h,c,u,d=!1,f=!1,p=1,_=!1){this._isDisposed=!1;let m=!1;if(this.engine=e,"object"==typeof r&&null!==r?(m=r.updatable??!1,s=r.postponeInternalCreation,a=r.stride,l=r.instanced,h=r.offset,c=r.size,u=r.type,d=r.normalized??!1,f=r.useBytes??!1,p=r.divisor??1,_=r.takeBufferOwnership??!1,this._label=r.label):m=!!r,t instanceof n?(this._buffer=t,this._ownsBuffer=_):(this._buffer=new n(e,t,m,a,s,l,f,p,this._label),this._ownsBuffer=!0),this.uniqueId=o._Counter++,this._kind=i,void 0===u){const e=this.getData();this.type=e?o.GetDataType(e):o.FLOAT}else this.type=u;const g=o.GetTypeByteLength(this.type);f?(this._size=c||(a?a/g:o.DeduceStride(i)),this.byteStride=a||this._buffer.byteStride||this._size*g,this.byteOffset=h||0):(this._size=c||a||o.DeduceStride(i),this.byteStride=a?a*g:this._buffer.byteStride||this._size*g,this.byteOffset=(h||0)*g),this.normalized=d,this._instanced=void 0!==l&&l,this._instanceDivisor=l?p: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(){this._buffer?._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();return i?o.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/o.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/o.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*o.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){o.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case o.UVKind:case o.UV2Kind:case o.UV3Kind:case o.UV4Kind:case o.UV5Kind:case o.UV6Kind:return 2;case o.NormalKind:case o.PositionKind:return 3;case o.ColorKind:case o.ColorInstanceKind:case o.MatricesIndicesKind:case o.MatricesIndicesExtraKind:case o.MatricesWeightsKind:case o.MatricesWeightsExtraKind:case o.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?o.BYTE:e instanceof Uint8Array?o.UNSIGNED_BYTE:e instanceof Int16Array?o.SHORT:e instanceof Uint16Array?o.UNSIGNED_SHORT:e instanceof Int32Array?o.INT:e instanceof Uint32Array?o.UNSIGNED_INT:o.FLOAT}static GetTypeByteLength(e){switch(e){case o.BYTE:case o.UNSIGNED_BYTE:return 1;case o.SHORT:case o.UNSIGNED_SHORT:return 2;case o.INT:case o.UNSIGNED_INT:case o.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,r,s,n,a,l){if(e instanceof Array){let s=t/4;const o=i/4;for(let t=0;ts[t]=e)),s}if(!(e instanceof Array||e instanceof Float32Array)||0!==r||e.length!==u){if(e instanceof Array){const t=r/4;return e.slice(t,t+u)}if(e instanceof ArrayBuffer)return new Float32Array(e,r,u);{const t=e.byteOffset+r;if(3&t&&(s.V.Warn("Float array must be aligned to 4-bytes border"),h=!0),h){const i=new Uint8Array(u*Float32Array.BYTES_PER_ELEMENT),r=new Uint8Array(e.buffer,t,i.length);return i.set(r),new Float32Array(i.buffer)}return new Float32Array(e.buffer,t,u)}}return h?e.slice():e}}o._Counter=0,o.BYTE=5120,o.UNSIGNED_BYTE=5121,o.SHORT=5122,o.UNSIGNED_SHORT=5123,o.INT=5124,o.UNSIGNED_INT=5125,o.FLOAT=5126,o.PositionKind="position",o.NormalKind="normal",o.TangentKind="tangent",o.UVKind="uv",o.UV2Kind="uv2",o.UV3Kind="uv3",o.UV4Kind="uv4",o.UV5Kind="uv5",o.UV6Kind="uv6",o.ColorKind="color",o.ColorInstanceKind="instanceColor",o.MatricesIndicesKind="matricesIndices",o.MatricesWeightsKind="matricesWeights",o.MatricesIndicesExtraKind="matricesIndicesExtra",o.MatricesWeightsExtraKind="matricesWeightsExtra"},75801:(e,t,i)=>{"use strict";i.d(t,{n:()=>r});class r{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=r._Counter++}}r._Counter=0},91112:(e,t,i)=>{"use strict";i.d(t,{K:()=>r});class r{constructor(e,t,i=3,r){this._engine=e,this._label=r,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,r){return this._engine.readFromStorageBuffer(this._buffer,e,t,i,r)}dispose(){const e=this._engine._storageBuffers,t=e.indexOf(this);-1!==t&&(e[t]=e[e.length-1],e.pop()),this._engine._releaseBuffer(this._buffer),this._buffer=null}}},81310:(e,t,i)=>{"use strict";i.d(t,{G:()=>n});var r=i(94212),s=i(12721);class n{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(s.R.NormalKind))return null;let i,n=this.pickedMesh.getIndices();0===n?.length&&(n=null);const o=r.AA.Vector3[0],a=r.AA.Vector3[1],l=r.AA.Vector3[2];if(t){const e=this.pickedMesh.getVerticesData(s.R.NormalKind);let t=n?r.Pq.FromArrayToRef(e,3*n[3*this.faceId],o):o.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),h=n?r.Pq.FromArrayToRef(e,3*n[3*this.faceId+1],a):a.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),c=n?r.Pq.FromArrayToRef(e,3*n[3*this.faceId+2],l):l.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]);t=t.scale(this.bu),h=h.scale(this.bv),c=c.scale(1-this.bu-this.bv),i=new r.Pq(t.x+h.x+c.x,t.y+h.y+c.y,t.z+h.z+c.z)}else{const e=this.pickedMesh.getVerticesData(s.R.PositionKind),t=n?r.Pq.FromArrayToRef(e,3*n[3*this.faceId],o):o.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),h=n?r.Pq.FromArrayToRef(e,3*n[3*this.faceId+1],a):a.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),c=n?r.Pq.FromArrayToRef(e,3*n[3*this.faceId+2],l):l.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]),u=t.subtract(h),d=c.subtract(h);i=r.Pq.Cross(u,d)}const h=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(r.AA.Matrix[0].copyFrom(i),i=r.AA.Matrix[0],i.setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(r.AA.Matrix[1]),i=r.AA.Matrix[1]),r.Pq.TransformNormalToRef(t,i,t)};if(e&&h(this.pickedMesh,i),this.ray){const t=r.AA.Vector3[0].copyFrom(i);e||h(this.pickedMesh,t),r.Pq.Dot(t,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i}getTextureCoordinates(e=s.R.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;const t=this.pickedMesh.getIndices();if(!t)return null;const i=this.pickedMesh.getVerticesData(e);if(!i)return null;let n=r.I9.FromArray(i,2*t[3*this.faceId]),o=r.I9.FromArray(i,2*t[3*this.faceId+1]),a=r.I9.FromArray(i,2*t[3*this.faceId+2]);return n=n.scale(this.bu),o=o.scale(this.bv),a=a.scale(1-this.bu-this.bv),new r.I9(n.x+o.x+a.x,n.y+o.y+a.y)}}},75174:(e,t,i)=>{"use strict";i.d(t,{ge:()=>s,p9:()=>n,rX:()=>r});let r=!1;function s(e){r=e}const n={get UseOpenGLOrientationForUV(){return r},set UseOpenGLOrientationForUV(e){r=e}}},62061:(e,t,i)=>{"use strict";i.d(t,{H:()=>d});var r=i(15287),s=i(40220),n=i(89518),o=i(56225),a=i(4756),l=i(83839),h=i(60590),c=i(18310),u=i(89237);class d{get options(){return this._options}get shaderPath(){return this._shaderPath}constructor(e,t,i,r={}){this._bindings={},this._samplers={},this._contextIsDirty=!1,this.fastMode=!1,this.onCompiled=null,this.onError=null,this.name=e,this._engine=t,this.uniqueId=l.K.UniqueId,t.enableGPUTimingMeasurements&&(this.gpuTimeInFrame=new u.e),this._engine.getCaps().supportComputeShaders?r.bindingsMapping?(this._context=t.createComputeContext(),this._shaderPath=i,this._options={bindingsMapping:{},defines:[],...r}):h.V.Error("You must provide the binding mappings as browsers don't support reflection for wgsl shaders yet!"):h.V.Error("This engine does not support compute shaders!")}getClassName(){return"ComputeShader"}setTexture(e,t,i=!0){const r=this._bindings[e];this._bindings[e]={type:i?0:4,object:t,indexInGroupEntries:r?.indexInGroupEntries},this._contextIsDirty||(this._contextIsDirty=!r||r.object!==t||r.type!==this._bindings[e].type)}setStorageTexture(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:1,object:t,indexInGroupEntries:i?.indexInGroupEntries}}setExternalTexture(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:6,object:t,indexInGroupEntries:i?.indexInGroupEntries}}setVideoTexture(e,t){return!!t.externalTexture&&(this.setExternalTexture(e,t.externalTexture),!0)}setUniformBuffer(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:d._BufferIsDataBuffer(t)?7:2,object:t,indexInGroupEntries:i?.indexInGroupEntries}}setStorageBuffer(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:d._BufferIsDataBuffer(t)?7:3,object:t,indexInGroupEntries:i?.indexInGroupEntries}}setTextureSampler(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||!t.compareSampler(i.object)),this._bindings[e]={type:5,object:t,indexInGroupEntries:i?.indexInGroupEntries}}isReady(){let e=this._effect;for(const e in this._bindings){const t=this._bindings[e],i=t.type,r=t.object;switch(i){case 0:case 4:case 1:case 6:if(!r.isReady())return!1}}const t=[],i=this._shaderPath;if(this._options.defines)for(let e=0;e{const n=()=>{this.dispatch(e,t,i)?s():setTimeout(n,r)};n()}))}serialize(){const e=n.p.Serialize(this);e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={};for(const t in this._bindings){const i=this._bindings[t],r=i.object;switch(i.type){case 0:case 4:case 1:{const s=r.serialize();s&&(e.textures[t]=s,e.bindings[t]={type:i.type});break}}}return e}static Parse(e,t,i){const r=n.p.Parse((()=>new d(e.name,t.getEngine(),e.shaderPath,e.options)),e,t,i);for(const s in e.textures){const n=e.bindings[s],o=a.g.Parse(e.textures[s],t,i);0===n.type?r.setTexture(s,o):4===n.type?r.setTexture(s,o,!1):r.setStorageTexture(s,o)}return r}static _BufferIsDataBuffer(e){return void 0!==e.underlyingResource}}(0,r.Cg)([(0,s.lK)()],d.prototype,"name",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"fastMode",void 0),(0,o.Y5)("BABYLON.ComputeShader",d)},19164:(e,t,i)=>{"use strict";i.r(t),i.d(t,{ComputeShaderBoundingHelper:()=>l});var r=i(62061),s=i(91112),n=i(12721),o=i(94212),a=i(4216);i(69841).l.ShadersStoreWGSL.boundingInfoComputeShader="struct Results {minX : atomic,\nminY : atomic,\nminZ : atomic,\nmaxX : atomic,\nmaxY : atomic,\nmaxZ : atomic,\ndummy1 : i32,\ndummy2 : i32,};fn floatToBits(value: f32)->i32 {return bitcast(value);}\nfn bitsToFloat(value: i32)->f32 {return bitcast(value);}\nfn atomicMinFloat(atomicVar: ptr,read_write>,value: f32) {let intValue=floatToBits(value);loop {let oldIntValue=atomicLoad(atomicVar);let oldValue=bitsToFloat(oldIntValue);if (value>=oldValue) {break;}\nif (atomicCompareExchangeWeak(atomicVar,oldIntValue,intValue).old_value==oldIntValue) {break;}}}\nfn atomicMaxFloat(atomicVar: ptr,read_write>,value: f32) {let intValue=floatToBits(value);loop {let oldIntValue=atomicLoad(atomicVar);let oldValue=bitsToFloat(oldIntValue);if (value<=oldValue) {break;}\nif (atomicCompareExchangeWeak(atomicVar,oldIntValue,intValue).old_value==oldIntValue) {break;}}}\nfn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4\n{let offset=i32(index) *4; \nlet 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);}\nconst identity=mat4x4f(\nvec4f(1.0,0.0,0.0,0.0),\nvec4f(0.0,1.0,0.0,0.0),\nvec4f(0.0,0.0,1.0,0.0),\nvec4f(0.0,0.0,0.0,1.0)\n);struct Settings {morphTargetTextureInfo: vec3f,\nmorphTargetCount: i32,\nindexResult : u32,};@group(0) @binding(0) var positionBuffer : array;@group(0) @binding(1) var resultBuffer : array;@group(0) @binding(7) var settings : Settings;\n#if NUM_BONE_INFLUENCERS>0\n@group(0) @binding(2) var boneSampler : texture_2d;@group(0) @binding(3) var indexBuffer : array;@group(0) @binding(4) var weightBuffer : array;\n#if NUM_BONE_INFLUENCERS>4\n@group(0) @binding(5) var indexExtraBuffer : array;@group(0) @binding(6) var weightExtraBuffer : array;\n#endif\n#endif\n#ifdef MORPHTARGETS\n@group(0) @binding(8) var morphTargets : texture_2d_array;@group(0) @binding(9) var morphTargetInfluences : array;@group(0) @binding(10) var morphTargetTextureIndices : array;\n#endif\n#ifdef MORPHTARGETS\nfn readVector3FromRawSampler(targetIndex : i32,vertexIndex : u32)->vec3f\n{ \nlet vertexID=f32(vertexIndex)*settings.morphTargetTextureInfo.x;let y=floor(vertexID/settings.morphTargetTextureInfo.y);let x=vertexID-y*settings.morphTargetTextureInfo.y;let textureUV=vec2(i32(x),i32(y));return textureLoad(morphTargets,textureUV,i32(morphTargetTextureIndices[targetIndex]),0).xyz;}\n#endif\n@compute @workgroup_size(256,1,1)\nfn main(@builtin(global_invocation_id) global_id : vec3) {let index=global_id.x;if (index>=arrayLength(&positionBuffer)/3) {return;}\nlet position=vec3f(positionBuffer[index*3],positionBuffer[index*3+1],positionBuffer[index*3+2]);var finalWorld=identity;var positionUpdated=position;\n#if NUM_BONE_INFLUENCERS>0\nvar influence : mat4x4;let matricesIndices=indexBuffer[index];let matricesWeights=weightBuffer[index];influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\nlet matricesIndicesExtra=indexExtraBuffer[index];let matricesWeightsExtra=weightExtraBuffer[index];influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra.x)*matricesWeightsExtra.x;\n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra.y)*matricesWeightsExtra.y;\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra.z)*matricesWeightsExtra.z;\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra.w)*matricesWeightsExtra.w;\n#endif \n#endif \nfinalWorld=finalWorld*influence;\n#endif\n#ifdef MORPHTARGETS\nfor (var i=0; i=settings.morphTargetCount) {break;}\npositionUpdated=positionUpdated+(readVector3FromRawSampler(i,index)-position)*morphTargetInfluences[i];}\n#endif\nvar worldPos=finalWorld*vec4f(positionUpdated.x,positionUpdated.y,positionUpdated.z,1.0);atomicMinFloat(&resultBuffer[settings.indexResult].minX,worldPos.x);atomicMinFloat(&resultBuffer[settings.indexResult].minY,worldPos.y);atomicMinFloat(&resultBuffer[settings.indexResult].minZ,worldPos.z);atomicMaxFloat(&resultBuffer[settings.indexResult].maxX,worldPos.x);atomicMaxFloat(&resultBuffer[settings.indexResult].maxY,worldPos.y);atomicMaxFloat(&resultBuffer[settings.indexResult].maxZ,worldPos.z);}\n";class l{constructor(e){this._computeShadersCache={},this._positionBuffers={},this._indexBuffers={},this._weightBuffers={},this._indexExtraBuffers={},this._weightExtraBuffers={},this._morphTargetInfluenceBuffers={},this._morphTargetTextureIndexBuffers={},this._ubos=[],this._uboIndex=0,this._processedMeshes=[],this._computeShaders=[],this._uniqueComputeShaders=new Set,this._resultBuffers=[],this._engine=e}_getComputeShader(e,t,i){let s;const n=e.join("\n");if(this._computeShadersCache[n])s=this._computeShadersCache[n];else{const o={positionBuffer:{group:0,binding:0},resultBuffer:{group:0,binding:1},settings:{group:0,binding:7}};t&&(o.boneSampler={group:0,binding:2},o.indexBuffer={group:0,binding:3},o.weightBuffer={group:0,binding:4},o.indexExtraBuffer={group:0,binding:5},o.weightExtraBuffer={group:0,binding:6}),i&&(o.morphTargets={group:0,binding:8},o.morphTargetInfluences={group:0,binding:9},o.morphTargetTextureIndices={group:0,binding:10}),s=new r.H(`boundingInfoCompute${t?"_bones":""}${i?"_morphs":""}`,this._engine,"boundingInfo",{bindingsMapping:o,defines:e}),this._computeShadersCache[n]=s}return s}_getUBO(){if(this._uboIndex>=this._ubos.length){const e=new a.D(this._engine);e.addFloat3("morphTargetTextureInfo",0,0,0),e.addUniform("morphTargetCount",1),e.addUniform("indexResult",1),this._ubos.push(e)}return this._ubos[this._uboIndex++]}_extractDataAndLink(e,t,i,r,n,o){let a;const l=t.getTotalVertices();if(o[t.uniqueId])a=o[t.uniqueId];else{const e=t.getVertexBuffer(i)?.getFloatData(l);a=new s.K(this._engine,Float32Array.BYTES_PER_ELEMENT*l*r),a.update(e),o[t.uniqueId]=a}e.setStorageBuffer(n,a)}_prepareStorage(e,t,i,r,n,o){let a;r[i]?a=r[i]:(a=new s.K(this._engine,Float32Array.BYTES_PER_ELEMENT*n),r[i]=a),a.update(o),e.setStorageBuffer(t,a)}async processAsync(e){await this.registerMeshListAsync(e),this.processMeshList(),await this.fetchResultsForMeshListAsync()}registerMeshListAsync(e){this._disposeForMeshList(),Array.isArray(e)||(e=[e]);let t=0;for(let i=0;i{const t=()=>{const i=this._uniqueComputeShaders.keys();for(let e=i.next();!0!==e.done;e=i.next())if(!e.value.isReady())return void setTimeout(t,10);e()};t()}))}processMeshList(){if(0===this._processedMeshes.length)return;this._uboIndex=0;const e=8*this._processedMeshes.length,t=new Float32Array(e),i=new s.K(this._engine,Float32Array.BYTES_PER_ELEMENT*e);this._resultBuffers.push(i);for(let e=0;e0,h=l?o:s;if(this._extractDataAndLink(h,t,n.R.PositionKind,3,"positionBuffer",this._positionBuffers),t&&t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&t.skeleton.useTextureToStoreBoneMatrices){this._extractDataAndLink(h,t,n.R.MatricesIndicesKind,4,"indexBuffer",this._indexBuffers),this._extractDataAndLink(h,t,n.R.MatricesWeightsKind,4,"weightBuffer",this._weightBuffers);const e=t.skeleton.getTransformMatrixTexture(t);h.setTexture("boneSampler",e,!1),t.numBoneInfluencers>4&&(this._extractDataAndLink(h,t,n.R.MatricesIndicesExtraKind,4,"indexExtraBuffer",this._indexExtraBuffers),this._extractDataAndLink(h,t,n.R.MatricesWeightsExtraKind,4,"weightExtraBuffer",this._weightExtraBuffers))}const c=this._getUBO();if(l){const e=a._targetStoreTexture;h.setTexture("morphTargets",e,!1),this._prepareStorage(h,"morphTargetInfluences",t.uniqueId,this._morphTargetInfluenceBuffers,a.numInfluencers,a.influences),this._prepareStorage(h,"morphTargetTextureIndices",t.uniqueId,this._morphTargetTextureIndexBuffers,a.numInfluencers,a._morphTargetTextureIndices),c.updateFloat3("morphTargetTextureInfo",a._textureVertexStride,a._textureWidth,a._textureHeight),c.updateInt("morphTargetCount",a.numInfluencers),c.update()}h.setStorageBuffer("resultBuffer",i),h.setUniformBuffer("settings",c),h.dispatch(Math.ceil(r/256)),this._engine.flushFramebuffer()}}fetchResultsForMeshListAsync(){return new Promise((e=>{const t=[];let i=0;for(let e=0;e{let t=0;for(let e=0;e0&&(s.minimizeInPlace(l.getBoundingInfo().minimum),n.maximizeInPlace(l.getBoundingInfo().maximum)),l._refreshBoundingInfoDirect(a)}t+=8*this._processedMeshes.length}for(const e of this._resultBuffers)e.dispose();this._resultBuffers=[],this._uboIndex=0,e()}))}))}_disposeCache(e){for(const t in e)e[t].dispose()}_disposeForMeshList(){for(const e of this._resultBuffers)e.dispose();this._resultBuffers=[],this._processedMeshes=[],this._computeShaders=[],this._uniqueComputeShaders=new Set}dispose(){this._disposeCache(this._positionBuffers),this._positionBuffers={},this._disposeCache(this._indexBuffers),this._indexBuffers={},this._disposeCache(this._weightBuffers),this._weightBuffers={},this._disposeCache(this._morphTargetInfluenceBuffers),this._morphTargetInfluenceBuffers={},this._disposeCache(this._morphTargetTextureIndexBuffers),this._morphTargetTextureIndexBuffers={};for(const e of this._ubos)e.dispose();this._ubos=[],this._computeShadersCache={},this._engine=void 0,this._disposeForMeshList()}}},43306:(e,t,i)=>{"use strict";i.r(t),i.d(t,{TransformFeedbackBoundingHelper:()=>l});var r=i(12721),s=i(85770),n=i(890),o=i(94212),a=i(69841);i(39948),i(66682),i(9158),i(11783),i(99216),i(44219),i(78792),i(95532);a.l.ShadersStore.gpuTransformVertexShader="attribute vec3 position;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\nout vec3 outPosition;const mat4 identity=mat4(\nvec4(1.0,0.0,0.0,0.0),\nvec4(0.0,1.0,0.0,0.0),\nvec4(0.0,0.0,1.0,0.0),\nvec4(0.0,0.0,0.0,1.0)\n);void main(void) {vec3 positionUpdated=position;\n#include\n#include[0..maxSimultaneousMorphTargets]\nmat4 finalWorld=identity;\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);outPosition=worldPos.xyz;}";a.l.ShadersStore.gpuTransformPixelShader="#version 300 es\nvoid main() {discard;}\n";class l{constructor(e){this._buffers={},this._effects={},this._meshListCounter=0,this._engine=e}processAsync(e){return Array.isArray(e)||(e=[e]),this._meshListCounter=0,this._processMeshList(e),Promise.resolve()}_processMeshList(e){const t=this._engine.getCaps().parallelShaderCompile;this._engine.getCaps().parallelShaderCompile=void 0;for(let t=0;t4&&(h.push(r.R.MatricesIndicesExtraKind),h.push(r.R.MatricesWeightsExtraKind));const e=i.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+i.numBoneInfluencers),e.isUsingTextureForMatrices?(a.push("#define BONETEXTURE"),-1===l.indexOf("boneTextureWidth")&&l.push("boneTextureWidth"),-1===c.indexOf("boneSampler")&&c.push("boneSampler")):(a.push("#define BonesPerMesh "+(e.bones.length+1)),-1===l.indexOf("mBones")&&l.push("mBones"))}else a.push("#define NUM_BONE_INFLUENCERS 0");const u=i?i.morphTargetManager:null;if(u){o=u.numMaxInfluencers||u.numInfluencers,o>0&&a.push("#define MORPHTARGETS"),u.isUsingTextureForTargets&&(a.push("#define MORPHTARGETS_TEXTURE"),-1===l.indexOf("morphTargetTextureIndices")&&l.push("morphTargetTextureIndices"),-1===c.indexOf("morphTargets")&&c.push("morphTargets")),a.push("#define NUM_MORPH_INFLUENCERS "+o);for(let e=0;e0&&(l=l.slice(),l.push("morphTargetInfluences"),l.push("morphTargetCount"),l.push("morphTargetTextureInfo"),l.push("morphTargetTextureIndices"))}const d=i.bakedVertexAnimationManager;d&&d.isEnabled&&(a.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===l.indexOf("bakedVertexAnimationSettings")&&l.push("bakedVertexAnimationSettings"),-1===l.indexOf("bakedVertexAnimationTextureSizeInverted")&&l.push("bakedVertexAnimationTextureSizeInverted"),-1===l.indexOf("bakedVertexAnimationTime")&&l.push("bakedVertexAnimationTime"),-1===c.indexOf("bakedVertexAnimationTexture")&&c.push("bakedVertexAnimationTexture"),(0,s.J2)(h,i,a));const f=a.join("\n");if(this._effects[f])n=this._effects[f];else{const e={attributes:h,uniformsNames:l,uniformBuffersNames:[],samplers:c,defines:f,fallbacks:null,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:o},maxSimultaneousLights:0,transformFeedbackVaryings:["outPosition"]};n=this._engine.createEffect("gpuTransform",e,this._engine),this._effects[f]=n}this._compute(i,n)}this._engine.getCaps().parallelShaderCompile=t}_compute(e,t){const i=this._engine;let o;const a=e.getTotalVertices();if(this._buffers[e.uniqueId])o=this._buffers[e.uniqueId];else{const t=new Float32Array(3*a);o=new r.h(e.getEngine(),t,!0,3),this._buffers[e.uniqueId]=o}t.getEngine().enableEffect(t),e._bindDirect(t,null,!0),(0,s.f$)(e,t);const h=e.morphTargetManager;h&&h.numInfluencers>0&&(0,s.nR)(e,t);const c=e.bakedVertexAnimationManager;c&&c.isEnabled&&e.bakedVertexAnimationManager?.bind(t,!1);const u=o.getData();if(i.bindTransformFeedbackBuffer(o.getBuffer()),i.setRasterizerState(!1),i.beginTransformFeedback(!0),i.drawArraysType(2,0,a),i.endTransformFeedback(),i.setRasterizerState(!0),i.readTransformFeedbackBuffer(u),i.bindTransformFeedbackBuffer(null),0===this._meshListCounter)e._refreshBoundingInfo(u,null);else{const t=e.getBoundingInfo().boundingBox,i=(0,n.b8)(u,0,a);l._Min.copyFrom(t.minimum).minimizeInPlace(i.minimum),l._Max.copyFrom(t.maximum).maximizeInPlace(i.maximum),e._refreshBoundingInfoDirect({minimum:l._Min,maximum:l._Max})}}registerMeshListAsync(e){return Array.isArray(e)||(e=[e]),this._meshList=e,this._meshListCounter=0,Promise.resolve()}processMeshList(){0!==this._meshList.length&&(this._processMeshList(this._meshList),this._meshListCounter++)}fetchResultsForMeshListAsync(){return this._meshListCounter=0,Promise.resolve()}dispose(){for(const e in this._buffers)this._buffers[e].dispose();this._buffers={},this._effects={},this._engine=null}}l._Min=new o.Pq,l._Max=new o.Pq},58292:(e,t,i)=>{"use strict";var r,s,n,o,a,l,h;i.d(t,{ST:()=>s,Ze:()=>n,bq:()=>r,dR:()=>h,h8:()=>o,pI:()=>a,sZ:()=>l}),function(e){e[e.Generic=0]="Generic",e[e.Keyboard=1]="Keyboard",e[e.Mouse=2]="Mouse",e[e.Touch=3]="Touch",e[e.DualShock=4]="DualShock",e[e.Xbox=5]="Xbox",e[e.Switch=6]="Switch",e[e.DualSense=7]="DualSense"}(r||(r={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical",e[e.LeftClick=2]="LeftClick",e[e.MiddleClick=3]="MiddleClick",e[e.RightClick=4]="RightClick",e[e.BrowserBack=5]="BrowserBack",e[e.BrowserForward=6]="BrowserForward",e[e.MouseWheelX=7]="MouseWheelX",e[e.MouseWheelY=8]="MouseWheelY",e[e.MouseWheelZ=9]="MouseWheelZ",e[e.Move=12]="Move"}(s||(s={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical",e[e.LeftClick=2]="LeftClick",e[e.MiddleClick=3]="MiddleClick",e[e.RightClick=4]="RightClick",e[e.BrowserBack=5]="BrowserBack",e[e.BrowserForward=6]="BrowserForward",e[e.MouseWheelX=7]="MouseWheelX",e[e.MouseWheelY=8]="MouseWheelY",e[e.MouseWheelZ=9]="MouseWheelZ",e[e.DeltaHorizontal=10]="DeltaHorizontal",e[e.DeltaVertical=11]="DeltaVertical"}(n||(n={})),function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.L2=6]="L2",e[e.R2=7]="R2",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.L3=10]="L3",e[e.R3=11]="R3",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.TouchPad=17]="TouchPad",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(o||(o={})),function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.L2=6]="L2",e[e.R2=7]="R2",e[e.Create=8]="Create",e[e.Options=9]="Options",e[e.L3=10]="L3",e[e.R3=11]="R3",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.TouchPad=17]="TouchPad",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(a||(a={})),function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.LT=6]="LT",e[e.RT=7]="RT",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LS=10]="LS",e[e.RS=11]="RS",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.LStickXAxis=17]="LStickXAxis",e[e.LStickYAxis=18]="LStickYAxis",e[e.RStickXAxis=19]="RStickXAxis",e[e.RStickYAxis=20]="RStickYAxis"}(l||(l={})),function(e){e[e.B=0]="B",e[e.A=1]="A",e[e.Y=2]="Y",e[e.X=3]="X",e[e.L=4]="L",e[e.R=5]="R",e[e.ZL=6]="ZL",e[e.ZR=7]="ZR",e[e.Minus=8]="Minus",e[e.Plus=9]="Plus",e[e.LS=10]="LS",e[e.RS=11]="RS",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.Capture=17]="Capture",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(h||(h={}))},77333:(e,t,i)=>{"use strict";i.d(t,{c:()=>s});var r=i(43279);class s{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new r.cP,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}},78035:(e,t,i)=>{"use strict";i.d(t,{Z:()=>p});var r=i(58292),s=i(43279),n=i(7474);class o{static CreateDeviceEvent(e,t,i,s,n,o,a){switch(e){case r.bq.Keyboard:return this._CreateKeyboardEvent(i,s,n,o);case r.bq.Mouse:if(i===r.ST.MouseWheelX||i===r.ST.MouseWheelY||i===r.ST.MouseWheelZ)return this._CreateWheelEvent(e,t,i,s,n,o);case r.bq.Touch:return this._CreatePointerEvent(e,t,i,s,n,o,a);default:throw`Unable to generate event for device ${r.bq[e]}`}}static _CreatePointerEvent(e,t,i,s,n,o,a){const l=this._CreateMouseEvent(e,t,i,s,n,o);e===r.bq.Mouse?(l.deviceType=r.bq.Mouse,l.pointerId=1,l.pointerType="mouse"):(l.deviceType=r.bq.Touch,l.pointerId=a??t,l.pointerType="touch");let h=0;return h+=n.pollInput(e,t,r.ST.LeftClick),h+=2*n.pollInput(e,t,r.ST.RightClick),h+=4*n.pollInput(e,t,r.ST.MiddleClick),l.buttons=h,i===r.ST.Move?l.type="pointermove":i>=r.ST.LeftClick&&i<=r.ST.RightClick&&(l.type=1===s?"pointerdown":"pointerup",l.button=i-2),l}static _CreateWheelEvent(e,t,i,s,o,a){const l=this._CreateMouseEvent(e,t,i,s,o,a);switch(l.pointerId=1,l.type="wheel",l.deltaMode=n.s.DOM_DELTA_PIXEL,l.deltaX=0,l.deltaY=0,l.deltaZ=0,i){case r.ST.MouseWheelX:l.deltaX=s;break;case r.ST.MouseWheelY:l.deltaY=s;break;case r.ST.MouseWheelZ:l.deltaZ=s}return l}static _CreateMouseEvent(e,t,i,s,n,o){const a=this._CreateEvent(o),l=n.pollInput(e,t,r.ST.Horizontal),h=n.pollInput(e,t,r.ST.Vertical);return o?(a.movementX=0,a.movementY=0,a.offsetX=a.movementX-o.getBoundingClientRect().x,a.offsetY=a.movementY-o.getBoundingClientRect().y):(a.movementX=n.pollInput(e,t,10),a.movementY=n.pollInput(e,t,11),a.offsetX=0,a.offsetY=0),this._CheckNonCharacterKeys(a,n),a.clientX=l,a.clientY=h,a.x=l,a.y=h,a.deviceType=e,a.deviceSlot=t,a.inputIndex=i,a}static _CreateKeyboardEvent(e,t,i,s){const n=this._CreateEvent(s);return this._CheckNonCharacterKeys(n,i),n.deviceType=r.bq.Keyboard,n.deviceSlot=0,n.inputIndex=e,n.type=1===t?"keydown":"keyup",n.key=String.fromCharCode(e),n.keyCode=e,n}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(r.bq.Keyboard),s=i&&1===t.pollInput(r.bq.Keyboard,0,18),n=i&&1===t.pollInput(r.bq.Keyboard,0,17),o=i&&(1===t.pollInput(r.bq.Keyboard,0,91)||1===t.pollInput(r.bq.Keyboard,0,92)||1===t.pollInput(r.bq.Keyboard,0,93)),a=i&&1===t.pollInput(r.bq.Keyboard,0,16);e.altKey=s,e.ctrlKey=n,e.metaKey=o,e.shiftKey=a}static _CreateEvent(e){const t={preventDefault:()=>{}};return t.target=e,t}}class a{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,((e,t,r,s)=>{const n=o.CreateDeviceEvent(e,t,r,s,this);i(e,t,n)})):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===r.bq.Mouse||e===r.bq.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}var l=i(68191),h=i(9723);const c=Object.keys(r.ST).length/2;class u{constructor(e,t,i,r){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=h.S0.IsSafari(),this._usingMacOS=(0,l.XD)()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=e=>{},this._keyboardUpEvent=e=>{},this._keyboardBlurEvent=e=>{},this._pointerMoveEvent=e=>{},this._pointerDownEvent=e=>{},this._pointerUpEvent=e=>{},this._pointerCancelEvent=e=>{},this._pointerWheelEvent=e=>{},this._pointerBlurEvent=e=>{},this._pointerMacOSChromeOutEvent=e=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=(0,l.XD)()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=(0,l.XD)()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=h.S0.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=r,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){const s=this._inputs[e][t];if(!s)throw`Unable to find device ${r.bq[e]}`;e>=r.bq.DualShock&&e<=r.bq.DualSense&&this._updateDevice(e,t,i);const n=s[i];if(void 0===n)throw`Unable to find input ${i} for device ${r.bq[e]} in slot ${t}`;return i===r.ST.Move&&h.S0.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),n}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){const e=this?._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs)for(const e of this._inputs)if(e)for(const t in e){const i=e[+t];if(i)for(let e=0;e{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(r.bq.Keyboard,0,255));const t=this._inputs[r.bq.Keyboard][0];if(t){t[e.keyCode]=1;const i=e;i.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&"Meta"!==e.key&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(r.bq.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(r.bq.Keyboard,0,255));const t=this._inputs[r.bq.Keyboard][0];if(t){t[e.keyCode]=0;const i=e;if(i.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(const e of this._metaKeys){const i=o.CreateDeviceEvent(r.bq.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(r.bq.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(r.bq.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[r.bq.Keyboard][0];for(let t=0;t{const t=this._getPointerType(e);let i=t===r.bq.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===r.bq.Touch&&-1===i){const r=this._activeTouchIds.indexOf(-1);if(!(r>=0))return void h.S0.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=r,this._activeTouchIds[r]=e.pointerId,this._onDeviceConnected(t,i)}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const n=e;n.inputIndex=r.ST.Move,s[r.ST.Horizontal]=e.clientX,s[r.ST.Vertical]=e.clientY,t===r.bq.Touch&&0===s[r.ST.LeftClick]&&(s[r.ST.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,n),this._usingSafari||-1===e.button||(n.inputIndex=e.button+2,s[e.button+2]=s[e.button+2]?0:1,this._onInputChanged(t,i,n))}},this._pointerDownEvent=e=>{const t=this._getPointerType(e);let i=t===r.bq.Mouse?0:e.pointerId;if(t===r.bq.Touch){let t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t&&(t=this._activeTouchIds.indexOf(-1)),!(t>=0))return void h.S0.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=t,this._activeTouchIds[t]=e.pointerId}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]?t===r.bq.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const n=s[r.ST.Horizontal],o=s[r.ST.Vertical];if(t===r.bq.Mouse){if(void 0===e.pointerId&&(e.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(e){}}else if(e.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(e.pointerId)}catch(e){}s[r.ST.Horizontal]=e.clientX,s[r.ST.Vertical]=e.clientY,s[e.button+2]=1;const a=e;a.inputIndex=e.button+2,this._onInputChanged(t,i,a),n===e.clientX&&o===e.clientY||(a.inputIndex=r.ST.Move,this._onInputChanged(t,i,a))}},this._pointerUpEvent=e=>{const t=this._getPointerType(e),i=t===r.bq.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===r.bq.Touch){if(-1===i)return;this._activeTouchIds[i]=-1}const s=this._inputs[t]?.[i];if(s&&0!==s[e.button+2]){const n=s[r.ST.Horizontal],o=s[r.ST.Vertical];s[r.ST.Horizontal]=e.clientX,s[r.ST.Vertical]=e.clientY,s[e.button+2]=0;const a=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),n===e.clientX&&o===e.clientY||(a.inputIndex=r.ST.Move,this._onInputChanged(t,i,a)),a.inputIndex=e.button+2,t===r.bq.Mouse&&this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(t,i,a),t===r.bq.Touch&&this._onDeviceDisconnected(t,i)}},this._pointerCancelEvent=e=>{if("mouse"===e.pointerType){const e=this._inputs[r.bq.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=r.ST.LeftClick;t<=r.ST.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=o.CreateDeviceEvent(r.bq.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(r.bq.Mouse,0,i)}}else{const t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t)return;this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[r.bq.Touch][t][r.ST.LeftClick]=0;const i=o.CreateDeviceEvent(r.bq.Touch,t,r.ST.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(r.bq.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(r.bq.Touch,t)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"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(e){}this._pointerBlurEvent=()=>{if(this.isDeviceAvailable(r.bq.Mouse)){const e=this._inputs[r.bq.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=r.ST.LeftClick;t<=r.ST.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=o.CreateDeviceEvent(r.bq.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(r.bq.Mouse,0,i)}}if(this.isDeviceAvailable(r.bq.Touch)){const e=this._inputs[r.bq.Touch];for(let t=0;t{const t=r.bq.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,c));const i=this._inputs[t][0];if(i){i[r.ST.MouseWheelX]=e.deltaX||0,i[r.ST.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[r.ST.MouseWheelZ]=e.deltaZ||0;const s=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[r.ST.MouseWheelX]&&(s.inputIndex=r.ST.MouseWheelX,this._onInputChanged(t,0,s)),0!==i[r.ST.MouseWheelY]&&(s.inputIndex=r.ST.MouseWheelY,this._onInputChanged(t,0,s)),0!==i[r.ST.MouseWheelZ]&&(s.inputIndex=r.ST.MouseWheelZ,this._onInputChanged(t,0,s))}},this._usingMacOS&&this._isUsingChromium&&(this._pointerMacOSChromeOutEvent=e=>{e.buttons>1&&this._pointerCancelEvent(e)},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}),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add((()=>{if(this.isDeviceAvailable(r.bq.Mouse)){const e=this._inputs[r.bq.Mouse][0];e[r.ST.MouseWheelX]=0,e[r.ST.MouseWheelY]=0,e[r.ST.MouseWheelZ]=0}}))}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){const r=navigator.getGamepads()[t];if(r&&e===this._gamepads[t]){const s=this._inputs[e][t];i>=r.buttons.length?s[i]=r.axes[i-r.buttons.length].valueOf():s[i]=r.buttons[i].value}}_getGamepadDeviceType(e){return-1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?r.bq.DualSense:r.bq.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?r.bq.Xbox:-1!==e.indexOf("057e")?r.bq.Switch:r.bq.Generic}_getPointerType(e){let t=r.bq.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=r.bq.Touch),t}}var d=i(77333);class f{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=e=>{for(let t=0;t{const t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};const t=Object.keys(r.bq).length/2;this._devices=new Array(t);const i=(e,t)=>{this._devices[e]||(this._devices[e]=new Array),this._devices[e][t]||(this._devices[e][t]=t);for(const i of this._registeredManagers){const r=new d.c(this._deviceInputSystem,e,t);i._addDevice(r)}},s=(e,t)=>{this._devices[e]?.[t]&&delete this._devices[e][t];for(const i of this._registeredManagers)i._removeDevice(e,t)},n=(e,t,i)=>{if(i)for(const r of this._registeredManagers)r._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new a(i,s,n):this._deviceInputSystem=new u(e,i,s,n)}dispose(){this._deviceInputSystem.dispose()}}class p{getDeviceSource(e,t){if(void 0===t){if(void 0===this._firstDevice[e])return null;t=this._firstDevice[e]}return this._devices[e]&&void 0!==this._devices[e][t]?this._devices[e][t]:null}getDeviceSources(e){return this._devices[e]?this._devices[e].filter((e=>!!e)):[]}constructor(e){const t=Object.keys(r.bq).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new f(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new s.cP((e=>{for(const t of this._devices)if(t)for(const i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)})),this.onDeviceDisconnectedObservable=new s.cP,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){const i=this._devices[e]?.[t];this.onDeviceDisconnectedObservable.notifyObservers(i),this._devices[e]?.[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){this._devices[e]?.[t]?.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case r.bq.Keyboard:case r.bq.Mouse:this._firstDevice[e]=0;break;case r.bq.Touch:case r.bq.DualSense:case r.bq.DualShock:case r.bq.Xbox:case r.bq.Switch:case r.bq.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t)for(let i=0;i{"use strict";var r=i(7107),s=i(60590),n=i(28909),o=i(71627),a=i(55935),l=i(47221);a.$.prototype._partialLoadFile=function(e,t,i,r,s=null){this._loadFile(e,(e=>{i[t]=e,i._internalCount++,6===i._internalCount&&r(i)}),void 0,void 0,!0,((e,t)=>{s&&e&&s(e.status+" "+e.statusText,t)}))},a.$.prototype._cascadeLoadFiles=function(e,t,i,r=null){const s=[];s._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(i[e],e,s,t,r)},a.$.prototype._cascadeLoadImgs=function(e,t,i,r,s=null,n){const o=[];o._internalCount=0;for(let a=0;a<6;a++)this._partialLoadImg(r[a],a,o,e,t,i,s,n)},a.$.prototype._partialLoadImg=function(e,t,i,r,s,a,l=null,h){const c=(0,o.z)();(0,n.W$)(e,(e=>{i[t]=e,i._internalCount++,r&&r.removePendingData(c),6===i._internalCount&&a&&a(s,i)}),((e,t)=>{r&&r.removePendingData(c),l&&l(e,t)}),r?r.offlineProvider:null,h),r&&r.addPendingData(c)},a.$.prototype.createCubeTextureBase=function(e,t,i,n,o=null,a=null,h,c=null,u=!1,d=0,f=0,p=null,_=null,m=null,g=!1,v=null){const x=p||new r.h(this,7);x.isCube=!0,x.url=e,x.generateMipMaps=!n,x._lodGenerationScale=d,x._lodGenerationOffset=f,x._useSRGBBuffer=!!g&&this._caps.supportSRGBBuffers&&(this.version>1||this.isWebGPU||!!n),x!==p&&(x.label=e.substring(0,60)),this._doNotHandleContextLost||(x._extension=c,x._files=i,x._buffer=v);const b=e;this._transformTextureUrl&&!p&&(e=this._transformTextureUrl(e));const S=e.split("?")[0],T=S.lastIndexOf("."),C=c||(T>-1?S.substring(T).toLowerCase():""),y=(0,l.gT)(C),E=(r,l)=>{e===b?a&&r&&a(r.status+" "+r.statusText,l):(s.V.Warn(`Failed to load ${e}, falling back to the ${b}`),this.createCubeTextureBase(b,t,i,!!n,o,a,h,c,u,d,f,x,_,m,g,v))};if(y)y.then((r=>{const n=e=>{_&&_(x,e),r.loadCubeData(e,x,u,o,a)};v?n(v):i&&6===i.length?r.supportCascades?this._cascadeLoadFiles(t,(e=>n(e.map((e=>new Uint8Array(e))))),i,a):a?a("Textures type does not support cascades."):s.V.Warn("Texture loader does not support cascades."):this._loadFile(e,(e=>n(new Uint8Array(e))),void 0,void 0,!0,E)}));else{if(!i||0===i.length)throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");this._cascadeLoadImgs(t,x,((e,t)=>{m&&m(e,t)}),i,a)}return this._internalTexturesCache.push(x),x}},88217:(e,t,i)=>{"use strict";i.d(t,{nO:()=>E,pB:()=>T,jC:()=>y,M0:()=>C,Iq:()=>D,J:()=>w});class r{constructor(){this.children=[]}isValid(e){return!0}process(e,t){let i="";if(this.line){let r=this.line;const s=t.processor;if(s){s.lineProcessor&&(r=s.lineProcessor(r,t.isFragment,t.processingContext));const i=t.processor?.attributeKeywordName??"attribute",n=t.isFragment&&t.processor?.varyingFragmentKeywordName?t.processor?.varyingFragmentKeywordName:!t.isFragment&&t.processor?.varyingVertexKeywordName?t.processor?.varyingVertexKeywordName:"varying";!t.isFragment&&s.attributeProcessor&&this.line.startsWith(i)?r=s.attributeProcessor(this.line,e,t.processingContext):s.varyingProcessor&&(s.varyingCheck?.(this.line,t.isFragment)||!s.varyingCheck&&this.line.startsWith(n))?r=s.varyingProcessor(this.line,t.isFragment,e,t.processingContext):s.uniformProcessor&&s.uniformRegexp&&s.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(r=s.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):s.uniformBufferProcessor&&s.uniformBufferRegexp&&s.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(r=s.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):s.textureProcessor&&s.textureRegexp&&s.textureRegexp.test(this.line)?r=s.textureProcessor(this.line,t.isFragment,e,t.processingContext):(s.uniformProcessor||s.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?s.uniformProcessor&&(r=s.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):s.uniformBufferProcessor&&(r=s.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,s.endOfUniformBufferProcessor&&(r=s.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}i+=r+"\n"}return this.children.forEach((r=>{i+=r.process(e,t)})),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),i}}class s{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(e);else{const e=t.split(";");for(let t=0;t{c=c.trim(),""!==c&&(i.push(c),c="")},n=e=>{ra._Stack[r],l=()=>-1===r?"!!INVALID EXPRESSION!!":a._Stack[r--];let h=0,c="";for(;h1){for(s();-1!==r&&a._OperatorPriority[o()]>=a._OperatorPriority[u];)i.push(l());n(u),h++}else c+=t;h++}for(s();-1!==r;)"("===o()?l():i.push(l());return a._InfixToPostfixCache.size>=a.InfixToPostfixCacheLimitSize&&a.ClearCache(),a._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(a._InfixToPostfixCache.entries()).sort(((e,t)=>e[1].accessTime-t[1].accessTime));for(let t=0;t":i=r>s;break;case"<":i=r=":i=r>=s;break;case"==":i=r===s;break;case"!=":i=r!==s}return i}}var d=i(75108),f=i(2636);const p=/defined\s*?\((.+?)\)/g,_=/defined\s*?\[(.+?)\]/g,m=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,g=/__decl__/,v=/light\{X\}.(\w*)/g,x=/\{X\}/g,b=[],S=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;function T(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}function C(e,t,i,r){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),D(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e,t.defines));const s=function(e,t,i){let r=function(e,t){if(t.processor?.noPrecision)return e;const i=t.shouldUseHighPrecisionShader;return-1===e.indexOf("precision highp float")?e=i?"precision highp float;\n"+e:"precision mediump float;\n"+e:i||(e=e.replace("precision highp float","precision mediump float")),e}(e,t);if(!t.processor)return r;if(0===t.processor.shaderLanguage&&-1!==r.indexOf("#version 3")&&(r=r.replace("#version 300 es",""),!t.processor.parseGLES3))return r;const s=t.defines,n=O(t,i);return t.processor.preProcessor&&(r=t.processor.preProcessor(r,s,n,t.isFragment,t.processingContext)),r=M(r,n,t),t.processor.postProcessor&&(r=t.processor.postProcessor(r,s,t.isFragment,t.processingContext,i?{drawBuffersExtensionDisabled:!i.getCaps().drawBuffersExtension}:{})),i?._features.needShaderCodeInlining&&(r=i.inlineShaderCode(r)),r}(e,t,r);i(s,e)}))}function y(e,t,i,r){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),D(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e,t.defines));const s=function(e,t,i){let r=e;const s=t.defines,n=O(t,i);return t.processor?.preProcessor&&(r=t.processor.preProcessor(r,s,n,t.isFragment,t.processingContext)),r=M(r,n,t),t.processor?.postProcessor&&(r=t.processor.postProcessor(r,s,t.isFragment,t.processingContext,i?{drawBuffersExtensionDisabled:!i.getCaps().drawBuffersExtension}:{})),i._features.needShaderCodeInlining&&(r=i.inlineShaderCode(r)),r}(e,t,r);i(s,e)}))}function E(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}function P(e){const t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new l(t[1].trim(),"!"===e[0]);const i=["==","!=",">=","<=","<",">"];let r="",s=0;for(r of i)if(s=e.indexOf(r),s>-1)break;if(-1===s)return new l(e);const n=e.substring(0,s).trim(),o=e.substring(s+r.length).trim();return new u(n,r,o)}function A(e,t){const i=new o,r=e.substring(0,t);let s=e.substring(t);return s=s.substring(0,(s.indexOf("//")+1||s.length+1)-1).trim(),i.testExpression="#ifdef"===r?new l(s):"#ifndef"===r?new l(s,!0):function(e){e=e.replace(p,"defined[$1]");const t=a.infixToPostfix(e),i=[];for(const e of t)if("||"!==e&&"&&"!==e)i.push(e);else if(i.length>=2){let t=i[i.length-1],r=i[i.length-2];i.length-=2;const s="&&"==e?new c:new h;"string"==typeof t&&(t=t.replace(_,"defined($1)")),"string"==typeof r&&(r=r.replace(_,"defined($1)")),s.leftOperand="string"==typeof r?P(r):r,s.rightOperand="string"==typeof t?P(t):t,i.push(s)}let r=i[i.length-1];return"string"==typeof r&&(r=r.replace(_,"defined($1)")),"string"==typeof r?P(r):r}(s),i}function R(e,t,i){let s=e.currentLine;for(;I(e,i);){s=e.currentLine;const n=s.substring(0,5).toLowerCase();if("#else"===n){const i=new r;return t.children.push(i),void I(e,i)}if("#elif"===n){const e=A(s,5);t.children.push(e),i=e}}}function I(e,t){for(;e.canRead;){e.lineIndex++;const i=e.currentLine;if(i.indexOf("#")>=0){const r=S.exec(i);if(r&&r.length){switch(r[0]){case"#ifdef":{const r=new n;t.children.push(r);const s=A(i,6);r.children.push(s),R(e,r,s);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const r=new n;t.children.push(r);const s=A(i,7);r.children.push(s),R(e,r,s);break}case"#if":{const r=new n,s=A(i,3);t.children.push(r),r.children.push(s),R(e,r,s);break}}continue}}const s=new r;if(s.line=i,t.children.push(s),"#"===i[0]&&"d"===i[1]){const e=i.replace(";","").split(" ");s.additionalDefineKey=e[1],3===e.length&&(s.additionalDefineValue=e[2])}}return!1}function M(e,t,i){const n=new r,o=new s;return o.lineIndex=-1,o.lines=e.split("\n"),I(o,n),n.process(t,i)}function O(e,t){const i=e.defines,r={};for(const e of i){const t=e.replace("#define","").replace(";","").trim().split(" ");r[t[0]]=t.length>1?t[1]:""}return 0===e.processor?.shaderLanguage&&(r.GL_ES="true"),r.__VERSION__=e.version,r[e.platformName]="true",(0,f.xt)(r,t?.isNDCHalfZRange,t?.useReverseDepthBuffer,t?.useExactSrgbConversions),r}function D(e,t,i){let r;for(b.length=0;null!==(r=m.exec(e));)b.push(r);let s=String(e),n=[e],o=!1;for(const e of b){let r=e[1];if(-1!==r.indexOf("__decl__")&&(r=r.replace(g,""),t.supportsUniformBuffers&&(r=r.replace("Vertex","Ubo").replace("Fragment","Ubo")),r+="Declaration"),!t.includesShadersStore[r]){const e=t.shadersRepository+"ShadersInclude/"+r+".fx";return void w.loadFile(e,(e=>{t.includesShadersStore[r]=e,D(n.join(""),t,i)}))}{let i=t.includesShadersStore[r];if(e[2]){const t=e[3].split(",");for(let e=0;et+"{X}"))),i+=o.replace(x,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(v,((e,t)=>t+"{X}"))),i=i.replace(x,r)}const s=[];for(const t of n){const r=t.split(e[0]);for(let e=0;e=0||i.indexOf("#include <")>=0}}b.length=0,s=n.join(""),o?D(s.toString(),t,i):i(s)}const w={loadFile:(e,t,i,r,s,n)=>{throw(0,d.n)("FileTools")}}},16964:(e,t,i)=>{"use strict";i.d(t,{B:()=>s});const r=/(flat\s)?\s*varying\s*.*/;class s{constructor(){this.shaderLanguage=0}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return r.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const r=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){const t=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(r||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else if(-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e}}},96281:(e,t,i)=>{"use strict";i.d(t,{d:()=>r});class r{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))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){return this._MSAARenderBuffers?.[e]??null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}},42167:(e,t,i)=>{"use strict";i.d(t,{x:()=>r});class r{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))}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}setEngine(e){this.engine=e}_fillEffectInformation(e,t,i,r,s,n,o,a){const l=this.engine;if(l.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let h;for(this.engine.getUniforms(this,i).forEach(((e,t)=>{r[i[t]]=e})),this._uniforms=r,h=0;h{n[e]=t}));for(const e of l.getAttributes(this,o))a.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r||2!==r.length)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s||3!==s.length)return s=[t,i,r],this._valueCache[e]=s,!0;let n=!1;return s[0]!==t&&(s[0]=t,n=!0),s[1]!==i&&(s[1]=i,n=!0),s[2]!==r&&(s[2]=r,n=!0),n}_cacheFloat4(e,t,i,r,s){let n=this._valueCache[e];if(!n||4!==n.length)return n=[t,i,r,s],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]!==r&&(n[2]=r,o=!0),n[3]!==s&&(n[3]=s,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this.engine.setInt4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setUInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this.engine.setUInt4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setFloat3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this.engine.setFloat4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}},89237:(e,t,i)=>{"use strict";i.d(t,{e:()=>s});var r=i(78641);class s{constructor(){this._gpuTimeInFrameId=-1,this.counter=new r.A}_addDuration(e,t){e{"use strict";i.d(t,{W0:()=>o,iL:()=>n,kZ:()=>l,sg:()=>s,xt:()=>a});var r=i(75108);i(68191);const s={};function n(e,t,i=""){return i+(t?t+"\n":"")+e}function o(e,t,i,n,o,a,l){const h=l||s.loadFile;if(h)return h(e,t,i,n,o,a);throw(0,r.n)("FileTools")}function a(e,t,i,r){if(e)return t?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,i?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(r?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return t&&(e+="#define IS_NDC_HALF_ZRANGE"),i&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),r&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}function l(e,t,i=!1,r){switch(e){case 3:{const e=(ArrayBuffer,new Int8Array(t));return r&&e.set(new Int8Array(r)),e}case 0:{const e=(ArrayBuffer,new Uint8Array(t));return r&&e.set(new Uint8Array(r)),e}case 4:{const e=t instanceof ArrayBuffer?new Int16Array(t):new Int16Array(i?t/2:t);return r&&e.set(new Int16Array(r)),e}case 5:case 8:case 9:case 10:case 2:{const e=t instanceof ArrayBuffer?new Uint16Array(t):new Uint16Array(i?t/2:t);return r&&e.set(new Uint16Array(r)),e}case 6:{const e=t instanceof ArrayBuffer?new Int32Array(t):new Int32Array(i?t/4:t);return r&&e.set(new Int32Array(r)),e}case 7:case 11:case 12:case 13:case 14:case 15:{const e=t instanceof ArrayBuffer?new Uint32Array(t):new Uint32Array(i?t/4:t);return r&&e.set(new Uint32Array(r)),e}case 1:{const e=t instanceof ArrayBuffer?new Float32Array(t):new Float32Array(i?t/4:t);return r&&e.set(new Float32Array(r)),e}}const s=(ArrayBuffer,new Uint8Array(t));return r&&s.set(new Uint8Array(r)),s}},55935:(e,t,i)=>{"use strict";i.d(t,{$:()=>x,r:()=>v});var r=i(34268),s=i(60590),n=i(36217),o=i(82352),a=i(64736),l=i(14506),h=i(67715),c=i(69905),u=i(94895),d=i(75108),f=i(7107),p=i(68191),_=i(43279),m=i(2636),g=i(47221);function v(e,t){if((0,p.BA)()){const{requestAnimationFrame:i}=t||window;if("function"==typeof i)return i(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}class x{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,this._depthCullingState.depthFunc=e?518: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)return this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return this.isNDCHalfZRange&&(e+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}_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()}n.M.ResetCache()}_rebuildGraphicsResources(){this.wipeCaches(!0),this._rebuildEffects(),this._rebuildComputeEffects?.(),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){s.V.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}_restoreEngineAfterContextLost(e){setTimeout((async()=>{this._clearEmptyResources();const t=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,r=this._depthCullingState.depthMask,s=this._stencilState.stencilTest;await e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=r,this._stencilState.stencilTest=s,this._flagContextRestored()}),0)}get isDisposed(){return this._isDisposed}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return 0}set snapshotRenderingMode(e){}getClassName(){return"AbstractEngine"}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){const e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get activeRenderLoops(){return this._activeRenderLoops}stopRenderLoop(e){if(!e)return this._activeRenderLoops.length=0,void this._cancelFrame();const t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),0==this._activeRenderLoops.length&&this._cancelFrame())}_cancelFrame(){if(0!==this._frameHandler){const e=this._frameHandler;if(this._frameHandler=0,(0,p.BA)()){const{cancelAnimationFrame:t}=this.getHostWindow()||window;if("function"==typeof t)return t(e)}else if("function"==typeof cancelAnimationFrame)return cancelAnimationFrame(e);return clearTimeout(e)}}beginFrame(){this.onBeginFrameObservable.notifyObservers(this)}endFrame(){this._frameId++,this.onEndFrameObservable.notifyObservers(this)}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&0===this._frameHandler&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}_renderFrame(){for(let e=0;e-1?e.substring(P).toLowerCase():"");A.indexOf("?")>-1&&(A=A.split("?")[0]);const R=(0,g.gT)(A,m);n&&n.addPendingData(y),y.url=e,y.generateMipMaps=!t,y.samplingMode=o,y.invertY=i,y._useSRGBBuffer=this._getUseSRGBBuffer(!!b,t),this._doNotHandleContextLost||(y._buffer=u);let I=null;a&&!d&&(I=y.onLoadedObservable.add(a)),d||this._internalTexturesCache.push(y);const M=(i,d)=>{n&&n.removePendingData(y),e===E?(I&&y.onLoadedObservable.remove(I),r.q.UseFallbackTexture&&e!==r.q.FallbackTexture&&this._createTextureBase(r.q.FallbackTexture,t,y.invertY,n,o,null,l,h,c,u,y),i=(i||"Unknown error")+(r.q.UseFallbackTexture?" - Fallback texture was used":""),y.onErrorObservable.notifyObservers({message:i,exception:d}),l&&l(i,d)):(s.V.Warn(`Failed to load ${e}, falling back to ${E}`),this._createTextureBase(E,t,y.invertY,n,o,a,l,h,c,u,y,p,_,m,v,b))};if(R){const t=async e=>{(await R).loadData(e,y,((e,t,i,r,s,a)=>{a?M("TextureLoader failed to load data"):h(y,A,n,{width:e,height:t},y.invertY,!i,r,(()=>(s(),!1)),o)}),v)};u?u instanceof ArrayBuffer?t(new Uint8Array(u)):ArrayBuffer.isView(u)?t(u):l&&l("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,(e=>t(new Uint8Array(e))),void 0,n?n.offlineProvider:void 0,!0,((e,t)=>{M("Unable to load "+(e&&e.responseURL,t))}))}else{const i=e=>{T&&!this._doNotHandleContextLost&&(y._buffer=e),h(y,A,n,e,y.invertY,t,!1,c,o)};!S||C?u&&("string"==typeof u.decoding||u.close)?i(u):x._FileToolsLoadImage(e||"",i,M,n?n.offlineProvider:null,m,y.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof u||u instanceof ArrayBuffer||ArrayBuffer.isView(u)||u instanceof Blob?x._FileToolsLoadImage(u,i,M,n?n.offlineProvider:null,m,y.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):u&&i(u)}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:(0,p.Nf)()?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.35.2"}static get Version(){return"7.35.2"}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){this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new l.N,this._stencilStateComposer=new h.u,this._stencilState=new c.K,this._alphaState=new u.i,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 _.cP,this.onCanvasFocusObservable=new _.cP,this.onNewSceneAddedObservable=new _.cP,this.onResizeObservable=new _.cP,this.onCanvasPointerOutObservable=new _.cP,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 _.cP,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=()=>this._renderLoop(),this.onBeforeShaderCompilationObservable=new _.cP,this.onAfterShaderCompilationObservable=new _.cP,this.onBeginFrameObservable=new _.cP,this.onEndFrameObservable=new _.cP,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new _.cP,this.onContextRestoredObservable=new _.cP,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 _.cP,r.q.Instances.push(this),this.startTime=a.j.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,o.I.SetMatrixPrecision(!!t.useHighPrecisionMatrix),(0,p.XD)()&&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=t.audioEngineOptions?.audioContext??null,this._audioDestination=t.audioEngineOptions?.audioDestination??null,this.premultipliedAlpha=t.premultipliedAlpha??!0,this._doNotHandleContextLost=!!t.doNotHandleContextLost,this._isStencilEnable=!!t.stencil,this.useExactSrgbConversions=t.useExactSrgbConversions??!1;const s=(0,p.BA)()&&window.devicePixelRatio||1,n=t.limitDeviceRatio||s;i=i||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=i?1/Math.min(n,s):1,this._lastDevicePixelRatio=s,this._creationOptions=t}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const e=(0,p.BA)()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}if((0,p.BA)()&&(0,p.Nf)())if(this._renderingCanvas){const e=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||e.width||this._renderingCanvas.width||100,i=this._renderingCanvas.clientHeight||e.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)return!1;if(e|=0,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 e=0;e{const e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&(0,p.Nf)()&&"ontouchend"in document},this._checkForMobile(),(0,p.BA)()&&window.addEventListener("resize",this._checkForMobile))}createVideoElement(e){return document.createElement("video")}_reportDrawCall(e=1){this._drawCalls?.addCount(e,!1)}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return 1e3*this._timeStep}_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("undefined"==typeof document)return new OffscreenCanvas(e,t);const i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return x._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,i,r,s,n){throw(0,d.n)("FileTools")}_loadFile(e,t,i,r,s,n){const o=(0,m.W0)(e,t,i,r,s,n);return this._activeRequests.push(o),o.onCompleteObservable.add((()=>{const e=this._activeRequests.indexOf(o);-1!==e&&this._activeRequests.splice(e,1)})),o}static _FileToolsLoadFile(e,t,i,r,s,n){if(m.sg.loadFile)return m.sg.loadFile(e,t,i,r,s,n);throw(0,d.n)("FileTools")}dispose(){for(this.releaseEffects(),this._isDisposed=!0,this.stopRenderLoop(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._renderingCanvas=null,this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(;this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();this.releaseComputeEffects?.(),n.M.ResetCache();for(const e of this._activeRequests)e.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(),(0,p.BA)()&&window.removeEventListener("resize",this._checkForMobile);const e=r.q.Instances.indexOf(this);e>=0&&r.q.Instances.splice(e,1),r.q.Instances.length||(r.q.OnEnginesDisposedObservable.notifyObservers(this),r.q.OnEnginesDisposedObservable.clear()),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw(0,d.n)("LoadingScreen")}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{"use strict";i.d(t,{q:()=>s});var r=i(43279);class s{static get LastCreatedEngine(){return 0===this.Instances.length?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}}s.Instances=[],s.OnEnginesDisposedObservable=new r.cP,s._LastCreatedScene=null,s.UseFallbackTexture=!0,s.FallbackTexture=""},82352:(e,t,i)=>{"use strict";i.d(t,{I:()=>r});class r{static SetMatrixPrecision(e){if(r.MatrixTrackPrecisionChange=!1,e&&!r.MatrixUse64Bits&&r.MatrixTrackedMatrices)for(let e=0;e{"use strict";i.d(t,{l:()=>r});class r{static GetShadersRepository(e=0){return 0===e?r.ShadersRepository:r.ShadersRepositoryWGSL}static GetShadersStore(e=0){return 0===e?r.ShadersStore:r.ShadersStoreWGSL}static GetIncludesShadersStore(e=0){return 0===e?r.IncludesShadersStore:r.IncludesShadersStoreWGSL}}r.ShadersRepository="src/Shaders/",r.ShadersStore={},r.IncludesShadersStore={},r.ShadersRepositoryWGSL="src/ShadersWGSL/",r.ShadersStoreWGSL={},r.IncludesShadersStoreWGSL={}},66593:(e,t,i)=>{"use strict";i.d(t,{C5:()=>g,Cm:()=>l,EX:()=>c,GX:()=>u,N5:()=>a,YM:()=>p,bS:()=>v,kf:()=>h,tI:()=>d,tg:()=>f});var r=i(42167),s=i(2636);const n=new WeakMap,o={_webGLVersion:2,cachedPipelines:{}};function a(e){let t=n.get(e);if(!t){if(!e)return o;t={_webGLVersion:e.TEXTURE_BINDING_3D?2:1,_context:e,cachedPipelines:{}},n.set(e,t)}return t}function l(e){n.delete(e)}function h(e,t,i,r,s,n){const o=a(r);return n||(n=o._createShaderProgramInjection??d),n(e,m(t,"vertex",r,o._contextWasLost),m(i,"fragment",r,o._contextWasLost),r,s,o.validateShaderPrograms)}function c(e,t,i,r,s,n=null,o){const l=a(s);o||(o=l._createShaderProgramInjection??d);const h=l._webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"";return o(e,_(t,"vertex",r,h,s,l._contextWasLost),_(i,"fragment",r,h,s,l._contextWasLost),s,n,l.validateShaderPrograms)}function u(e,t){const i=new r.x,s=a(e);return s.parallelShaderCompile&&(i.isParallelCompiled=!0),i.context=s._context,i}function d(e,t,i,r,s=null,n){const o=r.createProgram();if(e.program=o,!o)throw new Error("Unable to create program");return r.attachShader(o,t),r.attachShader(o,i),r.linkProgram(o),e.context=r,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||f(e,r,n),o}function f(e,t,i){const r=e.context,s=e.vertexShader,n=e.fragmentShader,o=e.program;if(!r.getProgramParameter(o,r.LINK_STATUS)){if(!t.getShaderParameter(s,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(s);if(i)throw e.vertexCompilationError=i,new Error("VERTEX SHADER "+i)}if(!t.getShaderParameter(n,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(n);if(i)throw e.fragmentCompilationError=i,new Error("FRAGMENT SHADER "+i)}const i=r.getProgramInfoLog(o);if(i)throw e.programLinkError=i,new Error(i)}if(i&&(r.validateProgram(o),!r.getProgramParameter(o,r.VALIDATE_STATUS))){const t=r.getProgramInfoLog(o);if(t)throw e.programValidationError=t,new Error(t)}r.deleteShader(s),r.deleteShader(n),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}function p(e,t,i,r,s,n,o,l,u,d="",f,p,_){const m=a(e.context);p||(p=m.createRawShaderProgramInjection??h),_||(_=m.createShaderProgramInjection??c);const g=e;g.program=r?p(g,t,i,g.context,u):_(g,t,i,l,g.context,u),g.program.__SPECTOR_rebuildProgram=o,f()}function _(e,t,i,r,n,o){return m((0,s.iL)(e,i,r),t,n,o)}function m(e,t,i,r){const s=i.createShader("vertex"===t?i.VERTEX_SHADER:i.FRAGMENT_SHADER);if(!s){let e=i.NO_ERROR,s=i.NO_ERROR;for(;(s=i.getError())!==i.NO_ERROR;)e=s;throw new Error(`Something went wrong while creating a gl ${t} shader object. gl error=${e}, gl isContextLost=${i.isContextLost()}, _contextWasLost=${r}`)}return i.shaderSource(s,e),i.compileShader(s),s}function g(e,t){t.useProgram(e)}function v(e,t){const i=e;if(!i.isParallelCompiled)return void t(e);const r=i.onCompiled;i.onCompiled=()=>{r?.(),t(e)}}},722:(e,t,i)=>{"use strict";i.r(t),i.d(t,{ThinEngine:()=>v});var r=i(66593),s=i(61340),n=i(60590),o=i(68191);class a{constructor(){this.shaderLanguage=0}postProcessor(e,t,i,r,s){if(s.drawBuffersExtensionDisabled){const t=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(t,"")}return e}}var l=i(16964),h=i(7240),c=i(44512),u=i(55935),d=i(96281),f=i(7107),p=i(36217),_=i(2636),m=i(73010);class g{}class v extends u.${get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return p.M.ShadersRepository}static set ShadersRepository(e){p.M.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 o=null;if(e.getContext){if(o=e,this._renderingCanvas=o,void 0===i.preserveDrawingBuffer&&(i.preserveDrawingBuffer=!1),void 0===i.xrCompatible&&(i.xrCompatible=!1),navigator&&navigator.userAgent){this._setupMobileChecks();const e=navigator.userAgent;for(const t of v.ExceptionList){const r=t.key,s=t.targets;if(new RegExp(r).test(e)){if(t.capture&&t.captureConstraint){const i=t.capture,r=t.captureConstraint,s=new RegExp(i).exec(e);if(s&&s.length>0&&parseInt(s[s.length-1])>=r)continue}for(const e of s)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost||(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,n.V.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost((()=>this._initGLContext()))},o.addEventListener("webglcontextlost",this._onContextLost,!1),o.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=o.getContext("webgl2",i)||o.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!o)throw new Error("The provided canvas is null or undefined.");try{this._gl=o.getContext("webgl",i)||o.getContext("experimental-webgl",i)}catch(e){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 t=this._gl.getContextAttributes();t&&(i.stencil=t.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==i.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e1?new l.B:new a;const h=`Babylon.js v${v.Version}`;n.V.Log(h+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",h);const c=(0,r.N5)(this._gl);c.validateShaderPrograms=this.validateShaderPrograms,c.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||null!==this._gl.getExtension("OES_standard_derivatives"),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||null!==this._gl.getExtension("OES_element_index_uint"),fragmentDepthSupported:this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),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:1!==this._webGLVersion,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(null!=e&&(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"),36193!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=36193),34842!==this._gl.RGBA16F&&(this._gl.RGBA16F=34842),34836!==this._gl.RGBA32F&&(this._gl.RGBA32F=34836),35056!==this._gl.DEPTH24_STENCIL8&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(1===this._webGLVersion&&(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&&5131!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=null!==this._maxMSAASamplesOverride?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES),this._caps.maxDrawBuffers=this._gl.getParameter(this._gl.MAX_DRAW_BUFFERS);else{const e=this._gl.getExtension("WEBGL_draw_buffers");if(null!==e){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=e.drawBuffersWEBGL.bind(e),this._caps.maxDrawBuffers=this._gl.getParameter(e.MAX_DRAW_BUFFERS_WEBGL),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let t=0;t<16;t++)this._gl["COLOR_ATTACHMENT"+t+"_WEBGL"]=e["COLOR_ATTACHMENT"+t+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const e=this._gl.getExtension("WEBGL_depth_texture");null!=e&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=e.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const e=this._gl.getExtension("OES_vertex_array_object");null!=e&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=e.createVertexArrayOES.bind(e),this._gl.bindVertexArray=e.bindVertexArrayOES.bind(e),this._gl.deleteVertexArray=e.deleteVertexArrayOES.bind(e))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const e=this._gl.getExtension("ANGLE_instanced_arrays");null!=e?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=e.drawArraysInstancedANGLE.bind(e),this._gl.drawElementsInstanced=e.drawElementsInstancedANGLE.bind(e),this._gl.vertexAttribDivisor=e.vertexAttribDivisorANGLE.bind(e)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const e=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),t=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);e&&t&&(this._caps.highPrecisionShaderSupported=0!==e.precision&&0!==t.precision)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const e=this._gl.getExtension("EXT_blend_minmax");null!=e&&(this._caps.blendMinMax=!0,this._gl.MAX=e.MAX_EXT,this._gl.MIN=e.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 e=this._gl.getExtension("EXT_sRGB");null!=e&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:e.SRGB_EXT,SRGB8:e.SRGB_ALPHA_EXT,SRGB8_ALPHA8:e.SRGB_ALPHA_EXT})}if(this._creationOptions){const e=this._creationOptions.forceSRGBBufferSupportState;void 0!==e&&(this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&e)}}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let e=0;e=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){const r=e.program,s=this._gl.getUniformBlockIndex(r,t);this._gl.uniformBlockBinding(r,s,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,r,s,n,o){const a=this._currentBufferPointers[t];if(!a)return;let l=!1;a.active?(a.buffer!==e&&(a.buffer=e,l=!0),a.size!==i&&(a.size=i,l=!0),a.type!==r&&(a.type=r,l=!0),a.normalized!==s&&(a.normalized=s,l=!0),a.stride!==n&&(a.stride=n,l=!0),a.offset!==o&&(a.offset=o,l=!0)):(l=!0,a.active=!0,a.index=t,a.size=i,a.type=r,a.normalized=s,a.stride=n,a.offset=o,a.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),r===this._gl.UNSIGNED_INT||r===this._gl.INT?this._gl.vertexAttribIPointer(t,i,r,n,o):this._gl.vertexAttribPointer(t,i,r,s,n,o))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const r=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let s=0;s=0){const t=r[s];let o=null;if(i&&(o=i[t]),o||(o=e[t]),!o)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);const a=o.getBuffer();a&&(this._vertexAttribPointer(a,n,o.getSize(),o.type,o.normalized,o.byteStride,o.byteOffset),o.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,o.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(a))))}}}recordVertexArrayObject(e,t,i,r){const s=this._gl.createVertexArray();if(!s)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(s),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,r),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),s}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,r,s){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==s){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=s;const t=s.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let n=0;for(let o=0;o=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,i[o],this._gl.FLOAT,!1,r,n)),n+=4*i[o]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,r){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===i||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,r)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t1||this.isWebGPU)),(1!==a||this._caps.textureFloatLinearFiltering)&&(2!==a||this._caps.textureHalfFloatLinearFiltering)||(l=1),1!==a||this._caps.textureFloat||(a=0,n.V.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const d=this._gl,p=new f.h(this,r),_=e.width||e,m=e.height||e,g=e.depth||0,v=e.layers||0,x=this._getSamplingParameters(l,o),b=0!==v?d.TEXTURE_2D_ARRAY:0!==g?d.TEXTURE_3D:d.TEXTURE_2D,S=this._getRGBABufferInternalSizedFormat(a,h,c),T=this._getInternalFormat(h),C=this._getWebGLTextureType(a);return this._bindTextureDirectly(b,p),0!==v?(p.is2DArray=!0,d.texImage3D(b,0,S,_,m,v,0,T,C,null)):0!==g?(p.is3D=!0,d.texImage3D(b,0,S,_,m,g,0,T,C,null)):d.texImage2D(b,0,S,_,m,0,T,C,null),d.texParameteri(b,d.TEXTURE_MAG_FILTER,x.mag),d.texParameteri(b,d.TEXTURE_MIN_FILTER,x.min),d.texParameteri(b,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(b,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),o&&this._gl.generateMipmap(b),this._bindTextureDirectly(b,null),p._useSRGBBuffer=c,p.baseWidth=_,p.baseHeight=m,p.width=_,p.height=m,p.depth=v,p.isReady=!0,p.samples=u,p.generateMipMaps=o,p.samplingMode=l,p.type=a,p.format=h,p.label=s,this._internalTexturesCache.push(p),p}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)}createTexture(e,t,i,r,s=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,p,_){return this._createTextureBase(e,t,i,r,s,n,o,((...e)=>this._prepareWebGLTexture(...e,h)),((e,t,i,s,n,o)=>{const a=this._gl,l=i.width===e&&i.height===t;n._creationFlags=p??0;const h=this._getTexImageParametersForCreateTexture(n.format,n._useSRGBBuffer);if(l)return a.texImage2D(a.TEXTURE_2D,0,h.internalFormat,h.format,h.type,i),!1;const c=this._caps.maxTextureSize;if(i.width>c||i.height>c||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!(!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(i,0,0,i.width,i.height,0,0,e,t),a.texImage2D(a.TEXTURE_2D,0,h.internalFormat,h.format,h.type,this._workingCanvas),n.width=e,n.height=t,1));{const e=new f.h(this,2);this._bindTextureDirectly(a.TEXTURE_2D,e,!0),a.texImage2D(a.TEXTURE_2D,0,h.internalFormat,h.format,h.type,i),this._rescaleTexture(e,n,r,h.format,(()=>{this._releaseTexture(e),this._bindTextureDirectly(a.TEXTURE_2D,n,!0),o()}))}return!0}),a,l,h,c,u,d,_)}_getTexImageParametersForCreateTexture(e,t){let i,r;return 1===this.webGLVersion?(i=this._getInternalFormat(e,t),r=i):(i=this._getInternalFormat(e,!1),r=this._getRGBABufferInternalSizedFormat(0,e,t)),{internalFormat:r,format:i,type:this._gl.UNSIGNED_BYTE}}_rescaleTexture(e,t,i,r,s){}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){const r=this._getTextureTarget(t),s=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(r,this._gl.TEXTURE_MAG_FILTER,s.mag,t),this._setTextureParameterInteger(r,this._gl.TEXTURE_MIN_FILTER,s.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(r)),this._bindTextureDirectly(r,null),t.samplingMode=e}updateTextureDimensions(e,t,i,r=1){}updateTextureWrappingMode(e,t,i=null,r=null){const s=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==i&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==r&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(r),e),e._cachedWrapR=r),this._bindTextureDirectly(s,null)}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,n=0,o=0){const a=this._gl;let l=a.TEXTURE_2D;if(e.isCube&&(l=a.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=a.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(l,o,t,i,r,0,s)}_uploadDataToTextureDirectly(e,t,i=0,r=0,s,n=!1){const o=this._gl,a=this._getWebGLTextureType(e.type),l=this._getInternalFormat(e.format),h=void 0===s?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(s,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let c=o.TEXTURE_2D;e.isCube&&(c=o.TEXTURE_CUBE_MAP_POSITIVE_X+i);const u=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),f=n?e.width:Math.pow(2,Math.max(u-r,0)),p=n?e.height:Math.pow(2,Math.max(d-r,0));o.texImage2D(c,r,h,f,p,0,l,a,t)}updateTextureData(e,t,i,r,s,n,o=0,a=0,l=!1){const h=this._gl,c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=h.TEXTURE_2D,f=h.TEXTURE_2D;e.isCube&&(f=h.TEXTURE_CUBE_MAP_POSITIVE_X+o,d=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),h.texSubImage2D(f,a,i,r,s,n,u,c,t),l&&this._gl.generateMipmap(f),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){const s=this._gl,n=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,i,r),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,i,r,s){const n=this._gl;if(!n)return;const o=this._getSamplingParameters(s,!i);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,o.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,o.min),i||r||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,r,s,n,o,a,l,h){const u=this.getCaps().maxTextureSize,d=Math.min(u,this.needPOTTextures?(0,c.R)(r.width,u):r.width),f=Math.min(u,this.needPOTTextures?(0,c.R)(r.height,u):r.height),p=this._gl;p&&(e._hardwareTexture?(this._bindTextureDirectly(p.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===s||!!s),e.baseWidth=r.width,e.baseHeight=r.height,e.width=d,e.height=f,e.isReady=!0,e.type=-1!==e.type?e.type:0,e.format=-1!==e.format?e.format:h??(".jpg"!==t||e._useSRGBBuffer?5:4),a(d,f,r,t,e,(()=>{this._prepareWebGLTextureContinuation(e,i,n,o,l)}))||this._prepareWebGLTextureContinuation(e,i,n,o,l)):i&&i.removePendingData(e))}_getInternalFormatFromDepthTextureFormat(e,t,i){const r=this._gl;if(!t)return r.STENCIL_INDEX8;let s=i?r.DEPTH_STENCIL:r.DEPTH_COMPONENT;return this.webGLVersion>1?15===e?s=r.DEPTH_COMPONENT16:16===e?s=r.DEPTH_COMPONENT24:17===e||13===e?s=i?r.DEPTH24_STENCIL8:r.DEPTH_COMPONENT24:14===e?s=r.DEPTH_COMPONENT32F:18===e&&(s=i?r.DEPTH32F_STENCIL8:r.DEPTH_COMPONENT32F):s=r.DEPTH_COMPONENT16,s}_setupFramebufferDepthAttachments(e,t,i,r,s=1,n){const o=this._gl;n=n??(e?13:14);const a=this._getInternalFormatFromDepthTextureFormat(n,t,e);return e&&t?this._createRenderBuffer(i,r,s,o.DEPTH_STENCIL,a,o.DEPTH_STENCIL_ATTACHMENT):t?this._createRenderBuffer(i,r,s,a,a,o.DEPTH_ATTACHMENT):e?this._createRenderBuffer(i,r,s,a,a,o.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,r,s,n,o=!0){const a=this._gl.createRenderbuffer();return this._updateRenderBuffer(a,e,t,i,r,s,n,o)}_updateRenderBuffer(e,t,i,r,s,n,o,a=!0){const l=this._gl;return l.bindRenderbuffer(l.RENDERBUFFER,e),r>1&&l.renderbufferStorageMultisample?l.renderbufferStorageMultisample(l.RENDERBUFFER,r,n,t,i):l.renderbufferStorage(l.RENDERBUFFER,s,t,i),l.framebufferRenderbuffer(l.FRAMEBUFFER,o,l.RENDERBUFFER,e),a&&l.bindRenderbuffer(l.RENDERBUFFER,null),e}_releaseTexture(e){this._deleteTexture(e._hardwareTexture),this.unbindAllTextures();const t=this._internalTexturesCache.indexOf(e);-1!==t&&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?.release()}_setProgram(e){this._currentProgram!==e&&((0,r.C5)(e,this._gl),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let t=0;t-1;if(i&&o&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||r){if(this._activateCurrentTexture(),t&&t.isMultiview)throw n.V.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,t?._hardwareTexture?.underlyingResource??null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(s=!0,this._activateCurrentTexture());return o&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),s}_bindTexture(e,t,i){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;const r=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(r,t)}unbindAllTextures(){for(let e=0;e1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,r){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){const i=this._boundUniforms[e];i&&i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,r=!1,s=""){if(!t)return null!=this._boundTexturesCache[e]&&(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 i=t.getInternalTexture();i&&(i._associatedChannel=e),t.update()}else if(4===t.delayLoadState)return t.delayLoad(),!1;let n;n=r?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray: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 a=this._getTextureTarget(n);if(o&&this._bindTextureDirectly(a,n,i),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;const e=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=e,t.wrapV=e}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(a,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,r){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(let t=0;t=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){const e=Object.keys(this._compiledEffects);for(const t of e)this._compiledEffects[t].dispose();this._compiledEffects={}}dispose(){(0,o.BA)()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored))),super.dispose(),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.unbindAllAttributes(),this._boundUniforms={},this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._currentProgram=null,this._creationOptions.loseContextOnDispose&&this._gl.getExtension("WEBGL_lose_context")?.loseContext(),(0,r.Cm)(this._gl)}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){const t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0;const r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);const s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,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 e=t.RGBA,r=t.UNSIGNED_BYTE,s=new Uint8Array(4);t.readPixels(0,0,1,1,e,r,s),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(r),t.deleteFramebuffer(s),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(1===this._webGLVersion){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}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}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(1===this._webGLVersion){if(void 0!==t)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;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;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;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;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;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;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:default:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}readPixels(e,t,i,r,s=!0,n=!0){const o=s?4:3,a=s?this._gl.RGBA:this._gl.RGB,l=new Uint8Array(r*i*o);return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,r,a,this._gl.UNSIGNED_BYTE,l),Promise.resolve(l)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(null!==this._HasMajorPerformanceCaveat)return!this._HasMajorPerformanceCaveat;if(null===this._IsSupported)try{const e=u.$._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=null!=t&&!!window.WebGLRenderingContext}catch(e){this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(null===this._HasMajorPerformanceCaveat)try{const e=u.$._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch(e){this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}}v._TempClearColorUint32=new Uint32Array(4),v._TempClearColorInt32=new Int32Array(4),v.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"]}],v._ConcatenateShader=_.iL,v._IsSupported=null,v._HasMajorPerformanceCaveat=null},7474:(e,t,i)=>{"use strict";var r;i.d(t,{b:()=>r,s:()=>s}),function(e){e[e.PointerMove=0]="PointerMove",e[e.PointerDown=1]="PointerDown",e[e.PointerUp=2]="PointerUp"}(r||(r={}));class s{}s.DOM_DELTA_PIXEL=0,s.DOM_DELTA_LINE=1,s.DOM_DELTA_PAGE=2},80109:(e,t,i)=>{"use strict";i.d(t,{Bu:()=>n,TB:()=>r,W0:()=>s});class r{}r.KEYDOWN=1,r.KEYUP=2;class s{constructor(e,t){this.type=e,this.event=t}}class n extends s{get skipOnPointerObservable(){return this.skipOnKeyboardObservable}set skipOnPointerObservable(e){this.skipOnKeyboardObservable=e}constructor(e,t){super(e,t),this.type=e,this.event=t,this.skipOnKeyboardObservable=!1}}},1241:(e,t,i)=>{"use strict";i.d(t,{Vn:()=>n,Zp:()=>s,mx:()=>a,tT:()=>o});var r=i(94212);class s{}s.POINTERDOWN=1,s.POINTERUP=2,s.POINTERMOVE=4,s.POINTERWHEEL=8,s.POINTERPICK=16,s.POINTERTAP=32,s.POINTERDOUBLETAP=64;class n{constructor(e,t){this.type=e,this.event=t}}class o extends n{constructor(e,t,i,s){super(e,t),this.ray=null,this.originalPickingInfo=null,this.skipOnPointerObservable=!1,this.localPosition=new r.I9(i,s)}}class a extends n{get pickInfo(){return this._pickInfo||this._generatePickInfo(),this._pickInfo}constructor(e,t,i,r=null){super(e,t),this._pickInfo=i,this._inputManager=r}_generatePickInfo(){this._inputManager&&(this._pickInfo=this._inputManager._pickMove(this.event),this._inputManager._setRayOnPointerInfo(this._pickInfo,this.event),this._inputManager=null)}}},14952:(e,t,i)=>{"use strict";i.d(t,{c:()=>r});class r{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}r.FALLOFF_DEFAULT=0,r.FALLOFF_PHYSICAL=1,r.FALLOFF_GLTF=2,r.FALLOFF_STANDARD=3,r.LIGHTMAP_DEFAULT=0,r.LIGHTMAP_SPECULAR=1,r.LIGHTMAP_SHADOWSONLY=2,r.INTENSITYMODE_AUTOMATIC=0,r.INTENSITYMODE_LUMINOUSPOWER=1,r.INTENSITYMODE_LUMINOUSINTENSITY=2,r.INTENSITYMODE_ILLUMINANCE=3,r.INTENSITYMODE_LUMINANCE=4,r.LIGHTTYPEID_POINTLIGHT=0,r.LIGHTTYPEID_DIRECTIONALLIGHT=1,r.LIGHTTYPEID_SPOTLIGHT=2,r.LIGHTTYPEID_HEMISPHERICLIGHT=3},1649:(e,t,i)=>{"use strict";i.d(t,{FG:()=>a,Kq:()=>b,ZR:()=>p,tb:()=>x});var r=i(68907),s=i(85260);const n=32768,o=65535;function a(e,t){let i=0;for(let r=0;r>3]&1<<(7&r))&&(t[i++]=r);const r=i-1;for(;i>(i-=e)&(1<>(r-=8);if(e=new Uint8Array([e])[0],a.value+e>l)return null;const t=o[a.value-1];for(;e-- >0;)o[a.value++]=t}else{if(!(a.value>6}function p(e,t,i,n,o,a){const p=i.value,_=(0,r.PX)(t,i),m=(0,r.PX)(t,i);i.value+=4;const g=(0,r.PX)(t,i);if(i.value+=4,_<0||_>=s.U0||m<0||m>=s.U0)throw new Error("Wrong HUF_ENCSIZE");const v=new Array(s.U0),x=new Array(s.A_);if(function(e){for(let t=0;ti)return;let u=l(6,h,c,e,a);const d=u.l;if(h=u.c,c=u.lc,o[r]=d,d==s.Hh){if(a.value-t.value>i)throw new Error("Error in HufUnpackEncTable");u=l(8,h,c,e,a);let d=u.l+s.gn;if(h=u.c,c=u.lc,r+d>n+1)throw new Error("Error in HufUnpackEncTable");for(;d--;)o[r++]=0;r--}else if(d>=s.LU){let e=d-s.LU+2;if(r+e>n+1)throw new Error("Error in HufUnpackEncTable");for(;e--;)o[r++]=0;r--}}!function(e){for(let e=0;e<=58;++e)u[e]=0;for(let t=0;t0;--e){const i=t+u[e]>>1;u[e]=t,t=i}for(let t=0;t0&&(e[t]=i|u[i]++<<6)}}(o)}(e,i,n-(i.value-p),_,m,v),g>8*(n-(i.value-p)))throw new Error("Wrong hufUncompress");!function(e,t,i,r){for(;t<=i;t++){const i=f(e[t]),n=d(e[t]);if(i>>n)throw new Error("Invalid table entry");if(n>s.LK){const e=r[i>>n-s.LK];if(e.len)throw new Error("Invalid table entry");if(e.lit++,e.p){const t=e.p;e.p=new Array(e.lit);for(let i=0;i0;o--){const o=r[(i<=s.LK;){const a=t[p>>_-s.LK&s.lR];if(a.len){_-=a.len;const e=c(a.lit,o,p,_,i,r,l,u,m);e&&(p=e.c,_=e.lc)}else{if(!a.p)throw new Error("hufDecode issues");let t;for(t=0;t=s&&f(e[a.p[t]])==(p>>_-s&(1<>=v,_-=v;_>0;){const e=t[p<32767?t-65536:t}function g(e,t){const i=m(e),r=m(t),s=i+(1&r)+(r>>1);return{a:s,b:s-r}}function v(e,t){const i=_(e),r=_(t),s=i-(r>>1)&o;return{a:r+s-n&o,b:s}}function x(e,t,i,r,s,n,o){const a=o<16384,l=i>s?s:i;let h,c,u=1;for(;u<=l;)u<<=1;for(u>>=1,h=u,u>>=1;u>=1;){c=0;const o=c+n*(s-h),l=n*u,d=n*h,f=r*u,p=r*h;let _,m,x,b;for(;c<=o;c+=d){let s=c;const n=c+r*(i-h);for(;s<=n;s+=p){const i=s+f,r=s+l,n=r+f;if(a){let o=g(e[s+t],e[r+t]);_=o.a,x=o.b,o=g(e[i+t],e[n+t]),m=o.a,b=o.b,o=g(_,m),e[s+t]=o.a,e[i+t]=o.b,o=g(x,b),e[r+t]=o.a,e[n+t]=o.b}else{let o=v(e[s+t],e[r+t]);_=o.a,x=o.b,o=v(e[i+t],e[n+t]),m=o.a,b=o.b,o=v(_,m),e[s+t]=o.a,e[i+t]=o.b,o=v(x,b),e[r+t]=o.a,e[n+t]=o.b}}if(i&u){const i=s+l;let r;r=a?g(e[s+t],e[i+t]):v(e[s+t],e[i+t]),_=r.a,e[i+t]=r.b,e[s+t]=_}}if(s&u){let s=c;const n=c+r*(i-h);for(;s<=n;s+=p){const i=s+f;let r;r=a?g(e[s+t],e[i+t]):v(e[s+t],e[i+t]),_=r.a,e[i+t]=r.b,e[s+t]=_}}h=u,u>>=1}return c}function b(e,t,i){for(let r=0;r{"use strict";i.d(t,{S4:()=>a,VE:()=>h,_k:()=>c,r:()=>l,tg:()=>u});var r=i(1649),s=i(91727),n=i(68907),o=i(85260);function a(e){return new DataView(e.array.buffer,e.offset.value,e.size)}function l(e){const t=e.viewer.buffer.slice(e.offset.value,e.offset.value+e.size),i=new Uint8Array((0,s._)(t)),r=new Uint8Array(i.length);return(0,n.XE)(i),(0,n.KA)(i,r),new DataView(r.buffer)}function h(e){const t=e.array.slice(e.offset.value,e.offset.value+e.size),i=fflate.unzlibSync(t),r=new Uint8Array(i.length);return(0,n.XE)(i),(0,n.KA)(i,r),new DataView(r.buffer)}function c(e){const t=e.array.slice(e.offset.value,e.offset.value+e.size),i=fflate.unzlibSync(t),r=e.lines*e.channels*e.width,s=1==e.type?new Uint16Array(r):new Uint32Array(r);let n=0,o=0;const a=new Array(4);for(let t=0;t=o.cQ)throw new Error("Wrong PIZ_COMPRESSION BITMAP_SIZE");if(c<=u)for(let e=0;e{"use strict";function r(e){let t=e.byteLength;const i=new Array;let r=0;const s=new DataView(e);for(;t>0;){const e=s.getInt8(r++);if(e<0){const n=-e;t-=n+1;for(let e=0;er})},9668:(e,t,i)=>{"use strict";var r;i.d(t,{V:()=>r,u:()=>s}),function(e){e[e.Float=0]="Float",e[e.HalfFloat=1]="HalfFloat"}(r||(r={}));class s{}s.DefaultOutputType=r.HalfFloat,s.FFLATEUrl="https://unpkg.com/fflate@0.8.2"},68907:(e,t,i)=>{"use strict";i.d(t,{Ff:()=>_,Jn:()=>d,KA:()=>b,LD:()=>m,PX:()=>c,Sn:()=>g,T$:()=>l,XE:()=>x,_S:()=>u,cL:()=>h,fz:()=>f,he:()=>r,tB:()=>p,zX:()=>v});var r,s,n=i(56984),o=i(85260);!function(e){e[e.NO_COMPRESSION=0]="NO_COMPRESSION",e[e.RLE_COMPRESSION=1]="RLE_COMPRESSION",e[e.ZIPS_COMPRESSION=2]="ZIPS_COMPRESSION",e[e.ZIP_COMPRESSION=3]="ZIP_COMPRESSION",e[e.PIZ_COMPRESSION=4]="PIZ_COMPRESSION",e[e.PXR24_COMPRESSION=5]="PXR24_COMPRESSION"}(r||(r={})),function(e){e[e.INCREASING_Y=0]="INCREASING_Y",e[e.DECREASING_Y=1]="DECREASING_Y"}(s||(s={}));const a=function(){const e=new ArrayBuffer(4),t=new Float32Array(e),i=new Uint32Array(e),r=new Uint32Array(512),s=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-27?(r[e]=0,r[256|e]=32768,s[e]=24,s[256|e]=24):t<-14?(r[e]=1024>>-t-14,r[256|e]=1024>>-t-14|32768,s[e]=-t-1,s[256|e]=-t-1):t<=15?(r[e]=t+15<<10,r[256|e]=t+15<<10|32768,s[e]=13,s[256|e]=13):t<128?(r[e]=31744,r[256|e]=64512,s[e]=24,s[256|e]=24):(r[e]=31744,r[256|e]=64512,s[e]=13,s[256|e]=13)}const n=new Uint32Array(2048),o=new Uint32Array(64),a=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,i=0;for(;!(8388608&t);)t<<=1,i-=8388608;t&=-8388609,i+=947912704,n[e]=t|i}for(let e=1024;e<2048;++e)n[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)o[e]=e<<23;o[31]=1199570944,o[32]=2147483648;for(let e=33;e<63;++e)o[e]=2147483648+(e-32<<23);o[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(a[e]=1024);return{floatView:t,uint32View:i,baseTable:r,shiftTable:s,mantissaTable:n,exponentTable:o,offsetTable:a}}();function l(e,t){const i=new Uint8Array(e);let r=0;for(;0!=i[t.value+r];)r+=1;const s=(new TextDecoder).decode(i.slice(t.value,t.value+r));return t.value=t.value+r+1,s}function h(e,t){const i=e.getInt32(t.value,!0);return t.value+=o.b7,i}function c(e,t){const i=e.getUint32(t.value,!0);return t.value+=o.b7,i}function u(e,t){const i=e.getUint8(t.value);return t.value+=o.aN,i}function d(e,t){const i=e.getUint16(t.value,!0);return t.value+=o.JH,i}function f(e,t){const i=e[t.value];return t.value+=o.aN,i}function p(e,t){let i;return i="getBigInt64"in DataView.prototype?Number(e.getBigInt64(t.value,!0)):e.getUint32(t.value+4,!0)+Number(e.getUint32(t.value,!0)<<32),t.value+=o.Kl,i}function _(e,t){const i=e.getFloat32(t.value,!0);return t.value+=o.Y3,i}function m(e,t){return function(e){const t=(31744&e)>>10,i=1023&e;return(e>>15?-1:1)*(t?31===t?i?NaN:1/0:Math.pow(2,t-15)*(1+i/1024):i/1024*6103515625e-14)}(d(e,t))}function g(e,t){return function(e){if(Math.abs(e)>65504)throw new Error("Value out of range.Consider using float instead of half-float.");e=(0,n.Clamp)(e,-65504,65504),a.floatView[0]=e;const t=a.uint32View[0],i=t>>23&511;return a.baseTable[i]+((8388607&t)>>a.shiftTable[i])}(_(e,t))}function v(e,t,i,r){switch(i){case"string":case"stringvector":case"iccProfile":return function(e,t,i){const r=(new TextDecoder).decode(new Uint8Array(e).slice(t.value,t.value+i));return t.value=t.value+i,r}(e.buffer,t,r);case"chlist":return function(e,t,i){const r=t.value,s=[];for(;t.valuen||(t[s++]=e[i++],s>n));)t[s++]=e[r++]}},37642:(e,t,i)=>{"use strict";i.d(t,{d:()=>l,u:()=>h});var r=i(68907),s=i(12540),n=i(85260),o=i(9723),a=i(9668);async function l(e,t,i,l){const h={size:0,viewer:t,array:new Uint8Array(t.buffer),offset:i,width:e.dataWindow.xMax-e.dataWindow.xMin+1,height:e.dataWindow.yMax-e.dataWindow.yMin+1,channels:e.channels.length,channelLineOffsets:{},scanOrder:()=>0,bytesPerLine:0,outLineWidth:0,lines:0,scanlineBlockSize:0,inputSize:null,type:0,uncompress:null,getter:()=>0,format:5,outputChannels:0,decodeChannels:{},blockCount:null,byteArray:null,linearSpace:!1,textureType:0};switch(e.compression){case r.he.NO_COMPRESSION:h.lines=1,h.uncompress=s.S4;break;case r.he.RLE_COMPRESSION:h.lines=1,h.uncompress=s.r;break;case r.he.ZIPS_COMPRESSION:h.lines=1,h.uncompress=s.VE,await o.S0.LoadScriptAsync(a.u.FFLATEUrl);break;case r.he.ZIP_COMPRESSION:h.lines=16,h.uncompress=s.VE,await o.S0.LoadScriptAsync(a.u.FFLATEUrl);break;case r.he.PIZ_COMPRESSION:h.lines=32,h.uncompress=s.tg;break;case r.he.PXR24_COMPRESSION:h.lines=16,h.uncompress=s._k,await o.S0.LoadScriptAsync(a.u.FFLATEUrl);break;default:throw new Error(r.he[e.compression]+" is unsupported")}h.scanlineBlockSize=h.lines;const c={};for(const t of e.channels)switch(t.name){case"Y":case"R":case"G":case"B":case"A":c[t.name]=!0,h.type=t.pixelType}let u=!1;if(c.R&&c.G&&c.B)u=!c.A,h.outputChannels=4,h.decodeChannels={R:0,G:1,B:2,A:3};else{if(!c.Y)throw new Error("EXRLoader.parse: file contains unsupported data channels.");h.outputChannels=1,h.decodeChannels={Y:0}}if(1===h.type)switch(l){case a.V.Float:h.getter=r.LD,h.inputSize=n.JH;break;case a.V.HalfFloat:h.getter=r.Jn,h.inputSize=n.JH}else{if(2!==h.type)throw new Error("Unsupported pixelType "+h.type+" for "+e.compression);switch(l){case a.V.Float:h.getter=r.Ff,h.inputSize=n.Y3;break;case a.V.HalfFloat:h.getter=r.Sn,h.inputSize=n.Y3}}h.blockCount=h.height/h.scanlineBlockSize;for(let e=0;ee:h.scanOrder=e=>h.height-1-e,4==h.outputChannels?(h.format=5,h.linearSpace=!0):(h.format=6,h.linearSpace=!1),h}function h(e,t,i,n){const o={value:0};for(let a=0;ae.height?e.height-l:e.scanlineBlockSize;const h=e.size=e.height)continue;const n=i*e.bytesPerLine,l=(e.height-1-s)*e.outLineWidth;for(let i=0;i{"use strict";i.d(t,{V:()=>o});var r=i(60590),s=i(68907);const n=20000630;function o(e,t){if(e.getUint32(0,!0)!=n)throw new Error("Incorrect OpenEXR format");const i=e.getUint8(4),o=e.getUint8(5),a={singleTile:!!(2&o),longName:!!(4&o),deepFormat:!!(8&o),multiPart:!!(16&o)};t.value=8;const l={};let h=!0;for(;h;){const i=(0,s.T$)(e.buffer,t);if(i){const n=(0,s.T$)(e.buffer,t),o=(0,s.PX)(e,t),a=(0,s.zX)(e,t,n,o);void 0===a?r.V.Warn(`Unknown header attribute type ${n}'.`):l[i]=a}else h=!1}if(-5&o)throw new Error("Unsupported file format");return{version:i,spec:a,...l}}},85260:(e,t,i)=>{"use strict";i.d(t,{A_:()=>d,Ez:()=>l,Hh:()=>_,JH:()=>o,Kl:()=>a,LK:()=>c,LU:()=>p,U0:()=>u,Y3:()=>s,aN:()=>n,b7:()=>r,cQ:()=>h,gn:()=>m,lR:()=>f});const r=4,s=4,n=1,o=2,a=8,l=65536,h=l>>3,c=14,u=65537,d=1<{"use strict";i.r(t),i.d(t,{_BasisTextureLoader:()=>n});var r=i(68622),s=i(9723);class n{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,n,o){if(Array.isArray(e))return;const a=t.getEngine().getCaps(),l={supportedCompressionFormats:{etc1:!!a.etc1,s3tc:!!a.s3tc,pvrtc:!!a.pvrtc,etc2:!!a.etc2,astc:!!a.astc,bc7:!!a.bptc}};(0,r.yk)(e,l).then((e=>{const i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;(0,r.aB)(t,e),t.getEngine()._setCubeMapTextureParams(t,i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()})).catch((e=>{s.S0.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,o&&o(e)}))}loadData(e,t,i){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}};(0,r.yk)(e,o).then((e=>{const s=e.fileInfo.images[0].levels[0],n=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(s.width,s.height,n,-1!==e.format,(()=>{(0,r.aB)(t,e)}))})).catch((e=>{s.S0.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),s.S0.Warn(`Failed to transcode Basis file: ${e}`),i(0,0,!1,!1,(()=>{}),!0)}))}}},50153:(e,t,i)=>{"use strict";i.r(t),i.d(t,{_DDSTextureLoader:()=>n});var r=i(13798),s=i(26589);class n{constructor(){this.supportCascades=!0}loadCubeData(e,t,i,n){const o=t.getEngine();let a,l=!1,h=1e3;if(Array.isArray(e))for(let i=0;i1)&&t.generateMipMaps,o._unpackFlipY(a.isCompressed),s.DDSTools.UploadDDSLevels(o,t,r,a,l,6,-1,i),a.isFourCC||1!==a.mipmapCount?h=a.mipmapCount-1:o.generateMipMapsForCubemap(t)}else{const n=e;a=s.DDSTools.GetDDSInfo(n),t.width=a.width,t.height=a.height,i&&(a.sphericalPolynomial=new r.Q),l=(a.isRGB||a.isLuminance||a.mipmapCount>1)&&t.generateMipMaps,o._unpackFlipY(a.isCompressed),s.DDSTools.UploadDDSLevels(o,t,n,a,l,6),a.isFourCC||1!==a.mipmapCount?h=a.mipmapCount-1:o.generateMipMapsForCubemap(t,!1)}o._setCubeMapTextureParams(t,l,h),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n({isDDS:!0,width:t.width,info:a,data:e,texture:t})}loadData(e,t,i){const r=s.DDSTools.GetDDSInfo(e),n=(r.isRGB||r.isLuminance||r.mipmapCount>1)&&t.generateMipMaps&&Math.max(r.width,r.height)>>r.mipmapCount-1==1;i(r.width,r.height,n,r.isFourCC,(()=>{s.DDSTools.UploadDDSLevels(t.getEngine(),t,e,r,n,1)}))}}},33815:(e,t,i)=>{"use strict";i.r(t),i.d(t,{_ENVTextureLoader:()=>s});var r=i(48195);class s{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,s,n){if(Array.isArray(e))return;const o=(0,r.cU)(e);if(o){t.width=o.width,t.height=o.width;try{(0,r.ow)(t,o),(0,r.o5)(t,e,o).then((()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}),(e=>{n?.("Can not upload environment levels",e)}))}catch(e){n?.("Can not upload environment file",e)}}else n&&n("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}},3197:(e,t,i)=>{"use strict";i.r(t),i.d(t,{_ExrTextureLoader:()=>o});var r=i(44969),s=i(37642),n=i(9668);class o{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,r,s){throw".exr not supported in Cube."}async loadData(e,t,i){const o=new DataView(e.buffer),a={value:0},l=(0,r.V)(o,a),h=await(0,s.d)(l,o,a,n.u.DefaultOutputType);(0,s.u)(h,l,o,a),i(l.dataWindow.xMax-l.dataWindow.xMin+1,l.dataWindow.yMax-l.dataWindow.yMin+1,t.generateMipMaps,!1,(()=>{const e=t.getEngine();t.format=l.format,t.type=h.textureType,t.invertY=!1,t._gammaSpace=!l.linearSpace,h.byteArray&&e._uploadDataToTextureDirectly(t,h.byteArray,0,0,void 0,!0)}))}}},46628:(e,t,i)=>{"use strict";i.r(t),i.d(t,{_HDRTextureLoader:()=>s});var r=i(22377);class s{constructor(){this.supportCascades=!1}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=(0,r.NK)(s),o=(0,r.LT)(s,n),a=n.width*n.height,l=new Float32Array(4*a);for(let e=0;e{const e=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,e._uploadDataToTextureDirectly(t,l)}))}}},53797:(e,t,i)=>{"use strict";i.r(t),i.d(t,{_KTXTextureLoader:()=>o});var r=i(52710),s=i(27606),n=i(60590);class o{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,s){if(Array.isArray(e))return;t._invertVScale=!t.invertY;const n=t.getEngine(),o=new r.H(e,6),a=o.numberOfMipmapLevels>1&&t.generateMipMaps;n._unpackFlipY(!0),o.uploadLevels(t,t.generateMipMaps),t.width=o.pixelWidth,t.height=o.pixelHeight,n._setCubeMapTextureParams(t,a,o.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}loadData(e,t,i,o){if(r.H.IsValid(e)){t._invertVScale=!t.invertY;const s=new r.H(e,1),n=function(e){switch(e){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}(s.glInternalFormat);n?(t.format=n,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=s.glInternalFormat,i(s.pixelWidth,s.pixelHeight,t.generateMipMaps,!0,(()=>{s.uploadLevels(t,t.generateMipMaps)}),s.isInvalid)}else s.Z.IsValid(e)?new s.Z(t.getEngine())._uploadAsync(e,t,o).then((()=>{i(t.width,t.height,t.generateMipMaps,!0,(()=>{}),!1)}),(e=>{n.V.Warn(`Failed to load KTX2 texture data: ${e.message}`),i(0,0,!1,!1,(()=>{}),!0)})):(n.V.Error("texture missing KTX identifier"),i(0,0,!1,!1,(()=>{}),!0))}}},47221:(e,t,i)=>{"use strict";i.d(t,{gT:()=>a,hy:()=>o,kf:()=>n});var r=i(60590);const s=new Map;function n(e,t){o(e)&&r.V.Warn(`Extension with the name '${name}' already exists`),s.set(e,t)}function o(e){return s.delete(e)}function a(e,t){"image/ktx"!==t&&"image/ktx2"!==t||(e=".ktx"),s.has(e)||(e.endsWith(".dds")&&n(".dds",(()=>Promise.resolve().then(i.bind(i,50153)).then((e=>new e._DDSTextureLoader)))),e.endsWith(".basis")&&n(".basis",(()=>Promise.resolve().then(i.bind(i,60232)).then((e=>new e._BasisTextureLoader)))),e.endsWith(".env")&&n(".env",(()=>Promise.resolve().then(i.bind(i,33815)).then((e=>new e._ENVTextureLoader)))),e.endsWith(".hdr")&&n(".hdr",(()=>Promise.resolve().then(i.bind(i,46628)).then((e=>new e._HDRTextureLoader)))),(e.endsWith(".ktx")||e.endsWith(".ktx2"))&&(n(".ktx",(()=>Promise.resolve().then(i.bind(i,53797)).then((e=>new e._KTXTextureLoader)))),n(".ktx2",(()=>Promise.resolve().then(i.bind(i,53797)).then((e=>new e._KTXTextureLoader))))),e.endsWith(".tga")&&n(".tga",(()=>Promise.resolve().then(i.bind(i,60254)).then((e=>new e._TGATextureLoader)))),e.endsWith(".exr")&&n(".exr",(()=>Promise.resolve().then(i.bind(i,3197)).then((e=>new e._ExrTextureLoader)))));const r=s.get(e);return r?Promise.resolve(r(t)):null}},60254:(e,t,i)=>{"use strict";i.r(t),i.d(t,{_TGATextureLoader:()=>s});var r=i(96172);class s{constructor(){this.supportCascades=!1}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=(0,r.O_)(s);i(n.width,n.height,t.generateMipMaps,!1,(()=>{(0,r.FA)(t,s)}))}}},23199:(e,t,i)=>{"use strict";i.d(t,{t:()=>u});var r=i(15287),s=i(40220),n=i(43279),o=i(94212),a=i(34268),l=i(71627),h=(i(28909),i(29305)),c=i(89518);class u extends h.D{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.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}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){return this._texture?(null===this._texture._gammaSpace&&(this._texture._gammaSpace=this._gammaSpace),this._texture._gammaSpace&&!this._texture._useSRGBBuffer):this._gammaSpace}set gammaSpace(e){if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}this.getScene()?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this)))}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),this.getScene()?.markAllMaterialsAsDirty(1,(e=>e.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}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=(0,l.z)()),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=u.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 n.cP,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?u._IsScene(e)?this._scene=e:this._engine=e:this._scene=a.q.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 o.uq.IdentityReadOnly}getReflectionTextureMatrix(){return o.uq.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,r,s,n){const o=this._getEngine();if(!o)return null;const a=o._getUseSRGBBuffer(!!s,t),l=o.getLoadedTexturesCache();for(let o=0;o=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){const e=this._parentContainer.textures.indexOf(this);e>-1&&this._parentContainer.textures.splice(e,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=c.p.Serialize(this);return c.p.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0!==i)for(let r=0;r{0==--i&&t()})):0==--i&&t()}}else t()}static _IsScene(e){return"Scene"===e.getClassName()}}u.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,(0,r.Cg)([(0,s.lK)()],u.prototype,"uniqueId",void 0),(0,r.Cg)([(0,s.lK)()],u.prototype,"name",void 0),(0,r.Cg)([(0,s.lK)()],u.prototype,"displayName",void 0),(0,r.Cg)([(0,s.lK)()],u.prototype,"metadata",void 0),(0,r.Cg)([(0,s.lK)("hasAlpha")],u.prototype,"_hasAlpha",void 0),(0,r.Cg)([(0,s.lK)("getAlphaFromRGB")],u.prototype,"_getAlphaFromRGB",void 0),(0,r.Cg)([(0,s.lK)()],u.prototype,"level",void 0),(0,r.Cg)([(0,s.lK)("coordinatesIndex")],u.prototype,"_coordinatesIndex",void 0),(0,r.Cg)([(0,s.lK)()],u.prototype,"optimizeUVAllocation",void 0),(0,r.Cg)([(0,s.lK)("coordinatesMode")],u.prototype,"_coordinatesMode",void 0),(0,r.Cg)([(0,s.lK)()],u.prototype,"wrapU",null),(0,r.Cg)([(0,s.lK)()],u.prototype,"wrapV",null),(0,r.Cg)([(0,s.lK)()],u.prototype,"wrapR",void 0),(0,r.Cg)([(0,s.lK)()],u.prototype,"anisotropicFilteringLevel",void 0),(0,r.Cg)([(0,s.lK)()],u.prototype,"isCube",null),(0,r.Cg)([(0,s.lK)()],u.prototype,"is3D",null),(0,r.Cg)([(0,s.lK)()],u.prototype,"is2DArray",null),(0,r.Cg)([(0,s.lK)()],u.prototype,"gammaSpace",null),(0,r.Cg)([(0,s.lK)()],u.prototype,"invertZ",void 0),(0,r.Cg)([(0,s.lK)()],u.prototype,"lodLevelInAlpha",void 0),(0,r.Cg)([(0,s.lK)()],u.prototype,"lodGenerationOffset",null),(0,r.Cg)([(0,s.lK)()],u.prototype,"lodGenerationScale",null),(0,r.Cg)([(0,s.lK)()],u.prototype,"linearSpecularLOD",null),(0,r.Cg)([(0,s.uM)()],u.prototype,"irradianceTexture",null),(0,r.Cg)([(0,s.lK)()],u.prototype,"isRenderTarget",void 0)},54699:(e,t,i)=>{"use strict";var r=i(82266),s=i(23199);s.t.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(s.t.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=r.d.ConvertCubeMapTextureToSphericalPolynomial(this),null===this._texture._sphericalPolynomialPromise?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then((e=>{this._texture._sphericalPolynomial=e,this._texture._sphericalPolynomialComputed=!0}))),null}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0})},7107:(e,t,i)=>{"use strict";i.d(t,{G:()=>r,h:()=>o});var r,s=i(43279),n=i(18310);!function(e){e[e.Unknown=0]="Unknown",e[e.Url=1]="Url",e[e.Temp=2]="Temp",e[e.Raw=3]="Raw",e[e.Dynamic=4]="Dynamic",e[e.RenderTarget=5]="RenderTarget",e[e.MultiRenderTarget=6]="MultiRenderTarget",e[e.Cube=7]="Cube",e[e.CubeRaw=8]="CubeRaw",e[e.CubePrefiltered=9]="CubePrefiltered",e[e.Raw3D=10]="Raw3D",e[e.Raw2DArray=11]="Raw2DArray",e[e.DepthStencil=12]="DepthStencil",e[e.CubeRawRGBD=13]="CubeRawRGBD",e[e.Depth=14]="Depth"}(r||(r={}));class o extends n.u{get useMipMaps(){return this.generateMipMaps}set useMipMaps(e){this.generateMipMaps=e}get uniqueId(){return this._uniqueId}_setUniqueId(e){this._uniqueId=e}getEngine(){return this._engine}get source(){return this._source}constructor(e,t,i=!1){super(),this.isReady=!1,this.isCube=!1,this.is3D=!1,this.is2DArray=!1,this.isMultiview=!1,this.url="",this.generateMipMaps=!1,this.samples=0,this.type=-1,this.format=-1,this.onLoadedObservable=new s.cP,this.onErrorObservable=new s.cP,this.onRebuildCallback=null,this.width=0,this.height=0,this.depth=0,this.baseWidth=0,this.baseHeight=0,this.baseDepth=0,this.invertY=!1,this._invertVScale=!1,this._associatedChannel=-1,this._source=0,this._buffer=null,this._bufferView=null,this._bufferViewArray=null,this._bufferViewArrayArray=null,this._size=0,this._extension="",this._files=null,this._workingCanvas=null,this._workingContext=null,this._cachedCoordinatesMode=null,this._isDisabled=!1,this._compression=null,this._sphericalPolynomial=null,this._sphericalPolynomialPromise=null,this._sphericalPolynomialComputed=!1,this._lodGenerationScale=0,this._lodGenerationOffset=0,this._useSRGBBuffer=!1,this._creationFlags=0,this._lodTextureHigh=null,this._lodTextureMid=null,this._lodTextureLow=null,this._isRGBD=!1,this._linearSpecularLOD=!1,this._irradianceTexture=null,this._hardwareTexture=null,this._maxLodLevel=null,this._references=1,this._gammaSpace=null,this._premulAlpha=!1,this._dynamicTextureSource=null,this._engine=e,this._source=t,this._uniqueId=o._Counter++,i||(this._hardwareTexture=e._createHardwareTexture())}incrementReferences(){this._references++}updateSize(e,t,i=1){this._engine.updateTextureDimensions(this,e,t,i),this.width=e,this.height=t,this.depth=i,this.baseWidth=e,this.baseHeight=t,this.baseDepth=i,this._size=e*t*i}_rebuild(){if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){const e=this.onRebuildCallback(this),t=t=>{t._swapAndDie(this,!1),this.isReady=e.isReady};return void(e.isAsync?e.proxy.then(t):t(e.proxy))}let e;switch(this.source){case 2:case 12:case 14:break;case 1:return void(e=this._engine.createTexture(this._originalUrl??this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,(e=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer));case 3:e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer),e._swapAndDie(this,!1),this.isReady=!0;break;case 10:e=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case 11:e=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case 4:e=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),e._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case 7:return void(e=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,(()=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer,ArrayBuffer.isView(this._buffer)?this._buffer:null));case 8:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this._originalFormat??this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case 13:return;case 9:return e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,(e=>{e&&e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension),void(e._sphericalPolynomial=this._sphericalPolynomial)}}_swapAndDie(e,t=!0){this._hardwareTexture?.setUsage(e._source,this.generateMipMaps,this.is2DArray,this.isCube,this.is3D,this.width,this.height,this.depth),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);const i=this._engine.getLoadedTexturesCache();let r=i.indexOf(this);-1!==r&&i.splice(r,1),r=i.indexOf(e),-1===r&&i.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}o._Counter=0},63199:(e,t,i)=>{"use strict";var r,s,n;i.d(t,{GQ:()=>n,Ok:()=>r,Xl:()=>s}),function(e){e[e.ETC1S=0]="ETC1S",e[e.UASTC4x4=1]="UASTC4x4"}(r||(r={})),function(e){e[e.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",e[e.BC7_RGBA=1]="BC7_RGBA",e[e.BC3_RGBA=2]="BC3_RGBA",e[e.BC1_RGB=3]="BC1_RGB",e[e.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",e[e.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",e[e.ETC2_RGBA=6]="ETC2_RGBA",e[e.ETC1_RGB=7]="ETC1_RGB",e[e.RGBA32=8]="RGBA32",e[e.R8=9]="R8",e[e.RG8=10]="RG8"}(s||(s={})),function(e){e[e.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",e[e.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",e[e.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",e[e.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",e[e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",e[e.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",e[e.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",e[e.RGBA8Format=32856]="RGBA8Format",e[e.R8Format=33321]="R8Format",e[e.RG8Format=33323]="RG8Format"}(n||(n={}))},58059:(e,t,i)=>{"use strict";i.d(t,{$:()=>u});var r=i(43279),s=i(94212),n=i(4756),o=i(2449),a=i(44512),l=i(36217),h=i(60590),c=i(25266);l.M.prototype.setDepthStencilTexture=function(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)};class u extends n.g{get renderListPredicate(){return this._objectRenderer.renderListPredicate}set renderListPredicate(e){this._objectRenderer.renderListPredicate=e}get renderList(){return this._objectRenderer.renderList}set renderList(e){this._objectRenderer.renderList=e}get particleSystemList(){return this._objectRenderer.particleSystemList}set particleSystemList(e){this._objectRenderer.particleSystemList=e}get getCustomRenderList(){return this._objectRenderer.getCustomRenderList}set getCustomRenderList(e){this._objectRenderer.getCustomRenderList=e}get renderParticles(){return this._objectRenderer.renderParticles}set renderParticles(e){this._objectRenderer.renderParticles=e}get renderSprites(){return this._objectRenderer.renderSprites}set renderSprites(e){this._objectRenderer.renderSprites=e}get forceLayerMaskCheck(){return this._objectRenderer.forceLayerMaskCheck}set forceLayerMaskCheck(e){this._objectRenderer.forceLayerMaskCheck=e}get activeCamera(){return this._objectRenderer.activeCamera}set activeCamera(e){this._objectRenderer.activeCamera=e}get customIsReadyFunction(){return this._objectRenderer.customIsReadyFunction}set customIsReadyFunction(e){this._objectRenderer.customIsReadyFunction=e}get customRenderFunction(){return this._objectRenderer.customRenderFunction}set customRenderFunction(e){this._objectRenderer.customRenderFunction=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)}get onBeforeRenderObservable(){return this._objectRenderer.onBeforeRenderObservable}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}get onAfterRenderObservable(){return this._objectRenderer.onAfterRenderObservable}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 _waitingRenderList(){return this._objectRenderer._waitingRenderList}set _waitingRenderList(e){this._objectRenderer._waitingRenderList=e}get renderPassId(){return this._objectRenderer.renderPassId}get renderPassIds(){return this._objectRenderer.renderPassIds}get currentRefreshId(){return this._objectRenderer.currentRefreshId}setMaterialForRendering(e,t){this._objectRenderer.setMaterialForRendering(e,t)}get isMulti(){return this._renderTarget?.isMulti??!1}get renderTargetOptions(){return this._renderTargetOptions}get renderTarget(){return this._renderTarget}_onRatioRescale(){this._sizeRatio&&this.resize(this._initialSizeParameter)}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}get depthStencilTexture(){return this._renderTarget?._depthStencilTexture??null}constructor(e,t,i,o=!1,a=!0,l=0,u=!1,d=n.g.TRILINEAR_SAMPLINGMODE,f=!0,p=!1,_=!1,m=5,g=!1,v,x,b=!1,S=!1){let T,C=!0;if("object"==typeof o){const e=o;o=!!e.generateMipMaps,a=e.doNotChangeAspectRatio??!0,l=e.type??0,u=!!e.isCube,d=e.samplingMode??n.g.TRILINEAR_SAMPLINGMODE,f=e.generateDepthBuffer??!0,p=!!e.generateStencilBuffer,_=!!e.isMulti,m=e.format??5,g=!!e.delayAllocation,v=e.samples,x=e.creationFlags,b=!!e.noColorAttachment,S=!!e.useSRGBBuffer,T=e.colorAttachment,C=e.gammaSpace??C}if(super(null,i,!o,void 0,d,void 0,void 0,void 0,void 0,m),this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new r.cP,this.onAfterUnbindObservable=new r.cP,this.onClearObservable=new r.cP,this.onResizeObservable=new r.cP,this._cleared=!1,this.skipInitialClear=!1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=s.Pq.Zero(),this._dumpToolsLoading=!1,!(i=this.getScene()))return;const y=this.getScene().getEngine();this._gammaSpace=C,this._coordinatesMode=n.g.PROJECTION_MODE,this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._processSizeParameter(t),this._objectRenderer=new c.P(e,i,{numPasses:u?6:this.getRenderLayers()||1,doNotChangeAspectRatio:a}),this._objectRenderer.onBeforeRenderingManagerRenderObservable.add((()=>{for(const e of this._scene._beforeRenderTargetClearStage)e.action(this,this._currentFaceIndex,this._currentLayer);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(y):this.skipInitialClear||y.clear(this.clearColor||this._scene.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||this._scene.updateTransformMatrix(!0);for(const e of this._scene._beforeRenderTargetDrawStage)e.action(this,this._currentFaceIndex,this._currentLayer)})),this._objectRenderer.onAfterRenderingManagerRenderObservable.add((()=>{for(const e of this._scene._afterRenderTargetDrawStage)e.action(this,this._currentFaceIndex,this._currentLayer);const e=this._texture?.generateMipMaps??!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,this._currentFaceIndex,this._postProcesses,this.ignoreCameraViewport):this._currentUseCameraPostProcess&&this._scene.postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,this._currentFaceIndex);for(const e of this._scene._afterRenderTargetPostProcessStage)e.action(this,this._currentFaceIndex,this._currentLayer);this._texture&&(this._texture.generateMipMaps=e),this._doNotChangeAspectRatio||this._scene.updateTransformMatrix(!0),this._currentDumpForDebug&&(this._dumpTools?this._dumpTools.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),y):h.V.Error("dumpTools module is still being loaded. To speed up the process import dump tools directly in your project"))})),this._objectRenderer.onFastPathRenderObservable.add((()=>{this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(y):this.skipInitialClear||y.clear(this.clearColor||this._scene.clearColor,!0,!0,!0)})),this._resizeObserver=y.onResizeObservable.add((()=>{})),this._generateMipMaps=!!o,this._doNotChangeAspectRatio=a,_||(this._renderTargetOptions={generateMipMaps:o,type:l,format:this._format??void 0,samplingMode:this.samplingMode,generateDepthBuffer:f,generateStencilBuffer:p,samples:v,creationFlags:x,noColorAttachment:b,useSRGBBuffer:S,colorAttachment:T,label:this.name},this.samplingMode===n.g.NEAREST_SAMPLINGMODE&&(this.wrapU=n.g.CLAMP_ADDRESSMODE,this.wrapV=n.g.CLAMP_ADDRESSMODE),g||(u?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=n.g.INVCUBIC_MODE,this._textureMatrix=s.uq.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==v&&(this.samples=v)))}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,n){this._renderTarget?.createDepthStencilTexture(e,t,i,r,s,n)}_processSizeParameter(e){if(e.ratio){this._sizeRatio=e.ratio;const t=this._getEngine();this._size={width:this._bestReflectionRenderTargetDimension(t.getRenderWidth(),this._sizeRatio),height:this._bestReflectionRenderTargetDimension(t.getRenderHeight(),this._sizeRatio)}}else this._size=e}get samples(){return this._renderTarget?.samples??this._samples}set samples(e){this._renderTarget&&(this._samples=this._renderTarget.setSamples(e))}addPostProcess(e){if(!this._postProcessManager){const e=this.getScene();if(!e)return;this._postProcessManager=new o.X(e),this._postProcesses=new Array}this._postProcesses.push(e),this._postProcesses[0].autoClear=!1}clearPostProcesses(e=!1){if(this._postProcesses){if(e)for(const e of this._postProcesses)e.dispose();this._postProcesses=[]}}removePostProcess(e){if(!this._postProcesses)return;const t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses.splice(t,1),this._postProcesses.length>0&&(this._postProcesses[0].autoClear=!1))}resetRefreshCounter(){this._objectRenderer.resetRefreshCounter()}get refreshRate(){return this._objectRenderer.refreshRate}set refreshRate(e){this._objectRenderer.refreshRate=e}_shouldRender(){return this._objectRenderer.shouldRender()}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;return this._size.depth||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){const t=this.isCube;this._renderTarget?.dispose(),this._renderTarget=null;const i=this.getScene();i&&(this._processSizeParameter(e),this._renderTarget=t?i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==this._renderTargetOptions.samples&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){this._dumpToolsLoading||(this._dumpToolsLoading=!0,Promise.resolve().then(i.bind(i,465)).then((e=>this._dumpTools=e))),this._objectRenderer.prepareRenderList(),this.onBeforeBindObservable.notifyObservers(this),this._objectRenderer.initRender(this.getRenderWidth(),this.getRenderHeight());const e=this._objectRenderer._checkReadiness();return this.onAfterUnbindObservable.notifyObservers(this),this._objectRenderer.finishRender(),e}_render(e=!1,t=!1){const i=this.getScene();if(i){if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._objectRenderer.prepareRenderList(),this.onBeforeBindObservable.notifyObservers(this),this._objectRenderer.initRender(this.getRenderWidth(),this.getRenderHeight()),!this.is2DArray&&!this.is3D||this.isMulti)if(this.isCube&&!this.isMulti)for(let r=0;r<6;r++)this._renderToTarget(r,e,t),i.incrementRenderId(),i.resetCachedMaterial();else this._renderToTarget(0,e,t);else for(let r=0;r{this.onAfterRenderObservable.notifyObservers(t)}))}_prepareFrame(e,t,i,r){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):r&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,r=0){const s=this.getScene();if(!s)return;const n=s.getEngine();this._currentFaceIndex=e,this._currentLayer=r,this._currentUseCameraPostProcess=t,this._currentDumpForDebug=i,this._prepareFrame(s,e,r,t),n._debugPushGroup?.(`render to face #${e} layer #${r}`,2),this._objectRenderer.render(e+r,!0),n._debugPopGroup?.(2),this._unbindFrameBuffer(n,e),this._texture&&this.isCube&&5===e&&n.generateMipMapsForCubemap(this._texture,!0)}setRenderingOrder(e,t=null,i=null,r=null){this._objectRenderer.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t){this._objectRenderer.setRenderingAutoClearDepthStencil(e,t)}clone(){const e=this.getSize(),t=new u(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 i of e.cameras)t=i.customRenderTargets.indexOf(this),t>=0&&i.customRenderTargets.splice(t,1);this._renderTarget?.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this._objectRenderer._rebuild(),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._objectRenderer.freeRenderingGroups()}getViewCount(){return 1}}u.REFRESHRATE_RENDER_ONCE=c.P.REFRESHRATE_RENDER_ONCE,u.REFRESHRATE_RENDER_ONEVERYFRAME=c.P.REFRESHRATE_RENDER_ONEVERYFRAME,u.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=c.P.REFRESHRATE_RENDER_ONEVERYTWOFRAMES,n.g._CreateRenderTargetTexture=(e,t,i,r,s)=>new u(e,t,i,r)},4756:(e,t,i)=>{"use strict";i.d(t,{g:()=>g});var r=i(15287),s=i(40220),n=i(43279),o=i(94212),a=i(23199),l=i(56225),h=i(75108),c=i(72649),u=i(14798),d=i(30573),f=i(5800),p=i(61572),_=i(75174),m=i(89518);class g extends a.t{static _CreateVideoTexture(e,t,i,r=!1,s=!1,n=g.TRILINEAR_SAMPLINGMODE,o={},a,l=5){throw(0,h.n)("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,r,s=g.TRILINEAR_SAMPLINGMODE,o=null,a=null,l=null,h=!1,u,d,f,p,m){let v;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 n.cP,this._isBlocking=!0,this.name=e||"",this.url=e;let x=!1,b=null,S=!0;"object"==typeof i&&null!==i?(v=i.noMipmap??!1,r=i.invertY??!_.rX,s=i.samplingMode??g.TRILINEAR_SAMPLINGMODE,o=i.onLoad??null,a=i.onError??null,l=i.buffer??null,h=i.deleteBuffer??!1,u=i.format,d=i.mimeType,f=i.loaderOptions,p=i.creationFlags,x=i.useSRGBBuffer??!1,b=i.internalTexture??null,S=i.gammaSpace??S,m=i.forcedExtension??m):v=!!i,this._gammaSpace=S,this._noMipmap=v,this._invertY=void 0===r?!_.rX:r,this._initialSamplingMode=s,this._buffer=l,this._deleteBuffer=h,this._mimeType=d,this._loaderOptions=f,this._creationFlags=p,this._useSRGBBuffer=x,this._forcedExtension=m,u&&(this._format=u);const T=this.getScene(),C=this._getEngine();if(!C)return;C.onBeforeTextureInitObservable.notifyObservers(this);const y=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),null!==this._texture._cachedWrapU&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),null!==this._texture._cachedWrapV&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),null!==this._texture._cachedWrapR&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),o&&o(),!this.isBlocking&&T&&T.resetCachedMaterial()},E=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},a&&a(e,t),g.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!b)return this._delayedOnLoad=y,void(this._delayedOnError=E);if(this._texture=b??this._getFromCache(this.url,v,s,this._invertY,x,this.isCube),this._texture)if(this._texture.isReady)c._.SetImmediate((()=>y()));else{const e=this._texture.onLoadedObservable.add(y);this._texture.onErrorObservable.add((t=>{E(t.message,t.exception),this._texture?.onLoadedObservable.remove(e)}))}else if(T&&T.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=y,this._delayedOnError=E;else{try{this._texture=C.createTexture(this.url,v,this._invertY,T,s,y,E,this._buffer,void 0,this._format,this._forcedExtension,d,f,p,x)}catch(e){throw E("error loading",e),e}h&&(this._buffer=null)}}updateURL(e,t=null,i,r){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,(e=>e.hasTexture(this)))),this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=r,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(4!==this.delayLoadState)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?c._.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null)}_prepareRowForTextureGeneration(e,t,i,r){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,o.Pq.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,r),r.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,r.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,r.z+=this.wRotationCenter}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,this._cachedTextureMatrix&&this._rowGenerationMatrix||(this._cachedTextureMatrix=o.uq.Zero(),this._rowGenerationMatrix=new o.uq,this._t0=o.Pq.Zero(),this._t1=o.Pq.Zero(),this._t2=o.Pq.Zero()),o.uq.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(o.uq.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,o.AA.Matrix[0]),o.uq.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,o.AA.Matrix[1]),o.uq.ScalingToRef(this._cachedUScale,this._cachedVScale,0,o.AA.Matrix[2]),o.uq.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,o.AA.Matrix[3]),o.AA.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(o.AA.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(o.AA.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(o.AA.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),o.uq.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,(e=>e.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!==g.PROJECTION_MODE)return this._cachedReflectionTextureMatrix;if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=o.uq.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=o.uq.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 g.PLANAR_MODE:o.uq.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 g.PROJECTION_MODE:{o.uq.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:o.uq.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,(e=>e.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 m.p.Clone((()=>new g(this._texture?this._texture.url:null,this.getScene(),e)),this)}serialize(){const e=this.name;g.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(g._SerializeInternalTextureUniqueId);return t?((g.SerializeBuffers||g.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substring(0,5)?(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,"+(0,f.EL)(this._buffer):(g.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?(0,p.lP)(this):(0,p.nh)(this))),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,g._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=this._texture?.uniqueId),t.internalTextureLabel=this._texture?.label,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 r=u.n.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&r.updateSamplingMode&&r._samplingMode&&r._samplingMode!==e.samplingMode&&r.updateSamplingMode(e.samplingMode),r}if(e.isCube&&!e.isRenderTarget)return g._CubeTextureParser(e,t,i);const r=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!r)return null;let s;if(r){const i=t.getEngine().getLoadedTexturesCache();for(const t of i)if(t.uniqueId===e.internalTextureUniqueId){s=t;break}}const n=t=>{if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){const i=e.samplingMode;t&&t.samplingMode!==i&&t.updateSamplingMode(i)}if(t&&e.animations)for(let i=0;i{let r=!0;if(e.noMipmap&&(r=!1),e.mirrorPlane){const i=g._CreateMirror(e.name,e.renderTargetSize,t,r);return i._waitingRenderList=e.renderList,i.mirrorPlane=d.Z.FromArray(e.mirrorPlane),n(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i{n(o)}),e._creationFlags??0,e._useSRGBBuffer??!1),o.name=e.name;else{let a;a=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||g.UseSerializedUrlIfAny)&&(a=e.url);const l={noMipmap:!r,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{n(o)},internalTexture:s};o=new g(a,t,l)}return o}}),e,t)}static CreateFromBase64String(e,t,i,r,s,n=g.TRILINEAR_SAMPLINGMODE,o=null,a=null,l=5,h,c){return new g("data:"+t,i,r,s,n,o,a,e,!1,l,void 0,void 0,h,c)}static LoadFromDataString(e,t,i,r=!1,s,n=!0,o=g.TRILINEAR_SAMPLINGMODE,a=null,l=null,h=5,c,u){return"data:"!==e.substring(0,5)&&(e="data:"+e),new g(e,i,s,n,o,a,l,t,r,h,void 0,void 0,c,u)}}g.SerializeBuffers=!0,g.ForceSerializeBuffers=!1,g.OnTextureLoadErrorObservable=new n.cP,g._SerializeInternalTextureUniqueId=!1,g._CubeTextureParser=(e,t,i)=>{throw(0,h.n)("CubeTexture")},g._CreateMirror=(e,t,i,r)=>{throw(0,h.n)("MirrorTexture")},g._CreateRenderTargetTexture=(e,t,i,r,s)=>{throw(0,h.n)("RenderTargetTexture")},g.NEAREST_SAMPLINGMODE=1,g.NEAREST_NEAREST_MIPLINEAR=8,g.BILINEAR_SAMPLINGMODE=2,g.LINEAR_LINEAR_MIPNEAREST=11,g.TRILINEAR_SAMPLINGMODE=3,g.LINEAR_LINEAR_MIPLINEAR=3,g.NEAREST_NEAREST_MIPNEAREST=4,g.NEAREST_LINEAR_MIPNEAREST=5,g.NEAREST_LINEAR_MIPLINEAR=6,g.NEAREST_LINEAR=7,g.NEAREST_NEAREST=1,g.LINEAR_NEAREST_MIPNEAREST=9,g.LINEAR_NEAREST_MIPLINEAR=10,g.LINEAR_LINEAR=2,g.LINEAR_NEAREST=12,g.EXPLICIT_MODE=0,g.SPHERICAL_MODE=1,g.PLANAR_MODE=2,g.CUBIC_MODE=3,g.PROJECTION_MODE=4,g.SKYBOX_MODE=5,g.INVCUBIC_MODE=6,g.EQUIRECTANGULAR_MODE=7,g.FIXED_EQUIRECTANGULAR_MODE=8,g.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,g.CLAMP_ADDRESSMODE=0,g.WRAP_ADDRESSMODE=1,g.MIRROR_ADDRESSMODE=2,g.UseSerializedUrlIfAny=!1,(0,r.Cg)([(0,s.lK)()],g.prototype,"url",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"uOffset",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"vOffset",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"uScale",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"vScale",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"uAng",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"vAng",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"wAng",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"uRotationCenter",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"vRotationCenter",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"wRotationCenter",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"homogeneousRotationInUVTransform",void 0),(0,r.Cg)([(0,s.lK)()],g.prototype,"isBlocking",null),(0,l.Y5)("BABYLON.Texture",g),m.p._TextureParser=g.Parse},18310:(e,t,i)=>{"use strict";i.d(t,{u:()=>r});class r{get wrapU(){return this._cachedWrapU}set wrapU(e){this._cachedWrapU=e}get wrapV(){return this._cachedWrapV}set wrapV(e){this._cachedWrapV=e}get wrapR(){return this._cachedWrapR}set wrapR(e){this._cachedWrapR=e}get anisotropicFilteringLevel(){return this._cachedAnisotropicFilteringLevel}set anisotropicFilteringLevel(e){this._cachedAnisotropicFilteringLevel=e}get comparisonFunction(){return this._comparisonFunction}set comparisonFunction(e){this._comparisonFunction=e}get useMipMaps(){return this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}constructor(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}setParameters(e=1,t=1,i=1,r=1,s=2,n=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=r,this.samplingMode=s,this._comparisonFunction=n,this}compareSampler(e){return this._cachedWrapU===e._cachedWrapU&&this._cachedWrapV===e._cachedWrapV&&this._cachedWrapR===e._cachedWrapR&&this._cachedAnisotropicFilteringLevel===e._cachedAnisotropicFilteringLevel&&this.samplingMode===e.samplingMode&&this._comparisonFunction===e._comparisonFunction&&this._useMipMaps===e._useMipMaps}}},29305:(e,t,i)=>{"use strict";i.d(t,{D:()=>s});var r=i(29962);class s{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}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return void 0!==e?.shareDepth}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=r.o.Zero(),this._cachedBaseSize=r.o.Zero(),this._initialSamplingMode=2,this._texture=s._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return 4===this.delayLoadState?(this.delayLoad(),!1):!!this._texture&&this._texture.isReady}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._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):(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,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)}}},57551:(e,t,i)=>{"use strict";function r(e){-1===e.indexOf("vClipPlane")&&e.push("vClipPlane"),-1===e.indexOf("vClipPlane2")&&e.push("vClipPlane2"),-1===e.indexOf("vClipPlane3")&&e.push("vClipPlane3"),-1===e.indexOf("vClipPlane4")&&e.push("vClipPlane4"),-1===e.indexOf("vClipPlane5")&&e.push("vClipPlane5"),-1===e.indexOf("vClipPlane6")&&e.push("vClipPlane6")}function s(e,t,i){const r=!!(e.clipPlane??t.clipPlane),s=!!(e.clipPlane2??t.clipPlane2),n=!!(e.clipPlane3??t.clipPlane3),o=!!(e.clipPlane4??t.clipPlane4),a=!!(e.clipPlane5??t.clipPlane5),l=!!(e.clipPlane6??t.clipPlane6);r&&i.push("#define CLIPPLANE"),s&&i.push("#define CLIPPLANE2"),n&&i.push("#define CLIPPLANE3"),o&&i.push("#define CLIPPLANE4"),a&&i.push("#define CLIPPLANE5"),l&&i.push("#define CLIPPLANE6")}function n(e,t,i){let r=!1;const s=!!(e.clipPlane??t.clipPlane),n=!!(e.clipPlane2??t.clipPlane2),o=!!(e.clipPlane3??t.clipPlane3),a=!!(e.clipPlane4??t.clipPlane4),l=!!(e.clipPlane5??t.clipPlane5),h=!!(e.clipPlane6??t.clipPlane6);return i.CLIPPLANE!==s&&(i.CLIPPLANE=s,r=!0),i.CLIPPLANE2!==n&&(i.CLIPPLANE2=n,r=!0),i.CLIPPLANE3!==o&&(i.CLIPPLANE3=o,r=!0),i.CLIPPLANE4!==a&&(i.CLIPPLANE4=a,r=!0),i.CLIPPLANE5!==l&&(i.CLIPPLANE5=l,r=!0),i.CLIPPLANE6!==h&&(i.CLIPPLANE6=h,r=!0),r}function o(e,t,i){let r=t.clipPlane??i.clipPlane;a(e,"vClipPlane",r),r=t.clipPlane2??i.clipPlane2,a(e,"vClipPlane2",r),r=t.clipPlane3??i.clipPlane3,a(e,"vClipPlane3",r),r=t.clipPlane4??i.clipPlane4,a(e,"vClipPlane4",r),r=t.clipPlane5??i.clipPlane5,a(e,"vClipPlane5",r),r=t.clipPlane6??i.clipPlane6,a(e,"vClipPlane6",r)}function a(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}i.d(t,{Eq:()=>n,TV:()=>r,gS:()=>o,tv:()=>s})},90446:(e,t,i)=>{"use strict";function r(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}i.d(t,{B:()=>r})},87741:(e,t,i)=>{"use strict";i.d(t,{Q:()=>l});var r=i(15287),s=i(40220),n=i(11084),o=i(89518),a=i(90446);class l{constructor(){this._dirty=!0,this._tempColor=new n.ov(0,0,0,0),this._globalCurve=new n.ov(0,0,0,0),this._highlightsCurve=new n.ov(0,0,0,0),this._midtonesCurve=new n.ov(0,0,0,0),this._shadowsCurve=new n.ov(0,0,0,0),this._positiveCurve=new n.ov(0,0,0,0),this._negativeCurve=new n.ov(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",r="vCameraColorCurveNeutral",s="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(r,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(s,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,r,s){null!=e&&(e=l._Clamp(e,0,360),t=l._Clamp(t,-100,100),i=l._Clamp(i,-100,100),r=l._Clamp(r,-100,100),t=l._ApplyColorGradingSliderNonlinear(t),t*=.5,r=l._ApplyColorGradingSliderNonlinear(r),t<0&&(t*=-1,e=(e+180)%360),l._FromHSBToRef(e,t,50+.25*r,s),s.scaleToRef(2,s),s.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(e,t,i,r){let s=l._Clamp(e,0,360);const n=l._Clamp(t/100,0,1),o=l._Clamp(i/100,0,1);if(0===n)r.r=o,r.g=o,r.b=o;else{s/=60;const e=Math.floor(s),t=s-e,i=o*(1-n),a=o*(1-n*t),l=o*(1-n*(1-t));switch(e){case 0:r.r=o,r.g=l,r.b=i;break;case 1:r.r=a,r.g=o,r.b=i;break;case 2:r.r=i,r.g=o,r.b=l;break;case 3:r.r=i,r.g=a,r.b=o;break;case 4:r.r=l,r.g=i,r.b=o;break;default:r.r=o,r.g=i,r.b=a}}r.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return o.p.Clone((()=>new l),this)}serialize(){return o.p.Serialize(this)}static Parse(e){return o.p.Parse((()=>new l),e,null,null)}}l.PrepareUniforms=a.B,(0,r.Cg)([(0,s.lK)()],l.prototype,"_globalHue",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_globalDensity",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_globalSaturation",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_globalExposure",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_highlightsHue",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_highlightsDensity",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_highlightsSaturation",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_highlightsExposure",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_midtonesHue",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_midtonesDensity",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_midtonesSaturation",void 0),(0,r.Cg)([(0,s.lK)()],l.prototype,"_midtonesExposure",void 0),o.p._ColorCurvesParser=l.Parse},61340:(e,t,i)=>{"use strict";function r(e){return void 0===e.getPipelineContext}i.d(t,{E:()=>r})},15311:(e,t,i)=>{"use strict";i.d(t,{E:()=>r});class r{static GetEffect(e){return void 0===e.getPipelineContext?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){this.effect=e,void 0!==t&&(this.defines=t),i&&this.drawContext?.reset()}dispose(){this.effect&&(this.effect.dispose(),this.effect=null),this.drawContext?.dispose()}}},73010:(e,t,i)=>{"use strict";i.d(t,{b4:()=>h,bu:()=>u,mO:()=>c,uR:()=>f});var r=i(68191),s=i(66593),n=i(69841),o=i(60590),a=i(88217),l=i(2636);function h(e,t){return(0,s.N5)(t).cachedPipelines[e]}function c(e){const t=e._name,i=e.context;if(t&&i){const e=(0,s.N5)(i),r=e.cachedPipelines[t];r?.dispose(),delete e.cachedPipelines[t]}}function u(e,t,i,s,n,o,l){let h,c;const u=(0,r.BA)()?o?.getHostDocument():null;h="string"==typeof t?t:t.vertexSource?"source:"+t.vertexSource:t.vertexElement?u?.getElementById(t.vertexElement)||t.vertexElement:t.vertex||t,c="string"==typeof t?t:t.fragmentSource?"source:"+t.fragmentSource:t.fragmentElement?u?.getElementById(t.fragmentElement)||t.fragmentElement:t.fragment||t;const f=[void 0,void 0],p=()=>{if(f[0]&&f[1]){e.isFragment=!0;const[r,h]=f;(0,a.M0)(h,e,((o,h)=>{l&&(l._fragmentSourceCodeBeforeMigration=h),i&&(o=i("fragment",o));const c=(0,a.nO)(r,o,e);e=null;const u=function(e,t,i,r){return i?{vertexSourceCode:(1===r?"//":"")+"#define SHADER_NAME vertex:"+(i.vertexElement||i.vertex||i.spectorName||i)+"\n"+e,fragmentSourceCode:(1===r?"//":"")+"#define SHADER_NAME fragment:"+(i.fragmentElement||i.fragment||i.spectorName||i)+"\n"+t}:{vertexSourceCode:e,fragmentSourceCode:t}}(c.vertexCode,c.fragmentCode,t,n);s?.(u.vertexSourceCode,u.fragmentSourceCode)}),o)}};d(h,"Vertex","",(t=>{(0,a.pB)(e),(0,a.M0)(t,e,((e,r)=>{l&&(l._rawVertexSourceCode=t,l._vertexSourceCodeBeforeMigration=r),i&&(e=i("vertex",e)),f[0]=e,p()}),o)}),n),d(c,"Fragment","Pixel",(e=>{l&&(l._rawFragmentSourceCode=e),f[1]=e,p()}),n)}function d(e,t,i,s,o,a){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void s((0,r.Zl)(e));if("source:"===e.substring(0,7))return void s(e.substring(7));if("base64:"===e.substring(0,7))return void s(window.atob(e.substring(7)));const h=n.l.GetShadersStore(o);if(h[e+t+"Shader"])return void s(h[e+t+"Shader"]);if(i&&h[e+i+"Shader"])return void s(h[e+i+"Shader"]);let c;if(c="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:n.l.GetShadersRepository(o)+e,!(a=a||l.W0))throw new Error("loadFileInjection is not defined");a(c+"."+t.toLowerCase()+".fx",s)}const f=(e,t,i,r)=>{try{const n=e.existingPipelineContext||t(e.shaderProcessingContext);return n._name=e.name,e.name&&e.context&&((0,s.N5)(e.context).cachedPipelines[e.name]=n),i(n,e.vertex,e.fragment,!!e.createAsRaw,"","",e.rebuildRebind,e.defines,e.transformFeedbackVaryings,"",(()=>{r(n,(()=>{e.onRenderingStateCompiled?.(n)}))})),n}catch(e){throw o.V.Error("Error compiling effect"),e}}},36217:(e,t,i)=>{"use strict";i.d(t,{M:()=>a});var r=i(43279),s=i(60590),n=i(69841),o=i(73010);class a{static get ShadersRepository(){return n.l.ShadersRepository}static set ShadersRepository(e){n.l.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new r.cP),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,s=null,n,l=null,h=null,c=null,u=null,d,f="",p=0,_){this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new r.cP,this.onErrorObservable=new r.cP,this._onBindObservable=null,this._isDisposed=!1,this._refCount=1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=f;const m=this._key.replace(/\r/g,"").replace(/\n/g,"|");let g;if(t.attributes){const e=t;if(this._engine=i,this._attributesNames=e.attributes,this._uniformsNames=e.uniformsNames.concat(e.samplers),this._samplerList=e.samplers.slice(),this.defines=e.defines,this.onError=e.onError,this.onCompiled=e.onCompiled,this._fallbacks=e.fallbacks,this._indexParameters=e.indexParameters,this._transformFeedbackVaryings=e.transformFeedbackVaryings||null,this._multiTarget=!!e.multiTarget,this._shaderLanguage=e.shaderLanguage??0,e.uniformBuffersNames){this._uniformBuffersNamesList=e.uniformBuffersNames.slice();for(let t=0;t{this._vertexSourceCode=e,this._fragmentSourceCode=i,this._prepareEffect(t)}),this._shaderLanguage,this._engine,this)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!this._engine.isDisposed||!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}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){this.isReady()?e(this):(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){return void this._processCompilationErrors(t,e)}this._isDisposed||setTimeout((()=>{this._checkIsReady(e)}),16)}get vertexSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:this._pipelineContext?._getVertexShaderCode()??this._vertexSourceCode}get fragmentSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:this._pipelineContext?._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("\n"),addGlobalDefines:!1,extendedProcessingOptions:{indexParameters:this._indexParameters,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,supportsUniformBuffers:this._engine.supportsUniformBuffers},extendedCreatePipelineOptions:{transformFeedbackVaryings:this._transformFeedbackVaryings,createAsRaw:!(!this._vertexSourceCodeOverride||!this._fragmentSourceCodeOverride)}}}_rebuildProgram(e,t,i,r){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{r&&r(t)},this.onCompiled=()=>{const e=this.getEngine().scenes;if(e)for(let t=0;tthis._rebuildProgram(e,t,i,r),defines:r,transformFeedbackVaryings:this._transformFeedbackVaryings,name:this._key.replace(/\r/g,"").replace(/\n/g,"|"),createAsRaw:i,parallelShaderCompile:a._caps.parallelShaderCompile,shaderProcessingContext:this._processingContext,onRenderingStateCompiled:i=>{t&&!e&&this._engine._deletePipelineContext(t),i&&this._onRenderingStateCompiled(i)}},this._engine.createPipelineContext.bind(this._engine),this._engine._preparePipelineContext.bind(this._engine),this._engine._executeWhenRenderingStateIsCompiled.bind(this._engine)),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(e){this._processCompilationErrors(e,t)}}_getShaderCodeAndErrorLine(e,t,i){const r=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/;let s=null;if(t&&e){const n=t.match(r);if(n&&2===n.length){const t=parseInt(n[1]),r=e.split("\n",-1);r.length>=t&&(s=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${r[t-1]}`)}}return[e,s]}_processCompilationErrors(e,t=null){this._compilationError=e.message;const i=this._attributesNames,r=this._fallbacks;if(s.V.Error("Unable to compile effect:"),s.V.Error("Uniforms: "+this._uniformsNames.map((function(e){return" "+e}))),s.V.Error("Attributes: "+i.map((function(e){return" "+e}))),s.V.Error("Defines:\n"+this.defines),a.LogShaderCodeOnCompilationError){let e=null,t=null,i=null;this._pipelineContext?._getVertexShaderCode()&&([i,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),i&&(s.V.Error("Vertex code:"),s.V.Error(i))),this._pipelineContext?._getFragmentShaderCode()&&([i,t]=this._getShaderCodeAndErrorLine(this._pipelineContext?._getFragmentShaderCode(),this._compilationError,!0),i&&(s.V.Error("Fragment code:"),s.V.Error(i))),e&&s.V.Error(e),t&&s.V.Error(t)}s.V.Error("Error: "+this._compilationError);const n=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,n()),r?(this._pipelineContext=null,r.hasMoreFallbacks?(this._allFallbacksProcessed=!1,s.V.Error("Trying next fallback."),this.defines=r.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,n(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||n())}get isSupported(){return""===this._compilationError}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){const r=this._samplerList.indexOf(e);for(let e=1;e0||this._isDisposed||(this._pipelineContext&&(0,o.mO)(this._pipelineContext),this._engine._releaseEffect(this),this.clearCodeCache(),this._isDisposed=!0)}static RegisterShader(e,t,i,r=0){t&&(n.l.GetShadersStore(r)[`${e}PixelShader`]=t),i&&(n.l.GetShadersStore(r)[`${e}VertexShader`]=i)}static ResetCache(){a._BaseCache={}}}a.LogShaderCodeOnCompilationError=!0,a.AutomaticallyClearCodeCache=!1,a._UniqueIdSeed=0,a._BaseCache={},a.ShadersStore=n.l.ShadersStore,a.IncludesShadersStore=n.l.IncludesShadersStore},50606:(e,t,i)=>{"use strict";i.d(t,{$:()=>c,J:()=>h});var r=i(12721),s=i(13093),n=i(43279),o=i(36217),a=i(15311);i(18013);const l={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class h{constructor(e,t=l){this._fullscreenViewport=new s.L(0,0,1,1);const i=t.positions??l.positions,n=t.indices??l.indices;this.engine=e,this._vertexBuffers={[r.R.PositionKind]:new r.R(e,i,r.R.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(n),this._onContextRestoredObserver=e.onContextRestoredObservable.add((()=>{this._indexBuffer=e.createIndexBuffer(n);for(const e in this._vertexBuffers)this._vertexBuffers[e]._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 void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();const i=null===t?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[r.R.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[r.R.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class c{static RegisterShaderCodeProcessing(e,t){t?c._CustomShaderCodeProcessing[e??""]=t:delete c._CustomShaderCodeProcessing[e??""]}static _GetShaderCodeProcessing(e){return c._CustomShaderCodeProcessing[e]??c._CustomShaderCodeProcessing[""]}get name(){return this.options.name}set name(e){this.options.name=e}isReady(){return this._drawWrapper.effect?.isReady()??!1}get drawWrapper(){return this._drawWrapper}get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){this.alphaMode=0,this.onEffectCreatedObservable=new n.cP(void 0,!0),this.onApplyObservable=new n.cP,this._shadersLoaded=!1,this._webGPUReady=!1,this._importPromises=[],this.options={...e,name:e.name||"effectWrapper",engine:e.engine,uniforms:e.uniforms||e.uniformNames||[],uniformNames:void 0,samplers:e.samplers||e.samplerNames||[],samplerNames:void 0,attributeNames:e.attributeNames||["position"],uniformBuffers:e.uniformBuffers||[],defines:e.defines||"",useShaderStore:e.useShaderStore||!1,vertexUrl:e.vertexUrl||e.vertexShader||"postprocess",vertexShader:void 0,fragmentShader:e.fragmentShader||"pass",indexParameters:e.indexParameters,blockCompilation:e.blockCompilation||!1,shaderLanguage:e.shaderLanguage||0,onCompiled:e.onCompiled||void 0,extraInitializations:e.extraInitializations||void 0,extraInitializationsAsync:e.extraInitializationsAsync||void 0,useAsPostProcess:e.useAsPostProcess??!1},this.options.uniformNames=this.options.uniforms,this.options.samplerNames=this.options.samplers,this.options.vertexShader=this.options.vertexUrl,this.options.useAsPostProcess&&(-1===this.options.samplers.indexOf("textureSampler")&&this.options.samplers.push("textureSampler"),-1===this.options.uniforms.indexOf("scale")&&this.options.uniforms.push("scale")),e.vertexUrl||e.vertexShader?this._shaderPath={vertexSource:this.options.vertexShader}:(this.options.useAsPostProcess||(this.options.uniforms.push("scale"),this.onApplyObservable.add((()=>{this.effect.setFloat2("scale",1,1)}))),this._shaderPath={vertex:this.options.vertexShader}),this._shaderPath.fragmentSource=this.options.fragmentShader,this._shaderPath.spectorName=this.options.name,this.options.useShaderStore&&(this._shaderPath.fragment=this._shaderPath.fragmentSource,this._shaderPath.vertex||(this._shaderPath.vertex=this._shaderPath.vertexSource),delete this._shaderPath.fragmentSource,delete this._shaderPath.vertexSource),this.onApplyObservable.add((()=>{this.bind()})),this.options.useShaderStore||(this._onContextRestoredObserver=this.options.engine.onContextRestoredObservable.add((()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()}))),this._drawWrapper=new a.E(this.options.engine),this._webGPUReady=1===this.options.shaderLanguage;const t=Array.isArray(this.options.defines)?this.options.defines.join("\n"):this.options.defines;this._postConstructor(this.options.blockCompilation,t,this.options.extraInitializations)}_gatherImports(e=!1,t){this.options.useAsPostProcess&&(e&&this._webGPUReady?t.push(Promise.all([Promise.resolve().then(i.bind(i,45010))])):t.push(Promise.all([Promise.resolve().then(i.bind(i,18013))])))}_postConstructor(e,t=null,i,r){this._importPromises.length=0,r&&this._importPromises.push(...r);const s=this.options.engine.isWebGPU&&!c.ForceGLSL;this._gatherImports(s,this._importPromises),void 0!==i&&i(s,this._importPromises),s&&this._webGPUReady&&(this.options.shaderLanguage=1),e||this.updateEffect(t)}updateEffect(e=null,t=null,i=null,r,s,n,a,l){const h=c._GetShaderCodeProcessing(this.name);if(h?.defineCustomBindings){const r=t?.slice()??[];r.push(...this.options.uniforms);const s=i?.slice()??[];s.push(...this.options.samplers),e=h.defineCustomBindings(this.name,e,r,s),t=r,i=s}this.options.defines=e||"";const u=this._shadersLoaded||0===this._importPromises.length?void 0:async()=>{await Promise.all(this._importPromises),this._shadersLoaded=!0};let d;d=this.options.extraInitializationsAsync?async()=>{u?.(),await this.options.extraInitializationsAsync}:u,this.options.useShaderStore?this._drawWrapper.effect=this.options.engine.createEffect({vertex:a??this._shaderPath.vertex,fragment:l??this._shaderPath.fragment},{attributes:this.options.attributeNames,uniformsNames:t||this.options.uniforms,uniformBuffersNames:this.options.uniformBuffers,samplers:i||this.options.samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:s??this.options.onCompiled,onError:n??null,indexParameters:r||this.options.indexParameters,processCodeAfterIncludes:h?.processCodeAfterIncludes?(e,t)=>h.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:h?.processFinalCode?(e,t)=>h.processFinalCode(this.name,e,t):null,shaderLanguage:this.options.shaderLanguage,extraInitializationsAsync:d},this.options.engine):this._drawWrapper.effect=new o.M(this._shaderPath,this.options.attributeNames,t||this.options.uniforms,i||this.options.samplerNames,this.options.engine,e,void 0,s||this.options.onCompiled,void 0,void 0,void 0,this.options.shaderLanguage,d),this.onEffectCreatedObservable.notifyObservers(this._drawWrapper.effect)}bind(){this.options.useAsPostProcess&&(this.options.engine.setAlphaMode(this.alphaMode),this.drawWrapper.effect.setFloat2("scale",1,1)),c._GetShaderCodeProcessing(this.name)?.bindCustomBindings?.(this.name,this._drawWrapper.effect)}dispose(e=!1){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.onEffectCreatedObservable.clear(),this.effect.dispose()}}c.ForceGLSL=!1,c._CustomShaderCodeProcessing={}},61923:(e,t,i)=>{"use strict";i.d(t,{C:()=>n,_:()=>s});var r=i(90446);function s(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),(t.VIGNETTE||t.DITHER)&&e.push("vInverseScreenSize"),t.VIGNETTE&&(e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&(0,r.B)(e),t.DITHER&&e.push("ditherIntensity")}function n(e,t){t.COLORGRADING&&e.push("txColorTransform")}},69648:(e,t,i)=>{"use strict";i.d(t,{p:()=>d});var r=i(15287),s=i(40220),n=i(43279),o=i(11084),a=i(87741),l=i(44512),h=i(89518),c=i(61923),u=i(56225);class d{constructor(){this.colorCurves=new a.Q,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=d.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new o.ov(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=d.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new n.cP}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)return 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,void(e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled);if(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===d._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,this._toneMappingEnabled)switch(this._toneMappingType){case d.TONEMAPPING_KHR_PBR_NEUTRAL:e.TONEMAPPING=3;break;case d.TONEMAPPING_ACES:e.TONEMAPPING=2;break;default:e.TONEMAPPING=1}else e.TONEMAPPING=0;e.CONTRAST=1!==this.contrast,e.EXPOSURE=1!==this.exposure,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&&a.Q.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),r=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,r),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const s=null!=t?t:r/i;let n=Math.tan(.5*this.vignetteCameraFov),o=n*s;const a=Math.sqrt(o*n);o=(0,l.zF)(o,a,this.vignetteStretch),n=(0,l.zF)(n,a,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 t=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(t-1)/t,.5/t,t,this.colorGradingTexture.level)}}clone(){return h.p.Clone((()=>new d),this)}serialize(){return h.p.Serialize(this)}static Parse(e){const t=h.p.Parse((()=>new d),e,null,null);return void 0!==e.vignetteCentreX&&(t.vignetteCenterX=e.vignetteCentreX),void 0!==e.vignetteCentreY&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}}d.TONEMAPPING_STANDARD=0,d.TONEMAPPING_ACES=1,d.TONEMAPPING_KHR_PBR_NEUTRAL=2,d.PrepareUniforms=c._,d.PrepareSamplers=c.C,d._VIGNETTEMODE_MULTIPLY=0,d._VIGNETTEMODE_OPAQUE=1,(0,r.Cg)([(0,s.wL)()],d.prototype,"colorCurves",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_colorCurvesEnabled",void 0),(0,r.Cg)([(0,s.uM)("colorGradingTexture")],d.prototype,"_colorGradingTexture",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_colorGradingEnabled",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_colorGradingWithGreenDepth",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_colorGradingBGR",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_exposure",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_toneMappingEnabled",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_toneMappingType",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_contrast",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"vignetteStretch",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"vignetteCenterX",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"vignetteCenterY",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"vignetteWeight",void 0),(0,r.Cg)([(0,s.qK)()],d.prototype,"vignetteColor",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"vignetteCameraFov",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_vignetteBlendMode",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_vignetteEnabled",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_ditheringEnabled",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_ditheringIntensity",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_skipFinalColorClamp",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_applyByPostProcess",void 0),(0,r.Cg)([(0,s.lK)()],d.prototype,"_isEnabled",void 0),h.p._ImageProcessingConfigurationParser=d.Parse,(0,u.Y5)("BABYLON.ImageProcessingConfiguration",d)},85770:(e,t,i)=>{"use strict";i.d(t,{Bb:()=>G,DL:()=>c,ER:()=>E,GD:()=>U,IC:()=>D,IF:()=>f,J2:()=>x,Jz:()=>w,Kd:()=>T,L0:()=>S,MF:()=>d,N4:()=>V,Nc:()=>B,OR:()=>O,RL:()=>C,VO:()=>L,Y7:()=>k,YT:()=>g,Yy:()=>u,_8:()=>m,az:()=>I,c4:()=>P,f$:()=>b,fm:()=>R,lo:()=>M,mA:()=>v,nR:()=>_,ni:()=>y,qB:()=>F,qL:()=>A,te:()=>p,wu:()=>N});var r=i(60590),s=i(11084),n=i(34268),o=i(14952),a=i(57551);const l=s.v9.Black(),h={NUM_MORPH_INFLUENCERS:0};function c(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){const e=i.activeCamera;1===e.mode&&r.V.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}function u(e,t,i,r=!1){i&&e.fogEnabled&&(!t||t.applyFog)&&0!==e.fogMode&&(i.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),r?(e.fogColor.toLinearSpaceToRef(l,e.getEngine().useExactSrgbConversions),i.setColor3("vFogColor",l)):i.setColor3("vFogColor",e.fogColor))}function d(e,t,i){h.NUM_MORPH_INFLUENCERS=i,f(e,t,h)}function f(e,t,i){const s=i.NUM_MORPH_INFLUENCERS;if(s>0&&n.q.LastCreatedEngine){const o=n.q.LastCreatedEngine.getCaps().maxVertexAttribs,a=t.morphTargetManager;if(a?.isUsingTextureForTargets)return;const l=a&&a.supportsNormals&&i.NORMAL,h=a&&a.supportsTangents&&i.TANGENT,c=a&&a.supportsUVs&&i.UV1;for(let i=0;io&&r.V.Error("Cannot add more vertex attributes for mesh "+t.name)}}function p(e,t=!1){e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"),t&&(e.push("previousWorld0"),e.push("previousWorld1"),e.push("previousWorld2"),e.push("previousWorld3"))}function _(e,t){const i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}function m(e,t){t.bindToEffect(e,"Scene")}function g(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}function v(e,t,i){const r=e.getTextureMatrix();t.updateMatrix(i+"Matrix",r)}function x(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}function b(e,t,i){var r;if(t&&e&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){const s=e.skeleton;if(s.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureWidth")>-1){const i=s.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(s.bones.length+1))}else{const n=s.getTransformMatrices(e);n&&(t.setMatrices("mBones",n),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=n.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),r=n,i.previousBones[e.uniqueId].set(r)))}}}function S(e,t,i){e.transferToEffect(t,i+"")}function T(e,t,i,r,s,n=!0){e._bindLight(t,i,r,s,n)}function C(e,t,i,r,s=4){const n=Math.min(t.lightSources.length,s);for(let s=0;s0&&(r.addCPUSkinningFallback(0,t),e.push("matricesIndices"),e.push("matricesWeights"),i.NUM_BONE_INFLUENCERS>4&&(e.push("matricesIndicesExtra"),e.push("matricesWeightsExtra")))}function E(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&p(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push("instanceColor")}function P(e,t,i=4,r=0){let s=0;for(let n=0;n0&&(s=r+n,t.addFallback(s,"LIGHT"+n)),e.SHADOWS||(e["SHADOW"+n]&&t.addFallback(r,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(r,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(r,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(r,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(r,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(r,"SHADOWCLOSEESM"+n));return s++}function A(e,t){return t.fogEnabled&&e.applyFog&&0!==t.fogMode}function R(e,t,i,r,s,n,o,a=!1){o._areMiscDirty&&(o.LOGARITHMICDEPTH=i,o.POINTSIZE=r,o.FOG=s&&A(e,t),o.NONUNIFORMSCALING=e.nonUniformScaling,o.ALPHATEST=n,o.DECAL_AFTER_DETAIL=a)}function I(e,t,i,r,s=4,n=!1){if(!i._areLightsDirty)return i._needNormals;let o=0;const a={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n)for(const n of t.lightSources)if(M(e,t,n,o,i,r,a),o++,o===s)break;i.SPECULARTERM=a.specularEnabled,i.SHADOWS=a.shadowEnabled;for(let e=o;e0&&(a.shadowEnabled=!0,t.prepareDefines(s,r))}}i.lightmapMode!=o.c.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,s["LIGHTMAPEXCLUDED"+r]=!0,s["LIGHTMAPNOSPECULAR"+r]=i.lightmapMode==o.c.LIGHTMAP_SHADOWSONLY):(s["LIGHTMAPEXCLUDED"+r]=!1,s["LIGHTMAPNOSPECULAR"+r]=!1)}function O(e,t,i,r,s,n=null,o=!1){let l=k(e,r);!1!==n&&(l=(0,a.Eq)(i,e,r)),r.DEPTHPREPASS!==!t.getColorWrite()&&(r.DEPTHPREPASS=!r.DEPTHPREPASS,l=!0),r.INSTANCES!==s&&(r.INSTANCES=s,l=!0),r.THIN_INSTANCES!==o&&(r.THIN_INSTANCES=o,l=!0),l&&r.markAsUnprocessed()}function D(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;const i=void 0!==t.BONETEXTURE;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!i&&void 0;const r=e.getScene().prePassRenderer;if(r&&r.enabled){const i=-1===r.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=i}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}function w(e,t){const i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.NUM_MORPH_INFLUENCERS=i.numMaxInfluencers||i.numInfluencers,t.MORPHTARGETS=t.NUM_MORPH_INFLUENCERS>0,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}function N(e,t){const i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!(!i||!i.isEnabled)}function F(e,t,i,r,s=!1,n=!0,o=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent("normal"),t._needNormals&&e.isVerticesDataPresent("tangent")&&(t.TANGENT=!0);for(let i=1;i<=6;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);if(i){const i=e.useVertexColors&&e.isVerticesDataPresent("color");t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&n}return e.isVerticesDataPresent("instanceColor")&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),r&&D(e,t),s&&w(e,t),o&&N(e,t),!0}function L(e,t){if(e.activeCamera){const i=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}function B(e,t,i){const r=t.ORDER_INDEPENDENT_TRANSPARENCY,s=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,r===t.ORDER_INDEPENDENT_TRANSPARENCY&&s===t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS||t.markAsUnprocessed()}function V(e,t,i){const r=t.PREPASS;if(!t._arePrePassDirty)return;const s=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:9,define:"PREPASS_LOCAL_POSITION",index:"PREPASS_LOCAL_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:11,define:"PREPASS_VELOCITY_LINEAR",index:"PREPASS_VELOCITY_LINEAR_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:10,define:"PREPASS_SCREENSPACE_DEPTH",index:"PREPASS_SCREENSPACE_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"},{type:8,define:"PREPASS_WORLD_NORMAL",index:"PREPASS_WORLD_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace,t.PREPASS_COLOR=!0,t.PREPASS_COLOR_INDEX=0;for(let i=0;i{"use strict";i.d(t,{D:()=>n});var r=i(60590),s=i(9723);class n{constructor(e,t,i,r,s=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||s,this._dynamic=i,this._name=r??"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return void 0!==this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}_fillAlignment(e){let t;if(t=e<=2?e:4,this._uniformLocationPointer%t!=0){const e=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;const i=this._uniformLocationPointer-e;for(let e=0;e0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},16==t?t*=i:t=t*i+(4-t)*i,r=[];for(let e=0;e1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1]))return this._needSync=!1,void(this._createBufferOnWrite=this._engine._features.trackUbosInFrame);this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(n._UpdatedUbosInFrame[this._name]||(n._UpdatedUbosInFrame[this._name]=0),n._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}else this._createBufferOnWrite=this._engine._features.trackUbosInFrame;else this.create()}_createNewBuffer(){this._bufferIndex+10?(this._needSync=0!==this._bufferIndex,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(void 0===s){if(this._buffer)return void r.V.Error("Cannot add an uniform after UBO has been created. uniformName="+e);this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;e{"use strict";i.d(t,{$x:()=>r,_0:()=>o,xp:()=>s});var r,s,n=i(94212);!function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(r||(r={}));class o{}o.X=new n.Pq(1,0,0),o.Y=new n.Pq(0,1,0),o.Z=new n.Pq(0,0,1),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(s||(s={}))},11084:(e,t,i)=>{"use strict";i.d(t,{IG:()=>f,ov:()=>d,v9:()=>u});var r=i(34130),s=i(56225),n=i(34910),o=i(56984);function a(e){return Math.pow(e,n.tk)}function l(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function h(e){return Math.pow(e,n.rv)}function c(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}class u{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=255*this.r|0;return e=397*e^255*this.g,e=397*e^255*this.b,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 u.FromArrayToRef(e,t,this),this}toColor4(e=1){return new d(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return.3*this.r+.59*this.g+.11*this.b}multiply(e){return new u(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 u(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=n.bH){return(0,o.WithinEpsilon)(this.r,e.r,t)&&(0,o.WithinEpsilon)(this.g,e.g,t)&&(0,o.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 u(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=(0,o.Clamp)(this.r,e,t),i.g=(0,o.Clamp)(this.g,e,t),i.b=(0,o.Clamp)(this.b,e,t),i}add(e){return new u(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 u(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 u(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-i,r}clone(){return new u(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(255*this.r),t=Math.round(255*this.g),i=Math.round(255*this.b);return"#"+(0,o.ToHex)(e)+(0,o.ToHex)(t)+(0,o.ToHex)(i)}fromHexString(e){return"#"!==e.substring(0,1)||7!==e.length||(this.r=parseInt(e.substring(1,3),16)/255,this.g=parseInt(e.substring(3,5),16)/255,this.b=parseInt(e.substring(5,7),16)/255),this}toHSV(){return this.toHSVToRef(new u)}toHSVToRef(e){const t=this.r,i=this.g,r=this.b,s=Math.max(t,i,r),n=Math.min(t,i,r);let o=0,a=0;const l=s,h=s-n;return 0!==s&&(a=h/s),s!=n&&(s==t?(o=(i-r)/h,i=0&&n<=1?(a=s,l=o):n>=1&&n<=2?(a=o,l=s):n>=2&&n<=3?(l=s,h=o):n>=3&&n<=4?(l=o,h=s):n>=4&&n<=5?(a=o,h=s):n>=5&&n<=6&&(a=s,h=o);const c=i-s;return r.r=a+c,r.g=l+c,r.b=h+c,r}static FromHSV(e,t,i){const r=new u(0,0,0);return u.HSVtoRGBToRef(e,t,i,r),r}static FromHexString(e){return new u(0,0,0).fromHexString(e)}static FromArray(e,t=0){return new u(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 u(e/255,t/255,i/255)}static Lerp(e,t,i){const r=new u(0,0,0);return u.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,r,s){const n=s*s,o=s*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+s,c=o-n,d=e.r*a+i.r*l+t.r*h+r.r*c,f=e.g*a+i.g*l+t.g*h+r.g*c,p=e.b*a+i.b*l+t.b*h+r.b*c;return new u(d,f,p)}static Hermite1stDerivative(e,t,i,r,s){const n=u.Black();return this.Hermite1stDerivativeToRef(e,t,i,r,s,n),n}static Hermite1stDerivativeToRef(e,t,i,r,s,n){const o=s*s;n.r=6*(o-s)*e.r+(3*o-4*s+1)*t.r+6*(-o+s)*i.r+(3*o-2*s)*r.r,n.g=6*(o-s)*e.g+(3*o-4*s+1)*t.g+6*(-o+s)*i.g+(3*o-2*s)*r.g,n.b=6*(o-s)*e.b+(3*o-4*s+1)*t.b+6*(-o+s)*i.b+(3*o-2*s)*r.b}static Red(){return new u(1,0,0)}static Green(){return new u(0,1,0)}static Blue(){return new u(0,0,1)}static Black(){return new u(0,0,0)}static get BlackReadOnly(){return u._BlackReadOnly}static White(){return new u(1,1,1)}static Purple(){return new u(.5,0,.5)}static Magenta(){return new u(1,0,1)}static Yellow(){return new u(1,1,0)}static Gray(){return new u(.5,.5,.5)}static Teal(){return new u(0,1,1)}static Random(){return new u(Math.random(),Math.random(),Math.random())}}u._BlackReadOnly=u.Black(),Object.defineProperties(u.prototype,{dimension:{value:[3]},rank:{value:1}});class d{constructor(e=0,t=0,i=0,r=1){this.r=e,this.g=t,this.b=i,this.a=r}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new d(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}addInPlaceFromFloats(e,t,i,r){return this.r+=e,this.g+=t,this.b+=i,this.a+=r,this}subtract(e){return new d(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this}subtractFromFloats(e,t,i,r){return new d(this.r-e,this.g-t,this.b-i,this.a-r)}subtractFromFloatsToRef(e,t,i,r,s){return s.r=this.r-e,s.g=this.g-t,s.b=this.b-i,s.a=this.a-r,s}scale(e){return new d(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=(0,o.Clamp)(this.r,e,t),i.g=(0,o.Clamp)(this.g,e,t),i.b=(0,o.Clamp)(this.b,e,t),i.a=(0,o.Clamp)(this.a,e,t),i}multiply(e){return new d(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this}multiplyByFloats(e,t,i,r){return new d(this.r*e,this.g*t,this.b*i,this.a*r)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this}maximizeInPlace(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this}minimizeInPlaceFromFloats(e,t,i,r){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this.a=Math.min(r,this.a),this}maximizeInPlaceFromFloats(e,t,i,r){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this.a=Math.max(r,this.a),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}equalsWithEpsilon(e,t=n.bH){return(0,o.WithinEpsilon)(this.r,e.r,t)&&(0,o.WithinEpsilon)(this.g,e.g,t)&&(0,o.WithinEpsilon)(this.b,e.b,t)&&(0,o.WithinEpsilon)(this.a,e.a,t)}equalsToFloats(e,t,i,r){return this.r===e&&this.g===t&&this.b===i&&this.a===r}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=255*this.r|0;return e=397*e^255*this.g,e=397*e^255*this.b,e=397*e^255*this.a,e}clone(){return(new d).copyFrom(this)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,r){return this.r=e,this.g=t,this.b=i,this.a=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){const t=Math.round(255*this.r),i=Math.round(255*this.g),r=Math.round(255*this.b);if(e)return"#"+(0,o.ToHex)(t)+(0,o.ToHex)(i)+(0,o.ToHex)(r);const s=Math.round(255*this.a);return"#"+(0,o.ToHex)(t)+(0,o.ToHex)(i)+(0,o.ToHex)(r)+(0,o.ToHex)(s)}fromHexString(e){return"#"!==e.substring(0,1)||9!==e.length&&7!==e.length||(this.r=parseInt(e.substring(1,3),16)/255,this.g=parseInt(e.substring(3,5),16)/255,this.b=parseInt(e.substring(5,7),16)/255,9===e.length&&(this.a=parseInt(e.substring(7,9),16)/255)),this}toLinearSpace(e=!1){const t=new d;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=l(this.r),e.g=l(this.g),e.b=l(this.b)):(e.r=a(this.r),e.g=a(this.g),e.b=a(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new d;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=c(this.r),e.g=c(this.g),e.b=c(this.b)):(e.r=h(this.r),e.g=h(this.g),e.b=h(this.b)),e.a=this.a,this}static FromHexString(e){return"#"!==e.substring(0,1)||9!==e.length&&7!==e.length?new d(0,0,0,0):new d(0,0,0,1).fromHexString(e)}static Lerp(e,t,i){return d.LerpToRef(e,t,i,new d)}static LerpToRef(e,t,i,r){return r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i,r.a=e.a+(t.a-e.a)*i,r}static Hermite(e,t,i,r,s){const n=s*s,o=s*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+s,c=o-n,u=e.r*a+i.r*l+t.r*h+r.r*c,f=e.g*a+i.g*l+t.g*h+r.g*c,p=e.b*a+i.b*l+t.b*h+r.b*c,_=e.a*a+i.a*l+t.a*h+r.a*c;return new d(u,f,p,_)}static Hermite1stDerivative(e,t,i,r,s){const n=new d;return this.Hermite1stDerivativeToRef(e,t,i,r,s,n),n}static Hermite1stDerivativeToRef(e,t,i,r,s,n){const o=s*s;n.r=6*(o-s)*e.r+(3*o-4*s+1)*t.r+6*(-o+s)*i.r+(3*o-2*s)*r.r,n.g=6*(o-s)*e.g+(3*o-4*s+1)*t.g+6*(-o+s)*i.g+(3*o-2*s)*r.g,n.b=6*(o-s)*e.b+(3*o-4*s+1)*t.b+6*(-o+s)*i.b+(3*o-2*s)*r.b,n.a=6*(o-s)*e.a+(3*o-4*s+1)*t.a+6*(-o+s)*i.a+(3*o-2*s)*r.a}static FromColor3(e,t=1){return new d(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new d(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,r){return new d(e/255,t/255,i/255,r/255)}static CheckColors4(e,t){if(e.length===3*t){const t=[];for(let i=0;inew d(0,0,0,0))),(0,s.Y5)("BABYLON.Color3",u),(0,s.Y5)("BABYLON.Color4",d)},34910:(e,t,i)=>{"use strict";i.d(t,{a6:()=>n,bH:()=>o,rv:()=>r,tk:()=>s});const r=1/2.2,s=2.2,n=(1+Math.sqrt(5))/2,o=.001},59881:(e,t,i)=>{"use strict";i.d(t,{P:()=>s});var r=i(30573);class s{static GetPlanes(e){const t=[];for(let e=0;e<6;e++)t.push(new r.Z(0,0,0,0));return s.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){s.GetNearPlaneToRef(e,t[0]),s.GetFarPlaneToRef(e,t[1]),s.GetLeftPlaneToRef(e,t[2]),s.GetRightPlaneToRef(e,t[3]),s.GetTopPlaneToRef(e,t[4]),s.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}}},890:(e,t,i)=>{"use strict";i.d(t,{Y4:()=>h,b8:()=>l,cD:()=>a});var r=i(15287),s=i(94212),n=i(40220);class o{static extractMinAndMaxIndexed(e,t,i,r,s,n){for(let o=i;o=0&&(t[i]=p,t[i+2]=l)}}(0,r.Cg)([n.Cx.filter(((...[e,t])=>!Array.isArray(e)&&!Array.isArray(t)))],o,"extractMinAndMaxIndexed",null),(0,r.Cg)([n.Cx.filter(((...[e])=>!Array.isArray(e)))],o,"extractMinAndMax",null)},73864:(e,t,i)=>{"use strict";i.d(t,{uM:()=>a.uM,Xy:()=>a.Xy,_0:()=>r._0,vr:()=>a.vr,v9:()=>s.v9,ov:()=>s.ov,xp:()=>r.xp,jj:()=>a.jj,bH:()=>n.bH,PP:()=>o.P,uq:()=>c.uq,t4:()=>a.t4,a6:()=>n.a6,Cu:()=>a.Cu,tO:()=>a.tO,Zc:()=>l.Z,k0:()=>d,B5:()=>u,PT:()=>c.PT,or:()=>h.o,$x:()=>r.$x,IG:()=>s.IG,AA:()=>c.AA,rv:()=>n.rv,tk:()=>n.tk,I9:()=>c.I9,Pq:()=>c.Pq,IU:()=>c.IU,LM:()=>f.L});var r=i(4514),s=i(11084),n=i(34910),o=i(59881),a=i(50324),l=i(30573),h=i(29962),c=i(94212);class u{constructor(e=c.Pq.Zero(),t=c.Pq.Up()){this.position=e,this.normal=t}clone(){return new u(this.position.clone(),this.normal.clone())}}class d{constructor(e=c.Pq.Zero(),t=c.Pq.Up(),i=c.I9.Zero()){this.position=e,this.normal=t,this.uv=i}clone(){return new d(this.position.clone(),this.normal.clone(),this.uv.clone())}}var f=i(13093)},50324:(e,t,i)=>{"use strict";i.d(t,{Cu:()=>c,Xy:()=>h,jj:()=>d,t4:()=>r,tO:()=>u,uM:()=>l,vr:()=>a});var r,s=i(56984),n=i(94212),o=i(34910);!function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(r||(r={}));class a{static Interpolate(e,t,i,r,s){const n=1-3*r+3*t,o=3*r-6*t,a=3*t;let l=e;for(let t=0;t<5;t++){const t=l*l;l-=1/(3*n*t+2*o*l+a)*(n*(t*l)+o*t+a*l-e),l=Math.min(1,Math.max(0,l))}return 3*Math.pow(1-l,2)*l*i+3*(1-l)*Math.pow(l,2)*s+Math.pow(l,3)}}class l{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return 180*this._radians/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){const i=t.subtract(e),r=Math.atan2(i.y,i.x);return new l(r)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(0===i)return new l(Math.PI/2);i=Math.sqrt(i);let r=e.dot(t)/i;r=(0,s.Clamp)(r,-1,1);const n=Math.acos(r);return new l(n)}static FromRadians(e){return new l(e)}static FromDegrees(e){return new l(e*Math.PI/180)}}class h{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;const r=Math.pow(t.x,2)+Math.pow(t.y,2),s=(Math.pow(e.x,2)+Math.pow(e.y,2)-r)/2,o=(r-Math.pow(i.x,2)-Math.pow(i.y,2))/2,a=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new n.I9((s*(t.y-i.y)-o*(e.y-t.y))/a,((e.x-t.x)*o-(t.x-i.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);const h=this.startAngle.degrees();let c=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();c-h>180&&(c-=360),c-h<-180&&(c+=360),u-c>180&&(u-=360),u-c<-180&&(u+=360),this.orientation=c-h<0?0:1,this.angle=l.FromDegrees(0===this.orientation?h-u:u-h)}}class c{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new n.I9(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new n.I9(e,t),r=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(r).length(),this}addArcTo(e,t,i,r,s=36){if(this.closed)return this;const o=this._points[this._points.length-1],a=new n.I9(e,t),l=new n.I9(i,r),c=new h(o,a,l);let u=c.angle.radians()/s;0===c.orientation&&(u*=-1);let d=c.startAngle.radians()+u;for(let e=0;e(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r,o=this._points[this._points.length-1];for(let a=0;a<=s;a++){const l=a/s,h=n(l,o.x,e,i),c=n(l,o.y,t,r);this.addLineTo(h,c)}return this}addBezierCurveTo(e,t,i,r,s,n,o=36){if(this.closed)return this;const a=(e,t,i,r,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*s,l=this._points[this._points.length-1];for(let h=0;h<=o;h++){const c=h/o,u=a(c,l.x,e,i,s),d=a(c,l.y,t,r,n);this.addLineTo(u,d)}return this}isPointInside(e){let t=!1;const i=this._points.length;for(let r=i-1,s=0;sNumber.EPSILON){if(a<0&&(i=this._points[s],o=-o,n=this._points[r],a=-a),e.yn.y)continue;if(e.y===i.y&&e.x===i.x)return!0;{const r=a*(e.x-i.x)-o*(e.y-i.y);if(0===r)return!0;if(r<0)continue;t=!t}}else{if(e.y!==i.y)continue;if(n.x<=e.x&&e.x<=i.x||i.x<=e.x&&e.x<=n.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];e+=this._points[0].subtract(t).length()}return e}area(){const e=this._points.length;let t=0;for(let i=e-1,r=0;r1)return n.I9.Zero();const t=e*this.length();let i=0;for(let e=0;e=i&&t<=a){const e=o.normalize(),r=t-i;return new n.I9(s.x+e.x*r,s.y+e.y*r)}i=a}return n.I9.Zero()}static StartingAt(e,t){return new c(e,t)}}class u{constructor(e,t=null,i,r=!1){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:n.Pq.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:n.uq.Identity()};for(let t=0;tt){const i=e;e=t,t=i}const i=this.getCurve(),r=this.getPointAt(e);let s=this.getPreviousPointIndexAt(e);const n=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,a=[];return 0!==e&&(s++,a.push(r)),a.push(...i.slice(s,o)),1===t&&1!==e||a.push(n),new u(a,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let t=0;tt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,r=e.length();if(0===r&&(r=1),null==t){let t;t=(0,s.WithinEpsilon)(Math.abs(e.y)/r,1,o.bH)?(0,s.WithinEpsilon)(Math.abs(e.x)/r,1,o.bH)?(0,s.WithinEpsilon)(Math.abs(e.z)/r,1,o.bH)?n.Pq.Zero():new n.Pq(0,0,1):new n.Pq(1,0,0):new n.Pq(0,-1,0),i=n.Pq.Cross(e,t)}else i=n.Pq.Cross(e,t),n.Pq.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;const i=this.getPoints();if(e<=0)return this._setPointAtData(0,0,i[0],0,t);if(e>=1)return this._setPointAtData(1,1,i[i.length-1],i.length-1,t);let r,s=i[0],o=0;const a=e*this.length();for(let l=1;la){const i=(o-a)/h,n=s.subtract(r),c=r.add(n.scaleInPlace(i));return this._setPointAtData(e,1-i,c,l-1,t)}s=r}return this._pointAtData}_setPointAtData(e,t,i,r,s){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=r,this._pointAtData.interpolateReady=s,s&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=n.uq.Identity();const e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){const t=e+1,i=this._tangents[e].clone(),r=this._normals[e].clone(),s=this._binormals[e].clone(),o=this._tangents[t].clone(),a=this._normals[t].clone(),l=this._binormals[t].clone(),h=n.PT.RotationQuaternionFromAxis(r,s,i),c=n.PT.RotationQuaternionFromAxis(a,l,o);n.PT.Slerp(h,c,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class d{static CreateQuadraticBezier(e,t,i,r){r=r>2?r:3;const s=[],o=(e,t,i,r)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r;for(let a=0;a<=r;a++)s.push(new n.Pq(o(a/r,e.x,t.x,i.x),o(a/r,e.y,t.y,i.y),o(a/r,e.z,t.z,i.z)));return new d(s)}static CreateCubicBezier(e,t,i,r,s){s=s>3?s:4;const o=[],a=(e,t,i,r,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*s;for(let l=0;l<=s;l++)o.push(new n.Pq(a(l/s,e.x,t.x,i.x,r.x),a(l/s,e.y,t.y,i.y,r.y),a(l/s,e.z,t.z,i.z,r.z)));return new d(o)}static CreateHermiteSpline(e,t,i,r,s){const o=[],a=1/s;for(let l=0;l<=s;l++)o.push(n.Pq.Hermite(e,t,i,r,l*a));return new d(o)}static CreateCatmullRomSpline(e,t,i){const r=[],s=1/t;let o=0;if(i){const i=e.length;for(let a=0;a{"use strict";i.d(t,{Z:()=>s});var r=i(94212);class s{constructor(e,t,i,s){this.normal=new r.Pq(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new s(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=397*e^this.d,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 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){const t=s._TmpMatrix;e.invertToRef(t);const i=t.m,r=this.normal.x,n=this.normal.y,o=this.normal.z,a=this.d,l=r*i[0]+n*i[1]+o*i[2]+a*i[3],h=r*i[4]+n*i[5]+o*i[6]+a*i[7],c=r*i[8]+n*i[9]+o*i[10]+a*i[11],u=r*i[12]+n*i[13]+o*i[14]+a*i[15];return new s(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 r=t.x-e.x,s=t.y-e.y,n=t.z-e.z,o=i.x-e.x,a=i.y-e.y,l=i.z-e.z,h=s*l-n*a,c=n*o-r*l,u=r*a-s*o,d=Math.sqrt(h*h+c*c+u*u);let f;return f=0!==d?1/d:0,this.normal.x=h*f,this.normal.y=c*f,this.normal.z=u*f,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return r.Pq.Dot(this.normal,e)<=t}signedDistanceTo(e){return r.Pq.Dot(e,this.normal)+this.d}static FromArray(e){return new s(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const r=new s(0,0,0,0);return r.copyFromPoints(e,t,i),r}static FromPositionAndNormal(e,t){const i=new s(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 r.Pq.Dot(i,t)+s}}s._TmpMatrix=r.uq.Identity()},56984:(e,t,i)=>{"use strict";function r(e){return parseInt(e.toString().replace(/\W/g,""))}function s(e,t,i=1401298e-51){return Math.abs(e-t)<=i}function n(e,t){return e===t?e:Math.random()*(t-e)+e}function o(e,t,i){return e+(t-e)*i}function a(e,t,i){let r=_(t-e,360);return r>180&&(r-=360),e+r*u(i)}function l(e,t,i){let r=0;return r=e!=t?u((i-e)/(t-e)):0,r}function h(e,t,i,r,s){const n=s*s,o=s*n;return e*(2*o-3*n+1)+i*(-2*o+3*n)+t*(o-2*n+s)+r*(o-n)}function c(e,t,i,r,s){const n=s*s;return 6*(n-s)*e+(3*n-4*s+1)*t+6*(-n+s)*i+(3*n-2*s)*r}function u(e,t=0,i=1){return Math.min(i,Math.max(t,e))}function d(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function f(e){const t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()}function p(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(0===e)return-1/0;let t=0;if(e<1){for(;e<1;)t++,e*=2;t=-t}else if(e>1)for(;e>1;)t++,e=Math.floor(e/2);return t}function _(e,t){return e-Math.floor(e/t)*t}function m(e,t,i){return(e-t)/(i-t)}function g(e,t,i){return e*(i-t)+t}function v(e,t){let i=_(t-e,360);return i>180&&(i-=360),i}function x(e,t){const i=_(e,2*t);return t-Math.abs(i-t)}function b(e,t,i){let r=u(i);return r=-2*r*r*r+3*r*r,t*r+e*(1-r)}function S(e,t,i){let r=0;return r=Math.abs(t-e)<=i?t:e+Math.sign(t-e)*i,r}function T(e,t,i){const r=v(e,t);let s=0;return s=-iu,DeltaAngle:()=>v,Denormalize:()=>g,ExtractAsInt:()=>r,Hermite:()=>h,Hermite1stDerivative:()=>c,HighestCommonFactor:()=>E,ILog2:()=>p,InverseLerp:()=>l,Lerp:()=>o,LerpAngle:()=>a,MoveTowards:()=>S,MoveTowardsAngle:()=>T,Normalize:()=>m,NormalizeRadians:()=>d,PercentToRange:()=>y,PingPong:()=>x,RandomRange:()=>n,RangeToPercent:()=>C,Repeat:()=>_,SmoothStep:()=>b,ToHex:()=>f,WithinEpsilon:()=>s})},29962:(e,t,i)=>{"use strict";i.d(t,{o:()=>r});class r{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){let e=0|this.width;return e=397*e^this.height,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 r(this.width*e,this.height*t)}clone(){return new r(this.width,this.height)}equals(e){return!!e&&this.width===e.width&&this.height===e.height}get surface(){return this.width*this.height}static Zero(){return new r(0,0)}add(e){return new r(this.width+e.width,this.height+e.height)}subtract(e){return new r(this.width-e.width,this.height-e.height)}scale(e){return new r(this.width*e,this.height*e)}static Lerp(e,t,i){const s=e.width+(t.width-e.width)*i,n=e.height+(t.height-e.height)*i;return new r(s,n)}}},94212:(e,t,i)=>{"use strict";i.d(t,{AA:()=>m,I9:()=>c,IU:()=>d,PT:()=>f,Pq:()=>u,uq:()=>p});var r=i(34910),s=i(34130),n=i(56225),o=i(82352),a=i(34268),l=i(56984);const h=e=>parseInt(e.toString().replace(/\W/g,""));class c{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let e=h(this.x);return e=397*e^h(this.y),e}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return c.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 c(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 c(this.x+e.x,this.y+e.y)}subtract(e){return new c(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 c(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 c(this.x*e,this.y*t)}divide(e){return new c(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 c(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,i){return i.x=this.x-e,i.y=this.y-t,i}negate(){return new c(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.x=-this.x,e.y=-this.y,e}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){return new c(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=r.bH){return e&&(0,l.WithinEpsilon)(this.x,e.x,t)&&(0,l.WithinEpsilon)(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new c(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 c(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e}rotateToRef(e,t){const i=Math.cos(e),r=Math.sin(e),s=i*this.x-r*this.y,n=r*this.x+i*this.y;return t.x=s,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 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new c;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t&&(e.x=this.x,e.y=this.y),this.scaleToRef(1/t,e)}clone(){return new c(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new c(0,0)}static One(){return new c(1,1)}static Random(e=0,t=1){return new c((0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats((0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t))}static get ZeroReadOnly(){return c._ZeroReadOnly}static FromArray(e,t=0){return new c(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static FromFloatsToRef(e,t,i){return i.copyFromFloats(e,t),i}static CatmullRom(e,t,i,r,s){const n=s*s,o=s*n,a=.5*(2*t.x+(-e.x+i.x)*s+(2*e.x-5*t.x+4*i.x-r.x)*n+(-e.x+3*t.x-3*i.x+r.x)*o),l=.5*(2*t.y+(-e.y+i.y)*s+(2*e.y-5*t.y+4*i.y-r.y)*n+(-e.y+3*t.y-3*i.y+r.y)*o);return new c(a,l)}static ClampToRef(e,t,i,r){return r.x=(0,l.Clamp)(e.x,t.x,i.x),r.y=(0,l.Clamp)(e.y,t.y,i.y),r}static Clamp(e,t,i){const r=(0,l.Clamp)(e.x,t.x,i.x),s=(0,l.Clamp)(e.y,t.y,i.y);return new c(r,s)}static Hermite(e,t,i,r,s){const n=s*s,o=s*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+s,u=o-n,d=e.x*a+i.x*l+t.x*h+r.x*u,f=e.y*a+i.y*l+t.y*h+r.y*u;return new c(d,f)}static Hermite1stDerivative(e,t,i,r,s){return this.Hermite1stDerivativeToRef(e,t,i,r,s,new c)}static Hermite1stDerivativeToRef(e,t,i,r,s,n){const o=s*s;return n.x=6*(o-s)*e.x+(3*o-4*s+1)*t.x+6*(-o+s)*i.x+(3*o-2*s)*r.x,n.y=6*(o-s)*e.y+(3*o-4*s+1)*t.y+6*(-o+s)*i.y+(3*o-2*s)*r.y,n}static Lerp(e,t,i){return c.LerpToRef(e,t,i,new c)}static LerpToRef(e,t,i,r){return r.x=e.x+(t.x-e.x)*i,r.y=e.y+(t.y-e.y)*i,r}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){return c.NormalizeToRef(e,new c)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=e.xt.x?e.x:t.x,r=e.y>t.y?e.y:t.y;return new c(i,r)}static Transform(e,t){return c.TransformToRef(e,t,new c)}static TransformToRef(e,t,i){const r=t.m,s=e.x*r[0]+e.y*r[4]+r[12],n=e.x*r[1]+e.y*r[5]+r[13];return i.x=s,i.y=n,i}static PointInTriangle(e,t,i,r){const s=.5*(-i.y*r.x+t.y*(-i.x+r.x)+t.x*(i.y-r.y)+i.x*r.y),n=s<0?-1:1,o=(t.y*r.x-t.x*r.y+(r.y-t.y)*e.x+(t.x-r.x)*e.y)*n,a=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*n;return o>0&&a>0&&o+a<2*s*n}static Distance(e,t){return Math.sqrt(c.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,r=e.y-t.y;return i*i+r*r}static Center(e,t){return c.CenterToRef(e,t,new c)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){const r=c.DistanceSquared(t,i);if(0===r)return c.Distance(e,t);const s=i.subtract(t),n=Math.max(0,Math.min(1,c.Dot(e.subtract(t),s)/r)),o=t.add(s.multiplyByFloats(n,n));return c.Distance(e,o)}}c._ZeroReadOnly=c.Zero(),Object.defineProperties(c.prototype,{dimension:{value:[2]},rank:{value:1}});class u{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(){let e=h(this._x);return e=397*e^h(this._y),e=397*e^h(this._z),e}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 u.FromArrayToRef(e,t,this),this}toQuaternion(){return f.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 u(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._isDirty=!0,t}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new u(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 u(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,r){return r._x=this._x-e,r._y=this._y-t,r._z=this._z-i,r._isDirty=!0,r}negate(){return new u(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e._x=-1*this._x,e._y=-1*this._y,e._z=-1*this._z,e._isDirty=!0,e}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new u(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._isDirty=!0,t}getNormalToRef(e){const t=this.length();let i=Math.acos(this.y/t);const r=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const s=t*Math.sin(i)*Math.cos(r),n=t*Math.cos(i),o=t*Math.sin(i)*Math.sin(r);return e.set(s,n,o),e}applyRotationQuaternionToRef(e,t){const i=this._x,r=this._y,s=this._z,n=e._x,o=e._y,a=e._z,l=e._w,h=2*(o*s-a*r),c=2*(a*i-n*s),u=2*(n*r-o*i);return t._x=i+l*h+o*u-a*c,t._y=r+l*c+a*h-n*u,t._z=s+l*u+n*c-o*h,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new u)}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._isDirty=!0,t}projectOnPlane(e,t){return this.projectOnPlaneToRef(e,t,new u)}projectOnPlaneToRef(e,t,i){const r=e.normal,s=e.d,n=_.Vector3[0];this.subtractToRef(t,n),n.normalize();const o=u.Dot(n,r);if(Math.abs(o)<1e-10)i.setAll(1/0);else{const e=-(u.Dot(t,r)+s)/o,a=n.scaleInPlace(e);t.addToRef(a,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=r.bH){return e&&(0,l.WithinEpsilon)(this._x,e._x,t)&&(0,l.WithinEpsilon)(this._y,e._y,t)&&(0,l.WithinEpsilon)(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t._x=this._x*e._x,t._y=this._y*e._y,t._z=this._z*e._z,t._isDirty=!0,t}multiplyByFloats(e,t,i){return new u(this._x*e,this._y*t,this._z*i)}divide(e){return new u(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t._x=this._x/e._x,t._y=this._y/e._y,t._z=this._z/e._z,t._isDirty=!0,t}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return ethis._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),i=Math.abs(this._y);if(!(0,l.WithinEpsilon)(t,i,e))return!0;const r=Math.abs(this._z);return!(0,l.WithinEpsilon)(t,r,e)||!(0,l.WithinEpsilon)(i,r,e)}get isNonUniform(){const e=Math.abs(this._x);return e!==Math.abs(this._y)||e!==Math.abs(this._z)}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 u(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 u(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("xyz"===(e=e.toLowerCase()))return this;const t=_.Vector3[0].copyFrom(this);return this.x=t[e[0]],this.y=t[e[1]],this.z=t[e[2]],this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(_.Matrix[0]),u.TransformCoordinatesToRef(this,_.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,_.Vector3[0]),_.Vector3[0].rotateByQuaternionToRef(e,_.Vector3[0]),t.addToRef(_.Vector3[0],i),i}cross(e){return u.CrossToRef(this,e,new u)}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new u)}normalizeToRef(e){const t=this.length();return 0===t||1===t?(e._x=this._x,e._y=this._y,e._z=this._z,e._isDirty=!0,e):this.scaleToRef(1/t,e)}clone(){return new u(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,r){const s=u.Dot(e,i);return(s-r)/(s-u.Dot(t,i))}static GetAngleBetweenVectors(e,t,i){const r=e.normalizeToRef(_.Vector3[1]),s=t.normalizeToRef(_.Vector3[2]);let n=u.Dot(r,s);n=(0,l.Clamp)(n,-1,1);const o=Math.acos(n),a=_.Vector3[3];return u.CrossToRef(r,s,a),u.Dot(a,i)>0?isNaN(o)?0:o:isNaN(o)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(e,t,i){_.Vector3[0].copyFrom(e);const r=_.Vector3[0];_.Vector3[1].copyFrom(t);const s=_.Vector3[1];_.Vector3[2].copyFrom(i);const n=_.Vector3[2],o=_.Vector3[3],a=_.Vector3[4];r.normalize(),s.normalize(),n.normalize(),u.CrossToRef(n,r,o),u.CrossToRef(o,n,a);const h=Math.atan2(u.Dot(s,o),u.Dot(s,a));return(0,l.NormalizeRadians)(h)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const r=m.Vector3[0];return t.subtractToRef(e,r),i._y=Math.atan2(r.x,r.z)||0,i._x=Math.atan2(Math.sqrt(r.x**2+r.z**2),r.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){const i=u.Zero();return u.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,s){i=(0,l.Clamp)(i,0,1);const n=_.Vector3[0],o=_.Vector3[1];n.copyFrom(e);const a=n.length();n.normalizeFromLength(a),o.copyFrom(t);const h=o.length();o.normalizeFromLength(h);const c=u.Dot(n,o);let d,f;if(c<1-r.bH){const e=Math.acos(c),t=1/Math.sin(e);d=Math.sin((1-i)*e)*t,f=Math.sin(i*e)*t}else d=1-i,f=i;return n.scaleInPlace(d),o.scaleInPlace(f),s.copyFrom(n).addInPlace(o),s.scaleInPlace((0,l.Lerp)(a,h,i)),s}static SmoothToRef(e,t,i,r,s){return u.SlerpToRef(e,t,0===r?1:i/r,s),s}static FromArray(e,t=0){return new u(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return u.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 u.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,r){return r.copyFromFloats(e,t,i),r}static Zero(){return new u(0,0,0)}static One(){return new u(1,1,1)}static Up(){return new u(0,1,0)}static get UpReadOnly(){return u._UpReadOnly}static get DownReadOnly(){return u._DownReadOnly}static get RightReadOnly(){return u._RightReadOnly}static get LeftReadOnly(){return u._LeftReadOnly}static get LeftHandedForwardReadOnly(){return u._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return u._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return u._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return u._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return u._ZeroReadOnly}static get OneReadOnly(){return u._OneReadOnly}static Down(){return new u(0,-1,0)}static Forward(e=!1){return new u(0,0,e?-1:1)}static Backward(e=!1){return new u(0,0,e?1:-1)}static Right(){return new u(1,0,0)}static Left(){return new u(-1,0,0)}static Random(e=0,t=1){return new u((0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats((0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t))}static TransformCoordinates(e,t){const i=u.Zero();return u.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return u.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,r,s){const n=r.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],a=e*n[1]+t*n[5]+i*n[9]+n[13],l=e*n[2]+t*n[6]+i*n[10]+n[14],h=1/(e*n[3]+t*n[7]+i*n[11]+n[15]);return s._x=o*h,s._y=a*h,s._z=l*h,s._isDirty=!0,s}static TransformNormal(e,t){const i=u.Zero();return u.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,r,s){const n=r.m;return s._x=e*n[0]+t*n[4]+i*n[8],s._y=e*n[1]+t*n[5]+i*n[9],s._z=e*n[2]+t*n[6]+i*n[10],s._isDirty=!0,s}static CatmullRom(e,t,i,r,s){const n=s*s,o=s*n,a=.5*(2*t._x+(-e._x+i._x)*s+(2*e._x-5*t._x+4*i._x-r._x)*n+(-e._x+3*t._x-3*i._x+r._x)*o),l=.5*(2*t._y+(-e._y+i._y)*s+(2*e._y-5*t._y+4*i._y-r._y)*n+(-e._y+3*t._y-3*i._y+r._y)*o),h=.5*(2*t._z+(-e._z+i._z)*s+(2*e._z-5*t._z+4*i._z-r._z)*n+(-e._z+3*t._z-3*i._z+r._z)*o);return new u(a,l,h)}static Clamp(e,t,i){const r=new u;return u.ClampToRef(e,t,i,r),r}static ClampToRef(e,t,i,r){let s=e._x;s=s>i._x?i._x:s,s=si._y?i._y:n,n=ni._z?i._z:o,o=o0&&I<0?(O.copyFrom(o),D=t,w=i):I>0&&M<0?(O.copyFrom(h),D=i,w=s):(O.copyFrom(a).scaleInPlace(-1),D=s,w=t);const N=_.Vector3[9],F=_.Vector3[4];if(D.subtractToRef(S,E),w.subtractToRef(S,N),u.CrossToRef(E,N,F),!(u.Dot(F,c)<0))return n.copyFrom(S),Math.abs(v*x);const L=_.Vector3[5];u.CrossToRef(O,F,L),L.normalize();const B=_.Vector3[9];B.copyFrom(D).subtractInPlace(S);const V=B.length();if(Vthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this}minimizeInPlaceFromFloats(e,t,i,r){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this.z=Math.min(i,this.z),this.w=Math.min(r,this.w),this}maximizeInPlaceFromFloats(e,t,i,r){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this.z=Math.max(i,this.z),this.w=Math.max(r,this.w),this}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e.z=Math.floor(this.z),e.w=Math.floor(this.w),e}floor(){return new d(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 d(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 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new d)}normalizeToRef(e){const t=this.length();return 0===t||1===t?(e.x=this.x,e.y=this.y,e.z=this.z,e.w=this.w,e):this.scaleToRef(1/t,e)}toVector3(){return new u(this.x,this.y,this.z)}clone(){return new d(this.x,this.y,this.z,this.w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.x=this.y=this.z=this.w=e,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}static FromArray(e,t){return t||(t=0),new d(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 d.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,r,s){return s.x=e,s.y=t,s.z=i,s.w=r,s}static Zero(){return new d(0,0,0,0)}static One(){return new d(1,1,1,1)}static Random(e=0,t=1){return new d((0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t))}static RandomToRef(e=0,t=1,i){return i.x=(0,l.RandomRange)(e,t),i.y=(0,l.RandomRange)(e,t),i.z=(0,l.RandomRange)(e,t),i.w=(0,l.RandomRange)(e,t),i}static Clamp(e,t,i){return d.ClampToRef(e,t,i,new d)}static ClampToRef(e,t,i,r){return r.x=(0,l.Clamp)(e.x,t.x,i.x),r.y=(0,l.Clamp)(e.y,t.y,i.y),r.z=(0,l.Clamp)(e.z,t.z,i.z),r.w=(0,l.Clamp)(e.w,t.w,i.w),r}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return d._ZeroReadOnly}static Normalize(e){return d.NormalizeToRef(e,new d)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=new d;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new d;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(d.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,r=e.y-t.y,s=e.z-t.z,n=e.w-t.w;return i*i+r*r+s*s+n*n}static Center(e,t){return d.CenterToRef(e,t,new d)}static CenterToRef(e,t,i){return i.x=(e.x+t.x)/2,i.y=(e.y+t.y)/2,i.z=(e.z+t.z)/2,i.w=(e.w+t.w)/2,i}static TransformCoordinates(e,t){return d.TransformCoordinatesToRef(e,t,new d)}static TransformCoordinatesToRef(e,t,i){return d.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,r,s){const n=r.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],a=e*n[1]+t*n[5]+i*n[9]+n[13],l=e*n[2]+t*n[6]+i*n[10]+n[14],h=e*n[3]+t*n[7]+i*n[11]+n[15];return s.x=o,s.y=a,s.z=l,s.w=h,s}static TransformNormal(e,t){return d.TransformNormalToRef(e,t,new d)}static TransformNormalToRef(e,t,i){const r=t.m,s=e.x*r[0]+e.y*r[4]+e.z*r[8],n=e.x*r[1]+e.y*r[5]+e.z*r[9],o=e.x*r[2]+e.y*r[6]+e.z*r[10];return i.x=s,i.y=n,i.z=o,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,r,s,n){const o=s.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=r,n}static FromVector3(e,t=0){return new d(e._x,e._y,e._z,t)}static Dot(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w}}d._ZeroReadOnly=d.Zero(),Object.defineProperties(d.prototype,{dimension:{value:[4]},rank:{value:1}});class f{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,r=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=r}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=h(this._x);return e=397*e^h(this._y),e=397*e^h(this._z),e=397*e^h(this._w),e}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 f.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=r.bH){return e&&(0,l.WithinEpsilon)(this._x,e._x,t)&&(0,l.WithinEpsilon)(this._y,e._y,t)&&(0,l.WithinEpsilon)(this._z,e._z,t)&&(0,l.WithinEpsilon)(this._w,e._w,t)}clone(){return new f(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,i,r){return this._x=e,this._y=t,this._z=i,this._w=r,this._isDirty=!0,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new f(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t}addInPlaceFromFloats(e,t,i,r){return this._x+=e,this._y+=t,this._z+=i,this._w+=r,this._isDirty=!0,this}subtractToRef(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t}subtractFromFloats(e,t,i,r){return this.subtractFromFloatsToRef(e,t,i,r,new f)}subtractFromFloatsToRef(e,t,i,r,s){return s._x=this._x-e,s._y=this._y-t,s._z=this._z-i,s._w=this._w-r,s._isDirty=!0,s}subtract(e){return new f(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 f(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 f(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,r=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,s=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,r,s,n),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,i,r){return this._x*=e,this._y*=t,this._z*=i,this._w*=r,this._isDirty=!0,this}divide(e){throw new ReferenceError("Can not divide a quaternion")}divideToRef(e,t){throw new ReferenceError("Can not divide a quaternion")}divideInPlace(e){throw new ReferenceError("Can not divide a quaternion")}minimizeInPlace(){throw new ReferenceError("Can not minimize a quaternion")}minimizeInPlaceFromFloats(){throw new ReferenceError("Can not minimize a quaternion")}maximizeInPlace(){throw new ReferenceError("Can not maximize a quaternion")}maximizeInPlaceFromFloats(){throw new ReferenceError("Can not maximize a quaternion")}negate(){return this.negateToRef(new f)}negateInPlace(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this}negateToRef(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e}equalsToFloats(e,t,i,r){return this._x===e&&this._y===t&&this._z===i&&this._w===r}floorToRef(e){throw new ReferenceError("Can not floor a quaternion")}floor(){throw new ReferenceError("Can not floor a quaternion")}fractToRef(e){throw new ReferenceError("Can not fract a quaternion")}fract(){throw new ReferenceError("Can not fract a quaternion")}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new f(-this._x,-this._y,-this._z,this._w)}invert(){const e=this.conjugate(),t=this.lengthSquared();return 0==t||1==t||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();const e=this.lengthSquared();return 0==e||1==e||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 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new f(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){const e=u.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,r=this._y,s=this._w,n=r*t-i*s,o=.4999999;if(n<-o)e._y=2*Math.atan2(r,s),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(n>o)e._y=2*Math.atan2(r,s),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const o=s*s,a=t*t,l=i*i,h=r*r;e._z=Math.atan2(2*(i*r+t*s),-a-l+h+o),e._x=Math.asin(-2*n),e._y=Math.atan2(2*(t*i+r*s),a-l-h+o),e._isDirty=!0}return e}toAlphaBetaGammaToRef(e){const t=this._z,i=this._x,r=this._y,s=this._w,n=Math.sqrt(i*i+r*r),o=Math.sqrt(t*t+s*s),a=2*Math.atan2(n,o),l=2*Math.atan2(t,s),h=2*Math.atan2(r,i),c=(l+h)/2,u=(l-h)/2;return e.set(u,a,c),e}toRotationMatrix(e){return p.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return f.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 f;return f.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,r=i[0],s=i[4],n=i[8],o=i[1],a=i[5],l=i[9],h=i[2],c=i[6],u=i[10],d=r+a+u;let f;return d>0?(f=.5/Math.sqrt(d+1),t._w=.25/f,t._x=(c-l)*f,t._y=(n-h)*f,t._z=(o-s)*f,t._isDirty=!0):r>a&&r>u?(f=2*Math.sqrt(1+r-a-u),t._w=(c-l)/f,t._x=.25*f,t._y=(s+o)/f,t._z=(n+h)/f,t._isDirty=!0):a>u?(f=2*Math.sqrt(1+a-r-u),t._w=(n-h)/f,t._x=(s+o)/f,t._y=.25*f,t._z=(l+c)/f,t._isDirty=!0):(f=2*Math.sqrt(1+u-r-a),t._w=(o-s)/f,t._x=(n+h)/f,t._y=(l+c)/f,t._z=.25*f,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){const r=f.Dot(e,t);return 1-r*r<=i}static SmoothToRef(e,t,i,r,s){let n=0===r?1:i/r;return n=(0,l.Clamp)(n,0,1),f.SlerpToRef(e,t,n,s),s}static Zero(){return new f(0,0,0,0)}static Inverse(e){return new f(-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 f(0,0,0,1)}static IsIdentity(e){return e&&0===e._x&&0===e._y&&0===e._z&&1===e._w}static RotationAxis(e,t){return f.RotationAxisToRef(e,t,new f)}static RotationAxisToRef(e,t,i){i._w=Math.cos(t/2);const r=Math.sin(t/2)/e.length();return i._x=e._x*r,i._y=e._y*r,i._z=e._z*r,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new f(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromFloatsToRef(e,t,i,r,s){return s.copyFromFloats(e,t,i,r),s}static FromEulerAngles(e,t,i){const r=new f;return f.RotationYawPitchRollToRef(t,e,i,r),r}static FromEulerAnglesToRef(e,t,i,r){return f.RotationYawPitchRollToRef(t,e,i,r),r}static FromEulerVector(e){const t=new f;return f.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return f.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,s=r.bH){const n=u.Dot(e,t)+1;return nMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(u.CrossToRef(e,t,m.Vector3[0]),i.set(m.Vector3[0].x,m.Vector3[0].y,m.Vector3[0].z,n)),i.normalize()}static RotationYawPitchRoll(e,t,i){const r=new f;return f.RotationYawPitchRollToRef(e,t,i,r),r}static RotationYawPitchRollToRef(e,t,i,r){const s=.5*i,n=.5*t,o=.5*e,a=Math.sin(s),l=Math.cos(s),h=Math.sin(n),c=Math.cos(n),u=Math.sin(o),d=Math.cos(o);return r._x=d*h*l+u*c*a,r._y=u*c*l-d*h*a,r._z=d*c*a-u*h*l,r._w=d*c*l+u*h*a,r._isDirty=!0,r}static RotationAlphaBetaGamma(e,t,i){const r=new f;return f.RotationAlphaBetaGammaToRef(e,t,i,r),r}static RotationAlphaBetaGammaToRef(e,t,i,r){const s=.5*(i+e),n=.5*(i-e),o=.5*t;return r._x=Math.cos(n)*Math.sin(o),r._y=Math.sin(n)*Math.sin(o),r._z=Math.sin(s)*Math.cos(o),r._w=Math.cos(s)*Math.cos(o),r._isDirty=!0,r}static RotationQuaternionFromAxis(e,t,i){const r=new f(0,0,0,0);return f.RotationQuaternionFromAxisToRef(e,t,i,r),r}static RotationQuaternionFromAxisToRef(e,t,i,r){const s=_.Matrix[0];return e=e.normalizeToRef(_.Vector3[0]),t=t.normalizeToRef(_.Vector3[1]),i=i.normalizeToRef(_.Vector3[2]),p.FromXYZAxesToRef(e,t,i,s),f.FromRotationMatrixToRef(s,r),r}static FromLookDirectionLH(e,t){const i=new f;return f.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const r=_.Matrix[0];return p.LookDirectionLHToRef(e,t,r),f.FromRotationMatrixToRef(r,i),i}static FromLookDirectionRH(e,t){const i=new f;return f.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const r=_.Matrix[0];return p.LookDirectionRHToRef(e,t,r),f.FromRotationMatrixToRef(r,i)}static Slerp(e,t,i){const r=f.Identity();return f.SlerpToRef(e,t,i,r),r}static SlerpToRef(e,t,i,r){let s,n,o=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,a=!1;if(o<0&&(a=!0,o=-o),o>.999999)n=1-i,s=a?-i:i;else{const e=Math.acos(o),t=1/Math.sin(e);n=Math.sin((1-i)*e)*t,s=a?-Math.sin(i*e)*t:Math.sin(i*e)*t}return r._x=n*e._x+s*t._x,r._y=n*e._y+s*t._y,r._z=n*e._z+s*t._z,r._w=n*e._w+s*t._w,r._isDirty=!0,r}static Hermite(e,t,i,r,s){const n=s*s,o=s*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+s,c=o-n,u=e._x*a+i._x*l+t._x*h+r._x*c,d=e._y*a+i._y*l+t._y*h+r._y*c,p=e._z*a+i._z*l+t._z*h+r._z*c,_=e._w*a+i._w*l+t._w*h+r._w*c;return new f(u,d,p,_)}static Hermite1stDerivative(e,t,i,r,s){const n=new f;return this.Hermite1stDerivativeToRef(e,t,i,r,s,n),n}static Hermite1stDerivativeToRef(e,t,i,r,s,n){const o=s*s;return n._x=6*(o-s)*e._x+(3*o-4*s+1)*t._x+6*(-o+s)*i._x+(3*o-2*s)*r._x,n._y=6*(o-s)*e._y+(3*o-4*s+1)*t._y+6*(-o+s)*i._y+(3*o-2*s)*r._y,n._z=6*(o-s)*e._z+(3*o-4*s+1)*t._z+6*(-o+s)*i._z+(3*o-2*s)*r._z,n._w=6*(o-s)*e._w+(3*o-4*s+1)*t._w+6*(-o+s)*i._w+(3*o-2*s)*r._w,n._isDirty=!0,n}static Normalize(e){const t=f.Zero();return f.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){const r=new f;return f.ClampToRef(e,t,i,r),r}static ClampToRef(e,t,i,r){return r.copyFromFloats((0,l.Clamp)(e.x,t.x,i.x),(0,l.Clamp)(e.y,t.y,i.y),(0,l.Clamp)(e.z,t.z,i.z),(0,l.Clamp)(e.w,t.w,i.w))}static Random(e=0,t=1){return new f((0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats((0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t),(0,l.RandomRange)(e,t),(0,l.RandomRange)(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(f.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,r=e.y-t.y,s=e.z-t.z,n=e.w-t.w;return i*i+r*r+s*s+n*n}static Center(e,t){return f.CenterToRef(e,t,f.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(f.prototype,{dimension:{value:[4]},rank:{value:1}});class p{static get Use64Bits(){return o.I.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=p._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,r=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=!this._isIdentity&&t,this._isIdentity3x2Dirty=!this._isIdentity3x2&&r}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,o.I.MatrixTrackPrecisionChange&&o.I.MatrixTrackedMatrices.push(this),this._m=new o.I.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;const e=this._m;this._isIdentity=1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]||0!==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]?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(!0===this._isIdentity)return 1;const e=this._m,t=e[0],i=e[1],r=e[2],s=e[3],n=e[4],o=e[5],a=e[6],l=e[7],h=e[8],c=e[9],u=e[10],d=e[11],f=e[12],p=e[13],_=e[14],m=e[15],g=u*m-_*d,v=c*m-p*d,x=c*_-p*u,b=h*m-f*d,S=h*_-u*f,T=h*p-f*c;return t*+(o*g-a*v+l*x)+i*-(n*g-a*b+l*S)+r*+(n*v-o*b+l*T)+s*-(n*x-o*S+a*T)}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]}\n${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]}\n${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]}\n${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(e=null,t=0){if(!e)return this._m;const i=this._m;for(let r=0;r<16;r++)e[t+r]=i[r];return this}asArray(){return this._m}fromArray(e,t=0){return p.FromArrayToRef(e,t,this)}copyFromFloats(...e){return p.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 p.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 p;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,r=t._m,s=e.m;for(let e=0;e<16;e++)r[e]=i[e]+s[e];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,i=e.m;return t[0]+=i[0],t[1]+=i[1],t[2]+=i[2],t[3]+=i[3],t[4]+=i[4],t[5]+=i[5],t[6]+=i[6],t[7]+=i[7],t[8]+=i[8],t[9]+=i[9],t[10]+=i[10],t[11]+=i[11],t[12]+=i[12],t[13]+=i[13],t[14]+=i[14],t[15]+=i[15],this.markAsUpdated(),this}addInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];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 e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractToRef(e,t){const i=this._m,r=e.m,s=t._m;for(let e=0;e<16;e++)s[e]=i[e]-r[e];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new p)}subtractFromFloatsToRef(...e){const t=e.pop(),i=this._m,r=t._m,s=e;for(let e=0;e<16;e++)r[e]=i[e]-s[e];return t.markAsUpdated(),t}invertToRef(e){if(!0===this._isIdentity)return p.IdentityToRef(e),e;const t=this._m,i=t[0],r=t[1],s=t[2],n=t[3],o=t[4],a=t[5],l=t[6],h=t[7],c=t[8],u=t[9],d=t[10],f=t[11],_=t[12],m=t[13],g=t[14],v=t[15],x=d*v-g*f,b=u*v-m*f,S=u*g-m*d,T=c*v-_*f,C=c*g-d*_,y=c*m-_*u,E=+(a*x-l*b+h*S),P=-(o*x-l*T+h*C),A=+(o*b-a*T+h*y),R=-(o*S-a*C+l*y),I=i*E+r*P+s*A+n*R;if(0===I)return e.copyFrom(this),e;const M=1/I,O=l*v-g*h,D=a*v-m*h,w=a*g-m*l,N=o*v-_*h,F=o*g-_*l,L=o*m-_*a,B=l*f-d*h,V=a*f-u*h,k=a*d-u*l,U=o*f-c*h,G=o*d-c*l,z=o*u-c*a,W=-(r*x-s*b+n*S),H=+(i*x-s*T+n*C),X=-(i*b-r*T+n*y),q=+(i*S-r*C+s*y),Y=+(r*O-s*D+n*w),K=-(i*O-s*N+n*F),j=+(i*D-r*N+n*L),$=-(i*w-r*F+s*L),Q=-(r*B-s*V+n*k),Z=+(i*B-s*U+n*G),J=-(i*V-r*U+n*z),ee=+(i*k-r*G+s*z);return p.FromValuesToRef(E*M,W*M,Y*M,Q*M,P*M,H*M,K*M,Z*M,A*M,X*M,j*M,J*M,R*M,q*M,$*M,ee*M,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 u(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 p.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]),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 p;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]*=i[e];return this.markAsUpdated(),this}multiplyByFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e[i];return this.markAsUpdated(),this}multiplyByFloatsToRef(...e){const t=e.pop(),i=this._m,r=t._m,s=e;for(let e=0;e<16;e++)r[e]=i[e]*s[e];return t.markAsUpdated(),t}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,i){const r=this._m,s=e.m,n=r[0],o=r[1],a=r[2],l=r[3],h=r[4],c=r[5],u=r[6],d=r[7],f=r[8],p=r[9],_=r[10],m=r[11],g=r[12],v=r[13],x=r[14],b=r[15],S=s[0],T=s[1],C=s[2],y=s[3],E=s[4],P=s[5],A=s[6],R=s[7],I=s[8],M=s[9],O=s[10],D=s[11],w=s[12],N=s[13],F=s[14],L=s[15];return t[i]=n*S+o*E+a*I+l*w,t[i+1]=n*T+o*P+a*M+l*N,t[i+2]=n*C+o*A+a*O+l*F,t[i+3]=n*y+o*R+a*D+l*L,t[i+4]=h*S+c*E+u*I+d*w,t[i+5]=h*T+c*P+u*M+d*N,t[i+6]=h*C+c*A+u*O+d*F,t[i+7]=h*y+c*R+u*D+d*L,t[i+8]=f*S+p*E+_*I+m*w,t[i+9]=f*T+p*P+_*M+m*N,t[i+10]=f*C+p*A+_*O+m*F,t[i+11]=f*y+p*R+_*D+m*L,t[i+12]=g*S+v*E+x*I+b*w,t[i+13]=g*T+v*P+x*M+b*N,t[i+14]=g*C+v*A+x*O+b*F,t[i+15]=g*y+v*R+x*D+b*L,this}divide(e){return this.divideToRef(e,new p)}divideToRef(e,t){const i=this._m,r=e.m,s=t._m;for(let e=0;e<16;e++)s[e]=i[e]/r[e];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]/=i[e];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);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 e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);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 p)}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 e=0;e<16;e++)i[e]=-t[e];return e.markAsUpdated(),e}equals(e){const t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;const i=this.m,r=t.m;return i[0]===r[0]&&i[1]===r[1]&&i[2]===r[2]&&i[3]===r[3]&&i[4]===r[4]&&i[5]===r[5]&&i[6]===r[6]&&i[7]===r[7]&&i[8]===r[8]&&i[9]===r[9]&&i[10]===r[10]&&i[11]===r[11]&&i[12]===r[12]&&i[13]===r[13]&&i[14]===r[14]&&i[15]===r[15]}equalsWithEpsilon(e,t=0){const i=this._m,r=e.m;for(let e=0;e<16;e++)if(!(0,l.WithinEpsilon)(i[e],r[e],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 p)}floorToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=Math.floor(t[e]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new p)}fractToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=t[e]-Math.floor(t[e]);return e.markAsUpdated(),e}clone(){const e=new p;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=h(this._m[0]);for(let t=1;t<16;t++)e=397*e^h(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new f,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,r,s=!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||_.Vector3[0]).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]),r){const t=(s?r.absoluteScaling.x:r.scaling.x)<0?-1:1,i=(s?r.absoluteScaling.y:r.scaling.y)<0?-1:1,n=(s?r.absoluteScaling.z:r.scaling.z)<0?-1:1;e.x*=t,e.y*=i,e.z*=n}else this.determinant()<=0&&(e.y*=-1);if(0===e._x||0===e._y||0===e._z)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){const i=1/e._x,r=1/e._y,s=1/e._z;p.FromValuesToRef(n[0]*i,n[1]*i,n[2]*i,0,n[4]*r,n[5]*r,n[6]*r,0,n[8]*s,n[9]*s,n[10]*s,0,0,0,0,1,_.Matrix[0]),f.FromRotationMatrixToRef(_.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=4*e;return new d(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=4*e;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 p;return p.TransposeToRef(this,e),e}transposeToRef(e){return p.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,r,s){if(e<0||e>3)return this;const n=4*e;return this._m[n+0]=t,this._m[n+1]=i,this._m[n+2]=r,this._m[n+3]=s,this.markAsUpdated(),this}scale(e){const t=new p;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=_.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return p.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 p;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=_.Vector3[0];if(!this.decompose(t))return p.IdentityToRef(e),e;const i=this._m,r=1/t._x,s=1/t._y,n=1/t._z;return p.FromValuesToRef(i[0]*r,i[1]*r,i[2]*r,0,i[4]*s,i[5]*s,i[6]*s,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 p;return p.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let r=0;r<16;r++)i._m[r]=e[r+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,r){return r._m[0]=e[0+t]*i,r._m[1]=e[1+t]*i,r._m[2]=e[2+t]*i,r._m[3]=e[3+t]*i,r._m[4]=e[4+t]*i,r._m[5]=e[5+t]*i,r._m[6]=e[6+t]*i,r._m[7]=e[7+t]*i,r._m[8]=e[8+t]*i,r._m[9]=e[9+t]*i,r._m[10]=e[10+t]*i,r._m[11]=e[11+t]*i,r._m[12]=e[12+t]*i,r._m[13]=e[13+t]*i,r._m[14]=e[14+t]*i,r._m[15]=e[15+t]*i,r.markAsUpdated(),r}static get IdentityReadOnly(){return p._IdentityReadOnly}static FromValuesToRef(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m){const g=m._m;g[0]=e,g[1]=t,g[2]=i,g[3]=r,g[4]=s,g[5]=n,g[6]=o,g[7]=a,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=f,g[14]=p,g[15]=_,m.markAsUpdated()}static FromValues(e,t,i,r,s,n,o,a,l,h,c,u,d,f,_,m){const g=new p,v=g._m;return v[0]=e,v[1]=t,v[2]=i,v[3]=r,v[4]=s,v[5]=n,v[6]=o,v[7]=a,v[8]=l,v[9]=h,v[10]=c,v[11]=u,v[12]=d,v[13]=f,v[14]=_,v[15]=m,g.markAsUpdated(),g}static Compose(e,t,i){const r=new p;return p.ComposeToRef(e,t,i,r),r}static ComposeToRef(e,t,i,r){const s=r._m,n=t._x,o=t._y,a=t._z,l=t._w,h=n+n,c=o+o,u=a+a,d=n*h,f=n*c,p=n*u,_=o*c,m=o*u,g=a*u,v=l*h,x=l*c,b=l*u,S=e._x,T=e._y,C=e._z;return s[0]=(1-(_+g))*S,s[1]=(f+b)*S,s[2]=(p-x)*S,s[3]=0,s[4]=(f-b)*T,s[5]=(1-(d+g))*T,s[6]=(m+v)*T,s[7]=0,s[8]=(p+x)*C,s[9]=(m-v)*C,s[10]=(1-(d+_))*C,s[11]=0,s[12]=i._x,s[13]=i._y,s[14]=i._z,s[15]=1,r.markAsUpdated(),r}static Identity(){const e=p.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 p.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=p.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 p;return p.RotationXToRef(e,t),t}static Invert(e){const t=new p;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),r=Math.cos(e);return p.FromValuesToRef(1,0,0,0,0,r,i,0,0,-i,r,0,0,0,0,1,t),t._updateIdentityStatus(1===r&&0===i),t}static RotationY(e){const t=new p;return p.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),r=Math.cos(e);return p.FromValuesToRef(r,0,-i,0,0,1,0,0,i,0,r,0,0,0,0,1,t),t._updateIdentityStatus(1===r&&0===i),t}static RotationZ(e){const t=new p;return p.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),r=Math.cos(e);return p.FromValuesToRef(r,i,0,0,-i,r,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(1===r&&0===i),t}static RotationAxis(e,t){const i=new p;return p.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const r=Math.sin(-t),s=Math.cos(-t),n=1-s;e=e.normalizeToRef(_.Vector3[0]);const o=i._m;return o[0]=e._x*e._x*n+s,o[1]=e._x*e._y*n-e._z*r,o[2]=e._x*e._z*n+e._y*r,o[3]=0,o[4]=e._y*e._x*n+e._z*r,o[5]=e._y*e._y*n+s,o[6]=e._y*e._z*n-e._x*r,o[7]=0,o[8]=e._z*e._x*n-e._y*r,o[9]=e._z*e._y*n+e._x*r,o[10]=e._z*e._z*n+s,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 n=u.Dot(t,e),o=i._m;if(n<-1+r.bH)o[0]=-1,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=s?1:-1,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=s?-1:1,o[11]=0;else{const i=u.Cross(t,e),r=1/(1+n);o[0]=i._x*i._x*r+n,o[1]=i._y*i._x*r-i._z,o[2]=i._z*i._x*r+i._y,o[3]=0,o[4]=i._x*i._y*r+i._z,o[5]=i._y*i._y*r+n,o[6]=i._z*i._y*r-i._x,o[7]=0,o[8]=i._x*i._z*r-i._y,o[9]=i._y*i._z*r+i._x,o[10]=i._z*i._z*r+n,o[11]=0}return o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const r=new p;return p.RotationYawPitchRollToRef(e,t,i,r),r}static RotationYawPitchRollToRef(e,t,i,r){return f.RotationYawPitchRollToRef(e,t,i,_.Quaternion[0]),_.Quaternion[0].toRotationMatrix(r),r}static Scaling(e,t,i){const r=new p;return p.ScalingToRef(e,t,i,r),r}static ScalingToRef(e,t,i,r){return p.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,r),r._updateIdentityStatus(1===e&&1===t&&1===i),r}static Translation(e,t,i){const r=new p;return p.TranslationToRef(e,t,i,r),r}static TranslationToRef(e,t,i,r){return p.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,r),r._updateIdentityStatus(0===e&&0===t&&0===i),r}static Lerp(e,t,i){const r=new p;return p.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){const s=r._m,n=e.m,o=t.m;for(let e=0;e<16;e++)s[e]=n[e]*(1-i)+o[e]*i;return r.markAsUpdated(),r}static DecomposeLerp(e,t,i){const r=new p;return p.DecomposeLerpToRef(e,t,i,r),r}static DecomposeLerpToRef(e,t,i,r){const s=_.Vector3[0],n=_.Quaternion[0],o=_.Vector3[1];e.decompose(s,n,o);const a=_.Vector3[2],l=_.Quaternion[1],h=_.Vector3[3];t.decompose(a,l,h);const c=_.Vector3[4];u.LerpToRef(s,a,i,c);const d=_.Quaternion[2];f.SlerpToRef(n,l,i,d);const m=_.Vector3[5];return u.LerpToRef(o,h,i,m),p.ComposeToRef(c,d,m,r),r}static LookAtLH(e,t,i){const r=new p;return p.LookAtLHToRef(e,t,i,r),r}static LookAtLHToRef(e,t,i,r){const s=_.Vector3[0],n=_.Vector3[1],o=_.Vector3[2];t.subtractToRef(e,o),o.normalize(),u.CrossToRef(i,o,s);const a=s.lengthSquared();0===a?s.x=1:s.normalizeFromLength(Math.sqrt(a)),u.CrossToRef(o,s,n),n.normalize();const l=-u.Dot(s,e),h=-u.Dot(n,e),c=-u.Dot(o,e);return p.FromValuesToRef(s._x,n._x,o._x,0,s._y,n._y,o._y,0,s._z,n._z,o._z,0,l,h,c,1,r),r}static LookAtRH(e,t,i){const r=new p;return p.LookAtRHToRef(e,t,i,r),r}static LookAtRHToRef(e,t,i,r){const s=_.Vector3[0],n=_.Vector3[1],o=_.Vector3[2];e.subtractToRef(t,o),o.normalize(),u.CrossToRef(i,o,s);const a=s.lengthSquared();0===a?s.x=1:s.normalizeFromLength(Math.sqrt(a)),u.CrossToRef(o,s,n),n.normalize();const l=-u.Dot(s,e),h=-u.Dot(n,e),c=-u.Dot(o,e);return p.FromValuesToRef(s._x,n._x,o._x,0,s._y,n._y,o._y,0,s._z,n._z,o._z,0,l,h,c,1,r),r}static LookDirectionLH(e,t){const i=new p;return p.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const r=_.Vector3[0];r.copyFrom(e),r.scaleInPlace(-1);const s=_.Vector3[1];return u.CrossToRef(t,r,s),p.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,r._x,r._y,r._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new p;return p.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const r=_.Vector3[2];return u.CrossToRef(t,e,r),p.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,r,s){const n=new p;return p.OrthoLHToRef(e,t,i,r,n,s),n}static OrthoLHToRef(e,t,i,r,s,n){const o=2/e,a=2/t,l=2/(r-i),h=-(r+i)/(r-i);return p.FromValuesToRef(o,0,0,0,0,a,0,0,0,0,l,0,0,0,h,1,s),n&&s.multiplyToRef(g,s),s._updateIdentityStatus(1===o&&1===a&&1===l&&0===h),s}static OrthoOffCenterLH(e,t,i,r,s,n,o){const a=new p;return p.OrthoOffCenterLHToRef(e,t,i,r,s,n,a,o),a}static OrthoOffCenterLHToRef(e,t,i,r,s,n,o,a){const l=2/(t-e),h=2/(r-i),c=2/(n-s),u=-(n+s)/(n-s),d=(e+t)/(e-t),f=(r+i)/(i-r);return p.FromValuesToRef(l,0,0,0,0,h,0,0,0,0,c,0,d,f,u,1,o),a&&o.multiplyToRef(g,o),o.markAsUpdated(),o}static ObliqueOffCenterLHToRef(e,t,i,r,s,n,o,a,l,h,c){const u=-o*Math.cos(a),d=-o*Math.sin(a);return p.TranslationToRef(0,0,-l,_.Matrix[1]),p.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,_.Matrix[0]),_.Matrix[1].multiplyToRef(_.Matrix[0],_.Matrix[0]),p.TranslationToRef(0,0,l,_.Matrix[1]),_.Matrix[0].multiplyToRef(_.Matrix[1],_.Matrix[0]),p.OrthoOffCenterLHToRef(e,t,i,r,s,n,h,c),_.Matrix[0].multiplyToRef(h,h),h}static OrthoOffCenterRH(e,t,i,r,s,n,o){const a=new p;return p.OrthoOffCenterRHToRef(e,t,i,r,s,n,a,o),a}static OrthoOffCenterRHToRef(e,t,i,r,s,n,o,a){return p.OrthoOffCenterLHToRef(e,t,i,r,s,n,o,a),o._m[10]*=-1,o}static ObliqueOffCenterRHToRef(e,t,i,r,s,n,o,a,l,h,c){const u=o*Math.cos(a),d=o*Math.sin(a);return p.TranslationToRef(0,0,l,_.Matrix[1]),p.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,_.Matrix[0]),_.Matrix[1].multiplyToRef(_.Matrix[0],_.Matrix[0]),p.TranslationToRef(0,0,-l,_.Matrix[1]),_.Matrix[0].multiplyToRef(_.Matrix[1],_.Matrix[0]),p.OrthoOffCenterRHToRef(e,t,i,r,s,n,h,c),_.Matrix[0].multiplyToRef(h,h),h}static PerspectiveLH(e,t,i,r,s,n=0){const o=new p,a=2*i/e,l=2*i/t,h=(r+i)/(r-i),c=-2*r*i/(r-i),u=Math.tan(n);return p.FromValuesToRef(a,0,0,0,0,l,0,u,0,0,h,1,0,0,c,0,o),s&&o.multiplyToRef(g,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,r,s,n=0,o=!1){const a=new p;return p.PerspectiveFovLHToRef(e,t,i,r,a,!0,s,n,o),a}static PerspectiveFovLHToRef(e,t,i,r,s,n=!0,o,a=0,l=!1){const h=i,c=r,u=1/Math.tan(.5*e),d=n?u/t:u,f=n?u:u*t,_=l&&0===h?-1:0!==c?(c+h)/(c-h):1,m=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,v=Math.tan(a);return p.FromValuesToRef(d,0,0,0,0,f,0,v,0,0,_,1,0,0,m,0,s),o&&s.multiplyToRef(g,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseLHToRef(e,t,i,r,s,n=!0,o,a=0){const l=1/Math.tan(.5*e),h=n?l/t:l,c=n?l:l*t,u=Math.tan(a);return p.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,1,0,0,1,0,s),o&&s.multiplyToRef(g,s),s._updateIdentityStatus(!1),s}static PerspectiveFovRH(e,t,i,r,s,n=0,o=!1){const a=new p;return p.PerspectiveFovRHToRef(e,t,i,r,a,!0,s,n,o),a}static PerspectiveFovRHToRef(e,t,i,r,s,n=!0,o,a=0,l=!1){const h=i,c=r,u=1/Math.tan(.5*e),d=n?u/t:u,f=n?u:u*t,_=l&&0===h?1:0!==c?-(c+h)/(c-h):-1,m=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,v=Math.tan(a);return p.FromValuesToRef(d,0,0,0,0,f,0,v,0,0,_,-1,0,0,m,0,s),o&&s.multiplyToRef(g,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseRHToRef(e,t,i,r,s,n=!0,o,a=0){const l=1/Math.tan(.5*e),h=n?l/t:l,c=n?l:l*t,u=Math.tan(a);return p.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,-1,0,0,-1,0,s),o&&s.multiplyToRef(g,s),s._updateIdentityStatus(!1),s}static GetFinalMatrix(e,t,i,r,s,n){const o=e.width,a=e.height,l=e.x,h=e.y,c=p.FromValues(o/2,0,0,0,0,-a/2,0,0,0,0,n-s,0,l+o/2,a/2+h,s,1),u=new p;return t.multiplyToRef(i,u),u.multiplyToRef(r,u),u.multiplyToRef(c,u)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return o.I.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 o.I.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new p;return p.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,r=i[0],s=i[4],n=i[8],o=i[12],a=i[1],l=i[5],h=i[9],c=i[13],u=i[2],d=i[6],f=i[10],p=i[14],_=i[3],m=i[7],g=i[11],v=i[15],x=t._m;return x[0]=r,x[1]=s,x[2]=n,x[3]=o,x[4]=a,x[5]=l,x[6]=h,x[7]=c,x[8]=u,x[9]=d,x[10]=f,x[11]=p,x[12]=_,x[13]=m,x[14]=g,x[15]=v,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new p;return p.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,r=e.normal.y,s=e.normal.z,n=-2*i,o=-2*r,a=-2*s;return p.FromValuesToRef(n*i+1,o*i,a*i,0,n*r,o*r+1,a*r,0,n*s,o*s,a*s+1,0,n*e.d,o*e.d,a*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,r){return p.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,r),r}static FromQuaternionToRef(e,t){const i=e._x*e._x,r=e._y*e._y,s=e._z*e._z,n=e._x*e._y,o=e._z*e._w,a=e._z*e._x,l=e._y*e._w,h=e._y*e._z,c=e._x*e._w;return t._m[0]=1-2*(r+s),t._m[1]=2*(n+o),t._m[2]=2*(a-l),t._m[3]=0,t._m[4]=2*(n-o),t._m[5]=1-2*(s+i),t._m[6]=2*(h+c),t._m[7]=0,t._m[8]=2*(a+l),t._m[9]=2*(h-c),t._m[10]=1-2*(r+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}p._UpdateFlagSeed=0,p._IdentityReadOnly=p.Identity(),Object.defineProperties(p.prototype,{dimension:{value:[4,4]},rank:{value:2}});class _{}_.Vector3=(0,s.ln)(11,u.Zero),_.Matrix=(0,s.ln)(2,p.Identity),_.Quaternion=(0,s.ln)(3,f.Zero);class m{}m.Vector2=(0,s.ln)(3,c.Zero),m.Vector3=(0,s.ln)(13,u.Zero),m.Vector4=(0,s.ln)(3,d.Zero),m.Quaternion=(0,s.ln)(3,f.Zero),m.Matrix=(0,s.ln)(8,p.Identity),(0,n.Y5)("BABYLON.Vector2",c),(0,n.Y5)("BABYLON.Vector3",u),(0,n.Y5)("BABYLON.Vector4",d),(0,n.Y5)("BABYLON.Matrix",p);const g=p.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1)},13093:(e,t,i)=>{"use strict";i.d(t,{L:()=>r});class r{constructor(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}toGlobal(e,t){return new r(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 r(this.x,this.y,this.width,this.height)}}},13798:(e,t,i)=>{"use strict";i.d(t,{O:()=>h,Q:()=>c});var r=i(94212),s=i(73864);const n=[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))],o=[()=>1,e=>e.y,e=>e.z,e=>e.x,e=>e.x*e.y,e=>e.y*e.z,e=>3*e.z*e.z-1,e=>e.x*e.z,e=>e.x*e.x-e.y*e.y],a=(e,t)=>n[e]*o[e](t),l=[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 h{constructor(){this.preScaled=!1,this.l00=r.Pq.Zero(),this.l1_1=r.Pq.Zero(),this.l10=r.Pq.Zero(),this.l11=r.Pq.Zero(),this.l2_2=r.Pq.Zero(),this.l2_1=r.Pq.Zero(),this.l20=r.Pq.Zero(),this.l21=r.Pq.Zero(),this.l22=r.Pq.Zero()}addLight(e,t,i){s.AA.Vector3[0].set(t.r,t.g,t.b);const r=s.AA.Vector3[0],n=s.AA.Vector3[1];r.scaleToRef(i,n),n.scaleToRef(a(0,e),s.AA.Vector3[2]),this.l00.addInPlace(s.AA.Vector3[2]),n.scaleToRef(a(1,e),s.AA.Vector3[2]),this.l1_1.addInPlace(s.AA.Vector3[2]),n.scaleToRef(a(2,e),s.AA.Vector3[2]),this.l10.addInPlace(s.AA.Vector3[2]),n.scaleToRef(a(3,e),s.AA.Vector3[2]),this.l11.addInPlace(s.AA.Vector3[2]),n.scaleToRef(a(4,e),s.AA.Vector3[2]),this.l2_2.addInPlace(s.AA.Vector3[2]),n.scaleToRef(a(5,e),s.AA.Vector3[2]),this.l2_1.addInPlace(s.AA.Vector3[2]),n.scaleToRef(a(6,e),s.AA.Vector3[2]),this.l20.addInPlace(s.AA.Vector3[2]),n.scaleToRef(a(7,e),s.AA.Vector3[2]),this.l21.addInPlace(s.AA.Vector3[2]),n.scaleToRef(a(8,e),s.AA.Vector3[2]),this.l22.addInPlace(s.AA.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(l[0]),this.l1_1.scaleInPlace(l[1]),this.l10.scaleInPlace(l[2]),this.l11.scaleInPlace(l[3]),this.l2_2.scaleInPlace(l[4]),this.l2_1.scaleInPlace(l[5]),this.l20.scaleInPlace(l[6]),this.l21.scaleInPlace(l[7]),this.l22.scaleInPlace(l[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(n[0]),this.l1_1.scaleInPlace(n[1]),this.l10.scaleInPlace(n[2]),this.l11.scaleInPlace(n[3]),this.l2_2.scaleInPlace(n[4]),this.l2_1.scaleInPlace(n[5]),this.l20.scaleInPlace(n[6]),this.l21.scaleInPlace(n[7]),this.l22.scaleInPlace(n[8])}updateFromArray(e){return r.Pq.FromArrayToRef(e[0],0,this.l00),r.Pq.FromArrayToRef(e[1],0,this.l1_1),r.Pq.FromArrayToRef(e[2],0,this.l10),r.Pq.FromArrayToRef(e[3],0,this.l11),r.Pq.FromArrayToRef(e[4],0,this.l2_2),r.Pq.FromArrayToRef(e[5],0,this.l2_1),r.Pq.FromArrayToRef(e[6],0,this.l20),r.Pq.FromArrayToRef(e[7],0,this.l21),r.Pq.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return r.Pq.FromFloatsToRef(e[0],e[1],e[2],this.l00),r.Pq.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),r.Pq.FromFloatsToRef(e[6],e[7],e[8],this.l10),r.Pq.FromFloatsToRef(e[9],e[10],e[11],this.l11),r.Pq.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),r.Pq.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),r.Pq.FromFloatsToRef(e[18],e[19],e[20],this.l20),r.Pq.FromFloatsToRef(e[21],e[22],e[23],this.l21),r.Pq.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return(new h).updateFromArray(e)}static FromPolynomial(e){const t=new h;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 c{constructor(){this.x=r.Pq.Zero(),this.y=r.Pq.Zero(),this.z=r.Pq.Zero(),this.xx=r.Pq.Zero(),this.yy=r.Pq.Zero(),this.zz=r.Pq.Zero(),this.xy=r.Pq.Zero(),this.yz=r.Pq.Zero(),this.zx=r.Pq.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=h.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){s.AA.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=s.AA.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),s.AA.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),s.AA.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(s.AA.Vector3[0]).addInPlace(s.AA.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(s.AA.Vector3[0]).subtractInPlace(s.AA.Vector3[1]),this.zz.copyFrom(e.l00),s.AA.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(s.AA.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 c).updateFromHarmonics(e)}static FromArray(e){const t=new c;return r.Pq.FromArrayToRef(e[0],0,t.x),r.Pq.FromArrayToRef(e[1],0,t.y),r.Pq.FromArrayToRef(e[2],0,t.z),r.Pq.FromArrayToRef(e[3],0,t.xx),r.Pq.FromArrayToRef(e[4],0,t.yy),r.Pq.FromArrayToRef(e[5],0,t.zz),r.Pq.FromArrayToRef(e[6],0,t.yz),r.Pq.FromArrayToRef(e[7],0,t.zx),r.Pq.FromArrayToRef(e[8],0,t.xy),t}}},7240:(e,t,i)=>{"use strict";i.d(t,{A:()=>s});var r=i(75801);class s extends r.n{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}},82266:(e,t,i)=>{"use strict";i.d(t,{d:()=>h});var r=i(94212),s=i(56984),n=i(13798),o=i(34910),a=i(11084);class l{constructor(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r}}class h{static ConvertCubeMapTextureToSphericalPolynomial(e){if(!e.isCube)return null;e.getScene()?.getEngine().flushFramebuffer();const t=e.getSize().width,i=e.readPixels(0,void 0,void 0,!1),r=e.readPixels(1,void 0,void 0,!1);let s,n;e.isRenderTarget?(s=e.readPixels(3,void 0,void 0,!1),n=e.readPixels(2,void 0,void 0,!1)):(s=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),a=e.readPixels(5,void 0,void 0,!1),l=e.gammaSpace;let h=0;return 1!=e.textureType&&2!=e.textureType||(h=1),new Promise((e=>{Promise.all([r,i,s,n,o,a]).then((([i,r,s,n,o,a])=>{const c={size:t,right:r,left:i,up:s,down:n,front:o,back:a,format:5,type:h,gammaSpace:l};e(this.ConvertCubeMapToSphericalPolynomial(c))}))}))}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new n.O;let i=0;const r=2/e.size,l=r,h=.5*r,c=h-1;for(let n=0;n<6;n++){const u=this._FileFaces[n],d=e[u.name];let f=c;const p=5===e.format?4:3;for(let n=0;nb){const t=b/e;g*=t,v*=t,x*=t}}else g=(0,s.Clamp)(g,0,b),v=(0,s.Clamp)(v,0,b),x=(0,s.Clamp)(x,0,b);const S=new a.v9(g,v,x);t.addLight(c,S,m),i+=m,_+=r}f+=l}}const u=4*Math.PI*6/6/i;return t.scaleInPlace(u),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),n.Q.FromHarmonics(t)}}h._FileFaces=[new l("right",new r.Pq(1,0,0),new r.Pq(0,0,-1),new r.Pq(0,-1,0)),new l("left",new r.Pq(-1,0,0),new r.Pq(0,0,1),new r.Pq(0,-1,0)),new l("up",new r.Pq(0,1,0),new r.Pq(1,0,0),new r.Pq(0,0,1)),new l("down",new r.Pq(0,-1,0),new r.Pq(1,0,0),new r.Pq(0,0,-1)),new l("front",new r.Pq(0,0,1),new r.Pq(1,0,0),new r.Pq(0,-1,0)),new l("back",new r.Pq(0,0,-1),new r.Pq(-1,0,0),new r.Pq(0,-1,0))],h.MAX_HDRI_VALUE=4096,h.PRESERVE_CLAMPED_COLORS=!1},22377:(e,t,i)=>{"use strict";i.d(t,{I9:()=>c,LT:()=>l,NK:()=>o,VH:()=>a});var r=i(5060);function s(e,t,i,r,s,n){s>0?(s=function(e,t){return t>1023?1*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?1*Math.pow(2,-1074)*Math.pow(2,t+1074):1*Math.pow(2,t)}(0,s-136),e[n+0]=t*s,e[n+1]=i*s,e[n+2]=r*s):(e[n+0]=0,e[n+1]=0,e[n+2]=0)}function n(e,t){let i="",r="";for(let s=t;s32767)throw"HDR Bad header format, unsupported size";return a+=r.length+1,{height:t,width:i,dataPosition:a}}function a(e,t,i=!1){const s=new Uint8Array(e),n=o(s),a=l(s,n);return r.D.ConvertPanoramaToCubemap(a,n.width,n.height,t,i)}function l(e,t){return function(e,t){let i=t.height;const r=t.width;let n,o,a,l,c,u=t.dataPosition,d=0,f=0,p=0;const _=new ArrayBuffer(4*r),m=new Uint8Array(_),g=new ArrayBuffer(t.width*t.height*4*3),v=new Float32Array(g);for(;i>0;){if(n=e[u++],o=e[u++],a=e[u++],l=e[u++],2!=n||2!=o||128&a||t.width<8||t.width>32767)return h(e,t);if((a<<8|l)!=r)throw"HDR Bad header format, wrong scan line width";for(d=0,p=0;p<4;p++)for(f=(p+1)*r;d128){if(c=n-128,0==c||c>f-d)throw"HDR Bad Format, bad scanline data (run)";for(;c-- >0;)m[d++]=o}else{if(c=n,0==c||c>f-d)throw"HDR Bad Format, bad scanline data (non-run)";if(m[d++]=o,--c>0)for(let t=0;t0;){for(h=0;h{"use strict";i.d(t,{D:()=>s});var r=i(94212);class s{static ConvertPanoramaToCubemap(e,t,i,r,s=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";return{front:this.CreateCubemapTexture(r,this.FACE_FRONT,e,t,i,s),back:this.CreateCubemapTexture(r,this.FACE_BACK,e,t,i,s),left:this.CreateCubemapTexture(r,this.FACE_LEFT,e,t,i,s),right:this.CreateCubemapTexture(r,this.FACE_RIGHT,e,t,i,s),up:this.CreateCubemapTexture(r,this.FACE_UP,e,t,i,s),down:this.CreateCubemapTexture(r,this.FACE_DOWN,e,t,i,s),size:r,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,r,s,n=!1){const o=new ArrayBuffer(e*e*4*3),a=new Float32Array(o),l=n?Math.max(1,Math.round(r/4/e)):1,h=1/l,c=h*h,u=t[1].subtract(t[0]).scale(h/e),d=t[3].subtract(t[2]).scale(h/e),f=1/e;let p=0;for(let n=0;nMath.PI;)s-=2*Math.PI;let o=s/Math.PI;const a=n/Math.PI;o=.5*o+.5;let l=Math.round(o*i);l<0?l=0:l>=i&&(l=i-1);let h=Math.round(a*r);h<0?h=0:h>=r&&(h=r-1);const c=r-h-1;return{r:t[c*i*3+3*l+0],g:t[c*i*3+3*l+1],b:t[c*i*3+3*l+2]}}}s.FACE_LEFT=[new r.Pq(-1,-1,-1),new r.Pq(1,-1,-1),new r.Pq(-1,1,-1),new r.Pq(1,1,-1)],s.FACE_RIGHT=[new r.Pq(1,-1,1),new r.Pq(-1,-1,1),new r.Pq(1,1,1),new r.Pq(-1,1,1)],s.FACE_FRONT=[new r.Pq(1,-1,-1),new r.Pq(1,-1,1),new r.Pq(1,1,-1),new r.Pq(1,1,1)],s.FACE_BACK=[new r.Pq(-1,-1,1),new r.Pq(-1,-1,-1),new r.Pq(-1,1,1),new r.Pq(-1,1,-1)],s.FACE_DOWN=[new r.Pq(1,1,-1),new r.Pq(1,1,1),new r.Pq(-1,1,-1),new r.Pq(-1,1,1)],s.FACE_UP=[new r.Pq(-1,-1,-1),new r.Pq(-1,-1,1),new r.Pq(1,-1,-1),new r.Pq(1,-1,1)]},76486:(e,t,i)=>{"use strict";i.d(t,{Z:()=>r});class r{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,(e=>(e=e.slice(1,e.length-1),r._HandleParenthesisContent(e,t)))):r._HandleParenthesisContent(e,t))||"false"!==e&&r.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);const s=e.split("||");for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)){let n=r._SimplifyNegation(s[e].trim());const o=n.split("&&");if(o.length>1)for(let e=0;e(e=e.replace(/[\s]/g,(()=>""))).length%2?"!":""))).trim())?e="false":"!false"===e&&(e="true"),e}}},34130:(e,t,i)=>{"use strict";function r(e,t){const i=[];for(let r=0;ro,ln:()=>s,mI:()=>r});const n=["push","splice","pop","shift","unshift"];function o(e,t){const i=n.map((i=>function(e,t,i){const r=e[t];if("function"!=typeof r)return null;const s=function(){const r=e.length,n=s.previous.apply(e,arguments);return i(t,r),n};return r.next=s,s.previous=r,e[t]=s,()=>{const i=s.previous;if(!i)return;const r=s.next;r?(i.next=r,r.previous=i):(i.next=void 0,e[t]=i),s.next=void 0,s.previous=void 0}}(e,i,t)));return()=>{i.forEach((e=>{e?.()}))}}},68622:(e,t,i)=>{"use strict";i.d(t,{$e:()=>l,ED:()=>x,Sl:()=>c,SV:()=>h,yT:()=>u,aB:()=>v,af:()=>_,yk:()=>m});var r,s=i(9723),n=i(4756),o=i(7107);function a(){let e=null;function t(e,t,i,r,s){const n=e.getImageTranscodedSizeInBytes(t,i,r);let o=new Uint8Array(n);return e.transcodeImage(o,t,i,r,1,0)?(s&&(o=function(e,t,i,r){const s=new Uint16Array(4),n=new Uint16Array(i*r),o=i/4,a=r/4;for(let t=0;t>2&3],n[h++]=s[l>>4&3],n[h++]=s[l>>6&3]}}return n}(o,0,e.getImageWidth(t,i)+3&-4,e.getImageHeight(t,i)+3&-4)),o):null}onmessage=i=>{if("init"===i.data.action){if(i.data.url)try{importScripts(i.data.url)}catch(e){postMessage({action:"error",error:e})}e||(e=BASIS({wasmBinary:i.data.wasmBinary})),null!==e&&e.then((e=>{BASIS=e,e.initializeBasis(),postMessage({action:"init"})}))}else if("transcode"===i.data.action){const e=i.data.config,r=i.data.imageData,s=new BASIS.BasisFile(r),n=function(e){const t=e.getHasAlpha(),i=e.getNumImages(),r=[];for(let t=0;t{let i;switch(e){case r.cTFETC1:i=36196;break;case r.cTFBC1:i=33776;break;case r.cTFBC4:i=33779;break;case r.cTFASTC_4x4:i=37808;break;case r.cTFETC2:i=37496;break;case r.cTFBC7:i=36492}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i};let d=null,f=null,p=0;const _=e=>{f=e},m=(e,t)=>{const i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise(((e,r)=>{(d||(d=new Promise(((e,t)=>{f?e(f):s.S0.LoadFileAsync(s.S0.GetBabylonScriptURL(c.WasmModuleURL)).then((i=>{if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");const r=URL.createObjectURL(new Blob([`(${a})()`],{type:"application/javascript"}));f=new Worker(r),function(e,t,i){return new Promise(((r,n)=>{const o=t=>{"init"===t.data.action?(e.removeEventListener("message",o),r(e)):"error"===t.data.action&&n(t.data.error||"error initializing worker")};e.addEventListener("message",o),e.postMessage({action:"init",url:i?s.S0.GetBabylonScriptURL(i):void 0,wasmBinary:t},[t])}))}(f,i,c.JSModuleURL).then(e,t)})).catch(t)}))),d).then((()=>{const s=p++,n=t=>{"transcode"===t.data.action&&t.data.id===s&&(f.removeEventListener("message",n),t.data.success?e(t.data):r("Transcode is not supported on this device"))};f.addEventListener("message",n);const o=new Uint8Array(i.byteLength);o.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),f.postMessage({action:"transcode",id:s,imageData:o,config:t,ignoreSupportedFormats:!1},[o.buffer])}),(e=>{r(e)}))}))},g=(e,t)=>{let i=t._gl?.TEXTURE_2D;e.isCube&&(i=t._gl?.TEXTURE_CUBE_MAP),t._bindTextureDirectly(i,e,!0)},v=(e,t)=>{const i=e.getEngine();for(let a=0;a{i._releaseTexture(t),g(e,i)}))}else{e.width=l.width,e.height=l.height,e.generateMipMaps=t.fileInfo.images[a].levels.length>1;const r=x.GetInternalFormatFromBasisFormat(t.format,i);e.format=r,g(e,i),t.fileInfo.images[a].levels.forEach(((t,s)=>{i._uploadCompressedDataToTextureDirectly(e,r,t.width,t.height,t.transcodedPixels,a,s)})),!i._features.basisNeedsPOT||Math.log2(e.width)%1==0&&Math.log2(e.height)%1==0||(s.S0.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."),e._cachedWrapU=n.g.CLAMP_ADDRESSMODE,e._cachedWrapV=n.g.CLAMP_ADDRESSMODE)}}},x={JSModuleURL:c.JSModuleURL,WasmModuleURL:c.WasmModuleURL,GetInternalFormatFromBasisFormat:u,TranscodeAsync:m,LoadTextureFromTranscodeResult:v};Object.defineProperty(x,"JSModuleURL",{get:function(){return c.JSModuleURL},set:function(e){c.JSModuleURL=e}}),Object.defineProperty(x,"WasmModuleURL",{get:function(){return c.WasmModuleURL},set:function(e){c.WasmModuleURL=e}})},61572:(e,t,i)=>{"use strict";function r(e,t,i=!1){const r=t.width,s=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT;const i=new Uint8Array(t);for(;--t>=0;){let r=e[t];r<0?r=0:r>1&&(r=1),i[t]=255*r}e=i}const n=document.createElement("canvas");n.width=r,n.height=s;const o=n.getContext("2d");if(!o)return null;const a=o.createImageData(r,s);if(a.data.set(e),o.putImageData(a,0,0),i){const e=document.createElement("canvas");e.width=r,e.height=s;const t=e.getContext("2d");return t?(t.translate(0,s),t.scale(1,-1),t.drawImage(n,0,0),e.toDataURL("image/png")):null}return n.toDataURL("image/png")}function s(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const n=e._readPixelsSync(t,i);return n?r(n,e.getSize(),s.invertY):null}async function n(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const n=await e.readPixels(t,i);return n?r(n,e.getSize(),s.invertY):null}i.d(t,{D8:()=>o,c9:()=>r,lP:()=>s,nh:()=>n});const o={GenerateBase64StringFromPixelData:r,GenerateBase64StringFromTexture:s,GenerateBase64StringFromTextureAsync:n}},26589:(e,t,i)=>{"use strict";i.d(t,{DDSTools:()=>p});var r=i(56984),s=i(60590),n=i(82266),o=i(28876);i(7244);const a=131072,l=131072;function h(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}const c=h("DXT1"),u=h("DXT3"),d=h("DXT5"),f=h("DX10");class p{static GetDDSInfo(e){const t=new Int32Array(e.buffer,e.byteOffset,31),i=new Int32Array(e.buffer,e.byteOffset,35);let r=1;t[2]&a&&(r=Math.max(1,t[7]));const s=t[21],n=s===f?i[32]:0;let o=0;switch(s){case 113:o=2;break;case 116:o=1;break;case f:if(10===n){o=2;break}if(2===n){o=1;break}}return{width:t[4],height:t[3],mipmapCount:r,isFourCC:!(4&~t[20]),isRGB:!(64&~t[20]),isLuminance:(t[20]&l)===l,isCube:!(512&~t[28]),isCompressed:s===c||s===u||s===d,dxgiFormat:n,textureType:o}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,r,s,n){const a=new Float32Array(r),l=new Uint16Array(s,i);let h=0;for(let i=0;i>8)}static _GetRGBArrayBuffer(e,t,i,r,s,n,o,a){const l=new Uint8Array(r),h=new Uint8Array(s,i);let c=0;for(let i=0;i>8&255,D>>16&255,D>>24&255))])}var D;const w=p._ExtractLongWordOrder(x[23]),N=p._ExtractLongWordOrder(x[24]),F=p._ExtractLongWordOrder(x[25]),L=p._ExtractLongWordOrder(x[26]);O&&(R=e._getRGBABufferInternalSizedFormat(r.textureType)),E=1,x[2]&a&&!1!==o&&(E=Math.max(1,x[7]));const B=_||0,V=e.getCaps();for(let s=B;s0?r.sphericalPolynomial=n.d.ConvertCubeMapToSphericalPolynomial({size:x[4],right:g[0],left:g[1],up:g[2],down:g[3],front:g[4],back:g[5],format:5,type:1,gammaSpace:!1}):r.sphericalPolynomial=void 0}}p.StoreLODInAlphaChannel=!1},23559:(e,t,i)=>{"use strict";i.d(t,{B:()=>n,K:()=>o});const r={},s={};function n(e){const t=e.getClassName();return s[t]||(s[t]={}),s[t]}function o(e){const t=e.getClassName();if(r[t])return r[t];r[t]={};const i=r[t];let n=e,o=t;for(;o;){const e=s[o];for(const t in e)i[t]=e[t];let t,r=!1;do{if(t=Object.getPrototypeOf(n),!t.getClassName){r=!0;break}if(t.getClassName()!==o)break;n=t}while(t);if(r)break;o=t.getClassName(),n=t}return i}},40220:(e,t,i)=>{"use strict";i.d(t,{$z:()=>n,Cx:()=>x,GG:()=>g,P_:()=>u,WM:()=>c,Y9:()=>h,bR:()=>m,fW:()=>v,jT:()=>l,lK:()=>o,n1:()=>_,qK:()=>p,uM:()=>a,wL:()=>f,xG:()=>d});var r=i(23559);function s(e,t){return(i,s)=>{const n=(0,r.B)(i);n[s]||(n[s]={type:e,sourceName:t})}}function n(e,t=null){return function(e,t=null){return(i,r)=>{const s=t||"_"+r;Object.defineProperty(i,r,{get:function(){return this[s]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[s]!==t&&(this[s]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function o(e){return s(0,e)}function a(e){return s(1,e)}function l(e){return s(2,e)}function h(e){return s(3,e)}function c(e){return s(4,e)}function u(e){return s(5,e)}function d(e){return s(6,e)}function f(e){return s(7,e)}function p(e){return s(8,e)}function _(e){return s(9,e)}function m(e){return s(10,e)}function g(e){return s(12,e)}function v(e){return s(11,e)}function x(e,t,i,r){const s=i.value;i.value=(...i)=>{let n=s;if("undefined"!=typeof _native&&_native[t]){const e=_native[t];n=r?(...t)=>r(...t)?e(...t):s(...t):e}return e[t]=n,n(...i)}}x.filter=function(e){return(t,i,r)=>x(t,i,r,e)}},89518:(e,t,i)=>{"use strict";i.d(t,{p:()=>h});var r=i(75108),s=i(84015),n=i(11084),o=i(94212),a=i(23559);const l=function(e,t,i,r={}){const n=e();s.Y&&s.Y.HasTags(t)&&s.Y.AddTagsTo(n,s.Y.GetTags(t,!0));const o=(0,a.K)(n),l={};for(const e in o){const s=o[e],a=t[e],c=s.type;if(null!=a&&("uniqueId"!==e||h.AllowLoadingUniqueId))switch(c){case 0:case 6:case 11:n[e]=a;break;case 1:r.cloneTexturesOnlyOnce&&l[a.uniqueId]?n[e]=l[a.uniqueId]:(n[e]=i||a.isRenderTarget?a:a.clone(),l[a.uniqueId]=n[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:n[e]=i?a:a.clone()}}return n};class h{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw(0,r.n)("ImageProcessingConfiguration")},h._FresnelParametersParser=e=>{throw(0,r.n)("FresnelParameters")},h._ColorCurvesParser=e=>{throw(0,r.n)("ColorCurves")},h._TextureParser=(e,t,i)=>{throw(0,r.n)("Texture")}},35290:(e,t,i)=>{"use strict";i.d(t,{r:()=>n});var r=i(60590);const s=(e,t,i)=>e?e.getClassName&&"Mesh"===e.getClassName()?null:!e.getClassName||"SubMesh"!==e.getClassName()&&"PhysicsBody"!==e.getClassName()?e.clone?e.clone():Array.isArray(e)?e.slice():i&&"object"==typeof e?{...e}:null:e.clone(t):null;class n{static DeepCopy(e,t,i,n,o=!1){const a=function(e){const t=[];do{Object.getOwnPropertyNames(e).forEach((function(e){-1===t.indexOf(e)&&t.push(e)}))}while(e=Object.getPrototypeOf(e));return t}(e);for(const l of a){if("_"===l[0]&&(!n||-1===n.indexOf(l)))continue;if(l.endsWith("Observable"))continue;if(i&&-1!==i.indexOf(l))continue;const a=e[l],h=typeof a;if("function"!==h)try{if("object"===h)if(a instanceof Uint8Array)t[l]=Uint8Array.from(a);else if(a instanceof Array){if(t[l]=[],a.length>0)if("object"==typeof a[0])for(let e=0;e{"use strict";i.d(t,{n:()=>s});const r={};function s(e,t=!1){if(!t||!r[e])return r[e]=!0,`${e} needs to be imported before as it contains a side-effect required by your code.`}},68191:(e,t,i)=>{"use strict";function r(){return"undefined"!=typeof window}function s(){return"undefined"!=typeof navigator}function n(){return"undefined"!=typeof document}function o(e){let t="",i=e.firstChild;for(;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}i.d(t,{Az:()=>a,BA:()=>r,Nf:()=>n,XD:()=>s,Zl:()=>o});const a={IsWindowObjectExist:r,IsNavigatorAvailable:s,IsDocumentAvailable:n,GetDOMTextContent:o}},465:(e,t,i)=>{"use strict";i.r(t),i.d(t,{Dispose:()=>d,DumpData:()=>u,DumpDataAsync:()=>c,DumpFramebuffer:()=>h,DumpTools:()=>f});var r=i(50606),s=i(9723),n=i(56984),o=i(34268);let a,l=null;async function h(e,t,i,r,s="image/png",n,o){const a=await i.readPixels(0,0,e,t);u(e,t,new Uint8Array(a.buffer),r,s,n,!0,void 0,o)}function c(e,t,i,r="image/png",s,n=!1,o=!1,a){return new Promise((l=>{u(e,t,i,(e=>l(e)),r,s,n,o,a)}))}function u(e,t,h,c,u="image/png",f,p=!1,_=!1,m){(async function(){return l||(l=new Promise(((e,t)=>{let s,n=null;const l={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};Promise.resolve().then(i.bind(i,722)).then((({ThinEngine:h})=>{try{s=new OffscreenCanvas(100,100),n=new h(s,!1,l)}catch(e){s=document.createElement("canvas"),n=new h(s,!1,l)}o.q.Instances.pop(),o.q.OnEnginesDisposedObservable.add((e=>{n&&e!==n&&!n.isDisposed&&0===o.q.Instances.length&&d()})),n.getCaps().parallelShaderCompile=void 0;const c=new r.J(n);Promise.resolve().then(i.bind(i,30927)).then((({passPixelShader:i})=>{if(!n)return void t("Engine is not defined");const o=new r.$({engine:n,name:i.name,fragmentShader:i.shader,samplerNames:["textureSampler"]});a={canvas:s,engine:n,renderer:c,wrapper:o},e(a)}))})).catch(t)}))),await l})().then((i=>{if(i.engine.setSize(e,t,!0),h instanceof Float32Array){const e=new Uint8Array(h.length);let t=h.length;for(;t--;){const i=h[t];e[t]=Math.round(255*(0,n.Clamp)(i))}h=e}const r=i.engine.createRawTexture(h,e,t,5,!1,!p,1);i.renderer.setViewport(),i.renderer.applyEffectWrapper(i.wrapper),i.wrapper.effect._bindTexture("textureSampler",r),i.renderer.draw(),_?s.S0.ToBlob(i.canvas,(e=>{const t=new FileReader;t.onload=e=>{const t=e.target.result;c&&c(t)},t.readAsArrayBuffer(e)}),u,m):s.S0.EncodeScreenshotCanvasData(i.canvas,c,u,f,m),r.dispose()}))}function d(){a?(a.wrapper.dispose(),a.renderer.dispose(),a.engine.dispose()):l?.then((e=>{e.wrapper.dispose(),e.renderer.dispose(),e.engine.dispose()})),l=null,a=null}const f={DumpData:u,DumpDataAsync:c,DumpFramebuffer:h,Dispose:d};s.S0.DumpData=u,s.S0.DumpDataAsync=c,s.S0.DumpFramebuffer=h},48195:(e,t,i)=>{"use strict";i.d(t,{$h:()=>S,Hx:()=>x,RZ:()=>v,bv:()=>y,cU:()=>g,gW:()=>P,o5:()=>T,ow:()=>E,qY:()=>A});var r=i(9723),s=i(94212),n=i(56984),o=i(13798),a=i(7107),l=i(23199),h=i(88193),c=i(52660),u=i(60590),d=i(2069),f=(i(54699),i(465));const p="image/png",_=2,m=[134,22,135,150,246,214,150,54];function g(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let i=0;for(let e=0;e_)throw new Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "${_}".`);return 2===e.version?e:e={...e,version:2,imageType:p}}async function x(e,t={}){const i=e.getInternalTexture();if(!i)return Promise.reject("The cube texture is invalid.");const r=t.imageType??p,s=i.getEngine();if(2!==e.textureType&&1!==e.textureType&&0!==e.textureType&&0!==e.textureType&&7!==e.textureType&&-1!==e.textureType)return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");let o=1;if(!s.getCaps().textureFloatRender&&(o=2,!s.getCaps().textureHalfFloatRender))return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");e.sphericalPolynomial;const a=e.getInternalTexture()?._sphericalPolynomialPromise,l=i.width,c=new h.Z(s),u={};s.flushFramebuffer();const g=(0,n.ILog2)(i.width);for(let i=0;i<=g;i++){const n=Math.pow(2,g-i);for(let a=0;a<6;a++){let l=await e.readPixels(a,i,void 0,!1);if(l&&l.byteLength===l.length){const e=new Float32Array(4*l.byteLength);for(let t=0;t{if(i){const i=t.createTexture(null,!0,!0,null,1,null,(e=>{d(e)}),e);r?.onEffectCreatedObservable.addOnce((a=>{a.executeWhenCompiled((()=>{r.externalTextureSamplerBinding=!0,r.onApply=r=>{r._bindTexture("textureSampler",i),r.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([r],h,!0,n,o),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(s),u())}))}))}else{if(t._uploadImageToTexture(c,e,n,o),a){const i=l[o];i&&t._uploadImageToTexture(i._texture,e,n,0)}u()}}))}async function y(e,t,s=p){if(!r.S0.IsExponentOfTwo(e.width))throw new Error("Texture size must be a power of two");const o=(0,n.ILog2)(e.width)+1,h=e.getEngine();let u=!1,d=!1,f=null,_=null,m=null;const g=h.getCaps();e.format=5,e.type=0,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,h.updateTextureSamplingMode(3,e),g.textureLOD?h._features.supportRenderAndCopyToLodForFloatTextures?g.textureHalfFloatRender&&g.textureHalfFloatLinearFiltering?(u=!0,e.type=2):g.textureFloatRender&&g.textureFloatLinearFiltering&&(u=!0,e.type=1):u=!1:(u=!1,d=!0,m={});let v=0;if(u)h.isWebGPU?(v=1,await Promise.resolve().then(i.bind(i,79388))):await Promise.resolve().then(i.bind(i,64849)),f=new c.w("rgbdDecode","rgbdDecode",null,null,1,null,3,h,!1,void 0,e.type,void 0,null,!1,void 0,v),e._isRGBD=!1,e.invertY=!1,_=h.createRenderTargetCubeTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:e.type,format:5});else if(e._isRGBD=!0,e.invertY=!0,d){const t=3,i=e._lodGenerationScale,r=e._lodGenerationOffset;for(let s=0;sC(t,h,u,f,a,r,i,d,m,_,e)));else{const t=new Image;t.src=a,l=new Promise(((s,n)=>{t.onload=()=>{C(t,h,u,f,a,r,i,d,m,_,e).then((()=>s())).catch((e=>{n(e)}))},t.onerror=e=>{n(e)}}))}x.push(l)}if(t.length{_&&(h._releaseTexture(e),_._swapAndDie(e)),f&&f.dispose(),d&&(e._lodTextureHigh&&e._lodTextureHigh._texture&&(e._lodTextureHigh._texture.isReady=!0),e._lodTextureMid&&e._lodTextureMid._texture&&(e._lodTextureMid._texture.isReady=!0),e._lodTextureLow&&e._lodTextureLow._texture&&(e._lodTextureLow._texture.isReady=!0))}))}function E(e,t){const i=(t=v(t)).irradiance;if(!i)return;const r=new o.Q;s.Pq.FromArrayToRef(i.x,0,r.x),s.Pq.FromArrayToRef(i.y,0,r.y),s.Pq.FromArrayToRef(i.z,0,r.z),s.Pq.FromArrayToRef(i.xx,0,r.xx),s.Pq.FromArrayToRef(i.yy,0,r.yy),s.Pq.FromArrayToRef(i.zz,0,r.zz),s.Pq.FromArrayToRef(i.yz,0,r.yz),s.Pq.FromArrayToRef(i.zx,0,r.zx),s.Pq.FromArrayToRef(i.xy,0,r.xy),e._sphericalPolynomial=r}function P(e,t,i,r,s){const n=y(e.getEngine().createRawCubeTexture(null,e.width,e.format,e.type,e.generateMipMaps,e.invertY,e.samplingMode,e._compression),t).then((()=>e));return e.onRebuildCallback=e=>({proxy:n,isReady:!0,isAsync:!0}),e._source=13,e._bufferViewArrayArray=t,e._lodGenerationScale=r,e._lodGenerationOffset=s,e._sphericalPolynomial=i,y(e,t).then((()=>(e.isReady=!0,e)))}const A={GetEnvInfo:g,CreateEnvTextureAsync:x,CreateImageDataArrayBufferViews:S,UploadEnvLevelsAsync:T,UploadLevelsAsync:y,UploadEnvSpherical:E}},14914:(e,t,i)=>{"use strict";i.d(t,{Cf:()=>r,bu:()=>n,tG:()=>s});class r extends Error{}r._setPrototypeOf=Object.setPrototypeOf||((e,t)=>(e.__proto__=t,e));const s={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class n extends r{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",r._setPrototypeOf(this,n.prototype)}}},28909:(e,t,i)=>{"use strict";i.d(t,{M1:()=>S,Mi:()=>v,NJ:()=>y,VB:()=>x,W$:()=>C,ZP:()=>I,dy:()=>O,eC:()=>b,f2:()=>R,hX:()=>g,my:()=>A,qc:()=>T,rh:()=>w,rz:()=>M,sh:()=>P,wS:()=>D,zU:()=>E});var r=i(67313),s=i(68191),n=i(43279),o=i(20934),a=i(56703),l=i(14914),h=i(5800),c=i(88217),u=i(34268),d=i(60590),f=i(72649),p=i(2636),_=i(55935);const m=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class g extends l.bu{constructor(e,t){super(e,l.tG.LoadFileError),this.name="LoadFileError",l.Cf._setPrototypeOf(this,g.prototype),t instanceof r.u?this.request=t:this.file=t}}class v extends l.bu{constructor(e,t){super(e,l.tG.RequestFileError),this.request=t,this.name="RequestFileError",l.Cf._setPrototypeOf(this,v.prototype)}}class x extends l.bu{constructor(e,t){super(e,l.tG.ReadFileError),this.file=t,this.name="ReadFileError",l.Cf._setPrototypeOf(this,x.prototype)}}const b={DefaultRetryStrategy:a.a.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e,ScriptBaseUrl:"",ScriptPreprocessUrl:e=>e,CleanUrl:e=>e.replace(/#/gm,"%23")},S=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&b.CorsBehavior)if("string"==typeof b.CorsBehavior||b.CorsBehavior instanceof String)t.crossOrigin=b.CorsBehavior;else{const i=b.CorsBehavior(e);i&&(t.crossOrigin=i)}},T={getRequiredSize:null},C=(e,t,i,s,n="",a)=>{const l=u.q.LastCreatedEngine;if("undefined"==typeof HTMLImageElement&&!l?._features.forceBitmapOverHTMLImageElement)return i("LoadImage is only supported in web or BabylonNative environments."),null;let c,d=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(c=URL.createObjectURL(new Blob([e],{type:n})),d=!0):c=`data:${n};base64,`+(0,h.EL)(e):e instanceof Blob?(c=URL.createObjectURL(e),d=!0):(c=b.CleanUrl(e),c=b.PreprocessUrl(c));const f=t=>{if(i){const r=c||e.toString();i(`Error while trying to load image: ${0===r.indexOf("http")||r.length<=128?r:r.slice(0,128)+"..."}`,t)}};if(l?._features.forceBitmapOverHTMLImageElement)return E(c,(r=>{l.createImageBitmap(new Blob([r],{type:n}),{premultiplyAlpha:"none",...a}).then((e=>{t(e),d&&URL.revokeObjectURL(c)})).catch((t=>{i&&i("Error while trying to load image: "+e,t)}))}),void 0,s||void 0,!0,((e,t)=>{f(t)})),null;const p=new Image;if(T.getRequiredSize){const t=T.getRequiredSize(e);t.width&&(p.width=t.width),t.height&&(p.height=t.height)}S(c,p);const _=[],m=()=>{_.forEach((e=>{e.target.removeEventListener(e.name,e.handler)})),_.length=0};_.push({target:p,name:"load",handler:()=>{m(),t(p),d&&p.src&&URL.revokeObjectURL(p.src)}}),_.push({target:p,name:"error",handler:e=>{m(),f(e),d&&p.src&&URL.revokeObjectURL(p.src)}}),_.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==p.src||"report"===e.disposition)return;m();const t=new Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);u.q.UseFallbackTexture=!1,f(t),d&&p.src&&URL.revokeObjectURL(p.src),p.src=""}}),_.forEach((e=>{e.target.addEventListener(e.name,e.handler)}));const g="blob:"===c.substring(0,5),v="data:"===c.substring(0,5),x=()=>{g||v||!r.u.IsCustomRequestAvailable?p.src=c:E(c,((e,t,i)=>{const r=new Blob([e],{type:!n&&i?i:n}),s=URL.createObjectURL(r);d=!0,p.src=s}),void 0,s||void 0,!0,((e,t)=>{f(t)}))};if(!g&&!v&&s&&s.enableTexturesOffline)s.open((()=>{s&&s.loadImage(c,p)}),x);else{if(-1!==c.indexOf("file:")){const e=decodeURIComponent(c.substring(5).toLowerCase());if(o.T.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(o.T.FilesToLoad[e])}catch(i){t=URL.createObjectURL(o.T.FilesToLoad[e])}p.src=t,d=!0}catch(e){p.src=""}return p}}x()}return p},y=(e,t,i,r,s)=>{const o=new FileReader,a={onCompleteObservable:new n.cP,abort:()=>o.abort()};return o.onloadend=()=>a.onCompleteObservable.notifyObservers(a),s&&(o.onerror=()=>{s(new x(`Unable to read ${e.name}`,e))}),o.onload=e=>{t(e.target.result)},i&&(o.onprogress=i),r?o.readAsArrayBuffer(e):o.readAsText(e),a},E=(e,t,i,r,s,a,l)=>{if(e.name)return y(e,t,i,s,a?e=>{a(void 0,e)}:void 0);const h=e;if(-1!==h.indexOf("file:")){let e=decodeURIComponent(h.substring(5).toLowerCase());0===e.indexOf("./")&&(e=e.substring(2));const r=o.T.FilesToLoad[e];if(r)return y(r,t,i,s,a?e=>a(void 0,new g(e.message,e.file)):void 0)}const{match:c,type:u}=I(h);if(c){const e={onCompleteObservable:new n.cP,abort:()=>()=>{}};try{const e=s?M(h):O(h);t(e,void 0,u)}catch(e){a?a(void 0,e):d.V.Error(e.message||"Failed to parse the Data URL")}return f._.SetImmediate((()=>{e.onCompleteObservable.notifyObservers(e)})),e}return P(h,((e,i)=>{t(e,i?.responseURL,i?.getResponseHeader("content-type"))}),i,r,s,a?e=>{a(e.request,new g(e.message,e.request))}:void 0,l)},P=(e,t,i,o,a,l,h)=>{e=b.CleanUrl(e),e=b.PreprocessUrl(e);const c=b.BaseUrl+e;let u=!1;const f={onCompleteObservable:new n.cP,abort:()=>u=!0},p=()=>{let e,n=new r.u,o=null;const p=()=>{n&&(i&&n.removeEventListener("progress",i),e&&n.removeEventListener("readystatechange",e),n.removeEventListener("loadend",_))};let _=()=>{p(),f.onCompleteObservable.notifyObservers(f),f.onCompleteObservable.clear(),i=void 0,e=null,_=null,l=void 0,h=void 0,t=void 0};f.abort=()=>{u=!0,_&&_(),n&&n.readyState!==(XMLHttpRequest.DONE||4)&&n.abort(),null!==o&&(clearTimeout(o),o=null),n=null};const m=e=>{const t=e.message||"Unknown error";l&&n?l(new v(t,n)):d.V.Error(t)},g=d=>{if(n){if(n.open("GET",c),h)try{h(n)}catch(e){return void m(e)}a&&(n.responseType="arraybuffer"),i&&n.addEventListener("progress",i),_&&n.addEventListener("loadend",_),e=()=>{if(!u&&n&&n.readyState===(XMLHttpRequest.DONE||4)){if(e&&n.removeEventListener("readystatechange",e),n.status>=200&&n.status<300||0===n.status&&(!(0,s.BA)()||A())){try{t&&t(a?n.response:n.responseText,n)}catch(e){m(e)}return}const i=b.DefaultRetryStrategy;if(i){const e=i(c,n,d);if(-1!==e)return p(),n=new r.u,void(o=setTimeout((()=>g(d+1)),e))}const h=new v("Error status: "+n.status+" "+n.statusText+" - Unable to load "+c,n);l&&l(h)}},n.addEventListener("readystatechange",e),n.send()}};g(0)};if(o&&o.enableSceneOffline){const r=e=>{e&&e.status>400?l&&l(e):p()},s=()=>{o&&o.loadFile(b.BaseUrl+e,(e=>{!u&&t&&t(e),f.onCompleteObservable.notifyObservers(f)}),i?e=>{!u&&i&&i(e)}:void 0,r,a)};o.open(s,r)}else p();return f},A=()=>"undefined"!=typeof location&&"file:"===location.protocol,R=e=>m.test(e),I=e=>{const t=m.exec(e);return null===t||0===t.length?{match:!1,type:""}:{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function M(e){return(0,h.yS)(e.split(",")[1])}const O=e=>(0,h.AV)(e.split(",")[1]);let D;_.$._FileToolsLoadImage=C,p.sg.loadFile=E,c.J.loadFile=E;const w=(e,t,i,r,s,n,o,a,l,h)=>{D={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:r,IsFileURL:s,LoadFile:n,LoadImage:o,ReadFile:a,RequestFile:l,SetCorsBehavior:h},Object.defineProperty(D,"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(D,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(D,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(D,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})};w(M,O,b,R,A,E,C,y,P,S)},20934:(e,t,i)=>{"use strict";i.d(t,{T:()=>r});class r{}r.FilesToLoad={}},71627:(e,t,i)=>{"use strict";function r(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}i.d(t,{S:()=>s,z:()=>r});const s={RandomId:r}},14798:(e,t,i)=>{"use strict";i.d(t,{n:()=>n});var r=i(60590),s=i(56225);class n{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=(0,s.n9)(e);if(t)return t;r.V.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let n=window||this;for(let e=0,t=i.length;e{"use strict";i.d(t,{H:()=>s});var r=i(60590);class s{constructor(e,t){if(this.data=e,this.isInvalid=!1,!s.IsValid(e))return this.isInvalid=!0,void r.V.Error("texture missing KTX identifier");const i=Uint32Array.BYTES_PER_ELEMENT,n=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),o=67305985===n.getUint32(0,!0);return this.glType=n.getUint32(1*i,o),this.glTypeSize=n.getUint32(2*i,o),this.glFormat=n.getUint32(3*i,o),this.glInternalFormat=n.getUint32(4*i,o),this.glBaseInternalFormat=n.getUint32(5*i,o),this.pixelWidth=n.getUint32(6*i,o),this.pixelHeight=n.getUint32(7*i,o),this.pixelDepth=n.getUint32(8*i,o),this.numberOfArrayElements=n.getUint32(9*i,o),this.numberOfFaces=n.getUint32(10*i,o),this.numberOfMipmapLevels=n.getUint32(11*i,o),this.bytesOfKeyValueData=n.getUint32(12*i,o),0!==this.glType?(r.V.Error("only compressed formats currently supported"),void(this.isInvalid=!0)):(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth?(r.V.Error("only 2D textures currently supported"),void(this.isInvalid=!0)):0!==this.numberOfArrayElements?(r.V.Error("texture arrays not currently supported"),void(this.isInvalid=!0)):this.numberOfFaces!==t?(r.V.Error("number of faces expected"+t+", but found "+this.numberOfFaces),void(this.isInvalid=!0)):void(this.loadType=s.COMPRESSED_2D))}uploadLevels(e,t){switch(this.loadType){case s.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);case s.TEX_2D:case s.COMPRESSED_3D:case s.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=s.HEADER_LEN+this.bytesOfKeyValueData,r=this.pixelWidth,n=this.pixelHeight;const o=t?this.numberOfMipmapLevels:1;for(let t=0;t=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&49===t[5]&&49===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}s.HEADER_LEN=64,s.COMPRESSED_2D=0,s.COMPRESSED_3D=1,s.TEX_2D=2,s.TEX_3D=3},27606:(e,t,i)=>{"use strict";i.d(t,{$:()=>l,Z:()=>h});var r=i(28382),s=i(9723),n=i(63199);function o(e,t){const i=t?.jsDecoderModule||KTX2DECODER;e&&(e.wasmUASTCToASTC&&(i.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(i.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(i.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(i.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(i.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(i.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(i.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(i.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(i.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder)),t&&(t.wasmUASTCToASTC&&(i.LiteTranscoder_UASTC_ASTC.WasmBinary=t.wasmUASTCToASTC),t.wasmUASTCToBC7&&(i.LiteTranscoder_UASTC_BC7.WasmBinary=t.wasmUASTCToBC7),t.wasmUASTCToRGBA_UNORM&&(i.LiteTranscoder_UASTC_RGBA_UNORM.WasmBinary=t.wasmUASTCToRGBA_UNORM),t.wasmUASTCToRGBA_SRGB&&(i.LiteTranscoder_UASTC_RGBA_SRGB.WasmBinary=t.wasmUASTCToRGBA_SRGB),t.wasmUASTCToR8_UNORM&&(i.LiteTranscoder_UASTC_R8_UNORM.WasmBinary=t.wasmUASTCToR8_UNORM),t.wasmUASTCToRG8_UNORM&&(i.LiteTranscoder_UASTC_RG8_UNORM.WasmBinary=t.wasmUASTCToRG8_UNORM),t.jsMSCTranscoder&&(i.MSCTranscoder.JSModule=t.jsMSCTranscoder),t.wasmMSCTranscoder&&(i.MSCTranscoder.WasmBinary=t.wasmMSCTranscoder),t.wasmZSTDDecoder&&(i.ZSTDDecoder.WasmBinary=t.wasmZSTDDecoder))}function a(e){let t;void 0===e&&"undefined"!=typeof KTX2DECODER&&(e=KTX2DECODER),onmessage=i=>{if(i.data)switch(i.data.action){case"init":{const r=i.data.urls;r&&(r.jsDecoderModule&&void 0===e&&(importScripts(r.jsDecoderModule),e=KTX2DECODER),o(r)),i.data.wasmBinaries&&o(void 0,{...i.data.wasmBinaries,jsDecoderModule:e}),t=new e.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":e.KTX2Decoder.DefaultDecoderOptions=i.data.options;break;case"decode":t.decode(i.data.data,i.data.caps,i.data.options).then((e=>{const t=[];for(let i=0;i{postMessage({action:"decoded",success:!1,msg:e})}))}}}class l{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:[n.Xl.BC1_RGB,n.Xl.BC3_RGBA],yes:{transcodeFormat:n.Xl.RGBA32,engineFormat:32856,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}}class h{static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if(h._WorkerPoolPromise||h._DecoderModulePromise)return;const t={jsDecoderModule:s.S0.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:s.S0.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:s.S0.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:s.S0.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:s.S0.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:s.S0.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:s.S0.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:s.S0.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:s.S0.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:s.S0.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?h._WorkerPoolPromise=new Promise((i=>{const s=`${o}(${a})()`,n=URL.createObjectURL(new Blob([s],{type:"application/javascript"}));i(new r.h(e,(()=>function(e,t,i){return new Promise(((t,r)=>{const s=t=>{e.removeEventListener("error",s),e.removeEventListener("message",n),r(t)},n=i=>{"init"===i.data.action&&(e.removeEventListener("error",s),e.removeEventListener("message",n),t(e))};e.addEventListener("error",s),e.addEventListener("message",n),e.postMessage({action:"init",urls:i,wasmBinaries:undefined})}))}(new Worker(n),0,t))))})):void 0===h._KTX2DecoderModule?h._DecoderModulePromise=s.S0.LoadBabylonScriptAsync(t.jsDecoderModule).then((()=>(h._KTX2DecoderModule=KTX2DECODER,h._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,h._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,o(t,h._KTX2DecoderModule),new h._KTX2DecoderModule.KTX2Decoder))):(h._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,h._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,h._DecoderModulePromise=Promise.resolve(new h._KTX2DecoderModule.KTX2Decoder))}constructor(e,t=h.DefaultNumWorkers){this._engine=e;const i="object"==typeof t&&t.workerPool||h.WorkerPool;if(i)h._WorkerPoolPromise=Promise.resolve(i);else{"object"==typeof t?h._KTX2DecoderModule=t?.binariesAndModulesContainer?.jsDecoderModule:"undefined"!=typeof KTX2DECODER&&(h._KTX2DecoderModule=KTX2DECODER);const e="number"==typeof t?t:t.numWorkers??h.DefaultNumWorkers;h._Initialize(e)}}_uploadAsync(e,t,i){const r=this._engine.getCaps(),s={astc:!!r.astc,bptc:!!r.bptc,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,etc1:!!r.etc1};if(h._WorkerPoolPromise)return h._WorkerPoolPromise.then((r=>new Promise(((n,o)=>{r.push(((r,a)=>{const l=e=>{r.removeEventListener("error",l),r.removeEventListener("message",c),o(e),a()},c=e=>{if("decoded"===e.data.action){if(r.removeEventListener("error",l),r.removeEventListener("message",c),e.data.success)try{this._createTexture(e.data.decodedData,t,i),n()}catch(e){o({message:e})}else o({message:e.data.msg});a()}};r.addEventListener("error",l),r.addEventListener("message",c),r.postMessage({action:"setDefaultDecoderOptions",options:h.DefaultDecoderOptions._getKTX2DecoderOptions()});const u=new Uint8Array(e.byteLength);u.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),r.postMessage({action:"decode",data:u,caps:s,options:i},[u.buffer])}))}))));if(h._DecoderModulePromise)return h._DecoderModulePromise.then((i=>(h.DefaultDecoderOptions.isDirty&&(h._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions=h.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise(((s,n)=>{i.decode(e,r).then((e=>{this._createTexture(e,t),s()})).catch((e=>{n({message:e})}))})))));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}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 i=0;i=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&50===t[5]&&48===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}h.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},h.DefaultNumWorkers=h.GetDefaultNumWorkers(),h.DefaultDecoderOptions=new l},60590:(e,t,i)=>{"use strict";i.d(t,{V:()=>r});class r{static _CheckLimit(e,t){let i=r._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},r._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){const i=r._LogLimitOutputs[e];if(!i||!r.MessageLimitReached)return;const s=this._Levels[t];i.current===i.limit&&r[s.name](r.MessageLimitReached.replace(/%LIMIT%/g,""+i.limit).replace(/%TYPE%/g,s.name??""))}static _AddLogEntry(e){r._LogCache=e+r._LogCache,r.OnNewCacheEntry&&r.OnNewCacheEntry(e)}static _FormatMessage(e){const t=e=>e<10?"0"+e:""+e,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(void 0!==i&&!r._CheckLimit(s,i))return;const n=r._FormatMessage(s),o=this._Levels[e],a=Array.isArray(t)?t.slice(1):[];o.logFunc&&o.logFunc("BJS - "+n,...a);const l=`
${n}

`;r._AddLogEntry(l),r._GenerateLimitMessage(s,e)}static get LogCache(){return r._LogCache}static ClearLogCache(){r._LogCache="",r._LogLimitOutputs={},r.errorsCount=0}static set LogLevels(e){r.Log=r._LogDisabled,r.Warn=r._LogDisabled,r.Error=r._LogDisabled,[r.MessageLogLevel,r.WarningLogLevel,r.ErrorLogLevel].forEach((t=>{if((e&t)===t){const e=this._Levels[t];r[e.name]=r._LogEnabled.bind(r,t)}}))}}r.NoneLogLevel=0,r.MessageLogLevel=1,r.WarningLogLevel=2,r.ErrorLogLevel=4,r.AllLogLevel=7,r.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",r._LogCache="",r._LogLimitOutputs={},r._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],r.errorsCount=0,r.Log=r._LogEnabled.bind(r,r.MessageLogLevel),r.Warn=r._LogEnabled.bind(r,r.WarningLogLevel),r.Error=r._LogEnabled.bind(r,r.ErrorLogLevel)},43279:(e,t,i)=>{"use strict";i.d(t,{cP:()=>n,nu:()=>s,qO:()=>r});class r{constructor(e,t=!1,i,r){this.initialize(e,t,i,r)}initialize(e,t=!1,i,r){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=r,this}}class s{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){if(this._remove){const e=this._remove.deref();e&&e()}}}class n{static FromPromise(e,t){const i=new n;return e.then((e=>{i.notifyObservers(e)})).catch((e=>{if(!t)throw e;t.notifyObservers(e)})),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 r(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,r=null,n=!1){if(!e)return null;const o=new s(e,t,r);return o.unregisterOnNextCall=n,i?this._observers.unshift(o):this._observers.push(o),this._onObserverAdded&&this._onObserverAdded(o),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(o,this._lastNotifiedValue),o._remove=new WeakRef((()=>{this.remove(o)})),o}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return!!e&&(e._remove=null,-1!==this._observers.indexOf(e)&&(this._deferUnregister(e),!0))}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-1!==i&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0)}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,r,s){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=r,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=s;for(const i of this._observers)if(!i._willBeUnregistered&&(i.mask&t&&(i.unregisterOnNextCall&&this._deferUnregister(i),i.scope?n.lastReturnValue=i.callback.apply(i.scope,[e,n]):n.lastReturnValue=i.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 r=this._eventState;r.mask=i,r.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,r)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){const e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new n;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}}},78641:(e,t,i)=>{"use strict";i.d(t,{A:()=>s});var r=i(64736);class s{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){s.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){s.Enabled&&(this._startMonitoringTime=r.j.Now)}endMonitoring(e=!0){if(!s.Enabled)return;e&&this.fetchNewFrame();const t=r.j.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=r.j.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}s.Enabled=!0},64736:(e,t,i)=>{"use strict";i.d(t,{j:()=>s});var r=i(68191);class s{static get Now(){return(0,r.BA)()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}},56703:(e,t,i)=>{"use strict";i.d(t,{a:()=>r});class r{static ExponentialBackoff(e=3,t=500){return(i,r,s)=>0!==r.status||s>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,s)*t}}},2069:(e,t,i)=>{"use strict";i.d(t,{G:()=>n});var r=i(52660),s=i(28876);class n{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const s=t.getEngine(),n=s.getCaps(),o=t.isReady;let a=!1;n.textureHalfFloatRender&&n.textureHalfFloatLinearFiltering?(a=!0,t.type=2):n.textureFloatRender&&n.textureFloatLinearFiltering&&(a=!0,t.type=1),a&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const l=async()=>{const n=s.isWebGPU,o=n?1:0;t.isReady=!1,n?await Promise.all([Promise.resolve().then(i.bind(i,79388)),Promise.resolve().then(i.bind(i,41572))]):await Promise.all([Promise.resolve().then(i.bind(i,64849)),Promise.resolve().then(i.bind(i,32957))]);const a=new r.w("rgbdDecode","rgbdDecode",null,null,1,null,3,s,!1,void 0,t.type,void 0,null,!1,void 0,o);a.externalTextureSamplerBinding=!0;const l=s.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});a.onEffectCreatedObservable.addOnce((i=>{i.executeWhenCompiled((()=>{a.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([a],l,!0),s.restoreDefaultFramebuffer(),s._releaseTexture(t),a&&a.dispose(),l._swapAndDie(t),t.isReady=!0}))}))};a&&(o?l():e.onLoadObservable.addOnce(l))}static EncodeTextureToRGBD(e,t,i=0){return(0,s.Qs)("rgbdEncode",e,t,i,1,5)}}},39464:(e,t,i)=>{"use strict";i.d(t,{L:()=>r,b:()=>s});class r{constructor(e){this.length=0,this.data=new Array(e),this._id=r._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=2*(this.length+e.length));for(let t=0;t=this.length?-1:t}contains(e){return-1!==this.indexOf(e)}}r._GlobalId=0;class s extends r{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||(this.push(e),0))}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;t{"use strict";i.d(t,{w:()=>r});class r{constructor(){this._count=0,this._data={}}copyFrom(e){this.clear(),e.forEach(((e,t)=>this.add(e,t)))}get(e){const t=this._data[e];if(void 0!==t)return t}getOrAddWithFactory(e,t){let i=this.get(e);return void 0!==i||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){const i=this.get(e);return void 0!==i?i:(this.add(e,t),t)}contains(e){return void 0!==this._data[e]}add(e,t){return void 0===this._data[e]&&(this._data[e]=t,++this._count,!0)}set(e,t){return void 0!==this._data[e]&&(this._data[e]=t,!0)}getAndRemove(e){const t=this.get(e);return void 0!==t?(delete this._data[e],--this._count,t):null}remove(e){return!!this.contains(e)&&(delete this._data[e],--this._count,!0)}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(const t in this._data)e(t,this._data[t])}first(e){for(const t in this._data){const i=e(t,this._data[t]);if(i)return i}return null}}},5800:(e,t,i)=>{"use strict";i.d(t,{AV:()=>a,EL:()=>o,LW:()=>h,Tq:()=>n,UH:()=>s,jq:()=>r,nQ:()=>c,yS:()=>l});const r=(e,t)=>e.endsWith(t),s=(e,t)=>!!e&&e.startsWith(t),n=e=>{if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let i=0;i{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let i,r,s,n,o,a,l,h="",c=0;const u=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;c>2,o=(3&i)<<4|r>>4,a=(15&r)<<2|s>>6,l=63&s,isNaN(r)?a=l=64:isNaN(s)&&(l=64),h+=t.charAt(n)+t.charAt(o)+t.charAt(a)+t.charAt(l);return h},a=e=>atob(e),l=e=>{const t=a(e),i=t.length,r=new Uint8Array(new ArrayBuffer(i));for(let e=0;e{let i=String(e);for(;i.length{"use strict";i.d(t,{Y:()=>s});var r=i(76486);class s{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>s.HasTags(e),e.addTags=t=>s.AddTagsTo(e,t),e.removeTags=t=>s.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>s.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 e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){const t=[];for(const i in e._tags)Object.prototype.hasOwnProperty.call(e._tags,i)&&!0===e._tags[i]&&t.push(i);return t.join(" ")}return e._tags}static AddTagsTo(e,t){t&&"string"==typeof t&&t.split(" ").forEach((function(t){s._AddTagTo(e,t)}))}static _AddTagTo(e,t){""!==(t=t.trim())&&"true"!==t&&"false"!==t&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(s.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!s.HasTags(e))return;const i=t.split(" ");for(const t in i)s._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?s.HasTags(e):r.Z.Eval(t,(t=>s.HasTags(e)&&e._tags[t])))}}},28876:(e,t,i)=>{"use strict";i.d(t,{EE:()=>a,LO:()=>_,LZ:()=>u,Oz:()=>p,Qs:()=>l,SX:()=>d});var r=i(4756),s=i(58059),n=i(78239),o=i(52660);function a(e,t,i,o=!0){const a=e.getScene(),l=a.getEngine(),h=new s.$("resized"+e.name,{width:t,height:i},a,!e.noMipmap,!0,e._texture.type,!1,e.samplingMode,!1);h.wrapU=e.wrapU,h.wrapV=e.wrapV,h.uOffset=e.uOffset,h.vOffset=e.vOffset,h.uScale=e.uScale,h.vScale=e.vScale,h.uAng=e.uAng,h.vAng=e.vAng,h.wAng=e.wAng,h.coordinatesIndex=e.coordinatesIndex,h.level=e.level,h.anisotropicFilteringLevel=e.anisotropicFilteringLevel,h._texture.isReady=!1,e.wrapU=r.g.CLAMP_ADDRESSMODE,e.wrapV=r.g.CLAMP_ADDRESSMODE;const c=new n.v("pass",1,null,o?r.g.BILINEAR_SAMPLINGMODE:r.g.NEAREST_SAMPLINGMODE,l,!1,0);return c.externalTextureSamplerBinding=!0,c.onEffectCreatedObservable.addOnce((t=>{t.executeWhenCompiled((()=>{c.onApply=function(t){t.setTexture("textureSampler",e)};const t=h.renderTarget;t&&(a.postProcessManager.directRender([c],t),l.unBindFramebuffer(t),h.disposeFramebufferObjects(),c.dispose(),h.getInternalTexture().isReady=!0)}))})),h}function l(e,t,i,r,s,n,a,l){const h=t.getEngine();return t.isReady=!1,s=s??t.samplingMode,r=r??t.type,n=n??t.format,a=a??t.width,l=l??t.height,-1===r&&(r=0),new Promise((c=>{const u=new o.w("postprocess",e,null,null,1,null,s,h,!1,void 0,r,void 0,null,!1,n);u.externalTextureSamplerBinding=!0;const d=h.createRenderTargetTexture({width:a,height:l},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:r,format:n});u.onEffectCreatedObservable.addOnce((e=>{e.executeWhenCompiled((()=>{u.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([u],d,!0),h.restoreDefaultFramebuffer(),h._releaseTexture(t),u&&u.dispose(),d._swapAndDie(t),t.type=r,t.format=5,t.isReady=!0,c(t)}))}))}))}let h,c;function u(e){h||(h=new Float32Array(1),c=new Int32Array(h.buffer)),h[0]=e;const t=c[0];let i=t>>16&32768,r=t>>12&2047;const s=t>>23&255;return s<103?i:s>142?(i|=31744,i|=(255==s?0:1)&&8388607&t,i):s<113?(r|=2048,i|=(r>>114-s)+(r>>113-s&1),i):(i|=s-112<<10|r>>1,i+=1&r,i)}function d(e){const t=(32768&e)>>15,i=(31744&e)>>10,r=1023&e;return 0===i?(t?-1:1)*Math.pow(2,-14)*(r/Math.pow(2,10)):31==i?r?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+r/Math.pow(2,10))}const f=async(e,t,n,a,l)=>{const h=e.getScene(),c=h.getEngine();let u;if(c.isWebGPU?e.isCube?await Promise.resolve().then(i.bind(i,61951)):await Promise.resolve().then(i.bind(i,58316)):e.isCube?await Promise.resolve().then(i.bind(i,47084)):await Promise.resolve().then(i.bind(i,46143)),e.isCube){const e=["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"];u=new o.w("lodCube","lodCube",{uniforms:["lod","gamma"],samplingMode:r.g.NEAREST_NEAREST_MIPNEAREST,engine:c,defines:e[a],shaderLanguage:c.isWebGPU?1:0})}else u=new o.w("lod","lod",{uniforms:["lod","gamma"],samplingMode:r.g.NEAREST_NEAREST_MIPNEAREST,engine:c,shaderLanguage:c.isWebGPU?1:0});await new Promise((e=>{u.onEffectCreatedObservable.addOnce((t=>{t.executeWhenCompiled((()=>{e(0)}))}))}));const d=new s.$("temp",{width:t,height:n},h,!1);u.onApply=function(t){t.setTexture("textureSampler",e),t.setFloat("lod",l),t.setInt("gamma",e.gammaSpace?1:0)};const f=e.getInternalTexture();try{if(d.renderTarget&&f){const i=f.samplingMode;0!==l?e.updateSamplingMode(r.g.NEAREST_NEAREST_MIPNEAREST):e.updateSamplingMode(r.g.NEAREST_NEAREST),h.postProcessManager.directRender([u],d.renderTarget,!0),e.updateSamplingMode(i);const s=await c.readPixels(0,0,t,n),o=new Uint8Array(s.buffer,0,s.byteLength);return c.unBindFramebuffer(d.renderTarget),o}throw Error("Render to texture failed.")}finally{d.dispose(),u.dispose()}};async function p(e,t,i,r=0,s=0){return!e.isReady()&&e._texture&&await new Promise(((t,i)=>{null!==e._texture?e._texture.onLoadedObservable.addOnce((()=>{t(0)})):i(0)})),await f(e,t,i,r,s)}const _={CreateResizedCopy:a,ApplyPostProcess:l,ToHalfFloat:u,FromHalfFloat:d,GetTextureDataAsync:p}},96172:(e,t,i)=>{"use strict";i.d(t,{FA:()=>g,O_:()=>m,uT:()=>v});var r=i(60590);const s=1,n=2,o=3,a=9,l=10,h=11,c=48,u=4,d=0,f=1,p=2,_=3;function m(e){let t=0;return{id_length:e[t++],colormap_type:e[t++],image_type:e[t++],colormap_index:e[t++]|e[t++]<<8,colormap_length:e[t++]|e[t++]<<8,colormap_size:e[t++],origin:[e[t++]|e[t++]<<8,e[t++]|e[t++]<<8],width:e[t++]|e[t++]<<8,height:e[t++]|e[t++]<<8,pixel_size:e[t++],flags:e[t++]}}function g(e,t){if(t.length<19)return void r.V.Error("Unable to load TGA file - Not enough data to contain header");let i=18;const g=m(t);if(g.id_length+i>t.length)return void r.V.Error("Unable to load TGA file - Not enough data");i+=g.id_length;let x,b=!1,S=!1,T=!1;switch(g.image_type){case a:b=!0;case s:S=!0;break;case l:b=!0;case n:break;case h:b=!0;case o:T=!0}const C=g.pixel_size>>3,y=g.width*g.height*C;let E,P,A,R,I,M,O;if(S&&(E=t.subarray(i,i+=g.colormap_length*(g.colormap_size>>3))),b){let e,r,s;x=new Uint8Array(y);let n=0;const o=new Uint8Array(C);for(;i>u){default:case p:P=0,R=1,O=g.width,A=0,I=1,M=g.height;break;case d:P=0,R=1,O=g.width,A=g.height-1,I=-1,M=-1;break;case _:P=g.width-1,R=-1,O=-1,A=0,I=1,M=g.height;break;case f:P=g.width-1,R=-1,O=-1,A=g.height-1,I=-1,M=-1}const D="_getImageData"+(T?"Grey":"")+g.pixel_size+"bits",w=v[D](g,E,x,A,I,M,P,R,O);e.getEngine()._uploadDataToTextureDirectly(e,w)}const v={GetTGAHeader:m,UploadContent:g,_getImageData8bits:function(e,t,i,r,s,n,o,a,l){const h=i,c=t,u=e.width,d=e.height;let f,p,_,m=0;const g=new Uint8Array(u*d*4);for(_=r;_!==n;_+=s)for(p=o;p!==l;p+=a,m++)f=h[m],g[4*(p+u*_)+3]=255,g[4*(p+u*_)+2]=c[3*f+0],g[4*(p+u*_)+1]=c[3*f+1],g[4*(p+u*_)+0]=c[3*f+2];return g},_getImageData16bits:function(e,t,i,r,s,n,o,a,l){const h=i,c=e.width,u=e.height;let d,f,p,_=0;const m=new Uint8Array(c*u*4);for(p=r;p!==n;p+=s)for(f=o;f!==l;f+=a,_+=2){d=h[_+0]+(h[_+1]<<8);const e=255*((31744&d)>>10)/31|0,t=255*((992&d)>>5)/31|0,i=255*(31&d)/31|0;m[4*(f+c*p)+0]=e,m[4*(f+c*p)+1]=t,m[4*(f+c*p)+2]=i,m[4*(f+c*p)+3]=32768&d?0:255}return m},_getImageData24bits:function(e,t,i,r,s,n,o,a,l){const h=i,c=e.width,u=e.height;let d,f,p=0;const _=new Uint8Array(c*u*4);for(f=r;f!==n;f+=s)for(d=o;d!==l;d+=a,p+=3)_[4*(d+c*f)+3]=255,_[4*(d+c*f)+2]=h[p+0],_[4*(d+c*f)+1]=h[p+1],_[4*(d+c*f)+0]=h[p+2];return _},_getImageData32bits:function(e,t,i,r,s,n,o,a,l){const h=i,c=e.width,u=e.height;let d,f,p=0;const _=new Uint8Array(c*u*4);for(f=r;f!==n;f+=s)for(d=o;d!==l;d+=a,p+=4)_[4*(d+c*f)+2]=h[p+0],_[4*(d+c*f)+1]=h[p+1],_[4*(d+c*f)+0]=h[p+2],_[4*(d+c*f)+3]=h[p+3];return _},_getImageDataGrey8bits:function(e,t,i,r,s,n,o,a,l){const h=i,c=e.width,u=e.height;let d,f,p,_=0;const m=new Uint8Array(c*u*4);for(p=r;p!==n;p+=s)for(f=o;f!==l;f+=a,_++)d=h[_],m[4*(f+c*p)+0]=d,m[4*(f+c*p)+1]=d,m[4*(f+c*p)+2]=d,m[4*(f+c*p)+3]=255;return m},_getImageDataGrey16bits:function(e,t,i,r,s,n,o,a,l){const h=i,c=e.width,u=e.height;let d,f,p=0;const _=new Uint8Array(c*u*4);for(f=r;f!==n;f+=s)for(d=o;d!==l;d+=a,p+=2)_[4*(d+c*f)+0]=h[p+0],_[4*(d+c*f)+1]=h[p+0],_[4*(d+c*f)+2]=h[p+0],_[4*(d+c*f)+3]=h[p+1];return _}}},72649:(e,t,i)=>{"use strict";i.d(t,{_:()=>s});var r=i(68191);class s{static SetImmediate(e){(0,r.BA)()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}},44512:(e,t,i)=>{"use strict";function r(e){let t=1;do{t*=2}while(te-i?i:t}function o(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}function a(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}function l(e,t,i=2){let r;switch(i){case 1:r=a(e);break;case 2:r=n(e);break;default:r=o(e)}return Math.min(r,t)}i.d(t,{C4:()=>a,L8:()=>r,OG:()=>n,R:()=>l,zF:()=>s})},9723:(e,t,i)=>{"use strict";i.d(t,{LV:()=>v,S0:()=>m,s7:()=>g});var r=i(43279),s=i(68191),n=i(60590),o=i(35290),a=i(64736),l=i(75108),h=i(67313),c=i(34268),u=i(28909),d=i(72649),f=i(14798),p=i(71627),_=i(44512);class m{static get BaseUrl(){return u.eC.BaseUrl}static set BaseUrl(e){u.eC.BaseUrl=e}static get CleanUrl(){return u.eC.CleanUrl}static set CleanUrl(e){u.eC.CleanUrl=e}static IsAbsoluteUrl(e){return 0===e.indexOf("//")||-1!==e.indexOf("://")&&-1!==e.indexOf(".")&&-1!==e.indexOf("/")&&!(e.indexOf(":")>e.indexOf("/"))&&(e.indexOf("://"){(0,u.zU)(e,(e=>{i(e)}),void 0,void 0,t,((e,t)=>{r(t)}))}))}static GetBabylonScriptURL(e,t){if(!e)return"";if(m.ScriptBaseUrl&&e.startsWith(m._DefaultCdnUrl)){const t="/"===m.ScriptBaseUrl[m.ScriptBaseUrl.length-1]?m.ScriptBaseUrl.substring(0,m.ScriptBaseUrl.length-1):m.ScriptBaseUrl;e=e.replace(m._DefaultCdnUrl,t)}return e=m.ScriptPreprocessUrl(e),t&&(e=m.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,r){e=m.GetBabylonScriptURL(e),m.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=m.GetBabylonScriptURL(e),m.LoadScriptAsync(e)}static LoadScript(e,t,i,r,n=!1){if("function"==typeof importScripts){try{importScripts(e),t&&t()}catch(t){i?.(`Unable to load script '${e}' in worker`,t)}return}if(!(0,s.BA)())return void i?.(`Cannot load script '${e}' outside of a window or a worker`);const o=document.getElementsByTagName("head")[0],a=document.createElement("script");n?(a.setAttribute("type","module"),a.innerText=e):(a.setAttribute("type","text/javascript"),a.setAttribute("src",e)),r&&(a.id=r),a.onload=()=>{t&&t()},a.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},o.appendChild(a)}static LoadScriptAsync(e,t){return new Promise(((i,r)=>{this.LoadScript(e,(()=>{i()}),((e,t)=>{r(t||new Error(e))}),t)}))}static ReadFileAsDataURL(e,t,i){const s=new FileReader,n={onCompleteObservable:new r.cP,abort:()=>s.abort()};return s.onloadend=()=>{n.onCompleteObservable.notifyObservers(n)},s.onload=e=>{t(e.target.result)},s.onprogress=i,s.readAsDataURL(e),n}static ReadFile(e,t,i,r,s){return(0,u.NJ)(e,t,i,r,s)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,r){o.r.DeepCopy(e,t,i,r)}static IsEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i{const r=atob(this.toDataURL(t,i).split(",")[1]),s=r.length,n=new Uint8Array(s);for(let e=0;et(e))):e.toBlob((function(e){t(e)}),i,r)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){const e=new Date;t="screenshot_"+(e.getFullYear()+"-"+(e.getMonth()+1)).slice(2)+"-"+e.getDate()+"_"+e.getHours()+"-"+("0"+e.getMinutes()).slice(-2)+".png"}m.Download(e,t)}else if(e&&"undefined"!=typeof URL){const t=URL.createObjectURL(e),i=window.open("");if(!i)return;const r=i.document.createElement("img");r.onload=function(){URL.revokeObjectURL(t)},r.src=t,i.document.body.appendChild(r)}}static EncodeScreenshotCanvasData(e,t,i="image/png",r,s){if("string"!=typeof r&&t){if(t){if(m._IsOffScreenCanvas(e))return void e.convertToBlob({type:i,quality:s}).then((e=>{const i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{const e=i.result;t(e)}}));const r=e.toDataURL(i,s);t(r)}}else this.ToBlob(e,(function(e){e&&m.DownloadBlob(e,r),t&&t("")}),i,s)}static Download(e,t){if("undefined"==typeof URL)return;const i=window.URL.createObjectURL(e),r=document.createElement("a");document.body.appendChild(r),r.style.display="none",r.href=i,r.download=t,r.addEventListener("click",(()=>{r.parentElement&&r.parentElement.removeChild(r)})),r.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,i,r,s="image/png",n=!1,o){throw(0,l.n)("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,r="image/png",s){throw(0,l.n)("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,r,s="image/png",n=1,o=!1,a,h=!1,c=!1,u=!0,d,f){throw(0,l.n)("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,r="image/png",s=1,n=!1,o,a=!1,h=!1,c=!0,u,d){throw(0,l.n)("ScreenshotTools")}static RandomId(){return(0,p.z)()}static IsBase64(e){return(0,u.f2)(e)}static DecodeBase64(e){return(0,u.rz)(e)}static get errorsCount(){return n.V.errorsCount}static Log(e){n.V.Log(e)}static Warn(e){n.V.Warn(e)}static Error(e){n.V.Error(e)}static get LogCache(){return n.V.LogCache}static ClearLogCache(){n.V.ClearLogCache()}static set LogLevels(e){n.V.LogLevels=e}static set PerformanceLogLevel(e){return(e&m.PerformanceUserMarkLogLevel)===m.PerformanceUserMarkLogLevel?(m.StartPerformanceCounter=m._StartUserMark,void(m.EndPerformanceCounter=m._EndUserMark)):(e&m.PerformanceConsoleLogLevel)===m.PerformanceConsoleLogLevel?(m.StartPerformanceCounter=m._StartPerformanceConsole,void(m.EndPerformanceCounter=m._EndPerformanceConsole)):(m.StartPerformanceCounter=m._StartPerformanceCounterDisabled,void(m.EndPerformanceCounter=m._EndPerformanceCounterDisabled))}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!m._Performance){if(!(0,s.BA)())return;m._Performance=window.performance}t&&m._Performance.mark&&m._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&m._Performance.mark&&(m._Performance.mark(e+"-End"),m._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(m._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(m._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return a.j.Now}static GetClassName(e,t=!1){let i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),i}static First(e,t){for(const i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,r=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const s=t?e:Object.getPrototypeOf(e);i=s.constructor.__bjsclassName__,r=s.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=r?r+".":"")+i:null}static DelayAsync(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}static IsSafari(){return!!(0,s.XD)()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}function g(e,t){return i=>{i.__bjsclassName__=e,i.__bjsmoduleName__=null!=t?t:null}}m.UseCustomRequestHeaders=!1,m.CustomRequestHeaders=h.u.CustomRequestHeaders,m.GetDOMTextContent=s.Zl,m._DefaultCdnUrl="https://cdn.babylonjs.com",m.GetAbsoluteUrl="object"==typeof document?e=>{const t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?e=>new URL(e,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},m.NoneLogLevel=n.V.NoneLogLevel,m.MessageLogLevel=n.V.MessageLogLevel,m.WarningLogLevel=n.V.WarningLogLevel,m.ErrorLogLevel=n.V.ErrorLogLevel,m.AllLogLevel=n.V.AllLogLevel,m.IsWindowObjectExist=s.BA,m.PerformanceNoneLogLevel=0,m.PerformanceUserMarkLogLevel=1,m.PerformanceConsoleLogLevel=2,m.StartPerformanceCounter=m._StartPerformanceCounterDisabled,m.EndPerformanceCounter=m._EndPerformanceCounterDisabled;class v{constructor(e,t,i,r=0){this.iterations=e,this.index=r-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{s&&s()?r.breakLoop():setTimeout((()=>{for(let n=0;n=e)break;if(i(o),s&&s()){r.breakLoop();break}}r.executeNext()}),n)}),r)}}m.Mix=_.zF,m.IsExponentOfTwo=_.L8,c.q.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"},56225:(e,t,i)=>{"use strict";i.d(t,{Uu:()=>o,Y5:()=>s,n9:()=>n});const r={};function s(e,t){r[e]=t}function n(e){return r[e]}function o(e){for(const t in r)if(e instanceof r[t]&&!t.includes("Abstract"))return t;return"Unknown"}},83839:(e,t,i)=>{"use strict";i.d(t,{K:()=>r});class r{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}r._UniqueIdCounter=1},67313:(e,t,i)=>{"use strict";i.d(t,{u:()=>r});class r{constructor(){this._xhr="undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest,this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(r.CustomRequestHeaders).length>0||r.CustomRequestModifiers.length>0}get requestURL(){return this._requestURL}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in r.CustomRequestHeaders){const t=r.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return r.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){r.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const e of r.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;e(this._xhr,t)}t=(t=t.replace("file:http:","http:")).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)}}r.CustomRequestHeaders={},r.CustomRequestModifiers=new Array,r.SkipRequestModificationForBabylonCDN=!0},28382:(e,t,i)=>{"use strict";i.d(t,{T:()=>r,h:()=>s});class r{constructor(e){this._pendingActions=new Array,this._workerInfos=e.map((e=>({workerPromise:Promise.resolve(e),idle:!0})))}dispose(){for(const e of this._workerInfos)e.workerPromise.then((e=>{e.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 t=this._pendingActions.shift();t?this._execute(e,t):e.idle=!0}))}))}}class s extends r{constructor(e,t,i=s.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length{t(i,(()=>{r(),e.idle&&(e.timeoutId=setTimeout((()=>{e.workerPromise.then((e=>{e.terminate()}));const t=this._workerInfos.indexOf(e);-1!==t&&this._workerInfos.splice(t,1)}),this._options.idleTimeElapsedBeforeRelease))}))}))}}s.DefaultOptions={idleTimeElapsedBeforeRelease:1e3}},78239:(e,t,i)=>{"use strict";i.d(t,{s:()=>l,v:()=>a});var r=i(52660),s=i(55935),n=i(56225),o=i(89518);class a extends r.w{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,r,s,n,o=0,a=!1){super(e,"pass",null,null,t,i,r,s,n,void 0,o,void 0,null,a)}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,418))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,30927))])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return o.p.Parse((()=>new a(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,r)}}(0,n.Y5)("BABYLON.PassPostProcess",a);class l extends r.w{get face(){return this._face}set face(e){if(!(e<0||e>5))switch(this._face=e,this._face){case 0:this.updateEffect("#define POSITIVEX");break;case 1:this.updateEffect("#define NEGATIVEX");break;case 2:this.updateEffect("#define POSITIVEY");break;case 3:this.updateEffect("#define NEGATIVEY");break;case 4:this.updateEffect("#define POSITIVEZ");break;case 5:this.updateEffect("#define NEGATIVEZ")}}getClassName(){return"PassCubePostProcess"}constructor(e,t,i=null,r,s,n,o=0,a=!1){super(e,"passCube",null,null,t,i,r,s,n,"#define POSITIVEX",o,void 0,null,a),this._face=0}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,12253))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,88412))])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return o.p.Parse((()=>new l(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,r)}}s.$._RescalePostProcessFactory=e=>new a("rescale",1,null,2,e,!1,0)},52660:(e,t,i)=>{"use strict";i.d(t,{w:()=>p});var r=i(15287),s=i(39464),n=i(43279),o=i(94212),a=i(36217),l=i(40220),h=i(89518),c=i(56225),u=i(55935),d=i(44512),f=i(50606);u.$.prototype.setTextureFromPostProcess=function(e,t,i){let r=null;t&&(t._forcedOutputTexture?r=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(r=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,r?.texture??null,i)},u.$.prototype.setTextureFromPostProcessOutput=function(e,t,i){this._bindTexture(e,t?._outputTexture?.texture??null,i)},a.M.prototype.setTextureFromPostProcess=function(e,t){this._engine.setTextureFromPostProcess(this._samplers[e],t,e)},a.M.prototype.setTextureFromPostProcessOutput=function(e,t){this._engine.setTextureFromPostProcessOutput(this._samplers[e],t,e)};class p{static get ForceGLSL(){return f.$.ForceGLSL}static set ForceGLSL(e){f.$.ForceGLSL=e}static RegisterShaderCodeProcessing(e,t){f.$.RegisterShaderCodeProcessing(e,t)}get name(){return this._effectWrapper.name}set name(e){this._effectWrapper.name=e}get alphaMode(){return this._effectWrapper.alphaMode}set alphaMode(e){this._effectWrapper.alphaMode=e}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach((e=>{e.setSamples(this._samples)}))}get shaderLanguage(){return this._shaderLanguage}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,r,a,l,h=1,c,u,d=null,_=0,m="postprocess",g,v=!1,x=5,b,S){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._webGPUReady=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new s.L(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new o.I9(1,1),this._texelSize=o.I9.Zero(),this.onActivateObservable=new n.cP,this.onSizeChangedObservable=new n.cP,this.onApplyObservable=new n.cP,this.onBeforeRenderObservable=new n.cP,this.onAfterRenderObservable=new n.cP;let T,C=1,y=null;if(i&&!Array.isArray(i)){const e=i;i=e.uniforms??null,r=e.samplers??null,C=e.size??1,l=e.camera??null,h=e.samplingMode??1,c=e.engine,u=e.reusable,d=Array.isArray(e.defines)?e.defines.join("\n"):e.defines??null,_=e.textureType??0,m=e.vertexUrl??"postprocess",g=e.indexParameters,v=e.blockCompilation??!1,x=e.textureFormat??5,b=e.shaderLanguage??0,y=e.uniformBuffers??null,S=e.extraInitializations,T=e.effectWrapper}else a&&(C="number"==typeof a?a:{width:a.width,height:a.height});const E=!!T;if(this._effectWrapper=T??new f.$({name:e,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:t,engine:c||l?.getScene().getEngine(),uniforms:i,samplers:r,uniformBuffers:y,defines:d,vertexUrl:m,indexParameters:g,blockCompilation:!0,shaderLanguage:b,extraInitializations:void 0}),this.name=e,this.onEffectCreatedObservable=this._effectWrapper.onEffectCreatedObservable,null!=l?(this._camera=l,this._scene=l.getScene(),l.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):c&&(this._engine=c,this._engine.postProcesses.push(this)),this._options=C,this.renderTargetSamplingMode=h||1,this._reusable=u||!1,this._textureType=_,this._textureFormat=x,this._shaderLanguage=b||0,this._samplers=r||[],-1===this._samplers.indexOf("textureSampler")&&this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=m,this._parameters=i||[],-1===this._parameters.indexOf("scale")&&this._parameters.push("scale"),this._uniformBuffers=y||[],this._indexParameters=g,!E){this._webGPUReady=1===this._shaderLanguage;const e=[];this._gatherImports(this._engine.isWebGPU&&!p.ForceGLSL,e),this._effectWrapper._webGPUReady=this._webGPUReady,this._effectWrapper._postConstructor(v,d,S,e)}}_gatherImports(e=!1,t){e&&this._webGPUReady?t.push(Promise.all([Promise.resolve().then(i.bind(i,45010))])):t.push(Promise.all([Promise.resolve().then(i.bind(i,18013))]))}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._effectWrapper.drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){0==this._textures.length&&(this._textures=new s.L(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,r,s,n,o,a){this._effectWrapper.updateEffect(e,t,i,r,s,n,o,a),this._postProcessDefines=Array.isArray(this._effectWrapper.options.defines)?this._effectWrapper.options.defines.join("\n"):this._effectWrapper.options.defines}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 e=!1;for(let i=0;i0&&this._textures.reset(),this.width=e,this.height=t;let n=null;if(i)for(let e=0;e{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)})),this._flushTextureCache(),this._renderId++}return u||(u=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(o/l,a/h),this._engine.bindFramebuffer(u,0,o,a,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(u,0,void 0,void 0,this.forceFullscreenViewport)),this._engine._debugInsertMarker?.(`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(0===this.alphaMode||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:r.clearColor,r._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),u}get isSupported(){return this._effectWrapper.drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){return this._effectWrapper.isReady()}apply(){if(!this._effectWrapper.isReady())return null;let e;return this._engine.enableEffect(this._effectWrapper.drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),e=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._effectWrapper.drawWrapper.effect._bindTexture("textureSampler",e?.texture),this._effectWrapper.drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._effectWrapper.drawWrapper.effect),this._effectWrapper.bind(),this._effectWrapper.drawWrapper.effect}_disposeTextures(){this._shareOutputWithPostProcess||this._forcedOutputTexture?this._disposeTextureCache():(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)}dispose(e){let t;if(e=e||this._camera,this._disposeTextures(),this._scene&&(t=this._scene.postProcesses.indexOf(this),-1!==t&&this._scene.postProcesses.splice(t,1)),this._parentContainer){const e=this._parentContainer.postProcesses.indexOf(this);e>-1&&this._parentContainer.postProcesses.splice(e,1),this._parentContainer=null}if(t=this._engine.postProcesses.indexOf(this),-1!==t&&this._engine.postProcesses.splice(t,1),e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),0===t&&e._postProcesses.length>0){const e=this._camera._getFirstPostProcess();e&&e.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear(),this.onEffectCreatedObservable.clear()}}serialize(){const e=h.p.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.uniformBuffers=this._uniformBuffers,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=p.Parse(e,this._scene,"");return t?(t.onActivateObservable=this.onActivateObservable.clone(),t.onSizeChangedObservable=this.onSizeChangedObservable.clone(),t.onApplyObservable=this.onApplyObservable.clone(),t.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),t.onAfterRenderObservable=this.onAfterRenderObservable.clone(),t._prePassEffectConfiguration=this._prePassEffectConfiguration,t):null}static Parse(e,t,i){const r=(0,c.n9)(e.customType);if(!r||!r._Parse)return null;const s=t?t.getCameraById(e.cameraId):null;return r._Parse(e,s,t,i)}static _Parse(e,t,i,r){return h.p.Parse((()=>new p(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat)),e,i,r)}}(0,r.Cg)([(0,l.lK)()],p.prototype,"uniqueId",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"name",null),(0,r.Cg)([(0,l.lK)()],p.prototype,"width",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"height",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"renderTargetSamplingMode",void 0),(0,r.Cg)([(0,l.qK)()],p.prototype,"clearColor",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"autoClear",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"forceAutoClearInAlphaMode",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"alphaMode",null),(0,r.Cg)([(0,l.lK)()],p.prototype,"alphaConstants",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"enablePixelPerfectMode",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"forceFullscreenViewport",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"scaleMode",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"alwaysForcePOT",void 0),(0,r.Cg)([(0,l.lK)("samples")],p.prototype,"_samples",void 0),(0,r.Cg)([(0,l.lK)()],p.prototype,"adaptScaleToCurrentViewport",void 0),(0,c.Y5)("BABYLON.PostProcess",p)},2449:(e,t,i)=>{"use strict";i.d(t,{X:()=>n});var r=i(12721),s=i(43279);class n{constructor(e){this._vertexBuffers={},this.onBeforeRenderObservable=new s.cP,this._scene=e}_prepareBuffers(){if(this._vertexBuffers[r.R.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[r.R.PositionKind]=new r.R(this._scene.getEngine(),e,r.R.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[r.R.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!(!i||!(t=t||i._postProcesses.filter((e=>null!=e)))||0===t.length||!this._scene.postProcessesEnabled||(t[0].activate(i,e,null!=t),0))}directRender(e,t=null,i=!1,r=0,s=0,n=!1){const o=this._scene.getEngine();for(let a=0;anull!=e))).length||!this._scene.postProcessesEnabled)return;const o=this._scene.getEngine();for(let a=0,l=r.length;a{"use strict";i.d(t,{P:()=>o});var r=i(43279),s=i(75653),n=i(34130);class o{get renderList(){return this._renderList}set renderList(e){this._renderList!==e&&(this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=(0,n.lL)(e,this._renderListHasChanged)),this._renderList=e)}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}setMaterialForRendering(e,t){let i;i=Array.isArray(e)?e:[e];for(let e=0;e{const i=this._renderList?this._renderList.length:0;(0===t&&i>0||0===i)&&this._scene.meshes.forEach((e=>{e._markSubMeshesAsLightDirty()}))},this.particleSystemList=null,this.getCustomRenderList=null,this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.onBeforeRenderObservable=new r.cP,this.onAfterRenderObservable=new r.cP,this.onBeforeRenderingManagerRenderObservable=new r.cP,this.onAfterRenderingManagerRenderObservable=new r.cP,this.onFastPathRenderObservable=new r.cP,this._currentRefreshId=-1,this._refreshRate=1,this._currentSceneCamera=null,this.name=e,this._scene=t,this.renderList=[],this._renderPassIds=[],this.options={numPasses:1,doNotChangeAspectRatio:!0,...i},this._createRenderPassId(),this.renderPassId=this._renderPassIds[0],this._renderingManager=new s.m(t),this._renderingManager._useSceneAutoClearSetup=!0}_releaseRenderPassId(){const e=this._scene.getEngine();for(let t=0;t1&&(e.incrementRenderId(),e.resetCachedMaterial())}const n=this.particleSystemList||e.particleSystems;for(const e of n)e.isReady()||(r=!1);return t.currentRenderPassId=i,r}_prepareRenderingManager(e,t,i){const r=this._scene,s=r.activeCamera;this._renderingManager.reset();const n=r.getRenderId();for(let o=0;o{"use strict";i.d(t,{U:()=>n});var r=i(39464),s=i(94212);class n{set opaqueSortCompareFn(e){this._opaqueSortCompareFn=e||n.PainterSortCompare,this._renderOpaque=this._renderOpaqueSorted}set alphaTestSortCompareFn(e){this._alphaTestSortCompareFn=e||n.PainterSortCompare,this._renderAlphaTest=this._renderAlphaTestSorted}set transparentSortCompareFn(e){this._transparentSortCompareFn=e||n.defaultTransparentSortCompare,this._renderTransparent=this._renderTransparentSorted}constructor(e,t,i=null,s=null,n=null){this.index=e,this._opaqueSubMeshes=new r.L(256),this._transparentSubMeshes=new r.L(256),this._alphaTestSubMeshes=new r.L(256),this._depthOnlySubMeshes=new r.L(256),this._particleSystems=new r.L(256),this._spriteManagers=new r.L(256),this._empty=!0,this._edgesRenderers=new r.b(16),this._scene=t,this.opaqueSortCompareFn=i,this.alphaTestSortCompareFn=s,this.transparentSortCompareFn=n}render(e,t,i,r){if(e)return void e(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,this._depthOnlySubMeshes);const s=this._scene.getEngine();0!==this._depthOnlySubMeshes.length&&(s.setColorWrite(!1),this._renderAlphaTest(this._depthOnlySubMeshes),s.setColorWrite(!0)),0!==this._opaqueSubMeshes.length&&this._renderOpaque(this._opaqueSubMeshes),0!==this._alphaTestSubMeshes.length&&this._renderAlphaTest(this._alphaTestSubMeshes);const n=s.getStencilBuffer();if(s.setStencilBuffer(!1),t&&this._renderSprites(),i&&this._renderParticles(r),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),0!==this._transparentSubMeshes.length||this._scene.useOrderIndependentTransparency){if(s.setStencilBuffer(n),this._scene.useOrderIndependentTransparency){const e=this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);e.length&&this._renderTransparent(e)}else this._renderTransparent(this._transparentSubMeshes);s.setAlphaMode(0)}if(s.setStencilBuffer(!1),this._edgesRenderers.length){for(let e=0;et._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){const i=e.getMesh(),r=t.getMesh();return i.material&&r.material?i.material.uniqueId-r.material.uniqueId:i.uniqueId-r.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(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(0===this._particleSystems.length)return;const t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i{"use strict";i.d(t,{m:()=>n,o:()=>s});var r=i(20005);class s{}class n{get maintainStateBetweenFrames(){return this._maintainStateBetweenFrames}set maintainStateBetweenFrames(e){e!==this._maintainStateBetweenFrames&&(this._maintainStateBetweenFrames=e,this._maintainStateBetweenFrames||this.restoreDispachedFlags())}restoreDispachedFlags(){for(const e of this._scene.meshes)if(e.subMeshes)for(const t of e.subMeshes)t._wasDispatched=!1;if(this._scene.spriteManagers)for(const e of this._scene.spriteManagers)e._wasDispatched=!1;for(const e of this._scene.particleSystems)e._wasDispatched=!1}constructor(e){this._useSceneAutoClearSetup=!1,this._renderingGroups=new Array,this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderingGroupInfo=new s,this._maintainStateBetweenFrames=!1,this._scene=e;for(let e=n.MIN_RENDERINGGROUPS;e{"use strict";var r=i(69841);i(32405);r.l.IncludesShadersStore.backgroundUboDeclaration="layout(std140,column_major) uniform;uniform Material\n{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;};\n#include\n"},95532:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.bakedVertexAnimation="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\n#ifdef INSTANCES\n#define BVASNAME bakedVertexAnimationSettingsInstanced\n#else\n#define BVASNAME bakedVertexAnimationSettings\n#endif\nfloat 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];\n#if NUM_BONE_INFLUENCERS>1\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3];\n#endif\nfinalWorld=finalWorld*VATInfluence;}\n#endif\n"},66682:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.bakedVertexAnimationDeclaration="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform float bakedVertexAnimationTime;uniform vec2 bakedVertexAnimationTextureSizeInverted;uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture;\n#ifdef INSTANCES\nattribute vec4 bakedVertexAnimationSettingsInstanced;\n#endif\n#define inline\nmat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame)\n{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);}\n#endif\n"},39948:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bonesDeclaration:()=>n});const r="bonesDeclaration",s="#if NUM_BONE_INFLUENCERS>0\nattribute vec4 matricesIndices;attribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra;\n#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nuniform highp sampler2D boneSampler;uniform float boneTextureWidth;\n#else\nuniform mat4 mBones[BonesPerMesh];\n#endif\n#ifdef BONES_VELOCITY_ENABLED\nuniform mat4 mPreviousBones[BonesPerMesh];\n#endif\n#ifdef BONETEXTURE\n#define inline\nmat4 readMatrixFromRawSampler(sampler2D smp,float index)\n{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);}\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},78792:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bonesVertex:()=>n});const r="bonesVertex",s="#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3];\n#endif\n#else\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\n#endif\nfinalWorld=finalWorld*influence;\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},97315:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.boundingBoxRendererUboDeclaration="#ifdef WEBGL2\nuniform vec4 color;uniform mat4 world;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#else\nlayout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;};\n#endif\n"},90249:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bumpFragment:()=>n});const r="bumpFragment",s="vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#elif defined(BUMP)\nfloat normalScale=vBumpInfos.y;\n#else\nfloat normalScale=1.0;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#elif defined(BUMP)\nvec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams);\n#else\nvec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.));\n#endif\n#elif defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nvec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.));\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef DETAIL\nvec4 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);\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\n#define CUSTOM_FRAGMENT_BUMP_FRAGMENT\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3(normalMatrix)*normalW);\n#elif !defined(DETAIL)\nnormalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y);\n#else\nvec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0;\n#if DETAIL_NORMALBLENDMETHOD==0 \ndetailNormal.xy*=vDetailInfos.z;vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z));\n#elif DETAIL_NORMALBLENDMETHOD==1 \ndetailNormal.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;\n#endif\nnormalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y);\n#endif\n#elif defined(DETAIL)\ndetailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z);\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},29424:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bumpFragmentFunctions:()=>o});var r=i(69841);i(5301);const s="bumpFragmentFunctions",n="#if defined(BUMP)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)\n#endif\n#if defined(DETAIL)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail)\n#endif\n#if defined(BUMP) && defined(PARALLAX)\nconst 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)\n{float delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;}\nelse\n{currRayHeight-=stepSize;vLastOffset=vCurrOffset;\n#ifdef PARALLAX_RHS\nvCurrOffset-=stepSize*vMaxOffset;\n#else\nvCurrOffset+=stepSize*vMaxOffset;\n#endif\nlastSampledHeight=currSampledHeight;}}\nreturn vCurrOffset;}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{float height=texture2D(bumpSampler,vBumpUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height;\n#ifdef PARALLAX_RHS\nreturn texCoordOffset;\n#else\nreturn -texCoordOffset;\n#endif\n}\n#endif\n";r.l.IncludesShadersStore[s]=n;const o={name:s,shader:n}},82267:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bumpFragmentMainFunctions:()=>n});const r="bumpFragmentMainFunctions",s="#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#if defined(WEBGL2) || defined(WEBGPU)\nmat4 toNormalMatrix(mat4 wMatrix)\n{mat4 ret=inverse(wMatrix);ret=transpose(ret);ret[0][3]=0.;ret[1][3]=0.;ret[2][3]=0.;ret[3]=vec4(0.,0.,0.,1.);return ret;}\n#else\nmat4 toNormalMatrix(mat4 m)\n{float\na00=m[0][0],a01=m[0][1],a02=m[0][2],a03=m[0][3],\na10=m[1][0],a11=m[1][1],a12=m[1][2],a13=m[1][3],\na20=m[2][0],a21=m[2][1],a22=m[2][2],a23=m[2][3],\na30=m[3][0],a31=m[3][1],a32=m[3][2],a33=m[3][3],\nb00=a00*a11-a01*a10,\nb01=a00*a12-a02*a10,\nb02=a00*a13-a03*a10,\nb03=a01*a12-a02*a11,\nb04=a01*a13-a03*a11,\nb05=a02*a13-a03*a12,\nb06=a20*a31-a21*a30,\nb07=a20*a32-a22*a30,\nb08=a20*a33-a23*a30,\nb09=a21*a32-a22*a31,\nb10=a21*a33-a23*a31,\nb11=a22*a33-a23*a32,\ndet=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;mat4 mi=mat4(\na11*b11-a12*b10+a13*b09,\na02*b10-a01*b11-a03*b09,\na31*b05-a32*b04+a33*b03,\na22*b04-a21*b05-a23*b03,\na12*b08-a10*b11-a13*b07,\na00*b11-a02*b08+a03*b07,\na32*b02-a30*b05-a33*b01,\na20*b05-a22*b02+a23*b01,\na10*b10-a11*b08+a13*b06,\na01*b08-a00*b10-a03*b06,\na30*b04-a31*b02+a33*b00,\na21*b02-a20*b04-a23*b00,\na11*b07-a10*b09-a12*b06,\na00*b09-a01*b07+a02*b06,\na31*b01-a30*b03-a32*b00,\na20*b03-a21*b01+a22*b00)/det;return mat4(mi[0][0],mi[1][0],mi[2][0],mi[3][0],\nmi[0][1],mi[1][1],mi[2][1],mi[3][1],\nmi[0][2],mi[1][2],mi[2][2],mi[3][2],\nmi[0][3],mi[1][3],mi[2][3],mi[3][3]);}\n#endif\n#endif\nvec3 perturbNormalBase(mat3 cotangentFrame,vec3 normal,float scale)\n{\n#ifdef NORMALXYSCALE\nnormal=normalize(normal*vec3(scale,scale,1.0));\n#endif\nreturn normalize(cotangentFrame*normal);}\nvec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale)\n{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);}\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams)\n{vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;float det=max(dot(tangent,tangent),dot(bitangent,bitangent));float invmax=det==0.0 ? 0.0 : inversesqrt(det);return mat3(tangent*invmax,bitangent*invmax,normal);}\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},78595:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.bumpVertex="#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif\n"},17727:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.bumpVertexDeclaration="#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n"},89797:(e,t,i)=>{"use strict";i.r(t),i.d(t,{clipPlaneFragment:()=>n});const r="clipPlaneFragment",s="#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nif (false) {}\n#endif\n#ifdef CLIPPLANE\nelse if (fClipDistance>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE2\nelse if (fClipDistance2>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE3\nelse if (fClipDistance3>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE4\nelse if (fClipDistance4>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE5\nelse if (fClipDistance5>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE6\nelse if (fClipDistance6>0.0)\n{discard;}\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},77165:(e,t,i)=>{"use strict";i.r(t),i.d(t,{clipPlaneFragmentDeclaration:()=>n});const r="clipPlaneFragmentDeclaration",s="#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nvarying float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nvarying float fClipDistance6;\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},71471:(e,t,i)=>{"use strict";i.r(t),i.d(t,{clipPlaneVertex:()=>n});const r="clipPlaneVertex",s="#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\n#endif\n#ifdef CLIPPLANE5\nfClipDistance5=dot(worldPos,vClipPlane5);\n#endif\n#ifdef CLIPPLANE6\nfClipDistance6=dot(worldPos,vClipPlane6);\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},18355:(e,t,i)=>{"use strict";i.r(t),i.d(t,{clipPlaneVertexDeclaration:()=>n});const r="clipPlaneVertexDeclaration",s="#ifdef CLIPPLANE\nuniform vec4 vClipPlane;varying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;varying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;varying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;varying float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nuniform vec4 vClipPlane5;varying float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nuniform vec4 vClipPlane6;varying float fClipDistance6;\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},22464:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.decalFragment="#ifdef DECAL\n#ifdef GAMMADECAL\ndecalColor.rgb=toLinearSpace(decalColor.rgb);\n#endif\n#ifdef DECAL_SMOOTHALPHA\ndecalColor.a*=decalColor.a;\n#endif\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a);\n#endif\n"},14774:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.decalFragmentDeclaration="#ifdef DECAL\nuniform vec4 vDecalInfos;\n#endif\n"},81160:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.decalVertexDeclaration="#ifdef DECAL\nuniform vec4 vDecalInfos;uniform mat4 decalMatrix;\n#endif\n"},16792:(e,t,i)=>{"use strict";var r=i(69841);i(32405),i(13580);r.l.IncludesShadersStore.defaultUboDeclaration="layout(std140,column_major) uniform;uniform Material\n{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;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n"},51314:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.depthPrePass="#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);return;\n#endif\n"},27185:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.fogFragment="#ifdef FOG\nfloat fog=CalcFogFactor();\n#ifdef PBR\nfog=toLinearSpace(fog);\n#endif\ncolor.rgb=mix(vFogColor,color.rgb,fog);\n#endif\n"},64657:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fogFragmentDeclaration:()=>n});const r="fogFragmentDeclaration",s="#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;uniform vec3 vFogColor;varying vec3 vFogDistance;float CalcFogFactor()\n{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)\n{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);}\nelse if (FOGMODE_EXP==vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDensity);}\nelse if (FOGMODE_EXP2==vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);}\nreturn clamp(fogCoeff,0.0,1.0);}\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},90715:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.fogVertex="#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif\n"},77735:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.fogVertexDeclaration="#ifdef FOG\nvarying vec3 vFogDistance;\n#endif\n"},49046:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.fresnelFunction="#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{float fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);}\n#endif\n"},93784:(e,t,i)=>{"use strict";i.d(t,{Q:()=>n});const r="gaussianSplattingVertexDeclaration",s="attribute vec2 position;uniform mat4 view;uniform mat4 projection;uniform mat4 world;";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},10316:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.harmonicsFunctions="#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nvec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00\n+ vSphericalL1_1*(normal.y)\n+ vSphericalL10*(normal.z)\n+ vSphericalL11*(normal.x)\n+ vSphericalL2_2*(normal.y*normal.x)\n+ vSphericalL2_1*(normal.y*normal.z)\n+ vSphericalL20*((3.0*normal.z*normal.z)-1.0)\n+ vSphericalL21*(normal.z*normal.x)\n+ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));}\n#else\nvec3 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;}\n#endif\n#endif\n"},98392:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.hdrFilteringFunctions="#ifdef NUM_SAMPLES\n#if NUM_SAMPLES>0\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfloat radicalInverse_VdC(uint bits) \n{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; }\nvec2 hammersley(uint i,uint N)\n{return vec2(float(i)/float(N),radicalInverse_VdC(i));}\n#else\nfloat vanDerCorpus(int n,int base)\n{float invBase=1.0/float(base);float denom =1.0;float result =0.0;for(int i=0; i<32; ++i)\n{if(n>0)\n{denom =mod(float(n),2.0);result+=denom*invBase;invBase=invBase/2.0;n =int(float(n)/2.0);}}\nreturn result;}\nvec2 hammersley(int i,int N)\n{return vec2(float(i)/float(N),vanDerCorpus(i,2));}\n#endif\nfloat log4(float x) {return log2(x)/2.;}\nconst float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);const float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;const float K=4.;\n#define inline\nvec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)\n{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);\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfor(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;\n#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\n#endif\nresult+=c;}}\nresult=result*NUM_SAMPLES_FLOAT_INVERSED;return result;}\n#define inline\nvec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)\n{vec3 n=normalize(inputN);vec3 c=textureCube(inputTexture,n).rgb; \nif (alphaG==0.) {\n#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\n#endif\nreturn 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.;\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfor(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;\n#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\n#endif\nresult+=c*NoL;}}\nresult=result/weight;return result;}}\n#endif\n#endif\n"},94388:(e,t,i)=>{"use strict";i.r(t),i.d(t,{helperFunctions:()=>n});const r="helperFunctions",s="const float PI=3.1415926535897932384626433832795;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float HALF_MIN=5.96046448e-08; \nconst 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;\n#define saturate(x) clamp(x,0.0,1.0)\n#define absEps(x) abs(x)+Epsilon\n#define maxEps(x) max(x,Epsilon)\n#define saturateEps(x) clamp(x,Epsilon,1.0)\nmat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);return outMatrix;}\nmat3 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),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;}\n#if USE_EXACT_SRGB_CONVERSIONS\nvec3 toLinearSpaceExact(vec3 color)\n{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));\n#else\nreturn\nvec3(\ncolor.r<=0.04045 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.04045 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.04045 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\nvec3 toGammaSpaceExact(vec3 color)\n{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055);\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));\n#else\nreturn\nvec3(\ncolor.r<=0.0031308 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.0031308 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.0031308 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\n#endif\nfloat toLinearSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,LinearEncodePowerApprox);\n#endif\n}\nvec3 toLinearSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3(LinearEncodePowerApprox));\n#endif\n}\nvec4 toLinearSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toLinearSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);\n#endif\n}\nfloat toGammaSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,GammaEncodePowerApprox);\n#endif\n}\nvec3 toGammaSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3(GammaEncodePowerApprox));\n#endif\n}\nvec4 toGammaSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toGammaSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);\n#endif\n}\nfloat square(float value)\n{return value*value;}\nvec3 square(vec3 value)\n{return value*value;}\nfloat pow5(float value) {float sq=value*value;return sq*sq*value;}\nfloat getLuminance(vec3 color)\n{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}\nfloat getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}\nfloat dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;}\nconst 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); }\nvec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;}\nvec3 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;}\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},65343:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.imageProcessingCompatibility="#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2));\n#endif\n"},75651:(e,t,i)=>{"use strict";i.r(t),i.d(t,{imageProcessingDeclaration:()=>n});const r="imageProcessingDeclaration",s="#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#if defined(VIGNETTE) || defined(DITHER)\nuniform vec2 vInverseScreenSize;\n#endif\n#ifdef VIGNETTE\nuniform vec4 vignetteSettings1;uniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;uniform vec4 vCameraColorCurveNeutral;uniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef DITHER\nuniform float ditherIntensity;\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},88658:(e,t,i)=>{"use strict";i.r(t),i.d(t,{imageProcessingFunctions:()=>n});const r="imageProcessingFunctions",s="#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n/** \n* Polyfill for SAMPLE_TEXTURE_3D,which is unsupported in WebGL.\n* sampler3dSetting.x=textureOffset (0.5/textureSize).\n* sampler3dSetting.y=textureSize.\n*/\n#define inline\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{float sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);float sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;sliceUV.x+=sliceInteger*sliceSize;sliceUV=saturate(sliceUV);vec4 slice0Color=texture2D(colorTransform,sliceUV);sliceUV.x+=sliceSize;sliceUV=saturate(sliceUV);vec4 slice1Color=texture2D(colorTransform,sliceUV);vec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;}\n#endif\n#if TONEMAPPING==3\nconst float PBRNeutralStartCompression=0.8-0.04;const float PBRNeutralDesaturation=0.15;vec3 PBRNeutralToneMapping( vec3 color ) {float x=min(color.r,min(color.g,color.b));float offset=x<0.08 ? x-6.25*x*x : 0.04;color-=offset;float peak=max(color.r,max(color.g,color.b));if (peak{"use strict";i(69841).l.IncludesShadersStore.importanceSampling="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);}\nvec3 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);}\nvec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { \nfloat 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);}"},56865:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.instancesDeclaration="#ifdef INSTANCES\nattribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;\n#ifdef INSTANCESCOLOR\nattribute vec4 instanceColor;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform mat4 world;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nattribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3;\n#ifdef THIN_INSTANCES\nuniform mat4 previousWorld;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform mat4 world;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nuniform mat4 previousWorld;\n#endif\n#endif\n"},18411:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.instancesVertex="#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nmat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,\npreviousWorld2,previousWorld3);\n#endif\n#ifdef THIN_INSTANCES\nfinalWorld=world*finalWorld;\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nfinalPreviousWorld=previousWorld*finalPreviousWorld;\n#endif\n#endif\n#else\nmat4 finalWorld=world;\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nmat4 finalPreviousWorld=previousWorld;\n#endif\n#endif\n"},953:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};"},81749:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lightFragment:()=>n});const r="lightFragment",s="#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n#else\nvec4 diffuse{X}=light{X}.vLightDiffuse;\n#define CUSTOM_LIGHT{X}_COLOR \n#ifdef PBR\n#ifdef SPOTLIGHT{X}\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,vPositionW);\n#elif defined(POINTLIGHT{X})\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,vPositionW);\n#elif defined(HEMILIGHT{X})\npreInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(DIRLIGHT{X})\npreInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#endif\npreInfo.NdotV=NdotV;\n#ifdef SPOTLIGHT{X}\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.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);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.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);\n#else\npreInfo.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);\n#endif\n#elif defined(POINTLIGHT{X})\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\n#else\npreInfo.attenuation=1.0;\n#endif\n#ifdef HEMILIGHT{X}\npreInfo.roughness=roughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#ifdef IRIDESCENCE\npreInfo.iridescenceIntensity=iridescenceIntensity;\n#endif\n#ifdef HEMILIGHT{X}\ninfo.diffuse=computeHemisphericDiffuseLighting(preInfo,diffuse{X}.rgb,light{X}.vLightGround);\n#elif defined(SS_TRANSLUCENCY)\ninfo.diffuse=computeDiffuseAndTransmittedLighting(preInfo,diffuse{X}.rgb,subSurfaceOut.transmittance);\n#else\ninfo.diffuse=computeDiffuseLighting(preInfo,diffuse{X}.rgb);\n#endif\n#ifdef SPECULARTERM\n#ifdef ANISOTROPIC\ninfo.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb);\n#else\ninfo.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb);\n#endif\n#endif\n#ifdef SHEEN\n#ifdef SHEEN_LINKWITHALBEDO\npreInfo.roughness=sheenOut.sheenIntensity;\n#else\n#ifdef HEMILIGHT{X}\npreInfo.roughness=sheenOut.sheenRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#endif\ninfo.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb);\n#endif\n#ifdef CLEARCOAT\n#ifdef HEMILIGHT{X}\npreInfo.roughness=clearcoatOut.clearCoatRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\ninfo.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,diffuse{X}.rgb);\n#ifdef CLEARCOAT_TINT\nabsorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption;\n#ifdef SPECULARTERM\ninfo.specular*=absorption;\n#endif\n#endif\ninfo.diffuse*=info.clearCoat.w;\n#ifdef SPECULARTERM\ninfo.specular*=info.clearCoat.w;\n#endif\n#ifdef SHEEN\ninfo.sheen*=info.clearCoat.w;\n#endif\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightTexture{X},textureProjectionMatrix{X},vPositionW);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nfor (int i=0; i=0.) {index{X}=i;break;}}\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nif (index{X}>=0)\n#endif\n{\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#else\nshadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#endif\n#else\nshadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}];\n#endif\n#ifndef SHADOWCSMNOBLEND{X}\nfloat frustumLength=frustumLengths{X}[index{X}];float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)\n{index{X}+=1;float nextShadow=0.;\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nnextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#else\nnextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#endif\n#else\nnextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\nshadow=mix(nextShadow,shadow,diffRatio);\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);\n#endif\n}\n#endif\n}\n#elif defined(SHADOWCLOSEESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;shadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\naggShadow+=shadow;numLights+=1.0;\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor.rgb*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef CLEARCOAT\n#ifndef LIGHTMAPNOSPECULAR{X}\nclearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef SHEEN\n#ifndef LIGHTMAPNOSPECULAR{X}\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#else\n#ifdef SHADOWCSMDEBUG{X}\ndiffuseBase+=info.diffuse*shadowDebug{X};\n#else \ndiffuseBase+=info.diffuse*shadow;\n#endif\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#ifdef CLEARCOAT\nclearCoatBase+=info.clearCoat.rgb*shadow;\n#endif\n#ifdef SHEEN\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},23133:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lightFragmentDeclaration:()=>n});const r="lightFragmentDeclaration",s="#ifdef LIGHT{X}\nuniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\n#else\nvec4 vLightSpecular{X}=vec4(0.);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform 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};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};\n#else\nuniform highp sampler2DArray shadowTexture{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);vec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowTexture{X};\n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowTexture{X};\n#else\nuniform sampler2D shadowTexture{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};uniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X};\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},58769:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lightUboDeclaration:()=>n});const r="lightUboDeclaration",s="#ifdef LIGHT{X}\nuniform Light{X}\n{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;vec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;vec2 depthValues;} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X};\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform 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};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};\n#else\nuniform highp sampler2DArray shadowTexture{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);vec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowTexture{X}; \n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowTexture{X};\n#else\nuniform sampler2D shadowTexture{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},96951:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lightVxFragmentDeclaration:()=>n});const r="lightVxFragmentDeclaration",s="#ifdef LIGHT{X}\nuniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\n#else\nvec4 vLightSpecular{X}=vec4(0.);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#elif defined(SHADOWCUBE{X})\n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};uniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},19215:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lightVxUboDeclaration:()=>n});const r="lightVxUboDeclaration",s="#ifdef LIGHT{X}\nuniform Light{X}\n{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;vec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;vec2 depthValues;} light{X};\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#elif defined(SHADOWCUBE{X})\n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},97295:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lightsFragmentFunctions:()=>n});const r="lightsFragmentFunctions",s="struct lightingInfo\n{vec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};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.)\n{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}\nelse\n{lightVectorW=normalize(-lightData.xyz);}\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nlightingInfo 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)\n{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;float ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;}\nlightingInfo 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;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;\n#endif\nreturn result;}\n#define inline\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix,vec3 posW){vec4 strq=textureProjectionMatrix*vec4(posW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},25012:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.logDepthDeclaration="#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;varying float vFragmentDepth;\n#endif\n"},6922:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.logDepthFragment="#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif\n"},88336:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.logDepthVertex="#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif\n"},40371:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.mainUVVaryingDeclaration="#ifdef MAINUV{X}\nvarying vec2 vMainUV{X};\n#endif\n"},13580:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.meshUboDeclaration="#ifdef WEBGL2\nuniform mat4 world;uniform float visibility;\n#else\nlayout(std140,column_major) uniform;uniform Mesh\n{mat4 world;float visibility;};\n#endif\n#define WORLD_UBO\n"},44219:(e,t,i)=>{"use strict";i.r(t),i.d(t,{morphTargetsVertex:()=>n});const r="morphTargetsVertex",s="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\n#if {X}==0\nfor (int i=0; i=morphTargetCount) break;vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;positionUpdated+=(readVector3FromRawSampler(i,vertexID)-position)*morphTargetInfluences[i];vertexID+=1.0;\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(readVector3FromRawSampler(i,vertexID) -normal)*morphTargetInfluences[i];vertexID+=1.0;\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated+=(readVector3FromRawSampler(i,vertexID).xy-uv)*morphTargetInfluences[i];vertexID+=1.0;\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(readVector3FromRawSampler(i,vertexID) -tangent.xyz)*morphTargetInfluences[i];\n#endif\n}\n#endif\n#else\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}];\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},11783:(e,t,i)=>{"use strict";i.r(t),i.d(t,{morphTargetsVertexDeclaration:()=>n});const r="morphTargetsVertexDeclaration",s="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#ifdef MORPHTARGETS_UV\nattribute vec2 uv_{X};\n#endif\n#elif {X}==0\nuniform int morphTargetCount;\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},99216:(e,t,i)=>{"use strict";i.r(t),i.d(t,{morphTargetsVertexGlobal:()=>n});const r="morphTargetsVertexGlobal",s="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nfloat vertexID;\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},9158:(e,t,i)=>{"use strict";i.r(t),i.d(t,{morphTargetsVertexGlobalDeclaration:()=>n});const r="morphTargetsVertexGlobalDeclaration",s="#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#ifdef MORPHTARGETS_TEXTURE \nuniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform highp sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex)\n{ \nfloat 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;}\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},36881:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.oitDeclaration="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out vec2 depth; \nlayout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor;\n#define MAX_DEPTH 99999.0\nhighp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler;\n#endif\n"},40401:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.oitFragment="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\nfloat fragDepth=gl_FragCoord.z; \n#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS\nuint halfFloat=packHalf2x16(vec2(fragDepth));vec2 full=unpackHalf2x16(halfFloat);fragDepth=full.x;\n#endif\nivec2 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);\n#ifdef USE_REVERSE_DEPTHBUFFER\nfloat furthestDepth=-lastDepth.x;float nearestDepth=lastDepth.y;\n#else\nfloat nearestDepth=-lastDepth.x;float furthestDepth=lastDepth.y;\n#endif\nfloat alphaMultiplier=1.0-lastFrontColor.a;\n#ifdef USE_REVERSE_DEPTHBUFFER\nif (fragDepth>nearestDepth || fragDepthfurthestDepth) {\n#endif\nreturn;}\n#ifdef USE_REVERSE_DEPTHBUFFER\nif (fragDepthfurthestDepth) {\n#else\nif (fragDepth>nearestDepth && fragDepth{"use strict";i.r(t),i.d(t,{packingFunctions:()=>n});const r="packingFunctions",s="vec4 pack(float depth)\n{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;}\nfloat unpack(vec4 color)\n{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);}";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},67350:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.pbrBRDFFunctions="#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);}\n#endif\n#ifdef ENVIRONMENTBRDF\nvec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV);\n#ifdef ENVIRONMENTBRDF_RGBD\nbrdfLookup.rgb=fromRGBD(brdfLookup.rgba);\n#endif\nreturn brdfLookup.rgb;}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y;\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y;\n#endif\nreturn reflectance;}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#endif\nreturn reflectance;}\n#endif\n/* NOT USED\n#if defined(SHEEN) && defined(SHEEN_SOFTER)\nfloat getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness)\n{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));}\n#endif\n*/\n#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)\nvec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF)\n/**\n* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture.\n* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table\n*/\nvec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;}\n#endif\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\nfloat fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\n#ifdef CLEARCOAT\nvec3 getR0RemappedForClearCoat(vec3 f0) {\n#ifdef CLEARCOAT_DEFAULTIOR\n#ifdef MOBILE\nreturn saturate(f0*(f0*0.526868+0.529324)-0.0482256);\n#else\nreturn saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);\n#endif\n#else\nvec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t);\n#endif\n}\n#endif\n#ifdef IRIDESCENCE\nconst mat3 XYZ_TO_REC709=mat3(\n3.2404542,-0.9692660, 0.0556434,\n-1.5371385, 1.8760108,-0.2040259,\n-0.4985314, 0.0415560, 1.0572252\n);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);}\nvec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));}\nfloat getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));}\nvec3 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;}\nvec3 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;}\nfloat 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 (iridescenceIOR{"use strict";var r=i(69841);i(32405),i(13580);r.l.IncludesShadersStore.pbrUboDeclaration="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;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n"},72992:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.pointCloudVertex="#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n"},59317:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.prePassDeclaration="#ifdef PREPASS\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor;\n#ifdef PREPASS_LOCAL_POSITION\nvarying highp vec3 vPosition;\n#endif\n#ifdef PREPASS_DEPTH\nvarying highp vec3 vViewPos;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)\nvarying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition;\n#endif\n#endif\n"},85639:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.prePassVertex="#ifdef PREPASS_DEPTH\nvViewPos=(view*worldPos).rgb;\n#endif\n#ifdef PREPASS_LOCAL_POSITION\nvPosition=positionUpdated.xyz;\n#endif\n#if (defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*worldPos;\n#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);\n#else\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#endif\n"},57819:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.prePassVertexDeclaration="#ifdef PREPASS\n#ifdef PREPASS_LOCAL_POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef PREPASS_DEPTH\nvarying vec3 vViewPos;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)\nuniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#endif\n"},51068:(e,t,i)=>{"use strict";i.r(t),i.d(t,{reflectionFunction:()=>n});const r="reflectionFunction",s="vec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)\n{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0); }\nvec3 computeMirroredFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)\n{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(1.0-s,t,0); }\nvec3 computeEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{vec3 cameraToVertex=normalize(worldPos.xyz-eyePosition);vec3 r=normalize(reflect(cameraToVertex,worldNormal));r=vec3(reflectionMatrix*vec4(r,0));float lon=atan(r.z,r.x);float lat=acos(r.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0);}\nvec3 computeSphericalCoords(vec4 worldPos,vec3 worldNormal,mat4 view,mat4 reflectionMatrix)\n{vec3 viewDir=normalize(vec3(view*worldPos));vec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));vec3 r=reflect(viewDir,viewNormal);r=vec3(reflectionMatrix*vec4(r,0));r.z=r.z-1.0;float m=2.0*length(r);return vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);}\nvec3 computePlanarCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{vec3 viewDir=worldPos.xyz-eyePosition;vec3 coords=normalize(reflect(viewDir,worldNormal));return vec3(reflectionMatrix*vec4(coords,1));}\nvec3 computeCubicCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;}\nvec3 computeCubicLocalCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix,vec3 reflectionSize,vec3 reflectionPosition)\n{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);coords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;}\nvec3 computeProjectionCoords(vec4 worldPos,mat4 view,mat4 reflectionMatrix)\n{return vec3(reflectionMatrix*(view*worldPos));}\nvec3 computeSkyBoxCoords(vec3 positionW,mat4 reflectionMatrix)\n{return vec3(reflectionMatrix*vec4(positionW,1.));}\n#ifdef REFLECTION\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);return computeFixedEquirectangularCoords(worldPos,worldNormal,direction);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nreturn computeEquirectangularCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nreturn computeSphericalCoords(worldPos,worldNormal,view,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nreturn computePlanarCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_CUBIC\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nreturn computeCubicLocalCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix,vReflectionSize,vReflectionPosition);\n#else\nreturn computeCubicCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn computeProjectionCoords(worldPos,view,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn computeSkyBoxCoords(vPositionUVW,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},5301:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.samplerFragmentDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying vec2 v_VARYINGNAME_UV;\n#endif\nuniform sampler2D _SAMPLERNAME_Sampler;\n#endif\n"},2251:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.samplerVertexDeclaration="#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0\nvarying vec2 v_VARYINGNAME_UV;\n#endif\n"},84525:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.samplerVertexImplementation="#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0\nif (v_INFONAME_==0.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));}\n#ifdef UV2\nelse if (v_INFONAME_==1.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2,1.0,0.0));}\n#endif\n#ifdef UV3\nelse if (v_INFONAME_==2.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));}\n#endif\n#ifdef UV4\nelse if (v_INFONAME_==3.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));}\n#endif\n#ifdef UV5\nelse if (v_INFONAME_==4.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));}\n#endif\n#ifdef UV6\nelse if (v_INFONAME_==5.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));}\n#endif\n#endif\n"},32405:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.sceneUboDeclaration="layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif \nmat4 view;mat4 projection;vec4 vEyePosition;};\n"},8338:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.screenSpaceRayTrace="float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); }\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nfloat linearizeDepth(float depth,float near,float far) {\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nreturn -(near*far)/(far-depth*(far-near));\n#else\nreturn (near*far)/(far-depth*(far-near));\n#endif\n}\n#endif\n/**\nparam csOrigin Camera-space ray origin,which must be \nwithin the view volume and must have z>0.01 and project within the valid screen rectangle\nparam csDirection Unit length camera-space ray direction\nparam projectToPixelMatrix A projection matrix that maps to **pixel** coordinates \n(**not** [-1,+1] normalized device coordinates).\nparam csZBuffer The camera-space Z buffer\nparam csZBufferSize Dimensions of csZBuffer\nparam csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer\nparam nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value\nfor clipping rays headed towards the camera\nparam stride Step in horizontal or vertical pixels between samples. This is a float\nbecause integer math is slow on GPUs,but should be set to an integer>=1\nparam jitterFraction Number between 0 and 1 for how far to bump the ray in stride units\nto conceal banding artifacts,plus the stride ray offset.\nparam maxSteps Maximum number of iterations. Higher gives better images but may be slow\nparam maxRayTraceDistance Maximum camera-space distance to trace before returning a miss\nparam selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions.\n1 is a reasonable value,depending on the scene you may need to set this value to 2\nparam hitPixel Pixel coordinates of the first intersection with the scene\nparam numIterations number of iterations performed\nparam csHitPoint Camera space location of the ray hit\n*/\n#define inline\nbool traceScreenSpaceRay1(\nvec3 csOrigin,\nvec3 csDirection,\nmat4 projectToPixelMatrix,\nsampler2D csZBuffer,\nvec2 csZBufferSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nsampler2D csZBackBuffer,\nfloat csZBackSizeFactor,\n#endif\nfloat csZThickness,\nfloat nearPlaneZ,\nfloat farPlaneZ,\nfloat stride,\nfloat jitterFraction,\nfloat maxSteps,\nfloat maxRayTraceDistance,\nfloat selfCollisionNumSkip,\nout vec2 startPixel,\nout vec2 hitPixel,\nout vec3 csHitPoint,\nout float numIterations\n#ifdef SSRAYTRACE_DEBUG\n,out vec3 debugColor\n#endif\n)\n{\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance;\n#else\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax) ? yMax : yMin))/(P1.y-P0.y);}\nif ((P1.x>xMax) || (P1.xxMax) ? xMax : xMin))/(P1.x-P0.x));}\nP1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha);\n#endif\nP1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)rayZMax) { \nfloat t=rayZMin; rayZMin=rayZMax; rayZMax=t;}\nsceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nsceneZMax=linearizeDepth(sceneZMax,nearPlaneZ,farPlaneZ);\n#endif\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nsceneBackZ=linearizeDepth(sceneBackZ,nearPlaneZ,farPlaneZ);\n#endif\nhit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax);\n#else\nhit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax);\n#endif\n#else\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nsceneBackZ=linearizeDepth(sceneBackZ,nearPlaneZ,farPlaneZ);\n#endif\nhit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0);\n#else\nhit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax);\n#endif\n#endif\n}\npqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;}\n#ifdef SSRAYTRACE_ENABLE_REFINEMENT\nif (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 ||\n(refinementStepCount<=stride*1.4) &&\n(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);}\n#endif\nreturn hit;}\n/**\ntexCoord: in the [0,1] range\ndepth: depth in view space (range [znear,zfar]])\n*/\nvec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef ORTHOGRAPHIC_CAMERA\nndc.z=-projection[2].z*depth+projection[3].z;\n#else\nndc.z=-projection[2].z-projection[3].z/depth;\n#endif\n#else\n#ifdef ORTHOGRAPHIC_CAMERA\nndc.z=projection[2].z*depth+projection[3].z;\n#else\nndc.z=projection[2].z+projection[3].z/depth;\n#endif\n#endif\nndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}\n"},73391:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowMapFragment:()=>n});const r="shadowMapFragment",s="float depthSM=vDepthMetricSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\n#if SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\ndepthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\ndepthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_FragDepth=clamp(1.0-depthSM,0.0,1.0);\n#else\ngl_FragDepth=clamp(depthSM,0.0,1.0); \n#endif\n#elif SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#if SM_ESM==1\ndepthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);\n#endif\n#if SM_FLOAT==1\ngl_FragColor=vec4(depthSM,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depthSM);\n#endif\nreturn;";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},19893:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowMapFragmentSoftTransparentShadow:()=>n});const r="shadowMapFragmentSoftTransparentShadow",s="#if SM_SOFTTRANSPARENTSHADOW==1\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM.x*alpha) discard;\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},94949:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowMapVertexMetric:()=>n});const r="shadowMapVertexMetric",s="#if SM_USEDISTANCE==1\nvPositionWSM=worldPos.xyz;\n#endif\n#if SM_DEPTHTEXTURE==1\n#ifdef IS_NDC_HALF_ZRANGE\n#define BIASFACTOR 0.5\n#else\n#define BIASFACTOR 1.0\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#else\ngl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#endif\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nzSM=gl_Position.z;gl_Position.z=0.0;\n#elif SM_USEDISTANCE==0\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\nvDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n";i(69841).l.IncludesShadersStore[r]=s;const n={name:r,shader:s}},34091:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowsFragmentFunctions:()=>n});const r="shadowsFragmentFunctions",s="#ifdef SHADOWS\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{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);}\n#endif\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}\n#define inline\nfloat computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{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;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nreturn depth>shadow ? darkness : 1.0;}\n#define inline\nfloat computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{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);\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}\n#endif\n#define inline\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{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)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadow=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nreturn shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}}\n#define inline\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{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)\n{return 1.0;}\nelse\n{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);\n#ifndef SHADOWFLOAT\nif (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{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)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\n#ifdef IS_NDC_HALF_ZRANGE\n#define ZINCLIP clipSpace.z\n#else\n#define ZINCLIP uvDepth.z\n#endif\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define GREATEST_LESS_THAN_ONE 0.99999994\n#define DISABLE_UNIFORMITY_ANALYSIS\n#define inline\nfloat computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{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);}\n#define inline\nfloat computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{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; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 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);}\n#define inline\nfloat computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{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; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 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);}\n#define inline\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{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);}}\n#define inline\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{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; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 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);}}\n#define inline\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{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; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 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);}}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.)\n);const vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n#define inline\nfloat 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)\n{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;}\nelse\n{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{"use strict";i.r(t),i.d(t,{shadowsVertex:()=>n});const r="shadowsVertex",s="#ifdef SHADOWS\n#if defined(SHADOWCSM{X})\nvPositionFromCamera{X}=view*worldPos;for (int i=0; i{"use strict";i(69841).l.IncludesShadersStore.subSurfaceScatteringFunctions="bool testLightingForSSS(float diffusionProfile)\n{return diffusionProfile<1.;}"},9482:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.uvAttributeDeclaration="#ifdef UV{X}\nattribute vec2 uv{X};\n#endif\n"},81448:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.uvVariableDeclaration="#if !defined(UV{X}) && defined(MAINUV{X})\nvec2 uv{X}=vec2(0.,0.);\n#endif\n#ifdef MAINUV{X}\nvMainUV{X}=uv{X};\n#endif\n"},61374:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStore.vertexColorMixing="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvColor=vec4(1.0);\n#ifdef VERTEXCOLOR\n#ifdef VERTEXALPHA\nvColor*=color;\n#else\nvColor.rgb*=color.rgb;\n#endif\n#endif\n#ifdef INSTANCESCOLOR\nvColor*=instanceColor;\n#endif\n#endif\n"},20692:(e,t,i)=>{"use strict";i.r(t),i.d(t,{anaglyphPixelShader:()=>n});const r="anaglyphPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{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);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},91341:(e,t,i)=>{"use strict";i.r(t),i.d(t,{backgroundPixelShader:()=>o});var r=i(69841);r.l.IncludesShadersStore.backgroundFragmentDeclaration="uniform vec4 vEyePosition;uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;uniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef PROJECTED_GROUND\nuniform vec2 projectedGroundInfos;\n#endif\n",i(29925),i(94388),i(51068),i(75651),i(23133),i(58769),i(97295),i(34091),i(88658),i(25012),i(77165),i(64657),i(89797),i(81749),i(6922),i(27185);const s="backgroundPixelShader",n="#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#include\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV==1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV==2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#ifdef PROJECTED_GROUND\nfloat diskIntersectWithBackFaceCulling(vec3 ro,vec3 rd,vec3 c,float r) {float d=rd.y;if(d>0.0) { return 1e6; }\nvec3 o=ro-c;float t=-o.y/d;vec3 q=o+rd*t;return (dot(q,q)\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\nfloat shadow=1.;float globalShadow=0.;float shadowLightCount=0.;float aggShadow=0.;float numLights=0.;\n#include[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n#ifndef BACKMAT_SHADOWONLY\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\n#ifdef PROJECTED_GROUND\nvec3 reflectionVector=project(viewDirectionW,vEyePosition.xyz);reflectionVector=vec3(reflectionMatrix*vec4(reflectionVector,1.));\n#else\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);} else {reflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\nvec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 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;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor;\n#endif\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\nvec4 color=vec4(finalColor,finalAlpha);\n#else\nvec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha);\n#endif\n#include\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n#if !defined(SKIPFINALCOLORCLAMP)\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#endif\n#else\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0);\n#endif\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},80723:(e,t,i)=>{"use strict";i.r(t),i.d(t,{backgroundVertexShader:()=>o});var r=i(69841);r.l.IncludesShadersStore.backgroundVertexDeclaration="uniform mat4 view;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n",i(29925),i(94388),i(39948),i(66682),i(56865),i(18355),i(77735),i(96951),i(19215),i(25012),i(18411),i(78792),i(95532),i(71471),i(90715),i(2946),i(88336);const s="backgroundVertexShader",n="precision highp float;\n#include<__decl__backgroundVertex>\n#include\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nvarying vec2 vDiffuseUV;\n#endif\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif\n#include\n#include\n#include\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);}\n#else\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#endif\nvec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 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));}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},41341:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bilateralBlurPixelShader:()=>n});const r="bilateralBlurPixelShader",s="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;}\nvec3 normal=textureLod(normalSampler,vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nfloat 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;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nfloat 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;}\nglFragColor=vec4(sum/wsum,1.);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},47318:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bilateralBlurQualityPixelShader:()=>n});const r="bilateralBlurQualityPixelShader",s="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;}\nvec3 normal=textureLod(normalSampler,vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nfloat 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;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nfloat 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;}}\nglFragColor=vec4(sum/wsum,1.);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},27897:(e,t,i)=>{"use strict";i.r(t),i.d(t,{blackAndWhitePixelShader:()=>n});const r="blackAndWhitePixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},94811:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bloomMergePixelShader:()=>n});const r="bloomMergePixelShader",s="uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); }\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},16400:(e,t,i)=>{"use strict";i.r(t),i.d(t,{boundingBoxRendererPixelShader:()=>o});var r=i(69841);r.l.IncludesShadersStore.boundingBoxRendererFragmentDeclaration="uniform vec4 color;\n",i(97315);const s="boundingBoxRendererPixelShader",n="#include<__decl__boundingBoxRendererFragment>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},81473:(e,t,i)=>{"use strict";i.r(t),i.d(t,{boundingBoxRendererVertexShader:()=>o});var r=i(69841);r.l.IncludesShadersStore.boundingBoxRendererVertexDeclaration="uniform mat4 world;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n",i(97315);const s="boundingBoxRendererVertexShader",n="attribute vec3 position;\n#include<__decl__boundingBoxRendererVertex>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec4 worldPos=world*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},76437:(e,t,i)=>{"use strict";i.r(t),i.d(t,{chromaticAberrationPixelShader:()=>n});const r="chromaticAberrationPixelShader",s="uniform sampler2D textureSampler; \nuniform float chromatic_aberration;uniform float radialIntensity;uniform vec2 direction;uniform vec2 centerPosition;uniform float screen_width;uniform float screen_height;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);vec2 directionOfEffect=direction;if(directionOfEffect.x==0. && directionOfEffect.y==0.){directionOfEffect=normalize(centered_screen_pos);}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+ centered_screen_pos.y*centered_screen_pos.y;float radius=sqrt(radius2);vec3 ref_indices=vec3(-0.3,0.0,0.3);float ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;float ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;vec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);vec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);vec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);vec4 r=texture2D(textureSampler,ref_coords_r);vec4 g=texture2D(textureSampler,ref_coords_g);vec4 b=texture2D(textureSampler,ref_coords_b);float a=clamp(r.a+g.a+b.a,0.,1.);gl_FragColor=vec4(r.r,g.g,b.b,a);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},29743:(e,t,i)=>{"use strict";i.r(t),i.d(t,{circleOfConfusionPixelShader:()=>n});const r="circleOfConfusionPixelShader",s="uniform sampler2D depthSampler;varying vec2 vUV;\n#ifndef COC_DEPTH_NOT_NORMALIZED\nuniform vec2 cameraMinMaxZ;\n#endif\nuniform float focusDistance;uniform float cocPrecalculation;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float depth=texture2D(depthSampler,vUV).r;\n#define CUSTOM_COC_DEPTH\n#ifdef COC_DEPTH_NOT_NORMALIZED\nfloat pixelDistance=depth*1000.0;\n#else\nfloat pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; \n#endif\n#define CUSTOM_COC_PIXELDISTANCE\nfloat coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},27683:(e,t,i)=>{"use strict";i.r(t),i.d(t,{colorPixelShader:()=>o});var r=i(69841);i(77165),i(64657),i(89797),i(27185);const s="colorPixelShader",n="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\n#define VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n#include(color,gl_FragColor)\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},53501:(e,t,i)=>{"use strict";i.r(t),i.d(t,{colorVertexShader:()=>o});var r=i(69841);i(39948),i(66682),i(18355),i(77735),i(56865),i(18411),i(78792),i(95532),i(71471),i(90715),i(61374);const s="colorVertexShader",n="attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\n#ifdef FOG\nuniform mat4 view;\n#endif\n#include\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},42711:(e,t,i)=>{"use strict";i.r(t),i.d(t,{colorCorrectionPixelShader:()=>n});const r="colorCorrectionPixelShader",s="uniform sampler2D textureSampler; \nuniform sampler2D colorTable; \nvarying vec2 vUV;const float SLICE_COUNT=16.0; \n#define inline\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat 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;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},59188:(e,t,i)=>{"use strict";i.r(t),i.d(t,{convolutionPixelShader:()=>n});const r="convolutionPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9];\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},76978:(e,t,i)=>{"use strict";i.r(t),i.d(t,{copyTexture3DLayerToTexturePixelShader:()=>n});const r="copyTexture3DLayerToTexturePixelShader",s="precision highp sampler3D;uniform sampler3D textureSampler;uniform int layerNum;varying vec2 vUV;void main(void) {vec3 coord=vec3(0.0,0.0,float(layerNum));coord.xy=vec2(vUV.x,vUV.y)*vec2(textureSize(textureSampler,0).xy);vec3 color=texelFetch(textureSampler,ivec3(coord),0).rgb;gl_FragColor=vec4(color,1);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},92224:(e,t,i)=>{"use strict";i.r(t),i.d(t,{copyTextureToTexturePixelShader:()=>o});var r=i(69841);i(94388);const s="copyTextureToTexturePixelShader",n="uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV;\n#include\nvoid main(void) \n{vec4 color=texture2D(textureSampler,vUV);\n#ifdef DEPTH_TEXTURE\ngl_FragDepth=color.r;\n#else\nif (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);}\ngl_FragColor=color;\n#endif\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},85800:(e,t,i)=>{"use strict";i.r(t),i.d(t,{defaultPixelShader:()=>o});var r=i(69841);i(14774);r.l.IncludesShadersStore.defaultFragmentDeclaration="uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;uniform vec4 vSpecularColor;uniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;uniform vec4 refractionRightColor;\n#endif\n#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D)\nuniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; \n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX)\nuniform mat4 reflectionMatrix;\n#endif\n#ifndef REFLECTIONMAP_SKYBOX\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include\n#define ADDITIONAL_FRAGMENT_DECLARATION\n",i(16792),i(59317),i(36881),i(40371),i(94388),i(23133),i(58769),i(97295),i(34091),i(5301),i(49046),i(51068),i(75651),i(88658),i(82267),i(29424),i(77165),i(25012),i(64657),i(89797),i(90249),i(22464),i(51314),i(81749),i(6922),i(27185),i(40401);const s="defaultPixelShader",n="#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#include[SCENE_MRT_COUNT]\n#include\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include[1..7]\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULARTERM)\n#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular)\n#endif\n#include\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS)\nif (baseColor.a(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)\n#endif\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef DETAIL\nbaseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y);\n#endif\n#if defined(DECAL) && defined(DECAL_AFTER_DETAIL)\nvec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset);\n#include(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\nfloat glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);specularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef LIGHTMAP\nvec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);\n#ifdef RGBDLIGHTMAP\nlightmapColor.rgb=fromRGBD(lightmapColor);\n#endif\nlightmapColor.rgb*=vLightmapInfos.y;\n#endif\n#include[0..maxSimultaneousLights]\naggShadow=aggShadow/numLights;vec4 refractionColor=vec4(0.,0.,0.,1.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\n#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC\nrefractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition);\n#endif\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;vec4 refractionLookup=textureCube(refractionCubeSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;}\n#else\nvec3 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);\n#endif\n#ifdef RGBDREFRACTION\nrefractionColor.rgb=fromRGBD(refractionColor);\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor.rgb=toGammaSpace(refractionColor.rgb);\n#endif\nrefractionColor.rgb*=vRefractionInfos.x;\n#endif\nvec4 reflectionColor=vec4(0.,0.,0.,1.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nvReflectionUVW.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias);\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW);\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;reflectionColor=texture2D(reflection2DSampler,coords);\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor.rgb=toGammaSpace(reflectionColor.rgb);\n#endif\nreflectionColor.rgb*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n#ifdef ALPHATEST\n#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS\nif (alpha\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color);\n#endif\n#endif\ncolor.a*=visibility;\n#ifdef PREMULTIPLYALPHA\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\n#ifdef PREPASS\nfloat writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;\n#ifdef PREPASS_COLOR\ngl_FragData[PREPASS_COLOR_INDEX]=color; \n#endif\n#ifdef PREPASS_POSITION\ngl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);\n#endif\n#ifdef PREPASS_LOCAL_POSITION\ngl_FragData[PREPASS_LOCAL_POSITION_INDEX]=vec4(vPosition,writeGeometryInfo);\n#endif\n#if defined(PREPASS_VELOCITY)\nvec2 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);\n#elif defined(PREPASS_VELOCITY_LINEAR)\nvec2 velocity=vec2(0.5)*((vPreviousPosition.xy/vPreviousPosition.w)-(vCurrentPosition.xy/vCurrentPosition.w));gl_FragData[PREPASS_VELOCITY_LINEAR_INDEX]=vec4(velocity,0.0,writeGeometryInfo);\n#endif\n#ifdef PREPASS_IRRADIANCE\ngl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); \n#endif\n#ifdef PREPASS_DEPTH\ngl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); \n#endif\n#ifdef PREPASS_SCREENSPACE_DEPTH\ngl_FragData[PREPASS_SCREENSPACE_DEPTH_INDEX]=vec4(gl_FragCoord.z,0.0,0.0,writeGeometryInfo);\n#endif\n#ifdef PREPASS_NORMAL\n#ifdef PREPASS_NORMAL_WORLDSPACE\ngl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo);\n#else\ngl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo);\n#endif\n#endif\n#ifdef PREPASS_WORLD_NORMAL\ngl_FragData[PREPASS_WORLD_NORMAL_INDEX]=vec4(normalW*0.5+0.5,writeGeometryInfo);\n#endif\n#ifdef PREPASS_ALBEDO\ngl_FragData[PREPASS_ALBEDO_INDEX]=vec4(baseColor.rgb,writeGeometryInfo);\n#endif\n#ifdef PREPASS_ALBEDO_SQRT\ngl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqrt(baseColor.rgb),writeGeometryInfo);\n#endif\n#ifdef PREPASS_REFLECTIVITY\n#if defined(SPECULAR)\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularMapColor))*writeGeometryInfo; \n#else\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularColor),1.0)*writeGeometryInfo;\n#endif\n#endif\n#endif\n#if !defined(PREPASS) || defined(WEBGL2)\ngl_FragColor=color;\n#endif\n#include\n#if ORDER_INDEPENDENT_TRANSPARENCY\nif (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-color.a);} else {backColor+=color;}\n#endif\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},35936:(e,t,i)=>{"use strict";i.r(t),i.d(t,{defaultVertexShader:()=>o});var r=i(69841);i(81160);r.l.IncludesShadersStore.defaultVertexDeclaration="uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif \nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;uniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;uniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform mat4 bumpMatrix;\n#endif\n#ifdef REFLECTION\nuniform mat4 reflectionMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;uniform mat4 detailMatrix;\n#endif\n#include\n#define ADDITIONAL_VERTEX_DECLARATION\n",i(16792),i(9482),i(94388),i(39948),i(66682),i(56865),i(57819),i(40371),i(2251),i(17727),i(18355),i(77735),i(96951),i(19215),i(9158),i(11783),i(25012),i(99216),i(44219),i(18411),i(78792),i(95532),i(85639),i(81448),i(84525),i(78595),i(71471),i(90715),i(2946),i(61374),i(72992),i(88336);const s="defaultVertexShader",n="#include<__decl__defaultVertex>\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#include[2..7]\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\n#include\n#include[1..7]\n#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)\n#if defined(SPECULARTERM)\n#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular)\n#endif\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include\n#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#endif\n#define CUSTOM_VERTEX_UPDATE_WORLDPOS\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\nvPositionW=vec3(worldPos);\n#ifdef PREPASS\n#include\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n#ifndef UV1\nvec2 uvUpdated=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uvUpdated;\n#endif\n#include[2..7]\n#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)\n#if defined(SPECULARTERM)\n#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x)\n#endif\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},2297:(e,t,i)=>{"use strict";i.r(t),i.d(t,{depthPixelShader:()=>o});var r=i(69841);i(77165),i(72693),i(89797);const s="depthPixelShader",n="#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\nvarying float vDepthMetric;\n#ifdef PACKED\n#include\n#endif\n#ifdef STORE_CAMERASPACE_Z\nvarying vec4 vViewPos;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef STORE_CAMERASPACE_Z\n#ifdef PACKED\ngl_FragColor=pack(vViewPos.z);\n#else\ngl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);\n#endif\n#else\n#ifdef NONLINEARDEPTH\n#ifdef PACKED\ngl_FragColor=pack(gl_FragCoord.z);\n#else\ngl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);\n#endif\n#else\n#ifdef PACKED\ngl_FragColor=pack(vDepthMetric);\n#else\ngl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);\n#endif\n#endif\n#endif\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},6069:(e,t,i)=>{"use strict";i.r(t),i.d(t,{depthVertexShader:()=>o});var r=i(69841);i(39948),i(66682),i(9158),i(11783),i(18355),i(56865);r.l.IncludesShadersStore.pointCloudVertexDeclaration="#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n",i(99216),i(44219),i(18411),i(78792),i(95532),i(71471),i(72992);const s="depthVertexShader",n="attribute vec3 position;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;uniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef STORE_CAMERASPACE_Z\nuniform mat4 view;varying vec4 vViewPos;\n#endif\n#include\nvarying float vDepthMetric;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#include\ngl_Position=viewProjection*worldPos;\n#ifdef STORE_CAMERASPACE_Z\nvViewPos=view*worldPos;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));\n#else\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#endif\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},16845:(e,t,i)=>{"use strict";i.r(t),i.d(t,{depthBoxBlurPixelShader:()=>n});const r="depthBoxBlurPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},95610:(e,t,i)=>{"use strict";i.r(t),i.d(t,{depthOfFieldMergePixelShader:()=>n});const r="depthOfFieldMergePixelShader",s="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r;\n#if BLUR_LEVEL==0\nvec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL==1\nif(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);}\n#endif\n#if BLUR_LEVEL==2\nif(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);}\n#endif\n}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},17239:(e,t,i)=>{"use strict";i.r(t),i.d(t,{displayPassPixelShader:()=>n});const r="displayPassPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D passSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(passSampler,vUV);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},83062:(e,t,i)=>{"use strict";i.r(t),i.d(t,{extractHighlightsPixelShader:()=>o});var r=i(69841);i(94388);const s="extractHighlightsPixelShader",n="#include\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},88770:(e,t,i)=>{"use strict";i.r(t),i.d(t,{filterPixelShader:()=>n});const r="filterPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},93705:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingBilateralBlurPixelShader:()=>n});const r="fluidRenderingBilateralBlurPixelShader",s="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;}\nint 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;}\nglFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},21959:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingParticleDepthPixelShader:()=>n});const r="fluidRenderingParticleDepthPixelShader",s="uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nvarying float velocityNorm;\n#endif\nvoid 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);\n#ifndef FLUIDRENDERING_RHS\nnormal.z=-normal.z;\n#endif\nvec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos;\n#ifdef WEBGPU\ngl_FragDepth=clipSpacePos.z/clipSpacePos.w;\n#else\ngl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5;\n#endif\n#ifdef FLUIDRENDERING_RHS\nrealViewPos.z=-realViewPos.z;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nglFragColor=vec4(realViewPos.z,velocityNorm,0.,1.);\n#else\nglFragColor=vec4(realViewPos.z,0.,0.,1.);\n#endif\n}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},49377:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingParticleDepthVertexShader:()=>n});const r="fluidRenderingParticleDepthVertexShader",s="attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nattribute vec3 velocity;varying float velocityNorm;\n#endif\nvoid 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;\n#ifdef FLUIDRENDERING_VELOCITY\nvelocityNorm=length(velocity);\n#endif\n}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},76558:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingParticleDiffusePixelShader:()=>n});const r="fluidRenderingParticleDiffusePixelShader",s="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);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},28566:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingParticleThicknessPixelShader:()=>n});const r="fluidRenderingParticleThicknessPixelShader",s="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);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},3420:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingParticleThicknessVertexShader:()=>n});const r="fluidRenderingParticleThicknessVertexShader",s="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;}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},35116:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingRenderPixelShader:()=>n});const r="fluidRenderingRenderPixelShader",s="#define DISABLE_UNIFORMITY_ANALYSIS\n#define IOR 1.333\n#define ETA 1.0/IOR\n#define F0 0.02\nuniform sampler2D textureSampler;uniform sampler2D depthSampler;\n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nuniform sampler2D diffuseSampler;\n#else\nuniform vec3 diffuseColor;\n#endif\n#ifdef FLUIDRENDERING_FIXED_THICKNESS\nuniform float thickness;uniform sampler2D bgDepthSampler;\n#else\nuniform float minimumThickness;uniform sampler2D thicknessSampler;\n#endif\n#ifdef FLUIDRENDERING_ENVIRONMENT\nuniform samplerCube reflectionSampler;\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nuniform sampler2D debugSampler;\n#endif\nuniform 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;\n#ifdef FLUIDRENDERING_RHS\nndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#else\nndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#endif\nndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}\nvec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);}\nvoid main(void) {vec2 texCoord=vUV;\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nvec4 color=texture2D(debugSampler,texCoord);\n#ifdef FLUIDRENDERING_DEBUG_DEPTH\nglFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);}\n#else\nglFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);}\n#endif\nreturn;\n#endif\nvec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r;\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nfloat thickness=texture2D(thicknessSampler,texCoord).x;\n#else\nfloat bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5;\n#endif\nvec4 backColor=texture2D(textureSampler,texCoord);\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nif (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) {\n#else\nif (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) {\n#endif\n#ifdef FLUIDRENDERING_COMPOSITE_MODE\nglFragColor.rgb=backColor.rgb*backColor.a;glFragColor.a=backColor.a;\n#else\nglFragColor=backColor;\n#endif\nreturn;}\nvec3 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;}\nvec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;}\nvec3 normal=normalize(cross(ddy,ddx));\n#ifdef FLUIDRENDERING_RHS\nnormal=-normal;\n#endif\n#ifndef WEBGPU\nif(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);}\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL)\nglFragColor=vec4(normal*0.5+0.5,1.0);return;\n#endif\nvec3 rayDir=normalize(viewPos); \n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nvec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb;\n#endif\nvec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower);\n#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING\nfloat 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;\n#endif\nvec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);\n#ifdef FLUIDRENDERING_COMPOSITE_MODE\nif (transmitted.a==0.) transmitted.a=thickness;\n#endif\nvec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); \nvec3 refractionColor=transmitted.rgb*transmittance;\n#ifdef FLUIDRENDERING_ENVIRONMENT\nvec3 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;\n#else\nvec3 finalColor=refractionColor+specular;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nfloat velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0));\n#endif\nglFragColor=vec4(finalColor,transmitted.a);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},53360:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingStandardBlurPixelShader:()=>n});const r="fluidRenderingStandardBlurPixelShader",s="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;}\nfloat 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;}\nsum/=wsum;glFragColor=vec4(sum.rgb,1.);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},75424:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fxaaPixelShader:()=>n});const r="fxaaPixelShader",s="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nuniform 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);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid 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);\n#ifndef MALI\nif(range=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan)\n{lumaN=lumaW;}\nif (!horzSpan) \n{lumaS=lumaE;}\nif (horzSpan) \n{lengthSign=texelSize.y;}\nfloat 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)\n{lengthSign=-lengthSign;}\nfloat 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) \n{posB.x+=lengthSign*0.5;}\nif (horzSpan)\n{posB.y+=lengthSign*0.5;}\nvec2 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) \n{lumaNN=lumaSS;}\nfloat 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) \n{posN.x-=offNP.x*3.0;}\nif (!doneN) \n{posN.y-=offNP.y*3.0;}\nbool doneNP=(!doneN) || (!doneP);if (!doneP) \n{posP.x+=offNP.x*3.0;}\nif (!doneP)\n{posP.y+=offNP.y*3.0;}\nif (doneNP)\n{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;}\nfloat dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan)\n{dstN=posM.y-posN.y;}\nif (!horzSpan) \n{dstP=posP.y-posM.y;}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN{"use strict";i.r(t),i.d(t,{fxaaVertexShader:()=>n});const r="fxaaVertexShader",s="attribute vec2 position;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 vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=(position*madd+madd);sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},67058:(e,t,i)=>{"use strict";i.r(t),i.d(t,{gaussianSplattingPixelShader:()=>o});var r=i(69841);i(77165),i(25012),i(64657),i(6922),i(27185);r.l.IncludesShadersStore.gaussianSplattingFragmentDeclaration="vec4 gaussianColor(vec4 inColor)\n{float A=-dot(vPosition,vPosition);if (A<-4.0) discard;float B=exp(A)*inColor.a;\n#include\nvec3 color=inColor.rgb;\n#ifdef FOG\n#include\n#endif\nreturn vec4(color,B);}\n",i(89797);const s="gaussianSplattingPixelShader",n="#include\n#include\n#include\nvarying vec4 vColor;varying vec2 vPosition;\n#include\nvoid main () { \n#include\ngl_FragColor=gaussianColor(vColor);}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},21325:(e,t,i)=>{"use strict";i.r(t),i.d(t,{gaussianSplattingVertexShader:()=>o});var r=i(69841);i(93784),i(32405),i(13580);r.l.IncludesShadersStore.gaussianSplattingUboDeclaration="#include\n#include\nattribute vec2 position;",i(18355),i(77735),i(25012);r.l.IncludesShadersStore.gaussianSplatting="#if !defined(WEBGL2) && !defined(WEBGPU) && !defined(NATIVE)\nmat3 transpose(mat3 matrix) {return mat3(matrix[0][0],matrix[1][0],matrix[2][0],\nmatrix[0][1],matrix[1][1],matrix[2][1],\nmatrix[0][2],matrix[1][2],matrix[2][2]);}\n#endif\nvec2 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);}\nstruct Splat {vec4 center;vec4 color;vec4 covA;vec4 covB;};Splat readSplat(float splatIndex)\n{Splat splat;vec2 splatUV=getDataUV(splatIndex,dataTextureSize);splat.center=texture2D(centersTexture,splatUV);splat.color=texture2D(colorsTexture,splatUV);splat.covA=texture2D(covariancesATexture,splatUV)*splat.center.w;splat.covB=texture2D(covariancesBTexture,splatUV)*splat.center.w;return splat;}\nvec4 gaussianSplatting(vec2 meshPos,vec3 worldPos,vec2 scale,vec3 covA,vec3 covB,mat4 worldMatrix,mat4 viewMatrix,mat4 projectionMatrix)\n{mat4 modelView=viewMatrix*worldMatrix;vec4 camspace=viewMatrix*vec4(worldPos,1.);vec4 pos2d=projectionMatrix*camspace;float bounds=1.2*pos2d.w;if (pos2d.z<-pos2d.w || pos2d.x<-bounds || pos2d.x>bounds\n|| pos2d.y<-bounds || pos2d.y>bounds) {return vec4(0.0,0.0,2.0,1.0);}\nmat3 Vrk=mat3(\ncovA.x,covA.y,covA.z,\ncovA.y,covB.x,covB.y,\ncovA.z,covB.y,covB.z\n);mat3 J=mat3(\nfocal.x/camspace.z,0.,-(focal.x*camspace.x)/(camspace.z*camspace.z),\n0.,focal.y/camspace.z,-(focal.y*camspace.y)/(camspace.z*camspace.z),\n0.,0.,0.\n);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)\n{return vec4(0.0,0.0,2.0,1.0);}\nvec2 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);vec2 vCenter=vec2(pos2d);return vec4(\nvCenter \n+ ((meshPos.x*majorAxis\n+ meshPos.y*minorAxis)*invViewport*pos2d.w)*scale,pos2d.zw);}",i(71471),i(90715),i(88336);const s="gaussianSplattingVertexShader",n="#include<__decl__gaussianSplattingVertex>\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\nattribute float splatIndex;uniform vec2 invViewport;uniform vec2 dataTextureSize;uniform vec2 focal;uniform sampler2D covariancesATexture;uniform sampler2D covariancesBTexture;uniform sampler2D centersTexture;uniform sampler2D colorsTexture;varying vec4 vColor;varying vec2 vPosition;\n#include\nvoid main () {Splat splat=readSplat(splatIndex);vec3 covA=splat.covA.xyz;vec3 covB=vec3(splat.covA.w,splat.covB.xy);vec4 worldPos=world*vec4(splat.center.xyz,1.0);vColor=splat.color;vPosition=position;gl_Position=gaussianSplatting(position,worldPos.xyz,vec2(1.,1.),covA,covB,world,view,projection);\n#include\n#include\n#include\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},2146:(e,t,i)=>{"use strict";i.r(t),i.d(t,{geometryPixelShader:()=>o});var r=i(69841);i(77165);r.l.IncludesShadersStore.mrtFragmentDeclaration="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n",i(82267),i(29424),i(94388),i(89797),i(90249);const s="geometryPixelShader",n="#extension GL_EXT_draw_buffers : require\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\nprecision highp float;\n#ifdef BUMP\nvarying mat4 vWorldView;varying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#if defined(VELOCITY) || defined(VELOCITY_LINEAR)\nvarying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#ifdef NEED_UV\nvarying vec2 vUV;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIVITY)\n#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nuniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV;\n#endif\n#ifdef ALBEDOTEXTURE\nvarying vec2 vAlbedoUV;uniform sampler2D albedoSampler;\n#endif\n#ifdef REFLECTIVITYCOLOR\nuniform vec3 reflectivityColor;\n#endif\n#ifdef ALBEDOCOLOR\nuniform vec3 albedoColor;\n#endif\n#ifdef METALLIC\nuniform float metallic;\n#endif\n#if defined(ROUGHNESS) || defined(GLOSSINESS)\nuniform float glossiness;\n#endif\n#endif\n#if defined(ALPHATEST) && defined(NEED_UV)\nuniform sampler2D diffuseSampler;\n#endif\n#include\n#include[SCENE_MRT_COUNT]\n#include\n#include\n#include\nvoid main() {\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nvec3 normalOutput;\n#ifdef BUMP\nvec3 normalW=normalize(vNormalW);\n#include\n#ifdef NORMAL_WORLDSPACE\nnormalOutput=normalW;\n#else\nnormalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0)));\n#endif\n#else\nnormalOutput=normalize(vNormalV);\n#endif\n#ifdef ENCODE_NORMAL\nnormalOutput=normalOutput*0.5+0.5;\n#endif\n#ifdef DEPTH\ngl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n#endif\n#ifdef NORMAL\ngl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0);\n#endif\n#ifdef SCREENSPACE_DEPTH\ngl_FragData[SCREENSPACE_DEPTH_INDEX]=vec4(gl_FragCoord.z,0.0,0.0,1.0);\n#endif\n#ifdef POSITION\ngl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0);\n#endif\n#ifdef VELOCITY\nvec2 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);\n#endif\n#ifdef VELOCITY_LINEAR\nvec2 velocity=vec2(0.5)*((vPreviousPosition.xy/vPreviousPosition.w) -\n(vCurrentPosition.xy/vCurrentPosition.w));gl_FragData[VELOCITY_LINEAR_INDEX]=vec4(velocity,0.0,1.0);\n#endif\n#ifdef REFLECTIVITY\nvec4 reflectivity=vec4(0.0,0.0,0.0,1.0);\n#ifdef METALLICWORKFLOW\nfloat metal=1.0;float roughness=1.0;\n#ifdef ORMTEXTURE\nmetal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g;\n#endif\n#ifdef METALLIC\nmetal*=metallic;\n#endif\n#ifdef ROUGHNESS\nroughness*=(1.0-glossiness); \n#endif\nreflectivity.a-=roughness;vec3 color=vec3(1.0);\n#ifdef ALBEDOTEXTURE\ncolor=texture2D(albedoSampler,vAlbedoUV).rgb;\n#ifdef GAMMAALBEDO\ncolor=toLinearSpace(color);\n#endif\n#endif\n#ifdef ALBEDOCOLOR\ncolor*=albedoColor.xyz;\n#endif\nreflectivity.rgb=mix(vec3(0.04),color,metal);\n#else\n#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nreflectivity=texture2D(reflectivitySampler,vReflectivityUV);\n#ifdef GAMMAREFLECTIVITYTEXTURE\nreflectivity.rgb=toLinearSpace(reflectivity.rgb);\n#endif\n#else \n#ifdef REFLECTIVITYCOLOR\nreflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0;\n#endif\n#endif\n#ifdef GLOSSINESSS\nreflectivity.a*=glossiness; \n#endif\n#endif\ngl_FragData[REFLECTIVITY_INDEX]=reflectivity;\n#endif\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},24077:(e,t,i)=>{"use strict";i.r(t),i.d(t,{geometryVertexShader:()=>o});var r=i(69841);i(39948),i(66682),i(9158),i(11783),i(56865);r.l.IncludesShadersStore.geometryVertexDeclaration="uniform mat4 viewProjection;uniform mat4 view;",i(32405);r.l.IncludesShadersStore.geometryUboDeclaration="#include\n",i(18355),i(99216),i(44219),i(18411),i(78792),i(95532),i(71471),i(78595);const s="geometryVertexShader",n="precision highp float;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include<__decl__geometryVertex>\n#include\nattribute vec3 position;attribute vec3 normal;\n#ifdef NEED_UV\nvarying vec2 vUV;\n#ifdef ALPHATEST\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef BUMP\nuniform mat4 bumpMatrix;varying vec2 vBumpUV;\n#endif\n#ifdef REFLECTIVITY\nuniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef BUMP\nvarying mat4 vWorldView;\n#endif\n#ifdef BUMP\nvarying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#if defined(VELOCITY) || defined(VELOCITY_LINEAR)\nuniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include\n#include\nvec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0));\n#ifdef BUMP\nvWorldView=view*finalWorld;mat3 normalWorld=mat3(finalWorld);vNormalW=normalize(normalWorld*normalUpdated);\n#else\n#ifdef NORMAL_WORLDSPACE\nvNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#else\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0)));\n#endif\n#endif\nvViewPos=view*worldPos;\n#if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);\n#else\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#endif\n#if defined(POSITION) || defined(BUMP)\nvPositionW=worldPos.xyz/worldPos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#include\n#ifdef NEED_UV\n#ifdef UV1\n#if defined(ALPHATEST) && defined(ALPHATEST_UV1)\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#else\nvUV=uv;\n#endif\n#ifdef BUMP_UV1\nvBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV1\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV1\nvAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#endif\n#ifdef UV2\n#if defined(ALPHATEST) && defined(ALPHATEST_UV2)\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#else\nvUV=uv2;\n#endif\n#ifdef BUMP_UV2\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV2\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV2\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#endif\n#include\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},16655:(e,t,i)=>{"use strict";i.r(t),i.d(t,{glowBlurPostProcessPixelShader:()=>n});const r="glowBlurPostProcessPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 direction;uniform float blurWidth;float getLuminance(vec3 color)\n{return dot(color,vec3(0.2126,0.7152,0.0722));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float weights[7];weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;vec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);vec2 texelStep=texelSize*direction*blurWidth;vec2 start=vUV-3.0*texelStep;vec4 baseColor=vec4(0.,0.,0.,0.);vec2 texelOffset=vec2(0.,0.);for (int i=0; i<7; i++)\n{vec4 texel=texture2D(textureSampler,start+texelOffset);baseColor.a+=texel.a*weights[i];float luminance=getLuminance(baseColor.rgb);float luminanceTexel=getLuminance(texel.rgb);float choice=step(luminanceTexel,luminance);baseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;texelOffset+=texelStep;}\ngl_FragColor=baseColor;}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},42591:(e,t,i)=>{"use strict";i.r(t),i.d(t,{glowMapGenerationPixelShader:()=>o});var r=i(69841);i(94388),i(77165),i(89797);const s="glowMapGenerationPixelShader",n="#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform sampler2D diffuseSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform sampler2D emissiveSampler;\n#endif\n#ifdef VERTEXALPHA\nvarying vec4 vColor;\n#endif\nuniform vec4 glowColor;uniform float glowIntensity;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\nvec4 finalColor=glowColor;\n#ifdef DIFFUSE\nvec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);\n#ifdef DIFFUSE_ISLINEAR\nalbedoTexture=toGammaSpace(albedoTexture);\n#endif\n#ifdef GLOW\nfinalColor.a*=albedoTexture.a;\n#endif\n#ifdef HIGHLIGHT\nfinalColor.a=albedoTexture.a;\n#endif\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vUVOpacity);\n#ifdef OPACITYRGB\nfinalColor.a*=getLuminance(opacityMap.rgb);\n#else\nfinalColor.a*=opacityMap.a;\n#endif\nfinalColor.a*=opacityIntensity;\n#endif\n#ifdef VERTEXALPHA\nfinalColor.a*=vColor.a;\n#endif\n#ifdef ALPHATEST\nif (finalColor.a{"use strict";i.r(t),i.d(t,{glowMapGenerationVertexShader:()=>o});var r=i(69841);i(39948),i(66682),i(9158),i(11783),i(18355),i(56865),i(99216),i(44219),i(18411),i(78792),i(95532),i(71471);const s="glowMapGenerationVertexShader",n="attribute vec3 position;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;varying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform mat4 diffuseMatrix;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform mat4 opacityMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform mat4 emissiveMatrix;\n#endif\n#ifdef VERTEXALPHA\nattribute vec4 color;varying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef CUBEMAP\nvPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*worldPos;gl_Position=vPosition;\n#endif\n#ifdef DIFFUSE\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef OPACITY\n#ifdef OPACITYUV1\nvUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef OPACITYUV2\nvUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef VERTEXALPHA\nvColor=color;\n#endif\n#include\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},74969:(e,t,i)=>{"use strict";i.r(t),i.d(t,{glowMapMergePixelShader:()=>n});const r="glowMapMergePixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\nuniform float offset;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);baseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\n#if LDR\nbaseColor=clamp(baseColor,0.,1.0);\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},99347:(e,t,i)=>{"use strict";i.r(t),i.d(t,{glowMapMergeVertexShader:()=>n});const r="glowMapMergeVertexShader",s="attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},55099:(e,t,i)=>{"use strict";i.r(t),i.d(t,{grainPixelShader:()=>o});var r=i(69841);i(94388);const s="grainPixelShader",n="#include\nuniform sampler2D textureSampler; \nuniform float intensity;uniform float animatedSeed;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{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);}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},80424:(e,t,i)=>{"use strict";i.r(t),i.d(t,{hdrFilteringPixelShader:()=>o});var r=i(69841);i(94388),i(71826),i(67350),i(98392);const s="hdrFilteringPixelShader",n="#include\n#include\n#include\n#include\nuniform 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);}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},77318:(e,t,i)=>{"use strict";i.r(t),i.d(t,{hdrFilteringVertexShader:()=>n});const r="hdrFilteringVertexShader",s="attribute vec2 position;varying vec3 direction;uniform vec3 up;uniform vec3 right;uniform vec3 front;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nmat3 view=mat3(up,right,front);direction=view*vec3(position,1.0);gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},13079:(e,t,i)=>{"use strict";i.r(t),i.d(t,{highlightsPixelShader:()=>n});const r="highlightsPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{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); }";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},17897:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblCombineVoxelGridsPixelShader:()=>n});const r="iblCombineVoxelGridsPixelShader",s="precision highp float;precision highp sampler3D;varying vec2 vUV;uniform sampler3D voxelXaxisSampler;uniform sampler3D voxelYaxisSampler;uniform sampler3D voxelZaxisSampler;uniform float layer;void main(void) {vec3 coordZ=vec3(vUV.x,vUV.y,layer);float voxelZ=texture(voxelZaxisSampler,coordZ).r;vec3 coordX=vec3(1.0-layer,vUV.y,vUV.x);float voxelX=texture(voxelXaxisSampler,coordX).r;vec3 coordY=vec3(layer,vUV.x,vUV.y);float voxelY=texture(voxelYaxisSampler,coordY).r;float voxel=(voxelX>0.0 || voxelY>0.0 || voxelZ>0.0) ? 1.0 : 0.0;glFragColor=vec4(vec3(voxel),1.0);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},99638:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblGenerateVoxelMipPixelShader:()=>n});const r="iblGenerateVoxelMipPixelShader",s="precision highp float;precision highp sampler3D;varying vec2 vUV;uniform sampler3D srcMip;uniform int layerNum;void main(void) {ivec3 Coords=ivec3(2)*ivec3(gl_FragCoord.x,gl_FragCoord.y,layerNum);uint tex =\nuint(texelFetch(srcMip,Coords+ivec3(0,0,0),0).x>0.0f ? 1u : 0u)\n<< 0u |\nuint(texelFetch(srcMip,Coords+ivec3(1,0,0),0).x>0.0f ? 1u : 0u)\n<< 1u |\nuint(texelFetch(srcMip,Coords+ivec3(0,1,0),0).x>0.0f ? 1u : 0u)\n<< 2u |\nuint(texelFetch(srcMip,Coords+ivec3(1,1,0),0).x>0.0f ? 1u : 0u)\n<< 3u |\nuint(texelFetch(srcMip,Coords+ivec3(0,0,1),0).x>0.0f ? 1u : 0u)\n<< 4u |\nuint(texelFetch(srcMip,Coords+ivec3(1,0,1),0).x>0.0f ? 1u : 0u)\n<< 5u |\nuint(texelFetch(srcMip,Coords+ivec3(0,1,1),0).x>0.0f ? 1u : 0u)\n<< 6u |\nuint(texelFetch(srcMip,Coords+ivec3(1,1,1),0).x>0.0f ? 1u : 0u)\n<< 7u;glFragColor.rgb=vec3(float(tex)/255.0f,0.0f,0.0f);glFragColor.a=1.0;}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},17864:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowAccumulationPixelShader:()=>n});const r="iblShadowAccumulationPixelShader",s="#ifdef GL_ES\nprecision mediump float;\n#endif\nvarying vec2 vUV;uniform vec4 accumulationParameters;\n#define remanence accumulationParameters.x\n#define resetb accumulationParameters.y\n#define sceneSize accumulationParameters.z\nuniform sampler2D motionSampler;uniform sampler2D positionSampler;uniform sampler2D spatialBlurSampler;uniform sampler2D oldAccumulationSampler;uniform sampler2D prevPositionSampler;vec2 max2(vec2 v,vec2 w) { return vec2(max(v.x,w.x),max(v.y,w.y)); }\nvoid main(void) {bool reset=bool(resetb);vec2 gbufferRes=vec2(textureSize(motionSampler,0));ivec2 gbufferPixelCoord=ivec2(vUV*gbufferRes);vec2 shadowRes=vec2(textureSize(spatialBlurSampler,0));ivec2 shadowPixelCoord=ivec2(vUV*shadowRes);vec4 LP=texelFetch(positionSampler,gbufferPixelCoord,0);if (0.0==LP.w) {gl_FragColor=vec4(1.0,0.0,0.0,1.0);return;}\nvec2 velocityColor=texelFetch(motionSampler,gbufferPixelCoord,0).xy;vec2 prevCoord=vUV+velocityColor;vec3 PrevLP=texture(prevPositionSampler,prevCoord).xyz;vec3 PrevShadows=texture(oldAccumulationSampler,prevCoord).xyz;vec2 newShadows=texelFetch(spatialBlurSampler,shadowPixelCoord,0).xy;PrevShadows.z =\n!reset && all(lessThan(abs(prevCoord-vec2(0.5)),vec2(0.5))) &&\ndistance(LP.xyz,PrevLP)<5e-2*sceneSize\n? max(PrevShadows.z/(1.0+PrevShadows.z),1.0-remanence)\n: 1.0;PrevShadows=max(vec3(0.0),PrevShadows);gl_FragColor =\nvec4(mix(PrevShadows.x,newShadows.x,PrevShadows.z),\nmix(PrevShadows.y,newShadows.y,PrevShadows.z),PrevShadows.z,1.0);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},73588:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowDebugPixelShader:()=>n});const r="iblShadowDebugPixelShader",s="#ifdef GL_ES\nprecision mediump float;\n#endif\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D debugSampler;uniform vec4 sizeParams;\n#define offsetX sizeParams.x\n#define offsetY sizeParams.y\n#define widthScale sizeParams.z\n#define heightScale sizeParams.w\nvoid main(void) {vec2 uv =\nvec2((offsetX+vUV.x)*widthScale,(offsetY+vUV.y)*heightScale);vec4 background=texture2D(textureSampler,vUV);vec4 debugColour=texture2D(debugSampler,vUV);if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {gl_FragColor.rgba=background;} else {gl_FragColor.rgb=mix(debugColour.rgb,background.rgb,0.0);gl_FragColor.a=1.0;}}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},64367:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowGBufferDebugPixelShader:()=>n});const r="iblShadowGBufferDebugPixelShader",s="#ifdef GL_ES\nprecision mediump float;\n#endif\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform sampler2D positionSampler;uniform sampler2D velocitySampler;uniform vec4 sizeParams;uniform float maxDepth;\n#define offsetX sizeParams.x\n#define offsetY sizeParams.y\n#define widthScale sizeParams.z\n#define heightScale sizeParams.w\nvoid main(void) {vec2 uv =\nvec2((offsetX+vUV.x)*widthScale,(offsetY+vUV.y)*heightScale);vec4 backgroundColour=texture2D(textureSampler,vUV).rgba;vec4 depth=texture2D(depthSampler,vUV);vec4 worldNormal=texture2D(normalSampler,vUV);vec4 worldPosition=texture2D(positionSampler,vUV);vec4 velocityLinear=texture2D(velocitySampler,vUV);if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {gl_FragColor.rgba=backgroundColour;} else {gl_FragColor.a=1.0;if (uv.x<=0.25) {gl_FragColor.rgb=depth.rgb;gl_FragColor.a=1.0;} else if (uv.x<=0.5) {velocityLinear.rg=velocityLinear.rg*0.5+0.5;gl_FragColor.rgb=velocityLinear.rgb;} else if (uv.x<=0.75) {gl_FragColor.rgb=worldPosition.rgb;} else {gl_FragColor.rgb=worldNormal.rgb;}}}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},80018:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowSpatialBlurPixelShader:()=>n});const r="iblShadowSpatialBlurPixelShader",s="precision highp sampler2D;\n#define PI 3.1415927\nvarying vec2 vUV;uniform sampler2D depthSampler;uniform sampler2D worldNormalSampler;uniform sampler2D voxelTracingSampler;uniform vec4 blurParameters;\n#define stridef blurParameters.x\n#define worldScale blurParameters.y\nconst float weights[5]=float[5](0.0625,0.25,0.375,0.25,0.0625);const int nbWeights=5;vec2 max2(vec2 v,vec2 w) {return vec2(max(v.x,w.x),max(v.y,w.y));}\nvoid main(void)\n{vec2 gbufferRes=vec2(textureSize(depthSampler,0));ivec2 gbufferPixelCoord=ivec2(vUV*gbufferRes);vec2 shadowRes=vec2(textureSize(voxelTracingSampler,0));ivec2 shadowPixelCoord=ivec2(vUV*shadowRes);vec3 N=texelFetch(worldNormalSampler,gbufferPixelCoord,0).xyz;if (length(N)<0.01) {glFragColor=vec4(1.0,1.0,0.0,1.0);return;}\nfloat depth=-texelFetch(depthSampler,gbufferPixelCoord,0).x;vec3 X=vec3(0.0);for(int y=0; y>1),y-(nbWeights>>1));ivec2 shadowCoords=shadowPixelCoord+int(stridef)*ivec2(x-(nbWeights>>1),y-(nbWeights>>1));vec2 T=texelFetch(voxelTracingSampler,shadowCoords,0).xy;float ddepth=-texelFetch(depthSampler,gBufferCoords,0).x-depth;vec3 dN=texelFetch(worldNormalSampler,gBufferCoords,0).xyz-N;float w=weights[x]*weights[y] *\nexp2(max(-1000.0/(worldScale*worldScale),-0.5) *\n(ddepth*ddepth) -\n1e1*dot(dN,dN));X+=vec3(w*T.x,w*T.y,w);}}\ngl_FragColor=vec4(X.x/X.z,X.y/X.z,1.0,1.0);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},74747:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowVoxelTracingPixelShader:()=>n});const r="iblShadowVoxelTracingPixelShader",s="precision highp sampler2D;precision highp sampler3D;\n#define PI 3.1415927\nvarying vec2 vUV;\n#define DISABLE_UNIFORMITY_ANALYSIS\nuniform sampler2D depthSampler;uniform sampler2D worldNormalSampler;uniform sampler2D blueNoiseSampler;uniform sampler2D icdfxSampler;uniform sampler2D icdfySampler;uniform sampler3D voxelGridSampler;uniform vec4 shadowParameters;\n#define SHADOWdirs shadowParameters.x\n#define SHADOWframe shadowParameters.y\n#define SHADOWenvRot shadowParameters.w\nuniform vec4 voxelBiasParameters;\n#define highestMipLevel voxelBiasParameters.z\nuniform vec4 sssParameters;\n#define SSSsamples sssParameters.x\n#define SSSstride sssParameters.y\n#define SSSmaxDistance sssParameters.z\n#define SSSthickness sssParameters.w\nuniform vec4 shadowOpacity;uniform mat4 projMtx;uniform mat4 viewMtx;uniform mat4 invProjMtx;uniform mat4 invViewMtx;uniform mat4 wsNormalizationMtx;uniform mat4 invVPMtx;\n#define PI 3.1415927\n#define GOLD 0.618034\nstruct AABB3f {vec3 m_min;vec3 m_max;};struct Ray {vec3 orig;vec3 dir;vec3 dir_rcp;float t_min;float t_max;};Ray make_ray(const vec3 origin,const vec3 direction,const float tmin,\nconst float tmax) {Ray ray;ray.orig=origin;ray.dir=direction;ray.dir_rcp=1.0f/direction;ray.t_min=tmin;ray.t_max=tmax;return ray;}\nbool ray_box_intersection(const in AABB3f aabb,const in Ray ray,\nout float distance_near,out float distance_far) {vec3 tbot=ray.dir_rcp*(aabb.m_min-ray.orig);vec3 ttop=ray.dir_rcp*(aabb.m_max-ray.orig);vec3 tmin=min(ttop,tbot);vec3 tmax=max(ttop,tbot);distance_near=max(ray.t_min,max(tmin.x,max(tmin.y,tmin.z)));distance_far=min(ray.t_max,min(tmax.x,min(tmax.y,tmax.z)));return distance_near<=distance_far;}\n#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nstruct VoxelMarchDiagnosticInfo {float heat;ivec3 voxel_intersect_coords;};\n#endif\nuint hash(uint i) {i ^= i>>16u;i*=0x7FEB352Du;i ^= i>>15u;i*=0x846CA68Bu;i ^= i>>16u;return i;}\nfloat uint2float(uint i) {return uintBitsToFloat(0x3F800000u | (i>>9u))-1.0;}\nvec3 uv_to_normal(vec2 uv) {vec3 N;vec2 uvRange=uv;float theta=uvRange.x*2.0*PI;float phi=uvRange.y*PI;N.x=cos(theta)*sin(phi);N.z=sin(theta)*sin(phi);N.y=cos(phi);return N;}\nvec2 plasticSequence(const uint rstate) {return vec2(uint2float(rstate*3242174889u),\nuint2float(rstate*2447445414u));}\nfloat goldenSequence(const uint rstate) {return uint2float(rstate*2654435769u);}\nfloat distanceSquared(vec2 a,vec2 b) {vec2 diff=a-b;return dot(diff,diff);}\nvoid genTB(const vec3 N,out vec3 T,out vec3 B) {float s=N.z<0.0 ? -1.0 : 1.0;float a=-1.0/(s+N.z);float b=N.x*N.y*a;T=vec3(1.0+s*N.x*N.x*a,s*b,-s*N.x);B=vec3(b,s+N.y*N.y*a,-N.y);}\nint stack[24]; \n#define PUSH(i) stack[stackLevel++]=i; \n#define POP() stack[--stackLevel] \n#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nbool anyHitVoxels(const Ray ray_vs,\nout VoxelMarchDiagnosticInfo voxel_march_diagnostic_info) {\n#else\nbool anyHitVoxels(const Ray ray_vs) {\n#endif\nvec3 invD=ray_vs.dir_rcp;vec3 D=ray_vs.dir;vec3 O=ray_vs.orig;ivec3 negD=ivec3(lessThan(D,vec3(0,0,0)));int voxel0=negD.x | negD.y<<1 | negD.z<<2;vec3 t0=-O*invD,t1=(vec3(1.0)-O)*invD;int maxLod=int(highestMipLevel);int stackLevel=0;\n#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nuint steps=0u;\n#endif\nPUSH(maxLod<<24);while (stackLevel>0) {int elem=POP();ivec4 Coords =\nivec4(elem & 0xFF,elem>>8 & 0xFF,elem>>16 & 0xFF,elem>>24);if (Coords.w==0) {\n#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nvoxel_march_diagnostic_info.heat=float(steps)/24.0;\n#endif\nreturn true;}\n#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\n++steps;\n#endif\nfloat invRes=exp2(float(Coords.w-maxLod));vec3 bbmin=invRes*vec3(Coords.xyz+negD);vec3 bbmax=invRes*vec3(Coords.xyz-negD+ivec3(1));vec3 mint=mix(t0,t1,bbmin);vec3 maxt=mix(t0,t1,bbmax);vec3 midt=0.5*(mint+maxt);mint.x=max(0.0,mint.x);midt.x=max(0.0,midt.x);int nodeMask=int(\nround(texelFetch(voxelGridSampler,Coords.xyz,Coords.w).x*255.0));Coords.w--;int voxelBit=voxel0;Coords.xyz=(Coords.xyz<<1)+negD;int packedCoords =\nCoords.x | Coords.y<<8 | Coords.z<<16 | Coords.w<<24;if (max(mint.x,max(mint.y,mint.z))0.0 && stepCountedge_tint_const) {vec4 VP2=VP;VP2.y*=-1.0;vec4 unormWP=invViewMtx*VP2;vec3 WP=(wsNormalizationMtx*unormWP).xyz;vec2 vxNoise =\nvec2(uint2float(hash(dirId*2u)),uint2float(hash(dirId*2u+1u)));\n#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nVoxelMarchDiagnosticInfo voxel_march_diagnostic_info;opacity=max(opacity,\nshadowOpacity.x*voxelShadow(WP,L.xyz,N,vxNoise,\nvoxel_march_diagnostic_info));heat+=voxel_march_diagnostic_info.heat;\n#else\nopacity =\nmax(opacity,shadowOpacity.x*voxelShadow(WP,L.xyz,N,vxNoise));\n#endif\nvec3 VL=(viewMtx*L).xyz;\n#ifdef RIGHT_HANDED\nfloat nearPlaneZ=-projMtx[3][2]/(projMtx[2][2]-1.0); \nfloat farPlaneZ=-projMtx[3][2]/(projMtx[2][2]+1.0);\n#else\nfloat nearPlaneZ=-projMtx[3][2]/(projMtx[2][2]+1.0); \nfloat farPlaneZ=-projMtx[3][2]/(projMtx[2][2]-1.0);\n#endif\nfloat ssShadow=shadowOpacity.y *\nscreenSpaceShadow(VP2.xyz,VL,Resolution,nearPlaneZ,farPlaneZ,\nabs(2.0*noise.z-1.0));opacity=max(opacity,ssShadow);shadowAccum+=min(1.0-opacity,cosNL);sampleWeight+=cosNL;vec3 VR=-(viewMtx*vec4(reflect(-L.xyz,N),0.0)).xyz;specShadowAccum+=max(1.0-(opacity*pow(VR.z,8.0)),0.0);}\nnoise.z=fract(noise.z+GOLD);}\n#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\ngl_FragColor=vec4(shadowAccum/float(sampleWeight),\nspecShadowAccum/float(sampleWeight),heat/float(sampleWeight),1.0);\n#else\ngl_FragColor=vec4(shadowAccum/float(sampleWeight),specShadowAccum/float(sampleWeight),0.0,1.0);\n#endif\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},47473:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowsCdfxPixelShader:()=>n});const r="iblShadowsCdfxPixelShader",s="precision highp sampler2D;\n#define PI 3.1415927\nvarying vec2 vUV;uniform sampler2D cdfy;void main(void) {ivec2 cdfyRes=textureSize(cdfy,0);ivec2 currentPixel=ivec2(gl_FragCoord.xy);float cdfx=0.0;for (int x=1; x<=currentPixel.x; x++) {cdfx+=texelFetch(cdfy,ivec2(x-1,cdfyRes.y-1),0).x;}\ngl_FragColor=vec4(vec3(cdfx),1.0);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},98824:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowsCdfyPixelShader:()=>n});const r="iblShadowsCdfyPixelShader",s="precision highp sampler2D;precision highp samplerCube;\n#define PI 3.1415927\nvarying vec2 vUV;\n#ifdef IBL_USE_CUBE_MAP\nuniform samplerCube iblSource;\n#else\nuniform sampler2D iblSource;\n#endif\nuniform int iblHeight;\n#ifdef IBL_USE_CUBE_MAP\nvec3 equirectangularToCubemapDirection(vec2 uv) {float longitude=uv.x*2.0*PI-PI;float latitude=PI*0.5-uv.y*PI;vec3 direction;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;}\nfloat fetchCube(vec2 uv) {vec3 direction=equirectangularToCubemapDirection(uv);return sin(PI*uv.y)*dot(textureCubeLodEXT(iblSource,direction,0.0).rgb,\nvec3(0.3,0.6,0.1));}\n#else\nfloat fetchPanoramic(ivec2 Coords,float envmapHeight) {return sin(PI*(float(Coords.y)+0.5)/envmapHeight) *\ndot(texelFetch(iblSource,Coords,0).rgb,vec3(0.3,0.6,0.1));}\n#endif\nvoid main(void) {ivec2 coords=ivec2(gl_FragCoord.x,gl_FragCoord.y);float cdfy=0.0;for (int y=1; y<=coords.y; y++) {\n#ifdef IBL_USE_CUBE_MAP\nvec2 uv=vec2(vUV.x,(float(y-1)+0.5)/float(iblHeight));cdfy+=fetchCube(uv);\n#else\ncdfy+=fetchPanoramic(ivec2(coords.x,y-1),float(iblHeight));\n#endif\n}\ngl_FragColor=vec4(cdfy,0.0,0.0,1.0);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},8970:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowsIcdfxPixelShader:()=>n});const r="iblShadowsIcdfxPixelShader",s="precision highp sampler2D;\n#define PI 3.1415927\nvarying vec2 vUV;uniform sampler2D cdfx;float fetchCDF(int x) {return texelFetch(cdfx,ivec2(x,0),0).x;}\nfloat bisect(int size,float targetValue)\n{int a=0,b=size-1;while (b-a>1) {int c=a+b>>1;if (fetchCDF(c){"use strict";i.r(t),i.d(t,{iblShadowsIcdfyPixelShader:()=>n});const r="iblShadowsIcdfyPixelShader",s="precision highp sampler2D;\n#define PI 3.1415927\nvarying vec2 vUV;uniform sampler2D cdfy;float fetchCDF(int y,int invocationId) {return texelFetch(cdfy,ivec2(invocationId,y),0).x;}\nfloat bisect(int size,float targetValue,int invocationId)\n{int a=0,b=size-1;while (b-a>1) {int c=a+b>>1;if (fetchCDF(c,invocationId){"use strict";i.r(t),i.d(t,{iblShadowsImportanceSamplingDebugPixelShader:()=>n});const r="iblShadowsImportanceSamplingDebugPixelShader",s="precision highp samplerCube;\n#define PI 3.1415927\nvarying vec2 vUV;uniform sampler2D cdfy;uniform sampler2D icdfy;uniform sampler2D cdfx;uniform sampler2D icdfx;\n#ifdef IBL_USE_CUBE_MAP\nuniform samplerCube iblSource;\n#else\nuniform sampler2D iblSource;\n#endif\nuniform sampler2D textureSampler;\n#define cdfyVSize 0.4\n#define cdfxVSize 0.1\n#define cdfyHSize 0.5\nuniform vec4 sizeParams;\n#define offsetX sizeParams.x\n#define offsetY sizeParams.y\n#define widthScale sizeParams.z\n#define heightScale sizeParams.w\n#ifdef IBL_USE_CUBE_MAP\nvec3 equirectangularToCubemapDirection(vec2 uv) {float longitude=uv.x*2.0*PI-PI;float latitude=PI*0.5-uv.y*PI;vec3 direction;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;}\n#endif\nvoid main(void) {vec3 colour=vec3(0.0);vec2 uv =\nvec2((offsetX+vUV.x)*widthScale,(offsetY+vUV.y)*heightScale);vec3 backgroundColour=texture2D(textureSampler,vUV).rgb;const float iblStart=1.0-cdfyVSize;const float cdfyStart=1.0-2.0*cdfyVSize;const float cdfxStart=1.0-2.0*cdfyVSize-cdfxVSize;const float icdfxStart=1.0-2.0*cdfyVSize-2.0*cdfxVSize;\n#ifdef IBL_USE_CUBE_MAP\nvec3 direction=equirectangularToCubemapDirection(\n(uv-vec2(0.0,iblStart))*vec2(1.0,1.0/cdfyVSize));vec3 iblColour=textureCubeLodEXT(iblSource,direction,0.0).rgb;\n#else\nvec3 iblColour=texture2D(iblSource,(uv-vec2(0.0,iblStart)) *\nvec2(1.0,1.0/cdfyVSize))\n.rgb;\n#endif\nfloat cdfyColour =\ntexture2D(cdfy,(uv-vec2(0.0,cdfyStart))*vec2(2.0,1.0/cdfyVSize))\n.r;float icdfyColour =\ntexture2D(icdfy,(uv-vec2(0.5,cdfyStart))*vec2(2.0,1.0/cdfyVSize))\n.r;float cdfxColour =\ntexture2D(cdfx,(uv-vec2(0.0,cdfxStart))*vec2(1.0,1.0/cdfxVSize))\n.r;float icdfxColour=texture2D(icdfx,(uv-vec2(0.0,icdfxStart)) *\nvec2(1.0,1.0/cdfxVSize))\n.r;if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {colour=backgroundColour;} else if (uv.y>iblStart) {colour+=iblColour;} else if (uv.y>cdfyStart && uv.x<0.5) {colour.r+=0.003*cdfyColour;} else if (uv.y>cdfyStart && uv.x>0.5) {colour.r+=icdfyColour;} else if (uv.y>cdfxStart) {colour.r+=0.00003*cdfxColour;} else if (uv.y>icdfxStart) {colour.r+=icdfxColour;}\ngl_FragColor=vec4(colour,1.0);glFragColor.rgb=mix(gl_FragColor.rgb,backgroundColour,0.5);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},83145:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblVoxelGridPixelShader:()=>n});const r="iblVoxelGridPixelShader",s="precision highp float;layout(location=0) out highp float glFragData[MAX_DRAW_BUFFERS];varying vec3 vNormalizedPosition;uniform float nearPlane;uniform float farPlane;uniform float stepSize;void main(void) {vec3 normPos=vNormalizedPosition.xyz;if (normPos.zfarPlane) {discard;}\nglFragData[0]=normPos.z=nearPlane+stepSize && normPos.z=nearPlane+2.0*stepSize && normPos.z=nearPlane+3.0*stepSize && normPos.z4\nglFragData[4]=normPos.z>=nearPlane+4.0*stepSize && normPos.z=nearPlane+5.0*stepSize && normPos.z=nearPlane+6.0*stepSize && normPos.z=nearPlane+7.0*stepSize && normPos.z{"use strict";i.r(t),i.d(t,{iblVoxelGridVertexShader:()=>n});const r="iblVoxelGridVertexShader",s="attribute vec3 position;attribute vec3 normal;varying vec3 vNormalizedPosition;uniform mat4 world;uniform mat4 invWorldScale;uniform mat4 viewMatrix;void main(void) {gl_Position=viewMatrix*invWorldScale*world*vec4(position,1.);vNormalizedPosition.xyz=gl_Position.xyz*0.5+0.5;\n#ifdef IS_NDC_HALF_ZRANGE\ngl_Position.z=gl_Position.z*0.5+0.5;\n#endif\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},68859:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblVoxelGrid2dArrayDebugPixelShader:()=>n});const r="iblVoxelGrid2dArrayDebugPixelShader",s="precision highp sampler2DArray;varying vec2 vUV;uniform sampler2DArray voxelTexture;uniform sampler2D textureSampler;uniform int slice;void main(void) {ivec3 size=textureSize(voxelTexture,0);float dimension=sqrt(float(size.z));vec2 samplePos=fract(vUV.xy*vec2(dimension));int sampleIndex=int(floor(vUV.x*float(dimension))+floor(vUV.y*float(dimension))*dimension);glFragColor.rgb=texture(voxelTexture,vec3(samplePos.xy,sampleIndex)).rrr;glFragColor.a=1.0;glFragColor.rgb+=texture(textureSampler,vUV.xy).rgb;}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},95171:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblVoxelGrid3dDebugPixelShader:()=>n});const r="iblVoxelGrid3dDebugPixelShader",s="precision highp sampler3D;varying vec2 vUV;uniform sampler3D voxelTexture;uniform sampler2D voxelSlabTexture;uniform sampler2D textureSampler;uniform vec4 sizeParams;\n#define offsetX sizeParams.x\n#define offsetY sizeParams.y\n#define widthScale sizeParams.z\n#define heightScale sizeParams.w\nuniform float mipNumber;void main(void) {vec2 uv =\nvec2((offsetX+vUV.x)*widthScale,(offsetY+vUV.y)*heightScale);vec4 background=texture2D(textureSampler,vUV);vec4 voxelSlab=texture2D(voxelSlabTexture,vUV);ivec3 size=textureSize(voxelTexture,int(mipNumber));float dimension=ceil(sqrt(float(size.z)));vec2 samplePos=fract(uv.xy*vec2(dimension));int sampleIndex=int(floor(uv.x*float(dimension)) +\nfloor(uv.y*float(dimension))*dimension);float mip_separator=0.0;if (samplePos.x<0.01 || samplePos.y<0.01) {mip_separator=1.0;}\nbool outBounds=sampleIndex>size.z-1 ? true : false;sampleIndex=clamp(sampleIndex,0,size.z-1);ivec2 samplePosInt=ivec2(samplePos.xy*vec2(size.xy));vec3 voxel=texelFetch(voxelTexture,\nivec3(samplePosInt.x,samplePosInt.y,sampleIndex),\nint(mipNumber))\n.rgb;if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {gl_FragColor.rgba=background;} else {if (outBounds) {voxel=vec3(0.15,0.0,0.0);} else {if (voxel.r>0.001) {voxel.g=1.0;}\nvoxel.r+=mip_separator;}\nglFragColor.rgb=mix(background.rgb,voxelSlab.rgb,voxelSlab.a)+voxel;glFragColor.a=1.0;}}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},81284:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblVoxelSlabDebugPixelShader:()=>n});const r="iblVoxelSlabDebugPixelShader",s="precision highp float;varying vec3 vNormalizedPosition;uniform float nearPlane;uniform float farPlane;uniform float stepSize;void main(void) {vec3 normPos=vNormalizedPosition.xyz;float chunkSize=stepSize*float(MAX_DRAW_BUFFERS);float numChunks=1.0/chunkSize;float positionInChunk=fract(normPos.z/chunkSize);float slab=floor(positionInChunk*float(MAX_DRAW_BUFFERS)) /\nfloat(MAX_DRAW_BUFFERS);if (normPos.x<0.0 || normPos.y<0.0 || normPos.z<0.0 ||\nnormPos.x>1.0 || normPos.y>1.0 || normPos.z>1.0) {gl_FragColor=vec4(0.0,0.0,0.0,0.0);} else {gl_FragColor=vec4(slab,0.0,0.0,0.75);}}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},71650:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblVoxelSlabDebugVertexShader:()=>n});const r="iblVoxelSlabDebugVertexShader",s="attribute vec3 position;varying vec3 vNormalizedPosition;uniform mat4 world;uniform mat4 invWorldScale;uniform mat4 cameraViewMatrix;uniform mat4 projection;uniform mat4 viewMatrix;void main(void) {vec4 worldPosition=(world*vec4(position,1.));gl_Position=projection*cameraViewMatrix*worldPosition;vNormalizedPosition=(viewMatrix*invWorldScale*worldPosition).rgb;vNormalizedPosition.xyz=vNormalizedPosition.xyz*vec3(0.5)+vec3(0.5);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},27220:(e,t,i)=>{"use strict";i.r(t),i.d(t,{imageProcessingPixelShader:()=>o});var r=i(69841);i(75651),i(94388),i(88658);const s="imageProcessingPixelShader",n="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},45245:(e,t,i)=>{"use strict";i.r(t),i.d(t,{kernelBlurPixelShader:()=>o});var r=i(69841);i(953),i(72693);r.l.IncludesShadersStore.kernelBlurFragment="#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif\n";r.l.IncludesShadersStore.kernelBlurFragment2="#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif\n";const s="kernelBlurPixelShader",n="uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; }\n#endif\n#include[0..varyingCount]\n#ifdef PACKEDFLOAT\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float computedWeight=0.0;\n#ifdef PACKEDFLOAT\nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include[0..varyingCount]\n#include[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},95527:(e,t,i)=>{"use strict";i.r(t),i.d(t,{kernelBlurVertexShader:()=>o});var r=i(69841);i(953);r.l.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";const s="kernelBlurVertexShader",n="attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter;\n#include[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nsampleCenter=(position*madd+madd);\n#include[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},59329:(e,t,i)=>{"use strict";i.r(t),i.d(t,{layerPixelShader:()=>o});var r=i(69841);i(94388);const s="layerPixelShader",n="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#if defined(CONVERT_TO_GAMMA)\nbaseColor.rgb=toGammaSpace(baseColor.rgb);\n#elif defined(CONVERT_TO_LINEAR)\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},11115:(e,t,i)=>{"use strict";i.r(t),i.d(t,{layerVertexShader:()=>n});const r="layerVertexShader",s="attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},54262:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lensFlarePixelShader:()=>n});const r="lensFlarePixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},45980:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lensFlareVertexShader:()=>n});const r="lensFlareVertexShader",s="attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},85550:(e,t,i)=>{"use strict";i.r(t),i.d(t,{linePixelShader:()=>o});var r=i(69841);i(77165),i(25012),i(6922),i(89797);const s="linePixelShader",n="#include\nuniform vec4 color;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},42644:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lineVertexShader:()=>o});var r=i(69841);r.l.IncludesShadersStore.lineVertexDeclaration="uniform mat4 viewProjection;\n#define ADDITIONAL_VERTEX_DECLARATION\n",i(32405),i(13580);r.l.IncludesShadersStore.lineUboDeclaration="layout(std140,column_major) uniform;\n#include\n#include\n",i(56865),i(18355),i(25012),i(18411),i(71471),i(88336);const s="lineVertexShader",n="#include<__decl__lineVertex>\n#include\n#include\nattribute vec3 position;attribute vec4 normal;uniform float width;uniform float aspectRatio;\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\nmat4 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;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#include\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},46143:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lodPixelShader:()=>n});const r="lodPixelShader",s="#extension GL_EXT_shader_texture_lod : enable\nprecision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform sampler2D textureSampler;uniform float lod;uniform vec2 texSize;uniform int gamma;void main(void)\n{gl_FragColor=texture2DLodEXT(textureSampler,vUV,lod);if (gamma==0) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},47084:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lodCubePixelShader:()=>n});const r="lodCubePixelShader",s="precision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform samplerCube textureSampler;uniform float lod;uniform int gamma;void main(void)\n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x),lod);\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x),lod);\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x),lod);\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x),lod);\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001),lod);\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001),lod);\n#endif\nif (gamma==0) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},33287:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererPixelShader:()=>n});const r="meshUVSpaceRendererPixelShader",s="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;}\ngl_FragColor=texture2D(textureSampler,vDecalTC);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},82017:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererVertexShader:()=>o});var r=i(69841);i(39948),i(66682),i(9158),i(11783),i(56865),i(99216),i(44219),i(18411),i(78792),i(95532);const s="meshUVSpaceRendererVertexShader",n="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nvoid main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW;\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvNormalW=normalize(normWorldSM*normalUpdated);\n#endif\nvec3 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);}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},33534:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererFinaliserPixelShader:()=>n});const r="meshUVSpaceRendererFinaliserPixelShader",s="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;}\nif (mask_p21>0.5) {col+=texture2D(textureSampler,uv_p21);total_weight+=1.0;}\nif (mask_p10>0.5) {col+=texture2D(textureSampler,uv_p10);total_weight+=1.0;}\nif (mask_p12>0.5) {col+=texture2D(textureSampler,uv_p12);total_weight+=1.0;}\nif (total_weight>0.0) {gl_FragColor=col/total_weight;} else {gl_FragColor=col;}}}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},13460:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererFinaliserVertexShader:()=>n});const r="meshUVSpaceRendererFinaliserVertexShader",s="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;}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},99990:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererMaskerPixelShader:()=>n});const r="meshUVSpaceRendererMaskerPixelShader",s="varying vec2 vUV;void main(void) {gl_FragColor=vec4(1.0,1.0,1.0,1.0);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},96924:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererMaskerVertexShader:()=>n});const r="meshUVSpaceRendererMaskerVertexShader",s="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;}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},28377:(e,t,i)=>{"use strict";i.r(t),i.d(t,{motionBlurPixelShader:()=>n});const r="motionBlurPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize;\n#ifdef OBJECT_BASED\nuniform sampler2D velocitySampler;\n#else\nuniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#ifdef GEOMETRY_SUPPORTED\n#ifdef OBJECT_BASED\nvec2 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)\nbreak;vec2 offset=vUV+velocity*(hlim+float(i));\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset,0.0);\n#else\nresult+=texture2D(textureSampler,offset);\n#endif\n}\ngl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0;\n#else\nvec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; \nvec4 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)\nbreak;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset1,0.0);\n#else\nresult+=texture2D(textureSampler,offset1);\n#endif\n}\ngl_FragColor=result/float(nSamples);\n#endif\n#else\ngl_FragColor=texture2D(textureSampler,vUV);\n#endif\n}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},17738:(e,t,i)=>{"use strict";i.r(t),i.d(t,{oitBackBlendPixelShader:()=>n});const r="oitBackBlendPixelShader",s="precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { \ndiscard;}}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},4172:(e,t,i)=>{"use strict";i.r(t),i.d(t,{oitFinalPixelShader:()=>n});const r="oitFinalPixelShader",s="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(\nfrontColor.rgb+alphaMultiplier*backColor.rgb,\nfrontColor.a+backColor.a\n);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},32192:(e,t,i)=>{"use strict";i.r(t),i.d(t,{outlinePixelShader:()=>o});var r=i(69841);i(77165),i(25012),i(89797),i(6922);const s="outlinePixelShader",n="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},65038:(e,t,i)=>{"use strict";i.r(t),i.d(t,{outlineVertexShader:()=>o});var r=i(69841);i(39948),i(66682),i(9158),i(11783),i(18355),i(56865),i(25012),i(99216),i(44219),i(18411),i(78792),i(95532),i(71471),i(88336);const s="outlineVertexShader",n="attribute vec3 position;attribute vec3 normal;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform float offset;\n#include\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\nvec3 offsetPosition=positionUpdated+(normalUpdated*offset);\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n#include\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},50619:(e,t,i)=>{"use strict";i.r(t),i.d(t,{particlesPixelShader:()=>o});var r=i(69841);i(77165),i(75651),i(25012),i(94388),i(88658),i(64657),i(89797),i(6922),i(27185);const s="particlesPixelShader",n="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nvarying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler;\n#include\n#include\n#include\n#include\n#include\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;uniform sampler2D rampSampler;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat 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);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n#include\n#include(color,baseColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},70917:(e,t,i)=>{"use strict";i.r(t),i.d(t,{particlesVertexShader:()=>o});var r=i(69841);i(18355),i(77735),i(25012),i(71471),i(90715),i(88336);const s="particlesVertexShader",n="attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD\nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;\n#ifdef ANIMATESHEET\nuniform vec3 particlesInfos; \n#endif\nvarying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include\n#include\n#include\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 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;}\n#ifdef BILLBOARDSTRETCHED\nvec3 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);\n#ifdef BILLBOARDSTRETCHED_LOCAL\nvec3 row1=direction;\n#else\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\n#endif\nmat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;}\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size;\n#ifdef BILLBOARD\nvec3 rotatedCorner;\n#ifdef BILLBOARDY\nrotatedCorner.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;\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.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;\n#else\nrotatedCorner.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;\n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\ngl_Position=projection*vec4(viewPos,1.0);\n#else\nvec3 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);\n#endif\nvColor=color;\n#ifdef ANIMATESHEET\nfloat 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;\n#else\nvUV=offset;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},30927:(e,t,i)=>{"use strict";i.r(t),i.d(t,{passPixelShader:()=>n});const r="passPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},88412:(e,t,i)=>{"use strict";i.r(t),i.d(t,{passCubePixelShader:()=>n});const r="passCubePixelShader",s="varying vec2 vUV;uniform samplerCube textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\n#endif\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},43004:(e,t,i)=>{"use strict";i.r(t),i.d(t,{pbrPixelShader:()=>o});var r=i(69841);i(59317),i(36881),i(14774);r.l.IncludesShadersStore.pbrFragmentDeclaration="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;\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REALTIME_FILTERING\nuniform vec2 vReflectionFilteringInfo;\n#endif\nuniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; \n#endif\n#endif\n#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)\nuniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; \n#endif\n#ifdef CLEARCOAT\nuniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams;\n#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\n#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\n#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\n#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT\nuniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance;\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix;\n#endif\n#endif\n#endif\n#ifdef IRIDESCENCE\nuniform vec4 vIridescenceParams;\n#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\n#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\n#endif\n#endif\n#ifdef ANISOTROPIC\nuniform vec3 vAnisotropy;\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix;\n#endif\n#endif\n#ifdef SHEEN\nuniform vec4 vSheenColor;\n#ifdef SHEEN_ROUGHNESS\nuniform float vSheenRoughness;\n#endif\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\n#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\n#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\n#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix;\n#ifdef REALTIME_FILTERING\nuniform vec2 vRefractionFilteringInfo;\n#endif\n#ifdef SS_DISPERSION\nuniform float dispersion;\n#endif\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix;\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix;\n#endif\nuniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity;uniform vec4 vTranslucencyColor;\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\nuniform vec2 vTranslucencyColorInfos;uniform mat4 translucencyColorMatrix;\n#endif\n#endif\n#ifdef PREPASS\n#ifdef SS_SCATTERING\nuniform float scatteringDiffusionProfile;\n#endif\n#endif\n#if DEBUGMODE>0\nuniform vec2 vDebugMode;\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform 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;\n#else\nuniform 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;\n#endif\n#endif\n#define ADDITIONAL_FRAGMENT_DECLARATION\n",i(42413),i(40371);r.l.IncludesShadersStore.pbrFragmentExtraDeclaration="varying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#include[1..7]\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n",i(23133),i(58769),i(5301);r.l.IncludesShadersStore.samplerFragmentAlternateDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying vec2 v_VARYINGNAME_UV;\n#endif\n#endif\n";r.l.IncludesShadersStore.pbrFragmentSamplersDeclaration="#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform sampler2D clearCoatRoughnessSampler;\n#endif\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform sampler2D sheenRoughnessSampler;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform samplerCube irradianceSampler;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform sampler2D irradianceSampler;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#ifdef SS_REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh;\n#endif\n#endif\n#endif\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_SAMPLERNAME_,translucencyColor)\n#endif\n",i(75651),i(77165),i(25012),i(64657),i(94388),i(34001),i(71826);r.l.IncludesShadersStore.pbrHelperFunctions="#define MINIMUMVARIANCE 0.0005\nfloat convertRoughnessToAverageSlope(float roughness)\n{return square(roughness)+MINIMUMVARIANCE;}\nfloat fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;}\nvec2 getAARoughnessFactors(vec3 normalVector) {\n#ifdef SPECULARAA\nvec3 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);\n#else\nreturn vec2(0.);\n#endif\n}\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_LEGACY\nvec2 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);}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection;if (anisotropy>=0.0) {anisotropicFrameDirection=B;} else {anisotropicFrameDirection=T;}\nvec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;}\n#else\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);}\nvec3 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;}\n#endif\n#endif\n#if defined(CLEARCOAT) || defined(SS_REFRACTION)\nvec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);}\nvec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));}\nvec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;}\nvec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0),\ncocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),\nclearCoatIntensity);return clearCoatAbsorption;}\n#endif\n#ifdef MICROSURFACEAUTOMATIC\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;}\n#endif\n",i(88658),i(34091),i(10316);r.l.IncludesShadersStore.pbrDirectLightingSetupFunctions="struct preLightingInfo\n{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness;\n#ifdef IRIDESCENCE\nfloat iridescenceIntensity;\n#endif\n};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N,vec3 posW) {preLightingInfo result;result.lightOffset=lightData.xyz-posW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\npreLightingInfo 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;}\npreLightingInfo 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;\n#ifdef SPECULARTERM\nresult.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));\n#endif\nreturn result;}";r.l.IncludesShadersStore.pbrDirectLightingFalloffFunctions="float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{return max(0.,1.0-length(lightOffset)/range);}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{return 1.0/maxEps(lightDistanceSquared);}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle)\n{falloff=max(0.,pow(cosAngle,exponent));}\nreturn falloff;}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}",i(67350),i(98392);r.l.IncludesShadersStore.pbrDirectLightingFunctions="#define CLEARCOATREFLECTANCE90 1.0\nstruct lightingInfo\n{vec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef CLEARCOAT\nvec4 clearCoat;\n#endif\n#ifdef SHEEN\nvec3 sheen;\n#endif\n};float adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) {\n#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\nfloat lightRoughness=lightRadius/lightDistance;float totalRoughness=saturate(lightRoughness+roughness);return totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nvec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {return mix(groundColor,lightColor,info.NdotL);}\nvec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {float diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;}\n#define inline\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix,vec3 posW){vec4 strq=textureProjectionMatrix*vec4(posW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return toLinearSpace(textureColor);}\n#ifdef SS_TRANSLUCENCY\nvec3 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;}\n#endif\n#ifdef SPECULARTERM\nvec3 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);\n#ifdef IRIDESCENCE\nfresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);\n#endif\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\n#ifdef BRDF_V_HEIGHT_CORRELATED\nfloat smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG);\n#else\nfloat smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG);\n#endif\nvec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;}\n#endif\n#ifdef ANISOTROPIC\nvec3 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);\n#ifdef IRIDESCENCE\nfresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);\n#endif\nfloat 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;}\n#endif\n#ifdef CLEARCOAT\nvec4 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(\nclearCoatTerm*info.attenuation*NccdotL*lightColor,\n1.0-fresnel\n);}\nvec3 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;}\n#endif\n#ifdef SHEEN\nvec3 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\nfloat visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG);\n#else */\nfloat visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */\nfloat sheenTerm=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;}\n#endif\n";r.l.IncludesShadersStore.pbrIBLFunctions="#if defined(REFLECTION) || defined(SS_REFRACTION)\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;float lod=log2(microsurfaceAverageSlopeTexels);return lod;}\nfloat getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {float lod=log2(cubeMapDimensionPixels)*roughness;return lod;}\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION)\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {float temp=NdotVUnclamped+ambientOcclusion;return saturate(square(temp)-1.0+ambientOcclusion);}\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION)\nfloat 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);}\n#endif\n#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA)\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {float microsurfaceAverageSlope=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);}\n#endif\n",i(82267),i(29424),i(51068),i(22464);r.l.IncludesShadersStore.pbrBlockAlbedoOpacity="struct albedoOpacityOutParams\n{vec3 surfaceAlbedo;float alpha;};\n#define pbr_inline\nalbedoOpacityOutParams albedoOpacityBlock(\nin vec4 vAlbedoColor\n#ifdef ALBEDO\n,in vec4 albedoTexture\n,in vec2 albedoInfos\n#endif\n#ifdef OPACITY\n,in vec4 opacityMap\n,in vec2 vOpacityInfos\n#endif\n#ifdef DETAIL\n,in vec4 detailColor\n,in vec4 vDetailInfos\n#endif\n#ifdef DECAL\n,in vec4 decalColor\n,in vec4 vDecalInfos\n#endif \n)\n{albedoOpacityOutParams outParams;vec3 surfaceAlbedo=vAlbedoColor.rgb;float alpha=vAlbedoColor.a;\n#ifdef ALBEDO\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\n#ifdef GAMMAALBEDO\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\n#else\nsurfaceAlbedo*=albedoTexture.rgb;\n#endif\nsurfaceAlbedo*=albedoInfos.y;\n#endif\n#ifndef DECAL_AFTER_DETAIL\n#include\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nsurfaceAlbedo*=vColor.rgb;\n#endif\n#ifdef DETAIL\nfloat detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; \n#endif\n#ifdef DECAL_AFTER_DETAIL\n#include\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALBEDO\n#ifdef OPACITY\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST \n#if DEBUGMODE != 88\nif (alpha{"use strict";i.r(t),i.d(t,{pbrVertexShader:()=>o});var r=i(69841);i(81160);r.l.IncludesShadersStore.pbrVertexDeclaration="uniform mat4 view;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif \n#ifdef ALBEDO\nuniform mat4 albedoMatrix;uniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;uniform vec4 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;uniform mat4 reflectivityMatrix;\n#endif\n#ifdef METALLIC_REFLECTANCE\nuniform vec2 vMetallicReflectanceInfos;uniform mat4 metallicReflectanceMatrix;\n#endif\n#ifdef REFLECTANCE\nuniform vec2 vReflectanceInfos;uniform mat4 reflectanceMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;uniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;\n#endif\n#ifdef CLEARCOAT\n#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\n#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\n#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\n#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;uniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix;\n#endif\n#endif\n#ifdef IRIDESCENCE\n#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\n#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix;\n#endif\n#endif\n#ifdef SHEEN\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\n#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\n#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\n#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionInfos;uniform mat4 refractionMatrix;\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix;\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\nuniform vec2 vTranslucencyColorInfos;uniform mat4 translucencyColorMatrix;\n#endif\n#endif\n#ifdef NORMAL\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform 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;\n#else\nuniform 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;\n#endif\n#endif\n#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;uniform mat4 detailMatrix;\n#endif\n#include\n#define ADDITIONAL_VERTEX_DECLARATION\n",i(42413),i(9482),i(40371),i(94388),i(39948),i(66682),i(56865),i(57819),i(2251),i(10316),i(17727),i(18355),i(77735),i(96951),i(19215),i(9158),i(11783),i(25012),i(99216),i(44219),i(18411),i(78792),i(95532),i(85639),i(81448),i(84525),i(78595),i(71471),i(90715),i(2946),i(61374),i(88336);const s="pbrVertexShader",n="precision highp float;\n#include<__decl__pbrVertex>\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#include[2..7]\n#include[1..7]\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\n#include\n#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy)\n#endif\n#ifdef SUBSURFACE\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor)\n#endif\nvarying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include\n#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos);\n#ifdef PREPASS\n#include\n#endif\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector);\n#endif\n#endif\n#define CUSTOM_VERTEX_UPDATE_WORLDPOS\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#if DEBUGMODE>0\nvClipSpacePosition=gl_Position;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n#ifndef UV1\nvec2 uvUpdated=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uvUpdated;\n#endif\n#include[2..7]\n#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z)\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheenRoughness,_INFONAME_,SheenInfos.z)\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x)\n#endif\n#ifdef SUBSURFACE\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x)\n#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_MATRIXNAME_,translucencyColor,_INFONAME_,TranslucencyColorInfos.x)\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},7987:(e,t,i)=>{"use strict";i.r(t),i.d(t,{pickingPixelShader:()=>n});const r="pickingPixelShader",s="#if defined(INSTANCES)\nvarying vec4 vMeshID;\n#else\nuniform vec4 meshID;\n#endif\nvoid main(void) {\n#if defined(INSTANCES)\ngl_FragColor=vMeshID;\n#else\ngl_FragColor=meshID;\n#endif\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},37837:(e,t,i)=>{"use strict";i.r(t),i.d(t,{pickingVertexShader:()=>o});var r=i(69841);i(39948),i(66682),i(9158),i(11783),i(56865),i(99216),i(44219),i(18411),i(78792),i(95532);const s="pickingVertexShader",n="attribute vec3 position;\n#if defined(INSTANCES)\nattribute vec4 instanceMeshID;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform mat4 viewProjection;\n#if defined(INSTANCES)\nvarying vec4 vMeshID;\n#endif\nvoid main(void) {\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;\n#if defined(INSTANCES)\nvMeshID=instanceMeshID;\n#endif\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},18013:(e,t,i)=>{"use strict";i.r(t),i.d(t,{postprocessVertexShader:()=>n});const r="postprocessVertexShader",s="attribute vec2 position;uniform vec2 scale;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=(position*madd+madd)*scale;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},92911:(e,t,i)=>{"use strict";i.r(t),i.d(t,{proceduralVertexShader:()=>n});const r="proceduralVertexShader",s="attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},64849:(e,t,i)=>{"use strict";i.r(t),i.d(t,{rgbdDecodePixelShader:()=>o});var r=i(69841);i(94388);const s="rgbdDecodePixelShader",n="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},32957:(e,t,i)=>{"use strict";i.r(t),i.d(t,{rgbdEncodePixelShader:()=>o});var r=i(69841);i(94388);const s="rgbdEncodePixelShader",n="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},69319:(e,t,i)=>{"use strict";i.r(t),i.d(t,{rsmFullGlobalIlluminationPixelShader:()=>n});const r="rsmFullGlobalIlluminationPixelShader",s="/**\n* The implementation is a direct application of the formula found in http:\n*/\nprecision 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;\n#ifdef TRANSFORM_NORMAL\nuniform mat4 invView;\n#endif\nvec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;int width=int(rsmInfo.x);int height=int(rsmInfo.y);for (int j=0; j{"use strict";i.r(t),i.d(t,{rsmGlobalIlluminationPixelShader:()=>n});const r="rsmGlobalIlluminationPixelShader",s="/**\n* The implementation is an application of the formula found in http:\n* 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).\n*/\nprecision 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;\n#ifdef TRANSFORM_NORMAL\nuniform mat4 invView;\n#endif\nfloat mod289(float x){return x-floor(x*(1.0/289.0))*289.0;}\nvec4 mod289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;}\nvec4 perm(vec4 x){return mod289(((x*34.0)+1.0)*x);}\nfloat 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);}\nvec3 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; \nfloat dist2=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*weightSquare*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}\nreturn clamp(indirectDiffuse*intensity,0.0,1.0);}\nvoid main(void) \n{vec3 positionW=texture2D(textureSampler,vUV).xyz;vec3 normalW=texture2D(normalSampler,vUV).xyz;\n#ifdef DECODE_NORMAL\nnormalW=normalW*2.0-1.0;\n#endif\n#ifdef TRANSFORM_NORMAL\nnormalW=(invView*vec4(normalW,0.)).xyz;\n#endif\ngl_FragColor.rgb=computeIndirect(positionW,normalW);gl_FragColor.a=1.0;}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},87193:(e,t,i)=>{"use strict";i.r(t),i.d(t,{screenSpaceReflection2PixelShader:()=>o});var r=i(69841);i(94388),i(67350),i(8338);const s="screenSpaceReflection2PixelShader",n="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSR_SUPPORTED\nuniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler;\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nuniform sampler2D backDepthSampler;uniform float backSizeFactor;\n#endif\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nuniform samplerCube envCubeSampler;\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize;\n#endif\n#endif\nuniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float farPlaneZ;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;\n#include\n#include\n#include\nvec3 hash(vec3 a)\n{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);}\nfloat computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0;\n#ifdef SSR_ATTENUATE_SCREEN_BORDERS\nvec2 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);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE\nattenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS\nattenuation*=1.0-(numIterations/maxSteps);\n#endif\n#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION\nvec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation;\n#endif\nreturn attenuation;}\n#endif\nvoid main()\n{\n#ifdef SSR_SUPPORTED\nvec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {\n#ifdef SSR_USE_BLUR\ngl_FragColor=vec4(0.);\n#else\ngl_FragColor=colorFull;\n#endif\nreturn;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\nvec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; \n#ifdef SSR_DECODE_NORMAL\ncsNormal=csNormal*2.0-1.0;\n#endif\n#ifdef SSR_NORMAL_IS_IN_WORLDSPACE\ncsNormal=(view*vec4(csNormal,0.0)).xyz;\n#endif\nfloat depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\ndepth=linearizeDepth(depth,nearPlaneZ,farPlaneZ);\n#endif\nvec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);\n#ifdef ORTHOGRAPHIC_CAMERA\nvec3 csViewDirection=vec3(0.,0.,1.);\n#else\nvec3 csViewDirection=normalize(csPosition);\n#endif\nvec3 csReflectedVector=reflect(csViewDirection,csNormal);\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nvec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0));\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nvec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition);\n#endif\n#ifdef SSR_INVERTCUBICMAP\nwReflectedVector.y*=-1.0;\n#endif\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nwReflectedVector.z*=-1.0;\n#endif\nvec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz;\n#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE\nenvColor=toLinearSpace(envColor);\n#endif\n#else\nvec3 envColor=color;\n#endif\nfloat reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations;\n#ifdef SSRAYTRACE_DEBUG\nvec3 debugColor;\n#endif\n#ifdef SSR_ATTENUATE_FACING_CAMERA\nreflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector));\n#endif\nif (reflectionAttenuation>0.0) {\n#ifdef SSR_USE_BLUR\nvec3 jitt=vec3(0.);\n#else\nfloat roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; \n#endif\nvec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); \nrayHasHit=traceScreenSpaceRay1(\ncsPosition,\nnormalize(csReflectedVector+jitt),\nprojectionPixel,\ndepthSampler,\ntexSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nbackDepthSampler,\nbackSizeFactor,\n#endif\nthickness,\nnearPlaneZ,\nfarPlaneZ,\nstepSize,\njitter,\nmaxSteps,\nmaxDistance,\nselfCollisionNumSkip,\nstartPixel,\nhitPixel,\nhitPoint,\nnumIterations\n#ifdef SSRAYTRACE_DEBUG\n,debugColor\n#endif\n);}\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=vec4(debugColor,1.);return;\n#endif\nvec3 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;\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\nreflectedColor=toLinearSpace(reflectedColor);\n#endif\nreflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;}\n#ifndef SSR_BLEND_WITH_FRESNEL\nSSR*=fresnel;\n#endif\n#ifdef SSR_USE_BLUR\nfloat 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; \nfloat 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);}\ngl_FragColor=vec4(SSR,blur_radius/255.0); \n#else\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,colorFull.a);\n#endif\n#else\ngl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0);\n#endif\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},83514:(e,t,i)=>{"use strict";i.r(t),i.d(t,{screenSpaceReflection2BlurPixelShader:()=>n});const r="screenSpaceReflection2BlurPixelShader",s="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform 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)\n{vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;}\nvoid main()\n{vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;}\nfloat blurRadius=colorFull.a*255.0; \nvec2 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);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},36253:(e,t,i)=>{"use strict";i.r(t),i.d(t,{screenSpaceReflection2BlurCombinerPixelShader:()=>o});var r=i(69841);i(94388),i(67350),i(8338);const s="screenSpaceReflection2BlurCombinerPixelShader",n="uniform sampler2D textureSampler; \nuniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV;\n#include\n#ifdef SSR_BLEND_WITH_FRESNEL\n#include\n#include\nuniform mat4 projection;uniform mat4 invProjectionMatrix;uniform sampler2D normalSampler;uniform sampler2D depthSampler;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nuniform float nearPlaneZ;uniform float farPlaneZ;\n#endif\n#endif\nvoid main()\n{\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=texture2D(textureSampler,vUV);\n#else\nvec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\ndepth=linearizeDepth(depth,nearPlaneZ,farPlaneZ);\n#endif\nvec3 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);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,color.a);\n#endif\n}\n";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},42451:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowMapPixelShader:()=>o});var r=i(69841);i(72693);r.l.IncludesShadersStore.bayerDitherFunctions="float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);}\nfloat bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5*mod(_P,4.0)); \nreturn 4.0*bayerDither2(P1)+bayerDither2(P2);}\nfloat bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5 *mod(_P,4.0)); \nvec2 P4=floor(0.25*mod(_P,8.0)); \nreturn 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);}\n";r.l.IncludesShadersStore.shadowMapFragmentExtraDeclaration="#if SM_FLOAT==0\n#include\n#endif\n#if SM_SOFTTRANSPARENTSHADOW==1\n#include\nuniform vec2 softTransparentShadowSM;\n#endif\nvarying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nuniform vec3 lightDataSM;varying vec3 vPositionWSM;\n#endif\nuniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n",i(77165),i(89797),i(73391);const s="shadowMapPixelShader",n="#include\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEXTURE\nvec4 opacityMap=texture2D(diffuseSampler,vUV);float alphaFromAlphaTexture=opacityMap.a;\n#if SM_SOFTTRANSPARENTSHADOW==1\nif (softTransparentShadowSM.y==1.0) {opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alphaFromAlphaTexture=opacityMap.x+opacityMap.y+opacityMap.z;}\n#endif\n#ifdef ALPHATESTVALUE\nif (alphaFromAlphaTexture=softTransparentShadowSM.x*alphaFromAlphaTexture) discard;\n#else\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM.x) discard;\n#endif\n#endif\n#include\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},32166:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowMapVertexShader:()=>o});var r=i(69841);i(39948),i(66682),i(9158),i(11783),i(94388);r.l.IncludesShadersStore.sceneVertexDeclaration="uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\nuniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition;\n";r.l.IncludesShadersStore.meshVertexDeclaration="uniform mat4 world;uniform float visibility;\n";r.l.IncludesShadersStore.shadowMapVertexDeclaration="#include\n#include\n",i(32405),i(13580);r.l.IncludesShadersStore.shadowMapUboDeclaration="layout(std140,column_major) uniform;\n#include\n#include\n";r.l.IncludesShadersStore.shadowMapVertexExtraDeclaration="#if SM_NORMALBIAS==1\nuniform vec3 lightDataSM;\n#endif\nuniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nvarying vec3 vPositionWSM;\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n",i(18355),i(99216),i(44219),i(18411),i(78792),i(95532);r.l.IncludesShadersStore.shadowMapVertexNormalBias="#if SM_NORMALBIAS==1\n#if SM_DIRECTIONINLIGHTDATA==1\nvec3 worldLightDirSM=normalize(-lightDataSM.xyz);\n#else\nvec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM);\n#endif\nfloat ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM;\n#endif\n",i(94949),i(71471);const s="shadowMapVertexShader",n="attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef INSTANCES\nattribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;\n#endif\n#include\n#include<__decl__shadowMapVertex>\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef NORMAL\nmat3 normWorldSM=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvec3 vNormalW=normalize(normWorldSM*normalUpdated);\n#endif\n#endif\n#include\ngl_Position=viewProjection*worldPos;\n#include\n#ifdef ALPHATEXTURE\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},3367:(e,t,i)=>{"use strict";i.r(t),i.d(t,{sharpenPixelShader:()=>n});const r="sharpenPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},3916:(e,t,i)=>{"use strict";i.r(t),i.d(t,{spritesPixelShader:()=>o});var r=i(69841);i(64657),i(25012),i(6922),i(27185),i(65343);const s="spritesPixelShader",n="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler;\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#ifdef PIXEL_PERFECT\nvec2 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;}\n#endif\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#ifdef PIXEL_PERFECT\nvec2 uv=uvPixelPerfect(vUV);\n#else\nvec2 uv=vUV;\n#endif\nvec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.)\n{if (color.a<0.95)\ndiscard;}\ncolor*=vColor;\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},3290:(e,t,i)=>{"use strict";i.r(t),i.d(t,{spritesVertexShader:()=>o});var r=i(69841);i(77735),i(25012),i(88336);const s="spritesVertexShader",n="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;\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 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); \nvColor=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;\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStore[s]=n;const o={name:s,shader:n}},33258:(e,t,i)=>{"use strict";i.r(t),i.d(t,{ssao2PixelShader:()=>n});const r="ssao2PixelShader",s="precision highp float;uniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSAO\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);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()\n{vec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;float depth=textureLod(depthSampler,vUV,0.0).r;float depthSign=sign(depth);depth=depth*depthSign;vec3 normal=textureLod(normalSampler,vUV,0.0).rgb;float occlusion=0.0;float correctedRadius=min(radius,minZAspect*depth/near);vec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);vec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);vec3 origin=vViewRay*vDepthFactor;vec3 rvec=random*2.0-1.0;rvec.z=0.0;float dotProduct=dot(rvec,normal);rvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i1.0 || offset.y>1.0) {continue;}\nfloat 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;}\nocclusion=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);}\n#endif\n#ifdef BLUR\nuniform float outSize;uniform float soften;uniform float tolerance;uniform int samples;\n#ifndef BLUR_BYPASS\nuniform sampler2D depthSampler;\n#ifdef BLUR_LEGACY\n#define inline\nfloat 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;}\n#endif\n#endif\nvoid main()\n{float result=0.0;\n#ifdef BLUR_BYPASS\nresult=textureLod(textureSampler,vUV,0.0).r;\n#else\n#ifdef BLUR_H\nvec2 step=vec2(1.0/outSize,0.0);\n#else\nvec2 step=vec2(0.0,1.0/outSize);\n#endif\n#ifdef BLUR_LEGACY\nresult=blur13Bilateral(textureSampler,vUV,step);\n#else\nfloat compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; i{"use strict";i.r(t),i.d(t,{ssaoCombinePixelShader:()=>n});const r="ssaoCombinePixelShader",s="uniform sampler2D textureSampler;uniform sampler2D originalColor;uniform vec4 viewport;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);vec4 sceneColor=texture2D(originalColor,vUV);gl_FragColor=sceneColor*ssaoColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},7672:(e,t,i)=>{"use strict";i.r(t),i.d(t,{taaPixelShader:()=>n});const r="taaPixelShader",s="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);}\n";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},47088:(e,t,i)=>{"use strict";i.r(t),i.d(t,{tonemapPixelShader:()=>n});const r="tonemapPixelShader",s="varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst 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;\n#endif\nfloat Luminance(vec3 c)\n{return dot(c,vec3(0.22,0.707,0.071));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_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;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_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;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},44341:(e,t,i)=>{"use strict";i.r(t),i.d(t,{vrDistortionCorrectionPixelShader:()=>n});const r="vrDistortionCorrectionPixelShader",s="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; \nfloat 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;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}";i(69841).l.ShadersStore[r]=s;const n={name:r,shader:s}},50128:(e,t,i)=>{"use strict";var r=i(69841);i(14910);r.l.IncludesShadersStoreWGSL.backgroundUboDeclaration="uniform vPrimaryColor: vec4f;uniform vPrimaryColorShadow: vec4f;uniform vDiffuseInfos: vec2f;uniform vReflectionInfos: vec2f;uniform diffuseMatrix: mat4x4f;uniform reflectionMatrix: mat4x4f;uniform vReflectionMicrosurfaceInfos: vec3f;uniform fFovMultiplier: f32;uniform pointSize: f32;uniform shadowLevel: f32;uniform alpha: f32;uniform vBackgroundCenter: vec3f;uniform vReflectionControl: vec4f;uniform projectedGroundInfos: vec2f;\n#include\n"},71281:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.bakedVertexAnimation="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\n#ifdef INSTANCES\nlet VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w;\n#else\nlet VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;\n#endif\nlet 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];\n#if NUM_BONE_INFLUENCERS>1\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3];\n#endif\nfinalWorld=finalWorld*VATInfluence;}\n#endif\n"},68273:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.bakedVertexAnimationDeclaration="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d;\n#ifdef INSTANCES\nattribute bakedVertexAnimationSettingsInstanced : vec4;\n#endif\nfn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4\n{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);}\n#endif\n"},25589:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bonesDeclarationWGSL:()=>n});const r="bonesDeclaration",s="#if NUM_BONE_INFLUENCERS>0\nattribute matricesIndices : vec4;attribute matricesWeights : vec4;\n#if NUM_BONE_INFLUENCERS>4\nattribute matricesIndicesExtra : vec4;attribute matricesWeightsExtra : vec4;\n#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nvar boneSampler : texture_2d;uniform boneTextureWidth : f32;\n#else\nuniform mBones : array;\n#ifdef BONES_VELOCITY_ENABLED\nuniform mPreviousBones : array;\n#endif\n#endif\n#ifdef BONETEXTURE\nfn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4\n{let offset=i32(index) *4; \nlet 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);}\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},40903:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bonesVertexWGSL:()=>n});const r="bonesVertex",s="#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nvar influence : mat4x4;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3];\n#endif \n#else \ninfluence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];\n#endif \n#endif\nfinalWorld=finalWorld*influence;\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},99312:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bumpFragmentWGSL:()=>n});const r="bumpFragment",s="var uvOffset: vec2f= vec2f(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL)\n#ifdef NORMALXYSCALE\nvar normalScale: f32=1.0;\n#elif defined(BUMP)\nvar normalScale: f32=uniforms.vBumpInfos.y;\n#else\nvar normalScale: f32=1.0;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nvar TBN: mat3x3f=mat3x3(input.vTBN0,input.vTBN1,input.vTBN2); \n#elif defined(BUMP)\nvar TBNUV: vec2f=select(-fragmentInputs.vBumpUV,fragmentInputs.vBumpUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,input.vPositionW,TBNUV,uniforms.vTangentSpaceParams);\n#else\nvar TBNUV: vec2f=select(-fragmentInputs.vDetailUV,fragmentInputs.vDetailUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,input.vPositionW,TBNUV, vec2f(1.,1.));\n#endif\n#elif defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nvar TBN: mat3x3f=mat3x3(input.vTBN0,input.vTBN1,input.vTBN2); \n#else\nvar TBNUV: vec2f=select( -fragmentInputs.vMainUV1,fragmentInputs.vMainUV1,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW,input.vPositionW,TBNUV, vec2f(1.,1.));\n#endif\n#endif\n#ifdef PARALLAX\nvar invTBN: mat3x3f=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,fragmentInputs.vBumpUV,uniforms.vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,uniforms.vBumpInfos.z);\n#endif\n#endif\n#ifdef DETAIL\nvar detailColor: vec4f=textureSample(detailSampler,detailSamplerSampler,fragmentInputs.vDetailUV+uvOffset);var detailNormalRG: vec2f=detailColor.wy*2.0-1.0;var detailNormalB: f32=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));var detailNormal: vec3f= vec3f(detailNormalRG,detailNormalB);\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\n#define CUSTOM_FRAGMENT_BUMP_FRAGMENT\nnormalW=normalize(textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3x3f(uniforms.normalMatrix[0].xyz,uniforms.normalMatrix[1].xyz,uniforms.normalMatrix[2].xyz)*normalW);\n#elif !defined(DETAIL)\nnormalW=perturbNormal(TBN,textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV+uvOffset).xyz,uniforms.vBumpInfos.y);\n#else\nvar bumpNormal: vec3f=textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV+uvOffset).xyz*2.0-1.0;\n#if DETAIL_NORMALBLENDMETHOD==0 \ndetailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);var blendedNormal: vec3f=normalize( vec3f(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z));\n#elif DETAIL_NORMALBLENDMETHOD==1 \ndetailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);bumpNormal+= vec3f(0.0,0.0,1.0);detailNormal*= vec3f(-1.0,-1.0,1.0);var blendedNormal: vec3f=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal;\n#endif\nnormalW=perturbNormalBase(TBN,blendedNormal,uniforms.vBumpInfos.y);\n#endif\n#elif defined(DETAIL)\ndetailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);normalW=perturbNormalBase(TBN,detailNormal,uniforms.vDetailInfos.z);\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},87087:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bumpFragmentFunctionsWGSL:()=>o});var r=i(69841);i(59224);const s="bumpFragmentFunctions",n="#if defined(BUMP)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)\n#endif\n#if defined(DETAIL)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail)\n#endif\n#if defined(BUMP) && defined(PARALLAX)\nconst minSamples: f32=4.;const maxSamples: f32=15.;const iMaxSamples: i32=15;fn parallaxOcclusion(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32)->vec2f {var parallaxLimit: f32=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;var vOffsetDir: vec2f=normalize(vViewDirCoT.xy);var vMaxOffset: vec2f=vOffsetDir*parallaxLimit;var numSamples: f32=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));var stepSize: f32=1.0/numSamples;var currRayHeight: f32=1.0;var vCurrOffset: vec2f= vec2f(0,0);var vLastOffset: vec2f= vec2f(0,0);var lastSampledHeight: f32=1.0;var currSampledHeight: f32=1.0;var keepWorking: bool=true;for (var i: i32=0; icurrRayHeight)\n{var delta1: f32=currSampledHeight-currRayHeight;var delta2: f32=(currRayHeight+stepSize)-lastSampledHeight;var ratio: f32=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;}\nelse\n{currRayHeight-=stepSize;vLastOffset=vCurrOffset;\n#ifdef PARALLAX_RHS\nvCurrOffset-=stepSize*vMaxOffset;\n#else\nvCurrOffset+=stepSize*vMaxOffset;\n#endif\nlastSampledHeight=currSampledHeight;}}\nreturn vCurrOffset;}\nfn parallaxOffset(viewDir: vec3f,heightScale: f32)->vec2f\n{var height: f32=textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV).w;var texCoordOffset: vec2f=heightScale*viewDir.xy*height;\n#ifdef PARALLAX_RHS\nreturn texCoordOffset;\n#else\nreturn -texCoordOffset;\n#endif\n}\n#endif\n";r.l.IncludesShadersStoreWGSL[s]=n;const o={name:s,shader:n}},56332:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bumpFragmentMainFunctionsWGSL:()=>n});const r="bumpFragmentMainFunctions",s="#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL)\n#if defined(TANGENT) && defined(NORMAL) \nvarying vTBN0: vec3f;varying vTBN1: vec3f;varying vTBN2: vec3f;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform normalMatrix: mat4x4f;fn toNormalMatrix(m: mat4x4f)->mat4x4f\n{var a00=m[0][0];var a01=m[0][1];var a02=m[0][2];var a03=m[0][3];var a10=m[1][0];var a11=m[1][1];var a12=m[1][2];var a13=m[1][3];var a20=m[2][0]; \nvar a21=m[2][1];var a22=m[2][2];var a23=m[2][3];var a30=m[3][0]; \nvar a31=m[3][1];var a32=m[3][2];var a33=m[3][3];var b00=a00*a11-a01*a10;var b01=a00*a12-a02*a10;var b02=a00*a13-a03*a10;var b03=a01*a12-a02*a11;var b04=a01*a13-a03*a11;var b05=a02*a13-a03*a12;var b06=a20*a31-a21*a30;var b07=a20*a32-a22*a30;var b08=a20*a33-a23*a30;var b09=a21*a32-a22*a31;var b10=a21*a33-a23*a31;var b11=a22*a33-a23*a32;var det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;var mi=mat4x4(\n(a11*b11-a12*b10+a13*b09)/det,\n(a02*b10-a01*b11-a03*b09)/det,\n(a31*b05-a32*b04+a33*b03)/det,\n(a22*b04-a21*b05-a23*b03)/det,\n(a12*b08-a10*b11-a13*b07)/det,\n(a00*b11-a02*b08+a03*b07)/det,\n(a32*b02-a30*b05-a33*b01)/det,\n(a20*b05-a22*b02+a23*b01)/det,\n(a10*b10-a11*b08+a13*b06)/det,\n(a01*b08-a00*b10-a03*b06)/det,\n(a30*b04-a31*b02+a33*b00)/det,\n(a21*b02-a20*b04-a23*b00)/det,\n(a11*b07-a10*b09-a12*b06)/det,\n(a00*b09-a01*b07+a02*b06)/det,\n(a31*b01-a30*b03-a32*b00)/det,\n(a20*b03-a21*b01+a22*b00)/det);return mat4x4(mi[0][0],mi[1][0],mi[2][0],mi[3][0],\nmi[0][1],mi[1][1],mi[2][1],mi[3][1],\nmi[0][2],mi[1][2],mi[2][2],mi[3][2],\nmi[0][3],mi[1][3],mi[2][3],mi[3][3]);}\n#endif\nfn perturbNormalBase(cotangentFrame: mat3x3f,normal: vec3f,scale: f32)->vec3f\n{var output=normal;\n#ifdef NORMALXYSCALE\noutput=normalize(output* vec3f(scale,scale,1.0));\n#endif\nreturn normalize(cotangentFrame*output);}\nfn perturbNormal(cotangentFrame: mat3x3f,textureSample: vec3f,scale: f32)->vec3f\n{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);}\nfn cotangent_frame(normal: vec3f,p: vec3f,uv: vec2f,tangentSpaceParams: vec2f)->mat3x3f\n{var dp1: vec3f=dpdx(p);var dp2: vec3f=dpdy(p);var duv1: vec2f=dpdx(uv);var duv2: vec2f=dpdy(uv);var dp2perp: vec3f=cross(dp2,normal);var dp1perp: vec3f=cross(normal,dp1);var tangent: vec3f=dp2perp*duv1.x+dp1perp*duv2.x;var bitangent: vec3f=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;var det: f32=max(dot(tangent,tangent),dot(bitangent,bitangent));var invmax: f32=select(inverseSqrt(det),0.0,det==0.0);return mat3x3f(tangent*invmax,bitangent*invmax,normal);}\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},73918:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.bumpVertex="#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nvar tbnNormal: vec3f=normalize(normalUpdated);var tbnTangent: vec3f=normalize(tangentUpdated.xyz);var tbnBitangent: vec3f=cross(tbnNormal,tbnTangent)*tangentUpdated.w;var matTemp= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz)* mat3x3f(tbnTangent,tbnBitangent,tbnNormal);vertexOutputs.vTBN0=matTemp[0];vertexOutputs.vTBN1=matTemp[1];vertexOutputs.vTBN2=matTemp[2];\n#endif\n#endif\n"},96760:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.bumpVertexDeclaration="#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL) \nvarying vTBN0: vec3f;varying vTBN1: vec3f;varying vTBN2: vec3f;\n#endif\n#endif\n"},76794:(e,t,i)=>{"use strict";i.r(t),i.d(t,{clipPlaneFragmentWGSL:()=>n});const r="clipPlaneFragment",s="#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nif (false) {}\n#endif\n#ifdef CLIPPLANE\nelse if (fragmentInputs.fClipDistance>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE2\nelse if (fragmentInputs.fClipDistance2>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE3\nelse if (fragmentInputs.fClipDistance3>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE4\nelse if (fragmentInputs.fClipDistance4>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE5\nelse if (fragmentInputs.fClipDistance5>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE6\nelse if (fragmentInputs.fClipDistance6>0.0)\n{discard;}\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},96140:(e,t,i)=>{"use strict";i.r(t),i.d(t,{clipPlaneFragmentDeclarationWGSL:()=>n});const r="clipPlaneFragmentDeclaration",s="#ifdef CLIPPLANE\nvarying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nvarying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nvarying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nvarying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nvarying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nvarying fClipDistance6: f32;\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},57728:(e,t,i)=>{"use strict";i.r(t),i.d(t,{clipPlaneVertexWGSL:()=>n});const r="clipPlaneVertex",s="#ifdef CLIPPLANE\nvertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nvertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nvertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nvertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4);\n#endif\n#ifdef CLIPPLANE5\nvertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5);\n#endif\n#ifdef CLIPPLANE6\nvertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6);\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},30486:(e,t,i)=>{"use strict";i.r(t),i.d(t,{clipPlaneVertexDeclarationWGSL:()=>n});const r="clipPlaneVertexDeclaration",s="#ifdef CLIPPLANE\nuniform vClipPlane: vec4;varying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nuniform vClipPlane2: vec4;varying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nuniform vClipPlane3: vec4;varying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nuniform vClipPlane4: vec4;varying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nuniform vClipPlane5: vec4;varying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nuniform vClipPlane6: vec4;varying fClipDistance6: f32;\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},17327:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.decalFragment="#ifdef DECAL\nvar decalTempColor=decalColor.rgb;var decalTempAlpha=decalColor.a;\n#ifdef GAMMADECAL\ndecalTempColor=toLinearSpaceVec3(decalColor.rgb);\n#endif\n#ifdef DECAL_SMOOTHALPHA\ndecalTempAlpha=decalColor.a*decalColor.a;\n#endif\nsurfaceAlbedo=mix(surfaceAlbedo.rgb,decalTempColor,decalTempAlpha);\n#endif\n"},59051:(e,t,i)=>{"use strict";var r=i(69841);i(14910),i(10598);r.l.IncludesShadersStoreWGSL.defaultUboDeclaration="uniform diffuseLeftColor: vec4f;uniform diffuseRightColor: vec4f;uniform opacityParts: vec4f;uniform reflectionLeftColor: vec4f;uniform reflectionRightColor: vec4f;uniform refractionLeftColor: vec4f;uniform refractionRightColor: vec4f;uniform emissiveLeftColor: vec4f;uniform emissiveRightColor: vec4f;uniform vDiffuseInfos: vec2f;uniform vAmbientInfos: vec2f;uniform vOpacityInfos: vec2f;uniform vReflectionInfos: vec2f;uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f;uniform vEmissiveInfos: vec2f;uniform vLightmapInfos: vec2f;uniform vSpecularInfos: vec2f;uniform vBumpInfos: vec3f;uniform diffuseMatrix: mat4x4f;uniform ambientMatrix: mat4x4f;uniform opacityMatrix: mat4x4f;uniform reflectionMatrix: mat4x4f;uniform emissiveMatrix: mat4x4f;uniform lightmapMatrix: mat4x4f;uniform specularMatrix: mat4x4f;uniform bumpMatrix: mat4x4f;uniform vTangentSpaceParams: vec2f;uniform pointSize: f32;uniform alphaCutOff: f32;uniform refractionMatrix: mat4x4f;uniform vRefractionInfos: vec4f;uniform vRefractionPosition: vec3f;uniform vRefractionSize: vec3f;uniform vSpecularColor: vec4f;uniform vEmissiveColor: vec3f;uniform vDiffuseColor: vec4f;uniform vAmbientColor: vec3f;\n#define ADDITIONAL_UBO_DECLARATION\n#include\n#include\n"},81859:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.depthPrePass="#ifdef DEPTHPREPASS\nfragmentOutputs.color= vec4f(0.,0.,0.,1.0);return fragmentOutputs;\n#endif\n"},31034:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.fogFragment="#ifdef FOG\nvar fog: f32=CalcFogFactor();\n#ifdef PBR\nfog=toLinearSpace(fog);\n#endif\ncolor= vec4f(mix(uniforms.vFogColor,color.rgb,fog),color.a);\n#endif\n"},10668:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fogFragmentDeclarationWGSL:()=>n});const r="fogFragmentDeclaration",s="#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\nconst E=2.71828;uniform vFogInfos: vec4f;uniform vFogColor: vec3f;varying vFogDistance: vec3f;fn CalcFogFactor()->f32\n{var fogCoeff: f32=1.0;var fogStart: f32=uniforms.vFogInfos.y;var fogEnd: f32=uniforms.vFogInfos.z;var fogDensity: f32=uniforms.vFogInfos.w;var fogDistance: f32=length(fragmentInputs.vFogDistance);if (FOGMODE_LINEAR==uniforms.vFogInfos.x)\n{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);}\nelse if (FOGMODE_EXP==uniforms.vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDensity);}\nelse if (FOGMODE_EXP2==uniforms.vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);}\nreturn clamp(fogCoeff,0.0,1.0);}\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},45184:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.fogVertex="#ifdef FOG\nvertexOutputs.vFogDistance=(scene.view*worldPos).xyz;\n#endif\n"},86934:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.fogVertexDeclaration="#ifdef FOG\nvarying vFogDistance: vec3f;\n#endif\n"},27493:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.fresnelFunction="#ifdef FRESNEL\nfn computeFresnelTerm(viewDirection: vec3f,worldNormal: vec3f,bias: f32,power: f32)->f32\n{let fresnelTerm: f32=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);}\n#endif\n"},36437:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.harmonicsFunctions="#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nfn computeEnvironmentIrradiance(normal: vec3f)->vec3f {return uniforms.vSphericalL00\n+ uniforms.vSphericalL1_1*(normal.y)\n+ uniforms.vSphericalL10*(normal.z)\n+ uniforms.vSphericalL11*(normal.x)\n+ uniforms.vSphericalL2_2*(normal.y*normal.x)\n+ uniforms.vSphericalL2_1*(normal.y*normal.z)\n+ uniforms.vSphericalL20*((3.0*normal.z*normal.z)-1.0)\n+ uniforms.vSphericalL21*(normal.z*normal.x)\n+ uniforms.vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));}\n#else\nfn computeEnvironmentIrradiance(normal: vec3f)->vec3f {var Nx: f32=normal.x;var Ny: f32=normal.y;var Nz: f32=normal.z;var C1: vec3f=uniforms.vSphericalZZ.rgb;var Cx: vec3f=uniforms.vSphericalX.rgb;var Cy: vec3f=uniforms.vSphericalY.rgb;var Cz: vec3f=uniforms.vSphericalZ.rgb;var Cxx_zz: vec3f=uniforms.vSphericalXX_ZZ.rgb;var Cyy_zz: vec3f=uniforms.vSphericalYY_ZZ.rgb;var Cxy: vec3f=uniforms.vSphericalXY.rgb;var Cyz: vec3f=uniforms.vSphericalYZ.rgb;var Czx: vec3f=uniforms.vSphericalZX.rgb;var a1: vec3f=Cyy_zz*Ny+Cy;var a2: vec3f=Cyz*Nz+a1;var b1: vec3f=Czx*Nz+Cx;var b2: vec3f=Cxy*Ny+b1;var b3: vec3f=Cxx_zz*Nx+b2;var t1: vec3f=Cz *Nz+C1;var t2: vec3f=a2 *Ny+t1;var t3: vec3f=b3 *Nx+t2;return t3;}\n#endif\n#endif\n"},49335:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.hdrFilteringFunctions="#ifdef NUM_SAMPLES\n#if NUM_SAMPLES>0\nfn radicalInverse_VdC(value: u32)->f32 \n{var bits=(value<<16u) | (value>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return f32(bits)*2.3283064365386963e-10; }\nfn hammersley(i: u32,N: u32)->vec2f\n{return vec2f( f32(i)/ f32(N),radicalInverse_VdC(i));}\nfn log4(x: f32)->f32 {return log2(x)/2.;}\nconst NUM_SAMPLES_FLOAT: f32= f32(NUM_SAMPLES);const NUM_SAMPLES_FLOAT_INVERSED: f32=1./NUM_SAMPLES_FLOAT;const K: f32=4.;fn irradiance(inputTexture: texture_cube,inputSampler: sampler,inputN: vec3f,filteringInfo: vec2f)->vec3f\n{var n: vec3f=normalize(inputN);var result: vec3f= vec3f(0.0);var tangent: vec3f=select(vec3f(1.,0.,0.),vec3f(0.,0.,1.),abs(n.z)<0.999);tangent=normalize(cross(tangent,n));var bitangent: vec3f=cross(n,tangent);var tbn: mat3x3f= mat3x3f(tangent,bitangent,n);var maxLevel: f32=filteringInfo.y;var dim0: f32=filteringInfo.x;var omegaP: f32=(4.*PI)/(6.*dim0*dim0);for(var i: u32=0u; i0.) {var pdf_inversed: f32=PI/NoL;var omegaS: f32=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;var l: f32=log4(omegaS)-log4(omegaP)+log4(K);var mipLevel: f32=clamp(l,0.0,maxLevel);var c: vec3f=textureSampleLevel(inputTexture,inputSampler,tbn*Ls,mipLevel).rgb;\n#ifdef GAMMA_INPUT\nc=toLinearSpaceVec3(c);\n#endif\nresult+=c;}}\nresult=result*NUM_SAMPLES_FLOAT_INVERSED;return result;}\nfn radiance(alphaG: f32,inputTexture: texture_cube,inputSampler: sampler,inputN: vec3f,filteringInfo: vec2f)->vec3f\n{var n: vec3f=normalize(inputN);var c: vec3f=textureSample(inputTexture,inputSampler,n).rgb; \nif (alphaG==0.) {\n#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\n#endif\nreturn c;} else {var result: vec3f= vec3f(0.);var tangent: vec3f=select(vec3f(1.,0.,0.),vec3f(0.,0.,1.),abs(n.z)<0.999);tangent=normalize(cross(tangent,n));var bitangent: vec3f=cross(n,tangent);var tbn: mat3x3f= mat3x3f(tangent,bitangent,n);var maxLevel: f32=filteringInfo.y;var dim0: f32=filteringInfo.x;var omegaP: f32=(4.*PI)/(6.*dim0*dim0);var weight: f32=0.;for(var i: u32=0u; i0.) {var pdf_inversed: f32=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);var omegaS: f32=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;var l: f32=log4(omegaS)-log4(omegaP)+log4(K);var mipLevel: f32=clamp( f32(l),0.0,maxLevel);weight+=NoL;var c: vec3f=textureSampleLevel(inputTexture,inputSampler,tbn*L,mipLevel).rgb;\n#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\n#endif\nresult+=c*NoL;}}\nresult=result/weight;return result;}}\n#endif\n#endif\n"},87647:(e,t,i)=>{"use strict";i.r(t),i.d(t,{helperFunctionsWGSL:()=>n});const r="helperFunctions",s="const PI: f32=3.1415926535897932384626433832795;const RECIPROCAL_PI: f32=0.3183098861837907;const RECIPROCAL_PI2: f32=0.15915494309189535;const HALF_MIN: f32=5.96046448e-08; \nconst LinearEncodePowerApprox: f32=2.2;const GammaEncodePowerApprox: f32=1.0/LinearEncodePowerApprox;const LuminanceEncodeApprox: vec3=vec3 (0.2126,0.7152,0.0722);const Epsilon:f32=0.0000001;fn square(x: f32)->f32 {return x*x;}\nfn saturate(x: f32)->f32 {return clamp(x,0.0,1.0);}\nfn saturateVec3(x: vec3f)->vec3f {return clamp(x,vec3f(0.0),vec3f(1.0));}\nfn saturateEps(x: f32)->f32 {return clamp(x,Epsilon,1.0);} \nfn maxEps(x: f32)->f32 {return max(x,Epsilon);}\nfn maxEpsVec3(x: vec3f)->vec3f {return max(x,vec3f(Epsilon));}\nfn absEps(x: f32)->f32 {return abs(x)+Epsilon;}\nfn transposeMat3(inMatrix: mat3x3f)->mat3x3f {let i0: vec3=inMatrix[0];let i1: vec3=inMatrix[1];let i2: vec3=inMatrix[2];let outMatrix:mat3x3f=mat3x3f(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);return outMatrix;}\nfn 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,\nb11/det,(a22*a00-a02*a20)/det,(-a12*a00+a02*a10)/det,\nb21/det,(-a21*a00+a01*a20)/det,(a11*a00-a01*a10)/det);}\n#if USE_EXACT_SRGB_CONVERSIONS\nfn toLinearSpaceExact(color: vec3)->vec3\n{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)));}\nfn toGammaSpaceExact(color: vec3)->vec3\n{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)));}\n#endif\nfn toLinearSpace(color: f32)->f32\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nvar nearZeroSection=0.0773993808*color;var remainingSection=pow(0.947867299*(color+0.055),2.4);return select(remainingSection,nearZeroSection,color<=0.04045);\n#else\nreturn pow(color,LinearEncodePowerApprox);\n#endif\n}\nfn toLinearSpaceVec3(color: vec3)->vec3\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3(LinearEncodePowerApprox));\n#endif\n}\nfn toLinearSpaceVec4(color: vec4)->vec4\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4f(toLinearSpaceExact(color.rgb),color.a);\n#else\nreturn vec4f(pow(color.rgb,vec3f(LinearEncodePowerApprox)),color.a);\n#endif\n}\nfn toGammaSpace(color: vec4)->vec4\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toGammaSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);\n#endif\n}\nfn toGammaSpaceVec3(color: vec3)->vec3\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3(GammaEncodePowerApprox));\n#endif\n}\nfn squareVec3(value: vec3)->vec3\n{return value*value;}\nfn pow5(value: f32)->f32 {let sq: f32=value*value;return sq*sq*value;}\nfn getLuminance(color: vec3)->f32\n{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}\nfn getRand(seed: vec2)->f32 {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}\nfn 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;}\nconst 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); }\nfn fromRGBD(rgbd: vec4)->vec3 {let rgb=toLinearSpaceVec3(rgbd.rgb);return rgb/rgbd.a;}\nfn 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;}\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},33882:(e,t,i)=>{"use strict";i.r(t),i.d(t,{imageProcessingDeclarationWGSL:()=>n});const r="imageProcessingDeclaration",s="#ifdef EXPOSURE\nuniform exposureLinear: f32;\n#endif\n#ifdef CONTRAST\nuniform contrast: f32;\n#endif\n#if defined(VIGNETTE) || defined(DITHER)\nuniform vInverseScreenSize: vec2f;\n#endif\n#ifdef VIGNETTE\nuniform vignetteSettings1: vec4f;uniform vignetteSettings2: vec4f;\n#endif\n#ifdef COLORCURVES\nuniform vCameraColorCurveNegative: vec4f;uniform vCameraColorCurveNeutral: vec4f;uniform vCameraColorCurvePositive: vec4f;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nvar txColorTransformSampler: sampler;var txColorTransform: texture_3d;\n#else\nvar txColorTransformSampler: sampler;var txColorTransform: texture_2d;\n#endif\nuniform colorTransformSettings: vec4f;\n#endif\n#ifdef DITHER\nuniform ditherIntensity: f32;\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},33731:(e,t,i)=>{"use strict";i.r(t),i.d(t,{imageProcessingFunctionsWGSL:()=>n});const r="imageProcessingFunctions",s="#if TONEMAPPING==3\nconst PBRNeutralStartCompression: f32=0.8-0.04;const PBRNeutralDesaturation: f32=0.15;fn PBRNeutralToneMapping( color: vec3f )->vec3f {var x: f32=min(color.r,min(color.g,color.b));var offset: f32=select(0.04,x-6.25*x*x,x<0.08);var result=color;result-=offset;var peak: f32=max(result.r,max(result.g,result.b));if (peakvec3f\n{var a: vec3f=v*(v+0.0245786)-0.000090537;var b: vec3f=v*(0.983729*v+0.4329510)+0.238081;return a/b;}\nfn ACESFitted(color: vec3f)->vec3f\n{var output=ACESInputMat*color;output=RRTAndODTFit(output);output=ACESOutputMat*output;output=saturateVec3(output);return output;}\n#endif\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_DEFINITIONS\nfn applyImageProcessing(result: vec4f)->vec4f {\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATSTART\nvar rgb=result.rgb;;\n#ifdef EXPOSURE\nrgb*=uniforms.exposureLinear;\n#endif\n#ifdef VIGNETTE\nvar viewportXY: vec2f=fragmentInputs.position.xy*uniforms.vInverseScreenSize;viewportXY=viewportXY*2.0-1.0;var vignetteXY1: vec3f= vec3f(viewportXY*uniforms.vignetteSettings1.xy+uniforms.vignetteSettings1.zw,1.0);var vignetteTerm: f32=dot(vignetteXY1,vignetteXY1);var vignette: f32=pow(vignetteTerm,uniforms.vignetteSettings2.w);var vignetteColor: vec3f=uniforms.vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvar vignetteColorMultiplier: vec3f=mix(vignetteColor, vec3f(1,1,1),vignette);rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nrgb=mix(vignetteColor,rgb,vignette);\n#endif\n#endif\n#if TONEMAPPING==3\nrgb=PBRNeutralToneMapping(rgb);\n#elif TONEMAPPING==2\nrgb=ACESFitted(rgb);\n#elif TONEMAPPING==1\nconst tonemappingCalibration: f32=1.590579;rgb=1.0-exp2(-tonemappingCalibration*rgb);\n#endif\nrgb=toGammaSpaceVec3(rgb);rgb=saturateVec3(rgb);\n#ifdef CONTRAST\nvar resultHighContrast: vec3f=rgb*rgb*(3.0-2.0*rgb);if (uniforms.contrast<1.0) {rgb=mix( vec3f(0.5,0.5,0.5),rgb,uniforms.contrast);} else {rgb=mix(rgb,resultHighContrast,uniforms.contrast-1.0);}\n#endif\n#ifdef COLORGRADING\nvar colorTransformInput: vec3f=rgb*uniforms.colorTransformSettings.xxx+uniforms.colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvar colorTransformOutput: vec3f=textureSample(txColorTransform,txColorTransformSampler,colorTransformInput).rgb;\n#else\nvar colorTransformOutput: vec3f=textureSample(txColorTransform,txColorTransformSampler,colorTransformInput,uniforms.colorTransformSettings.yz).rgb;\n#endif\nrgb=mix(rgb,colorTransformOutput,uniforms.colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\nvar luma: f32=getLuminance(rgb);var curveMix: vec2f=clamp( vec2f(luma*3.0-1.5,luma*-3.0+1.5), vec2f(0.0), vec2f(1.0));var colorCurve: vec4f=uniforms.vCameraColorCurveNeutral+curveMix.x*uniforms.vCameraColorCurvePositive-curveMix.y*uniforms.vCameraColorCurveNegative;rgb*=colorCurve.rgb;rgb=mix( vec3f(luma),rgb,colorCurve.a);\n#endif\n#ifdef DITHER\nvar rand: f32=getRand(fragmentInputs.position.xy*uniforms.vInverseScreenSize);var dither: f32=mix(-uniforms.ditherIntensity,uniforms.ditherIntensity,rand);rgb=saturateVec3(rgb+ vec3f(dither));\n#endif\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND\nreturn vec4f(rgb,result.a);}";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},60755:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.importanceSampling="fn hemisphereCosSample(u: vec2f)->vec3f {var phi: f32=2.*PI*u.x;var cosTheta2: f32=1.-u.y;var cosTheta: f32=sqrt(cosTheta2);var sinTheta: f32=sqrt(1.-cosTheta2);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}\nfn hemisphereImportanceSampleDggx(u: vec2f,a: f32)->vec3f {var phi: f32=2.*PI*u.x;var cosTheta2: f32=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));var cosTheta: f32=sqrt(cosTheta2);var sinTheta: f32=sqrt(1.-cosTheta2);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}\nfn hemisphereImportanceSampleDCharlie(u: vec2f,a: f32)->vec3f { \nvar phi: f32=2.*PI*u.x;var sinTheta: f32=pow(u.y,a/(2.*a+1.));var cosTheta: f32=sqrt(1.-sinTheta*sinTheta);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}"},41416:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.instancesDeclaration="#ifdef INSTANCES\nattribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4;\n#ifdef INSTANCESCOLOR\nattribute instanceColor : vec4;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nattribute previousWorld0 : vec4;attribute previousWorld1 : vec4;attribute previousWorld2 : vec4;attribute previousWorld3 : vec4;\n#ifdef THIN_INSTANCES\nuniform previousWorld : mat4x4;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nuniform previousWorld : mat4x4;\n#endif\n#endif\n"},32764:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.instancesVertex="#ifdef INSTANCES\nvar finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nvar finalPreviousWorld=mat4x4(\nvertexInputs.previousWorld0,vertexInputs.previousWorld1,\nvertexInputs.previousWorld2,vertexInputs.previousWorld3);\n#endif\n#ifdef THIN_INSTANCES\n#if !defined(WORLD_UBO)\nfinalWorld=uniforms.world*finalWorld;\n#else\nfinalWorld=mesh.world*finalWorld;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nfinalPreviousWorld=uniforms.previousWorld*finalPreviousWorld;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nvar finalWorld=uniforms.world;\n#else\nvar finalWorld=mesh.world;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)\nvar finalPreviousWorld=uniforms.previousWorld;\n#endif\n#endif\n"},57932:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.kernelBlurVaryingDeclaration="varying sampleCoord{X}: vec2f;"},55090:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lightFragmentWGSL:()=>n});const r="lightFragment",s="#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n#else\nvar diffuse{X}: vec4f=light{X}.vLightDiffuse;\n#define CUSTOM_LIGHT{X}_COLOR \n#ifdef PBR\n#ifdef SPOTLIGHT{X}\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,fragmentInputs.vPositionW);\n#elif defined(POINTLIGHT{X})\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,fragmentInputs.vPositionW);\n#elif defined(HEMILIGHT{X})\npreInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(DIRLIGHT{X})\npreInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#endif\npreInfo.NdotV=NdotV;\n#ifdef SPOTLIGHT{X}\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.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);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.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);\n#else\npreInfo.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);\n#endif\n#elif defined(POINTLIGHT{X})\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\n#else\npreInfo.attenuation=1.0;\n#endif\n#ifdef HEMILIGHT{X}\npreInfo.roughness=roughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#ifdef IRIDESCENCE\npreInfo.iridescenceIntensity=iridescenceIntensity;\n#endif\n#ifdef HEMILIGHT{X}\ninfo.diffuse=computeHemisphericDiffuseLighting(preInfo,diffuse{X}.rgb,light{X}.vLightGround);\n#elif defined(SS_TRANSLUCENCY)\ninfo.diffuse=computeDiffuseAndTransmittedLighting(preInfo,diffuse{X}.rgb,subSurfaceOut.transmittance);\n#else\ninfo.diffuse=computeDiffuseLighting(preInfo,diffuse{X}.rgb);\n#endif\n#ifdef SPECULARTERM\n#ifdef ANISOTROPIC\ninfo.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb);\n#else\ninfo.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb);\n#endif\n#endif\n#ifdef SHEEN\n#ifdef SHEEN_LINKWITHALBEDO\npreInfo.roughness=sheenOut.sheenIntensity;\n#else\n#ifdef HEMILIGHT{X}\npreInfo.roughness=sheenOut.sheenRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#endif\ninfo.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb);\n#endif\n#ifdef CLEARCOAT\n#ifdef HEMILIGHT{X}\npreInfo.roughness=clearcoatOut.clearCoatRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\ninfo.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,diffuse{X}.rgb);\n#ifdef CLEARCOAT_TINT\nabsorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption;\n#ifdef SPECULARTERM\ninfo.specular*=absorption;\n#endif\n#endif\ninfo.diffuse*=info.clearCoat.w;\n#ifdef SPECULARTERM\ninfo.specular*=info.clearCoat.w;\n#endif\n#ifdef SHEEN\ninfo.sheen*=info.clearCoat.w;\n#endif\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightTexture{X},projectionLightTexture{X}Sampler,uniforms.textureProjectionMatrix{X},fragmentInputs.vPositionW);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSMDEBUG{X}\nvar shadowDebug{X}: vec3f;\n#endif\n#ifdef SHADOWCSM{X}\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nvar index{X}: i32=-1;\n#else\nvar index{X}: i32=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nvar diff{X}: f32=0.;vPositionFromLight{X}[0]=fragmentInputs.vPositionFromLight{X}_0;vPositionFromLight{X}[1]=fragmentInputs.vPositionFromLight{X}_1;vPositionFromLight{X}[2]=fragmentInputs.vPositionFromLight{X}_2;vPositionFromLight{X}[3]=fragmentInputs.vPositionFromLight{X}_3;vDepthMetric{X}[0]=fragmentInputs.vDepthMetric{X}_0;vDepthMetric{X}[1]=fragmentInputs.vDepthMetric{X}_1;vDepthMetric{X}[2]=fragmentInputs.vDepthMetric{X}_2;vDepthMetric{X}[3]=fragmentInputs.vDepthMetric{X}_3;for (var i:i32=0; i=0.) {index{X}=i;break;}}\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nif (index{X}>=0)\n#endif\n{\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#else\nshadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#endif\n#else\nshadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=vec3f(shadow)*vCascadeColorsMultiplier{X}[index{X}];\n#endif\n#ifndef SHADOWCSMNOBLEND{X}\nvar frustumLength:f32=uniforms.frustumLengths{X}[index{X}];var diffRatio:f32=clamp(diff{X}/frustumLength,0.,1.)*uniforms.cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)\n{index{X}+=1;var nextShadow: f32=0.;\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],,shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nnextShadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#else\nnextShadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#endif\n#else\nnextShadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\nshadow=mix(nextShadow,shadow,diffRatio);\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);\n#endif\n}\n#endif\n}\n#elif defined(SHADOWCLOSEESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(fragmentInputs.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(fragmentInputs.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(fragmentInputs.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(fragmentInputs.vPositionW,light{X}.vLightData.xyz,shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;shadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\naggShadow+=shadow;numLights+=1.0;\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor.rgb*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef CLEARCOAT\n#ifndef LIGHTMAPNOSPECULAR{X}\nclearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef SHEEN\n#ifndef LIGHTMAPNOSPECULAR{X}\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#else\n#ifdef SHADOWCSMDEBUG{X}\ndiffuseBase+=info.diffuse*shadowDebug{X};\n#else \ndiffuseBase+=info.diffuse*shadow;\n#endif\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#ifdef CLEARCOAT\nclearCoatBase+=info.clearCoat.rgb*shadow;\n#endif\n#ifdef SHEEN\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},71426:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lightUboDeclarationWGSL:()=>n});const r="lightUboDeclaration",s="#ifdef LIGHT{X}\nstruct Light{X}\n{vLightData: vec4f,\nvLightDiffuse: vec4f,\nvLightSpecular: vec4f,\n#ifdef SPOTLIGHT{X}\nvLightDirection: vec4f,\nvLightFalloff: vec4f,\n#elif defined(POINTLIGHT{X})\nvLightFalloff: vec4f,\n#elif defined(HEMILIGHT{X})\nvLightGround: vec3f,\n#endif\nshadowsInfo: vec4f,\ndepthValues: vec2f} ;var light{X} : Light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform textureProjectionMatrix{X}: mat4x4f;var projectionLightTexture{X}Sampler: sampler;var projectionLightTexture{X}: texture_2d;\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform lightMatrix{X}: array;uniform viewFrustumZ{X}: array;uniform frustumLengths{X}: array;uniform cascadeBlendFactor{X}: f32;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f;var vPositionFromLight{X}: array;var vDepthMetric{X} : array;\n#if defined(SHADOWPCSS{X})\nvar shadowTexture{X}Sampler: sampler_comparison; \nvar shadowTexture{X}: texture_depth_2d_array;var depthTexture{X}Sampler: sampler;var depthTexture{X}: texture_2d_array;uniform lightSizeUVCorrection{X}: array;uniform depthCorrection{X}: array;uniform penumbraDarkness{X}: f32;\n#elif defined(SHADOWPCF{X})\nvar shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d_array;\n#else \nvar shadowTexture{X}Sampler: sampler; \nvar shadowTexture{X}: texture_2d_array;\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vCascadeColorsMultiplier{X}: array=array\n(\nvec3f ( 1.5,0.0,0.0 ),\nvec3f ( 0.0,1.5,0.0 ),\nvec3f ( 0.0,0.0,5.5 ),\nvec3f ( 1.5,0.0,5.5 ),\nvec3f ( 1.5,1.5,0.0 ),\nvec3f ( 1.0,1.0,1.0 ),\nvec3f ( 0.0,1.0,5.5 ),\nvec3f ( 0.5,3.5,0.75 )\n);\n#endif\n#elif defined(SHADOWCUBE{X})\nvar shadowTexture{X}Sampler: sampler;var shadowTexture{X}: texture_cube;\n#else\nvarying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;\n#if defined(SHADOWPCSS{X})\nvar shadowTexture{X}Sampler: sampler_comparison; \nvar shadowTexture{X}: texture_depth_2d;var depthTexture{X}Sampler: sampler; \nvar depthTexture{X}: texture_2d;\n#elif defined(SHADOWPCF{X})\nvar shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d;\n#else\nvar shadowTexture{X}Sampler: sampler; \nvar shadowTexture{X}: texture_2d;\n#endif\nuniform lightMatrix{X}: mat4x4f;\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},85188:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lightVxUboDeclarationWGSL:()=>n});const r="lightVxUboDeclaration",s="#ifdef LIGHT{X}\nstruct Light{X}\n{vLightData: vec4f,\nvLightDiffuse: vec4f,\nvLightSpecular: vec4f,\n#ifdef SPOTLIGHT{X}\nvLightDirection: vec4f,\nvLightFalloff: vec4f,\n#elif defined(POINTLIGHT{X})\nvLightFalloff: vec4f,\n#elif defined(HEMILIGHT{X})\nvLightGround: vec3f,\n#endif\nshadowsInfo: vec4f,\ndepthValues: vec2f} ;var light{X} : Light{X};\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform lightMatrix{X}: array;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f;\n#elif defined(SHADOWCUBE{X})\n#else\nvarying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;uniform lightMatrix{X}: mat4x4f;\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},34992:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lightsFragmentFunctionsWGSL:()=>n});const r="lightsFragmentFunctions",s="struct lightingInfo\n{diffuse: vec3f,\n#ifdef SPECULARTERM\nspecular: vec3f,\n#endif\n#ifdef NDOTL\nndl: f32,\n#endif\n};fn computeLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var result: lightingInfo;var lightVectorW: vec3f;var attenuation: f32=1.0;if (lightData.w==0.)\n{var direction: vec3f=lightData.xyz-fragmentInputs.vPositionW;var attenuation: f32=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}\nelse\n{lightVectorW=normalize(-lightData.xyz);}\nvar ndl: f32=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvar angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nfn computeSpotLighting(viewDirectionW: vec3f,vNormal: vec3f ,lightData: vec4f,lightDirection: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var result: lightingInfo;var direction: vec3f=lightData.xyz-fragmentInputs.vPositionW;var lightVectorW: vec3f=normalize(direction);var attenuation: f32=max(0.,1.0-length(direction)/range);var cosAngle: f32=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w)\n{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;var ndl: f32=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvar angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nresult.diffuse=vec3f(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3f(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;}\nfn computeHemisphericLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,groundColor: vec3f,glossiness: f32)->lightingInfo {var result: lightingInfo;var ndl: f32=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\nvar angleW: vec3f=normalize(viewDirectionW+lightData.xyz);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;\n#endif\nreturn result;}\nfn computeProjectionTextureDiffuseLighting(projectionLightTexture: texture_2d,projectionLightSampler: sampler,textureProjectionMatrix: mat4x4f,posW: vec3f)->vec3f {var strq: vec4f=textureProjectionMatrix*vec4f(posW,1.0);strq/=strq.w;var textureColor: vec3f=textureSample(projectionLightTexture,projectionLightSampler,strq.xy).rgb;return textureColor;}";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},21859:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.logDepthDeclaration="#ifdef LOGARITHMICDEPTH\nuniform logarithmicDepthConstant: f32;varying vFragmentDepth: f32;\n#endif\n"},85551:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.logDepthFragment="#ifdef LOGARITHMICDEPTH\nfragmentOutputs.fragDepth=log2(fragmentInputs.vFragmentDepth)*uniforms.logarithmicDepthConstant*0.5;\n#endif\n"},18201:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.logDepthVertex="#ifdef LOGARITHMICDEPTH\nvertexOutputs.vFragmentDepth=1.0+vertexOutputs.position.w;vertexOutputs.position.z=log2(max(0.000001,vertexOutputs.vFragmentDepth))*uniforms.logarithmicDepthConstant;\n#endif\n"},36174:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.mainUVVaryingDeclaration="#ifdef MAINUV{X}\nvarying vMainUV{X}: vec2f;\n#endif\n"},10598:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.meshUboDeclaration="struct Mesh {world : mat4x4,\nvisibility : f32,};var mesh : Mesh;\n#define WORLD_UBO\n"},43610:(e,t,i)=>{"use strict";i.r(t),i.d(t,{morphTargetsVertexWGSL:()=>n});const r="morphTargetsVertex",s="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\n#if {X}==0\nfor (var i=0; i=uniforms.morphTargetCount) {break;}\nvertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler(i,vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[i];vertexID=vertexID+1.0;\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated=normalUpdated+(readVector3FromRawSampler(i,vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[i];vertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(readVector3FromRawSampler(i,vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[i];vertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated=vec4f(tangentUpdated.xyz+(readVector3FromRawSampler(i,vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[i],tangentUpdated.a);\n#endif\n}\n#endif\n#else\npositionUpdated=positionUpdated+(vertexInputs.position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(vertexInputs.normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated=vec4f(tangentUpdated.xyz+(vertexInputs.tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}],tangentUpdated.a);\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(vertexInputs.uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},51148:(e,t,i)=>{"use strict";i.r(t),i.d(t,{morphTargetsVertexDeclarationWGSL:()=>n});const r="morphTargetsVertexDeclaration",s="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute position{X} : vec3;\n#ifdef MORPHTARGETS_NORMAL\nattribute normal{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute tangent{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_UV\nattribute uv_{X} : vec2;\n#endif\n#elif {X}==0\nuniform morphTargetCount: i32;\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},8573:(e,t,i)=>{"use strict";i.r(t),i.d(t,{morphTargetsVertexGlobalWGSL:()=>n});const r="morphTargetsVertexGlobal",s="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nvar vertexID : f32;\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},47381:(e,t,i)=>{"use strict";i.r(t),i.d(t,{morphTargetsVertexGlobalDeclarationWGSL:()=>n});const r="morphTargetsVertexGlobalDeclaration",s="#ifdef MORPHTARGETS\nuniform morphTargetInfluences : array;\n#ifdef MORPHTARGETS_TEXTURE \nuniform morphTargetTextureIndices : array;uniform morphTargetTextureInfo : vec3;var morphTargets : texture_2d_array;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3\n{ \nlet 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;}\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},73048:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.oitDeclaration="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\n#define MAX_DEPTH 99999.0\nvar oitDepthSamplerSampler: sampler;var oitDepthSampler: texture_2d;var oitFrontColorSamplerSampler: sampler;var oitFrontColorSampler: texture_2d;\n#endif\n"},63270:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.oitFragment="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\nvar fragDepth: f32=fragmentInputs.position.z; \n#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS\nvar halfFloat: i32=packHalf2x16( vec2f(fragDepth));var full: vec2f=unpackHalf2x16(halfFloat);fragDepth=full.x;\n#endif\nvar fragCoord: vec2i=vec2i(fragmentInputs.position.xy);var lastDepth: vec2f=textureLoad(oitDepthSampler,fragCoord,0).rg;var lastFrontColor: vec4f=textureLoad(oitFrontColorSampler,fragCoord,0);fragmentOutputs.depth=vec2f(-MAX_DEPTH);fragmentOutputs.frontColor=lastFrontColor;fragmentOutputs.backColor= vec4f(0.0);\n#ifdef USE_REVERSE_DEPTHBUFFER\nvar furthestDepth: f32=-lastDepth.x;var nearestDepth: f32=lastDepth.y;\n#else\nvar nearestDepth: f32=-lastDepth.x;var furthestDepth: f32=lastDepth.y;\n#endif\nvar alphaMultiplier: f32=1.0-lastFrontColor.a;\n#ifdef USE_REVERSE_DEPTHBUFFER\nif (fragDepth>nearestDepth || fragDepthfurthestDepth) {\n#endif\nreturn fragmentOutputs;}\n#ifdef USE_REVERSE_DEPTHBUFFER\nif (fragDepthfurthestDepth) {\n#else\nif (fragDepth>nearestDepth && fragDepth{"use strict";i.r(t),i.d(t,{packingFunctionsWGSL:()=>n});const r="packingFunctions",s="fn pack(depth: f32)->vec4f\n{const bit_shift: vec4f= vec4f(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const bit_mask: vec4f= vec4f(0.0,1.0/255.0,1.0/255.0,1.0/255.0);var res: vec4f=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}\nfn unpack(color: vec4f)->f32\n{const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},20427:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.pbrBRDFFunctions="#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nfn getEnergyConservationFactor(specularEnvironmentR0: vec3f,environmentBrdf: vec3f)->vec3f {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);}\n#endif\n#ifdef ENVIRONMENTBRDF\nfn getBRDFLookup(NdotV: f32,perceptualRoughness: f32)->vec3f {var UV: vec2f= vec2f(NdotV,perceptualRoughness);var brdfLookup: vec4f= textureSample(environmentBrdfSampler,environmentBrdfSamplerSampler,UV);\n#ifdef ENVIRONMENTBRDF_RGBD\nbrdfLookup=vec4f(fromRGBD(brdfLookup.rgba),brdfLookup.a);\n#endif\nreturn brdfLookup.rgb;}\nfn getReflectanceFromBRDFWithEnvLookup(specularEnvironmentR0: vec3f,specularEnvironmentR90: vec3f,environmentBrdf: vec3f)->vec3f {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvar reflectance: vec3f=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y;\n#else\nvar reflectance: vec3f=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y;\n#endif\nreturn reflectance;}\nfn getReflectanceFromBRDFLookup(specularEnvironmentR0: vec3f,environmentBrdf: vec3f)->vec3f {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvar reflectance: vec3f=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);\n#else\nvar reflectance: vec3f=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#endif\nreturn reflectance;}\n#endif\n/* NOT USED\n#if defined(SHEEN) && defined(SHEEN_SOFTER)\nfn getBRDFLookupCharlieSheen(NdotV: f32,perceptualRoughness: f32)->f32\n{var c: f32=1.0-NdotV;var c3: f32=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));}\n#endif\n*/\n#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)\nfn getReflectanceFromAnalyticalBRDFLookup_Jones(VdotN: f32,reflectance0: vec3f,reflectance90: vec3f,smoothness: f32)->vec3f\n{var weight: f32=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF)\n/**\n* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture.\n* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table\n*/\nfn getSheenReflectanceFromBRDFLookup(reflectance0: vec3f,environmentBrdf: vec3f)->vec3f {var sheenEnvironmentReflectance: vec3f=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;}\n#endif\nfn fresnelSchlickGGXVec3(VdotH: f32,reflectance0: vec3f,reflectance90: vec3f)->vec3f\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\nfn fresnelSchlickGGX(VdotH: f32,reflectance0: f32,reflectance90: f32)->f32\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\n#ifdef CLEARCOAT\nfn getR0RemappedForClearCoat(f0: vec3f)->vec3f {\n#ifdef CLEARCOAT_DEFAULTIOR\n#ifdef MOBILE\nreturn saturateVec3(f0*(f0*0.526868+0.529324)-0.0482256);\n#else\nreturn saturateVec3(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);\n#endif\n#else\nvar s: vec3f=sqrt(f0);var t: vec3f=(uniforms.vClearCoatRefractionParams.z+uniforms.vClearCoatRefractionParams.w*s)/(uniforms.vClearCoatRefractionParams.w+uniforms.vClearCoatRefractionParams.z*s);return squareVec3(t);\n#endif\n}\n#endif\n#ifdef IRIDESCENCE\nconst XYZ_TO_REC709: mat3x3f= mat3x3f(\n3.2404542,-0.9692660, 0.0556434,\n-1.5371385, 1.8760108,-0.2040259,\n-0.4985314, 0.0415560, 1.0572252\n);fn getIORTfromAirToSurfaceR0(f0: vec3f)->vec3f {var sqrtF0: vec3f=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);}\nfn getR0fromIORsVec3(iorT: vec3f,iorI: f32)->vec3f {return squareVec3((iorT- vec3f(iorI))/(iorT+ vec3f(iorI)));}\nfn getR0fromIORs(iorT: f32,iorI: f32)->f32 {return square((iorT-iorI)/(iorT+iorI));}\nfn evalSensitivity(opd: f32,shift: vec3f)->vec3f {var phase: f32=2.0*PI*opd*1.0e-9;const val: vec3f= vec3f(5.4856e-13,4.4201e-13,5.2481e-13);const pos: vec3f= vec3f(1.6810e+06,1.7953e+06,2.2084e+06);const vr: vec3f= vec3f(4.3278e+09,9.3046e+09,6.6121e+09);var xyz: vec3f=val*sqrt(2.0*PI*vr)*cos(pos*phase+shift)*exp(-square(phase)*vr);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;var srgb: vec3f=XYZ_TO_REC709*xyz;return srgb;}\nfn evalIridescence(outsideIOR: f32,eta2: f32,cosTheta1: f32,thinFilmThickness: f32,baseF0: vec3f)->vec3f {var I: vec3f= vec3f(1.0);var iridescenceIOR: f32=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));var sinTheta2Sq: f32=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));var cosTheta2Sq: f32=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;}\nvar cosTheta2: f32=sqrt(cosTheta2Sq);var R0: f32=getR0fromIORs(iridescenceIOR,outsideIOR);var R12: f32=fresnelSchlickGGX(cosTheta1,R0,1.);var R21: f32=R12;var T121: f32=1.0-R12;var phi12: f32=0.0;if (iridescenceIORf32\n{var a2: f32=alphaG*alphaG;var d: f32=NdotH*NdotH*(a2-1.0)+1.0;return a2/(PI*d*d);}\n#ifdef SHEEN\nfn normalDistributionFunction_CharlieSheen(NdotH: f32,alphaG: f32)->f32\n{var invR: f32=1./alphaG;var cos2h: f32=NdotH*NdotH;var sin2h: f32=1.-cos2h;return (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);}\n#endif\n#ifdef ANISOTROPIC\nfn normalDistributionFunction_BurleyGGX_Anisotropic(NdotH: f32,TdotH: f32,BdotH: f32,alphaTB: vec2f)->f32 {var a2: f32=alphaTB.x*alphaTB.y;var v: vec3f= vec3f(alphaTB.y*TdotH,alphaTB.x *BdotH,a2*NdotH);var v2: f32=dot(v,v);var w2: f32=a2/v2;return a2*w2*w2*RECIPROCAL_PI;}\n#endif\n#ifdef BRDF_V_HEIGHT_CORRELATED\nfn smithVisibility_GGXCorrelated(NdotL: f32,NdotV: f32,alphaG: f32)->f32 {\n#ifdef MOBILE\nvar GGXV: f32=NdotL*(NdotV*(1.0-alphaG)+alphaG);var GGXL: f32=NdotV*(NdotL*(1.0-alphaG)+alphaG);return 0.5/(GGXV+GGXL);\n#else\nvar a2: f32=alphaG*alphaG;var GGXV: f32=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);var GGXL: f32=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);return 0.5/(GGXV+GGXL);\n#endif\n}\n#else\nfn smithVisibilityG1_TrowbridgeReitzGGXFast(dot: f32,alphaG: f32)->f32\n{\n#ifdef MOBILE\nreturn 1.0/(dot+alphaG+(1.0-alphaG)*dot ));\n#else\nvar alphaSquared: f32=alphaG*alphaG;return 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot));\n#endif\n}\nfn smithVisibility_TrowbridgeReitzGGXFast(NdotL: f32,NdotV: f32,alphaG: f32)->f32\n{var visibility: f32=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);return visibility;}\n#endif\n#ifdef ANISOTROPIC\nfn smithVisibility_GGXCorrelated_Anisotropic(NdotL: f32,NdotV: f32,TdotV: f32,BdotV: f32,TdotL: f32,BdotL: f32,alphaTB: vec2f)->f32 {var lambdaV: f32=NdotL*length( vec3f(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));var lambdaL: f32=NdotV*length( vec3f(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));var v: f32=0.5/(lambdaV+lambdaL);return v;}\n#endif\n#ifdef CLEARCOAT\nfn visibility_Kelemen(VdotH: f32)->f32 {return 0.25/(VdotH*VdotH); }\n#endif\n#ifdef SHEEN\nfn visibility_Ashikhmin(NdotL: f32,NdotV: f32)->f32\n{return 1./(4.*(NdotL+NdotV-NdotL*NdotV));}\n/* NOT USED\n#ifdef SHEEN_SOFTER\nfn l(x: f32,alphaG: f32)->f32\n{var oneMinusAlphaSq: f32=(1.0-alphaG)*(1.0-alphaG);var a: f32=mix(21.5473,25.3245,oneMinusAlphaSq);var b: f32=mix(3.82987,3.32435,oneMinusAlphaSq);var c: f32=mix(0.19823,0.16801,oneMinusAlphaSq);var d: f32=mix(-1.97760,-1.27393,oneMinusAlphaSq);var e: f32=mix(-4.32054,-4.85967,oneMinusAlphaSq);return a/(1.0+b*pow(x,c))+d*x+e;}\nfn lambdaSheen(cosTheta: f32,alphaG: f32)->f32\n{return abs(cosTheta)<0.5 ? exp(l(cosTheta,alphaG)) : exp(2.0*l(0.5,alphaG)-l(1.0-cosTheta,alphaG));}\nfn visibility_CharlieSheen(NdotL: f32,NdotV: f32,alphaG: f32)->f32\n{var G: f32=1.0/(1.0+lambdaSheen(NdotV,alphaG)+lambdaSheen(NdotL,alphaG));return G/(4.0*NdotV*NdotL);}\n#endif\n*/\n#endif\nfn diffuseBRDF_Burley(NdotL: f32,NdotV: f32,VdotH: f32,roughness: f32)->f32 {var diffuseFresnelNV: f32=pow5(saturateEps(1.0-NdotL));var diffuseFresnelNL: f32=pow5(saturateEps(1.0-NdotV));var diffuseFresnel90: f32=0.5+2.0*VdotH*VdotH*roughness;var fresnel: f32 =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);return fresnel/PI;}\n#ifdef SS_TRANSLUCENCY\nfn transmittanceBRDF_Burley(tintColor: vec3f,diffusionDistance: vec3f,thickness: f32)->vec3f {var S: vec3f=1./maxEpsVec3(diffusionDistance);var temp: vec3f=exp((-0.333333333*thickness)*S);return tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);}\nfn computeWrappedDiffuseNdotL(NdotL: f32,w: f32)->f32 {var t: f32=1.0+w;var invt2: f32=1.0/(t*t);return saturate((NdotL+w)*invt2);}\n#endif\n"},53894:(e,t,i)=>{"use strict";var r=i(69841);i(14910),i(10598);r.l.IncludesShadersStoreWGSL.pbrUboDeclaration="uniform vAlbedoInfos: vec2f;uniform vAmbientInfos: vec4f;uniform vOpacityInfos: vec2f;uniform vEmissiveInfos: vec2f;uniform vLightmapInfos: vec2f;uniform vReflectivityInfos: vec3f;uniform vMicroSurfaceSamplerInfos: vec2f;uniform vReflectionInfos: vec2f;uniform vReflectionFilteringInfo: vec2f;uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f;uniform vBumpInfos: vec3f;uniform albedoMatrix: mat4x4f;uniform ambientMatrix: mat4x4f;uniform opacityMatrix: mat4x4f;uniform emissiveMatrix: mat4x4f;uniform lightmapMatrix: mat4x4f;uniform reflectivityMatrix: mat4x4f;uniform microSurfaceSamplerMatrix: mat4x4f;uniform bumpMatrix: mat4x4f;uniform vTangentSpaceParams: vec2f;uniform reflectionMatrix: mat4x4f;uniform vReflectionColor: vec3f;uniform vAlbedoColor: vec4f;uniform vLightingIntensity: vec4f;uniform vReflectionMicrosurfaceInfos: vec3f;uniform pointSize: f32;uniform vReflectivityColor: vec4f;uniform vEmissiveColor: vec3f;uniform vAmbientColor: vec3f;uniform vDebugMode: vec2f;uniform vMetallicReflectanceFactors: vec4f;uniform vMetallicReflectanceInfos: vec2f;uniform metallicReflectanceMatrix: mat4x4f;uniform vReflectanceInfos: vec2f;uniform reflectanceMatrix: mat4x4f;uniform vSphericalL00: vec3f;uniform vSphericalL1_1: vec3f;uniform vSphericalL10: vec3f;uniform vSphericalL11: vec3f;uniform vSphericalL2_2: vec3f;uniform vSphericalL2_1: vec3f;uniform vSphericalL20: vec3f;uniform vSphericalL21: vec3f;uniform vSphericalL22: vec3f;uniform vSphericalX: vec3f;uniform vSphericalY: vec3f;uniform vSphericalZ: vec3f;uniform vSphericalXX_ZZ: vec3f;uniform vSphericalYY_ZZ: vec3f;uniform vSphericalZZ: vec3f;uniform vSphericalXY: vec3f;uniform vSphericalYZ: vec3f;uniform vSphericalZX: vec3f;\n#define ADDITIONAL_UBO_DECLARATION\n#include\n#include\n"},85620:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.prePassDeclaration="#ifdef PREPASS\n#ifdef PREPASS_LOCAL_POSITION\nvarying vPosition : vec3f;\n#endif\n#ifdef PREPASS_DEPTH\nvarying vViewPos: vec3f;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)\nvarying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f;\n#endif\n#endif\n"},51152:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.prePassVertex="#ifdef PREPASS_DEPTH\nvertexOutputs.vViewPos=(scene.view*worldPos).rgb;\n#endif\n#ifdef PREPASS_LOCAL_POSITION\nvertexOutputs.vPosition=positionUpdated.xyz;\n#endif\n#if (defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED)\nvertexOutputs.vCurrentPosition=scene.viewProjection*worldPos;\n#if NUM_BONE_INFLUENCERS>0\nvar previousInfluence: mat4x4f;previousInfluence=mPreviousBones[ i32(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[ i32(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[ i32(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[ i32(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*previousInfluence* vec4f(positionUpdated,1.0);\n#else\nvertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0);\n#endif\n#endif\n"},17894:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.prePassVertexDeclaration="#ifdef PREPASS\n#ifdef PREPASS_LOCAL_POSITION\nvarying vPosition : vec3f;\n#endif\n#ifdef PREPASS_DEPTH\nvarying vViewPos: vec3f;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)\nuniform previousViewProjection: mat4x4f;varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f;\n#endif\n#endif\n"},7769:(e,t,i)=>{"use strict";i.r(t),i.d(t,{reflectionFunctionWGSL:()=>n});const r="reflectionFunction",s="fn computeFixedEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,direction: vec3f)->vec3f\n{var lon: f32=atan2(direction.z,direction.x);var lat: f32=acos(direction.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(s,t,0); }\nfn computeMirroredFixedEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,direction: vec3f)->vec3f\n{var lon: f32=atan2(direction.z,direction.x);var lat: f32=acos(direction.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(1.0-s,t,0); }\nfn computeEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f\n{var cameraToVertex: vec3f=normalize(worldPos.xyz-eyePosition);var r: vec3f=normalize(reflect(cameraToVertex,worldNormal));r= (reflectionMatrix* vec4f(r,0)).xyz;var lon: f32=atan2(r.z,r.x);var lat: f32=acos(r.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(s,t,0);}\nfn computeSphericalCoords(worldPos: vec4f,worldNormal: vec3f,view: mat4x4f,reflectionMatrix: mat4x4f)->vec3f\n{var viewDir: vec3f=normalize((view*worldPos).xyz);var viewNormal: vec3f=normalize((view* vec4f(worldNormal,0.0)).xyz);var r: vec3f=reflect(viewDir,viewNormal);r= (reflectionMatrix* vec4f(r,0)).xyz;r.z=r.z-1.0;var m: f32=2.0*length(r);return vec3f(r.x/m+0.5,1.0-r.y/m-0.5,0);}\nfn computePlanarCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f\n{var viewDir: vec3f=worldPos.xyz-eyePosition;var coords: vec3f=normalize(reflect(viewDir,worldNormal));return (reflectionMatrix* vec4f(coords,1)).xyz;}\nfn computeCubicCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f\n{var viewDir: vec3f=normalize(worldPos.xyz-eyePosition);var coords: vec3f=reflect(viewDir,worldNormal);coords= (reflectionMatrix* vec4f(coords,0)).xyz;\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;}\nfn computeCubicLocalCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f,reflectionSize: vec3f,reflectionPosition: vec3f)->vec3f\n{var viewDir: vec3f=normalize(worldPos.xyz-eyePosition);var coords: vec3f=reflect(viewDir,worldNormal);coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);coords=(reflectionMatrix* vec4f(coords,0)).xyz;\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;}\nfn computeProjectionCoords(worldPos: vec4f,view: mat4x4f,reflectionMatrix: mat4x4f)->vec3f\n{return (reflectionMatrix*(view*worldPos)).xyz;}\nfn computeSkyBoxCoords(positionW: vec3f,reflectionMatrix: mat4x4f)->vec3f\n{return (reflectionMatrix* vec4f(positionW,1.)).xyz;}\n#ifdef REFLECTION\nfn computeReflectionCoords(worldPos: vec4f,worldNormal: vec3f)->vec3f\n{\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nvar direction: vec3f=normalize(fragmentInputs.vDirectionW);return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvar direction: vec3f=normalize(fragmentInputs.vDirectionW);return computeFixedEquirectangularCoords(worldPos,worldNormal,direction);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nreturn computeEquirectangularCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nreturn computeSphericalCoords(worldPos,worldNormal,scene.view,uniforms.reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nreturn computePlanarCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_CUBIC\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nreturn computeCubicLocalCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix,uniforms.vReflectionSize,uniforms.vReflectionPosition);\n#else\nreturn computeCubicCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix);\n#endif\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn computeProjectionCoords(worldPos,scene.view,uniforms.reflectionMatrix);\n#endif\n#ifndef REFLECTIONMAP_CUBIC\n#ifdef REFLECTIONMAP_SKYBOX\nreturn computeSkyBoxCoords(fragmentInputs.vPositionUVW,uniforms.reflectionMatrix);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3f(0,0,0);\n#endif\n}\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},59224:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.samplerFragmentDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying v_VARYINGNAME_UV: vec2f;\n#endif\nvar _SAMPLERNAME_SamplerSampler: sampler;var _SAMPLERNAME_Sampler: texture_2d;\n#endif\n"},30642:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.samplerVertexDeclaration="#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0\nvarying v_VARYINGNAME_UV: vec2f;\n#endif\n"},84326:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.samplerVertexImplementation="#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0\nif (uniforms.v_INFONAME_==0.)\n{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(uvUpdated,1.0,0.0)).xy;}\n#ifdef UV2\nelse if (uniforms.v_INFONAME_==1.)\n{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv2,1.0,0.0)).xy;}\n#endif\n#ifdef UV3\nelse if (uniforms.v_INFONAME_==2.)\n{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv3,1.0,0.0)).xy;}\n#endif\n#ifdef UV4\nelse if (uniforms.v_INFONAME_==3.)\n{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv4,1.0,0.0)).xy;}\n#endif\n#ifdef UV5\nelse if (uniforms.v_INFONAME_==4.)\n{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv5,1.0,0.0)).xy;}\n#endif\n#ifdef UV6\nelse if (uniforms.v_INFONAME_==5.)\n{vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv6,1.0,0.0)).xy;}\n#endif\n#endif\n"},14910:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.sceneUboDeclaration="struct Scene {viewProjection : mat4x4,\n#ifdef MULTIVIEW\nviewProjectionR : mat4x4,\n#endif \nview : mat4x4,\nprojection : mat4x4,\nvEyePosition : vec4,};var scene : Scene;\n"},46357:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.screenSpaceRayTrace="fn distanceSquared(a: vec2f,b: vec2f)->f32 { \nvar temp=a-b; \nreturn dot(temp,temp); }\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nfn linearizeDepth(depth: f32,near: f32,far: f32)->f32 {\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nreturn -(near*far)/(far-depth*(far-near));\n#else\nreturn (near*far)/(far-depth*(far-near));\n#endif\n}\n#endif\n/**\nparam csOrigin Camera-space ray origin,which must be \nwithin the view volume and must have z>0.01 and project within the valid screen rectangle\nparam csDirection Unit length camera-space ray direction\nparam projectToPixelMatrix A projection matrix that maps to **pixel** coordinates \n(**not** [-1,+1] normalized device coordinates).\nparam csZBuffer The camera-space Z buffer\nparam csZBufferSize Dimensions of csZBuffer\nparam csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer\nparam nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value\nfor clipping rays headed towards the camera. Should be the actual near plane if screen-space depth is enabled.\nparam farPlaneZ The far plane for the camera. Used when screen-space depth is enabled.\nparam stride Step in horizontal or vertical pixels between samples. This is a var because: f32 integer math is slow on GPUs,but should be set to an integer>=1\nparam jitterFraction Number between 0 and 1 for how far to bump the ray in stride units\nto conceal banding artifacts,plus the stride ray offset.\nparam maxSteps Maximum number of iterations. Higher gives better images but may be slow\nparam maxRayTraceDistance Maximum camera-space distance to trace before returning a miss\nparam selfCollisionNumSkip Number of steps to skip at start when raytracing to avar self: voidnull collisions.\n1 is a reasonable value,depending on the scene you may need to set this value to 2\nparam hitPixel Pixel coordinates of the first intersection with the scene\nparam numIterations number of iterations performed\nparam csHitPovar Camera: i32 space location of the ray hit\n*/\nfn traceScreenSpaceRay1(\ncsOrigin: vec3f,\ncsDirection: vec3f,\nprojectToPixelMatrix: mat4x4f,\ncsZBuffer: texture_2d,\ncsZBufferSize: vec2f,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\ncsZBackBuffer: texture_2d,\ncsZBackSizeFactor: f32,\n#endif\ncsZThickness: f32,\nnearPlaneZ: f32,\nfarPlaneZ: f32,\nstride: f32,\njitterFraction: f32,\nmaxSteps: f32,\nmaxRayTraceDistance: f32,\nselfCollisionNumSkip: f32,\nstartPixel: ptr,\nhitPixel: ptr,\ncsHitPoint: ptr,\nnumIterations: ptr\n#ifdef SSRAYTRACE_DEBUG\n,debugColor: ptr\n#endif\n)->bool\n{\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nvar rayLength: f32=select(maxRayTraceDistance,(-nearPlaneZ-csOrigin.z)/csDirection.z,(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ);\n#else\nvar rayLength: f32=select(maxRayTraceDistance,(nearPlaneZ-csOrigin.z)/csDirection.z,(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax)))/(P1.y-P0.y);}\nif ((P1.x>xMax) || (P1.xxMax)))/(P1.x-P0.x));}\nP1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha);\n#endif\nP1+= vec2f(select(0.0,0.01,distanceSquared(P0,P1)<0.0001));var delta: vec2f=P1-P0;var permute: bool=false;if (abs(delta.x)rayZMax) { \nvar t: f32=rayZMin; rayZMin=rayZMax; rayZMax=t;}\nsceneZMax=textureLoad(csZBuffer,vec2(*hitPixel),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nsceneZMax=linearizeDepth(sceneZMax,nearPlaneZ,farPlaneZ);\n#endif\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nvar sceneBackZ: f32=textureLoad(csZBackBuffer,vec2(*hitPixel/csZBackSizeFactor),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nsceneBackZ=linearizeDepth(sceneBackZ,nearPlaneZ,farPlaneZ);\n#endif\nhit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax);\n#else\nhit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax);\n#endif\n#else\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nvar sceneBackZ: f32=textureLoad(csZBackBuffer,vec2(*hitPixel/csZBackSizeFactor),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nsceneBackZ=linearizeDepth(sceneBackZ,nearPlaneZ,farPlaneZ);\n#endif\nhit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0);\n#else\nhit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax);\n#endif\n#endif\nstepCount+=1.0;}\npqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;}\n#ifdef SSRAYTRACE_ENABLE_REFINEMENT\nif (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;var invStride: f32=1.0/stride;dPQK*=invStride;var refinementStepCount: f32=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 ||\n((refinementStepCount<=stride*1.4) &&\n(rayZMax(*hitPixel),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nsceneZMax=linearizeDepth(sceneZMax,nearPlaneZ,farPlaneZ);\n#endif\nrefinementStepCount+=1.0;}\npqk-=dPQK;refinementStepCount-=1.0;stepCount+=refinementStepCount/stride;}\n#endif\nQ0=vec3f(Q0.xy+dQ.xy*stepCount,pqk.z);*csHitPoint=Q0/pqk.w;*numIterations=stepCount+1.0;\n#ifdef SSRAYTRACE_DEBUG\nif (((pqk.x+dPQK.x)*stepDirection)>end) {*debugColor= vec3f(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {*debugColor= vec3f(1,0,0);} else if (sceneZMax==0.0) {*debugColor= vec3f(1,1,0);} else {*debugColor= vec3f(0,stepCount/maxSteps,0);}\n#endif\nreturn hit;}\n/**\ntexCoord: in the [0,1] range\ndepth: depth in view space (range [znear,zfar]])\n*/\nfn computeViewPosFromUVDepth(texCoord: vec2f,depth: f32,projection: mat4x4f,invProjectionMatrix: mat4x4f)->vec3f {var xy=texCoord*2.0-1.0;var z: f32;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef ORTHOGRAPHIC_CAMERA\nz=-projection[2].z*depth+projection[3].z;\n#else\nz=-projection[2].z-projection[3].z/depth;\n#endif\n#else\n#ifdef ORTHOGRAPHIC_CAMERA\nz=projection[2].z*depth+projection[3].z;\n#else\nz=projection[2].z+projection[3].z/depth;\n#endif\n#endif\nvar w=1.0;var ndc=vec4f(xy,z,w);var eyePos: vec4f=invProjectionMatrix*ndc;var result=eyePos.xyz/eyePos.w;return result;}\n"},43140:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowMapFragmentWGSL:()=>n});const r="shadowMapFragment",s="var depthSM: f32=fragmentInputs.vDepthMetricSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\n#if SM_USEDISTANCE==1\ndepthSM=(length(fragmentInputs.vPositionWSM-uniforms.lightDataSM)+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\ndepthSM=(-fragmentInputs.zSM+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;\n#else\ndepthSM=(fragmentInputs.zSM+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;\n#endif\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\nfragmentOutputs.fragDepth=clamp(1.0-depthSM,0.0,1.0);\n#else\nfragmentOutputs.fragDepth=clamp(depthSM,0.0,1.0); \n#endif\n#elif SM_USEDISTANCE==1\ndepthSM=(length(fragmentInputs.vPositionWSM-uniforms.lightDataSM)+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;\n#endif\n#if SM_ESM==1\ndepthSM=clamp(exp(-min(87.,uniforms.biasAndScaleSM.z*depthSM)),0.,1.);\n#endif\n#if SM_FLOAT==1\nfragmentOutputs.color= vec4f(depthSM,1.0,1.0,1.0);\n#else\nfragmentOutputs.color=pack(depthSM);\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},17836:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowMapFragmentSoftTransparentShadowWGSL:()=>n});const r="shadowMapFragmentSoftTransparentShadow",s="#if SM_SOFTTRANSPARENTSHADOW==1\nif ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.softTransparentShadowSM.x*alpha) {discard;}\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},18902:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowMapVertexMetricWGSL:()=>n});const r="shadowMapVertexMetric",s="#if SM_USEDISTANCE==1\nvertexOutputs.vPositionWSM=worldPos.xyz;\n#endif\n#if SM_DEPTHTEXTURE==1\n#ifdef IS_NDC_HALF_ZRANGE\n#define BIASFACTOR 0.5\n#else\n#define BIASFACTOR 1.0\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.position.z-=uniforms.biasAndScaleSM.x*vertexOutputs.position.w*BIASFACTOR;\n#else\nvertexOutputs.position.z+=uniforms.biasAndScaleSM.x*vertexOutputs.position.w*BIASFACTOR;\n#endif\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvertexOutputs.zSM=vertexOutputs.position.z;vertexOutputs.position.z=0.0;\n#elif SM_USEDISTANCE==0\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetricSM=(-vertexOutputs.position.z+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;\n#else\nvertexOutputs.vDepthMetricSM=(vertexOutputs.position.z+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},94662:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowsFragmentFunctionsWGSL:()=>n});const r="shadowsFragmentFunctions",s="#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfn unpack(color: vec4f)->f32\n{const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}\n#endif\nfn computeFallOff(value: f32,clipSpace: vec2f,frustumEdgeFalloff: f32)->f32\n{var mask: f32=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}\nfn computeShadowCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,darkness: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadow: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nreturn select(darkness,1.0,depth>shadow);}\nfn computeShadowWithPoissonSamplingCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,mapSize: f32,darkness: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;var visibility: f32=1.;var poissonDisk: array;poissonDisk[0]= vec3f(-1.0,1.0,-1.0);poissonDisk[1]= vec3f(1.0,-1.0,-1.0);poissonDisk[2]= vec3f(-1.0,-1.0,-1.0);poissonDisk[3]= vec3f(1.0,-1.0,1.0);\n#ifndef SHADOWFLOAT\nif (unpack(textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[0]*mapSize)),shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nvar esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return esm;}\nfn computeShadowWithCloseESMCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nvar esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;}\nfn computeShadowCSM(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d_array,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,uv,layer));\n#else\nvar shadow: f32=textureSample(shadowTexture,shadowSampler,uv,layer).x;\n#endif\nreturn select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );}\nfn computeShadow(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadow: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nreturn select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );}}\nfn computeShadowWithPoissonSampling(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,mapSize: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);var visibility: f32=1.;var poissonDisk: array;poissonDisk[0]= vec2f(-0.94201624,-0.39906216);poissonDisk[1]= vec2f(0.94558609,-0.76890725);poissonDisk[2]= vec2f(-0.094184101,-0.92938870);poissonDisk[3]= vec2f(0.34495938,0.29387760);\n#ifndef SHADOWFLOAT\nif (unpack(textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[0]*mapSize,0.)),shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nvar esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithCloseESM(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nvar esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\nfn getZInClip(clipSpace: vec3f,uvDepth: vec3f)->f32\n{\n#ifdef IS_NDC_HALF_ZRANGE\nreturn clipSpace.z;\n#else\nreturn uvDepth.z;\n#endif\n}\nconst GREATEST_LESS_THAN_ONE: f32=0.99999994;\n#define DISABLE_UNIFORMITY_ANALYSIS\nfn computeShadowWithCSMPCF1(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var shadow: f32=textureSampleCompare(shadowTexture,shadowSampler,uvDepth.xy,layer,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithCSMPCF3(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithCSMPCF5(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),layer,uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),layer,uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),layer,uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),layer,uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithPCF1(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var shadow: f32=textureSampleCompareLevel(shadowTexture,shadowSampler,uvDepth.xy,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithPCF3(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithPCF5(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nconst PoissonSamplers32: array=array (\nvec3f(0.06407013,0.05409927,0.),\nvec3f(0.7366577,0.5789394,0.),\nvec3f(-0.6270542,-0.5320278,0.),\nvec3f(-0.4096107,0.8411095,0.),\nvec3f(0.6849564,-0.4990818,0.),\nvec3f(-0.874181,-0.04579735,0.),\nvec3f(0.9989998,0.0009880066,0.),\nvec3f(-0.004920578,-0.9151649,0.),\nvec3f(0.1805763,0.9747483,0.),\nvec3f(-0.2138451,0.2635818,0.),\nvec3f(0.109845,0.3884785,0.),\nvec3f(0.06876755,-0.3581074,0.),\nvec3f(0.374073,-0.7661266,0.),\nvec3f(0.3079132,-0.1216763,0.),\nvec3f(-0.3794335,-0.8271583,0.),\nvec3f(-0.203878,-0.07715034,0.),\nvec3f(0.5912697,0.1469799,0.),\nvec3f(-0.88069,0.3031784,0.),\nvec3f(0.5040108,0.8283722,0.),\nvec3f(-0.5844124,0.5494877,0.),\nvec3f(0.6017799,-0.1726654,0.),\nvec3f(-0.5554981,0.1559997,0.),\nvec3f(-0.3016369,-0.3900928,0.),\nvec3f(-0.5550632,-0.1723762,0.),\nvec3f(0.925029,0.2995041,0.),\nvec3f(-0.2473137,0.5538505,0.),\nvec3f(0.9183037,-0.2862392,0.),\nvec3f(0.2469421,0.6718712,0.),\nvec3f(0.3916397,-0.4328209,0.),\nvec3f(-0.03576927,-0.6220032,0.),\nvec3f(-0.04661255,0.7995201,0.),\nvec3f(0.4402924,0.3640312,0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.)\n);const PoissonSamplers64: array=array (\nvec3f(-0.613392,0.617481,0.),\nvec3f(0.170019,-0.040254,0.),\nvec3f(-0.299417,0.791925,0.),\nvec3f(0.645680,0.493210,0.),\nvec3f(-0.651784,0.717887,0.),\nvec3f(0.421003,0.027070,0.),\nvec3f(-0.817194,-0.271096,0.),\nvec3f(-0.705374,-0.668203,0.),\nvec3f(0.977050,-0.108615,0.),\nvec3f(0.063326,0.142369,0.),\nvec3f(0.203528,0.214331,0.),\nvec3f(-0.667531,0.326090,0.),\nvec3f(-0.098422,-0.295755,0.),\nvec3f(-0.885922,0.215369,0.),\nvec3f(0.566637,0.605213,0.),\nvec3f(0.039766,-0.396100,0.),\nvec3f(0.751946,0.453352,0.),\nvec3f(0.078707,-0.715323,0.),\nvec3f(-0.075838,-0.529344,0.),\nvec3f(0.724479,-0.580798,0.),\nvec3f(0.222999,-0.215125,0.),\nvec3f(-0.467574,-0.405438,0.),\nvec3f(-0.248268,-0.814753,0.),\nvec3f(0.354411,-0.887570,0.),\nvec3f(0.175817,0.382366,0.),\nvec3f(0.487472,-0.063082,0.),\nvec3f(-0.084078,0.898312,0.),\nvec3f(0.488876,-0.783441,0.),\nvec3f(0.470016,0.217933,0.),\nvec3f(-0.696890,-0.549791,0.),\nvec3f(-0.149693,0.605762,0.),\nvec3f(0.034211,0.979980,0.),\nvec3f(0.503098,-0.308878,0.),\nvec3f(-0.016205,-0.872921,0.),\nvec3f(0.385784,-0.393902,0.),\nvec3f(-0.146886,-0.859249,0.),\nvec3f(0.643361,0.164098,0.),\nvec3f(0.634388,-0.049471,0.),\nvec3f(-0.688894,0.007843,0.),\nvec3f(0.464034,-0.188818,0.),\nvec3f(-0.440840,0.137486,0.),\nvec3f(0.364483,0.511704,0.),\nvec3f(0.034028,0.325968,0.),\nvec3f(0.099094,-0.308023,0.),\nvec3f(0.693960,-0.366253,0.),\nvec3f(0.678884,-0.204688,0.),\nvec3f(0.001801,0.780328,0.),\nvec3f(0.145177,-0.898984,0.),\nvec3f(0.062655,-0.611866,0.),\nvec3f(0.315226,-0.604297,0.),\nvec3f(-0.780145,0.486251,0.),\nvec3f(-0.371868,0.882138,0.),\nvec3f(0.200476,0.494430,0.),\nvec3f(-0.494552,-0.711051,0.),\nvec3f(0.612476,0.705252,0.),\nvec3f(-0.578845,-0.768792,0.),\nvec3f(-0.772454,-0.090976,0.),\nvec3f(0.504440,0.372295,0.),\nvec3f(0.155736,0.065157,0.),\nvec3f(0.391522,0.849605,0.),\nvec3f(-0.620106,-0.328104,0.),\nvec3f(0.789239,-0.419965,0.),\nvec3f(-0.545396,0.538133,0.),\nvec3f(-0.178564,-0.596057,0.)\n);fn computeShadowWithCSMPCSS(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uvDepthLayer: vec4f= vec4f(uvDepth.x,uvDepth.y,f32(layer),uvDepth.z);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;for (var i: i32=0; i,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;var exitCondition: bool=depthMetric>1.0 || depthMetric<0.0;for (var i: i32=0; i,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);}\nfn computeShadowWithPCSS32(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);}\nfn computeShadowWithPCSS64(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);}\nfn computeShadowWithCSMPCSS16(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\nfn computeShadowWithCSMPCSS32(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\nfn computeShadowWithCSMPCSS64(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},48453:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowsVertexWGSL:()=>n});const r="shadowsVertex",s="#ifdef SHADOWS\n#if defined(SHADOWCSM{X})\nvertexOutputs.vPositionFromCamera{X}=scene.view*worldPos;\n#if SHADOWCSMNUM_CASCADES{X}>0\nvertexOutputs.vPositionFromLight{X}_0=uniforms.lightMatrix{X}[0]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_0=(-vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_0= (vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif\n#if SHADOWCSMNUM_CASCADES{X}>1\nvertexOutputs.vPositionFromLight{X}_1=uniforms.lightMatrix{X}[1]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_1=(-vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_1= (vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#if SHADOWCSMNUM_CASCADES{X}>2\nvertexOutputs.vPositionFromLight{X}_2=uniforms.lightMatrix{X}[2]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_2=(-vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_2= (vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#if SHADOWCSMNUM_CASCADES{X}>3\nvertexOutputs.vPositionFromLight{X}_3=uniforms.lightMatrix{X}[3]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_3=(-vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_3= (vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvertexOutputs.vPositionFromLight{X}=uniforms.lightMatrix{X}*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}=(-vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}=(vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif\n#endif\n";i(69841).l.IncludesShadersStoreWGSL[r]=s;const n={name:r,shader:s}},20115:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.uvAttributeDeclaration="#ifdef UV{X}\nattribute uv{X}: vec2f;\n#endif\n"},80699:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.uvVariableDeclaration="#ifdef MAINUV{X}\n#if !defined(UV{X})\nvar uv{X}: vec2f=vec2f(0.,0.);\n#else\nvar uv{X}: vec2f=vertexInputs.uv{X};\n#endif\nvertexOutputs.vMainUV{X}=uv{X};\n#endif\n"},42321:(e,t,i)=>{"use strict";i(69841).l.IncludesShadersStoreWGSL.vertexColorMixing="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvertexOutputs.vColor=vec4f(1.0);\n#ifdef VERTEXCOLOR\n#ifdef VERTEXALPHA\nvertexOutputs.vColor*=vertexInputs.color;\n#else\nvertexOutputs.vColor=vec4f(vertexOutputs.vColor.rgb*vertexInputs.color.rgb,vertexOutputs.vColor.a);\n#endif\n#endif\n#ifdef INSTANCESCOLOR\nvertexOutputs.vColor*=vertexInputs.instanceColor;\n#endif\n#endif\n"},2153:(e,t,i)=>{"use strict";i.r(t),i.d(t,{anaglyphPixelShaderWGSL:()=>n});const r="anaglyphPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var leftSamplerSampler: sampler;var leftSampler: texture_2d;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var leftFrag: vec4f=textureSample(leftSampler,leftSamplerSampler,input.vUV);leftFrag= vec4f(1.0,leftFrag.g,leftFrag.b,1.0);var rightFrag: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);rightFrag= vec4f(rightFrag.r,1.0,1.0,1.0);fragmentOutputs.color= vec4f(rightFrag.rgb*leftFrag.rgb,1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},61853:(e,t,i)=>{"use strict";i.r(t),i.d(t,{backgroundPixelShaderWGSL:()=>o});var r=i(69841);i(50128),i(87647),i(7769),i(33882),i(71426),i(34992),i(94662),i(33731),i(21859),i(96140),i(10668),i(76794),i(55090),i(85551),i(31034);const s="backgroundPixelShader",n="#include\n#include\nvarying vPositionW: vec3f;\n#ifdef MAINUV1\nvarying vMainUV1: vec2f;\n#endif \n#ifdef MAINUV2 \nvarying vMainUV2: vec2f; \n#endif \n#ifdef NORMAL\nvarying vNormalW: vec3f;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV==1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV==2\n#define vDiffuseUV vMainUV2\n#else\nvarying vDiffuseUV: vec2f;\n#endif\nvar diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d;\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nvar reflectionSamplerSampler: sampler;var reflectionSampler: texture_cube;\n#ifdef TEXTURELODSUPPORT\n#else\nvar reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_cube;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_cube;\n#endif\n#else\nvar reflectionSamplerSampler: sampler;var reflectionSampler: texture_2d;\n#ifdef TEXTURELODSUPPORT\n#else\nvar reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_2d;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_2d;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vPositionUVW: vec3f;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vDirectionW: vec3f;\n#endif\n#endif\n#include\n#endif\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include\n#include\n#include\n#include\n#include\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nfn fresnelSchlickEnvironmentGGX(VdotN: f32,reflectance0: vec3f,reflectance90: vec3f,smoothness: f32)->vec3f\n{var weight: f32=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#ifdef PROJECTED_GROUND\nfn diskIntersectWithBackFaceCulling(ro: vec3f,rd: vec3f,c: vec3f,r: f32)->f32 {var d: f32=rd.y;if(d>0.0) { return 1e6; }\nvar o: vec3f=ro-c;var t: f32=-o.y/d;var q: vec3f=o+rd*t;return select(1e6,t,(dot(q,q)f32 {var b: f32=dot(ro,rd);var c: f32=dot(ro,ro)-ra*ra;var h: f32=b*b-c;if(h<0.0) { return -1.0; }\nh=sqrt(h);return-b+h;}\nfn project(viewDirectionW: vec3f,eyePosition: vec3f)->vec3f {var radius: f32=uniforms.projectedGroundInfos.x;var height: f32=uniforms.projectedGroundInfos.y;var camDir: vec3f=-viewDirectionW;var skySphereDistance: f32=sphereIntersect(eyePosition,camDir,radius);var skySpherePositionW: vec3f=eyePosition+camDir*skySphereDistance;var p: vec3f=normalize(skySpherePositionW);var upEyePosition=vec3f(eyePosition.x,eyePosition.y-height,eyePosition.z);var sIntersection: f32=sphereIntersect(upEyePosition,p,radius);var h: vec3f= vec3f(0.0,-height,0.0);var dIntersection: f32=diskIntersectWithBackFaceCulling(upEyePosition,p,h,radius);p=(upEyePosition+min(sIntersection,dIntersection)*p);return p;}\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvar viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-input.vPositionW);\n#ifdef NORMAL\nvar normalW: vec3f=normalize(fragmentInputs.vNormalW);\n#else\nvar normalW: vec3f= vec3f(0.0,1.0,0.0);\n#endif\nvar shadow: f32=1.;var globalShadow: f32=0.;var shadowLightCount: f32=0.;var aggShadow: f32=0.;var numLights: f32=0.;\n#include[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n#ifndef BACKMAT_SHADOWONLY\nvar reflectionColor: vec4f= vec4f(1.,1.,1.,1.);\n#ifdef REFLECTION\n#ifdef PROJECTED_GROUND\nvar reflectionVector: vec3f=project(viewDirectionW,scene.vEyePosition.xyz);reflectionVector= (uniforms.reflectionMatrix*vec4f(reflectionVector,1.)).xyz;\n#else\nvar reflectionVector: vec3f=computeReflectionCoords( vec4f(fragmentInputs.vPositionW,1.0),normalW);\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nvar reflectionCoords: vec3f=reflectionVector;\n#else\nvar reflectionCoords: vec2f=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nvar reflectionLOD: f32=uniforms.vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=textureSampleLevel(reflectionSampler,reflectionSamplerSampler,reflectionCoords,reflectionLOD);\n#else\nvar lodReflectionNormalized: f32=saturate(reflectionLOD);var lodReflectionNormalizedDoubled: f32=lodReflectionNormalized*2.0;var reflectionSpecularMid: vec4f=textureSample(reflectionSampler,reflectionSamplerSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix(\ntextureSample(reflectionrHighSampler,reflectionrHighSamplerSampler,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);} else {reflectionColor=mix(\nreflectionSpecularMid,\ntextureSample(reflectionLowSampler,reflectionLowSamplerSampler,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);}\n#endif\n#else\nvar reflectionSample: vec4f=textureSample(reflectionSampler,reflectionSamplerSampler,reflectionCoords);reflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor=vec4f(fromRGBD(reflectionColor).rgb,reflectionColor.a);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=vec4f(toLinearSpaceVec3(reflectionColor.rgb),reflectionColor.a);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=vec4f(reflectionColor.bgr,reflectionColor.a);\n#endif\nreflectionColor=vec4f(reflectionColor.rgb*uniforms.vReflectionInfos.x,reflectionColor.a);\n#endif\nvar diffuseColor: vec3f= vec3f(1.,1.,1.);var finalAlpha: f32=uniforms.alpha;\n#ifdef DIFFUSE\nvar diffuseMap: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,input.vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap=vec4f(toLinearSpaceVec3(diffuseMap.rgb),diffuseMap.a);\n#endif\ndiffuseMap=vec4f(diffuseMap.rgb *uniforms.vDiffuseInfos.y,diffuseMap.a);\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n#ifdef REFLECTIONFRESNEL\nvar colorBase: vec3f=diffuseColor;\n#else\nvar colorBase: vec3f=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,vec3f(0.0));\n#ifdef USERGBCOLOR\nvar finalColor: vec3f=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvar mainColor: vec3f=mix(uniforms.vPrimaryColorShadow.rgb,uniforms.vPrimaryColor.rgb,colorBase);\n#else\nvar mainColor: vec3f=uniforms.vPrimaryColor.rgb;\n#endif\nvar finalColor: vec3f=colorBase*mainColor;\n#endif\n#ifdef REFLECTIONFRESNEL\nvar reflectionAmount: vec3f=uniforms.vReflectionControl.xxx;var reflectionReflectance0: vec3f=uniforms.vReflectionControl.yyy;var reflectionReflectance90: vec3f=uniforms.vReflectionControl.zzz;var VdotN: f32=dot(normalize(scene.vEyePosition.xyz),normalW);var planarReflectionFresnel: vec3f=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nvar reflectionDistanceFalloff: f32=1.0-saturate(length(vPositionW.xyz-uniforms.vBackgroundCenter)*uniforms.vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,saturateVec3(reflectionAmount));\n#endif\n#ifdef OPACITYFRESNEL\nvar viewAngleToFloor: f32=dot(normalW,normalize(scene.vEyePosition.xyz-uniforms.vBackgroundCenter));const startAngle: f32=0.1;var fadeFactor: f32=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor;\n#endif\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*uniforms.shadowLevel,finalColor,globalShadow);\n#endif\nvar color: vec4f= vec4f(finalColor,finalAlpha);\n#else\nvar color: vec4f= vec4f(uniforms.vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*uniforms.alpha);\n#endif\n#include\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n#if !defined(SKIPFINALCOLORCLAMP)\ncolor=vec4f(clamp(color.rgb,vec3f(0.),vec3f(30.0)),color.a);\n#endif\n#else\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\ncolor=vec4f(color.rgb *color.a,color.a);\n#endif\n#ifdef NOISE\ncolor=vec4f(color.rgb+dither(fragmentInputs.vPositionW.xy,0.5),color.a);color=max(color,vec4f(0.0));\n#endif\nfragmentOutputs.color=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},18135:(e,t,i)=>{"use strict";i.r(t),i.d(t,{backgroundVertexShaderWGSL:()=>o});var r=i(69841);i(50128),i(87647),i(25589),i(68273),i(41416),i(30486),i(86934),i(85188),i(21859),i(32764),i(40903),i(71281),i(57728),i(45184),i(48453),i(18201);const s="backgroundVertexShader",n="#include\n#include\nattribute position: vec3f;\n#ifdef NORMAL\nattribute normal: vec3f;\n#endif\n#include\n#include\n#include\nvarying vPositionW: vec3f;\n#ifdef NORMAL\nvarying vNormalW: vec3f;\n#endif\n#ifdef UV1\nattribute uv: vec2f;\n#endif\n#ifdef UV2\nattribute uv2: vec2f;\n#endif\n#ifdef MAINUV1\nvarying vMainUV1: vec2f;\n#endif\n#ifdef MAINUV2\nvarying vMainUV2: vec2f;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nvarying vDiffuseUV: vec2f;\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vPositionUVW: vec3f;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vDirectionW: vec3f;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#ifdef REFLECTIONMAP_SKYBOX\nvertexOutputs.vPositionUVW=input.position;\n#endif\n#include\n#include\n#include\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {vertexOutputs.position=scene.viewProjection*finalWorld* vec4f(input.position,1.0);} else {vertexOutputs.position=scene.viewProjectionR*finalWorld* vec4f(input.position,1.0);}\n#else\nvertexOutputs.position=scene.viewProjection*finalWorld* vec4f(input.position,1.0);\n#endif\nvar worldPos: vec4f=finalWorld* vec4f(input.position,1.0);vertexOutputs.vPositionW= worldPos.xyz;\n#ifdef NORMAL\nvar normalWorld: mat3x3f=mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvertexOutputs.vNormalW=normalize(normalWorld*input.normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvertexOutputs.vDirectionW=normalize((finalWorld*vec4f(input.position,0.0)).xyz);\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nvar screenToWorld: mat3x3f=inverseMat3( mat3x3f(finalWorld*scene.viewProjection));var segment: vec3f=mix(vertexOutputs.vDirectionW,screenToWorld* vec3f(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vertexOutputs.vDirectionW=normalize(segment);} else {vertexOutputs.vDirectionW=normalize(vertexOutputs.vDirectionW+(vertexOutputs.vDirectionW-segment));}\n#endif\n#endif\n#ifndef UV1\nvar uv: vec2f=vec2f(0.,0.);\n#else\nvar uv=input.uv;\n#endif\n#ifndef UV2\nvar uv2: vec2f=vec2f(0.,0.);\n#else\nvar uv2=input.uv2;\n#endif\n#ifdef MAINUV1\nvertexOutputs.vMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvertexOutputs.vMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nif (uniforms.vDiffuseInfos.x==0.)\n{vertexOutputs.vDiffuseUV= (uniforms.diffuseMatrix* vec4f(uv,1.0,0.0)).xy;}\nelse\n{vertexOutputs.vDiffuseUV= (uniforms.diffuseMatrix* vec4f(uv2,1.0,0.0)).xy;}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\nvertexOutputs.vColor=vertexInputs.color;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},84910:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bilateralBlurPixelShaderWGSL:()=>n});const r="bilateralBlurPixelShader",s="var textureSamplerSampler: sampler;var textureSampler: texture_2d;var normalSamplerSampler: sampler;var normalSampler: texture_2d;var depthSamplerSampler: sampler;var depthSampler: texture_2d;uniform filterSize: i32;uniform blurDir: vec2f;uniform depthThreshold: f32;uniform normalThreshold: f32;varying vUV: vec2f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.).rgb;var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.).x;if (depth>=1e6 || depth<=0.) {fragmentOutputs.color= vec4f(color,1.);return fragmentOutputs;}\nvar normal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nvar sigma: f32= f32(uniforms.filterSize);var two_sigma2: f32=2.0*sigma*sigma;var sigmaDepth: f32=uniforms.depthThreshold;var two_sigmaDepth2: f32=2.0*sigmaDepth*sigmaDepth;var sigmaNormal: f32=uniforms.normalThreshold;var two_sigmaNormal2: f32=2.0*sigmaNormal*sigmaNormal;var sum: vec3f= vec3f(0.);var wsum: f32=0.;for (var x: i32=-uniforms.filterSize; x<=uniforms.filterSize; x++) {var coords=vec2f(f32(x));var sampleColor: vec3f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV+coords*uniforms.blurDir,0.).rgb;var sampleDepth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV+coords*uniforms.blurDir,0.).r;var sampleNormal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV+coords*uniforms.blurDir,0.).rgb;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nvar r: f32=dot(coords,coords);var w: f32=exp(-r/two_sigma2);var depthDelta: f32=abs(sampleDepth-depth);var wd: f32=step(depthDelta,uniforms.depthThreshold);var normalDelta: vec3f=abs(sampleNormal-normal);var wn: f32=step(normalDelta.x+normalDelta.y+normalDelta.z,uniforms.normalThreshold);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}\nfragmentOutputs.color= vec4f(sum/wsum,1.);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},46563:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bilateralBlurQualityPixelShaderWGSL:()=>n});const r="bilateralBlurQualityPixelShader",s="var textureSamplerSampler: sampler;var textureSampler: texture_2d;var normalSamplerSampler: sampler;var normalSampler: texture_2d;var depthSamplerSampler: sampler;var depthSampler: texture_2d;uniform filterSize: i32;uniform blurDir: vec2f;uniform depthThreshold: f32;uniform normalThreshold: f32;varying vUV: vec2f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.).rgb;var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.).x;if (depth>=1e6 || depth<=0.) {fragmentOutputs.color= vec4f(color,1.);return fragmentOutputs;}\nvar normal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nvar sigma: f32= f32(uniforms.filterSize);var two_sigma2: f32=2.0*sigma*sigma;var sigmaDepth: f32=uniforms.depthThreshold;var two_sigmaDepth2: f32=2.0*sigmaDepth*sigmaDepth;var sigmaNormal: f32=uniforms.normalThreshold;var two_sigmaNormal2: f32=2.0*sigmaNormal*sigmaNormal;var sum: vec3f= vec3f(0.);var wsum: f32=0.;for (var x: i32=-uniforms.filterSize; x<=uniforms.filterSize; x++) {for (var y: i32=-uniforms.filterSize; y<=uniforms.filterSize; y++) {var coords: vec2f= vec2f(f32(x),f32(y))*uniforms.blurDir;var sampleColor: vec3f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV+coords,0.).rgb;var sampleDepth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV+coords,0.).r;var sampleNormal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV+coords,0.).rgb;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nvar r: f32=dot(coords,coords);var w: f32=exp(-r/two_sigma2);var rDepth: f32=sampleDepth-depth;var wd: f32=exp(-rDepth*rDepth/two_sigmaDepth2);var rNormal: f32=abs(sampleNormal.x-normal.x)+abs(sampleNormal.y-normal.y)+abs(sampleNormal.z-normal.z);var wn: f32=exp(-rNormal*rNormal/two_sigmaNormal2);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}}\nfragmentOutputs.color= vec4f(sum/wsum,1.);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},31162:(e,t,i)=>{"use strict";i.r(t),i.d(t,{blackAndWhitePixelShaderWGSL:()=>n});const r="blackAndWhitePixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform degree: f32;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var luminance: f32=dot(color, vec3f(0.3,0.59,0.11)); \nvar blackAndWhite: vec3f= vec3f(luminance,luminance,luminance);fragmentOutputs.color= vec4f(color-((color-blackAndWhite)*uniforms.degree),1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},63186:(e,t,i)=>{"use strict";i.r(t),i.d(t,{bloomMergePixelShaderWGSL:()=>n});const r="bloomMergePixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var bloomBlurSampler: sampler;var bloomBlur: texture_2d;uniform bloomWeight: f32;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);var blurred: vec3f=textureSample(bloomBlur,bloomBlurSampler,input.vUV).rgb;fragmentOutputs.color=vec4f(fragmentOutputs.color.rgb+(blurred.rgb*uniforms.bloomWeight),fragmentOutputs.color.a);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},83063:(e,t,i)=>{"use strict";i.r(t),i.d(t,{boundingBoxRendererPixelShaderWGSL:()=>n});const r="boundingBoxRendererPixelShader",s="uniform color: vec4f;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nfragmentOutputs.color=uniforms.color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},10737:(e,t,i)=>{"use strict";i.r(t),i.d(t,{boundingBoxRendererVertexShaderWGSL:()=>n});const r="boundingBoxRendererVertexShader",s="attribute position: vec3f;uniform world: mat4x4f;uniform viewProjection: mat4x4f;\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvar worldPos: vec4f=uniforms.world* vec4f(input.position,1.0);vertexOutputs.position=uniforms.viewProjection*worldPos;\n#define CUSTOM_VERTEX_MAIN_END\n}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},44134:(e,t,i)=>{"use strict";i.r(t),i.d(t,{chromaticAberrationPixelShaderWGSL:()=>n});const r="chromaticAberrationPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform chromatic_aberration: f32;uniform radialIntensity: f32;uniform direction: vec2f;uniform centerPosition: vec2f;uniform screen_width: f32;uniform screen_height: f32;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var centered_screen_pos: vec2f= vec2f(input.vUV.x-uniforms.centerPosition.x,input.vUV.y-uniforms.centerPosition.y);var directionOfEffect: vec2f=uniforms.direction;if(directionOfEffect.x==0. && directionOfEffect.y==0.){directionOfEffect=normalize(centered_screen_pos);}\nvar radius2: f32=centered_screen_pos.x*centered_screen_pos.x\n+ centered_screen_pos.y*centered_screen_pos.y;var radius: f32=sqrt(radius2);var ref_indices: vec3f= vec3f(-0.3,0.0,0.3);var ref_shiftX: f32=uniforms.chromatic_aberration*pow(radius,uniforms.radialIntensity)*directionOfEffect.x/uniforms.screen_width;var ref_shiftY: f32=uniforms.chromatic_aberration*pow(radius,uniforms.radialIntensity)*directionOfEffect.y/uniforms.screen_height;var ref_coords_r: vec2f=vec2f(input.vUV.x+ref_indices.r*ref_shiftX,input.vUV.y+ref_indices.r*ref_shiftY*0.5);var ref_coords_g: vec2f=vec2f(input.vUV.x+ref_indices.g*ref_shiftX,input.vUV.y+ref_indices.g*ref_shiftY*0.5);var ref_coords_b: vec2f=vec2f(input.vUV.x+ref_indices.b*ref_shiftX,input.vUV.y+ref_indices.b*ref_shiftY*0.5);var r=textureSample(textureSampler,textureSamplerSampler,ref_coords_r);var g=textureSample(textureSampler,textureSamplerSampler,ref_coords_g);var b=textureSample(textureSampler,textureSamplerSampler,ref_coords_b);var a=clamp(r.a+g.a+b.a,0.,1.);fragmentOutputs.color=vec4f(r.r,g.g,b.b,a);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},89328:(e,t,i)=>{"use strict";i.r(t),i.d(t,{circleOfConfusionPixelShaderWGSL:()=>n});const r="circleOfConfusionPixelShader",s="varying vUV: vec2f;var depthSamplerSampler: sampler;var depthSampler: texture_2d;\n#ifndef COC_DEPTH_NOT_NORMALIZED\nuniform cameraMinMaxZ: vec2f;\n#endif\nuniform focusDistance: f32;uniform cocPrecalculation: f32;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var depth: f32=textureSample(depthSampler,depthSamplerSampler,input.vUV).r;\n#define CUSTOM_COC_DEPTH\n#ifdef COC_DEPTH_NOT_NORMALIZED\nlet pixelDistance=depth*1000.0;\n#else\nlet pixelDistance: f32=(uniforms.cameraMinMaxZ.x+uniforms.cameraMinMaxZ.y*depth)*1000.0; \n#endif\n#define CUSTOM_COC_PIXELDISTANCE\nvar coc: f32=abs(uniforms.cocPrecalculation*((uniforms.focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);fragmentOutputs.color= vec4f(coc,coc,coc,1.0);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},88516:(e,t,i)=>{"use strict";i.r(t),i.d(t,{colorPixelShaderWGSL:()=>o});var r=i(69841);i(96140),i(10668),i(76794),i(31034);const s="colorPixelShader",n="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\n#define VERTEXCOLOR\nvarying vColor: vec4f;\n#else\nuniform color: vec4f;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nfragmentOutputs.color=input.vColor;\n#else\nfragmentOutputs.color=uniforms.color;\n#endif\n#include(color,fragmentOutputs.color)\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},88130:(e,t,i)=>{"use strict";i.r(t),i.d(t,{colorVertexShaderWGSL:()=>o});var r=i(69841);i(25589),i(68273),i(30486),i(86934),i(41416),i(32764),i(40903),i(71281),i(57728),i(45184),i(42321);const s="colorVertexShader",n="attribute position: vec3f;\n#ifdef VERTEXCOLOR\nattribute color: vec4f;\n#endif\n#include\n#include\n#include\n#include\n#ifdef FOG\nuniform view: mat4x4f;\n#endif\n#include\nuniform viewProjection: mat4x4f;\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vColor: vec4f;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvar worldPos: vec4f=finalWorld* vec4f(input.position,1.0);vertexOutputs.position=uniforms.viewProjection*worldPos;\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},82308:(e,t,i)=>{"use strict";i.r(t),i.d(t,{colorCorrectionPixelShaderWGSL:()=>n});const r="colorCorrectionPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;varying vUV: vec2f;var colorTableSampler: sampler;var colorTable: texture_2d;const SLICE_COUNT: f32=16.0; \nfn sampleAs3DTexture(uv: vec3f,width: f32)->vec4f {var sliceSize: f32=1.0/width; \nvar slicePixelSize: f32=sliceSize/width; \nvar sliceInnerSize: f32=slicePixelSize*(width-1.0); \nvar zSlice0: f32=min(floor(uv.z*width),width-1.0);var zSlice1: f32=min(zSlice0+1.0,width-1.0);var xOffset: f32=slicePixelSize*0.5+uv.x*sliceInnerSize;var s0: f32=xOffset+(zSlice0*sliceSize);var s1: f32=xOffset+(zSlice1*sliceSize);var slice0Color: vec4f=textureSample(colorTable,colorTableSampler,vec2f(s0,uv.y));var slice1Color: vec4f=textureSample(colorTable,colorTableSampler,vec2f(s1,uv.y));var zOffset: f32=((uv.z*width)%(1.0));return mix(slice0Color,slice1Color,zOffset);}\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var screen_color: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);fragmentOutputs.color=sampleAs3DTexture(screen_color.rgb,SLICE_COUNT);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},79799:(e,t,i)=>{"use strict";i.r(t),i.d(t,{convolutionPixelShaderWGSL:()=>n});const r="convolutionPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f;uniform kernel: array;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var onePixel: vec2f= vec2f(1.0,1.0)/uniforms.screenSize;var colorSum: vec4f =\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(-1,-1))*uniforms.kernel[0] +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(0,-1))*uniforms.kernel[1] +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(1,-1))*uniforms.kernel[2] +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(-1,0))*uniforms.kernel[3] +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(0,0))*uniforms.kernel[4] +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(1,0))*uniforms.kernel[5] +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(-1,1))*uniforms.kernel[6] +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(0,1))*uniforms.kernel[7] +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(1,1))*uniforms.kernel[8];var kernelWeight: f32 =\nuniforms.kernel[0] +\nuniforms.kernel[1] +\nuniforms.kernel[2] +\nuniforms.kernel[3] +\nuniforms.kernel[4] +\nuniforms.kernel[5] +\nuniforms.kernel[6] +\nuniforms.kernel[7] +\nuniforms.kernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;}\nfragmentOutputs.color= vec4f((colorSum/kernelWeight).rgb,1);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},4357:(e,t,i)=>{"use strict";i.r(t),i.d(t,{copyTexture3DLayerToTexturePixelShaderWGSL:()=>n});const r="copyTexture3DLayerToTexturePixelShader",s="var textureSampler: texture_3d;uniform layerNum: i32;varying vUV: vec2f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {let coord=vec3f(vec2f(input.vUV.x,input.vUV.y)*vec2f(textureDimensions(textureSampler,0).xy),f32(uniforms.layerNum));let color=textureLoad(textureSampler,vec3i(coord),0).rgb;fragmentOutputs.color= vec4f(color,1);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},89517:(e,t,i)=>{"use strict";i.r(t),i.d(t,{copyTextureToTexturePixelShaderWGSL:()=>o});var r=i(69841);i(87647);const s="copyTextureToTexturePixelShader",n="uniform conversion: f32;var textureSamplerSampler: sampler;var textureSampler: texture_2d;varying vUV: vec2f;\n#include\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var color: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);\n#ifdef DEPTH_TEXTURE\nfragmentOutputs.fragDepth=color.r;\n#else\nif (uniforms.conversion==1.) {color=toLinearSpaceVec4(color);} else if (uniforms.conversion==2.) {color=toGammaSpace(color);}\nfragmentOutputs.color=color;\n#endif\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},49694:(e,t,i)=>{"use strict";i.r(t),i.d(t,{defaultPixelShaderWGSL:()=>o});var r=i(69841);i(59051),i(85620),i(73048),i(36174),i(87647),i(71426),i(34992),i(94662),i(59224),i(27493),i(7769),i(33882),i(33731),i(56332),i(87087),i(96140),i(21859),i(10668),i(76794),i(99312),i(17327),i(81859),i(55090),i(85551),i(31034),i(63270);const s="defaultPixelShader",n="#include\n#include[SCENE_MRT_COUNT]\n#include\n#define CUSTOM_FRAGMENT_BEGIN\nvarying vPositionW: vec3f;\n#ifdef NORMAL\nvarying vNormalW: vec3f;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vColor: vec4f;\n#endif\n#include[1..7]\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include\n#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nvar refractionCubeSamplerSampler: sampler;var refractionCubeSampler: texture_cube;\n#else\nvar refraction2DSamplerSampler: sampler;var refraction2DSampler: texture_2d;\n#endif\n#endif\n#if defined(SPECULARTERM)\n#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular)\n#endif\n#include\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nvar reflectionCubeSamplerSampler: sampler;var reflectionCubeSampler: texture_cube;\n#else\nvar reflection2DSamplerSampler: sampler;var reflection2DSampler: texture_2d;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vPositionUVW: vec3f;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vDirectionW: vec3f;\n#endif\n#endif\n#include\n#endif\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvar viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-fragmentInputs.vPositionW);var baseColor: vec4f= vec4f(1.,1.,1.,1.);var diffuseColor: vec3f=uniforms.vDiffuseColor.rgb;var alpha: f32=uniforms.vDiffuseColor.a;\n#ifdef NORMAL\nvar normalW: vec3f=normalize(fragmentInputs.vNormalW);\n#else\nvar normalW: vec3f=normalize(-cross(dpdx(fragmentInputs.vPositionW),dpdy(fragmentInputs.vPositionW)));\n#endif\n#include\n#ifdef TWOSIDEDLIGHTING\nnormalW=select(-normalW,normalW,fragmentInputs.frontFacing);\n#endif\n#ifdef DIFFUSE\nbaseColor=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vDiffuseUV+uvOffset);\n#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS)\nif (baseColor.a(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)\n#endif\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor=vec4f(baseColor.rgb*fragmentInputs.vColor.rgb,baseColor.a);\n#endif\n#ifdef DETAIL\nbaseColor=vec4f(baseColor.rgb*2.0*mix(0.5,detailColor.r,uniforms.vDetailInfos.y),baseColor.a);\n#endif\n#if defined(DECAL) && defined(DECAL_AFTER_DETAIL)\nvar decalColor: vec4f=textureSample(decalSampler,decalSamplerSampler,fragmentInputs.vDecalUV+uvOffset);\n#include(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\nvar baseAmbientColor: vec3f= vec3f(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=textureSample(ambientSampler,ambientSamplerSampler,fragmentInputs.vAmbientUV+uvOffset).rgb*uniforms.vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\nvar glossiness: f32=uniforms.vSpecularColor.a;var specularColor: vec3f=uniforms.vSpecularColor.rgb;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\nvar specularMapColor: vec4f=textureSample(specularSampler,specularSamplerSampler,fragmentInputs.vSpecularUV+uvOffset);specularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#endif\nvar diffuseBase: vec3f= vec3f(0.,0.,0.);var info: lightingInfo;\n#ifdef SPECULARTERM\nvar specularBase: vec3f= vec3f(0.,0.,0.);\n#endif\nvar shadow: f32=1.;var aggShadow: f32=0.;var numLights: f32=0.;\n#ifdef LIGHTMAP\nvar lightmapColor: vec4f=textureSample(lightmapSampler,lightmapSamplerSampler,fragmentInputs.vLightmapUV+uvOffset);\n#ifdef RGBDLIGHTMAP\nlightmapColor=vec4f(fromRGBD(lightmapColor),lightmapColor.a);\n#endif\nlightmapColor=vec4f(lightmapColor.rgb*uniforms.vLightmapInfos.y,lightmapColor.a);\n#endif\n#include[0..maxSimultaneousLights]\naggShadow=aggShadow/numLights;var refractionColor: vec4f= vec4f(0.,0.,0.,1.);\n#ifdef REFRACTION\nvar refractionVector: vec3f=normalize(refract(-viewDirectionW,normalW,uniforms.vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\n#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC\nrefractionVector=parallaxCorrectNormal(fragmentInputs.vPositionW,refractionVector,uniforms.vRefractionSize,uniforms.vRefractionPosition);\n#endif\nrefractionVector.y=refractionVector.y*uniforms.vRefractionInfos.w;var refractionLookup: vec4f=textureSample(refractionCubeSampler,refractionCubeSamplerSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;}\n#else\nvar vRefractionUVW: vec3f= (uniforms.refractionMatrix*(scene.view* vec4f(fragmentInputs.vPositionW+refractionVector*uniforms.vRefractionInfos.z,1.0))).xyz;var refractionCoords: vec2f=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=textureSample(refraction2DSampler,refraction2DSamplerSampler,refractionCoords);\n#endif\n#ifdef RGBDREFRACTION\nrefractionColor=vec4f(fromRGBD(refractionColor),refractionColor.a);\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=vec4f(toGammaSpaceVec3(refractionColor.rgb),refractionColor.a);\n#endif\nrefractionColor=vec4f(refractionColor.rgb*uniforms.vRefractionInfos.x,refractionColor.a);\n#endif\nvar reflectionColor: vec4f= vec4f(0.,0.,0.,1.);\n#ifdef REFLECTION\nvar vReflectionUVW: vec3f=computeReflectionCoords( vec4f(fragmentInputs.vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nvReflectionUVW=vec3f(vReflectionUVW.x,vReflectionUVW.y,vReflectionUVW.z*-1.0);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nvar bias: f32=uniforms.vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureSampleLevel(reflectionCubeSampler,reflectionCubeSamplerSampler,vReflectionUVW,bias);\n#else\nreflectionColor=textureSample(reflectionCubeSampler,reflectionCubeSamplerSampler,vReflectionUVW);\n#endif\n#else\nvar coords: vec2f=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;reflectionColor=textureSample(reflection2DSampler,reflection2DSamplerSampler,coords);\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor=vec4f(fromRGBD(reflectionColor),reflectionColor.a);\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=vec4f(toGammaSpaceVec3(reflectionColor.rgb),reflectionColor.a);\n#endif\nreflectionColor=vec4f(reflectionColor.rgb*uniforms.vReflectionInfos.x,reflectionColor.a);\n#ifdef REFLECTIONFRESNEL\nvar reflectionFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.reflectionRightColor.a,uniforms.reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor=vec4f(reflectionColor.rgb*specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a);\n#else\nreflectionColor=vec4f(reflectionColor.rgb*uniforms.reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a);\n#endif\n#else\nreflectionColor=vec4f(reflectionColor.rgb*uniforms.reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a);\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nvar refractionFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.refractionRightColor.a,uniforms.refractionLeftColor.a);refractionColor=vec4f(refractionColor.rgb*uniforms.refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*uniforms.refractionRightColor.rgb,refractionColor.a);\n#endif\n#ifdef OPACITY\nvar opacityMap: vec4f=textureSample(opacitySampler,opacitySamplerSampler,fragmentInputs.vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap=vec4f(opacityMap.rgb* vec3f(0.3,0.59,0.11),opacityMap.a);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* uniforms.vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*uniforms.vOpacityInfos.y;\n#endif\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=fragmentInputs.vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nvar opacityFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.opacityParts.z,uniforms.opacityParts.w);alpha+=uniforms.opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*uniforms.opacityParts.y;\n#endif\n#ifdef ALPHATEST\n#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS\nif (alpha\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor=vec4f(toLinearSpaceVec3(color.rgb),color.a);\n#else\n#ifdef IMAGEPROCESSING\ncolor=vec4f(toLinearSpaceVec3(color.rgb),color.a);color=applyImageProcessing(color);\n#endif\n#endif\ncolor=vec4f(color.rgb,color.a*mesh.visibility);\n#ifdef PREMULTIPLYALPHA\ncolor=vec4f(color.rgb*color.a, color.a);\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\n#ifdef PREPASS\nvar writeGeometryInfo: f32=select(0.0,1.0,color.a>0.4);var fragData: array,SCENE_MRT_COUNT>;\n#ifdef PREPASS_COLOR\nfragData[PREPASS_COLOR_INDEX]=color; \n#endif\n#ifdef PREPASS_POSITION\nfragData[PREPASS_POSITION_INDEX]=vec4f(fragmentInputs.vPositionW,writeGeometryInfo);\n#endif\n#ifdef PREPASS_LOCAL_POSITION\nfragData[PREPASS_LOCAL_POSITION_INDEX]=vec4f(fragmentInputs.vPosition,writeGeometryInfo);\n#endif\n#ifdef PREPASS_VELOCITY\nvar a: vec2f=(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w)*0.5+0.5;var b: vec2f=(fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w)*0.5+0.5;var velocity: vec2f=abs(a-b);velocity= vec2f(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;fragData[PREPASS_VELOCITY_INDEX]= vec4f(velocity,0.0,writeGeometryInfo);\n#elif defined(PREPASS_VELOCITY_LINEAR)\nvar velocity : vec2f=vec2f(0.5)*((fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w) -\n(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w));fragData[PREPASS_VELOCITY_LINEAR_INDEX]=vec4f(velocity,0.0,writeGeometryInfo);\n#endif\n#ifdef PREPASS_IRRADIANCE\nfragData[PREPASS_IRRADIANCE_INDEX]=vec4f(0.0,0.0,0.0,writeGeometryInfo); \n#endif\n#ifdef PREPASS_DEPTH\nfragData[PREPASS_DEPTH_INDEX]=vec4f(fragmentInputs.vViewPos.z,0.0,0.0,writeGeometryInfo); \n#endif\n#ifdef PREPASS_SCREENSPACE_DEPTH\nfragData[PREPASS_SCREENSPACE_DEPTH_INDEX]=vec4f(fragmentInputs.position.z,0.0,0.0,writeGeometryInfo);\n#endif\n#ifdef PREPASS_NORMAL\n#ifdef PREPASS_NORMAL_WORLDSPACE\nfragData[PREPASS_NORMAL_INDEX]=vec4f(normalW,writeGeometryInfo);\n#else\nfragData[PREPASS_NORMAL_INDEX]=vec4f(normalize((scene.view*vec4f(normalW,0.0)).rgb),writeGeometryInfo);\n#endif\n#endif\n#ifdef PREPASS_WORLD_NORMAL\nfragData[PREPASS_WORLD_NORMAL_INDEX]=vec4f(normalW*0.5+0.5,writeGeometryInfo);\n#endif\n#ifdef PREPASS_ALBEDO\nfragData[PREPASS_ALBEDO_INDEX]=vec4f(baseColor.rgb,writeGeometryInfo);\n#endif\n#ifdef PREPASS_ALBEDO_SQRT\nfragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4f(sqrt(baseColor.rgb),writeGeometryInfo);\n#endif\n#ifdef PREPASS_REFLECTIVITY\n#if defined(SPECULAR)\nfragData[PREPASS_REFLECTIVITY_INDEX]=vec4f(toLinearSpaceVec4(specularMapColor))*writeGeometryInfo; \n#else\nfragData[PREPASS_REFLECTIVITY_INDEX]=vec4f(toLinearSpaceVec3(specularColor),1.0)*writeGeometryInfo;\n#endif\n#endif\n#if SCENE_MRT_COUNT>0\nfragmentOutputs.fragData0=fragData[0];\n#endif\n#if SCENE_MRT_COUNT>1\nfragmentOutputs.fragData1=fragData[1];\n#endif\n#if SCENE_MRT_COUNT>2\nfragmentOutputs.fragData2=fragData[2];\n#endif\n#if SCENE_MRT_COUNT>3\nfragmentOutputs.fragData3=fragData[3];\n#endif\n#if SCENE_MRT_COUNT>4\nfragmentOutputs.fragData4=fragData[4];\n#endif\n#if SCENE_MRT_COUNT>5\nfragmentOutputs.fragData5=fragData[5];\n#endif\n#if SCENE_MRT_COUNT>6\nfragmentOutputs.fragData6=fragData[6];\n#endif\n#if SCENE_MRT_COUNT>7\nfragmentOutputs.fragData7=fragData[7];\n#endif\n#endif\n#if !defined(PREPASS) && !defined(ORDER_INDEPENDENT_TRANSPARENCY)\nfragmentOutputs.color=color;\n#endif\n#include\n#if ORDER_INDEPENDENT_TRANSPARENCY\nif (fragDepth==nearestDepth) {fragmentOutputs.frontColor=vec4f(fragmentOutputs.frontColor.rgb+color.rgb*color.a*alphaMultiplier,1.0-alphaMultiplier*(1.0-color.a));} else {fragmentOutputs.backColor+=color;}\n#endif\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},22177:(e,t,i)=>{"use strict";i.r(t),i.d(t,{defaultVertexShaderWGSL:()=>o});var r=i(69841);i(59051),i(20115),i(87647),i(25589),i(68273),i(41416),i(17894),i(36174),i(30642),i(96760),i(30486),i(86934);r.l.IncludesShadersStoreWGSL.lightVxFragmentDeclaration="#ifdef LIGHT{X}\nuniform vLightData{X}: vec4f;uniform vLightDiffuse{X}: vec4f;\n#ifdef SPECULARTERM\nuniform vLightSpecular{X}: vec4f;\n#else\nvar vLightSpecular{X}: vec4f= vec4f(0.);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform lightMatrix{X}: mat4x4f[SHADOWCSMNUM_CASCADES{X}];varying var vPositionFromLight{X}: vec4f[SHADOWCSMNUM_CASCADES{X}];varying var vDepthMetric{X}: f32[SHADOWCSMNUM_CASCADES{X}];varying var vPositionFromCamera{X}: vec4f;\n#elif defined(SHADOWCUBE{X})\n#else\nvarying var vPositionFromLight{X}: vec4f;varying var vDepthMetric{X}: f32;uniform lightMatrix{X}: mat4x4f;\n#endif\nuniform shadowsInfo{X}: vec4f;uniform depthValues{X}: vec2f;\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vLightDirection{X}: vec4f;uniform vLightFalloff{X}: vec4f;\n#elif defined(POINTLIGHT{X})\nuniform vLightFalloff{X}: vec4f;\n#elif defined(HEMILIGHT{X})\nuniform vLightGround{X}: vec3f;\n#endif\n#endif\n",i(85188),i(47381),i(51148),i(21859),i(8573),i(43610),i(32764),i(40903),i(71281),i(51152),i(80699),i(84326),i(73918),i(57728),i(45184),i(48453),i(42321),i(18201);const s="defaultVertexShader",n="#include\n#define CUSTOM_VERTEX_BEGIN\nattribute position: vec3f;\n#ifdef NORMAL\nattribute normal: vec3f;\n#endif\n#ifdef TANGENT\nattribute tangent: vec4f;\n#endif\n#ifdef UV1\nattribute uv: vec2f;\n#endif\n#include[2..7]\n#ifdef VERTEXCOLOR\nattribute color: vec4f;\n#endif\n#include\n#include\n#include\n#include\n#include\n#include[1..7]\n#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)\n#if defined(SPECULARTERM)\n#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular)\n#endif\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)\nvarying vPositionW: vec3f;\n#ifdef NORMAL\nvarying vNormalW: vec3f;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vColor: vec4f;\n#endif\n#include\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vPositionUVW: vec3f;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vDirectionW: vec3f;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvar positionUpdated: vec3f=vertexInputs.position;\n#ifdef NORMAL\nvar normalUpdated: vec3f=vertexInputs.normal;\n#endif\n#ifdef TANGENT\nvar tangentUpdated: vec4f=vertexInputs.tangent;\n#endif\n#ifdef UV1\nvar uvUpdated: vec2f=vertexInputs.uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvertexOutputs.vPositionUVW=positionUpdated;\n#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include\n#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)\nvertexOutputs.vCurrentPosition=scene.viewProjection*finalWorld*vec4f(positionUpdated,1.0);vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*vec4f(positionUpdated,1.0);\n#endif\n#include\n#include\nvar worldPos: vec4f=finalWorld*vec4f(positionUpdated,1.0);\n#ifdef NORMAL\nvar normalWorld: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvertexOutputs.vNormalW=normalUpdated/ vec3f(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vertexOutputs.vNormalW=normalize(normalWorld*vertexOutputs.vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvertexOutputs.vNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#endif\n#define CUSTOM_VERTEX_UPDATE_WORLDPOS\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {vertexOutputs.position=scene.viewProjection*worldPos;} else {vertexOutputs.position=scene.viewProjectionR*worldPos;}\n#else\nvertexOutputs.position=scene.viewProjection*worldPos;\n#endif\nvertexOutputs.vPositionW= worldPos.xyz;\n#ifdef PREPASS\n#include\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvertexOutputs.vDirectionW=normalize((finalWorld* vec4f(positionUpdated,0.0)).xyz);\n#endif\n#ifndef UV1\nvar uvUpdated: vec2f=vec2f(0.,0.);\n#endif\n#ifdef MAINUV1\nvertexOutputs.vMainUV1=uvUpdated;\n#endif\n#include[2..7]\n#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)\n#if defined(SPECULARTERM)\n#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x)\n#endif\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},66246:(e,t,i)=>{"use strict";i.r(t),i.d(t,{depthPixelShaderWGSL:()=>o});var r=i(69841);i(96140),i(2456),i(76794);const s="depthPixelShader",n="#ifdef ALPHATEST\nvarying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d;\n#endif\n#include\nvarying vDepthMetric: f32;\n#ifdef PACKED\n#include\n#endif\n#ifdef STORE_CAMERASPACE_Z\nvarying vViewPos: vec4f;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#include\n#ifdef ALPHATEST\nif (textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV).a<0.4) {discard;}\n#endif\n#ifdef STORE_CAMERASPACE_Z\n#ifdef PACKED\nfragmentOutputs.color=pack(input.vViewPos.z);\n#else\nfragmentOutputs.color= vec4f(input.vViewPos.z,0.0,0.0,1.0);\n#endif\n#else\n#ifdef NONLINEARDEPTH\n#ifdef PACKED\nfragmentOutputs.color=pack(input.position.z);\n#else\nfragmentOutputs.color= vec4f(input.position.z,0.0,0.0,0.0);\n#endif\n#else\n#ifdef PACKED\nfragmentOutputs.color=pack(input.vDepthMetric);\n#else\nfragmentOutputs.color= vec4f(input.vDepthMetric,0.0,0.0,1.0);\n#endif\n#endif\n#endif\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},61420:(e,t,i)=>{"use strict";i.r(t),i.d(t,{depthVertexShaderWGSL:()=>o});var r=i(69841);i(25589),i(68273),i(47381),i(51148),i(30486),i(41416),i(8573),i(43610),i(32764),i(40903),i(71281),i(57728);const s="depthVertexShader",n="attribute position: vec3f;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform viewProjection: mat4x4f;uniform depthValues: vec2f;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vUV: vec2f;uniform diffuseMatrix: mat4x4f;\n#ifdef UV1\nattribute uv: vec2f;\n#endif\n#ifdef UV2\nattribute uv2: vec2f;\n#endif\n#endif\n#ifdef STORE_CAMERASPACE_Z\nuniform view: mat4x4f;varying vViewPos: vec4f;\n#endif\nvarying vDepthMetric: f32;\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;\n#ifdef UV1\nvar uvUpdated: vec2f=input.uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvar worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);\n#include\nvertexOutputs.position=uniforms.viewProjection*worldPos;\n#ifdef STORE_CAMERASPACE_Z\nvertexOutputs.vViewPos=uniforms.view*worldPos;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric=((-vertexOutputs.position.z+uniforms.depthValues.x)/(uniforms.depthValues.y));\n#else\nvertexOutputs.vDepthMetric=((vertexOutputs.position.z+uniforms.depthValues.x)/(uniforms.depthValues.y));\n#endif\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy;\n#endif\n#ifdef UV2\nvertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(input.uv2,1.0,0.0)).xy;\n#endif\n#endif\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},32472:(e,t,i)=>{"use strict";i.r(t),i.d(t,{depthBoxBlurPixelShaderWGSL:()=>n});const r="depthBoxBlurPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var colorDepth: vec4f=vec4f(0.0);for (var x: i32=-OFFSET; x<=OFFSET; x++) {for (var y: i32=-OFFSET; y<=OFFSET; y++) {colorDepth+=textureSample(textureSampler,textureSamplerSampler,input.vUV+ vec2f(f32(x),f32(y))/uniforms.screenSize);}}\nfragmentOutputs.color=(colorDepth/ f32((OFFSET*2+1)*(OFFSET*2+1)));}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},41289:(e,t,i)=>{"use strict";i.r(t),i.d(t,{depthOfFieldMergePixelShaderWGSL:()=>n});const r="depthOfFieldMergePixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var circleOfConfusionSamplerSampler: sampler;var circleOfConfusionSampler: texture_2d;var blurStep0Sampler: sampler;var blurStep0: texture_2d;\n#if BLUR_LEVEL>0\nvar blurStep1Sampler: sampler;var blurStep1: texture_2d;\n#endif\n#if BLUR_LEVEL>1\nvar blurStep2Sampler: sampler;var blurStep2: texture_2d;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var coc: f32=textureSampleLevel(circleOfConfusionSampler,circleOfConfusionSamplerSampler,input.vUV,0.0).r;\n#if BLUR_LEVEL==0\nvar original: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var blurred0: vec4f=textureSampleLevel(blurStep0,blurStep0Sampler,input.vUV,0.0);fragmentOutputs.color=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL==1\nif(coc<0.5){var original: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);fragmentOutputs.color=mix(original,blurred1,coc/0.5);}else{var blurred0: vec4f=textureSampleLevel(blurStep0,blurStep0Sampler,input.vUV,0.0);var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);fragmentOutputs.color=mix(blurred1,blurred0,(coc-0.5)/0.5);}\n#endif\n#if BLUR_LEVEL==2\nif(coc<0.33){var original: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var blurred2: vec4f=textureSampleLevel(blurStep2,blurStep2Sampler,input.vUV,0.0);fragmentOutputs.color=mix(original,blurred2,coc/0.33);}else if(coc<0.66){var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);var blurred2: vec4f=textureSampleLevel(blurStep2,blurStep2Sampler,input.vUV,0.0);fragmentOutputs.color=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{var blurred0: vec4f=textureSampleLevel(blurStep0,blurStep0Sampler,input.vUV,0.0);var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);fragmentOutputs.color=mix(blurred1,blurred0,(coc-0.66)/0.34);}\n#endif\n}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},63788:(e,t,i)=>{"use strict";i.r(t),i.d(t,{displayPassPixelShaderWGSL:()=>n});const r="displayPassPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var passSamplerSampler: sampler;var passSampler: texture_2d;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(passSampler,passSamplerSampler,input.vUV);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},9574:(e,t,i)=>{"use strict";i.r(t),i.d(t,{extractHighlightsPixelShaderWGSL:()=>o});var r=i(69841);i(87647);const s="extractHighlightsPixelShader",n="#include\nvarying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform threshold: f32;uniform exposure: f32;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);var luma: f32=dot(LuminanceEncodeApprox,fragmentOutputs.color.rgb*uniforms.exposure);fragmentOutputs.color=vec4f(step(uniforms.threshold,luma)*fragmentOutputs.color.rgb,fragmentOutputs.color.a);}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},26879:(e,t,i)=>{"use strict";i.r(t),i.d(t,{filterPixelShaderWGSL:()=>n});const r="filterPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform kernelMatrix: mat4x4f;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var baseColor: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var updatedColor: vec3f=(uniforms.kernelMatrix* vec4f(baseColor,1.0)).rgb;fragmentOutputs.color= vec4f(updatedColor,1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},92862:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingBilateralBlurPixelShaderWGSL:()=>n});const r="fluidRenderingBilateralBlurPixelShader",s="var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform maxFilterSize: i32;uniform blurDir: vec2f;uniform projectedParticleConstant: f32;uniform depthThreshold: f32;varying vUV: vec2f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var depth: f32=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.).x;if (depth>=1e6 || depth<=0.) {fragmentOutputs.color=vec4f(vec3f(depth),1.);return fragmentOutputs;}\nvar filterSize: i32=min(uniforms.maxFilterSize,i32(ceil(uniforms.projectedParticleConstant/depth)));var sigma: f32=f32(filterSize)/3.0;var two_sigma2: f32=2.0*sigma*sigma;var sigmaDepth: f32=uniforms.depthThreshold/3.0;var two_sigmaDepth2: f32=2.0*sigmaDepth*sigmaDepth;var sum: f32=0.;var wsum: f32=0.;var sumVel: f32=0.;for (var x: i32=-filterSize; x<=filterSize; x++) {var coords: vec2f=vec2f(f32(x));var sampleDepthVel: vec2f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV+coords*uniforms.blurDir,0.).rg;var r: f32=dot(coords,coords);var w: f32=exp(-r/two_sigma2);var rDepth: f32=sampleDepthVel.r-depth;var wd: f32=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;}\nfragmentOutputs.color=vec4f(sum/wsum,sumVel/wsum,0.,1.);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},40264:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingParticleDepthPixelShaderWGSL:()=>n});const r="fluidRenderingParticleDepthPixelShader",s="uniform projection: mat4x4f;varying uv: vec2f;varying viewPos: vec3f;varying sphereRadius: f32;\n#ifdef FLUIDRENDERING_VELOCITY\nvarying velocityNorm: f32;\n#endif\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var normalxy: vec2f=input.uv*2.0-1.0;var r2: f32=dot(normalxy,normalxy);if (r2>1.0) {discard;}\nvar normal: vec3f=vec3f(normalxy,sqrt(1.0-r2));\n#ifndef FLUIDRENDERING_RHS\nnormal.z=-normal.z;\n#endif\nvar realViewPos: vec4f=vec4f(input.viewPos+normal*input.sphereRadius,1.0);var clipSpacePos: vec4f=uniforms.projection*realViewPos;fragmentOutputs.fragDepth=clipSpacePos.z/clipSpacePos.w;\n#ifdef FLUIDRENDERING_RHS\nrealViewPos.z=-realViewPos.z;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nfragmentOutputs.color=vec4f(realViewPos.z,input.velocityNorm,0.,1.);\n#else\nfragmentOutputs.color=vec4f(realViewPos.z,0.,0.,1.);\n#endif\n}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},27014:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingParticleDepthVertexShaderWGSL:()=>n});const r="fluidRenderingParticleDepthVertexShader",s="attribute position: vec3f;attribute offset: vec2f;uniform view: mat4x4f;uniform projection: mat4x4f;uniform size: vec2f;varying uv: vec2f;varying viewPos: vec3f;varying sphereRadius: f32;\n#ifdef FLUIDRENDERING_VELOCITY\nattribute velocity: vec3f;varying velocityNorm: f32;\n#endif\n@vertex\nfn main(input: VertexInputs)->FragmentInputs {var cornerPos: vec3f=vec3f(\nvec2f(input.offset.x-0.5,input.offset.y-0.5)*uniforms.size,\n0.0\n);vertexOutputs.viewPos=(uniforms.view*vec4f(input.position,1.0)).xyz;vertexOutputs.position=uniforms.projection*vec4f(vertexOutputs.viewPos+cornerPos,1.0);vertexOutputs.uv=input.offset;vertexOutputs.sphereRadius=uniforms.size.x/2.0;\n#ifdef FLUIDRENDERING_VELOCITY\nvertexOutputs.velocityNorm=length(velocity);\n#endif\n}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},89753:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingParticleDiffusePixelShaderWGSL:()=>n});const r="fluidRenderingParticleDiffusePixelShader",s="uniform particleAlpha: f32;varying uv: vec2f;varying diffuseColor: vec3f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var normalxy: vec2f=input.uv*2.0-1.0;var r2: f32=dot(normalxy,normalxy);if (r2>1.0) {discard;}\nfragmentOutputs.color=vec4f(input.diffuseColor,1.0);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},45261:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingParticleThicknessPixelShaderWGSL:()=>n});const r="fluidRenderingParticleThicknessPixelShader",s="uniform particleAlpha: f32;varying uv: vec2f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var normalxy: vec2f=input.uv*2.0-1.0;var r2: f32=dot(normalxy,normalxy);if (r2>1.0) {discard;}\nvar thickness: f32=sqrt(1.0-r2);fragmentOutputs.color=vec4f(vec3f(uniforms.particleAlpha*thickness),1.0);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},64615:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingParticleThicknessVertexShaderWGSL:()=>n});const r="fluidRenderingParticleThicknessVertexShader",s="attribute position: vec3f;attribute offset: vec2f;uniform view: mat4x4f;uniform projection: mat4x4f;uniform size: vec2f;varying uv: vec2f;@vertex\nfn main(input: VertexInputs)->FragmentInputs {var cornerPos: vec3f=vec3f(\nvec2f(input.offset.x-0.5,input.offset.y-0.5)*uniforms.size,\n0.0\n);var viewPos: vec3f=(uniforms.view*vec4f(input.position,1.0)).xyz+cornerPos;vertexOutputs.position=uniforms.projection*vec4f(viewPos,1.0);vertexOutputs.uv=input.offset;}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},37009:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingRenderPixelShaderWGSL:()=>n});const r="fluidRenderingRenderPixelShader",s="#define DISABLE_UNIFORMITY_ANALYSIS\n#define IOR 1.333\n#define ETA 1.0/IOR\n#define F0 0.02\nvar textureSamplerSampler: sampler;var textureSampler: texture_2d;var depthSamplerSampler: sampler;var depthSampler: texture_2d;\n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nvar diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d;\n#else\nuniform diffuseColor: vec3f;\n#endif\n#ifdef FLUIDRENDERING_FIXED_THICKNESS\nuniform thickness: f32;var bgDepthSamplerSampler: sampler;var bgDepthSampler: texture_2d;\n#else\nuniform minimumThickness: f32;var thicknessSamplerSampler: sampler;var thicknessSampler: texture_2d;\n#endif\n#ifdef FLUIDRENDERING_ENVIRONMENT\nvar reflectionSamplerSampler: sampler;var reflectionSampler: texture_cube;\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nvar debugSamplerSampler: sampler;var debugSampler: texture_2d;\n#endif\nuniform viewMatrix: mat4x4f;uniform projectionMatrix: mat4x4f;uniform invProjectionMatrix: mat4x4f;uniform texelSize: vec2f;uniform dirLight: vec3f;uniform cameraFar: f32;uniform density: f32;uniform refractionStrength: f32;uniform fresnelClamp: f32;uniform specularPower: f32;varying vUV: vec2f;fn computeViewPosFromUVDepth(texCoord: vec2f,depth: f32)->vec3f {var ndc: vec4f=vec4f(texCoord*2.0-1.0,0.0,1.0);\n#ifdef FLUIDRENDERING_RHS\nndc.z=-uniforms.projectionMatrix[2].z+uniforms.projectionMatrix[3].z/depth;\n#else\nndc.z=uniforms.projectionMatrix[2].z+uniforms.projectionMatrix[3].z/depth;\n#endif\nndc.w=1.0;var eyePos: vec4f=uniforms.invProjectionMatrix*ndc;return eyePos.xyz/eyePos.w;}\nfn getViewPosFromTexCoord(texCoord: vec2f)->vec3f {var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);}\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var texCoord: vec2f=input.vUV;\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nvar color: vec4f=textureSample(debugSampler,debugSamplerSampler,texCoord);\n#ifdef FLUIDRENDERING_DEBUG_DEPTH\nfragmentOutputs.color=vec4f(color.rgb/vec3f(2.0),1.);if (color.r>0.999 && color.g>0.999) {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,texCoord);}\n#else\nfragmentOutputs.color=vec4f(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,texCoord);}\n#endif\nreturn fragmentOutputs;\n#endif\nvar depthVel: vec2f=textureSampleLevel(depthSampler,depthSamplerSampler,texCoord,0.).rg;var depth: f32=depthVel.r;\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nvar thickness: f32=textureSample(thicknessSampler,thicknessSamplerSampler,texCoord).x;\n#else\nvar thickness: f32=uniforms.thickness;var bgDepth: f32=textureSample(bgDepthSampler,bgDepthSamplerSampler,texCoord).x;var depthNonLinear: f32=uniforms.projectionMatrix[2].z+uniforms.projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5;\n#endif\nvar backColor: vec4f=textureSample(textureSampler,textureSamplerSampler,texCoord);\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nif (depth>=uniforms.cameraFar || depth<=0. || thickness<=uniforms.minimumThickness) {\n#else\nif (depth>=uniforms.cameraFar || depth<=0. || bgDepth<=depthNonLinear) {\n#endif\n#ifdef FLUIDRENDERING_COMPOSITE_MODE\nfragmentOutputs.color=vec4f(backColor.rgb*backColor.a,backColor.a);\n#else\nfragmentOutputs.color=backColor;\n#endif\nreturn fragmentOutputs;}\nvar viewPos: vec3f=computeViewPosFromUVDepth(texCoord,depth);var ddx: vec3f=getViewPosFromTexCoord(texCoord+vec2f(uniforms.texelSize.x,0.))-viewPos;var ddy: vec3f=getViewPosFromTexCoord(texCoord+vec2f(0.,uniforms.texelSize.y))-viewPos;var ddx2: vec3f=viewPos-getViewPosFromTexCoord(texCoord+vec2f(-uniforms.texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;}\nvar ddy2: vec3f=viewPos-getViewPosFromTexCoord(texCoord+vec2f(0.,-uniforms.texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;}\nvar normal: vec3f=normalize(cross(ddy,ddx));\n#ifdef FLUIDRENDERING_RHS\nnormal=-normal;\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL)\nfragmentOutputs.color=vec4f(normal*0.5+0.5,1.0);return fragmentOutputs;\n#endif\nvar rayDir: vec3f=normalize(viewPos); \n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nvar diffuseColor: vec3f=textureSampleLevel(diffuseSampler,diffuseSamplerSampler,texCoord,0.0).rgb;\n#else\nvar diffuseColor: vec3f=uniforms.diffuseColor;\n#endif\nvar lightDir: vec3f=normalize((uniforms.viewMatrix*vec4f(-uniforms.dirLight,0.)).xyz);var H: vec3f =normalize(lightDir-rayDir);var specular: f32 =pow(max(0.0,dot(H,normal)),uniforms.specularPower);\n#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING\nvar diffuse: f32 =max(0.0,dot(lightDir,normal))*1.0;fragmentOutputs.color=vec4f(vec3f(0.1) /*ambient*/+vec3f(0.42,0.50,1.00)*diffuse+vec3f(0,0,0.2)+specular,1.);return fragmentOutputs;\n#endif\nvar refractionDir: vec3f=refract(rayDir,normal,ETA);var transmitted: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,vec2f(texCoord+refractionDir.xy*thickness*uniforms.refractionStrength),0.0);\n#ifdef FLUIDRENDERING_COMPOSITE_MODE\nif (transmitted.a==0.) {transmitted.a=thickness;}\n#endif\nvar transmittance: vec3f=exp(-uniforms.density*thickness*(1.0-diffuseColor)); \nvar refractionColor: vec3f=transmitted.rgb*transmittance;\n#ifdef FLUIDRENDERING_ENVIRONMENT\nvar reflectionDir: vec3f=reflect(rayDir,normal);var reflectionColor: vec3f=(textureSample(reflectionSampler,reflectionSamplerSampler,reflectionDir).rgb);var fresnel: f32=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,uniforms.fresnelClamp);var finalColor: vec3f=mix(refractionColor,reflectionColor,fresnel)+specular;\n#else\nvar finalColor: vec3f=refractionColor+specular;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nvar velocity: f32=depthVel.g;finalColor=mix(finalColor,vec3f(1.0),smoothstep(0.3,1.0,velocity/6.0));\n#endif\nfragmentOutputs.color=vec4f(finalColor,transmitted.a);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},5769:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fluidRenderingStandardBlurPixelShaderWGSL:()=>n});const r="fluidRenderingStandardBlurPixelShader",s="var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform filterSize: i32;uniform blurDir: vec2f;varying vUV: vec2f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var s: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.);if (s.r==0.) {fragmentOutputs.color=vec4f(0.,0.,0.,1.);return fragmentOutputs;}\nvar sigma: f32=f32(uniforms.filterSize)/3.0;var twoSigma2: f32=2.0*sigma*sigma;var sum: vec4f=vec4f(0.);var wsum: f32=0.;for (var x: i32=-uniforms.filterSize; x<=uniforms.filterSize; x++) {var coords: vec2f=vec2f(f32(x));var sampl: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV+coords*uniforms.blurDir,0.);var w: f32=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;}\nsum/=wsum;fragmentOutputs.color=vec4f(sum.rgb,1.);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},54525:(e,t,i)=>{"use strict";i.r(t),i.d(t,{fxaaPixelShaderWGSL:()=>n});const r="fxaaPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform texelSize: vec2f;varying sampleCoordS: vec2f;varying sampleCoordE: vec2f;varying sampleCoordN: vec2f;varying sampleCoordW: vec2f;varying sampleCoordNW: vec2f;varying sampleCoordSE: vec2f;varying sampleCoordNE: vec2f;varying sampleCoordSW: vec2f;const fxaaQualitySubpix: f32=1.0;const fxaaQualityEdgeThreshold: f32=0.166;const fxaaQualityEdgeThresholdMin: f32=0.0833;const kLumaCoefficients: vec3f= vec3f(0.2126,0.7152,0.0722);fn FxaaLuma(rgba: vec4f)->f32 {return dot(rgba.rgb,kLumaCoefficients);} \n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var posM: vec2f;posM.x=input.vUV.x;posM.y=input.vUV.y;var rgbyM: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var lumaM: f32=FxaaLuma(rgbyM);var lumaS: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordS,0.0));var lumaE: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordE,0.0));var lumaN: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordN,0.0));var lumaW: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordW,0.0));var maxSM: f32=max(lumaS,lumaM);var minSM: f32=min(lumaS,lumaM);var maxESM: f32=max(lumaE,maxSM);var minESM: f32=min(lumaE,minSM);var maxWN: f32=max(lumaN,lumaW);var minWN: f32=min(lumaN,lumaW);var rangeMax: f32=max(maxWN,maxESM);var rangeMin: f32=min(minWN,minESM);var rangeMaxScaled: f32=rangeMax*fxaaQualityEdgeThreshold;var range: f32=rangeMax-rangeMin;var rangeMaxClamped: f32=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range=edgeVert;var subpixA: f32=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan)\n{lumaN=lumaW;}\nif (!horzSpan) \n{lumaS=lumaE;}\nif (horzSpan) \n{lengthSign=uniforms.texelSize.y;}\nvar subpixB: f32=(subpixA*(1.0/12.0))-lumaM;var gradientN: f32=lumaN-lumaM;var gradientS: f32=lumaS-lumaM;var lumaNN: f32=lumaN+lumaM;var lumaSS: f32=lumaS+lumaM;var pairN: bool=abs(gradientN)>=abs(gradientS);var gradient: f32=max(abs(gradientN),abs(gradientS));if (pairN)\n{lengthSign=-lengthSign;}\nvar subpixC: f32=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);var posB: vec2f;posB.x=posM.x;posB.y=posM.y;var offNP: vec2f;offNP.x=select(uniforms.texelSize.x,0.0,(!horzSpan));offNP.y=select(uniforms.texelSize.y,0.0,(horzSpan));if (!horzSpan) \n{posB.x+=lengthSign*0.5;}\nif (horzSpan)\n{posB.y+=lengthSign*0.5;}\nvar posN: vec2f;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;var posP: vec2f;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;var subpixD: f32=((-2.0)*subpixC)+3.0;var lumaEndN: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posN,0.0));var subpixE: f32=subpixC*subpixC;var lumaEndP: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posP,0.0));if (!pairN) \n{lumaNN=lumaSS;}\nvar gradientScaled: f32=gradient*1.0/4.0;var lumaMM: f32=lumaM-lumaNN*0.5;var subpixF: f32=subpixD*subpixE;var lumaMLTZero: bool=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;var doneN: bool=abs(lumaEndN)>=gradientScaled;var doneP: bool=abs(lumaEndP)>=gradientScaled;if (!doneN) \n{posN.x-=offNP.x*3.0;}\nif (!doneN) \n{posN.y-=offNP.y*3.0;}\nvar doneNP: bool=(!doneN) || (!doneP);if (!doneP) \n{posP.x+=offNP.x*3.0;}\nif (!doneP)\n{posP.y+=offNP.y*3.0;}\nif (doneNP)\n{if (!doneN) {lumaEndN=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posN.xy,0.0));}\nif (!doneP) {lumaEndP=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posP.xy,0.0));}\nif (!doneN) {lumaEndN=lumaEndN-lumaNN*0.5;}\nif (!doneP) {lumaEndP=lumaEndP-lumaNN*0.5;}\ndoneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) {posN.x-=offNP.x*12.0;}\nif (!doneN) {posN.y-=offNP.y*12.0;}\ndoneNP=(!doneN) || (!doneP);if (!doneP) {posP.x+=offNP.x*12.0;}\nif (!doneP) {posP.y+=offNP.y*12.0;}}\nvar dstN: f32=posM.x-posN.x;var dstP: f32=posP.x-posM.x;if (!horzSpan)\n{dstN=posM.y-posN.y;}\nif (!horzSpan) \n{dstP=posP.y-posM.y;}\nvar goodSpanN: bool=(lumaEndN<0.0) != lumaMLTZero;var spanLength: f32=(dstP+dstN);var goodSpanP: bool=(lumaEndP<0.0) != lumaMLTZero;var spanLengthRcp: f32=1.0/spanLength;var directionN: bool=dstN{"use strict";i.r(t),i.d(t,{fxaaVertexShaderWGSL:()=>n});const r="fxaaVertexShader",s="attribute position: vec2f;uniform texelSize: vec2f;varying vUV: vec2f;varying sampleCoordS: vec2f;varying sampleCoordE: vec2f;varying sampleCoordN: vec2f;varying sampleCoordW: vec2f;varying sampleCoordNW: vec2f;varying sampleCoordSE: vec2f;varying sampleCoordNE: vec2f;varying sampleCoordSW: vec2f;const madd: vec2f= vec2f(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.vUV=(input.position*madd+madd);vertexOutputs.sampleCoordS=vertexOutputs.vUV+ vec2f( 0.0,1.0)*uniforms.texelSize;vertexOutputs.sampleCoordE=vertexOutputs.vUV+ vec2f( 1.0,0.0)*uniforms.texelSize;vertexOutputs.sampleCoordN=vertexOutputs.vUV+ vec2f( 0.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordW=vertexOutputs.vUV+ vec2f(-1.0,0.0)*uniforms.texelSize;vertexOutputs.sampleCoordNW=vertexOutputs.vUV+ vec2f(-1.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordSE=vertexOutputs.vUV+ vec2f( 1.0,1.0)*uniforms.texelSize;vertexOutputs.sampleCoordNE=vertexOutputs.vUV+ vec2f( 1.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordSW=vertexOutputs.vUV+ vec2f(-1.0,1.0)*uniforms.texelSize;vertexOutputs.position=vec4f(input.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},99407:(e,t,i)=>{"use strict";i.r(t),i.d(t,{gaussianSplattingPixelShaderWGSL:()=>o});var r=i(69841);i(96140),i(21859),i(10668),i(85551),i(31034);r.l.IncludesShadersStoreWGSL.gaussianSplattingFragmentDeclaration="fn gaussianColor(inColor: vec4f,inPosition: vec2f)->vec4f\n{var A : f32=-dot(inPosition,inPosition);if (A>-4.0)\n{var B: f32=exp(A)*inColor.a;\n#include\nvar color: vec3f=inColor.rgb;\n#ifdef FOG\n#include\n#endif\nreturn vec4f(color,B);} else {return vec4f(0.0);}}\n",i(76794);const s="gaussianSplattingPixelShader",n="#include\n#include\n#include\nvarying vColor: vec4f;varying vPosition: vec2f;\n#include\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#include\nfragmentOutputs.color=gaussianColor(input.vColor,input.vPosition);}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},92026:(e,t,i)=>{"use strict";i.r(t),i.d(t,{gaussianSplattingVertexShaderWGSL:()=>o});var r=i(69841);i(14910),i(10598),i(30486),i(86934),i(21859);r.l.IncludesShadersStoreWGSL.gaussianSplatting="fn getDataUV(index: f32,dataTextureSize: vec2f)->vec2 {let y: f32=floor(index/dataTextureSize.x);let x: f32=index-y*dataTextureSize.x;return vec2f((x+0.5),(y+0.5));}\nstruct Splat {center: vec4f,\ncolor: vec4f,\ncovA: vec4f,\ncovB: vec4f,};fn readSplat(splatIndex: f32,dataTextureSize: vec2f)->Splat {var splat: Splat;let splatUV=getDataUV(splatIndex,dataTextureSize);let splatUVi32=vec2(i32(splatUV.x),i32(splatUV.y));splat.center=textureLoad(centersTexture,splatUVi32,0);splat.color=textureLoad(colorsTexture,splatUVi32,0);splat.covA=textureLoad(covariancesATexture,splatUVi32,0)*splat.center.w;splat.covB=textureLoad(covariancesBTexture,splatUVi32,0)*splat.center.w;return splat;}\nfn gaussianSplatting(\nmeshPos: vec2,\nworldPos: vec3,\nscale: vec2,\ncovA: vec3,\ncovB: vec3,\nworldMatrix: mat4x4,\nviewMatrix: mat4x4,\nprojectionMatrix: mat4x4,\nfocal: vec2f,\ninvViewport: vec2f\n)->vec4f {let modelView=viewMatrix*worldMatrix;let camspace=viewMatrix*vec4f(worldPos,1.0);let pos2d=projectionMatrix*camspace;let bounds=1.2*pos2d.w;if (pos2d.z<0. || pos2d.x<-bounds || pos2d.x>bounds || pos2d.y<-bounds || pos2d.y>bounds) {return vec4f(0.0,0.0,2.0,1.0);}\nlet Vrk=mat3x3(\ncovA.x,covA.y,covA.z,\ncovA.y,covB.x,covB.y,\ncovA.z,covB.y,covB.z\n);let J=mat3x3(\nfocal.x/camspace.z,0.0,-(focal.x*camspace.x)/(camspace.z*camspace.z),\n0.0,focal.y/camspace.z,-(focal.y*camspace.y)/(camspace.z*camspace.z),\n0.0,0.0,0.0\n);let invy=mat3x3(\n1.0,0.0,0.0,\n0.0,-1.0,0.0,\n0.0,0.0,1.0\n);let T=invy*transpose(mat3x3(\nmodelView[0].xyz,\nmodelView[1].xyz,\nmodelView[2].xyz))*J;let cov2d=transpose(T)*Vrk*T;let mid=(cov2d[0][0]+cov2d[1][1])/2.0;let radius=length(vec2((cov2d[0][0]-cov2d[1][1])/2.0,cov2d[0][1]));let lambda1=mid+radius;let lambda2=mid-radius;if (lambda2<0.0) {return vec4f(0.0,0.0,2.0,1.0);}\nlet diagonalVector=normalize(vec2(cov2d[0][1],lambda1-cov2d[0][0]));let majorAxis=min(sqrt(2.0*lambda1),1024.0)*diagonalVector;let minorAxis=min(sqrt(2.0*lambda2),1024.0)*vec2(diagonalVector.y,-diagonalVector.x);let vCenter=vec2(pos2d.x,pos2d.y);return vec4f(\nvCenter+((meshPos.x*majorAxis+meshPos.y*minorAxis)*invViewport*pos2d.w)*scale,\npos2d.z,\npos2d.w\n);}\n",i(57728),i(45184),i(18201);const s="gaussianSplattingVertexShader",n="#include\n#include\n#include\n#include\n#include\nattribute splatIndex: f32;attribute position: vec2f;uniform invViewport: vec2f;uniform dataTextureSize: vec2f;uniform focal: vec2f;var covariancesATexture: texture_2d;var covariancesBTexture: texture_2d;var centersTexture: texture_2d;var colorsTexture: texture_2d;varying vColor: vec4f;varying vPosition: vec2f;\n#include\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {var splat: Splat=readSplat(input.splatIndex,uniforms.dataTextureSize);var covA: vec3f=splat.covA.xyz;var covB: vec3f=vec3f(splat.covA.w,splat.covB.xy);let worldPos: vec4f=mesh.world*vec4f(splat.center.xyz,1.0);vertexOutputs.vColor=splat.color;vertexOutputs.vPosition=input.position;vertexOutputs.position=gaussianSplatting(input.position,worldPos.xyz,vec2f(1.0,1.0),covA,covB,mesh.world,scene.view,scene.projection,uniforms.focal,uniforms.invViewport);\n#include\n#include\n#include\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},55745:(e,t,i)=>{"use strict";i.r(t),i.d(t,{geometryPixelShaderWGSL:()=>o});var r=i(69841);i(96140),i(56332),i(87087),i(87647),i(76794),i(99312);const s="geometryPixelShader",n="#ifdef BUMP\nvarying vWorldView0: vec4f;varying vWorldView1: vec4f;varying vWorldView2: vec4f;varying vWorldView3: vec4f;varying vNormalW: vec3f;\n#else\nvarying vNormalV: vec3f;\n#endif\nvarying vViewPos: vec4f;\n#if defined(POSITION) || defined(BUMP)\nvarying vPositionW: vec3f;\n#endif\n#if defined(VELOCITY) || defined(VELOCITY_LINEAR)\nvarying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f;\n#endif\n#ifdef NEED_UV\nvarying vUV: vec2f;\n#endif\n#ifdef BUMP\nuniform vBumpInfos: vec3f;uniform vTangentSpaceParams: vec2f;\n#endif\n#if defined(REFLECTIVITY)\n#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nvar reflectivitySamplerSampler: sampler;var reflectivitySampler: texture_2d;varying vReflectivityUV: vec2f;\n#endif\n#ifdef ALBEDOTEXTURE\nvarying vAlbedoUV: vec2f;var albedoSamplerSampler: sampler;var albedoSampler: texture_2d;\n#endif\n#ifdef REFLECTIVITYCOLOR\nuniform reflectivityColor: vec3f;\n#endif\n#ifdef ALBEDOCOLOR\nuniform albedoColor: vec3f;\n#endif\n#ifdef METALLIC\nuniform metallic: f32;\n#endif\n#if defined(ROUGHNESS) || defined(GLOSSINESS)\nuniform glossiness: f32;\n#endif\n#endif\n#if defined(ALPHATEST) && defined(NEED_UV)\nvar diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d;\n#endif\n#include\n#include\n#include\n#include\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#include\n#ifdef ALPHATEST\nif (textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV).a<0.4) {discard;}\n#endif\nvar normalOutput: vec3f;\n#ifdef BUMP\nvar normalW: vec3f=normalize(input.vNormalW);\n#include\n#ifdef NORMAL_WORLDSPACE\nnormalOutput=normalW;\n#else\nnormalOutput=normalize( vec3f(mat4x4f(input.vWorldView0,input.vWorldView0,input.vWorldView2,input.vWorldView3)* vec4f(normalW,0.0)));\n#endif\n#else\nnormalOutput=normalize(input.vNormalV);\n#endif\n#ifdef ENCODE_NORMAL\nnormalOutput=normalOutput*0.5+0.5;\n#endif\nvar fragData: array,SCENE_MRT_COUNT>;\n#ifdef DEPTH\nfragData[DEPTH_INDEX]=vec4f(input.vViewPos.z/input.vViewPos.w,0.0,0.0,1.0);\n#endif\n#ifdef NORMAL\nfragData[NORMAL_INDEX]=vec4f(normalOutput,1.0);\n#endif\n#ifdef SCREENSPACE_DEPTH\nfragData[SCREENSPACE_DEPTH_INDEX]=vec4f(fragmentInputs.position.z,0.0,0.0,1.0);\n#endif\n#ifdef POSITION\nfragData[POSITION_INDEX]= vec4f(input.vPositionW,1.0);\n#endif\n#ifdef VELOCITY\nvar a: vec2f=(input.vCurrentPosition.xy/input.vCurrentPosition.w)*0.5+0.5;var b: vec2f=(input.vPreviousPosition.xy/input.vPreviousPosition.w)*0.5+0.5;var velocity: vec2f=abs(a-b);velocity= vec2f(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;fragData[VELOCITY_INDEX]= vec4f(velocity,0.0,1.0);\n#endif\n#ifdef VELOCITY_LINEAR\nvar velocity : vec2f=vec2f(0.5)*((input.vPreviousPosition.xy /\ninput.vPreviousPosition.w) -\n(input.vCurrentPosition.xy /\ninput.vCurrentPosition.w));fragData[VELOCITY_LINEAR_INDEX]=vec4f(velocity,0.0,1.0);\n#endif\n#ifdef REFLECTIVITY\nvar reflectivity: vec4f= vec4f(0.0,0.0,0.0,1.0);\n#ifdef METALLICWORKFLOW\nvar metal: f32=1.0;var roughness: f32=1.0;\n#ifdef ORMTEXTURE\nmetal*=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV).b;roughness*=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV).g;\n#endif\n#ifdef METALLIC\nmetal*=uniforms.metallic;\n#endif\n#ifdef ROUGHNESS\nroughness*=(1.0-uniforms.glossiness); \n#endif\nreflectivity=vec4f(reflectivity.rgb,reflectivity.a-roughness);var color: vec3f= vec3f(1.0);\n#ifdef ALBEDOTEXTURE\ncolor=textureSample(albedoSampler,albedoSamplerSampler,input.vAlbedoUV).rgb;\n#ifdef GAMMAALBEDO\ncolor=toLinearSpaceVec4(color);\n#endif\n#endif\n#ifdef ALBEDOCOLOR\ncolor*=uniforms.albedoColor.xyz;\n#endif\nreflectivity=vec4f(mix( vec3f(0.04),color,metal),reflectivity.a);\n#else\n#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nreflectivity=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV);\n#ifdef GAMMAREFLECTIVITYTEXTURE\nreflectivity=vec4f(toLinearSpaceVec3(reflectivity.rgb),reflectivity.a);\n#endif\n#else \n#ifdef REFLECTIVITYCOLOR\nreflectivity=vec4f(toLinearSpaceVec3(uniforms.reflectivityColor.xyz),1.0);\n#endif\n#endif\n#ifdef GLOSSINESSS\nreflectivity=vec4f(reflectivity.rgb,reflectivity.a*glossiness); \n#endif\n#endif\nfragData[REFLECTIVITY_INDEX]=reflectivity;\n#endif\n#if SCENE_MRT_COUNT>0\nfragmentOutputs.fragData0=fragData[0];\n#endif\n#if SCENE_MRT_COUNT>1\nfragmentOutputs.fragData1=fragData[1];\n#endif\n#if SCENE_MRT_COUNT>2\nfragmentOutputs.fragData2=fragData[2];\n#endif\n#if SCENE_MRT_COUNT>3\nfragmentOutputs.fragData3=fragData[3];\n#endif\n#if SCENE_MRT_COUNT>4\nfragmentOutputs.fragData4=fragData[4];\n#endif\n#if SCENE_MRT_COUNT>5\nfragmentOutputs.fragData5=fragData[5];\n#endif\n#if SCENE_MRT_COUNT>6\nfragmentOutputs.fragData6=fragData[6];\n#endif\n#if SCENE_MRT_COUNT>7\nfragmentOutputs.fragData7=fragData[7];\n#endif\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},20267:(e,t,i)=>{"use strict";i.r(t),i.d(t,{geometryVertexShaderWGSL:()=>o});var r=i(69841);i(25589),i(68273),i(47381),i(51148),i(41416),i(14910),i(30486),i(8573),i(43610),i(32764),i(40903),i(71281),i(57728),i(73918);const s="geometryVertexShader",n="#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nattribute position: vec3f;attribute normal: vec3f;\n#ifdef NEED_UV\nvarying vUV: vec2f;\n#ifdef ALPHATEST\nuniform diffuseMatrix: mat4x4f;\n#endif\n#ifdef BUMP\nuniform bumpMatrix: mat4x4f;varying vBumpUV: vec2f;\n#endif\n#ifdef REFLECTIVITY\nuniform reflectivityMatrix: mat4x4f;uniform albedoMatrix: mat4x4f;varying vReflectivityUV: vec2f;varying vAlbedoUV: vec2f;\n#endif\n#ifdef UV1\nattribute uv: vec2f;\n#endif\n#ifdef UV2\nattribute uv2: vec2f;\n#endif\n#endif\n#ifdef BUMP\nvarying vWorldView0: vec4f;varying vWorldView1: vec4f;varying vWorldView2: vec4f;varying vWorldView3: vec4f;\n#endif\n#ifdef BUMP\nvarying vNormalW: vec3f;\n#else\nvarying vNormalV: vec3f;\n#endif\nvarying vViewPos: vec4f;\n#if defined(POSITION) || defined(BUMP)\nvarying vPositionW: vec3f;\n#endif\n#if defined(VELOCITY) || defined(VELOCITY_LINEAR)\nuniform previousViewProjection: mat4x4f;varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;var normalUpdated: vec3f=input.normal;\n#ifdef UV1\nvar uvUpdated: vec2f=input.uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=scene.viewProjection*finalWorld*vec4f(positionUpdated,1.0);vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0);\n#endif\n#include\n#include\nvar worldPos: vec4f= vec4f(finalWorld* vec4f(positionUpdated,1.0));\n#ifdef BUMP\nlet vWorldView=scene.view*finalWorld;vertexOutputs.vWorldView0=vWorldView[0];vertexOutputs.vWorldView1=vWorldView[1];vertexOutputs.vWorldView2=vWorldView[2];vertexOutputs.vWorldView3=vWorldView[3];let normalWorld: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);vertexOutputs.vNormalW=normalize(normalWorld*normalUpdated);\n#else\n#ifdef NORMAL_WORLDSPACE\nvertexOutputs.vNormalV=normalize((finalWorld* vec4f(normalUpdated,0.0)).xyz);\n#else\nvertexOutputs.vNormalV=normalize(((scene.view*finalWorld)* vec4f(normalUpdated,0.0)).xyz);\n#endif\n#endif\nvertexOutputs.vViewPos=scene.view*worldPos;\n#if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED)\nvertexOutputs.vCurrentPosition=scene.viewProjection*finalWorld* vec4f(positionUpdated,1.0);\n#if NUM_BONE_INFLUENCERS>0\nvar previousInfluence: mat4x4f;previousInfluence=mPreviousBones[ i32(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[ i32(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[ i32(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[ i32(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*previousInfluence* vec4f(positionUpdated,1.0);\n#else\nvertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0);\n#endif\n#endif\n#if defined(POSITION) || defined(BUMP)\nvertexOutputs.vPositionW=worldPos.xyz/worldPos.w;\n#endif\nvertexOutputs.position=scene.viewProjection*finalWorld* vec4f(positionUpdated,1.0);\n#include\n#ifdef NEED_UV\n#ifdef UV1\n#if defined(ALPHATEST) && defined(ALPHATEST_UV1)\nvertexOutputs.vUV=(uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy;\n#else\nvertexOutputs.vUV=input.uv;\n#endif\n#ifdef BUMP_UV1\nvertexOutputs.vBumpUV=(uniforms.bumpMatrix* vec4f(uvUpdated,1.0,0.0)).xy;\n#endif\n#ifdef REFLECTIVITY_UV1\nvertexOutputs.vReflectivityUV=(uniforms.reflectivityMatrix* vec4f(uvUpdated,1.0,0.0)).xy;\n#endif\n#ifdef ALBEDO_UV1\nvertexOutputs.vAlbedoUV=(uniforms.albedoMatrix* vec4f(uvUpdated,1.0,0.0)).xy;\n#endif\n#endif\n#ifdef UV2\n#if defined(ALPHATEST) && defined(ALPHATEST_UV2)\nvertexOutputs.vUV=(uniforms.diffuseMatrix* vec4f(input.uv2,1.0,0.0)).xy;\n#else\nvertexOutputs.vUV=input.uv2;\n#endif\n#ifdef BUMP_UV2\nvertexOutputs.vBumpUV=(uniforms.bumpMatrix* vec4f(input.uv2,1.0,0.0)).xy;\n#endif\n#ifdef REFLECTIVITY_UV2\nvertexOutputs.vReflectivityUV=(uniforms.reflectivityMatrix* vec4f(input.uv2,1.0,0.0)).xy;\n#endif\n#ifdef ALBEDO_UV2\nvertexOutputs.vAlbedoUV=(uniforms.albedoMatrix* vec4f(input.uv2,1.0,0.0)).xy;\n#endif\n#endif\n#endif\n#include\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},41368:(e,t,i)=>{"use strict";i.r(t),i.d(t,{glowBlurPostProcessPixelShaderWGSL:()=>n});const r="glowBlurPostProcessPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f;uniform direction: vec2f;uniform blurWidth: f32;fn getLuminance(color: vec3f)->f32\n{return dot(color, vec3f(0.2126,0.7152,0.0722));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var weights: array;weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;var texelSize: vec2f= vec2f(1.0/uniforms.screenSize.x,1.0/uniforms.screenSize.y);var texelStep: vec2f=texelSize*uniforms.direction*uniforms.blurWidth;var start: vec2f=input.vUV-3.0*texelStep;var baseColor: vec4f= vec4f(0.,0.,0.,0.);var texelOffset: vec2f= vec2f(0.,0.);for (var i: i32=0; i<7; i++)\n{var texel: vec4f=textureSample(textureSampler,textureSamplerSampler,start+texelOffset);baseColor=vec4f(baseColor.rgb,baseColor.a+texel.a*weights[i]);var luminance: f32=getLuminance(baseColor.rgb);var luminanceTexel: f32=getLuminance(texel.rgb);var choice: f32=step(luminanceTexel,luminance);baseColor=vec4f(choice*baseColor.rgb+(1.0-choice)*texel.rgb,baseColor.a);texelOffset+=texelStep;}\nfragmentOutputs.color=baseColor;}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},69276:(e,t,i)=>{"use strict";i.r(t),i.d(t,{glowMapGenerationPixelShaderWGSL:()=>o});var r=i(69841);i(87647),i(96140),i(76794);const s="glowMapGenerationPixelShader",n="#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)\n#include\n#endif\n#ifdef DIFFUSE\nvarying vUVDiffuse: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d;\n#endif\n#ifdef OPACITY\nvarying vUVOpacity: vec2f;var opacitySamplerSampler: sampler;var opacitySampler: texture_2d;uniform opacityIntensity: f32;\n#endif\n#ifdef EMISSIVE\nvarying vUVEmissive: vec2f;var emissiveSamplerSampler: sampler;var emissiveSampler: texture_2d;\n#endif\n#ifdef VERTEXALPHA\nvarying vColor: vec4f;\n#endif\nuniform glowColor: vec4f;uniform glowIntensity: f32;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#include\nvar finalColor: vec4f=uniforms.glowColor;\n#ifdef DIFFUSE\nvar albedoTexture: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vUVDiffuse);\n#ifdef DIFFUSE_ISLINEAR\nalbedoTexture=toGammaSpace(albedoTexture);\n#endif\n#ifdef GLOW\nfinalColor=vec4f(finalColor.rgb,finalColor.a*albedoTexture.a);\n#endif\n#ifdef HIGHLIGHT\nfinalColor=vec4f(finalColor.rgb,albedoTexture.a);\n#endif\n#endif\n#ifdef OPACITY\nvar opacityMap: vec4f=textureSample(opacitySampler,opacitySamplerSampler,fragmentInputs.vUVOpacity);\n#ifdef OPACITYRGB\nfinalColor=vec4f(finalColor.rgb,finalColor.a*getLuminance(opacityMap.rgb));\n#else\nfinalColor=vec4f(finalColor.rgb,finalColor.a*opacityMap.a);\n#endif\nfinalColor=vec4f(finalColor.rgb,finalColor.a*uniforms.opacityIntensity);\n#endif\n#ifdef VERTEXALPHA\nfinalColor=vec4f(finalColor.rgb,finalColor.a*fragmentInputs.vColor.a);\n#endif\n#ifdef ALPHATEST\nif (finalColor.a{"use strict";i.r(t),i.d(t,{glowMapGenerationVertexShaderWGSL:()=>o});var r=i(69841);i(25589),i(68273),i(47381),i(51148),i(30486),i(41416),i(8573),i(43610),i(32764),i(40903),i(71281),i(57728);const s="glowMapGenerationVertexShader",n="attribute position: vec3f;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform viewProjection: mat4x4f;varying vPosition: vec4f;\n#ifdef UV1\nattribute uv: vec2f;\n#endif\n#ifdef UV2\nattribute uv2: vec2f;\n#endif\n#ifdef DIFFUSE\nvarying vUVDiffuse: vec2f;uniform diffuseMatrix: mat4x4f;\n#endif\n#ifdef OPACITY\nvarying vUVOpacity: vec2f;uniform opacityMatrix: mat4x4f;\n#endif\n#ifdef EMISSIVE\nvarying vUVEmissive: vec2f;uniform emissiveMatrix: mat4x4f;\n#endif\n#ifdef VERTEXALPHA\nattribute color: vec4f;varying vColor: vec4f;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;\n#ifdef UV1\nvar uvUpdated: vec2f=input.uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvar worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);\n#ifdef CUBEMAP\nvertexOutputs.vPosition=worldPos;vertexOutputs.position=uniforms.viewProjection*finalWorld* vec4f(input.position,1.0);\n#else\nvertexOutputs.vPosition=uniforms.viewProjection*worldPos;vertexOutputs.position=vertexOutputs.vPosition;\n#endif\n#ifdef DIFFUSE\n#ifdef DIFFUSEUV1\nvertexOutputs.vUVDiffuse= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy;\n#endif\n#ifdef DIFFUSEUV2\nvertexOutputs.vUVDiffuse= (uniforms.diffuseMatrix* vec4f(input.uv2,1.0,0.0)).xy;\n#endif\n#endif\n#ifdef OPACITY\n#ifdef OPACITYUV1\nvertexOutputs.vUVOpacity= (uniforms.opacityMatrix* vec4f(uvUpdated,1.0,0.0)).xy;\n#endif\n#ifdef OPACITYUV2\nvertexOutputs.vUVOpacity= (uniforms.opacityMatrix* vec4f(input.uv2,1.0,0.0)).xy;\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvertexOutputs.vUVEmissive= (uniforms.emissiveMatrix* vec4f(uvUpdated,1.0,0.0)).xy;\n#endif\n#ifdef EMISSIVEUV2\nvertexOutputs.vUVEmissive= (uniforms.emissiveMatrix* vec4f(input.uv2,1.0,0.0)).xy;\n#endif\n#endif\n#ifdef VERTEXALPHA\nvertexOutputs.vColor=vertexInputs.color;\n#endif\n#include\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},68940:(e,t,i)=>{"use strict";i.r(t),i.d(t,{glowMapMergePixelShaderWGSL:()=>n});const r="glowMapMergePixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;\n#ifdef EMISSIVE\nvar textureSampler2Sampler: sampler;var textureSampler2: texture_2d;\n#endif\nuniform offset: f32;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvar baseColor: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);\n#ifdef EMISSIVE\nbaseColor+=textureSample(textureSampler2,textureSampler2Sampler,input.vUV);baseColor*=uniforms.offset;\n#else\nbaseColor=vec4f(baseColor.rgb,abs(uniforms.offset-baseColor.a));\n#ifdef STROKE\nvar alpha: f32=smoothstep(.0,.1,baseColor.a);baseColor=vec4f(baseColor.rgb*alpha,alpha);\n#endif\n#endif\n#if LDR\nbaseColor=clamp(baseColor,0.,1.0);\n#endif\nfragmentOutputs.color=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},86010:(e,t,i)=>{"use strict";i.r(t),i.d(t,{glowMapMergeVertexShaderWGSL:()=>n});const r="glowMapMergeVertexShader",s="attribute position: vec2f;varying vUV: vec2f;\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {const madd: vec2f= vec2f(0.5,0.5);\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.vUV=input.position*madd+madd;vertexOutputs.position= vec4f(input.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},35624:(e,t,i)=>{"use strict";i.r(t),i.d(t,{grainPixelShaderWGSL:()=>o});var r=i(69841);i(87647);const s="grainPixelShader",n="#include\nvarying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform intensity: f32;uniform animatedSeed: f32;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);var seed: vec2f=input.vUV*uniforms.animatedSeed;var grain: f32=dither(seed,uniforms.intensity);var lum: f32=getLuminance(fragmentOutputs.color.rgb);var grainAmount: f32=(cos(-PI+(lum*PI*2.))+1.)/2.;fragmentOutputs.color=vec4f(fragmentOutputs.color.rgb+grain*grainAmount,fragmentOutputs.color.a);fragmentOutputs.color=vec4f(max(fragmentOutputs.color.rgb,vec3f(0.0)),fragmentOutputs.color.a);}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},17477:(e,t,i)=>{"use strict";i.r(t),i.d(t,{hdrFilteringPixelShaderWGSL:()=>o});var r=i(69841);i(87647),i(60755),i(20427),i(49335);const s="hdrFilteringPixelShader",n="#include\n#include\n#include\n#include\nuniform alphaG: f32;var inputTextureSampler: sampler;var inputTexture: texture_cube;uniform vFilteringInfo: vec2f;uniform hdrScale: f32;varying direction: vec3f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=radiance(uniforms.alphaG,inputTexture,inputTextureSampler,input.direction,uniforms.vFilteringInfo);fragmentOutputs.color= vec4f(color*uniforms.hdrScale,1.0);}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},44623:(e,t,i)=>{"use strict";i.r(t),i.d(t,{hdrFilteringVertexShaderWGSL:()=>n});const r="hdrFilteringVertexShader",s="attribute position: vec2f;varying direction: vec3f;uniform up: vec3f;uniform right: vec3f;uniform front: vec3f;\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvar view: mat3x3f= mat3x3f(uniforms.up,uniforms.right,uniforms.front);vertexOutputs.direction=view*vec3f(input.position,1.0);vertexOutputs.position= vec4f(input.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},28162:(e,t,i)=>{"use strict";i.r(t),i.d(t,{highlightsPixelShaderWGSL:()=>n});const r="highlightsPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;const RGBLuminanceCoefficients: vec3f= vec3f(0.2126,0.7152,0.0722);\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var tex: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);var c: vec3f=tex.rgb;var luma: f32=dot(c.rgb,RGBLuminanceCoefficients);fragmentOutputs.color= vec4f(pow(c, vec3f(25.0-luma*15.0)),tex.a); }";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},48016:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblCombineVoxelGridsPixelShaderWGSL:()=>n});const r="iblCombineVoxelGridsPixelShader",s="varying vUV: vec2f;var voxelXaxisSamplerSampler: sampler;var voxelXaxisSampler: texture_3d;var voxelYaxisSamplerSampler: sampler;var voxelYaxisSampler: texture_3d;var voxelZaxisSamplerSampler: sampler;var voxelZaxisSampler: texture_3d;uniform layer: f32;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var coordZ: vec3f= vec3f(fragmentInputs.vUV.x,fragmentInputs.vUV.y,uniforms.layer);var voxelZ: f32=textureSample(voxelZaxisSampler,voxelZaxisSamplerSampler,coordZ).r;var coordX: vec3f= vec3f(1.0-uniforms.layer,fragmentInputs.vUV.y,fragmentInputs.vUV.x);var voxelX: f32=textureSample(voxelXaxisSampler,voxelXaxisSamplerSampler,coordX).r;var coordY: vec3f= vec3f(uniforms.layer,fragmentInputs.vUV.x,fragmentInputs.vUV.y);var voxelY: f32=textureSample(voxelYaxisSampler,voxelYaxisSamplerSampler,coordY).r;var voxel=select(0.0,1.0,(voxelX>0.0 || voxelY>0.0 || voxelZ>0.0));fragmentOutputs.color= vec4f( vec3f(voxel),1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},88789:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblGenerateVoxelMipPixelShaderWGSL:()=>n});const r="iblGenerateVoxelMipPixelShader",s="varying vUV: vec2f;var srcMip: texture_3d;uniform layerNum: i32;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var Coords=vec3i(2)*vec3i(vec2i(fragmentInputs.position.xy),uniforms.layerNum);var tex =\n(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(0,0,0),0).x>0.0f))\n<< 0u) |\n(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(1,0,0),0).x>0.0f))\n<< 1u) |\n(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(0,1,0),0).x>0.0f))\n<< 2u) |\n(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(1,1,0),0).x>0.0f))\n<< 3u) |\n(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(0,0,1),0).x>0.0f))\n<< 4u) |\n(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(1,0,1),0).x>0.0f))\n<< 5u) |\n(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(0,1,1),0).x>0.0f))\n<< 6u) |\n(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(1,1,1),0).x>0.0f))\n<< 7u);fragmentOutputs.color=vec4f( f32(tex)/255.0f,0.0f,0.0f,1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},41115:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowAccumulationPixelShaderWGSL:()=>n});const r="iblShadowAccumulationPixelShader",s="varying vUV: vec2f;uniform accumulationParameters: vec4f;\n#define remanence uniforms.accumulationParameters.x\n#define resetb uniforms.accumulationParameters.y\n#define sceneSize uniforms.accumulationParameters.z\nvar motionSampler: texture_2d;var positionSampler: texture_2d;var spatialBlurSampler : texture_2d;var oldAccumulationSamplerSampler: sampler;var oldAccumulationSampler: texture_2d;var prevPositionSamplerSampler: sampler;var prevPositionSampler: texture_2d;fn max2(v: vec2f,w: vec2f)->vec2f { \nreturn vec2f(max(v.x,w.x),max(v.y,w.y)); }\nfn lessThan(x: vec2f,y: vec2f)->vec2 {return xFragmentOutputs {var reset: bool= bool(resetb);var gbufferRes : vec2f=vec2f(textureDimensions(positionSampler,0));var gbufferPixelCoord: vec2i= vec2i(input.vUV*gbufferRes);var shadowRes : vec2f=vec2f(textureDimensions(spatialBlurSampler,0));var shadowPixelCoord: vec2i= vec2i(input.vUV*shadowRes);var LP: vec4f=textureLoad(positionSampler,gbufferPixelCoord,0);if (0.0==LP.w) {fragmentOutputs.color=vec4f(1.0,0.0,0.0,1.0);return fragmentOutputs;}\nvar velocityColor: vec2f=textureLoad(motionSampler,gbufferPixelCoord,0).xy;var prevCoord: vec2f=input.vUV+velocityColor;var PrevLP: vec3f=textureSampleLevel(prevPositionSampler,prevPositionSamplerSampler,prevCoord,0.0).xyz;var PrevShadows: vec3f=textureSampleLevel(oldAccumulationSampler,oldAccumulationSamplerSampler,prevCoord,0.0).xyz;var newShadows : vec2f=textureLoad(spatialBlurSampler,shadowPixelCoord,0).xy;PrevShadows.z=select(1.0,max(PrevShadows.z/(1.0+PrevShadows.z),1.0-remanence),!reset && all(lessThan(abs(prevCoord- vec2f(0.5)), vec2f(0.5))) &&\ndistance(LP.xyz,PrevLP)<5e-2*sceneSize);PrevShadows=max( vec3f(0.0),PrevShadows);fragmentOutputs.color= vec4f(mix(PrevShadows.x,newShadows.x,PrevShadows.z),\nmix(PrevShadows.y,newShadows.y,PrevShadows.z),PrevShadows.z,1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},65461:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowDebugPixelShaderWGSL:()=>n});const r="iblShadowDebugPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var debugSamplerSampler: sampler;var debugSampler: texture_2d;uniform sizeParams: vec4f;\n#define offsetX uniforms.sizeParams.x\n#define offsetY uniforms.sizeParams.y\n#define widthScale uniforms.sizeParams.z\n#define heightScale uniforms.sizeParams.w\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var uv: vec2f =\nvec2f((offsetX+fragmentInputs.vUV.x)*widthScale,(offsetY+fragmentInputs.vUV.y)*heightScale);var background: vec4f=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.vUV);var debugColour: vec4f=textureSample(debugSampler,debugSamplerSampler,fragmentInputs.vUV);if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {fragmentOutputs.color=background;} else {fragmentOutputs.color=vec4f(mix(debugColour.rgb,background.rgb,0.0),1.0);}}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},23008:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowGBufferDebugPixelShaderWGSL:()=>n});const r="iblShadowGBufferDebugPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var depthSampler: sampler;var depthTexture: texture_2d;var normalSampler: sampler;var normalTexture: texture_2d;var positionSampler: sampler;var positionTexture: texture_2d;var velocitySampler: sampler;var velocityTexture: texture_2d;uniform sizeParams: vec4f;uniform maxDepth: f32;\n#define offsetX uniforms.sizeParams.x\n#define offsetY uniforms.sizeParams.y\n#define widthScale uniforms.sizeParams.z\n#define heightScale uniforms.sizeParams.w\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var uv: vec2f =\nvec2f((offsetX+input.vUV.x)*widthScale,(offsetY+input.vUV.y)*heightScale);var backgroundColour: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgba;var depth: vec4f=textureSample(depthTexture,depthSampler,input.vUV);var worldNormal: vec4f=textureSample(normalTexture,normalSampler,input.vUV);var worldPosition: vec4f=textureSample(positionTexture,positionSampler,input.vUV);var velocityLinear: vec4f=textureSample(velocityTexture,velocitySampler,input.vUV);if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {fragmentOutputs.color=backgroundColour;} else {if (uv.x<=0.25) {fragmentOutputs.color=vec4f(depth.rgb,1.0);} else if (uv.x<=0.5) {velocityLinear=vec4f(velocityLinear.r*0.5+0.5,velocityLinear.g*0.5+0.5,velocityLinear.b,velocityLinear.a);fragmentOutputs.color=vec4f(velocityLinear.rgb,1.0);} else if (uv.x<=0.75) {fragmentOutputs.color=vec4f(worldPosition.rgb,1.0);} else {fragmentOutputs.color=vec4f(worldNormal.rgb,1.0);}}}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},45647:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowSpatialBlurPixelShaderWGSL:()=>n});const r="iblShadowSpatialBlurPixelShader",s="#define PI 3.1415927\nvarying vUV: vec2f;var depthSampler: texture_2d;var worldNormalSampler: texture_2d;var voxelTracingSampler : texture_2d;uniform blurParameters: vec4f;\n#define stridef uniforms.blurParameters.x\n#define worldScale uniforms.blurParameters.y\nconst weights=array(0.0625,0.25,0.375,0.25,0.0625);const nbWeights: i32=5;fn max2(v: vec2f,w: vec2f)->vec2f {return vec2f(max(v.x,w.x),max(v.y,w.y));}\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var gbufferRes=vec2f(textureDimensions(depthSampler,0));var gbufferPixelCoord= vec2i(fragmentInputs.vUV*gbufferRes);var shadowRes=vec2f(textureDimensions(voxelTracingSampler,0));var shadowPixelCoord= vec2i(fragmentInputs.vUV*shadowRes);var N: vec3f=textureLoad(worldNormalSampler,gbufferPixelCoord,0).xyz;if (length(N)<0.01) {fragmentOutputs.color=vec4f(1.0,1.0,0.0,1.0);return fragmentOutputs;}\nvar depth: f32=-textureLoad(depthSampler,gbufferPixelCoord,0).x;var X: vec3f= vec3f(0.0);for(var y: i32=0; y>1),y-(nbWeights>>1));var shadowCoords: vec2i=shadowPixelCoord+i32(stridef)*vec2i(x-(nbWeights>>1),y-(nbWeights>>1));var T : vec2f=textureLoad(voxelTracingSampler,shadowCoords,0).xy;var ddepth: f32=-textureLoad(depthSampler,gBufferCoords,0).x-depth;var dN: vec3f=textureLoad(worldNormalSampler,gBufferCoords,0).xyz-N;var w: f32=weights[x]*weights[y] *\nexp2(max(-1000.0/(worldScale*worldScale),-0.5) *\n(ddepth*ddepth) -\n1e1*dot(dN,dN));X+= vec3f(w*T.x,w*T.y,w);}}\nfragmentOutputs.color= vec4f(X.x/X.z,X.y/X.z,0.0,1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},35680:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowVoxelTracingPixelShaderWGSL:()=>n});const r="iblShadowVoxelTracingPixelShader",s="#define PI 3.1415927\nvarying vUV: vec2f;\n#define DISABLE_UNIFORMITY_ANALYSIS\nvar depthSampler: texture_2d;var worldNormalSampler : texture_2d;var blueNoiseSampler: texture_2d;var icdfxSamplerSampler: sampler;var icdfxSampler: texture_2d;var icdfySamplerSampler: sampler;var icdfySampler: texture_2d;var voxelGridSamplerSampler: sampler;var voxelGridSampler: texture_3d;uniform shadowParameters: vec4f;\n#define SHADOWdirs uniforms.shadowParameters.x\n#define SHADOWframe uniforms.shadowParameters.y\n#define SHADOWenvRot uniforms.shadowParameters.w\nuniform voxelBiasParameters : vec4f;\n#define highestMipLevel uniforms.voxelBiasParameters.z\nuniform sssParameters: vec4f;\n#define SSSsamples uniforms.sssParameters.x\n#define SSSstride uniforms.sssParameters.y\n#define SSSmaxDistance uniforms.sssParameters.z\n#define SSSthickness uniforms.sssParameters.w\nuniform shadowOpacity: vec4f;uniform projMtx: mat4x4f;uniform viewMtx: mat4x4f;uniform invProjMtx: mat4x4f;uniform invViewMtx: mat4x4f;uniform wsNormalizationMtx: mat4x4f;uniform invVPMtx: mat4x4f;\n#define PI 3.1415927\n#define GOLD 0.618034\nstruct AABB3f {m_min: vec3f,\nm_max: vec3f,};struct Ray {orig: vec3f,\ndir: vec3f,\ndir_rcp: vec3f,\nt_min: f32,\nt_max: f32,};fn make_ray(origin: vec3f,direction: vec3f,tmin: f32,\ntmax: f32)->Ray {var ray: Ray;ray.orig=origin;ray.dir=direction;ray.dir_rcp=1.0f/direction;ray.t_min=tmin;ray.t_max=tmax;return ray;}\nfn ray_box_intersection(aabb: AABB3f,ray: Ray ,\ndistance_near: ptr,distance_far: ptr)->bool{var tbot: vec3f=ray.dir_rcp*(aabb.m_min-ray.orig);var ttop: vec3f=ray.dir_rcp*(aabb.m_max-ray.orig);var tmin: vec3f=min(ttop,tbot);var tmax: vec3f=max(ttop,tbot);*distance_near=max(ray.t_min,max(tmin.x,max(tmin.y,tmin.z)));*distance_far=min(ray.t_max,min(tmax.x,min(tmax.y,tmax.z)));return *distance_near<=*distance_far;}\n#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nstruct VoxelMarchDiagnosticInfo {heat: f32,\nvoxel_intersect_coords: vec3i,};\n#endif\nfn hash(i: u32)->u32 {var temp=i ^ (i>>16u);temp*=0x7FEB352Du;temp ^= temp>>15u;temp*=0x846CA68Bu;temp ^= temp>>16u;return temp;}\nfn uintBitsToFloat(x: u32)->f32 {return bitcast(x);}\nfn uint2float(i: u32)->f32 {return uintBitsToFloat(0x3F800000u | (i>>9u))-1.0;}\nfn uv_to_normal(uv: vec2f)->vec3f {var N: vec3f;var uvRange: vec2f=uv;var theta: f32=uvRange.x*2.0*PI;var phi: f32=uvRange.y*PI;N.x=cos(theta)*sin(phi);N.z=sin(theta)*sin(phi);N.y=cos(phi);return N;}\nfn plasticSequence(rstate: u32)->vec2f {return vec2f(uint2float(rstate*3242174889u),\nuint2float(rstate*2447445414u));}\nfn goldenSequence(rstate: u32)->f32 {return uint2float(rstate*2654435769u);}\nfn distanceSquared(a: vec2f,b: vec2f)->f32 {var diff: vec2f=a-b;return dot(diff,diff);}\nfn genTB(N: vec3f,T: ptr,B: ptr) {var s: f32=select(1.0,-1.0,N.z<0.0);var a: f32=-1.0/(s+N.z);var b: f32=N.x*N.y*a;*T= vec3f(1.0+s*N.x*N.x*a,s*b,-s*N.x);*B= vec3f(b,s+N.y*N.y*a,-N.y);}\nfn lessThan(x: vec3f,y: vec3f)->vec3 {return x)->bool {\n#else\nfn anyHitVoxels(ray_vs: Ray)->bool {\n#endif\nvar stack=array(); \nvar invD: vec3f=ray_vs.dir_rcp;var D: vec3f=ray_vs.dir;var O: vec3f=ray_vs.orig;var negD=vec3i(lessThan(D, vec3f(0,0,0)));var voxel0: i32=negD.x | (negD.y<<1) | (negD.z<<2);var t0: vec3f=-O*invD;var t1=(vec3f(1.0)-O)*invD;var maxLod: i32= i32(highestMipLevel);var stackLevel: i32=0;\n#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nvar steps: u32=0u;\n#endif\nstack[stackLevel]=maxLod<<24;stackLevel++;while (stackLevel>0) {stackLevel=stackLevel-1;var elem: i32=stack[stackLevel];var Coords: vec4i =\nvec4i(elem & 0xFF,(elem>>8) & 0xFF,(elem>>16) & 0xFF,elem>>24);if (Coords.w==0) {\n#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\n*voxel_march_diagnostic_info.heat= f32(steps)/24.0;\n#endif\nreturn true;}\n#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\n++steps;\n#endif\nvar invRes: f32=exp2(f32(Coords.w-maxLod));var bbmin: vec3f=invRes*vec3f(Coords.xyz+negD);var bbmax: vec3f=invRes*vec3f(Coords.xyz-negD+vec3i(1));var mint: vec3f=mix(t0,t1,bbmin);var maxt: vec3f=mix(t0,t1,bbmax);var midt: vec3f=0.5*(mint+maxt);mint.x=max(0.0,mint.x);midt.x=max(0.0,midt.x);var nodeMask: u32= u32(\nround(textureLoad(voxelGridSampler,Coords.xyz,Coords.w).x*255.0));Coords.w--;var voxelBit: u32=u32(voxel0);Coords=vec4i((Coords.xyz<f32 {return (near*far)/(far-depth*(far-near));}\nfn screenSpaceShadow(csOrigin: vec3f,csDirection: vec3f,csZBufferSize: vec2f,\nnearPlaneZ: f32,farPlaneZ: f32,noise: f32)->f32 {\n#ifdef RIGHT_HANDED\nvar csZDir : f32=-1.0;\n#else \nvar csZDir : f32=1.0;\n#endif\nvar ssSamples: f32=SSSsamples;var ssMaxDist: f32=SSSmaxDistance;var ssStride: f32=SSSstride;var ssThickness: f32=SSSthickness;var rayLength: f32 =\nselect(ssMaxDist,(nearPlaneZ-csOrigin.z)/csDirection.z,\ncsZDir*(csOrigin.z+ssMaxDist*csDirection.z)0.0 && stepCount)->f32 {\n#else\nfn voxelShadow(wsOrigin: vec3f,wsDirection: vec3f,wsNormal: vec3f,\nDitherNoise: vec2f)->f32 {\n#endif\nvar vxResolution: f32=f32(textureDimensions(voxelGridSampler,0).x);var T: vec3f;var B: vec3f;genTB(wsDirection,&T,&B);var DitherXY: vec2f=sqrt(DitherNoise.x)* vec2f(cos(2.0*PI*DitherNoise.y),\nsin(2.0*PI*DitherNoise.y));var Dithering : vec3f=(uniforms.voxelBiasParameters.x*wsNormal +\nuniforms.voxelBiasParameters.y*wsDirection +\nDitherXY.x*T+DitherXY.y*B) /\nvxResolution;var O: vec3f=0.5*wsOrigin+0.5+Dithering;var ray_vs=make_ray(O,wsDirection,0.0,10.0);var voxel_aabb: AABB3f;voxel_aabb.m_min=vec3f(0);voxel_aabb.m_max=vec3f(1);var near: f32=0;var far: f32=0;if (!ray_box_intersection(voxel_aabb,ray_vs,&near,&far)) {return 0.0;}\nray_vs.t_min=max(ray_vs.t_min,near);ray_vs.t_max=min(ray_vs.t_max,far);\n#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nreturn select(0.0f,1.0f,anyHitVoxels(ray_vs,voxel_march_diagnostic_info));\n#else\nreturn select(0.0f,1.0f,anyHitVoxels(ray_vs));\n#endif\n}\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var nbDirs=u32(SHADOWdirs);var frameId=u32(SHADOWframe);var envRot: f32=SHADOWenvRot;var Resolution: vec2f= vec2f(textureDimensions(depthSampler,0));var currentPixel=vec2i(fragmentInputs.vUV*Resolution);var GlobalIndex =\n(frameId*u32(Resolution.y)+u32(currentPixel.y))*u32(Resolution.x) +\nu32(currentPixel.x);var N : vec3f=textureLoad(worldNormalSampler,currentPixel,0).xyz;if (length(N)<0.01) {fragmentOutputs.color=vec4f(1.0,1.0,0.0,1.0);return fragmentOutputs;}\nvar normalizedRotation: f32=envRot/(2.0*PI);var depth : f32=textureLoad(depthSampler,currentPixel,0).x;\n#ifndef IS_NDC_HALF_ZRANGE\ndepth=depth*2.0-1.0;\n#endif\nvar temp : vec2f=(vec2f(currentPixel)+vec2f(0.5))*2.0/Resolution -\nvec2f(1.0);var VP : vec4f=uniforms.invProjMtx*vec4f(temp.x,-temp.y,depth,1.0);VP/=VP.w;N=normalize(N);var noise\n: vec3f =\ntextureLoad(blueNoiseSampler,currentPixel & vec2i(0xFF),0).xyz;noise.z=fract(noise.z+goldenSequence(frameId*nbDirs));\n#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nvar heat: f32=0.0f;\n#endif\nvar shadowAccum: f32=0.0;var specShadowAccum: f32=0.0;var sampleWeight : f32=0;for (var i: u32=0; iedge_tint_const) {var VP2: vec4f=VP;VP2.y*=-1.0;var unormWP : vec4f=uniforms.invViewMtx*VP2;var WP: vec3f=(uniforms.wsNormalizationMtx*unormWP).xyz;var vxNoise: vec2f =\nvec2f(uint2float(hash(dirId*2)),uint2float(hash(dirId*2+1)));\n#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nVoxelMarchDiagnosticInfo voxel_march_diagnostic_info;opacity=max(opacity,\nuniforms.shadowOpacity.x*voxelShadow(WP,L.xyz,N,vxNoise,\nvoxel_march_diagnostic_info));heat+=voxel_march_diagnostic_info.heat;\n#else\nopacity =\nmax(opacity,uniforms.shadowOpacity.x*voxelShadow(WP,L.xyz,N,vxNoise));\n#endif\nvar VL : vec3f=(uniforms.viewMtx*L).xyz;\n#ifdef RIGHT_HANDED\nvar nearPlaneZ: f32=-2.0*uniforms.projMtx[3][2]/(uniforms.projMtx[2][2]-1.0); \nvar farPlaneZ: f32=-uniforms.projMtx[3][2]/(uniforms.projMtx[2][2]+1.0);\n#else\nvar nearPlaneZ: f32=-2.0*uniforms.projMtx[3][2]/(uniforms.projMtx[2][2]+1.0); \nvar farPlaneZ: f32=-uniforms.projMtx[3][2]/(uniforms.projMtx[2][2]-1.0);\n#endif\nvar ssShadow: f32=uniforms.shadowOpacity.y *\nscreenSpaceShadow(VP2.xyz,VL,Resolution,nearPlaneZ,farPlaneZ,\nabs(2.0*noise.z-1.0));opacity=max(opacity,ssShadow);shadowAccum+=min(1.0-opacity,cosNL);sampleWeight+=cosNL;var VR : vec3f=-(uniforms.viewMtx*vec4f(reflect(-L.xyz,N),0.0)).xyz;specShadowAccum+=max(1.0-(opacity*pow(VR.z,8.0)),0.0);}\nnoise.z=fract(noise.z+GOLD);}\n#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION\nfragmentOutputs.color =\nvec4f(shadowAccum/sampleWeight,specShadowAccum/sampleWeight,heat/sampleWeight,1.0);\n#else\nfragmentOutputs.color=vec4f(shadowAccum/sampleWeight,specShadowAccum/sampleWeight,0.0,1.0);\n#endif\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},43572:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowsCdfxPixelShaderWGSL:()=>n});const r="iblShadowsCdfxPixelShader",s="#define PI 3.1415927\nvarying vUV: vec2f;var cdfy: texture_2d;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var cdfyRes=textureDimensions(cdfy,0);var currentPixel=vec2u(fragmentInputs.position.xy);var cdfx: f32=0.0;for (var x: u32=1; x<=currentPixel.x; x++) {cdfx+=textureLoad(cdfy, vec2u(x-1,cdfyRes.y-1),0).x;}\nfragmentOutputs.color= vec4f( vec3f(cdfx),1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},85917:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowsCdfyPixelShaderWGSL:()=>n});const r="iblShadowsCdfyPixelShader",s="#define PI 3.1415927\nvarying vUV: vec2f;\n#ifdef IBL_USE_CUBE_MAP\nvar iblSourceSampler: sampler;var iblSource: texture_cube;\n#else\nvar iblSourceSampler: sampler;var iblSource: texture_2d;\n#endif\nuniform iblHeight: i32;\n#ifdef IBL_USE_CUBE_MAP\nfn equirectangularToCubemapDirection(uv: vec2f)->vec3f {var longitude: f32=uv.x*2.0*PI-PI;var latitude: f32=PI*0.5-uv.y*PI;var direction: vec3f;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;}\nfn fetchCube(uv: vec2f)->f32 {var direction: vec3f=equirectangularToCubemapDirection(uv);return sin(PI*uv.y)*dot(textureSampleLevel(iblSource,iblSourceSampler,direction,0.0).rgb,\nvec3f(0.3,0.6,0.1));}\n#else\nfn fetchPanoramic(Coords: vec2i,envmapHeight: f32)->f32 {return sin(PI*( f32(Coords.y)+0.5)/envmapHeight) *\ndot(textureLoad(iblSource,Coords,0).rgb, vec3f(0.3,0.6,0.1));}\n#endif\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var coords: vec2i= vec2i(fragmentInputs.position.xy);var cdfy: f32=0.0;for (var y: i32=1; y<=coords.y; y++) {\n#ifdef IBL_USE_CUBE_MAP\nvar uv: vec2f= vec2f(input.vUV.x,( f32(y-1)+0.5)/ f32(uniforms.iblHeight));cdfy+=fetchCube(uv);\n#else\ncdfy+=fetchPanoramic( vec2i(coords.x,y-1), f32(uniforms.iblHeight));\n#endif\n}\nfragmentOutputs.color= vec4f(cdfy,0.0,0.0,1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},38957:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowsIcdfxPixelShaderWGSL:()=>n});const r="iblShadowsIcdfxPixelShader",s="#define PI 3.1415927\nvarying vUV: vec2f;var cdfx: texture_2d;fn fetchCDF(x: u32)->f32 {return textureLoad(cdfx, vec2u(x,0),0).x;}\nfn bisect(size: u32,targetValue: f32)->f32\n{var a: u32=0;var b=size-1;while (b-a>1) {var c: u32=(a+b)>>1;if (fetchCDF(c)FragmentOutputs {var cdfSize: vec2u=textureDimensions(cdfx,0);var cdfWidth: u32=cdfSize.x;var icdfWidth: u32=cdfWidth-1;var currentPixel: vec2u= vec2u(fragmentInputs.position.xy);if (currentPixel.x==0)\n{fragmentOutputs.color= vec4f(0.0);}\nelse if (currentPixel.x==icdfWidth-1) {fragmentOutputs.color= vec4f(1.0);} else {var targetValue: f32=fetchCDF(cdfWidth-1)*input.vUV.x;fragmentOutputs.color= vec4f( vec3f(bisect(cdfWidth,targetValue)),1.0);}}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},27844:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowsIcdfyPixelShaderWGSL:()=>n});const r="iblShadowsIcdfyPixelShader",s="#define PI 3.1415927\nvarying vUV: vec2f;var cdfy: texture_2d;fn fetchCDF(y: u32,invocationId: u32)->f32 {return textureLoad(cdfy, vec2u(invocationId,y),0).x;}\nfn bisect(size: u32,targetValue: f32,invocationId: u32)->f32\n{var a: u32=0;var b=size-1;while (b-a>1) {var c=(a+b)>>1;if (fetchCDF(c,invocationId)FragmentOutputs {var cdfSize: vec2u=textureDimensions(cdfy,0);var cdfHeight: u32=cdfSize.y;var currentPixel: vec2u= vec2u(fragmentInputs.position.xy);if (currentPixel.y==0) {fragmentOutputs.color= vec4f(0.0);}\nelse if (currentPixel.y==cdfHeight-2) {fragmentOutputs.color= vec4f(1.0);} else {var targetValue: f32=fetchCDF(cdfHeight-1,currentPixel.x)*input.vUV.y;fragmentOutputs.color= vec4f( vec3f(bisect(cdfHeight,targetValue,currentPixel.x)),1.0);}}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},78685:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblShadowsImportanceSamplingDebugPixelShaderWGSL:()=>n});const r="iblShadowsImportanceSamplingDebugPixelShader",s="#define PI 3.1415927\nvarying vUV: vec2f;var cdfySampler: sampler;var cdfy: texture_2d;var icdfySampler: sampler;var icdfy: texture_2d;var cdfxSampler: sampler;var cdfx: texture_2d;var icdfxSampler: sampler;var icdfx: texture_2d;\n#ifdef IBL_USE_CUBE_MAP\nvar iblSourceSampler: sampler;var iblSource: texture_cube;\n#else\nvar iblSourceSampler: sampler;var iblSource: texture_2d;\n#endif\nvar textureSamplerSampler: sampler;var textureSampler: texture_2d;\n#define cdfyVSize 0.4\n#define cdfxVSize 0.1\n#define cdfyHSize 0.5\nuniform sizeParams: vec4f;\n#ifdef IBL_USE_CUBE_MAP\nfn equirectangularToCubemapDirection(uv: vec2f)->vec3f {var longitude: f32=uv.x*2.0*PI-PI;var latitude: f32=PI*0.5-uv.y*PI;var direction: vec3f;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;}\n#endif\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs { \nvar colour: vec3f= vec3f(0.0);var uv: vec2f =\nvec2f((uniforms.sizeParams.x+input.vUV.x)*uniforms.sizeParams.z,(uniforms.sizeParams.y+input.vUV.y)*uniforms.sizeParams.w);var backgroundColour: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;const iblStart: f32=1.0-cdfyVSize;const cdfyStart: f32=1.0-2.0*cdfyVSize;const cdfxStart: f32=1.0-2.0*cdfyVSize-cdfxVSize;const icdfxStart: f32=1.0-2.0*cdfyVSize-2.0*cdfxVSize;\n#ifdef IBL_USE_CUBE_MAP\nvar direction: vec3f=equirectangularToCubemapDirection(\n(uv- vec2f(0.0,iblStart))* vec2f(1.0,1.0/cdfyVSize));var iblColour: vec3f=textureSampleLevel(iblSource,iblSourceSampler,direction,0.0).rgb;\n#else\nvar iblColour: vec3f=textureSample(iblSource,iblSourceSampler,(uv- vec2f(0.0,iblStart)) *\nvec2f(1.0,1.0/cdfyVSize))\n.rgb;\n#endif\nvar cdfyColour: f32 =\ntextureSample(cdfy,cdfySampler,(uv- vec2f(0.0,cdfyStart))* vec2f(2.0,1.0/cdfyVSize)).r;var icdfyColour: f32 =\ntextureSample(icdfy,icdfySampler,(uv- vec2f(0.5,cdfyStart))* vec2f(2.0,1.0/cdfyVSize)).r;var cdfxColour: f32 =\ntextureSample(cdfx,cdfxSampler,(uv- vec2f(0.0,cdfxStart))* vec2f(1.0,1.0/cdfxVSize)).r;var icdfxColour: f32=textureSample(icdfx,icdfxSampler,(uv- vec2f(0.0,icdfxStart)) *\nvec2f(1.0,1.0/cdfxVSize)).r;if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {colour=backgroundColour;} else if (uv.y>iblStart) {colour+=iblColour;} else if (uv.y>cdfyStart && uv.x<0.5) {colour.r+=0.003*cdfyColour;} else if (uv.y>cdfyStart && uv.x>0.5) {colour.r+=icdfyColour;} else if (uv.y>cdfxStart) {colour.r+=0.00003*cdfxColour;} else if (uv.y>icdfxStart) {colour.r+=icdfxColour;}\nfragmentOutputs.color =vec4(mix(colour,backgroundColour,0.5),1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},75904:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblVoxelGridPixelShaderWGSL:()=>n});const r="iblVoxelGridPixelShader",s="varying vNormalizedPosition: vec3f;uniform nearPlane: f32;uniform farPlane: f32;uniform stepSize: f32;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var normPos: vec3f=input.vNormalizedPosition.xyz;if (normPos.zuniforms.farPlane) {discard;}\nfragmentOutputs.fragData0=select(vec4f(0.0),vec4f(1.0),normPos.z=uniforms.nearPlane+uniforms.stepSize && normPos.z=uniforms.nearPlane+2.0*uniforms.stepSize && normPos.z=uniforms.nearPlane+3.0*uniforms.stepSize && normPos.z4\nfragmentOutputs.fragData4=select(vec4f(0.0),vec4f(1.0),normPos.z>=uniforms.nearPlane+4.0*uniforms.stepSize && normPos.z=uniforms.nearPlane+5.0*uniforms.stepSize && normPos.z=uniforms.nearPlane+6.0*uniforms.stepSize && normPos.z=uniforms.nearPlane+7.0*uniforms.stepSize && normPos.z{"use strict";i.r(t),i.d(t,{iblVoxelGridVertexShaderWGSL:()=>n});const r="iblVoxelGridVertexShader",s="attribute position: vec3f;attribute normal: vec3f;varying vNormalizedPosition: vec3f;uniform world: mat4x4f;uniform invWorldScale: mat4x4f;uniform viewMatrix: mat4x4f;@vertex\nfn main(input : VertexInputs)->FragmentInputs {vertexOutputs.position=uniforms.viewMatrix*uniforms.invWorldScale*uniforms.world* vec4f(input.position,1.);vertexOutputs.vNormalizedPosition=vertexOutputs.position.xyz*0.5+0.5;\n#ifdef IS_NDC_HALF_ZRANGE\nvertexOutputs.position=vec4f(vertexOutputs.position.x,vertexOutputs.position.y,vertexOutputs.position.z*0.5+0.5,vertexOutputs.position.w);\n#endif\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},7426:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblVoxelGrid2dArrayDebugPixelShaderWGSL:()=>n});const r="iblVoxelGrid2dArrayDebugPixelShader",s="varying vUV: vec2f;var voxelTextureSampler: sampler;var voxelTexture: texture_3d;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform slice: i32;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var size: vec3u=textureDimensions(voxelTexture,0);var dimension: f32=sqrt( f32(size.z));var samplePos: vec2f=fract(input.vUV.xy* vec2f(dimension));var sampleIndex: u32= u32(floor(input.vUV.x* f32(dimension))+floor(input.vUV.y* f32(dimension))*dimension);var color=textureSample(voxelTexture,voxelTextureSampler, vec3f(samplePos.xy,sampleIndex)).rrr;color+=textureSample(textureSampler,textureSamplerSampler,input.vUV.xy).rgb;fragmentOutputs.color=vec4f(color,1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},20008:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblVoxelGrid3dDebugPixelShaderWGSL:()=>n});const r="iblVoxelGrid3dDebugPixelShader",s="varying vUV: vec2f;var voxelTextureSampler: sampler;var voxelTexture: texture_3d;var voxelSlabTextureSampler: sampler;var voxelSlabTexture: texture_2d;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform sizeParams: vec4f;\n#define offsetX uniforms.sizeParams.x\n#define offsetY uniforms.sizeParams.y\n#define widthScale uniforms.sizeParams.z\n#define heightScale uniforms.sizeParams.w\nuniform mipNumber: f32;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var uv: vec2f =\nvec2f((offsetX+input.vUV.x)*widthScale,(offsetY+input.vUV.y)*heightScale);var background: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);var voxelSlab: vec4f=textureSample(voxelSlabTexture,voxelSlabTextureSampler,input.vUV);var size: vec3u=textureDimensions(voxelTexture, i32(uniforms.mipNumber));var dimension: f32=ceil(sqrt( f32(size.z)));var samplePos: vec2f=fract(uv.xy* vec2f(dimension));var sampleIndex: u32= u32(floor(uv.x* f32(dimension)) +\nfloor(uv.y* f32(dimension))*dimension);var mip_separator: f32=0.0;if (samplePos.x<0.01 || samplePos.y<0.01) {mip_separator=1.0;}\nvar outBounds: bool=select(false,true,sampleIndex>size.z-1);sampleIndex=clamp(sampleIndex,0,size.z-1);var samplePosInt: vec2i= vec2i(samplePos.xy* vec2f(size.xy));var voxel: vec3f=textureLoad(voxelTexture,\nvec3i(i32(samplePosInt.x),i32(samplePosInt.y),i32(sampleIndex)),\ni32(uniforms.mipNumber)).rgb;if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {fragmentOutputs.color=background;} else {if (outBounds) {voxel= vec3f(0.15,0.0,0.0);} else {if (voxel.r>0.001) {voxel.g=1.0;}\nvoxel.r+=mip_separator;}\nfragmentOutputs.color=vec4f(mix(background.rgb,voxelSlab.rgb,voxelSlab.a)+voxel,1.0);}}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},16615:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblVoxelSlabDebugPixelShaderWGSL:()=>n});const r="iblVoxelSlabDebugPixelShader",s="varying vNormalizedPosition: vec3f;uniform nearPlane: f32;uniform farPlane: f32;uniform stepSize: f32;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var normPos: vec3f=input.vNormalizedPosition.xyz;var chunkSize: f32=uniforms.stepSize* f32(MAX_DRAW_BUFFERS);var numChunks: f32=1.0/chunkSize;var positionInChunk: f32=fract(normPos.z/chunkSize);var slab: f32=floor(positionInChunk* f32(MAX_DRAW_BUFFERS)) /\nf32(MAX_DRAW_BUFFERS);if (normPos.x<0.0 || normPos.y<0.0 || normPos.z<0.0 ||\nnormPos.x>1.0 || normPos.y>1.0 || normPos.z>1.0) {fragmentOutputs.color= vec4f(0.0,0.0,0.0,0.0);} else {fragmentOutputs.color= vec4f(slab,0.0,0.0,0.75);}}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},94369:(e,t,i)=>{"use strict";i.r(t),i.d(t,{iblVoxelSlabDebugVertexShaderWGSL:()=>n});const r="iblVoxelSlabDebugVertexShader",s="attribute position: vec3f;varying vNormalizedPosition: vec3f;uniform world: mat4x4f;uniform invWorldScale: mat4x4f;uniform cameraViewMatrix: mat4x4f;uniform projection: mat4x4f;uniform viewMatrix: mat4x4f;@vertex\nfn main(input : VertexInputs)->FragmentInputs {var worldPosition: vec4f=(uniforms.world* vec4f(input.position,1.));vertexOutputs.position=uniforms.projection*uniforms.cameraViewMatrix*worldPosition;vertexOutputs.vNormalizedPosition=(uniforms.viewMatrix*uniforms.invWorldScale*worldPosition).rgb;vertexOutputs.vNormalizedPosition=vertexOutputs.vNormalizedPosition* vec3f(0.5)+ vec3f(0.5);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},41123:(e,t,i)=>{"use strict";i.r(t),i.d(t,{imageProcessingPixelShaderWGSL:()=>o});var r=i(69841);i(33882),i(87647),i(33731);const s="imageProcessingPixelShader",n="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var result: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\nresult=vec4f(toLinearSpaceVec3(result.rgb),result.a);\n#endif\nresult=applyImageProcessing(result);\n#else\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\nfragmentOutputs.color=result;}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},56558:(e,t,i)=>{"use strict";i.r(t),i.d(t,{kernelBlurPixelShaderWGSL:()=>o});var r=i(69841);i(57932),i(2456);r.l.IncludesShadersStoreWGSL.kernelBlurFragment="#ifdef DOF\nfactor=sampleCoC(fragmentInputs.sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCoord{X}))*computedWeight;\n#else\nblend+=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCoord{X})*computedWeight;\n#endif\n";r.l.IncludesShadersStoreWGSL.kernelBlurFragment2="#ifdef DOF\nfactor=sampleCoC(fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif\n";const s="kernelBlurPixelShader",n="var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform delta: vec2f;varying sampleCenter: vec2f;\n#ifdef DOF\nvar circleOfConfusionSamplerSampler: sampler;var circleOfConfusionSampler: texture_2d;fn sampleCoC(offset: vec2f)->f32 {var coc: f32=textureSample(circleOfConfusionSampler,circleOfConfusionSamplerSampler,offset).r;return coc; }\n#endif\n#include[0..varyingCount]\n#ifdef PACKEDFLOAT\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var computedWeight: f32=0.0;\n#ifdef PACKEDFLOAT\nvar blend: f32=0.;\n#else\nvar blend: vec4f= vec4f(0.);\n#endif\n#ifdef DOF\nvar sumOfWeights: f32=CENTER_WEIGHT; \nvar factor: f32=0.0;\n#ifdef PACKEDFLOAT\nblend+=unpack(textureSample(textureSampler,textureSamplerSampler,input.sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=textureSample(textureSampler,textureSamplerSampler,input.sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include[0..varyingCount]\n#include[0..depCount]\n#ifdef PACKEDFLOAT\nfragmentOutputs.color=pack(blend);\n#else\nfragmentOutputs.color=blend;\n#endif\n#ifdef DOF\nfragmentOutputs.color/=sumOfWeights;\n#endif\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},42876:(e,t,i)=>{"use strict";i.r(t),i.d(t,{kernelBlurVertexShaderWGSL:()=>o});var r=i(69841);i(57932);r.l.IncludesShadersStoreWGSL.kernelBlurVertex="vertexOutputs.sampleCoord{X}=vertexOutputs.sampleCenter+uniforms.delta*KERNEL_OFFSET{X};";const s="kernelBlurVertexShader",n="attribute position: vec2f;uniform delta: vec2f;varying sampleCenter: vec2f;\n#include[0..varyingCount]\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {const madd: vec2f= vec2f(0.5,0.5);\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.sampleCenter=(input.position*madd+madd);\n#include[0..varyingCount]\nvertexOutputs.position= vec4f(input.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},28246:(e,t,i)=>{"use strict";i.r(t),i.d(t,{layerPixelShaderWGSL:()=>o});var r=i(69841);i(87647);const s="layerPixelShader",n="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform color: vec4f;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvar baseColor: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);\n#if defined(CONVERT_TO_GAMMA)\nbaseColor=toGammaSpace(baseColor);\n#elif defined(CONVERT_TO_LINEAR)\nbaseColor=toLinearSpaceVec4(baseColor);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nfragmentOutputs.color=baseColor*uniforms.color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},56028:(e,t,i)=>{"use strict";i.r(t),i.d(t,{layerVertexShaderWGSL:()=>n});const r="layerVertexShader",s="attribute position: vec2f;uniform scale: vec2f;uniform offset: vec2f;uniform textureMatrix: mat4x4f;varying vUV: vec2f;const madd: vec2f= vec2f(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvar shiftedPosition: vec2f=input.position*uniforms.scale+uniforms.offset;vertexOutputs.vUV=(uniforms.textureMatrix* vec4f(shiftedPosition*madd+madd,1.0,0.0)).xy;vertexOutputs.position= vec4f(shiftedPosition,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},19121:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lensFlarePixelShaderWGSL:()=>n});const r="lensFlarePixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform color: vec4f;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvar baseColor: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);fragmentOutputs.color=baseColor*uniforms.color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},72987:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lensFlareVertexShaderWGSL:()=>n});const r="lensFlareVertexShader",s="attribute position: vec2f;uniform viewportMatrix: mat4x4f;varying vUV: vec2f;const madd: vec2f= vec2f(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.vUV=input.position*madd+madd;vertexOutputs.position=uniforms.viewportMatrix* vec4f(input.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},27127:(e,t,i)=>{"use strict";i.r(t),i.d(t,{linePixelShaderWGSL:()=>o});var r=i(69841);i(96140),i(21859),i(85551),i(76794);const s="linePixelShader",n="#include\nuniform color: vec4f;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#include\nfragmentOutputs.color=uniforms.color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},7217:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lineVertexShaderWGSL:()=>o});var r=i(69841);i(41416),i(30486),i(14910),i(10598),i(21859),i(32764),i(57728),i(18201);const s="lineVertexShader",n="#define ADDITIONAL_VERTEX_DECLARATION\n#include\n#include\n#include\n#include\nattribute position: vec3f;attribute normal: vec4f;uniform width: f32;uniform aspectRatio: f32;\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\nvar worldViewProjection: mat4x4f=scene.viewProjection*finalWorld;var viewPosition: vec4f=worldViewProjection* vec4f(input.position,1.0);var viewPositionNext: vec4f=worldViewProjection* vec4f(input.normal.xyz,1.0);var currentScreen: vec2f=viewPosition.xy/viewPosition.w;var nextScreen: vec2f=viewPositionNext.xy/viewPositionNext.w;currentScreen=vec2f(currentScreen.x*uniforms.aspectRatio,currentScreen.y);nextScreen=vec2f(nextScreen.x*uniforms.aspectRatio,nextScreen.y);var dir: vec2f=normalize(nextScreen-currentScreen);var normalDir: vec2f= vec2f(-dir.y,dir.x);normalDir*=uniforms.width/2.0;normalDir=vec2f(normalDir.x/uniforms.aspectRatio,normalDir.y);var offset: vec4f= vec4f(normalDir*input.normal.w,0.0,0.0);vertexOutputs.position=viewPosition+offset;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvar worldPos: vec4f=finalWorld*vec4f(input.position,1.0);\n#include\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},58316:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lodPixelShaderWGSL:()=>n});const r="lodPixelShader",s="const GammaEncodePowerApprox=1.0/2.2;varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform lod: f32;uniform gamma: i32;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,fragmentInputs.vUV,uniforms.lod);if (uniforms.gamma==0) {fragmentOutputs.color=vec4f(pow(fragmentOutputs.color.rgb,vec3f(GammaEncodePowerApprox)),fragmentOutputs.color.a);}}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},61951:(e,t,i)=>{"use strict";i.r(t),i.d(t,{lodCubePixelShaderWGSL:()=>n});const r="lodCubePixelShader",s="const GammaEncodePowerApprox=1.0/2.2;varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_cube;uniform lod: f32;uniform gamma: i32;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {let uv=fragmentInputs.vUV*2.0-1.0;\n#ifdef POSITIVEX\nfragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(1.001,uv.y,uv.x),uniforms.lod);\n#endif\n#ifdef NEGATIVEX\nfragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(-1.001,uv.y,uv.x),uniforms.lod);\n#endif\n#ifdef POSITIVEY\nfragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(uv.y,1.001,uv.x),uniforms.lod);\n#endif\n#ifdef NEGATIVEY\nfragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(uv.y,-1.001,uv.x),uniforms.lod);\n#endif\n#ifdef POSITIVEZ\nfragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(uv,1.001),uniforms.lod);\n#endif\n#ifdef NEGATIVEZ\nfragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(uv,-1.001),uniforms.lod);\n#endif\nif (uniforms.gamma==0) {fragmentOutputs.color=vec4f(pow(fragmentOutputs.color.rgb,vec3f(GammaEncodePowerApprox)),fragmentOutputs.color.a);}}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},49584:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererPixelShaderWGSL:()=>n});const r="meshUVSpaceRendererPixelShader",s="varying vDecalTC: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {if (input.vDecalTC.x<0. || input.vDecalTC.x>1. || input.vDecalTC.y<0. || input.vDecalTC.y>1.) {discard;}\nfragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vDecalTC);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},4830:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererVertexShaderWGSL:()=>o});var r=i(69841);i(25589),i(68273),i(47381),i(51148),i(41416),i(8573),i(43610),i(32764),i(40903),i(71281);const s="meshUVSpaceRendererVertexShader",n="attribute position: vec3f;attribute normal: vec3f;attribute uv: vec2f;uniform projMatrix: mat4x4f;varying vDecalTC: vec2f;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;var normalUpdated: vec3f=input.normal;\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvar worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);var normWorldSM: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);var vNormalW: vec3f;\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/ vec3f(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvNormalW=normalize(normWorldSM*normalUpdated);\n#endif\nvar normalView: vec3f=normalize((uniforms.projMatrix* vec4f(vNormalW,0.0)).xyz);var decalTC: vec3f=(uniforms.projMatrix*worldPos).xyz;vertexOutputs.vDecalTC=decalTC.xy;vertexOutputs.position=vec4f(input.uv*2.0-1.0,select(decalTC.z,2.,normalView.z>0.0),1.0);}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},83479:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererFinaliserPixelShaderWGSL:()=>n});const r="meshUVSpaceRendererFinaliserPixelShader",s="#define DISABLE_UNIFORMITY_ANALYSIS\nvarying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var maskTextureSamplerSampler: sampler;var maskTextureSampler: texture_2d;uniform textureSize: vec2f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var mask: vec4f=textureSample(maskTextureSampler,maskTextureSamplerSampler,input.vUV).rgba;if (mask.r>0.5) {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);} else {var texelSize: vec2f=4.0/uniforms.textureSize;var uv_p01: vec2f=input.vUV+ vec2f(-1.0,0.0)*texelSize;var uv_p21: vec2f=input.vUV+ vec2f(1.0,0.0)*texelSize;var uv_p10: vec2f=input.vUV+ vec2f(0.0,-1.0)*texelSize;var uv_p12: vec2f=input.vUV+ vec2f(0.0,1.0)*texelSize;var mask_p01: f32=textureSample(maskTextureSampler,maskTextureSamplerSampler,uv_p01).r;var mask_p21: f32=textureSample(maskTextureSampler,maskTextureSamplerSampler,uv_p21).r;var mask_p10: f32=textureSample(maskTextureSampler,maskTextureSamplerSampler,uv_p10).r;var mask_p12: f32=textureSample(maskTextureSampler,maskTextureSamplerSampler,uv_p12).r;var col: vec4f= vec4f(0.0,0.0,0.0,0.0);var total_weight: f32=0.0;if (mask_p01>0.5) {col+=textureSample(textureSampler,textureSamplerSampler,uv_p01);total_weight+=1.0;}\nif (mask_p21>0.5) {col+=textureSample(textureSampler,textureSamplerSampler,uv_p21);total_weight+=1.0;}\nif (mask_p10>0.5) {col+=textureSample(textureSampler,textureSamplerSampler,uv_p10);total_weight+=1.0;}\nif (mask_p12>0.5) {col+=textureSample(textureSampler,textureSamplerSampler,uv_p12);total_weight+=1.0;}\nif (total_weight>0.0) {fragmentOutputs.color=col/total_weight;} else {fragmentOutputs.color=col;}}}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},55153:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererFinaliserVertexShaderWGSL:()=>n});const r="meshUVSpaceRendererFinaliserVertexShader",s="attribute position: vec3f;attribute uv: vec2f;uniform worldViewProjection: mat4x4f;varying vUV: vec2f;@vertex\nfn main(input : VertexInputs)->FragmentInputs {vertexOutputs.position=uniforms.worldViewProjection* vec4f(input.position,1.0);vertexOutputs.positionvUV=input.uv;}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},49373:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererMaskerPixelShaderWGSL:()=>n});const r="meshUVSpaceRendererMaskerPixelShader",s="varying vUV: vec2f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color= vec4f(1.0,1.0,1.0,1.0);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},72919:(e,t,i)=>{"use strict";i.r(t),i.d(t,{meshUVSpaceRendererMaskerVertexShaderWGSL:()=>n});const r="meshUVSpaceRendererMaskerVertexShader",s="attribute uv: vec2f;varying vUV: vec2f;@vertex\nfn main(input : VertexInputs)->FragmentInputs {vertexOutputs.position= vec4f( vec2f(input.uv.x,input.uv.y)*2.0-1.0,0.,1.0);vertexOutputs.vUV=input.uv;}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},95400:(e,t,i)=>{"use strict";i.r(t),i.d(t,{motionBlurPixelShaderWGSL:()=>n});const r="motionBlurPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform motionStrength: f32;uniform motionScale: f32;uniform screenSize: vec2f;\n#ifdef OBJECT_BASED\nvar velocitySamplerSampler: sampler;var velocitySampler: texture_2d;\n#else\nvar depthSamplerSampler: sampler;var depthSampler: texture_2d;uniform inverseViewProjection: mat4x4f;uniform prevViewProjection: mat4x4f;uniform projection: mat4x4f;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#ifdef GEOMETRY_SUPPORTED\n#ifdef OBJECT_BASED\nvar texelSize: vec2f=1.0/uniforms.screenSize;var velocityColor: vec4f=textureSample(velocitySampler,velocitySamplerSampler,input.vUV);velocityColor=vec4f(velocityColor.rg*2.0- vec2f(1.0),velocityColor.b,velocityColor.a);var velocity: vec2f= vec2f(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=uniforms.motionScale*uniforms.motionStrength;var speed: f32=length(velocity/texelSize);var samplesCount: i32= i32(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;var hlim: f32= f32(-samplesCount)*0.5+0.5;var result: vec4f=textureSample(textureSampler,textureSamplerSampler, input.vUV);for (var i: i32=1; i< i32(SAMPLES); i++)\n{if (i>=samplesCount) {break;}\nvar offset: vec2f=input.vUV+velocity*(hlim+ f32(i));\n#if defined(WEBGPU)\nresult+=textureSampleLevel(textureSampler,textureSamplerSampler, offset,0.0);\n#else\nresult+=textureSample(textureSampler,textureSamplerSampler, offset);\n#endif\n}\nfragmentOutputs.color=vec4f(result.rgb/ f32(samplesCount),1.0);\n#else\nvar texelSize: vec2f=1.0/uniforms.screenSize;var depth: f32=textureSample(depthSampler,depthSamplerSampler,input.vUV).r;depth=uniforms.projection[2].z+uniforms.projection[3].z/depth; \nvar cpos: vec4f= vec4f(input.vUV*2.0-1.0,depth,1.0);cpos=uniforms.inverseViewProjection*cpos;cpos/=cpos.w;var ppos: vec4f=uniforms.prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;var velocity: vec2f=(ppos.xy-input.vUV)*uniforms.motionScale*uniforms.motionStrength;var speed: f32=length(velocity/texelSize);var nSamples: i32= i32(clamp(speed,1.0,SAMPLES));var result: vec4f=textureSample(textureSampler,textureSamplerSampler, input.vUV);for (var i: i32=1; i< i32(SAMPLES); i++) {if (i>=nSamples) {break;}\nvar offset1: vec2f=input.vUV+velocity*( f32(i)/ f32(nSamples-1)-0.5);\n#if defined(WEBGPU)\nresult+=textureSampleLevel(textureSampler,textureSamplerSampler, offset1,0.0);\n#else\nresult+=textureSample(textureSampler,textureSamplerSampler, offset1);\n#endif\n}\nfragmentOutputs.color=result/ f32(nSamples);\n#endif\n#else\nfragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler, input.vUV);\n#endif\n}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},29551:(e,t,i)=>{"use strict";i.r(t),i.d(t,{oitBackBlendPixelShaderWGSL:()=>n});const r="oitBackBlendPixelShader",s="var uBackColor: texture_2d;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureLoad(uBackColor,vec2i(fragmentInputs.position.xy),0);if (fragmentOutputs.color.a==0.0) {discard;}}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},21937:(e,t,i)=>{"use strict";i.r(t),i.d(t,{oitFinalPixelShaderWGSL:()=>n});const r="oitFinalPixelShader",s="var uFrontColor: texture_2d;var uBackColor: texture_2d;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var fragCoord: vec2i=vec2i(fragmentInputs.position.xy);var frontColor: vec4f=textureLoad(uFrontColor,fragCoord,0);var backColor: vec4f=textureLoad(uBackColor,fragCoord,0);var alphaMultiplier: f32=1.0-frontColor.a;fragmentOutputs.color=vec4f(\nfrontColor.rgb+alphaMultiplier*backColor.rgb,\nfrontColor.a+backColor.a\n);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},55515:(e,t,i)=>{"use strict";i.r(t),i.d(t,{outlinePixelShaderWGSL:()=>o});var r=i(69841);i(96140),i(21859),i(76794),i(85551);const s="outlinePixelShader",n="uniform color: vec4f;\n#ifdef ALPHATEST\nvarying vUV: vec2;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#ifdef ALPHATEST\nif (textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vUV).a<0.4) {discard;}\n#endif\n#include\nfragmentOutputs.color=uniforms.color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},18789:(e,t,i)=>{"use strict";i.r(t),i.d(t,{outlineVertexShaderWGSL:()=>o});var r=i(69841);i(25589),i(68273),i(47381),i(51148),i(30486),i(41416),i(21859),i(8573),i(43610),i(32764),i(40903),i(71281),i(57728),i(18201);const s="outlineVertexShader",n="attribute position: vec3f;attribute normal: vec3f;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform offset: f32;\n#include\nuniform viewProjection: mat4x4f;\n#ifdef ALPHATEST\nvarying vUV: vec2f;uniform diffuseMatrix: mat4x4f; \n#ifdef UV1\nattribute uv: vec2f;\n#endif\n#ifdef UV2\nattribute uv2: vec2f;\n#endif\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input: VertexInputs)->FragmentInputs {var positionUpdated: vec3f=vertexInputs.position;var normalUpdated: vec3f=vertexInputs.normal;\n#ifdef UV1\nvar uvUpdated: vec2f=vertexInputs.uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\nvar offsetPosition: vec3f=positionUpdated+(normalUpdated*uniforms.offset);\n#include\n#include\n#include\nvar worldPos: vec4f=finalWorld*vec4f(offsetPosition,1.0);vertexOutputs.position=uniforms.viewProjection*worldPos;\n#ifdef ALPHATEST\n#ifdef UV1\nvertexOutputs.vUV=(uniforms.diffuseMatrix*vec4f(uvUpdated,1.0,0.0)).xy;\n#endif\n#ifdef UV2\nvertexOutputs.vUV=(uniforms.diffuseMatrix*vec4f(vertexInputs.uv2,1.0,0.0)).xy;\n#endif\n#endif\n#include\n#include\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},86144:(e,t,i)=>{"use strict";i.r(t),i.d(t,{particlesPixelShaderWGSL:()=>o});var r=i(69841);i(96140),i(33882),i(21859),i(87647),i(33731),i(10668),i(76794),i(85551),i(31034);const s="particlesPixelShader",n="varying vUV: vec2f;varying vColor: vec4f;uniform textureMask: vec4f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d;\n#include\n#include\n#include\n#include\n#include\n#ifdef RAMPGRADIENT\nvarying remapRanges: vec4f;var rampSamplerSampler: sampler;var rampSampler: texture_2d;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvar textureColor: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV);var baseColor: vec4f=(textureColor*uniforms.textureMask+( vec4f(1.,1.,1.,1.)-uniforms.textureMask))*input.vColor;\n#ifdef RAMPGRADIENT\nvar alpha: f32=baseColor.a;var remappedColorIndex: f32=clamp((alpha-input.remapRanges.x)/input.remapRanges.y,0.0,1.0);var rampColor: vec4f=textureSample(rampSampler,rampSamplerSampler,vec2f(1.0-remappedColorIndex,0.));baseColor=vec4f(baseColor.rgb*rampColor.rgb,baseColor.a);var finalAlpha: f32=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-input.remapRanges.z)/input.remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nvar sourceAlpha: f32=input.vColor.a*textureColor.a;baseColor=vec4f(baseColor.rgb*sourceAlpha+ vec3f(1.0)*(1.0-sourceAlpha),baseColor.a);\n#endif\n#include\n#include(color,baseColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor=vec4f(toLinearSpaceVec3(baseColor.rgb),baseColor.a);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor=vec4f(toLinearSpaceVec3(baseColor.rgb),baseColor.a);baseColor=applyImageProcessing(baseColor);\n#endif\n#endif\nfragmentOutputs.color=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},25806:(e,t,i)=>{"use strict";i.r(t),i.d(t,{particlesVertexShaderWGSL:()=>o});var r=i(69841);i(30486),i(86934),i(21859),i(57728),i(45184),i(18201);const s="particlesVertexShader",n="attribute position: vec3f;attribute color: vec4f;attribute angle: f32;attribute size: vec2f;\n#ifdef ANIMATESHEET\nattribute cellIndex: f32;\n#endif\n#ifndef BILLBOARD\nattribute direction: vec3f;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute direction: vec3f;\n#endif\n#ifdef RAMPGRADIENT\nattribute remapData: vec4f;\n#endif\nattribute offset: vec2f;uniform view: mat4x4f;uniform projection: mat4x4f;uniform translationPivot: vec2f;\n#ifdef ANIMATESHEET\nuniform particlesInfos: vec3f; \n#endif\nvarying vUV: vec2f;varying vColor: vec4f;varying vPositionW: vec3f;\n#ifdef RAMPGRADIENT\nvarying remapRanges: vec4f;\n#endif\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform invView: mat4x4f;\n#endif\n#include\n#include\n#include\n#ifdef BILLBOARD\nuniform eyePosition: vec3f;\n#endif\nfn rotate(yaxis: vec3f,rotatedCorner: vec3f)->vec3f {var xaxis: vec3f=normalize(cross( vec3f(0.,1.0,0.),yaxis));var zaxis: vec3f=normalize(cross(yaxis,xaxis));var row0: vec3f= vec3f(xaxis.x,xaxis.y,xaxis.z);var row1: vec3f= vec3f(yaxis.x,yaxis.y,yaxis.z);var row2: vec3f= vec3f(zaxis.x,zaxis.y,zaxis.z);var rotMatrix: mat3x3f= mat3x3f(row0,row1,row2);var alignedCorner: vec3f=rotMatrix*rotatedCorner;return vertexInputs.position+alignedCorner;}\n#ifdef BILLBOARDSTRETCHED\nfn rotateAlign(toCamera: vec3f,rotatedCorner: vec3f)->vec3f {var normalizedToCamera: vec3f=normalize(toCamera);var normalizedCrossDirToCamera: vec3f=normalize(cross(normalize(vertexInputs.direction),normalizedToCamera));var row0: vec3f= vec3f(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);var row2: vec3f= vec3f(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\n#ifdef BILLBOARDSTRETCHED_LOCAL\nvar row1: vec3f=vertexInputs.direction;\n#else\nvar crossProduct: vec3f=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));var row1: vec3f= vec3f(crossProduct.x,crossProduct.y,crossProduct.z);\n#endif\nvar rotMatrix: mat3x3f= mat3x3f(row0,row1,row2);var alignedCorner: vec3f=rotMatrix*rotatedCorner;return input.position+alignedCorner;}\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvar cornerPos: vec2f;cornerPos=( vec2f(input.offset.x-0.5,input.offset.y -0.5)-uniforms.translationPivot)*input.size;\n#ifdef BILLBOARD\nvar rotatedCorner: vec3f;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.z=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.y=0.;var yaxis: vec3f=input.position-uniforms.eyePosition;yaxis.y=0.;vertexOutputs.vPositionW=rotate(normalize(yaxis),rotatedCorner);var viewPos: vec3f=(uniforms.view* vec4f(vertexOutputs.vPositionW,1.0)).xyz;\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.y=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.z=0.;var toCamera: vec3f=input.position-uniforms.eyePosition;vertexOutputs.vPositionW=rotateAlign(toCamera,rotatedCorner);var viewPos: vec3f=(uniforms.view* vec4f(vertexOutputs.vPositionW,1.0)).xyz;\n#else\nrotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.y=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.z=0.;var viewPos: vec3f=(uniforms.view* vec4f(input.position,1.0)).xyz+rotatedCorner;vertexOutputs.vPositionW=(uniforms.invView* vec4f(viewPos,1)).xyz;\n#endif\n#ifdef RAMPGRADIENT\nvertexOutputs.remapRanges=input.remapData;\n#endif\nvertexOutputs.position=uniforms.projection* vec4f(viewPos,1.0);\n#else\nvar rotatedCorner: vec3f;rotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.z=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.y=0.;var yaxis: vec3f=normalize(vertexInputs.direction);vertexOutputs.vPositionW=rotate(yaxis,rotatedCorner);vertexOutputs.position=uniforms.projection*uniforms.view* vec4f(vertexOutputs.vPositionW,1.0);\n#endif\nvertexOutputs.vColor=input.color;\n#ifdef ANIMATESHEET\nvar rowOffset: f32=floor(input.cellIndex*uniforms.particlesInfos.z);var columnOffset: f32=input.cellIndex-rowOffset/uniforms.particlesInfos.z;var uvScale: vec2f=uniforms.particlesInfos.xy;var uvOffset: vec2f= vec2f(input.offset.x ,1.0-input.offset.y);vertexOutputs.vUV=(uvOffset+ vec2f(columnOffset,rowOffset))*uvScale;\n#else\nvertexOutputs.vUV=input.offset;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)\nvar worldPos: vec4f= vec4f(vertexOutputs.vPositionW,1.0);\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},418:(e,t,i)=>{"use strict";i.r(t),i.d(t,{passPixelShaderWGSL:()=>n});const r="passPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},12253:(e,t,i)=>{"use strict";i.r(t),i.d(t,{passCubePixelShaderWGSL:()=>n});const r="passCubePixelShader",s="varying var vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_cube;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var uv: vec2f=input.vUV*2.0-1.0;\n#ifdef POSITIVEX\nfragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\nfragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\nfragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\nfragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\nfragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\nfragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv,-1.001));\n#endif\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},66854:(e,t,i)=>{"use strict";i.r(t),i.d(t,{pbrPixelShaderWGSL:()=>o});var r=i(69841);i(85620),i(73048),i(53894),i(36174);r.l.IncludesShadersStoreWGSL.pbrFragmentExtraDeclaration="varying vPositionW: vec3f;\n#if DEBUGMODE>0\nvarying vClipSpacePosition: vec4f;\n#endif\n#include[1..7]\n#ifdef NORMAL\nvarying vNormalW: vec3f;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vEnvironmentIrradiance: vec3f;\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vColor: vec4f;\n#endif\n",i(71426),i(59224);r.l.IncludesShadersStoreWGSL.samplerFragmentAlternateDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying v_VARYINGNAME_UV: vec2f;\n#endif\n#endif\n";r.l.IncludesShadersStoreWGSL.pbrFragmentSamplersDeclaration="#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nvar clearCoatRoughnessSamplerSampler: sampler;var clearCoatRoughnessSampler: texture_2d;\n#endif\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS)\nvar sheenRoughnessSamplerSampler: sampler;var sheenRoughnessSampler: texture_2d;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nvar reflectionSamplerSampler: sampler;var reflectionSampler: texture_cube;\n#ifdef LODBASEDMICROSFURACE\n#else\nvar reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_cube;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_cube;\n#endif\n#ifdef USEIRRADIANCEMAP\nvar irradianceSamplerSampler: sampler;var irradianceSampler: texture_cube;\n#endif\n#else\nvar reflectionSamplerSampler: sampler;var reflectionSampler: texture_2d;\n#ifdef LODBASEDMICROSFURACE\n#else\nvar reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_2d;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_2d;\n#endif\n#ifdef USEIRRADIANCEMAP\nvar irradianceSamplerSampler: sampler;var irradianceSampler: texture_2d;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vPositionUVW: vec3f;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vDirectionW: vec3f;\n#endif\n#endif\n#endif\n#ifdef ENVIRONMENTBRDF\nvar environmentBrdfSamplerSampler: sampler;var environmentBrdfSampler: texture_2d;\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#ifdef SS_REFRACTIONMAP_3D\nvar refractionSamplerSampler: sampler;var refractionSampler: texture_cube;\n#ifdef LODBASEDMICROSFURACE\n#else\nvar refractionLowSamplerSampler: sampler;var refractionLowSampler: texture_cube;var refractionHighSamplerSampler: sampler;var refractionHighSampler: texture_cube;\n#endif\n#else\nvar refractionSamplerSampler: sampler;var refractionSampler: texture_2d;\n#ifdef LODBASEDMICROSFURACE\n#else\nvar refractionLowSamplerSampler: sampler;var refractionLowSampler: texture_2d;var refractionHighSamplerSampler: sampler;var refractionHighSampler: texture_2d;\n#endif\n#endif\n#endif\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_SAMPLERNAME_,translucencyColor)\n#endif\n",i(33882),i(96140),i(21859),i(10668),i(87647);r.l.IncludesShadersStoreWGSL.subSurfaceScatteringFunctions="fn testLightingForSSS(diffusionProfile: f32)->bool\n{return diffusionProfile<1.;}",i(60755);r.l.IncludesShadersStoreWGSL.pbrHelperFunctions="#define MINIMUMVARIANCE 0.0005\nfn convertRoughnessToAverageSlope(roughness: f32)->f32\n{return roughness*roughness+MINIMUMVARIANCE;}\nfn fresnelGrazingReflectance(reflectance0: f32)->f32 {var reflectance90: f32=saturate(reflectance0*25.0);return reflectance90;}\nfn getAARoughnessFactors(normalVector: vec3f)->vec2f {\n#ifdef SPECULARAA\nvar nDfdx: vec3f=dpdx(normalVector.xyz);var nDfdy: vec3f=dpdy(normalVector.xyz);var slopeSquare: f32=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));var geometricRoughnessFactor: f32=pow(saturate(slopeSquare),0.333);var geometricAlphaGFactor: f32=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2f(geometricRoughnessFactor,geometricAlphaGFactor);\n#else\nreturn vec2f(0.);\n#endif\n}\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_LEGACY\nfn getAnisotropicRoughness(alphaG: f32,anisotropy: f32)->vec2f {var alphaT: f32=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);var alphaB: f32=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2f(alphaT,alphaB);}\nfn getAnisotropicBentNormals(T: vec3f,B: vec3f,N: vec3f,V: vec3f,anisotropy: f32,roughness: f32)->vec3f {var anisotropicFrameDirection: vec3f=select(T,B,anisotropy>=0.0);var anisotropicFrameTangent: vec3f=cross(normalize(anisotropicFrameDirection),V);var anisotropicFrameNormal: vec3f=cross(anisotropicFrameTangent,anisotropicFrameDirection);var anisotropicNormal: vec3f=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;}\n#else\nfn getAnisotropicRoughness(alphaG: f32,anisotropy: f32)->vec2f {var alphaT: f32=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);var alphaB: f32=max(alphaG,MINIMUMVARIANCE);return vec2f(alphaT,alphaB);}\nfn getAnisotropicBentNormals(T: vec3f,B: vec3f,N: vec3f,V: vec3f,anisotropy: f32,roughness: f32)->vec3f {var bentNormal: vec3f=cross(B,V);bentNormal=normalize(cross(bentNormal,B));var sq=1.0-anisotropy*(1.0-roughness);var a: f32=sq*sq*sq*sq;bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;}\n#endif\n#endif\n#if defined(CLEARCOAT) || defined(SS_REFRACTION)\nfn cocaLambertVec3(alpha: vec3f,distance: f32)->vec3f {return exp(-alpha*distance);}\nfn cocaLambert(NdotVRefract: f32,NdotLRefract: f32,alpha: vec3f,thickness: f32)->vec3f {return cocaLambertVec3(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));}\nfn computeColorAtDistanceInMedia(color: vec3f,distance: f32)->vec3f {return -log(color)/distance;}\nfn computeClearCoatAbsorption(NdotVRefract: f32,NdotLRefract: f32,clearCoatColor: vec3f,clearCoatThickness: f32,clearCoatIntensity: f32)->vec3f {var clearCoatAbsorption: vec3f=mix( vec3f(1.0),\ncocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),\nclearCoatIntensity);return clearCoatAbsorption;}\n#endif\n#ifdef MICROSURFACEAUTOMATIC\nfn computeDefaultMicroSurface(microSurface: f32,reflectivityColor: vec3f)->f32\n{const kReflectivityNoAlphaWorkflow_SmoothnessMax: f32=0.95;var reflectivityLuminance: f32=getLuminance(reflectivityColor);var reflectivityLuma: f32=sqrt(reflectivityLuminance);var resultMicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return resultMicroSurface;}\n#endif\n",i(33731),i(94662),i(36437);r.l.IncludesShadersStoreWGSL.pbrDirectLightingSetupFunctions="struct preLightingInfo\n{lightOffset: vec3f,\nlightDistanceSquared: f32,\nlightDistance: f32,\nattenuation: f32,\nL: vec3f,\nH: vec3f,\nNdotV: f32,\nNdotLUnclamped: f32,\nNdotL: f32,\nVdotH: f32,\nroughness: f32,\n#ifdef IRIDESCENCE\niridescenceIntensity: f32\n#endif\n};fn computePointAndSpotPreLightingInfo(lightData: vec4f,V: vec3f,N: vec3f,posW: vec3f)->preLightingInfo {var result: preLightingInfo;result.lightOffset=lightData.xyz-posW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\nfn computeDirectionalPreLightingInfo(lightData: vec4f,V: vec3f,N: vec3f)->preLightingInfo {var result: preLightingInfo;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\nfn computeHemisphericPreLightingInfo(lightData: vec4f,V: vec3f,N: vec3f)->preLightingInfo {var result: preLightingInfo;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL;\n#ifdef SPECULARTERM\nresult.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));\n#endif\nreturn result;}";r.l.IncludesShadersStoreWGSL.pbrDirectLightingFalloffFunctions="fn computeDistanceLightFalloff_Standard(lightOffset: vec3f,range: f32)->f32\n{return max(0.,1.0-length(lightOffset)/range);}\nfn computeDistanceLightFalloff_Physical(lightDistanceSquared: f32)->f32\n{return 1.0/maxEps(lightDistanceSquared);}\nfn computeDistanceLightFalloff_GLTF(lightDistanceSquared: f32,inverseSquaredRange: f32)->f32\n{var lightDistanceFalloff: f32=1.0/maxEps(lightDistanceSquared);var factor: f32=lightDistanceSquared*inverseSquaredRange;var attenuation: f32=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;}\nfn computeDistanceLightFalloff(lightOffset: vec3f,lightDistanceSquared: f32,range: f32,inverseSquaredRange: f32)->f32\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfn computeDirectionalLightFalloff_Standard(lightDirection: vec3f,directionToLightCenterW: vec3f,cosHalfAngle: f32,exponent: f32)->f32\n{var falloff: f32=0.0;var cosAngle: f32=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle)\n{falloff=max(0.,pow(cosAngle,exponent));}\nreturn falloff;}\nfn computeDirectionalLightFalloff_Physical(lightDirection: vec3f,directionToLightCenterW: vec3f,cosHalfAngle: f32)->f32\n{const kMinusLog2ConeAngleIntensityRatio: f32=6.64385618977; \nvar concentrationKappa: f32=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);var lightDirectionSpreadSG: vec4f= vec4f(-lightDirection*concentrationKappa,-concentrationKappa);var falloff: f32=exp2(dot( vec4f(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;}\nfn computeDirectionalLightFalloff_GLTF(lightDirection: vec3f,directionToLightCenterW: vec3f,lightAngleScale: f32,lightAngleOffset: f32)->f32\n{var cd: f32=dot(-lightDirection,directionToLightCenterW);var falloff: f32=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;}\nfn computeDirectionalLightFalloff(lightDirection: vec3f,directionToLightCenterW: vec3f,cosHalfAngle: f32,exponent: f32,lightAngleScale: f32,lightAngleOffset: f32)->f32\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}",i(20427),i(49335);r.l.IncludesShadersStoreWGSL.pbrDirectLightingFunctions="#define CLEARCOATREFLECTANCE90 1.0\nstruct lightingInfo\n{diffuse: vec3f,\n#ifdef SPECULARTERM\nspecular: vec3f,\n#endif\n#ifdef CLEARCOAT\nclearCoat: vec4f,\n#endif\n#ifdef SHEEN\nsheen: vec3f\n#endif\n};fn adjustRoughnessFromLightProperties(roughness: f32,lightRadius: f32,lightDistance: f32)->f32 {\n#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\nvar lightRoughness: f32=lightRadius/lightDistance;var totalRoughness: f32=saturate(lightRoughness+roughness);return totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfn computeHemisphericDiffuseLighting(info: preLightingInfo,lightColor: vec3f,groundColor: vec3f)->vec3f {return mix(groundColor,lightColor,info.NdotL);}\nfn computeDiffuseLighting(info: preLightingInfo,lightColor: vec3f)->vec3f {var diffuseTerm: f32=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;}\nfn computeProjectionTextureDiffuseLighting(projectionLightTexture: texture_2d,projectionLightSampler: sampler,textureProjectionMatrix: mat4x4f,posW: vec3f)->vec3f{var strq: vec4f=textureProjectionMatrix* vec4f(posW,1.0);strq/=strq.w;var textureColor: vec3f=textureSample(projectionLightTexture,projectionLightSampler,strq.xy).rgb;return toLinearSpaceVec3(textureColor);}\n#ifdef SS_TRANSLUCENCY\nfn computeDiffuseAndTransmittedLighting(info: preLightingInfo,lightColor: vec3f,transmittance: vec3f)->vec3f {var NdotL: f32=absEps(info.NdotLUnclamped);var wrapNdotL: f32=computeWrappedDiffuseNdotL(NdotL,0.02);var trAdapt: f32=step(0.,info.NdotLUnclamped);var transmittanceNdotL: vec3f=mix(transmittance*wrapNdotL, vec3f(wrapNdotL),trAdapt);var diffuseTerm: f32=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;}\n#endif\n#ifdef SPECULARTERM\nfn computeSpecularLighting(info: preLightingInfo,N: vec3f,reflectance0: vec3f,reflectance90: vec3f,geometricRoughnessFactor: f32,lightColor: vec3f)->vec3f {var NdotH: f32=saturateEps(dot(N,info.H));var roughness: f32=max(info.roughness,geometricRoughnessFactor);var alphaG: f32=convertRoughnessToAverageSlope(roughness);var fresnel: vec3f=fresnelSchlickGGXVec3(info.VdotH,reflectance0,reflectance90);\n#ifdef IRIDESCENCE\nfresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);\n#endif\nvar distribution: f32=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvar smithVisibility: f32=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG);\n#else\nvar smithVisibility: f32=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG);\n#endif\nvar specTerm: vec3f=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;}\n#endif\n#ifdef ANISOTROPIC\nfn computeAnisotropicSpecularLighting(info: preLightingInfo,V: vec3f,N: vec3f,T: vec3f,B: vec3f,anisotropy: f32,reflectance0: vec3f,reflectance90: vec3f,geometricRoughnessFactor: f32,lightColor: vec3f)->vec3f {var NdotH: f32=saturateEps(dot(N,info.H));var TdotH: f32=dot(T,info.H);var BdotH: f32=dot(B,info.H);var TdotV: f32=dot(T,V);var BdotV: f32=dot(B,V);var TdotL: f32=dot(T,info.L);var BdotL: f32=dot(B,info.L);var alphaG: f32=convertRoughnessToAverageSlope(info.roughness);var alphaTB: vec2f=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,vec2f(geometricRoughnessFactor*geometricRoughnessFactor));var fresnel: vec3f=fresnelSchlickGGXVec3(info.VdotH,reflectance0,reflectance90);\n#ifdef IRIDESCENCE\nfresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);\n#endif\nvar distribution: f32=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);var smithVisibility: f32=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);var specTerm: vec3f=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;}\n#endif\n#ifdef CLEARCOAT\nfn computeClearCoatLighting(info: preLightingInfo,Ncc: vec3f,geometricRoughnessFactor: f32,clearCoatIntensity: f32,lightColor: vec3f)->vec4f {var NccdotL: f32=saturateEps(dot(Ncc,info.L));var NccdotH: f32=saturateEps(dot(Ncc,info.H));var clearCoatRoughness: f32=max(info.roughness,geometricRoughnessFactor);var alphaG: f32=convertRoughnessToAverageSlope(clearCoatRoughness);var fresnel: f32=fresnelSchlickGGX(info.VdotH,uniforms.vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;var distribution: f32=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);var kelemenVisibility: f32=visibility_Kelemen(info.VdotH);var clearCoatTerm: f32=fresnel*distribution*kelemenVisibility;return vec4f(\nclearCoatTerm*info.attenuation*NccdotL*lightColor,\n1.0-fresnel\n);}\nfn computeClearCoatLightingAbsorption(NdotVRefract: f32,L: vec3f,Ncc: vec3f,clearCoatColor: vec3f,clearCoatThickness: f32,clearCoatIntensity: f32)->vec3f {var LRefract: vec3f=-refract(L,Ncc,uniforms.vClearCoatRefractionParams.y);var NdotLRefract: f32=saturateEps(dot(Ncc,LRefract));var absorption: vec3f=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;}\n#endif\n#ifdef SHEEN\nfn computeSheenLighting(info: preLightingInfo,N: vec3f,reflectance0: vec3f,reflectance90: vec3f,geometricRoughnessFactor: f32,lightColor: vec3f)->vec3f {var NdotH: f32=saturateEps(dot(N,info.H));var roughness: f32=max(info.roughness,geometricRoughnessFactor);var alphaG: f32=convertRoughnessToAverageSlope(roughness);var fresnel: f32=1.;var distribution: f32=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER\nvar visibility: f32=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG);\n#else */\nvar visibility: f32=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */\nvar sheenTerm: f32=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;}\n#endif\n";r.l.IncludesShadersStoreWGSL.pbrIBLFunctions="#if defined(REFLECTION) || defined(SS_REFRACTION)\nfn getLodFromAlphaG(cubeMapDimensionPixels: f32,microsurfaceAverageSlope: f32)->f32 {var microsurfaceAverageSlopeTexels: f32=cubeMapDimensionPixels*microsurfaceAverageSlope;var lod: f32=log2(microsurfaceAverageSlopeTexels);return lod;}\nfn getLinearLodFromRoughness(cubeMapDimensionPixels: f32,roughness: f32)->f32 {var lod: f32=log2(cubeMapDimensionPixels)*roughness;return lod;}\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION)\nfn environmentRadianceOcclusion(ambientOcclusion: f32,NdotVUnclamped: f32)->f32 {var temp: f32=NdotVUnclamped+ambientOcclusion;return saturate(temp*temp-1.0+ambientOcclusion);}\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION)\nfn environmentHorizonOcclusion(view: vec3f,normal: vec3f,geometricNormal: vec3f)->f32 {var reflection: vec3f=reflect(view,normal);var temp: f32=saturate(1.0+1.1*dot(reflection,geometricNormal));return temp*temp;}\n#endif\n#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA)\nfn UNPACK_LOD(x: f32)->f32 {return (1.0-x)*255.0;}\nfn getLodFromAlphaGNdotV(cubeMapDimensionPixels: f32,alphaG: f32,NdotV: f32)->f32 {var microsurfaceAverageSlope: f32=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);}\n#endif\n",i(56332),i(87087),i(7769),i(17327);r.l.IncludesShadersStoreWGSL.pbrBlockAlbedoOpacity="struct albedoOpacityOutParams\n{surfaceAlbedo: vec3f,\nalpha: f32};\n#define pbr_inline\nfn albedoOpacityBlock(\nvAlbedoColor: vec4f\n#ifdef ALBEDO\n,albedoTexture: vec4f\n,albedoInfos: vec2f\n#endif\n#ifdef OPACITY\n,opacityMap: vec4f\n,vOpacityInfos: vec2f\n#endif\n#ifdef DETAIL\n,detailColor: vec4f\n,vDetailInfos: vec4f\n#endif\n#ifdef DECAL\n,decalColor: vec4f\n,vDecalInfos: vec4f\n#endif\n)->albedoOpacityOutParams\n{var outParams: albedoOpacityOutParams;var surfaceAlbedo: vec3f=vAlbedoColor.rgb;var alpha: f32=vAlbedoColor.a;\n#ifdef ALBEDO\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\n#ifdef GAMMAALBEDO\nsurfaceAlbedo*=toLinearSpaceVec3(albedoTexture.rgb);\n#else\nsurfaceAlbedo*=albedoTexture.rgb;\n#endif\nsurfaceAlbedo*=albedoInfos.y;\n#endif\n#ifndef DECAL_AFTER_DETAIL\n#include\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nsurfaceAlbedo*=fragmentInputs.vColor.rgb;\n#endif\n#ifdef DETAIL\nvar detailAlbedo: f32=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; \n#endif\n#ifdef DECAL_AFTER_DETAIL\n#include\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALBEDO\n#ifdef OPACITY\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=fragmentInputs.vColor.a;\n#endif\n#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST \n#if DEBUGMODE != 88\nif (alpha{"use strict";i.r(t),i.d(t,{pbrVertexShaderWGSL:()=>o});var r=i(69841);i(53894),i(20115),i(36174),i(87647),i(25589),i(68273),i(41416),i(17894),i(30642),i(36437),i(96760),i(30486),i(86934),i(85188),i(47381),i(51148),i(21859),i(8573),i(43610),i(32764),i(40903),i(71281),i(51152),i(80699),i(84326),i(73918),i(57728),i(45184),i(48453),i(42321),i(18201);const s="pbrVertexShader",n="#include\n#define CUSTOM_VERTEX_BEGIN\nattribute position: vec3f;\n#ifdef NORMAL\nattribute normal: vec3f;\n#endif\n#ifdef TANGENT\nattribute tangent: vec4f;\n#endif\n#ifdef UV1\nattribute uv: vec2f;\n#endif\n#include[2..7]\n#include[1..7]\n#ifdef VERTEXCOLOR\nattribute color: vec4f;\n#endif\n#include\n#include\n#include\n#include\n#include\n#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy)\n#endif\n#ifdef SUBSURFACE\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor)\n#endif\nvarying vPositionW: vec3f;\n#if DEBUGMODE>0\nvarying vClipSpacePosition: vec4f;\n#endif\n#ifdef NORMAL\nvarying vNormalW: vec3f;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vEnvironmentIrradiance: vec3f;\n#include\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vColor: vec4f;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vPositionUVW: vec3f;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vDirectionW: vec3f;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvar positionUpdated: vec3f=vertexInputs.position;\n#ifdef NORMAL\nvar normalUpdated: vec3f=vertexInputs.normal;\n#endif\n#ifdef TANGENT\nvar tangentUpdated: vec4f=vertexInputs.tangent;\n#endif\n#ifdef UV1\nvar uvUpdated: vec2f=vertexInputs.uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvertexOutputs.vPositionUVW=positionUpdated;\n#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include\n#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)\nvertexOutputs.vCurrentPosition=scene.viewProjection*finalWorld*vec4f(positionUpdated,1.0);vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*vec4f(positionUpdated,1.0);\n#endif\n#include\n#include\nvar worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);vertexOutputs.vPositionW= worldPos.xyz;\n#ifdef PREPASS\n#include\n#endif\n#ifdef NORMAL\nvar normalWorld: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvertexOutputs.vNormalW=normalUpdated/ vec3f(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vertexOutputs.vNormalW=normalize(normalWorld*vertexOutputs.vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvertexOutputs.vNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvar reflectionVector: vec3f= (uniforms.reflectionMatrix* vec4f(vertexOutputs.vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvertexOutputs.vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector);\n#endif\n#endif\n#define CUSTOM_VERTEX_UPDATE_WORLDPOS\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {vertexOutputs.position=scene.viewProjection*worldPos;} else {vertexOutputs.position=scene.viewProjectionR*worldPos;}\n#else\nvertexOutputs.position=scene.viewProjection*worldPos;\n#endif\n#if DEBUGMODE>0\nvertexOutputs.vClipSpacePosition=vertexOutputs.position;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvertexOutputs.vDirectionW=normalize((finalWorld*vec4f(positionUpdated,0.0)).xyz);\n#endif\n#ifndef UV1\nvar uvUpdated: vec2f= vec2f(0.,0.);\n#endif\n#ifdef MAINUV1\nvertexOutputs.vMainUV1=uvUpdated;\n#endif\n#include[2..7]\n#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z)\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheenRoughness,_INFONAME_,SheenInfos.z)\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x)\n#endif\n#ifdef SUBSURFACE\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x)\n#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_MATRIXNAME_,translucencyColor,_INFONAME_,TranslucencyColorInfos.x)\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},38020:(e,t,i)=>{"use strict";i.r(t),i.d(t,{pickingPixelShaderWGSL:()=>n});const r="pickingPixelShader",s="#if defined(INSTANCES)\nvarying vMeshID: vec4f;\n#else\nuniform meshID: vec4f;\n#endif\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#if defined(INSTANCES)\nfragmentOutputs.color=input.vMeshID;\n#else\nfragmentOutputs.color=uniforms.meshID;\n#endif\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},17570:(e,t,i)=>{"use strict";i.r(t),i.d(t,{pickingVertexShaderWGSL:()=>o});var r=i(69841);i(25589),i(68273),i(47381),i(51148),i(41416),i(8573),i(43610),i(32764),i(40903),i(71281);const s="pickingVertexShader",n="attribute position: vec3f;\n#if defined(INSTANCES)\nattribute instanceMeshID: vec4f;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform viewProjection: mat4x4f;\n#if defined(INSTANCES)\nvarying vMeshID: vec4f;\n#endif\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvar worldPos: vec4f=finalWorld*vec4f(input.position,1.0);vertexOutputs.position=uniforms.viewProjection*worldPos;\n#if defined(INSTANCES)\nvertexOutputs.vMeshID=input.instanceMeshID;\n#endif\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},45010:(e,t,i)=>{"use strict";i.r(t),i.d(t,{postprocessVertexShaderWGSL:()=>n});const r="postprocessVertexShader",s="attribute position: vec2;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},67402:(e,t,i)=>{"use strict";i.r(t),i.d(t,{proceduralVertexShaderWGSL:()=>n});const r="proceduralVertexShader",s="attribute position: vec2f;varying vPosition: vec2f;varying vUV: vec2f;const madd: vec2f= vec2f(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.vPosition=input.position;vertexOutputs.vUV=input.position*madd+madd;vertexOutputs.position= vec4f(input.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},79388:(e,t,i)=>{"use strict";i.r(t),i.d(t,{rgbdDecodePixelShaderWGSL:()=>o});var r=i(69841);i(87647);const s="rgbdDecodePixelShader",n="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=vec4f(fromRGBD(textureSample(textureSampler,textureSamplerSampler,input.vUV)),1.0);}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},41572:(e,t,i)=>{"use strict";i.r(t),i.d(t,{rgbdEncodePixelShaderWGSL:()=>o});var r=i(69841);i(87647);const s="rgbdEncodePixelShader",n="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=toRGBD(textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb);}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},91944:(e,t,i)=>{"use strict";i.r(t),i.d(t,{rsmFullGlobalIlluminationPixelShaderWGSL:()=>n});const r="rsmFullGlobalIlluminationPixelShader",s="/**\n* The implementation is a direct application of the formula found in http:\n*/\nvarying vUV: vec2f;uniform rsmLightMatrix: mat4x4f;uniform rsmInfo: vec4f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var normalSamplerSampler: sampler;var normalSampler: texture_2d;var rsmPositionW: texture_2d;var rsmNormalW: texture_2d;var rsmFlux: texture_2d;\n#ifdef TRANSFORM_NORMAL\nuniform invView: mat4x4f;\n#endif\nfn computeIndirect(p: vec3f,n: vec3f)->vec3f {var indirectDiffuse: vec3f= vec3f(0.);var intensity: f32=uniforms.rsmInfo.z;var edgeArtifactCorrection: f32=uniforms.rsmInfo.w;var texRSM: vec4f=uniforms.rsmLightMatrix* vec4f(p,1.);texRSM=vec4f(texRSM.xy/texRSM.w,texRSM.z,texRSM.w);texRSM=vec4f(texRSM.xy*0.5+0.5,texRSM.z,texRSM.w);var width: i32= i32(uniforms.rsmInfo.x);var height: i32= i32(uniforms.rsmInfo.y);for (var j: i32=0; j(i,j);var vplPositionW: vec3f=textureLoad(rsmPositionW,uv,0).xyz;var vplNormalW: vec3f=textureLoad(rsmNormalW,uv,0).xyz*2.0-1.0;var vplFlux: vec3f=textureLoad(rsmFlux,uv,0).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; \nvar dist2: f32=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}}\nreturn clamp(indirectDiffuse*intensity,vec3f(0.0),vec3f(1.0));}\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var positionW: vec3f=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.vUV).xyz;var normalW: vec3f=textureSample(normalSampler,normalSamplerSampler,fragmentInputs.vUV).xyz;\n#ifdef DECODE_NORMAL\nnormalW=normalW*2.0-1.0;\n#endif\n#ifdef TRANSFORM_NORMAL\nnormalW=(uniforms.invView* vec4f(normalW,0.)).xyz;\n#endif\nfragmentOutputs.color=vec4f(computeIndirect(positionW,normalW),1.0);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},31583:(e,t,i)=>{"use strict";i.r(t),i.d(t,{rsmGlobalIlluminationPixelShaderWGSL:()=>n});const r="rsmGlobalIlluminationPixelShader",s="/**\n* The implementation is an application of the formula found in http:\n* 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).\n*/\nvarying vUV: vec2f;uniform rsmLightMatrix: mat4x4f;uniform rsmInfo: vec4f;uniform rsmInfo2: vec4f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var normalSamplerSampler: sampler;var normalSampler: texture_2d;var rsmPositionWSampler: sampler;var rsmPositionW: texture_2d;var rsmNormalWSampler: sampler;var rsmNormalW: texture_2d;var rsmFluxSampler: sampler;var rsmFlux: texture_2d;var rsmSamples: texture_2d;\n#ifdef TRANSFORM_NORMAL\nuniform invView: mat4x4f;\n#endif\nfn mod289(x: f32)->f32{return x-floor(x*(1.0/289.0))*289.0;}\nfn mod289Vec4(x: vec4f)->vec4f {return x-floor(x*(1.0/289.0))* 289.0;}\nfn perm(x: vec4f)->vec4f {return mod289Vec4(((x*34.0)+1.0)*x) ;}\nfn noise(p: vec3f)->f32{var a: vec3f=floor(p);var d: vec3f=p-a;d=d*d*(3.0-2.0*d);var b: vec4f=a.xxyy+ vec4f(0.0,1.0,0.0,1.0);var k1: vec4f=perm(b.xyxy);var k2: vec4f=perm(k1.xyxy+b.zzww);var c: vec4f=k2+a.zzzz;var k3: vec4f=perm(c);var k4: vec4f=perm(c+1.0);var o1: vec4f=fract(k3*(1.0/41.0));var o2: vec4f=fract(k4*(1.0/41.0));var o3: vec4f=o2*d.z+o1*(1.0-d.z);var o4: vec2f=o3.yw*d.x+o3.xz*(1.0-d.x);return o4.y*d.y+o4.x*(1.0-d.y);}\nfn computeIndirect(p: vec3f,n: vec3f)->vec3f {var indirectDiffuse: vec3f= vec3f(0.);var numSamples: i32= i32(uniforms.rsmInfo.x);var radius: f32=uniforms.rsmInfo.y;var intensity: f32=uniforms.rsmInfo.z;var edgeArtifactCorrection: f32=uniforms.rsmInfo.w;var texRSM: vec4f=uniforms.rsmLightMatrix* vec4f(p,1.);texRSM=vec4f(texRSM.xy/texRSM.w,texRSM.z,texRSM.w);texRSM=vec4f(texRSM.xy*0.5+0.5,texRSM.z,texRSM.w);var angle: f32=noise(p*uniforms.rsmInfo2.x);var c: f32=cos(angle);var s: f32=sin(angle);for (var i: i32=0; i(i,0),0).xyz;var weightSquare: f32=rsmSample.z;if (uniforms.rsmInfo2.y==1.0){rsmSample=vec3f(rsmSample.x*c+rsmSample.y*s,-rsmSample.x*s+rsmSample.y*c,rsmSample.z);}\nvar uv: vec2f=texRSM.xy+rsmSample.xy*radius;if (uv.x<0. || uv.x>1. || uv.y<0. || uv.y>1.) {continue;}\nvar vplPositionW: vec3f=textureSampleLevel(rsmPositionW,rsmPositionWSampler,uv,0.).xyz;var vplNormalW: vec3f=textureSampleLevel(rsmNormalW,rsmNormalWSampler,uv,0.).xyz*2.0-1.0;var vplFlux: vec3f=textureSampleLevel(rsmFlux,rsmFluxSampler,uv,0.).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; \nvar dist2: f32=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*weightSquare*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}\nreturn clamp(indirectDiffuse*intensity,vec3f(0.0),vec3f(1.0));}\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var positionW: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).xyz;var normalW: vec3f=textureSample(normalSampler,normalSamplerSampler,input.vUV).xyz;\n#ifdef DECODE_NORMAL\nnormalW=normalW*2.0-1.0;\n#endif\n#ifdef TRANSFORM_NORMAL\nnormalW=(uniforms.invView* vec4f(normalW,0.)).xyz;\n#endif\nfragmentOutputs.color=vec4f(computeIndirect(positionW,normalW),1.0);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},98e3:(e,t,i)=>{"use strict";i.r(t),i.d(t,{screenSpaceReflection2PixelShaderWGSL:()=>o});var r=i(69841);i(87647),i(20427),i(46357);const s="screenSpaceReflection2PixelShader",n="var textureSamplerSampler: sampler;var textureSampler: texture_2d;varying vUV: vec2f;\n#ifdef SSR_SUPPORTED\nvar reflectivitySamplerSampler: sampler;var reflectivitySampler: texture_2d;var normalSampler: texture_2d;var depthSampler: texture_2d;\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nvar backDepthSampler: texture_2d;uniform backSizeFactor: f32;\n#endif\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nvar envCubeSamplerSampler: sampler;var envCubeSampler: texture_cube;\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nuniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f;\n#endif\n#endif\nuniform view: mat4x4f;uniform invView: mat4x4f;uniform projection: mat4x4f;uniform invProjectionMatrix: mat4x4f;uniform projectionPixel: mat4x4f;uniform nearPlaneZ: f32;uniform farPlaneZ: f32;uniform stepSize: f32;uniform maxSteps: f32;uniform strength: f32;uniform thickness: f32;uniform roughnessFactor: f32;uniform reflectionSpecularFalloffExponent: f32;uniform maxDistance: f32;uniform selfCollisionNumSkip: f32;uniform reflectivityThreshold: f32;\n#include\n#include\n#include\nfn hash(a: vec3f)->vec3f\n{var result=fract(a*0.8);result+=dot(result,result.yxz+19.19);return fract((result.xxy+result.yxx)*result.zyx);}\nfn computeAttenuationForIntersection(ihitPixel: vec2f,hitUV: vec2f,vsRayOrigin: vec3f,vsHitPoint: vec3f,reflectionVector: vec3f,maxRayDistance: f32,numIterations: f32)->f32 {var attenuation: f32=1.0;\n#ifdef SSR_ATTENUATE_SCREEN_BORDERS\nvar dCoords: vec2f=smoothstep(vec2f(0.2),vec2f(0.6),abs( vec2f(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS\nattenuation*=1.0-(numIterations/uniforms.maxSteps);\n#endif\n#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION\nvar reflectionNormal: vec3f=texelFetch(normalSampler,hitPixel,0).xyz;var directionBasedAttenuation: f32=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation;\n#endif\nreturn attenuation;}\n#endif\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#ifdef SSR_SUPPORTED\nvar colorFull: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var color: vec3f=colorFull.rgb;var reflectivity: vec4f=textureSampleLevel(reflectivitySampler,reflectivitySamplerSampler,input.vUV,0.0);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=uniforms.reflectivityThreshold) {\n#ifdef SSR_USE_BLUR\nfragmentOutputs.color= vec4f(0.);\n#else\nfragmentOutputs.color=colorFull;\n#endif\nreturn fragmentOutputs;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpaceVec3(color);\n#endif\nvar texSize: vec2f= vec2f(textureDimensions(depthSampler,0));var csNormal: vec3f=textureLoad(normalSampler,vec2(input.vUV*texSize),0).xyz; \n#ifdef SSR_DECODE_NORMAL\ncsNormal=csNormal*2.0-1.0;\n#endif\n#ifdef SSR_NORMAL_IS_IN_WORLDSPACE\ncsNormal=(uniforms.view* vec4f(csNormal,0.0)).xyz;\n#endif\nvar depth: f32=textureLoad(depthSampler,vec2(input.vUV*texSize),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\ndepth=linearizeDepth(depth,uniforms.nearPlaneZ,uniforms.farPlaneZ);\n#endif\nvar csPosition: vec3f=computeViewPosFromUVDepth(input.vUV,depth,uniforms.projection,uniforms.invProjectionMatrix);\n#ifdef ORTHOGRAPHIC_CAMERA\nvar csViewDirection: vec3f= vec3f(0.,0.,1.);\n#else\nvar csViewDirection: vec3f=normalize(csPosition);\n#endif\nvar csReflectedVector: vec3f=reflect(csViewDirection,csNormal);\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nvar wReflectedVector: vec3f=(uniforms.invView* vec4f(csReflectedVector,0.0)).xyz;\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nvar worldPos: vec4f=uniforms.invView* vec4f(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),uniforms.vReflectionSize,uniforms.vReflectionPosition);\n#endif\n#ifdef SSR_INVERTCUBICMAP\nwReflectedVector.y*=-1.0;\n#endif\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nwReflectedVector.z*=-1.0;\n#endif\nvar envColor: vec3f=textureSampleLevel(envCubeSampler,envCubeSamplerSampler,wReflectedVector,0.0).xyz;\n#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE\nenvColor=toLinearSpaceVec3(envColor);\n#endif\n#else\nvar envColor: vec3f=color;\n#endif\nvar reflectionAttenuation: f32=1.0;var rayHasHit: bool=false;var startPixel: vec2f;var hitPixel: vec2f;var hitPoint: vec3f;var numIterations: f32;\n#ifdef SSRAYTRACE_DEBUG\nvar debugColor: vec3f;\n#endif\n#ifdef SSR_ATTENUATE_FACING_CAMERA\nreflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector));\n#endif\nif (reflectionAttenuation>0.0) {\n#ifdef SSR_USE_BLUR\nvar jitt: vec3f= vec3f(0.);\n#else\nvar roughness: f32=1.0-reflectivity.a;var jitt: vec3f=mix( vec3f(0.0),hash(csPosition)- vec3f(0.5),roughness)*uniforms.roughnessFactor; \n#endif\nvar uv2: vec2f=input.vUV*texSize;var c: f32=(uv2.x+uv2.y)*0.25;var jitter: f32=((c)%(1.0)); \nrayHasHit=traceScreenSpaceRay1(\ncsPosition,\nnormalize(csReflectedVector+jitt),\nuniforms.projectionPixel,\ndepthSampler,\ntexSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nbackDepthSampler,\nuniforms.backSizeFactor,\n#endif\nuniforms.thickness,\nuniforms.nearPlaneZ,\nuniforms.farPlaneZ,\nuniforms.stepSize,\njitter,\nuniforms.maxSteps,\nuniforms.maxDistance,\nuniforms.selfCollisionNumSkip,\n&startPixel,\n&hitPixel,\n&hitPoint,\n&numIterations\n#ifdef SSRAYTRACE_DEBUG\n,&debugColor\n#endif\n);}\n#ifdef SSRAYTRACE_DEBUG\nfragmentOutputs.color= vec4f(debugColor,1.);return fragmentOutputs;\n#endif\nvar F0: vec3f=reflectivity.rgb;var fresnel: vec3f=fresnelSchlickGGXVec3(max(dot(csNormal,-csViewDirection),0.0),F0, vec3f(1.));var SSR: vec3f=envColor;if (rayHasHit) {var reflectedColor: vec3f=textureLoad(textureSampler,vec2(hitPixel),0).rgb;\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\nreflectedColor=toLinearSpaceVec3(reflectedColor);\n#endif\nreflectionAttenuation*=computeAttenuationForIntersection(hitPixel,hitPixel/texSize,csPosition,hitPoint,csReflectedVector,uniforms.maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;}\n#ifndef SSR_BLEND_WITH_FRESNEL\nSSR*=fresnel;\n#endif\n#ifdef SSR_USE_BLUR\nvar blur_radius: f32=0.0;var roughness: f32=1.0-reflectivity.a*(1.0-uniforms.roughnessFactor);if (roughness>0.001) {var cone_angle: f32=min(roughness,0.999)*3.14159265*0.5;var cone_len: f32=distance(startPixel,hitPixel);var op_len: f32=2.0*tan(cone_angle)*cone_len; \nvar a: f32=op_len;var h: f32=cone_len;var a2: f32=a*a;var fh2: f32=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);}\nfragmentOutputs.color= vec4f(SSR,blur_radius/255.0); \n#else\n#ifdef SSR_BLEND_WITH_FRESNEL\nvar reflectionMultiplier: vec3f=clamp(pow(fresnel*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0));\n#else\nvar reflectionMultiplier: vec3f=clamp(pow(reflectivity.rgb*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0));\n#endif\nvar colorMultiplier: vec3f=1.0-reflectionMultiplier;var finalColor: vec3f=(color*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpaceVec3(finalColor);\n#endif\nfragmentOutputs.color= vec4f(finalColor,colorFull.a);\n#endif\n#else\nfragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);\n#endif\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},86763:(e,t,i)=>{"use strict";i.r(t),i.d(t,{screenSpaceReflection2BlurPixelShaderWGSL:()=>n});const r="screenSpaceReflection2BlurPixelShader",s="var textureSamplerSampler: sampler;var textureSampler: texture_2d;varying vUV: vec2f;uniform texelOffsetScale: vec2f;const weights: array=array(0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);fn processSample(uv: vec2f,i: f32,stepSize: vec2f,accumulator: ptr,denominator: ptr)\n{var offsetUV: vec2f=stepSize*i+uv;var coefficient: f32=weights[ i32(2.0-abs(i))];*accumulator+=textureSampleLevel(textureSampler,textureSamplerSampler,offsetUV,0.0)*coefficient;*denominator+=coefficient;}\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var colorFull: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);if (dot(colorFull, vec4f(1.0))==0.0) {fragmentOutputs.color=colorFull;return fragmentOutputs;}\nvar blurRadius: f32=colorFull.a*255.0; \nvar stepSize: vec2f=uniforms.texelOffsetScale.xy*blurRadius;var accumulator: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0)*0.214607;var denominator: f32=0.214607;processSample(input.vUV,1.0,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.2,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.4,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.6,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.8,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.2,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.4,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.6,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.8,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*2.0,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.2,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.4,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.6,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.8,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.2,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.4,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.6,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.8,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*2.0,stepSize,&accumulator,&denominator);fragmentOutputs.color= vec4f(accumulator.rgb/denominator,colorFull.a);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},20136:(e,t,i)=>{"use strict";i.r(t),i.d(t,{screenSpaceReflection2BlurCombinerPixelShaderWGSL:()=>o});var r=i(69841);i(87647),i(20427),i(46357);const s="screenSpaceReflection2BlurCombinerPixelShader",n="var textureSamplerSampler: sampler;var textureSampler: texture_2d; \nvar mainSamplerSampler: sampler;var mainSampler: texture_2d;var reflectivitySamplerSampler: sampler;var reflectivitySampler: texture_2d;uniform strength: f32;uniform reflectionSpecularFalloffExponent: f32;uniform reflectivityThreshold: f32;varying vUV: vec2f;\n#include\n#ifdef SSR_BLEND_WITH_FRESNEL\n#include\n#include\nuniform projection: mat4x4f;uniform invProjectionMatrix: mat4x4f;var normalSampler: texture_2d;var depthSampler: texture_2d;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\nuniform nearPlaneZ: f32;uniform farPlaneZ: f32;\n#endif\n#endif\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#ifdef SSRAYTRACE_DEBUG\nfragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);\n#else\nvar SSR: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var color: vec4f=textureSample(mainSampler,textureSamplerSampler,input.vUV);var reflectivity: vec4f=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vUV);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=uniforms.reflectivityThreshold) {fragmentOutputs.color=color;return fragmentOutputs;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpaceVec4(color);\n#endif\n#ifdef SSR_BLEND_WITH_FRESNEL\nvar texSize: vec2f= vec2f(textureDimensions(depthSampler,0));var csNormal: vec3f=textureLoad(normalSampler,vec2(input.vUV*texSize),0).xyz;var depth: f32=textureLoad(depthSampler,vec2(input.vUV*texSize),0).r;\n#ifdef SSRAYTRACE_SCREENSPACE_DEPTH\ndepth=linearizeDepth(depth,uniforms.nearPlaneZ,uniforms.farPlaneZ);\n#endif\nvar csPosition: vec3f=computeViewPosFromUVDepth(input.vUV,depth,uniforms.projection,uniforms.invProjectionMatrix);var csViewDirection: vec3f=normalize(csPosition);var F0: vec3f=reflectivity.rgb;var fresnel: vec3f=fresnelSchlickGGXVec3(max(dot(csNormal,-csViewDirection),0.0),F0, vec3f(1.));var reflectionMultiplier: vec3f=clamp(pow(fresnel*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0));\n#else\nvar reflectionMultiplier: vec3f=clamp(pow(reflectivity.rgb*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0));\n#endif\nvar colorMultiplier: vec3f=1.0-reflectionMultiplier;var finalColor: vec3f=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpaceVec3(finalColor);\n#endif\nfragmentOutputs.color= vec4f(finalColor,color.a);\n#endif\n}\n";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},89778:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowMapPixelShaderWGSL:()=>o});var r=i(69841);i(2456);r.l.IncludesShadersStoreWGSL.bayerDitherFunctions="fn bayerDither2(_P: vec2f)->f32 {return ((2.0*_P.y+_P.x+1.0)%(4.0));}\nfn bayerDither4(_P: vec2f)->f32 {var P1: vec2f=((_P)%(2.0)); \nvar P2: vec2f=floor(0.5*((_P)%(4.0))); \nreturn 4.0*bayerDither2(P1)+bayerDither2(P2);}\nfn bayerDither8(_P: vec2f)->f32 {var P1: vec2f=((_P)%(2.0)); \nvar P2: vec2f=floor(0.5 *((_P)%(4.0))); \nvar P4: vec2f=floor(0.25*((_P)%(8.0))); \nreturn 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);}\n";r.l.IncludesShadersStoreWGSL.shadowMapFragmentExtraDeclaration="#if SM_FLOAT==0\n#include\n#endif\n#if SM_SOFTTRANSPARENTSHADOW==1\n#include\nuniform softTransparentShadowSM: vec2f;\n#endif\nvarying vDepthMetricSM: f32;\n#if SM_USEDISTANCE==1\nuniform lightDataSM: vec3f;varying vPositionWSM: vec3f;\n#endif\nuniform biasAndScaleSM: vec3f;uniform depthValuesSM: vec2f;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying zSM: f32;\n#endif\n",i(96140),i(76794),i(43140);const s="shadowMapPixelShader",n="#include\n#ifdef ALPHATEXTURE\nvarying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#include\n#ifdef ALPHATEXTURE\nvar opacityMap: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vUV);var alphaFromAlphaTexture: f32=opacityMap.a;\n#if SM_SOFTTRANSPARENTSHADOW==1\nif (uniforms.softTransparentShadowSM.y==1.0) {opacityMap=vec4f(opacityMap.rgb* vec3f(0.3,0.59,0.11),opacityMap.a);alphaFromAlphaTexture=opacityMap.x+opacityMap.y+opacityMap.z;}\n#endif\n#ifdef ALPHATESTVALUE\nif (alphaFromAlphaTexture=uniforms.softTransparentShadowSM.x*alphaFromAlphaTexture) {discard;}\n#else\nif ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.softTransparentShadowSM.x) {discard;} \n#endif\n#endif\n#include\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},90396:(e,t,i)=>{"use strict";i.r(t),i.d(t,{shadowMapVertexShaderWGSL:()=>o});var r=i(69841);i(25589),i(68273),i(47381),i(51148),i(87647),i(14910),i(10598);r.l.IncludesShadersStoreWGSL.shadowMapVertexExtraDeclaration="#if SM_NORMALBIAS==1\nuniform lightDataSM: vec3f;\n#endif\nuniform biasAndScaleSM: vec3f;uniform depthValuesSM: vec2f;varying vDepthMetricSM: f32;\n#if SM_USEDISTANCE==1\nvarying vPositionWSM: vec3f;\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying zSM: f32;\n#endif\n",i(30486),i(8573),i(43610),i(32764),i(40903),i(71281);r.l.IncludesShadersStoreWGSL.shadowMapVertexNormalBias="#if SM_NORMALBIAS==1\n#if SM_DIRECTIONINLIGHTDATA==1\nvar worldLightDirSM: vec3f=normalize(-uniforms.lightDataSM.xyz);\n#else\nvar directionToLightSM: vec3f=uniforms.lightDataSM.xyz-worldPos.xyz;var worldLightDirSM: vec3f=normalize(directionToLightSM);\n#endif\nvar ndlSM: f32=dot(vNormalW,worldLightDirSM);var sinNLSM: f32=sqrt(1.0-ndlSM*ndlSM);var normalBiasSM: f32=uniforms.biasAndScaleSM.y*sinNLSM;worldPos=vec4f(worldPos.xyz-vNormalW*normalBiasSM,worldPos.w);\n#endif\n",i(18902),i(57728);const s="shadowMapVertexShader",n="attribute position: vec3f;\n#ifdef NORMAL\nattribute normal: vec3f;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef INSTANCES\nattribute world0: vec4f;attribute world1: vec4f;attribute world2: vec4f;attribute world3: vec4f;\n#endif\n#include\n#include\n#include\n#ifdef ALPHATEXTURE\nvarying vUV: vec2f;uniform diffuseMatrix: mat4x4f;\n#ifdef UV1\nattribute uv: vec2f;\n#endif\n#ifdef UV2\nattribute uv2: vec2f;\n#endif\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;\n#ifdef UV1\nvar uvUpdated: vec2f=input.uv;\n#endif\n#ifdef NORMAL\nvar normalUpdated: vec3f=input.normal;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvar worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);\n#ifdef NORMAL\nvar normWorldSM: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvar vNormalW: vec3f=normalUpdated/ vec3f(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvar vNormalW: vec3f=normalize(normWorldSM*normalUpdated);\n#endif\n#endif\n#include\nvertexOutputs.position=scene.viewProjection*worldPos;\n#include\n#ifdef ALPHATEXTURE\n#ifdef UV1\nvertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy;\n#endif\n#ifdef UV2\nvertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(input.uv2,1.0,0.0)).xy;\n#endif\n#endif\n#include\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},68820:(e,t,i)=>{"use strict";i.r(t),i.d(t,{sharpenPixelShaderWGSL:()=>n});const r="sharpenPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f;uniform sharpnessAmounts: vec2f;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var onePixel: vec2f= vec2f(1.0,1.0)/uniforms.screenSize;var color: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);var edgeDetection: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(0,-1)) +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(-1,0)) +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(1,0)) +\ntextureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(0,1)) -\ncolor*4.0;fragmentOutputs.color=max(vec4f(color.rgb*uniforms.sharpnessAmounts.y,color.a)-(uniforms.sharpnessAmounts.x* vec4f(edgeDetection.rgb,0)),vec4f(0.));}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},25151:(e,t,i)=>{"use strict";i.r(t),i.d(t,{spritesPixelShaderWGSL:()=>o});var r=i(69841);i(10668),i(21859),i(85551),i(31034);r.l.IncludesShadersStoreWGSL.imageProcessingCompatibility="#ifdef IMAGEPROCESSINGPOSTPROCESS\nfragmentOutputs.color=vec4f(pow(fragmentOutputs.color.rgb, vec3f(2.2)),fragmentOutputs.color.a);\n#endif\n";const s="spritesPixelShader",n="uniform alphaTest: i32;varying vColor: vec4f;varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d;\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#ifdef PIXEL_PERFECT\nfn uvPixelPerfect(uv: vec2f)->vec2f {var res: vec2f= vec2f(textureDimensions(diffuseSampler,0));var uvTemp=uv*res;var seam: vec2f=floor(uvTemp+0.5);uvTemp=seam+clamp((uvTemp-seam)/fwidth(uvTemp),vec2f(-0.5),vec2f(0.5));return uvTemp/res;}\n#endif\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#ifdef PIXEL_PERFECT\nvar uv: vec2f=uvPixelPerfect(input.vUV);\n#else\nvar uv: vec2f=input.vUV;\n#endif\nvar color: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,uv);var fAlphaTest: f32= f32(uniforms.alphaTest);if (fAlphaTest != 0.)\n{if (color.a<0.95) {discard;}}\ncolor*=input.vColor;\n#include\n#include\nfragmentOutputs.color=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},56029:(e,t,i)=>{"use strict";i.r(t),i.d(t,{spritesVertexShaderWGSL:()=>o});var r=i(69841);i(86934),i(21859),i(18201);const s="spritesVertexShader",n="attribute position: vec4f;attribute options: vec2f;attribute offsets: vec2f;attribute inverts: vec2f;attribute cellInfo: vec4f;attribute color: vec4f;uniform view: mat4x4f;uniform projection: mat4x4f;varying vUV: vec2f;varying vColor: vec4f;\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvar viewPos: vec3f=(uniforms.view* vec4f(input.position.xyz,1.0)).xyz; \nvar cornerPos: vec2f;var angle: f32=input.position.w;var size: vec2f= vec2f(input.options.x,input.options.y);var offset: vec2f=input.offsets.xy;cornerPos= vec2f(offset.x-0.5,offset.y -0.5)*size;var rotatedCorner: vec3f;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;vertexOutputs.position=uniforms.projection*vec4f(viewPos,1.0); \nvertexOutputs.vColor=input.color;var uvOffset: vec2f= vec2f(abs(offset.x-input.inverts.x),abs(1.0-offset.y-input.inverts.y));var uvPlace: vec2f=input.cellInfo.xy;var uvSize: vec2f=input.cellInfo.zw;vertexOutputs.vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vertexOutputs.vUV.y=uvPlace.y+uvSize.y*uvOffset.y;\n#ifdef FOG\nvertexOutputs.vFogDistance=viewPos;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";r.l.ShadersStoreWGSL[s]=n;const o={name:s,shader:n}},20661:(e,t,i)=>{"use strict";i.r(t),i.d(t,{ssao2PixelShaderWGSL:()=>n});const r="ssao2PixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;\n#ifdef SSAO\nconst scales: array=array(\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);uniform near: f32;uniform radius: f32;var depthSamplerSampler: sampler;var depthSampler: texture_2d;var randomSamplerSampler: sampler;var randomSampler: texture_2d;var normalSamplerSampler: sampler;var normalSampler: texture_2d;uniform randTextureTiles: f32;uniform samplesFactor: f32;uniform sampleSphere: array;uniform totalStrength: f32;uniform base: f32;uniform xViewport: f32;uniform yViewport: f32;uniform depthProjection: mat3x3f;uniform maxZ: f32;uniform minZAspect: f32;uniform texelSize: vec2f;uniform projection: mat4x4f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var random: vec3f=textureSampleLevel(randomSampler,randomSamplerSampler,input.vUV*uniforms.randTextureTiles,0.0).rgb;var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.0).r;var depthSign: f32=sign(depth);depth=depth*depthSign;var normal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV,0.0).rgb;var occlusion: f32=0.0;var correctedRadius: f32=min(uniforms.radius,uniforms.minZAspect*depth/uniforms.near);var vViewRay: vec3f= vec3f((input.vUV.x*2.0-1.0)*uniforms.xViewport,(input.vUV.y*2.0-1.0)*uniforms.yViewport,depthSign);var vDepthFactor: vec3f=uniforms.depthProjection* vec3f(1.0,1.0,depth);var origin: vec3f=vViewRay*vDepthFactor;var rvec: vec3f=random*2.0-1.0;rvec.z=0.0;var dotProduct: f32=dot(rvec,normal);rvec=select( vec3f(-rvec.y,0.0,rvec.x),rvec,1.0-abs(dotProduct)>1e-2);var tangent: vec3f=normalize(rvec-normal*dot(rvec,normal));var bitangent: vec3f=cross(normal,tangent);var tbn: mat3x3f= mat3x3f(tangent,bitangent,normal);var difference: f32;for (var i: i32=0; i1.0 || offset.y>1.0) {continue;}\nvar sampleDepth: f32=abs(textureSampleLevel(depthSampler,depthSamplerSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;var rangeCheck: f32=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;}\nocclusion=occlusion*(1.0-smoothstep(uniforms.maxZ*0.75,uniforms.maxZ,depth));var ao: f32=1.0-uniforms.totalStrength*occlusion*uniforms.samplesFactor;var result: f32=clamp(ao+uniforms.base,0.0,1.0);fragmentOutputs.color= vec4f( vec3f(result),1.0);}\n#else\n#ifdef BLUR\nuniform outSize: f32;uniform soften: f32;uniform tolerance: f32;uniform samples: i32;\n#ifndef BLUR_BYPASS\nvar depthSamplerSampler: sampler;var depthSampler: texture_2d;\n#ifdef BLUR_LEGACY\nfn blur13Bilateral(image: texture_2d,imageSampler: sampler,uv: vec2f,step: vec2f)->f32 {var result: f32=0.0;var off1: vec2f= vec2f(1.411764705882353)*step;var off2: vec2f= vec2f(3.2941176470588234)*step;var off3: vec2f= vec2f(5.176470588235294)*step;var compareDepth: f32=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv,0.0).r);var sampleDepth: f32;var weight: f32;var weightSum: f32=30.0;result+=textureSampleLevel(image,imageSampler,uv,0.0).r*30.0;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureSampleLevel(image,imageSampler,uv+off1,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureSampleLevel(image,imageSampler,uv-off1,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv+off2,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv-off2,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv+off3,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv-off3,0.0).r*weight;return result/weightSum;}\n#endif\n#endif\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var result: f32=0.0;\n#ifdef BLUR_BYPASS\nresult=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0).r;\n#else\n#ifdef BLUR_H\nvar step: vec2f= vec2f(1.0/uniforms.outSize,0.0);\n#else\nvar step: vec2f= vec2f(0.0,1.0/uniforms.outSize);\n#endif\n#ifdef BLUR_LEGACY\nresult=blur13Bilateral(textureSampler,textureSamplerSampler,input.vUV,step);\n#else\nvar compareDepth: f32=abs(textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.0).r);var weightSum: f32=0.0;for (var i: i32=-uniforms.samples; i{"use strict";i.r(t),i.d(t,{ssaoCombinePixelShaderWGSL:()=>n});const r="ssaoCombinePixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var originalColorSampler: sampler;var originalColor: texture_2d;uniform viewport: vec4f;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvar ssaoColor: vec4f=textureSample(textureSampler,textureSamplerSampler,uniforms.viewport.xy+input.vUV*uniforms.viewport.zw);var sceneColor: vec4f=textureSample(originalColor,originalColorSampler,input.vUV);fragmentOutputs.color=sceneColor*ssaoColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},88559:(e,t,i)=>{"use strict";i.r(t),i.d(t,{taaPixelShaderWGSL:()=>n});const r="taaPixelShader",s="var textureSampler: texture_2d;var historySampler: texture_2d;uniform factor: f32;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {let c=textureLoad(textureSampler,vec2(fragmentInputs.position.xy),0);let h=textureLoad(historySampler,vec2(fragmentInputs.position.xy),0);fragmentOutputs.color= mix(h,c,uniforms.factor);}\n";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},41739:(e,t,i)=>{"use strict";i.r(t),i.d(t,{tonemapPixelShaderWGSL:()=>n});const r="tonemapPixelShader",s="varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform _ExposureAdjustment: f32;\n#if defined(HABLE_TONEMAPPING)\nconst A: f32=0.15;const B: f32=0.50;const C: f32=0.10;const D: f32=0.20;const E: f32=0.02;const F: f32=0.30;const W: f32=11.2;\n#endif\nfn Luminance(c: vec3f)->f32\n{return dot(c, vec3f(0.22,0.707,0.071));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var colour: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nvar lum: f32=Luminance(colour.rgb); \nvar lumTm: f32=lum*uniforms._ExposureAdjustment;var scale: f32=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=uniforms._ExposureAdjustment;const ExposureBias: f32=2.0;var x: vec3f=ExposureBias*colour;var curr: vec3f=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x= vec3f(W,W,W);var whiteScale: vec3f=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=uniforms._ExposureAdjustment;var X: vec3f=max( vec3f(0.0,0.0,0.0),colour-0.004);var retColor: vec3f=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour= vec3f(1.0,1.0,1.0)-exp2(-uniforms._ExposureAdjustment*colour);\n#endif\nfragmentOutputs.color= vec4f(colour.rgb,1.0);}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},79132:(e,t,i)=>{"use strict";i.r(t),i.d(t,{vrDistortionCorrectionPixelShaderWGSL:()=>n});const r="vrDistortionCorrectionPixelShader",s="#define DISABLE_UNIFORMITY_ANALYSIS\nvarying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform LensCenter: vec2f;uniform Scale: vec2f;uniform ScaleIn: vec2f;uniform HmdWarpParam: vec4f;fn HmdWarp(in01: vec2f)->vec2f {var theta: vec2f=(in01-uniforms.LensCenter)*uniforms.ScaleIn; \nvar rSq: f32=theta.x*theta.x+theta.y*theta.y;var rvector: vec2f=theta*(uniforms.HmdWarpParam.x+uniforms.HmdWarpParam.y*rSq+uniforms.HmdWarpParam.z*rSq*rSq+uniforms.HmdWarpParam.w*rSq*rSq*rSq);return uniforms.LensCenter+uniforms.Scale*rvector;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\n@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var tc: vec2f=HmdWarp(input.vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0) {fragmentOutputs.color=vec4f(0.0,0.0,0.0,0.0);}\nelse{fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,tc);}}";i(69841).l.ShadersStoreWGSL[r]=s;const n={name:r,shader:s}},94895:(e,t,i)=>{"use strict";i.d(t,{i:()=>r});class r{constructor(){this._blendFunctionParameters=new Array(4),this._blendEquationParameters=new Array(2),this._blendConstants=new Array(4),this._isBlendConstantsDirty=!1,this._alphaBlend=!1,this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this.reset()}get isDirty(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty||this._isBlendEquationParametersDirty}get alphaBlend(){return this._alphaBlend}set alphaBlend(e){this._alphaBlend!==e&&(this._alphaBlend=e,this._isAlphaBlendDirty=!0)}setAlphaBlendConstants(e,t,i,r){this._blendConstants[0]===e&&this._blendConstants[1]===t&&this._blendConstants[2]===i&&this._blendConstants[3]===r||(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=i,this._blendConstants[3]=r,this._isBlendConstantsDirty=!0)}setAlphaBlendFunctionParameters(e,t,i,r){this._blendFunctionParameters[0]===e&&this._blendFunctionParameters[1]===t&&this._blendFunctionParameters[2]===i&&this._blendFunctionParameters[3]===r||(this._blendFunctionParameters[0]=e,this._blendFunctionParameters[1]=t,this._blendFunctionParameters[2]=i,this._blendFunctionParameters[3]=r,this._isBlendFunctionParametersDirty=!0)}setAlphaEquationParameters(e,t){this._blendEquationParameters[0]===e&&this._blendEquationParameters[1]===t||(this._blendEquationParameters[0]=e,this._blendEquationParameters[1]=t,this._isBlendEquationParametersDirty=!0)}reset(){this._alphaBlend=!1,this._blendFunctionParameters[0]=null,this._blendFunctionParameters[1]=null,this._blendFunctionParameters[2]=null,this._blendFunctionParameters[3]=null,this._blendEquationParameters[0]=null,this._blendEquationParameters[1]=null,this._blendConstants[0]=null,this._blendConstants[1]=null,this._blendConstants[2]=null,this._blendConstants[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1}apply(e){this.isDirty&&(this._isAlphaBlendDirty&&(this._alphaBlend?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),this._isBlendEquationParametersDirty&&(e.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1),this._isBlendConstantsDirty&&(e.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1))}}},14506:(e,t,i)=>{"use strict";i.d(t,{N:()=>r});class r{constructor(e=!0){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,e&&this.reset()}get isDirty(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0)}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0)}reset(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._zOffsetUnits=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!0,this._isFrontFaceDirty=!1}apply(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset||this.zOffsetUnits?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,this.zOffsetUnits)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(e.frontFace(this.frontFace),this._isFrontFaceDirty=!1))}}},69905:(e,t,i)=>{"use strict";i.d(t,{K:()=>r});class r{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=r.ALWAYS,this.funcRef=1,this.funcMask=255,this.opStencilFail=r.KEEP,this.opDepthFail=r.KEEP,this.opStencilDepthPass=r.REPLACE}get stencilFunc(){return this.func}set stencilFunc(e){this.func=e}get stencilFuncRef(){return this.funcRef}set stencilFuncRef(e){this.funcRef=e}get stencilFuncMask(){return this.funcMask}set stencilFuncMask(e){this.funcMask=e}get stencilOpStencilFail(){return this.opStencilFail}set stencilOpStencilFail(e){this.opStencilFail=e}get stencilOpDepthFail(){return this.opDepthFail}set stencilOpDepthFail(e){this.opDepthFail=e}get stencilOpStencilDepthPass(){return this.opStencilDepthPass}set stencilOpStencilDepthPass(e){this.opStencilDepthPass=e}get stencilMask(){return this.mask}set stencilMask(e){this.mask=e}get stencilTest(){return this.enabled}set stencilTest(e){this.enabled=e}}r.ALWAYS=519,r.KEEP=7680,r.REPLACE=7681},67715:(e,t,i)=>{"use strict";i.d(t,{u:()=>r});class r{get isDirty(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._isStencilFuncDirty=!0)}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef!==e&&(this._funcRef=e,this._isStencilFuncDirty=!0)}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._isStencilFuncDirty=!0)}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._isStencilOpDirty=!0)}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._isStencilOpDirty=!0)}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._isStencilOpDirty=!0)}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._isStencilMaskDirty=!0)}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._isStencilTestDirty=!0)}constructor(e=!0){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.useStencilGlobalOnly=!1,e&&this.reset()}reset(){this.stencilMaterial=void 0,this.stencilGlobal?.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){if(!e)return;const t=!this.useStencilGlobalOnly&&!!this.stencilMaterial?.enabled;this.enabled=t?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=t?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=t?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=t?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=t?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=t?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=t?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=t?this.stencilMaterial.mask:this.stencilGlobal.mask,this.isDirty&&(this._isStencilTestDirty&&(this.enabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.mask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFunc(this.func,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOp(this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),this._isStencilOpDirty=!1))}}},83194:(e,t,i)=>{"use strict";i.d(t,{h:()=>r});class r{}r._IsPickingAvailable=!1},14747:(e,t,i)=>{"use strict";i.d(t,{b:()=>u});var r=i(15287),s=i(94212),n=i(40220),o=i(43279),a=i(34268),l=i(75108),h=i(89518);class c{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new o.cP,this._onClonedObservable=new o.cP}}class u{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,r){const s=this._NodeConstructors[e];return s?s(t,i,r):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return!!this._nodeDataStorage._doNotSerialize||!!this._parentNode&&this._parentNode.doNotSerialize}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&&void 0!==this._parentNode._children&&null!==this._parentNode._children){const t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1),e||this._nodeDataStorage._isDisposed||this._addToSceneRootNodes()}this._parentNode=e,this._isDirty=!0,this._parentNode&&(void 0!==this._parentNode._children&&null!==this._parentNode._children||(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(){-1===this._nodeDataStorage._sceneRootNodesIndex&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(-1!==this._nodeDataStorage._sceneRootNodesIndex){const e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}getClassName(){return"Node"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onEnabledStateChangedObservable(){return this._nodeDataStorage._onEnabledStateChangedObservable}get onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null,i=!0){this._isDirty=!1,this._nodeDataStorage=new c,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new o.cP,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=s.uq.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new o.cP,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||a.q.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache(),i&&this._addToSceneRootNodes()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){return-1!==this._behaviors.indexOf(e)||(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-1===t||(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&&this._parentNode.isSynchronized()}isSynchronized(){return!(this._parentNode&&!this.isSynchronizedWithParent())&&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!1===e?this._nodeDataStorage._isEnabled:!!this._nodeDataStorage._isEnabled&&this._nodeDataStorage._isParentEnabled}_syncParentEnabledState(){this._nodeDataStorage._isParentEnabled=!this._parentNode||this._parentNode.isEnabled(),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||this.parent.isDescendantOf(e))}_getDescendants(e,t=!1,i){if(this._children)for(let r=0;r(!t||t(e))&&void 0!==e.cullingStrategy)),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){e!==this._nodeDataStorage._isReady&&(e?(this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0):this._nodeDataStorage._isReady=!1)}getAnimationByName(e){for(let t=0;tnew u(e,this.getScene())),this);if(t&&(r.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;i{throw(0,l.n)("AnimationRange")},u._NodeConstructors={},(0,r.Cg)([(0,n.lK)()],u.prototype,"name",void 0),(0,r.Cg)([(0,n.lK)()],u.prototype,"id",void 0),(0,r.Cg)([(0,n.lK)()],u.prototype,"uniqueId",void 0),(0,r.Cg)([(0,n.lK)()],u.prototype,"state",void 0),(0,r.Cg)([(0,n.lK)()],u.prototype,"metadata",void 0)},88193:(e,t,i)=>{"use strict";i.d(t,{Z:()=>k,F:()=>L});var r=i(9723),s=i(64736),n=i(43279),o=i(39464),a=i(47131),l=i(84015),h=i(94212),c=i(69648),u=i(4216),d=i(81310),f=i(89357),p=i(2449),_=i(75653),m=i(9180),g=i(68191),v=i(34268),x=i(75108),b=i(1241),S=i(96772),T=i(80109),C=i(58292),y=i(78035),E=i(83194);class P{constructor(){this._singleClick=!1,this._doubleClick=!1,this._hasSwiped=!1,this._ignore=!1}get singleClick(){return this._singleClick}get doubleClick(){return this._doubleClick}get hasSwiped(){return this._hasSwiped}get ignore(){return this._ignore}set singleClick(e){this._singleClick=e}set doubleClick(e){this._doubleClick=e}set hasSwiped(e){this._hasSwiped=e}set ignore(e){this._ignore=e}}class A{constructor(e){this._alreadyAttached=!1,this._meshPickProceed=!1,this._currentPickResult=null,this._previousPickResult=null,this._activePointerIds=new Array,this._activePointerIdsCount=0,this._doubleClickOccured=!1,this._isSwiping=!1,this._swipeButtonPressed=-1,this._skipPointerTap=!1,this._isMultiTouchGesture=!1,this._pointerX=0,this._pointerY=0,this._startingPointerPosition=new h.I9(0,0),this._previousStartingPointerPosition=new h.I9(0,0),this._startingPointerTime=0,this._previousStartingPointerTime=0,this._pointerCaptures={},this._meshUnderPointerId={},this._movePointerInfo=null,this._cameraObserverCount=0,this._delayedClicks=[null,null,null,null,null],this._deviceSourceManager=null,this._scene=e||v.q.LastCreatedScene,this._scene}get meshUnderPointer(){return this._movePointerInfo&&(this._movePointerInfo._generatePickInfo(),this._movePointerInfo=null),this._pointerOverMesh}getMeshUnderPointerByPointerId(e){return this._meshUnderPointerId[e]||null}get unTranslatedPointer(){return new h.I9(this._unTranslatedPointerX,this._unTranslatedPointerY)}get pointerX(){return this._pointerX}set pointerX(e){this._pointerX=e}get pointerY(){return this._pointerY}set pointerY(e){this._pointerY=e}_updatePointerPosition(e){const t=this._scene.getEngine().getInputElementClientRect();t&&(this._pointerX=e.clientX-t.left,this._pointerY=e.clientY-t.top,this._unTranslatedPointerX=this._pointerX,this._unTranslatedPointerY=this._pointerY)}_processPointerMove(e,t){const i=this._scene,r=i.getEngine(),s=r.getInputElement();s&&(s.tabIndex=r.canvasTabIndex,i.doNotHandleCursors||(s.style.cursor=i.defaultCursor)),this._setCursorAndPointerOverMesh(e,t,i);for(const r of i._pointerMoveStage){e=e||this._pickMove(t);const i=!!e?.pickedMesh;e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,i,s)}const n=t.inputIndex>=C.ST.MouseWheelX&&t.inputIndex<=C.ST.MouseWheelZ?b.Zp.POINTERWHEEL:b.Zp.POINTERMOVE;let o;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,n)),e?(o=new b.mx(n,t,e),this._setRayOnPointerInfo(e,t)):(o=new b.mx(n,t,null,this),this._movePointerInfo=o),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(o,n)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&E.h._IsPickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,h.uq.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){const r=this._scene,s=new b.tT(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(s.originalPickingInfo=e,s.ray=e.ray,"xr-near"===t.pointerType&&e.originMesh&&(s.nearInteractionPickingInfo=e)),r.onPrePointerObservable.notifyObservers(s,i),!!s.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const r=i.getEngine().getInputElement();if(e?.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&r&&this._pointerOverMesh){const e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(r.style.cursor=e.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=C.ST.Move,this._checkPrePointerObservable(e,i,b.Zp.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,b.Zp.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e?.pickedMesh){this._pickedDownMesh=e.pickedMesh;const r=e.pickedMesh._getActionManagerForTrigger();if(r){if(r.hasPickTriggers)switch(r.processTrigger(5,f.X.CreateNew(e.pickedMesh,t,e)),t.button){case 0:r.processTrigger(2,f.X.CreateNew(e.pickedMesh,t,e));break;case 1:r.processTrigger(4,f.X.CreateNew(e.pickedMesh,t,e));break;case 2:r.processTrigger(3,f.X.CreateNew(e.pickedMesh,t,e))}r.hasSpecificTrigger(8)&&window.setTimeout((()=>{const e=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,(e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh),!1,i.cameraToUseForPointers);e?.pickedMesh&&r&&0!==this._activePointerIdsCount&&Date.now()-this._startingPointerTime>A.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,r.processTrigger(8,f.X.CreateNew(e.pickedMesh,t)))}),A.LongPressDelay)}}else for(const r of i._pointerDownStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let r;const s=b.Zp.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,s),r=new b.mx(s,t,e),this._setRayOnPointerInfo(e,t)):r=new b.mx(s,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(r,s)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const r=new PointerEvent("pointerup",t);r.inputIndex=C.ST.Move;const s=new P;i?s.doubleClick=!0:s.singleClick=!0,this._checkPrePointerObservable(e,r,b.Zp.POINTERUP)||this._processPointerUp(e,r,s)}_processPointerUp(e,t,i){const r=this._scene;if(e?.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(r.onPointerPick&&r.onPointerPick(t,e),i.singleClick&&!i.ignore&&r.onPointerObservable.observers.length>this._cameraObserverCount)){const i=b.Zp.POINTERPICK,s=new b.mx(i,t,e);this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(s,i)}const s=e.pickedMesh._getActionManagerForTrigger();if(s&&!i.ignore){s.processTrigger(7,f.X.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&s.processTrigger(1,f.X.CreateNew(e.pickedMesh,t,e));const r=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&r&&r.processTrigger(6,f.X.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const s of r._pointerUpStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,f.X.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const s=new b.mx(b.Zp.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(s,b.Zp.POINTERUP),r.onPointerUp&&r.onPointerUp(t,e,b.Zp.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let s=0;if(i.singleClick?s=b.Zp.POINTERTAP:i.doubleClick&&(s=b.Zp.POINTERDOUBLETAP),s){const i=new b.mx(s,t,e);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(s)&&r.onPointerObservable.notifyObservers(i,s)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,r=null){const s=this._scene,n=s.getEngine();r||(r=n.getInputElement()),this._alreadyAttached&&this.detachControl(),r&&(this._alreadyAttachedTo=r),this._deviceSourceManager=new y.Z(n),this._initActionManager=e=>{if(!this._meshPickProceed){const t=s.skipPointerUpPicking||0===s._registeredActions&&!this._checkForPicking()&&!s.onPointerUp?null:s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerUpPredicate,s.pointerUpFastCheck,s.cameraToUseForPointers,s.pointerUpTrianglePredicate);this._currentPickResult=t,t&&(e=t.hit&&t.pickedMesh?t.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return e},this._delayedSimpleClick=(e,t,i)=>{if((Date.now()-this._previousStartingPointerTime>A.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,this._delayedClicks[e])){const t=this._delayedClicks[e].evt,i=b.Zp.POINTERTAP,r=new b.mx(i,t,this._currentPickResult);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(i)&&s.onPointerObservable.notifyObservers(r,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,r)=>{const s=new P;this._currentPickResult=null;let n=null,o=e.hasSpecificMask(b.Zp.POINTERPICK)||t.hasSpecificMask(b.Zp.POINTERPICK)||e.hasSpecificMask(b.Zp.POINTERTAP)||t.hasSpecificMask(b.Zp.POINTERTAP)||e.hasSpecificMask(b.Zp.POINTERDOUBLETAP)||t.hasSpecificMask(b.Zp.POINTERDOUBLETAP);!o&&S.G&&(n=this._initActionManager(n,s),n&&(o=n.hasPickTriggers));let a=!1;if(o){const o=i.button;if(s.hasSwiped=this._isPointerSwiping(),!s.hasSwiped){let l=!A.ExclusiveDoubleClickMode;if(l||(l=!e.hasSpecificMask(b.Zp.POINTERDOUBLETAP)&&!t.hasSpecificMask(b.Zp.POINTERDOUBLETAP),l&&!S.G.HasSpecificTrigger(6)&&(n=this._initActionManager(n,s),n&&(l=!n.hasSpecificTrigger(6)))),l)(Date.now()-this._previousStartingPointerTime>A.DoubleClickDelay||o!==this._previousButtonPressed)&&(s.singleClick=!0,r(s,this._currentPickResult),a=!0);else{const e={evt:i,clickInfo:s,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,o,s,r),A.DoubleClickDelay)};this._delayedClicks[o]=e}let h=e.hasSpecificMask(b.Zp.POINTERDOUBLETAP)||t.hasSpecificMask(b.Zp.POINTERDOUBLETAP);!h&&S.G.HasSpecificTrigger(6)&&(n=this._initActionManager(n,s),n&&(h=n.hasSpecificTrigger(6))),h&&(o===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>A.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>A.DragMovementThreshold),n.isPointerLock&&n._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=C.ST.MouseWheelX&&e.inputIndex<=C.ST.MouseWheelZ?b.Zp.POINTERWHEEL:b.Zp.POINTERMOVE))return;if(!s.cameraToUseForPointers&&!s.activeCamera)return;if(s.skipPointerMovePicking)return void this._processPointerMove(new d.G,e);s.pointerMovePredicate||(s.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||s.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!s.cameraToUseForPointers||!!(s.cameraToUseForPointers.layerMask&e.layerMask)));const t=s._registeredActions>0||s.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{const t=this._activePointerIds.indexOf(-1);if(-1===t?this._activePointerIds.push(e.pointerId):this._activePointerIds[t]=e.pointerId,this._activePointerIdsCount++,this._pickedDownMesh=null,this._meshPickProceed=!1,A.ExclusiveDoubleClickMode)for(let t=0;te.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!s.cameraToUseForPointers||!!(s.cameraToUseForPointers.layerMask&e.layerMask))),this._pickedDownMesh=null,i=s.skipPointerDownPicking||0===s._registeredActions&&!this._checkForPicking()&&!s.onPointerDown?new d.G:s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerDownPredicate,s.pointerDownFastCheck,s.cameraToUseForPointers,s.pointerDownTrianglePredicate),this._processPointerDown(i,e)},this._onPointerUp=e=>{const t=this._activePointerIds.indexOf(e.pointerId);-1!==t&&(this._activePointerIds[t]=-1,this._activePointerIdsCount--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),s.preventDefaultOnPointerUp&&r&&(e.preventDefault(),r.focus()),this._initClickEvent(s.onPrePointerObservable,s.onPointerObservable,e,((t,i)=>{if(s.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,b.Zp.POINTERUP))return this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),void(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1));t.hasSwiped||(t.singleClick&&s.onPrePointerObservable.hasSpecificMask(b.Zp.POINTERTAP)&&this._checkPrePointerObservable(null,e,b.Zp.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&s.onPrePointerObservable.hasSpecificMask(b.Zp.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,b.Zp.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}this._pointerCaptures[e.pointerId]?(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(s.cameraToUseForPointers||s.activeCamera)&&(s.pointerUpPredicate||(s.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!s.cameraToUseForPointers||!!(s.cameraToUseForPointers.layerMask&e.layerMask))),!this._meshPickProceed&&(S.G&&S.G.HasTriggers||this._checkForPicking()||s.onPointerUp)&&this._initActionManager(null,t),i||(i=this._currentPickResult),this._processPointerUp(i,e,t),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))):this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1)})))},this._onKeyDown=e=>{const t=T.TB.KEYDOWN;if(s.onPreKeyboardObservable.hasObservers()){const i=new T.Bu(t,e);if(s.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){const i=new T.W0(t,e);s.onKeyboardObservable.notifyObservers(i,t)}s.actionManager&&s.actionManager.processTrigger(14,f.X.CreateNewFromScene(s,e))},this._onKeyUp=e=>{const t=T.TB.KEYUP;if(s.onPreKeyboardObservable.hasObservers()){const i=new T.Bu(t,e);if(s.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){const i=new T.W0(t,e);s.onKeyboardObservable.notifyObservers(i,t)}s.actionManager&&s.actionManager.processTrigger(15,f.X.CreateNewFromScene(s,e))},this._deviceSourceManager.onDeviceConnectedObservable.add((r=>{r.deviceType===C.bq.Mouse?r.onInputChangedObservable.add((s=>{this._originMouseEvent=s,s.inputIndex===C.ST.LeftClick||s.inputIndex===C.ST.MiddleClick||s.inputIndex===C.ST.RightClick||s.inputIndex===C.ST.BrowserBack||s.inputIndex===C.ST.BrowserForward?t&&1===r.getInput(s.inputIndex)?this._onPointerDown(s):e&&0===r.getInput(s.inputIndex)&&this._onPointerUp(s):i&&(s.inputIndex===C.ST.Move?this._onPointerMove(s):s.inputIndex!==C.ST.MouseWheelX&&s.inputIndex!==C.ST.MouseWheelY&&s.inputIndex!==C.ST.MouseWheelZ||this._onPointerMove(s))})):r.deviceType===C.bq.Touch?r.onInputChangedObservable.add((s=>{s.inputIndex===C.ST.LeftClick&&(t&&1===r.getInput(s.inputIndex)?(this._onPointerDown(s),this._activePointerIdsCount>1&&(this._isMultiTouchGesture=!0)):e&&0===r.getInput(s.inputIndex)&&(this._onPointerUp(s),0===this._activePointerIdsCount&&(this._isMultiTouchGesture=!1))),i&&s.inputIndex===C.ST.Move&&this._onPointerMove(s)})):r.deviceType===C.bq.Keyboard&&r.onInputChangedObservable.add((e=>{"keydown"===e.type?this._onKeyDown(e):"keyup"===e.type&&this._onKeyUp(e)}))})),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,r){if(!(this._meshUnderPointerId[t]!==e||e&&e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const s=this._meshUnderPointerId[t];let n;s&&(n=s._getActionManagerForTrigger(10),n&&n.processTrigger(10,f.X.CreateNew(s,r,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,n=e._getActionManagerForTrigger(9),n&&n.processTrigger(9,f.X.CreateNew(e,r,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null);for(const t in this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}}A.DragMovementThreshold=10,A.LongPressDelay=500,A.DoubleClickDelay=300,A.ExclusiveDoubleClickMode=!1;var R=i(78641),I=i(11084),M=i(59881),O=i(83839),D=i(28909),w=i(14952),N=i(34130);class F{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var L,B=i(60590),V=i(56225);!function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(L||(L={}));class k{static DefaultMaterialFactory(e){throw(0,x.n)("StandardMaterial")}static CollisionCoordinatorFactory(){throw(0,x.n)("DefaultCollisionCoordinator")}get clearColor(){return this._clearColor}set clearColor(e){e!==this._clearColor&&(this._clearColor=e,this.onClearColorChangedObservable.notifyObservers(this._clearColor))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case 0:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case 1:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case 2:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1}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 environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}getNodes(){let e=[];return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach((t=>e=e.concat(t.bones))),e}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 A.DragMovementThreshold}static set DragMovementThreshold(e){A.DragMovementThreshold=e}static get LongPressDelay(){return A.LongPressDelay}static set LongPressDelay(e){A.LongPressDelay=e}static get DoubleClickDelay(){return A.DoubleClickDelay}static set DoubleClickDelay(e){A.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return A.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){A.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){const r=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,s=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return h.AA.Vector4[0].set(r.x,r.y,r.z,s?-1:1),e&&(i?e.setFloat3(t,h.AA.Vector4[0].x,h.AA.Vector4[0].y,h.AA.Vector4[0].z):e.setVector4(t,h.AA.Vector4[0])),h.AA.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=(0,N.lL)(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=k.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}get frameGraph(){return this._frameGraph}set frameGraph(e){if(this._frameGraph)return this._frameGraph=e,void(e||(this.customRenderFunction=this._currentCustomRenderFunction));this._frameGraph=e,e&&(this._currentCustomRenderFunction=this.customRenderFunction,this.customRenderFunction=this._renderWithFrameGraph)}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=k.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){this._inputManager=new A(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this._clearColor=new I.ov(.2,.2,.3,1),this.onClearColorChangedObservable=new n.cP,this.ambientColor=new I.v9(0,0,0),this.environmentIntensity=1,this._performancePriority=0,this.onScenePerformancePriorityChangedObservable=new n.cP,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[],this.effectLayers=[],this.sounds=null,this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],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 n.cP,this._onDisposeObserver=null,this.onBeforeRenderObservable=new n.cP,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new n.cP,this.onAfterRenderCameraObservable=new n.cP,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new n.cP,this.onAfterAnimationsObservable=new n.cP,this.onBeforeDrawPhaseObservable=new n.cP,this.onAfterDrawPhaseObservable=new n.cP,this.onReadyObservable=new n.cP,this.onBeforeCameraRenderObservable=new n.cP,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new n.cP,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new n.cP,this.onAfterActiveMeshesEvaluationObservable=new n.cP,this.onBeforeParticlesRenderingObservable=new n.cP,this.onAfterParticlesRenderingObservable=new n.cP,this.onDataLoadedObservable=new n.cP,this.onNewCameraAddedObservable=new n.cP,this.onCameraRemovedObservable=new n.cP,this.onNewLightAddedObservable=new n.cP,this.onLightRemovedObservable=new n.cP,this.onNewGeometryAddedObservable=new n.cP,this.onGeometryRemovedObservable=new n.cP,this.onNewTransformNodeAddedObservable=new n.cP,this.onTransformNodeRemovedObservable=new n.cP,this.onNewMeshAddedObservable=new n.cP,this.onMeshRemovedObservable=new n.cP,this.onNewSkeletonAddedObservable=new n.cP,this.onSkeletonRemovedObservable=new n.cP,this.onNewMaterialAddedObservable=new n.cP,this.onNewMultiMaterialAddedObservable=new n.cP,this.onMaterialRemovedObservable=new n.cP,this.onMultiMaterialRemovedObservable=new n.cP,this.onNewTextureAddedObservable=new n.cP,this.onTextureRemovedObservable=new n.cP,this.onBeforeRenderTargetsRenderObservable=new n.cP,this.onAfterRenderTargetsRenderObservable=new n.cP,this.onBeforeStepObservable=new n.cP,this.onAfterStepObservable=new n.cP,this.onActiveCameraChanged=new n.cP,this.onActiveCamerasChanged=new n.cP,this.onBeforeRenderingGroupObservable=new n.cP,this.onAfterRenderingGroupObservable=new n.cP,this.onMeshImportedObservable=new n.cP,this.onAnimationFileImportedObservable=new n.cP,this._registeredForLateAnimationBindings=new o.b(256),this._pointerPickingConfiguration=new F,this.onPrePointerObservable=new n.cP,this.onPointerObservable=new n.cP,this.onPreKeyboardObservable=new n.cP,this.onKeyboardObservable=new n.cP,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=k.FOGMODE_NONE,this.fogColor=new I.v9(.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._frameGraph=null,this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new h.Pq(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new o.b(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new R.A,this._activeIndices=new R.A,this._activeParticles=new R.A,this._activeBones=new R.A,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 o.L(256),this._processedMaterials=new o.L(256),this._renderTargets=new o.b(256),this._materialsRenderTargets=new o.b(256),this._activeParticleSystems=new o.L(256),this._activeSkeletons=new o.b(32),this._softwareSkinnedMeshes=new o.b(32),this._activeAnimatables=new Array,this._transformMatrix=h.uq.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=m.B.Create(),this._beforeClearStage=m.B.Create(),this._beforeRenderTargetClearStage=m.B.Create(),this._gatherRenderTargetsStage=m.B.Create(),this._gatherActiveCameraRenderTargetsStage=m.B.Create(),this._isReadyForMeshStage=m.B.Create(),this._beforeEvaluateActiveMeshStage=m.B.Create(),this._evaluateSubMeshStage=m.B.Create(),this._preActiveMeshStage=m.B.Create(),this._cameraDrawRenderTargetStage=m.B.Create(),this._beforeCameraDrawStage=m.B.Create(),this._beforeRenderTargetDrawStage=m.B.Create(),this._beforeRenderingGroupDrawStage=m.B.Create(),this._beforeRenderingMeshStage=m.B.Create(),this._afterRenderingMeshStage=m.B.Create(),this._afterRenderingGroupDrawStage=m.B.Create(),this._afterCameraDrawStage=m.B.Create(),this._afterCameraPostProcessStage=m.B.Create(),this._afterRenderTargetDrawStage=m.B.Create(),this._afterRenderTargetPostProcessStage=m.B.Create(),this._afterRenderStage=m.B.Create(),this._pointerMoveStage=m.B.Create(),this._pointerDownStage=m.B.Create(),this._pointerUpStage=m.B.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||v.q.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(v.q._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new _.m(this),p.X&&(this.postProcessManager=new p.X(this)),(0,g.BA)()&&this.attachControl(),this._createUbo(),c.p&&(this._imageProcessingConfiguration=new c.p),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 void 0!==this._animationRatio?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){if(this._isDisposed)return!1;let t;const i=this.getEngine(),r=i.currentRenderPassId;i.currentRenderPassId=this.activeCamera?.renderPassId??r;let s=!0;for(this._pendingData.length>0&&(s=!1),this.prePassRenderer?.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&s&&(s=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t0;for(const e of this._isReadyForMeshStage)e.action(r,n)||(s=!1);if(!e)continue;const o=r.material||this.defaultMaterial;if(o)if(o._storeEffectOnSubMeshes)for(const e of r.subMeshes){const t=e.getMaterial();t&&t.hasRenderTargetTextures&&null!=t.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(t)&&(this._processedMaterials.push(t),this._materialsRenderTargets.concatWithNoDuplicate(t.getRenderTargetTextures()))}else o.hasRenderTargetTextures&&null!=o.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(o)&&(this._processedMaterials.push(o),this._materialsRenderTargets.concatWithNoDuplicate(o.getRenderTargetTextures()))}if(e)for(t=0;t0)for(const e of this.activeCameras)e.isReady(!0)||(s=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(s=!1));for(const e of this.particleSystems)e.isReady()||(s=!1);if(this.layers)for(const e of this.layers)e.isReady()||(s=!1);return i.areAllEffectsReady()||(s=!1),i.currentRenderPassId=r,s}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){const t=()=>{e(),setTimeout((()=>{this.unregisterBeforeRender(t)}))};this.registerBeforeRender(t)}executeOnceBeforeRender(e,t){void 0!==t?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);-1!==i&&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),null===this._executeWhenReadyTimeoutId&&this._checkIsReady(t)}whenReadyAsync(e=!1){return new Promise((t=>{this.executeWhenReady((()=>{t()}),e)}))}_checkIsReady(e=!1){return this._registerTransientComponents(),this.isReady(e)?(this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):this._isDisposed?(this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):void(this._executeWhenReadyTimeoutId=setTimeout((()=>{this.incrementRenderId(),this._checkIsReady(e)}),100))}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=s.j.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,r){i||r||!this._multiviewSceneUbo||(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag||(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?M.P.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=M.P.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,r):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e){const t=new u.D(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 O.K.UniqueId}addMesh(e,t=!1){this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),r.S0.SetImmediate((()=>{this.onNewMeshAddedObservable.notifyObservers(e)})),t&&e.getChildMeshes().forEach((e=>{this.addMesh(e)})))}removeMesh(e,t=!1){const i=this.meshes.indexOf(e);return-1!==i&&(this.meshes.splice(i,1),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.removeMesh(e)})),i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneTransformNodesArray||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){const t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){const e=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=e,e._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-1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){const t=this.morphTargetManagers.indexOf(e);return-1!==t&&this.morphTargetManagers.splice(t,1),t}removeLight(e){const t=this.lights.indexOf(e);if(-1!==t){for(const t of this.meshes)t._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(-1!==t&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){const t=this.activeCameras.indexOf(e);-1!==t&&this.activeCameras.splice(t,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-1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){const t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){const t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){const t=this.multiMaterials.indexOf(e);return-1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){const t=e._indexInSceneMaterialArray;if(-1!==t&&t{this.onNewLightAddedObservable.notifyObservers(e)}))}}sortLightsByPriority(){this.requireLightSorting&&this.lights.sort(w.c.CompareLightsPriority)}addCamera(e){this._blockEntityCollection||(this.cameras.push(e),r.S0.SetImmediate((()=>{this.onNewCameraAddedObservable.notifyObservers(e)})),e.parent||e._addToSceneRootNodes())}addSkeleton(e){this._blockEntityCollection||(this.skeletons.push(e),r.S0.SetImmediate((()=>{this.onNewSkeletonAddedObservable.notifyObservers(e)})))}addParticleSystem(e){this._blockEntityCollection||this.particleSystems.push(e)}addAnimation(e){this._blockEntityCollection||this.animations.push(e)}addAnimationGroup(e){this._blockEntityCollection||this.animationGroups.push(e)}addMultiMaterial(e){this._blockEntityCollection||(this.multiMaterials.push(e),r.S0.SetImmediate((()=>{this.onNewMultiMaterialAddedObservable.notifyObservers(e)})))}addMaterial(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneMaterialArray||(e._indexInSceneMaterialArray=this.materials.length,this.materials.push(e),r.S0.SetImmediate((()=>{this.onNewMaterialAddedObservable.notifyObservers(e)})))}addMorphTargetManager(e){this._blockEntityCollection||this.morphTargetManagers.push(e)}addGeometry(e){this._blockEntityCollection||(this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=this.geometries.length),this.geometries.push(e))}addActionManager(e){this.actionManagers.push(e)}addTexture(e){this._blockEntityCollection||(this.textures.push(e),this.onNewTextureAddedObservable.notifyObservers(e))}switchActiveCamera(e,t=!0){this._engine.getInputElement()&&(this.activeCamera&&this.activeCamera.detachControl(),this.activeCamera=e,t&&e.attachControl())}setActiveCameraById(e){const t=this.getCameraById(e);return t?(this.activeCamera=t,t):null}setActiveCameraByName(e){const t=this.getCameraByName(e);return t?(this.activeCamera=t,t):null}getAnimationGroupByName(e){for(let t=0;tt.uniqueId===e))}getMaterialById(e,t=!1){return this._getMaterial(t,(t=>t.id===e))}getMaterialByName(e,t=!1){return this._getMaterial(t,(t=>t.name===e))}getLastMaterialById(e,t=!1){for(let t=this.materials.length-1;t>=0;t--)if(this.materials[t].id===e)return this.materials[t];if(t)for(let t=this.multiMaterials.length-1;t>=0;t--)if(this.multiMaterials[t].id===e)return this.multiMaterials[t];return null}getTextureByUniqueId(e){for(let t=0;t{this.onNewGeometryAddedObservable.notifyObservers(e)})),0))}removeGeometry(e){let t;if(this._geometriesByUniqueId){if(t=this._geometriesByUniqueId[e.uniqueId],void 0===t)return!1}else if(t=this.geometries.indexOf(e),t<0)return!1;if(t!==this.geometries.length-1){const e=this.geometries[this.geometries.length-1];e&&(this.geometries[t]=e,this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=t))}return this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=void 0),this.geometries.pop(),this.onGeometryRemovedObservable.notifyObservers(e),!0}getGeometries(){return this.geometries}getMeshById(e){for(let t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const r=this.getLightById(e);if(r)return r;const s=this.getCameraById(e);if(s)return s;return this.getBoneById(e)||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const r=this.getLightByName(e);if(r)return r;const s=this.getCameraByName(e);if(s)return s;return this.getBoneByName(e)||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){if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=s,this._skipEvaluateActiveMeshesCompletely=e,r)for(let e=0;ee.dispose()))}_evaluateActiveMeshes(){if(this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode)return void(this._activeMeshes.length>0&&(this.activeCamera?._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset()));if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const e=this._activeMeshes.length;for(let t=0;t0&&t.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||t.alwaysSelectAsActiveMesh||t.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(t),this.activeCamera._activeMeshes.push(t),r!==t&&r._activate(this._renderId,!1);for(const e of this._preActiveMeshStage)e.action(t);t._activate(this._renderId,!1)&&(t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(r=t):r._internalAbstractMeshDataInfo._onlyForInstances=!1,r._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(t,r)),t._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e0){const r=this.getActiveSubMeshCandidates(t),s=r.length;i=i||1===s;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 e of this._gatherActiveCameraRenderTargetsStage)e.action(this._renderTargets);let n=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){r.S0.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e0),this._renderId++}for(const e of this._cameraDrawRenderTargetStage)n=e.action(this.activeCamera)||n;this._intermediateRendering=!1}this._engine.currentRenderPassId=e.outputRenderTarget?.renderPassId??e.renderPassId??0,n&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame();for(const e of this._beforeCameraDrawStage)e.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),s.snapshotRendering&&1===s.snapshotRenderingMode&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const e of this._afterCameraDrawStage)e.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const t=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,t)}for(const e of this._afterCameraPostProcessStage)e.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(0===e.cameraRigMode||e._renderingMultiview)return e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),void this.onAfterRenderCameraObservable.notifyObservers(e);if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let t=0;t-1&&(13===i.trigger&&i._executeCurrent(f.X.CreateNew(t,void 0,r)),t.actionManager.hasSpecificTrigger(13,(e=>{const t=e.mesh?e.mesh:e;return r===t}))&&13!==i.trigger||t._intersectionsInProgress.splice(n,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(k.MinDeltaTime,Math.min(this._engine.getDeltaTime(),k.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let r=0;const s=this._engine.getLockstepMaxSteps();let n=Math.floor(e/t);for(n=Math.min(n,s);e>0&&r0)for(let e=0;e0),this._intermediateRendering=!0;for(let i=0;i0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=t?.renderPassId??0,this.activeCamera=t,this._activeCamera&&22!==this._activeCamera.cameraRigMode&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const e of this._beforeClearStage)e.action();this._clearFrameBuffer(this.activeCamera);for(const e of this._gatherRenderTargetsStage)e.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}}this._checkIntersections();for(const e of this._afterRenderStage)e.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let e=0;e{e.onAnimationEndObservable.clear(),e.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 t of e)t.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){B.V.Error("An error occurred while calling onDisposeObservable!",e)}if(this.detachControl(),this._engine.getInputElement())for(let e=0;ee.dispose(!0))),this._disposeList(this.transformNodes,(e=>e.dispose(!0)));const t=this.cameras;this._disposeList(t),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 i=this._engine.scenes.indexOf(this);i>-1&&this._engine.scenes.splice(i,1),v.q._LastCreatedScene===this&&(this._engine.scenes.length>0?v.q._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:v.q._LastCreatedScene=null),i=this._engine._virtualScenes.indexOf(this),i>-1&&this._engine._virtualScenes.splice(i,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.onClearColorChangedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){const i=e.slice(0);t=t??(e=>e.dispose());for(const e of i)t(e);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0),this.meshes.filter(e).forEach((e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;const r=e.getBoundingInfo(),s=r.boundingBox.minimumWorld,n=r.boundingBox.maximumWorld;h.Pq.CheckExtends(s,t,i),h.Pq.CheckExtends(n,t,i)})),{min:t,max:i}}createPickingRay(e,t,i,r,s=!1){throw(0,x.n)("Ray")}createPickingRayToRef(e,t,i,r,s,n=!1,o=!1){throw(0,x.n)("Ray")}createPickingRayInCameraSpace(e,t,i){throw(0,x.n)("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,r){throw(0,x.n)("Ray")}pick(e,t,i,r,s,n){const o=(0,x.n)("Ray",!0);return o&&B.V.Warn(o),new d.G}pickWithBoundingInfo(e,t,i,r,s){const n=(0,x.n)("Ray",!0);return n&&B.V.Warn(n),new d.G}pickWithRay(e,t,i,r){throw(0,x.n)("Ray")}multiPick(e,t,i,r,s){throw(0,x.n)("Ray")}multiPickWithRay(e,t,i){throw(0,x.n)("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(void 0===t)return e;const r=[];for(const s in e){const n=e[s];l.Y&&l.Y.MatchesQuery(n,t)&&(!i||i(n))&&r.push(n)}return r}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,i=null,r=null){this._renderingManager.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t,i=!0,r=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,r)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(const i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,r,s,n,o){const a=(0,D.zU)(e,t,i,r?this.offlineProvider:void 0,s,n,o);return this._activeRequests.push(a),a.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),a}_loadFileAsync(e,t,i,r,s){return new Promise(((n,o)=>{this._loadFile(e,(e=>{n(e)}),t,i,r,((e,t)=>{o(t)}),s)}))}_requestFile(e,t,i,r,s,n,o){const a=(0,D.sh)(e,t,i,r?this.offlineProvider:void 0,s,n,o);return this._activeRequests.push(a),a.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),a}_requestFileAsync(e,t,i,r,s){return new Promise(((n,o)=>{this._requestFile(e,(e=>{n(e)}),t,i,r,(e=>{o(e)}),s)}))}_readFile(e,t,i,r,s){const n=(0,D.NJ)(e,t,i,r,s);return this._activeRequests.push(n),n.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),n}_readFileAsync(e,t,i){return new Promise(((r,s)=>{this._readFile(e,(e=>{r(e)}),t,i,(e=>{s(e)}))}))}getPerfCollector(){throw(0,x.n)("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)}}k.FOGMODE_NONE=0,k.FOGMODE_EXP=1,k.FOGMODE_EXP2=2,k.FOGMODE_LINEAR=3,k.MinDeltaTime=1,k.MaxDeltaTime=1e3,(0,V.Y5)("BABYLON.Scene",k)},9180:(e,t,i)=>{"use strict";i.d(t,{B:()=>s,v:()=>r});class r{}r.NAME_EFFECTLAYER="EffectLayer",r.NAME_LAYER="Layer",r.NAME_LENSFLARESYSTEM="LensFlareSystem",r.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",r.NAME_PARTICLESYSTEM="ParticleSystem",r.NAME_GAMEPAD="Gamepad",r.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",r.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",r.NAME_PREPASSRENDERER="PrePassRenderer",r.NAME_DEPTHRENDERER="DepthRenderer",r.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer",r.NAME_IBLSHADOWSRENDERER="IblShadowsRenderer",r.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",r.NAME_SPRITE="Sprite",r.NAME_SUBSURFACE="SubSurface",r.NAME_OUTLINERENDERER="Outline",r.NAME_PROCEDURALTEXTURE="ProceduralTexture",r.NAME_SHADOWGENERATOR="ShadowGenerator",r.NAME_OCTREE="Octree",r.NAME_PHYSICSENGINE="PhysicsEngine",r.NAME_AUDIO="Audio",r.NAME_FLUIDRENDERER="FluidRenderer",r.STEP_ISREADYFORMESH_EFFECTLAYER=0,r.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,r.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,r.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0,r.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,r.STEP_BEFORECAMERADRAW_PREPASS=0,r.STEP_BEFORECAMERADRAW_EFFECTLAYER=1,r.STEP_BEFORECAMERADRAW_LAYER=2,r.STEP_BEFORERENDERTARGETDRAW_PREPASS=0,r.STEP_BEFORERENDERTARGETDRAW_LAYER=1,r.STEP_BEFORERENDERINGMESH_PREPASS=0,r.STEP_BEFORERENDERINGMESH_OUTLINE=1,r.STEP_AFTERRENDERINGMESH_PREPASS=0,r.STEP_AFTERRENDERINGMESH_OUTLINE=1,r.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,r.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,r.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,r.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,r.STEP_BEFORECLEAR_PREPASS=1,r.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0,r.STEP_AFTERRENDERTARGETDRAW_PREPASS=0,r.STEP_AFTERRENDERTARGETDRAW_LAYER=1,r.STEP_AFTERCAMERADRAW_PREPASS=0,r.STEP_AFTERCAMERADRAW_EFFECTLAYER=1,r.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2,r.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3,r.STEP_AFTERCAMERADRAW_LAYER=4,r.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5,r.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0,r.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0,r.STEP_AFTERRENDER_AUDIO=0,r.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0,r.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,r.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2,r.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,r.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,r.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1,r.STEP_POINTERMOVE_SPRITE=0,r.STEP_POINTERDOWN_SPRITE=0,r.STEP_POINTERUP_SPRITE=0;class s extends Array{constructor(e){super(...e)}static Create(){return Object.create(s.prototype)}registerStep(e,t,i){let r=0,s=Number.MAX_VALUE;for(;r{"use strict";function r(e,t,i,r){var s,n=arguments.length,o=n<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var a=e.length-1;a>=0;a--)(s=e[a])&&(o=(n<3?s(o):n>3?s(t,i,o):s(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o}i.d(t,{Cg:()=>r}),Object.create,Object.create},66570:e=>{"use strict";function t(e,t,n){n=n||2;var o,a,l,u,d,p,_,m=t&&t.length,g=m?t[0]*n:e.length,v=i(e,0,g,n,!0),x=[];if(!v||v.next===v.prev)return x;if(m&&(v=function(e,t,s,n){var o,a,l,u=[];for(o=0,a=t.length;o80*n){o=l=e[0],a=u=e[1];for(var b=n;bl&&(l=d),p>u&&(u=p);_=0!==(_=Math.max(l-o,u-a))?1/_:0}return s(v,x,n,o,a,_),x}function i(e,t,i,r,s){var n,o;if(s===P(e,t,i,r)>0)for(n=t;n=t;n-=r)o=C(n,e[n],e[n+1],o);return o&&g(o,o.next)&&(y(o),o=o.next),o}function r(e,t){if(!e)return e;t||(t=e);var i,r=e;do{if(i=!1,r.steiner||!g(r,r.next)&&0!==m(r.prev,r,r.next))r=r.next;else{if(y(r),(r=t=r.prev)===r.next)break;i=!0}}while(i||r!==t);return t}function s(e,t,i,h,c,u,f){if(e){!f&&u&&function(e,t,i,r){var s=e;do{null===s.z&&(s.z=d(s.x,s.y,t,i,r)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next}while(s!==e);s.prevZ.nextZ=null,s.prevZ=null,function(e){var t,i,r,s,n,o,a,l,h=1;do{for(i=e,e=null,n=null,o=0;i;){for(o++,r=i,a=0,t=0;t0||l>0&&r;)0!==a&&(0===l||!r||i.z<=r.z)?(s=i,i=i.nextZ,a--):(s=r,r=r.nextZ,l--),n?n.nextZ=s:e=s,s.prevZ=n,n=s;i=r}n.nextZ=null,h*=2}while(o>1)}(s)}(e,h,c,u);for(var p,_,m=e;e.prev!==e.next;)if(p=e.prev,_=e.next,u?o(e,h,c,u):n(e))t.push(p.i/i),t.push(e.i/i),t.push(_.i/i),y(e),e=_.next,m=_.next;else if((e=_)===m){f?1===f?s(e=a(r(e),t,i),t,i,h,c,u,2):2===f&&l(e,t,i,h,c,u):s(r(e),t,i,h,c,u,1);break}}}function n(e){var t=e.prev,i=e,r=e.next;if(m(t,i,r)>=0)return!1;for(var s=e.next.next;s!==e.prev;){if(p(t.x,t.y,i.x,i.y,r.x,r.y,s.x,s.y)&&m(s.prev,s,s.next)>=0)return!1;s=s.next}return!0}function o(e,t,i,r){var s=e.prev,n=e,o=e.next;if(m(s,n,o)>=0)return!1;for(var a=s.xn.x?s.x>o.x?s.x:o.x:n.x>o.x?n.x:o.x,c=s.y>n.y?s.y>o.y?s.y:o.y:n.y>o.y?n.y:o.y,u=d(a,l,t,i,r),f=d(h,c,t,i,r),_=e.prevZ,g=e.nextZ;_&&_.z>=u&&g&&g.z<=f;){if(_!==e.prev&&_!==e.next&&p(s.x,s.y,n.x,n.y,o.x,o.y,_.x,_.y)&&m(_.prev,_,_.next)>=0)return!1;if(_=_.prevZ,g!==e.prev&&g!==e.next&&p(s.x,s.y,n.x,n.y,o.x,o.y,g.x,g.y)&&m(g.prev,g,g.next)>=0)return!1;g=g.nextZ}for(;_&&_.z>=u;){if(_!==e.prev&&_!==e.next&&p(s.x,s.y,n.x,n.y,o.x,o.y,_.x,_.y)&&m(_.prev,_,_.next)>=0)return!1;_=_.prevZ}for(;g&&g.z<=f;){if(g!==e.prev&&g!==e.next&&p(s.x,s.y,n.x,n.y,o.x,o.y,g.x,g.y)&&m(g.prev,g,g.next)>=0)return!1;g=g.nextZ}return!0}function a(e,t,i){var s=e;do{var n=s.prev,o=s.next.next;!g(n,o)&&v(n,s,s.next,o)&&S(n,o)&&S(o,n)&&(t.push(n.i/i),t.push(s.i/i),t.push(o.i/i),y(s),y(s.next),s=e=o),s=s.next}while(s!==e);return r(s)}function l(e,t,i,n,o,a){var l=e;do{for(var h=l.next.next;h!==l.prev;){if(l.i!==h.i&&_(l,h)){var c=T(l,h);return l=r(l,l.next),c=r(c,c.next),s(l,t,i,n,o,a),void s(c,t,i,n,o,a)}h=h.next}l=l.next}while(l!==e)}function h(e,t){return e.x-t.x}function c(e,t){var i=function(e,t){var i,r=t,s=e.x,n=e.y,o=-1/0;do{if(n<=r.y&&n>=r.next.y&&r.next.y!==r.y){var a=r.x+(n-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(a<=s&&a>o){if(o=a,a===s){if(n===r.y)return r;if(n===r.next.y)return r.next}i=r.x=r.x&&r.x>=c&&s!==r.x&&p(ni.x||r.x===i.x&&u(i,r)))&&(i=r,f=l)),r=r.next}while(r!==h);return i}(e,t);if(!i)return t;var s=T(i,e),n=r(i,i.next);return r(s,s.next),t===i?n:t}function u(e,t){return m(e.prev,e,t.prev)<0&&m(t.next,e,e.next)<0}function d(e,t,i,r,s){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-i)*s)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*s)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function f(e){var t=e,i=e;do{(t.x=0&&(e-o)*(r-a)-(i-o)*(t-a)>=0&&(i-o)*(n-a)-(s-o)*(r-a)>=0}function _(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){var i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&v(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}(e,t)&&(S(e,t)&&S(t,e)&&function(e,t){var i=e,r=!1,s=(e.x+t.x)/2,n=(e.y+t.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&s<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(r=!r),i=i.next}while(i!==e);return r}(e,t)&&(m(e.prev,e,t.prev)||m(e,t.prev,t))||g(e,t)&&m(e.prev,e,e.next)>0&&m(t.prev,t,t.next)>0)}function m(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function g(e,t){return e.x===t.x&&e.y===t.y}function v(e,t,i,r){var s=b(m(e,t,i)),n=b(m(e,t,r)),o=b(m(i,r,e)),a=b(m(i,r,t));return s!==n&&o!==a||!(0!==s||!x(e,i,t))||!(0!==n||!x(e,r,t))||!(0!==o||!x(i,e,r))||!(0!==a||!x(i,t,r))}function x(e,t,i){return t.x<=Math.max(e.x,i.x)&&t.x>=Math.min(e.x,i.x)&&t.y<=Math.max(e.y,i.y)&&t.y>=Math.min(e.y,i.y)}function b(e){return e>0?1:e<0?-1:0}function S(e,t){return m(e.prev,e,e.next)<0?m(e,t,e.next)>=0&&m(e,e.prev,t)>=0:m(e,t,e.prev)<0||m(e,e.next,t)<0}function T(e,t){var i=new E(e.i,e.x,e.y),r=new E(t.i,t.x,t.y),s=e.next,n=t.prev;return e.next=t,t.prev=e,i.next=s,s.prev=i,r.next=i,i.prev=r,n.next=r,r.prev=n,r}function C(e,t,i,r){var s=new E(e,t,i);return r?(s.next=r.next,s.prev=r,r.next.prev=s,r.next=s):(s.prev=s,s.next=s),s}function y(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function E(e,t,i){this.i=e,this.x=t,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function P(e,t,i,r){for(var s=0,n=t,o=i-r;n0&&(r+=e[s-1].length,i.holes.push(r))}return i}},34258:e=>{e.exports=function(){var e={},t=this,i=(new Function("try {return this===window;}catch(e){ return false;}"),new Function("try {return this===global;}catch(e){return false;}")),r=new Function("try {return typeof importScripts === 'function';}catch(e){return false;}");if(i()&&r(),i()||r()){var s=t;if(r()){onmessage=function(e){if(e.data.className&&e.data.methodName){var i=(r=e.data.className,s=e.data.methodName,n=t,r.split(".").forEach((function(e){n&&(n=n[e])})),n?n[s]:null);if(!i)return console.error("could not find "+e.data.className+"."+e.data.methodName);postMessage({result:i.apply(null,e.data.args),id:e.data.id})}var r,s,n}}}return function(e,t,i){"use strict";t.geom=t.geom||{},t.exe=t.exe||{},t.eval=t.eval||{},t.core=t.core||{},t.promhx=t.promhx||{};var r={},s=function(){return A.__string_rec(this,"")};function n(e,t){function i(){}i.prototype=e;var r=new i;for(var s in t)r[s]=t[s];return t.toString!==Object.prototype.toString&&(r.toString=t.toString),r}var o=function(){};r.HxOverrides=o,o.__name__=["HxOverrides"],o.strDate=function(e){switch(e.length){case 8:var t=e.split(":"),i=new Date;return i.setTime(0),i.setUTCHours(t[0]),i.setUTCMinutes(t[1]),i.setUTCSeconds(t[2]),i;case 10:var r=e.split("-");return new Date(r[0],r[1]-1,r[2],0,0,0);case 19:var s=e.split(" "),n=s[0].split("-"),o=s[1].split(":");return new Date(n[0],n[1]-1,n[2],o[0],o[1],o[2]);default:throw new P("Invalid date format : "+e)}},o.cca=function(e,t){var i=e.charCodeAt(t);if(i==i)return i},o.substr=function(e,t,i){return null!=t&&0!=t&&null!=i&&i<0?"":(null==i&&(i=e.length),t<0?(t=e.length+t)<0&&(t=0):i<0&&(i=e.length+i-t),e.substr(t,i))},o.iter=function(e){return{cur:0,arr:e,hasNext:function(){return this.cur0&&(1==n?this.buf.b+="n":(this.buf.b+="u",this.buf.b+=null==n?"null":""+n),n=0),this.serialize(e[d]))}n>0&&(1==n?this.buf.b+="n":(this.buf.b+="u",this.buf.b+=null==n?"null":""+n)),this.buf.b+="h";break;case l:this.buf.b+="l";for(var f=e.h,_=null;null!=f;){var m;_=f[0],f=f[1],m=_,this.serialize(m)}this.buf.b+="h";break;case Date:var v=e;this.buf.b+="v",this.buf.add(v.getTime());break;case T:this.buf.b+="b";for(var S=e,y=S.keys();y.hasNext();){var E=y.next();this.serializeString(E),this.serialize(null!=_t[E]?S.getReserved(E):S.h[E])}this.buf.b+="h";break;case x:this.buf.b+="q";for(var R=e,I=R.keys();I.hasNext();){var M=I.next();this.buf.b+=":",this.buf.b+=null==M?"null":""+M,this.serialize(R.h[M])}this.buf.b+="h";break;case b:this.buf.b+="M";for(var O=e,D=O.keys();D.hasNext();){var w=D.next(),N=h.field(w,"__id__");h.deleteField(w,"__id__"),this.serialize(w),w.__id__=N,this.serialize(O.h[w.__id__])}this.buf.b+="h";break;case C:for(var F=e,L=0,B=F.length-2,V=new u,k=g.BASE64;L>2)),V.add(k.charAt(63&(U<<4|G>>4))),V.add(k.charAt(63&(G<<2|z>>6))),V.add(k.charAt(63&z))}if(L==B){var W=F.get(L++),H=F.get(L++);V.add(k.charAt(W>>2)),V.add(k.charAt(63&(W<<4|H>>4))),V.add(k.charAt(H<<2&63))}else if(L==B+1){var X=F.get(L++);V.add(k.charAt(X>>2)),V.add(k.charAt(X<<4&63))}var q=V.b;this.buf.b+="s",null==q.length?this.buf.b+="null":this.buf.b+=""+q.length,this.buf.b+=":",this.buf.b+=null==q?"null":""+q;break;default:this.useCache&&this.cache.pop(),null!=e.hxSerialize?(this.buf.b+="C",this.serializeString(p.getClassName(s)),this.useCache&&this.cache.push(e),e.hxSerialize(this),this.buf.b+="g"):(this.buf.b+="c",this.serializeString(p.getClassName(s)),this.useCache&&this.cache.push(e),this.serializeFields(e))}break;case 4:if(A.__instanceof(e,ft)){var Y=p.getClassName(e);this.buf.b+="A",this.serializeString(Y)}else if(A.__instanceof(e,pt))this.buf.b+="B",this.serializeString(p.getEnumName(e));else{if(this.useCache&&this.serializeRef(e))return;this.buf.b+="o",this.serializeFields(e)}break;case 7:var K=t[2];if(this.useCache){if(this.serializeRef(e))return;this.cache.pop()}this.useEnumIndex?this.buf.b+="j":this.buf.b+="w",this.serializeString(p.getEnumName(K)),this.useEnumIndex?(this.buf.b+=":",this.buf.b+=c.string(e[1])):this.serializeString(e[0]),this.buf.b+=":";var j=e.length;this.buf.b+=c.string(j-2);for(var $=2;$57)break;e=10*e+(r-48),this.pos++}else{if(this.pos!=i)break;t=!0,this.pos++}}return t&&(e*=-1),e},readFloat:function(){for(var e=this.pos;;){var t=this.buf.charCodeAt(this.pos);if(!(t>=43&&t<58||101==t||69==t))break;this.pos++}return c.parseFloat(o.substr(this.buf,e,this.pos-e))},unserializeObject:function(e){for(;;){if(this.pos>=this.length)throw new P("Invalid object");if(103==this.buf.charCodeAt(this.pos))break;var t=this.unserialize();if("string"!=typeof t)throw new P("Invalid object key");var i=this.unserialize();e[t]=i}this.pos++},unserializeEnum:function(e,t){if(58!=this.get(this.pos++))throw new P("Invalid enum format");var i=this.readDigits();if(0==i)return p.createEnum(e,t);for(var r=[];i-- >0;)r.push(this.unserialize());return p.createEnum(e,t,r)},unserialize:function(){switch(this.get(this.pos++)){case 110:return null;case 116:return!0;case 102:return!1;case 122:return 0;case 105:return this.readDigits();case 100:return this.readFloat();case 121:var e=this.readDigits();if(58!=this.get(this.pos++)||this.length-this.pos=this.cache.length)throw new P("Invalid reference");return this.cache[a];case 82:var h=this.readDigits();if(h<0||h>=this.scache.length)throw new P("Invalid string reference");return this.scache[h];case 120:throw new P(this.unserialize());case 99:var c=this.unserialize(),u=this.resolver.resolveClass(c);if(null==u)throw new P("Class not found "+c);var f=p.createEmptyInstance(u);return this.cache.push(f),this.unserializeObject(f),f;case 119:var _=this.unserialize(),m=this.resolver.resolveEnum(_);if(null==m)throw new P("Enum not found "+_);var g=this.unserializeEnum(m,this.unserialize());return this.cache.push(g),g;case 106:var S=this.unserialize(),y=this.resolver.resolveEnum(S);if(null==y)throw new P("Enum not found "+S);this.pos++;var E=this.readDigits(),A=p.getEnumConstructs(y)[E];if(null==A)throw new P("Unknown enum index "+S+"@"+E);var R=this.unserializeEnum(y,A);return this.cache.push(R),R;case 108:var I=new l;for(this.cache.push(I),this.buf;104!=this.buf.charCodeAt(this.pos);)I.add(this.unserialize());return this.pos++,I;case 98:var M=new T;for(this.cache.push(M),this.buf;104!=this.buf.charCodeAt(this.pos);){var O=this.unserialize();M.set(O,this.unserialize())}return this.pos++,M;case 113:var D=new x;this.cache.push(D),this.buf;for(var w=this.get(this.pos++);58==w;){var N=this.readDigits();D.set(N,this.unserialize()),w=this.get(this.pos++)}if(104!=w)throw new P("Invalid IntMap format");return D;case 77:var F=new b;for(this.cache.push(F),this.buf;104!=this.buf.charCodeAt(this.pos);){var L=this.unserialize();F.set(L,this.unserialize())}return this.pos++,F;case 118:var B;if(this.buf.charCodeAt(this.pos)>=48&&this.buf.charCodeAt(this.pos)<=57&&this.buf.charCodeAt(this.pos+1)>=48&&this.buf.charCodeAt(this.pos+1)<=57&&this.buf.charCodeAt(this.pos+2)>=48&&this.buf.charCodeAt(this.pos+2)<=57&&this.buf.charCodeAt(this.pos+3)>=48&&this.buf.charCodeAt(this.pos+3)<=57&&45==this.buf.charCodeAt(this.pos+4)){var V=o.substr(this.buf,this.pos,19);B=o.strDate(V),this.pos+=19}else{var k=this.readFloat(),U=new Date;U.setTime(k),B=U}return this.cache.push(B),B;case 115:var G=this.readDigits(),z=this.buf;if(58!=this.get(this.pos++)||this.length-this.pos>2)+(q>=2?q-1:0);for(var Y=X+(G-q),K=C.alloc(H),j=0;X>4);var Z=W[d.fastCodeAt(z,X++)];K.set(j++,Q<<4|Z>>2);var J=W[d.fastCodeAt(z,X++)];K.set(j++,Z<<6|J)}if(q>=2){var ee=W[d.fastCodeAt(z,X++)],te=W[d.fastCodeAt(z,X++)];if(K.set(j++,ee<<2|te>>4),3==q){var ie=W[d.fastCodeAt(z,X++)];K.set(j++,te<<4|ie>>2)}}return this.pos+=G,this.cache.push(K),K;case 67:var re=this.unserialize(),se=this.resolver.resolveClass(re);if(null==se)throw new P("Class not found "+re);var ne=p.createEmptyInstance(se);if(this.cache.push(ne),ne.hxUnserialize(this),103!=this.get(this.pos++))throw new P("Invalid custom data");return ne;case 65:var oe=this.unserialize(),ae=this.resolver.resolveClass(oe);if(null==ae)throw new P("Class not found "+oe);return ae;case 66:var le=this.unserialize(),he=this.resolver.resolveEnum(le);if(null==he)throw new P("Enum not found "+le);return he}throw this.pos--,new P("Invalid char "+this.buf.charAt(this.pos)+" at position "+this.pos)},__class__:v};var x=function(){this.h={}};r["haxe.ds.IntMap"]=x,x.__name__=["haxe","ds","IntMap"],x.__interfaces__=[_],x.prototype={set:function(e,t){this.h[e]=t},remove:function(e){return!!this.h.hasOwnProperty(e)&&(delete this.h[e],!0)},keys:function(){var e=[];for(var t in this.h)this.h.hasOwnProperty(t)&&e.push(0|t);return o.iter(e)},__class__:x};var b=function(){this.h={},this.h.__keys__={}};r["haxe.ds.ObjectMap"]=b,b.__name__=["haxe","ds","ObjectMap"],b.__interfaces__=[_],b.prototype={set:function(e,t){var i=e.__id__||(e.__id__=++b.count);this.h[i]=t,this.h.__keys__[i]=e},keys:function(){var e=[];for(var t in this.h.__keys__)this.h.hasOwnProperty(t)&&e.push(this.h.__keys__[t]);return o.iter(e)},__class__:b};var S=r["haxe.ds.Option"]={__ename__:["haxe","ds","Option"],__constructs__:["Some","None"]};S.Some=function(e){var t=["Some",0,e];return t.__enum__=S,t.toString=s,t},S.None=["None",1],S.None.toString=s,S.None.__enum__=S;var T=function(){this.h={}};r["haxe.ds.StringMap"]=T,T.__name__=["haxe","ds","StringMap"],T.__interfaces__=[_],T.prototype={set:function(e,t){null!=_t[e]?this.setReserved(e,t):this.h[e]=t},get:function(e){return null!=_t[e]?this.getReserved(e):this.h[e]},setReserved:function(e,t){null==this.rh&&(this.rh={}),this.rh["$"+e]=t},getReserved:function(e){return null==this.rh?null:this.rh["$"+e]},keys:function(){var e=this.arrayKeys();return o.iter(e)},arrayKeys:function(){var e=[];for(var t in this.h)this.h.hasOwnProperty(t)&&e.push(t);if(null!=this.rh)for(var t in this.rh)36==t.charCodeAt(0)&&e.push(t.substr(1));return e},__class__:T};var C=function(e){this.length=e.byteLength,this.b=new gt(e),this.b.bufferValue=e,e.hxBytes=this,e.bytes=this.b};r["haxe.io.Bytes"]=C,C.__name__=["haxe","io","Bytes"],C.alloc=function(e){return new C(new mt(e))},C.prototype={get:function(e){return this.b[e]},set:function(e,t){this.b[e]=255&t},__class__:C};var y=r["haxe.io.Error"]={__ename__:["haxe","io","Error"],__constructs__:["Blocked","Overflow","OutsideBounds","Custom"]};y.Blocked=["Blocked",0],y.Blocked.toString=s,y.Blocked.__enum__=y,y.Overflow=["Overflow",1],y.Overflow.toString=s,y.Overflow.__enum__=y,y.OutsideBounds=["OutsideBounds",2],y.OutsideBounds.toString=s,y.OutsideBounds.__enum__=y,y.Custom=function(e){var t=["Custom",3,e];return t.__enum__=y,t.toString=s,t};var E=function(){};r["haxe.io.FPHelper"]=E,E.__name__=["haxe","io","FPHelper"],E.i32ToFloat=function(e){var t=e>>>23&255,i=8388607&e;return 0==i&&0==t?0:(1-(e>>>31<<1))*(1+Math.pow(2,-23)*i)*Math.pow(2,t-127)},E.floatToI32=function(e){if(0==e)return 0;var t;t=e<0?-e:e;var i=Math.floor(Math.log(t)/.6931471805599453);return i<-127?i=-127:i>128&&(i=128),(e<0?-2147483648:0)|i+127<<23|8388607&Math.round(8388608*(t/Math.pow(2,i)-1))},E.i64ToDouble=function(e,t){var i=(t>>20&2047)-1023,r=4294967296*(1048575&t)+2147483648*(e>>>31)+(2147483647&e);return 0==r&&-1023==i?0:(1-(t>>>31<<1))*(1+Math.pow(2,-52)*r)*Math.pow(2,i)},E.doubleToI64=function(e){var t=E.i64tmp;if(0==e)t.low=0,t.high=0;else{var i;i=e<0?-e:e;var r,s=Math.floor(Math.log(i)/.6931471805599453),n=4503599627370496*(i/Math.pow(2,s)-1),o=0|(r=Math.round(n)),a=r/4294967296|0;t.low=o,t.high=(e<0?-2147483648:0)|s+1023<<20|a}return t};var P=function(e){Error.call(this),this.val=e,this.message=String(e),Error.captureStackTrace&&Error.captureStackTrace(this,P)};r["js._Boot.HaxeError"]=P,P.__name__=["js","_Boot","HaxeError"],P.__super__=Error,P.prototype=n(Error.prototype,{__class__:P});var A=function(){};r["js.Boot"]=A,A.__name__=["js","Boot"],A.getClass=function(e){if(e instanceof Array&&null==e.__enum__)return Array;var t=e.__class__;if(null!=t)return t;var i=A.__nativeClassName(e);return null!=i?A.__resolveNativeClass(i):null},A.__string_rec=function(e,t){if(null==e)return"null";if(t.length>=5)return"<...>";var i=typeof e;switch("function"==i&&(e.__name__||e.__ename__)&&(i="object"),i){case"object":if(e instanceof Array){if(e.__enum__){if(2==e.length)return e[0];var r=e[0]+"(";t+="\t";for(var s=2,n=e.length;s0?",":"")+A.__string_rec(e[c],t)}return l+"]"}var u;try{u=e.toString}catch(e){return e instanceof P&&(e=e.val),"???"}if(null!=u&&u!=Object.toString&&"function"==typeof u){var d=e.toString();if("[object Object]"!=d)return d}var f=null,p="{\n";t+="\t";var _=null!=e.hasOwnProperty;for(var f in e)_&&!e.hasOwnProperty(f)||"prototype"!=f&&"__class__"!=f&&"__super__"!=f&&"__interfaces__"!=f&&"__properties__"!=f&&(2!=p.length&&(p+=", \n"),p+=t+f+" : "+A.__string_rec(e[f],t));return p+"\n"+(t=t.substring(1))+"}";case"function":return"";case"string":return e;default:return String(e)}},A.__interfLoop=function(e,t){if(null==e)return!1;if(e==t)return!0;var i=e.__interfaces__;if(null!=i)for(var r=0,s=i.length;re.byteLength)throw new P(y.OutsideBounds)};r["js.html.compat.DataView"]=I,I.__name__=["js","html","compat","DataView"],I.prototype={getInt8:function(e){var t=this.buf.a[this.offset+e];return t>=128?t-256:t},getUint8:function(e){return this.buf.a[this.offset+e]},getInt16:function(e,t){var i=this.getUint16(e,t);return i>=32768?i-65536:i},getUint16:function(e,t){return t?this.buf.a[this.offset+e]|this.buf.a[this.offset+e+1]<<8:this.buf.a[this.offset+e]<<8|this.buf.a[this.offset+e+1]},getInt32:function(e,t){var i=this.offset+e,r=this.buf.a[i++],s=this.buf.a[i++],n=this.buf.a[i++],o=this.buf.a[i++];return t?r|s<<8|n<<16|o<<24:o|n<<8|s<<16|r<<24},getUint32:function(e,t){var i=this.getInt32(e,t);return i<0?i+4294967296:i},getFloat32:function(e,t){return E.i32ToFloat(this.getInt32(e,t))},getFloat64:function(e,t){var i=this.getInt32(e,t),r=this.getInt32(e+4,t);return E.i64ToDouble(t?i:r,t?r:i)},setInt8:function(e,t){this.buf.a[e+this.offset]=t<0?t+128&255:255&t},setUint8:function(e,t){this.buf.a[e+this.offset]=255&t},setInt16:function(e,t,i){this.setUint16(e,t<0?t+65536:t,i)},setUint16:function(e,t,i){var r=e+this.offset;i?(this.buf.a[r]=255&t,this.buf.a[r++]=t>>8&255):(this.buf.a[r++]=t>>8&255,this.buf.a[r]=255&t)},setInt32:function(e,t,i){this.setUint32(e,t,i)},setUint32:function(e,t,i){var r=e+this.offset;i?(this.buf.a[r++]=255&t,this.buf.a[r++]=t>>8&255,this.buf.a[r++]=t>>16&255,this.buf.a[r++]=t>>>24):(this.buf.a[r++]=t>>>24,this.buf.a[r++]=t>>16&255,this.buf.a[r++]=t>>8&255,this.buf.a[r++]=255&t)},setFloat32:function(e,t,i){this.setUint32(e,E.floatToI32(t),i)},setFloat64:function(e,t,i){var r=E.doubleToI64(t);i?(this.setUint32(e,r.low),this.setUint32(e,r.high)):(this.setUint32(e,r.high),this.setUint32(e,r.low))},__class__:I};var M=function(){};r["js.html.compat.Uint8Array"]=M,M.__name__=["js","html","compat","Uint8Array"],M._new=function(e,t,i){var r;if("number"==typeof e){r=[];for(var s=0;si.byteLength)throw new P("set() outside of range");for(var s=0,n=e.byteLength;si.byteLength)throw new P("set() outside of range");for(var l=0,h=a.length;l0||t.handleError(e._errorVal),e._resolved&&!e._pending)try{t.handleResolve(i(e._val))}catch(e){e instanceof P&&(e=e.val),t.handleError(e)}},O.linkAll=function(e,t){for(var i=function(i,r,s){if(0==i.length||O.allFulfilled(i)){for(var n,o=[],a=nt(e)();a.hasNext();){var l=a.next();o.push(l==r?s:l._val)}n=o,t.handleResolve(n)}},r=nt(e)();r.hasNext();){var s=r.next();s._update.push({async:t,linkf:function(e,t,i){return function(r){e(t,i,r)}}(i,function(t){for(var i=[],r=nt(e)();r.hasNext();){var n=r.next();n!=s&&i.push(n)}return i}(),s)})}O.allFulfilled(e)&&t.handleResolve(function(t){for(var i=[],r=nt(e)();r.hasNext();){var s=r.next();i.push(s._val)}return i}())},O.pipeLink=function(e,t,i){var r=!1,s=function(e){if(!r){r=!0;var s=i(e);s._update.push({async:t,linkf:lt(t,t.handleResolve)}),O.immediateLinkUpdate(s,t,(function(e){return e}))}};if(e._update.push({async:t,linkf:s}),e._resolved&&!e._pending)try{s(e._val)}catch(e){e instanceof P&&(e=e.val),t.handleError(e)}},O.allResolved=function(e){for(var t=nt(e)();t.hasNext();)if(!t.next()._resolved)return!1;return!0},O.allFulfilled=function(e){for(var t=nt(e)();t.hasNext();)if(!t.next()._fulfilled)return!1;return!0},O.prototype={catchError:function(e){return this._error.push(e),this},errorThen:function(e){return this._errorMap=e,this},isResolved:function(){return this._resolved},isErrored:function(){return this._errored},isErrorHandled:function(){return this._error.length>0},isErrorPending:function(){return this._errorPending},isFulfilled:function(){return this._fulfilled},isPending:function(){return this._pending},handleResolve:function(e){this._resolve(e)},_resolve:function(e){var t,i,r=this;this._pending?L.enqueue((t=lt(this,this._resolve),i=e,function(){t(i)})):(this._resolved=!0,this._pending=!0,L.queue.add((function(){r._val=e;for(var t=0,i=r._update;t0)for(var i=0,r=t._error;i0))throw new P(e);for(var n=0,o=t._update;n0&&null!=(t=L.queue.pop());)t();return L.queue.isEmpty()},L.clear=function(){L.queue=new l},L.f=function(){var e=L.queue.pop();null!=e&&e(),L.queue.isEmpty()||L.continueOnNextLoop()},L.continueOnNextLoop=function(){null!=L.nextLoop?L.nextLoop(L.f):setImmediate(L.f)};var B=r["promhx.error.PromiseError"]={__ename__:["promhx","error","PromiseError"],__constructs__:["AlreadyResolved","DownstreamNotFullfilled"]};B.AlreadyResolved=function(e){var t=["AlreadyResolved",0,e];return t.__enum__=B,t.toString=s,t},B.DownstreamNotFullfilled=function(e){var t=["DownstreamNotFullfilled",1,e];return t.__enum__=B,t.toString=s,t};var V=function(){};r["verb.Verb"]=V,V.__name__=["verb","Verb"],V.main=function(){e.log("verb 2.1.0")};var k=function(){};r["verb.core.ArrayExtensions"]=k,k.__name__=["verb","core","ArrayExtensions"],k.alloc=function(e,t){if(!(t<0))for(;e.length0;){for(var r=e.pop(),s=!0,n=0;ne)return 0;if(t>e-t&&(t=e-t),U.memo_exists(e,t))return U.get_memo(e,t);for(var i=1,r=e,s=1,n=t+1;se)return 0;t>e-t&&(t=e-t);for(var i=1,r=1,s=t+1;r=l&&o<=h||a>=l&&a<=h||l>=o&&l<=a||h>=o&&h<=a},G.prototype={fromPoint:function(e){return new G([e])},add:function(e){if(!this.initialized)return this.dim=e.length,this.min=e.slice(0),this.max=e.slice(0),this.initialized=!0,this;for(var t=0,i=this.dim;tthis.max[r]&&(this.max[r]=e[r]),e[r]e&&(e=n,t=s)}return t},getAxisLength:function(e){return e<0||e>this.dim-1?0:Math.abs(this.min[e]-this.max[e])},intersect:function(e,t){if(!this.initialized)return null;var i=this.min,r=this.max,s=e.min,n=e.max;if(!this.intersects(e,t))return null;for(var o=[],a=[],l=0,h=this.dim;l0?1:-1})),r=Math.floor(e.length/2),(s=new ue(e[r],n,i)).left=this.buildTree(e.slice(0,r),t+1,s),s.right=this.buildTree(e.slice(r+1),t+1,s),s)},nearest:function(e,t,i){var r,s=this,n=new he((function(e){return-e.item1})),o=null;r=o=function(i){for(var r,a,l,h,c=i.dimension,u=s.distanceFunction(e,i.kdPoint.point),d=[],f=0,p=s.dim;ft&&n.pop()},m=0,g=s.dim;m0&&(this.content[0]=t,this.sinkDown(0)),e},peek:function(){return this.content[0]},remove:function(e){for(var t=this.content.length,i=0;i0;){var i=Math.floor((e+1)/2)-1,r=this.content[i];if(!(this.scoreFunction(t)=0;){for(o=[],a=e[c],d=s-1;d>=0;){for(l=a[r-1]*t[r-1][d],u=r-2;u>=1;)h=u-1,l+=a[u]*t[u][d]+a[h]*t[h][d],u-=2;0==u&&(l+=a[0]*t[0][d]),o[d]=l,d--}n[c]=o,c--}return n},ge.add=function(e,t){for(var i=[],r=0,s=e.length;r=0;){for(n=a[i],r=i+1;rr?1:-1}));for(var l=[],h=0,c=s.length;h=.1*m*n||isNaN(u));)m*=.5,++x;if(m*g20)throw new P("Numerical gradient fails");if(d[m]=t[m]+g,s=e(d),d[m]=t[m]-g,n=e(d),d[m]=t[m],isNaN(s)||isNaN(n))g/=16;else{if(f[m]=(s-n)/(2*g),o=t[m]-g,a=t[m],l=t[m]+g,h=(s-r)/g,c=(r-n)/g,u=Pe.max([Math.abs(f[m]),Math.abs(r),Math.abs(s),Math.abs(n),Math.abs(o),Math.abs(a),Math.abs(l),1e-8]),!(Math.min(Pe.max([Math.abs(h-f[m]),Math.abs(c-f[m]),Math.abs(h-c)])/u,g/u)>.001))break;g/=16}}return f},Se.tensor=function(e,t){for(var i,r,s=e.length,n=t.length,o=[],a=s-1;a>=0;){i=[],r=e[a];for(var l=n-1;l>=3;)i[l]=r*t[l],i[--l]=r*t[l],i[--l]=r*t[l],i[--l]=r*t[l],--l;for(;l>=0;)i[l]=r*t[l],--l;o[a]=i,a--}return o};var Te=function(e,t,i,r,s,n){this.solution=e,this.value=t,this.gradient=i,this.invHessian=r,this.iterations=s,this.message=n};r["verb.core.MinimizationResult"]=Te,Te.__name__=["verb","core","MinimizationResult"],Te.prototype={__class__:Te};var Ce=function(){};r["verb.core.ISerializable"]=Ce,Ce.__name__=["verb","core","ISerializable"],Ce.prototype={__class__:Ce};var ye=t.core.Deserializer=function(){};r["verb.core.Deserializer"]=ye,ye.__name__=["verb","core","Deserializer"],ye.deserialize=function(e){return new v(e).unserialize()};var Ee=t.core.Trig=function(){};r["verb.core.Trig"]=Ee,Ee.__name__=["verb","core","Trig"],Ee.isPointInPlane=function(e,t,i){return Math.abs(Pe.dot(Pe.sub(e,t.origin),t.normal))o?{u:s,pt:i}:{u:r+(s-r)*c/o,pt:Pe.add(a,Pe.mul(c,l))}};var Pe=t.core.Vec=function(){};r["verb.core.Vec"]=Pe,Pe.__name__=["verb","core","Vec"],Pe.angleBetween=function(e,t){return Math.acos(Pe.dot(e,t)/(Pe.norm(e)*Pe.norm(t)))},Pe.positiveAngleBetween=function(e,t,i){var r=Pe.cross(e,t),s=Pe.norm(e)*Pe.norm(t),n=Pe.dot(e,t),o=Pe.norm(r)/s,a=n/s,l=Math.atan2(o,a),h=Pe.dot(i,r);return Math.abs(h)0?l:-l},Pe.signedAngleBetween=function(e,t,i){var r=Pe.cross(e,t),s=Pe.norm(e)*Pe.norm(t),n=Pe.dot(e,t),o=Pe.norm(r)/s,a=n/s,l=Math.atan2(o,a);return Pe.dot(i,r)>0?l:2*Math.PI-l},Pe.angleBetweenNormalized2d=function(e,t){var i=e[0]*t[1]-e[1]*t[0];return Math.atan2(i,Pe.dot(e,t))},Pe.domain=function(e){return k.last(e)-k.first(e)},Pe.range=function(e){for(var t=[],i=0,r=0;rt&&i>0)return[];if(t>e&&i<0)return[];for(var r=[],s=e;s<=t;)r.push(s),s+=i;return r},Pe.neg=function(e){return e.map((function(e){return-e}))},Pe.min=function(e){return a.fold(e,(function(e,t){return Math.min(e,t)}),1/0)},Pe.max=function(e){return a.fold(e,(function(e,t){return Math.max(e,t)}),-1/0)},Pe.all=function(e){return a.fold(e,(function(e,t){return t&&e}),!0)},Pe.finite=function(e){return e.map((function(e){return isFinite(e)}))},Pe.onRay=function(e,t,i){return Pe.add(e,Pe.mul(i,t))},Pe.lerp=function(e,t,i){return Pe.add(Pe.mul(e,t),Pe.mul(1-e,i))},Pe.normalized=function(e){return Pe.div(e,Pe.norm(e))},Pe.cross=function(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]},Pe.dist=function(e,t){return Pe.norm(Pe.sub(e,t))},Pe.distSquared=function(e,t){return Pe.normSquared(Pe.sub(e,t))},Pe.sum=function(e){return a.fold(e,(function(e,t){return t+e}),0)},Pe.addAll=function(e){var t=nt(e)();if(!t.hasNext())return null;var i=t.next().length;return a.fold(e,(function(e,t){return Pe.add(t,e)}),Pe.rep(i,0))},Pe.addAllMutate=function(e){for(var t=e[0],i=1,r=e.length;iz.TOLERANCE)return!1}return!0},Pe.sortedSetUnion=function(e,t){for(var i=[],r=0,s=0;r=e.length)i.push(t[s]),s++;else if(s>=t.length)i.push(e[r]),r++;else{var n=e[r]-t[s];Math.abs(n)0?(i.push(t[s]),s++):(i.push(e[r]),r++)}return i},Pe.sortedSetSub=function(e,t){for(var i=[],r=0,s=0;r=t.length?(i.push(e[r]),r++):Math.abs(e[r]-t[s])z.EPSILON&&(i=new Re(s,0),t.push(i)),i.inc()}return t},Ae.isRationalSurfaceClosed=function(e,t){var i;null==t&&(t=!0);for(var r=0,s=(i=t?e.controlPoints:ge.transpose(e.controlPoints))[0].length;rh&&(P=d?[l+(P[0]-h),P[1]]:[h-z.EPSILON,P[1]]),P[1]u&&(P=f?[P[0],c+(P[0]-u)]:[P[0],u-z.EPSILON]),Pe.norm(Pe.mul(P[0]-s[0],i[1][0]))+Pe.norm(Pe.mul(P[1]-s[1],i[0][1]))x&&(P=b?v+(P-x):x),Pe.norm(Pe.mul(P-S,p[1]))(s=null!=r?r:Ae.rationalBezierCurveArcLength(e)))return k.last(e.knots);var n,o=e.knots[0],a=0,l=k.last(e.knots),h=s,c=0,u=0;for(n=null!=i?i:2*z.TOLERANCE;h-a>n;)c=(o+l)/2,(u=Ae.rationalBezierCurveArcLength(e,c))>t?(l=c,h=u):(o=c,a=u);return(o+l)/2},Ae.rationalCurveArcLength=function(e,t,i){null==i&&(i=16),null==t&&(t=k.last(e.knots));for(var r=Fe.decomposeCurveIntoBeziers(e),s=0,n=r[0],o=0;sz.EPSILON)return!1}i=k.last(e);for(var o=e.length-t-1,a=e.length;oz.EPSILON)return!1}return Ie.isNonDecreasing(e)},Ie.isNonDecreasing=function(e){for(var t=k.first(e),i=0,r=e.length;is)return n;for(var o,a=t,l=0,h=a,c=0,u=0;l=t[l+1];)l++;o.push(l),n.push(De.basisFunctionsGivenKnotSpanIndex(l,a,e,t)),a+=s}return new Q(o,n)},De.regularlySpacedDerivativeBasisFunctions=function(e,t,i){for(var r=t.length-e-2,s=(k.last(t)-t[0])/i,n=[],o=[],a=t[0],l=De.knotSpanGivenN(r,e,a,t),h=i+1,c=0;c=t[l+1];)l++;o.push(l),n.push(De.derivativeBasisFunctionsGivenNI(l,a,e,r,t)),a+=s}return new Q(o,n)},De.surfacePointGivenBasesKnotSpans=function(e,t,i,r,s,n,o,a){for(var l,h=Pe.zeros1d(a),c=r-e,u=s-t,d=0,f=t+1;d=M&&(m[v][0]=m[g][0]/n[S+1][b],x=m[v][0]*n[b][S]);for(var O=b>=-1?1:-b,D=1+(A-1<=S?M-1:i-A);Or[e+1]-z.EPSILON)return e;if(i=r[o+1];)iz.EPSILON})),(function(e,t){var i=Pe.sub(e.min.uv0,t.min.uv0),r=Pe.dot(i,i),s=Pe.sub(e.max.uv0,t.max.uv0),n=Pe.dot(s,s),o=Pe.sub(e.min.uv0,t.max.uv0),a=Pe.dot(o,o),l=Pe.sub(e.max.uv0,t.min.uv0),h=Pe.dot(l,l);return r0&&(_.push(_[_.length-1].opp),u.push(_))}if(0==c.length&&s.length>0&&(f||d0;){var o=r.pop(),a=s.pop();if(!o.empty()&&!a.empty()&&o.boundingBox().intersects(a.boundingBox(),i)){var l=o.indivisible(i),h=a.indivisible(i);if(l&&h)n.push(new Q(o.yield(),a.yield()));else if(!l||h)if(l||!h){var c=o.split(),u=a.split();r.push(c.item1),s.push(u.item1),r.push(c.item1),s.push(u.item0),r.push(c.item0),s.push(u.item1),r.push(c.item0),s.push(u.item0)}else{var d=o.split();r.push(d.item1),s.push(a),r.push(d.item0),s.push(a)}else{var f=a.split();r.push(o),s.push(f.item1),r.push(o),s.push(f.item0)}}}return n},we.curves=function(e,t,i){var r=we.boundingBoxTrees(new fe(e),new fe(t),0);return k.unique(r.map((function(r){return we.curvesWithEstimate(e,t,k.first(r.item0.knots),k.first(r.item1.knots),i)})).filter((function(e){return Pe.distSquared(e.point0,e.point1)h[f]+z.EPSILON||((null==c||vu.u)&&(u=new ne(v,Pe.onRay(e.origin,e.dir,v),Pe.onRay(n[f],o[f],g/h[f]))))}}return null==u||null==c?null:new Z(c,u)},we.mergeTriangleClipIntervals=function(e,t,i,r,s,n){if(t.min.u>e.max.u+z.EPSILON||e.min.u>t.max.u+z.EPSILON)return null;var o,a;o=e.min.u>t.min.u?new Q(e.min,0):new Q(t.min,1),a=e.max.uc&&(h=1,c=u),d>c&&(h=2,c=d),0==h?(n=t[1],o=t[2],a=r[1],l=r[2]):1==h?(n=t[0],o=t[2],a=r[0],l=r[2]):(n=t[0],o=t[1],a=r[0],l=r[1]);var f=-Pe.dot(e,t),p=-Pe.dot(i,r),_=n*l-o*a,m=(o*p-f*l)/_,g=(f*a-n*p)/_;return new X(0==h?[0,m,g]:1==h?[m,0,g]:[m,g,0],Pe.normalized(s))},we.threePlanes=function(e,t,i,r,s,n){var o=Pe.cross(i,s),a=Pe.dot(e,o);if(Math.abs(a)1)return null;var _=Pe.add(e,Pe.mul(p,c)),m=Pe.dot(a,l),g=Pe.dot(a,a),v=Pe.dot(l,l),x=Pe.sub(_,s),b=Pe.dot(x,a),S=Pe.dot(x,l),T=m*m-g*v;if(Math.abs(T)1+z.EPSILON||y>1+z.EPSILON||y<-z.EPSILON||C<-z.EPSILON||C+y>1+z.EPSILON?null:new se(_,C,y,p)},we.segmentAndPlane=function(e,t,i,r){var s=Pe.dot(r,Pe.sub(t,e));if(Math.abs(s)1+z.EPSILON||n<-z.EPSILON?null:{p:n}};var Ne=t.eval.Make=function(){};r["verb.eval.Make"]=Ne,Ne.__name__=["verb","eval","Make"],Ne.rationalTranslationalSurface=function(e,t){for(var i=De.rationalCurvePoint(t,k.first(t.knots)),r=k.first(t.knots),s=k.last(t.knots),n=2*t.controlPoints.length,o=(s-r)/(n-1),a=[],l=0;l=0&&(u-=n[o].mult),c=u>0?Fe.surfaceKnotRefine(e,Pe.rep(u,t),i):e;var d=De.knotSpan(s,t,r);return Math.abs(t-k.first(r))e.length-1&&(t=e.length-1);for(var r=e[0].knots,s=[],n=[],o=0,a=e[0].controlPoints.length;oz.EPSILON&&(E=Pe.mul(1/P,E),A=Pe.mul(1/P,A)),m[0][C]=o[C];var R=o[C];g[0][C]=a[C];for(var I=A,M=0,O=1,D=s+1;Ot?e:t},Fe.curveElevateDegree=function(e,t){if(t<=e.degree)return e;var i=e.knots.length-e.degree-2,r=e.degree,s=e.knots,n=e.controlPoints,o=t-e.degree,a=e.controlPoints[0].length,l=Pe.zeros2d(r+o+1,r+1),h=[],c=[],u=[],d=i+r+1,f=t,p=Math.floor(f/2),_=[],m=[];l[0][0]=1,l[f][r]=1;for(var g=1,v=p+1;g0?Math.floor((j+2)/2):1,X=D>0?Math.floor(f-(D+1)/2):f,D>0){for(var $=K-L,Q=[],Z=r;Z>Y;)Q[Z-Y-1]=$/(s[w+Z]-L),Z--;for(var J=1,ee=D+1;J=re;)h[se]=Pe.add(Pe.mul(Q[se-re],h[se]),Pe.mul(1-Q[se-re],h[se-1])),se--;u[ie]=h[r]}}for(var ne=H,oe=f+1;ne1)for(var de=O-2,fe=O,pe=K-L,_e=(K-m[O-1])/pe,me=1;mege;){if(ve=H){if(xe-ge<=O-f+j){var Te=(K-m[xe-ge])/pe;c[be]=Pe.lerp(Te,c[be],c[be+1])}}else c[be]=Pe.lerp(_e,c[be],c[be+1]);ve+=1,xe-=1,be-=1}de-=1,fe+=1}if(w!=r)for(var Ce=0,ye=f-j;Ce=0;){for(;t[P]<=s[y]&&y>l;)c[E-i-1]=r[y-i-1],u[E]=s[y],E-=1,y-=1;c[E-i-1]=c[E-i];for(var A=1,R=i+1;Ar||!Ee.threePointsAreFlat(n,l,o,r)){var u=t+.5*(i-t),d=Le.rationalCurveAdaptiveSampleRange(e,t,u,r,s),f=Le.rationalCurveAdaptiveSampleRange(e,u,i,r,s);return d.slice(0,-1).concat(f)}return s?[[t].concat(n),[i].concat(o)]:[n,o]},Le.rationalSurfaceNaive=function(e,t,i){t<1&&(t=1),i<1&&(i=1),e.degreeU,e.degreeV,e.controlPoints;for(var r=e.knotsU,s=e.knotsV,n=(k.last(r)-r[0])/t,o=(k.last(s)-s[0])/i,a=[],l=[],h=[],c=0,u=t+1;cs?t.minDivsU=t.minDivsU:t.minDivsU=s,r=t.minDivsV>n?t.minDivsV=t.minDivsV:t.minDivsV=n;for(var o=k.last(e.knotsU),a=e.knotsU[0],l=k.last(e.knotsV),h=e.knotsV[0],c=(o-a)/i,u=(l-h)/r,d=[],f=[],p=0,_=r+1;p<_;){for(var m=p++,g=[],v=0,x=i+1;vn.corners[0].uv[0]+s&&e.uv[0]n.corners[0].uv[1]+s&&e.uv[1]=e.maxDepth)return!1;if(this.hasBadNormals())return this.fixNormals(),!1;if(this.splitVert=Pe.normSquared(Pe.sub(this.corners[0].normal,this.corners[1].normal))>e.normTol||Pe.normSquared(Pe.sub(this.corners[2].normal,this.corners[3].normal))>e.normTol,this.splitHoriz=Pe.normSquared(Pe.sub(this.corners[1].normal,this.corners[2].normal))>e.normTol||Pe.normSquared(Pe.sub(this.corners[3].normal,this.corners[0].normal))>e.normTol,this.splitVert||this.splitHoriz)return!0;var i=this.center();return Pe.normSquared(Pe.sub(i.normal,this.corners[0].normal))>e.normTol||Pe.normSquared(Pe.sub(i.normal,this.corners[1].normal))>e.normTol||Pe.normSquared(Pe.sub(i.normal,this.corners[2].normal))>e.normTol||Pe.normSquared(Pe.sub(i.normal,this.corners[3].normal))>e.normTol},divide:function(e){null==e&&(e=new Be),null==e.normTol&&(e.normTol=.085),null==e.minDepth&&(e.minDepth=0),null==e.maxDepth&&(e.maxDepth=10),this._divide(e,0,!0)},_divide:function(e,t,i){if(this.evalCorners(),this.shouldDivide(e,t)){if(t++,this.splitVert&&!this.splitHoriz?i=!1:!this.splitVert&&this.splitHoriz&&(i=!0),this.horizontal=i,this.horizontal){var r=[this.corners[0],this.corners[1],this.midpoint(1),this.midpoint(3)],s=[this.midpoint(3),this.midpoint(1),this.corners[2],this.corners[3]];this.children=[new Ve(this.srf,r),new Ve(this.srf,s)],this.children[0].neighbors=[this.neighbors[0],this.neighbors[1],this.children[1],this.neighbors[3]],this.children[1].neighbors=[this.children[0],this.neighbors[1],this.neighbors[2],this.neighbors[3]]}else{var n=[this.corners[0],this.midpoint(0),this.midpoint(2),this.corners[3]],o=[this.midpoint(0),this.corners[1],this.corners[2],this.midpoint(2)];this.children=[new Ve(this.srf,n),new Ve(this.srf,o)],this.children[0].neighbors=[this.neighbors[0],this.children[1],this.neighbors[2],this.neighbors[3]],this.children[1].neighbors=[this.neighbors[0],this.neighbors[1],this.neighbors[2],this.children[0]]}for(var a=0,l=this.children;a0&&this._pool.length>0;){var i=this._queue.shift(),r=[i.id],s=[this._pool.shift()];this._working.h[r[0]]=s[0],s[0].onmessage=function(i,r){return function(s){t._working.remove(r[0]),t._pool.push(i[0]);try{t._callbacks.h.hasOwnProperty(r[0])&&(t._callbacks.h[r[0]](s.data.result),t._callbacks.remove(r[0]))}catch(t){t instanceof P&&(t=t.val),e.log(t)}t.processQueue()}}(s,r),s[0].postMessage(i)}},__class__:Ue};var Ge=function(e,t,i){this.className=e,this.methodName=t,this.args=i,this.id=Ge.uuid++};r["verb.exe._WorkerPool.Work"]=Ge,Ge.__name__=["verb","exe","_WorkerPool","Work"],Ge.prototype={__class__:Ge};var ze=function(){};r["verb.geom.ICurve"]=ze,ze.__name__=["verb","geom","ICurve"],ze.__interfaces__=[Ce],ze.prototype={__class__:ze};var We=t.geom.NurbsCurve=function(e){this._data=Ie.isValidNurbsCurveData(e)};r["verb.geom.NurbsCurve"]=We,We.__name__=["verb","geom","NurbsCurve"],We.__interfaces__=[ze],We.byKnotsControlPointsWeights=function(e,t,i,r){return new We(new q(e,t.slice(),De.homogenize1d(i,r)))},We.byPoints=function(e,t){return null==t&&(t=3),new We(Ne.rationalInterpCurve(e,t))},We.__super__=W,We.prototype=n(W.prototype,{degree:function(){return this._data.degree},knots:function(){return this._data.knots.slice(0)},controlPoints:function(){return De.dehomogenize1d(this._data.controlPoints)},weights:function(){return De.weight1d(this._data.controlPoints)},asNurbs:function(){return new q(this.degree(),this.knots(),De.homogenize1d(this.controlPoints(),this.weights()))},clone:function(){return new We(this._data)},domain:function(){return new Z(k.first(this._data.knots),k.last(this._data.knots))},transform:function(e){return new We(Fe.rationalCurveTransform(this._data,e))},transformAsync:function(e){return ke.dispatchMethod(Fe,"rationalCurveTransform",[this._data,e]).then((function(e){return new We(e)}))},point:function(e){return De.rationalCurvePoint(this._data,e)},pointAsync:function(e){return ke.dispatchMethod(De,"rationalCurvePoint",[this._data,e])},tangent:function(e){return De.rationalCurveTangent(this._data,e)},tangentAsync:function(e){return ke.dispatchMethod(De,"rationalCurveTangent",[this._data,e])},derivatives:function(e,t){return null==t&&(t=1),De.rationalCurveDerivatives(this._data,e,t)},derivativesAsync:function(e,t){return null==t&&(t=1),ke.dispatchMethod(De,"rationalCurveDerivatives",[this._data,e,t])},closestPoint:function(e){return Ae.rationalCurveClosestPoint(this._data,e)},closestPointAsync:function(e){return ke.dispatchMethod(Ae,"rationalCurveClosestPoint",[this._data,e])},closestParam:function(e){return Ae.rationalCurveClosestParam(this._data,e)},closestParamAsync:function(e){return ke.dispatchMethod(Ae,"rationalCurveClosestParam",[this._data,e])},length:function(){return Ae.rationalCurveArcLength(this._data)},lengthAsync:function(){return ke.dispatchMethod(Ae,"rationalCurveArcLength",[this._data])},lengthAtParam:function(e){return Ae.rationalCurveArcLength(this._data,e)},lengthAtParamAsync:function(){return ke.dispatchMethod(Ae,"rationalCurveArcLength",[this._data])},paramAtLength:function(e,t){return Ae.rationalCurveParamAtArcLength(this._data,e,t)},paramAtLengthAsync:function(e,t){return ke.dispatchMethod(Ae,"rationalCurveParamAtArcLength",[this._data,e,t])},divideByEqualArcLength:function(e){return Me.rationalCurveByEqualArcLength(this._data,e)},divideByEqualArcLengthAsync:function(e){return ke.dispatchMethod(Me,"rationalCurveByEqualArcLength",[this._data,e])},divideByArcLength:function(e){return Me.rationalCurveByArcLength(this._data,e)},divideByArcLengthAsync:function(e){return ke.dispatchMethod(Me,"rationalCurveByArcLength",[this._data,e])},split:function(e){return Me.curveSplit(this._data,e).map((function(e){return new We(e)}))},splitAsync:function(e){return ke.dispatchMethod(Me,"curveSplit",[this._data,e]).then((function(e){return e.map((function(e){return new We(e)}))}))},reverse:function(){return new We(Fe.curveReverse(this._data))},reverseAsync:function(){return ke.dispatchMethod(Fe,"curveReverse",[this._data]).then((function(e){return new We(e)}))},tessellate:function(e){return Le.rationalCurveAdaptiveSample(this._data,e,!1)},tessellateAsync:function(e){return ke.dispatchMethod(Le,"rationalCurveAdaptiveSample",[this._data,e,!1])},__class__:We});var He=t.geom.Arc=function(e,t,i,r,s,n){We.call(this,Ne.arc(e,t,i,r,s,n)),this._center=e,this._xaxis=t,this._yaxis=i,this._radius=r,this._minAngle=s,this._maxAngle=n};r["verb.geom.Arc"]=He,He.__name__=["verb","geom","Arc"],He.__super__=We,He.prototype=n(We.prototype,{center:function(){return this._center},xaxis:function(){return this._xaxis},yaxis:function(){return this._yaxis},radius:function(){return this._radius},minAngle:function(){return this._minAngle},maxAngle:function(){return this._maxAngle},__class__:He});var Xe=t.geom.BezierCurve=function(e,t){We.call(this,Ne.rationalBezierCurve(e,t))};r["verb.geom.BezierCurve"]=Xe,Xe.__name__=["verb","geom","BezierCurve"],Xe.__super__=We,Xe.prototype=n(We.prototype,{__class__:Xe});var qe=t.geom.Circle=function(e,t,i,r){He.call(this,e,t,i,r,0,2*Math.PI)};r["verb.geom.Circle"]=qe,qe.__name__=["verb","geom","Circle"],qe.__super__=He,qe.prototype=n(He.prototype,{__class__:qe});var Ye=function(){};r["verb.geom.ISurface"]=Ye,Ye.__name__=["verb","geom","ISurface"],Ye.__interfaces__=[Ce],Ye.prototype={__class__:Ye};var Ke=t.geom.NurbsSurface=function(e){this._data=Ie.isValidNurbsSurfaceData(e)};r["verb.geom.NurbsSurface"]=Ke,Ke.__name__=["verb","geom","NurbsSurface"],Ke.__interfaces__=[Ye],Ke.byKnotsControlPointsWeights=function(e,t,i,r,s,n){return new Ke(new Y(e,t,i,r,De.homogenize2d(s,n)))},Ke.byCorners=function(e,t,i,r){return new Ke(Ne.fourPointSurface(e,t,i,r))},Ke.byLoftingCurves=function(e,t){return new Ke(Ne.loftedSurface(function(t){for(var i=[],r=0;r{},12439:()=>{},87699:()=>{}},t={};function i(r){var s=t[r];if(void 0!==s)return s.exports;var n=t[r]={exports:{}};return e[r](n,n.exports,i),n.exports}i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};return(()=>{"use strict";i.r(r),i.d(r,{Runner:()=>mZ,fontsEnum:()=>aZ,getRunnerInstance:()=>_Z});var e={};i.r(e),i.d(e,{AbstractActionManager:()=>G.G,AbstractAssetContainer:()=>Qt,AbstractAssetTask:()=>$A,AbstractEngine:()=>Ot.$,AbstractMesh:()=>Nt,AcquireNativeObjectAsync:()=>dh,Action:()=>q,ActionEvent:()=>Y.X,ActionManager:()=>ue,AddAnimationExtensions:()=>me.SM,AddBlock:()=>KT,AddIndividualParser:()=>di,AddParser:()=>ci,AddRayExtensions:()=>Ki,AddressMode:()=>Dh,AdvancedTimer:()=>bd,Aggregations:()=>ZE,AggregatorBlock:()=>PA,AlignBlock:()=>zP,AlphaState:()=>aL.i,AmmoJSPlugin:()=>Yx,AnaglyphArcRotateCamera:()=>xs,AnaglyphFreeCamera:()=>bs,AnaglyphGamepadCamera:()=>Ss,AnaglyphPostProcess:()=>gs,AnaglyphUniversalCamera:()=>Ts,Analyser:()=>ti,AndOrNotEvaluator:()=>jA.Z,Angle:()=>hc.uM,Animatable:()=>me.rT,AnimatedInputBlockTypes:()=>Bg,Animation:()=>pe.X5,AnimationAssetTask:()=>eR,AnimationEvent:()=>we,AnimationGroup:()=>Fe.AnimationGroup,AnimationGroupMask:()=>ke,AnimationGroupMaskMode:()=>Le,AnimationKeyInterpolation:()=>Ne,AnimationPropertiesOverride:()=>ge,AnimationRange:()=>Be.K,AnisotropyBlock:()=>NC,ApplyLut:()=>kb.Kq,ApplyPostProcess:()=>Ac.Qs,Arc2:()=>hc.Xy,ArcFollowCamera:()=>ls,ArcRotateCamera:()=>is,ArcRotateCameraGamepadInput:()=>Er,ArcRotateCameraInputsManager:()=>Or,ArcRotateCameraKeyboardMoveInput:()=>Rr,ArcRotateCameraMouseWheelInput:()=>Ir,ArcRotateCameraPointersInput:()=>Mr,ArcRotateCameraVRDeviceOrientationInput:()=>Dr,ArcTan2Block:()=>gC,AssetContainer:()=>ei,AssetTaskState:()=>NA,AssetsManager:()=>lR,AssetsProgressEvent:()=>QA,AsyncLock:()=>jI,AsyncLoop:()=>Ue.LV,AttachToBoxBehavior:()=>Ii,AudioEngine:()=>ri,AudioSceneComponent:()=>_i,AutoLayoutMode:()=>Wh,AutoReleaseWorkerPool:()=>jy.h,AutoRotationBehavior:()=>Ei,AxesViewer:()=>Wo,Axis:()=>hc._0,AxisDragGizmo:()=>zo,AxisScaleGizmo:()=>J_,BRDFTextureTools:()=>Pm,BabylonFileLoaderConfiguration:()=>tb,BackEase:()=>Se,BackgroundMaterial:()=>xm,BakedVertexAnimationManager:()=>gi,BallAndSocketConstraint:()=>ZM,BaseCameraMouseWheelInput:()=>vr,BaseCameraPointersInput:()=>xr,BaseError:()=>nt.Cf,BaseParticleSystem:()=>nv,BaseSixDofDragBehavior:()=>tr,BaseTexture:()=>js.t,BasisFileInfo:()=>hR.$e,BasisTools:()=>hR.ED,BasisToolsOptions:()=>hR.Sl,BasisTranscodeConfiguration:()=>hR.SV,BezierCurve:()=>hc.vr,BezierCurveEase:()=>Oe,BiPlanarBlock:()=>ZC,BinaryFileAssetTask:()=>iR,BindBonesParameters:()=>Bt.f$,BindFogParameters:()=>Bt.Yy,BindLight:()=>Bt.Kd,BindLightProperties:()=>Bt.L0,BindLights:()=>Bt.RL,BindLogDepth:()=>Bt.DL,BindMorphTargetParameters:()=>Bt.nR,BindSceneUniformBuffer:()=>Bt._8,BindTextureMatrix:()=>Bt.mA,BlackAndWhitePostProcess:()=>PO,BlendFactor:()=>Kh,BlendOperation:()=>jh,BloomEffect:()=>MO,BloomMergePostProcess:()=>IO,BlurPostProcess:()=>_m,Bone:()=>Si.$,BoneAxesViewer:()=>Ho,BoneIKController:()=>dr,BoneLookController:()=>fr,BonesBlock:()=>gS,BooleanGeometryBlock:()=>aA,BooleanGeometryOperations:()=>$E,BounceEase:()=>Te,BouncingBehavior:()=>Pi,BoundingBlock:()=>oA,BoundingBox:()=>ht,BoundingBoxGizmo:()=>tm,BoundingBoxRenderer:()=>yw,BoundingInfo:()=>_t,BoundingInfoHelper:()=>Ao,BoundingSphere:()=>ct,BoxBlock:()=>sP,BoxBuilder:()=>jo,BoxParticleEmitter:()=>sI,Buffer:()=>st.h,BufferBindingType:()=>Bh,BufferMapState:()=>yh,BufferUsage:()=>Eh,CSG:()=>nE,CSG2:()=>VE,Camera:()=>rt,CameraGizmo:()=>pm,CameraInputTypes:()=>br,CameraInputsManager:()=>Sr,CannonJSPlugin:()=>Xx,CanvasAlphaMode:()=>nc,CanvasToneMappingMode:()=>oc,CapsuleBlock:()=>pP,CapsuleBuilder:()=>aa,CascadedShadowGenerator:()=>Cx,ChromaticAberrationPostProcess:()=>OO,CircleEase:()=>be,CircleOfConfusionPostProcess:()=>DO,ClampBlock:()=>$T,CleanGeometryBlock:()=>IP,ClearCoatBlock:()=>LC,ClipPlanesBlock:()=>gT,ClipboardEventTypes:()=>yu,ClipboardInfo:()=>Eu,CloudBlock:()=>KC,CloudPoint:()=>mM,Collider:()=>_o,Color3:()=>hc.v9,Color3Gradient:()=>QR,Color4:()=>hc.ov,ColorConverterBlock:()=>ry,ColorCorrectionPostProcess:()=>wO,ColorCurves:()=>mb.Q,ColorGradient:()=>$R,ColorGradingTexture:()=>Mb,ColorMergerBlock:()=>tC,ColorSplitterBlock:()=>ov,ColorWrite:()=>Yh,CombineAction:()=>oe,CompareFunction:()=>Fh,CompatibilityOptions:()=>Tt.p9,CompilationMessageType:()=>Gh,CompleteGreasedLineColorTable:()=>wE,CompleteGreasedLineWidthTable:()=>DE,CompressionCodes:()=>zb.he,ComputeBindingType:()=>kl,ComputeEffect:()=>Eo,ComputeNormalsBlock:()=>OP,ComputePassTimestampLocation:()=>ec,ComputeShader:()=>Po.H,ComputeShaderBoundingHelper:()=>Io.ComputeShaderBoundingHelper,ComputeShaderParticleSystem:()=>aM,Condition:()=>K,ConditionBlock:()=>yP,ConditionBlockTests:()=>qE,ConditionalBlock:()=>YC,ConditionalBlockConditions:()=>HC,ConeDirectedParticleEmitter:()=>vI,ConeParticleEmitter:()=>gI,Constants:()=>Il,ContainerAssetTask:()=>ZA,ConversionMode:()=>zp,ConvolutionPostProcess:()=>NO,Coordinate:()=>hc.xp,CopyFloatData:()=>Ct,CopyTextureToTexture:()=>Kp,CopyTools:()=>LI.D8,CreateBox:()=>Ko,CreateBoxVertexData:()=>qo,CreateCapsule:()=>oa,CreateCapsuleVertexData:()=>na,CreateCylinder:()=>No,CreateCylinderVertexData:()=>wo,CreateDashedLines:()=>Ia,CreateDashedLinesVertexData:()=>Pa,CreateDecal:()=>ol,CreateDecoderAsync:()=>Wb.d,CreateDisc:()=>da,CreateDiscVertexData:()=>ua,CreateEnvTextureAsync:()=>Wl.Hx,CreateGeodesic:()=>dl,CreateGoldberg:()=>_l,CreateGoldbergVertexData:()=>pl,CreateGreasedLine:()=>ME,CreateGreasedLineMaterial:()=>IE,CreateGround:()=>io,CreateGroundFromHeightMap:()=>so,CreateGroundFromHeightMapVertexData:()=>to,CreateGroundVertexData:()=>Jn,CreateHemisphere:()=>cm,CreateIcoSphere:()=>Qa,CreateIcoSphereVertexData:()=>$a,CreateImageBitmapFromSource:()=>Js,CreateImageDataArrayBufferViews:()=>Wl.$h,CreateLathe:()=>Wa,CreateLineSystem:()=>Aa,CreateLineSystemVertexData:()=>Ea,CreateLines:()=>Ra,CreatePickingRay:()=>Ni,CreatePickingRayInCameraSpace:()=>Li,CreatePickingRayInCameraSpaceToRef:()=>Bi,CreatePickingRayToRef:()=>Fi,CreatePlane:()=>Qi,CreatePlaneVertexData:()=>$i,CreatePolygon:()=>La,CreatePolygonVertexData:()=>Fa,CreatePolyhedron:()=>Ka,CreatePolyhedronVertexData:()=>Ya,CreateResizedCopy:()=>Ac.EE,CreateRibbon:()=>ha,CreateRibbonVertexData:()=>la,CreateScreenshot:()=>zR,CreateScreenshotAsync:()=>WR,CreateScreenshotUsingRenderTarget:()=>XR,CreateScreenshotUsingRenderTargetAsync:()=>qR,CreateScreenshotWithResizeAsync:()=>HR,CreateSegmentedBoxVertexData:()=>Yo,CreateSphere:()=>Qo,CreateSphereVertexData:()=>$o,CreateText:()=>xl,CreateTextShapePaths:()=>vl,CreateTiledBox:()=>va,CreateTiledBoxVertexData:()=>ga,CreateTiledGround:()=>ro,CreateTiledGroundVertexData:()=>eo,CreateTiledPlane:()=>_a,CreateTiledPlaneVertexData:()=>pa,CreateTorus:()=>ao,CreateTorusKnot:()=>Sa,CreateTorusKnotVertexData:()=>ba,CreateTorusVertexData:()=>oo,CreateTube:()=>Xa,CrossBlock:()=>QT,CubeMapToSphericalPolynomialTools:()=>Lx.d,CubeTexture:()=>gm,CubeTextureAssetTask:()=>nR,CubicEase:()=>Ce,CullMode:()=>qh,CurrentScreenBlock:()=>jg,Curve3:()=>hc.jj,CurveBlock:()=>iy,CurveBlockTypes:()=>qC,CustomBlock:()=>ZT,CustomOptimization:()=>CR,CustomParticleEmitter:()=>cI,CustomProceduralTexture:()=>Kb,CylinderBlock:()=>fP,CylinderBuilder:()=>Fo,CylinderDirectedParticleEmitter:()=>mI,CylinderParticleEmitter:()=>_I,DDSTools:()=>cR.DDSTools,DataBuffer:()=>pr.n,DataReader:()=>tI,DataStorage:()=>iI,Database:()=>sM,DebugBlock:()=>ZP,DebugLayer:()=>Xo,DebugLayerTab:()=>Uo,DecalBuilder:()=>al,DecalMapConfiguration:()=>my,DecalMapDefines:()=>_y,Decode:()=>bi.Tq,DecodeBase64ToBinary:()=>bi.yS,DecodeBase64ToString:()=>bi.AV,DecodeBase64UrlToBinary:()=>$m.rz,DecodeBase64UrlToString:()=>$m.dy,DecodeFloat32:()=>zb.Sn,DecodeRunLength:()=>Ub._,DeepCopier:()=>ce.r,DefaultCollisionCoordinator:()=>mo,DefaultKTX2DecoderOptions:()=>MI.$,DefaultLoadingScreen:()=>Nx,DefaultRenderingPipeline:()=>iD,Deferred:()=>uR,DepthCullingState:()=>Gc.N,DepthOfFieldBlurPostProcess:()=>FO,DepthOfFieldEffect:()=>BO,DepthOfFieldEffectBlurLevel:()=>DM,DepthOfFieldMergePostProcess:()=>LO,DepthPeelingRenderer:()=>Aw,DepthPeelingSceneComponent:()=>Rw,DepthReducer:()=>gx,DepthRenderer:()=>px,DepthRendererSceneComponent:()=>Ew,DepthSortedParticle:()=>fM,DerivativeBlock:()=>VS,DesaturateBlock:()=>DC,DetailMapConfiguration:()=>Nn,DeviceInputEventType:()=>gr.b,DeviceLostReason:()=>ac,DeviceOrientationCamera:()=>rs,DeviceSource:()=>Al.c,DeviceSourceManager:()=>Rl.Z,DeviceType:()=>Pl.bq,DirectionalLight:()=>hm,DirectionalLightFrustumViewer:()=>El,DiscBlock:()=>_P,DiscBuilder:()=>fa,DiscardBlock:()=>LS,DisplayPassPostProcess:()=>VO,DistanceBlock:()=>dC,DistanceConstraint:()=>JM,DistanceJoint:()=>ea,DivideBlock:()=>sC,DoNothingAction:()=>ne,DomManagement:()=>ii.Az,DotBlock:()=>JT,DracoCompression:()=>Zy,DragOperation:()=>em,DrawWrapper:()=>gt.E,DualSenseInput:()=>Pl.pI,DualShockButton:()=>Kr,DualShockDpad:()=>jr,DualShockInput:()=>Pl.h8,DualShockPad:()=>cs,DumpTools:()=>UR.DumpTools,DynamicFloat32Array:()=>kI,DynamicTexture:()=>Gn,EXROutputType:()=>Gb.V,EasingFunction:()=>xe,EdgesRenderer:()=>Mw,Effect:()=>Cl.M,EffectFallbacks:()=>Tn,EffectLayer:()=>Lv,EffectLayerSceneComponent:()=>Bv,EffectRenderer:()=>Yp.J,EffectWrapper:()=>Yp.$,ElasticEase:()=>ye,ElbowBlock:()=>$C,EncodeArrayBufferToBase64:()=>bi.EL,EndsWith:()=>bi.jq,Engine:()=>an,EngineFactory:()=>Cu,EngineFormat:()=>rS.GQ,EngineInstrumentation:()=>Nv,EngineStore:()=>he.q,EngineView:()=>Fl,EnvironmentHelper:()=>bm,EnvironmentTextureTools:()=>Wl.qY,Epsilon:()=>hc.bH,EquiRectangularCubeTexture:()=>Db,EquiRectangularCubeTextureAssetTask:()=>aR,ErrorCodes:()=>nt.tG,ErrorFilter:()=>lc,EventConstants:()=>gr.s,EventState:()=>z.qO,ExecuteCodeAction:()=>ae,ExitFullscreen:()=>rn,ExitPointerlock:()=>nn,ExponentialEase:()=>Ee,ExrLoaderGlobalConfiguration:()=>Gb.u,ExternalTexture:()=>Wc,ExtractHighlightsPostProcess:()=>RO,ExtrudePolygon:()=>Ba,ExtrudeShape:()=>ka,ExtrudeShapeCustom:()=>Ua,FactorGradient:()=>ZR,FadeInOutBehavior:()=>Mi,FeatureName:()=>Ch,FileTools:()=>$m.wS,FileToolsOptions:()=>$m.eC,FilesInput:()=>pR,FilesInputStore:()=>fR.T,FilterMode:()=>wh,FilterPostProcess:()=>kO,FixFlippedFaces:()=>mt.Y4,FlowGraph:()=>sd,FlowGraphAbsBlock:()=>pf,FlowGraphAcosBlock:()=>Xf,FlowGraphAcoshBlock:()=>Zf,FlowGraphAddBlock:()=>rf,FlowGraphAsinBlock:()=>Hf,FlowGraphAsinhBlock:()=>Qf,FlowGraphAtan2Block:()=>Yf,FlowGraphAtanBlock:()=>qf,FlowGraphAtanhBlock:()=>Jf,FlowGraphBitwiseAndBlock:()=>gp,FlowGraphBitwiseLeftShiftBlock:()=>bp,FlowGraphBitwiseNotBlock:()=>mp,FlowGraphBitwiseOrBlock:()=>vp,FlowGraphBitwiseRightShiftBlock:()=>Sp,FlowGraphBitwiseXorBlock:()=>xp,FlowGraphBlock:()=>ju,FlowGraphBranchBlock:()=>pd,FlowGraphCeilBlock:()=>vf,FlowGraphClampBlock:()=>Af,FlowGraphConditionalDataBlock:()=>wd,FlowGraphConnection:()=>Ru,FlowGraphConnectionType:()=>Pu,FlowGraphConsoleLogBlock:()=>ld,FlowGraphConstantBlock:()=>Ld,FlowGraphContext:()=>ed,FlowGraphContextLogger:()=>od,FlowGraphCoordinateTransformBlock:()=>Fd,FlowGraphCoordinator:()=>nd,FlowGraphCosBlock:()=>zf,FlowGraphCoshBlock:()=>jf,FlowGraphCountLeadingZerosBlock:()=>Tp,FlowGraphCountOneBitsBlock:()=>yp,FlowGraphCountTrailingZerosBlock:()=>Cp,FlowGraphCounterBlock:()=>Ed,FlowGraphCrossBlock:()=>hp,FlowGraphCubeRootBlock:()=>np,FlowGraphDataConnection:()=>Hu,FlowGraphDebounceBlock:()=>Ad,FlowGraphDegToRadBlock:()=>kf,FlowGraphDeterminantBlock:()=>fp,FlowGraphDivideBlock:()=>of,FlowGraphDoNBlock:()=>_d,FlowGraphDotBlock:()=>lf,FlowGraphEBlock:()=>hf,FlowGraphEqBlock:()=>Of,FlowGraphEventBlock:()=>Ju,FlowGraphExecutionBlock:()=>Qu,FlowGraphExpBlock:()=>ep,FlowGraphFlipFlopBlock:()=>Rd,FlowGraphFloorBlock:()=>gf,FlowGraphForLoopBlock:()=>md,FlowGraphFractBlock:()=>xf,FlowGraphGetPropertyBlock:()=>Bd,FlowGraphGetVariableBlock:()=>Nd,FlowGraphGreaterThanBlock:()=>Ff,FlowGraphGreaterThanOrEqualBlock:()=>Lf,FlowGraphInfBlock:()=>uf,FlowGraphInterpolateBlock:()=>Mf,FlowGraphInvertMatrixBlock:()=>pp,FlowGraphIsInfBlock:()=>Vf,FlowGraphIsNanBlock:()=>Bf,FlowGraphLengthBlock:()=>ap,FlowGraphLessThanBlock:()=>wf,FlowGraphLessThanOrEqualBlock:()=>Nf,FlowGraphLog10Block:()=>rp,FlowGraphLog2Block:()=>ip,FlowGraphLogBlock:()=>tp,FlowGraphLogicAndBlock:()=>Yd,FlowGraphLogicNotBlock:()=>jd,FlowGraphLogicOrBlock:()=>Kd,FlowGraphMatMulBlock:()=>_p,FlowGraphMaxBlock:()=>yf,FlowGraphMeshPickEventBlock:()=>id,FlowGraphMinBlock:()=>Cf,FlowGraphMultiGateBlock:()=>Td,FlowGraphMultiplyBlock:()=>nf,FlowGraphNaNBlock:()=>df,FlowGraphNegBlock:()=>bf,FlowGraphNormalizeBlock:()=>lp,FlowGraphPauseAnimationBlock:()=>Dd,FlowGraphPiBlock:()=>cf,FlowGraphPlayAnimationBlock:()=>Md,FlowGraphPowBlock:()=>op,FlowGraphRadToDegBlock:()=>Uf,FlowGraphRandomBlock:()=>af,FlowGraphReceiveCustomEventBlock:()=>Pp,FlowGraphRemainderBlock:()=>Tf,FlowGraphRotate2DBlock:()=>cp,FlowGraphRotate3DBlock:()=>up,FlowGraphSaturateBlock:()=>If,FlowGraphSceneReadyEventBlock:()=>Ep,FlowGraphSceneTickEventBlock:()=>Ap,FlowGraphSendCustomEventBlock:()=>fd,FlowGraphSequenceBlock:()=>Id,FlowGraphSetPropertyBlock:()=>dd,FlowGraphSetVariableBlock:()=>hd,FlowGraphSignBlock:()=>_f,FlowGraphSignalConnection:()=>$u,FlowGraphSinBlock:()=>Gf,FlowGraphSinhBlock:()=>Kf,FlowGraphSqrtBlock:()=>sp,FlowGraphState:()=>rd,FlowGraphStopAnimationBlock:()=>Od,FlowGraphSubtractBlock:()=>sf,FlowGraphSwitchBlock:()=>Cd,FlowGraphTanBlock:()=>Wf,FlowGraphTanhBlock:()=>$f,FlowGraphThrottleBlock:()=>gd,FlowGraphTimerBlock:()=>Sd,FlowGraphTransposeBlock:()=>dp,FlowGraphTruncBlock:()=>mf,FlowGraphWaitAllBlock:()=>yd,FlowGraphWhileLoopBlock:()=>Pd,FluidRenderer:()=>sN,FluidRendererSceneComponent:()=>rN,FluidRenderingDebug:()=>Yw,FluidRenderingObject:()=>jw,FluidRenderingObjectCustomParticles:()=>Jw,FluidRenderingObjectParticleSystem:()=>$w,FluidRenderingTargetRenderer:()=>Zw,FlyCamera:()=>ns,FlyCameraInputsManager:()=>ss,FlyCameraKeyboardInput:()=>wr,FlyCameraMouseInput:()=>Nr,FogBlock:()=>cT,FollowBehavior:()=>lr,FollowCamera:()=>as,FollowCameraInputsManager:()=>os,FollowCameraKeyboardMoveInput:()=>Fr,FollowCameraMouseWheelInput:()=>Lr,FollowCameraPointersInput:()=>Br,FragCoordBlock:()=>kS,FragDepthBlock:()=>HS,FragmentOutputBlock:()=>Hg,FragmentOutputBlockColorSpace:()=>Fg,FrameGraph:()=>e_,FrameGraphBlackAndWhiteTask:()=>c_,FrameGraphBloomTask:()=>x_,FrameGraphBlurTask:()=>v_,FrameGraphCircleOfConfusionTask:()=>C_,FrameGraphClearTextureTask:()=>r_,FrameGraphContext:()=>jp,FrameGraphCopyToBackbufferColorTask:()=>Up,FrameGraphCopyToTextureTask:()=>K_,FrameGraphCullObjectsTask:()=>w_,FrameGraphDepthOfFieldTask:()=>M_,FrameGraphExtractHighlightsTask:()=>g_,FrameGraphGeometryRendererTask:()=>B_,FrameGraphObjectList:()=>Z_,FrameGraphObjectRendererTask:()=>k_,FrameGraphPass:()=>Lp,FrameGraphPostProcessTask:()=>h_,FrameGraphRenderContext:()=>$p,FrameGraphRenderPass:()=>Vp,FrameGraphTAAObjectRendererTask:()=>H_,FrameGraphTask:()=>kp,FrameGraphTextureManager:()=>Jp,FramingBehavior:()=>Ai,FreeCamera:()=>es,FreeCameraDeviceOrientationInput:()=>Wr,FreeCameraGamepadInput:()=>Hr,FreeCameraInputsManager:()=>zr,FreeCameraKeyboardMoveInput:()=>Vr,FreeCameraMouseInput:()=>kr,FreeCameraMouseWheelInput:()=>Ur,FreeCameraTouchInput:()=>Gr,FreeCameraVirtualJoystickInput:()=>Zr,FresnelBlock:()=>hC,FresnelParameters:()=>gb,FromHalfFloat:()=>Ac.SX,FrontFace:()=>Xh,FrontFacingBlock:()=>BS,Frustum:()=>hc.PP,FxaaPostProcess:()=>kR,GIRSM:()=>MN,GIRSMManager:()=>ON,GIRSMRenderPluginMaterial:()=>wN,GPUParticleSystem:()=>lM,GPUPicker:()=>bo,GUID:()=>Au.S,Gamepad:()=>Cr,GamepadCamera:()=>ps,GamepadManager:()=>us,GamepadSystemSceneComponent:()=>ds,GaussianBlock:()=>dS,GaussianSplattingBlock:()=>uS,GaussianSplattingMaterial:()=>pS,GaussianSplattingMesh:()=>wA,GenerateBase64StringFromPixelData:()=>LI.c9,GenerateBase64StringFromTexture:()=>LI.lP,GenerateBase64StringFromTextureAsync:()=>LI.nh,GenericPad:()=>yr,GeodesicData:()=>ul,Geometry:()=>yt,GeometryArcTan2Block:()=>lA,GeometryBufferRenderer:()=>qO,GeometryBufferRendererSceneComponent:()=>KO,GeometryClampBlock:()=>_A,GeometryCollectionBlock:()=>RP,GeometryCrossBlock:()=>mA,GeometryCurveBlock:()=>gA,GeometryCurveBlockTypes:()=>QE,GeometryDesaturateBlock:()=>vA,GeometryDistanceBlock:()=>SA,GeometryDotBlock:()=>TA,GeometryElbowBlock:()=>MP,GeometryInfoBlock:()=>JP,GeometryInputBlock:()=>rP,GeometryInterceptorBlock:()=>EA,GeometryLengthBlock:()=>CA,GeometryLerpBlock:()=>hA,GeometryModBlock:()=>fA,GeometryNLerpBlock:()=>cA,GeometryOptimizeBlock:()=>oP,GeometryOutputBlock:()=>tP,GeometryPosterizeBlock:()=>xA,GeometryPowBlock:()=>pA,GeometryRenderingTextureClearType:()=>Fn,GeometryReplaceColorBlock:()=>bA,GeometryRotate2dBlock:()=>yA,GeometrySmoothStepBlock:()=>dA,GeometryStepBlock:()=>uA,GeometryTextureBlock:()=>sA,GeometryTextureFetchBlock:()=>nA,GeometryTransformBlock:()=>BP,GeometryTrigonometryBlock:()=>LP,GeometryTrigonometryBlockOperations:()=>KE,GetClass:()=>X.n9,GetClassName:()=>X.Uu,GetDOMTextContent:()=>ii.Zl,GetEnvInfo:()=>Wl.cU,GetEnvironmentBRDFTexture:()=>Em,GetExrHeader:()=>Hb.V,GetFogState:()=>Bt.qL,GetFontOffset:()=>Zs,GetForwardRay:()=>qi,GetForwardRayToRef:()=>Yi,GetHotSpotToRef:()=>Ky,GetIndividualParser:()=>fi,GetInternalFormatFromBasisFormat:()=>hR.yT,GetParser:()=>ui,GetPointsCount:()=>OE,GetTGAHeader:()=>BR.O_,GetTextureDataAsync:()=>Ac.Oz,GetTransformedPosition:()=>Yy,Gizmo:()=>Go,GizmoAnchorPoint:()=>Vo,GizmoCoordinatesMode:()=>ko,GizmoManager:()=>am,GlowLayer:()=>Vv,GoldbergMesh:()=>fl,GradientBlock:()=>yC,GradientBlockColorStep:()=>CC,GradientHelper:()=>JR,GrainPostProcess:()=>UO,GreasedLineBaseMesh:()=>PE,GreasedLineMaterialDefaults:()=>yy,GreasedLineMesh:()=>AE,GreasedLineMeshColorDistribution:()=>pE,GreasedLineMeshColorDistributionType:()=>Oy,GreasedLineMeshColorMode:()=>My,GreasedLineMeshMaterialType:()=>Iy,GreasedLineMeshWidthDistribution:()=>_E,GreasedLinePluginMaterial:()=>Ay,GreasedLineRibbonAutoDirectionMode:()=>fE,GreasedLineRibbonFacesMode:()=>dE,GreasedLineRibbonMesh:()=>RE,GreasedLineRibbonPointsMode:()=>uE,GreasedLineSimpleMaterial:()=>Ry,GreasedLineTools:()=>Ey,GridBlock:()=>uP,GroundBuilder:()=>no,GroundMesh:()=>Zn,HDRCubeTexture:()=>Vx,HDRCubeTextureAssetTask:()=>oR,HDRFiltering:()=>Bx,HDRTools:()=>Fx.I9,Halton2DSequence:()=>z_,HandConstraintBehavior:()=>ur,HandConstraintOrientation:()=>nr,HandConstraintVisibility:()=>or,HandConstraintZone:()=>sr,HandPart:()=>gv,HandleFallbacksForShadows:()=>Bt.c4,HardwareScalingOptimization:()=>xR,HavokPlugin:()=>fO,HeightToNormalBlock:()=>WS,HemisphereBuilder:()=>um,HemisphericLight:()=>Lo,HemisphericParticleEmitter:()=>dI,HighlightLayer:()=>Uv,HighlightsPostProcess:()=>GO,Hinge2Joint:()=>ra,HingeConstraint:()=>eO,HingeJoint:()=>ia,HtmlElementTexture:()=>wb,HufUncompress:()=>kb.ZR,IWebXRControllerPhysicsOptions:()=>_L,IblShadowsRenderPipeline:()=>kw,IcoSphereBlock:()=>hP,IcoSphereBuilder:()=>Za,ImageAssetTask:()=>rR,ImageProcessingBlock:()=>wS,ImageProcessingConfiguration:()=>gn.p,ImageProcessingPostProcess:()=>zO,ImageSourceBlock:()=>dT,IncrementValueAction:()=>ie,IndexFormat:()=>Qh,InitializeCSG2Async:()=>UE,InputBlock:()=>Kg,InspectableType:()=>jR,InstancedLinesMesh:()=>ya,InstancedMesh:()=>Kt,InstancesBlock:()=>vS,InstantiateBlock:()=>KP,InstantiateLinearBlock:()=>jP,InstantiateOnFacesBlock:()=>XP,InstantiateOnVerticesBlock:()=>HP,InstantiateOnVolumeBlock:()=>qP,InstantiateRadialBlock:()=>$P,InstantiatedEntries:()=>Jt,IntFloatConverterBlock:()=>QP,InterleaveScalar:()=>zb.KA,InternalTexture:()=>Fs.h,InternalTextureSource:()=>Fs.G,InterpolateValueAction:()=>_e,IntersectionInfo:()=>ot,IsBase64DataUrl:()=>$m.f2,IsCSG2Ready:()=>kE,IsDocumentAvailable:()=>ii.Nf,IsFileURL:()=>$m.my,IsNavigatorAvailable:()=>ii.XD,IsWindowObjectExist:()=>ii.BA,IsWrapper:()=>Ol.E,JoystickAxis:()=>Xr,KeepAssets:()=>Zt,KeyboardEventTypes:()=>Ar.TB,KeyboardInfo:()=>Ar.W0,KeyboardInfoPre:()=>Ar.Bu,KhronosTextureContainer:()=>_R.H,KhronosTextureContainer2:()=>MI.Z,LatheBuilder:()=>Ha,Lattice:()=>yE,LatticeBlock:()=>FP,LatticePluginMaterial:()=>EE,Layer:()=>zv,LayerSceneComponent:()=>Gv,LengthBlock:()=>fC,LensFlare:()=>rx,LensFlareSystem:()=>sx,LensFlareSystemSceneComponent:()=>nx,LensFlaresOptimization:()=>TR,LensRenderingPipeline:()=>sD,LerpBlock:()=>rC,Light:()=>$t,LightBlock:()=>uT,LightGizmo:()=>fm,LightInformationBlock:()=>bS,LineEdgesRenderer:()=>Ow,LinesBuilder:()=>Ma,LinesMesh:()=>Ca,LoadFile:()=>$m.zU,LoadFileError:()=>$m.hX,LoadImage:()=>$m.W$,LoadImageConfiguration:()=>$m.qc,LoadOp:()=>ic,LoadTextureFromTranscodeResult:()=>hR.aB,LockConstraint:()=>iO,Logger:()=>Z.V,LoopBlock:()=>sy,MapMode:()=>Ph,MapRangeBlock:()=>CP,MappingBlock:()=>eA,MappingTypes:()=>jE,Material:()=>Vt,MaterialAnisotropicDefines:()=>wm,MaterialClearCoatDefines:()=>Im,MaterialDefines:()=>xn,MaterialDetailMapDefines:()=>wn,MaterialFlags:()=>Sn,MaterialGreasedLineDefines:()=>Py,MaterialHelper:()=>vb,MaterialHelperGeometryRendering:()=>Bn,MaterialIridescenceDefines:()=>Om,MaterialPluginBase:()=>Dn,MaterialPluginEvent:()=>cy,MaterialPluginManager:()=>En,MaterialSheenDefines:()=>Fm,MaterialSubSurfaceDefines:()=>Bm,MathBlock:()=>TP,MathBlockOperations:()=>XE,Matrix:()=>hc.uq,MatrixBuilderBlock:()=>WC,MatrixComposeBlock:()=>tA,MatrixDeterminantBlock:()=>JC,MatrixTransposeBlock:()=>ey,MaxBlock:()=>cC,MergeGeometryBlock:()=>AP,MergeMeshesOptimization:()=>PR,Mesh:()=>Yt,MeshAssetTask:()=>JA,MeshAttributeExistsBlock:()=>ty,MeshAttributeExistsBlockTypes:()=>XC,MeshBlock:()=>lP,MeshBuilder:()=>bl,MeshDebugMode:()=>wy,MeshDebugPluginMaterial:()=>Fy,MeshExploder:()=>dR,MeshLODLevel:()=>Gt,MeshParticleEmitter:()=>hI,MeshUVSpaceRenderer:()=>oE,MeshoptCompression:()=>Jy,MinBlock:()=>uC,MinMaxReducer:()=>mx,MipmapFilterMode:()=>Nh,MirrorTexture:()=>mm,ModBlock:()=>zC,ModelShape:()=>dM,MorphTarget:()=>kx,MorphTargetManager:()=>Gx,MorphTargetsBlock:()=>xS,MotionBlurPostProcess:()=>jO,MotorEnabledJoint:()=>ta,MultiMaterial:()=>kt,MultiObserver:()=>mR,MultiPick:()=>Hi,MultiPickWithRay:()=>Xi,MultiPointerScaleBehavior:()=>er,MultiRenderTarget:()=>Xb,MultiplyBlock:()=>iv,NLerpBlock:()=>EC,NativeDataStream:()=>zl,NativeEngine:()=>gh,NativePointerInput:()=>Pl.Ze,NativeXRFrame:()=>ZL,NativeXRLayerRenderTargetTextureProvider:()=>jn,NativeXRLayerWrapper:()=>Kn,NativeXRRenderTarget:()=>$n,NegateBlock:()=>pC,Node:()=>Ze.b,NodeGeometry:()=>nP,NodeGeometryBlock:()=>eP,NodeGeometryBlockConnectionPointTypes:()=>GE,NodeGeometryBuildState:()=>iP,NodeGeometryConnectionPoint:()=>JE,NodeGeometryConnectionPointCompatibilityStates:()=>zE,NodeGeometryConnectionPointDirection:()=>WE,NodeGeometryContextualSources:()=>HE,NodeMaterial:()=>pv,NodeMaterialBlock:()=>Gg,NodeMaterialBlockConnectionPointMode:()=>iS,NodeMaterialBlockConnectionPointTypes:()=>Og,NodeMaterialBlockTargets:()=>Dg,NodeMaterialConnectionPoint:()=>Ug,NodeMaterialConnectionPointCompatibilityStates:()=>wg,NodeMaterialConnectionPointCustomObject:()=>cS,NodeMaterialConnectionPointDirection:()=>Ng,NodeMaterialDefines:()=>fv,NodeMaterialModes:()=>rv,NodeMaterialOptimizer:()=>dy,NodeMaterialSystemValues:()=>Lg,NodeMaterialTeleportInBlock:()=>qT,NodeMaterialTeleportOutBlock:()=>YT,NodeRenderGraph:()=>o_,NodeRenderGraphBlackAndWhitePostProcessBlock:()=>u_,NodeRenderGraphBlock:()=>wp,NodeRenderGraphBlockConnectionPointTypes:()=>Rp,NodeRenderGraphBloomPostProcessBlock:()=>b_,NodeRenderGraphBlurPostProcessBlock:()=>S_,NodeRenderGraphBuildState:()=>n_,NodeRenderGraphCircleOfConfusionPostProcessBlock:()=>y_,NodeRenderGraphClearBlock:()=>s_,NodeRenderGraphConnectionPoint:()=>Dp,NodeRenderGraphConnectionPointCompatibilityStates:()=>Ip,NodeRenderGraphConnectionPointDirection:()=>Mp,NodeRenderGraphCopyTextureBlock:()=>j_,NodeRenderGraphCullObjectsBlock:()=>N_,NodeRenderGraphDepthOfFieldPostProcessBlock:()=>O_,NodeRenderGraphElbowBlock:()=>a_,NodeRenderGraphExtractHighlightsPostProcessBlock:()=>D_,NodeRenderGraphGenerateMipmapsBlock:()=>Q_,NodeRenderGraphGeometryRendererBlock:()=>V_,NodeRenderGraphInputBlock:()=>i_,NodeRenderGraphObjectRendererBlock:()=>G_,NodeRenderGraphOutputBlock:()=>Gp,NodeRenderGraphTAAObjectRendererBlock:()=>X_,NodeRenderGraphTeleportInBlock:()=>q_,NodeRenderGraphTeleportOutBlock:()=>Y_,NoiseBlock:()=>PP,NoiseProceduralTexture:()=>jb,NormalBlendBlock:()=>RC,NormalizeBlock:()=>eC,NormalizeVectorBlock:()=>wP,NullBlock:()=>mP,NullEngine:()=>wl,NullEngineOptions:()=>Dl,ObjectRenderer:()=>F_.P,Observable:()=>z.cP,Observer:()=>z.nu,OcclusionMaterial:()=>Sb,Octree:()=>Oo,OctreeBlock:()=>Mo,OctreeSceneComponent:()=>Do,OimoJSPlugin:()=>qx,OnAfterEnteringVRObservableEvent:()=>uo,OneMinusBlock:()=>aC,Orientation:()=>hc.t4,OutlineRenderer:()=>qw,PBRAnisotropicConfiguration:()=>Nm,PBRBaseMaterial:()=>Gm,PBRBaseSimpleMaterial:()=>Tb,PBRClearCoatConfiguration:()=>Mm,PBRIridescenceConfiguration:()=>Dm,PBRMaterial:()=>zm,PBRMaterialDefines:()=>Um,PBRMetallicRoughnessBlock:()=>GC,PBRMetallicRoughnessMaterial:()=>Cb,PBRSheenConfiguration:()=>Lm,PBRSpecularGlossinessMaterial:()=>yb,PBRSubSurfaceConfiguration:()=>Vm,PHI:()=>hc.a6,PadNumber:()=>bi.LW,PanoramaToCubeMapTools:()=>Ob.D,Parse:()=>pi,ParseFloat16:()=>zb.LD,ParseFloat32:()=>zb.Ff,ParseInt32:()=>zb.cL,ParseInt64:()=>zb.tB,ParseNullTerminatedString:()=>zb.T$,ParseUint16:()=>zb.Jn,ParseUint32:()=>zb.PX,ParseUint8:()=>zb._S,ParseUint8Array:()=>zb.fz,ParseValue:()=>zb.zX,Particle:()=>rI,ParticleBlendMultiplyBlock:()=>Zg,ParticleHelper:()=>cM,ParticleRampGradientBlock:()=>Qg,ParticleSystem:()=>AI,ParticleSystemSet:()=>hM,ParticleTextureBlock:()=>$g,ParticlesOptimization:()=>yR,PassCubePostProcess:()=>_s.s,PassPostProcess:()=>_s.v,Path2:()=>hc.Cu,Path3D:()=>hc.tO,PathCursor:()=>Ve,PerfCollectionStrategy:()=>qI,PerfCounter:()=>on.A,PerformanceConfigurator:()=>Ml.I,PerformanceMonitor:()=>Bs,PerformanceViewerCollector:()=>HI,PerturbNormalBlock:()=>FS,PhotoDome:()=>Tm,Physics6DoFConstraint:()=>QM,Physics6DoFLimit:()=>$M,PhysicsActivationControl:()=>RM,PhysicsAggregate:()=>nO,PhysicsBody:()=>VM,PhysicsConstraint:()=>jM,PhysicsConstraintAxis:()=>SM,PhysicsConstraintAxisLimitMode:()=>bM,PhysicsConstraintMotorType:()=>yM,PhysicsConstraintType:()=>TM,PhysicsEngine:()=>Hx,PhysicsEngineV2:()=>BM,PhysicsEventType:()=>EM,PhysicsHelper:()=>mO,PhysicsImpostor:()=>sa,PhysicsJoint:()=>Jo,PhysicsMaterialCombineMode:()=>IM,PhysicsMotionType:()=>PM,PhysicsPrestepType:()=>AM,PhysicsRadialExplosionEventOptions:()=>SO,PhysicsRadialImpulseFalloff:()=>MM,PhysicsRaycastResult:()=>Wx,PhysicsShape:()=>kM,PhysicsShapeBox:()=>WM,PhysicsShapeCapsule:()=>GM,PhysicsShapeContainer:()=>qM,PhysicsShapeConvexHull:()=>HM,PhysicsShapeCylinder:()=>zM,PhysicsShapeGroundMesh:()=>KM,PhysicsShapeHeightField:()=>YM,PhysicsShapeMesh:()=>XM,PhysicsShapeSphere:()=>UM,PhysicsShapeType:()=>CM,PhysicsUpdraftEventOptions:()=>TO,PhysicsUpdraftMode:()=>OM,PhysicsViewer:()=>Sl,PhysicsVortexEventOptions:()=>CO,Pick:()=>zi,PickWithBoundingInfo:()=>Gi,PickWithRay:()=>Wi,PickingCustomization:()=>Di,PickingInfo:()=>At.G,PipelineErrorReason:()=>zh,PivotTools:()=>ji,Plane:()=>hc.Zc,PlaneBlock:()=>aP,PlaneBuilder:()=>Zi,PlaneDragGizmo:()=>sm,PlaneRotationGizmo:()=>im,PlayAnimationAction:()=>re,PlaySoundAction:()=>de,PointColor:()=>vM,PointLight:()=>wx,PointParticleEmitter:()=>uI,PointerDragBehavior:()=>Ji,PointerEventTypes:()=>yi.Zp,PointerInfo:()=>yi.mx,PointerInfoBase:()=>yi.Vn,PointerInfoPre:()=>yi.tT,PointerInput:()=>Pl.ST,PointsCloudSystem:()=>xM,PointsGroup:()=>gM,Polar:()=>zy,Polygon:()=>wa,PolygonBuilder:()=>Va,PolygonMeshBuilder:()=>Na,PolyhedronBuilder:()=>ja,PolyhedronData:()=>cl,PositionGizmo:()=>nm,PositionNormalTextureVertex:()=>hc.k0,PositionNormalVertex:()=>hc.B5,PostProcess:()=>ms.w,PostProcessManager:()=>_x.X,PostProcessRenderEffect:()=>AO,PostProcessRenderPipeline:()=>JO,PostProcessRenderPipelineManager:()=>eD,PostProcessRenderPipelineManagerSceneComponent:()=>tD,PostProcessesOptimization:()=>SR,PosterizeBlock:()=>SC,PowBlock:()=>_C,PowerEase:()=>Pe,PowerPreference:()=>Th,PrePassOutputBlock:()=>qS,PrePassRenderer:()=>Gw,PrePassRendererSceneComponent:()=>zw,PrePassTextureBlock:()=>XT,PrecisionDate:()=>ai.j,PredicateCondition:()=>$,Predictor:()=>zb.XE,PrepareAttributesForBakedVertexAnimation:()=>Bt.J2,PrepareAttributesForBones:()=>Bt.ni,PrepareAttributesForInstances:()=>Bt.ER,PrepareAttributesForMorphTargets:()=>Bt.IF,PrepareAttributesForMorphTargetsInfluencers:()=>Bt.MF,PrepareDefinesForAttributes:()=>Bt.qB,PrepareDefinesForBakedVertexAnimation:()=>Bt.wu,PrepareDefinesForBones:()=>Bt.IC,PrepareDefinesForCamera:()=>Bt.Y7,PrepareDefinesForFrameBoundValues:()=>Bt.OR,PrepareDefinesForLight:()=>Bt.lo,PrepareDefinesForLights:()=>Bt.az,PrepareDefinesForMergedUV:()=>Bt.YT,PrepareDefinesForMisc:()=>Bt.fm,PrepareDefinesForMorphTargets:()=>Bt.Jz,PrepareDefinesForMultiview:()=>Bt.VO,PrepareDefinesForOIT:()=>Bt.Nc,PrepareDefinesForPrePass:()=>Bt.N4,PrepareUniformsAndSamplersForLight:()=>Bt.GD,PrepareUniformsAndSamplersList:()=>Bt.Bb,PressureObserverWrapper:()=>VI,PrimitiveTopology:()=>Hh,PrismaticConstraint:()=>rO,ProceduralTexture:()=>cv,ProceduralTextureSceneComponent:()=>hv,PropertyTypeForEdition:()=>Xp,ProximityCastResult:()=>yO,PushAttributesForInstances:()=>Bt.te,PushMaterial:()=>bn,QuadraticEase:()=>Ae,QuadraticErrorSimplification:()=>bE,QuarticEase:()=>Re,Quaternion:()=>hc.PT,QueryType:()=>sc,QueueNewFrame:()=>Ot.r,QuinticEase:()=>Ie,RGBDTextureTools:()=>Cm.G,RSMCreatePluginMaterial:()=>IN,Ragdoll:()=>aO,RagdollBoneProperties:()=>oO,RandomBlock:()=>EP,RandomBlockLocks:()=>YE,RandomGUID:()=>Au.z,RandomNumberBlock:()=>mC,RawCubeTexture:()=>$b,RawTexture:()=>xi,RawTexture2DArray:()=>Ux,RawTexture3D:()=>Qb,Ray:()=>wi,RayHelper:()=>Tl,ReadFile:()=>$m.NJ,ReadFileError:()=>$m.VB,RecastJSCrowd:()=>rM,RecastJSPlugin:()=>iM,ReciprocalBlock:()=>xC,ReflectBlock:()=>MC,ReflectionBlock:()=>FC,ReflectionProbe:()=>Kx,ReflectionTextureBaseBlock:()=>pT,ReflectionTextureBlock:()=>_T,ReflectiveShadowMap:()=>AN,Reflector:()=>BI,RefractBlock:()=>OC,RefractionBlock:()=>VC,RefractionPostProcess:()=>$O,RefractionTexture:()=>Zb,RegisterClass:()=>X.Y5,RegisterMaterialPlugin:()=>In,RegisterNativeTypeAsync:()=>fh,RegisterTargetForLateAnimationBinding:()=>me.BT,RemapBlock:()=>ev,RenderPassTimestampLocation:()=>tc,RenderTargetTexture:()=>ln.$,RenderTargetWrapper:()=>qs,RenderTargetsOptimization:()=>ER,RenderingGroup:()=>Kw.U,RenderingGroupInfo:()=>cx.o,RenderingManager:()=>cx.m,ReplaceColorBlock:()=>bC,RequestFile:()=>$m.sh,RequestFileError:()=>$m.Mi,RequestFullscreen:()=>tn,RequestPointerlock:()=>sn,ResizeImageBitmap:()=>en,RetryStrategy:()=>eI.a,ReverseLutFromBitmap:()=>kb.FG,RibbonBuilder:()=>ca,RichType:()=>Mu,RichTypeAny:()=>Ou,RichTypeBoolean:()=>Nu,RichTypeColor3:()=>ku,RichTypeColor4:()=>Uu,RichTypeFlowGraphInteger:()=>zu,RichTypeMatrix:()=>Vu,RichTypeNumber:()=>wu,RichTypeQuaternion:()=>Gu,RichTypeString:()=>Du,RichTypeVector2:()=>Fu,RichTypeVector3:()=>Lu,RichTypeVector4:()=>Bu,RollingAverage:()=>Vs,Rotate2dBlock:()=>IC,RotationGizmo:()=>rm,RotationXBlock:()=>VP,RotationYBlock:()=>kP,RotationZBlock:()=>UP,RuntimeAnimation:()=>De.x,RuntimeError:()=>nt.bu,SSAO2RenderingPipeline:()=>oD,SSAORenderingPipeline:()=>lD,SSRRenderingPipeline:()=>_D,SamplerBindingType:()=>Vh,Scalar:()=>Gy,ScaleBlock:()=>jT,ScaleGizmo:()=>om,ScalingBlock:()=>GP,ScanData:()=>Wb.u,Scene:()=>oi.Z,SceneComponentConstants:()=>Ut.v,SceneDepthBlock:()=>mT,SceneInstrumentation:()=>Fv,SceneLoader:()=>xg,SceneLoaderAnimationGroupLoadingMode:()=>jm,SceneLoaderFlags:()=>St,SceneOptimization:()=>gR,SceneOptimizer:()=>RR,SceneOptimizerOptions:()=>AR,ScenePerformancePriority:()=>oi.F,SceneRecorder:()=>RI,SceneSerializer:()=>DR,ScreenSizeBlock:()=>US,ScreenSpaceBlock:()=>GS,ScreenSpaceCurvaturePostProcess:()=>ID,ScreenSpaceReflectionPostProcess:()=>cD,ScreenshotTools:()=>KR,SerializationHelper:()=>it.p,SetBasisTranscoderWorker:()=>hR.af,SetColorsBlock:()=>bP,SetCorsBehavior:()=>$m.M1,SetMaterialIDBlock:()=>NP,SetNormalsBlock:()=>vP,SetParentAction:()=>le,SetPositionsBlock:()=>gP,SetStateAction:()=>ee,SetTangentsBlock:()=>SP,SetToDefaultGaussianSplatting:()=>mS,SetUVsBlock:()=>xP,SetValueAction:()=>te,ShaderCodeInliner:()=>$l,ShaderLanguage:()=>Eb,ShaderMaterial:()=>xo,ShaderStage:()=>Lh,ShaderStore:()=>Cs.l,ShadowDepthWrapper:()=>py,ShadowGenerator:()=>ux,ShadowGeneratorSceneComponent:()=>yx,ShadowLight:()=>lm,ShadowMapBlock:()=>XS,ShadowsOptimization:()=>bR,ShapeBuilder:()=>za,ShapeCastResult:()=>EO,SharpenPostProcess:()=>ZO,SheenBlock:()=>wC,SimplexPerlin3DBlock:()=>AC,SimplicationQueueSceneComponent:()=>SE,SimplificationQueue:()=>hE,SimplificationSettings:()=>lE,SimplificationType:()=>cE,SineEase:()=>Me,SixDofDragBehavior:()=>ir,Size:()=>hc.or,Skeleton:()=>Ti,SkeletonViewer:()=>yl,SliderConstraint:()=>tO,SmartArray:()=>Qe.L,SmartArrayNoDuplicate:()=>Qe.b,SmoothStepBlock:()=>vC,SnapshotRenderingHelper:()=>YI,SolidParticle:()=>uM,SolidParticleSystem:()=>_M,SolidParticleVertex:()=>pM,Sound:()=>si,SoundTrack:()=>ni,SourceTextureFormat:()=>rS.Ok,Space:()=>hc.$x,SphereBlock:()=>cP,SphereBuilder:()=>Zo,SphereDirectedParticleEmitter:()=>pI,SphereParticleEmitter:()=>fI,Spherical:()=>Wy,SphericalHarmonics:()=>Ks.O,SphericalPolynomial:()=>Ks.Q,SplatReaderBlock:()=>_S,SpotLight:()=>dm,SpringConstraint:()=>sO,Sprite:()=>$x,SpriteManager:()=>Jx,SpriteMap:()=>JF,SpriteMapFrameRotationDirection:()=>ZF,SpritePackedManager:()=>eL,SpriteSceneComponent:()=>Qx,Stage:()=>Ut.B,StandardMaterial:()=>Un,StandardMaterialDefines:()=>kn,StandardRenderingPipeline:()=>uD,StartsWith:()=>bi.UH,StateCondition:()=>Q,StencilOperation:()=>$h,StencilState:()=>lL.K,StencilStateComposer:()=>kc.u,StepBlock:()=>oC,StereoscopicArcRotateCamera:()=>As,StereoscopicFreeCamera:()=>Rs,StereoscopicGamepadCamera:()=>Is,StereoscopicInterlacePostProcess:()=>Es,StereoscopicInterlacePostProcessI:()=>ys,StereoscopicScreenUniversalCamera:()=>Os,StereoscopicUniversalCamera:()=>Ms,StickValues:()=>Tr,StopAnimationAction:()=>se,StopSoundAction:()=>fe,StorageBuffer:()=>_r.K,StorageReadBlock:()=>ny,StorageTextureAccess:()=>Uh,StorageWriteBlock:()=>oy,StoreOp:()=>rc,StringDictionary:()=>$r.w,StringTools:()=>bi.nQ,SubEmitter:()=>lI,SubEmitterType:()=>nI,SubMesh:()=>vt,SubSurfaceBlock:()=>kC,SubSurfaceSceneComponent:()=>Xw,SubtractBlock:()=>nC,SurfaceMagnetismBehavior:()=>rr,SwitchBooleanAction:()=>J,SwitchInput:()=>Pl.dR,TAARenderingPipeline:()=>mD,TBNBlock:()=>NS,TGATools:()=>BR.uT,Tags:()=>Ge.Y,TargetCamera:()=>Jr,TargetedAnimation:()=>Fe.TargetedAnimation,TeleportInBlock:()=>iA,TeleportOutBlock:()=>rA,TestBase64DataUrl:()=>$m.ZP,TextFileAssetTask:()=>tR,Texture:()=>vi.g,TextureAspect:()=>Mh,TextureAssetTask:()=>sR,TextureBlock:()=>fT,TextureDimension:()=>Ah,TextureFormat:()=>Oh,TextureOptimization:()=>vR,TexturePacker:()=>Yb,TexturePackerFrame:()=>qb,TextureSampleType:()=>kh,TextureSampler:()=>Jb.u,TextureTools:()=>Ac.LO,TextureUsage:()=>Rh,TextureViewDimension:()=>Ih,ThinBlackAndWhitePostProcess:()=>l_,ThinBloomEffect:()=>m_,ThinBlurPostProcess:()=>p_,ThinCircleOfConfusionPostProcess:()=>T_,ThinDepthOfFieldEffect:()=>I_,ThinDepthOfFieldEffectBlurLevel:()=>qp,ThinEngine:()=>Ls.ThinEngine,ThinExtractHighlightsPostProcess:()=>__,ThinRenderTargetTexture:()=>tS,ThinTexture:()=>eS.D,TiledBoxBuilder:()=>xa,TiledPlaneBuilder:()=>ma,TimerState:()=>vd,TmpColors:()=>hc.IG,TmpVectors:()=>hc.AA,ToGammaSpace:()=>hc.rv,ToHalfFloat:()=>Ac.LZ,ToLinearSpace:()=>hc.tk,TonemapPostProcess:()=>AD,TonemappingOperator:()=>gD,Tools:()=>Ue.S0,TorusBlock:()=>dP,TorusBuilder:()=>lo,TorusKnotBuilder:()=>Ta,TouchCamera:()=>ts,TrailMesh:()=>aE,Trajectory:()=>OI,TrajectoryClassifier:()=>FI,TranscodeAsync:()=>hR.yk,TranscodeTarget:()=>rS.Xl,TransformBlock:()=>zg,TransformFeedbackBoundingHelper:()=>Ro.TransformFeedbackBoundingHelper,TransformNode:()=>Pt,TranslationBlock:()=>WP,TriPlanarBlock:()=>QC,TrigonometryBlock:()=>uv,TrigonometryBlockOperations:()=>av,TubeBuilder:()=>qa,TwirlBlock:()=>zS,UncompressPIZ:()=>Vb.tg,UncompressPXR:()=>Vb._k,UncompressRAW:()=>Vb.S4,UncompressRLE:()=>Vb.r,UncompressZIP:()=>Vb.VE,UniformBuffer:()=>Rt.D,UniversalCamera:()=>fs,UnregisterAllMaterialPlugins:()=>On,UnregisterMaterialPlugin:()=>Mn,UploadContent:()=>BR.FA,UploadEnvLevelsAsync:()=>Wl.o5,UploadEnvSpherical:()=>Wl.ow,UploadLevelsAsync:()=>Wl.bv,UtilityLayerRenderer:()=>Bo,VRCameraMetrics:()=>ws,VRDeviceOrientationArcRotateCamera:()=>pn,VRDeviceOrientationFreeCamera:()=>_n,VRDeviceOrientationGamepadCamera:()=>mn,VRDistortionCorrectionPostProcess:()=>Ns,VRExperienceHelper:()=>fo,VRMultiviewToSingleviewPostProcess:()=>dn,ValidatedNativeDataStream:()=>vh,ValueCondition:()=>j,Vector2:()=>hc.I9,Vector2ToFixed:()=>Hy,Vector3:()=>hc.Pq,Vector3ToFixed:()=>Xy,Vector4:()=>hc.IU,Vector4ToFixed:()=>qy,VectorConverterBlock:()=>DP,VectorMergerBlock:()=>Jg,VectorSplitterBlock:()=>iC,VertexAnimationBaker:()=>Ci,VertexBuffer:()=>st.R,VertexData:()=>bt,VertexDataMaterialInfo:()=>xt,VertexFormat:()=>Zh,VertexOutputBlock:()=>Wg,VertexStepMode:()=>Jh,VideoDome:()=>wv,VideoRecorder:()=>VR,VideoTexture:()=>Dv,ViewDirectionBlock:()=>lC,Viewport:()=>hc.LM,VirtualJoystick:()=>Qr,VirtualJoysticksCamera:()=>Ds,VolumetricLightScatteringPostProcess:()=>RD,VoronoiNoiseBlock:()=>jC,Wav2Decode:()=>kb.tb,WaveBlock:()=>TC,WaveBlockKind:()=>vT,WebGL2ParticleSystem:()=>oM,WebGL2ShaderProcessor:()=>Tu.B,WebGLDataBuffer:()=>ks.A,WebGLHardwareTexture:()=>Us.d,WebGLPipelineContext:()=>Su.x,WebGPUCacheBindGroups:()=>Kc,WebGPUCacheRenderPipeline:()=>Lc,WebGPUCacheRenderPipelineTree:()=>Vc,WebGPUCacheSampler:()=>Dc,WebGPUDataBuffer:()=>Pc,WebGPUDrawContext:()=>Xc,WebGPUEngine:()=>gu,WebGPUPipelineContext:()=>uc,WebGPURenderTargetWrapper:()=>fu,WebGPUShaderProcessor:()=>cc,WebGPUTintWASM:()=>lu,WebRequest:()=>go.u,WebXRAbstractFeature:()=>Ig,WebXRAbstractMotionController:()=>bg,WebXRAnchorSystem:()=>uL,WebXRBackgroundRemover:()=>pL,WebXRCamera:()=>qm,WebXRControllerComponent:()=>Km,WebXRControllerMovement:()=>yL,WebXRControllerPhysics:()=>mL,WebXRControllerPointerSelection:()=>Mg,WebXRDefaultExperience:()=>Iv,WebXRDefaultExperienceOptions:()=>Rv,WebXRDepthSensing:()=>kL,WebXRDomOverlay:()=>CL,WebXREnterExitUI:()=>Tv,WebXREnterExitUIButton:()=>bv,WebXREnterExitUIOptions:()=>Sv,WebXRExperienceHelper:()=>Ym,WebXREyeTracking:()=>PL,WebXRFeatureName:()=>hr,WebXRFeaturePointSystem:()=>vL,WebXRFeaturesManager:()=>cr,WebXRGenericHandController:()=>HL,WebXRGenericTriggerMotionController:()=>Sg,WebXRHTCViveMotionController:()=>$L,WebXRHand:()=>Ev,WebXRHandJoint:()=>vv,WebXRHandTracking:()=>Pv,WebXRHitTest:()=>gL,WebXRHitTestLegacy:()=>hL,WebXRImageTracking:()=>TL,WebXRInput:()=>Rg,WebXRInputSource:()=>Ag,WebXRLayerRenderTargetTextureProvider:()=>Wn,WebXRLayers:()=>VL,WebXRLightEstimation:()=>EL,WebXRManagedOutputCanvas:()=>Yn,WebXRManagedOutputCanvasOptions:()=>qn,WebXRMeshDetector:()=>bL,WebXRMicrosoftMixedRealityController:()=>qL,WebXRMotionControllerManager:()=>Eg,WebXRMotionControllerTeleportation:()=>Av,WebXRNearControllerMode:()=>mv,WebXRNearInteraction:()=>xv,WebXROculusTouchMotionController:()=>KL,WebXRPlaneDetector:()=>fL,WebXRProfiledMotionController:()=>Cg,WebXRRawCameraAccess:()=>WL,WebXRSessionManager:()=>Qn,WebXRSpaceWarp:()=>zL,WebXRSpaceWarpRenderTargetTextureProvider:()=>GL,WebXRState:()=>tL,WebXRTrackingState:()=>iL,WebXRWalkingLocomotion:()=>OL,WeightedSound:()=>mi,WorkerPool:()=>jy.T,WorleyNoise3DBlock:()=>PC,XRSpaceWarpRenderTarget:()=>UL,Xbox360Button:()=>qr,Xbox360Dpad:()=>Yr,Xbox360Pad:()=>hs,XboxInput:()=>Pl.sZ,_BabylonLoaderRegistered:()=>eb,_BasisTextureLoader:()=>Lb._BasisTextureLoader,_CommonDispose:()=>Qs,_CommonInit:()=>$s,_CreationDataStorage:()=>zt,_DDSTextureLoader:()=>Wm._DDSTextureLoader,_ENVTextureLoader:()=>Hm._ENVTextureLoader,_ExrTextureLoader:()=>Bb._ExrTextureLoader,_GetCompatibleTextureLoader:()=>ch.gT,_HDRTextureLoader:()=>Fb._HDRTextureLoader,_InstancesBatch:()=>Ht,_KTXTextureLoader:()=>Xm._KTXTextureLoader,_MeshCollisionData:()=>It,_OcclusionDataStorage:()=>Nl,_PrimaryIsoTriangle:()=>hl,_TGATextureLoader:()=>Nb._TGATextureLoader,_TimeToken:()=>Vl,_UpdateRGBDAsync:()=>Wl.gW,_forceSceneHelpersToBundle:()=>Mv,_forceTransformFeedbackToBundle:()=>Ul,_injectLTSFileTools:()=>$m.rh,_staticOffsetValueColor3:()=>pe.eA,_staticOffsetValueColor4:()=>pe.nl,_staticOffsetValueQuaternion:()=>pe.s$,_staticOffsetValueSize:()=>pe.vF,_staticOffsetValueVector2:()=>pe.rq,_staticOffsetValueVector3:()=>pe.y4,addClipPlaneUniforms:()=>Ln.TV,allocateAndCopyTypedBuffer:()=>Xs.kZ,anaglyphPixelShader:()=>lw.anaglyphPixelShader,anaglyphPixelShaderWGSL:()=>hw.anaglyphPixelShaderWGSL,appendSceneAsync:()=>ug,backbufferColorTextureHandle:()=>Np,backbufferDepthStencilTextureHandle:()=>Fp,backgroundPixelShader:()=>_b.backgroundPixelShader,backgroundPixelShaderWGSL:()=>fb.backgroundPixelShaderWGSL,backgroundVertexShader:()=>pb.backgroundVertexShader,backgroundVertexShaderWGSL:()=>db.backgroundVertexShaderWGSL,bilateralBlurPixelShader:()=>NN.bilateralBlurPixelShader,bilateralBlurPixelShaderWGSL:()=>VN.bilateralBlurPixelShaderWGSL,bilateralBlurQualityPixelShader:()=>FN.bilateralBlurQualityPixelShader,bilateralBlurQualityPixelShaderWGSL:()=>kN.bilateralBlurQualityPixelShaderWGSL,bindClipPlane:()=>Ln.gS,blackAndWhitePixelShader:()=>ow.blackAndWhitePixelShader,blackAndWhitePixelShaderWGSL:()=>aw.blackAndWhitePixelShaderWGSL,bloomMergePixelShader:()=>ZD.bloomMergePixelShader,bloomMergePixelShaderWGSL:()=>JD.bloomMergePixelShaderWGSL,bonesDeclaration:()=>CS.bonesDeclaration,bonesDeclarationWGSL:()=>SS.bonesDeclarationWGSL,bonesVertex:()=>yS.bonesVertex,bonesVertexWGSL:()=>TS.bonesVertexWGSL,boundingBoxRendererPixelShader:()=>qN.boundingBoxRendererPixelShader,boundingBoxRendererPixelShaderWGSL:()=>KN.boundingBoxRendererPixelShaderWGSL,boundingBoxRendererVertexShader:()=>YN.boundingBoxRendererVertexShader,boundingBoxRendererVertexShaderWGSL:()=>jN.boundingBoxRendererVertexShaderWGSL,bumpFragment:()=>tT.bumpFragment,bumpFragmentFunctions:()=>rT.bumpFragmentFunctions,bumpFragmentFunctionsWGSL:()=>eT.bumpFragmentFunctionsWGSL,bumpFragmentMainFunctions:()=>iT.bumpFragmentMainFunctions,bumpFragmentMainFunctionsWGSL:()=>JS.bumpFragmentMainFunctionsWGSL,bumpFragmentWGSL:()=>ZS.bumpFragmentWGSL,captureEquirectangularFromScene:()=>KI,chromaticAberrationPixelShader:()=>rD.chromaticAberrationPixelShader,chromaticAberrationPixelShaderWGSL:()=>YD.chromaticAberrationPixelShaderWGSL,circleOfConfusionPixelShader:()=>$D.circleOfConfusionPixelShader,circleOfConfusionPixelShaderWGSL:()=>QD.circleOfConfusionPixelShaderWGSL,className:()=>Ue.s7,clipPlaneFragment:()=>CT.clipPlaneFragment,clipPlaneFragmentDeclaration:()=>yT.clipPlaneFragmentDeclaration,clipPlaneFragmentDeclarationWGSL:()=>bT.clipPlaneFragmentDeclarationWGSL,clipPlaneFragmentWGSL:()=>xT.clipPlaneFragmentWGSL,clipPlaneVertex:()=>ET.clipPlaneVertex,clipPlaneVertexDeclaration:()=>PT.clipPlaneVertexDeclaration,clipPlaneVertexDeclarationWGSL:()=>TT.clipPlaneVertexDeclarationWGSL,clipPlaneVertexWGSL:()=>ST.clipPlaneVertexWGSL,colorCorrectionPixelShader:()=>dw.colorCorrectionPixelShader,colorCorrectionPixelShaderWGSL:()=>fw.colorCorrectionPixelShaderWGSL,colorPixelShader:()=>xb.colorPixelShader,colorPixelShaderWGSL:()=>FA.colorPixelShaderWGSL,colorVertexShader:()=>bb.colorVertexShader,colorVertexShaderWGSL:()=>LA.colorVertexShaderWGSL,computeMaxExtents:()=>CE,convolutionPixelShader:()=>cw.convolutionPixelShader,convolutionPixelShaderWGSL:()=>uw.convolutionPixelShaderWGSL,copyTexture3DLayerToTexturePixelShader:()=>sF.copyTexture3DLayerToTexturePixelShader,copyTexture3DLayerToTexturePixelShaderWGSL:()=>nF.copyTexture3DLayerToTexturePixelShaderWGSL,copyTextureToTexturePixelShader:()=>eM.copyTextureToTexturePixelShader,copyTextureToTexturePixelShaderWGSL:()=>tM.copyTextureToTexturePixelShaderWGSL,createDetailMapPlugin:()=>Cy,createPBRAnisotropicPlugin:()=>gy,createPBRBRDFPlugin:()=>vy,createPBRClearCoatPlugin:()=>xy,createPBRIridescencePlugin:()=>by,createPBRSheenPlugin:()=>Sy,createPBRSubSurfacePlugin:()=>Ty,createYieldingScheduler:()=>We,defaultPixelShader:()=>Ly.defaultPixelShader,defaultPixelShaderWGSL:()=>Vy.defaultPixelShaderWGSL,defaultVertexShader:()=>By.defaultVertexShader,defaultVertexShaderWGSL:()=>ky.defaultVertexShaderWGSL,depthBoxBlurPixelShader:()=>Ox.depthBoxBlurPixelShader,depthBoxBlurPixelShaderWGSL:()=>Ax.depthBoxBlurPixelShaderWGSL,depthOfFieldMergePixelShader:()=>KD.depthOfFieldMergePixelShader,depthOfFieldMergePixelShaderWGSL:()=>jD.depthOfFieldMergePixelShaderWGSL,depthPixelShader:()=>dx.depthPixelShader,depthPixelShaderWGSL:()=>zN.depthPixelShaderWGSL,depthVertexShader:()=>fx.depthVertexShader,depthVertexShaderWGSL:()=>WN.depthVertexShaderWGSL,displayPassPixelShader:()=>bw.displayPassPixelShader,displayPassPixelShaderWGSL:()=>Sw.displayPassPixelShaderWGSL,editableInPropertyPage:()=>t_,expandToProperty:()=>$e.$z,extractHighlightsPixelShader:()=>ew.extractHighlightsPixelShader,extractHighlightsPixelShaderWGSL:()=>tw.extractHighlightsPixelShaderWGSL,extractMinAndMax:()=>mt.b8,extractMinAndMaxIndexed:()=>mt.cD,filterPixelShader:()=>mw.filterPixelShader,filterPixelShaderWGSL:()=>gw.filterPixelShaderWGSL,fluidRenderingBilateralBlurPixelShader:()=>fN.fluidRenderingBilateralBlurPixelShader,fluidRenderingBilateralBlurPixelShaderWGSL:()=>yN.fluidRenderingBilateralBlurPixelShaderWGSL,fluidRenderingParticleDepthPixelShader:()=>oN.fluidRenderingParticleDepthPixelShader,fluidRenderingParticleDepthPixelShaderWGSL:()=>gN.fluidRenderingParticleDepthPixelShaderWGSL,fluidRenderingParticleDepthVertexShader:()=>nN.fluidRenderingParticleDepthVertexShader,fluidRenderingParticleDepthVertexShaderWGSL:()=>mN.fluidRenderingParticleDepthVertexShaderWGSL,fluidRenderingParticleDiffusePixelShader:()=>dN.fluidRenderingParticleDiffusePixelShader,fluidRenderingParticleDiffusePixelShaderWGSL:()=>CN.fluidRenderingParticleDiffusePixelShaderWGSL,fluidRenderingParticleDiffuseVertexShader:()=>uN,fluidRenderingParticleDiffuseVertexShaderWGSL:()=>TN,fluidRenderingParticleThicknessPixelShader:()=>lN.fluidRenderingParticleThicknessPixelShader,fluidRenderingParticleThicknessPixelShaderWGSL:()=>xN.fluidRenderingParticleThicknessPixelShaderWGSL,fluidRenderingParticleThicknessVertexShader:()=>aN.fluidRenderingParticleThicknessVertexShader,fluidRenderingParticleThicknessVertexShaderWGSL:()=>vN.fluidRenderingParticleThicknessVertexShaderWGSL,fluidRenderingRenderPixelShader:()=>_N.fluidRenderingRenderPixelShader,fluidRenderingRenderPixelShaderWGSL:()=>PN.fluidRenderingRenderPixelShaderWGSL,fluidRenderingStandardBlurPixelShader:()=>pN.fluidRenderingStandardBlurPixelShader,fluidRenderingStandardBlurPixelShaderWGSL:()=>EN.fluidRenderingStandardBlurPixelShaderWGSL,fogFragmentDeclaration:()=>RT.fogFragmentDeclaration,fogFragmentDeclarationWGSL:()=>AT.fogFragmentDeclarationWGSL,fxaaPixelShader:()=>iw.fxaaPixelShader,fxaaPixelShaderWGSL:()=>sw.fxaaPixelShaderWGSL,fxaaVertexShader:()=>rw.fxaaVertexShader,fxaaVertexShaderWGSL:()=>nw.fxaaVertexShaderWGSL,gaussianSplattingVertexDeclaration:()=>uy.Q,gaussianSplattingVertexDeclarationWGSL:()=>hy,geometryPixelShader:()=>WO.geometryPixelShader,geometryPixelShaderWGSL:()=>HN.geometryPixelShaderWGSL,geometryVertexShader:()=>HO.geometryVertexShader,geometryVertexShaderWGSL:()=>XN.geometryVertexShaderWGSL,getDimensionsFromTextureSize:()=>Zp,getRichTypeFromValue:()=>Wu,glowBlurPostProcessPixelShader:()=>jv.glowBlurPostProcessPixelShader,glowBlurPostProcessPixelShaderWGSL:()=>Zv.glowBlurPostProcessPixelShaderWGSL,glowMapGenerationPixelShader:()=>Wv.glowMapGenerationPixelShader,glowMapGenerationPixelShaderWGSL:()=>Xv.glowMapGenerationPixelShaderWGSL,glowMapGenerationVertexShader:()=>Hv.glowMapGenerationVertexShader,glowMapGenerationVertexShaderWGSL:()=>qv.glowMapGenerationVertexShaderWGSL,glowMapMergePixelShader:()=>Yv.glowMapMergePixelShader,glowMapMergePixelShaderWGSL:()=>$v.glowMapMergePixelShaderWGSL,glowMapMergeVertexShader:()=>Kv.glowMapMergeVertexShader,glowMapMergeVertexShaderWGSL:()=>Qv.glowMapMergeVertexShaderWGSL,grainPixelShader:()=>XD.grainPixelShader,grainPixelShaderWGSL:()=>qD.grainPixelShaderWGSL,hdrFilteringPixelShader:()=>aS.hdrFilteringPixelShader,hdrFilteringPixelShaderWGSL:()=>hS.hdrFilteringPixelShaderWGSL,hdrFilteringVertexShader:()=>oS.hdrFilteringVertexShader,hdrFilteringVertexShaderWGSL:()=>lS.hdrFilteringVertexShaderWGSL,helperFunctions:()=>jS.helperFunctions,helperFunctionsWGSL:()=>_c.helperFunctionsWGSL,highlightsPixelShader:()=>vw.highlightsPixelShader,highlightsPixelShaderWGSL:()=>xw.highlightsPixelShaderWGSL,iblCombineVoxelGridsPixelShader:()=>SF.iblCombineVoxelGridsPixelShader,iblCombineVoxelGridsPixelShaderWGSL:()=>bF.iblCombineVoxelGridsPixelShaderWGSL,iblGenerateVoxelMipPixelShader:()=>TF.iblGenerateVoxelMipPixelShader,iblGenerateVoxelMipPixelShaderWGSL:()=>CF.iblGenerateVoxelMipPixelShaderWGSL,iblShadowAccumulationPixelShader:()=>fF.iblShadowAccumulationPixelShader,iblShadowAccumulationPixelShaderWGSL:()=>dF.iblShadowAccumulationPixelShaderWGSL,iblShadowDebugPixelShader:()=>lF.iblShadowDebugPixelShader,iblShadowDebugPixelShaderWGSL:()=>hF.iblShadowDebugPixelShaderWGSL,iblShadowGBufferDebugPixelShader:()=>yF.iblShadowGBufferDebugPixelShader,iblShadowGBufferDebugPixelShaderWGSL:()=>EF.iblShadowGBufferDebugPixelShaderWGSL,iblShadowSpatialBlurPixelShader:()=>uF.iblShadowSpatialBlurPixelShader,iblShadowSpatialBlurPixelShaderWGSL:()=>cF.iblShadowSpatialBlurPixelShaderWGSL,iblShadowVoxelTracingPixelShader:()=>oF.iblShadowVoxelTracingPixelShader,iblShadowVoxelTracingPixelShaderWGSL:()=>aF.iblShadowVoxelTracingPixelShaderWGSL,iblShadowsCdfxPixelShader:()=>AF.iblShadowsCdfxPixelShader,iblShadowsCdfxPixelShaderWGSL:()=>PF.iblShadowsCdfxPixelShaderWGSL,iblShadowsCdfyPixelShader:()=>IF.iblShadowsCdfyPixelShader,iblShadowsCdfyPixelShaderWGSL:()=>RF.iblShadowsCdfyPixelShaderWGSL,iblShadowsCombinePixelShader:()=>mF,iblShadowsCombinePixelShaderWGSL:()=>xF,iblShadowsIcdfxPixelShader:()=>OF.iblShadowsIcdfxPixelShader,iblShadowsIcdfxPixelShaderWGSL:()=>MF.iblShadowsIcdfxPixelShaderWGSL,iblShadowsIcdfyPixelShader:()=>wF.iblShadowsIcdfyPixelShader,iblShadowsIcdfyPixelShaderWGSL:()=>DF.iblShadowsIcdfyPixelShaderWGSL,iblShadowsImportanceSamplingDebugPixelShader:()=>FF.iblShadowsImportanceSamplingDebugPixelShader,iblShadowsImportanceSamplingDebugPixelShaderWGSL:()=>NF.iblShadowsImportanceSamplingDebugPixelShaderWGSL,iblVoxelGrid2dArrayDebugPixelShader:()=>LF.iblVoxelGrid2dArrayDebugPixelShader,iblVoxelGrid2dArrayDebugPixelShaderWGSL:()=>BF.iblVoxelGrid2dArrayDebugPixelShaderWGSL,iblVoxelGrid3dDebugPixelShader:()=>zF.iblVoxelGrid3dDebugPixelShader,iblVoxelGrid3dDebugPixelShaderWGSL:()=>WF.iblVoxelGrid3dDebugPixelShaderWGSL,iblVoxelGridPixelShader:()=>VF.iblVoxelGridPixelShader,iblVoxelGridPixelShaderWGSL:()=>UF.iblVoxelGridPixelShaderWGSL,iblVoxelGridVertexShader:()=>kF.iblVoxelGridVertexShader,iblVoxelGridVertexShaderWGSL:()=>GF.iblVoxelGridVertexShaderWGSL,iblVoxelSlabDebugPixelShader:()=>XF.iblVoxelSlabDebugPixelShader,iblVoxelSlabDebugPixelShaderWGSL:()=>YF.iblVoxelSlabDebugPixelShaderWGSL,iblVoxelSlabDebugVertexShader:()=>HF.iblVoxelSlabDebugVertexShader,iblVoxelSlabDebugVertexShaderWGSL:()=>qF.iblVoxelSlabDebugVertexShaderWGSL,imageProcessingDeclaration:()=>$S.imageProcessingDeclaration,imageProcessingDeclarationWGSL:()=>YS.imageProcessingDeclarationWGSL,imageProcessingFunctions:()=>QS.imageProcessingFunctions,imageProcessingFunctionsWGSL:()=>KS.imageProcessingFunctionsWGSL,imageProcessingPixelShader:()=>WD.imageProcessingPixelShader,imageProcessingPixelShaderWGSL:()=>zD.imageProcessingPixelShaderWGSL,importAnimationsAsync:()=>gg,inlineScheduler:()=>ze,kernelBlurPixelShader:()=>DD.kernelBlurPixelShader,kernelBlurPixelShaderWGSL:()=>ND.kernelBlurPixelShaderWGSL,kernelBlurVertexShader:()=>wD.kernelBlurVertexShader,kernelBlurVertexShaderWGSL:()=>FD.kernelBlurVertexShaderWGSL,layerPixelShader:()=>Jv.layerPixelShader,layerPixelShaderWGSL:()=>tx.layerPixelShaderWGSL,layerVertexShader:()=>ex.layerVertexShader,layerVertexShaderWGSL:()=>ix.layerVertexShaderWGSL,lensFlarePixelShader:()=>ox.lensFlarePixelShader,lensFlarePixelShaderWGSL:()=>lx.lensFlarePixelShaderWGSL,lensFlareVertexShader:()=>ax.lensFlareVertexShader,lensFlareVertexShaderWGSL:()=>hx.lensFlareVertexShaderWGSL,lightFragment:()=>LT.lightFragment,lightFragmentDeclaration:()=>FT.lightFragmentDeclaration,lightFragmentWGSL:()=>IT.lightFragmentWGSL,lightUboDeclaration:()=>BT.lightUboDeclaration,lightUboDeclarationWGSL:()=>MT.lightUboDeclarationWGSL,lightVxFragmentDeclaration:()=>kT.lightVxFragmentDeclaration,lightVxUboDeclaration:()=>VT.lightVxUboDeclaration,lightVxUboDeclarationWGSL:()=>OT.lightVxUboDeclarationWGSL,lightsFragmentFunctions:()=>UT.lightsFragmentFunctions,lightsFragmentFunctionsWGSL:()=>DT.lightsFragmentFunctionsWGSL,linePixelShader:()=>$N.linePixelShader,linePixelShaderWGSL:()=>ZN.linePixelShaderWGSL,lineVertexShader:()=>QN.lineVertexShader,lineVertexShaderWGSL:()=>JN.lineVertexShaderWGSL,loadAssetContainerAsync:()=>pg,loadSceneAsync:()=>lg,lodCubePixelShader:()=>wR.lodCubePixelShader,lodCubePixelShaderWGSL:()=>FR.lodCubePixelShaderWGSL,lodPixelShader:()=>NR.lodPixelShader,lodPixelShaderWGSL:()=>LR.lodPixelShaderWGSL,makeAsyncFunction:()=>Ke,makeSyncFunction:()=>Ye,meshUVSpaceRendererFinaliserPixelShader:()=>GA.meshUVSpaceRendererFinaliserPixelShader,meshUVSpaceRendererFinaliserPixelShaderWGSL:()=>YA.meshUVSpaceRendererFinaliserPixelShaderWGSL,meshUVSpaceRendererFinaliserVertexShader:()=>zA.meshUVSpaceRendererFinaliserVertexShader,meshUVSpaceRendererFinaliserVertexShaderWGSL:()=>KA.meshUVSpaceRendererFinaliserVertexShaderWGSL,meshUVSpaceRendererMaskerPixelShader:()=>UA.meshUVSpaceRendererMaskerPixelShader,meshUVSpaceRendererMaskerPixelShaderWGSL:()=>qA.meshUVSpaceRendererMaskerPixelShaderWGSL,meshUVSpaceRendererMaskerVertexShader:()=>kA.meshUVSpaceRendererMaskerVertexShader,meshUVSpaceRendererMaskerVertexShaderWGSL:()=>XA.meshUVSpaceRendererMaskerVertexShaderWGSL,meshUVSpaceRendererPixelShader:()=>VA.meshUVSpaceRendererPixelShader,meshUVSpaceRendererPixelShaderWGSL:()=>HA.meshUVSpaceRendererPixelShaderWGSL,meshUVSpaceRendererVertexShader:()=>BA.meshUVSpaceRendererVertexShader,meshUVSpaceRendererVertexShaderWGSL:()=>WA.meshUVSpaceRendererVertexShaderWGSL,morphTargetsVertex:()=>IS.morphTargetsVertex,morphTargetsVertexDeclaration:()=>MS.morphTargetsVertexDeclaration,morphTargetsVertexDeclarationWGSL:()=>PS.morphTargetsVertexDeclarationWGSL,morphTargetsVertexGlobal:()=>OS.morphTargetsVertexGlobal,morphTargetsVertexGlobalDeclaration:()=>DS.morphTargetsVertexGlobalDeclaration,morphTargetsVertexGlobalDeclarationWGSL:()=>RS.morphTargetsVertexGlobalDeclarationWGSL,morphTargetsVertexGlobalWGSL:()=>AS.morphTargetsVertexGlobalWGSL,morphTargetsVertexWGSL:()=>ES.morphTargetsVertexWGSL,motionBlurPixelShader:()=>pw.motionBlurPixelShader,motionBlurPixelShaderWGSL:()=>_w.motionBlurPixelShaderWGSL,nativeOverride:()=>$e.Cx,normalizeEnvInfo:()=>Wl.RZ,oitBackBlendPixelShader:()=>KF.oitBackBlendPixelShader,oitBackBlendPixelShaderWGSL:()=>$F.oitBackBlendPixelShaderWGSL,oitFinalPixelShader:()=>jF.oitFinalPixelShader,oitFinalPixelShaderWGSL:()=>QF.oitFinalPixelShaderWGSL,outlinePixelShader:()=>eF.outlinePixelShader,outlinePixelShaderWGSL:()=>iF.outlinePixelShaderWGSL,outlineVertexShader:()=>tF.outlineVertexShader,outlineVertexShaderWGSL:()=>rF.outlineVertexShaderWGSL,packingFunctions:()=>lT.packingFunctions,packingFunctionsWGSL:()=>nT.packingFunctionsWGSL,particlesPixelShader:()=>wM.particlesPixelShader,particlesPixelShaderWGSL:()=>FM.particlesPixelShaderWGSL,particlesVertexShader:()=>NM.particlesVertexShader,particlesVertexShaderWGSL:()=>LM.particlesVertexShaderWGSL,passCubePixelShader:()=>BD.passCubePixelShader,passCubePixelShaderWGSL:()=>kD.passCubePixelShaderWGSL,passPixelShader:()=>LD.passPixelShader,passPixelShaderWGSL:()=>VD.passPixelShaderWGSL,pbrPixelShader:()=>Ib.pbrPixelShader,pbrPixelShaderWGSL:()=>Ab.pbrPixelShaderWGSL,pbrVertexShader:()=>Rb.pbrVertexShader,pbrVertexShaderWGSL:()=>Pb.pbrVertexShaderWGSL,pickingPixelShader:()=>So.pickingPixelShader,pickingPixelShaderWGSL:()=>Co.pickingPixelShaderWGSL,pickingVertexShader:()=>To.pickingVertexShader,pickingVertexShaderWGSL:()=>yo.pickingVertexShaderWGSL,postprocessVertexShader:()=>MD.postprocessVertexShader,postprocessVertexShaderWGSL:()=>OD.postprocessVertexShaderWGSL,prepareDefinesForClipPlanes:()=>Ln.Eq,prepareStringDefinesForClipPlanes:()=>Ln.tv,proceduralVertexShader:()=>nS.proceduralVertexShader,proceduralVertexShaderWGSL:()=>sS.proceduralVertexShaderWGSL,reflectionFunction:()=>HT.reflectionFunction,reflectionFunctionWGSL:()=>WT.reflectionFunctionWGSL,registerSceneLoaderPlugin:()=>ng,registerTextureLoader:()=>ch.kf,rgbdDecodePixelShader:()=>$I.rgbdDecodePixelShader,rgbdDecodePixelShaderWGSL:()=>ZI.rgbdDecodePixelShaderWGSL,rgbdEncodePixelShader:()=>QI.rgbdEncodePixelShader,rgbdEncodePixelShaderWGSL:()=>JI.rgbdEncodePixelShaderWGSL,rsmFullGlobalIlluminationPixelShader:()=>BN.rsmFullGlobalIlluminationPixelShader,rsmFullGlobalIlluminationPixelShaderWGSL:()=>GN.rsmFullGlobalIlluminationPixelShaderWGSL,rsmGlobalIlluminationPixelShader:()=>LN.rsmGlobalIlluminationPixelShader,rsmGlobalIlluminationPixelShaderWGSL:()=>UN.rsmGlobalIlluminationPixelShaderWGSL,runCoroutine:()=>He,runCoroutineAsync:()=>qe,runCoroutineSync:()=>Xe,screenSpaceReflection2BlurCombinerPixelShader:()=>CD.screenSpaceReflection2BlurCombinerPixelShader,screenSpaceReflection2BlurCombinerPixelShaderWGSL:()=>PD.screenSpaceReflection2BlurCombinerPixelShaderWGSL,screenSpaceReflection2BlurPixelShader:()=>TD.screenSpaceReflection2BlurPixelShader,screenSpaceReflection2BlurPixelShaderWGSL:()=>ED.screenSpaceReflection2BlurPixelShaderWGSL,screenSpaceReflection2PixelShader:()=>SD.screenSpaceReflection2PixelShader,screenSpaceReflection2PixelShaderWGSL:()=>yD.screenSpaceReflection2PixelShaderWGSL,serialize:()=>$e.lK,serializeAsCameraReference:()=>$e.fW,serializeAsColor3:()=>$e.jT,serializeAsColor4:()=>$e.qK,serializeAsColorCurves:()=>$e.wL,serializeAsFresnelParameters:()=>$e.Y9,serializeAsImageProcessingConfiguration:()=>$e.n1,serializeAsMatrix:()=>$e.GG,serializeAsMeshReference:()=>$e.xG,serializeAsQuaternion:()=>$e.bR,serializeAsTexture:()=>$e.uM,serializeAsVector2:()=>$e.WM,serializeAsVector3:()=>$e.P_,setAndStartTimer:()=>xd,setOpenGLOrientationForUV:()=>Tt.ge,setStereoscopicAnaglyphRigMode:()=>vs,setStereoscopicRigMode:()=>Ps,setVRRigMode:()=>fn,shadowMapFragment:()=>hT.shadowMapFragment,shadowMapFragmentSoftTransparentShadow:()=>Dx.shadowMapFragmentSoftTransparentShadow,shadowMapFragmentSoftTransparentShadowWGSL:()=>Rx.shadowMapFragmentSoftTransparentShadowWGSL,shadowMapFragmentWGSL:()=>oT.shadowMapFragmentWGSL,shadowMapPixelShader:()=>Ix.shadowMapPixelShader,shadowMapPixelShaderWGSL:()=>Ex.shadowMapPixelShaderWGSL,shadowMapVertexMetric:()=>aT.shadowMapVertexMetric,shadowMapVertexMetricWGSL:()=>sT.shadowMapVertexMetricWGSL,shadowMapVertexShader:()=>Mx.shadowMapVertexShader,shadowMapVertexShaderWGSL:()=>Px.shadowMapVertexShaderWGSL,shadowsFragmentFunctions:()=>GT.shadowsFragmentFunctions,shadowsFragmentFunctionsWGSL:()=>wT.shadowsFragmentFunctionsWGSL,shadowsVertex:()=>zT.shadowsVertex,shadowsVertexWGSL:()=>NT.shadowsVertexWGSL,sharpenPixelShader:()=>QO.sharpenPixelShader,sharpenPixelShaderWGSL:()=>HD.sharpenPixelShaderWGSL,spritesPixelShader:()=>rL.spritesPixelShader,spritesPixelShaderWGSL:()=>nL.spritesPixelShaderWGSL,spritesVertexShader:()=>sL.spritesVertexShader,spritesVertexShaderWGSL:()=>oL.spritesVertexShaderWGSL,ssao2PixelShader:()=>vD.ssao2PixelShader,ssao2PixelShaderWGSL:()=>xD.ssao2PixelShaderWGSL,ssaoCombinePixelShader:()=>aD.ssaoCombinePixelShader,ssaoCombinePixelShaderWGSL:()=>bD.ssaoCombinePixelShaderWGSL,textureSizeIsObject:()=>Qp,tonemapPixelShader:()=>Tw.tonemapPixelShader,tonemapPixelShaderWGSL:()=>Cw.tonemapPixelShaderWGSL,unregisterTextureLoader:()=>ch.hy,useOpenGLOrientationForUV:()=>Tt.rX,vrDistortionCorrectionPixelShader:()=>UD.vrDistortionCorrectionPixelShader,vrDistortionCorrectionPixelShaderWGSL:()=>GD.vrDistortionCorrectionPixelShaderWGSL});var t={};i.r(t),i.d(t,{AbstractButton3D:()=>nV,AdvancedDynamicTexture:()=>$B,AdvancedDynamicTextureInstrumentation:()=>QB,BaseGradient:()=>qB,BaseSlider:()=>IB,Button:()=>pB,Button3D:()=>oV,Checkbox:()=>mB,CheckboxGroup:()=>DB,ColorPicker:()=>bB,Container:()=>hB,Container3D:()=>aV,Control:()=>lB,Control3D:()=>rV,CornerHandle:()=>AV,CylinderPanel:()=>hV,DisplayGrid:()=>WB,Ellipse:()=>SB,FluentBackplateMaterial:()=>_V,FluentButtonMaterial:()=>xV,FluentMaterial:()=>uV,FluentMaterialDefines:()=>cV,FocusableButton:()=>TB,FrameGraphGUITask:()=>ZB,GUI3DManager:()=>QV,GizmoHandle:()=>EV,Grid:()=>xB,HandMenu:()=>fV,HandleMaterial:()=>CV,HandleState:()=>yV,HolographicBackplate:()=>mV,HolographicButton:()=>gV,HolographicSlate:()=>IV,Image:()=>fB,ImageBasedSlider:()=>HB,ImageScrollBar:()=>VB,InputPassword:()=>yB,InputText:()=>vB,InputTextArea:()=>CB,KeyPropertySet:()=>GB,Line:()=>EB,LinearGradient:()=>YB,MRDLBackplateMaterial:()=>kV,MRDLSliderBarMaterial:()=>FV,MRDLSliderThumbMaterial:()=>BV,MathTools:()=>aB,Matrix2D:()=>oB,Measure:()=>sB,MeshButton3D:()=>MV,MultiLine:()=>AB,MultiLinePoint:()=>PB,NearMenu:()=>OV,NodeRenderGraphGUIBlock:()=>JB,PlanePanel:()=>DV,RadialGradient:()=>KB,RadioButton:()=>RB,RadioGroup:()=>wB,Rectangle:()=>cB,ScatterPanel:()=>wV,ScrollBar:()=>BB,ScrollViewer:()=>kB,SelectionPanel:()=>FB,SelectorGroup:()=>OB,SideHandle:()=>PV,SlateGizmo:()=>RV,Slider:()=>MB,Slider3D:()=>UV,SliderGroup:()=>NB,SpherePanel:()=>GV,StackPanel:()=>_B,StackPanel3D:()=>zV,Style:()=>jB,TextBlock:()=>dB,TextWrapper:()=>gB,TextWrapping:()=>uB,ToggleButton:()=>UB,TouchButton3D:()=>bV,TouchHolographicButton:()=>SV,TouchHolographicButtonV3:()=>$V,TouchHolographicMenu:()=>dV,TouchMeshButton3D:()=>WV,ValueAndUnit:()=>JL,Vector2WithInfo:()=>nB,Vector3WithInfo:()=>iV,VirtualKeyboard:()=>zB,VolumeBasedPanel:()=>lV,XmlLoader:()=>tV,name:()=>XB});var s={};i.r(s),i.d(s,{LodDto:()=>ZK,lodEnum:()=>WK});var n={};i.r(n),i.d(n,{Part:()=>JK});var o={};i.r(o),i.d(o,{SerenitySwirlData:()=>tj,SerenitySwirlDto:()=>ej});var a={};i.r(a),i.d(a,{ArabicArchwayData:()=>sj,ArabicArchwayDrawingPart:()=>nj,ArabicArchwayDrawingPartShapes:()=>oj,ArabicArchwayDto:()=>rj,ArabicArchwayDtoBase:()=>ij});var l={};i.r(l),i.d(l,{ArabicArchway:()=>a,SerenitySwirl:()=>o});var h={};i.r(h),i.d(h,{EternalLoveData:()=>hj,EternalLoveDto:()=>lj,EternalLoveDtoBase:()=>aj});var c={};i.r(c),i.d(c,{EternalLove:()=>h});var u={};i.r(u),i.d(u,{CalmCupData:()=>dj,CalmCupDto:()=>uj,CalmCupDtoBase:()=>cj});var d={};i.r(d),i.d(d,{DragonCupData:()=>_j,DragonCupDto:()=>pj,DragonCupDtoBase:()=>fj,DragonCupModelDto:()=>mj});var f={};i.r(f),i.d(f,{CalmCup:()=>u,DragonCup:()=>d});var p={};i.r(p),i.d(p,{PhoneNestData:()=>xj,PhoneNestDrawDto:()=>yj,PhoneNestDrawingPart:()=>bj,PhoneNestDrawingPartShapes:()=>Sj,PhoneNestDto:()=>vj,PhoneNestDtoBase:()=>gj,PhoneNestMainPart:()=>Tj,PhoneNestModelDto:()=>Cj});var _={};i.r(_),i.d(_,{PhoneNest:()=>p});var m={};i.r(m),i.d(m,{SpicyBoxData:()=>Aj,SpicyBoxDto:()=>Pj,SpicyBoxDtoBase:()=>Ej,SpicyBoxModelDto:()=>Rj});var g={};i.r(g),i.d(g,{SpicyBox:()=>m});var v={};i.r(v),i.d(v,{Boxes:()=>g,Cups:()=>f,Desktop:()=>_,Medals:()=>c,Vases:()=>l});var x={};i.r(x),i.d(x,{ZenHideoutData:()=>Oj,ZenHideoutDrawingPart:()=>Dj,ZenHideoutDrawingPartShapes:()=>wj,ZenHideoutDto:()=>Mj,ZenHideoutDtoBase:()=>Ij});var b={};i.r(b),i.d(b,{ZenHideout:()=>x});var S={};i.r(S),i.d(S,{BeamPart:()=>Hj,CeilingPart:()=>Jj,ColumnPart:()=>Wj,CornerEntranceDto:()=>t$,CornerEntrancePart:()=>$j,CornerPart:()=>zj,CornerStairDto:()=>Kj,CornerStairPart:()=>jj,FloorPart:()=>e$,Houses:()=>b,RoofBeamsPart:()=>qj,RoofCoverOneSidedDto:()=>Qj,RoofCoverPart:()=>Zj,RoofPanelPart:()=>Yj,RoofPart:()=>Xj,SandwitchPanelDto:()=>Vj,SandwitchPanelFlexDto:()=>kj,SandwitchPart:()=>Uj,SandwitchPartFlex:()=>Gj,WindowCornerDto:()=>Nj,WindowCornerPart:()=>Bj,WindowRectangularDto:()=>Fj,WindowRectangularPart:()=>Lj});var T={};i.r(T),i.d(T,{WingtipVillaData:()=>r$,WingtipVillaDto:()=>i$});var C={};i.r(C),i.d(C,{ChirpyChaletData:()=>n$,ChirpyChaletDto:()=>s$});var y={};i.r(y),i.d(y,{ChirpyChalet:()=>C,WingtipVilla:()=>T});var E={};i.r(E),i.d(E,{BirdHouses:()=>y});var P={};i.r(P),i.d(P,{SnakeChairData:()=>l$,SnakeChairDrawDto:()=>f$,SnakeChairDrawingPart:()=>h$,SnakeChairDrawingPartShapes:()=>c$,SnakeChairDto:()=>a$,SnakeChairDtoBase:()=>o$,SnakeChairMainPart:()=>u$,SnakeChairModelDto:()=>d$});var A={};i.r(A),i.d(A,{SnakeChair:()=>P});var R={};i.r(R),i.d(R,{ElegantTableData:()=>m$,ElegantTableDrawDto:()=>C$,ElegantTableDrawingPart:()=>g$,ElegantTableDrawingPartShapes:()=>v$,ElegantTableDto:()=>_$,ElegantTableDtoBase:()=>p$,ElegantTableLegByIndexDto:()=>S$,ElegantTableLegPart:()=>x$,ElegantTableModelDto:()=>T$,ElegantTableTopPart:()=>b$});var I={};i.r(I),i.d(I,{GoodCoffeeTableData:()=>P$,GoodCoffeeTableDrawDto:()=>N$,GoodCoffeeTableDrawingPart:()=>A$,GoodCoffeeTableDrawingPartShapes:()=>R$,GoodCoffeeTableDto:()=>E$,GoodCoffeeTableDtoBase:()=>y$,GoodCoffeeTableLegByIndexDto:()=>D$,GoodCoffeeTableLegPart:()=>I$,GoodCoffeeTableModelDto:()=>w$,GoodCoffeeTableShelfPart:()=>M$,GoodCoffeeTableTopPart:()=>O$});var M={};i.r(M),i.d(M,{SnakeTableData:()=>B$,SnakeTableDrawDto:()=>z$,SnakeTableDrawingPart:()=>V$,SnakeTableDrawingPartShapes:()=>k$,SnakeTableDto:()=>L$,SnakeTableDtoBase:()=>F$,SnakeTableMainPart:()=>U$,SnakeTableModelDto:()=>G$});var O={};i.r(O),i.d(O,{ElegantTable:()=>R,GoodCoffeeTable:()=>I,SnakeTable:()=>M});var D={};i.r(D),i.d(D,{Chairs:()=>A,Tables:()=>O});var w={};i.r(w),i.d(w,{Architecture:()=>S,Enums:()=>s,Furniture:()=>D,KidsCorner:()=>E,Shared:()=>n,ThreeDPrinting:()=>v});var N={};i.r(N),i.d(N,{FontDefinition:()=>K$,Text3DData:()=>q$,Text3DDto:()=>H$,Text3DFaceDefinitionDto:()=>$$,Text3DFaceDto:()=>X$,Text3DLetterByIndexDto:()=>Y$,Text3DModelDto:()=>j$,Texts3DFaceDto:()=>Q$,faceTextVarEnum:()=>YK,faceTypeEnum:()=>KK,fontVariantsEnum:()=>qK,fontsEnum:()=>XK,fontsModel:()=>W$,recAlignmentEnum:()=>jK});var F={};i.r(F),i.d(F,{PyramidSimpeByIndexDto:()=>tQ,PyramidSimpleAffectorsDto:()=>J$,PyramidSimpleCellPart:()=>cQ,PyramidSimpleData:()=>eQ,PyramidSimpleDto:()=>Z$,PyramidSimpleFacePart:()=>uQ,PyramidSimpleModelCellDto:()=>nQ,PyramidSimpleModelCellsDto:()=>rQ,PyramidSimpleModelCellsIndexDto:()=>sQ,PyramidSimpleModelDto:()=>iQ,PyramidSimpleModelFaceCellIndexDto:()=>aQ,PyramidSimpleModelFaceCellsUIndexDto:()=>lQ,PyramidSimpleModelFaceCellsVIndexDto:()=>hQ,PyramidSimpleModelFaceIndexDto:()=>oQ});var L={};i.r(L),i.d(L,{PyramidSimple:()=>F});var B={};i.r(B),i.d(B,{FacePatterns:()=>L});var V={};i.r(V),i.d(V,{outputShapeEnum:()=>dQ});var k={};i.r(k),i.d(k,{Enums:()=>V,Patterns:()=>B,Text3D:()=>N});var U={};i.r(U),i.d(U,{Asset:()=>ZH,BabylonCamera:()=>wH,BabylonGaussianSplatting:()=>kH,BabylonGizmo:()=>qH,BabylonGui:()=>VH,BabylonIO:()=>NH,BabylonLight:()=>LH,BabylonMaterial:()=>FH,BabylonMesh:()=>UH,BabylonMeshBuilder:()=>XH,BabylonNode:()=>$H,BabylonPick:()=>zH,BabylonRay:()=>WH,BabylonScene:()=>jH,BabylonTexture:()=>BH,BabylonTools:()=>HH,BabylonTransforms:()=>GH,BabylonWebXR:()=>YH,Base:()=>Kz,Draw:()=>QH,JSCAD:()=>nX,JSON:()=>JH,Line:()=>eX,Manifold:()=>oX,OCCT:()=>Yz,Polyline:()=>tX,Tag:()=>iX,Time:()=>rX,Verb:()=>sX});var G=i(96772),z=i(43279),W=i(94212),H=i(11084),X=i(56225);class q{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new z.cP,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 e=this._condition.serialize();return e.children.push(i),t&&t.children.push(e),e}return t&&t.children.push(i),i}}q._SerializeValueAsString=e=>"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e instanceof W.I9?e.x+", "+e.y:e instanceof W.Pq?e.x+", "+e.y+", "+e.z:e instanceof H.v9?e.r+", "+e.g+", "+e.b:e instanceof H.ov?e.r+", "+e.g+", "+e.b+", "+e.a:e,q._GetTargetProperty=e=>({name:"target",targetType:e._isMesh?"MeshProperties":e._isLight?"LightProperties":e._isCamera?"CameraProperties":e._isMaterial?"MaterialProperties":"SceneProperties",value:e._isScene?"Scene":e.name}),(0,X.Y5)("BABYLON.Action",q);var Y=i(89357);class K{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 j extends K{static get IsEqual(){return j._IsEqual}static get IsDifferent(){return j._IsDifferent}static get IsGreater(){return j._IsGreater}static get IsLesser(){return j._IsLesser}constructor(e,t,i,r,s=j.IsEqual){super(e),this.propertyPath=i,this.value=r,this.operator=s,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case j.IsGreater:return this._effectiveTarget[this._property]>this.value;case j.IsLesser:return this._effectiveTarget[this._property]-1&&this._scene.actionManagers.splice(e,1);const t=this._scene.meshes.filter((e=>e.actionManager===this));for(const e of t)e.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=ue.OnPickTrigger&&t.trigger<=ue.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=ue.OnPickTrigger&&t.trigger<=ue.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===ue.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(Z.V.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,ue.Triggers[e.trigger]?ue.Triggers[e.trigger]++:ue.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){const t=this.actions.indexOf(e);return-1!==t&&(this.actions.splice(t,1),ue.Triggers[e.trigger]-=1,0===ue.Triggers[e.trigger]&&delete ue.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0)}processTrigger(e,t){for(let i=0;i{if(null===r){const e=parseFloat(t);return"true"===t||"false"===t?"true"===t:isNaN(e)?t:e}const s=r.split("."),n=t.split(",");for(let e=0;e{if(e.detached)return;const h=[];let c=null,u=null;const d=e.combine&&e.combine.length>0;if(2===e.type?h.push(r):h.push(t),d){const t=[];for(let i=0;i{const i=(0,X.n9)("BABYLON."+e);return i&&new i(...t)})(e.name,h);if(f instanceof K&&null!==o){const e=new ne(t,o);a?a.then(e):r.registerAction(e),a=e}null===l?f instanceof K?(o=f,f=a):(o=null,a?a.then(f):r.registerAction(f)):l.push(f);for(let i=0;i0){const e=s.properties[0].value,t=null===s.properties[0].targetType?e:i.getMeshByName(e);t._meshId&&(t.mesh=i.getMeshById(t._meshId)),r={trigger:ue[s.name],parameter:t}}else r=ue[s.name];for(let e=0;e{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()}))}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[q._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:q._SerializeValueAsString(this.value)},{name:"duration",value:q._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:q._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}}(0,X.Y5)("BABYLON.InterpolateValueAction",_e);var me=i(66418);class ge{constructor(){this.enableBlending=!1,this.blendingSpeed=.01,this.loopMode=pe.X5.ANIMATIONLOOPMODE_CYCLE}}var ve=i(50324);class xe{constructor(){this._easingMode=xe.EASINGMODE_EASEIN}setEasingMode(e){const t=Math.min(Math.max(e,0),2);this._easingMode=t}getEasingMode(){return this._easingMode}easeInCore(e){throw new Error("You must implement this method")}ease(e){switch(this._easingMode){case xe.EASINGMODE_EASEIN:return this.easeInCore(e);case xe.EASINGMODE_EASEOUT:return 1-this.easeInCore(1-e)}return e>=.5?.5*(1-this.easeInCore(2*(1-e)))+.5:.5*this.easeInCore(2*e)}}xe.EASINGMODE_EASEIN=0,xe.EASINGMODE_EASEOUT=1,xe.EASINGMODE_EASEINOUT=2;class be extends xe{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class Se extends xe{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 Te extends xe{constructor(e=3,t=2){super(),this.bounces=e,this.bounciness=t}easeInCore(e){const t=Math.max(0,this.bounces);let i=this.bounciness;i<=1&&(i=1.001);const r=Math.pow(i,t),s=1-i,n=(1-r)/s+.5*r,o=e*n,a=Math.log(-o*(1-i)+1)/Math.log(i),l=Math.floor(a),h=l+1,c=(1-Math.pow(i,l))/(s*n),u=.5*(c+(1-Math.pow(i,h))/(s*n)),d=e-u,f=u-c;return-Math.pow(1/i,t-l)/(f*f)*(d-f)*(d+f)}}class Ce extends xe{easeInCore(e){return e*e*e}}class ye extends xe{constructor(e=3,t=3){super(),this.oscillations=e,this.springiness=t}easeInCore(e){let t;const i=Math.max(0,this.oscillations),r=Math.max(0,this.springiness);return t=0==r?e:(Math.exp(r*e)-1)/(Math.exp(r)-1),t*Math.sin((6.283185307179586*i+1.5707963267948966)*e)}}class Ee extends xe{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 Pe extends xe{constructor(e=2){super(),this.power=e}easeInCore(e){const t=Math.max(0,this.power);return Math.pow(e,t)}}class Ae extends xe{easeInCore(e){return e*e}}class Re extends xe{easeInCore(e){return e*e*e*e}}class Ie extends xe{easeInCore(e){return e*e*e*e*e}}class Me extends xe{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}class Oe extends xe{constructor(e=0,t=0,i=1,r=1){super(),this.x1=e,this.y1=t,this.x2=i,this.y2=r}easeInCore(e){return ve.vr.Interpolate(e,this.x1,this.y1,this.x2,this.y2)}}var De=i(34493);class we{constructor(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}_clone(){return new we(this.frame,this.action,this.onlyOnce)}}var Ne,Fe=i(7042);!function(e){e[e.NONE=0]="NONE",e[e.STEP=1]="STEP"}(Ne||(Ne={}));var Le,Be=i(888);class Ve{constructor(e){this._path=e,this._onchange=new Array,this.value=0,this.animations=[]}getPoint(){const e=this._path.getPointAtLengthPosition(this.value);return new W.Pq(e.x,0,e.y)}moveAhead(e=.002){return this.move(e),this}moveBack(e=.002){return this.move(-e),this}move(e){if(Math.abs(e)>1)throw"step size should be less than 1.";return this.value+=e,this._ensureLimits(),this._raiseOnChange(),this}_ensureLimits(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this}_raiseOnChange(){return this._onchange.forEach((e=>e(this))),this}onchange(e){return this._onchange.push(e),this}}!function(e){e[e.Include=0]="Include",e[e.Exclude=1]="Exclude"}(Le||(Le={}));class ke{constructor(e,t=0){this.mode=t,this.disabled=!1,this._targetNames=new Set,e&&this.addTargetName(e)}addTargetName(e){if(Array.isArray(e))for(const t of e)this._targetNames.add(t);else this._targetNames.add(e)}removeTargetName(e){if(Array.isArray(e))for(const t of e)this._targetNames.delete(t);else this._targetNames.delete(e)}hasTarget(e){return this._targetNames.has(e)}retainsTarget(e){return this._targetNames.has(e)===(0===this.mode)}}var Ue=i(9723),Ge=i(84015);function ze(e,t,i){try{const r=e.next();r.done?t(r):r.value?r.value.then((()=>{r.value=void 0,t(r)}),i):t(r)}catch(e){i(e)}}function We(e=25){let t;return(i,r,s)=>{const n=performance.now();void 0===t||n-t>e?(t=n,setTimeout((()=>{ze(i,r,s)}),0)):ze(i,r,s)}}function He(e,t,i,r,s){const n=()=>{let o;const a=e=>{e.done?i(e.value):void 0===o?o=!0:n()};do{o=void 0,s&&s.aborted?r(new Error("Aborted")):t(e,a,r),void 0===o&&(o=!1)}while(o)};n()}function Xe(e,t){let i;return He(e,ze,(e=>i=e),(e=>{throw e}),t),i}function qe(e,t,i){return new Promise(((r,s)=>{He(e,t,r,s,i)}))}function Ye(e,t){return(...i)=>Xe(e(...i),t)}function Ke(e,t,i){return(...r)=>qe(e(...r),t,i)}var je=i(15287),$e=i(40220),Qe=i(39464),Ze=i(14747),Je=i(75108),et=i(13093),tt=i(59881),it=i(89518);class rt extends Ze.b{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===rt.PERSPECTIVE_CAMERA)this.fovMode===rt.FOVMODE_VERTICAL_FIXED?(t=2*this.minZ*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=2*this.minZ*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{const i=this.getEngine().getRenderWidth()/2,r=this.getEngine().getRenderHeight()/2;e=(this.orthoRight??i)-(this.orthoLeft??-i),t=(this.orthoTop??r)-(this.orthoBottom??-r)}return e*t}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}get hasMoved(){return this._hasMoved}constructor(e,t,i,r=!0){super(e,i,!1),this._position=W.Pq.Zero(),this._upVector=W.Pq.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=rt.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new et.L(0,0,1,1),this.layerMask=268435455,this.fovMode=rt.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=rt.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new z.cP,this.onProjectionMatrixChangedObservable=new z.cP,this.onAfterCheckInputsObservable=new z.cP,this.onRestoreStateObservable=new z.cP,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new W.uq,this._postProcesses=new Array,this._activeMeshes=new Qe.L(256),this._globalPosition=W.Pq.Zero(),this._computedViewMatrix=W.uq.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=W.uq.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=W.PT.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),r&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}hasStateStored(){return!!this._stateStored}_restoreStateValues(){return!!this._stateStored&&(this.fov=this._storedFov,!0)}restoreState(){return!!this._restoreStateValues()&&(this.onRestoreStateObservable.notifyObservers(this),!0)}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i-1?(Z.V.Error("You're trying to reuse a post process not defined as reusable."),0):(null==t||t<0?this._postProcesses.push(e):null===this._postProcesses[t]?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);-1!==t&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()}getWorldMatrix(){return this._isSynchronizedViewMatrix()||this.getViewMatrix(),this._worldMatrix}_getViewMatrix(){return W.uq.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()||(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,void 0!==e&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;const t=this.getEngine(),i=this.getScene(),r=t.useReverseDepthBuffer;if(this.mode===rt.PERSPECTIVE_CAMERA){let e;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),e=i.useRightHandedSystem?W.uq.PerspectiveFovRHToRef:W.uq.PerspectiveFovLHToRef,e(this.fov,t.getAspectRatio(this),r?this.maxZ:this.minZ,r?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===rt.FOVMODE_VERTICAL_FIXED,t.isNDCHalfZRange,this.projectionPlaneTilt,r)}else{const e=t.getRenderWidth()/2,s=t.getRenderHeight()/2;i.useRightHandedSystem?this.oblique?W.uq.ObliqueOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-s,this.orthoTop??s,r?this.maxZ:this.minZ,r?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):W.uq.OrthoOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-s,this.orthoTop??s,r?this.maxZ:this.minZ,r?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange):this.oblique?W.uq.ObliqueOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-s,this.orthoTop??s,r?this.maxZ:this.minZ,r?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):W.uq.OrthoOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-s,this.orthoTop??s,r?this.maxZ:this.minZ,r?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=this.oblique?.angle,this._cache.obliqueLength=this.oblique?.length,this._cache.obliqueOffset=this.oblique?.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){return(this.radius||(this.target?W.Pq.Distance(this.position,this.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?tt.P.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=tt.P.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let t=!1;return this.rigCameras.forEach((i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)})),t}return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw(0,Je.n)("Ray")}getForwardRayToRef(e,t=100,i,r){throw(0,Je.n)("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 e=this._rigCameras.pop();e&&e.dispose()}if(this._parentContainer){const e=this._parentContainer.cameras.indexOf(this);e>-1&&this._parentContainer.cameras.splice(e,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==rt.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let e=this._postProcesses.length;for(;--e>=0;){const t=this._postProcesses[e];t&&t.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 e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=Ue.S0.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==rt.RIG_MODE_NONE){const e=this.createRigCamera(this.name+"_L",0);e&&(e._isLeftCamera=!0);const t=this.createRigCamera(this.name+"_R",1);t&&(t._isRightCamera=!0),e&&t&&(this._rigCameras.push(e),this._rigCameras.push(t))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return W.uq.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,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=Ue.S0.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;ert._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,r=rt.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),s=it.p.Parse(r,e,t);if(void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),s.inputs&&(s.inputs.parse(e),s._setupInputs()),e.upVector&&(s.upVector=W.Pq.FromArray(e.upVector)),s.setPosition&&(s.position.copyFromFloats(0,0,0),s.setPosition(W.Pq.FromArray(e.position))),e.target&&s.setTarget&&s.setTarget(W.Pq.FromArray(e.target)),e.cameraRigMode){const t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};s.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;t{throw(0,Je.n)("UniversalCamera")},rt.PERSPECTIVE_CAMERA=0,rt.ORTHOGRAPHIC_CAMERA=1,rt.FOVMODE_VERTICAL_FIXED=0,rt.FOVMODE_HORIZONTAL_FIXED=1,rt.RIG_MODE_NONE=0,rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,rt.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,rt.RIG_MODE_STEREOSCOPIC_INTERLACED=14,rt.RIG_MODE_VR=20,rt.RIG_MODE_CUSTOM=22,rt.ForceAttachControlToAlwaysPreventDefault=!1,(0,je.Cg)([(0,$e.P_)("position")],rt.prototype,"_position",void 0),(0,je.Cg)([(0,$e.P_)("upVector")],rt.prototype,"_upVector",void 0),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"orthoLeft",null),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"orthoRight",null),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"orthoBottom",null),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"orthoTop",null),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"fov",void 0),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"projectionPlaneTilt",void 0),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"minZ",void 0),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"maxZ",void 0),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"inertia",void 0),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"mode",null),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"layerMask",void 0),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"fovMode",void 0),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"cameraRigMode",void 0),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"interaxialDistance",void 0),(0,je.Cg)([(0,$e.lK)()],rt.prototype,"isStereoscopicSideBySide",void 0);var st=i(12721),nt=i(14914);class ot{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}var at=i(34130),lt=i(34910);class ht{constructor(e,t,i){this.vectors=(0,at.mI)(8,W.Pq.Zero),this.center=W.Pq.Zero(),this.centerWorld=W.Pq.Zero(),this.extendSize=W.Pq.Zero(),this.extendSizeWorld=W.Pq.Zero(),this.directions=(0,at.mI)(3,W.Pq.Zero),this.vectorsWorld=(0,at.mI)(8,W.Pq.Zero),this.minimumWorld=W.Pq.Zero(),this.maximumWorld=W.Pq.Zero(),this.minimum=W.Pq.Zero(),this.maximum=W.Pq.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const r=e.x,s=e.y,n=e.z,o=t.x,a=t.y,l=t.z,h=this.vectors;this.minimum.copyFromFloats(r,s,n),this.maximum.copyFromFloats(o,a,l),h[0].copyFromFloats(r,s,n),h[1].copyFromFloats(o,a,l),h[2].copyFromFloats(o,s,n),h[3].copyFromFloats(r,a,n),h[4].copyFromFloats(r,s,l),h[5].copyFromFloats(o,a,n),h[6].copyFromFloats(r,a,l),h[7].copyFromFloats(o,s,l),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||W.uq.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=ht._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),r=i.length();i.normalizeFromLength(r);const s=r*e,n=i.scaleInPlace(.5*s),o=this.center.subtractToRef(n,t[1]),a=this.center.addToRef(n,t[2]);return this.reConstruct(o,a,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,r=this.directions,s=this.vectorsWorld,n=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)s[e].copyFrom(n[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let r=0;r<8;++r){const o=s[r];W.Pq.TransformCoordinatesToRef(n[r],e,o),t.minimizeInPlace(o),i.maximizeInPlace(o)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}W.Pq.FromArrayToRef(e.m,0,r[0]),W.Pq.FromArrayToRef(e.m,4,r[1]),W.Pq.FromArrayToRef(e.m,8,r[2]),this._worldMatrix=e}isInFrustum(e){return ht.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return ht.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,r=t.x,s=t.y,n=t.z,o=i.x,a=i.y,l=i.z,h=e.x,c=e.y,u=e.z,d=-lt.bH;return!(o-hh-r||a-cc-s||l-uu-n)}intersectsSphere(e){return ht.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,r=this.maximumWorld,s=i.x,n=i.y,o=i.z,a=r.x,l=r.y,h=r.z,c=e.x,u=e.y,d=e.z,f=t.x,p=t.y,_=t.z;return!(af||lp||h_)}dispose(){this._drawWrapperFront?.dispose(),this._drawWrapperBack?.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,r){const s=ht._TmpVector3[0];return W.Pq.ClampToRef(i,e,t,s),W.Pq.DistanceSquared(i,s)<=r*r}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const r=t[i];for(let t=0;t<8;++t)if(r.dotCoordinate(e[t])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let r=!0;const s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])>=0){r=!1;break}if(r)return!1}return!0}}ht._TmpVector3=(0,at.mI)(3,W.Pq.Zero);class ct{constructor(e,t,i){this.center=W.Pq.Zero(),this.centerWorld=W.Pq.Zero(),this.minimum=W.Pq.Zero(),this.maximum=W.Pq.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const r=W.Pq.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*r,this._update(i||W.uq.IdentityReadOnly)}scale(e){const t=this.radius*e,i=ct._TmpVector3,r=i[0].setAll(t),s=this.center.subtractToRef(r,i[1]),n=this.center.addToRef(r,i[2]);return this.reConstruct(s,n,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{W.Pq.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=ct._TmpVector3[0];W.Pq.TransformNormalFromFloatsToRef(1,1,1,e,t),this.radiusWorld=Math.max(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z))*this.radius}}isInFrustum(e){const t=this.centerWorld,i=this.radiusWorld;for(let r=0;r<6;r++)if(e[r].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){const t=this.centerWorld;for(let i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0}intersectsPoint(e){const t=W.Pq.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const r=W.Pq.Dot(t.centerWorld,e),s=Math.abs(W.Pq.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(W.Pq.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(W.Pq.Dot(t.directions[2],e))*t.extendSize.z;i.min=r-s,i.max=r+s},pt=(e,t,i)=>(ft(e,t,ut),ft(e,i,dt),!(ut.min>dt.max||dt.min>ut.max));class _t{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new ht(e,t,i),this.boundingSphere=new ct(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=_t._TmpVector3[0].copyFrom(e).subtractInPlace(t),r=_t._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=W.Pq.Minimize(this.minimum,e),i=W.Pq.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=W.AA.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=W.AA.Vector3[0];return W.Pq.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),W.Pq.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!(2!==t&&3!==t||!this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(!(1!==t&&3!==t)||this.boundingBox.isInFrustum(e))}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,_t._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(!ct.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!ht.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,r=e.boundingBox;return!!(pt(i.directions[0],i,r)&&pt(i.directions[1],i,r)&&pt(i.directions[2],i,r)&&pt(r.directions[0],i,r)&&pt(r.directions[1],i,r)&&pt(r.directions[2],i,r)&&pt(W.Pq.Cross(i.directions[0],r.directions[0]),i,r)&&pt(W.Pq.Cross(i.directions[0],r.directions[1]),i,r)&&pt(W.Pq.Cross(i.directions[0],r.directions[2]),i,r)&&pt(W.Pq.Cross(i.directions[1],r.directions[0]),i,r)&&pt(W.Pq.Cross(i.directions[1],r.directions[1]),i,r)&&pt(W.Pq.Cross(i.directions[1],r.directions[2]),i,r)&&pt(W.Pq.Cross(i.directions[2],r.directions[0]),i,r)&&pt(W.Pq.Cross(i.directions[2],r.directions[1]),i,r)&&pt(W.Pq.Cross(i.directions[2],r.directions[2]),i,r))}}_t._TmpVector3=(0,at.mI)(2,W.Pq.Zero);var mt=i(890),gt=i(15311);class vt{get materialDefines(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:this._getDrawWrapper()?.defines}set materialDefines(e){(this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)).defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new gt.E(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){t&&this._drawWrappers[e]?.dispose(),this._drawWrappers[e]=void 0}get effect(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:this._getDrawWrapper()?.effect??null}get _drawWrapper(){return this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,r=!0){const s=this._drawWrapper;s.setEffect(e,t,r),void 0!==i&&(s.materialContext=i),e||(s.defines=null,s.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e)return void this._removeDrawWrapper(e);for(const e of this._drawWrappers)e?.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,r,s,n,o,a=!0){return new vt(e,t,i,r,s,n,o,a)}constructor(e,t,i,r,s,n,o,a=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=r,this.indexCount=s,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=n,this._renderingMesh=o||n,l&&n.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=n.subMeshes.length-1,a&&(this.refreshBoundingInfo(),n.computeWorldMatrix(!0))}get IsGlobal(){return 0===this.verticesStart&&this.verticesCount===this._mesh.getTotalVertices()&&0===this.indexStart&&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(){return(this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null)||this._renderingMesh}getMaterial(e=!0){const t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)??this._renderingMesh.material;if(!t)return e?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(t)){const e=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==e&&(this._currentMaterial=e,this.resetDrawCache()),e}return t}_isMultiMaterial(e){return void 0!==e.getSubMaterial}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(st.R.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;const t=this._renderingMesh.getIndices();let i;if(0===this.indexStart&&this.indexCount===t.length){const e=this._renderingMesh.getBoundingInfo();i={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else i=(0,mt.cD)(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new _t(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)}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isCompletelyInFrustum(e)}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 t=this.indexStart;ta&&(a=t)}return new vt(e,o,a-o+1,t,i,r,s,n)}}class xt{}class bt{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=Ye(this._applyToCoroutine.bind(this)),this.uniqueId=bt._UniqueIDGenerator,bt._UniqueIDGenerator++}set(e,t){switch(e.length||Z.V.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case st.R.PositionKind:this.positions=e;break;case st.R.NormalKind:this.normals=e;break;case st.R.TangentKind:this.tangents=e;break;case st.R.UVKind:this.uvs=e;break;case st.R.UV2Kind:this.uvs2=e;break;case st.R.UV3Kind:this.uvs3=e;break;case st.R.UV4Kind:this.uvs4=e;break;case st.R.UV5Kind:this.uvs5=e;break;case st.R.UV6Kind:this.uvs6=e;break;case st.R.ColorKind:this.colors=e;break;case st.R.MatricesIndicesKind:this.matricesIndices=e;break;case st.R.MatricesWeightsKind:this.matricesWeights=e;break;case st.R.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case st.R.MatricesWeightsExtraKind:this.matricesWeightsExtra=e}}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(st.R.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(st.R.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(st.R.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(st.R.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(st.R.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(st.R.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(st.R.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(st.R.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(st.R.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(st.R.ColorKind,this.colors,t),this.hasVertexAlpha&&void 0!==e.hasVertexAlpha&&(e.hasVertexAlpha=!0),i&&(yield)),this.matricesIndices&&(e.setVerticesData(st.R.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(st.R.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(st.R.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(st.R.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 t=e;t.subMeshes=[];for(const e of this.materialInfos)new vt(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,t)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(st.R.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(st.R.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(st.R.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(st.R.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(st.R.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(st.R.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(st.R.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(st.R.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(st.R.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(st.R.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(st.R.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(st.R.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(st.R.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(st.R.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,r=e.length){const s=W.AA.Vector3[0],n=W.AA.Vector3[1];for(let o=i;o({vertexData:e}))):[{vertexData:e}];return Xe(this._mergeCoroutine(void 0,n,t,!1,i,r,s))}*_mergeCoroutine(e,t,i=!1,r,s,n=!1,o=!1){this._validate();let a=t.map((e=>e.vertexData)),l=this;if(o)for(const e of a)e&&(e._validate(),!this.normals&&e.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&e.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&e.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&e.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&e.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&e.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&e.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&e.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&e.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&e.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&e.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&e.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&e.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const e of a)if(e)if(o)this.normals&&!e.normals&&(e.normals=new Float32Array(e.positions.length)),this.tangents&&!e.tangents&&(e.tangents=new Float32Array(e.positions.length/3*4)),this.uvs&&!e.uvs&&(e.uvs=new Float32Array(e.positions.length/3*2)),this.uvs2&&!e.uvs2&&(e.uvs2=new Float32Array(e.positions.length/3*2)),this.uvs3&&!e.uvs3&&(e.uvs3=new Float32Array(e.positions.length/3*2)),this.uvs4&&!e.uvs4&&(e.uvs4=new Float32Array(e.positions.length/3*2)),this.uvs5&&!e.uvs5&&(e.uvs5=new Float32Array(e.positions.length/3*2)),this.uvs6&&!e.uvs6&&(e.uvs6=new Float32Array(e.positions.length/3*2)),this.colors&&!e.colors&&(e.colors=new Float32Array(e.positions.length/3*4),e.colors.fill(1)),this.matricesIndices&&!e.matricesIndices&&(e.matricesIndices=new Float32Array(e.positions.length/3*4)),this.matricesWeights&&!e.matricesWeights&&(e.matricesWeights=new Float32Array(e.positions.length/3*4)),this.matricesIndicesExtra&&!e.matricesIndicesExtra&&(e.matricesIndicesExtra=new Float32Array(e.positions.length/3*4)),this.matricesWeightsExtra&&!e.matricesWeightsExtra&&(e.matricesWeightsExtra=new Float32Array(e.positions.length/3*4));else if(e._validate(),!this.normals!=!e.normals||!this.tangents!=!e.tangents||!this.uvs!=!e.uvs||!this.uvs2!=!e.uvs2||!this.uvs3!=!e.uvs3||!this.uvs4!=!e.uvs4||!this.uvs5!=!e.uvs5||!this.uvs6!=!e.uvs6||!this.colors!=!e.colors||!this.matricesIndices!=!e.matricesIndices||!this.matricesWeights!=!e.matricesWeights||!this.matricesIndicesExtra!=!e.matricesIndicesExtra||!this.matricesWeightsExtra!=!e.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes");if(n){let i=0,r=0,s=0;const n=[];let o=null;const h=[];for(const t of this.splitBasedOnMaterialID())h.push({vertexData:t,transform:e});for(const e of t)if(e.vertexData)for(const t of e.vertexData.splitBasedOnMaterialID())h.push({vertexData:t,transform:e.transform});h.sort(((e,t)=>{const i=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,r=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return i>r?1:i===r?0:-1}));for(const e of h){const t=e.vertexData;if(i=t.materialInfos?t.materialInfos[0].materialIndex:0,o&&o.materialIndex===i)o.indexCount+=t.indices.length,o.verticesCount+=t.positions.length/3;else{const e=new xt;e.materialIndex=i,e.indexStart=r,e.indexCount=t.indices.length,e.verticesStart=s,e.verticesCount=t.positions.length/3,n.push(e),o=e}r+=t.indices.length,s+=t.positions.length/3}const c=h.splice(0,1)[0];l=c.vertexData,e=c.transform,a=h.map((e=>e.vertexData)),t=h,this.materialInfos=n}const h=a.reduce(((e,t)=>e+(t.indices?.length??0)),l.indices?.length??0);let c=s||a.some((e=>e.indices===l.indices))?l.indices?.slice():l.indices;if(h>0){let s=c?.length??0;if(c||(c=new Array(h)),c.length!==h){if(Array.isArray(c))c.length=h;else{const e=i||c instanceof Uint32Array?new Uint32Array(h):new Uint16Array(h);e.set(c),c=e}e&&e.determinant()<0&&bt._FlipFaces(c,0,s)}let n=l.positions?l.positions.length/3:0;for(const{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;t[e.vertexData.positions,e.transform]))),r&&(yield),l.normals&&(this.normals=bt._MergeElement(st.R.NormalKind,l.normals,e,t.map((e=>[e.vertexData.normals,e.transform]))),r&&(yield)),l.tangents&&(this.tangents=bt._MergeElement(st.R.TangentKind,l.tangents,e,t.map((e=>[e.vertexData.tangents,e.transform]))),r&&(yield)),l.uvs&&(this.uvs=bt._MergeElement(st.R.UVKind,l.uvs,e,t.map((e=>[e.vertexData.uvs,e.transform]))),r&&(yield)),l.uvs2&&(this.uvs2=bt._MergeElement(st.R.UV2Kind,l.uvs2,e,t.map((e=>[e.vertexData.uvs2,e.transform]))),r&&(yield)),l.uvs3&&(this.uvs3=bt._MergeElement(st.R.UV3Kind,l.uvs3,e,t.map((e=>[e.vertexData.uvs3,e.transform]))),r&&(yield)),l.uvs4&&(this.uvs4=bt._MergeElement(st.R.UV4Kind,l.uvs4,e,t.map((e=>[e.vertexData.uvs4,e.transform]))),r&&(yield)),l.uvs5&&(this.uvs5=bt._MergeElement(st.R.UV5Kind,l.uvs5,e,t.map((e=>[e.vertexData.uvs5,e.transform]))),r&&(yield)),l.uvs6&&(this.uvs6=bt._MergeElement(st.R.UV6Kind,l.uvs6,e,t.map((e=>[e.vertexData.uvs6,e.transform]))),r&&(yield)),l.colors&&(this.colors=bt._MergeElement(st.R.ColorKind,l.colors,e,t.map((e=>[e.vertexData.colors,e.transform]))),(void 0!==l.hasVertexAlpha||t.some((e=>void 0!==e.vertexData.hasVertexAlpha)))&&(this.hasVertexAlpha=l.hasVertexAlpha||t.some((e=>e.vertexData.hasVertexAlpha))),r&&(yield)),l.matricesIndices&&(this.matricesIndices=bt._MergeElement(st.R.MatricesIndicesKind,l.matricesIndices,e,t.map((e=>[e.vertexData.matricesIndices,e.transform]))),r&&(yield)),l.matricesWeights&&(this.matricesWeights=bt._MergeElement(st.R.MatricesWeightsKind,l.matricesWeights,e,t.map((e=>[e.vertexData.matricesWeights,e.transform]))),r&&(yield)),l.matricesIndicesExtra&&(this.matricesIndicesExtra=bt._MergeElement(st.R.MatricesIndicesExtraKind,l.matricesIndicesExtra,e,t.map((e=>[e.vertexData.matricesIndicesExtra,e.transform]))),r&&(yield)),l.matricesWeightsExtra&&(this.matricesWeightsExtra=bt._MergeElement(st.R.MatricesWeightsExtraKind,l.matricesWeightsExtra,e,t.map((e=>[e.vertexData.matricesWeightsExtra,e.transform])))),this}static _MergeElement(e,t,i,r){const s=r.filter((e=>null!==e[0]&&void 0!==e[0]));if(!t&&0==s.length)return t;if(!t)return this._MergeElement(e,s[0][0],s[0][1],s.slice(1));const n=s.reduce(((e,t)=>e+t[0].length),t.length),o=e===st.R.PositionKind?bt._TransformVector3Coordinates:e===st.R.NormalKind?bt._TransformVector3Normals:e===st.R.TangentKind?bt._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const e=new Float32Array(n);e.set(t),i&&o(e,i,0,t.length);let r=t.length;for(const[t,i]of s)e.set(t,r),i&&o(e,i,r,t.length),r+=t.length;return e}{const e=new Array(n);for(let i=0;i{const i=st.R.DeduceStride(e);if(t.length%i!=0)throw new Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},t=e(st.R.PositionKind,this.positions),i=(i,r)=>{const s=e(i,r);if(s!==t)throw new Error("The "+i+"s element count ("+s+") does not match the positions count ("+t+")")};this.normals&&i(st.R.NormalKind,this.normals),this.tangents&&i(st.R.TangentKind,this.tangents),this.uvs&&i(st.R.UVKind,this.uvs),this.uvs2&&i(st.R.UV2Kind,this.uvs2),this.uvs3&&i(st.R.UV3Kind,this.uvs3),this.uvs4&&i(st.R.UV4Kind,this.uvs4),this.uvs5&&i(st.R.UV5Kind,this.uvs5),this.uvs6&&i(st.R.UV6Kind,this.uvs6),this.colors&&i(st.R.ColorKind,this.colors),this.matricesIndices&&i(st.R.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(st.R.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(st.R.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(st.R.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return bt.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 bt._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return bt._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const r=new bt;if(e.isVerticesDataPresent(st.R.PositionKind)&&(r.positions=e.getVerticesData(st.R.PositionKind,t,i)),e.isVerticesDataPresent(st.R.NormalKind)&&(r.normals=e.getVerticesData(st.R.NormalKind,t,i)),e.isVerticesDataPresent(st.R.TangentKind)&&(r.tangents=e.getVerticesData(st.R.TangentKind,t,i)),e.isVerticesDataPresent(st.R.UVKind)&&(r.uvs=e.getVerticesData(st.R.UVKind,t,i)),e.isVerticesDataPresent(st.R.UV2Kind)&&(r.uvs2=e.getVerticesData(st.R.UV2Kind,t,i)),e.isVerticesDataPresent(st.R.UV3Kind)&&(r.uvs3=e.getVerticesData(st.R.UV3Kind,t,i)),e.isVerticesDataPresent(st.R.UV4Kind)&&(r.uvs4=e.getVerticesData(st.R.UV4Kind,t,i)),e.isVerticesDataPresent(st.R.UV5Kind)&&(r.uvs5=e.getVerticesData(st.R.UV5Kind,t,i)),e.isVerticesDataPresent(st.R.UV6Kind)&&(r.uvs6=e.getVerticesData(st.R.UV6Kind,t,i)),e.isVerticesDataPresent(st.R.ColorKind)){const s=e.geometry||e,n=s.getVertexBuffer(st.R.ColorKind),o=s.getVerticesData(st.R.ColorKind,t,i);if(3===n.getSize()){const e=new Float32Array(4*o.length/3);for(let t=0,i=0;t!Array.isArray(e)))],bt,"_TransformVector3Coordinates",null),(0,je.Cg)([$e.Cx.filter(((...[e])=>!Array.isArray(e)))],bt,"_TransformVector3Normals",null),(0,je.Cg)([$e.Cx.filter(((...[e])=>!Array.isArray(e)))],bt,"_TransformVector4Normals",null),(0,je.Cg)([$e.Cx.filter(((...[e])=>!Array.isArray(e)))],bt,"_FlipFaces",null);class St{static get ForceFullSceneLoadingForIncremental(){return St._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){St._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return St._ShowLoadingScreen}static set ShowLoadingScreen(e){St._ShowLoadingScreen=e}static get loggingLevel(){return St._LoggingLevel}static set loggingLevel(e){St._LoggingLevel=e}static get CleanBoneMatrixWeights(){return St._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){St._CleanBoneMatrixWeights=e}}St._ForceFullSceneLoadingForIncremental=!1,St._ShowLoadingScreen=!0,St._CleanBoneMatrixWeights=!1,St._LoggingLevel=0;var Tt=i(75174);function Ct(e,t,i,r,s,n,o,a){const l=t*st.R.GetTypeByteLength(i),h=o*t;if(a.length!==h)throw new Error("Output length is not valid");if(i===st.R.FLOAT&&s===l)if(e instanceof Array){const t=r/4;a.set(e,t)}else if(e instanceof ArrayBuffer){const t=new Float32Array(e,r,h);a.set(t)}else{const t=e.byteOffset+r;if(t%4)return Z.V.Warn("CopyFloatData: copied misaligned data."),void a.set(new Float32Array(e.buffer.slice(t,t+4*h)));const i=new Float32Array(e.buffer,t,h);a.set(i)}else st.R.ForEach(e,r,s,t,i,h,n,((e,t)=>a[t]=e))}class yt{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 yt(yt.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,r=!1,s=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||he.q.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=r,i?this.setAllVerticesData(i,r):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),s&&(this.applyToMesh(s),s.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e{e._rebuild()}))}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,r){i&&Array.isArray(t)&&(t=new Float32Array(t));const s=new st.R(this._engine,t,e,{updatable:i,postponeInternalCreation:0===this._meshes.length,stride:r,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(s)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){const r=e.getKind();this._vertexBuffers[r]&&i&&this._vertexBuffers[r].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[r]=e;const s=this._meshes,n=s.length;if(r===st.R.PositionKind){this._totalVertices=t??e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const i=this._extend&&this._extend.minimum||new W.Pq(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),r=this._extend&&this._extend.maximum||new W.Pq(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let e=0;e65535);for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1,r=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),null!=t&&(this._totalVertices=t);for(const e of this._meshes)e._createGlobalSubMesh(!r),e.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?void 0!==this._totalIndices?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;const i=this._indices;return t||e&&1!==this._meshes.length?i.slice():i}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){e&&this._vertexArrayObjects&&this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){const i=this._meshes,r=i.indexOf(e);-1!==r&&(i.splice(r,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,0===i.length&&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(st.R.PositionKind)))return;this._extend=(0,mt.b8)(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){const t=this._meshes.length;for(const i in this._vertexBuffers)1===t&&this._vertexBuffers[i].create(),i===st.R.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());1===t&&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 e of this._meshes)e._markSubMeshesAsAttributesDirty()}load(e,t){2!==this.delayLoadState&&(this.isReady()?t&&t():(this.delayLoadState=2,this._queueLoad(e,t)))}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,(i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);const r=this._meshes,s=r.length;for(let e=0;e0){for(let t=0;t0){for(let e=0;e0){for(let e=0;e-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new bt;t.indices=[];const i=this.getIndices();if(i)for(let e=0;e0){const r=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(st.R.PositionKind,r,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){const r=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(st.R.NormalKind,r,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){const r=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(st.R.TangentKind,r,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){const r=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(Tt.rX)for(let e=1;e0){const r=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(Tt.rX)for(let e=1;e0){const r=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(Tt.rX)for(let e=1;e0){const r=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(Tt.rX)for(let e=1;e0){const r=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(Tt.rX)for(let e=1;e0){const r=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(Tt.rX)for(let e=1;e0){const r=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(st.R.ColorKind,r,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){const r=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),s=[];for(let e=0;e>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(st.R.MatricesIndicesKind,s,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){const r=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),s=[];for(let e=0;e>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(st.R.MatricesIndicesExtraKind,s,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){const r=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(st.R.MatricesWeightsKind,r,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){const r=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(r,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){const r=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e>8),i.push((16711680&r)>>16),i.push(r>>24&255)}t.setVerticesData(st.R.MatricesIndicesKind,i,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(st.R.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const i=[];for(let t=0;t>8),i.push((16711680&r)>>16),i.push(r>>24&255)}t.setVerticesData(st.R.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(yt._CleanMatricesWeights(e,t),t.setVerticesData(st.R.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(st.R.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i-1))return;{const i=t.getScene().getLastSkeletonById(e.skeletonId);if(!i)return;r=i.bones.length}const s=t.getVerticesData(st.R.MatricesIndicesKind),n=t.getVerticesData(st.R.MatricesIndicesExtraKind),o=e.matricesWeights,a=e.matricesWeightsExtra,l=e.numBoneInfluencer,h=o.length;for(let e=0;el-1)&&(h=l-1),t>i){const i=1/t;for(let t=0;t<4;t++)o[e+t]*=i;if(a)for(let t=0;t<4;t++)a[e+t]*=i}else h>=4?(a[e+h-4]=1-t,n[e+h-4]=r):(o[e+h]=1-t,s[e+h]=r)}t.setVerticesData(st.R.MatricesIndicesKind,s),e.matricesWeightsExtra&&t.setVerticesData(st.R.MatricesIndicesExtraKind,n)}static Parse(e,t,i){const r=new yt(e.id,t,void 0,e.updatable);return r._loadedUniqueId=e.uniqueId,Ge.Y&&Ge.Y.AddTagsTo(r,e.tags),e.delayLoadingFile?(r.delayLoadState=4,r.delayLoadingFile=i+e.delayLoadingFile,r._boundingInfo=new _t(W.Pq.FromArray(e.boundingBoxMinimum),W.Pq.FromArray(e.boundingBoxMaximum)),r._delayInfo=[],e.hasUVs&&r._delayInfo.push(st.R.UVKind),e.hasUVs2&&r._delayInfo.push(st.R.UV2Kind),e.hasUVs3&&r._delayInfo.push(st.R.UV3Kind),e.hasUVs4&&r._delayInfo.push(st.R.UV4Kind),e.hasUVs5&&r._delayInfo.push(st.R.UV5Kind),e.hasUVs6&&r._delayInfo.push(st.R.UV6Kind),e.hasColors&&r._delayInfo.push(st.R.ColorKind),e.hasMatricesIndices&&r._delayInfo.push(st.R.MatricesIndicesKind),e.hasMatricesWeights&&r._delayInfo.push(st.R.MatricesWeightsKind),r._delayLoadingFunction=bt.ImportVertexData):bt.ImportVertexData(e,r),t.pushGeometry(r,!0),r}}const Et=W.uq.Compose(W.Pq.One(),W.PT.FromEulerAngles(0,Math.PI,0),W.Pq.Zero());class Pt extends Ze.b{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=!!(this._billboardMode&Pt.BILLBOARDMODE_USE_POSITION),this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==Pt.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t,!1),this._forward=new W.Pq(0,0,1),this._up=new W.Pq(0,1,0),this._right=new W.Pq(1,0,0),this._position=W.Pq.Zero(),this._rotation=W.Pq.Zero(),this._rotationQuaternion=null,this._scaling=W.Pq.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=Pt.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=W.uq.Zero(),this._usePivotMatrix=!1,this._absolutePosition=W.Pq.Zero(),this._absoluteScaling=W.Pq.Zero(),this._absoluteRotationQuaternion=W.PT.Identity(),this._pivotMatrix=W.uq.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new z.cP,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._markAsDirtyInternal()}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._markAsDirtyInternal()}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._markAsDirtyInternal()}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._markAsDirtyInternal()}_markAsDirtyInternal(){this._isDirty||(this._isDirty=!0,this.customMarkAsDirty&&this.customMarkAsDirty())}get forward(){return W.Pq.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return W.Pq.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return W.Pq.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=W.uq.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==Pt.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=W.uq.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const r=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);r&&i&&i(this,r);for(const e of this.getChildTransformNodes(!0))e.instantiateHierarchy(r,t,i);return r}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||W.PT.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this}unfreezeWorldMatrix(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this}get isWorldMatrixFrozen(){return this._isWorldMatrixFrozen}getAbsolutePosition(){return this.computeWorldMatrix(),this._absolutePosition}setAbsolutePosition(e){if(!e)return this;let t,i,r;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],r=arguments[2]}else t=e.x,i=e.y,r=e.z;if(this.parent){const e=W.AA.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),W.Pq.TransformCoordinatesFromFloatsToRef(t,i,r,e,this.position)}else this.position.x=t,this.position.y=i,this.position.z=r;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=W.Pq.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=W.AA.Matrix[0];return this._localMatrix.invertToRef(e),W.Pq.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=W.Pq.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,r=0,s=0){const n=Pt._LookAtVectorCache,o=0===s?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,n),this.setDirection(n,t,i,r),1===s&&this.parent)if(this.rotationQuaternion){const e=W.AA.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);const t=W.AA.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{const e=W.AA.Quaternion[0];W.PT.FromEulerVectorToRef(this.rotation,e);const t=W.AA.Matrix[0];e.toRotationMatrix(t);const i=W.AA.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(i),i.invert(),t.multiplyToRef(i,t),e.fromRotationMatrix(t),e.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=W.Pq.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return W.Pq.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,r=0){const s=-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?W.PT.RotationYawPitchRollToRef(s+t,o+i,r,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=s+t,this.rotation.z=r),this}setPivotPoint(e,t=0){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(1==t){const t=W.AA.Matrix[0];i.invertToRef(t),e=W.Pq.TransformCoordinates(e,t)}return this.setPivotMatrix(W.uq.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=W.Pq.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=W.Pq.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),W.Pq.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(const t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;const r=W.AA.Quaternion[0],s=W.AA.Vector3[0],n=W.AA.Vector3[1],o=W.AA.Matrix[1];W.uq.IdentityToRef(o);const a=W.AA.Matrix[0];this.computeWorldMatrix(!0);let l=this.rotationQuaternion;return l||(l=Pt._TmpRotation,W.PT.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),W.uq.ComposeToRef(this.scaling,l,this.position,a),this.parent&&a.multiplyToRef(this.parent.computeWorldMatrix(!0),a),e&&(e.computeWorldMatrix(!0).invertToRef(o),a.multiplyToRef(o,a)),a.decompose(n,r,s,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(r):r.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(s),this.parent=e,i&&this.setPivotMatrix(W.uq.Identity()),this}addChild(e,t=!1){return e.setParent(this,t),this}removeChild(e,t=!1){return e.setParent(null,t),this}get nonUniformScaling(){return this._nonUniformScaling}_updateNonUniformScalingState(e){return this._nonUniformScaling!==e&&(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,this.parent=e?this._currentParentWhenAttachingToBone:null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){let r;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&0!==i){if(this.parent){const i=this.parent.getWorldMatrix(),r=W.AA.Matrix[0];i.invertToRef(r),e=W.Pq.TransformNormal(e,r),i.determinant()<0&&(t*=-1)}r=W.PT.RotationAxisToRef(e,t,Pt._RotationAxisCache),r.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else r=W.PT.RotationAxisToRef(e,t,Pt._RotationAxisCache),this.rotationQuaternion.multiplyToRef(r,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=W.PT.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const r=W.AA.Vector3[0],s=W.AA.Vector3[1],n=W.AA.Vector3[2],o=W.AA.Quaternion[0],a=W.AA.Matrix[0],l=W.AA.Matrix[1],h=W.AA.Matrix[2],c=W.AA.Matrix[3];return e.subtractToRef(this.position,r),W.uq.TranslationToRef(r.x,r.y,r.z,a),W.uq.TranslationToRef(-r.x,-r.y,-r.z,l),W.uq.RotationAxisToRef(t,i,h),l.multiplyToRef(h,c),c.multiplyToRef(a,c),c.decompose(s,o,n),this.position.addInPlace(n),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const r=e.scale(t);if(i&&0!==i)this.setAbsolutePosition(this.getAbsolutePosition().add(r));else{const e=this.getPositionExpressedInLocalSpace().add(r);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let r;this.rotationQuaternion?r=this.rotationQuaternion:(r=W.AA.Quaternion[1],W.PT.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,r));const s=W.AA.Quaternion[0];return W.PT.RotationYawPitchRollToRef(t,e,i,s),r.multiplyInPlace(s),this.rotationQuaternion||r.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==Pt.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();const r=this._cache;r.pivotMatrixUpdated=!1,r.billboardMode=this.billboardMode,r.infiniteDistance=this.infiniteDistance,r.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;const s=this._getEffectiveParent(),n=Pt._TmpScaling;let o,a=this._position;if(this._infiniteDistance&&!this.parent&&t){const e=t.getWorldMatrix(),i=new W.Pq(e.m[12],e.m[13],e.m[14]);a=Pt._TmpTranslation,a.copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(n.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,o=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(W.PT.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(o=Pt._TmpRotation,W.PT.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,o)),this._usePivotMatrix){const e=W.AA.Matrix[1];W.uq.ScalingToRef(n.x,n.y,n.z,e);const t=W.AA.Matrix[0];o.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,W.AA.Matrix[4]),W.AA.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(a.x,a.y,a.z)}else W.uq.ComposeToRef(n,o,a,this._localMatrix);if(s&&s.getWorldMatrix){if(e&&s.computeWorldMatrix(e),r.useBillboardPath){if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),W.AA.Matrix[7])}else W.AA.Matrix[7].copyFrom(s.getWorldMatrix());const e=W.AA.Vector3[5],t=W.AA.Vector3[6],i=W.AA.Quaternion[0];W.AA.Matrix[7].decompose(t,i,e),W.uq.ScalingToRef(t.x,t.y,t.z,W.AA.Matrix[7]),W.AA.Matrix[7].setTranslation(e),Pt.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(W.AA.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),W.AA.Matrix[6]),W.AA.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(s.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(r.useBillboardPath&&t&&this.billboardMode&&!r.useBillboardPosition){const e=W.AA.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),W.AA.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&W.AA.Matrix[1].multiplyToRef(Et,W.AA.Matrix[1]),W.AA.Matrix[1].setTranslationFromFloats(0,0,0),W.AA.Matrix[1].invertToRef(W.AA.Matrix[0]),(this.billboardMode&Pt.BILLBOARDMODE_ALL)!==Pt.BILLBOARDMODE_ALL){W.AA.Matrix[0].decompose(void 0,W.AA.Quaternion[0],void 0);const e=W.AA.Vector3[1];W.AA.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&Pt.BILLBOARDMODE_X)!==Pt.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&Pt.BILLBOARDMODE_Y)!==Pt.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&Pt.BILLBOARDMODE_Z)!==Pt.BILLBOARDMODE_Z&&(e.z=0),W.uq.RotationYawPitchRollToRef(e.y,e.x,e.z,W.AA.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(W.AA.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(W.AA.Vector3[0])}else if(r.useBillboardPath&&t&&r.useBillboardPosition){const e=W.AA.Vector3[0];this._worldMatrix.getTranslationToRef(e);const i=t.globalPosition;this._worldMatrix.invertToRef(W.AA.Matrix[1]);const r=W.AA.Vector3[1];W.Pq.TransformCoordinatesToRef(i,W.AA.Matrix[1],r),r.normalize();const s=-Math.atan2(r.z,r.x)+Math.PI/2,n=Math.sqrt(r.x*r.x+r.z*r.z),o=-Math.atan2(r.y,n);if(W.PT.RotationYawPitchRollToRef(s,o,0,W.AA.Quaternion[0]),(this.billboardMode&Pt.BILLBOARDMODE_ALL)!==Pt.BILLBOARDMODE_ALL){const e=W.AA.Vector3[1];W.AA.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&Pt.BILLBOARDMODE_X)!==Pt.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&Pt.BILLBOARDMODE_Y)!==Pt.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&Pt.BILLBOARDMODE_Z)!==Pt.BILLBOARDMODE_Z&&(e.z=0),W.uq.RotationYawPitchRollToRef(e.y,e.x,e.z,W.AA.Matrix[0])}else W.uq.FromQuaternionToRef(W.AA.Quaternion[0],W.AA.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(W.AA.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(W.AA.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):s&&s._nonUniformScaling?this._updateNonUniformScalingState(s._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=W.uq.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const e=this.getChildren();for(let t=0;tnew Pt(e,this.getScene())),this);if(r.name=e,r.id=e,t&&(r.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;inew Pt(e.name,t)),e,t,i);if(e.localMatrix?r.setPreTransformMatrix(W.uq.FromArray(e.localMatrix)):e.pivotMatrix&&r.setPivotMatrix(W.uq.FromArray(e.pivotMatrix)),r.setEnabled(e.isEnabled),r._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(let t=0;t(!t||t(e))&&e instanceof Pt)),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){const e=this._parentContainer.transformNodes.indexOf(this);e>-1&&this._parentContainer.transformNodes.splice(e,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){const e=this.getChildTransformNodes(!0);for(const t of e)t.parent=null,t.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let r=null,s=null;t&&(this.rotationQuaternion?(s=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(r=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const n=this.getHierarchyBoundingVectors(e,i),o=n.max.subtract(n.min),a=Math.max(o.x,o.y,o.z);if(0===a)return this;const l=1/a;return this.scaling.scaleInPlace(l),t&&(this.rotationQuaternion&&s?this.rotationQuaternion.copyFrom(s):this.rotation&&r&&this.rotation.copyFrom(r)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}Pt.BILLBOARDMODE_NONE=0,Pt.BILLBOARDMODE_X=1,Pt.BILLBOARDMODE_Y=2,Pt.BILLBOARDMODE_Z=4,Pt.BILLBOARDMODE_ALL=7,Pt.BILLBOARDMODE_USE_POSITION=128,Pt.BillboardUseParentOrientation=!1,Pt._TmpRotation=W.PT.Zero(),Pt._TmpScaling=W.Pq.Zero(),Pt._TmpTranslation=W.Pq.Zero(),Pt._LookAtVectorCache=new W.Pq(0,0,0),Pt._RotationAxisCache=new W.PT,(0,je.Cg)([(0,$e.P_)("position")],Pt.prototype,"_position",void 0),(0,je.Cg)([(0,$e.P_)("rotation")],Pt.prototype,"_rotation",void 0),(0,je.Cg)([(0,$e.bR)("rotationQuaternion")],Pt.prototype,"_rotationQuaternion",void 0),(0,je.Cg)([(0,$e.P_)("scaling")],Pt.prototype,"_scaling",void 0),(0,je.Cg)([(0,$e.lK)("billboardMode")],Pt.prototype,"_billboardMode",void 0),(0,je.Cg)([(0,$e.lK)()],Pt.prototype,"scalingDeterminant",void 0),(0,je.Cg)([(0,$e.lK)("infiniteDistance")],Pt.prototype,"_infiniteDistance",void 0),(0,je.Cg)([(0,$e.lK)()],Pt.prototype,"ignoreNonUniformScaling",void 0),(0,je.Cg)([(0,$e.lK)()],Pt.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);var At=i(81310),Rt=i(4216);class It{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new W.Pq(0,0,0),this._diffPositionForCollisions=new W.Pq(0,0,0),this._collisionResponse=!0}}var Mt=i(4514),Ot=i(55935);class Dt{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=W.Pq.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class wt{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new Dt,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 It,this._enableDistantPicking=!1,this._rawBoundingInfo=null,this._sideOrientationHint=!1,this._inheritVisibility=!1}}class Nt extends Pt{static get BILLBOARDMODE_NONE(){return Pt.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return Pt.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return Pt.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return Pt.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return Pt.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return Pt.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)}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,(1===t&&1!==e||1!==t&&1===e)&&this._markSubMeshesAsDirty((e=>{e.markAsMiscDirty(),e.markAsPrePassDirty()}))}get inheritVisibility(){return this._internalAbstractMeshDataInfo._inheritVisibility}set inheritVisibility(e){this._internalAbstractMeshDataInfo._inheritVisibility=e}get isVisible(){if(!this._isVisible||!this.inheritVisibility||!this._parentNode)return this._isVisible;if(this._isVisible){let e=this._parentNode;for(;e;){const t=e.isVisible;if(void 0!==t)return t;e=e.parent}}return this._isVisible}set isVisible(e){this._isVisible=e}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._setMaterial(e)}_setMaterial(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(),this._unBindEffect()))}getMaterialForRenderPass(e){return this._internalAbstractMeshDataInfo._materialForRenderPass?.[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new wt,this._waitingMaterialId=null,this._waitingMorphTargetManagerId=null,this.cullingStrategy=Nt.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new z.cP,this.onCollisionPositionChangeObservable=new z.cP,this.onMaterialChangedObservable=new z.cP,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=H.v9.Red(),this.outlineWidth=.02,this.overlayColor=H.v9.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 W.Pq(.5,1,.5),this.ellipsoidOffset=new W.Pq(0,0,0),this.edgesWidth=1,this.edgesColor=new H.ov(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 z.cP,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>Ot.$.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),i&&this.onCollideObservable.notifyObservers(i),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},(t=this.getScene()).addMesh(this),this._resyncLightSources(),this._uniformBuffer=new Rt.D(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case 2:this.doNotSyncBoundingInfo=!0;case 1:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1}}_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: "+("InstancedMesh"!==this.getClassName()?"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!==Pt.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive)){if(!e)return this.actionManager;if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),null!==this._occlusionQuery&&(this._occlusionQuery=null),this.subMeshes){for(const e of this.subMeshes)e._rebuild();this.resetDrawCache()}}_resyncLightSources(){this._lightSources.length=0;for(const e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){const t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e);let r=!1;if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;r=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(r)}_unBindEffect(){for(const e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){const i=this._lightSources.indexOf(e);-1!==i&&(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,super.markAsDirty(e),this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,r){return this}updateVerticesData(e,t,i,r){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){return this.rawBoundingInfo??this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,i){return this._boundingInfo=new _t(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(st.R.MatricesIndicesKind)&&this.isVerticesDataPresent(st.R.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===Pt.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():super.getWorldMatrix()}_getWorldMatrixDeterminant(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():super._getWorldMatrixDeterminant()}get isAnInstance(){return!1}get hasInstances(){return!1}get hasThinInstances(){return!1}movePOV(e,t,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){const r=new W.uq;(this.rotationQuaternion?this.rotationQuaternion:W.PT.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(r);const s=W.Pq.Zero(),n=this.definedFacingForward?-1:1;return W.Pq.TransformCoordinatesFromFloatsToRef(e*n,t,i*n,r,s),s}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const r=this.definedFacingForward?1:-1;return new W.Pq(e*r,t,i*r)}_refreshBoundingInfo(e,t){if(e){const i=(0,mt.b8)(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new _t(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t0&&(W.uq.FromFloat32ArrayToRefScaled(i,Math.floor(16*r[u+d]),f,h),l.addToSelf(h));if(n&&o)for(d=0;d<4;d++)f=o[u+d],f>0&&(W.uq.FromFloat32ArrayToRefScaled(i,Math.floor(16*n[u+d]),f,h),l.addToSelf(h));c(e[t],e[t+1],e[t+2],l,a),a.toArray(e,t)}}(e,t,i,r,s,n,o)}_getData(e,t,i=st.R.PositionKind){const r=e.cache,s=e=>{if(r){const t=r._vertexData||(r._vertexData={});return t[e]||this.copyVerticesData(e,t),t[e]}return this.getVerticesData(e)};if(t||(t=s(i)),!t)return null;if(r?(r._outputData?r._outputData.set(t):r._outputData=new Float32Array(t),t=r._outputData):(e.applyMorph&&this.morphTargetManager||e.applySkeleton&&this.skeleton)&&(t=t.slice()),e.applyMorph&&this.morphTargetManager&&function(e,t,i){let r=null;switch(t){case st.R.PositionKind:r=e=>e.getPositions();break;case st.R.NormalKind:r=e=>e.getNormals();break;case st.R.TangentKind:r=e=>e.getTangents();break;case st.R.UVKind:r=e=>e.getUVs();break;default:return}for(let t=0;t4,o=n?s(st.R.MatricesIndicesExtraKind):null,a=n?s(st.R.MatricesWeightsExtraKind):null,l=this.skeleton.getTransformMatrices(this);Nt._ApplySkeleton(t,i,l,e,r,o,a)}}if(!1!==e.updatePositionsArray&&i===st.R.PositionKind){const e=this._internalAbstractMeshDataInfo._positions||[],i=e.length;if(e.length=t.length/3,i1||!r.IsGlobal)&&r.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const r=this.getBoundingInfo(),s=e.getBoundingInfo();if(r.intersects(s,t))return!0;if(i)for(const i of this.getChildMeshes())if(i.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 t=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=t.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,t.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const i=e.verticesStart,r=e.verticesStart+e.verticesCount;for(let s=i;s1&&!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.AA.Matrix[0],i=W.AA.Matrix[1];return W.uq.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,r=!1,s,n=!1){const o=new At.G,a=this.getClassName(),l="InstancedLinesMesh"===a||"LinesMesh"===a||"GreasedLineMesh"===a?this.intersectionThreshold:0,h=this.getBoundingInfo();if(!this.subMeshes)return o;if(!(n||e.intersectsSphere(h.boundingSphere,l)&&e.intersectsBox(h.boundingBox,l)))return o;if(r)return o.hit=!n,o.pickedMesh=n?null:this,o.distance=n?0:W.Pq.Distance(e.origin,h.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let c=null;const u=this._scene.getIntersectingSubMeshCandidates(this,e),d=u.length;let f=!1;for(let e=0;e1&&!n&&!s.canIntersects(e))continue;const o=s.intersects(e,this._positions,this.getIndices(),t,i);if(o&&(t||!c||o.distancee!==this&&e.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 t=e.includedOnlyMeshes.indexOf(this);-1!==t&&e.includedOnlyMeshes.splice(t,1),t=e.excludedMeshes.indexOf(this),-1!==t&&e.excludedMeshes.splice(t,1);const i=e.getShadowGenerators();if(i){const e=i.values();for(let i=e.next();!0!==i.done;i=e.next()){const e=i.value.getShadowMap();e&&e.renderList&&(t=e.renderList.indexOf(this),-1!==t&&e.renderList.splice(t,1))}}})),"InstancedMesh"===this.getClassName()&&"InstancedLinesMesh"===this.getClassName()||this.releaseSubMeshes();const s=r.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,s.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),s.wipeCaches(),r.removeMesh(this),this._parentContainer){const e=this._parentContainer.meshes.indexOf(this);e>-1&&this._parentContainer.meshes.splice(e,1),this._parentContainer=null}if(t&&this.material&&("MultiMaterial"===this.material.getClassName()?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i65535){t=!0;break}e.depthSortedIndices=t?new Uint32Array(i):new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){const t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:W.Pq.Zero()}e.depthSortedFacets=[];for(let t=0;tlt.bH?s.maximum.x-s.minimum.x:lt.bH,e.bbSize.y=s.maximum.y-s.minimum.y>lt.bH?s.maximum.y-s.minimum.y:lt.bH,e.bbSize.z=s.maximum.z-s.minimum.z>lt.bH?s.maximum.z-s.minimum.z:lt.bH;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=s,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),W.Pq.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,r&&bt.ComputeNormals(t,i,r,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const t=e.depthSortedIndices.length/3|0;for(let r=0;rs.subDiv.max||o<0||o>s.subDiv.max||a<0||a>s.subDiv.max?null:s.facetPartitioning[n+s.subDiv.max*o+s.subDiv.max*s.subDiv.max*a]}getClosestFacetAtCoordinates(e,t,i,r,s=!1,n=!0){const o=this.getWorldMatrix(),a=W.AA.Matrix[5];o.invertToRef(a);const l=W.AA.Vector3[8];W.Pq.TransformCoordinatesFromFloatsToRef(e,t,i,a,l);const h=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.z,r,s,n);return r&&W.Pq.TransformCoordinatesFromFloatsToRef(r.x,r.y,r.z,o,r),h}getClosestFacetAtLocalCoordinates(e,t,i,r,s=!1,n=!0){let o=null,a=0,l=0,h=0,c=0,u=0,d=0,f=0,p=0;const _=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;let v,x,b,S=Number.MAX_VALUE,T=S;for(let C=0;C=0||s&&!n&&c<=0)&&(c=x.x*b.x+x.y*b.y+x.z*b.z,u=-(x.x*e+x.y*t+x.z*i-c)/(x.x*x.x+x.y*x.y+x.z*x.z),d=e+x.x*u,f=t+x.y*u,p=i+x.z*u,a=d-e,l=f-t,h=p-i,T=a*a+l*l+h*h,Te.emitter===this))}}Nt.OCCLUSION_TYPE_NONE=0,Nt.OCCLUSION_TYPE_OPTIMISTIC=1,Nt.OCCLUSION_TYPE_STRICT=2,Nt.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,Nt.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,Nt.CULLINGSTRATEGY_STANDARD=0,Nt.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Nt.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Nt.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,(0,je.Cg)([$e.Cx.filter(((...[e,t,i,r,s])=>!(Array.isArray(e)||Array.isArray(t)||Array.isArray(i)||Array.isArray(r)||Array.isArray(s))))],Nt,"_ApplySkeleton",null),(0,X.Y5)("BABYLON.AbstractMesh",Nt);var Ft=i(30573);class Lt{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){it.p.Clone((()=>e),this)}serialize(){return it.p.Serialize(this)}parse(e,t,i){it.p.Parse((()=>this),e,t,i)}}(0,je.Cg)([(0,$e.lK)()],Lt.prototype,"func",null),(0,je.Cg)([(0,$e.lK)()],Lt.prototype,"funcRef",null),(0,je.Cg)([(0,$e.lK)()],Lt.prototype,"funcMask",null),(0,je.Cg)([(0,$e.lK)()],Lt.prototype,"opStencilFail",null),(0,je.Cg)([(0,$e.lK)()],Lt.prototype,"opDepthFail",null),(0,je.Cg)([(0,$e.lK)()],Lt.prototype,"opStencilDepthPass",null),(0,je.Cg)([(0,$e.lK)()],Lt.prototype,"mask",null),(0,je.Cg)([(0,$e.lK)()],Lt.prototype,"enabled",null);var Bt=i(85770);class Vt{get shaderLanguage(){return this._shaderLanguage}get canRenderToMRT(){return!1}set alpha(e){if(this._alpha===e)return;const t=this._alpha;this._alpha=e,1!==t&&1!==e||this.markAsDirty(Vt.MiscDirtyFlag+Vt.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(Vt.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(Vt.TextureDirtyFlag))}get cullBackFaces(){return this._cullBackFaces}get blockDirtyMechanism(){return this._blockDirtyMechanism}set blockDirtyMechanism(e){this._blockDirtyMechanism!==e&&(this._blockDirtyMechanism=e,e||this.markDirty())}atomicMaterialsUpdate(e){this.blockDirtyMechanism=!0;try{e(this)}finally{this.blockDirtyMechanism=!1}}get hasRenderTargetTextures(){return this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._eventInfo.hasRenderTargetTextures}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new z.cP),this._onBindObservable}set onBind(e){this._onBindObserver&&this.onBindObservable.remove(this._onBindObserver),this._onBindObserver=this.onBindObservable.add(e)}get onUnBindObservable(){return this._onUnBindObservable||(this._onUnBindObservable=new z.cP),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new z.cP),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(Vt.TextureDirtyFlag))}get alphaMode(){return this._alphaMode}set needDepthPrePass(e){this._needDepthPrePass!==e&&(this._needDepthPrePass=e,this._needDepthPrePass&&(this.checkReadyOnEveryCall=!0))}get needDepthPrePass(){return this._needDepthPrePass}get isPrePassCapable(){return!1}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAsDirty(Vt.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case Vt.WireFrameFillMode:case Vt.LineListDrawMode:case Vt.LineLoopDrawMode:case Vt.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?Vt.WireFrameFillMode:Vt.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case Vt.PointFillMode:case Vt.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?Vt.PointFillMode:Vt.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(Vt.MiscDirtyFlag))}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){const t=this.getScene().getEngine().getCaps().fragmentDepthSupported;e&&!t&&Z.V.Warn("Logarithmic depth has been requested for a material on a device that doesn't support it."),this._useLogarithmicDepth=e&&t,this._markAllSubMeshesAsMiscDirty()}_getDrawWrapper(){return this._drawWrapper}_setDrawWrapper(e){this._drawWrapper=e}constructor(e,t,i,r=!1){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!0,this._shaderLanguage=0,this._forceGLSL=!1,this.metadata=null,this.reservedDataStore=null,this.checkReadyOnEveryCall=!1,this.checkReadyOnlyOnce=!1,this.state="",this._alpha=1,this._backFaceCulling=!0,this._cullBackFaces=!0,this._blockDirtyMechanism=!1,this.sideOrientation=null,this.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new z.cP,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=2,this._needDepthPrePass=!1,this.disableDepthWrite=!1,this.disableColorWrite=!1,this.forceDepthWrite=!1,this.depthFunction=0,this.separateCullingPass=!1,this._fogEnabled=!0,this.pointSize=1,this.zOffset=0,this.zOffsetUnits=0,this.stencil=new Lt,this._useUBO=!1,this._fillMode=Vt.TriangleFillMode,this._cachedDepthWriteState=!1,this._cachedColorWriteState=!1,this._cachedDepthFunctionState=0,this._indexInSceneMaterialArray=-1,this.meshMap=null,this._parentContainer=null,this._uniformBufferLayoutBuilt=!1,this._eventInfo={},this._callbackPluginEventGeneric=()=>{},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||he.q.LastCreatedScene;s&&(this._scene=s,this._dirtyCallbacks={},this._forceGLSL=r,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||Ue.S0.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new gt.E(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._uniformBuffer=new Rt.D(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,this._createUniformBuffer(),i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),Vt.OnEventObservable.notifyObservers(this,1))}_createUniformBuffer(){const e=this.getScene().getEngine();this._uniformBuffer?.dispose(),e.isWebGPU&&!this._forceGLSL?(this._uniformBuffer=new Rt.D(e,void 0,void 0,this.name,!0),this._shaderLanguage=1):this._uniformBuffer=new Rt.D(this._scene.getEngine(),void 0,void 0,this.name),this._uniformBufferLayoutBuilt=!1}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){const r=t.materialDefines;return!!r&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}_getEffectiveOrientation(e){return null!==this.sideOrientation?this.sideOrientation:e.sideOrientation}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===Vt.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===Vt.MATERIAL_OPAQUE||this._transparencyMode===Vt.MATERIAL_ALPHATEST}needAlphaBlending(){return!this._disableAlphaBlending&&this.alpha<1}needAlphaBlendingForMesh(e){return e.visibility<1||!this._disableAlphaBlending&&(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 t of i.subMeshes)if(t.getMaterial()===this)for(const i of t._drawWrappers)i&&this._materialContext===i.materialContext&&(i._wasPreviouslyReady=!1,i._wasPreviouslyUsingInstances=null,i._forceRebindOnNextCall=e);e&&this.markAsDirty(Vt.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),r=(null==t?this.sideOrientation:t)===Vt.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(8,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const r=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),r._forceRebindOnNextCall=!1}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null,i){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,(0,Bt._8)(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),this._scene._cachedVisibility=e?e.visibility:1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){const e=this._scene.getEngine();this._cachedDepthWriteState=e.getDepthWrite(),e.setDepthWrite(!1)}if(this.disableColorWrite){const e=this._scene.getEngine();this._cachedColorWriteState=e.getColorWrite(),e.setColorWrite(!1)}if(0!==this.depthFunction){const e=this._scene.getEngine();this._cachedDepthFunctionState=e.getDepthFunction()||0,e.setDepthFunction(this.depthFunction)}}unbind(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(256,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(512,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(1024,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),Vt._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(const t of this.pluginManager._plugins){const i=e.pluginManager.getPlugin(t.name);i&&t.copyTo(i)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}return this._scene.meshes.filter((e=>e.material===this))}forceCompilation(e,t,i,r){const s={clipPlane:!1,useInstances:!1,...i},n=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const a=()=>{if(!this._scene||!this._scene.getEngine())return;const i=n.clipPlane;if(s.clipPlane&&(n.clipPlane=new Ft.Z(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,n=null;if(e.subMeshes){const t=new vt(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,s.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?n=t.effect.getCompilationError():(i=!1,setTimeout(a,16)))}i&&(this.allowShaderHotSwapping=o,n&&r&&r(n),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(a,16);s.clipPlane&&(n.clipPlane=i)};a()}forceCompilationAsync(e,t){return new Promise(((i,r)=>{this.forceCompilation(e,(()=>{i()}),t,(e=>{r(e)}))}))}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(Vt._DirtyCallbackArray.length=0,e&Vt.TextureDirtyFlag&&Vt._DirtyCallbackArray.push(Vt._TextureDirtyCallBack),e&Vt.LightDirtyFlag&&Vt._DirtyCallbackArray.push(Vt._LightsDirtyCallBack),e&Vt.FresnelDirtyFlag&&Vt._DirtyCallbackArray.push(Vt._FresnelDirtyCallBack),e&Vt.AttributesDirtyFlag&&Vt._DirtyCallbackArray.push(Vt._AttributeDirtyCallBack),e&Vt.MiscDirtyFlag&&Vt._DirtyCallbackArray.push(Vt._MiscDirtyCallBack),e&Vt.PrePassDirtyFlag&&Vt._DirtyCallbackArray.push(Vt._PrePassDirtyCallBack),Vt._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(Vt._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){const e=this.getScene().meshes;for(const t of e)if(t.subMeshes)for(const e of t.subMeshes)e.getMaterial()===this&&e.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 t of i.subMeshes)if(t.getMaterial(!1)===this)for(const i of t._drawWrappers)i&&i.defines&&i.defines.markAllAsDirty&&this._materialContext===i.materialContext&&e(i.defines)}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(Vt._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(Vt._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(Vt._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(Vt._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(Vt._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(Vt._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(Vt._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(Vt._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(Vt._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(Vt._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(0!==this._scene.performancePriority){this.checkReadyOnlyOnce=!0;const e=this._scene.onScenePerformancePriorityChangedObservable.addOnce((()=>{this.checkReadyOnlyOnce=!1}));this.onDisposeObservable.add((()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)}))}}setPrePassRenderer(e){return!1}dispose(e,t,i){const r=this.getScene();if(r.stopAnimation(this),r.freeProcessedMaterials(),r.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(2,this._eventInfo),this._parentContainer){const e=this._parentContainer.materials.indexOf(this);e>-1&&this._parentContainer.materials.splice(e,1),this._parentContainer=null}if(!0!==i)if(this.meshMap)for(const e in this.meshMap){const t=this.meshMap[e];t&&(this.releaseVertexArrayObject(t,!0),t.material=null)}else{const e=r.meshes;for(const t of e)t.material!==this||t.sourceMesh||(this.releaseVertexArrayObject(t,!0),t.material=null)}this._uniformBuffer.dispose(),this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}releaseVertexArrayObject(e,t){const i=e.geometry;if(i)if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(const r of e.subMeshes)i._releaseVertexArrayObject(r.effect),t&&r.effect&&r.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}serialize(){const e=it.p.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){if("BABYLON.PBRMaterial"===e.customType&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return Z.V.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null}else e.customType="BABYLON.StandardMaterial";const r=Ue.S0.Instantiate(e.customType).Parse(e,t,i);return r._loadedUniqueId=e.uniqueId,r}static _ParsePlugins(e,t,i,r){if(e.plugins)for(const s in e.plugins){const n=e.plugins[s];let o=t.pluginManager?.getPlugin(n.name);if(!o){const e=Ue.S0.Instantiate("BABYLON."+s);e&&(o=new e(t))}o?.parse(n,i,r)}}}Vt.TriangleFillMode=0,Vt.WireFrameFillMode=1,Vt.PointFillMode=2,Vt.PointListDrawMode=3,Vt.LineListDrawMode=4,Vt.LineLoopDrawMode=5,Vt.LineStripDrawMode=6,Vt.TriangleStripDrawMode=7,Vt.TriangleFanDrawMode=8,Vt.ClockWiseSideOrientation=0,Vt.CounterClockWiseSideOrientation=1,Vt.TextureDirtyFlag=1,Vt.LightDirtyFlag=2,Vt.FresnelDirtyFlag=4,Vt.AttributesDirtyFlag=8,Vt.MiscDirtyFlag=16,Vt.PrePassDirtyFlag=32,Vt.AllDirtyFlag=63,Vt.MATERIAL_OPAQUE=0,Vt.MATERIAL_ALPHATEST=1,Vt.MATERIAL_ALPHABLEND=2,Vt.MATERIAL_ALPHATESTANDBLEND=3,Vt.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,Vt.MATERIAL_NORMALBLENDMETHOD_RNM=1,Vt.OnEventObservable=new z.cP,Vt._AllDirtyCallBack=e=>e.markAllAsDirty(),Vt._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),Vt._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),Vt._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),Vt._MiscDirtyCallBack=e=>e.markAsMiscDirty(),Vt._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),Vt._LightsDirtyCallBack=e=>e.markAsLightDirty(),Vt._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),Vt._FresnelAndMiscDirtyCallBack=e=>{Vt._FresnelDirtyCallBack(e),Vt._MiscDirtyCallBack(e)},Vt._TextureAndMiscDirtyCallBack=e=>{Vt._TextureDirtyCallBack(e),Vt._MiscDirtyCallBack(e)},Vt._DirtyCallbackArray=[],Vt._RunDirtyCallBacks=e=>{for(const t of Vt._DirtyCallbackArray)t(e)},(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"id",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"uniqueId",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"name",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"metadata",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"checkReadyOnEveryCall",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"checkReadyOnlyOnce",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"state",void 0),(0,je.Cg)([(0,$e.lK)("alpha")],Vt.prototype,"_alpha",void 0),(0,je.Cg)([(0,$e.lK)("backFaceCulling")],Vt.prototype,"_backFaceCulling",void 0),(0,je.Cg)([(0,$e.lK)("cullBackFaces")],Vt.prototype,"_cullBackFaces",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"sideOrientation",void 0),(0,je.Cg)([(0,$e.lK)("alphaMode")],Vt.prototype,"_alphaMode",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"_needDepthPrePass",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"disableDepthWrite",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"disableColorWrite",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"forceDepthWrite",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"depthFunction",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"separateCullingPass",void 0),(0,je.Cg)([(0,$e.lK)("fogEnabled")],Vt.prototype,"_fogEnabled",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"pointSize",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"zOffset",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"zOffsetUnits",void 0),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"pointsCloud",null),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"fillMode",null),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"useLogarithmicDepth",null),(0,je.Cg)([(0,$e.lK)()],Vt.prototype,"transparencyMode",null);class kt extends Vt{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=(...i)=>{const r=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),r};const i=e.splice;e.splice=(t,r)=>{const s=i.apply(e,[t,r]);return this._markAllSubMeshesAsTexturesDirty(),s}}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){if(super.hasTexture(e))return!0;for(let t=0;t=0&&r.multiMaterials.splice(s,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new kt(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,Ge.Y&&Ge.Y.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach((e=>i.subMaterials.push(t.getLastMaterialById(e)))),i}}(0,X.Y5)("BABYLON.MultiMaterial",kt);var Ut=i(9180);class Gt{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class zt{}class Wt{constructor(){this.visibleInstances={},this.batchCache=new Ht,this.batchCacheReplacementModeInFrozenMode=new Ht,this.instancesBufferSize=2048}}class Ht{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class Xt{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class qt{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 Yt extends Nt{static _GetDefaultSideOrientation(e){return e||Yt.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(st.R.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(st.R.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 z.cP),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new z.cP),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new z.cP),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new z.cP),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new z.cP),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get sideOrientation(){return this._internalMeshDataInfo._sideOrientation}set sideOrientation(e){this._internalMeshDataInfo._sideOrientation=e,this._internalAbstractMeshDataInfo._sideOrientationHint=this._scene.useRightHandedSystem&&1===e||!this._scene.useRightHandedSystem&&0===e}get overrideMaterialSideOrientation(){return this.sideOrientation}set overrideMaterialSideOrientation(e){this.sideOrientation=e,this.material&&(this.material.sideOrientation=null)}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){e&&(this.material&&null===this.material.sideOrientation||this._internalAbstractMeshDataInfo._sideOrientationHint)&&(e.sideOrientation=null),this._setMaterial(e)}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesData}get previousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesPreviousData}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}_copySource(e,t,i=!0){const r=this.getScene();if(e._geometry&&e._geometry.applyToMesh(this),ce.r.DeepCopy(e,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=e,r.useClonedMeshMap&&(e._internalMeshDataInfo.meshMap||(e._internalMeshDataInfo.meshMap={}),e._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=e._originalBuilderSideOrientation,this._creationDataStorage=e._creationDataStorage,e._ranges){const t=e._ranges;for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&t[e]&&this.createAnimationRange(e,t[e].from,t[e].to)}if(e.metadata&&e.metadata.clone?this.metadata=e.metadata.clone():this.metadata=e.metadata,this._internalMetadata=e._internalMetadata,Ge.Y&&Ge.Y.HasTags(e)&&Ge.Y.AddTagsTo(this,Ge.Y.GetTags(e,!0)),this.setEnabled(e.isEnabled(!1)),this.parent=e.parent,this.setPivotMatrix(e.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=this.name+"."+e.id,this.material=e.material,!t){const t=e.getDescendants(!0);for(let e=0;e{e&&i&&(this._uniformBuffer?this.transferToEffect(t):i.bindOnlyWorldMatrix(t))},r&&this._copySource(r,s,n),null!==i&&(this.parent=i),this._instanceDataStorage.hardwareInstancedRendering=this.getEngine().getCaps().instancedArrays,this._internalMeshDataInfo._onMeshReadyObserverAdded=e=>{e.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 z.cP(this._internalMeshDataInfo._onMeshReadyObserverAdded),r&&r.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const r=0===this.getTotalVertices()||t&&t.doNotInstantiate&&(!0===t.doNotInstantiate||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));r.parent=e||this.parent,r.position=this.position.clone(),r.scaling=this.scaling.clone(),this.rotationQuaternion?r.rotationQuaternion=this.rotationQuaternion.clone():r.rotation=this.rotation.clone(),i&&i(this,r);for(const e of this.getChildTransformNodes(!0))"InstancedMesh"===e.getClassName()&&"Mesh"===r.getClassName()&&e.sourceMesh===this?e.instantiateHierarchy(r,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:r},i):e.instantiateHierarchy(r,t,i);return r}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices(),t+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;i0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){const e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort(((t,i)=>t.distanceOrScreenCoveragei.distanceOrScreenCoverage?-e:0))}addLODLevel(e,t){if(t&&t._masterMesh)return Z.V.Warn("You cannot use a mesh as LOD level twice"),this;const i=new Gt(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 e=0;e0||this.hasThinInstances);this.computeWorldMatrix();const n=this.material||r.defaultMaterial;if(n)if(n._storeEffectOnSubMeshes)for(const e of this.subMeshes){const t=e.getMaterial();if(t)if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,s))return!1}else if(!t.isReady(this,s))return!1}else if(!n.isReady(this,s))return!1;const o=i.currentRenderPassId;for(const e of this.lightSources){const t=e.getShadowGenerators();if(!t)continue;const r=t.values();for(let e=r.next();!0!==e.done;e=r.next()){const t=e.value;if(t&&(!t.getShadowMap()?.renderList||t.getShadowMap()?.renderList&&-1!==t.getShadowMap()?.renderList?.indexOf(this))){const e=t.getShadowMap().renderPassIds??[i.currentRenderPassId];for(let r=0;r0){const i=this.getIndices();if(!i)return null;const r=i.length;let s=!1;if(e)s=!0;else for(const e of this.subMeshes){if(e.indexStart+e.indexCount>r){s=!0;break}if(e.verticesStart+e.verticesCount>t){s=!0;break}}if(!s)return this.subMeshes[0]}return this.releaseSubMeshes(),new vt(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,r=0;for(;i%3!=0;)i++;this.releaseSubMeshes();for(let s=0;s=t);s++)vt.CreateFromIndices(0,r,s===e-1?t-r:i,this,void 0,!1),r+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,r){if(this._geometry)this._geometry.setVerticesData(e,t,i,r);else{const r=new bt;r.set(t,e);const s=this.getScene();new yt(yt.RandomId(),s,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=yt.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,r){return this._geometry?(r?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){const i=this.getVerticesData(st.R.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(st.R.PositionKind,i,!1,!1),t){const e=this.getIndices(),t=this.getVerticesData(st.R.NormalKind);if(!t)return this;bt.ComputeNormals(i,e,t),this.updateVerticesData(st.R.NormalKind,t,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry)return this;if(1===this._geometry.meshes.length)return this;const e=this._geometry,t=this._geometry.copy(yt.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let r=this._geometry;r||(r=new yt(yt.RandomId(),this.getScene(),void 0,void 0,this)),r.setIndexBuffer(e,t,i)}setIndices(e,t=null,i=!1,r=!1){if(this._geometry)this._geometry.setIndices(e,t,i,r);else{const t=new bt;t.indices=e;const r=this.getScene();new yt(yt.RandomId(),r,t,i,this)}return this}updateIndices(e,t,i=!1){return this._geometry?(this._geometry.updateIndices(e,t,i),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,i,r=!0){if(!this._geometry)return this;const s=this.getScene().getEngine();let n;if(this._unIndexed)n=this._getRenderingFillMode(i)===Vt.WireFrameFillMode?e._getLinesIndexBuffer(this.getIndices(),s):null;else switch(this._getRenderingFillMode(i)){case Vt.PointFillMode:n=null;break;case Vt.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),s);break;default:case Vt.TriangleFillMode:n=this._geometry.getIndexBuffer()}return this._bindDirect(t,n,r)}_bindDirect(e,t,i=!0){return this._geometry?(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(e),i&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(e,t,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(e,t),this):this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);const r=this.getScene().getEngine();return this._unIndexed&&t!==Vt.WireFrameFillMode||t==Vt.PointFillMode?r.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==Vt.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(),r=i._isInIntermediateRendering(),s=r?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,n=this._instanceDataStorage.batchCache;if(n.mustReturn=!1,n.renderSelf[e]=t||!s&&this.isEnabled()&&this.isVisible,n.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const t=this._instanceDataStorage.visibleInstances,s=i.getRenderId(),o=r?t.intermediateDefaultRenderId:t.defaultRenderId;n.visibleInstances[e]=t[s],!n.visibleInstances[e]&&o&&(n.visibleInstances[e]=t[o])}return n.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==n.visibleInstances[e]&&void 0!==n.visibleInstances[e],this._instanceDataStorage.previousBatch=n,n}_renderWithInstances(e,t,i,r,s){const n=i.visibleInstances[e._id],o=n?n.length:0,a=this._instanceDataStorage,l=a.instancesBufferSize;let h=a.instancesBuffer,c=a.instancesPreviousBuffer;const u=16*(o+1)*4;for(;a.instancesBufferSizee._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera1&&r.activeCamera===r.activeCameras[0]||s<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const n=this._getInstancesRenderList(e._id,!!i);if(n.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const o=r.getEngine();let a=0,l=null;this.ignoreCameraMaxZ&&r.activeCamera&&!r._isInIntermediateRendering()&&(a=r.activeCamera.maxZ,l=r.activeCamera,r.activeCamera.maxZ=0,r.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const h=e.getRenderingMesh(),c=n.hardwareInstancedRendering[e._id]||h.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,u=this._instanceDataStorage,d=e.getMaterial();if(!d)return l&&(l.maxZ=a,r.updateTransformMatrix(!0)),this;if(u.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===d){if(d._storeEffectOnSubMeshes&&!e._drawWrapper?._wasPreviouslyReady||!d._storeEffectOnSubMeshes&&!d._getDrawWrapper()._wasPreviouslyReady)return l&&(l.maxZ=a,r.updateTransformMatrix(!0)),this}else{if(d._storeEffectOnSubMeshes){if(!d.isReadyForSubMesh(this,e,c))return l&&(l.maxZ=a,r.updateTransformMatrix(!0)),this}else if(!d.isReady(this,c))return l&&(l.maxZ=a,r.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=d}let f;t&&o.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode),f=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const p=f?.effect??null;for(const t of r._beforeRenderingMeshStage)t.action(this,e,n,p);if(!f||!p)return l&&(l.maxZ=a,r.updateTransformMatrix(!0)),this;const _=i||this;let m;if(u.isFrozen||!this._internalMeshDataInfo._effectiveMaterial.backFaceCulling&&null===this._internalMeshDataInfo._effectiveMaterial.sideOrientation&&!this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)m=u.sideOrientation;else{const e=_._getWorldMatrixDeterminant();m=this._internalMeshDataInfo._effectiveMaterial._getEffectiveOrientation(this),e<0&&(m=m===Vt.ClockWiseSideOrientation?Vt.CounterClockWiseSideOrientation:Vt.ClockWiseSideOrientation),u.sideOrientation=m}const g=this._internalMeshDataInfo._effectiveMaterial._preBind(f,m);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&o.setDepthWrite(!0);const v=this._internalMeshDataInfo._effectiveMaterial,x=v.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),c||this._bind(e,p,x,!1);const b=_.getWorldMatrix();v._storeEffectOnSubMeshes?v.bindForSubMesh(b,this,e):v.bind(b,this),!v.backFaceCulling&&v.separateCullingPass&&(o.setState(!0,v.zOffset,!1,!g,v.cullBackFaces,v.stencil,v.zOffsetUnits),this._processRendering(this,e,p,x,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),o.setState(!0,v.zOffset,!1,g,v.cullBackFaces,v.stencil,v.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,p,x,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const t of r._afterRenderingMeshStage)t.action(this,e,n,p);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),l&&(l.maxZ=a,r.updateTransformMatrix(!0)),2!==r.performancePriority||u.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(st.R.MatricesWeightsKind)&&(this.isVerticesDataPresent(st.R.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(st.R.MatricesWeightsKind),t=e.length;for(let i=0;ii&&r++,0!==n&&u++,c+=n,i=n}if(l[u]++,u>n&&(n=u),0===c)s++;else{const i=1/c;let r=0;for(let s=0;s.001&&o++}}const h=this.skeleton.bones.length,c=this.getVerticesData(st.R.MatricesIndicesKind),u=this.getVerticesData(st.R.MatricesIndicesExtraKind);let d=0;for(let e=0;e=h||i<0)&&d++}return{skinned:!0,valid:0===s&&0===o&&0===d,report:"Number of Weights = "+i/4+"\nMaximum influences = "+n+"\nMissing Weights = "+s+"\nNot Sorted = "+r+"\nNot Normalized = "+o+"\nWeightCounts = ["+l+"]\nNumber of bones = "+h+"\nBad Bone Indices = "+d}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):4===this.delayLoadState&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return Ue.S0.LoadFile(this.delayLoadingFile,(t=>{t instanceof ArrayBuffer?this._delayLoadingFunction(t,this):this._delayLoadingFunction(JSON.parse(t),this),this.instances.forEach((e=>{e.refreshBoundingInfo(),e._syncSubMeshes()})),this.delayLoadState=1,e.removePendingData(this)}),(()=>{}),e.offlineProvider,t),this}isInFrustum(e){return 2!==this.delayLoadState&&!!super.isInFrustum(e)&&(this._checkDelayState(),!0)}setMaterialById(e){const t=this.getScene().materials;let i;for(i=t.length-1;i>-1;i--)if(t[i].id===e)return this.material=t[i],this;const r=this.getScene().multiMaterials;for(i=r.length-1;i>-1;i--)if(r[i].id===e)return this.material=r[i],this;return this}getAnimatables(){const e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(st.R.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(st.R.PositionKind);const r=W.Pq.Zero();let s;for(s=0;s{const a=e.width,l=e.height,h=this.getEngine().createCanvas(a,l).getContext("2d");h.drawImage(e,0,0);const c=h.getImageData(0,0,a,l).data;this.applyDisplacementMapFromBuffer(c,a,l,t,i,s,n,o),r&&r(this)}),a||(()=>{}),l.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,r,s,n,o,a=!1){if(!this.isVerticesDataPresent(st.R.PositionKind)||!this.isVerticesDataPresent(st.R.NormalKind)||!this.isVerticesDataPresent(st.R.UVKind))return Z.V.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const l=this.getVerticesData(st.R.PositionKind,!0,!0),h=this.getVerticesData(st.R.NormalKind),c=this.getVerticesData(st.R.UVKind);let u=W.Pq.Zero();const d=W.Pq.Zero(),f=W.I9.Zero();n=n||W.I9.Zero(),o=o||new W.I9(1,1);for(let a=0;a!this.getVertexBuffer(e)?.getIsInstanced())),i=this.getIndices(),r={},s=(e,t)=>{const r=new Float32Array(i.length*t);let s=0;for(let n=0;n{const t=r.length-1-e,i=r[t];for(let e=0;e{for(let e=0;e-1&&(r._waitingMorphTargetManagerId=e.morphTargetManagerId),void 0!==e.skeletonId&&null!==e.skeletonId&&(r.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(r.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let t=0;t4,l=a?this.getVerticesData(st.R.MatricesIndicesExtraKind):null,h=a?this.getVerticesData(st.R.MatricesWeightsExtraKind):null,c=e.getTransformMatrices(this),u=W.Pq.Zero(),d=new W.uq,f=new W.uq;let p,_=0;for(let e=0;e0&&(W.uq.FromFloat32ArrayToRefScaled(c,Math.floor(16*n[_+p]),m,f),d.addToSelf(f));if(a)for(p=0;p<4;p++)m=h[_+p],m>0&&(W.uq.FromFloat32ArrayToRefScaled(c,Math.floor(16*l[_+p]),m,f),d.addToSelf(f));W.Pq.TransformCoordinatesFromFloatsToRef(i._sourcePositions[e],i._sourcePositions[e+1],i._sourcePositions[e+2],d,u),u.toArray(r,e),t&&(W.Pq.TransformNormalFromFloatsToRef(i._sourceNormals[e],i._sourceNormals[e+1],i._sourceNormals[e+2],d,u),u.toArray(s,e)),d.reset()}return this.updateVerticesData(st.R.PositionKind,r),t&&this.updateVerticesData(st.R.NormalKind,s),this}static MinMax(e){let t=null,i=null;return e.forEach((function(e){const r=e.getBoundingInfo().boundingBox;t&&i?(t.minimizeInPlace(r.minimumWorld),i.maximizeInPlace(r.maximumWorld)):(t=r.minimumWorld,i=r.maximumWorld)})),t&&i?{min:t,max:i}:{min:W.Pq.Zero(),max:W.Pq.Zero()}}static Center(e){const t=e instanceof Array?Yt.MinMax(e):e;return W.Pq.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,r,s,n){return Xe(Yt._MergeMeshesCoroutine(e,t,i,r,s,n,!1))}static MergeMeshesAsync(e,t=!0,i,r,s,n){return qe(Yt._MergeMeshesCoroutine(e,t,i,r,s,n,!0),We())}static*_MergeMeshesCoroutine(e,t=!0,i,r,s,n,o){if(0===(e=e.filter(Boolean)).length)return null;let a;if(!i){let t=0;for(a=0;a=65536)return Z.V.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}n&&(s=!1);const l=new Array,h=new Array,c=new Array,u=e[0].sideOrientation;for(a=0;a{const t=e.computeWorldMatrix(!0);return{vertexData:bt.ExtractFromMesh(e,!1,!1),transform:t}},{vertexData:p,transform:_}=f(d);o&&(yield);const m=new Array(e.length-1);for(let t=1;t{throw(0,Je.n)("GroundMesh")},Yt._GoldbergMeshParser=(e,t)=>{throw(0,Je.n)("GoldbergMesh")},Yt._LinesMeshParser=(e,t)=>{throw(0,Je.n)("LinesMesh")},Yt._GreasedLineMeshParser=(e,t)=>{throw(0,Je.n)("GreasedLineMesh")},Yt._GreasedLineRibbonMeshParser=(e,t)=>{throw(0,Je.n)("GreasedLineRibbonMesh")},Yt._TrailMeshParser=(e,t)=>{throw(0,Je.n)("TrailMesh")},(0,X.Y5)("BABYLON.Mesh",Yt),Yt._instancedMeshFactory=(e,t)=>{const i=new Kt(e,t);if(t.instancedBuffers){i.instancedBuffers={};for(const e in t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e]}return i};class Kt extends Nt{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 e of t.getAnimationRanges())null!=e&&this.createAnimationRange(e.name,e.from,e.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){this._sourceMesh?.receiveShadows!==e&&Ue.S0.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){this._sourceMesh?.material!==e&&Ue.S0.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){this._sourceMesh?.visibility!==e&&Ue.S0.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){this._sourceMesh?.skeleton!==e&&Ue.S0.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&&Z.V.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}copyVerticesData(e,t){this._sourceMesh.copyVerticesData(e,t)}setVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,r),this.sourceMesh}updateVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,r),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let i;i="object"==typeof e?e:{applySkeleton:e,applyMorph:t};const r=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getData(i,null,st.R.PositionKind),r),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||Z.V.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!==Pt.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new W.uq);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,W.AA.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.AA.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&&0!==t.length){const t=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,t.boundingSphere)}else this._currentLOD=this.sourceMesh;return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e0&&-1===this.includedOnlyMeshes.indexOf(e)||this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)||!(0===this.includeOnlyWithLayerMask||this.includeOnlyWithLayerMask&e.layerMask)||0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask))}dispose(e,t=!1){if(this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){const e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(const e of this.getScene().meshes)e._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=$t.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const r=it.p.Clone(i,this);return e&&(r.name=e),t&&(r.parent=t),r.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(r),r}serialize(){const e=it.p.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)}))),it.p.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){return Ze.b.Construct("Light_Type_"+e,t,i)||null}static Parse(e,t){const i=$t.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const r=it.p.Parse(i,e,t);if(e.excludedMeshesIds&&(r._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(r._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(r.falloffType=e.falloffType),void 0!==e.lightmapMode&&(r.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t{const r=t.apply(e,i);for(const e of i)e._resyncLightSource(this);return r};const i=e.splice;e.splice=(t,r)=>{const s=i.apply(e,[t,r]);for(const e of s)e._resyncLightSource(this);return s};for(const t of e)t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...i)=>{const r=t.apply(e,i);return this._resyncMeshes(),r};const i=e.splice;e.splice=(t,r)=>{const s=i.apply(e,[t,r]);return this._resyncMeshes(),s},this._resyncMeshes()}_resyncMeshes(){for(const e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(const e of this.getScene().meshes)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0;const t=this.getTypeID();let i=this.intensityMode;switch(i===$t.INTENSITYMODE_AUTOMATIC&&(i=t===$t.LIGHTTYPEID_DIRECTIONALLIGHT?$t.INTENSITYMODE_ILLUMINANCE:$t.INTENSITYMODE_LUMINOUSINTENSITY),t){case $t.LIGHTTYPEID_POINTLIGHT:case $t.LIGHTTYPEID_SPOTLIGHT:switch(i){case $t.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case $t.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case $t.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case $t.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case $t.INTENSITYMODE_ILLUMINANCE:e=1;break;case $t.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001),e=2*Math.PI*(1-Math.cos(t));break}}break;case $t.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){const e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}$t.FALLOFF_DEFAULT=jt.c.FALLOFF_DEFAULT,$t.FALLOFF_PHYSICAL=jt.c.FALLOFF_PHYSICAL,$t.FALLOFF_GLTF=jt.c.FALLOFF_GLTF,$t.FALLOFF_STANDARD=jt.c.FALLOFF_STANDARD,$t.LIGHTMAP_DEFAULT=jt.c.LIGHTMAP_DEFAULT,$t.LIGHTMAP_SPECULAR=jt.c.LIGHTMAP_SPECULAR,$t.LIGHTMAP_SHADOWSONLY=jt.c.LIGHTMAP_SHADOWSONLY,$t.INTENSITYMODE_AUTOMATIC=jt.c.INTENSITYMODE_AUTOMATIC,$t.INTENSITYMODE_LUMINOUSPOWER=jt.c.INTENSITYMODE_LUMINOUSPOWER,$t.INTENSITYMODE_LUMINOUSINTENSITY=jt.c.INTENSITYMODE_LUMINOUSINTENSITY,$t.INTENSITYMODE_ILLUMINANCE=jt.c.INTENSITYMODE_ILLUMINANCE,$t.INTENSITYMODE_LUMINANCE=jt.c.INTENSITYMODE_LUMINANCE,$t.LIGHTTYPEID_POINTLIGHT=jt.c.LIGHTTYPEID_POINTLIGHT,$t.LIGHTTYPEID_DIRECTIONALLIGHT=jt.c.LIGHTTYPEID_DIRECTIONALLIGHT,$t.LIGHTTYPEID_SPOTLIGHT=jt.c.LIGHTTYPEID_SPOTLIGHT,$t.LIGHTTYPEID_HEMISPHERICLIGHT=jt.c.LIGHTTYPEID_HEMISPHERICLIGHT,(0,je.Cg)([(0,$e.jT)()],$t.prototype,"diffuse",void 0),(0,je.Cg)([(0,$e.jT)()],$t.prototype,"specular",void 0),(0,je.Cg)([(0,$e.lK)()],$t.prototype,"falloffType",void 0),(0,je.Cg)([(0,$e.lK)()],$t.prototype,"intensity",void 0),(0,je.Cg)([(0,$e.lK)()],$t.prototype,"range",null),(0,je.Cg)([(0,$e.lK)()],$t.prototype,"intensityMode",null),(0,je.Cg)([(0,$e.lK)()],$t.prototype,"radius",null),(0,je.Cg)([(0,$e.lK)()],$t.prototype,"_renderPriority",void 0),(0,je.Cg)([(0,$e.$z)("_reorderLightsInScene")],$t.prototype,"renderPriority",void 0),(0,je.Cg)([(0,$e.lK)("shadowEnabled")],$t.prototype,"_shadowEnabled",void 0),(0,je.Cg)([(0,$e.lK)("excludeWithLayerMask")],$t.prototype,"_excludeWithLayerMask",void 0),(0,je.Cg)([(0,$e.lK)("includeOnlyWithLayerMask")],$t.prototype,"_includeOnlyWithLayerMask",void 0),(0,je.Cg)([(0,$e.lK)("lightmapMode")],$t.prototype,"_lightmapMode",void 0);class Qt{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[],this.sounds=null,this.effectLayers=[],this.layers=[],this.reflectionProbes=[]}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach((t=>e=e.concat(t.bones))),e}}class Zt extends Qt{}class Jt{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 ei extends Qt{constructor(e){super(),this._wasAddedToScene=!1,(e=e||he.q.LastCreatedScene)&&(this.scene=e,this.proceduralTextures=[],e.onDisposeObservable.add((()=>{this._wasAddedToScene||this.dispose()})),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();for(const e of this.particleSystems)e.rebuild();for(const e of this.textures)e._rebuild()})))}_topologicalSort(e){const t=new Map;for(const i of e)t.set(i.uniqueId,i);const i={dependsOn:new Map,dependedBy:new Map};for(const t of e){const e=t.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(const r of e){const e=r.uniqueId,s=i.dependsOn.get(e);if(r instanceof Kt){const n=r.sourceMesh;t.has(n.uniqueId)&&(s.add(n.uniqueId),i.dependedBy.get(n.uniqueId).add(e))}const n=i.dependedBy.get(e);for(const s of r.getDescendants()){const r=s.uniqueId;t.has(r)&&(n.add(r),i.dependsOn.get(r).add(e))}}const r=[],s=[];for(const r of e){const e=r.uniqueId;0===i.dependsOn.get(e).size&&(s.push(r),t.delete(e))}const n=s;for(;n.length>0;){const e=n.shift();r.push(e);const s=i.dependedBy.get(e.uniqueId);for(const r of Array.from(s.values())){const s=i.dependsOn.get(r);s.delete(e.uniqueId),0===s.size&&t.get(r)&&(n.push(t.get(r)),t.delete(r))}}return t.size>0&&(Z.V.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach((e=>Z.V.Error(e.name)))),r}_addNodeAndDescendantsToList(e,t,i,r){if(i&&(!r||r(i))&&!t.has(i.uniqueId)){e.push(i),t.add(i.uniqueId);for(const s of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,s,r)}}_isNodeInContainer(e){return e instanceof Nt&&-1!==this.meshes.indexOf(e)||e instanceof Pt&&-1!==this.transformNodes.indexOf(e)||e instanceof $t&&-1!==this.lights.indexOf(e)||e instanceof rt&&-1!==this.cameras.indexOf(e)}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return Z.V.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 Z.V.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 Z.V.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 Z.V.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||Ue.S0.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const r={},s={},n=new Jt,o=[],a=[],l={doNotInstantiate:!0,...i},h=[],c=new Set;for(const e of this.transformNodes)null===e.parent&&this._addNodeAndDescendantsToList(h,c,e,l.predicate);for(const e of this.meshes)null===e.parent&&this._addNodeAndDescendantsToList(h,c,e,l.predicate);const u=this._topologicalSort(h),d=(i,o)=>{if(((t,i)=>{if(r[t.uniqueId]=i.uniqueId,s[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof Yt){const e=i;if(e.morphTargetManager){const i=t.morphTargetManager;e.morphTargetManager=i.clone();for(let t=0;te&&s[r[e.uniqueId]]))}}"InstancedMesh"!==n.getClassName()&&(n.material=s[r[t.uniqueId]])}else"MultiMaterial"===n.material.getClassName()?-1===this.scene.multiMaterials.indexOf(n.material)&&this.scene.addMultiMaterial(n.material):-1===this.scene.materials.indexOf(n.material)&&this.scene.addMaterial(n.material)}null===o.parent&&n.rootNodes.push(o)};return u.forEach((e=>{if("InstancedMesh"===e.getClassName()){const t=e,i=t.sourceMesh,n=r[i.uniqueId],o=("number"==typeof n?s[n]:i).createInstance(t.name);d(t,o)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?t=!1:l.doNotInstantiate&&(t="function"==typeof l.doNotInstantiate?!l.doNotInstantiate(e):!l.doNotInstantiate);const i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw new Error(`Could not clone or instantiate node on Asset Container ${e.name}`);d(e,i)}})),this.skeletons.forEach((t=>{if(l.predicate&&!l.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name);for(const e of this.meshes)if(e.skeleton===t&&!e.isAnInstance){const t=s[r[e.uniqueId]];if(!t||t.isAnInstance)continue;if(t.skeleton=i,-1!==o.indexOf(i))continue;o.push(i);for(const e of i.bones)e._linkedTransformNode&&(e._linkedTransformNode=s[r[e._linkedTransformNode.uniqueId]])}n.skeletons.push(i)})),this.animationGroups.forEach((t=>{if(l.predicate&&!l.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name,(e=>s[r[e.uniqueId]]||e));n.animationGroups.push(i)})),n}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||Ue.S0.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((t=>{e&&!e(t)||this.scene.addSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.addAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.addAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.addMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.addMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.addMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.addGeometry(t)})),this.transformNodes.forEach((i=>{e&&!e(i)||(this.scene.addTransformNode(i),t.push(i))})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.addActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.addTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.addReflectionProbe(t)}));for(const e of t)e.parent&&-1===this.scene.getNodes().indexOf(e.parent)&&(e.setParent?e.setParent(null):e.parent=null)}removeAllFromScene(){this._isValidHierarchy()||Ue.S0.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!1,this.removeFromScene(null),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this)}removeFromScene(e=null){this.cameras.forEach((t=>{e&&!e(t)||this.scene.removeCamera(t)})),this.lights.forEach((t=>{e&&!e(t)||this.scene.removeLight(t)})),this.meshes.forEach((t=>{e&&!e(t)||this.scene.removeMesh(t,!0)})),this.skeletons.forEach((t=>{e&&!e(t)||this.scene.removeSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.removeAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.removeAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.removeMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.removeMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.removeMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.removeGeometry(t)})),this.transformNodes.forEach((t=>{e&&!e(t)||this.scene.removeTransformNode(t)})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.removeActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.removeTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.removeReflectionProbe(t)}))}dispose(){this.cameras.slice(0).forEach((e=>{e.dispose()})),this.cameras.length=0,this.lights.slice(0).forEach((e=>{e.dispose()})),this.lights.length=0,this.meshes.slice(0).forEach((e=>{e.dispose()})),this.meshes.length=0,this.skeletons.slice(0).forEach((e=>{e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((e=>{e.dispose()})),this.animationGroups.length=0,this.multiMaterials.slice(0).forEach((e=>{e.dispose()})),this.multiMaterials.length=0,this.materials.slice(0).forEach((e=>{e.dispose()})),this.materials.length=0,this.geometries.slice(0).forEach((e=>{e.dispose()})),this.geometries.length=0,this.transformNodes.slice(0).forEach((e=>{e.dispose()})),this.transformNodes.length=0,this.actionManagers.slice(0).forEach((e=>{e.dispose()})),this.actionManagers.length=0,this.textures.slice(0).forEach((e=>{e.dispose()})),this.textures.length=0,this.reflectionProbes.slice(0).forEach((e=>{e.dispose()})),this.reflectionProbes.length=0,this.morphTargetManagers.slice(0).forEach((e=>{e.dispose()})),this.morphTargetManagers.length=0,this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(e&&t)for(const r of e){let e=!0;if(i)for(const t of i)if(r===t){e=!1;break}e&&(t.push(r),r._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,void 0===e&&(e=new Zt);for(const t in this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||("_environmentTexture"===t?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()}createRootMesh(){const e=new Yt("assetContainerRootMesh",this.scene);return this.meshes.forEach((t=>{t.parent||e.addChild(t)})),this.meshes.unshift(e),e}mergeAnimationsTo(e=he.q.LastCreatedScene,t,i=null){if(!e)return Z.V.Error("No scene available to merge animations to"),[];const r=i||(t=>{let i=null;const r=t.animations.length?t.animations[0].targetProperty:"",s=t.name.split(".").join("").split("_primitive")[0];switch(r){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(s);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(s);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(s)}return i});this.getNodes().forEach((e=>{const t=r(e);if(null!==t){for(const i of e.animations){const e=t.animations.filter((e=>e.targetProperty===i.targetProperty));for(const i of e){const e=t.animations.indexOf(i,0);e>-1&&t.animations.splice(e,1)}}t.animations=t.animations.concat(e.animations)}}));const s=[];return this.animationGroups.slice().forEach((e=>{s.push(e.clone(e.name,r)),e.animatables.forEach((e=>{e.stop()}))})),t.forEach((t=>{const i=r(t.target);i&&(e.beginAnimation(i,t.fromFrame,t.toFrame,t.loopAnimation,t.speedRatio,t.onAnimationEnd?t.onAnimationEnd:void 0,void 0,!0,void 0,t.onAnimationLoop?t.onAnimationLoop:void 0),e.stopAnimation(t.target))})),s}populateRootNodes(){this.rootNodes.length=0,this.meshes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.transformNodes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.lights.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.cameras.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}))}addAllAssetsToContainer(e){if(!e)return;const t=[],i=new Set;for(t.push(e);t.length>0;){const e=t.pop();if(e instanceof Yt?(e.geometry&&-1===this.geometries.indexOf(e.geometry)&&this.geometries.push(e.geometry),this.meshes.push(e)):e instanceof Pt?this.transformNodes.push(e):e instanceof $t?this.lights.push(e):e instanceof rt&&this.cameras.push(e),e instanceof Nt){if(e.material&&-1===this.materials.indexOf(e.material)){this.materials.push(e.material);for(const t of e.material.getActiveTextures())-1===this.textures.indexOf(t)&&this.textures.push(t)}e.skeleton&&-1===this.skeletons.indexOf(e.skeleton)&&this.skeletons.push(e.skeleton),e.morphTargetManager&&-1===this.morphTargetManagers.indexOf(e.morphTargetManager)&&this.morphTargetManagers.push(e.morphTargetManager)}for(const r of e.getChildren())i.has(r)||t.push(r);i.add(e)}this.populateRootNodes()}}class ti{constructor(e){this.SMOOTHING=.75,this.FFT_SIZE=512,this.BARGRAPHAMPLITUDE=256,this.DEBUGCANVASPOS={x:20,y:20},this.DEBUGCANVASSIZE={width:320,height:200},(e=e||he.q.LastCreatedScene)&&(this._scene=e,Ot.$.audioEngine?(this._audioEngine=Ot.$.audioEngine,this._audioEngine.canUseWebAudio&&this._audioEngine.audioContext&&(this._webAudioAnalyser=this._audioEngine.audioContext.createAnalyser(),this._webAudioAnalyser.minDecibels=-140,this._webAudioAnalyser.maxDecibels=0,this._byteFreqs=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._byteTime=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._floatFreqs=new Float32Array(this._webAudioAnalyser.frequencyBinCount))):Ue.S0.Warn("No audio engine initialized, failed to create an audio analyser"))}getFrequencyBinCount(){return this._audioEngine.canUseWebAudio?this._webAudioAnalyser.frequencyBinCount:0}getByteFrequencyData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs)),this._byteFreqs}getByteTimeDomainData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteTimeDomainData(this._byteTime)),this._byteTime}getFloatFrequencyData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs)),this._floatFreqs}drawDebugCanvas(){if(this._audioEngine.canUseWebAudio&&(this._debugCanvas||(this._debugCanvas=document.createElement("canvas"),this._debugCanvas.width=this.DEBUGCANVASSIZE.width,this._debugCanvas.height=this.DEBUGCANVASSIZE.height,this._debugCanvas.style.position="absolute",this._debugCanvas.style.top=this.DEBUGCANVASPOS.y+"px",this._debugCanvas.style.left=this.DEBUGCANVASPOS.x+"px",this._debugCanvasContext=this._debugCanvas.getContext("2d"),document.body.appendChild(this._debugCanvas),this._registerFunc=()=>{this.drawDebugCanvas()},this._scene.registerBeforeRender(this._registerFunc)),this._registerFunc&&this._debugCanvasContext)){const e=this.getByteFrequencyData();this._debugCanvasContext.fillStyle="rgb(0, 0, 0)",this._debugCanvasContext.fillRect(0,0,this.DEBUGCANVASSIZE.width,this.DEBUGCANVASSIZE.height);for(let t=0;tnew ri(e,t,i);class ri{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 z.cP,this.onAudioLockedObservable=new z.cP,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!(0,ii.BA)())return;void 0!==window.AudioContext&&(this.canUseWebAudio=!0);const r=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{r&&r.canPlayType&&(r.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||r.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch(e){}try{r&&r.canPlayType&&r.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}lock(){this._triggerSuspendedState()}unlock(){if("running"===this._audioContext?.state)return this._hideMuteButton(),void(this.unlocked||(this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)));this._tryToRun?this._audioContext?.suspend().then((()=>{this._tryToRun=!1,this._triggerRunningState()})):this._triggerRunningState()}_resumeAudioContextOnStateChange(){this._audioContext?.addEventListener("statechange",(()=>{this.unlocked&&"running"!==this._audioContext?.state&&this._resumeAudioContext()}),{once:!0,passive:!0,signal:AbortSignal.timeout(3e3)})}_resumeAudioContext(){return this._audioContext?.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,"running"===this._audioContext.state&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,Z.V.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 e=".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) }",t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),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 si{get loop(){return this._loop}set loop(e){e!==this._loop&&(this._loop=e,this.updateOptions({loop:e}))}get currentTime(){if(this._htmlAudioElement)return this._htmlAudioElement.currentTime;if(Ot.$.audioEngine?.audioContext&&(this.isPlaying||this.isPaused)){const e=this.isPaused?0:Ot.$.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+e}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){if(e==this._spatialSound)return;const t=this.isPlaying;this.pause(),e?(this._spatialSound=e,this._updateSpatialParameters()):this._disableSpatialSound(),t&&this.play()}constructor(e,t,i,r=null,s){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 z.cP,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=W.Pq.Zero(),this._localDirection=new W.Pq(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||he.q.LastCreatedScene)if(this._scene=i,si._SceneComponentInitialization(i),this._readyToPlayCallback=r,this._customAttenuationFunction=(e,t,i,r,s)=>t0&&(r=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":i.push(t);case"Array":0===i.length&&(i=t);for(let e=0;e{this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback()}),{once:!0}),document.body.appendChild(this._htmlAudioElement),this._htmlAudioElement.load()):this._scene._loadFile(t,(e=>{this._soundLoaded(e)}),void 0,!0,!0,(e=>{e&&Z.V.Error("XHR "+e.status+" error on: "+t+"."),Z.V.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}));break}}break;default:e=!1}e?r||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)):Z.V.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){Z.V.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),Ot.$.audioEngine&&!Ot.$.audioEngine.WarnedWebAudioUnsupported&&(Z.V.Error("Web Audio is not supported by your browser."),Ot.$.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)}dispose(){Ot.$.audioEngine?.canUseWebAudio&&(this.isPlaying&&this.stop(),this._isReadyToPlay=!1,-1===this.soundTrackId?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._htmlAudioElement=null),this._streamingSource&&(this._streamingSource.disconnect(),this._streamingSource=null),this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedTransformNode=null),this._clearTimeoutsAndObservers())}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){Ot.$.audioEngine?.audioContext&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){Ot.$.audioEngine?.audioContext&&Ot.$.audioEngine.audioContext.decodeAudioData(e,(e=>{this._audioBufferLoaded(e)}),(e=>{Z.V.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)}))}setAudioBuffer(e){Ot.$.audioEngine?.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),void 0!==this._offset&&this._soundSource.loopStart!==this._offset&&(this._soundSource.loopStart=this._offset),void 0!==this._length&&this._length!==this._soundSource.loopEnd&&(this._soundSource.loopEnd=(0|this._offset)+this._length))))}_createSpatialParameters(){Ot.$.audioEngine?.canUseWebAudio&&Ot.$.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=this._soundPanner??Ot.$.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_disableSpatialSound(){this._spatialSound&&(this._inputAudioNode=this._soundGain,this._soundPanner?.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(){Ot.$.audioEngine?.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){Ot.$.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){t{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource&&(this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode)),this._htmlAudioElement){const e=()=>{if(Ot.$.audioEngine?.unlocked){if(!this._htmlAudioElement)return;this._htmlAudioElement.currentTime=t??0;const i=this._htmlAudioElement.play();void 0!==i&&i.catch((()=>{Ot.$.audioEngine?.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=Ot.$.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))}))}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=Ot.$.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))};e()}}else{const s=()=>{if(Ot.$.audioEngine?.audioContext){if(i=i||this._length,void 0!==t&&this._setOffset(t),this._soundSource){const e=this._soundSource;e.onended=()=>{e.disconnect()}}if(this._soundSource=Ot.$.audioEngine?.audioContext.createBufferSource(),this._soundSource&&this._inputAudioNode){this._soundSource.buffer=this._audioBuffer,this._soundSource.connect(this._inputAudioNode),this._soundSource.loop=this.loop,void 0!==t&&(this._soundSource.loopStart=t),void 0!==i&&(this._soundSource.loopEnd=(0|t)+i),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},r=e?Ot.$.audioEngine?.audioContext.currentTime+e:Ot.$.audioEngine.audioContext.currentTime;const s=((this.isPaused?this.currentTime:0)+(this._offset??0))%this._soundSource.buffer.duration;this._soundSource.start(r,s,this.loop?void 0:i)}}};"suspended"===Ot.$.audioEngine?.audioContext.state?this._tryToPlayTimeout=setTimeout((()=>{"suspended"===Ot.$.audioEngine?.audioContext.state?(Ot.$.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=Ot.$.audioEngine.onAudioUnlockedObservable.addOnce((()=>{s()})))):s()}),500):s()}this._startTime=r,this.isPlaying=!0,this.isPaused=!1}catch(e){Z.V.Error("Error while trying to play audio: "+this.name+", "+e.message)}}_onended(){this.isPlaying=!1,this._startTime=0,this._currentTime=0,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)}stop(e){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(Ot.$.audioEngine?.audioContext&&this._soundSource){const t=e?Ot.$.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(t)}else this.isPlaying=!1;else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource?.disconnect(),this.isPlaying=!1,this.isPaused=!0):Ot.$.audioEngine?.audioContext&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=Ot.$.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){Ot.$.audioEngine?.canUseWebAudio&&this._soundGain&&(t&&Ot.$.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(Ot.$.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,Ot.$.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,Ot.$.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=e=>this._onRegisterAfterWorldMatrixUpdate(e),this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)}detachFromMesh(){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedTransformNode=null)}_onRegisterAfterWorldMatrixUpdate(e){if(e.getBoundingInfo){const t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);Ot.$.audioEngine?.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 si(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,t);return this.useCustomAttenuation&&i.setAttenuationFunction(this._customAttenuationFunction),i.setPosition(this._position),i.setPlaybackRate(this._playbackRate),e(),i}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){const e={name:this.name,url:this._url,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this._spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e}static Parse(e,t,i,r){const s=e.name;let n;n=e.url?i+e.url:i+s;const o={autoplay:e.autoplay,loop:e.loop,volume:e.volume,spatialSound:e.spatialSound,maxDistance:e.maxDistance,rolloffFactor:e.rolloffFactor,refDistance:e.refDistance,distanceModel:e.distanceModel,playbackRate:e.playbackRate};let a;if(r){const e=()=>{r._isReadyToPlay?(a._audioBuffer=r.getAudioBuffer(),a._isReadyToPlay=!0,a.autoplay&&a.play(0,a._offset,a._length)):setTimeout(e,300)};a=new si(s,new ArrayBuffer(0),t,null,o),e()}else a=new si(s,n,t,(()=>{t.removePendingData(a)}),o),t.addPendingData(a);if(e.position){const t=W.Pq.FromArray(e.position);a.setPosition(t)}if(e.isDirectional&&(a.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const t=W.Pq.FromArray(e.localDirectionToMesh);a.setLocalDirectionToMesh(t)}if(e.connectedMeshId){const i=t.getMeshById(e.connectedMeshId);i&&a.attachToMesh(i)}return e.metadata&&(a.metadata=e.metadata),a}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}_clearTimeoutsAndObservers(){this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&(Ot.$.audioEngine?.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}si._SceneComponentInitialization=e=>{throw(0,Je.n)("AudioSceneComponent")},(0,X.Y5)("BABYLON.Sound",si);class ni{constructor(e,t={}){this.id=-1,this._isInitialized=!1,(e=e||he.q.LastCreatedScene)&&(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(){Ot.$.audioEngine?.canUseWebAudio&&Ot.$.audioEngine.audioContext&&(this._outputAudioNode=Ot.$.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(Ot.$.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(Ot.$.audioEngine&&Ot.$.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){this._isInitialized||this._initializeSoundTrackAudioGraph(),Ot.$.audioEngine?.canUseWebAudio&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),void 0!==e.soundTrackId&&(-1===e.soundTrackId?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);-1!==t&&this.soundCollection.splice(t,1)}setVolume(e){Ot.$.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){if(Ot.$.audioEngine?.canUseWebAudio)for(let e=0;e{let s,n=[];if(i.sounds=i.sounds||[],void 0!==e.sounds&&null!==e.sounds)for(let o=0,a=e.sounds.length;o{e.play(),e.autoplay=!0,this.scene.mainSoundTrack.addSound(e)}))}removeFromContainer(e,t=!1){e.sounds&&e.sounds.forEach((e=>{e.stop(),e.autoplay=!1,this.scene.mainSoundTrack.removeSound(e),t&&e.dispose()}))}dispose(){const e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t0&&(r=t.activeCameras[0]),this.audioListenerPositionProvider){const e=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(e.x||0,e.y||0,e.z||0)}else r?this._cachedCameraPosition.equals(r.globalPosition)||(this._cachedCameraPosition.copyFrom(r.globalPosition),i.audioContext.listener.setPosition(r.globalPosition.x,r.globalPosition.y,r.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){const e=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(e.x||0,e.y||0,e.z||0,0,1,0)}else r?(r.rigCameras&&r.rigCameras.length>0&&(r=r.rigCameras[0]),r.getViewMatrix().invertToRef(this._invertMatrixTemp),W.Pq.TransformNormalToRef(_i._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);for(e=0;e{let t=e._getComponent(Ut.v.NAME_AUDIO);t||(t=new _i(e),e._addComponent(t))};class mi{constructor(e,t,i){if(this.loop=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._volume=1,this.isPlaying=!1,this.isPaused=!1,this._sounds=[],this._weights=[],t.length!==i.length)throw new Error("Sounds length does not equal weights length");this.loop=e,this._weights=i;let r=0;for(const e of i)r+=e;const s=r>0?1/r:0;for(let e=0;e{this._onended()}))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!==this._coneInnerAngle){if(this._coneOuterAnglee),this)}serialize(){return it.p.Serialize(this)}parse(e,t,i){it.p.Parse((()=>this),e,t,i)}}(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markSubMeshesAsAttributesDirty")],gi.prototype,"texture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markSubMeshesAsAttributesDirty")],gi.prototype,"isEnabled",void 0),(0,je.Cg)([(0,$e.lK)()],gi.prototype,"animationParameters",void 0),(0,je.Cg)([(0,$e.lK)()],gi.prototype,"time",void 0);var vi=i(4756);class xi extends vi.g{constructor(e,t,i,r,s,n=!0,o=!1,a=3,l=0,h,c){super(null,s,!n,o,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,h),this.format=r,this._engine&&(this._engine._caps.textureFloatLinearFiltering||1!==l||(a=1),this._engine._caps.textureHalfFloatLinearFiltering||2!==l||(a=1),this._texture=this._engine.createRawTexture(e,t,i,r,n,o,a,null,l,h??0,c??!1),this.wrapU=vi.g.CLAMP_ADDRESSMODE,this.wrapV=vi.g.CLAMP_ADDRESSMODE)}update(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer)}clone(){if(!this._texture)return super.clone();const e=new xi(null,this.getSize().width,this.getSize().height,this.format,this.getScene(),this._texture.generateMipMaps,this._invertY,this.samplingMode,this._texture.type,this._texture._creationFlags,this._useSRGBBuffer);return e._texture=this._texture,this._texture.incrementReferences(),e}static CreateLuminanceTexture(e,t,i,r,s=!0,n=!1,o=3){return new xi(e,t,i,1,r,s,n,o)}static CreateLuminanceAlphaTexture(e,t,i,r,s=!0,n=!1,o=3){return new xi(e,t,i,2,r,s,n,o)}static CreateAlphaTexture(e,t,i,r,s=!0,n=!1,o=3){return new xi(e,t,i,0,r,s,n,o)}static CreateRGBTexture(e,t,i,r,s=!0,n=!1,o=3,a=0,l=0,h=!1){return new xi(e,t,i,4,r,s,n,o,a,l,h)}static CreateRGBATexture(e,t,i,r,s=!0,n=!1,o=3,a=0,l=0,h=!1){return new xi(e,t,i,5,r,s,n,o,a,l,h)}static CreateRGBAStorageTexture(e,t,i,r,s=!0,n=!1,o=3,a=0,l=!1){return new xi(e,t,i,5,r,s,n,o,a,1,l)}static CreateRTexture(e,t,i,r,s=!0,n=!1,o=vi.g.TRILINEAR_SAMPLINGMODE,a=1){return new xi(e,t,i,6,r,s,n,o,a)}static CreateRStorageTexture(e,t,i,r,s=!0,n=!1,o=vi.g.TRILINEAR_SAMPLINGMODE,a=1){return new xi(e,t,i,6,r,s,n,o,a,1)}}var bi=i(5800),Si=i(87665);class Ti{get useTextureToStoreBoneMatrices(){return this._useTextureToStoreBoneMatrices}set useTextureToStoreBoneMatrices(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}get isUsingTextureForMatrices(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones}get uniqueId(){return this._uniqueId}constructor(e,t,i){this.name=e,this.id=t,this.bones=[],this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=W.uq.Identity(),this._currentRenderId=-1,this._ranges={},this._absoluteTransformIsDirty=!0,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new z.cP,this.bones=[],this._scene=i||he.q.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;const r=this._scene.getEngine().getCaps();this._canUseTextureForBones=r.textureFloat&&r.maxVertexTextureImageUnits>0}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 e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;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 e of this.bones)if(e._linkedTransformNode){const t=e._linkedTransformNode;e.position=t.position,t.rotationQuaternion?e.rotationQuaternion=t.rotationQuaternion:e.rotation=t.rotation,e.scaling=t.scaling}if(this.needInitialSkinMatrix)for(const e of this._meshesWithPoseMatrix){const t=e.getPoseMatrix();let i=this._isDirty;if(e._bonesTransformMatrices&&e._bonesTransformMatrices.length===16*(this.bones.length+1)||(e._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),i=!0),i){if(this._synchronizedWithMesh!==e){this._synchronizedWithMesh=e;for(const e of this.bones)e.getParent()||(e.getBindMatrix().multiplyToRef(t,W.AA.Matrix[1]),e._updateAbsoluteBindMatrices(W.AA.Matrix[1]));if(this.isUsingTextureForMatrices){const t=4*(this.bones.length+1);e._transformMatrixTexture&&e._transformMatrixTexture.getSize().width===t||(e._transformMatrixTexture&&e._transformMatrixTexture.dispose(),e._transformMatrixTexture=xi.CreateRGBATexture(e._bonesTransformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))}}this._computeTransformMatrices(e._bonesTransformMatrices,t),this.isUsingTextureForMatrices&&e._transformMatrixTexture&&e._transformMatrixTexture.update(e._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=xi.CreateRGBATexture(this._transformMatrices,4*(this.bones.length+1),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((t=>{t.enableBlending=!0,t.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(){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 t=0;t0&&(s.animation=i.animations[0].serialize()),e.ranges=[];for(const t in this._ranges){const i=this._ranges[t];if(!i)continue;const r={};r.name=t,r.from=i.from,r.to=i.to,e.ranges.push(r)}}return e}static Parse(e,t){const i=new Ti(e.name,e.id,t);let r;for(e.dimensionsAtRest&&(i.dimensionsAtRest=W.Pq.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix,r=0;r-1&&(n=i.bones[t.parentBoneIndex]);const o=t.rest?W.uq.FromArray(t.rest):null,a=new Si.$(t.name,i,n,W.uq.FromArray(t.matrix),o,null,s);void 0!==t.id&&null!==t.id&&(a.id=t.id),t.length&&(a.length=t.length),t.metadata&&(a.metadata=t.metadata),t.animation&&a.animations.push(pe.X5.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(i._hasWaitingData=!0,a._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(r=0;r0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=[],t=new Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()}))}}class Ci{constructor(e,t){this._scene=e,t instanceof Ti?(this._skeleton=t,this._mesh=null):(this._mesh=t,this._skeleton=t.skeleton)}async bakeVertexData(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=e.reduce(((e,t)=>e+t.to-t.from+1),0);if(isNaN(i))throw new Error("Invalid animation ranges.");let r=0;const s=new Float32Array(4*(t+1)*4*i);this._scene.stopAnimation(this._skeleton),this._skeleton.returnToRest();for(const t of e)for(let e=t.from;e<=t.to;e++)await this._executeAnimationFrame(s,e,r++);return s}async _executeAnimationFrame(e,t,i){return new Promise(((r,s)=>{this._scene.beginAnimation(this._skeleton,t,t,!1,1,(()=>{const t=this._skeleton.getTransformMatrices(this._mesh);e.set(t,i*t.length),r()}))}))}textureFromBakedVertexData(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=xi.CreateRGBATexture(e,4*(t+1),e.length/(4*(t+1)*4),this._scene,!1,!1,vi.g.NEAREST_NEAREST,1);return i.name="VAT"+this._skeleton.name,i}serializeBakedVertexDataToObject(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=4*(t+1),r=e.length/(4*(t+1)*4);return{vertexData:(0,bi.EL)(e),width:i,height:r}}loadBakedVertexDataFromObject(e){return new Float32Array((0,bi.yS)(e.vertexData))}serializeBakedVertexDataToJSON(e){return JSON.stringify(this.serializeBakedVertexDataToObject(e))}loadBakedVertexDataFromJSON(e){return this.loadBakedVertexDataFromObject(JSON.parse(e))}}var yi=i(1241);class Ei{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((e=>{e.type!==yi.Zp.POINTERDOWN?e.type===yi.Zp.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{if(this._reachTargetAlpha())return;const e=ai.j.Now;let t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();const i=e-this._lastInteractionTime-this._idleRotationWaitTime,r=Math.max(Math.min(i/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*r,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/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,this._lastFrameTime=null}resetLastInteractionTime(e){this._lastInteractionTime=e??ai.j.Now}_reachTargetAlpha(){return!(!this._attachedCamera||!this.targetAlpha)&&Math.abs(this._attachedCamera.alpha-this.targetAlpha){if(e&&(e.computeWorldMatrix(!0),e.getBoundingInfo)){const t=e.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=.05*t,this.upperRadiusTransitionRange=.05*t}})):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}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(Pi.EasingFunction.setEasingMode(Pi.EasingMode),this._radiusBounceTransition=pe.X5.CreateAnimation("radius",pe.X5.ANIMATIONTYPE_FLOAT,60,Pi.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=pe.X5.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()}}Pi.EasingFunction=new Se(.3),Pi.EasingMode=xe.EASINGMODE_EASEOUT;class Ai{constructor(){this.onTargetFramingAnimationEndObservable=new z.cP,this._mode=Ai.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();Ai.EasingFunction.setEasingMode(Ai.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==yi.Zp.POINTERDOWN?e.type===yi.Zp.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add((e=>{e&&e.getBoundingInfo&&this.zoomOnMesh(e,void 0,(()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()}))})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}zoomOnMesh(e,t=!1,i=null){e.computeWorldMatrix(!0);const r=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(r.minimumWorld,r.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);const r=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(r.min,r.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){const r=new W.Pq(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new W.Pq(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t{this.stopAllAnimations(),r&&r(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()})),l&&this._animatables.push(l),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=this._attachedCamera;if(!i)return 0;let r=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===Ai.IgnoreBoundsSizeMode&&(r=ri.upperRadiusLimit?i.upperRadiusLimit:r),r}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=ai.j.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation,i=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=pe.X5.CreateAnimation("beta",pe.X5.ANIMATIONTYPE_FLOAT,60,Ai.EasingFunction));const e=pe.X5.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,(()=>{this._clearAnimationLocks(),this.stopAllAnimations()}));e&&this._animatables.push(e)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=ai.j.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&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)}}Ai.EasingFunction=new Ee,Ai.EasingMode=xe.EASINGMODE_EASEINOUT,Ai.IgnoreBoundsSizeMode=0,Ai.FitFrustumSidesMode=1;class Ri{constructor(e,t=new W.Pq,i=0,r=!1){this.direction=e,this.rotatedDirection=t,this.diff=i,this.ignore=r}}class Ii{constructor(e){this._ui=e,this.name="AttachToBoxBehavior",this.distanceAwayFromFace=.15,this.distanceAwayFromBottomOfFace=.15,this._faceVectors=[new Ri(W.Pq.Up()),new Ri(W.Pq.Down()),new Ri(W.Pq.Left()),new Ri(W.Pq.Right()),new Ri(W.Pq.Forward()),new Ri(W.Pq.Forward().scaleInPlace(-1))],this._tmpMatrix=new W.uq,this._tmpVector=new W.Pq,this._zeroVector=W.Pq.Zero(),this._lookAtTmpMatrix=new W.uq}init(){}_closestFace(e){return this._faceVectors.forEach((t=>{this._target.rotationQuaternion||(this._target.rotationQuaternion=W.PT.RotationYawPitchRoll(this._target.rotation.y,this._target.rotation.x,this._target.rotation.z)),this._target.rotationQuaternion.toRotationMatrix(this._tmpMatrix),W.Pq.TransformCoordinatesToRef(t.direction,this._tmpMatrix,t.rotatedDirection),t.diff=W.Pq.GetAngleBetweenVectors(t.rotatedDirection,e,W.Pq.Cross(t.rotatedDirection,e))})),this._faceVectors.reduce(((e,t)=>e.ignore?t:t.ignore||e.diff{if(!this._scene.activeCamera)return;let t=this._scene.activeCamera.position;this._scene.activeCamera.devicePosition&&(t=this._scene.activeCamera.devicePosition);const i=this._closestFace(t.subtract(e.position));this._scene.activeCamera.leftCamera?this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix):this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix),W.Pq.TransformCoordinatesToRef(W.Pq.Up(),this._tmpMatrix,this._tmpVector),this._faceVectors.forEach((e=>{i.direction.x&&e.direction.x&&(e.ignore=!0),i.direction.y&&e.direction.y&&(e.ignore=!0),i.direction.z&&e.direction.z&&(e.ignore=!0)}));const r=this._closestFace(this._tmpVector);this._faceVectors.forEach((e=>{e.ignore=!1})),this._ui.position.copyFrom(e.position),i.direction.x&&(i.rotatedDirection.scaleToRef(e.scaling.x/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),i.direction.y&&(i.rotatedDirection.scaleToRef(e.scaling.y/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),i.direction.z&&(i.rotatedDirection.scaleToRef(e.scaling.z/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),this._ui.rotationQuaternion||(this._ui.rotationQuaternion=W.PT.RotationYawPitchRoll(this._ui.rotation.y,this._ui.rotation.x,this._ui.rotation.z)),i.rotatedDirection.scaleToRef(-1,this._tmpVector),this._lookAtToRef(this._tmpVector,r.rotatedDirection,this._ui.rotationQuaternion),r.direction.x&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.x/2,this._tmpVector),r.direction.y&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.y/2,this._tmpVector),r.direction.z&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.z/2,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)}))}detach(){this._scene.onBeforeRenderObservable.remove(this._onRenderObserver)}}class Mi{get delay(){return this.fadeInDelay}set delay(e){this.fadeInDelay=e,this.fadeOutDelay=e}constructor(){this.fadeInDelay=0,this.fadeOutDelay=0,this.fadeInTime=300,this.fadeOutTime=300,this._millisecondsPerFrame=1e3/60,this._hovered=!1,this._hoverValue=0,this._ownerNode=null,this._delay=0,this._time=300,this._update=()=>{if(this._ownerNode){if(this._hoverValue+=this._hovered?this._millisecondsPerFrame:-this._millisecondsPerFrame,this._setAllVisibility(this._ownerNode,(this._hoverValue-this._delay)/this._time),this._ownerNode.visibility>1){if(this._setAllVisibility(this._ownerNode,1),this._hoverValue>this._time)return this._hoverValue=this._time,void this._detachObserver()}else if(this._ownerNode.visibility<0&&(this._setAllVisibility(this._ownerNode,0),this._hoverValue<0))return this._hoverValue=0,void this._detachObserver();this._attachObserver()}}}get name(){return"FadeInOut"}init(){}attach(e){this._ownerNode=e,this._setAllVisibility(this._ownerNode,0)}detach(){this._ownerNode=null}fadeIn(e=!0){this._delay=e?this.fadeInDelay:this.fadeOutDelay,this._time=e?this.fadeInTime:this.fadeOutTime,this._detachObserver(),this._ownerNode&&(e&&this._ownerNode.visibility>=1||!e&&this._ownerNode.visibility<=0)||(this._hovered=e,this._hovered||(this._delay*=-1),this._ownerNode.visibility>=1?this._hoverValue=this._time:this._ownerNode.visibility<=0&&(this._hoverValue=0),this._update())}fadeOut(){this.fadeIn(!1)}_setAllVisibility(e,t){e.visibility=t,e.getChildMeshes().forEach((e=>{this._setAllVisibility(e,t)}))}_attachObserver(){this._onBeforeRenderObserver||(this._onBeforeRenderObserver=this._ownerNode?.getScene().onBeforeRenderObservable.add(this._update))}_detachObserver(){this._onBeforeRenderObserver&&(this._ownerNode?.getScene().onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=null)}}var Oi=i(83194);const Di={internalPickerForMesh:void 0};class wi{constructor(e,t,i=Number.MAX_VALUE,r=lt.bH){this.origin=e,this.direction=t,this.length=i,this.epsilon=r}clone(){return new wi(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const r=wi._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),s=wi._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let n,o,a,l,h=0,c=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xs.x)return!1}else if(n=1/this.direction.x,o=(r.x-this.origin.x)*n,a=(s.x-this.origin.x)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.ys.y)return!1}else if(n=1/this.direction.y,o=(r.y-this.origin.y)*n,a=(s.y-this.origin.y)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zs.z)return!1}else if(n=1/this.direction.z,o=(r.z-this.origin.z)*n,a=(s.z-this.origin.z)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){const i=e.center.x-this.origin.x,r=e.center.y-this.origin.y,s=e.center.z-this.origin.z,n=i*i+r*r+s*s,o=e.radius+t,a=o*o;if(n<=a)return!0;const l=i*this.direction.x+r*this.direction.y+s*this.direction.z;return!(l<0)&&n-l*l<=a}intersectsTriangle(e,t,i){const r=wi._TmpVector3[0],s=wi._TmpVector3[1],n=wi._TmpVector3[2],o=wi._TmpVector3[3],a=wi._TmpVector3[4];t.subtractToRef(e,r),i.subtractToRef(e,s),W.Pq.CrossToRef(this.direction,s,n);const l=W.Pq.Dot(r,n);if(0===l)return null;const h=1/l;this.origin.subtractToRef(e,o);const c=W.Pq.Dot(o,n)*h;if(c<-this.epsilon||c>1+this.epsilon)return null;W.Pq.CrossToRef(o,r,a);const u=W.Pq.Dot(this.direction,a)*h;if(u<-this.epsilon||c+u>1+this.epsilon)return null;const d=W.Pq.Dot(s,a)*h;return d>this.length?null:new ot(1-c-u,c,d)}intersectsPlane(e){let t;const i=W.Pq.Dot(e.normal,this.direction);if(Math.abs(i)<9.99999997475243e-7)return null;{const r=W.Pq.Dot(e.normal,this.origin);return t=(-e.d-r)/i,t<0?t<-9.99999997475243e-7?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{const e=(this.origin.y-t)/this.direction.y;return e>0?null:new W.Pq(this.origin.x+this.direction.x*-e,t,this.origin.z+this.direction.z*-e)}case"x":{const e=(this.origin.x-t)/this.direction.x;return e>0?null:new W.Pq(t,this.origin.y+this.direction.y*-e,this.origin.z+this.direction.z*-e)}case"z":{const e=(this.origin.z-t)/this.direction.z;return e>0?null:new W.Pq(this.origin.x+this.direction.x*-e,this.origin.y+this.direction.y*-e,t)}default:return null}}intersectsMesh(e,t,i,r=!1,s,n=!1){const o=W.AA.Matrix[0];return e.getWorldMatrix().invertToRef(o),this._tmpRay?wi.TransformToRef(this,o,this._tmpRay):this._tmpRay=wi.Transform(this,o),e.intersects(this._tmpRay,t,i,r,s,n)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let r=0;rt.distance?1:0}intersectionSegment(e,t,i){const r=this.origin,s=W.AA.Vector3[0],n=W.AA.Vector3[1],o=W.AA.Vector3[2],a=W.AA.Vector3[3];t.subtractToRef(e,s),this.direction.scaleToRef(wi._Rayl,o),r.addToRef(o,n),e.subtractToRef(r,a);const l=W.Pq.Dot(s,s),h=W.Pq.Dot(s,o),c=W.Pq.Dot(o,o),u=W.Pq.Dot(s,a),d=W.Pq.Dot(o,a),f=l*c-h*h;let p,_,m=f,g=f;fm&&(p=m,_=d+h,g=c)),_<0?(_=0,-u<0?p=0:-u>l?p=m:(p=-u,m=l)):_>g&&(_=g,-u+h<0?p=0:-u+h>l?p=m:(p=-u+h,m=l));const v=Math.abs(p)0&&x<=this.length&&T.lengthSquared()=e.distance?null:h:null}function ki(e,t,i,r,s,n){let o=null;const a=!!(e.activeCameras&&e.activeCameras.length>1&&e.cameraToUseForPointers!==e.activeCamera),l=e.cameraToUseForPointers||e.activeCamera,h=Di.internalPickerForMesh||Vi;for(let c=0;c1&&e.cameraToUseForPointers!==e.activeCamera),o=e.cameraToUseForPointers||e.activeCamera,a=Di.internalPickerForMesh||Vi;for(let l=0;l(e._tempPickingRay||(e._tempPickingRay=wi.Zero()),Fi(e,t,i,r,e._tempPickingRay,n||null),e._tempPickingRay)),r,s,!0);return o&&(o.ray=Ni(e,t,i,W.uq.Identity(),n||null)),o}function zi(e,t,i,r,s,n,o,a=!1){const l=ki(e,((r,s)=>(e._tempPickingRay||(e._tempPickingRay=wi.Zero()),Fi(e,t,i,r,e._tempPickingRay,n||null,!1,s),e._tempPickingRay)),r,s,!1,o);return l&&(l.ray=Ni(e,t,i,W.uq.Identity(),n||null)),l}function Wi(e,t,i,r,s){const n=ki(e,(i=>(e._pickWithRayInverseMatrix||(e._pickWithRayInverseMatrix=W.uq.Identity()),i.invertToRef(e._pickWithRayInverseMatrix),e._cachedRayForTransform||(e._cachedRayForTransform=wi.Zero()),wi.TransformToRef(t,e._pickWithRayInverseMatrix,e._cachedRayForTransform),e._cachedRayForTransform)),i,r,!1,s);return n&&(n.ray=t),n}function Hi(e,t,i,r,s,n){return Ui(e,(r=>Ni(e,t,i,r,s||null)),r,n)}function Xi(e,t,i,r){return Ui(e,(i=>(e._pickWithRayInverseMatrix||(e._pickWithRayInverseMatrix=W.uq.Identity()),i.invertToRef(e._pickWithRayInverseMatrix),e._cachedRayForTransform||(e._cachedRayForTransform=wi.Zero()),wi.TransformToRef(t,e._pickWithRayInverseMatrix,e._cachedRayForTransform),e._cachedRayForTransform)),i,r)}function qi(e,t=100,i,r){return Yi(e,new wi(W.Pq.Zero(),W.Pq.Zero(),t),t,i,r)}function Yi(e,t,i=100,r,s){r||(r=e.getWorldMatrix()),t.length=i,s?t.origin.copyFrom(s):t.origin.copyFrom(e.position);const n=W.AA.Vector3[2];n.set(0,0,e._scene.useRightHandedSystem?-1:1);const o=W.AA.Vector3[3];return W.Pq.TransformNormalToRef(n,r,o),W.Pq.NormalizeToRef(o,t.direction),t}function Ki(e,t){t&&(t.prototype.getForwardRay=function(e=100,t,i){return Yi(this,new wi(W.Pq.Zero(),W.Pq.Zero(),e),e,t,i)},t.prototype.getForwardRayToRef=function(e,t=100,i,r){return Yi(this,e,t,i,r)}),e&&(Oi.h._IsPickingAvailable=!0,e.prototype.createPickingRay=function(e,t,i,r,s=!1){return Ni(this,e,t,i,r,s)})}wi._TmpVector3=(0,at.mI)(6,W.Pq.Zero),wi._RayDistant=wi.Zero(),wi._Smallnum=1e-8,wi._Rayl=1e9,Ki(oi.Z,rt),oi.Z.prototype.createPickingRayToRef=function(e,t,i,r,s,n=!1,o=!1){return Fi(this,e,t,i,r,s,n,o)},oi.Z.prototype.createPickingRayInCameraSpace=function(e,t,i){return Li(this,e,t,i)},oi.Z.prototype.createPickingRayInCameraSpaceToRef=function(e,t,i,r){return Bi(this,e,t,i,r)},oi.Z.prototype.pickWithBoundingInfo=function(e,t,i,r,s){return Gi(this,e,t,i,r,s)},oi.Z.prototype.pick=function(e,t,i,r,s,n,o=!1){return zi(this,e,t,i,r,s,n,o)},oi.Z.prototype.pickWithRay=function(e,t,i,r){return Wi(this,e,t,i,r)},oi.Z.prototype.multiPick=function(e,t,i,r,s){return Hi(this,e,t,i,r,s)},oi.Z.prototype.multiPickWithRay=function(e,t,i){return Xi(this,e,t,i)};class ji{static _RemoveAndStorePivotPoint(e){e&&0===ji._PivotCached&&(e.getPivotPointToRef(ji._OldPivotPoint),ji._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,ji._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(W.uq.IdentityReadOnly),ji._OldPivotPoint.subtractToRef(e.getPivotPoint(),ji._PivotTranslation),ji._PivotTmpVector.copyFromFloats(1,1,1),ji._PivotTmpVector.subtractInPlace(e.scaling),ji._PivotTmpVector.multiplyInPlace(ji._PivotTranslation),e.position.addInPlace(ji._PivotTmpVector))),ji._PivotCached++}static _RestorePivotPoint(e){e&&!ji._OldPivotPoint.equalsToFloats(0,0,0)&&1===ji._PivotCached&&(e.setPivotPoint(ji._OldPivotPoint),e._postMultiplyPivotMatrix=ji._PivotPostMultiplyPivotMatrix,ji._PivotTmpVector.copyFromFloats(1,1,1),ji._PivotTmpVector.subtractInPlace(e.scaling),ji._PivotTmpVector.multiplyInPlace(ji._PivotTranslation),e.position.subtractInPlace(ji._PivotTmpVector)),this._PivotCached--}}function $i(e){const t=[],i=[],r=[],s=[],n=e.width||e.size||1,o=e.height||e.size||1,a=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE,l=n/2,h=o/2;i.push(-l,-h,0),r.push(0,0,-1),s.push(0,Tt.rX?1:0),i.push(l,-h,0),r.push(0,0,-1),s.push(1,Tt.rX?1:0),i.push(l,h,0),r.push(0,0,-1),s.push(1,Tt.rX?0:1),i.push(-l,h,0),r.push(0,0,-1),s.push(0,Tt.rX?0:1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),bt._ComputeSides(a,i,t,r,s,e.frontUVs,e.backUVs);const c=new bt;return c.indices=t,c.positions=i,c.normals=r,c.uvs=s,c}function Qi(e,t={},i=null){const r=new Yt(e,i);return t.sideOrientation=Yt._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,$i(t).applyToMesh(r,t.updatable),t.sourcePlane&&(r.translate(t.sourcePlane.normal,-t.sourcePlane.d),r.setDirection(t.sourcePlane.normal.scale(-1))),r}ji._PivotCached=0,ji._OldPivotPoint=new W.Pq,ji._PivotTranslation=new W.Pq,ji._PivotTmpVector=new W.Pq,ji._PivotPostMultiplyPivotMatrix=!1;const Zi={CreatePlane:Qi};bt.CreatePlane=$i,Yt.CreatePlane=(e,t,i,r,s)=>Qi(e,{size:t,width:t,height:t,sideOrientation:s,updatable:r},i);class Ji{get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}set enabled(e){e!=this._enabled&&this.onEnabledObservable.notifyObservers(e),this._enabled=e}get enabled(){return this._enabled}get options(){return this._options}set options(e){this._options=e}constructor(e){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this._activeDragButton=-1,this.maxDragAngle=0,this.dragButtons=[0,1,2],this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerId=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new z.cP,this.onDragStartObservable=new z.cP,this.onDragEndObservable=new z.cP,this.onEnabledObservable=new z.cP,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=e=>!0,this._tmpVector=new W.Pq(0,0,0),this._alternatePickedPoint=new W.Pq(0,0,0),this._worldDragAxis=new W.Pq(0,0,0),this._targetPosition=new W.Pq(0,0,0),this._attachedToElement=!1,this._startDragRay=new wi(new W.Pq,new W.Pq),this._lastPointerRay={},this._dragDelta=new W.Pq,this._pointA=new W.Pq(0,0,0),this._pointC=new W.Pq(0,0,0),this._localAxis=new W.Pq(0,0,0),this._lookAt=new W.Pq(0,0,0),this._options=e||{};let t=0;if(this._options.dragAxis&&t++,this._options.dragPlaneNormal&&t++,t>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}get name(){return"PointerDrag"}init(){}attach(e,t){this._scene=e.getScene(),e.isNearGrabbable=!0,this.attachedNode=e,Ji._PlaneScene||(this._debugMode?Ji._PlaneScene=this._scene:(Ji._PlaneScene=new oi.Z(this._scene.getEngine(),{virtual:!0}),Ji._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce((()=>{Ji._PlaneScene.dispose(),Ji._PlaneScene=null})))),this._dragPlane=Qi("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:Yt.DOUBLESIDE},Ji._PlaneScene),this.lastDragPosition=new W.Pq(0,0,0);const i=t||(e=>this.attachedNode==e||e.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add((e=>{if(this.enabled){if(e.type==yi.Zp.POINTERDOWN)this.startAndReleaseDragOnPointerEvents&&!this.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&i(e.pickInfo.pickedMesh)&&-1===this._activeDragButton&&-1!==this.dragButtons.indexOf(e.event.button)&&(this._activeDragButton=e.event.button,this._activePointerInfo=e,this._startDrag(e.event.pointerId,e.pickInfo.ray,e.pickInfo.pickedPoint));else if(e.type==yi.Zp.POINTERUP)!this.startAndReleaseDragOnPointerEvents||this.currentDraggingPointerId!=e.event.pointerId||this._activeDragButton!==e.event.button&&-1!==this._activeDragButton||this.releaseDrag();else if(e.type==yi.Zp.POINTERMOVE){const t=e.event.pointerId;if(this.currentDraggingPointerId===Ji._AnyMouseId&&t!==Ji._AnyMouseId){const i=e.event;("mouse"===i.pointerType||!this._scene.getEngine().hostInformation.isMobile&&i instanceof MouseEvent)&&(this._lastPointerRay[this.currentDraggingPointerId]&&(this._lastPointerRay[t]=this._lastPointerRay[this.currentDraggingPointerId],delete this._lastPointerRay[this.currentDraggingPointerId]),this.currentDraggingPointerId=t)}this._lastPointerRay[t]||(this._lastPointerRay[t]=new wi(new W.Pq,new W.Pq)),e.pickInfo&&e.pickInfo.ray&&(this._lastPointerRay[t].origin.copyFrom(e.pickInfo.ray.origin),this._lastPointerRay[t].direction.copyFrom(e.pickInfo.ray.direction),this.currentDraggingPointerId==t&&this.dragging&&this._moveDrag(e.pickInfo.ray))}}else this._attachedToElement&&this.releaseDrag()})),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{if(this._moving&&this.moveAttached){let e=!1;ji._RemoveAndStorePivotPoint(this.attachedNode),this._targetPosition.subtractToRef(this.attachedNode.absolutePosition,this._tmpVector),this._tmpVector.scaleInPlace(this.dragDeltaRatio),this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector,this._tmpVector),this.validateDrag(this._tmpVector)&&(this.attachedNode.setAbsolutePosition(this._tmpVector),e=!0),ji._RestorePivotPoint(this.attachedNode),e&&this.attachedNode.computeWorldMatrix()}}))}releaseDrag(){if(this.dragging&&(this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo})),this.currentDraggingPointerId=-1,this._activeDragButton=-1,this._activePointerInfo=null,this._moving=!1,this.detachCameraControls&&this._attachedToElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera){if("ArcRotateCamera"===this._scene.activeCamera.getClassName()){const e=this._scene.activeCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._scene.activeCamera.attachControl(!this._scene.activeCamera.inputs||this._scene.activeCamera.inputs.noPreventDefault);this._attachedToElement=!1}}startDrag(e=Ji._AnyMouseId,t,i){this._startDrag(e,t,i);let r=this._lastPointerRay[e];e===Ji._AnyMouseId&&(r=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),r&&this._moveDrag(r)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;ji._RemoveAndStorePivotPoint(this.attachedNode),t?(this._startDragRay.direction.copyFrom(t.direction),this._startDragRay.origin.copyFrom(t.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,i||this._tmpVector);const r=this._pickWithRayOnDragPlane(this._startDragRay);r?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(r),this.onDragStartObservable.notifyObservers({dragPlanePoint:r,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),ji._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;const t=this._pickWithRayOnDragPlane(e);if(t){ji._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?W.Pq.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),this._worldDragAxis.normalize(),i=W.Pq.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(i,this._dragDelta)):(i=this._dragDelta.length(),t.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:i,delta:this._dragDelta,dragPlanePoint:t,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this.lastDragPosition.copyFrom(t),ji._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(W.Pq.Dot(this._dragPlane.forward,e.direction));if(t>Math.PI/2&&(t=Math.PI-t),this.maxDragAngle>0&&t>this.maxDragAngle){if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*W.Pq.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);const t=W.Pq.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-t,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}return null}const i=this._dragPlane.forward,r=this._dragPlane.position,s=e.direction.dot(i);if(Math.abs(s).999?Math.abs(W.Pq.Dot(W.Pq.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(W.Pq.Right()):this._lookAt.copyFrom(W.Pq.UpReadOnly):(W.Pq.CrossToRef(this._localAxis,this._pointC,this._lookAt),W.Pq.CrossToRef(this._localAxis,this._lookAt,this._lookAt),this._lookAt.normalize()),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrientationForDragging?W.Pq.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(e.origin)),this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()),this._dragPlane.computeWorldMatrix(!0)}detach(){this._lastPointerRay={},this.attachedNode&&(this.attachedNode.isNearGrabbable=!1),this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this._dragPlane&&this._dragPlane.dispose(),this.releaseDrag()}}Ji._AnyMouseId=-2;class er{constructor(){this._startDistance=0,this._initialScale=new W.Pq(0,0,0),this._targetScale=new W.Pq(0,0,0),this._sceneRenderObserver=null,this._dragBehaviorA=new Ji({}),this._dragBehaviorA.moveAttached=!1,this._dragBehaviorB=new Ji({}),this._dragBehaviorB.moveAttached=!1}get name(){return"MultiPointerScale"}init(){}_getCurrentDistance(){return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length()}attach(e){this._ownerNode=e,this._dragBehaviorA.onDragStartObservable.add((()=>{this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging&&(this._dragBehaviorA.currentDraggingPointerId==this._dragBehaviorB.currentDraggingPointerId?this._dragBehaviorA.releaseDrag():(this._initialScale.copyFrom(e.scaling),this._startDistance=this._getCurrentDistance()))})),this._dragBehaviorB.onDragStartObservable.add((()=>{this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging&&(this._dragBehaviorA.currentDraggingPointerId==this._dragBehaviorB.currentDraggingPointerId?this._dragBehaviorB.releaseDrag():(this._initialScale.copyFrom(e.scaling),this._startDistance=this._getCurrentDistance()))})),[this._dragBehaviorA,this._dragBehaviorB].forEach((e=>{e.onDragObservable.add((()=>{if(this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging){const e=this._getCurrentDistance()/this._startDistance;this._initialScale.scaleToRef(e,this._targetScale)}}))})),e.addBehavior(this._dragBehaviorA),e.addBehavior(this._dragBehaviorB),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add((()=>{if(this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging){const t=this._targetScale.subtract(e.scaling).scaleInPlace(.1);t.length()>.01&&e.scaling.addInPlace(t)}}))}detach(){this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),[this._dragBehaviorA,this._dragBehaviorB].forEach((e=>{e.onDragStartObservable.clear(),e.onDragObservable.clear(),this._ownerNode.removeBehavior(e)}))}}class tr{constructor(){this._attachedToElement=!1,this._virtualMeshesInfo={},this._tmpVector=new W.Pq,this._tmpQuaternion=new W.PT,this._dragType={NONE:0,DRAG:1,DRAG_WITH_CONTROLLER:2,NEAR_DRAG:3},this._moving=!1,this._dragging=this._dragType.NONE,this.draggableMeshes=null,this.zDragFactor=3,this.currentDraggingPointerIds=[],this.detachCameraControls=!0,this.onDragStartObservable=new z.cP,this.onDragObservable=new z.cP,this.onDragEndObservable=new z.cP,this.allowMultiPointer=!0}get currentDraggingPointerId(){return void 0!==this.currentDraggingPointerIds[0]?this.currentDraggingPointerIds[0]:-1}set currentDraggingPointerId(e){this.currentDraggingPointerIds[0]=e}get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}get name(){return"BaseSixDofDrag"}get isMoving(){return this._moving}init(){}get _pointerCamera(){return this._scene.cameraToUseForPointers?this._scene.cameraToUseForPointers:this._scene.activeCamera}_createVirtualMeshInfo(){const e=new Pt("",tr._virtualScene);e.rotationQuaternion=new W.PT;const t=new Pt("",tr._virtualScene);t.rotationQuaternion=new W.PT;const i=new Pt("",tr._virtualScene);return i.rotationQuaternion=new W.PT,{dragging:!1,moving:!1,dragMesh:e,originMesh:t,pivotMesh:i,startingPivotPosition:new W.Pq,startingPivotOrientation:new W.PT,startingPosition:new W.Pq,startingOrientation:new W.PT,lastOriginPosition:new W.Pq,lastDragPosition:new W.Pq}}_resetVirtualMeshesPosition(){for(let e=0;el&&(l=Math.min(h-a,0)),o.scaleInPlace(l),o.addToRef(s.pivotMesh.absolutePosition,this._tmpVector),s.pivotMesh.setAbsolutePosition(this._tmpVector),o.addToRef(s.dragMesh.absolutePosition,this._tmpVector),s.dragMesh.setAbsolutePosition(this._tmpVector)}}attach(e){this._ownerNode=e,this._scene=this._ownerNode.getScene(),tr._virtualScene||(tr._virtualScene=new oi.Z(this._scene.getEngine(),{virtual:!0}),tr._virtualScene.detachControl());const t=e=>this._ownerNode===e||e.isDescendantOf(this._ownerNode)&&(!this.draggableMeshes||-1!==this.draggableMeshes.indexOf(e));this._pointerObserver=this._scene.onPointerObservable.add((e=>{const i=e.event.pointerId;this._virtualMeshesInfo[i]||(this._virtualMeshesInfo[i]=this._createVirtualMeshInfo());const r=this._virtualMeshesInfo[i],s="xr-near"===e.event.pointerType||"xr"===e.event.pointerType;if(e.type==yi.Zp.POINTERDOWN){if(!r.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&(!s||e.pickInfo.aimTransform)&&t(e.pickInfo.pickedMesh)){if((!this.allowMultiPointer||s)&&this.currentDraggingPointerIds.length>0)return;!this._pointerCamera||this._pointerCamera.cameraRigMode!==rt.RIG_MODE_NONE||this._pointerCamera._isLeftCamera||this._pointerCamera._isRightCamera||e.pickInfo.ray.origin.copyFrom(this._pointerCamera.globalPosition),this._ownerNode.computeWorldMatrix(!0);const t=this._virtualMeshesInfo[i];s?(this._dragging=e.pickInfo.originMesh?this._dragType.NEAR_DRAG:this._dragType.DRAG_WITH_CONTROLLER,t.originMesh.position.copyFrom(e.pickInfo.aimTransform.position),this._dragging===this._dragType.NEAR_DRAG&&e.pickInfo.gripTransform?t.originMesh.rotationQuaternion.copyFrom(e.pickInfo.gripTransform.rotationQuaternion):t.originMesh.rotationQuaternion.copyFrom(e.pickInfo.aimTransform.rotationQuaternion)):(this._dragging=this._dragType.DRAG,t.originMesh.position.copyFrom(e.pickInfo.ray.origin)),t.lastOriginPosition.copyFrom(t.originMesh.position),t.dragMesh.position.copyFrom(e.pickInfo.pickedPoint),t.lastDragPosition.copyFrom(e.pickInfo.pickedPoint),t.pivotMesh.position.copyFrom(this._ownerNode.getAbsolutePivotPoint()),t.pivotMesh.rotationQuaternion.copyFrom(this._ownerNode.absoluteRotationQuaternion),t.startingPosition.copyFrom(t.dragMesh.position),t.startingPivotPosition.copyFrom(t.pivotMesh.position),t.startingOrientation.copyFrom(t.dragMesh.rotationQuaternion),t.startingPivotOrientation.copyFrom(t.pivotMesh.rotationQuaternion),s?(t.originMesh.addChild(t.dragMesh),t.originMesh.addChild(t.pivotMesh)):t.originMesh.lookAt(t.dragMesh.position),t.dragging=!0,-1===this.currentDraggingPointerIds.indexOf(i)&&this.currentDraggingPointerIds.push(i),this.detachCameraControls&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._pointerCamera.inputs&&this._pointerCamera.inputs.attachedToElement?(this._pointerCamera.detachControl(),this._attachedToElement=!0):this.allowMultiPointer&&0!==this.currentDraggingPointerIds.length||(this._attachedToElement=!1)),this._targetDragStart(t.pivotMesh.position,t.pivotMesh.rotationQuaternion,i),this.onDragStartObservable.notifyObservers({position:t.pivotMesh.position})}}else if(e.type==yi.Zp.POINTERUP||e.type==yi.Zp.POINTERDOUBLETAP){const e=this.currentDraggingPointerIds.indexOf(i);r.dragging=!1,-1!==e&&(this.currentDraggingPointerIds.splice(e,1),0===this.currentDraggingPointerIds.length&&(this._moving=!1,this._dragging=this._dragType.NONE,this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._reattachCameraControls(),this._attachedToElement=!1)),r.originMesh.removeChild(r.dragMesh),r.originMesh.removeChild(r.pivotMesh),this._targetDragEnd(i),this.onDragEndObservable.notifyObservers({}))}else if(e.type==yi.Zp.POINTERMOVE&&-1!==this.currentDraggingPointerIds.indexOf(i)&&r.dragging&&e.pickInfo&&(e.pickInfo.ray||e.pickInfo.aimTransform)){let t=this.zDragFactor;(this.currentDraggingPointerIds.length>1||e.pickInfo.originMesh)&&(t=0),this._ownerNode.computeWorldMatrix(!0),s?this._pointerUpdateXR(e.pickInfo.aimTransform,e.pickInfo.gripTransform,i,t):this._pointerUpdate2D(e.pickInfo.ray,i,t),this._tmpQuaternion.copyFrom(r.startingPivotOrientation),this._tmpQuaternion.x=-this._tmpQuaternion.x,this._tmpQuaternion.y=-this._tmpQuaternion.y,this._tmpQuaternion.z=-this._tmpQuaternion.z,r.pivotMesh.absoluteRotationQuaternion.multiplyToRef(this._tmpQuaternion,this._tmpQuaternion),r.pivotMesh.absolutePosition.subtractToRef(r.startingPivotPosition,this._tmpVector),this.onDragObservable.notifyObservers({delta:this._tmpVector,position:r.pivotMesh.position,pickInfo:e.pickInfo}),this._targetDrag(this._tmpVector,this._tmpQuaternion,i),r.lastDragPosition.copyFrom(r.dragMesh.absolutePosition),this._moving=!0}}))}_applyZOffset(e,t,i){e.position.z-=e.position.z<1?t*i:t*i*e.position.z,e.position.z<0&&(e.position.z=0)}_targetDragStart(e,t,i){}_targetDrag(e,t,i){}_targetDragEnd(e){}_reattachCameraControls(){if(this._pointerCamera)if("ArcRotateCamera"===this._pointerCamera.getClassName()){const e=this._pointerCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._pointerCamera.attachControl(!this._pointerCamera.inputs||this._pointerCamera.inputs.noPreventDefault)}detach(){this._scene&&(this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._reattachCameraControls(),this._attachedToElement=!1),this._scene.onPointerObservable.remove(this._pointerObserver));for(const e in this._virtualMeshesInfo)this._virtualMeshesInfo[e].originMesh.dispose(),this._virtualMeshesInfo[e].dragMesh.dispose();this.onDragEndObservable.clear(),this.onDragObservable.clear(),this.onDragStartObservable.clear()}}class ir extends tr{constructor(){super(...arguments),this._sceneRenderObserver=null,this._targetPosition=new W.Pq(0,0,0),this._targetOrientation=new W.PT,this._targetScaling=new W.Pq(1,1,1),this._startingPosition=new W.Pq(0,0,0),this._startingOrientation=new W.PT,this._startingScaling=new W.Pq(1,1,1),this.onPositionChangedObservable=new z.cP,this.dragDeltaRatio=.2,this.rotateDraggedObject=!0,this.rotateAroundYOnly=!1,this.rotateWithMotionController=!0,this.disableMovement=!1,this.faceCameraOnDragStart=!1}get name(){return"SixDofDrag"}attach(e){super.attach(e),e.isNearGrabbable=!0,e.getChildMeshes().forEach((e=>{e.isNearGrabbable=!0})),this._virtualTransformNode=new Pt("virtual_sixDof",tr._virtualScene),this._virtualTransformNode.rotationQuaternion=W.PT.Identity(),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add((()=>{if(1===this.currentDraggingPointerIds.length&&this._moving&&!this.disableMovement){const t=W.AA.Vector3[0];t.copyFrom(this._targetPosition).subtractInPlace(e.absolutePosition).scaleInPlace(this.dragDeltaRatio);const i=W.AA.Vector3[1];if(i.copyFrom(t),e.parent){const r=W.AA.Matrix[0];e.parent.absoluteRotationQuaternion.toRotationMatrix(r),r.invert(),W.Pq.TransformNormalToRef(t,r,i)}if(e.position.addInPlace(i),this.onPositionChangedObservable.notifyObservers({position:e.absolutePosition}),!e.parent||e.parent.scaling&&!e.parent.scaling.isNonUniformWithinEpsilon(.001)){const t=W.AA.Quaternion[0];if(t.copyFrom(this._targetOrientation),e.parent){const i=W.AA.Quaternion[0];i.copyFrom(e.parent.absoluteRotationQuaternion),i.invertInPlace(),i.multiplyToRef(this._targetOrientation,t)}W.PT.SlerpToRef(e.rotationQuaternion,t,this.dragDeltaRatio,e.rotationQuaternion)}}}))}_getPositionOffsetAround(e,t,i){const r=W.AA.Matrix[0],s=W.AA.Matrix[1],n=W.AA.Matrix[2],o=W.AA.Matrix[3],a=W.AA.Matrix[4];return W.uq.TranslationToRef(e.x,e.y,e.z,r),W.uq.TranslationToRef(-e.x,-e.y,-e.z,s),W.uq.FromQuaternionToRef(i,n),W.uq.ScalingToRef(t,t,t,o),s.multiplyToRef(n,a),a.multiplyToRef(o,a),a.multiplyToRef(r,a),a.getTranslation()}_onePointerPositionUpdated(e,t){W.AA.Vector3[0].setAll(0),this._dragging===this._dragType.DRAG?this.rotateDraggedObject&&(this.rotateAroundYOnly?W.PT.RotationYawPitchRollToRef(t.toEulerAngles().y,0,0,W.AA.Quaternion[0]):W.AA.Quaternion[0].copyFrom(t),W.AA.Quaternion[0].multiplyToRef(this._startingOrientation,this._targetOrientation)):(this._dragging===this._dragType.NEAR_DRAG||this._dragging===this._dragType.DRAG_WITH_CONTROLLER&&this.rotateWithMotionController)&&t.multiplyToRef(this._startingOrientation,this._targetOrientation),this._targetPosition.copyFrom(this._startingPosition).addInPlace(e)}_twoPointersPositionUpdated(){const e=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].startingPosition,t=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].startingPosition,i=W.AA.Vector3[0];e.addToRef(t,i),i.scaleInPlace(.5);const r=W.AA.Vector3[1];t.subtractToRef(e,r);const s=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].dragMesh.absolutePosition,n=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].dragMesh.absolutePosition,o=W.AA.Vector3[2];s.addToRef(n,o),o.scaleInPlace(.5);const a=W.AA.Vector3[3];n.subtractToRef(s,a);const l=a.length()/r.length(),h=o.subtract(i),c=W.PT.FromEulerAngles(0,W.Pq.GetAngleBetweenVectorsOnPlane(r.normalize(),a.normalize(),W.Pq.UpReadOnly),0),u=this._ownerNode.parent;this._ownerNode.setParent(null);const d=this._getPositionOffsetAround(i.subtract(this._virtualTransformNode.getAbsolutePivotPoint()),l,c);this._virtualTransformNode.rotationQuaternion.multiplyToRef(c,this._ownerNode.rotationQuaternion),this._virtualTransformNode.scaling.scaleToRef(l,this._ownerNode.scaling),this._virtualTransformNode.position.addToRef(h.addInPlace(d),this._ownerNode.position),this.onPositionChangedObservable.notifyObservers({position:this._ownerNode.position}),this._ownerNode.setParent(u)}_targetDragStart(){const e=this.currentDraggingPointerIds.length;this._ownerNode.rotationQuaternion||(this._ownerNode.rotationQuaternion=W.PT.RotationYawPitchRoll(this._ownerNode.rotation.y,this._ownerNode.rotation.x,this._ownerNode.rotation.z));const t=this._ownerNode.getAbsolutePivotPoint();if(1===e){if(this._targetPosition.copyFrom(this._ownerNode.absolutePosition),this._targetOrientation.copyFrom(this._ownerNode.rotationQuaternion),this._targetScaling.copyFrom(this._ownerNode.absoluteScaling),this.faceCameraOnDragStart&&this._scene.activeCamera){const e=W.AA.Vector3[0];this._scene.activeCamera.position.subtractToRef(t,e),e.normalize();const i=W.AA.Quaternion[0];this._scene.useRightHandedSystem?W.PT.FromLookDirectionRHToRef(e,new W.Pq(0,1,0),i):W.PT.FromLookDirectionLHToRef(e,new W.Pq(0,1,0),i),i.normalize(),W.PT.RotationYawPitchRollToRef(i.toEulerAngles().y,0,0,W.AA.Quaternion[0]),this._targetOrientation.copyFrom(W.AA.Quaternion[0])}this._startingPosition.copyFrom(this._targetPosition),this._startingOrientation.copyFrom(this._targetOrientation),this._startingScaling.copyFrom(this._targetScaling)}else 2===e&&(this._virtualTransformNode.setPivotPoint(new W.Pq(0,0,0),0),this._virtualTransformNode.position.copyFrom(this._ownerNode.absolutePosition),this._virtualTransformNode.scaling.copyFrom(this._ownerNode.absoluteScaling),this._virtualTransformNode.rotationQuaternion.copyFrom(this._ownerNode.absoluteRotationQuaternion),this._virtualTransformNode.setPivotPoint(t,1),this._resetVirtualMeshesPosition())}_targetDrag(e,t){1===this.currentDraggingPointerIds.length?this._onePointerPositionUpdated(e,t):2===this.currentDraggingPointerIds.length&&this._twoPointersPositionUpdated()}_targetDragEnd(){if(1===this.currentDraggingPointerIds.length){this._resetVirtualMeshesPosition();const e=this.faceCameraOnDragStart;this.faceCameraOnDragStart=!1,this._targetDragStart(),this.faceCameraOnDragStart=e}}detach(){super.detach(),this._ownerNode&&this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),this._virtualTransformNode&&this._virtualTransformNode.dispose()}}class rr{constructor(){this._attachPointLocalOffset=new W.Pq,this._workingPosition=new W.Pq,this._workingQuaternion=new W.PT,this._lastTick=-1,this._hit=!1,this.hitNormalOffset=.05,this.meshes=[],this.interpolatePose=!0,this.lerpTime=250,this.keepOrientationVertical=!0,this.enabled=!0,this.maxStickingDistance=.8}get name(){return"SurfaceMagnetism"}init(){}attach(e,t){this._attachedMesh=e,this._scene=t||e.getScene(),this._attachedMesh.rotationQuaternion||(this._attachedMesh.rotationQuaternion=W.PT.RotationYawPitchRoll(this._attachedMesh.rotation.y,this._attachedMesh.rotation.x,this._attachedMesh.rotation.z)),this.updateAttachPoint(),this._workingPosition.copyFrom(this._attachedMesh.position),this._workingQuaternion.copyFrom(this._attachedMesh.rotationQuaternion),this._addObservables()}detach(){this._attachedMesh=null,this._removeObservables()}_getTargetPose(e){if(!this._attachedMesh)return null;if(e&&e.hit){const t=e.getNormal(!0,!0),i=e.pickedPoint;if(!t||!i)return null;t.normalize();const r=W.AA.Vector3[0];return r.copyFrom(t),r.scaleInPlace(this.hitNormalOffset),r.addInPlace(i),this._attachedMesh.parent&&(W.AA.Matrix[0].copyFrom(this._attachedMesh.parent.getWorldMatrix()).invert(),W.Pq.TransformNormalToRef(r,W.AA.Matrix[0],r)),{position:r,quaternion:W.PT.RotationYawPitchRoll(-Math.atan2(t.x,-t.z),this.keepOrientationVertical?0:Math.atan2(t.y,Math.sqrt(t.z*t.z+t.x*t.x)),0)}}return null}updateAttachPoint(){this._getAttachPointOffsetToRef(this._attachPointLocalOffset)}findAndUpdateTarget(e){if(this._hit=!1,!e.ray)return!1;const t=e.ray.intersectsMeshes(this.meshes)[0];if(this._attachedMesh&&t&&t.hit&&t.pickedMesh){const e=this._getTargetPose(t);e&&W.Pq.Distance(this._attachedMesh.position,e.position){this.enabled&&e.type==yi.Zp.POINTERMOVE&&e.pickInfo&&this.findAndUpdateTarget(e.pickInfo)})),this._lastTick=Date.now(),this._onBeforeRender=this._scene.onBeforeRenderObservable.add((()=>{const e=Date.now();this._updateTransformToGoal(e-this._lastTick),this._lastTick=e}))}_removeObservables(){this._scene.onPointerObservable.remove(this._pointerObserver),this._scene.onBeforeRenderObservable.remove(this._onBeforeRender),this._pointerObserver=null,this._onBeforeRender=null}}var sr,nr,or,ar=i(56984);class lr{constructor(){this._tmpQuaternion=new W.PT,this._tmpVectors=[new W.Pq,new W.Pq,new W.Pq,new W.Pq,new W.Pq,new W.Pq,new W.Pq],this._tmpMatrix=new W.uq,this._tmpInvertView=new W.uq,this._tmpForward=new W.Pq,this._tmpNodeForward=new W.Pq,this._tmpPosition=new W.Pq,this._workingPosition=new W.Pq,this._workingQuaternion=new W.PT,this._lastTick=-1,this._recenterNextUpdate=!0,this.interpolatePose=!0,this.lerpTime=500,this.ignoreCameraPitchAndRoll=!1,this.pitchOffset=15,this.maxViewVerticalDegrees=30,this.maxViewHorizontalDegrees=30,this.orientToCameraDeadzoneDegrees=60,this.ignoreDistanceClamp=!1,this.ignoreAngleClamp=!1,this.verticalMaxDistance=0,this.defaultDistance=.8,this.maximumDistance=2,this.minimumDistance=.3,this.useFixedVerticalOffset=!1,this.fixedVerticalOffset=0,this._enabled=!0}get followedCamera(){return this._followedCamera||this._scene.activeCamera}set followedCamera(e){this._followedCamera=e}get name(){return"Follow"}init(){}attach(e,t){this._scene=e.getScene(),this.attachedNode=e,t&&(this.followedCamera=t),this._addObservables()}detach(){this.attachedNode=null,this._removeObservables()}recenter(){this._recenterNextUpdate=!0}_angleBetweenVectorAndPlane(e,t){return this._tmpVectors[0].copyFrom(e),e=this._tmpVectors[0],this._tmpVectors[1].copyFrom(t),t=this._tmpVectors[1],e.normalize(),t.normalize(),Math.PI/2-Math.acos(W.Pq.Dot(e,t))}_length2D(e){return Math.sqrt(e.x*e.x+e.z*e.z)}_distanceClamp(e,t=!1){let i=this.minimumDistance,r=this.maximumDistance;const s=this.defaultDistance,n=this._tmpVectors[0];n.copyFrom(e);let o=n.length();if(n.normalizeFromLength(o),this.ignoreCameraPitchAndRoll){i=this._length2D(n)*i,r=this._length2D(n)*r;const t=this._length2D(e);n.scaleInPlace(o/t),o=t}let a=o;return a=t?s:(0,ar.Clamp)(o,i,r),e.copyFrom(n).scaleInPlace(a),o!==a}_applyVerticalClamp(e){0!==this.verticalMaxDistance&&(e.y=(0,ar.Clamp)(e.y,-this.verticalMaxDistance,this.verticalMaxDistance))}_toOrientationQuatToRef(e,t){W.PT.RotationYawPitchRollToRef(Math.atan2(e.x,e.z),Math.atan2(e.y,Math.sqrt(e.z*e.z+e.x*e.x)),0,t)}_applyPitchOffset(e){const t=this._tmpVectors[0],i=this._tmpVectors[1];t.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),i.copyFromFloats(1,0,0),W.Pq.TransformNormalToRef(t,e,t),t.y=0,t.normalize(),W.Pq.TransformNormalToRef(i,e,i),W.PT.RotationAxisToRef(i,this.pitchOffset*Math.PI/180,this._tmpQuaternion),t.rotateByQuaternionToRef(this._tmpQuaternion,t),this._toOrientationQuatToRef(t,this._tmpQuaternion),this._tmpQuaternion.toRotationMatrix(this._tmpMatrix),e.copyFrom(this._tmpMatrix)}_angularClamp(e,t){const i=this._tmpVectors[5];i.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1);const r=this._tmpVectors[6];r.copyFromFloats(1,0,0),W.Pq.TransformNormalToRef(i,e,i),W.Pq.TransformNormalToRef(r,e,r);const s=W.Pq.UpReadOnly;if(t.length()s&&(W.PT.RotationAxisToRef(r,-e+s,o),t.rotateByQuaternionToRef(o,t),n=!0)}const a=this._angleBetweenVectorAndPlane(t,r)*(this._scene.useRightHandedSystem?-1:1),l=this.maxViewHorizontalDegrees*Math.PI/180*.5;return a<-l?(W.PT.RotationAxisToRef(s,-a-l,o),t.rotateByQuaternionToRef(o,t),n=!0):a>l&&(W.PT.RotationAxisToRef(s,-a+l,o),t.rotateByQuaternionToRef(o,t),n=!0),n}_orientationClamp(e,t){const i=this._tmpVectors[0];i.copyFrom(e).scaleInPlace(-1).normalize();const r=this._tmpVectors[1],s=this._tmpVectors[2];r.copyFromFloats(0,1,0),W.Pq.CrossToRef(i,r,s);const n=s.length();nthis.orientToCameraDeadzoneDegrees}_updateLeashing(e){if(this.attachedNode&&this._enabled){const t=this.attachedNode.parent;this.attachedNode.setParent(null);const i=this.attachedNode.getWorldMatrix(),r=this._workingPosition,s=this._workingQuaternion,n=this.attachedNode.getPivotPoint(),o=this._tmpInvertView;o.copyFrom(e.getViewMatrix()),o.invert(),W.Pq.TransformCoordinatesToRef(n,i,r);const a=this._tmpPosition;a.copyFromFloats(0,0,0),W.Pq.TransformCoordinatesToRef(a,i,a),a.scaleInPlace(-1).subtractInPlace(n),r.subtractInPlace(e.globalPosition),this.ignoreCameraPitchAndRoll&&this._applyPitchOffset(o);let l=!1;const h=this._tmpForward;h.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),W.Pq.TransformNormalToRef(h,o,h);const c=this._tmpNodeForward;if(c.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),W.Pq.TransformNormalToRef(c,i,c),this._recenterNextUpdate)r.copyFrom(h).scaleInPlace(this.defaultDistance);else if(this.ignoreAngleClamp){const e=r.length();r.copyFrom(h).scaleInPlace(e)}else l=this._angularClamp(o,r);let u=!1;this.ignoreDistanceClamp||(u=this._distanceClamp(r,l),this._applyVerticalClamp(r)),this.useFixedVerticalOffset&&(r.y=a.y-e.globalPosition.y+this.fixedVerticalOffset),(l||u||this._passedOrientationDeadzone(r,c)||this._recenterNextUpdate)&&this._orientationClamp(r,s),this._workingPosition.subtractInPlace(n),this._recenterNextUpdate=!1,this.attachedNode.setParent(t)}}_updateTransformToGoal(e){if(!this.attachedNode||!this.followedCamera||!this._enabled)return;this.attachedNode.rotationQuaternion||(this.attachedNode.rotationQuaternion=W.PT.Identity());const t=this.attachedNode.parent;if(this.attachedNode.setParent(null),!this.interpolatePose)return this.attachedNode.position.copyFrom(this.followedCamera.globalPosition).addInPlace(this._workingPosition),void this.attachedNode.rotationQuaternion.copyFrom(this._workingQuaternion);const i=new W.Pq;i.copyFrom(this.attachedNode.position).subtractInPlace(this.followedCamera.globalPosition),W.Pq.SmoothToRef(i,this._workingPosition,e,this.lerpTime,i),i.addInPlace(this.followedCamera.globalPosition),this.attachedNode.position.copyFrom(i);const r=new W.PT;r.copyFrom(this.attachedNode.rotationQuaternion),W.PT.SmoothToRef(r,this._workingQuaternion,e,this.lerpTime,this.attachedNode.rotationQuaternion),this.attachedNode.setParent(t)}_addObservables(){this._lastTick=Date.now(),this._onBeforeRender=this._scene.onBeforeRenderObservable.add((()=>{if(!this.followedCamera)return;const e=Date.now();this._updateLeashing(this.followedCamera),this._updateTransformToGoal(e-this._lastTick),this._lastTick=e}))}_removeObservables(){this._onBeforeRender&&this._scene.onBeforeRenderObservable.remove(this._onBeforeRender)}}class hr{}hr.ANCHOR_SYSTEM="xr-anchor-system",hr.BACKGROUND_REMOVER="xr-background-remover",hr.HIT_TEST="xr-hit-test",hr.MESH_DETECTION="xr-mesh-detection",hr.PHYSICS_CONTROLLERS="xr-physics-controller",hr.PLANE_DETECTION="xr-plane-detection",hr.POINTER_SELECTION="xr-controller-pointer-selection",hr.TELEPORTATION="xr-controller-teleportation",hr.FEATURE_POINTS="xr-feature-points",hr.HAND_TRACKING="xr-hand-tracking",hr.IMAGE_TRACKING="xr-image-tracking",hr.NEAR_INTERACTION="xr-near-interaction",hr.DOM_OVERLAY="xr-dom-overlay",hr.MOVEMENT="xr-controller-movement",hr.LIGHT_ESTIMATION="xr-light-estimation",hr.EYE_TRACKING="xr-eye-tracking",hr.WALKING_LOCOMOTION="xr-walking-locomotion",hr.LAYERS="xr-layers",hr.DEPTH_SENSING="xr-depth-sensing",hr.SPACE_WARP="xr-space-warp",hr.RAW_CAMERA_ACCESS="xr-raw-camera-access";class cr{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];!t.enabled||t.featureImplementation.attached||t.featureImplementation.disableAutoAttach||this.attachFeature(e)}))})),this._xrSessionManager.onXRSessionEnded.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];t.enabled&&t.featureImplementation.attached&&this.detachFeature(e)}))}))}static AddWebXRFeature(e,t,i=1,r=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),r&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,r){const s=this._AvailableFeatures[e][t];if(!s)throw new Error("feature not found");return s(i,r)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){const t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&(t.featureImplementation.attach()||Ue.S0.Warn(`Feature ${e} failed to attach`))}detachFeature(e){const t=this._features[e];t&&t.featureImplementation.attached&&(t.featureImplementation.detach()||Ue.S0.Warn(`Feature ${e} failed to detach`))}disableFeature(e){const t="string"==typeof e?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))}dispose(){this.getEnabledFeatures().forEach((e=>{this.disableFeature(e)}))}enableFeature(e,t="latest",i={},r=!0,s=!0){const n="string"==typeof e?e:e.Name;let o=0;if("string"==typeof t){if(!t)throw new Error(`Error in provided version - ${n} (${t})`);if(o="stable"===t?cr.GetStableVersionOfFeature(n):"latest"===t?cr.GetLatestVersionOfFeature(n):+t,-1===o||isNaN(o))throw new Error(`feature not found - ${n} (${t})`)}else o=t;const a=cr._ConflictingFeatures[n];if(void 0!==a&&-1!==this.getEnabledFeatures().indexOf(a))throw new Error(`Feature ${n} cannot be enabled while ${a} is enabled.`);const l=this._features[n],h=cr.ConstructFeature(n,o,this._xrSessionManager,i);if(!h)throw new Error(`feature not found - ${n}`);l&&this.disableFeature(n);const c=h();if(c.dependsOn){const e=c.dependsOn.every((e=>!!this._features[e]));if(!e)throw new Error(`Dependant features missing. Make sure the following features are enabled - ${c.dependsOn.join(", ")}`)}if(c.isCompatible())return this._features[n]={featureImplementation:c,enabled:!0,version:o,required:s},r?this._xrSessionManager.session&&!this._features[n].featureImplementation.attached&&this.attachFeature(n):this._features[n].featureImplementation.disableAutoAttach=!0,this._features[n].featureImplementation;if(s)throw new Error("required feature not compatible");return Ue.S0.Warn(`Feature ${n} not compatible with the current environment/browser and was not enabled.`),c}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 t=this._features[i],r=t.featureImplementation.xrNativeFeatureName;if(r&&(t.required?(e.requiredFeatures=e.requiredFeatures||[],-1===e.requiredFeatures.indexOf(r)&&e.requiredFeatures.push(r)):(e.optionalFeatures=e.optionalFeatures||[],-1===e.optionalFeatures.indexOf(r)&&e.optionalFeatures.push(r))),t.featureImplementation.getXRSessionInitExtension){const i=await t.featureImplementation.getXRSessionInitExtension();e={...e,...i}}}return e}}cr._AvailableFeatures={},cr._ConflictingFeatures={[hr.TELEPORTATION]:hr.MOVEMENT,[hr.MOVEMENT]:hr.TELEPORTATION},function(e){e[e.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",e[e.RADIAL_SIDE=1]="RADIAL_SIDE",e[e.ULNAR_SIDE=2]="ULNAR_SIDE",e[e.BELOW_WRIST=3]="BELOW_WRIST"}(sr||(sr={})),function(e){e[e.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",e[e.HAND_ROTATION=1]="HAND_ROTATION"}(nr||(nr={})),function(e){e[e.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",e[e.PALM_UP=1]="PALM_UP",e[e.GAZE_FOCUS=2]="GAZE_FOCUS",e[e.PALM_AND_GAZE=3]="PALM_AND_GAZE"}(or||(or={}));class ur{constructor(){this._sceneRenderObserver=null,this._zoneAxis={},this.handConstraintVisibility=3,this.palmUpStrictness=.95,this.gazeProximityRadius=.15,this.targetOffset=.1,this.targetZone=2,this.zoneOrientationMode=1,this.nodeOrientationMode=1,this.handedness="none",this.lerpTime=100,this._zoneAxis[0]=new W.Pq(0,1,0),this._zoneAxis[1]=new W.Pq(-1,0,0),this._zoneAxis[2]=new W.Pq(1,0,0),this._zoneAxis[3]=new W.Pq(0,-1,0)}get name(){return"HandConstraint"}enable(){this._node.setEnabled(!0)}disable(){this._node.setEnabled(!1)}_getHandPose(){if(!this._handTracking)return null;let e;if(e="none"===this.handedness?this._handTracking.getHandByHandedness("left")||this._handTracking.getHandByHandedness("right"):this._handTracking.getHandByHandedness(this.handedness),e){const t=e.getJointMesh("pinky-finger-metacarpal"),i=e.getJointMesh("middle-finger-metacarpal"),r=e.getJointMesh("wrist");if(r&&i&&t){const s={position:i.absolutePosition,quaternion:new W.PT,id:e.xrController.uniqueId},n=W.AA.Vector3[0],o=W.AA.Vector3[1],a=W.AA.Vector3[2];return n.copyFrom(i.absolutePosition).subtractInPlace(r.absolutePosition).normalize(),o.copyFrom(t.absolutePosition).subtractInPlace(i.absolutePosition).normalize(),W.Pq.CrossToRef(n,o,o),W.Pq.CrossToRef(o,n,a),W.PT.FromLookDirectionLHToRef(o,n,s.quaternion),s}}return null}init(){}attach(e){this._node=e,this._scene=e.getScene(),this._node.rotationQuaternion||(this._node.rotationQuaternion=W.PT.RotationYawPitchRoll(this._node.rotation.y,this._node.rotation.x,this._node.rotation.z));let t=Date.now();this._sceneRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{const e=this._getHandPose();if(this._node.reservedDataStore=this._node.reservedDataStore||{},this._node.reservedDataStore.nearInteraction=this._node.reservedDataStore.nearInteraction||{},this._node.reservedDataStore.nearInteraction.excludedControllerId=null,e){const i=W.AA.Vector3[0],r=this._scene.activeCamera;i.copyFrom(this._zoneAxis[this.targetZone]);const s=W.AA.Quaternion[0];if(r&&(0===this.zoneOrientationMode||0===this.nodeOrientationMode)){const t=W.AA.Vector3[1];t.copyFrom(r.position).subtractInPlace(e.position).normalize(),this._scene.useRightHandedSystem?W.PT.FromLookDirectionRHToRef(t,W.Pq.UpReadOnly,s):W.PT.FromLookDirectionLHToRef(t,W.Pq.UpReadOnly,s)}1===this.zoneOrientationMode?e.quaternion.toRotationMatrix(W.AA.Matrix[0]):s.toRotationMatrix(W.AA.Matrix[0]),W.Pq.TransformNormalToRef(i,W.AA.Matrix[0],i),i.scaleInPlace(this.targetOffset);const n=W.AA.Vector3[2],o=W.AA.Quaternion[1];n.copyFrom(e.position).addInPlace(i),1===this.nodeOrientationMode?o.copyFrom(e.quaternion):o.copyFrom(s);const a=Date.now()-t;W.Pq.SmoothToRef(this._node.position,n,a,this.lerpTime,this._node.position),W.PT.SmoothToRef(this._node.rotationQuaternion,o,a,this.lerpTime,this._node.rotationQuaternion),this._node.reservedDataStore.nearInteraction.excludedControllerId=e.id}this._setVisibility(e),t=Date.now()}))}_setVisibility(e){let t=!0,i=!0;const r=this._scene.activeCamera;if(r){const s=r.getForwardRay();if(2===this.handConstraintVisibility||3===this.handConstraintVisibility){let t;i=!1,this._eyeTracking&&(t=this._eyeTracking.getEyeGaze()),t=t||s;const r=W.AA.Vector3[0];e?e.position.subtractToRef(t.origin,r):this._node.getAbsolutePosition().subtractToRef(t.origin,r);const n=W.Pq.Dot(r,t.direction),o=n*n;n>0&&r.lengthSquared()-o2*this.palmUpStrictness-1&&(t=!0)}}this._node.setEnabled(t&&i)}detach(){this._scene.onBeforeRenderObservable.remove(this._sceneRenderObserver)}linkToXRExperience(e){const t=e.featuresManager?e.featuresManager:e;if(t){try{this._eyeTracking=t.getEnabledFeature(hr.EYE_TRACKING)}catch{}try{this._handTracking=t.getEnabledFeature(hr.HAND_TRACKING)}catch{Ue.S0.Error("Hand tracking must be enabled for the Hand Menu to work")}}else Ue.S0.Error("XR features manager must be available or provided directly for the Hand Menu to work")}}class dr{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=W.Pq.Zero(),this.poleTargetPosition=W.Pq.Zero(),this.poleTargetLocalOffset=W.Pq.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=W.PT.Identity(),this._bone1Mat=W.uq.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=W.Pq.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;const r=t.getParent();if(!r)return this._notEnoughInformation=!0,void Z.V.Error("BoneIKController: bone must have a parent for IK to work.");if(this._bone1=r,0===this._bone2.children.length&&!this._bone2.length)return this._notEnoughInformation=!0,void Z.V.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");this.mesh=e,t.getSkeleton().computeAbsoluteMatrices();const s=t.getPosition();if(t.getAbsoluteMatrix().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,s.x>s.y&&s.x>s.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length&&this._bone2.length){const e=this._bone1.getScale(),t=this._bone2.getScale();this._bone1Length=this._bone1.length*e.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y}else if(this._bone2.children[0]){e.computeWorldMatrix(!0);const t=this._bone2.children[0].getAbsolutePosition(e),i=this._bone2.getAbsolutePosition(e),r=this._bone1.getAbsolutePosition(e);this._bone2Length=W.Pq.Distance(t,i),this._bone1Length=W.Pq.Distance(i,r)}else{e.computeWorldMatrix(!0);const t=this._bone2.getScale();this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y;const i=this._bone2.getAbsolutePosition(e),r=this._bone1.getAbsolutePosition(e);this._bone1Length=W.Pq.Distance(i,r)}this._bone1.getRotationMatrixToRef(1,e,this._bone1Mat),this.maxAngle=Math.PI,i&&(i.targetMesh&&(this.targetMesh=i.targetMesh,this.targetMesh.computeWorldMatrix(!0)),i.poleTargetMesh?(this.poleTargetMesh=i.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):i.poleTargetBone?this.poleTargetBone=i.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),i.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(i.poleTargetLocalOffset),i.poleAngle&&(this.poleAngle=i.poleAngle),i.bendAxis&&this._bendAxis.copyFrom(i.bendAxis),i.maxAngle&&(this.maxAngle=i.maxAngle),i.slerpAmount&&(this.slerpAmount=i.slerpAmount))}_setMaxAngle(e){e<0&&(e=0),(e>Math.PI||null==e)&&(e=Math.PI),this._maxAngle=e;const t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))}update(){if(this._notEnoughInformation)return;const e=this.targetPosition,t=this.poleTargetPosition,i=dr._TmpMats[0],r=dr._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&W.Pq.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);const s=dr._TmpVecs[0],n=dr._TmpVecs[1],o=dr._TmpVecs[2],a=dr._TmpVecs[3],l=dr._TmpVecs[4],h=dr._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,s),t.subtractToRef(s,l),0==l.x&&0==l.y&&0==l.z?l.y=1:l.normalize(),e.subtractToRef(s,a),a.normalize(),W.Pq.CrossToRef(a,l,n),n.normalize(),W.Pq.CrossToRef(a,n,o),o.normalize(),W.uq.FromXYZAxesToRef(o,a,n,i);const c=this._bone1Length,u=this._bone2Length;let d=W.Pq.Distance(s,e);this._maxReach>0&&(d=Math.min(this._maxReach,d));let f=(u*u+d*d-c*c)/(2*u*d),p=(d*d+c*c-u*u)/(2*d*c);f>1&&(f=1),p>1&&(p=1),f<-1&&(f=-1),p<-1&&(p=-1);const _=Math.acos(f),m=Math.acos(p);let g=-_-m;if(this._rightHandedSystem)W.uq.RotationYawPitchRollToRef(0,0,this._adjustRoll,r),r.multiplyToRef(i,i),W.uq.RotationAxisToRef(this._bendAxis,m,r),r.multiplyToRef(i,i);else{const e=dr._TmpVecs[5];e.copyFrom(this._bendAxis),e.x*=-1,W.uq.RotationAxisToRef(e,-m,r),r.multiplyToRef(i,i)}this.poleAngle&&(W.uq.RotationAxisToRef(a,this.poleAngle,r),i.multiplyToRef(r,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||W.PT.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),W.PT.FromRotationMatrixToRef(i,h),W.PT.SlerpToRef(this._bone1Quat,h,this.slerpAmount,this._bone1Quat),g=this._bone2Ang*(1-this.slerpAmount)+g*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,1,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,1,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,g,0),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=g}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new W.PT),e.getRotationQuaternionToRef(0,null,e._linkedTransformNode.rotationQuaternion))}}dr._TmpVecs=[W.Pq.Zero(),W.Pq.Zero(),W.Pq.Zero(),W.Pq.Zero(),W.Pq.Zero(),W.Pq.Zero()],dr._TmpQuat=W.PT.Identity(),dr._TmpMats=[W.uq.Identity(),W.uq.Identity()];class fr{get minYaw(){return this._minYaw}set minYaw(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get maxYaw(){return this._maxYaw}set maxYaw(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch=e,this._minPitchTan=Math.tan(e)}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)}constructor(e,t,i,r){if(this.upAxis=W.Pq.Up(),this.upAxisSpace=0,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=W.PT.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=W.Pq.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,r){if(r.adjustYaw&&(this.adjustYaw=r.adjustYaw),r.adjustPitch&&(this.adjustPitch=r.adjustPitch),r.adjustRoll&&(this.adjustRoll=r.adjustRoll),null!=r.maxYaw?this.maxYaw=r.maxYaw:this.maxYaw=Math.PI,null!=r.minYaw?this.minYaw=r.minYaw:this.minYaw=-Math.PI,null!=r.maxPitch?this.maxPitch=r.maxPitch:this.maxPitch=Math.PI,null!=r.minPitch?this.minPitch=r.minPitch:this.minPitch=-Math.PI,null!=r.slerpAmount&&(this.slerpAmount=r.slerpAmount),null!=r.upAxis&&(this.upAxis=r.upAxis),null!=r.upAxisSpace&&(this.upAxisSpace=r.upAxisSpace),null!=r.yawAxis||null!=r.pitchAxis){let e=Mt._0.Y,t=Mt._0.X;null!=r.yawAxis&&(e=r.yawAxis.clone(),e.normalize()),null!=r.pitchAxis&&(t=r.pitchAxis.clone(),t.normalize());const i=W.Pq.Cross(t,e);this._transformYawPitch=W.uq.Identity(),W.uq.FromXYZAxesToRef(t,e,i,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}void 0!==r.useAbsoluteValueForYaw&&(this.useAbsoluteValueForYaw=r.useAbsoluteValueForYaw)}t.getParent()||2!=this.upAxisSpace||(this.upAxisSpace=0)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped)return void(this._firstFrameSkipped=!0);const e=this.bone,t=fr._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target;const r=fr._TmpMats[0],s=fr._TmpMats[1],n=this.mesh,o=e.getParent(),a=fr._TmpVecs[1];a.copyFrom(this.upAxis),2==this.upAxisSpace&&o?(this._transformYawPitch&&W.Pq.TransformCoordinatesToRef(a,this._transformYawPitchInv,a),o.getDirectionToRef(a,this.mesh,a)):0==this.upAxisSpace&&(n.getDirectionToRef(a,a),1==n.scaling.x&&1==n.scaling.y&&1==n.scaling.z||a.normalize());let l=!1,h=!1;if(this._maxYaw==Math.PI&&this._minYaw==-Math.PI||(l=!0),this._maxPitch==Math.PI&&this._minPitch==-Math.PI||(h=!0),l||h){const e=fr._TmpMats[2],r=fr._TmpMats[3];if(2==this.upAxisSpace&&1==a.y&&o)o.getRotationMatrixToRef(1,this.mesh,e);else if(0!=this.upAxisSpace||1!=a.y||o){let t=fr._TmpVecs[2];t.copyFrom(this._fowardAxis),this._transformYawPitch&&W.Pq.TransformCoordinatesToRef(t,this._transformYawPitchInv,t),o?o.getDirectionToRef(t,this.mesh,t):n.getDirectionToRef(t,t);const i=W.Pq.Cross(a,t);i.normalize(),t=W.Pq.Cross(i,a),W.uq.FromXYZAxesToRef(i,a,t,e)}else e.copyFrom(n.getWorldMatrix());e.invertToRef(r);let s=null;if(h){const n=fr._TmpVecs[3];i.subtractToRef(t,n),W.Pq.TransformCoordinatesToRef(n,r,n),s=Math.sqrt(n.x*n.x+n.z*n.z);const o=Math.atan2(n.y,s);let a=o;o>this._maxPitch?(n.y=this._maxPitchTan*s,a=this._maxPitch):othis._maxYaw||aMath.PI?this._isAngleBetween(o,this._maxYaw,this._midYawConstraint)?(n.z=this._maxYawCos*s,n.x=this._maxYawSin*s,l=this._maxYaw):this._isAngleBetween(o,this._midYawConstraint,this._minYaw)&&(n.z=this._minYawCos*s,n.x=this._minYawSin*s,l=this._minYaw):a>this._maxYaw?(n.z=this._maxYawCos*s,n.x=this._maxYawSin*s,o<0&&this.useAbsoluteValueForYaw&&(n.x*=-1),l=this._maxYaw):aMath.PI){const e=fr._TmpVecs[8];e.copyFrom(Mt._0.Z),this._transformYawPitch&&W.Pq.TransformCoordinatesToRef(e,this._transformYawPitchInv,e);const t=fr._TmpMats[4];this._boneQuat.toRotationMatrix(t),this.mesh.getWorldMatrix().multiplyToRef(t,t),W.Pq.TransformCoordinatesToRef(e,t,e),W.Pq.TransformCoordinatesToRef(e,r,e);const i=Math.atan2(e.x,e.z);if(this._getAngleBetween(i,o)>this._getAngleBetween(i,this._midYawConstraint)){null==s&&(s=Math.sqrt(n.x*n.x+n.z*n.z));const e=this._getAngleBetween(i,this._maxYaw);this._getAngleBetween(i,this._minYaw)Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i}_getAngleBetween(e,t){let i=0;return i=(e=(e%=2*Math.PI)<0?e+2*Math.PI:e)<(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)?t-e:e-t,i>Math.PI&&(i=2*Math.PI-i),i}_isAngleBetween(e,t,i){if(e=(e%=2*Math.PI)<0?e+2*Math.PI:e,(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)<(i=(i%=2*Math.PI)<0?i+2*Math.PI:i)){if(e>t&&ei&&e{const e=new Uint8Array(4);return!!((new Uint32Array(e.buffer)[0]=1)&e[0])})();Object.defineProperty(st.R.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0}),Object.defineProperty(st.R.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0}),Object.defineProperty(st.R.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0}),st.R.prototype._rebuild=function(){this._buffer?._rebuild(),this._alignedBuffer?._rebuild()},st.R.prototype.dispose=function(){this._ownsBuffer&&this._buffer.dispose(),this._alignedBuffer?.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0},st.R.prototype.getWrapperBuffer=function(){return this._alignedBuffer||this._buffer},st.R.prototype._alignBuffer=function(){const e=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideAndOffsetMultiple4Bytes||this.byteStride%4==0&&this.byteOffset%4==0||!e)return;const t=st.R.GetTypeByteLength(this.type),i=this.byteStride+3&-4,r=i/t,s=this._maxVerticesCount,n=s*i/t;let o,a;if(Array.isArray(e)){const t=new Float32Array(e);o=new DataView(t.buffer,t.byteOffset,t.byteLength)}else o=e instanceof ArrayBuffer?new DataView(e,0,e.byteLength):new DataView(e.buffer,e.byteOffset,e.byteLength);a=this.type===st.R.BYTE?new Int8Array(n):this.type===st.R.UNSIGNED_BYTE?new Uint8Array(n):this.type===st.R.SHORT?new Int16Array(n):this.type===st.R.UNSIGNED_SHORT?new Uint16Array(n):this.type===st.R.INT?new Int32Array(n):this.type===st.R.UNSIGNED_INT?new Uint32Array(n):new Float32Array(n);const l=this.getSize();let h=this.byteOffset;for(let e=0;e{if(t.type!==yi.Zp.POINTERWHEEL)return;const i=t.event,r=i.deltaMode===gr.s.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*r*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*r*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*r*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,yi.Zp.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"}}(0,je.Cg)([(0,$e.lK)()],vr.prototype,"wheelPrecisionX",void 0),(0,je.Cg)([(0,$e.lK)()],vr.prototype,"wheelPrecisionY",void 0),(0,je.Cg)([(0,$e.lK)()],vr.prototype,"wheelPrecisionZ",void 0);class xr{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=Ue.S0.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let r=0,s=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=n=>{const o=n.event,a="touch"===o.pointerType;if(n.type!==yi.Zp.POINTERMOVE&&-1===this.buttons.indexOf(o.button))return;const l=o.target;if(this._altKey=o.altKey,this._ctrlKey=o.ctrlKey,this._metaKey=o.metaKey,this._shiftKey=o.shiftKey,this._buttonsPressed=o.buttons,t.isPointerLock){const e=o.movementX,t=o.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else{if(n.type!==yi.Zp.POINTERDOWN&&n.type!==yi.Zp.POINTERDOUBLETAP&&a&&this._pointA?.pointerId!==o.pointerId&&this._pointB?.pointerId!==o.pointerId)return;if(n.type!==yi.Zp.POINTERDOWN||-1!==this._currentActiveButton&&!a)if(n.type===yi.Zp.POINTERDOUBLETAP)this.onDoubleTap(o.pointerType);else if(n.type!==yi.Zp.POINTERUP||this._currentActiveButton!==o.button&&!a){if(n.type===yi.Zp.POINTERMOVE)if(e||o.preventDefault(),this._pointA&&null===this._pointB){const e=o.clientX-this._pointA.x,t=o.clientY-this._pointA.y;this._pointA.x=o.clientX,this._pointA.y=o.clientY,this.onTouch(this._pointA,e,t)}else if(this._pointA&&this._pointB){const e=this._pointA.pointerId===o.pointerId?this._pointA:this._pointB;e.x=o.clientX,e.y=o.clientY;const t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,a=t*t+i*i,l={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:o.pointerId,type:n.type};this.onMultiTouch(this._pointA,this._pointB,r,a,s,l),s=l,r=a}}else{try{l?.releasePointerCapture(o.pointerId)}catch(e){}a||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==o.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==o.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==r||s)&&(this.onMultiTouch(this._pointA,this._pointB,r,0,s,null),r=0,s=null),this._currentActiveButton=-1,this.onButtonUp(o),e||o.preventDefault()}else{try{l?.setPointerCapture(o.pointerId)}catch(e){}if(null===this._pointA)this._pointA={x:o.clientX,y:o.clientY,pointerId:o.pointerId,type:o.pointerType};else{if(null!==this._pointB)return;this._pointB={x:o.clientX,y:o.clientY,pointerId:o.pointerId,type:o.pointerType}}-1!==this._currentActiveButton||a||(this._currentActiveButton=o.button),this.onButtonDown(o),e||(o.preventDefault(),i&&i.focus())}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,yi.Zp.POINTERDOWN|yi.Zp.POINTERUP|yi.Zp.POINTERMOVE|yi.Zp.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,r=0,s=null,this.onLostFocus()},this._contextMenuBind=e=>this.onContextMenu(e),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const n=this.camera.getScene().getEngine().getHostWindow();n&&Ue.S0.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&Ue.S0.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,r,s,n){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}(0,je.Cg)([(0,$e.lK)()],xr.prototype,"buttons",void 0);var br={};class Sr{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();this.attached[t]?Z.V.Warn("camera input of type "+t+" already exists on camera"):(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)return i.detachControl(),i.camera=null,delete this.attached[t],void this.rebuildInputCheck()}}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=!rt.ForceAttachControlToAlwaysPreventDefault&&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 e in this.attached){const i=this.attached[e],r=it.p.Serialize(i);t[i.getClassName()]=r}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const e in t){const i=br[e];if(i){const r=t[e],s=it.p.Parse((()=>new i),r,null);this.add(s)}}}else for(const t in this.attached){const i=br[this.attached[t].getClassName()];if(i){const r=it.p.Parse((()=>new i),e,null);this.remove(this.attached[t]),this.add(r)}}}}class Tr{constructor(e,t){this.x=e,this.y=t}}class Cr{get isConnected(){return this._isConnected}constructor(e,t,i,r=0,s=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=Cr.GAMEPAD,this._leftStickAxisX=r,this._leftStickAxisY=s,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(){}}Cr.GAMEPAD=0,Cr.GENERIC=1,Cr.XBOX=2,Cr.POSE_ENABLED=3,Cr.DUALSHOCK=4;class yr extends Cr{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new z.cP,this.onButtonUpObservable=new z.cP,this.type=Cr.GENERIC,this._buttons=new Array(i.buttons.length)}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}update(){super.update();for(let e=0;e{e.type!==Cr.POSE_ENABLED&&(this.gamepad&&e.type!==Cr.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType(Cr.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(0!=t.x){const i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){const i=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=i&&Math.abs(i)>.005&&(e.inertialBetaOffset+=i)}}const i=this.gamepad.leftStick;if(i&&0!=i.y){const e=i.y/this.gamepadMoveSensibility;0!=e&&Math.abs(e)>.005&&(this.camera.inertialRadiusOffset-=e)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}(0,je.Cg)([(0,$e.lK)()],Er.prototype,"gamepadRotationSensibility",void 0),(0,je.Cg)([(0,$e.lK)()],Er.prototype,"gamepadMoveSensibility",void 0),br.ArcRotateCameraGamepadInput=Er;var Pr,Ar=i(80109);class Rr{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=Ue.S0.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===Ar.TB.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(-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.keysReset.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-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.keysReset.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,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?r/(1+this.wheelDeltaPercentage):r*(1+this.wheelDeltaPercentage),i}attachControl(e){e=Ue.S0.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==yi.Zp.POINTERWHEEL)return;const i=t.event;let r=0;const s=i.deltaMode===gr.s.DOM_DELTA_LINE?40:1,n=-i.deltaY*s;if(this.customComputeDeltaFromMouseWheel)r=this.customComputeDeltaFromMouseWheel(n,this,i);else if(this.wheelDeltaPercentage){if(r=this._computeDeltaFromMouseWheelLegacyEvent(n,this.camera.radius),r>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+r;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=(0,ar.Clamp)(e,0,Number.MAX_VALUE),r=this._computeDeltaFromMouseWheelLegacyEvent(n,e)}}else r=n/(40*this.wheelPrecision);r&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(r)):this.camera.inertialRadiusOffset+=r),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,yi.Zp.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=Ft.Z.FromPositionAndNormal(e.target,t)}_getPosition(){const e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,W.uq.Identity(),e,!1);0===e.targetScreenOffset.x&&0===e.targetScreenOffset.y||(this._viewOffset.set(e.targetScreenOffset.x,e.targetScreenOffset.y,0),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),this._globalOffset=W.Pq.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let r=0;return this._hitPlane&&(r=i.intersectsPlane(this._hitPlane)??0),i.origin.addInPlace(i.direction.scaleInPlace(r))}_zoomToMouse(e){const t=this.camera,i=1-t.inertia;if(t.lowerRadiusLimit){const r=t.lowerRadiusLimit??0;t.radius-(t.inertialRadiusOffset+e)/ir&&(e=(t.radius-r)*i-t.inertialRadiusOffset)}const r=e/i/t.radius,s=this._getPosition(),n=W.AA.Vector3[6];s.subtractToRef(t.target,n),n.scaleInPlace(r),n.scaleInPlace(i),this._inertialPanning.addInPlace(n),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,r),this._isPinching=!0):this._computeMultiTouchPanning(s,n)):this.multiTouchPanning?this._computeMultiTouchPanning(s,n):this.pinchZoom&&this._computePinchZoom(i,r))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}Mr.MinimumRadiusForPinch=.001,(0,je.Cg)([(0,$e.lK)()],Mr.prototype,"buttons",void 0),(0,je.Cg)([(0,$e.lK)()],Mr.prototype,"angularSensibilityX",void 0),(0,je.Cg)([(0,$e.lK)()],Mr.prototype,"angularSensibilityY",void 0),(0,je.Cg)([(0,$e.lK)()],Mr.prototype,"pinchPrecision",void 0),(0,je.Cg)([(0,$e.lK)()],Mr.prototype,"pinchDeltaPercentage",void 0),(0,je.Cg)([(0,$e.lK)()],Mr.prototype,"useNaturalPinchZoom",void 0),(0,je.Cg)([(0,$e.lK)()],Mr.prototype,"pinchZoom",void 0),(0,je.Cg)([(0,$e.lK)()],Mr.prototype,"panningSensibility",void 0),(0,je.Cg)([(0,$e.lK)()],Mr.prototype,"multiTouchPanning",void 0),(0,je.Cg)([(0,$e.lK)()],Mr.prototype,"multiTouchPanAndZoom",void 0),br.ArcRotateCameraPointersInput=Mr;class Or extends Sr{constructor(e){super(e)}addMouseWheel(){return this.add(new Ir),this}addPointers(){return this.add(new Mr),this}addKeyboard(){return this.add(new Rr),this}}Or.prototype.addVRDeviceOrientation=function(){return this.add(new Dr),this};class Dr{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=Ue.S0.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);const t=this.camera.getScene().getEngine().getHostWindow();t&&("undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t.addEventListener("deviceorientation",this._deviceOrientationHandler):Ue.S0.Warn("Permission not granted.")})).catch((e=>{Ue.S0.Error(e)})):t.addEventListener("deviceorientation",this._deviceOrientationHandler))}_onOrientationEvent(e){null!==e.alpha&&(this._alpha=(0|+e.alpha)*this.alphaCorrection),null!==e.gamma&&(this._gamma=(0|+e.gamma)*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"}}br.ArcRotateCameraVRDeviceOrientationInput=Dr;class wr{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=Ue.S0.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===Ar.TB.KEYDOWN)-1===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)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-1!==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)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,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(e)}),yi.Zp.POINTERDOWN|yi.Zp.POINTERUP|yi.Zp.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,i=this.camera.getEngine();if(!this.touchEnabled&&"touch"===t.pointerType)return;if(e.type!==yi.Zp.POINTERMOVE&&-1===this.buttons.indexOf(t.button))return;const r=t.target;if(e.type===yi.Zp.POINTERDOWN){try{r?.setPointerCapture(t.pointerId)}catch(t){}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||t.preventDefault(),i.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===yi.Zp.POINTERUP){try{r?.releasePointerCapture(t.pointerId)}catch(t){}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===yi.Zp.POINTERMOVE){if(!this._previousPosition)return void(i.isPointerLock&&this._onMouseMove(e.event));const r=t.clientX-this._previousPosition.x,s=t.clientY-this._previousPosition.y;this._rotateCamera(r,s),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){if(!this.camera.getEngine().isPointerLock)return;const t=e.movementX,i=e.movementY;this._rotateCamera(t,i),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){const i=this.camera,r=(e*=i._calculateHandednessMultiplier())/this.angularSensibility,s=t/this.angularSensibility,n=W.PT.RotationYawPitchRoll(i.rotation.y,i.rotation.x,i.rotation.z);let o;if(this.buttonsPitch.some((e=>e===this.activeButton))&&(o=W.PT.RotationAxis(Mt._0.X,s),n.multiplyInPlace(o)),this.buttonsYaw.some((e=>e===this.activeButton))){o=W.PT.RotationAxis(Mt._0.Y,r),n.multiplyInPlace(o);const e=i.bankedTurnLimit+i._trackRoll;if(i.bankedTurn&&-ee===this.activeButton))&&(o=W.PT.RotationAxis(Mt._0.Z,-r),i._trackRoll-=r,n.multiplyInPlace(o)),n.toEulerAnglesToRef(i.rotation)}}(0,je.Cg)([(0,$e.lK)()],Nr.prototype,"buttons",void 0),(0,je.Cg)([(0,$e.lK)()],Nr.prototype,"angularSensibility",void 0),br.FlyCameraMouseInput=Nr;class Fr{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=Ue.S0.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===Ar.TB.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,this._shiftPressed=i.shiftKey,(-1!==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)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-1!==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)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,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=>{-1!==this.keysHeightOffsetIncr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset+=this.heightSensibility:-1!==this.keysHeightOffsetDecr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset-=this.heightSensibility:-1!==this.keysRotationOffsetIncr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset+=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRotationOffsetDecr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset-=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRadiusIncr.indexOf(e)&&this._modifierRadius()?this.camera.radius+=this.radiusSensibility:-1!==this.keysRadiusDecr.indexOf(e)&&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}}(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysHeightOffsetIncr",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysHeightOffsetDecr",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysHeightOffsetModifierAlt",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysHeightOffsetModifierCtrl",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysHeightOffsetModifierShift",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysRotationOffsetIncr",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysRotationOffsetDecr",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysRotationOffsetModifierAlt",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysRotationOffsetModifierCtrl",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysRotationOffsetModifierShift",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysRadiusIncr",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysRadiusDecr",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysRadiusModifierAlt",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysRadiusModifierCtrl",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"keysRadiusModifierShift",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"heightSensibility",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"rotationSensibility",void 0),(0,je.Cg)([(0,$e.lK)()],Fr.prototype,"radiusSensibility",void 0),br.FollowCameraKeyboardMoveInput=Fr;class Lr{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=Ue.S0.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==yi.Zp.POINTERWHEEL)return;const i=t.event;let r=0;const s=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(+this.axisControlRadius+ +this.axisControlHeight+ +this.axisControlRotation&&Z.V.Warn("wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?r=.01*s*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?r=.01*s*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(r=.01*s*this.wheelDeltaPercentage*this.camera.rotationOffset)):r=s*this.wheelPrecision,r&&(this.axisControlRadius?this.camera.radius+=r:this.axisControlHeight?this.camera.heightOffset-=r:this.axisControlRotation&&(this.camera.rotationOffset-=r)),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,yi.Zp.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}(0,je.Cg)([(0,$e.lK)()],Lr.prototype,"axisControlRadius",void 0),(0,je.Cg)([(0,$e.lK)()],Lr.prototype,"axisControlHeight",void 0),(0,je.Cg)([(0,$e.lK)()],Lr.prototype,"axisControlRotation",void 0),(0,je.Cg)([(0,$e.lK)()],Lr.prototype,"wheelPrecision",void 0),(0,je.Cg)([(0,$e.lK)()],Lr.prototype,"wheelDeltaPercentage",void 0),br.FollowCameraMouseWheelInput=Lr;class Br extends xr{constructor(){super(...arguments),this.angularSensibilityX=1,this.angularSensibilityY=1,this.pinchPrecision=1e4,this.pinchDeltaPercentage=0,this.axisXControlRadius=!1,this.axisXControlHeight=!1,this.axisXControlRotation=!0,this.axisYControlRadius=!1,this.axisYControlHeight=!0,this.axisYControlRotation=!1,this.axisPinchControlRadius=!0,this.axisPinchControlHeight=!1,this.axisPinchControlRotation=!1,this.warningEnable=!0,this._warningCounter=0}getClassName(){return"FollowCameraPointersInput"}onTouch(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)}onMultiTouch(e,t,i,r,s,n){if(0===i&&null===s)return;if(0===r&&null===n)return;let o=(r-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(o*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=o*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=o*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=o*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=o),this.axisPinchControlHeight&&(this.camera.heightOffset+=o),this.axisPinchControlRadius&&(this.camera.radius-=o))}_warning(){if(!this.warningEnable||this._warningCounter++%100!=0)return;const e="It probably only makes sense to control ONE camera property with each pointer axis. Set 'warningEnable = false' if you are sure. Currently enabled: ";+this.axisXControlRotation+ +this.axisXControlHeight+ +this.axisXControlRadius<=1&&Z.V.Warn(e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),+this.axisYControlRotation+ +this.axisYControlHeight+ +this.axisYControlRadius<=1&&Z.V.Warn(e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),+this.axisPinchControlRotation+ +this.axisPinchControlHeight+ +this.axisPinchControlRadius<=1&&Z.V.Warn(e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}(0,je.Cg)([(0,$e.lK)()],Br.prototype,"angularSensibilityX",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"angularSensibilityY",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"pinchPrecision",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"pinchDeltaPercentage",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"axisXControlRadius",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"axisXControlHeight",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"axisXControlRotation",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"axisYControlRadius",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"axisYControlHeight",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"axisYControlRotation",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"axisPinchControlRadius",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"axisPinchControlHeight",void 0),(0,je.Cg)([(0,$e.lK)()],Br.prototype,"axisPinchControlRotation",void 0),br.FollowCameraPointersInput=Br;class Vr{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=Ue.S0.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===Ar.TB.KEYDOWN)-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.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)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-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.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)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.preventDefault()}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t{const s=r.event,n="touch"===s.pointerType;if(!this.touchEnabled&&n)return;if(r.type!==yi.Zp.POINTERMOVE&&-1===this.buttons.indexOf(s.button))return;const o=s.target;if(r.type===yi.Zp.POINTERDOWN){if(n&&-1!==this._activePointerId||!n&&-1!==this._currentActiveButton)return;this._activePointerId=s.pointerId;try{o?.setPointerCapture(s.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=s.button),this._previousPosition={x:s.clientX,y:s.clientY},e||(s.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(r.event)}else if(r.type===yi.Zp.POINTERUP){if(n&&this._activePointerId!==s.pointerId||!n&&this._currentActiveButton!==s.button)return;try{o?.releasePointerCapture(s.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||s.preventDefault(),this._activePointerId=-1}else if(r.type===yi.Zp.POINTERMOVE&&(this._activePointerId===s.pointerId||!n))if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(r.event);else if(this._previousPosition){const t=this.camera._calculateHandednessMultiplier(),i=(s.clientX-this._previousPosition.x)*t,r=s.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=i/this.angularSensibility,this.camera.cameraRotation.x+=r/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:i,offsetY:r}),this._previousPosition={x:s.clientX,y:s.clientY},e||s.preventDefault()}}),this._onMouseMove=i=>{if(!t.isPointerLock)return;const r=this.camera._calculateHandednessMultiplier(),s=i.movementX*r;this.camera.cameraRotation.y+=s/this.angularSensibility;const n=i.movementY;this.camera.cameraRotation.x+=n/this.angularSensibility,this._previousPosition=null,e||i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,yi.Zp.POINTERDOWN|yi.Zp.POINTERUP|yi.Zp.POINTERMOVE),i&&(this._contextMenuBind=e=>this.onContextMenu(e),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 e=this.camera.getEngine().getInputElement();e&&e.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"}}(0,je.Cg)([(0,$e.lK)()],kr.prototype,"buttons",void 0),(0,je.Cg)([(0,$e.lK)()],kr.prototype,"angularSensibility",void 0),br.FreeCameraMouseInput=kr,function(e){e[e.MoveRelative=0]="MoveRelative",e[e.RotateRelative=1]="RotateRelative",e[e.MoveScene=2]="MoveScene"}(Pr||(Pr={}));class Ur extends vr{constructor(){super(...arguments),this._moveRelative=W.Pq.Zero(),this._rotateRelative=W.Pq.Zero(),this._moveScene=W.Pq.Zero(),this._wheelXAction=Pr.MoveRelative,this._wheelXActionCoordinate=0,this._wheelYAction=Pr.MoveRelative,this._wheelYActionCoordinate=2,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){null===e&&this._wheelXAction!==Pr.MoveRelative||(this._wheelXAction=Pr.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==Pr.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){null===e&&this._wheelYAction!==Pr.MoveRelative||(this._wheelYAction=Pr.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==Pr.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){null===e&&this._wheelZAction!==Pr.MoveRelative||(this._wheelZAction=Pr.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==Pr.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){null===e&&this._wheelXAction!==Pr.RotateRelative||(this._wheelXAction=Pr.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==Pr.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){null===e&&this._wheelYAction!==Pr.RotateRelative||(this._wheelYAction=Pr.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==Pr.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){null===e&&this._wheelZAction!==Pr.RotateRelative||(this._wheelZAction=Pr.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==Pr.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){null===e&&this._wheelXAction!==Pr.MoveScene||(this._wheelXAction=Pr.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==Pr.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){null===e&&this._wheelYAction!==Pr.MoveScene||(this._wheelYAction=Pr.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==Pr.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){null===e&&this._wheelZAction!==Pr.MoveScene||(this._wheelZAction=Pr.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==Pr.MoveScene?null:this._wheelZActionCoordinate}checkInputs(){if(0===this._wheelDeltaX&&0===this._wheelDeltaY&&0==this._wheelDeltaZ)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=W.uq.Zero();this.camera.getViewMatrix().invertToRef(e);const t=W.Pq.Zero();W.Pq.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(0===e)return;if(null===t||null===i)return;let r=null;switch(t){case Pr.MoveRelative:r=this._moveRelative;break;case Pr.RotateRelative:r=this._rotateRelative;break;case Pr.MoveScene:r=this._moveScene}switch(i){case 0:r.set(e,0,0);break;case 1:r.set(0,e,0);break;case 2:r.set(0,0,e)}}}(0,je.Cg)([(0,$e.lK)()],Ur.prototype,"wheelXMoveRelative",null),(0,je.Cg)([(0,$e.lK)()],Ur.prototype,"wheelYMoveRelative",null),(0,je.Cg)([(0,$e.lK)()],Ur.prototype,"wheelZMoveRelative",null),(0,je.Cg)([(0,$e.lK)()],Ur.prototype,"wheelXRotateRelative",null),(0,je.Cg)([(0,$e.lK)()],Ur.prototype,"wheelYRotateRelative",null),(0,je.Cg)([(0,$e.lK)()],Ur.prototype,"wheelZRotateRelative",null),(0,je.Cg)([(0,$e.lK)()],Ur.prototype,"wheelXMoveScene",null),(0,je.Cg)([(0,$e.lK)()],Ur.prototype,"wheelYMoveScene",null),(0,je.Cg)([(0,$e.lK)()],Ur.prototype,"wheelZMoveScene",null),br.FreeCameraMouseWheelInput=Ur;class Gr{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=Ue.S0.IsSafari()}attachControl(e){e=Ue.S0.BackCompatCameraNoPreventDefault(arguments);let t=null;if(void 0===this._pointerInput&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{const r=i.event,s="mouse"===r.pointerType||this._isSafari&&void 0===r.pointerType;if(this.allowMouse||!s)if(i.type===yi.Zp.POINTERDOWN){if(e||r.preventDefault(),this._pointerPressed.push(r.pointerId),1!==this._pointerPressed.length)return;t={x:r.clientX,y:r.clientY}}else if(i.type===yi.Zp.POINTERUP){e||r.preventDefault();const i=this._pointerPressed.indexOf(r.pointerId);if(-1===i)return;if(this._pointerPressed.splice(i,1),0!=i)return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===yi.Zp.POINTERMOVE){if(e||r.preventDefault(),!t)return;if(0!=this._pointerPressed.indexOf(r.pointerId))return;this._offsetX=r.clientX-t.x,this._offsetY=-(r.clientY-t.y)}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,yi.Zp.POINTERDOWN|yi.Zp.POINTERUP|yi.Zp.POINTERMOVE),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null}this._pointerPressed.length=0,this._offsetX=null,this._offsetY=null}}checkInputs(){if(null===this._offsetX||null===this._offsetY)return;if(0===this._offsetX&&0===this._offsetY)return;const e=this.camera,t=e._calculateHandednessMultiplier();if(e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility,this.singleFingerRotate&&1===this._pointerPressed.length||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{const t=e._computeLocalCameraSpeed(),i=new W.Pq(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);W.uq.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(W.Pq.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}(0,je.Cg)([(0,$e.lK)()],Gr.prototype,"touchAngularSensibility",void 0),(0,je.Cg)([(0,$e.lK)()],Gr.prototype,"touchMoveSensibility",void 0),br.FreeCameraTouchInput=Gr;class zr extends Sr{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new Vr),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new kr(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new Ur,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new Gr),this}clear(){super.clear(),this._mouseInput=null}}zr.prototype.addDeviceOrientation=function(e){return this._deviceOrientationInput||(this._deviceOrientationInput=new Wr,e&&(this._deviceOrientationInput.smoothFactor=e),this.add(this._deviceOrientationInput)),this};class Wr{static WaitForOrientationChangeAsync(e){return new Promise(((t,i)=>{let r=!1;const s=()=>{window.removeEventListener("deviceorientation",s),r=!0,t()};e&&setTimeout((()=>{r||(window.removeEventListener("deviceorientation",s),i("WaitForOrientationChangeAsync timed out"))}),e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"==e?window.addEventListener("deviceorientation",s):Ue.S0.Warn("Permission not granted.")})).catch((e=>{Ue.S0.Error(e)})):window.addEventListener("deviceorientation",s)}))}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new W.PT,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new z.cP,this._orientationChanged=()=>{this._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-Ue.S0.ToRadians(this._screenOrientationAngle/2),this._screenQuaternion.copyFromFloats(0,Math.sin(this._screenOrientationAngle),0,Math.cos(this._screenOrientationAngle))},this._deviceOrientation=e=>{this.smoothFactor?(this._alpha=null!==e.alpha?Ue.S0.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=null!==e.beta?Ue.S0.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=null!==e.gamma?Ue.S0.SmoothAngleChange(this._gamma,e.gamma,this.smoothFactor):0):(this._alpha=null!==e.alpha?e.alpha:0,this._beta=null!==e.beta?e.beta:0,this._gamma=null!==e.gamma?e.gamma:0),null!==e.alpha&&this._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTransform=new W.PT(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}get camera(){return this._camera}set camera(e){this._camera=e,null==this._camera||this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new W.PT),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()};"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t():Ue.S0.Warn("Permission not granted.")})).catch((e=>{Ue.S0.Error(e)})):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(W.PT.RotationYawPitchRollToRef(Ue.S0.ToRadians(this._alpha),Ue.S0.ToRadians(this._beta),-Ue.S0.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTransform),this._camera.getScene().useRightHandedSystem?this._camera.rotationQuaternion.y*=-1:this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)}getClassName(){return"FreeCameraDeviceOrientationInput"}getSimpleName(){return"deviceOrientation"}}br.FreeCameraDeviceOrientationInput=Wr;class Hr{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=W.uq.Identity(),this._deltaTransform=W.Pq.Zero(),this._vector3=W.Pq.Zero(),this._vector2=W.I9.Zero()}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){const e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add((e=>{e.type!==Cr.POSE_ENABLED&&(this.gamepad&&e.type!==Cr.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType(Cr.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;0!==this.gamepadMoveSensibility&&(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&&0!==this.gamepadAngularSensibility?(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):W.uq.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);const r=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*r,0,-t.y*r),W.Pq.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"}}(0,je.Cg)([(0,$e.lK)()],Hr.prototype,"gamepadAngularSensibility",void 0),(0,je.Cg)([(0,$e.lK)()],Hr.prototype,"gamepadMoveSensibility",void 0),br.FreeCameraGamepadInput=Hr;var Xr,qr,Yr,Kr,jr,$r=i(47131);!function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(Xr||(Xr={}));class Qr{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={...Qr._GetDefaultOptions(),...t};if(this._leftJoystick=!!e,Qr._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=0,this._axisTargetedByUpAndDown=1,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new $r.w,this.deltaPosition=W.Pq.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{Qr._VJCanvasWidth=window.innerWidth,Qr._VJCanvasHeight=window.innerHeight,Qr.Canvas&&(Qr.Canvas.width=Qr._VJCanvasWidth,Qr.Canvas.height=Qr._VJCanvasHeight),Qr._HalfWidth=Qr._VJCanvasWidth/2},!Qr.Canvas){window.addEventListener("resize",this._onResize,!1),Qr.Canvas=document.createElement("canvas"),Qr._VJCanvasWidth=window.innerWidth,Qr._VJCanvasHeight=window.innerHeight,Qr.Canvas.width=window.innerWidth,Qr.Canvas.height=window.innerHeight,Qr.Canvas.style.width="100%",Qr.Canvas.style.height="100%",Qr.Canvas.style.position="absolute",Qr.Canvas.style.backgroundColor="transparent",Qr.Canvas.style.top="0px",Qr.Canvas.style.left="0px",Qr.Canvas.style.zIndex="5",Qr.Canvas.style.touchAction="none",Qr.Canvas.setAttribute("touch-action","none");const e=Qr.Canvas.getContext("2d");if(!e)throw new Error("Unable to create canvas for virtual joystick");Qr._VJCanvasContext=e,Qr._VJCanvasContext.strokeStyle="#ffffff",Qr._VJCanvasContext.lineWidth=2,document.body.appendChild(Qr.Canvas)}Qr._HalfWidth=Qr.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&&Qr._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new W.I9(0,0),this._joystickPreviousPointerPos=new W.I9(0,0),this._joystickPointerStartPos=new W.I9(0,0),this._deltaJoystickVector=new W.I9(0,0),this._onPointerDownHandlerRef=e=>{this._onPointerDown(e)},this._onPointerMoveHandlerRef=e=>{this._onPointerMove(e)},this._onPointerUpHandlerRef=e=>{this._onPointerUp(e)},Qr.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),Qr.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),Qr.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),Qr.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),Qr.Canvas.addEventListener("contextmenu",(e=>{e.preventDefault()}),!1),requestAnimationFrame((()=>{this._drawVirtualJoystick()}))}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){let t;e.preventDefault(),t=!0===this._leftJoystick?e.clientXQr._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)):Qr._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 t=new W.I9(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),i=t.length();i>this.containerSize&&t.scaleInPlace(this.containerSize/i),this._joystickPointerPos.x=this._joystickPointerStartPos.x+t.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+t.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?Qr._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,2*this.containerSize,2*this.containerSize):(Qr._VJCanvasContext.beginPath(),Qr._VJCanvasContext.strokeStyle=this._joystickColor,Qr._VJCanvasContext.lineWidth=2,Qr._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,2*Math.PI,!0),Qr._VJCanvasContext.stroke(),Qr._VJCanvasContext.closePath(),Qr._VJCanvasContext.beginPath(),Qr._VJCanvasContext.lineWidth=6,Qr._VJCanvasContext.strokeStyle=this._joystickColor,Qr._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,2*Math.PI,!0),Qr._VJCanvasContext.stroke(),Qr._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?Qr._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,2*this.puckSize,2*this.puckSize):(Qr._VJCanvasContext.beginPath(),Qr._VJCanvasContext.strokeStyle=this._joystickColor,Qr._VJCanvasContext.lineWidth=2,Qr._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,2*Math.PI,!0),Qr._VJCanvasContext.stroke(),Qr._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()):(Qr._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),Qr._VJCanvasContext.beginPath(),Qr._VJCanvasContext.fillStyle="white",Qr._VJCanvasContext.beginPath(),Qr._VJCanvasContext.strokeStyle="red",Qr._VJCanvasContext.lineWidth=6,Qr._VJCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),Qr._VJCanvasContext.stroke(),Qr._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)})),requestAnimationFrame((()=>{this._drawVirtualJoystick()})))}releaseCanvas(){Qr.Canvas&&(Qr.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),Qr.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),Qr.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),Qr.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(Qr.Canvas),Qr.Canvas=null),this._released=!0}}Qr._GlobalJoystickIndex=0,Qr._AlwaysVisibleSticks=0,zr.prototype.addVirtualJoystick=function(){return this.add(new Zr),this};class Zr{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){const e=this.camera,t=50*e._computeLocalCameraSpeed(),i=W.uq.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),r=W.Pq.TransformCoordinates(new W.Pq(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(r),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}}attachControl(){this._leftjoystick=new Qr(!0),this._leftjoystick.setAxisForUpDown(2),this._leftjoystick.setAxisForLeftRight(0),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new Qr(!1),this._rightjoystick.setAxisForUpDown(0),this._rightjoystick.setAxisForLeftRight(1),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")}detachControl(){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()}getClassName(){return"FreeCameraVirtualJoystickInput"}getSimpleName(){return"virtualJoystick"}}br.FreeCameraVirtualJoystickInput=Zr,Ze.b.AddNodeConstructor("TargetCamera",((e,t)=>()=>new Jr(e,W.Pq.Zero(),t)));class Jr extends rt{constructor(e,t,i,r=!0){super(e,t,i,r),this._tmpUpVector=W.Pq.Zero(),this._tmpTargetVector=W.Pq.Zero(),this.cameraDirection=new W.Pq(0,0,0),this.cameraRotation=new W.I9(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new W.PT,this.rotation=new W.Pq(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=W.Pq.Zero(),this._initialFocalDistance=1,this._viewMatrix=W.uq.Zero(),this._camMatrix=W.uq.Zero(),this._cameraTransformMatrix=W.uq.Zero(),this._cameraRotationMatrix=W.uq.Zero(),this._referencePoint=new W.Pq(0,0,1),this._transformedReferencePoint=W.Pq.Zero(),this._deferredPositionUpdate=new W.Pq,this._deferredRotationQuaternionUpdate=new W.PT,this._deferredRotationUpdate=new W.Pq,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=W.Pq.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)}_initCache(){super._initCache(),this._cache.lockedTarget=new W.Pq(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new W.Pq(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new W.PT(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()/(100*e.getFps()))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=lt.bH),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),W.uq.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&&W.PT.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)return this.parent.getWorldMatrix().invertToRef(W.AA.Matrix[0]),W.Pq.TransformNormalToRef(this.cameraDirection,W.AA.Matrix[0],W.AA.Vector3[0]),this._deferredPositionUpdate.addInPlace(W.AA.Vector3[0]),void(this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate));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;if(this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i){if(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,!this.noRotationConstraint){const e=1.570796;this._deferredRotationUpdate.x>e&&(this._deferredRotationUpdate.x=e),this._deferredRotationUpdate.x<-e&&(this._deferredRotationUpdate.x=-e)}this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(W.PT.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(t),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>Ot.$.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&i&&this.onCollide(i))},this.inputs=new zr(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Ue.S0.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new W.Pq(0,0,0),this.cameraRotation=new W.I9(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?W.Pq.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let r=e;this.applyGravity&&(r=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,r,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=W.Pq.Zero(),this._transformedDirection=W.Pq.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"}}(0,je.Cg)([(0,$e.P_)()],es.prototype,"ellipsoid",void 0),(0,je.Cg)([(0,$e.P_)()],es.prototype,"ellipsoidOffset",void 0),(0,je.Cg)([(0,$e.lK)()],es.prototype,"checkCollisions",void 0),(0,je.Cg)([(0,$e.lK)()],es.prototype,"applyGravity",void 0),(0,X.Y5)("BABYLON.FreeCamera",es),Ze.b.AddNodeConstructor("TouchCamera",((e,t)=>()=>new ts(e,W.Pq.Zero(),t)));class ts extends es{get touchAngularSensibility(){const e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){const e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addTouch(),this._setupInputs()}getClassName(){return"TouchCamera"}_setupInputs(){const e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!e:e.allowMouse=!t}}Ze.b.AddNodeConstructor("ArcRotateCamera",((e,t)=>()=>new is(e,0,0,1,W.Pq.Zero(),t)));class is extends Jr{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 W.uq,this._upToYMatrix=new W.uq,this._upVector=W.Pq.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){W.uq.RotationAlignToRef(W.Pq.UpReadOnly,this._upVector,this._yToUpMatrix),W.uq.RotationAlignToRef(this._upVector,W.Pq.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}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}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 null!=this._bouncingBehavior}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new Pi,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return null!=this._framingBehavior}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new Ai,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return null!=this._autoRotationBehavior}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new Ei,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,r,s,n,o=!0){super(e,W.Pq.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=W.Pq.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=W.I9.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this.restoreStateInterpolationFactor=0,this._viewMatrix=new W.uq,this.panningAxis=new W.Pq(1,1,0),this._transformedDirection=new W.Pq,this.mapPanning=!1,this._progressiveRestore=!1,this.onMeshTargetChangedObservable=new z.cP,this.checkCollisions=!1,this.collisionRadius=new W.Pq(.5,.5,.5),this._previousPosition=W.Pq.Zero(),this._collisionVelocity=W.Pq.Zero(),this._newPosition=W.Pq.Zero(),this._computationVector=W.Pq.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);const r=Math.cos(this.alpha),s=Math.sin(this.alpha),n=Math.cos(this.beta);let o=Math.sin(this.beta);0===o&&(o=1e-4);const a=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*r*o,this.radius*n,this.radius*s*o),a.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let l=this.upVector;this.allowUpsideDown&&this.beta<0&&(l=l.clone(),l=l.negate()),this._computeViewMatrix(this._position,a,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=W.Pq.Zero(),s&&this.setTarget(s),this.alpha=t,this.beta=i,this.radius=r,this.getViewMatrix(),this.inputs=new Or(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new W.Pq(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=W.I9.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 e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}return this._getLockedTargetPosition()||this._target}storeState(){return this._storedAlpha=this._goalAlpha=this.alpha,this._storedBeta=this._goalBeta=this.beta,this._storedRadius=this._goalRadius=this.radius,this._storedTarget=this._goalTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this._goalTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return this.hasStateStored()&&this.restoreStateInterpolationFactor>lt.bH&&this.restoreStateInterpolationFactor<1?(this.interpolateTo(this._storedAlpha,this._storedBeta,this._storedRadius,this._storedTarget,this._storedTargetScreenOffset),!0):!!super._restoreStateValues()&&(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)}interpolateTo(e=this.alpha,t=this.beta,i=this.radius,r=this.target,s=this.targetScreenOffset){this._progressiveRestore=!0,this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,e=(0,ar.Clamp)(e,this.lowerAlphaLimit??-1/0,this.upperAlphaLimit??1/0),t=(0,ar.Clamp)(t,this.lowerBetaLimit??-1/0,this.upperBetaLimit??1/0),i=(0,ar.Clamp)(i,this.lowerRadiusLimit??-1/0,this.upperRadiusLimit??1/0),this._goalAlpha=e,this._goalBeta=t,this._goalRadius=i,this._goalTarget=r,this._goalTargetScreenOffset=s}_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)}attachControl(e,t,i=!0,r=2){const s=arguments;t=Ue.S0.BackCompatCameraNoPreventDefault(s),this._useCtrlForPanning=i,this._panningMouseButton=r,"boolean"==typeof s[0]&&(s.length>1&&(this._useCtrlForPanning=s[1]),s.length>2&&(this._panningMouseButton=s[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),this._progressiveRestore){const e=this._scene.getEngine().getDeltaTime()/1e3,t=1-Math.pow(2,-e/this.restoreStateInterpolationFactor);this.setTarget(W.Pq.Lerp(this.getTarget(),this._goalTarget,t)),W.PT.RotationAlphaBetaGammaToRef(this._goalAlpha,this._goalBeta,0,W.AA.Quaternion[0]),W.PT.RotationAlphaBetaGammaToRef(this.alpha,this.beta,0,W.AA.Quaternion[1]),W.PT.SlerpToRef(W.AA.Quaternion[1],W.AA.Quaternion[0],t,W.AA.Quaternion[2]),W.AA.Quaternion[2].normalize(),W.AA.Quaternion[2].toAlphaBetaGammaToRef(W.AA.Vector3[0]),this.alpha=W.AA.Vector3[0].x,this.beta=W.AA.Vector3[0].y,this.radius+=(this._goalRadius-this.radius)*t,W.I9.LerpToRef(this.targetScreenOffset,this._goalTargetScreenOffset,t,this.targetScreenOffset),(W.Pq.DistanceSquared(this.getTarget(),this._goalTarget)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||W.Pq.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);const e=this.alpha;0===this._computationVector.x&&0===this._computationVector.z?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+=2*t*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,r=!1){if(r=this.overrideCloneAlphaBetaRadius??r,e.computeWorldMatrix)t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{const t=e,r=this._getTargetPosition();if(r&&!i&&r.equals(t))return;this._targetHost=null,this._target=t,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}r||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta);let r=Math.sin(this.beta);0===r&&(r=1e-4),0===this.radius&&(this.radius=1e-4);const s=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*r,this.radius*i,this.radius*t*r),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||W.Pq.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),s.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const e=this.getScene().collisionCoordinator;this._collider||(this._collider=e.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,e.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let e=this.upVector;this.allowUpsideDown&&r<0&&(e=e.negate()),this._computeViewMatrix(this._position,s,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=s,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=Yt.MinMax(e);let r=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);r=Math.max(Math.min(r,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=r*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:r},t)}focusOn(e,t=!1){let i,r;if(void 0===e.min){const t=e||this.getScene().meshes;i=Yt.MinMax(t),r=W.Pq.Distance(i.min,i.max)}else i=e,r=e.distance;this._target=Yt.Center(i),t||(this.maxZ=2*r)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case rt.RIG_MODE_STEREOSCOPIC_OVERUNDER:case rt.RIG_MODE_STEREOSCOPIC_INTERLACED:case rt.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}const r=new is(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return r._cameraRigParams={},r.isRigCamera=!0,r.rigParent=this,r.upVector=this.upVector,r.mode=this.mode,r.orthoLeft=this.orthoLeft,r.orthoRight=this.orthoRight,r.orthoBottom=this.orthoBottom,r.orthoTop=this.orthoTop,r}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case rt.RIG_MODE_STEREOSCOPIC_OVERUNDER:case rt.RIG_MODE_STEREOSCOPIC_INTERLACED:case rt.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){const r=W.Pq.Distance(e,t),s=this.getScene().getEngine().getAspectRatio(this),n=Math.tan(this.fov/2),o=n*s,a=.5*r*i,l=a*Math.sqrt(1+1/(o*o)),h=a*Math.sqrt(1+1/(n*n));return Math.max(l,h)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}(0,je.Cg)([(0,$e.lK)()],is.prototype,"alpha",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"beta",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"radius",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"overrideCloneAlphaBetaRadius",void 0),(0,je.Cg)([(0,$e.P_)("target")],is.prototype,"_target",void 0),(0,je.Cg)([(0,$e.xG)("targetHost")],is.prototype,"_targetHost",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"inertialAlphaOffset",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"inertialBetaOffset",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"inertialRadiusOffset",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"lowerAlphaLimit",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"upperAlphaLimit",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"lowerBetaLimit",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"upperBetaLimit",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"lowerRadiusLimit",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"upperRadiusLimit",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"inertialPanningX",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"inertialPanningY",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"pinchToPanMaxDistance",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"panningDistanceLimit",void 0),(0,je.Cg)([(0,$e.P_)()],is.prototype,"panningOriginTarget",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"panningInertia",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"zoomToMouseLocation",null),(0,je.Cg)([(0,$e.lK)()],is.prototype,"zoomOnFactor",void 0),(0,je.Cg)([(0,$e.WM)()],is.prototype,"targetScreenOffset",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"allowUpsideDown",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"useInputToRestoreState",void 0),(0,je.Cg)([(0,$e.lK)()],is.prototype,"restoreStateInterpolationFactor",void 0),(0,X.Y5)("BABYLON.ArcRotateCamera",is),Ze.b.AddNodeConstructor("DeviceOrientationCamera",((e,t)=>()=>new rs(e,W.Pq.Zero(),t)));class rs extends es{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new W.PT,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new W.PT,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((e=>{0!=this._dragFactor&&(this._initialQuaternion||(this._initialQuaternion=new W.PT),W.PT.FromEulerAnglesToRef(0,e.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=Mt._0.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new W.PT),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 ss extends Sr{constructor(e){super(e)}addKeyboard(){return this.add(new wr),this}addMouse(){return this.add(new Nr),this}}class ns extends Jr{get angularSensibility(){const e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){const t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysForward(){const e=this.inputs.attached.keyboard;return e?e.keysForward:[]}set keysForward(e){const t=this.inputs.attached.keyboard;t&&(t.keysForward=e)}get keysBackward(){const e=this.inputs.attached.keyboard;return e?e.keysBackward:[]}set keysBackward(e){const t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}constructor(e,t,i,r=!0){super(e,t,i,r),this.ellipsoid=new W.Pq(1,1,1),this.ellipsoidOffset=new W.Pq(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=W.Pq.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=W.Pq.Zero(),this._diffPosition=W.Pq.Zero(),this._newPosition=W.Pq.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{(e=>{this._newPosition.copyFrom(e),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>Ot.$.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new ss(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Ue.S0.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new W.Pq(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?W.Pq.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let r=e;this.applyGravity&&(r=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,r,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=W.Pq.Zero(),this._transformedDirection=W.Pq.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=t-this.rotation.z;Math.abs(i)>=.001&&(this.rotation.z+=i/e,Math.abs(t-this.rotation.z)<=.001&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}}(0,je.Cg)([(0,$e.P_)()],ns.prototype,"ellipsoid",void 0),(0,je.Cg)([(0,$e.P_)()],ns.prototype,"ellipsoidOffset",void 0),(0,je.Cg)([(0,$e.lK)()],ns.prototype,"checkCollisions",void 0),(0,je.Cg)([(0,$e.lK)()],ns.prototype,"applyGravity",void 0),(0,X.Y5)("BABYLON.FlyCamera",ns);class os extends Sr{constructor(e){super(e)}addKeyboard(){return this.add(new Fr),this}addMouseWheel(){return this.add(new Lr),this}addPointers(){return this.add(new Br),this}addVRDeviceOrientation(){return Z.V.Warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}Ze.b.AddNodeConstructor("FollowCamera",((e,t)=>()=>new as(e,W.Pq.Zero(),t))),Ze.b.AddNodeConstructor("ArcFollowCamera",((e,t)=>()=>new ls(e,0,0,1,null,t)));class as extends Jr{constructor(e,t,i,r=null){super(e,t,i),this.radius=12,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.rotationOffset=0,this.lowerRotationOffsetLimit=null,this.upperRotationOffsetLimit=null,this.heightOffset=4,this.lowerHeightOffsetLimit=null,this.upperHeightOffsetLimit=null,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=r,this.inputs=new os(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;const t=W.AA.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);const i=Math.atan2(t.m[8],t.m[10]),r=Ue.S0.ToRadians(this.rotationOffset)+i,s=e.getAbsolutePosition(),n=s.x+Math.sin(r)*this.radius,o=s.z+Math.cos(r)*this.radius,a=n-this.position.x,l=s.y+this.heightOffset-this.position.y,h=o-this.position.z;let c=a*this.cameraAcceleration*2,u=l*this.cameraAcceleration,d=h*this.cameraAcceleration*2;(c>this.maxCameraSpeed||c<-this.maxCameraSpeed)&&(c=c<1?-this.maxCameraSpeed:this.maxCameraSpeed),(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),this.position=new W.Pq(this.position.x+c,this.position.y+u,this.position.z+d),this.setTarget(s)}attachControl(e,t){t=Ue.S0.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(){null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffsetthis.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffsetthis.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}}(0,je.Cg)([(0,$e.lK)()],as.prototype,"radius",void 0),(0,je.Cg)([(0,$e.lK)()],as.prototype,"lowerRadiusLimit",void 0),(0,je.Cg)([(0,$e.lK)()],as.prototype,"upperRadiusLimit",void 0),(0,je.Cg)([(0,$e.lK)()],as.prototype,"rotationOffset",void 0),(0,je.Cg)([(0,$e.lK)()],as.prototype,"lowerRotationOffsetLimit",void 0),(0,je.Cg)([(0,$e.lK)()],as.prototype,"upperRotationOffsetLimit",void 0),(0,je.Cg)([(0,$e.lK)()],as.prototype,"heightOffset",void 0),(0,je.Cg)([(0,$e.lK)()],as.prototype,"lowerHeightOffsetLimit",void 0),(0,je.Cg)([(0,$e.lK)()],as.prototype,"upperHeightOffsetLimit",void 0),(0,je.Cg)([(0,$e.lK)()],as.prototype,"cameraAcceleration",void 0),(0,je.Cg)([(0,$e.lK)()],as.prototype,"maxCameraSpeed",void 0),(0,je.Cg)([(0,$e.xG)("lockedTargetId")],as.prototype,"lockedTarget",void 0);class ls extends Jr{constructor(e,t,i,r,s,n){super(e,W.Pq.Zero(),n),this.alpha=t,this.beta=i,this.radius=r,this._cartesianCoordinates=W.Pq.Zero(),this.setMeshTarget(s)}setMeshTarget(e){this._meshTarget=e,this._follow()}_follow(){if(!this._meshTarget)return;this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);const e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}_checkInputs(){super._checkInputs(),this._follow()}getClassName(){return"ArcFollowCamera"}}(0,X.Y5)("BABYLON.FollowCamera",as),(0,X.Y5)("BABYLON.ArcFollowCamera",ls),function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(qr||(qr={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Yr||(Yr={}));class hs extends Cr{constructor(e,t,i,r=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new z.cP,this.onButtonUpObservable=new z.cP,this.onPadDownObservable=new z.cP,this.onPadUpObservable=new z.cP,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=Cr.XBOX,this._isXboxOnePad=r}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,0)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,1)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,2)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,3)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,9)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,8)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,4)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,5)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,10)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,11)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,12)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,13)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,14)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,15)}update(){super.update(),this._isXboxOnePad,this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}!function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(Kr||(Kr={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(jr||(jr={}));class cs extends Cr{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 z.cP,this.onButtonUpObservable=new z.cP,this.onPadDownObservable=new z.cP,this.onPadUpObservable=new z.cP,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=Cr.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&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonCross(){return this._buttonCross}set buttonCross(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,0)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,1)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,2)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,3)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,9)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,8)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,4)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,5)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,10)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,11)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,12)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,13)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,14)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,15)}update(){super.update(),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}class us{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new z.cP,(0,ii.BA)()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new z.cP((e=>{for(const t in this._babylonGamepads){const i=this._babylonGamepads[t];i&&i._isConnected&&this.onGamepadConnectedObservable.notifyObserver(e,i)}})),this._onGamepadConnectedEvent=e=>{const t=e.gamepad;if(t.index in this._babylonGamepads&&this._babylonGamepads[t.index].isConnected)return;let i;this._babylonGamepads[t.index]?(i=this._babylonGamepads[t.index],i.browserGamepad=t,i._isConnected=!0):i=this._addNewGamepad(t),this.onGamepadConnectedObservable.notifyObservers(i),this._startMonitoringGamepads()},this._onGamepadDisconnectedEvent=e=>{const t=e.gamepad;for(const e in this._babylonGamepads)if(this._babylonGamepads[e].index===t.index){const t=this._babylonGamepads[e];t._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(t),t.dispose&&t.dispose();break}},this._gamepadSupport)if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){const e=this._scene?this._scene.getEngine().getHostWindow():window;e&&(e.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),e.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}get gamepads(){return this._babylonGamepads}getGamepadByType(e=Cr.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){let t;this._oneGamepadConnected||(this._oneGamepadConnected=!0);const i=-1!==e.id.search("054c")&&-1===e.id.search("0ce6"),r=-1!==e.id.search("Xbox One");return t=r||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")||-1!==e.id.search("045e")&&-1===e.id.search("Surface Dock")?new hs(e.id,e.index,e,r):i?new cs(e.id,e.index,e):new yr(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{-1===this._loggedErrors.indexOf(t.index)&&(Ue.S0.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&Ot.$.QueueNewFrame((()=>{this._checkGamepadsStatus()}))}_updateGamepadObjects(){const e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new fs(e,W.Pq.Zero(),t)));class fs extends ts{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"}}rt._CreateDefaultParsedCamera=(e,t)=>new fs(e,W.Pq.Zero(),t),Ze.b.AddNodeConstructor("GamepadCamera",((e,t)=>()=>new ps(e,W.Pq.Zero(),t)));class ps extends fs{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}var _s=i(78239),ms=i(52660);class gs extends ms.w{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,r,s,n){super(e,"anaglyph",null,["leftSampler"],t,i[1],r,s,n),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("leftSampler",this._passedProcess)}))}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(i.bind(i,2153)))):t.push(Promise.resolve().then(i.bind(i,20692))),super._gatherImports(e,t)}}function vs(e){e._rigCameras[0]._rigPostProcess=new _s.v(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new gs(e.name+"_anaglyph",1,e._rigCameras)}(0,X.Y5)("BABYLON.AnaglyphPostProcess",gs),Ze.b.AddNodeConstructor("AnaglyphArcRotateCamera",((e,t,i)=>()=>new xs(e,0,0,1,W.Pq.Zero(),i.interaxial_distance,t)));class xs extends is{constructor(e,t,i,r,s,n,o){super(e,t,i,r,s,o),this._setRigMode=()=>vs(this),this.interaxialDistance=n,this.setCameraRigMode(rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}getClassName(){return"AnaglyphArcRotateCamera"}}Ze.b.AddNodeConstructor("AnaglyphFreeCamera",((e,t,i)=>()=>new bs(e,W.Pq.Zero(),i.interaxial_distance,t)));class bs extends es{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>vs(this),this.interaxialDistance=i,this.setCameraRigMode(rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}Ze.b.AddNodeConstructor("AnaglyphGamepadCamera",((e,t,i)=>()=>new Ss(e,W.Pq.Zero(),i.interaxial_distance,t)));class Ss extends ps{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>vs(this),this.interaxialDistance=i,this.setCameraRigMode(rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}Ze.b.AddNodeConstructor("AnaglyphUniversalCamera",((e,t,i)=>()=>new Ts(e,W.Pq.Zero(),i.interaxial_distance,t)));class Ts extends fs{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>vs(this),this.interaxialDistance=i,this.setCameraRigMode(rt.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}var Cs=i(69841);Cs.l.ShadersStore.stereoscopicInterlacePixelShader="const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=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);\n#else\n#ifdef IS_STEREOSCOPIC_INTERLACED\nfloat 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);\n#else\nuseCamB=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);\n#endif\n#endif\nif (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;}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);}\n";class ys extends ms.w{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,r,s,n,o){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],s,n,o,r?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new W.I9(1/this.width,1/this.height),this.onSizeChangedObservable.add((()=>{this._stepSize=new W.I9(1/this.width,1/this.height)})),this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)}))}}class Es extends ms.w{getClassName(){return"StereoscopicInterlacePostProcess"}constructor(e,t,i,r,s,n){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],r,s,n,i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new W.I9(1/this.width,1/this.height),this.onSizeChangedObservable.add((()=>{this._stepSize=new W.I9(1/this.width,1/this.height)})),this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)}))}}function Ps(e){const t=e.cameraRigMode===rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,i=e.cameraRigMode===rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;e.cameraRigMode===rt.RIG_MODE_STEREOSCOPIC_INTERLACED?(e._rigCameras[0]._rigPostProcess=new _s.v(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new ys(e.name+"_stereoInterlace",e._rigCameras,!1,!0)):(e._rigCameras[i?1:0].viewport=new et.L(0,0,t?.5:1,t?1:.5),e._rigCameras[i?0:1].viewport=new et.L(t?.5:0,t?0:.5,t?.5:1,t?1:.5))}Ze.b.AddNodeConstructor("StereoscopicArcRotateCamera",((e,t,i)=>()=>new As(e,0,0,1,W.Pq.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class As extends is{constructor(e,t,i,r,s,n,o,a){super(e,t,i,r,s,a),this._setRigMode=()=>Ps(this),this.interaxialDistance=n,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:rt.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}getClassName(){return"StereoscopicArcRotateCamera"}}Ze.b.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new Rs(e,W.Pq.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Rs extends es{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>Ps(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:rt.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}Ze.b.AddNodeConstructor("StereoscopicGamepadCamera",((e,t,i)=>()=>new Is(e,W.Pq.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Is extends ps{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>Ps(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:rt.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}Ze.b.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new Ms(e,W.Pq.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Ms extends fs{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>Ps(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:rt.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}class Os extends fs{set distanceBetweenEyes(e){this._distanceBetweenEyes=e}get distanceBetweenEyes(){return this._distanceBetweenEyes}set distanceToProjectionPlane(e){this._distanceToProjectionPlane=e}get distanceToProjectionPlane(){return this._distanceToProjectionPlane}constructor(e,t,i,r=1,s=.065){super(e,t,i),this._distanceBetweenEyes=s,this._distanceToProjectionPlane=r,this.setCameraRigMode(rt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL,{stereoHalfAngle:0}),this._cameraRigParams.stereoHalfAngle=0,this._cameraRigParams.interaxialDistance=s}getClassName(){return"StereoscopicUniversalCamera"}createRigCamera(e){const t=new Jr(e,W.Pq.Zero(),this.getScene()),i=new Pt("tm_"+e,this.getScene());return t.parent=i,i.setPivotMatrix(W.uq.Identity(),!1),t.isRigCamera=!0,t.rigParent=this,t}_updateRigCameras(){for(let e=0;e()=>new Ds(e,W.Pq.Zero(),t)));class Ds extends es{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class ws{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 e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return W.uq.Translation(e,0,0)}get rightHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return W.uq.Translation(-e,0,0)}get leftPreViewMatrix(){return W.uq.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return W.uq.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){const e=new ws;return e.hResolution=1280,e.vResolution=800,e.hScreenSize=.149759993,e.vScreenSize=.0935999975,e.vScreenCenter=.0467999987,e.eyeToScreenDistance=.0410000011,e.lensSeparationDistance=.063500002,e.interpupillaryDistance=.064000003,e.distortionK=[1,.219999999,.239999995,0],e.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],e.postProcessScaleFactor=1.714605507808412,e.lensCenterOffset=.151976421,e}}class Ns extends ms.w{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,r){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,r.postProcessScaleFactor,t,vi.g.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=r.distortionK,this._postProcessScaleFactor=r.postProcessScaleFactor,this._lensCenterOffset=r.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add((()=>{this._scaleIn=new W.I9(2,2/this.aspectRatio),this._scaleFactor=new W.I9(1/this._postProcessScaleFactor*.5,1/this._postProcessScaleFactor*.5*this.aspectRatio),this._lensCenter=new W.I9(this._isRightEye?.5-.5*this._lensCenterOffset:.5+.5*this._lensCenterOffset,.5)})),this.onApplyObservable.add((e=>{e.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),e.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),e.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),e.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])}))}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(i.bind(i,79132)))):t.push(Promise.resolve().then(i.bind(i,44341))),super._gatherImports(e,t)}}Cs.l.ShadersStore.vrMultiviewToSingleviewPixelShader="precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}";var Fs=i(7107),Ls=i(722);class Bs{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new Vs(e)}sampleFrame(e=ai.j.Now){if(this._enabled){if(null!=this._lastFrameTimeMs){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 0===e?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 Vs{constructor(e){this._samples=new Array(e),this.reset()}add(e){let t;if(this.isSaturated()){const e=this._samples[this._pos];t=e-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(e-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}}var ks=i(7240),Us=i(96281);Ls.ThinEngine.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode!==e){switch(e){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: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 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 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}t||(this.depthCullingState.depthMask=0===e),this._alphaMode=e}else if(!t){const t=0===e;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}};var Gs=i(44512);function zs(e,t,i,r){let s,n=1;1===r?s=new Float32Array(t*i*4):2===r?(s=new Uint16Array(t*i*4),n=15360):s=7===r?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let r=0;r{const i=f.width,n=o(e);if(n){if(a){const e=this._getWebGLTextureType(s);let t=this._getInternalFormat(r);const o=this._getRGBABufferInternalSizedFormat(s);let l=!1;t===d.RGB&&(t=d.RGBA,l=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,f,!0),this._unpackFlipY(!1);const h=a(n);for(let r=0;r>r;for(let i=0;i<6;i++){let a=h[r][i];l&&(a=zs(a,n,n,s)),d.texImage2D(i,r,o,n,n,0,t,e,a)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(f,n,r,s,u);f.isReady=!0,t?.removePendingData(f),f.onLoadedObservable.notifyObservers(f),f.onLoadedObservable.clear(),l&&l()}};return this._loadFile(e,(e=>{p(e)}),void 0,t?.offlineProvider,!0,((e,i)=>{t?.removePendingData(f),h&&e&&h(e.status+" "+e.statusText,i)})),f},Ls.ThinEngine.prototype.createRawTexture2DArray=Ws(!1),Ls.ThinEngine.prototype.createRawTexture3D=Ws(!0),Ls.ThinEngine.prototype.updateRawTexture2DArray=Hs(!1),Ls.ThinEngine.prototype.updateRawTexture3D=Hs(!0);var Xs=i(2636);Ls.ThinEngine.prototype._readTexturePixelsSync=function(e,t,i,r=-1,s=0,n=null,o=!0,a=!1,l=0,h=0){const c=this._gl;if(!c)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const e=c.createFramebuffer();if(!e)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}c.bindFramebuffer(c.FRAMEBUFFER,this._dummyFramebuffer),r>-1?c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_CUBE_MAP_POSITIVE_X+r,e._hardwareTexture?.underlyingResource,s):c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,e._hardwareTexture?.underlyingResource,s);let u=void 0!==e.type?this._getWebGLTextureType(e.type):c.UNSIGNED_BYTE;return a?n||(n=(0,Xs.kZ)(e.type,4*t*i)):u===c.UNSIGNED_BYTE?(n||(n=new Uint8Array(4*t*i)),u=c.UNSIGNED_BYTE):(n||(n=new Float32Array(4*t*i)),u=c.FLOAT),o&&this.flushFramebuffer(),c.readPixels(l,h,t,i,c.RGBA,u,n),c.bindFramebuffer(c.FRAMEBUFFER,this._currentFramebuffer),n},Ls.ThinEngine.prototype._readTexturePixels=function(e,t,i,r=-1,s=0,n=null,o=!0,a=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,r,s,n,o,a,l,h))},Ls.ThinEngine.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let r;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),r=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,r,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},Ls.ThinEngine.prototype.updateDynamicVertexBuffer=function(e,t,i,r){this.bindArrayBuffer(e),void 0===i&&(i=0);const s=t.byteLength||t.length;void 0===r||r>=s&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+r)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,r):new Uint8Array(t.buffer,t.byteOffset+i,r),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()},Ls.ThinEngine.prototype._createDepthStencilCubeTexture=function(e,t){const i=new Fs.h(this,12);if(i.isCube=!0,1===this.webGLVersion)return Z.V.Error("Depth cube texture is not supported by WebGL 1."),i;const r={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t},s=this._gl;this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,i,!0),this._setupDepthStencilTexture(i,e,r.bilinearFiltering,r.comparisonFunction);for(let t=0;t<6;t++)r.generateStencil?s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,s.DEPTH24_STENCIL8,e,e,0,s.DEPTH_STENCIL,s.UNSIGNED_INT_24_8,null):s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,s.DEPTH_COMPONENT24,e,e,0,s.DEPTH_COMPONENT,s.UNSIGNED_INT,null);return this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(i),i},Ls.ThinEngine.prototype._setCubeMapTextureParams=function(e,t,i){const r=this._gl;r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,t?r.LINEAR_MIPMAP_LINEAR:r.LINEAR),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),e.samplingMode=t?3:2,t&&this.getCaps().textureMaxLevel&&void 0!==i&&i>0&&(r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAX_LEVEL,i),e._maxLodLevel=i),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null)},Ls.ThinEngine.prototype.createCubeTexture=function(e,t,i,r,s=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d,f=!1,p=null){const _=this._gl;return this.createCubeTextureBase(e,t,i,!!r,s,n,o,a,l,h,c,u,(e=>this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,e,!0)),((e,t)=>{const i=this.needPOTTextures?(0,Gs.R)(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,n=i,a=[_.TEXTURE_CUBE_MAP_POSITIVE_X,_.TEXTURE_CUBE_MAP_POSITIVE_Y,_.TEXTURE_CUBE_MAP_POSITIVE_Z,_.TEXTURE_CUBE_MAP_NEGATIVE_X,_.TEXTURE_CUBE_MAP_NEGATIVE_Y,_.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(!1);const l=o?this._getInternalFormat(o,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:_.RGBA;let h=o?this._getInternalFormat(o):_.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(h=l);for(let e=0;e0}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(){return this._textures?.[0]??null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}getBaseArrayLayer(e){if(!this._textures)return-1;const t=this._textures[e],i=this._layerIndices?.[e]??0,r=this._faceIndices?.[e]??0;return t.isCube?6*i+r:t.is3D?0:i}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;const r=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,r}constructor(e,t,i,r,s){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=r,this._depthStencilTexture=null,this.label=s}setTextures(e){Array.isArray(e)?this._textures=e:this._textures=e?[e]: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=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==i&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,n){return this._depthStencilTexture?.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=n,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:r,depthTextureFormat:s,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(){let e=null;if(this._isMulti){const t=this.textures;if(t&&t.length>0){let i=!1,r=t.length,s=-1;const n=t[t.length-1]._source;14!==n&&12!==n||(i=!0,s=t[t.length-1].format,r--);const o=[],a=[],l=[],h=[],c=[],u=[],d=[],f={};for(let e=0;e1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){if(this._textures)for(let e=0;e1){const s=this._context,n=s["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=i??this.layerIndices?.[t]??0,s.framebufferTextureLayer(s.FRAMEBUFFER,n,e._hardwareTexture.underlyingResource,r,i)):e.isCube?(i=i??this.faceIndices?.[t]??0,s.framebufferTexture2D(s.FRAMEBUFFER,n,s.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,r)):s.framebufferTexture2D(s.FRAMEBUFFER,n,s.TEXTURE_2D,e._hardwareTexture.underlyingResource,r)}else{const s=this._context,n=s["COLOR_ATTACHMENT"+t+"_WEBGL"],o=void 0!==i?s.TEXTURE_CUBE_MAP_POSITIVE_X+i:s.TEXTURE_2D;s.framebufferTexture2D(s.FRAMEBUFFER,n,o,e._hardwareTexture.underlyingResource,r)}n._bindUnboundFramebuffer(o)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const i=this._attachments?.length??this.textures.length;for(let e=0;e1){const e=r._hardwareTexture.getMSAARenderBuffer(0);i._MSAAFramebuffer=f.createFramebuffer(),this._bindUnboundFramebuffer(i._MSAAFramebuffer),f.framebufferRenderbuffer(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.RENDERBUFFER,e),this._bindUnboundFramebuffer(null)}}else this.updateRenderTargetTextureSampleCount(i,l);return i},Ls.ThinEngine.prototype._createDepthStencilTexture=function(e,t,i){const r=this._gl,s=e.layers||0,n=e.depth||0;let o=r.TEXTURE_2D;0!==s?o=r.TEXTURE_2D_ARRAY:0!==n&&(o=r.TEXTURE_3D);const a=new Fs.h(this,12);if(a.label=t.label,!this._caps.depthTextureExtension)return Z.V.Error("Depth texture is not supported by your browser or hardware."),a;const l={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t};if(this._bindTextureDirectly(o,a,!0),this._setupDepthStencilTexture(a,e,0!==l.comparisonFunction&&l.bilinearFiltering,l.comparisonFunction,l.samples),void 0!==l.depthTextureFormat){if(15!==l.depthTextureFormat&&16!==l.depthTextureFormat&&17!==l.depthTextureFormat&&13!==l.depthTextureFormat&&14!==l.depthTextureFormat&&18!==l.depthTextureFormat)return Z.V.Error(`Depth texture ${l.depthTextureFormat} format is not supported.`),a;a.format=l.depthTextureFormat}else a.format=l.generateStencil?13:16;const h=17===a.format||13===a.format||18===a.format;let c=r.UNSIGNED_INT;15===a.format?c=r.UNSIGNED_SHORT:17===a.format||13===a.format?c=r.UNSIGNED_INT_24_8:14===a.format?c=r.FLOAT:18===a.format&&(c=r.FLOAT_32_UNSIGNED_INT_24_8_REV);const u=h?r.DEPTH_STENCIL:r.DEPTH_COMPONENT,d=this._getInternalFormatFromDepthTextureFormat(a.format,!0,h);return a.is2DArray?r.texImage3D(o,0,d,a.width,a.height,s,0,u,c,null):a.is3D?r.texImage3D(o,0,d,a.width,a.height,n,0,u,c,null):r.texImage2D(o,0,d,a.width,a.height,0,u,c,null),this._bindTextureDirectly(o,null),this._internalTexturesCache.push(a),i._depthStencilBuffer&&(r.deleteRenderbuffer(i._depthStencilBuffer),i._depthStencilBuffer=null),this._bindUnboundFramebuffer(i._MSAAFramebuffer??i._framebuffer),i._generateStencilBuffer=h,i._depthStencilTextureWithStencil=h,i._depthStencilBuffer=this._setupFramebufferDepthAttachments(i._generateStencilBuffer,i._generateDepthBuffer,i.width,i.height,i.samples,a.format),this._bindUnboundFramebuffer(null),a},Ls.ThinEngine.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e)return 1;if(e.samples===t)return t;const i=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null);const r=e.texture?._hardwareTexture;if(r?.releaseMSAARenderBuffers(),e.texture&&t>1&&"function"==typeof i.renderbufferStorageMultisample){const s=i.createFramebuffer();if(!s)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=s,this._bindUnboundFramebuffer(e._MSAAFramebuffer);const n=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBABufferInternalSizedFormat(e.texture.type,e.texture.format,e.texture._useSRGBBuffer),i.COLOR_ATTACHMENT0,!1);if(!n)throw new Error("Unable to create multi sampled framebuffer");r?.addMSAARenderBuffer(n)}this._bindUnboundFramebuffer(e._MSAAFramebuffer??e._framebuffer),e.texture&&(e.texture.samples=t),e._samples=t;const s=e._depthStencilTexture?e._depthStencilTexture.format:void 0;return e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.width,e.height,t,s),this._bindUnboundFramebuffer(null),t},Ls.ThinEngine.prototype._setupDepthStencilTexture=function(e,t,i,r,s=1){const n=t.width??t,o=t.height??t,a=t.layers||0,l=t.depth||0;e.baseWidth=n,e.baseHeight=o,e.width=n,e.height=o,e.is2DArray=a>0,e.depth=a||l,e.isReady=!0,e.samples=s,e.generateMipMaps=!1,e.samplingMode=i?2:1,e.type=0,e._comparisonFunction=r;const h=this._gl,c=this._getTextureTarget(e),u=this._getSamplingParameters(e.samplingMode,!1);h.texParameteri(c,h.TEXTURE_MAG_FILTER,u.mag),h.texParameteri(c,h.TEXTURE_MIN_FILTER,u.min),h.texParameteri(c,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(c,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===r?(h.texParameteri(c,h.TEXTURE_COMPARE_FUNC,515),h.texParameteri(c,h.TEXTURE_COMPARE_MODE,h.NONE)):(h.texParameteri(c,h.TEXTURE_COMPARE_FUNC,r),h.texParameteri(c,h.TEXTURE_COMPARE_MODE,h.COMPARE_REF_TO_TEXTURE)))},Ls.ThinEngine.prototype.setDepthStencilTexture=function(e,t,i,r){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,r):this._setTexture(e,null,void 0,void 0,r))},Ls.ThinEngine.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),r={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};r.generateStencilBuffer=r.generateDepthBuffer&&r.generateStencilBuffer,(1!==r.type||this._caps.textureFloatLinearFiltering)&&(2!==r.type||this._caps.textureHalfFloatLinearFiltering)||(r.samplingMode=1);const s=this._gl,n=new Fs.h(this,5);this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,n,!0);const o=this._getSamplingParameters(r.samplingMode,r.generateMipMaps);1!==r.type||this._caps.textureFloat||(r.type=0,Z.V.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,o.mag),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,o.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 t=0;t<6;t++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(r.type,r.format),e,e,0,this._getInternalFormat(r.format),this._getWebGLTextureType(r.type),null);const a=s.createFramebuffer();return this._bindUnboundFramebuffer(a),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(r.generateStencilBuffer,r.generateDepthBuffer,e,e),r.generateMipMaps&&s.generateMipmap(s.TEXTURE_CUBE_MAP),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=a,i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=r.generateStencilBuffer,n.width=e,n.height=e,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=r.generateMipMaps,n.samplingMode=r.samplingMode,n.type=r.type,n.format=r.format,this._internalTexturesCache.push(n),i.setTextures(n),i};var Ks=i(13798),js=i(23199);function $s(e,t,i){e._onCanvasFocus=()=>{e.onCanvasFocusObservable.notifyObservers(e)},e._onCanvasBlur=()=>{e.onCanvasBlurObservable.notifyObservers(e)},e._onCanvasContextMenu=t=>{e.disableContextMenu&&t.preventDefault()},t.addEventListener("focus",e._onCanvasFocus),t.addEventListener("blur",e._onCanvasBlur),t.addEventListener("contextmenu",e._onCanvasContextMenu),e._onBlur=()=>{e.disablePerformanceMonitorInBackground&&e.performanceMonitor.disable(),e._windowIsBackground=!0},e._onFocus=()=>{e.disablePerformanceMonitorInBackground&&e.performanceMonitor.enable(),e._windowIsBackground=!1},e._onCanvasPointerOut=i=>{document.elementFromPoint(i.clientX,i.clientY)!==t&&e.onCanvasPointerOutObservable.notifyObservers(i)};const r=e.getHostWindow();r&&"function"==typeof r.addEventListener&&(r.addEventListener("blur",e._onBlur),r.addEventListener("focus",e._onFocus)),t.addEventListener("pointerout",e._onCanvasPointerOut),i.doNotHandleTouchAction||function(e){e&&e.setAttribute&&(e.setAttribute("touch-action","none"),e.style.touchAction="none",e.style.webkitTapHighlightColor="transparent")}(t),!Ot.$.audioEngine&&i.audioEngine&&Ot.$.AudioEngineFactory&&(Ot.$.audioEngine=Ot.$.AudioEngineFactory(e.getRenderingCanvas(),e.getAudioContext(),e.getAudioDestination())),(0,ii.Nf)()&&(e._onFullscreenChange=()=>{e.isFullscreen=!!document.fullscreenElement,e.isFullscreen&&e._pointerLockRequested&&t&&sn(t)},document.addEventListener("fullscreenchange",e._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",e._onFullscreenChange,!1),e._onPointerLockChange=()=>{e.isPointerLock=document.pointerLockElement===t},document.addEventListener("pointerlockchange",e._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",e._onPointerLockChange,!1)),e.enableOfflineSupport=void 0!==Ot.$.OfflineProviderFactory,e._deterministicLockstep=!!i.deterministicLockstep,e._lockstepMaxSteps=i.lockstepMaxSteps||0,e._timeStep=i.timeStep||1/60}function Qs(e,t){1===he.q.Instances.length&&Ot.$.audioEngine&&(Ot.$.audioEngine.dispose(),Ot.$.audioEngine=null);const i=e.getHostWindow();i&&"function"==typeof i.removeEventListener&&(i.removeEventListener("blur",e._onBlur),i.removeEventListener("focus",e._onFocus)),t&&(t.removeEventListener("focus",e._onCanvasFocus),t.removeEventListener("blur",e._onCanvasBlur),t.removeEventListener("pointerout",e._onCanvasPointerOut),t.removeEventListener("contextmenu",e._onCanvasContextMenu)),(0,ii.Nf)()&&(document.removeEventListener("fullscreenchange",e._onFullscreenChange),document.removeEventListener("mozfullscreenchange",e._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",e._onFullscreenChange),document.removeEventListener("msfullscreenchange",e._onFullscreenChange),document.removeEventListener("pointerlockchange",e._onPointerLockChange),document.removeEventListener("mspointerlockchange",e._onPointerLockChange),document.removeEventListener("mozpointerlockchange",e._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",e._onPointerLockChange))}function Zs(e){const t=document.createElement("span");t.textContent="Hg",t.style.font=e;const i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";const r=document.createElement("div");r.style.whiteSpace="nowrap",r.appendChild(t),r.appendChild(i),document.body.appendChild(r);let s=0,n=0;try{n=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",s=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(r)}return{ascent:s,height:n,descent:n-s}}function Js(e,t,i){return new Promise(((r,s)=>{const n=new Image;n.onload=()=>{n.decode().then((()=>{e.createImageBitmap(n,i).then((e=>{r(e)}))}))},n.onerror=()=>{s(`Error loading image ${n.src}`)},n.src=t}))}function en(e,t,i,r){const s=e.createCanvas(i,r).getContext("2d");if(!s)throw new Error("Unable to get 2d context for resizeImageBitmap");return s.drawImage(t,0,0),s.getImageData(0,0,i,r).data}function tn(e){const t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}function rn(){const e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}function sn(e){if(e.requestPointerLock){const t=e.requestPointerLock();t instanceof Promise?t.then((()=>{e.focus()})).catch((()=>{})):e.focus()}}function nn(){document.exitPointerLock&&document.exitPointerLock()}Ls.ThinEngine.prototype.createPrefilteredCubeTexture=function(e,t,r,s,n=null,o=null,a,l=null,h=!0){return this.createCubeTexture(e,t,null,!1,(async e=>{if(!e)return void(n&&n(null));const o=e.texture;if(h?e.info.sphericalPolynomial&&(o._sphericalPolynomial=e.info.sphericalPolynomial):o._sphericalPolynomial=new Ks.Q,o._source=9,this.getCaps().textureLOD)return void(n&&n(o));const a=this._gl,l=e.width;if(!l)return;const{DDSTools:c}=await Promise.resolve().then(i.bind(i,26589)),u=[];for(let i=0;i<3;i++){const n=1-i/2,h=s,d=Math.log2(l)*r+s,f=h+(d-h)*n,p=Math.round(Math.min(Math.max(f,0),d)),_=new Fs.h(this,2);if(_.type=o.type,_.format=o.format,_.width=Math.pow(2,Math.max(Math.log2(l)-p,0)),_.height=_.width,_.isCube=!0,_._cachedWrapU=0,_._cachedWrapV=0,this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,_,!0),_.samplingMode=2,a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),e.isDDS){const t=e.info,i=e.data;this._unpackFlipY(t.isCompressed),c.UploadDDSLevels(this,_,i,t,!0,6,p)}else Z.V.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null);const m=new js.t(t);m._isCube=!0,m._texture=_,_.isReady=!0,u.push(m)}o._lodTextureHigh=u[2],o._lodTextureMid=u[1],o._lodTextureLow=u[0],n&&n(o)}),o,a,l,h,r,s)},Ls.ThinEngine.prototype.createUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create uniform buffer");const r=new ks.A(i);return this.bindUniformBuffer(r),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),r.references=1,r},Ls.ThinEngine.prototype.createDynamicUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create dynamic uniform buffer");const r=new ks.A(i);return this.bindUniformBuffer(r),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),r.references=1,r},Ls.ThinEngine.prototype.updateUniformBuffer=function(e,t,i,r){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===r?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+r)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+r)),this.bindUniformBuffer(null)},Ls.ThinEngine.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},Ls.ThinEngine.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},Ls.ThinEngine.prototype.bindUniformBlock=function(e,t,i){const r=e.program,s=this._gl.getUniformBlockIndex(r,t);4294967295!==s&&this._gl.uniformBlockBinding(r,s,i)},Ot.$.prototype.displayLoadingUI=function(){if(!(0,ii.BA)())return;const e=this.loadingScreen;e&&e.displayLoadingUI()},Ot.$.prototype.hideLoadingUI=function(){if(!(0,ii.BA)())return;const e=this._loadingScreen;e&&e.hideLoadingUI()},Object.defineProperty(Ot.$.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=Ot.$.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(e){this._loadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(Ot.$.prototype,"loadingUIText",{set:function(e){this.loadingScreen.loadingUIText=e},enumerable:!0,configurable:!0}),Object.defineProperty(Ot.$.prototype,"loadingUIBackgroundColor",{set:function(e){this.loadingScreen.loadingUIBackgroundColor=e},enumerable:!0,configurable:!0}),Ot.$.prototype.getInputElement=function(){return this._renderingCanvas},Ot.$.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null},Ot.$.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null},Ot.$.prototype.getAspectRatio=function(e,t=!1){const i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)},Ot.$.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)},Ot.$.prototype._verifyPointerLock=function(){this._onPointerLockChange?.()},Ot.$.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){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)}this._alphaEquation=e}},Ot.$.prototype.getInputElement=function(){return this._renderingCanvas},Ot.$.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc},Ot.$.prototype.setDepthFunction=function(e){this._depthCullingState.depthFunc=e},Ot.$.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(516)},Ot.$.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(518)},Ot.$.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(513)},Ot.$.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(515)},Ot.$.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask},Ot.$.prototype.setDepthWrite=function(e){this._depthCullingState.depthMask=e},Ot.$.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest},Ot.$.prototype.setStencilBuffer=function(e){this._stencilState.stencilTest=e},Ot.$.prototype.getStencilMask=function(){return this._stencilState.stencilMask},Ot.$.prototype.setStencilMask=function(e){this._stencilState.stencilMask=e},Ot.$.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc},Ot.$.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef},Ot.$.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask},Ot.$.prototype.setStencilFunction=function(e){this._stencilState.stencilFunc=e},Ot.$.prototype.setStencilFunctionReference=function(e){this._stencilState.stencilFuncRef=e},Ot.$.prototype.setStencilFunctionMask=function(e){this._stencilState.stencilFuncMask=e},Ot.$.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail},Ot.$.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail},Ot.$.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass},Ot.$.prototype.setStencilOperationFail=function(e){this._stencilState.stencilOpStencilFail=e},Ot.$.prototype.setStencilOperationDepthFail=function(e){this._stencilState.stencilOpDepthFail=e},Ot.$.prototype.setStencilOperationPass=function(e){this._stencilState.stencilOpStencilDepthPass=e},Ot.$.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()},Ot.$.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)},Ot.$.prototype.setAlphaConstants=function(e,t,i,r){this._alphaState.setAlphaBlendConstants(e,t,i,r)},Ot.$.prototype.getAlphaMode=function(){return this._alphaMode},Ot.$.prototype.getAlphaEquation=function(){return this._alphaEquation},Ot.$.prototype.getRenderPassNames=function(){return this._renderPassNames},Ot.$.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]},Ot.$.prototype.createRenderPassId=function(e){const t=++Ot.$._RenderPassIdCounter;return this._renderPassNames[t]=e??"NONAME",t},Ot.$.prototype.releaseRenderPassId=function(e){this._renderPassNames[e]=void 0;for(let t=0;t{this._loadFile(e,(e=>{r(e)}),void 0,t,i,((e,t)=>{s(t)}))}))}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}getFontOffset(e){return Zs(e)}_cancelFrame(){if(this.customAnimationFrameRequester){if(0!==this._frameHandler){this._frameHandler=0;const{cancelAnimationFrame:e}=this.customAnimationFrameRequester;e&&e(this.customAnimationFrameRequester.requestID)}}else super._cancelFrame()}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&0===this._frameHandler&&(this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}enterPointerlock(){this._renderingCanvas&&sn(this._renderingCanvas)}exitPointerlock(){nn()}beginFrame(){this._measureFps(),super.beginFrame()}_deletePipelineContext(e){const t=e;t&&t.program&&t.transformFeedback&&(this.deleteTransformFeedback(t.transformFeedback),t.transformFeedback=null),super._deletePipelineContext(e)}createShaderProgram(e,t,i,r,s,n=null){s=s||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);const o=super.createShaderProgram(e,t,i,r,s,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),o}_createShaderProgram(e,t,i,r,s=null){const n=r.createProgram();if(e.program=n,!n)throw new Error("Unable to create program");if(r.attachShader(n,t),r.attachShader(n,i),this.webGLVersion>1&&s){const t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(n,s),e.transformFeedback=t}return r.linkProgram(n),this.webGLVersion>1&&s&&this.bindTransformFeedback(null),e.context=r,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((t=>{t._outputTexture===e&&(t._outputTexture=null)})),t.cameras.forEach((t=>{t._postProcesses.forEach((t=>{t&&t._outputTexture===e&&(t._outputTexture=null)}))}))}))}_rescaleTexture(e,t,i,r,s){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);const n=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});if(!this._rescalePostProcess&&an._RescalePostProcessFactory&&(this._rescalePostProcess=an._RescalePostProcessFactory(this)),this._rescalePostProcess){this._rescalePostProcess.externalTextureSamplerBinding=!0;const o=()=>{this._rescalePostProcess.onApply=function(t){t._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,r,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),s&&s()},a=this._rescalePostProcess.getEffect();a?a.executeWhenCompiled(o):this._rescalePostProcess.onEffectCreatedObservable.addOnce((e=>{e.executeWhenCompiled(o)}))}}wrapWebGLTexture(e,t=!1,i=3,r=0,s=0){const n=new Us.d(e,this._gl),o=new Fs.h(this,0,!0);return o._hardwareTexture=n,o.baseWidth=r,o.baseHeight=s,o.width=r,o.height=s,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,r=0){const s=this._gl,n=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),a=this._getRGBABufferInternalSizedFormat(e.type,o),l=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=s.TEXTURE_2D;e.isCube&&(h=s.TEXTURE_CUBE_MAP_POSITIVE_X+i),s.texImage2D(h,r,a,o,n,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion)return void Z.V.Error("WebGL 1 does not support texture comparison.");const i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(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),0===t?(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 ks.A(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){const r=this._gl;return new Promise(((s,n)=>{const o=()=>{const a=r.clientWaitSync(e,t,0);a!=r.WAIT_FAILED?a!=r.TIMEOUT_EXPIRED?s():setTimeout(o,i):n()};o()}))}_readPixelsAsync(e,t,i,r,s,n,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const a=this._gl,l=a.createBuffer();a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.bufferData(a.PIXEL_PACK_BUFFER,o.byteLength,a.STREAM_READ),a.readPixels(e,t,i,r,s,n,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null);const h=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(a.flush(),this._clientWaitAsync(h,0,10).then((()=>(a.deleteSync(h),a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,o),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),a.deleteBuffer(l),o)))):null}dispose(){this.hideLoadingUI(),this._rescalePostProcess&&this._rescalePostProcess.dispose(),Qs(this,this._renderingCanvas),super.dispose()}}an.ALPHA_DISABLE=0,an.ALPHA_ADD=1,an.ALPHA_COMBINE=2,an.ALPHA_SUBTRACT=3,an.ALPHA_MULTIPLY=4,an.ALPHA_MAXIMIZED=5,an.ALPHA_ONEONE=6,an.ALPHA_PREMULTIPLIED=7,an.ALPHA_PREMULTIPLIED_PORTERDUFF=8,an.ALPHA_INTERPOLATE=9,an.ALPHA_SCREENMODE=10,an.DELAYLOADSTATE_NONE=0,an.DELAYLOADSTATE_LOADED=1,an.DELAYLOADSTATE_LOADING=2,an.DELAYLOADSTATE_NOTLOADED=4,an.NEVER=512,an.ALWAYS=519,an.LESS=513,an.EQUAL=514,an.LEQUAL=515,an.GREATER=516,an.GEQUAL=518,an.NOTEQUAL=517,an.KEEP=7680,an.REPLACE=7681,an.INCR=7682,an.DECR=7683,an.INVERT=5386,an.INCR_WRAP=34055,an.DECR_WRAP=34056,an.TEXTURE_CLAMP_ADDRESSMODE=0,an.TEXTURE_WRAP_ADDRESSMODE=1,an.TEXTURE_MIRROR_ADDRESSMODE=2,an.TEXTUREFORMAT_ALPHA=0,an.TEXTUREFORMAT_LUMINANCE=1,an.TEXTUREFORMAT_LUMINANCE_ALPHA=2,an.TEXTUREFORMAT_RGB=4,an.TEXTUREFORMAT_RGBA=5,an.TEXTUREFORMAT_RED=6,an.TEXTUREFORMAT_R=6,an.TEXTUREFORMAT_RG=7,an.TEXTUREFORMAT_RED_INTEGER=8,an.TEXTUREFORMAT_R_INTEGER=8,an.TEXTUREFORMAT_RG_INTEGER=9,an.TEXTUREFORMAT_RGB_INTEGER=10,an.TEXTUREFORMAT_RGBA_INTEGER=11,an.TEXTURETYPE_UNSIGNED_BYTE=0,an.TEXTURETYPE_UNSIGNED_INT=0,an.TEXTURETYPE_FLOAT=1,an.TEXTURETYPE_HALF_FLOAT=2,an.TEXTURETYPE_BYTE=3,an.TEXTURETYPE_SHORT=4,an.TEXTURETYPE_UNSIGNED_SHORT=5,an.TEXTURETYPE_INT=6,an.TEXTURETYPE_UNSIGNED_INTEGER=7,an.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,an.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,an.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,an.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,an.TEXTURETYPE_UNSIGNED_INT_24_8=12,an.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,an.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,an.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,an.TEXTURE_NEAREST_SAMPLINGMODE=1,an.TEXTURE_BILINEAR_SAMPLINGMODE=2,an.TEXTURE_TRILINEAR_SAMPLINGMODE=3,an.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,an.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,an.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,an.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,an.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,an.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,an.TEXTURE_NEAREST_LINEAR=7,an.TEXTURE_NEAREST_NEAREST=1,an.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,an.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,an.TEXTURE_LINEAR_LINEAR=2,an.TEXTURE_LINEAR_NEAREST=12,an.TEXTURE_EXPLICIT_MODE=0,an.TEXTURE_SPHERICAL_MODE=1,an.TEXTURE_PLANAR_MODE=2,an.TEXTURE_CUBIC_MODE=3,an.TEXTURE_PROJECTION_MODE=4,an.TEXTURE_SKYBOX_MODE=5,an.TEXTURE_INVCUBIC_MODE=6,an.TEXTURE_EQUIRECTANGULAR_MODE=7,an.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,an.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,an.SCALEMODE_FLOOR=1,an.SCALEMODE_NEAREST=2,an.SCALEMODE_CEILING=3;var ln=i(58059);class hn extends ln.${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}}function cn(e,t){const i=new Rt.D(e,void 0,!0,t);return i.addUniform("viewProjection",16),i.addUniform("viewProjectionR",16),i.addUniform("view",16),i.addUniform("projection",16),i.addUniform("vEyePosition",4),i}an.prototype.createMultiviewRenderTargetTexture=function(e,t,i,r){const s=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";const n=this._createHardwareRenderTargetWrapper(!1,!1,{width:e,height:t});n._framebuffer=s.createFramebuffer();const o=new Fs.h(this,0,!0);return o.width=e,o.height=t,o.isMultiview=!0,i||(i=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,i),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.RGBA8,e,t,2)),n._colorTextureArray=i,r||(r=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,r),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.DEPTH24_STENCIL8,e,t,2)),n._depthStencilTextureArray=r,o.isReady=!0,n.setTextures(o),n._depthStencilTexture=o,n},an.prototype.bindMultiviewFramebuffer=function(e){const t=e,i=this._gl,r=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw"Invalid multiview frame buffer";this.getCaps().oculusMultiview?(r.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,t.samples,0,2),r.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,t.samples,0,2)):(r.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),r.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,0,2))},an.prototype.bindSpaceWarpFramebuffer=function(e){const t=e,i=this._gl,r=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw new Error("Invalid Space Warp framebuffer");r.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),r.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_ATTACHMENT,t._depthStencilTextureArray,0,0,2)},rt.prototype._useMultiviewToSingleView=!1,rt.prototype._multiviewTexture=null,rt.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?this._multiviewTexture.getRenderWidth()==e&&this._multiviewTexture.getRenderHeight()==t||(this._multiviewTexture.dispose(),this._multiviewTexture=new hn(this.getScene(),{width:e,height:t})):this._multiviewTexture=new hn(this.getScene(),{width:e,height:t})};const un=oi.Z.prototype.createSceneUniformBuffer;oi.Z.prototype._transformMatrixR=W.uq.Zero(),oi.Z.prototype._multiviewSceneUbo=null,oi.Z.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=cn(this.getEngine(),"scene_multiview")},oi.Z.prototype.createSceneUniformBuffer=function(e){return this._multiviewSceneUbo?cn(this.getEngine(),e):un.bind(this)(e)},oi.Z.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,W.AA.Matrix[0]),tt.P.GetRightPlaneToRef(W.AA.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))},oi.Z.prototype._renderMultiviewToSingleView=function(e){e._resizeOrCreateMultiviewTexture(e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.width>0?e._rigPostProcess.width:this.getEngine().getRenderWidth(!0),e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.height>0?e._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),e.outputRenderTarget=e._multiviewTexture,this._renderForCamera(e),e.outputRenderTarget=null;for(let t=0;t{})),this.onApplyObservable.add((e=>{r._scene.activeCamera&&r._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",r._multiviewTexture)}))}}function fn(e,t){const i=t.vrCameraMetrics||ws.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new et.L(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new W.uq,e._rigCameras[0]._cameraRigParams.vrHMatrix=i.leftHMatrix,e._rigCameras[0]._cameraRigParams.vrPreViewMatrix=i.leftPreViewMatrix,e._rigCameras[0].getProjectionMatrix=e._rigCameras[0]._getVRProjectionMatrix,e._rigCameras[1]._cameraRigParams.vrMetrics=i,e._rigCameras[1].viewport=new et.L(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new W.uq,e._rigCameras[1]._cameraRigParams.vrHMatrix=i.rightHMatrix,e._rigCameras[1]._cameraRigParams.vrPreViewMatrix=i.rightPreViewMatrix,e._rigCameras[1].getProjectionMatrix=e._rigCameras[1]._getVRProjectionMatrix,i.multiviewEnabled&&(e.getScene().getEngine().getCaps().multiview?(e._useMultiviewToSingleView=!0,e._rigPostProcess=new dn("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(Z.V.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new Ns("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new Ns("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))}Ze.b.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",((e,t)=>()=>new pn(e,0,0,1,W.Pq.Zero(),t)));class pn extends is{constructor(e,t,i,r,s,n,o=!0,a=ws.GetDefault()){super(e,t,i,r,s,n),this._setRigMode=e=>fn(this,e),a.compensateDistortion=o,this.setCameraRigMode(rt.RIG_MODE_VR,{vrCameraMetrics:a}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}Ze.b.AddNodeConstructor("VRDeviceOrientationFreeCamera",((e,t)=>()=>new _n(e,W.Pq.Zero(),t)));class _n extends rs{constructor(e,t,i,r=!0,s=ws.GetDefault()){super(e,t,i),this._setRigMode=e=>fn(this,e),s.compensateDistortion=r,this.setCameraRigMode(rt.RIG_MODE_VR,{vrCameraMetrics:s})}getClassName(){return"VRDeviceOrientationFreeCamera"}}Ze.b.AddNodeConstructor("VRDeviceOrientationGamepadCamera",((e,t)=>()=>new mn(e,W.Pq.Zero(),t)));class mn extends _n{constructor(e,t,i,r=!0,s=ws.GetDefault()){super(e,t,i,r,s),this._setRigMode=e=>fn(this,e),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}var gn=i(69648);class vn{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,r,s){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&(-1!==t.prePassRenderer.getIndex(2)||-1!==t.prePassRenderer.getIndex(11))){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=r.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());const s=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==s.frameId&&(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=r.clone()}}}class xn{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)-1===this._keys.indexOf(e)&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;tthis._setDefaultValue(e)))}_setDefaultValue(e){const t=this._externalProperties?.[e]?.type??typeof this[e],i=this._externalProperties?.[e]?.default;switch(t){case"number":this[e]=i??0;break;case"string":this[e]=i??"";break;default:this[e]=i??!1}}toString(){let e="";for(let t=0;tthis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const i=this._mesh.getScene();for(let e=0;e0&&(r.computeBonesUsingShaders=!1)}}else{const t=this._defines[this._currentRank];if(t)for(let i=0;ithis._handlePluginEvent(e,t),this._plugins.push(e),this._plugins.sort(((e,t)=>e.priority-t.priority)),this._codeInjectionPoints={};const i={};i[En._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const e of this._plugins)e.collectDefines(i),this._collectPointNames("vertex",e.getCustomCode("vertex",this._material.shaderLanguage)),this._collectPointNames("fragment",e.getCustomCode("fragment",this._material.shaderLanguage));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){-1===this._activePlugins.indexOf(e)&&(this._activePlugins.push(e),this._activePlugins.sort(((e,t)=>e.priority-t.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(((e,t)=>e.priority-t.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&&e.uniforms.push(...this._uniformList),this._samplerList.length>0&&e.samplers.push(...this._samplerList),this._uboList.length>0&&e.uniformBuffersNames.push(...this._uboList),e.customCode=this._injectCustomCode(e,e.customCode);break}case 8:{const e=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];const i=1===this._material.shaderLanguage;for(const t of this._plugins){const r=t.getUniforms(this._material.shaderLanguage);if(r){if(r.ubo)for(const t of r.ubo){if(t.size&&t.type){const r=t.arraySize??0;if(e.ubo.addUniform(t.name,t.size,r),i){let e;switch(t.type){case"mat4":e="mat4x4f";break;case"float":e="f32";break;default:e=`${t.type}f`}this._uboDeclaration+=`uniform ${t.name}: ${e}${r>0?`[${r}]`:""};\n`}else this._uboDeclaration+=`${t.type} ${t.name}${r>0?`[${r}]`:""};\n`}this._uniformList.push(t.name)}r.vertex&&(this._vertexDeclaration+=r.vertex+"\n"),r.fragment&&(this._fragmentDeclaration+=r.fragment+"\n")}t.getSamplers(this._samplerList),t.getUniformBuffersNames(this._uboList)}break}}}_collectPointNames(e,t){if(t)for(const i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,r)=>{t&&(r=t(i,r)),this._uboDeclaration&&(r=r.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(r=r.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(r=r.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const s=this._codeInjectionPoints?.[i];if(!s)return r;let n=null;for(let t in s){let s="";for(const r of this._activePlugins){let o=r.getCustomCode(i,this._material.shaderLanguage)?.[t];if(o){if(r.resolveIncludes){if(null===n){const t=0;n={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:Cs.l.GetShadersRepository(t),includesShadersStore:Cs.l.GetIncludesShadersStore(t),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}n.isFragment="fragment"===i,(0,Cn.Iq)(o,n,(e=>o=e))}s+=o+"\n"}}if(s.length>0)if("!"===t.charAt(0)){t=t.substring(1);let e="g";if("!"===t.charAt(0))e="",t=t.substring(1);else{const i=yn.exec(t);i&&i.length>=2&&(e=i[1],t=t.substring(e.length+1))}e.indexOf("g")<0&&(e+="g");const i=r,n=new RegExp(t,e);let o=n.exec(i);for(;null!==o;){let e=s;for(let t=0;t{On()}));const Pn=[];let An=!1,Rn=null;function In(e,t){An||(Rn=Vt.OnEventObservable.add((e=>{for(const[,t]of Pn)t(e)}),1),An=!0);const i=Pn.filter((([t,i])=>t===e));i.length>0?i[0][1]=t:Pn.push([e,t])}function Mn(e){for(let t=0;t{e.pluginManager=void 0}))),this._pluginDefineNames=r,this._pluginManager=e.pluginManager,s&&this._pluginManager._addPlugin(this),n&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,r){return!0}hardBindForSubMesh(e,t,i,r){}bindForSubMesh(e,t,i,r){}dispose(e){}getCustomCode(e,t=0){return null}collectDefines(e){if(this._pluginDefineNames)for(const t of Object.keys(this._pluginDefineNames)){if("_"===t[0])continue;const i=typeof this._pluginDefineNames[t];e[t]={type:"number"===i?"number":"string"===i?"string":"boolean"===i?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(e=0){return{}}copyTo(e){it.p.Clone((()=>e),this)}serialize(){return it.p.Serialize(this)}parse(e,t,i){it.p.Parse((()=>this),e,t,i)}}(0,je.Cg)([(0,$e.lK)()],Dn.prototype,"name",void 0),(0,je.Cg)([(0,$e.lK)()],Dn.prototype,"priority",void 0),(0,je.Cg)([(0,$e.lK)()],Dn.prototype,"resolveIncludes",void 0),(0,je.Cg)([(0,$e.lK)()],Dn.prototype,"registerForExtraEvents",void 0),(0,X.Y5)("BABYLON.MaterialPluginBase",Dn);class wn extends xn{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class Nn extends Dn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"DetailMap",140,new wn,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=Vt.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&&Sn.DetailTextureEnabled&&!this._texture.isReady())}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;const i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&Sn.DetailTextureEnabled&&this._isEnabled?((0,Bt.YT)(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&&Sn.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),(0,Bt.mA)(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&Sn.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){e&&this._texture?.dispose()}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}(0,je.Cg)([(0,$e.uM)("detailTexture"),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Nn.prototype,"texture",void 0),(0,je.Cg)([(0,$e.lK)()],Nn.prototype,"diffuseBlendLevel",void 0),(0,je.Cg)([(0,$e.lK)()],Nn.prototype,"roughnessBlendLevel",void 0),(0,je.Cg)([(0,$e.lK)()],Nn.prototype,"bumpLevel",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Nn.prototype,"normalBlendMethod",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Nn.prototype,"isEnabled",void 0);var Fn,Ln=i(57551);!function(e){e[e.Zero=0]="Zero",e[e.One=1]="One",e[e.MaxViewZ=2]="MaxViewZ"}(Fn||(Fn={}));class Bn{static CreateConfiguration(e){return Bn._Configurations[e]={defines:{},previousWorldMatrices:{},previousViewProjection:W.uq.Zero(),currentViewProjection:W.uq.Zero(),previousBones:{},lastUpdateFrameId:-1,excludedSkinnedMesh:[]},Bn._Configurations[e]}static DeleteConfiguration(e){delete Bn._Configurations[e]}static GetConfiguration(e){return Bn._Configurations[e]}static AddUniformsAndSamplers(e,t){e.push("previousWorld","previousViewProjection","mPreviousBones")}static MarkAsDirty(e,t){for(const i of t)if(i.subMeshes)for(const t of i.subMeshes)t._removeDrawWrapper(e)}static PrepareDefines(e,t,i){if(!i._arePrePassDirty)return;const r=Bn._Configurations[e];if(!r)return;i.PREPASS=!0,i.PREPASS_COLOR=!1,i.PREPASS_COLOR_INDEX=-1;let s=0;for(let e=0;e{this._markAllSubMeshesAsImageProcessingDirty()}))))}get isPrePassCapable(){return!this.disableDepthWrite}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}get canRenderToMRT(){return!0}constructor(e,t,i=!1){super(e,t,void 0,i||Un.ForceGLSL),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 H.v9(0,0,0),this.diffuseColor=new H.v9(1,1,1),this.specularColor=new H.v9(1,1,1),this.emissiveColor=new H.v9(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._shadersLoaded=!1,this._renderTargets=new Qe.L(16),this._worldViewProjectionMatrix=W.uq.Zero(),this._globalAmbientColor=new H.v9(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new Nn(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new vn,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),Un.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),Un.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!!(Un.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||!!(Un.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled)}needAlphaTesting(){return!!this._forceAlphaTest||this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===Vt.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==Vt.MATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,r=!1){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===r)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new kn(this._eventInfo.defineNames));const n=this.getScene(),o=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const a=n.getEngine();o._needNormals=(0,Bt.az)(n,e,o,!0,this._maxSimultaneousLights,this._disableLighting),(0,Bt.VO)(n,o);const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if((0,Bt.N4)(n,o,this.canRenderToMRT&&!l),(0,Bt.Nc)(n,o,l),Bn.PrepareDefines(a.currentRenderPassId,e,o),o._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,o._needUVs=!1;for(let e=1;e<=6;++e)o["MAINUV"+e]=!1;if(n.texturesEnabled){if(o.DIFFUSEDIRECTUV=0,o.BUMPDIRECTUV=0,o.AMBIENTDIRECTUV=0,o.OPACITYDIRECTUV=0,o.EMISSIVEDIRECTUV=0,o.SPECULARDIRECTUV=0,o.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&Un.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;(0,Bt.YT)(this._diffuseTexture,o,"DIFFUSE")}else o.DIFFUSE=!1;if(this._ambientTexture&&Un.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;(0,Bt.YT)(this._ambientTexture,o,"AMBIENT")}else o.AMBIENT=!1;if(this._opacityTexture&&Un.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;(0,Bt.YT)(this._opacityTexture,o,"OPACITY"),o.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else o.OPACITY=!1;if(this._reflectionTexture&&Un.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(o._needNormals=!0,o.REFLECTION=!0,o.ROUGHNESS=this._roughness>0,o.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,o.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===vi.g.INVCUBIC_MODE,o.REFLECTIONMAP_3D=this._reflectionTexture.isCube,o.REFLECTIONMAP_OPPOSITEZ=o.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,o.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case vi.g.EXPLICIT_MODE:o.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case vi.g.PLANAR_MODE:o.setReflectionMode("REFLECTIONMAP_PLANAR");break;case vi.g.PROJECTION_MODE:o.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case vi.g.SKYBOX_MODE:o.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case vi.g.SPHERICAL_MODE:o.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case vi.g.EQUIRECTANGULAR_MODE:o.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case vi.g.FIXED_EQUIRECTANGULAR_MODE:o.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case vi.g.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:o.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case vi.g.CUBIC_MODE:case vi.g.INVCUBIC_MODE:default:o.setReflectionMode("REFLECTIONMAP_CUBIC")}o.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else o.REFLECTION=!1,o.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&Un.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;(0,Bt.YT)(this._emissiveTexture,o,"EMISSIVE")}else o.EMISSIVE=!1;if(this._lightmapTexture&&Un.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;(0,Bt.YT)(this._lightmapTexture,o,"LIGHTMAP"),o.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,o.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else o.LIGHTMAP=!1;if(this._specularTexture&&Un.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;(0,Bt.YT)(this._specularTexture,o,"SPECULAR"),o.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else o.SPECULAR=!1;if(n.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&Un.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;(0,Bt.YT)(this._bumpTexture,o,"BUMP"),o.PARALLAX=this._useParallax,o.PARALLAX_RHS=n.useRightHandedSystem,o.PARALLAXOCCLUSION=this._useParallaxOcclusion,o.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else o.BUMP=!1,o.PARALLAX=!1,o.PARALLAX_RHS=!1,o.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&Un.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;o._needUVs=!0,o.REFRACTION=!0,o.REFRACTIONMAP_3D=this._refractionTexture.isCube,o.RGBDREFRACTION=this._refractionTexture.isRGBD,o.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize}else o.REFRACTION=!1;o.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else o.DIFFUSE=!1,o.AMBIENT=!1,o.OPACITY=!1,o.REFLECTION=!1,o.EMISSIVE=!1,o.LIGHTMAP=!1,o.BUMP=!1,o.REFRACTION=!1;o.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),o.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,o.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,o.SPECULAROVERALPHA=this._useSpecularOverAlpha,o.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,o.ALPHATEST_AFTERALLALPHACOMPUTATIONS=null!==this.transparencyMode,o.ALPHABLEND=null===this.transparencyMode||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=o,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(o._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(o),o.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,o.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}o._areFresnelDirty&&(Un.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(o.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,o.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,o.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,o.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,o.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,o.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,o._needNormals=!0,o.FRESNEL=!0):o.FRESNEL=!1),(0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,o,this._applyDecalMapAfterDetailMap),(0,Bt.OR)(n,a,this,o,r,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=o,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),(0,Bt.qB)(e,o,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let h=!1;if(o.isDirty){const r=o._areLightsDisposed;o.markAsProcessed();const s=new Tn;o.REFLECTION&&s.addFallback(0,"REFLECTION"),o.SPECULAR&&s.addFallback(0,"SPECULAR"),o.BUMP&&s.addFallback(0,"BUMP"),o.PARALLAX&&s.addFallback(1,"PARALLAX"),o.PARALLAX_RHS&&s.addFallback(1,"PARALLAX_RHS"),o.PARALLAXOCCLUSION&&s.addFallback(0,"PARALLAXOCCLUSION"),o.SPECULAROVERALPHA&&s.addFallback(0,"SPECULAROVERALPHA"),o.FOG&&s.addFallback(1,"FOG"),o.POINTSIZE&&s.addFallback(0,"POINTSIZE"),o.LOGARITHMICDEPTH&&s.addFallback(0,"LOGARITHMICDEPTH"),(0,Bt.c4)(o,s,this._maxSimultaneousLights),o.SPECULARTERM&&s.addFallback(0,"SPECULARTERM"),o.DIFFUSEFRESNEL&&s.addFallback(1,"DIFFUSEFRESNEL"),o.OPACITYFRESNEL&&s.addFallback(2,"OPACITYFRESNEL"),o.REFLECTIONFRESNEL&&s.addFallback(3,"REFLECTIONFRESNEL"),o.EMISSIVEFRESNEL&&s.addFallback(4,"EMISSIVEFRESNEL"),o.FRESNEL&&s.addFallback(4,"FRESNEL"),o.MULTIVIEW&&s.addFallback(0,"MULTIVIEW");const l=[st.R.PositionKind];o.NORMAL&&l.push(st.R.NormalKind),o.TANGENT&&l.push(st.R.TangentKind);for(let e=1;e<=6;++e)o["UV"+e]&&l.push(`uv${1===e?"":e}`);o.VERTEXCOLOR&&l.push(st.R.ColorKind),(0,Bt.ni)(l,e,o,s),(0,Bt.ER)(l,o),(0,Bt.IF)(l,e,o),(0,Bt.J2)(l,e,o);let c="default";const u=["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"],d=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],f=["Material","Scene","Mesh"],p={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:o.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=s,this._eventInfo.fallbackRank=0,this._eventInfo.defines=o,this._eventInfo.uniforms=u,this._eventInfo.attributes=l,this._eventInfo.samplers=d,this._eventInfo.uniformBuffersNames=f,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=p,this._callbackPluginEventGeneric(128,this._eventInfo),Bn.AddUniformsAndSamplers(u,d),vn.AddUniforms(u),vn.AddSamplers(d),gn.p&&(gn.p.PrepareUniforms(u,o),gn.p.PrepareSamplers(d,o)),(0,Bt.Bb)({uniformsNames:u,uniformBuffersNames:f,samplers:d,defines:o,maxSimultaneousLights:this._maxSimultaneousLights}),(0,Ln.TV)(u);const _={};this.customShaderNameResolve&&(c=this.customShaderNameResolve(c,u,f,d,o,l,_));const m=o.toString(),g=t.effect;let v=n.getEngine().createEffect(c,{attributes:l,uniformsNames:u,uniformBuffersNames:f,samplers:d,defines:m,fallbacks:s,onCompiled:this.onCompiled,onError:this.onError,indexParameters:p,processFinalCode:_.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:o.PREPASS,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,22177)),Promise.resolve().then(i.bind(i,49694))]):await Promise.all([Promise.resolve().then(i.bind(i,35936)),Promise.resolve().then(i.bind(i,85800))]),this._shadersLoaded=!0}},a);if(this._eventInfo.customCode=void 0,v)if(this._onEffectCreatedObservable&&(Vn.effect=v,Vn.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Vn)),this.allowShaderHotSwapping&&g&&!v.isReady()){if(v=g,o.markAsUnprocessed(),h=this.isFrozen,r)return o._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(v,o,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(o._renderId=n.getRenderId(),s._wasPreviouslyReady=!h,s._wasPreviouslyUsingInstances=r,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){const r=this.getScene(),s=i.materialDefines;if(!s)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,r,t,e,this.isFrozen),Bn.Bind(r.getEngine().currentRenderPassId,this._activeEffect,t,e),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),s.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=this._mustRebind(r,n,i,t.visibility);(0,Bt.f$)(t,n);const a=this._uniformBuffer;if(o){if(this.bindViewProjection(n),!a.useUbo||!this.isFrozen||!a.isSync||i._drawWrapper._forceRebindOnNextCall){if(Un.FresnelEnabled&&s.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(a.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),a.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&a.updateColor4("opacityParts",new H.v9(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(a.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),a.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(a.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),a.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(a.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),a.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),r.texturesEnabled){if(this._diffuseTexture&&Un.DiffuseTextureEnabled&&(a.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),(0,Bt.mA)(this._diffuseTexture,a,"diffuse")),this._ambientTexture&&Un.AmbientTextureEnabled&&(a.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),(0,Bt.mA)(this._ambientTexture,a,"ambient")),this._opacityTexture&&Un.OpacityTextureEnabled&&(a.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),(0,Bt.mA)(this._opacityTexture,a,"opacity")),this._hasAlphaChannel()&&a.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&Un.ReflectionTextureEnabled&&(a.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),a.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const e=this._reflectionTexture;a.updateVector3("vReflectionPosition",e.boundingBoxPosition),a.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this._emissiveTexture&&Un.EmissiveTextureEnabled&&(a.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),(0,Bt.mA)(this._emissiveTexture,a,"emissive")),this._lightmapTexture&&Un.LightmapTextureEnabled&&(a.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),(0,Bt.mA)(this._lightmapTexture,a,"lightmap")),this._specularTexture&&Un.SpecularTextureEnabled&&(a.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),(0,Bt.mA)(this._specularTexture,a,"specular")),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&Un.BumpTextureEnabled&&(a.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),(0,Bt.mA)(this._bumpTexture,a,"bump"),r._mirroredCameraPosition?a.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):a.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&Un.RefractionTextureEnabled){let e=1;if(this._refractionTexture.isCube||(a.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(e=this._refractionTexture.depth)),a.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,e,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const e=this._refractionTexture;a.updateVector3("vRefractionPosition",e.boundingBoxPosition),a.updateVector3("vRefractionSize",e.boundingBoxSize)}}}this.pointsCloud&&a.updateFloat("pointSize",this.pointSize),a.updateColor4("vSpecularColor",this.specularColor,this.specularPower),a.updateColor3("vEmissiveColor",Un.EmissiveTextureEnabled?this.emissiveColor:H.v9.BlackReadOnly),a.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),r.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),a.updateColor3("vAmbientColor",this._globalAmbientColor)}r.texturesEnabled&&(this._diffuseTexture&&Un.DiffuseTextureEnabled&&n.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&Un.AmbientTextureEnabled&&n.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&Un.OpacityTextureEnabled&&n.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&Un.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?n.setTexture("reflectionCubeSampler",this._reflectionTexture):n.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&Un.EmissiveTextureEnabled&&n.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&Un.LightmapTextureEnabled&&n.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&Un.SpecularTextureEnabled&&n.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&Un.BumpTextureEnabled&&n.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&Un.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),(0,Ln.gS)(n,this,r),this.bindEyePosition(n)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!o&&this.isFrozen||(r.lightsEnabled&&!this._disableLighting&&(0,Bt.RL)(r,t,n,s,this._maxSimultaneousLights),(r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||s.PREPASS)&&this.bindView(n),(0,Bt.Yy)(r,t,n),s.NUM_MORPH_INFLUENCERS&&(0,Bt.nR)(t,n),s.BAKED_VERTEX_ANIMATION_TEXTURE&&t.bakedVertexAnimationManager?.bind(n,s.INSTANCES),this.useLogarithmicDepth&&(0,Bt.DL)(s,n,r),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),a.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){t&&(this._diffuseTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._specularTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._refractionTexture?.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const r=it.p.Clone((()=>new Un(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return r.name=e,r.id=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}static Parse(e,t,i){const r=it.p.Parse((()=>new Un(e.name,t)),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),Vt._ParsePlugins(e,r,t,i),r}static get DiffuseTextureEnabled(){return Sn.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){Sn.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return Sn.DetailTextureEnabled}static set DetailTextureEnabled(e){Sn.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return Sn.AmbientTextureEnabled}static set AmbientTextureEnabled(e){Sn.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return Sn.OpacityTextureEnabled}static set OpacityTextureEnabled(e){Sn.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return Sn.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){Sn.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return Sn.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){Sn.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return Sn.SpecularTextureEnabled}static set SpecularTextureEnabled(e){Sn.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return Sn.BumpTextureEnabled}static set BumpTextureEnabled(e){Sn.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return Sn.LightmapTextureEnabled}static set LightmapTextureEnabled(e){Sn.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return Sn.RefractionTextureEnabled}static set RefractionTextureEnabled(e){Sn.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return Sn.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){Sn.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return Sn.FresnelEnabled}static set FresnelEnabled(e){Sn.FresnelEnabled=e}}Un.ForceGLSL=!1,(0,je.Cg)([(0,$e.uM)("diffuseTexture")],Un.prototype,"_diffuseTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesAndMiscDirty")],Un.prototype,"diffuseTexture",void 0),(0,je.Cg)([(0,$e.uM)("ambientTexture")],Un.prototype,"_ambientTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"ambientTexture",void 0),(0,je.Cg)([(0,$e.uM)("opacityTexture")],Un.prototype,"_opacityTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesAndMiscDirty")],Un.prototype,"opacityTexture",void 0),(0,je.Cg)([(0,$e.uM)("reflectionTexture")],Un.prototype,"_reflectionTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"reflectionTexture",void 0),(0,je.Cg)([(0,$e.uM)("emissiveTexture")],Un.prototype,"_emissiveTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"emissiveTexture",void 0),(0,je.Cg)([(0,$e.uM)("specularTexture")],Un.prototype,"_specularTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"specularTexture",void 0),(0,je.Cg)([(0,$e.uM)("bumpTexture")],Un.prototype,"_bumpTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"bumpTexture",void 0),(0,je.Cg)([(0,$e.uM)("lightmapTexture")],Un.prototype,"_lightmapTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"lightmapTexture",void 0),(0,je.Cg)([(0,$e.uM)("refractionTexture")],Un.prototype,"_refractionTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"refractionTexture",void 0),(0,je.Cg)([(0,$e.jT)("ambient")],Un.prototype,"ambientColor",void 0),(0,je.Cg)([(0,$e.jT)("diffuse")],Un.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.jT)("specular")],Un.prototype,"specularColor",void 0),(0,je.Cg)([(0,$e.jT)("emissive")],Un.prototype,"emissiveColor",void 0),(0,je.Cg)([(0,$e.lK)()],Un.prototype,"specularPower",void 0),(0,je.Cg)([(0,$e.lK)("useAlphaFromDiffuseTexture")],Un.prototype,"_useAlphaFromDiffuseTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesAndMiscDirty")],Un.prototype,"useAlphaFromDiffuseTexture",void 0),(0,je.Cg)([(0,$e.lK)("useEmissiveAsIllumination")],Un.prototype,"_useEmissiveAsIllumination",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"useEmissiveAsIllumination",void 0),(0,je.Cg)([(0,$e.lK)("linkEmissiveWithDiffuse")],Un.prototype,"_linkEmissiveWithDiffuse",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"linkEmissiveWithDiffuse",void 0),(0,je.Cg)([(0,$e.lK)("useSpecularOverAlpha")],Un.prototype,"_useSpecularOverAlpha",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"useSpecularOverAlpha",void 0),(0,je.Cg)([(0,$e.lK)("useReflectionOverAlpha")],Un.prototype,"_useReflectionOverAlpha",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"useReflectionOverAlpha",void 0),(0,je.Cg)([(0,$e.lK)("disableLighting")],Un.prototype,"_disableLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],Un.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.lK)("useObjectSpaceNormalMap")],Un.prototype,"_useObjectSpaceNormalMap",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"useObjectSpaceNormalMap",void 0),(0,je.Cg)([(0,$e.lK)("useParallax")],Un.prototype,"_useParallax",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"useParallax",void 0),(0,je.Cg)([(0,$e.lK)("useParallaxOcclusion")],Un.prototype,"_useParallaxOcclusion",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"useParallaxOcclusion",void 0),(0,je.Cg)([(0,$e.lK)()],Un.prototype,"parallaxScaleBias",void 0),(0,je.Cg)([(0,$e.lK)("roughness")],Un.prototype,"_roughness",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"roughness",void 0),(0,je.Cg)([(0,$e.lK)()],Un.prototype,"indexOfRefraction",void 0),(0,je.Cg)([(0,$e.lK)()],Un.prototype,"invertRefractionY",void 0),(0,je.Cg)([(0,$e.lK)()],Un.prototype,"alphaCutOff",void 0),(0,je.Cg)([(0,$e.lK)("useLightmapAsShadowmap")],Un.prototype,"_useLightmapAsShadowmap",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"useLightmapAsShadowmap",void 0),(0,je.Cg)([(0,$e.Y9)("diffuseFresnelParameters")],Un.prototype,"_diffuseFresnelParameters",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsFresnelDirty")],Un.prototype,"diffuseFresnelParameters",void 0),(0,je.Cg)([(0,$e.Y9)("opacityFresnelParameters")],Un.prototype,"_opacityFresnelParameters",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsFresnelAndMiscDirty")],Un.prototype,"opacityFresnelParameters",void 0),(0,je.Cg)([(0,$e.Y9)("reflectionFresnelParameters")],Un.prototype,"_reflectionFresnelParameters",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsFresnelDirty")],Un.prototype,"reflectionFresnelParameters",void 0),(0,je.Cg)([(0,$e.Y9)("refractionFresnelParameters")],Un.prototype,"_refractionFresnelParameters",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsFresnelDirty")],Un.prototype,"refractionFresnelParameters",void 0),(0,je.Cg)([(0,$e.Y9)("emissiveFresnelParameters")],Un.prototype,"_emissiveFresnelParameters",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsFresnelDirty")],Un.prototype,"emissiveFresnelParameters",void 0),(0,je.Cg)([(0,$e.lK)("useReflectionFresnelFromSpecular")],Un.prototype,"_useReflectionFresnelFromSpecular",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsFresnelDirty")],Un.prototype,"useReflectionFresnelFromSpecular",void 0),(0,je.Cg)([(0,$e.lK)("useGlossinessFromSpecularMapAlpha")],Un.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"useGlossinessFromSpecularMapAlpha",void 0),(0,je.Cg)([(0,$e.lK)("maxSimultaneousLights")],Un.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],Un.prototype,"maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.lK)("invertNormalMapX")],Un.prototype,"_invertNormalMapX",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"invertNormalMapX",void 0),(0,je.Cg)([(0,$e.lK)("invertNormalMapY")],Un.prototype,"_invertNormalMapY",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"invertNormalMapY",void 0),(0,je.Cg)([(0,$e.lK)("twoSidedLighting")],Un.prototype,"_twoSidedLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Un.prototype,"twoSidedLighting",void 0),(0,je.Cg)([(0,$e.lK)("applyDecalMapAfterDetailMap")],Un.prototype,"_applyDecalMapAfterDetailMap",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],Un.prototype,"applyDecalMapAfterDetailMap",void 0),(0,X.Y5)("BABYLON.StandardMaterial",Un),oi.Z.DefaultMaterialFactory=e=>new Un("default material",e),Ls.ThinEngine.prototype.createDynamicTexture=function(e,t,i,r){const s=new Fs.h(this,4);return s.baseWidth=e,s.baseHeight=t,i&&(e=this.needPOTTextures?(0,Gs.R)(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?(0,Gs.R)(t,this._caps.maxTextureSize):t),s.width=e,s.height=t,s.isReady=!1,s.generateMipMaps=i,s.samplingMode=r,this.updateTextureSamplingMode(r,s),this._internalTexturesCache.push(s),s},Ls.ThinEngine.prototype.updateDynamicTexture=function(e,t,i,r=!1,s,n=!1,o=!1){if(!e)return;const a=this._gl,l=a.TEXTURE_2D,h=this._bindTextureDirectly(l,e,!0,n);this._unpackFlipY(void 0===i?e.invertY:i),r&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(s||e.format),d=this._getRGBABufferInternalSizedFormat(e.type,u);a.texImage2D(l,0,d,u,c,t),e.generateMipMaps&&a.generateMipmap(l),h||this._bindTextureDirectly(l,null),r&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),s&&(e.format=s),e._dynamicTextureSource=t,e._premulAlpha=r,e.invertY=i||!1,e.isReady=!0};class Gn extends vi.g{constructor(e,t,i,r=!1,s=3,n=5,o){const a=!i||i._isScene;super(null,a?i:i?.scene,a?!r:i,o,s,void 0,void 0,void 0,void 0,n),this.name=e,this.wrapU=vi.g.CLAMP_ADDRESSMODE,this.wrapV=vi.g.CLAMP_ADDRESSMODE,this._generateMipMaps=r;const l=this._getEngine();if(!l)return;if(t.getContext)this._canvas=t,this._ownCanvas=!1,this._texture=l.createDynamicTexture(this._canvas.width,this._canvas.height,r,s);else{this._canvas=l.createCanvas(1,1),this._ownCanvas=!0;const e=t;e.width||0===e.width?this._texture=l.createDynamicTexture(e.width,e.height,r,s):this._texture=l.createDynamicTexture(t,t,r,s)}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,void 0===e||e,t,this._format||void 0,void 0,i)}drawText(e,t,i,r,s,n,o,a=!0){const l=this.getSize();if(n&&(this._context.fillStyle=n,this._context.fillRect(0,0,l.width,l.height)),this._context.font=r,null==t){const i=this._context.measureText(e);t=(l.width-i.width)/2}if(null==i){const e=parseInt(r.replace(/\D/g,""));i=l.height/2+e/3.65}this._context.fillStyle=s||"",this._context.fillText(e,t,i),a&&this.update(o)}dispose(){super.dispose(),this._ownCanvas&&this._canvas?.remove?.(),this._canvas=null,this._context=null}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Gn(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()&&Z.V.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return Gn._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return void 0!==e.toDataURL}_rebuild(){this.update()}}class zn{get isFixedFoveationSupported(){return"XRWebGLLayer"==this.layerType&&"number"==typeof this.layer.fixedFoveation}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){if(this.isFixedFoveationSupported){const t=Math.max(0,Math.min(1,e||0));this.layer.fixedFoveation=t}}createRenderTargetTextureProvider(e){return this._rttWrapper=this._createRenderTargetTextureProvider(e),this._rttWrapper}dispose(){this._rttWrapper&&(this._rttWrapper.dispose(),this._rttWrapper=null)}constructor(e,t,i,r,s){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this._createRenderTargetTextureProvider=s,this._rttWrapper=null}}class Wn{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}_createInternalTexture(e,t){const i=new Fs.h(this._engine,0,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new Us.d(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,r,s,n){if(!this._engine)throw new Error("Engine is disposed");const o={width:e,height:t},a=n?new hn(this._scene,o):new ln.$("XR renderTargetTexture",o,this._scene),l=a.renderTarget;if(l._samples=a.samples,!i&&r||(l._framebuffer=i),r)if(n)l._colorTextureArray=r;else{const e=this._createInternalTexture(o,r);l.setTexture(e,0),a._texture=e}return s&&(n?l._depthStencilTextureArray=s:l._depthStencilTexture=this._createInternalTexture(o,s)),a.disableRescaling(),this._renderTargetTextures.push(a),a}_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 Hn extends zn{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new Xn(e.scene,this))),this.layer=e}}class Xn extends Wn{constructor(e,t){super(e,t),this.layerWrapper=t,this._layer=t.layer,this._framebufferDimensions={framebufferWidth:this._layer.framebufferWidth,framebufferHeight:this._layer.framebufferHeight}}trySetViewportForView(e,t){const i=this._layer.getViewport(t);if(!i)return!1;const r=this._framebufferDimensions.framebufferWidth,s=this._framebufferDimensions.framebufferHeight;return e.x=i.x/r,e.y=i.y/s,e.width=i.width/r,e.height=i.height/s,!0}getRenderTargetTextureForEye(e){const t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,r=this._layer.framebuffer;return this._rtt&&t===this._framebufferDimensions.framebufferWidth&&i===this._framebufferDimensions.framebufferHeight&&r===this._framebuffer||(this._rtt=this._createRenderTargetTexture(t,i,r),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=r),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class qn{static GetDefaults(e){const t=new qn;return t.canvasOptions={antialias:!0,depth:!0,stencil:!e||e.isStencilEnable,alpha:!0,framebufferScaleFactor:1},t.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",t}}class Yn{constructor(e,t=qn.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new z.cP,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{const e=document.createElement("canvas");e.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(e)}e.onXRSessionInit.add((()=>{this._addCanvas()})),e.onXRSessionEnded.add((()=>{this._removeCanvas()})),this._makeCanvasCompatibleAsync()}dispose(){this._removeCanvas(),this._setManagedOutputCanvas(null),this.onXRLayerInitObservable.clear()}_makeCanvasCompatibleAsync(){this._canvasCompatiblePromise=new Promise(((e,t)=>{try{this.canvasContext&&this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then((()=>{e()}),(()=>{Ue.S0.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly."),e()})):e()}catch(e){t(e)}}))}async initializeXRLayerAsync(e){const t=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new Hn(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this._canvasCompatiblePromise.then((()=>{}),(()=>{})).then((()=>t()))}_addCanvas(){this._canvas&&this._engine&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce((()=>{this._setCanvasSize(!0)}))}_removeCanvas(){this._canvas&&this._engine&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)}_setCanvasSize(e=!0,t=this._xrLayerWrapper){this._canvas&&this._engine&&(e?t&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=t.getWidth()+"px",this._canvas.style.height=t.getHeight()+"px"):this._engine.setSize(t.getWidth(),t.getHeight())):this._originalCanvasSize&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=this._originalCanvasSize.width+"px",this._canvas.style.height=this._originalCanvasSize.height+"px"):this._engine.setSize(this._originalCanvasSize.width,this._originalCanvasSize.height)))}_setManagedOutputCanvas(e){this._removeCanvas(),e?(this._originalCanvasSize={width:e.offsetWidth,height:e.offsetHeight},this._canvas=e,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)}}class Kn extends zn{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new jn(e,this))),this.layer=e}}class jn extends Wn{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 $n{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 Qn{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 z.cP,this.onXRReferenceSpaceChanged=new z.cP,this.onXRSessionEnded=new z.cP,this.onXRSessionInit=new z.cP,this.onXRReferenceSpaceInitialized=new z.cP,this.onXRReady=new z.cP,this.inXRFrameLoop=!1,this.inXRSession=!1,this._worldScalingFactor=1,this.onWorldScaleFactorChangedObservable=new z.cP(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(){this.inXRSession&&this.exitXRAsync(),this.onXRReady.clear(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),this.onWorldScaleFactorChangedObservable.clear(),this._engine?.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}async exitXRAsync(){if(this.session&&this.inXRSession){this.inXRSession=!1;try{return await this.session.end()}catch{Z.V.Warn("Could not end XR session.")}}return Promise.resolve()}trySetViewportForView(e,t){return this._baseLayerRTTProvider?.trySetViewportForView(e,t)||!1}getRenderTargetTextureForEye(e){return this._baseLayerRTTProvider?.getRenderTargetTextureForEye(e)||null}getRenderTargetTextureForView(e){return this._baseLayerRTTProvider?.getRenderTargetTextureForView(e)||null}getWebXRRenderTarget(e){const t=this.scene.getEngine();return this._xrNavigator.xr.native?new $n(this):((e=e||qn.GetDefaults(t)).canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new Yn(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((t=>(this.session=t,this._sessionMode=e,this.inXRSession=!0,this.onXRSessionInit.notifyObservers(t),this.session.addEventListener("end",(()=>{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&&this._baseLayerRTTProvider?.dispose(),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null}),{once:!0}),this.session)))}isSessionSupportedAsync(e){return Qn.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){this.inXRSession&&this._engine&&(this._engine.customAnimationFrameRequester={requestAnimationFrame:e=>this.session.requestAnimationFrame(e),renderFunction:(e,t)=>{if(this.inXRSession&&this._engine&&(this.currentFrame=t,this.currentTimestamp=e,t)){this.inXRFrameLoop=!0;const e=this._baseLayerRTTProvider?.getFramebufferDimensions()||null;this._engine.framebufferDimensionsObject!==e&&(this._engine.framebufferDimensionsObject=e),this.onXRFrameObservable.notifyObservers(t),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1}}},this._engine.framebufferDimensionsObject=this._baseLayerRTTProvider?.getFramebufferDimensions()||null,this.onXRFrameObservable.addOnce((()=>{this.onXRReady.notifyObservers(this)})),"undefined"!=typeof window&&window.cancelAnimationFrame&&window.cancelAnimationFrame(this._engine._frameHandler),this._engine._renderLoop())}setReferenceSpaceTypeAsync(e="local-floor"){return this.session.requestReferenceSpace(e).then((e=>e),(e=>(Z.V.Error("XR.requestReferenceSpace failed for the following reason: "),Z.V.Error(e),Z.V.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then((e=>{const t=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(t)}),(e=>{throw Z.V.Error(e),'XR initialization failed: required "viewer" reference space type not supported.'}))))).then((e=>this.session.requestReferenceSpace("viewer").then((t=>(this.viewerReferenceSpace=t,e))))).then((e=>(this.referenceSpace=this.baseReferenceSpace=e,this.onXRReferenceSpaceInitialized.notifyObservers(e),this.referenceSpace)))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){this.isNative&&this._baseLayerRTTProvider?.dispose(),this._baseLayerWrapper=e,this._baseLayerRTTProvider=this._baseLayerWrapper?.createRenderTargetTextureProvider(this)||null}_getBaseLayerWrapper(){return this._baseLayerWrapper}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new Kn(e.baseLayer):new Hn(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((e=>{const t=void 0===e||e;return Promise.resolve(t)})).catch((e=>(Z.V.Warn(e),Promise.resolve(!1)))):Promise.resolve(!1)}get isNative(){return this._xrNavigator.xr.native??!1}get currentFrameRate(){return this.session?.frameRate}get supportedFrameRates(){return this.session?.supportedFrameRates}updateTargetFrameRate(e){return this.session.updateTargetFrameRate(e)}runInXRFrame(e,t=!0){this.inXRFrameLoop?e():!this.inXRSession&&t||this.onXRFrameObservable.addOnce(e)}get isFixedFoveationSupported(){return this._baseLayerWrapper?.isFixedFoveationSupported||!1}get fixedFoveation(){return this._baseLayerWrapper?.fixedFoveation||null}set fixedFoveation(e){const t=Math.max(0,Math.min(1,e||0));this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=t)}get enabledFeatures(){return this.session?.enabledFeatures??null}}Yt._GroundMeshParser=(e,t)=>Zn.Parse(e,t);class Zn extends Yt{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);this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){const i=this.getWorldMatrix(),r=W.AA.Matrix[5];i.invertToRef(r);const s=W.AA.Vector3[8];if(W.Pq.TransformCoordinatesFromFloatsToRef(e,0,t,r,s),e=s.x,t=s.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const n=this._getFacetAt(e,t),o=-(n.x*e+n.z*t+n.w)/n.y;return W.Pq.TransformCoordinatesFromFloatsToRef(0,o,0,i,s),s.y}getNormalAtCoordinates(e,t){const i=new W.Pq(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const r=this.getWorldMatrix(),s=W.AA.Matrix[5];r.invertToRef(s);const n=W.AA.Vector3[8];if(W.Pq.TransformCoordinatesFromFloatsToRef(e,0,t,s,n),e=n.x,t=n.z,ethis._maxX||tthis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const o=this._getFacetAt(e,t);return W.Pq.TransformNormalFromFloatsToRef(o.x,o.y,o.z,r,i),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){const i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),r=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),s=this._heightQuads[r*this._subdivisionsX+i];let n;return n=te.maxHeight){h=!0;const t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(n=0;n<=e.subdivisions;n++)for(o=0;o<=e.subdivisions;o++){const t=new W.Pq(o*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-n)*e.height/e.subdivisions-e.height/2),c=4*(((t.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(t.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth);let u=e.buffer[c]/255,d=e.buffer[c+1]/255,f=e.buffer[c+2]/255;const p=e.buffer[c+3]/255;h&&(u=1-u,d=1-d,f=1-f);const _=u*a.r+d*a.g+f*a.b;t.y=p>=l?e.minHeight+(e.maxHeight-e.minHeight)*_:e.minHeight-lt.bH,e.heightBuffer&&(e.heightBuffer[n*(e.subdivisions+1)+o]=t.y),i.push(t.x,t.y,t.z),r.push(0,0,0),s.push(o/e.subdivisions,1-n/e.subdivisions)}for(n=0;n=e.minHeight,c=i[3*s+1]>=e.minHeight,u=i[3*a+1]>=e.minHeight;h&&c&&u&&(t.push(r),t.push(s),t.push(a)),i[3*l+1]>=e.minHeight&&h&&u&&(t.push(l),t.push(r),t.push(a))}bt.ComputeNormals(i,t,r);const c=new bt;return c.indices=t,c.positions=i,c.normals=r,c.uvs=s,c}function io(e,t={},i){const r=new Zn(e,i);return r._setReady(!1),r._subdivisionsX=t.subdivisionsX||t.subdivisions||1,r._subdivisionsY=t.subdivisionsY||t.subdivisions||1,r._width=t.width||1,r._height=t.height||1,r._maxX=r._width/2,r._maxZ=r._height/2,r._minX=-r._maxX,r._minZ=-r._maxZ,Jn(t).applyToMesh(r,t.updatable),r._setReady(!0),r}function ro(e,t,i=null){const r=new Yt(e,i);return eo(t).applyToMesh(r,t.updatable),r}function so(e,t,i={},r=null){const s=i.width||10,n=i.height||10,o=i.subdivisions||1,a=i.minHeight||0,l=i.maxHeight||1,h=i.colorFilter||new H.v9(.3,.59,.11),c=i.alphaFilter||0,u=i.updatable,d=i.onReady;r=r||he.q.LastCreatedScene;const f=new Zn(e,r);let p;f._subdivisionsX=o,f._subdivisionsY=o,f._width=s,f._height=n,f._maxX=f._width/2,f._maxZ=f._height/2,f._minX=-f._maxX,f._minZ=-f._maxZ,f._setReady(!1),i.passHeightBufferInCallback&&(p=new Float32Array((o+1)*(o+1)));const _=(e,t,i)=>{to({width:s,height:n,subdivisions:o,minHeight:a,maxHeight:l,colorFilter:h,buffer:e,bufferWidth:t,bufferHeight:i,alphaFilter:c,heightBuffer:p}).applyToMesh(f,u),d&&d(f,p),f._setReady(!0)};if("string"==typeof t){const e=e=>{const t=e.width,i=e.height;if(r.isDisposed)return;const s=r?.getEngine().resizeImageBitmap(e,t,i);_(s,t,i)};Ue.S0.LoadImage(t,e,i.onError?i.onError:()=>{},r.offlineProvider)}else _(t.data,t.width,t.height);return f}const no={CreateGround:io,CreateGroundFromHeightMap:so,CreateTiledGround:ro};function oo(e){const t=[],i=[],r=[],s=[],n=e.diameter||1,o=e.thickness||.5,a=0|(e.tessellation||16),l=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE,h=a+1;for(let e=0;e<=a;e++){const l=e/a,c=e*Math.PI*2/a-Math.PI/2,u=W.uq.Translation(n/2,0,0).multiply(W.uq.RotationY(c));for(let n=0;n<=a;n++){const c=1-n/a,d=n*Math.PI*2/a+Math.PI,f=Math.cos(d),p=Math.sin(d);let _=new W.Pq(f,p,0),m=_.scale(o/2);const g=new W.I9(l,c);m=W.Pq.TransformCoordinates(m,u),_=W.Pq.TransformNormal(_,u),i.push(m.x,m.y,m.z),r.push(_.x,_.y,_.z),s.push(g.x,Tt.rX?1-g.y:g.y);const v=(e+1)%h,x=(n+1)%h;t.push(e*h+n),t.push(e*h+x),t.push(v*h+n),t.push(e*h+x),t.push(v*h+x),t.push(v*h+n)}}bt._ComputeSides(l,i,t,r,s,e.frontUVs,e.backUVs);const c=new bt;return c.indices=t,c.positions=i,c.normals=r,c.uvs=s,c}function ao(e,t={},i){const r=new Yt(e,i);return t.sideOrientation=Yt._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,oo(t).applyToMesh(r,t.updatable),r}bt.CreateGround=Jn,bt.CreateTiledGround=eo,bt.CreateGroundFromHeightMap=to,Yt.CreateGround=(e,t,i,r,s,n)=>io(e,{width:t,height:i,subdivisions:r,updatable:n},s),Yt.CreateTiledGround=(e,t,i,r,s,n,o,a,l)=>ro(e,{xmin:t,zmin:i,xmax:r,zmax:s,subdivisions:n,precision:o,updatable:l},a),Yt.CreateGroundFromHeightMap=(e,t,i,r,s,n,o,a,l,h,c)=>so(e,t,{width:i,height:r,subdivisions:s,minHeight:n,maxHeight:o,updatable:l,onReady:h,alphaFilter:c},a);const lo={CreateTorus:ao};bt.CreateTorus=oo,Yt.CreateTorus=(e,t,i,r,s,n,o)=>ao(e,{diameter:t,thickness:i,tessellation:r,sideOrientation:o,updatable:n},s);class ho{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=ho._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=ao("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;const t=new Un("targetMat",e);t.specularColor=H.v9.Black(),t.emissiveColor=new H.v9(.7,.7,.7),t.backFaceCulling=!1,this._gazeTracker.material=t}}_getForwardRay(e){return new wi(W.Pq.Zero(),new W.Pq(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()}}ho._IdCounter=0;class co extends ho{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){const t=this._getCamera();return t?t.getForwardRay(e):new wi(W.Pq.Zero(),W.Pq.Forward())}}class uo{}class fo{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 z.cP,this.onAfterEnteringVRObservable=new z.cP,this.onExitingVRObservable=new z.cP,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=fo.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new W.Pq(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new W.Pq(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new H.v9(.2,.2,1),this._pickedGazeColor=new H.v9(0,0,1),this.onNewMeshSelected=new z.cP,this.onNewMeshPicked=new z.cP,this.onBeforeCameraTeleport=new z.cP,this.onAfterCameraTeleport=new z.cP,this.onSelectedMeshUnselected=new z.cP,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=e=>{e.type!==Cr.POSE_ENABLED&&(e.leftStick&&e.onleftstickchanged((e=>{this._teleportationInitialized&&this.teleportationEnabled&&(this._checkTeleportWithRay(e,this._cameraGazer),this._checkTeleportBackwards(e,this._cameraGazer))})),e.rightStick&&e.onrightstickchanged((e=>{this._teleportationInitialized&&this._checkRotate(e,this._cameraGazer)})),e.type===Cr.XBOX&&(e.onbuttondown((e=>{this._interactionsEnabled&&0===e&&this._cameraGazer._selectionPointerDown()})),e.onbuttonup((e=>{this._interactionsEnabled&&0===e&&this._cameraGazer._selectionPointerUp()}))))},this._workingVector=W.Pq.Zero(),this._workingQuaternion=W.PT.Identity(),this._workingMatrix=W.uq.Identity(),Z.V.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||void 0!==t.useXR||(t.useXR=!0),void 0===t.createFallbackVRDeviceOrientationFreeCamera&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===t.createDeviceOrientationCamera&&(t.createDeviceOrientationCamera=!0),void 0===t.laserToggle&&(t.laserToggle=!0),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new W.Pq(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new rs("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 Jr&&this._scene.activeCamera.rotation)){const e=this._scene.activeCamera;e.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(W.PT.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z)),this._deviceOrientationCamera.rotation=e.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?Qn.IsSessionSupportedAsync("immersive-vr").then((i=>{i?(Z.V.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then((t=>{this.xr=t,this.xrTestDone=!0,this._cameraGazer=new co((()=>this.xr.baseExperience.camera),e),this.xr.baseExperience.onStateChangedObservable.add((e=>{switch(e){case 0:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case 1:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case 2:this._hasEnteredVR=!0;break;case 3:this._hasEnteredVR=!1}}))}))):this._completeVRInit(e,t)})):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new _n("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new co((()=>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 e=".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) }";e+=".babylonVRicon.vrdisplaypresenting { display: none; }";const t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),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=e=>{27===e.keyCode&&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())}),yi.Zp.POINTERDOUBLETAP,!1),e.onDisposeObservable.add((()=>{this.dispose()})),this._updateButtonVisibility(),this._circleEase=new be,this._circleEase.setEasingMode(xe.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add((t=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===yi.Zp.POINTERDOWN?this._cameraGazer._selectionPointerDown():t.type===yi.Zp.POINTERUP&&this._cameraGazer._selectionPointerUp())})),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&2===this.xr.baseExperience.state||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);else{if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){Z.V.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=W.PT.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();else if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){Z.V.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)return void(2===this.xr.baseExperience.state&&this.xr.pointerSelection.attach());this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>!!(this._isTeleportationFloor(e)||-1===e.name.indexOf("gazeTracker")&&-1===e.name.indexOf("teleportationTarget")&&-1===e.name.indexOf("torusTeleportation"))&&this.raySelectionPredicate(e),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);-1!==t&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){const t=e.floorMeshes||[];if(!t.length){const i=this._scene.getMeshByName(e.floorMeshName);i&&t.push(i)}if(this.xr)return t.forEach((e=>{this.xr.teleportation.addFloorMesh(e)})),void(this.xr.teleportation.attached||this.xr.teleportation.attach());if(!this.xrTestDone){const t=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(t),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};return void this._scene.registerBeforeRender(t)}}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),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction);const t=new gn.p;t.vignetteColor=new H.ov(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 e=W.PT.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),i=this.currentVRCamera.position;e.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,W.PT.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),W.Pq.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);const r=new wi(i,this._workingVector),s=this._scene.pickWithRay(r,this._raySelectionPredicate);s&&s.pickedPoint&&s.pickedMesh&&this._isTeleportationFloor(s.pickedMesh)&&s.distance<5&&this.teleportCamera(s.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}_createTeleportationCircles(){this._teleportationTarget=io("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;const e=new Gn("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;const t=e.getContext();t.beginPath(),t.arc(256,256,200,0,2*Math.PI,!1),t.fillStyle=this._teleportationFillColor,t.fill(),t.lineWidth=10,t.strokeStyle=this._teleportationBorderColor,t.stroke(),t.closePath(),e.update();const i=new Un("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;const r=ao("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);r.isPickable=!1,r.parent=this._teleportationTarget;const s=new pe.X5("animationInnerCircle","position.y",30,pe.X5.ANIMATIONTYPE_FLOAT,pe.X5.ANIMATIONLOOPMODE_CYCLE),n=[];n.push({frame:0,value:0}),n.push({frame:30,value:.4}),n.push({frame:60,value:0}),s.setKeys(n);const o=new Me;o.setEasingMode(xe.EASINGMODE_EASEINOUT),s.setEasingFunction(o),r.animations=[],r.animations.push(s),this._scene.beginAnimation(r,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 es))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];const t=W.PT.FromRotationMatrix(W.uq.RotationY(Math.PI/4*this._rotationAngle)),i=new pe.X5("animationRotation","rotationQuaternion",90,pe.X5.ANIMATIONTYPE_QUATERNION,pe.X5.ANIMATIONLOOPMODE_CONSTANT),r=[];r.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),r.push({frame:6,value:t}),i.setKeys(r),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];const s=new pe.X5("animationPP","vignetteWeight",90,pe.X5.ANIMATIONTYPE_FLOAT,pe.X5.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:0}),n.push({frame:3,value:4}),n.push({frame:6,value:0}),s.setKeys(n),s.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(s);const o=new pe.X5("animationPP2","vignetteStretch",90,pe.X5.ANIMATIONTYPE_FLOAT,pe.X5.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:3,value:10}),a.push({frame:6,value:0}),o.setKeys(a),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 es))return;let t,i;if(this._workingVector.copyFrom(e),this.isInVRMode||(this._workingVector.y+=this._defaultHeight),this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this._teleportationMode==fo.TELEPORTATIONMODE_CONSTANTSPEED){i=90;const e=W.Pq.Distance(this.currentVRCamera.position,this._workingVector);t=this._teleportationSpeed/e}else i=Math.round(90*this._teleportationTime/1e3),t=1;this.currentVRCamera.animations=[];const r=new pe.X5("animationCameraTeleportation","position",90,pe.X5.ANIMATIONTYPE_VECTOR3,pe.X5.ANIMATIONLOOPMODE_CONSTANT),s=[{frame:0,value:this.currentVRCamera.position},{frame:i,value:this._workingVector}];r.setKeys(s),r.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(r),this._postProcessMove.animations=[];const n=Math.round(i/2),o=new pe.X5("animationPP","vignetteWeight",90,pe.X5.ANIMATIONTYPE_FLOAT,pe.X5.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:n,value:8}),a.push({frame:i,value:0}),o.setKeys(a),this._postProcessMove.animations.push(o);const l=new pe.X5("animationPP2","vignetteStretch",90,pe.X5.ANIMATIONTYPE_FLOAT,pe.X5.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:n,value:10}),h.push({frame:i,value:0}),l.setKeys(h),this._postProcessMove.animations.push(l),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._scene.beginAnimation(this.currentVRCamera,0,i,!1,t,(()=>{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"}}fo.TELEPORTATIONMODE_CONSTANTTIME=0,fo.TELEPORTATIONMODE_CONSTANTSPEED=1;const po=function(){const e={root:0,found:!1};return function(t,i,r,s){e.root=0,e.found=!1;const n=i*i-4*t*r;if(n<0)return e;const o=Math.sqrt(n);let a=(-i-o)/(2*t),l=(-i+o)/(2*t);if(a>l){const e=l;l=a,a=e}return a>0&&a0&&l=0))}_canDoCollision(e,t,i,r){const s=W.Pq.Distance(this._basePointWorld,e),n=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(s>this._velocityWorldLength+n+t||!((e,t,i,r)=>!(e.x>i.x+r||i.x-r>t.x||e.y>i.y+r||i.y-r>t.y||e.z>i.z+r||i.z-r>t.z))(i,r,this._basePointWorld,this._velocityWorldLength+n))}_testTriangle(e,t,i,r,s,n,o){let a,l=!1;t||(t=[]),t[e]||(t[e]=new Ft.Z(0,0,0,0),t[e].copyFromPoints(i,r,s));const h=t[e];if(!n&&!h.isFrontFacingTo(this._normalizedVelocity,0))return;const c=h.signedDistanceTo(this._basePoint),u=W.Pq.Dot(h.normal,this._velocity);if(_o.DoubleSidedCheck&&u>1e-4)return;if(0==u){if(Math.abs(c)>=1)return;l=!0,a=0}else{a=(-1-c)/u;let e=(1-c)/u;if(a>e){const t=e;e=a,a=t}if(a>1||e<0)return;a<0&&(a=0),a>1&&(a=1)}this._collisionPoint.copyFromFloats(0,0,0);let d=!1,f=1;if(l||(this._basePoint.subtractToRef(h.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(a,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,r,s,h.normal)&&(d=!0,f=a,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!d){let e=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let t=2*W.Pq.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=po(e,t,n,f);o.found&&(f=o.root,d=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(r,this._tempVector),t=2*W.Pq.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=po(e,t,n,f),o.found&&(f=o.root,d=!0,this._collisionPoint.copyFrom(r)),this._basePoint.subtractToRef(s,this._tempVector),t=2*W.Pq.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=po(e,t,n,f),o.found&&(f=o.root,d=!0,this._collisionPoint.copyFrom(s)),r.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let a=this._edge.lengthSquared(),l=W.Pq.Dot(this._edge,this._velocity),h=W.Pq.Dot(this._edge,this._baseToVertex);if(e=a*-this._velocitySquaredLength+l*l,t=2*(a*W.Pq.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=po(e,t,n,f),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(f=o.root,d=!0,this._edge.scaleInPlace(e),i.addToRef(this._edge,this._collisionPoint))}if(s.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),a=this._edge.lengthSquared(),l=W.Pq.Dot(this._edge,this._velocity),h=W.Pq.Dot(this._edge,this._baseToVertex),e=a*-this._velocitySquaredLength+l*l,t=2*(a*W.Pq.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=po(e,t,n,f),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(f=o.root,d=!0,this._edge.scaleInPlace(e),r.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),a=this._edge.lengthSquared(),l=W.Pq.Dot(this._edge,this._velocity),h=W.Pq.Dot(this._edge,this._baseToVertex),e=a*-this._velocitySquaredLength+l*l,t=2*(a*W.Pq.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=po(e,t,n,f),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(f=o.root,d=!0,this._edge.scaleInPlace(e),s.addToRef(this._edge,this._collisionPoint))}}if(d){const e=f*f*this._velocitySquaredLength;(!this.collisionFound||e=r)return void s.copyFrom(e);const a=n?n.collisionMask:i.collisionMask;i._initialize(e,t,o);const l=n&&n.surroundingMeshes||this._scene.meshes;for(let e=0;enew mo;var go=i(67313);const vo={effect:null,subMesh:null};class xo extends bn{constructor(e,t,i,r={},s=!0){super(e,t,s),this._textures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new W.uq,this._cachedWorldViewProjectionMatrix=new W.uq,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options={needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1,...r}}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)}setTexture(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this}removeTexture(e){delete this._textures[e]}setTextureArray(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return-1===this._options.externalTextures.indexOf(e)&&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(((e,t)=>(t.toArray(e,e.length),e)),[]),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(((e,t)=>(t.toArray(e,e.length),e)),[]),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(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const i=new Float32Array(16*t.length);for(let e=0;et===e||t.startsWith(i)));return r>=0&&this.options.defines.splice(r,1),("boolean"!=typeof t||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){const r=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){const e=r?i._drawWrapper:this._drawWrapper;if(e.effect&&e._wasPreviouslyReady&&e._wasPreviouslyUsingInstances===t)return!0}const s=this.getScene(),n=s.getEngine(),o=[],a=[],l=new Tn;let h=this._shaderPath,c=this._options.uniforms,u=this._options.uniformBuffers,d=this._options.samplers;n.getCaps().multiview&&s.activeCamera&&s.activeCamera.outputRenderTarget&&s.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,o.push("#define MULTIVIEW"),-1!==c.indexOf("viewProjection")&&-1===c.indexOf("viewProjectionR")&&c.push("viewProjectionR"));for(let e=0;e4&&(a.push(st.R.MatricesIndicesExtraKind),a.push(st.R.MatricesWeightsExtraKind));const t=e.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),l.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(o.push("#define BONETEXTURE"),-1===c.indexOf("boneTextureWidth")&&c.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(o.push("#define BonesPerMesh "+(t.bones.length+1)),-1===c.indexOf("mBones")&&c.push("mBones"))}else o.push("#define NUM_BONE_INFLUENCERS 0");let f=0;const p=e?e.morphTargetManager:null;if(p){const e=p.supportsUVs&&-1!==o.indexOf("#define UV1"),t=p.supportsTangents&&-1!==o.indexOf("#define TANGENT"),i=p.supportsNormals&&-1!==o.indexOf("#define NORMAL");f=p.numMaxInfluencers||p.numInfluencers,e&&o.push("#define MORPHTARGETS_UV"),t&&o.push("#define MORPHTARGETS_TANGENT"),i&&o.push("#define MORPHTARGETS_NORMAL"),f>0&&o.push("#define MORPHTARGETS"),p.isUsingTextureForTargets&&(o.push("#define MORPHTARGETS_TEXTURE"),-1===c.indexOf("morphTargetTextureIndices")&&c.push("morphTargetTextureIndices"),-1===this._options.samplers.indexOf("morphTargets")&&this._options.samplers.push("morphTargets")),o.push("#define NUM_MORPH_INFLUENCERS "+f);for(let r=0;r0&&(c=c.slice(),c.push("morphTargetInfluences"),c.push("morphTargetCount"),c.push("morphTargetTextureInfo"),c.push("morphTargetTextureIndices"))}else o.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(o.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===c.indexOf("bakedVertexAnimationSettings")&&c.push("bakedVertexAnimationSettings"),-1===c.indexOf("bakedVertexAnimationTextureSizeInverted")&&c.push("bakedVertexAnimationTextureSizeInverted"),-1===c.indexOf("bakedVertexAnimationTime")&&c.push("bakedVertexAnimationTime"),-1===this._options.samplers.indexOf("bakedVertexAnimationTexture")&&this._options.samplers.push("bakedVertexAnimationTexture")),(0,Bt.J2)(a,e,o)}for(const e in this._textures)if(!this._textures[e].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&o.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&((0,Ln.TV)(c),(0,Ln.tv)(this,s,o)),s.fogEnabled&&e?.applyFog&&s.fogMode!==oi.Z.FOGMODE_NONE&&(o.push("#define FOG"),-1===c.indexOf("view")&&c.push("view"),-1===c.indexOf("vFogInfos")&&c.push("vFogInfos"),-1===c.indexOf("vFogColor")&&c.push("vFogColor")),this._useLogarithmicDepth&&(o.push("#define LOGARITHMICDEPTH"),-1===c.indexOf("logarithmicDepthConstant")&&c.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(c=c.slice(),u=u.slice(),d=d.slice(),h=this.customShaderNameResolve(this.name,c,u,d,o,a));const _=r?i._getDrawWrapper(void 0,!0):this._drawWrapper,m=_?.effect??null,g=_?.defines??null,v=o.join("\n");let x=m;return g!==v&&(x=n.createEffect(h,{attributes:a,uniformsNames:c,uniformBuffersNames:u,samplers:d,defines:v,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:f},shaderLanguage:this._options.shaderLanguage,extraInitializationsAsync:this._options.extraInitializationsAsync},n),r?i.setEffect(x,v,this._materialContext):_&&_.setEffect(x,v),this._onEffectCreatedObservable&&(vo.effect=x,vo.subMesh=i??e?.subMeshes[0]??null,this._onEffectCreatedObservable.notifyObservers(vo))),_._wasPreviouslyUsingInstances=!!t,!(!x?.isReady()??1)&&(m!==x&&s.resetCachedMaterial(),_._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){const i=this.getScene(),r=t??this.getEffect();r&&(-1!==this._options.uniforms.indexOf("world")&&r.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),r.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),r.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),-1!==this._options.uniforms.indexOf("view")&&r.setMatrix("view",i.getViewMatrix()))}bindForSubMesh(e,t,i){this.bind(e,t,i._drawWrapperOverride?.effect,i)}bind(e,t,i,r){const s=r&&this._storeEffectOnSubMeshes,n=i??(s?r.effect:this.getEffect());if(!n)return;const o=this.getScene();this._activeEffect=n,this.bindOnlyWorldMatrix(e,i);const a=this._options.uniformBuffers;let l=!1;if(n&&a&&a.length>0&&o.getEngine().supportsUniformBuffers)for(let i=0;i0&&(0,Bt.nR)(t,n);const i=t.bakedVertexAnimationManager;if(i&&i.isEnabled){const e=s?r._drawWrapper:this._drawWrapper;t.bakedVertexAnimationManager?.bind(n,!!e._wasPreviouslyUsingInstances)}}this._afterBind(t,n,r)}getActiveTextures(){const e=super.getActiveTextures();for(const t in this._textures)e.push(this._textures[t]);for(const t in this._textureArrays){const i=this._textureArrays[t];for(let t=0;tnew xo(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes)),this);t.name=e,t.id=e,"object"==typeof t._shaderPath&&(t._shaderPath={...t._shaderPath}),this._options={...this._options},Object.keys(this._options).forEach((e=>{const t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))})),this.stencil.copyTo(t.stencil);for(const e in this._textures)t.setTexture(e,this._textures[e]);for(const e in this._textureArrays)t.setTextureArray(e,this._textureArrays[e]);for(const e in this._externalTextures)t.setExternalTexture(e,this._externalTextures[e]);for(const e in this._ints)t.setInt(e,this._ints[e]);for(const e in this._uints)t.setUInt(e,this._uints[e]);for(const e in this._floats)t.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)t.setFloats(e,this._floatsArrays[e]);for(const e in this._colors3)t.setColor3(e,this._colors3[e]);for(const e in this._colors3Arrays)t._colors3Arrays[e]=this._colors3Arrays[e];for(const e in this._colors4)t.setColor4(e,this._colors4[e]);for(const e in this._colors4Arrays)t._colors4Arrays[e]=this._colors4Arrays[e];for(const e in this._vectors2)t.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)t.setVector3(e,this._vectors3[e]);for(const e in this._vectors4)t.setVector4(e,this._vectors4[e]);for(const e in this._quaternions)t.setQuaternion(e,this._quaternions[e]);for(const e in this._quaternionsArrays)t._quaternionsArrays[e]=this._quaternionsArrays[e];for(const e in this._matrices)t.setMatrix(e,this._matrices[e]);for(const e in this._matrixArrays)t._matrixArrays[e]=this._matrixArrays[e].slice();for(const e in this._matrices3x3)t.setMatrix3x3(e,this._matrices3x3[e]);for(const e in this._matrices2x2)t.setMatrix2x2(e,this._matrices2x2[e]);for(const e in this._vectors2Arrays)t.setArray2(e,this._vectors2Arrays[e]);for(const e in this._vectors3Arrays)t.setArray3(e,this._vectors3Arrays[e]);for(const e in this._vectors4Arrays)t.setArray4(e,this._vectors4Arrays[e]);for(const e in this._uniformBuffers)t.setUniformBuffer(e,this._uniformBuffers[e]);for(const e in this._textureSamplers)t.setTextureSampler(e,this._textureSamplers[e]);for(const e in this._storageBuffers)t.setStorageBuffer(e,this._storageBuffers[e]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){const t=this._textureArrays[e];for(let e=0;enew xo(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes)),e,t,i);let s;for(s in e.stencil&&r.stencil.parse(e.stencil,t,i),e.textures)r.setTexture(s,vi.g.Parse(e.textures[s],t,i));for(s in e.textureArrays){const n=e.textureArrays[s],o=[];for(let e=0;e(i%3==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>H.v9.FromArray(e)));r.setColor3Array(s,t)}for(s in e.colors4)r.setColor4(s,H.ov.FromArray(e.colors4[s]));for(s in e.colors4Arrays){const t=e.colors4Arrays[s].reduce(((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>H.ov.FromArray(e)));r.setColor4Array(s,t)}for(s in e.vectors2)r.setVector2(s,W.I9.FromArray(e.vectors2[s]));for(s in e.vectors3)r.setVector3(s,W.Pq.FromArray(e.vectors3[s]));for(s in e.vectors4)r.setVector4(s,W.IU.FromArray(e.vectors4[s]));for(s in e.quaternions)r.setQuaternion(s,W.PT.FromArray(e.quaternions[s]));for(s in e.matrices)r.setMatrix(s,W.uq.FromArray(e.matrices[s]));for(s in e.matrixArray)r._matrixArrays[s]=new Float32Array(e.matrixArray[s]);for(s in e.matrices3x3)r.setMatrix3x3(s,e.matrices3x3[s]);for(s in e.matrices2x2)r.setMatrix2x2(s,e.matrices2x2[s]);for(s in e.vectors2Arrays)r.setArray2(s,e.vectors2Arrays[s]);for(s in e.vectors3Arrays)r.setArray3(s,e.vectors3Arrays[s]);for(s in e.vectors4Arrays)r.setArray4(s,e.vectors4Arrays[s]);for(s in e.quaternionsArrays)r.setArray4(s,e.quaternionsArrays[s]);return r}static ParseFromFileAsync(e,t,i,r=""){return new Promise(((s,n)=>{const o=new go.u;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),n=this.Parse(t,i||he.q.LastCreatedScene,r);e&&(n.name=e),s(n)}else n("Unable to load the ShaderMaterial")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return new Promise(((r,s)=>{const n=new go.u;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const s=JSON.parse(JSON.parse(n.responseText).jsonPayload),o=JSON.parse(s.shaderMaterial),a=this.Parse(o,t||he.q.LastCreatedScene,i);a.snippetId=e,r(a)}else s("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}xo.SnippetUrl="https://snippet.babylonjs.com",xo.CreateFromSnippetAsync=xo.ParseFromSnippetAsync,(0,X.Y5)("BABYLON.ShaderMaterial",xo);class bo{constructor(){this._pickingTexture=null,this._idMap=[],this._thinIdMap=[],this._idColors=[],this._meshMaterialMap=new Map,this._meshRenderingCount=0,this._attributeName="instanceMeshID",this._shaderLanguage=0,this._pickingInProgress=!1}get shaderLanguage(){return this._shaderLanguage}get pickingInProgress(){return this._pickingInProgress}static _IdToRgb(e){bo._TempColor.r=(16711680&e)>>16,bo._TempColor.g=(65280&e)>>8,bo._TempColor.b=255&e}_getColorIdFromReadBuffer(e){return(this._readbuffer[e]<<16)+(this._readbuffer[e+1]<<8)+this._readbuffer[e+2]}static _SetColorData(e,t,i,r,s){e[t]=i/255,e[t+1]=r/255,e[t+2]=s/255,e[t+3]=1}_createRenderTarget(e,t,i){this._pickingTexture&&this._pickingTexture.dispose(),this._pickingTexture=new ln.$("pickingTexure",{width:t,height:i},e,!1,void 0,0,!1,1)}async _createColorMaterialAsync(e){this._defaultRenderMaterial&&this._defaultRenderMaterial.dispose(),this._defaultRenderMaterial=null,e.getEngine().isWebGPU&&(this._shaderLanguage=1);const t={attributes:[st.R.PositionKind,this._attributeName,"bakedVertexAnimationSettingsInstanced"],uniforms:["world","viewProjection","meshID"],needAlphaBlending:!1,defines:[],useClipPlane:null,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this.shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,38020)),Promise.resolve().then(i.bind(i,17570))]):await Promise.all([Promise.resolve().then(i.bind(i,7987)),Promise.resolve().then(i.bind(i,37837))])}};this._defaultRenderMaterial=new xo("pickingShader",e,"picking",t,!1),this._defaultRenderMaterial.onBindObservable.add(this._materialBindCallback,void 0,void 0,this)}_materialBindCallback(e){if(!e)return;const t=this._meshMaterialMap.get(e).getEffect();e.hasInstances||e.isAnInstance||e.hasThinInstances||t.setColor4("meshID",this._idColors[e.uniqueId],1),this._meshRenderingCount++}_generateColorData(e,t,i,r,s,n,o){const a=new Float32Array(4*(e+1));bo._SetColorData(a,0,r,s,n);for(let i=0;i{this._thinIdMap[i]={meshId:e,thinId:t}}));n+=t.thinInstanceCount,t.thinInstanceSetBuffer(this._attributeName,i,4)}else if(this._idMap[n]=e,n++,t.hasInstances){const i=t.instances,r=this._generateColorData(i.length,n,e,bo._TempColor.r,bo._TempColor.g,bo._TempColor.b,((e,t)=>{const r=i[e];this._idMap[t]=this._pickableMeshes.indexOf(r)}));n+=i.length;const s=t.getEngine(),o=new st.R(s,r,this._attributeName,!1,!1,4,!0);t.setVerticesBuffer(o,!0)}else this._idColors[t.uniqueId]=H.v9.FromInts(bo._TempColor.r,bo._TempColor.g,bo._TempColor.b)}}async pickAsync(e,t,i=!1){if(this._pickingInProgress)return null;if(!this._pickableMeshes||0===this._pickableMeshes.length)return null;const{x:r,y:s,rttSizeW:n,rttSizeH:o}=this._prepareForPicking(e,t);if(r<0||s<0||r>=n||s>=o)return null;this._pickingInProgress=!0;const a=o-s-1;return this._preparePickingBuffer(this._engine,n,o,r,a),this._executePicking(r,a,i)}async multiPickAsync(e,t=!1){if(this._pickingInProgress)return null;if(!this._pickableMeshes||0===this._pickableMeshes.length||0===e.length)return null;if(1===e.length){const i=await this.pickAsync(e[0].x,e[0].y,t);return{meshes:[i?.mesh??null],thinInstanceIndexes:i?.thinInstanceIndex?[i.thinInstanceIndex]:void 0}}this._pickingInProgress=!0;let i=e[0].x,r=e[0].x,s=e[0].y,n=e[0].y;for(let t=1;t{this._enableScissor(r,s,n,o)},this._cachedScene.customRenderTargets.push(this._pickingTexture)}_executePicking(e,t,i){return new Promise(((r,s)=>{if(!this._pickingTexture)return this._pickingInProgress=!1,void s();this._pickingTexture.onAfterRender=async()=>{if(this._disableScissor(),this._checkRenderStatus()){this._pickingTexture.onAfterRender=null;let s,n=null;const o=this._cachedScene.customRenderTargets.indexOf(this._pickingTexture);if(o>-1&&this._cachedScene.customRenderTargets.splice(o,1),await this._readTexturePixelsAsync(e,t)){const e=this._getColorIdFromReadBuffer(0);this._thinIdMap[e]?(n=this._pickableMeshes[this._thinIdMap[e].meshId],s=this._thinIdMap[e].thinId):n=this._pickableMeshes[this._idMap[e]]}i&&this.dispose(),this._pickingInProgress=!1,r(n?{mesh:n,thinInstanceIndex:s}:null)}}}))}_executeMultiPicking(e,t,i,r,s,n,o){return new Promise(((a,l)=>{if(!this._pickingTexture)return this._pickingInProgress=!1,void l();this._pickingTexture.onAfterRender=async()=>{if(this._disableScissor(),this._checkRenderStatus()){this._pickingTexture.onAfterRender=null;const l=[],h=[];if(await this._readTexturePixelsAsync(t,r-i-1,s,n))for(let r=0;r0){const e=this._cachedScene.customRenderTargets.indexOf(this._pickingTexture);return e>-1&&this._cachedScene.customRenderTargets.splice(e,1),!0}return this._meshRenderingCount=0,!1}_getMeshFromMultiplePoints(e,t,i,r,s){let n=4*(e-i-1),o=(r-t-1)*s*4;n=Math.max(n,0),o=Math.max(o,0);const a=this._getColorIdFromReadBuffer(n+o);let l,h=null;return a>0&&(this._thinIdMap[a]?(h=this._pickableMeshes[this._thinIdMap[a].meshId],l=this._thinIdMap[a].thinId):h=this._pickableMeshes[this._idMap[a]]),{pickedMesh:h,thinInstanceIndex:l}}_updateRenderList(){this._pickingTexture.renderList=[];for(const e of this._pickableMeshes)this._pickingTexture.setMaterialForRendering(e,this._meshMaterialMap.get(e)),this._pickingTexture.renderList.push(e)}async _readTexturePixelsAsync(e,t,i=1,r=1){if(!this._cachedScene||!this._pickingTexture?._texture)return!1;const s=this._cachedScene.getEngine();return await s._readTexturePixels(this._pickingTexture._texture,i,r,-1,0,this._readbuffer,!0,!0,e,t),!0}dispose(){this.setPickingList(null),this._cachedScene=null,this._pickingTexture?.dispose(),this._pickingTexture=null,this._defaultRenderMaterial?.dispose(),this._defaultRenderMaterial=null}}bo._TempColor={r:0,g:0,b:0};var So=i(7987),To=i(37837),Co=i(38020),yo=i(17570);class Eo{constructor(e,t,i,r=""){let s;this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new z.cP,this.onErrorObservable=new z.cP,this.onBindObservable=new z.cP,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=1,this.name=e,this._key=r,this._engine=i,this.uniqueId=Eo._UniqueIdSeed++,this.defines=t.defines??"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=t.entryPoint??"main",this._shaderStore=Cs.l.GetShadersStore(this._shaderLanguage),this._shaderRepository=Cs.l.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=Cs.l.GetIncludesShadersStore(this._shaderLanguage);const n=(0,ii.BA)()?this._engine.getHostDocument():null;s="string"==typeof e?e:e.computeSource?"source:"+e.computeSource:e.computeElement?n?.getElementById(e.computeElement)||e.computeElement:e.compute||e;const o={defines:this.defines.split("\n"),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:(e,t,i)=>{if(!i)return t;for(const e of i){const i=e.replace("#define","").replace(";","").trim().split(" ");if(2===i.length){const e=i[0],r=i[1];isNaN(parseInt(r))&&isNaN(parseFloat(r))||(t=`const ${e} = ${r};\n`+t)}}return t}};this._loadShader(s,"Compute","",(i=>{(0,Cn.pB)(o),(0,Cn.jC)(i,o,(r=>{this._rawComputeSourceCode=i,t.processFinalCode&&(r=t.processFinalCode(r));const s=(0,Cn.nO)(r,"",o);this._useFinalCode(s.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+"\n"+e}else this._computeSourceCode=e;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getCompilationError(){return this._compilationError}executeWhenCompiled(e){this.isReady()?e(this):(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){return void this._processCompilationErrors(t,e)}setTimeout((()=>{this._checkIsReady(e)}),16)}_loadShader(e,t,i,r){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void r((0,ii.Zl)(e));if("source:"===e.substring(0,7))return void r(e.substring(7));if("base64:"===e.substring(0,7))return void r(window.atob(e.substring(7)));if(this._shaderStore[e+t+"Shader"])return void r(this._shaderStore[e+t+"Shader"]);if(i&&this._shaderStore[e+i+"Shader"])return void r(this._shaderStore[e+i+"Shader"]);let s;s="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:this._shaderRepository+e,this._engine._loadFile(s+"."+t.toLowerCase()+".fx",r)}get computeSourceCode(){return this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._pipelineContext?._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,(e=>{e&&e.numErrors>0?this._processCompilationErrors(e,t):(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(e){this._processCompilationErrors(e,t)}}_processCompilationErrors(e,t=null){if(this._compilationError="",Z.V.Error("Unable to compile compute effect:"),this.defines&&Z.V.Error("Defines:\n"+this.defines),Eo.LogShaderCodeOnCompilationError){const e=this._pipelineContext?._getComputeShaderCode();e&&(Z.V.Error("Compute code:"),Z.V.Error(e))}if("string"==typeof e)this._compilationError=e,Z.V.Error("Error: "+this._compilationError);else for(const t of e.messages){let e="";void 0!==t.line&&(e+="Line "+t.line+", "),void 0!==t.offset&&(e+="Offset "+t.offset+", "),void 0!==t.length&&(e+="Length "+t.length+", "),e+=t.type+": "+t.text,this._compilationError&&(this._compilationError+="\n"),this._compilationError+=e,Z.V.Error(e)}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){Cs.l.GetShadersStore(1)[`${e}ComputeShader`]=t}}Eo._UniqueIdSeed=0,Eo.LogShaderCodeOnCompilationError=!0;var Po=i(62061);class Ao{constructor(e){this._engine=e}async _initializePlatform(){if(!this._platform)if(this._engine.getCaps().supportComputeShaders){const e=await Promise.resolve().then(i.bind(i,19164));this._platform=new e.ComputeShaderBoundingHelper(this._engine)}else{if(!this._engine.getCaps().supportTransformFeedbacks)throw new Error("Your engine does not support Compute Shaders or Transform Feedbacks");{const e=await Promise.resolve().then(i.bind(i,43306));this._platform=new e.TransformFeedbackBoundingHelper(this._engine)}}}async computeAsync(e){return await this._initializePlatform(),this._platform.processAsync(e)}async batchInitializeAsync(e){return await this._initializePlatform(),this._platform.registerMeshListAsync(e)}batchProcess(){this._platform.processMeshList()}async batchFetchResultsAsync(){return this._platform.fetchResultsForMeshListAsync()}dispose(){this._platform.dispose()}}var Ro=i(43306),Io=i(19164);class Mo{constructor(e,t,i,r,s,n){this.entries=[],this._boundingVectors=new Array,this._capacity=i,this._depth=r,this._maxDepth=s,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 i=e.getBoundingInfo();!e.isBlocked&&i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},Oo.CreationFuncForSubMeshes=(e,t)=>{e.getBoundingInfo().boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},oi.Z.prototype.createOrUpdateSelectionOctree=function(e=64,t=2){let i=this._getComponent(Ut.v.NAME_OCTREE);i||(i=new Do(this),this._addComponent(i)),this._selectionOctree||(this._selectionOctree=new Oo(Oo.CreationFuncForMeshes,e,t));const r=this.getWorldExtends();return this._selectionOctree.update(r.min,r.max,this.meshes),this._selectionOctree},Object.defineProperty(oi.Z.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),Nt.prototype.createOrUpdateSubmeshesOctree=function(e=64,t=2){const i=this.getScene();let r=i._getComponent(Ut.v.NAME_OCTREE);r||(r=new Do(i),i._addComponent(r)),this._submeshesOctree||(this._submeshesOctree=new Oo(Oo.CreationFuncForSubMeshes,e,t)),this.computeWorldMatrix(!0);const s=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(s.minimumWorld,s.maximumWorld,this.subMeshes),this._submeshesOctree};class Do{constructor(e){this.name=Ut.v.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new wi(W.Pq.Zero(),new W.Pq(1,1,1)),(e=e||he.q.LastCreatedScene)&&(this.scene=e,this.scene.getActiveMeshCandidates=()=>this.getActiveMeshCandidates(),this.scene.getActiveSubMeshCandidates=e=>this.getActiveSubMeshCandidates(e),this.scene.getCollidingSubMeshCandidates=(e,t)=>this.getCollidingSubMeshCandidates(e,t),this.scene.getIntersectingSubMeshCandidates=(e,t)=>this.getIntersectingSubMeshCandidates(e,t))}register(){this.scene.onMeshRemovedObservable.add((e=>{const t=this.scene.selectionOctree;if(null!=t){const i=t.dynamicContent.indexOf(e);-1!==i&&t.dynamicContent.splice(i,1)}})),this.scene.onMeshImportedObservable.add((e=>{const t=this.scene.selectionOctree;null!=t&&t.addMesh(e)}))}getActiveMeshCandidates(){return this.scene._selectionOctree?.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?(wi.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 wo(e){const t=e.height||2;let i=0===e.diameterTop?0:e.diameterTop||e.diameter||1,r=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;i=i||1e-5,r=r||1e-5;const s=0|(e.tessellation||24),n=0|(e.subdivisions||1),o=!!e.hasRings,a=!!e.enclose,l=0===e.cap?0:e.cap||Yt.CAP_ALL,h=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,c=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE,u=e.faceUV||new Array(3),d=e.faceColors,f=2+(1+(1!==h&&a?2:0))*(o?n:1);let p;for(p=0;p{const n=e?i/2:r/2;if(0===n)return;let o,a,l;const c=e?u[f-1]:u[0];let p=null;d&&(p=e?d[f-1]:d[0]);const b=m.length/3,S=e?t/2:-t/2,T=new W.Pq(0,S,0);m.push(T.x,T.y,T.z),g.push(0,e?1:-1,0);const C=c.y+.5*(c.w-c.y);v.push(c.x+.5*(c.z-c.x),Tt.rX?1-C:C),p&&x.push(p.r,p.g,p.b,p.a);const y=new W.I9(.5,.5);for(l=0;l<=s;l++){o=2*Math.PI*l*h/s;const t=Math.cos(-o),i=Math.sin(-o);a=new W.Pq(t*n,S,i*n);const r=new W.I9(t*y.x+.5,i*y.y+.5);m.push(a.x,a.y,a.z),g.push(0,e?1:-1,0);const u=c.y+(c.w-c.y)*r.y;v.push(c.x+(c.z-c.x)*r.x,Tt.rX?1-u:u),p&&x.push(p.r,p.g,p.b,p.a)}for(l=0;l(void 0!==o&&o instanceof oi.Z||(void 0!==o&&(l=a||Yt.DEFAULTSIDE,a=o),o=n,n=1),No(e,{height:t,diameterTop:i,diameterBottom:r,tessellation:s,subdivisions:n,sideOrientation:l,updatable:a},o)),Ze.b.AddNodeConstructor("Light_Type_3",((e,t)=>()=>new Lo(e,W.Pq.Zero(),t)));class Lo extends $t{constructor(e,t,i){super(e,i),this.groundColor=new H.v9(0,0,0),this.direction=t||W.Pq.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=W.Pq.Normalize(e.subtract(W.Pq.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=W.Pq.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=W.Pq.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=W.uq.Identity()),this._worldMatrix}getTypeID(){return $t.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}(0,je.Cg)([(0,$e.jT)()],Lo.prototype,"groundColor",void 0),(0,je.Cg)([(0,$e.P_)()],Lo.prototype,"direction",void 0),(0,X.Y5)("BABYLON.HemisphericLight",Lo);class Bo{getRenderCamera(e){if(this._renderCamera)return this._renderCamera;{let t;return t=this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera,e&&t&&t.isRigCamera?t.rigParent:t}}setRenderCamera(e){this._renderCamera=e}_getSharedGizmoLight(){return this._sharedGizmoLight||(this._sharedGizmoLight=new Lo("shared gizmo light",new W.Pq(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=H.v9.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return null==Bo._DefaultUtilityLayer?Bo._CreateDefaultUtilityLayerFromScene(he.q.LastCreatedScene):Bo._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return Bo._DefaultUtilityLayer=new Bo(e),Bo._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{Bo._DefaultUtilityLayer=null})),Bo._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return null==Bo._DefaultKeepDepthUtilityLayer&&(Bo._DefaultKeepDepthUtilityLayer=new Bo(he.q.LastCreatedScene),Bo._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,Bo._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{Bo._DefaultKeepDepthUtilityLayer=null}))),Bo._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 z.cP,this.utilityLayerScene=new oi.Z(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((t=>{if(!this.utilityLayerScene.activeCamera)return;if(!this.pickingEnabled)return;if(!this.processAllEvents&&t.type!==yi.Zp.POINTERMOVE&&t.type!==yi.Zp.POINTERUP&&t.type!==yi.Zp.POINTERDOWN&&t.type!==yi.Zp.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;const i=t.event;if(e.isPointerCaptured(i.pointerId))return void(this._pointerCaptures[i.pointerId]=!1);const r=i=>{let r=null;if(t.nearInteractionPickingInfo)r=t.nearInteractionPickingInfo.pickedMesh.getScene()==i?t.nearInteractionPickingInfo:new At.G;else if(i!==this.utilityLayerScene&&t.originalPickingInfo)r=t.originalPickingInfo;else{let s=null;this._renderCamera&&(s=i._activeCamera,i._activeCamera=this._renderCamera,t.ray=null),r=t.ray?i.pickWithRay(t.ray):i.pick(e.pointerX,e.pointerY),s&&(i._activeCamera=s)}return r},s=r(this.utilityLayerScene);if(!t.ray&&s&&(t.ray=s.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(t),this.onlyCheckPointerDownEvents&&t.type!=yi.Zp.POINTERDOWN)return t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new yi.mx(t.type,t.event,s),t.type),void(t.type===yi.Zp.POINTERUP&&this._pointerCaptures[i.pointerId]&&(this._pointerCaptures[i.pointerId]=!1));if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)s&&s.hit&&(t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new yi.mx(t.type,t.event,s),t.type),t.skipOnPointerObservable=!0);else{const i=r(e),n=t.event;i&&s&&(0===s.distance&&i.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):t.type===yi.Zp.POINTERDOWN?this._pointerCaptures[n.pointerId]=!0:t.type!==yi.Zp.POINTERMOVE&&t.type!==yi.Zp.POINTERUP||(this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,i,n)):!this._pointerCaptures[n.pointerId]&&(s.distance0)):!this._pointerCaptures[n.pointerId]&&s.distance>=i.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):(t.type!==yi.Zp.POINTERMOVE&&t.type!==yi.Zp.POINTERUP||this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,s,n))),t.type===yi.Zp.POINTERUP&&this._pointerCaptures[n.pointerId]&&(this._pointerCaptures[n.pointerId]=!1))}})),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add((e=>{this.shouldRender&&e==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 yi.mx(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()}}var Vo,ko,Uo;Bo._DefaultUtilityLayer=null,Bo._DefaultKeepDepthUtilityLayer=null,function(e){e[e.Origin=0]="Origin",e[e.Pivot=1]="Pivot"}(Vo||(Vo={})),function(e){e[e.World=0]="World",e[e.Local=1]="Local"}(ko||(ko={}));class Go{set scaleRatio(e){this._scaleRatio=e}get scaleRatio(){return this._scaleRatio}get isHovered(){return this._isHovered}get attachedMesh(){return this._attachedMesh}set attachedMesh(e){this._attachedMesh=e,e&&(this._attachedNode=e),this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}get attachedNode(){return this._attachedNode}set attachedNode(e){this._attachedNode=e,this._attachedMesh=null,this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._rootMesh.getChildMeshes().forEach((e=>{e.dispose()})),e.parent=this._rootMesh,this._customMeshSet=!0}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){this._additionalTransformNode=e}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){this._coordinatesMode=e;const t=1==e;this.updateGizmoRotationToMatchAttachedMesh=t,this.updateGizmoPositionToMatchAttachedMesh=!0}get coordinatesMode(){return this._coordinatesMode}set updateScale(e){this._updateScale=e}get updateScale(){return this._updateScale}_attachedNodeChanged(e){}constructor(e=Bo.DefaultUtilityLayer){this.gizmoLayer=e,this._attachedMesh=null,this._attachedNode=null,this._customRotationQuaternion=null,this._scaleRatio=1,this._isHovered=!1,this._customMeshSet=!1,this._updateGizmoRotationToMatchAttachedMesh=!0,this._updateGizmoPositionToMatchAttachedMesh=!0,this._anchorPoint=0,this._updateScale=!0,this._coordinatesMode=1,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=W.uq.RotationY(Math.PI),this._rootMesh=new Yt("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=W.PT.Identity(),this._beforeRenderObserver=this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add((()=>{this._update()}))}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e}_update(){if(this.attachedNode){let e=this.attachedNode;if(this.attachedMesh&&(e=this.attachedMesh||this.attachedNode),this.updateGizmoPositionToMatchAttachedMesh)if(1==this.anchorPoint&&e.getAbsolutePivotPoint){const t=e.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(t)}else{const t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new W.Pq(0,0,0);this._rootMesh.position.copyFrom(i)}if(this.updateGizmoRotationToMatchAttachedMesh){const t=e._isMesh||"AbstractMesh"===e.getClassName()||"TransformNode"===e.getClassName()||"InstancedMesh"===e.getClassName()?e:void 0;e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,Go.PreserveScaling?t:void 0),this._rootMesh.rotationQuaternion.normalize()}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){const t=this.gizmoLayer.utilityLayerScene.activeCamera,i=t.globalPosition;this._rootMesh.position.subtractToRef(i,W.AA.Vector3[0]);let r=this.scaleRatio;if(t.mode==rt.ORTHOGRAPHIC_CAMERA)t.orthoTop&&t.orthoBottom&&(r*=t.orthoTop-t.orthoBottom);else{const e=t.getScene().useRightHandedSystem?W.Pq.RightHandedForwardReadOnly:W.Pq.LeftHandedForwardReadOnly,i=t.getDirection(e);r*=W.Pq.Dot(W.AA.Vector3[0],i)}this._rootMesh.scaling.setAll(r),e._getWorldMatrixDeterminant()<0&&!Go.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}this.additionalTransformNode&&(this._rootMesh.computeWorldMatrix(!0),this._rootMesh.getWorldMatrix().multiplyToRef(this.additionalTransformNode.getWorldMatrix(),W.AA.Matrix[0]),W.AA.Matrix[0].decompose(this._rootMesh.scaling,this._rootMesh.rotationQuaternion,this._rootMesh.position))}_handlePivotMatrixInverse(e,t,i){if(e.isUsingPivotMatrix()&&!e.isUsingPostMultiplyPivotMatrix())return e.getPivotMatrix().invertToRef(W.AA.Matrix[5]),void W.AA.Matrix[5].multiplyToRef(t,i);i.copyFrom(t)}_matrixChanged(){if(this._attachedNode)if(this._attachedNode._isCamera){const e=this._attachedNode;let t,i;if(e.parent){const i=W.AA.Matrix[1];e.parent._worldMatrix.invertToRef(i),this._attachedNode._worldMatrix.multiplyToRef(i,W.AA.Matrix[0]),t=W.AA.Matrix[0]}else t=this._attachedNode._worldMatrix;if(e.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(t,W.AA.Matrix[1]),i=W.AA.Matrix[1]):i=t,i.decompose(W.AA.Vector3[1],W.AA.Quaternion[0],W.AA.Vector3[0]),"FreeCamera"===this._attachedNode.getClassName()||"FlyCamera"===this._attachedNode.getClassName()||"ArcFollowCamera"===this._attachedNode.getClassName()||"TargetCamera"===this._attachedNode.getClassName()||"TouchCamera"===this._attachedNode.getClassName()||"UniversalCamera"===this._attachedNode.getClassName()){const e=this._attachedNode;e.rotation=W.AA.Quaternion[0].toEulerAngles(),e.rotationQuaternion&&(e.rotationQuaternion.copyFrom(W.AA.Quaternion[0]),e.rotationQuaternion.normalize())}e.position.copyFrom(W.AA.Vector3[0])}else if(this._attachedNode._isMesh||"AbstractMesh"===this._attachedNode.getClassName()||"TransformNode"===this._attachedNode.getClassName()||"InstancedMesh"===this._attachedNode.getClassName()){const e=this._attachedNode;if(e.parent){const t=W.AA.Matrix[0],i=W.AA.Matrix[1];e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i);const r=W.AA.Matrix[4];if(this._handlePivotMatrixInverse(e,i,r),r.decompose(W.AA.Vector3[0],W.AA.Quaternion[0],e.position,Go.PreserveScaling?e:void 0,Go.UseAbsoluteScaling),W.AA.Quaternion[0].normalize(),e.isUsingPivotMatrix()){const t=W.AA.Quaternion[1];W.PT.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,t);const i=W.AA.Matrix[2];W.uq.ScalingToRef(e.scaling.x,e.scaling.y,e.scaling.z,i);const r=W.AA.Matrix[2];t.toRotationMatrix(r);const s=e.getPivotMatrix(),n=W.AA.Matrix[3];s.invertToRef(n),s.multiplyToRef(i,W.AA.Matrix[4]),W.AA.Matrix[4].multiplyToRef(r,W.AA.Matrix[5]),W.AA.Matrix[5].multiplyToRef(n,W.AA.Matrix[6]),W.AA.Matrix[6].getTranslationToRef(W.AA.Vector3[1]),e.position.subtractInPlace(W.AA.Vector3[1])}}else{const t=W.AA.Matrix[4];this._handlePivotMatrixInverse(e,this._attachedNode._worldMatrix,t),t.decompose(W.AA.Vector3[0],W.AA.Quaternion[0],e.position,Go.PreserveScaling?e:void 0,Go.UseAbsoluteScaling)}W.AA.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(W.AA.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(W.AA.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=W.AA.Quaternion[0].toEulerAngles())}else if("Bone"===this._attachedNode.getClassName()){const e=this._attachedNode,t=e.getParent();if(t){const i=W.AA.Matrix[0],r=W.AA.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,r),e.getLocalMatrix().copyFrom(r)}else e.getLocalMatrix().copyFrom(e.getFinalMatrix());e.markAsDirty()}else{const e=this._attachedNode;if(e.getTypeID){const t=e.getTypeID();if(t===$t.LIGHTTYPEID_DIRECTIONALLIGHT||t===$t.LIGHTTYPEID_SPOTLIGHT||t===$t.LIGHTTYPEID_POINTLIGHT){const t=e.parent;if(t){const i=W.AA.Matrix[0],r=W.AA.Matrix[1];t.getWorldMatrix().invertToRef(i),e.getWorldMatrix().multiplyToRef(i,r),r.decompose(void 0,W.AA.Quaternion[0],W.AA.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,W.AA.Quaternion[0],W.AA.Vector3[0]);e.position=new W.Pq(W.AA.Vector3[0].x,W.AA.Vector3[0].y,W.AA.Vector3[0].z),e.direction&&(e.direction=new W.Pq(e.direction.x,e.direction.y,e.direction.z))}}}}_setGizmoMeshMaterial(e,t){e&&e.forEach((e=>{e.material=t,e.color&&(e.color=t.diffuseColor)}))}static GizmoAxisPointerObserver(e,t){let i=!1;return e.utilityLayerScene.onPointerObservable.add((e=>{if(e.pickInfo){if(e.type===yi.Zp.POINTERMOVE){if(i)return;t.forEach((t=>{if(t.colliderMeshes&&t.gizmoMeshes){const i=-1!=t.colliderMeshes?.indexOf(e?.pickInfo?.pickedMesh),r=t.dragBehavior.enabled?i||t.active?t.hoverMaterial:t.material:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=r,e.color&&(e.color=r.diffuseColor)}))}}))}e.type===yi.Zp.POINTERDOWN&&t.has(e.pickInfo.pickedMesh?.parent)&&(i=!0,t.get(e.pickInfo.pickedMesh?.parent).active=!0,t.forEach((t=>{const i=(-1!=t.colliderMeshes?.indexOf(e?.pickInfo?.pickedMesh)||t.active)&&t.dragBehavior.enabled?t.hoverMaterial:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=i,e.color&&(e.color=i.diffuseColor)}))}))),e.type===yi.Zp.POINTERUP&&t.forEach((e=>{e.active=!1,i=!1,e.gizmoMeshes.forEach((t=>{t.material=e.dragBehavior.enabled?e.material:e.disableMaterial,t.color&&(t.color=e.material.diffuseColor)}))}))}}))}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}}Go.PreserveScaling=!1,Go.UseAbsoluteScaling=!0;class zo extends Go{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreateArrow(e,t,i=1,r=!1){const s=new Pt("arrow",e),n=No("cylinder",{diameterTop:0,height:.075,diameterBottom:.0375*(1+(i-1)/4),tessellation:96},e),o=No("cylinder",{diameterTop:.005*i,height:.275,diameterBottom:.005*i,tessellation:96},e);return n.parent=s,n.material=t,n.rotation.x=Math.PI/2,n.position.z+=.3,o.parent=s,o.material=t,o.position.z+=.1375,o.rotation.x=Math.PI/2,r&&(o.visibility=0,n.visibility=0),s}static _CreateArrowInstance(e,t){const i=new Pt("arrow",e);for(const e of t.getChildMeshes())e.createInstance(e.name).parent=i;return i}constructor(e,t=H.v9.Gray(),i=Bo.DefaultUtilityLayer,r=null,s=1,n=H.v9.Yellow(),o=H.v9.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new z.cP,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._parent=r,this._coloredMaterial=new Un("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new H.v9(.1,.1,.1)),this._hoverMaterial=new Un("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=n,this._disableMaterial=new Un("",i.utilityLayerScene),this._disableMaterial.diffuseColor=o,this._disableMaterial.alpha=.4;const a=zo._CreateArrow(i.utilityLayerScene,this._coloredMaterial,s),l=zo._CreateArrow(i.utilityLayerScene,this._coloredMaterial,s+4,!0);this._gizmoMesh=new Yt("",i.utilityLayerScene),this._gizmoMesh.addChild(a),this._gizmoMesh.addChild(l),this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._gizmoMesh.scaling.scaleInPlace(1/3),this._gizmoMesh.parent=this._rootMesh;let h=0;const c={snapDistance:0};this.dragBehavior=new Ji({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add((e=>{if(this.attachedNode){let t=!1;if(0==this.snapDistance)this.attachedNode.getWorldMatrix().getTranslationToRef(W.AA.Vector3[2]),W.AA.Vector3[2].addInPlace(e.delta),this.dragBehavior.validateDrag(W.AA.Vector3[2])&&(this.attachedNode.position&&this.attachedNode.position.addInPlaceFromFloats(e.delta.x,e.delta.y,e.delta.z),this.attachedNode.getWorldMatrix().addTranslationFromFloats(e.delta.x,e.delta.y,e.delta.z),this.attachedNode.updateCache(),t=!0);else if(h+=e.dragDistance,Math.abs(h)>this.snapDistance){const i=Math.floor(Math.abs(h)/this.snapDistance);h%=this.snapDistance,e.delta.normalizeToRef(W.AA.Vector3[1]),W.AA.Vector3[1].scaleInPlace(this.snapDistance*i),this.attachedNode.getWorldMatrix().getTranslationToRef(W.AA.Vector3[2]),W.AA.Vector3[2].addInPlace(W.AA.Vector3[1]),this.dragBehavior.validateDrag(W.AA.Vector3[2])&&(this.attachedNode.getWorldMatrix().addTranslationFromFloats(W.AA.Vector3[1].x,W.AA.Vector3[1].y,W.AA.Vector3[1].z),this.attachedNode.updateCache(),c.snapDistance=this.snapDistance*i*Math.sign(h),this.onSnapObservable.notifyObservers(c),t=!0)}t&&this._matrixChanged()}})),this.dragBehavior.onDragStartObservable.add((()=>{this._dragging=!0})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1}));const u=i._getSharedGizmoLight();u.includedOnlyMeshes=u.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const d={gizmoMeshes:a.getChildMeshes(),colliderMeshes:l.getChildMeshes(),material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(l,d),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(!this._customMeshSet&&(this._isHovered=!(-1==d.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),!this._parent)){const e=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(d.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(d.gizmoMeshes,e?d.material:d.disableMaterial)}))}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}}class Wo{get scaleLines(){return this._scaleLines}set scaleLines(e){this._scaleLines=e,this._xAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor),this._yAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor),this._zAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor)}get xAxis(){return this._xAxis}get yAxis(){return this._yAxis}get zAxis(){return this._zAxis}constructor(e,t=1,i=2,r,s,n,o=1){if(this._scaleLinesFactor=4,this._instanced=!1,this.scene=null,this._scaleLines=1,e=e||he.q.LastCreatedScene){if(!r){const t=new Un("xAxisMaterial",e);t.disableLighting=!0,t.emissiveColor=H.v9.Red().scale(.5),r=zo._CreateArrow(e,t,o)}if(!s){const t=new Un("yAxisMaterial",e);t.disableLighting=!0,t.emissiveColor=H.v9.Green().scale(.5),s=zo._CreateArrow(e,t,o)}if(!n){const t=new Un("zAxisMaterial",e);t.disableLighting=!0,t.emissiveColor=H.v9.Blue().scale(.5),n=zo._CreateArrow(e,t,o)}this._xAxis=r,this._yAxis=s,this._zAxis=n,this.scaleLines=t,null!=i&&(Wo._SetRenderingGroupId(this._xAxis,i),Wo._SetRenderingGroupId(this._yAxis,i),Wo._SetRenderingGroupId(this._zAxis,i)),this.scene=e,this.update(new W.Pq,W.Pq.Right(),W.Pq.Up(),W.Pq.Forward())}}update(e,t,i,r){this._xAxis.position.copyFrom(e),this._xAxis.setDirection(t),this._yAxis.position.copyFrom(e),this._yAxis.setDirection(i),this._zAxis.position.copyFrom(e),this._zAxis.setDirection(r)}createInstance(){const e=zo._CreateArrowInstance(this.scene,this._xAxis),t=zo._CreateArrowInstance(this.scene,this._yAxis),i=zo._CreateArrowInstance(this.scene,this._zAxis),r=new Wo(this.scene,this.scaleLines,null,e,t,i);return r._instanced=!0,r}dispose(){this._xAxis&&this._xAxis.dispose(!1,!this._instanced),this._yAxis&&this._yAxis.dispose(!1,!this._instanced),this._zAxis&&this._zAxis.dispose(!1,!this._instanced),this.scene=null}static _SetRenderingGroupId(e,t){e.getChildMeshes().forEach((e=>{e.renderingGroupId=t}))}}class Ho extends Wo{constructor(e,t,i,r=1){super(e,r),this.pos=W.Pq.Zero(),this.xaxis=W.Pq.Zero(),this.yaxis=W.Pq.Zero(),this.zaxis=W.Pq.Zero(),this.mesh=i,this.bone=t}update(){if(!this.mesh||!this.bone)return;const e=this.bone;e.getAbsolutePositionToRef(this.mesh,this.pos),e.getDirectionToRef(Mt._0.X,this.mesh,this.xaxis),e.getDirectionToRef(Mt._0.Y,this.mesh,this.yaxis),e.getDirectionToRef(Mt._0.Z,this.mesh,this.zaxis),super.update(this.pos,this.xaxis,this.yaxis,this.zaxis)}dispose(){this.mesh&&(this.mesh=null,this.bone=null,super.dispose())}}Object.defineProperty(oi.Z.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new Xo(this)),this._debugLayer},enumerable:!0,configurable:!0}),function(e){e[e.Properties=0]="Properties",e[e.Debug=1]="Debug",e[e.Statistics=2]="Statistics",e[e.Tools=3]="Tools",e[e.Settings=4]="Settings"}(Uo||(Uo={}));class Xo{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new z.cP),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new z.cP),this._onSelectionChangedObservable)}constructor(e){this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||he.q.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 e of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(e);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(const e of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(e);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}const t={...Xo.Config,...e};this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,t)}select(e,t){this.BJSINSPECTOR&&(t&&("[object String]"==Object.prototype.toString.call(t)?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))}_getGlobalInspector(){return"undefined"!=typeof INSPECTOR?INSPECTOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.Inspector?BABYLON:void 0}isVisible(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible}hide(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()}setAsActiveScene(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector._SetNewScene(this._scene)}popupSceneExplorer(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.PopupSceneExplorer()}popupInspector(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.PopupInspector()}popupEmbed(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.PopupEmbed()}show(e){return new Promise((t=>{if(void 0===this.BJSINSPECTOR){const i=e&&e.inspectorURL?e.inspectorURL:Xo.InspectorURL;Ue.S0.LoadBabylonScript(i,(()=>{this._createInspector(e),t(this)}))}else this._createInspector(e),t(this)}))}}function qo(e){let t=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23];const i=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],r=[];let s=[];const n=e.width||e.size||1,o=e.height||e.size||1,a=e.depth||e.size||1,l=e.wrap||!1;let h=void 0===e.topBaseAt?1:e.topBaseAt,c=void 0===e.bottomBaseAt?0:e.bottomBaseAt;h=(h+4)%4,c=(c+4)%4;let u=[2,0,3,1][h],d=[2,0,1,3][c],f=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-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(l){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],f=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,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 e=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],i=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const r=[17,18,19,16],s=[22,23,20,21];for(;u>0;)e.unshift(e.pop()),r.unshift(r.pop()),u--;for(;d>0;)i.unshift(i.pop()),s.unshift(s.pop()),d--;e=e.flat(),i=i.flat(),f=f.concat(e).concat(i),t.push(r[0],r[2],r[3],r[0],r[1],r[2]),t.push(s[0],s[2],s[3],s[0],s[1],s[2])}const p=[n/2,o/2,a/2];s=f.reduce(((e,t,i)=>e.concat(t*p[i%3])),[]);const _=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE,m=e.faceUV||new Array(6),g=e.faceColors,v=[];for(let e=0;e<6;e++)void 0===m[e]&&(m[e]=new W.IU(0,0,1,1)),g&&void 0===g[e]&&(g[e]=new H.ov(1,1,1,1));for(let e=0;e<6;e++)if(r.push(m[e].z,Tt.rX?1-m[e].w:m[e].w),r.push(m[e].x,Tt.rX?1-m[e].w:m[e].w),r.push(m[e].x,Tt.rX?1-m[e].y:m[e].y),r.push(m[e].z,Tt.rX?1-m[e].y:m[e].y),g)for(let t=0;t<4;t++)v.push(g[e].r,g[e].g,g[e].b,g[e].a);bt._ComputeSides(_,s,t,i,r,e.frontUVs,e.backUVs);const x=new bt;if(x.indices=t,x.positions=s,x.normals=i,x.uvs=r,g){const e=_===bt.DOUBLESIDE?v.concat(v):v;x.colors=e}return x}function Yo(e){const t=e.width||e.size||1,i=e.height||e.size||1,r=e.depth||e.size||1,s=0|(e.widthSegments||e.segments||1),n=0|(e.heightSegments||e.segments||1),o=0|(e.depthSegments||e.segments||1),a=new W.uq,l=new W.uq,h=new W.uq,c=Jn({width:t,height:r,subdivisionsX:s,subdivisionsY:o});W.uq.TranslationToRef(0,-i/2,0,l),W.uq.RotationZToRef(Math.PI,a),a.multiplyToRef(l,h),c.transform(h);const u=Jn({width:t,height:r,subdivisionsX:s,subdivisionsY:o});W.uq.TranslationToRef(0,i/2,0,h),u.transform(h);const d=Jn({width:i,height:r,subdivisionsX:n,subdivisionsY:o});W.uq.TranslationToRef(-t/2,0,0,l),W.uq.RotationZToRef(Math.PI/2,a),a.multiplyToRef(l,h),d.transform(h);const f=Jn({width:i,height:r,subdivisionsX:n,subdivisionsY:o});W.uq.TranslationToRef(t/2,0,0,l),W.uq.RotationZToRef(-Math.PI/2,a),a.multiplyToRef(l,h),f.transform(h);const p=Jn({width:t,height:i,subdivisionsX:s,subdivisionsY:n});W.uq.TranslationToRef(0,0,-r/2,l),W.uq.RotationXToRef(-Math.PI/2,a),a.multiplyToRef(l,h),p.transform(h);const _=Jn({width:t,height:i,subdivisionsX:s,subdivisionsY:n});return W.uq.TranslationToRef(0,0,r/2,l),W.uq.RotationXToRef(Math.PI/2,a),a.multiplyToRef(l,h),_.transform(h),c.merge([u,f,d,p,_],!0),c}function Ko(e,t={},i=null){const r=new Yt(e,i);return t.sideOrientation=Yt._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,qo(t).applyToMesh(r,t.updatable),r}Xo.InspectorURL=`${Ue.S0._DefaultCdnUrl}/v${Ot.$.Version}/inspector/babylon.inspector.bundle.js`,Xo.Config={overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0};const jo={CreateBox:Ko};function $o(e){const t=0|(e.segments||32),i=e.diameterX||e.diameter||1,r=e.diameterY||e.diameter||1,s=e.diameterZ||e.diameter||1,n=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,o=e.slice&&e.slice<=0?1:e.slice||1,a=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE,l=!!e.dedupTopBottomIndices,h=new W.Pq(i/2,r/2,s/2),c=2+t,u=2*c,d=[],f=[],p=[],_=[];for(let e=0;e<=c;e++){const t=e/c,i=t*Math.PI*o;for(let e=0;e<=u;e++){const r=e/u,s=r*Math.PI*2*n,o=W.uq.RotationZ(-i),a=W.uq.RotationY(s),l=W.Pq.TransformCoordinates(W.Pq.Up(),o),c=W.Pq.TransformCoordinates(l,a),d=c.multiply(h),m=c.divide(h).normalize();f.push(d.x,d.y,d.z),p.push(m.x,m.y,m.z),_.push(r,Tt.rX?1-t:t)}if(e>0){const t=f.length/3;for(let i=t-2*(u+1);i+u+21&&(d.push(i),d.push(i+1),d.push(i+u+1)),(eKo(e,{size:t,sideOrientation:s,updatable:r},i);const Zo={CreateSphere:Qo};bt.CreateSphere=$o,Yt.CreateSphere=(e,t,i,r,s,n)=>Qo(e,{segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:n,updatable:s},r);class Jo{constructor(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}get physicsJoint(){return this._physicsJoint}set physicsJoint(e){this._physicsJoint=e}set physicsPlugin(e){this._physicsPlugin=e}executeNativeFunction(e){e(this._physicsPlugin.world,this._physicsJoint)}}Jo.DistanceJoint=0,Jo.HingeJoint=1,Jo.BallAndSocketJoint=2,Jo.WheelJoint=3,Jo.SliderJoint=4,Jo.PrismaticJoint=5,Jo.UniversalJoint=6,Jo.Hinge2Joint=Jo.WheelJoint,Jo.PointToPointJoint=8,Jo.SpringJoint=9,Jo.LockJoint=10;class ea extends Jo{constructor(e){super(Jo.DistanceJoint,e)}updateDistance(e,t){this._physicsPlugin.updateDistanceJoint(this,e,t)}}class ta extends Jo{constructor(e,t){super(e,t)}setMotor(e,t){this._physicsPlugin.setMotor(this,e||0,t)}setLimit(e,t){this._physicsPlugin.setLimit(this,e,t)}}class ia extends ta{constructor(e){super(Jo.HingeJoint,e)}setMotor(e,t){this._physicsPlugin.setMotor(this,e||0,t)}setLimit(e,t){this._physicsPlugin.setLimit(this,e,t)}}class ra extends ta{constructor(e){super(Jo.Hinge2Joint,e)}setMotor(e,t,i=0){this._physicsPlugin.setMotor(this,e||0,t,i)}setLimit(e,t,i=0){this._physicsPlugin.setLimit(this,e,t,i)}}Yt._PhysicsImpostorParser=function(e,t,i){return new sa(t,i.physicsImpostor,{mass:i.physicsMass,friction:i.physicsFriction,restitution:i.physicsRestitution},e)};class sa{get isDisposed(){return this._isDisposed}get mass(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0}set mass(e){this.setMass(e)}get friction(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0}set friction(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,e)}get restitution(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0}set restitution(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,e)}get pressure(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0}set pressure(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}get stiffness(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0}set stiffness(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}get velocityIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0}set velocityIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}get positionIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0}set positionIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}constructor(e,t,i={mass:0},r){this.object=e,this.type=t,this._options=i,this._scene=r,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=W.Pq.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new W.PT,this._tmpQuat2=new W.PT,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 W.PT),this._options.disableBidirectionalTransformation||this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach((e=>{e(this)})))},this.afterStep=()=>{this._physicsEngine&&(this._onAfterPhysicsStepCallbacks.forEach((e=>{e(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,sa._TmpVecs[0]),this.object.translate(sa._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=e=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent)return;if(!this._physicsEngine)return;const t=this._physicsEngine.getImpostorWithPhysicsBody(e.body);t&&(this.onCollideEvent&&this.onCollideEvent(this,t),this._onPhysicsCollideCallbacks.filter((e=>-1!==e.otherImpostors.indexOf(t))).forEach((i=>{i.callback(this,t,e.point,e.distance,e.impulse,e.normal)})))},this.object?(this.object.parent&&0!==i.mass&&Z.V.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=W.PT.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new W.PT),this._options.mass=void 0===i.mass?0:i.mass,this._options.friction=void 0===i.friction?.2:i.friction,this._options.restitution=void 0===i.restitution?.2:i.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=void 0===i.pressure?200:i.pressure,this._options.stiffness=void 0===i.stiffness?1:i.stiffness,this._options.velocityIterations=void 0===i.velocityIterations?20:i.velocityIterations,this._options.positionIterations=void 0===i.positionIterations?20:i.positionIterations,this._options.fixedPoints=void 0===i.fixedPoints?0:i.fixedPoints,this._options.margin=void 0===i.margin?0:i.margin,this._options.damping=void 0===i.damping?0:i.damping,this._options.path=void 0===i.path?null:i.path,this._options.shape=void 0===i.shape?null:i.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&Z.V.Warn("You must affect impostors to children before affecting impostor to parent.")):Z.V.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))):Z.V.Error("No object was provided. A physics object is obligatory")}_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 Nt?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=sa.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}return sa.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):W.Pq.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):W.Pq.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):Z.V.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):Z.V.Warn("Function to remove was not found")}registerOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})}unregisterOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];let r=-1;this._onPhysicsCollideCallbacks.some(((e,s)=>{if(e.callback===t&&e.otherImpostors.length===i.length){const t=e.otherImpostors.every((e=>i.indexOf(e)>-1));return t&&(r=s),t}return!1}))?this._onPhysicsCollideCallbacks.splice(r,1):Z.V.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):W.PT.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),e=e.parent;return this._tmpQuat}applyForce(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this}applyImpulse(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this}createJoint(e,t,i){const r=new Jo(t,i);return this.addJoint(e,r),this}addJoint(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this}addAnchor(e,t,i,r,s){if(!this._physicsEngine)return this;const n=this._physicsEngine.getPhysicsPlugin();return n.appendAnchor?(this._physicsEngine&&n.appendAnchor(this,e,t,i,r,s),this):this}addHook(e,t,i,r){if(!this._physicsEngine)return this;const s=this._physicsEngine.getPhysicsPlugin();return s.appendAnchor?(this._physicsEngine&&s.appendHook(this,e,t,i,r),this):this}sleep(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this}wakeUp(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this}clone(e){return e?new sa(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 W.PT),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()}getBoxSizeToRef(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this}getRadius(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0}syncBoneWithImpostor(e,t,i,r,s){const n=sa._TmpVecs[0],o=this.object;if(o.rotationQuaternion)if(s){const i=sa._TmpQuat;o.rotationQuaternion.multiplyToRef(s,i),e.setRotationQuaternion(i,1,t)}else e.setRotationQuaternion(o.rotationQuaternion,1,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),null==r&&(r=i.length()),n.x*=r,n.y*=r,n.z*=r),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,r,s,n){const o=this.object;if(o.rotationQuaternion)if(s){const i=sa._TmpQuat;e.getRotationQuaternionToRef(1,t,i),i.multiplyToRef(s,o.rotationQuaternion)}else e.getRotationQuaternionToRef(1,t,o.rotationQuaternion);const a=sa._TmpVecs[0],l=sa._TmpVecs[1];n||((n=sa._TmpVecs[2]).x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,l),e.getAbsolutePositionToRef(t,a),null==r&&i&&(r=i.length()),null!=r&&(a.x+=l.x*r,a.y+=l.y*r,a.z+=l.z*r),o.setAbsolutePosition(a)}}function na(e={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const t=0|Math.max(e.subdivisions?e.subdivisions:2,1),i=0|Math.max(e.tessellation?e.tessellation:16,3),r=Math.max(e.height?e.height:1,0),s=Math.max(e.radius?e.radius:.25,0),n=0|Math.max(e.capSubdivisions?e.capSubdivisions:6,1),o=i,a=t,l=Math.max(e.radiusTop?e.radiusTop:s,0),h=Math.max(e.radiusBottom?e.radiusBottom:s,0),c=r-(l+h),u=2*Math.PI,d=Math.max(e.topCapSubdivisions?e.topCapSubdivisions:n,1),f=Math.max(e.bottomCapSubdivisions?e.bottomCapSubdivisions:n,1),p=Math.acos((h-l)/r);let _=[];const m=[],g=[],v=[];let x=0;const b=[],S=.5*c,T=.5*Math.PI;let C,y;const E=W.Pq.Zero(),P=W.Pq.Zero(),A=Math.cos(p),R=Math.sin(p),I=new W.I9(l*R,S+l*A).subtract(new W.I9(h*R,h*A-S)).length(),M=l*p+I+h*(T-p);let O=0;for(y=0;y<=d;y++){const e=[],t=T-p*(y/d);O+=l*p/d;const i=Math.cos(t),r=Math.sin(t),s=i*l;for(C=0;C<=o;C++){const t=C/o,n=t*u+0,a=Math.sin(n),h=Math.cos(n);P.x=s*a,P.y=S+r*l,P.z=s*h,m.push(P.x,P.y,P.z),E.set(i*a,r,i*h),g.push(E.x,E.y,E.z),v.push(t,Tt.rX?O/M:1-O/M),e.push(x),x++}b.push(e)}const D=r-l-h+A*l-A*h,w=R*(h-l)/D;for(y=1;y<=a;y++){const e=[];O+=I/a;const t=R*(y*(h-l)/a+l);for(C=0;C<=o;C++){const i=C/o,r=i*u+0,s=Math.sin(r),n=Math.cos(r);P.x=t*s,P.y=S+A*l-y*D/a,P.z=t*n,m.push(P.x,P.y,P.z),E.set(s,w,n).normalize(),g.push(E.x,E.y,E.z),v.push(i,Tt.rX?O/M:1-O/M),e.push(x),x++}b.push(e)}for(y=1;y<=f;y++){const e=[],t=T-p-(Math.PI-p)*(y/f);O+=h*p/f;const i=Math.cos(t),r=Math.sin(t),s=i*h;for(C=0;C<=o;C++){const t=C/o,n=t*u+0,a=Math.sin(n),l=Math.cos(n);P.x=s*a,P.y=r*h-S,P.z=s*l,m.push(P.x,P.y,P.z),E.set(i*a,r,i*l),g.push(E.x,E.y,E.z),v.push(t,Tt.rX?O/M:1-O/M),e.push(x),x++}b.push(e)}for(C=0;Cn?n:Math.floor(o);const a=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE,l=e.uvs,h=e.colors,c=[],u=[],d=[],f=[],p=[],_=[],m=[],g=[];let v;const x=[],b=[];let S,T,C;if(t.length<2){const e=[],i=[];for(T=0;T0&&(I=A[C].subtract(A[C-1]).length(),M=I+m[S],p[S].push(M),m[S]=M),C++;r&&(C--,c.push(A[0].x,A[0].y,A[0].z),I=A[C].subtract(A[0]).length(),M=I+m[S],p[S].push(M),m[S]=M),x[S]=R+E,b[S]=y,y+=R+E}let w,N,F=null,L=null;for(T=0;T{let s=r[0].length;const n=a;let o=0;const l=n._originalBuilderSideOrientation===Yt.DOUBLESIDE?2:1;for(let a=1;a<=l;++a)for(let a=0;aoa(e,t,i),bt.CreateCapsule=na;const ca={CreateRibbon:ha};function ua(e){const t=[],i=[],r=[],s=[],n=e.radius||.5,o=e.tessellation||64,a=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,l=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE;t.push(0,0,0),s.push(.5,.5);const h=2*Math.PI*a,c=1===a?h/o:h/(o-1);let u=0;for(let e=0;eha(e,{pathArray:t,closeArray:i,closePath:r,offset:s,updatable:o,sideOrientation:a,instance:l},n);const fa={CreateDisc:da};function pa(e){const t=e.pattern||Yt.NO_FLIP,i=e.tileWidth||e.tileSize||1,r=e.tileHeight||e.tileSize||1,s=e.alignHorizontal||0,n=e.alignVertical||0,o=e.width||e.size||1,a=Math.floor(o/i);let l=o-a*i;const h=e.height||e.size||1,c=Math.floor(h/r);let u=h-c*r;const d=i*a/2,f=r*c/2;let p=0,_=0,m=0,g=0,v=0,x=0;if(l>0||u>0){switch(m=-d,g=-f,v=d,x=f,s){case Yt.CENTER:l/=2,m-=l,v+=l;break;case Yt.LEFT:v+=l,p=-l/2;break;case Yt.RIGHT:m-=l,p=l/2}switch(n){case Yt.CENTER:u/=2,g-=u,x+=u;break;case Yt.BOTTOM:x+=u,_=-u/2;break;case Yt.TOP:g-=u,_=u/2}}const b=[],S=[],T=[];T[0]=[0,0,1,0,1,1,0,1],T[1]=[0,0,1,0,1,1,0,1],t!==Yt.ROTATE_TILE&&t!==Yt.ROTATE_ROW||(T[1]=[1,1,0,1,0,0,1,0]),t!==Yt.FLIP_TILE&&t!==Yt.FLIP_ROW||(T[1]=[1,0,0,0,0,1,1,1]),t!==Yt.FLIP_N_ROTATE_TILE&&t!==Yt.FLIP_N_ROTATE_ROW||(T[1]=[0,1,1,1,1,0,0,0]);let C=[];const y=[],E=[];let P=0;for(let e=0;e0||u>0){const e=u>0&&(n===Yt.CENTER||n===Yt.TOP),o=u>0&&(n===Yt.CENTER||n===Yt.BOTTOM),h=l>0&&(s===Yt.CENTER||s===Yt.RIGHT),T=l>0&&(s===Yt.CENTER||s===Yt.LEFT);let A,R,I,M,O=[];if(e&&h&&(b.push(m+p,g+_,0),b.push(-d+p,g+_,0),b.push(-d+p,g+u+_,0),b.push(m+p,g+u+_,0),E.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,A=1-l/i,R=1-u/r,I=1,M=1,O=[A,R,I,R,I,M,A,M],t===Yt.ROTATE_ROW&&(O=[1-A,1-R,1-I,1-R,1-I,1-M,1-A,1-M]),t===Yt.FLIP_ROW&&(O=[1-A,R,1-I,R,1-I,M,1-A,M]),t===Yt.FLIP_N_ROTATE_ROW&&(O=[A,1-R,I,1-R,I,1-M,A,1-M]),C=C.concat(O),y.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),e&&T&&(b.push(d+p,g+_,0),b.push(v+p,g+_,0),b.push(v+p,g+u+_,0),b.push(d+p,g+u+_,0),E.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,A=0,R=1-u/r,I=l/i,M=1,O=[A,R,I,R,I,M,A,M],(t===Yt.ROTATE_ROW||t===Yt.ROTATE_TILE&&a%2==0)&&(O=[1-A,1-R,1-I,1-R,1-I,1-M,1-A,1-M]),(t===Yt.FLIP_ROW||t===Yt.FLIP_TILE&&a%2==0)&&(O=[1-A,R,1-I,R,1-I,M,1-A,M]),(t===Yt.FLIP_N_ROTATE_ROW||t===Yt.FLIP_N_ROTATE_TILE&&a%2==0)&&(O=[A,1-R,I,1-R,I,1-M,A,1-M]),C=C.concat(O),y.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),o&&h&&(b.push(m+p,f+_,0),b.push(-d+p,f+_,0),b.push(-d+p,x+_,0),b.push(m+p,x+_,0),E.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,A=1-l/i,R=0,I=1,M=u/r,O=[A,R,I,R,I,M,A,M],(t===Yt.ROTATE_ROW&&c%2==1||t===Yt.ROTATE_TILE&&c%1==0)&&(O=[1-A,1-R,1-I,1-R,1-I,1-M,1-A,1-M]),(t===Yt.FLIP_ROW&&c%2==1||t===Yt.FLIP_TILE&&c%2==0)&&(O=[1-A,R,1-I,R,1-I,M,1-A,M]),(t===Yt.FLIP_N_ROTATE_ROW&&c%2==1||t===Yt.FLIP_N_ROTATE_TILE&&c%2==0)&&(O=[A,1-R,I,1-R,I,1-M,A,1-M]),C=C.concat(O),y.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),o&&T&&(b.push(d+p,f+_,0),b.push(v+p,f+_,0),b.push(v+p,x+_,0),b.push(d+p,x+_,0),E.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,A=0,R=0,I=l/i,M=u/r,O=[A,R,I,R,I,M,A,M],(t===Yt.ROTATE_ROW&&c%2==1||t===Yt.ROTATE_TILE&&(c+a)%2==1)&&(O=[1-A,1-R,1-I,1-R,1-I,1-M,1-A,1-M]),(t===Yt.FLIP_ROW&&c%2==1||t===Yt.FLIP_TILE&&(c+a)%2==1)&&(O=[1-A,R,1-I,R,1-I,M,1-A,M]),(t===Yt.FLIP_N_ROTATE_ROW&&c%2==1||t===Yt.FLIP_N_ROTATE_TILE&&(c+a)%2==1)&&(O=[A,1-R,I,1-R,I,1-M,A,1-M]),C=C.concat(O),y.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),e){const e=[];A=0,R=1-u/r,I=1,M=1,e[0]=[A,R,I,R,I,M,A,M],e[1]=[A,R,I,R,I,M,A,M],t!==Yt.ROTATE_TILE&&t!==Yt.ROTATE_ROW||(e[1]=[1-A,1-R,1-I,1-R,1-I,1-M,1-A,1-M]),t!==Yt.FLIP_TILE&&t!==Yt.FLIP_ROW||(e[1]=[1-A,R,1-I,R,1-I,M,1-A,M]),t!==Yt.FLIP_N_ROTATE_TILE&&t!==Yt.FLIP_N_ROTATE_ROW||(e[1]=[A,1-R,I,1-R,I,1-M,A,1-M]);for(let r=0;rda(e,{radius:t,tessellation:i,sideOrientation:n,updatable:s},r);const ma={CreateTiledPlane:_a};function ga(e){const t=e.faceUV||new Array(6),i=e.faceColors,r=e.pattern||Yt.NO_FLIP,s=e.width||e.size||1,n=e.height||e.size||1,o=e.depth||e.size||1,a=e.tileWidth||e.tileSize||1,l=e.tileHeight||e.tileSize||1,h=e.alignHorizontal||0,c=e.alignVertical||0,u=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE;for(let e=0;e<6;e++)void 0===t[e]&&(t[e]=new W.IU(0,0,1,1)),i&&void 0===i[e]&&(i[e]=new H.ov(1,1,1,1));const d=s/2,f=n/2,p=o/2,_=[];for(let e=0;e<2;e++)_[e]=pa({pattern:r,tileWidth:a,tileHeight:l,width:s,height:n,alignVertical:c,alignHorizontal:h,sideOrientation:u});for(let e=2;e<4;e++)_[e]=pa({pattern:r,tileWidth:a,tileHeight:l,width:o,height:n,alignVertical:c,alignHorizontal:h,sideOrientation:u});let m=c;c===Yt.BOTTOM?m=Yt.TOP:c===Yt.TOP&&(m=Yt.BOTTOM);for(let e=4;e<6;e++)_[e]=pa({pattern:r,tileWidth:a,tileHeight:l,width:s,height:o,alignVertical:m,alignHorizontal:h,sideOrientation:u});let g=[],v=[],x=[],b=[];const S=[],T=[],C=[],y=[];let E=0,P=0;for(let e=0;e<6;e++){const r=_[e].positions.length;T[e]=[],C[e]=[];for(let t=0;te+P))),P+=T[e].length,i)for(let t=0;t<4;t++)S.push(i[e].r,i[e].g,i[e].b,i[e].a)}const A=new W.Pq(0,0,p),R=W.uq.RotationY(Math.PI);g=T[0].map((e=>W.Pq.TransformNormal(e,R).add(A))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),v=C[0].map((e=>W.Pq.TransformNormal(e,R))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),g=g.concat(T[1].map((e=>e.subtract(A))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(C[1].map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const I=new W.Pq(d,0,0),M=W.uq.RotationY(-Math.PI/2);g=g.concat(T[2].map((e=>W.Pq.TransformNormal(e,M).add(I))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(C[2].map((e=>W.Pq.TransformNormal(e,M))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const O=W.uq.RotationY(Math.PI/2);g=g.concat(T[3].map((e=>W.Pq.TransformNormal(e,O).subtract(I))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(C[3].map((e=>W.Pq.TransformNormal(e,O))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const D=new W.Pq(0,f,0),w=W.uq.RotationX(Math.PI/2);g=g.concat(T[4].map((e=>W.Pq.TransformNormal(e,w).add(D))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(C[4].map((e=>W.Pq.TransformNormal(e,w))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const N=W.uq.RotationX(-Math.PI/2);g=g.concat(T[5].map((e=>W.Pq.TransformNormal(e,N).subtract(D))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(C[5].map((e=>W.Pq.TransformNormal(e,N))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),bt._ComputeSides(u,g,b,v,x);const F=new bt;if(F.indices=b,F.positions=g,F.normals=v,F.uvs=x,i){const e=u===bt.DOUBLESIDE?S.concat(S):S;F.colors=e}return F}function va(e,t,i=null){const r=new Yt(e,i);return t.sideOrientation=Yt._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,ga(t).applyToMesh(r,t.updatable),r}bt.CreateTiledPlane=pa;const xa={CreateTiledBox:va};function ba(e){const t=[],i=[],r=[],s=[],n=e.radius||2,o=e.tube||.5,a=e.radialSegments||32,l=e.tubularSegments||32,h=e.p||2,c=e.q||3,u=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE,d=e=>{const t=Math.cos(e),i=Math.sin(e),r=c/h*e,s=Math.cos(r),o=n*(2+s)*.5*t,a=n*(2+s)*i*.5,l=n*Math.sin(r)*.5;return new W.Pq(o,a,l)};let f,p;for(f=0;f<=a;f++){const e=f%a/a*2*h*Math.PI,t=d(e),r=d(e+.01),n=r.subtract(t);let c=r.add(t);const u=W.Pq.Cross(n,c);for(c=W.Pq.Cross(u,n),u.normalize(),c.normalize(),p=0;pSa(e,{radius:t,tube:i,radialSegments:r,tubularSegments:s,p:n,q:o,sideOrientation:h,updatable:l},a),Yt._LinesMeshParser=(e,t)=>Ca.Parse(e,t);class Ca extends Yt{_isShaderMaterial(e){return"ShaderMaterial"===e.getClassName()}constructor(e,t=null,r=null,s=null,n,o,a,l){super(e,t,r,s,n),this.useVertexColor=o,this.useVertexAlpha=a,this.color=new H.v9(1,1,1),this.alpha=1,this._shaderLanguage=0,s&&(this.color=s.color.clone(),this.alpha=s.alpha,this.useVertexColor=s.useVertexColor,this.useVertexAlpha=s.useVertexAlpha),this.intersectionThreshold=.1;const h={attributes:[st.R.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:[],useClipPlane:null,shaderLanguage:0};!1===a?h.needAlphaBlending=!1:h.defines.push("#define VERTEXALPHA"),o?(h.defines.push("#define VERTEXCOLOR"),h.attributes.push(st.R.ColorKind)):(h.uniforms.push("color"),this._color4=new H.ov),l?this.material=l:(this.getScene().getEngine().isWebGPU&&!Ca.ForceGLSL&&(this._shaderLanguage=1),h.shaderLanguage=this._shaderLanguage,h.extraInitializationsAsync=async()=>{1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,88130)),Promise.resolve().then(i.bind(i,88516))]):await Promise.all([Promise.resolve().then(i.bind(i,53501)),Promise.resolve().then(i.bind(i,27683))])},this.material=new xo("colorShader",this.getScene(),"color",h,!1),this.material.doNotSerialize=!0)}isReady(){return!!this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage||this.hasThinInstances)&&super.isReady()}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=Vt.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:e,g:t,b:i}=this.color;this._color4.set(e,t,i,this.alpha),this._lineMaterial.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const r=this.getScene().getEngine();return this._unIndexed?r.drawArraysType(Vt.LineListDrawMode,e.verticesStart,e.verticesCount,i):r.drawElementsType(Vt.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 Ca(e,this.getScene(),t,this,i)}createInstance(e){const t=new ya(e,this);if(this.instancedBuffers){t.instancedBuffers={};for(const e in this.instancedBuffers)t.instancedBuffers[e]=this.instancedBuffers[e]}return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){const i=new Ca(e.name,t);return i.color=H.v9.FromArray(e.color),i.alpha=e.alpha,i}}Ca.ForceGLSL=!1;class ya extends Kt{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function Ea(e){const t=[],i=[],r=e.lines,s=e.colors,n=[];let o=0;for(let e=0;e0&&(t.push(o-1),t.push(o)),o++}}const a=new bt;return a.indices=t,a.positions=i,s&&(a.colors=n),a}function Pa(e){const t=e.dashSize||3,i=e.gapSize||1,r=e.dashNb||200,s=e.points,n=[],o=[],a=W.Pq.Zero();let l=0,h=0,c=0,u=0,d=0,f=0,p=0;for(p=0;p{const t=W.Pq.Zero(),i=e.length/6;let n=0,o=0,a=0,l=0,h=0,c=0,u=0,d=0;for(u=0;uRa(e,{points:t,updatable:r,instance:s},i),Yt.CreateDashedLines=(e,t,i,r,s,n=null,o,a)=>Ia(e,{points:t,dashSize:i,gapSize:r,dashNb:s,updatable:o,instance:a},n);class Oa extends W.I9{constructor(e,t){super(e.x,e.y),this.index=t}}class Da{constructor(){this.elements=[]}add(e){const t=[];return e.forEach((e=>{const i=new Oa(e,this.elements.length);t.push(i),this.elements.push(i)})),t}computeBounds(){const e=new W.I9(this.elements[0].x,this.elements[0].y),t=new W.I9(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 wa{static Rectangle(e,t,i,r){return[new W.I9(e,t),new W.I9(i,t),new W.I9(i,r),new W.I9(e,r)]}static Circle(e,t=0,i=0,r=32){const s=[];let n=0;const o=2*Math.PI/r;for(let a=0;a!isNaN(e)));let i;const r=[];for(i=0;i<(2147483646&t.length);i+=2)r.push(new W.I9(t[i],t[i+1]));return r}static StartingAt(e,t){return ve.Cu.StartingAt(e,t)}}class Na{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,r=earcut){let s;this._points=new Da,this._outlinepoints=new Da,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=r,this._name=e,this._scene=i||he.q.LastCreatedScene,s=t instanceof ve.Cu?t.getPoints():t,this._addToepoint(s),this._points.add(s),this._outlinepoints.add(s),void 0===this.bjsEarcut&&Z.V.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new Da;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){const r=new Yt(this._name,this._scene),s=this.buildVertexData(t,i);return r.setVerticesData(st.R.PositionKind,s.positions,e),r.setVerticesData(st.R.NormalKind,s.normals,e),r.setVerticesData(st.R.UVKind,s.uvs,e),r.setIndices(s.indices),r}buildVertexData(e=0,t=2){const i=new bt,r=[],s=[],n=[],o=this._points.computeBounds();this._points.elements.forEach((e=>{r.push(0,1,0),s.push(e.x,0,e.y),n.push((e.x-o.min.x)/o.width,(e.y-o.min.y)/o.height)}));const a=[],l=this.bjsEarcut(this._epoints,this._eholes,2);for(let e=0;e0){const i=s.length/3;this._points.elements.forEach((t=>{r.push(0,-1,0),s.push(t.x,-e,t.y),n.push(1-(t.x-o.min.x)/o.width,1-(t.y-o.min.y)/o.height)}));const l=a.length;for(let e=0;e{this._addSide(s,r,n,a,o,i,e,!0,t)}))}return i.indices=a,i.positions=s,i.normals=r,i.uvs=n,i}_addSide(e,t,i,r,s,n,o,a,l){let h=e.length/3,c=0;for(let u=0;ul?Tl?C1),o=t.rotationFunction||(()=>0),a=t.closePath||t.ribbonCloseArray||!1,l=t.closeShape||t.ribbonClosePath||!1,h=0===t.cap?0:t.cap||Yt.NO_CAP,c=t.updatable,u=t.firstNormal||null,d=t.adjustFrame||!1;return Ga(e,s,r,null,null,n,o,a,l,h,!0,i,!!c,Yt._GetDefaultSideOrientation(t.sideOrientation),t.instance||null,t.invertUV||!1,t.frontUVs||null,t.backUVs||null,u,d)}function Ga(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m,g,v,x){const b=(e,t,i,r,s,n,o,a,l,h,c)=>{const u=i.getTangents(),d=i.getNormals(),f=i.getBinormals(),p=i.getDistances();if(c)for(let e=0;e0){let t=u[e-1];W.Pq.Dot(t,u[e])<0&&u[e].scaleInPlace(-1),t=d[e-1],W.Pq.Dot(t,d[e])<0&&d[e].scaleInPlace(-1),t=f[e-1],W.Pq.Dot(t,f[e])<0&&f[e].scaleInPlace(-1)}let _=0;const m=h&&a?a:()=>null!==n?n:0,g=h&&o?o:()=>null!==s?s:1;let v=l===Yt.NO_CAP||l===Yt.CAP_END?0:2;const x=W.AA.Matrix[0];for(let i=0;i{const t=Array(),i=W.Pq.Zero();let r;for(r=0;r3?0:h,c,x);const C=ha(e,{pathArray:T,closeArray:a,closePath:l,updatable:d,sideOrientation:f,invertUV:_,frontUVs:m||void 0,backUVs:g||void 0},u);return C._creationDataStorage.pathArray=T,C._creationDataStorage.path3D=S,C._creationDataStorage.cap=h,C}bt.CreatePolygon=Fa,Yt.CreatePolygon=(e,t,i,r,s,n,o=earcut)=>La(e,{shape:t,holes:r,updatable:s,sideOrientation:n},i,o),Yt.ExtrudePolygon=(e,t,i,r,s,n,o,a=earcut)=>Ba(e,{shape:t,holes:s,depth:i,updatable:n,sideOrientation:o},r,a);const za={ExtrudeShape:ka,ExtrudeShapeCustom:Ua};function Wa(e,t,i=null){const r=t.arc?t.arc<=0||t.arc>1?1:t.arc:1,s=void 0===t.closed||t.closed,n=t.shape,o=t.radius||1,a=t.tessellation||64,l=t.clip||0,h=t.updatable,c=Yt._GetDefaultSideOrientation(t.sideOrientation),u=t.cap||Yt.NO_CAP,d=2*Math.PI,f=[],p=t.invertUV||!1;let _=0,m=0;const g=d/a*r;let v,x;for(_=0;_<=a-l;_++){for(x=[],u!=Yt.CAP_START&&u!=Yt.CAP_ALL||(x.push(new W.Pq(0,n[0].y,0)),x.push(new W.Pq(Math.cos(_*g)*n[0].x*o,n[0].y,Math.sin(_*g)*n[0].x*o))),m=0;mka(e,{shape:t,path:i,scale:r,rotation:s,cap:0===n?0:n||Yt.NO_CAP,sideOrientation:l,instance:h,updatable:a},o),Yt.ExtrudeShapeCustom=(e,t,i,r,s,n,o,a,l,h,c,u)=>Ua(e,{shape:t,path:i,scaleFunction:r,rotationFunction:s,ribbonCloseArray:n,ribbonClosePath:o,cap:0===a?0:a||Yt.NO_CAP,sideOrientation:c,instance:u,updatable:h},l);const Ha={CreateLathe:Wa};function Xa(e,t,i=null){const r=t.path;let s=t.instance,n=1;void 0!==t.radius?n=t.radius:s&&(n=s._creationDataStorage.radius);const o=t.tessellation||64,a=t.radiusFunction||null;let l=t.cap||Yt.NO_CAP;const h=t.invertUV||!1,c=t.updatable,u=Yt._GetDefaultSideOrientation(t.sideOrientation);t.arc=t.arc&&(t.arc<=0||t.arc>1)?1:t.arc||1;const d=(e,t,i,r,s,n,o,a)=>{const l=t.getTangents(),h=t.getNormals(),c=t.getDistances(),u=2*Math.PI/s*a,d=n||(()=>r);let f,p,_,m;const g=W.AA.Matrix[0];let v=o===Yt.NO_CAP||o===Yt.CAP_END?0:2;for(let t=0;t{const r=Array();for(let s=0;s3?0:l,p=d(r,f,new Array,n,o,a,l,t.arc);const _=ha(e,{pathArray:p,closePath:!0,closeArray:!1,updatable:c,sideOrientation:u,invertUV:h,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return _._creationDataStorage.pathArray=p,_._creationDataStorage.path3D=f,_._creationDataStorage.tessellation=o,_._creationDataStorage.cap=l,_._creationDataStorage.arc=t.arc,_._creationDataStorage.radius=n,_}Yt.CreateLathe=(e,t,i,r,s,n,o)=>Wa(e,{shape:t,radius:i,tessellation:r,sideOrientation:o,updatable:n},s);const qa={CreateTube:Xa};function Ya(e){const t=[];t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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]]},t[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 i=e.type&&(e.type<0||e.type>=t.length)?0:e.type||0,r=e.size,s=e.sizeX||r||1,n=e.sizeY||r||1,o=e.sizeZ||r||1,a=e.custom||t[i],l=a.face.length,h=e.faceUV||new Array(l),c=e.faceColors,u=void 0===e.flat||e.flat,d=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE,f=[],p=[],_=[],m=[],g=[];let v=0,x=0;const b=[];let S,T,C,y,E,P,A=0,R=0;if(u)for(R=0;RXa(e,{path:t,radius:i,tessellation:r,radiusFunction:s,arc:1,cap:n,updatable:a,sideOrientation:l,instance:h},o);const ja={CreatePolyhedron:Ka};function $a(e){const t=e.sideOrientation||bt.DEFAULTSIDE,i=e.radius||1,r=void 0===e.flat||e.flat,s=0|(e.subdivisions||4),n=e.radiusX||i,o=e.radiusY||i,a=e.radiusZ||i,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=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],p=[],_=[],m=[],g=[];let v=0;const x=new Array(3),b=new Array(3);let S;for(S=0;S<3;S++)x[S]=W.Pq.Zero(),b[S]=W.I9.Zero();for(let e=0;e<20;e++){for(S=0;S<3;S++){const t=c[3*e+S];x[S].copyFromFloats(h[3*u[t]],h[3*u[t]+1],h[3*u[t]+2]),x[S].normalize(),b[S].copyFromFloats(.134765625*d[2*t]+.05859375+-.0390625*f[e],.2333984375*d[2*t+1]+.025390625+.01953125*f[e])}const t=(e,t,i,l)=>{const h=W.Pq.Lerp(x[0],x[2],t/s),c=W.Pq.Lerp(x[1],x[2],t/s),u=s===t?x[2]:W.Pq.Lerp(h,c,e/(s-t));let d;if(u.normalize(),r){const e=W.Pq.Lerp(x[0],x[2],l/s),t=W.Pq.Lerp(x[1],x[2],l/s);d=W.Pq.Lerp(e,t,i/(s-l))}else d=new W.Pq(u.x,u.y,u.z);d.x/=n,d.y/=o,d.z/=a,d.normalize();const f=W.I9.Lerp(b[0],b[2],t/s),S=W.I9.Lerp(b[1],b[2],t/s),T=s===t?b[2]:W.I9.Lerp(f,S,e/(s-t));_.push(u.x*n,u.y*o,u.z*a),m.push(d.x,d.y,d.z),g.push(T.x,Tt.rX?1-T.y:T.y),p.push(v),v++};for(let e=0;eKa(e,t,i);const Za={CreateIcoSphere:Qa};bt.CreateIcoSphere=$a,Yt.CreateIcoSphere=(e,t,i)=>Qa(e,t,i);const Ja=new W.Pq(1,0,0),el=new W.Pq(-1,0,0),tl=new W.Pq(0,1,0),il=new W.Pq(0,-1,0),rl=new W.Pq(0,0,1),sl=new W.Pq(0,0,-1);class nl{constructor(e=W.Pq.Zero(),t=W.Pq.Up(),i=W.I9.Zero(),r=0,s=0,n=null,o=null,a=null,l=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=r,this.vertexIdxForBones=s,this.localPositionOverride=n,this.localNormalOverride=o,this.matrixIndicesOverride=a,this.matrixWeightsOverride=l}clone(){return new nl(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,this.localPositionOverride?.slice(),this.localNormalOverride?.slice(),this.matrixIndicesOverride?.slice(),this.matrixWeightsOverride?.slice())}}function ol(e,t,i){const r=!!t.skeleton,s=i.localMode||r,n=t.getIndices(),o=r?t.getPositionData(!0,!0):t.getVerticesData(st.R.PositionKind),a=r?t.getNormalsData(!0,!0):t.getVerticesData(st.R.NormalKind),l=s?r?t.getVerticesData(st.R.PositionKind):o:null,h=s?r?t.getVerticesData(st.R.NormalKind):a:null,c=t.getVerticesData(st.R.UVKind),u=r?t.getVerticesData(st.R.MatricesIndicesKind):null,d=r?t.getVerticesData(st.R.MatricesWeightsKind):null,f=r?t.getVerticesData(st.R.MatricesIndicesExtraKind):null,p=r?t.getVerticesData(st.R.MatricesWeightsExtraKind):null,_=i.position||W.Pq.Zero();let m=i.normal||W.Pq.Up();const g=i.size||W.Pq.One(),v=i.angle||0;if(!m){const e=new W.Pq(0,0,1),i=t.getScene().activeCamera,r=W.Pq.TransformCoordinates(e,i.getWorldMatrix());m=i.globalPosition.subtract(r)}const x=-Math.atan2(m.z,m.x)-Math.PI/2,b=Math.sqrt(m.x*m.x+m.z*m.z),S=Math.atan2(m.y,b),T=new bt;T.indices=[],T.positions=[],T.normals=[],T.uvs=[],T.matricesIndices=r?[]:null,T.matricesWeights=r?[]:null,T.matricesIndicesExtra=f?[]:null,T.matricesWeightsExtra=p?[]:null;let C=0;const y=(e,t)=>{const r=new nl;if(!n||!o||!a)return r;const s=n[e];if(r.vertexIdx=3*s,r.vertexIdxForBones=4*s,r.position=new W.Pq(o[3*s],o[3*s+1],o[3*s+2]),W.Pq.TransformCoordinatesToRef(r.position,t,r.position),r.normal=new W.Pq(a[3*s],a[3*s+1],a[3*s+2]),W.Pq.TransformNormalToRef(r.normal,t,r.normal),i.captureUVS&&c){const e=c[2*s+1];r.uv=new W.I9(c[2*s],Tt.rX?1-e:e)}return r},E=[0,0,0,0],P=(e,t)=>{if(0===e.length)return e;const i=.5*Math.abs(W.Pq.Dot(g,t)),r=(e,t,i,r)=>{for(let s=0;s{const n=W.Pq.GetClipFactor(e.position,s.position,t,i);let o=E,a=E;if(u&&d){const t=e.matrixIndicesOverride?0:e.vertexIdxForBones,i=e.matrixIndicesOverride??u,l=e.matrixWeightsOverride??d,h=s.matrixIndicesOverride?0:s.vertexIdxForBones,c=s.matrixIndicesOverride??u,f=s.matrixWeightsOverride??d;o=[0,0,0,0],a=[0,0,0,0];let p=0;for(let e=0;e<4;++e)if(l[t+e]>0){const s=r(c,i[t+e],h,4);o[p]=i[t+e],a[p]=(0,ar.Lerp)(l[t+e],s>=0?f[s]:0,n),p++}for(let e=0;e<4&&p<4;++e){const s=c[h+e];-1===r(i,s,t,4)&&(o[p]=s,a[p]=(0,ar.Lerp)(0,f[h+e],n),p++)}const _=a[0]+a[1]+a[2]+a[3];a[0]/=_,a[1]/=_,a[2]/=_,a[3]/=_}const c=e.localPositionOverride?e.localPositionOverride[0]:l?.[e.vertexIdx]??0,f=e.localPositionOverride?e.localPositionOverride[1]:l?.[e.vertexIdx+1]??0,p=e.localPositionOverride?e.localPositionOverride[2]:l?.[e.vertexIdx+2]??0,_=s.localPositionOverride?s.localPositionOverride[0]:l?.[s.vertexIdx]??0,m=s.localPositionOverride?s.localPositionOverride[1]:l?.[s.vertexIdx+1]??0,g=s.localPositionOverride?s.localPositionOverride[2]:l?.[s.vertexIdx+2]??0,v=e.localNormalOverride?e.localNormalOverride[0]:h?.[e.vertexIdx]??0,x=e.localNormalOverride?e.localNormalOverride[1]:h?.[e.vertexIdx+1]??0,b=e.localNormalOverride?e.localNormalOverride[2]:h?.[e.vertexIdx+2]??0,S=v+((s.localNormalOverride?s.localNormalOverride[0]:h?.[s.vertexIdx]??0)-v)*n,T=x+((s.localNormalOverride?s.localNormalOverride[1]:h?.[s.vertexIdx+1]??0)-x)*n,C=b+((s.localNormalOverride?s.localNormalOverride[2]:h?.[s.vertexIdx+2]??0)-b)*n,y=Math.sqrt(S*S+T*T+C*C);return new nl(W.Pq.Lerp(e.position,s.position,n),W.Pq.Lerp(e.normal,s.normal,n).normalize(),W.I9.Lerp(e.uv,s.uv,n),-1,-1,l?[c+(_-c)*n,f+(m-f)*n,p+(g-p)*n]:null,h?[S/y,T/y,C/y]:null,o,a)};let n=null;e.length>3&&(n=[]);for(let r=0;r0,d=W.Pq.Dot(e[r+1].position,t)-i>0,f=W.Pq.Dot(e[r+2].position,t)-i>0;switch(o=(u?1:0)+(d?1:0)+(f?1:0),o){case 0:e.length>3?(n.push(e[r]),n.push(e[r+1]),n.push(e[r+2])):n=e;break;case 1:if(n=n??new Array,u&&(a=e[r+1],l=e[r+2],h=s(e[r],a),c=s(e[r],l)),d){a=e[r],l=e[r+2],h=s(e[r+1],a),c=s(e[r+1],l),n.push(h),n.push(l.clone()),n.push(a.clone()),n.push(l.clone()),n.push(h.clone()),n.push(c);break}f&&(a=e[r],l=e[r+1],h=s(e[r+2],a),c=s(e[r+2],l)),a&&l&&h&&c&&(n.push(a.clone()),n.push(l.clone()),n.push(h),n.push(c),n.push(h.clone()),n.push(l.clone()));break;case 2:n=n??new Array,u||(a=e[r].clone(),l=s(a,e[r+1]),h=s(a,e[r+2]),n.push(a),n.push(l),n.push(h)),d||(a=e[r+1].clone(),l=s(a,e[r+2]),h=s(a,e[r]),n.push(a),n.push(l),n.push(h)),f||(a=e[r+2].clone(),l=s(a,e[r]),h=s(a,e[r+1]),n.push(a),n.push(l),n.push(h))}}return n},A=t instanceof Yt?t:null,R=A?._thinInstanceDataStorage.matrixData,I=A?.thinInstanceCount||1,M=W.AA.Matrix[0];M.copyFrom(W.uq.IdentityReadOnly);for(let e=0;eol(e,t,{position:i,normal:r,size:s,angle:n});class ll{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&(e=Math.floor(e),Z.V.Warn("x is not an integer, floor(x) used")),t!==Math.floor(t)&&(t=Math.floor(t),Z.V.Warn("y is not an integer, floor(y) used"))}clone(){return new ll(this.x,this.y)}rotate60About(e){const t=this.x;return this.x=e.x+e.y-this.y,this.y=t+this.y-e.x,this}rotateNeg60About(e){const t=this.x;return this.x=t+this.y-e.y,this.y=e.x+e.y-t,this}rotate120(e,t){e!==Math.floor(e)&&(e=Math.floor(e),Z.V.Warn("m not an integer only floor(m) used")),t!==Math.floor(t)&&(t=Math.floor(t),Z.V.Warn("n not an integer only floor(n) used"));const i=this.x;return this.x=e-i-this.y,this.y=t+i,this}rotateNeg120(e,t){e!==Math.floor(e)&&(e=Math.floor(e),Z.V.Warn("m is not an integer, floor(m) used")),t!==Math.floor(t)&&(t=Math.floor(t),Z.V.Warn("n is not an integer, floor(n) used"));const i=this.x;return this.x=this.y-t,this.y=e+t-i-this.y,this}toCartesianOrigin(e,t){const i=W.Pq.Zero();return i.x=e.x+2*this.x*t+this.y*t,i.y=e.y+Math.sqrt(3)*this.y*t,i}static Zero(){return new ll(0,0)}}class hl{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new cl("icosahedron","Regular",[[0,lt.a6,-1],[-lt.a6,1,0],[-1,0,-lt.a6],[1,0,-lt.a6],[lt.a6,1,0],[0,lt.a6,1],[-1,0,lt.a6],[-lt.a6,-1,0],[0,-lt.a6,-1],[lt.a6,-1,0],[1,0,lt.a6],[0,-lt.a6,1]],[[0,2,1],[0,3,2],[0,4,3],[0,5,4],[0,1,5],[7,6,1],[8,7,2],[9,8,3],[10,9,4],[6,10,5],[2,7,1],[3,8,2],[4,9,3],[5,10,4],[1,6,5],[11,6,7],[11,7,8],[11,8,9],[11,9,10],[11,10,6]])}setIndices(){let e=12;const t={},i=this.m,r=this.n;let s,n,o,a,l,h=i,c=1,u=0;0!==r&&(h=(0,ar.HighestCommonFactor)(i,r)),c=i/h,u=r/h;const d=ll.Zero(),f=new ll(i,r),p=new ll(-r,i+r),_=ll.Zero(),m=ll.Zero(),g=ll.Zero();let v,x,b,S,T=[];const C=[],y=this.vertByDist,E=(i,r,s,n)=>{v=i+"|"+s,x=r+"|"+n,v in t||x in t?v in t&&!(x in t)?t[x]=t[v]:x in t&&!(v in t)&&(t[v]=t[x]):(t[v]=e,t[x]=e,e++),y[s][0]>2?C[t[v]]=[-y[s][0],y[s][1],t[v]]:C[t[v]]=[T[y[s][0]],y[s][1],t[v]]};this.IDATA.edgematch=[[1,"B"],[2,"B"],[3,"B"],[4,"B"],[0,"B"],[10,"O",14,"A"],[11,"O",10,"A"],[12,"O",11,"A"],[13,"O",12,"A"],[14,"O",13,"A"],[0,"O"],[1,"O"],[2,"O"],[3,"O"],[4,"O"],[19,"B",5,"A"],[15,"B",6,"A"],[16,"B",7,"A"],[17,"B",8,"A"],[18,"B",9,"A"]];for(let x=0;x<20;x++){if(T=this.IDATA.face[x],o=T[2],a=T[1],l=T[0],b=d.x+"|"+d.y,v=x+"|"+b,v in t||(t[v]=o,C[o]=[T[y[b][0]],y[b][1]]),b=f.x+"|"+f.y,v=x+"|"+b,v in t||(t[v]=a,C[a]=[T[y[b][0]],y[b][1]]),b=p.x+"|"+p.y,v=x+"|"+b,v in t||(t[v]=l,C[l]=[T[y[b][0]],y[b][1]]),s=this.IDATA.edgematch[x][0],n=this.IDATA.edgematch[x][1],"B"===n)for(let e=1;e2?C[t[v]]=[-y[b][0],y[b][1],t[v]]:C[t[v]]=[T[y[b][0]],y[b][1],t[v]])}this.closestTo=C,this.vecToidx=t}calcCoeffs(){const e=this.m,t=this.n,i=Math.sqrt(3)/3,r=e*e+t*t+e*t;this.coau=(e+t)/r,this.cobu=-t/r,this.coav=-i*(e-t)/r,this.cobv=i*(2*e+t)/r}createInnerFacets(){const e=this.m,t=this.n;for(let i=0;i0&&e0){const r=(0,ar.HighestCommonFactor)(e,t),s=e/r,n=t/r;for(let o=1;oe.x-t.x)),i.sort(((e,t)=>e.y-t.y));const o=new Array(e+t+1),a=new Array(e+t+1);for(let e=0;e{const s=i.clone();return"A"===r&&s.rotateNeg120(e,t),"B"===r&&s.rotate120(e,t),s.x<0?s.y:s.x+s.y},d=[],f=[],p=[],_=[],m={},g=[];let v=-1,x=-1;for(let e=0;ee[2]-t[2])),g.sort(((e,t)=>e[3]-t[3])),g.sort(((e,t)=>e[1]-t[1])),g.sort(((e,t)=>e[0]-t[0]));for(let e=0;et.vecToidx[e+i])))}mapABOBtoDATA(e,t){const i=t.IDATA.edgematch[e][0];for(let r=0;r-1?i[e][1]>0&&t[i[e][0]].push([e,i[e][1]]):t[12].push([e,i[e][0]]);const r=[];for(let e=0;e<12;e++)r[e]=e;let s=12;for(let e=0;e<12;e++){t[e].sort(((e,t)=>e[1]-t[1]));for(let i=0;ie[3]-t[3]));for(let e=0;e0;)s=t[a],this.face[s].indexOf(o)>-1?(n=(this.face[s].indexOf(o)+1)%3,o=this.face[s][n],i.push(o),r.push(s),t.splice(a,1),a=0):a++;return this.adjacentFaces.push(i),r}toGoldbergPolyhedronData(){const e=new cl("GeoDual","Goldberg",[],[]);e.name="GD dual";const t=this.vertex.length,i=new Array(t);for(let e=0;e{r=0,s=0,n=0,o=this.face[t];for(let e=0;e<3;e++)a=this.vertex[o[e]],r+=a[0],s+=a[1],n+=a[2];e.vertex[t]=[r/3,s/3,n/3]}));return e}static BuildGeodesicData(e){const t=new ul("Geodesic-m-n","Geodesic",[[0,lt.a6,-1],[-lt.a6,1,0],[-1,0,-lt.a6],[1,0,-lt.a6],[lt.a6,1,0],[0,lt.a6,1],[-1,0,lt.a6],[-lt.a6,-1,0],[0,-lt.a6,-1],[lt.a6,-1,0],[1,0,lt.a6],[0,-lt.a6,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let i=0;ir){const e=s;s=r,r=e,Z.V.Warn("n > m therefore m and n swapped")}const n=new hl;return n.build(r,s),Ka(e,{custom:ul.BuildGeodesicData(n),size:t.size,sizeX:t.sizeX,sizeY:t.sizeY,sizeZ:t.sizeZ,faceUV:t.faceUV,faceColors:t.faceColors,flat:t.flat,updatable:t.updatable,sideOrientation:t.sideOrientation,frontUVs:t.frontUVs,backUVs:t.backUVs},i)}Yt._GoldbergMeshParser=(e,t)=>fl.Parse(e,t);class fl extends Yt{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return void 0===t?(e>this.goldbergData.nbUnsharedFaces-1&&(Z.V.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(Z.V.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(Z.V.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let t=0;t1&&(c=1),l.push(c,u);for(let e=0;e<6;e++)c=n.x+o*Math.cos(a+e*Math.PI/3),u=n.y+o*Math.sin(a+e*Math.PI/3),c<0&&(c=0),c>1&&(c=1),h.push(c,u);for(let e=r;eH.ov.FromArray(e))),i.faceCenters=i.faceCenters.map((e=>W.Pq.FromArray(e))),i.faceZaxis=i.faceZaxis.map((e=>W.Pq.FromArray(e))),i.faceXaxis=i.faceXaxis.map((e=>W.Pq.FromArray(e))),i.faceYaxis=i.faceYaxis.map((e=>W.Pq.FromArray(e)));const r=new fl(e.name,t);return r.goldbergData=i,r}}function pl(e,t){const i=e.size,r=e.sizeX||i||1,s=e.sizeY||i||1,n=e.sizeZ||i||1,o=0===e.sideOrientation?0:e.sideOrientation||bt.DEFAULTSIDE,a=[],l=[],h=[],c=[];let u=1/0,d=-1/0,f=1/0,p=-1/0;for(let e=0;ea){const e=l;l=a,a=e,Z.V.Warn("n > m therefore m and n swapped")}const h=new hl;h.build(a,l);const c=ul.BuildGeodesicData(h),u=c.toGoldbergPolyhedronData(),d=new fl(e,i);t.sideOrientation=Yt._GetDefaultSideOrientation(t.sideOrientation),d._originalBuilderSideOrientation=t.sideOrientation,pl(t,u).applyToMesh(d,t.updatable),d.goldbergData.nbSharedFaces=c.sharedNodes,d.goldbergData.nbUnsharedFaces=c.poleNodes,d.goldbergData.adjacentFaces=c.adjacentFaces,d.goldbergData.nbFaces=d.goldbergData.nbSharedFaces+d.goldbergData.nbUnsharedFaces,d.goldbergData.nbFacesAtPole=(d.goldbergData.nbUnsharedFaces-12)/12;for(let e=0;e0?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 gl(e,t,i,r,s,n){const o=n.glyphs[e]||n.glyphs["?"];if(!o)return null;const a=new ml(s);if(o.o){const e=o.o.split(" ");for(let s=0,n=e.length;slt.bH&&(e.x=1*Math.sign(e.x)),Math.abs(e.y-1)>lt.bH&&(e.y=1*Math.sign(e.y)),Math.abs(e.z-1)>lt.bH&&(e.z=1*Math.sign(e.z))}_updateDebugConstraint(e,t){if(!e._initOptions)return;const{pivotA:i,pivotB:r,axisA:s,axisB:n,perpAxisA:o,perpAxisB:a}=e._initOptions;i&&r&&s&&n&&o&&a&&t.getDescendants(!0).forEach((e=>{const t=e.getDescendants(!0)[0],l=e.getDescendants(!0)[1],{parentBody:h,parentBodyIndex:c}=t.metadata,{childBody:u,childBodyIndex:d}=l.metadata,f=this._getTransformFromBodyToRef(h,W.AA.Matrix[0],c),p=this._getTransformFromBodyToRef(u,W.AA.Matrix[1],d);f.decomposeToTransformNode(t),this._makeScalingUnitInPlace(t.scaling),p.decomposeToTransformNode(l),this._makeScalingUnitInPlace(l.scaling);const _=t.getDescendants(!0)[0];_.position.copyFrom(i);const m=l.getDescendants(!0)[0];m.position.copyFrom(r),W.PT.FromRotationMatrixToRef(W.uq.FromXYZAxesToRef(s,o,W.Pq.CrossToRef(s,o,W.AA.Vector3[0]),W.AA.Matrix[0]),_.rotationQuaternion),W.PT.FromRotationMatrixToRef(W.uq.FromXYZAxesToRef(n,a,W.Pq.CrossToRef(n,a,W.AA.Vector3[1]),W.AA.Matrix[1]),m.rotationQuaternion)}))}showImpostor(e,t){if(!this._scene)return null;for(let t=0;tthis._updateDebugMeshes(),this._scene.registerBeforeRender(this._renderFunction)),this._numMeshes++),i}showBody(e){if(!this._scene)return null;for(let t=0;tthis._updateDebugMeshes(),this._scene.registerBeforeRender(this._renderFunction)),this._numBodies++),t}showInertia(e){if(!this._scene)return null;for(let t=0;tthis._updateInertiaMeshes(),this._scene.registerBeforeRender(this._inertiaRenderFunction)),this._numInertiaBodies++),t}showConstraint(e){if(!this._scene)return null;for(let t=0;tthis._updateDebugConstraints(),this._scene.registerBeforeRender(this._constraintRenderFunction)),this._numConstraints++),t}hideImpostor(e){if(!e||!this._scene||!this._utilityLayer)return;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let r=0;r-1&&this._debugMeshMeshes.splice(s,1),this._numMeshes--,this._numMeshes>0?(this._meshes[r]=this._meshes[this._numMeshes],this._impostors[r]=this._impostors[this._numMeshes],this._meshes[this._numMeshes]=null,this._impostors[this._numMeshes]=null):(this._meshes[0]=null,this._impostors[0]=null),t=!0;break}t&&0===this._numMeshes&&this._scene.unregisterBeforeRender(this._renderFunction)}hideBody(e){if(!e||!this._scene||!this._utilityLayer)return!1;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let r=0;r0?(this._bodyMeshes[r]=this._bodyMeshes[this._numBodies],this._bodies[r]=this._bodies[this._numBodies],this._bodyMeshes[this._numBodies]=null,this._bodies[this._numBodies]=null):(this._bodyMeshes[0]=null,this._bodies[0]=null),t=!0;break}return t&&0===this._numBodies&&this._scene.unregisterBeforeRender(this._renderFunction),t}hideInertia(e){if(!e||!this._scene||!this._utilityLayer)return!1;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let r=0;r0?(this._constraints[r]=this._constraints[this._numConstraints],this._constraintMeshes[r]=this._constraintMeshes[this._numConstraints],this._constraints[this._numConstraints]=null,this._constraintMeshes[this._numConstraints]=null):(this._constraints[0]=null,this._constraintMeshes[0]=null),t=!0;break}t&&0===this._numConstraints&&this._scene.unregisterBeforeRender(this._constraintRenderFunction)}_getDebugMaterial(e){return this._debugMaterial||(this._debugMaterial=new Un("",e),this._debugMaterial.wireframe=!0,this._debugMaterial.emissiveColor=H.v9.White(),this._debugMaterial.disableLighting=!0),this._debugMaterial}_getDebugInertiaMaterial(e){return this._debugInertiaMaterial||(this._debugInertiaMaterial=new Un("",e),this._debugInertiaMaterial.disableLighting=!0,this._debugInertiaMaterial.alpha=0),this._debugInertiaMaterial}_getDebugBoxMesh(e){return this._debugBoxMesh||(this._debugBoxMesh=Ko("physicsBodyBoxViewMesh",{size:1},e),this._debugBoxMesh.rotationQuaternion=W.PT.Identity(),this._debugBoxMesh.material=this._getDebugMaterial(e),this._debugBoxMesh.setEnabled(!1)),this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance")}_getDebugSphereMesh(e){return this._debugSphereMesh||(this._debugSphereMesh=Qo("physicsBodySphereViewMesh",{diameter:1},e),this._debugSphereMesh.rotationQuaternion=W.PT.Identity(),this._debugSphereMesh.material=this._getDebugMaterial(e),this._debugSphereMesh.setEnabled(!1)),this._debugSphereMesh.createInstance("physicsBodySphereViewInstance")}_getDebugCapsuleMesh(e){return this._debugCapsuleMesh||(this._debugCapsuleMesh=oa("physicsBodyCapsuleViewMesh",{height:1},e),this._debugCapsuleMesh.rotationQuaternion=W.PT.Identity(),this._debugCapsuleMesh.material=this._getDebugMaterial(e),this._debugCapsuleMesh.setEnabled(!1)),this._debugCapsuleMesh.createInstance("physicsBodyCapsuleViewInstance")}_getDebugCylinderMesh(e){return this._debugCylinderMesh||(this._debugCylinderMesh=No("physicsBodyCylinderViewMesh",{diameterTop:1,diameterBottom:1,height:1},e),this._debugCylinderMesh.rotationQuaternion=W.PT.Identity(),this._debugCylinderMesh.material=this._getDebugMaterial(e),this._debugCylinderMesh.setEnabled(!1)),this._debugCylinderMesh.createInstance("physicsBodyCylinderViewInstance")}_getDebugMeshMesh(e,t){const i=new Yt(e.name,t,null,e);return i.setParent(e),i.position=W.Pq.Zero(),i.material=this._getDebugMaterial(t),this._debugMeshMeshes.push(i),i}_getDebugMesh(e,t){if(!this._utilityLayer)return null;if(t&&t.parent&&t.parent.physicsImpostor)return null;let i=null;const r=this._utilityLayer.utilityLayerScene;if(!e.physicsBody)return Z.V.Warn("Unable to get physicsBody of impostor. It might be initialized later by its parent's impostor."),null;switch(e.type){case sa.BoxImpostor:i=this._getDebugBoxMesh(r),e.getBoxSizeToRef(i.scaling);break;case sa.SphereImpostor:{i=this._getDebugSphereMesh(r);const t=e.getRadius();i.scaling.x=2*t,i.scaling.y=2*t,i.scaling.z=2*t;break}case sa.CapsuleImpostor:{i=this._getDebugCapsuleMesh(r);const t=e.object.getBoundingInfo();i.scaling.x=2*(t.boundingBox.maximum.x-t.boundingBox.minimum.x)*e.object.scaling.x,i.scaling.y=(t.boundingBox.maximum.y-t.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=2*(t.boundingBox.maximum.z-t.boundingBox.minimum.z)*e.object.scaling.z;break}case sa.MeshImpostor:t&&(i=this._getDebugMeshMesh(t,r));break;case sa.NoImpostor:t?t.getChildMeshes().filter((e=>e.physicsImpostor?1:0)).forEach((e=>{if(e.physicsImpostor&&"Mesh"===e.getClassName()){const t=e.getBoundingInfo(),s=t.boundingBox.minimum,n=t.boundingBox.maximum;switch(e.physicsImpostor.type){case sa.BoxImpostor:i=this._getDebugBoxMesh(r),i.position.copyFrom(s),i.position.addInPlace(n),i.position.scaleInPlace(.5);break;case sa.SphereImpostor:i=this._getDebugSphereMesh(r);break;case sa.CylinderImpostor:i=this._getDebugCylinderMesh(r);break;default:i=null}i&&(i.scaling.x=n.x-s.x,i.scaling.y=n.y-s.y,i.scaling.z=n.z-s.z,i.parent=e)}})):Z.V.Warn("No target mesh parameter provided for NoImpostor. Skipping."),i=null;break;case sa.CylinderImpostor:{i=this._getDebugCylinderMesh(r);const t=e.object.getBoundingInfo();i.scaling.x=(t.boundingBox.maximum.x-t.boundingBox.minimum.x)*e.object.scaling.x,i.scaling.y=(t.boundingBox.maximum.y-t.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=(t.boundingBox.maximum.z-t.boundingBox.minimum.z)*e.object.scaling.z;break}}return i}_getDebugBodyMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=new Yt("custom",t),r=new bt,s=e.getGeometry();if(r.positions=s.positions,r.indices=s.indices,r.applyToMesh(i),e._pluginDataInstances){const t=new Float32Array(16*e._pluginDataInstances.length);i.thinInstanceSetBuffer("matrix",t,16,!1)}return i.material=this._getDebugMaterial(t),i}_getMeshDebugInertiaMatrixToRef(e,t){const i=e.inertiaOrientation??W.PT.Identity(),r=e.inertia??W.Pq.Zero(),s=e.centerOfMass??W.Pq.Zero(),n=6*(r.x-r.y+r.z),o=Math.sqrt(Math.max(n,0)),a=12*r.x-n,l=Math.sqrt(Math.max(a,0)),h=12*r.z-n,c=Math.sqrt(Math.max(h,0)),u=W.AA.Vector3[0];u.set(c,o,l);const d=W.uq.ScalingToRef(u.x,u.y,u.z,W.AA.Matrix[0]),f=i.toRotationMatrix(W.AA.Matrix[1]),p=W.uq.TranslationToRef(s.x,s.y,s.z,W.AA.Matrix[2]);return d.multiplyToRef(f,t),t.multiplyToRef(p,t),t}_getDebugInertiaMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=bl.CreateBox("custom",{size:1},t),r=W.uq.Identity();if(e._pluginDataInstances.length){const t=new Float32Array(16*e._pluginDataInstances.length);for(let i=0;i=0?W.uq.FromArrayToRef(r._thinInstanceDataStorage.matrixData,i,t):t.copyFrom(r.getWorldMatrix())}_getDebugConstraintMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene;if(!e._initOptions)return null;const{pivotA:i,pivotB:r,axisA:s,axisB:n,perpAxisA:o,perpAxisB:a}=e._initOptions;if(!(i&&r&&s&&n&&o&&a))return null;const l=new Yt("parentingDebugConstraint",t),h=e.getBodiesUsingConstraint();for(const e of h){const h=new Pt("parentOfPair",t);h.parent=l;const{parentBody:c,parentBodyIndex:u,childBody:d,childBodyIndex:f}=e,p=this._getTransformFromBodyToRef(c,W.AA.Matrix[0],u),_=this._getTransformFromBodyToRef(d,W.AA.Matrix[1],f),m=new Pt("parentCoordSystem",t);m.parent=h,m.metadata={parentBody:c,parentBodyIndex:u},p.decomposeToTransformNode(m);const g=new Pt("childCoordSystem",t);g.parent=h,g.metadata={childBody:d,childBodyIndex:f},_.decomposeToTransformNode(g);const v=W.PT.FromRotationMatrix(W.uq.FromXYZAxesToRef(s,o,s.cross(o),W.AA.Matrix[0])),x=W.PT.FromRotationMatrix(W.uq.FromXYZAxesToRef(n,a,n.cross(a),W.AA.Matrix[0])),b=i,S=r,T=new Pt("constraint_parent",t);T.position.copyFrom(b),T.rotationQuaternion=v,T.parent=m;const C=new Pt("constraint_child",t);C.parent=g,C.position.copyFrom(S),C.rotationQuaternion=x;const y=new Wo(t,this._constraintAxesSize);y.xAxis.parent=T,y.yAxis.parent=T,y.zAxis.parent=T;const E=new Wo(t,this._constraintAxesSize);E.xAxis.parent=C,E.yAxis.parent=C,E.zAxis.parent=C}return l}dispose(){for(let e=this._numMeshes-1;e>=0;e--)this.hideImpostor(this._impostors[0]);for(let e=this._numBodies-1;e>=0;e--)this.hideBody(this._bodies[0]);for(let e=this._numInertiaBodies-1;e>=0;e--)this.hideInertia(this._inertiaBodies[0]);this._debugBoxMesh&&this._debugBoxMesh.dispose(),this._debugSphereMesh&&this._debugSphereMesh.dispose(),this._debugCylinderMesh&&this._debugCylinderMesh.dispose(),this._debugMaterial&&this._debugMaterial.dispose(),this._impostors.length=0,this._scene=null,this._physicsEnginePlugin=null,this._utilityLayer&&(this._utilityLayer.dispose(),this._utilityLayer=null)}}class Tl{static CreateAndShow(e,t,i){const r=new Tl(e);return r.show(t,i),r}constructor(e){this.ray=e}show(e,t){if(!this._renderFunction&&this.ray){const t=this.ray;this._renderFunction=()=>this._render(),this._scene=e,this._renderPoints=[t.origin,t.origin.add(t.direction.scale(t.length))],this._renderLine=Ra("ray",{points:this._renderPoints,updatable:!0},e),this._renderLine.isPickable=!1,this._renderFunction&&this._scene.registerBeforeRender(this._renderFunction)}t&&this._renderLine&&this._renderLine.color.copyFrom(t)}hide(){this._renderFunction&&this._scene&&(this._scene.unregisterBeforeRender(this._renderFunction),this._scene=null,this._renderFunction=null,this._renderLine&&(this._renderLine.dispose(),this._renderLine=null),this._renderPoints=[])}_render(){const e=this.ray;if(!e)return;const t=this._renderPoints[1],i=Math.min(e.length,1e6);t.copyFrom(e.direction),t.scaleInPlace(i),t.addInPlace(e.origin),this._renderPoints[0].copyFrom(e.origin),Ra("ray",{points:this._renderPoints,updatable:!0,instance:this._renderLine},this._scene),this._renderLine?.refreshBoundingInfo()}attachToMesh(e,t,i,r){this._attachedToMesh=e;const s=this.ray;s&&(s.direction||(s.direction=W.Pq.Zero()),s.origin||(s.origin=W.Pq.Zero()),r&&(s.length=r),i||(i=W.Pq.Zero()),t||(t=new W.Pq(0,0,-1)),this._scene||(this._scene=e.getScene()),this._meshSpaceDirection?(this._meshSpaceDirection.copyFrom(t),this._meshSpaceOrigin.copyFrom(i)):(this._meshSpaceDirection=t.clone(),this._meshSpaceOrigin=i.clone()),this._onAfterRenderObserver||(this._onAfterRenderObserver=this._scene.onBeforeRenderObservable.add((()=>this._updateToMesh())),this._onAfterStepObserver=this._scene.onAfterStepObservable.add((()=>this._updateToMesh()))),this._attachedToMesh.computeWorldMatrix(!0),this._updateToMesh())}detachFromMesh(){this._attachedToMesh&&this._scene&&(this._onAfterRenderObserver&&(this._scene.onBeforeRenderObservable.remove(this._onAfterRenderObserver),this._scene.onAfterStepObservable.remove(this._onAfterStepObserver)),this._attachedToMesh=null,this._onAfterRenderObserver=null,this._onAfterStepObserver=null,this._scene=null)}_updateToMesh(){const e=this.ray;this._attachedToMesh&&e&&(this._attachedToMesh.isDisposed()?this.detachFromMesh():(this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection,e.direction),W.Pq.TransformCoordinatesToRef(this._meshSpaceOrigin,this._attachedToMesh.getWorldMatrix(),e.origin)))}dispose(){this.hide(),this.detachFromMesh(),this.ray=null}}var Cl=i(36217);class yl{static CreateBoneWeightShader(e,t){const i=e.skeleton,r=e.colorBase??H.v9.Black(),s=e.colorZero??H.v9.Blue(),n=e.colorQuarter??H.v9.Green(),o=e.colorHalf??H.v9.Yellow(),a=e.colorFull??H.v9.Red(),l=e.targetBoneIndex??0;Cl.M.ShadersStore["boneWeights:"+i.name+"VertexShader"]="precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 view;\n uniform mat4 projection;\n uniform mat4 worldViewProjection;\n\n #include\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include\n\n #include\n\n varying vec3 vColor;\n\n uniform vec3 colorBase;\n uniform vec3 colorZero;\n uniform vec3 colorQuarter;\n uniform vec3 colorHalf;\n uniform vec3 colorFull;\n\n uniform float targetBoneIndex;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include\n #include\n #include\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n vec3 color = colorBase;\n float totalWeight = 0.;\n if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){\n totalWeight += matricesWeights[0];\n }\n if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){\n totalWeight += matricesWeights[1];\n }\n if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){\n totalWeight += matricesWeights[2];\n }\n if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){\n totalWeight += matricesWeights[3];\n }\n\n color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight));\n color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight));\n color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight));\n color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight));\n vColor = color;\n\n gl_Position = projection * view * worldPos;\n }",Cl.M.ShadersStore["boneWeights:"+i.name+"FragmentShader"]="\n precision highp float;\n varying vec3 vPosition;\n\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4(vColor, 1.0);\n gl_FragColor = color;\n }\n ";const h=new xo("boneWeight:"+i.name,t,{vertex:"boneWeights:"+i.name,fragment:"boneWeights:"+i.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return h.setColor3("colorBase",r),h.setColor3("colorZero",s),h.setColor3("colorQuarter",n),h.setColor3("colorHalf",o),h.setColor3("colorFull",a),h.setFloat("targetBoneIndex",l),h.getClassName=()=>"BoneWeightShader",h.transparencyMode=Vt.MATERIAL_OPAQUE,h}static CreateSkeletonMapShader(e,t){const i=e.skeleton,r=e.colorMap??[{color:new H.v9(1,.38,.18),location:0},{color:new H.v9(.59,.18,1),location:.2},{color:new H.v9(.59,1,.18),location:.4},{color:new H.v9(1,.87,.17),location:.6},{color:new H.v9(1,.17,.42),location:.8},{color:new H.v9(.17,.68,1),location:1}],s=i.bones.length+1,n=yl._CreateBoneMapColorBuffer(s,r,t),o=new xo("boneWeights:"+i.name,t,{vertexSource:"precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 view;\n uniform mat4 projection;\n uniform mat4 worldViewProjection;\n uniform float colorMap["+4*i.bones.length+"];\n\n #include\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include\n #include\n\n varying vec3 vColor;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include\n #include\n #include\n\n vec3 color = vec3(0.);\n bool first = true;\n\n for (int i = 0; i < 4; i++) {\n int boneIdx = int(matricesIndices[i]);\n float boneWgt = matricesWeights[i];\n\n vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]);\n\n if (boneWgt > 0.) {\n if (first) {\n first = false;\n color = c;\n } else {\n color = mix(color, c, boneWgt);\n }\n }\n }\n\n vColor = color;\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n gl_Position = projection * view * worldPos;\n }",fragmentSource:"\n precision highp float;\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4( vColor, 1.0 );\n gl_FragColor = color;\n }\n "},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return o.setFloats("colorMap",n),o.getClassName=()=>"SkeletonMapShader",o.transparencyMode=Vt.MATERIAL_OPAQUE,o}static _CreateBoneMapColorBuffer(e,t,i){const r=new Gn("temp",{width:e,height:1},i,!1),s=r.getContext(),n=s.createLinearGradient(0,0,e,0);t.forEach((e=>{n.addColorStop(e.location,e.color.toHexString())})),s.fillStyle=n,s.fillRect(0,0,e,1),r.update();const o=[],a=s.getImageData(0,0,e,1).data,l=1/255;for(let e=0;eyl.DISPLAY_SPHERE_AND_SPURS&&(e=yl.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,r=!0,s=3,n={}){if(this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=r,this.renderingGroupId=s,this.options=n,this.color=H.v9.White(),this._debugLines=new Array,this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,n.pauseAnimations=n.pauseAnimations??!0,n.returnToRest=n.returnToRest??!1,n.displayMode=n.displayMode??yl.DISPLAY_LINES,n.displayOptions=n.displayOptions??{},n.displayOptions.midStep=n.displayOptions.midStep??.235,n.displayOptions.midStepFactor=n.displayOptions.midStepFactor??.155,n.displayOptions.sphereBaseSize=n.displayOptions.sphereBaseSize??.15,n.displayOptions.sphereScaleUnit=n.displayOptions.sphereScaleUnit??2,n.displayOptions.sphereFactor=n.displayOptions.sphereFactor??.865,n.displayOptions.spurFollowsChild=n.displayOptions.spurFollowsChild??!1,n.displayOptions.showLocalAxes=n.displayOptions.showLocalAxes??!1,n.displayOptions.localAxesSize=n.displayOptions.localAxesSize??.075,n.computeBonesUsingShaders=n.computeBonesUsingShaders??!0,n.useAllBones=n.useAllBones??!0,this._boneIndices=new Set,!n.useAllBones){const e=t?.getVerticesData(st.R.MatricesIndicesKind),i=t?.getVerticesData(st.R.MatricesWeightsKind);if(e&&i)for(let t=0;tyl.DISPLAY_SPHERE_AND_SPURS&&(o=yl.DISPLAY_LINES),this.displayMode=o,this.update(),this._bindObs()}_bindObs(){this.displayMode===yl.DISPLAY_LINES&&(this._obs=this.scene.onBeforeRenderObservable.add((()=>{this._displayLinesUpdate()})))}update(){switch(this.displayMode){case yl.DISPLAY_LINES:this._displayLinesUpdate();break;case yl.DISPLAY_SPHERES:this._buildSpheresAndSpurs(!0);break;case yl.DISPLAY_SPHERE_AND_SPURS:this._buildSpheresAndSpurs(!1)}this._buildLocalAxes()}set isEnabled(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))}get isEnabled(){return this._isEnabled}_getBonePosition(e,t,i,r=0,s=0,n=0){const o=W.AA.Matrix[0],a=t.getParent();if(o.copyFrom(t.getLocalMatrix()),0!==r||0!==s||0!==n){const e=W.AA.Matrix[1];W.uq.IdentityToRef(e),e.setTranslationFromFloats(r,s,n),e.multiplyToRef(o,o)}a&&o.multiplyToRef(a.getAbsoluteMatrix(),o),o.multiplyToRef(i,o),e.x=o.m[12],e.y=o.m[13],e.z=o.m[14]}_getLinesForBonesWithLength(e,t){const i=e.length;let r,s;t?(r=t.getWorldMatrix(),s=t.position):(r=new W.uq,s=e[0].position);let n=0;for(let t=0;t=0;r--){const t=e[r],o=t.getParent();if(!o||!this._boneIndices.has(t.getIndex())&&!this.options.useAllBones)continue;let a=this._debugLines[i];a||(a=[W.Pq.Zero(),W.Pq.Zero()],this._debugLines[i]=a),t.getAbsolutePositionToRef(s,a[0]),o.getAbsolutePositionToRef(s,a[1]),a[0].subtractInPlace(n),a[1].subtractInPlace(n),i++}r||s.dispose()}_revert(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)}_getAbsoluteBindPoseToRef(e,t){null!==e&&-1!==e._index?(this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBindMatrix().multiplyToRef(t,t)):t.copyFrom(W.uq.Identity())}_createSpur(e,t,i,r,s,n){const o=i.subtract(e),a=o.length(),l=o.normalize().scale(a),h=s.midStep||.165,c=s.midStepFactor||.215,u=l.scale(h),d=Ua("skeletonViewer",{shape:[new W.Pq(1,-1,0),new W.Pq(1,1,0),new W.Pq(-1,1,0),new W.Pq(-1,-1,0),new W.Pq(1,-1,0)],path:[W.Pq.Zero(),u,l],scaleFunction:e=>{switch(e){case 0:case 2:return 0;case 1:return a*c}return 0},sideOrientation:Yt.DEFAULTSIDE,updatable:!1},n),f=d.getTotalVertices(),p=[],_=[];for(let e=0;e9?_.push(r.getIndex(),0,0,0):_.push(t.getIndex(),0,0,0);return d.position=e.clone(),d.setVerticesData(st.R.MatricesWeightsKind,p,!1),d.setVerticesData(st.R.MatricesIndicesKind,_,!1),d.convertToFlatShadedMesh(),d}_getBoundingSphereForBone(e){if(!this.mesh)return null;const t=this.mesh.getVerticesData(st.R.PositionKind),i=this.mesh.getIndices(),r=this.mesh.getVerticesData(st.R.MatricesWeightsKind),s=this.mesh.getVerticesData(st.R.MatricesIndicesKind);if(!(t&&i&&r&&s))return null;const n=new W.Pq(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),o=new W.Pq(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);let a=0;for(let l=0;l1e-5){W.Pq.FromArrayToRef(t,3*h,W.AA.Vector3[0]),n.minimizeInPlace(W.AA.Vector3[0]),o.maximizeInPlace(W.AA.Vector3[0]),a++;break}}}return a>1?{center:W.Pq.Center(n,o),radius:W.Pq.Distance(n,o)/2}:null}_buildSpheresAndSpurs(e=!0){this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;const t=this.utilityLayer?.utilityLayerScene,i=this.skeleton.bones,r=[],s=[],n=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,t.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();let o=Number.NEGATIVE_INFINITY;const a=this.options.displayOptions||{};for(let n=0;n0)l.children.forEach((i=>{const r=new W.uq;i.getLocalMatrix().multiplyToRef(h,r);const n=new W.Pq;r.decompose(void 0,void 0,n);const u=W.Pq.Distance(c,n);u>o&&(o=u),e||s.push(this._createSpur(c,l,n,i,a,t))}));else{const i=this._getBoundingSphereForBone(l.getIndex());if(i&&(i.radius>o&&(o=i.radius),!e)){let e;const r=l.getParent();r?(this._getAbsoluteBindPoseToRef(r,h),h.decompose(void 0,void 0,W.AA.Vector3[0]),e=c.subtract(W.AA.Vector3[0]).normalize().scale(i.radius).add(c)):e=i.center.subtract(c).normalize().scale(i.radius).add(c),s.push(this._createSpur(c,l,e,null,a,t))}}const u=Qo("skeletonViewer",{segments:6,diameter:a.sphereBaseSize||.2,updatable:!0},t),d=u.getTotalVertices(),f=[],p=[];for(let e=0;e{e.setEnabled(t<6&&this._showLines||t>=6&&this._showPlanes)})),this._oldPosition.set(Number.NaN,Number.NaN,Number.NaN),this._visible=!0}hide(){this._lightHelperFrustumMeshes.forEach((e=>{e.setEnabled(!1)})),this._visible=!1}update(){if(!this._visible)return;if(this._oldPosition.equals(this._light.position)&&this._oldDirection.equals(this._light.direction)&&this._oldAutoCalc===this._light.autoCalcShadowZBounds&&this._oldMinZ===this._light.shadowMinZ&&this._oldMaxZ===this._light.shadowMaxZ)return;this._oldPosition.copyFrom(this._light.position),this._oldDirection.copyFrom(this._light.direction),this._oldAutoCalc=this._light.autoCalcShadowZBounds,this._oldMinZ=this._light.shadowMinZ,this._oldMaxZ=this._light.shadowMaxZ,W.AA.Vector3[0].set(this._light.orthoLeft,this._light.orthoBottom,void 0!==this._light.shadowMinZ?this._light.shadowMinZ:this._camera.minZ),W.AA.Vector3[1].set(this._light.orthoRight,this._light.orthoTop,void 0!==this._light.shadowMaxZ?this._light.shadowMaxZ:this._camera.maxZ);const e=this._getInvertViewMatrix();W.AA.Vector3[2].copyFromFloats(W.AA.Vector3[1].x,W.AA.Vector3[1].y,W.AA.Vector3[0].z),W.AA.Vector3[3].copyFromFloats(W.AA.Vector3[1].x,W.AA.Vector3[0].y,W.AA.Vector3[0].z),W.AA.Vector3[4].copyFromFloats(W.AA.Vector3[0].x,W.AA.Vector3[0].y,W.AA.Vector3[0].z),W.AA.Vector3[5].copyFromFloats(W.AA.Vector3[0].x,W.AA.Vector3[1].y,W.AA.Vector3[0].z),W.Pq.TransformCoordinatesToRef(W.AA.Vector3[2],e,W.AA.Vector3[2]),W.Pq.TransformCoordinatesToRef(W.AA.Vector3[3],e,W.AA.Vector3[3]),W.Pq.TransformCoordinatesToRef(W.AA.Vector3[4],e,W.AA.Vector3[4]),W.Pq.TransformCoordinatesToRef(W.AA.Vector3[5],e,W.AA.Vector3[5]),W.AA.Vector3[6].copyFromFloats(W.AA.Vector3[1].x,W.AA.Vector3[1].y,W.AA.Vector3[1].z),W.AA.Vector3[7].copyFromFloats(W.AA.Vector3[1].x,W.AA.Vector3[0].y,W.AA.Vector3[1].z),W.AA.Vector3[8].copyFromFloats(W.AA.Vector3[0].x,W.AA.Vector3[0].y,W.AA.Vector3[1].z),W.AA.Vector3[9].copyFromFloats(W.AA.Vector3[0].x,W.AA.Vector3[1].y,W.AA.Vector3[1].z),W.Pq.TransformCoordinatesToRef(W.AA.Vector3[6],e,W.AA.Vector3[6]),W.Pq.TransformCoordinatesToRef(W.AA.Vector3[7],e,W.AA.Vector3[7]),W.Pq.TransformCoordinatesToRef(W.AA.Vector3[8],e,W.AA.Vector3[8]),W.Pq.TransformCoordinatesToRef(W.AA.Vector3[9],e,W.AA.Vector3[9]),Ra("nearlines",{updatable:!0,points:this._nearLinesPoints,instance:this._lightHelperFrustumMeshes[0]},this._scene),Ra("farlines",{updatable:!0,points:this._farLinesPoints,instance:this._lightHelperFrustumMeshes[1]},this._scene),Ra("trlines",{updatable:!0,points:this._trLinesPoints,instance:this._lightHelperFrustumMeshes[2]},this._scene),Ra("brlines",{updatable:!0,points:this._brLinesPoints,instance:this._lightHelperFrustumMeshes[3]},this._scene),Ra("tllines",{updatable:!0,points:this._tlLinesPoints,instance:this._lightHelperFrustumMeshes[4]},this._scene),Ra("bllines",{updatable:!0,points:this._blLinesPoints,instance:this._lightHelperFrustumMeshes[5]},this._scene),W.AA.Vector3[2].toArray(this._nearPlaneVertices,0),W.AA.Vector3[3].toArray(this._nearPlaneVertices,3),W.AA.Vector3[4].toArray(this._nearPlaneVertices,6),W.AA.Vector3[5].toArray(this._nearPlaneVertices,9),this._lightHelperFrustumMeshes[6].geometry?.updateVerticesDataDirectly("position",this._nearPlaneVertices,0),W.AA.Vector3[6].toArray(this._farPlaneVertices,0),W.AA.Vector3[7].toArray(this._farPlaneVertices,3),W.AA.Vector3[8].toArray(this._farPlaneVertices,6),W.AA.Vector3[9].toArray(this._farPlaneVertices,9),this._lightHelperFrustumMeshes[7].geometry?.updateVerticesDataDirectly("position",this._farPlaneVertices,0),W.AA.Vector3[2].toArray(this._rightPlaneVertices,0),W.AA.Vector3[6].toArray(this._rightPlaneVertices,3),W.AA.Vector3[7].toArray(this._rightPlaneVertices,6),W.AA.Vector3[3].toArray(this._rightPlaneVertices,9),this._lightHelperFrustumMeshes[8].geometry?.updateVerticesDataDirectly("position",this._rightPlaneVertices,0),W.AA.Vector3[5].toArray(this._leftPlaneVertices,0),W.AA.Vector3[9].toArray(this._leftPlaneVertices,3),W.AA.Vector3[8].toArray(this._leftPlaneVertices,6),W.AA.Vector3[4].toArray(this._leftPlaneVertices,9),this._lightHelperFrustumMeshes[9].geometry?.updateVerticesDataDirectly("position",this._leftPlaneVertices,0),W.AA.Vector3[2].toArray(this._topPlaneVertices,0),W.AA.Vector3[6].toArray(this._topPlaneVertices,3),W.AA.Vector3[9].toArray(this._topPlaneVertices,6),W.AA.Vector3[5].toArray(this._topPlaneVertices,9),this._lightHelperFrustumMeshes[10].geometry?.updateVerticesDataDirectly("position",this._topPlaneVertices,0),W.AA.Vector3[3].toArray(this._bottomPlaneVertices,0),W.AA.Vector3[7].toArray(this._bottomPlaneVertices,3),W.AA.Vector3[8].toArray(this._bottomPlaneVertices,6),W.AA.Vector3[4].toArray(this._bottomPlaneVertices,9),this._lightHelperFrustumMeshes[11].geometry?.updateVerticesDataDirectly("position",this._bottomPlaneVertices,0)}dispose(){this._lightHelperFrustumMeshes.forEach((e=>{e.material?.dispose(),e.dispose()})),this._rootNode.dispose()}_createGeometry(){this._rootNode=new Pt("directionalLightHelperRoot_"+this._light.name,this._scene),this._rootNode.parent=this._light.parent,this._nearLinesPoints=[W.AA.Vector3[0],W.AA.Vector3[1],W.AA.Vector3[2],W.AA.Vector3[3],W.AA.Vector3[4]];const e=Ra("nearlines",{updatable:!0,points:this._nearLinesPoints},this._scene);e.parent=this._rootNode,e.alwaysSelectAsActiveMesh=!0,this._farLinesPoints=[W.AA.Vector3[5],W.AA.Vector3[6],W.AA.Vector3[7],W.AA.Vector3[8],W.AA.Vector3[9]];const t=Ra("farlines",{updatable:!0,points:this._farLinesPoints},this._scene);t.parent=this._rootNode,t.alwaysSelectAsActiveMesh=!0,this._trLinesPoints=[W.AA.Vector3[10],W.AA.Vector3[11]];const i=Ra("trlines",{updatable:!0,points:this._trLinesPoints},this._scene);i.parent=this._rootNode,i.alwaysSelectAsActiveMesh=!0,this._brLinesPoints=[W.AA.Vector3[12],W.AA.Vector3[0]];const r=Ra("brlines",{updatable:!0,points:this._brLinesPoints},this._scene);r.parent=this._rootNode,r.alwaysSelectAsActiveMesh=!0,this._tlLinesPoints=[W.AA.Vector3[1],W.AA.Vector3[2]];const s=Ra("tllines",{updatable:!0,points:this._tlLinesPoints},this._scene);s.parent=this._rootNode,s.alwaysSelectAsActiveMesh=!0,this._blLinesPoints=[W.AA.Vector3[3],W.AA.Vector3[4]];const n=Ra("bllines",{updatable:!0,points:this._blLinesPoints},this._scene);n.parent=this._rootNode,n.alwaysSelectAsActiveMesh=!0,this._lightHelperFrustumMeshes.push(e,t,i,r,s,n);const o=(e,t,i)=>{const r=new Yt(e+"plane",this._scene),s=new Un(e+"PlaneMat",this._scene);r.material=s,r.parent=this._rootNode,r.alwaysSelectAsActiveMesh=!0,s.emissiveColor=t,s.alpha=this.transparency,s.backFaceCulling=!1,s.disableLighting=!0;const n=new bt;n.positions=i,n.indices=[0,1,2,0,2,3],n.applyToMesh(r,!0),this._lightHelperFrustumMeshes.push(r)};this._nearPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._farPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._rightPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._leftPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._topPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._bottomPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],o("near",new H.v9(1,0,0),this._nearPlaneVertices),o("far",new H.v9(.3,0,0),this._farPlaneVertices),o("right",new H.v9(0,1,0),this._rightPlaneVertices),o("left",new H.v9(0,.3,0),this._leftPlaneVertices),o("top",new H.v9(0,0,1),this._topPlaneVertices),o("bottom",new H.v9(0,0,.3),this._bottomPlaneVertices),this._nearLinesPoints[0]=W.AA.Vector3[2],this._nearLinesPoints[1]=W.AA.Vector3[3],this._nearLinesPoints[2]=W.AA.Vector3[4],this._nearLinesPoints[3]=W.AA.Vector3[5],this._nearLinesPoints[4]=W.AA.Vector3[2],this._farLinesPoints[0]=W.AA.Vector3[6],this._farLinesPoints[1]=W.AA.Vector3[7],this._farLinesPoints[2]=W.AA.Vector3[8],this._farLinesPoints[3]=W.AA.Vector3[9],this._farLinesPoints[4]=W.AA.Vector3[6],this._trLinesPoints[0]=W.AA.Vector3[2],this._trLinesPoints[1]=W.AA.Vector3[6],this._brLinesPoints[0]=W.AA.Vector3[3],this._brLinesPoints[1]=W.AA.Vector3[7],this._tlLinesPoints[0]=W.AA.Vector3[4],this._tlLinesPoints[1]=W.AA.Vector3[8],this._blLinesPoints[0]=W.AA.Vector3[5],this._blLinesPoints[1]=W.AA.Vector3[9]}_getInvertViewMatrix(){return W.uq.LookAtLHToRef(this._light.position,this._light.position.add(this._light.direction),W.Pq.UpReadOnly,this._inverseViewMatrix),this._inverseViewMatrix.invertToRef(this._inverseViewMatrix),this._inverseViewMatrix}}var Pl=i(58292),Al=i(77333),Rl=i(78035);class Il{}Il.AUTOSAMPLERSUFFIX="Sampler",Il.DISABLEUA="#define DISABLE_UNIFORMITY_ANALYSIS",Il.ALPHA_DISABLE=0,Il.ALPHA_ADD=1,Il.ALPHA_COMBINE=2,Il.ALPHA_SUBTRACT=3,Il.ALPHA_MULTIPLY=4,Il.ALPHA_MAXIMIZED=5,Il.ALPHA_ONEONE=6,Il.ALPHA_PREMULTIPLIED=7,Il.ALPHA_PREMULTIPLIED_PORTERDUFF=8,Il.ALPHA_INTERPOLATE=9,Il.ALPHA_SCREENMODE=10,Il.ALPHA_ONEONE_ONEONE=11,Il.ALPHA_ALPHATOCOLOR=12,Il.ALPHA_REVERSEONEMINUS=13,Il.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,Il.ALPHA_ONEONE_ONEZERO=15,Il.ALPHA_EXCLUSION=16,Il.ALPHA_LAYER_ACCUMULATE=17,Il.ALPHA_EQUATION_ADD=0,Il.ALPHA_EQUATION_SUBSTRACT=1,Il.ALPHA_EQUATION_REVERSE_SUBTRACT=2,Il.ALPHA_EQUATION_MAX=3,Il.ALPHA_EQUATION_MIN=4,Il.ALPHA_EQUATION_DARKEN=5,Il.DELAYLOADSTATE_NONE=0,Il.DELAYLOADSTATE_LOADED=1,Il.DELAYLOADSTATE_LOADING=2,Il.DELAYLOADSTATE_NOTLOADED=4,Il.NEVER=512,Il.ALWAYS=519,Il.LESS=513,Il.EQUAL=514,Il.LEQUAL=515,Il.GREATER=516,Il.GEQUAL=518,Il.NOTEQUAL=517,Il.KEEP=7680,Il.ZERO=0,Il.REPLACE=7681,Il.INCR=7682,Il.DECR=7683,Il.INVERT=5386,Il.INCR_WRAP=34055,Il.DECR_WRAP=34056,Il.TEXTURE_CLAMP_ADDRESSMODE=0,Il.TEXTURE_WRAP_ADDRESSMODE=1,Il.TEXTURE_MIRROR_ADDRESSMODE=2,Il.TEXTURE_CREATIONFLAG_STORAGE=1,Il.TEXTUREFORMAT_ALPHA=0,Il.TEXTUREFORMAT_LUMINANCE=1,Il.TEXTUREFORMAT_LUMINANCE_ALPHA=2,Il.TEXTUREFORMAT_RGB=4,Il.TEXTUREFORMAT_RGBA=5,Il.TEXTUREFORMAT_RED=6,Il.TEXTUREFORMAT_R=6,Il.TEXTUREFORMAT_RG=7,Il.TEXTUREFORMAT_RED_INTEGER=8,Il.TEXTUREFORMAT_R_INTEGER=8,Il.TEXTUREFORMAT_RG_INTEGER=9,Il.TEXTUREFORMAT_RGB_INTEGER=10,Il.TEXTUREFORMAT_RGBA_INTEGER=11,Il.TEXTUREFORMAT_BGRA=12,Il.TEXTUREFORMAT_DEPTH24_STENCIL8=13,Il.TEXTUREFORMAT_DEPTH32_FLOAT=14,Il.TEXTUREFORMAT_DEPTH16=15,Il.TEXTUREFORMAT_DEPTH24=16,Il.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17,Il.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18,Il.TEXTUREFORMAT_STENCIL8=19,Il.TEXTUREFORMAT_UNDEFINED=4294967295,Il.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492,Il.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493,Il.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495,Il.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494,Il.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779,Il.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919,Il.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778,Il.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918,Il.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777,Il.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776,Il.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917,Il.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916,Il.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808,Il.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840,Il.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196,Il.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492,Il.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493,Il.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494,Il.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495,Il.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496,Il.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497,Il.TEXTURETYPE_UNSIGNED_BYTE=0,Il.TEXTURETYPE_UNSIGNED_INT=0,Il.TEXTURETYPE_FLOAT=1,Il.TEXTURETYPE_HALF_FLOAT=2,Il.TEXTURETYPE_BYTE=3,Il.TEXTURETYPE_SHORT=4,Il.TEXTURETYPE_UNSIGNED_SHORT=5,Il.TEXTURETYPE_INT=6,Il.TEXTURETYPE_UNSIGNED_INTEGER=7,Il.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,Il.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,Il.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,Il.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,Il.TEXTURETYPE_UNSIGNED_INT_24_8=12,Il.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,Il.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,Il.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,Il.TEXTURETYPE_UNDEFINED=16,Il.TEXTURE_2D=3553,Il.TEXTURE_2D_ARRAY=35866,Il.TEXTURE_CUBE_MAP=34067,Il.TEXTURE_CUBE_MAP_ARRAY=3735928559,Il.TEXTURE_3D=32879,Il.TEXTURE_NEAREST_SAMPLINGMODE=1,Il.TEXTURE_NEAREST_NEAREST=1,Il.TEXTURE_BILINEAR_SAMPLINGMODE=2,Il.TEXTURE_LINEAR_LINEAR=2,Il.TEXTURE_TRILINEAR_SAMPLINGMODE=3,Il.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,Il.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,Il.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,Il.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,Il.TEXTURE_NEAREST_LINEAR=7,Il.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,Il.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,Il.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,Il.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,Il.TEXTURE_LINEAR_NEAREST=12,Il.TEXTURE_EXPLICIT_MODE=0,Il.TEXTURE_SPHERICAL_MODE=1,Il.TEXTURE_PLANAR_MODE=2,Il.TEXTURE_CUBIC_MODE=3,Il.TEXTURE_PROJECTION_MODE=4,Il.TEXTURE_SKYBOX_MODE=5,Il.TEXTURE_INVCUBIC_MODE=6,Il.TEXTURE_EQUIRECTANGULAR_MODE=7,Il.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,Il.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Il.TEXTURE_FILTERING_QUALITY_OFFLINE=4096,Il.TEXTURE_FILTERING_QUALITY_HIGH=64,Il.TEXTURE_FILTERING_QUALITY_MEDIUM=16,Il.TEXTURE_FILTERING_QUALITY_LOW=8,Il.SCALEMODE_FLOOR=1,Il.SCALEMODE_NEAREST=2,Il.SCALEMODE_CEILING=3,Il.MATERIAL_TextureDirtyFlag=1,Il.MATERIAL_LightDirtyFlag=2,Il.MATERIAL_FresnelDirtyFlag=4,Il.MATERIAL_AttributesDirtyFlag=8,Il.MATERIAL_MiscDirtyFlag=16,Il.MATERIAL_PrePassDirtyFlag=32,Il.MATERIAL_AllDirtyFlag=63,Il.MATERIAL_TriangleFillMode=0,Il.MATERIAL_WireFrameFillMode=1,Il.MATERIAL_PointFillMode=2,Il.MATERIAL_PointListDrawMode=3,Il.MATERIAL_LineListDrawMode=4,Il.MATERIAL_LineLoopDrawMode=5,Il.MATERIAL_LineStripDrawMode=6,Il.MATERIAL_TriangleStripDrawMode=7,Il.MATERIAL_TriangleFanDrawMode=8,Il.MATERIAL_ClockWiseSideOrientation=0,Il.MATERIAL_CounterClockWiseSideOrientation=1,Il.ACTION_NothingTrigger=0,Il.ACTION_OnPickTrigger=1,Il.ACTION_OnLeftPickTrigger=2,Il.ACTION_OnRightPickTrigger=3,Il.ACTION_OnCenterPickTrigger=4,Il.ACTION_OnPickDownTrigger=5,Il.ACTION_OnDoublePickTrigger=6,Il.ACTION_OnPickUpTrigger=7,Il.ACTION_OnPickOutTrigger=16,Il.ACTION_OnLongPressTrigger=8,Il.ACTION_OnPointerOverTrigger=9,Il.ACTION_OnPointerOutTrigger=10,Il.ACTION_OnEveryFrameTrigger=11,Il.ACTION_OnIntersectionEnterTrigger=12,Il.ACTION_OnIntersectionExitTrigger=13,Il.ACTION_OnKeyDownTrigger=14,Il.ACTION_OnKeyUpTrigger=15,Il.PARTICLES_BILLBOARDMODE_Y=2,Il.PARTICLES_BILLBOARDMODE_ALL=7,Il.PARTICLES_BILLBOARDMODE_STRETCHED=8,Il.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9,Il.MESHES_CULLINGSTRATEGY_STANDARD=0,Il.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Il.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Il.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,Il.SCENELOADER_NO_LOGGING=0,Il.SCENELOADER_MINIMAL_LOGGING=1,Il.SCENELOADER_SUMMARY_LOGGING=2,Il.SCENELOADER_DETAILED_LOGGING=3,Il.PREPASS_IRRADIANCE_TEXTURE_TYPE=0,Il.PREPASS_POSITION_TEXTURE_TYPE=1,Il.PREPASS_VELOCITY_TEXTURE_TYPE=2,Il.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3,Il.PREPASS_COLOR_TEXTURE_TYPE=4,Il.PREPASS_DEPTH_TEXTURE_TYPE=5,Il.PREPASS_NORMAL_TEXTURE_TYPE=6,Il.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7,Il.PREPASS_WORLD_NORMAL_TEXTURE_TYPE=8,Il.PREPASS_LOCAL_POSITION_TEXTURE_TYPE=9,Il.PREPASS_SCREENSPACE_DEPTH_TEXTURE_TYPE=10,Il.PREPASS_VELOCITY_LINEAR_TEXTURE_TYPE=11,Il.PREPASS_ALBEDO_TEXTURE_TYPE=12,Il.BUFFER_CREATIONFLAG_READ=1,Il.BUFFER_CREATIONFLAG_WRITE=2,Il.BUFFER_CREATIONFLAG_READWRITE=3,Il.BUFFER_CREATIONFLAG_UNIFORM=4,Il.BUFFER_CREATIONFLAG_VERTEX=8,Il.BUFFER_CREATIONFLAG_INDEX=16,Il.BUFFER_CREATIONFLAG_STORAGE=32,Il.BUFFER_CREATIONFLAG_INDIRECT=64,Il.RENDERPASS_MAIN=0,Il.INPUT_ALT_KEY=18,Il.INPUT_CTRL_KEY=17,Il.INPUT_META_KEY1=91,Il.INPUT_META_KEY2=92,Il.INPUT_META_KEY3=93,Il.INPUT_SHIFT_KEY=16,Il.SNAPSHOTRENDERING_STANDARD=0,Il.SNAPSHOTRENDERING_FAST=1,Il.PERSPECTIVE_CAMERA=0,Il.ORTHOGRAPHIC_CAMERA=1,Il.FOVMODE_VERTICAL_FIXED=0,Il.FOVMODE_HORIZONTAL_FIXED=1,Il.RIG_MODE_NONE=0,Il.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,Il.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,Il.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,Il.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,Il.RIG_MODE_STEREOSCOPIC_INTERLACED=14,Il.RIG_MODE_VR=20,Il.RIG_MODE_CUSTOM=22,Il.MAX_SUPPORTED_UV_SETS=6,Il.GL_ALPHA_EQUATION_ADD=32774,Il.GL_ALPHA_EQUATION_MIN=32775,Il.GL_ALPHA_EQUATION_MAX=32776,Il.GL_ALPHA_EQUATION_SUBTRACT=32778,Il.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779,Il.GL_ALPHA_FUNCTION_SRC=768,Il.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769,Il.GL_ALPHA_FUNCTION_SRC_ALPHA=770,Il.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771,Il.GL_ALPHA_FUNCTION_DST_ALPHA=772,Il.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773,Il.GL_ALPHA_FUNCTION_DST_COLOR=774,Il.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775,Il.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776,Il.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769,Il.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770,Il.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771,Il.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772,Il.GL_ALPHA_FUNCTION_SRC1_COLOR=35065,Il.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_COLOR=35066,Il.GL_ALPHA_FUNCTION_SRC1_ALPHA=34185,Il.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_ALPHA=35067,Il.SnippetUrl="https://snippet.babylonjs.com",Il.FOGMODE_NONE=0,Il.FOGMODE_EXP=1,Il.FOGMODE_EXP2=2,Il.FOGMODE_LINEAR=3,Il.BYTE=5120,Il.UNSIGNED_BYTE=5121,Il.SHORT=5122,Il.UNSIGNED_SHORT=5123,Il.INT=5124,Il.UNSIGNED_INT=5125,Il.FLOAT=5126,Il.PositionKind="position",Il.NormalKind="normal",Il.TangentKind="tangent",Il.UVKind="uv",Il.UV2Kind="uv2",Il.UV3Kind="uv3",Il.UV4Kind="uv4",Il.UV5Kind="uv5",Il.UV6Kind="uv6",Il.ColorKind="color",Il.ColorInstanceKind="instanceColor",Il.MatricesIndicesKind="matricesIndices",Il.MatricesWeightsKind="matricesWeights",Il.MatricesIndicesExtraKind="matricesIndicesExtra",Il.MatricesWeightsExtraKind="matricesWeightsExtra";var Ml=i(82352),Ol=i(61340);class Dl{constructor(){this.renderWidth=512,this.renderHeight=256,this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4}}class wl extends an{isDeterministicLockStep(){return this._options.deterministicLockstep}getLockstepMaxSteps(){return this._options.lockstepMaxSteps}getHardwareScalingLevel(){return 1}constructor(e=new Dl){super(null),void 0===e.deterministicLockstep&&(e.deterministicLockstep=!1),void 0!==e.timeStep&&(this._timeStep=e.timeStep),void 0===e.lockstepMaxSteps&&(e.lockstepMaxSteps=4),this._options=e,Ml.I.SetMatrixPrecision(!!e.useHighPrecisionMatrix),this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:512,maxCubemapTextureSize:512,maxDrawBuffers:0,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!1,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:0,uintIndices:!1,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloat:!1,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!1,textureLOD:!1,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!1,instancedArrays:!1,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,maxMSAASamples:1,blendMinMax:!1,canUseGLInstanceID:!1,canUseGLVertexID:!1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:128,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!1,supportSSAO2:!1,supportIBLShadows:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!1,_collectUbosUpdatedInFrame:!1},e.renderingCanvas&&(this._renderingCanvas=e.renderingCanvas),Z.V.Log(`Babylon.js v${an.Version} - Null engine`);const t="undefined"!=typeof self?self:void 0!==i.g?i.g:window;"undefined"==typeof URL&&(t.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(t.Blob=function(){})}createVertexBuffer(e){const t=new pr.n;return t.references=1,t}createIndexBuffer(e){const t=new pr.n;return t.references=1,t}clear(e,t,i,r=!1){}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._options.renderWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._options.renderHeight}setViewport(e,t,i){this._cachedViewport=e}createShaderProgram(e,t,i,r,s){return{__SPECTOR_rebuildProgram:null}}getUniforms(e,t){return[]}getAttributes(e,t){return[]}bindSamplers(e){this._currentEffect=null}enableEffect(e){e=null!==e&&(0,Ol.E)(e)?e.effect:e,this._currentEffect=e,e&&(e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setState(e,t=0,i,r=!1,s,n,o=0){}setIntArray(e,t){return!0}setIntArray2(e,t){return!0}setIntArray3(e,t){return!0}setIntArray4(e,t){return!0}setFloatArray(e,t){return!0}setFloatArray2(e,t){return!0}setFloatArray3(e,t){return!0}setFloatArray4(e,t){return!0}setArray(e,t){return!0}setArray2(e,t){return!0}setArray3(e,t){return!0}setArray4(e,t){return!0}setMatrices(e,t){return!0}setMatrix3x3(e,t){return!0}setMatrix2x2(e,t){return!0}setFloat(e,t){return!0}setFloat2(e,t,i){return!0}setFloat3(e,t,i,r){return!0}setBool(e,t){return!0}setFloat4(e,t,i,r,s){return!0}setAlphaMode(e,t=!1){this._alphaMode!==e&&(this.alphaState.alphaBlend=0!==e,t||this.setDepthWrite(0===e),this._alphaMode=e)}bindBuffers(e,t,i){}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this.depthCullingState.reset(),this.alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}draw(e,t,i,r){}drawElementsType(e,t,i,r){}drawArraysType(e,t,i,r){}_createTexture(){return{}}_releaseTexture(e){}createTexture(e,t,i,r,s=3,n=null,o=null,a=null,l=null,h=null,c=null,u){const d=new Fs.h(this,1),f=String(e);return d.url=f,d.generateMipMaps=!t,d.samplingMode=s,d.invertY=i,d.baseWidth=this._options.textureSize,d.baseHeight=this._options.textureSize,d.width=this._options.textureSize,d.height=this._options.textureSize,h&&(d.format=h),d.isReady=!0,n&&setTimeout((()=>{n(d)})),this._internalTexturesCache.push(d),d}_createHardwareRenderTargetWrapper(e,t,i){const r=new qs(e,t,i,this);return this._renderTargetWrapperCache.push(r),r}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e),r={};void 0!==t&&"object"==typeof t?(r.generateMipMaps=t.generateMipMaps,r.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,r.generateStencilBuffer=r.generateDepthBuffer&&t.generateStencilBuffer,r.type=void 0===t.type?0:t.type,r.samplingMode=void 0===t.samplingMode?3:t.samplingMode):(r.generateMipMaps=t,r.generateDepthBuffer=!0,r.generateStencilBuffer=!1,r.type=0,r.samplingMode=3);const s=new Fs.h(this,5),n=e.width||e,o=e.height||e;return i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=!!r.generateStencilBuffer,s.baseWidth=n,s.baseHeight=o,s.width=n,s.height=o,s.isReady=!0,s.samples=1,s.generateMipMaps=!!r.generateMipMaps,s.samplingMode=r.samplingMode,s.type=r.type,this._internalTexturesCache.push(s),i}createRenderTargetCubeTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),r={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};r.generateStencilBuffer=r.generateDepthBuffer&&r.generateStencilBuffer,(1!==r.type||this._caps.textureFloatLinearFiltering)&&(2!==r.type||this._caps.textureHalfFloatLinearFiltering)||(r.samplingMode=1),i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=!!r.generateStencilBuffer;const s=new Fs.h(this,5);return s.baseWidth=e,s.baseHeight=e,s.width=e,s.height=e,s.isReady=!0,s.isCube=!0,s.samples=1,s.generateMipMaps=!!r.generateMipMaps,s.samplingMode=r.samplingMode,s.type=r.type,this._internalTexturesCache.push(s),i}updateTextureSamplingMode(e,t){t.samplingMode=e}createRawTexture(e,t,i,r,s,n,o,a=null,l=0,h=0,c=!1){const u=new Fs.h(this,3);return u.baseWidth=t,u.baseHeight=i,u.width=t,u.height=i,u.format=r,u.generateMipMaps=s,u.samplingMode=o,u.invertY=n,u._compression=a,u.type=l,u._useSRGBBuffer=c,this._doNotHandleContextLost||(u._bufferView=e),u}updateRawTexture(e,t,i,r,s=null,n=0,o=!1){e&&(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s,e.type=n,e._useSRGBBuffer=o)}bindFramebuffer(e,t,i,r,s){this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._currentFramebuffer=null,this._cachedViewport&&!s&&this.setViewport(this._cachedViewport,i,r)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._currentFramebuffer=null}createDynamicVertexBuffer(e){const t=new pr.n;return t.references=1,t.capacity=1,t}updateDynamicTexture(e,t,i,r=!1,s){}areAllEffectsReady(){return!0}getError(){return 0}_getUnpackAlignement(){return 1}_unpackFlipY(e){}updateDynamicIndexBuffer(e,t,i=0){}updateDynamicVertexBuffer(e,t,i,r){}_bindTextureDirectly(e,t){return this._boundTexturesCache[this._activeChannel]!==t&&(this._boundTexturesCache[this._activeChannel]=t,!0)}_bindTexture(e,t){e<0||this._bindTextureDirectly(0,t)}_deleteBuffer(e){}releaseEffects(){}displayLoadingUI(){}hideLoadingUI(){}set loadingUIText(e){}flushFramebuffer(){}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,n=0,o=0){}_uploadDataToTextureDirectly(e,t,i=0,r=0){}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){}_uploadImageToTexture(e,t,i=0,r=0){}}i(7244);class Nl{constructor(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=Nt.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=Nt.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE,this.forceRenderingWhenOccluded=!1}}Ot.$.prototype.getGPUFrameTimeCounter=function(){return null},Ot.$.prototype.captureGPUFrameTime=function(e){},Ot.$.prototype.createQuery=function(){return null},Ot.$.prototype.deleteQuery=function(e){return this},Ot.$.prototype.isQueryResultAvailable=function(e){return!1},Ot.$.prototype.getQueryResult=function(e){return 0},Ot.$.prototype.beginOcclusionQuery=function(e,t){return!1},Ot.$.prototype.endOcclusionQuery=function(e){return this},Object.defineProperty(Nt.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(e){this._occlusionDataStorage.isOcclusionQueryInProgress=e},enumerable:!1,configurable:!0}),Object.defineProperty(Nt.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new Nl),this.__occlusionDataStorage},enumerable:!1,configurable:!0}),Object.defineProperty(Nt.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(e){this._occlusionDataStorage.isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(Nt.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(e){this._occlusionDataStorage.occlusionQueryAlgorithmType=e},enumerable:!0,configurable:!0}),Object.defineProperty(Nt.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(e){this._occlusionDataStorage.occlusionType=e},enumerable:!0,configurable:!0}),Object.defineProperty(Nt.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(e){this._occlusionDataStorage.occlusionRetryCount=e},enumerable:!0,configurable:!0}),Object.defineProperty(Nt.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(e){this._occlusionDataStorage.forceRenderingWhenOccluded=e},enumerable:!0,configurable:!0}),Nt.prototype._checkOcclusionQuery=function(){const e=this._occlusionDataStorage;if(e.occlusionType===Nt.OCCLUSION_TYPE_NONE)return e.isOccluded=!1,!1;const t=this.getEngine();if(!t.getCaps().supportOcclusionQuery)return e.isOccluded=!1,!1;if(!t.isQueryResultAvailable)return e.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&null!==this._occlusionQuery&&void 0!==this._occlusionQuery)if(t.isQueryResultAvailable(this._occlusionQuery)){const i=t.getQueryResult(this._occlusionQuery);e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=!(i>0)}else{if(e.occlusionInternalRetryCounter++,!(-1!==e.occlusionRetryCount&&e.occlusionInternalRetryCounter>e.occlusionRetryCount))return e.occlusionType!==Nt.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==Nt.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}const i=this.getScene();if(i.getBoundingBoxRenderer){const r=i.getBoundingBoxRenderer();null===this._occlusionQuery&&(this._occlusionQuery=t.createQuery()),this._occlusionQuery&&t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery)&&(r.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return e.isOccluded};class Fl{}const Ll=new z.cP,Bl=new z.cP;Object.defineProperty(Ot.$.prototype,"onBeforeViewRenderObservable",{get:function(){return Ll}}),Object.defineProperty(Ot.$.prototype,"onAfterViewRenderObservable",{get:function(){return Bl}}),Object.defineProperty(Ot.$.prototype,"inputElement",{get:function(){return this._inputElement},set:function(e){this._inputElement!==e&&(this._inputElement=e,this._onEngineViewChanged?.())}}),Ot.$.prototype.getInputElement=function(){return this.inputElement||this.getRenderingCanvas()},Ot.$.prototype.registerView=function(e,t,i){this.views||(this.views=[]);for(const t of this.views)if(t.target===e)return t;const r=this.getRenderingCanvas();r&&(e.width=r.width,e.height=r.height);const s={target:e,camera:t,clearBeforeCopy:i,enabled:!0,id:(1e5*Math.random()).toFixed()};return this.views.push(s),t&&!Array.isArray(t)&&t.onDisposeObservable.add((()=>{this.unRegisterView(e)})),s},Ot.$.prototype.unRegisterView=function(e){if(!this.views||0===this.views.length)return this;for(const t of this.views)if(t.target===e){const e=this.views.indexOf(t);-1!==e&&this.views.splice(e,1);break}return this},Ot.$.prototype._renderViewStep=function(e){const t=e.target,i=t.getContext("2d");if(!i)return!0;const r=this.getRenderingCanvas();Ll.notifyObservers(e);const s=e.camera;let n=null,o=null,a=null;if(s&&(a=Array.isArray(s)?s[0].getScene():s.getScene(),n=a.activeCamera,o=a.activeCameras,Array.isArray(s)?a.activeCameras=s:(a.activeCamera=s,a.activeCameras=null)),this.activeView=e,e.customResize)e.customResize(t);else{const e=Math.floor(t.clientWidth/this._hardwareScalingLevel),i=Math.floor(t.clientHeight/this._hardwareScalingLevel),s=e!==t.width||r.width!==t.width||i!==t.height||r.height!==t.height;t.clientWidth&&t.clientHeight&&s&&(t.width=e,t.height=i,this.setSize(e,i))}return!(!r.width||!r.height||(this._renderFrame(),this.flushFramebuffer(),e.clearBeforeCopy&&i.clearRect(0,0,r.width,r.height),i.drawImage(r,0,0),a&&(a.activeCameras=o,a.activeCamera=n),Bl.notifyObservers(e),0))},Ot.$.prototype._renderViews=function(){if(!this.views||0===this.views.length)return!1;if(!this.getRenderingCanvas())return!1;let e;for(const t of this.views)if(t.enabled)if(t.target!==this.inputElement){if(!this._renderViewStep(t))return!1}else e=t;return!(e&&!this._renderViewStep(e)||(this.activeView=null,0))},Ot.$.prototype._debugPushGroup=function(e,t){},Ot.$.prototype._debugPopGroup=function(e){},Ot.$.prototype._debugInsertMarker=function(e,t){},Ot.$.prototype._debugFlushPendingCommands=function(){};class Vl{constructor(){this._timeElapsedQueryEnded=!1}}an.prototype.createQuery=function(){const e=this._gl.createQuery();if(!e)throw new Error("Unable to create Occlusion Query");return e},an.prototype.deleteQuery=function(e){return this._gl.deleteQuery(e),this},an.prototype.isQueryResultAvailable=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT_AVAILABLE)},an.prototype.getQueryResult=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT)},an.prototype.beginOcclusionQuery=function(e,t){const i=this._getGlAlgorithmType(e);return this._gl.beginQuery(i,t),!0},an.prototype.endOcclusionQuery=function(e){const t=this._getGlAlgorithmType(e);return this._gl.endQuery(t),this},an.prototype._createTimeQuery=function(){const e=this.getCaps().timerQuery;return e.createQueryEXT?e.createQueryEXT():this.createQuery()},an.prototype._deleteTimeQuery=function(e){const t=this.getCaps().timerQuery;t.deleteQueryEXT?t.deleteQueryEXT(e):this.deleteQuery(e)},an.prototype._getTimeQueryResult=function(e){const t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT):this.getQueryResult(e)},an.prototype._getTimeQueryAvailability=function(e){const t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(e)},an.prototype.startTimeQuery=function(){const e=this.getCaps(),t=e.timerQuery;if(!t)return null;const i=new Vl;if(this._gl.getParameter(t.GPU_DISJOINT_EXT),e.canUseTimestampForTimerQuery)i._startTimeQuery=this._createTimeQuery(),i._startTimeQuery&&t.queryCounterEXT(i._startTimeQuery,t.TIMESTAMP_EXT);else{if(this._currentNonTimestampToken)return this._currentNonTimestampToken;i._timeElapsedQuery=this._createTimeQuery(),i._timeElapsedQuery&&(t.beginQueryEXT?t.beginQueryEXT(t.TIME_ELAPSED_EXT,i._timeElapsedQuery):this._gl.beginQuery(t.TIME_ELAPSED_EXT,i._timeElapsedQuery)),this._currentNonTimestampToken=i}return i},an.prototype.endTimeQuery=function(e){const t=this.getCaps(),i=t.timerQuery;if(!i||!e)return-1;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery)return-1;e._endTimeQuery||(e._endTimeQuery=this._createTimeQuery(),e._endTimeQuery&&i.queryCounterEXT(e._endTimeQuery,i.TIMESTAMP_EXT))}else if(!e._timeElapsedQueryEnded){if(!e._timeElapsedQuery)return-1;i.endQueryEXT?i.endQueryEXT(i.TIME_ELAPSED_EXT):(this._gl.endQuery(i.TIME_ELAPSED_EXT),this._currentNonTimestampToken=null),e._timeElapsedQueryEnded=!0}const r=this._gl.getParameter(i.GPU_DISJOINT_EXT);let s=!1;if(e._endTimeQuery?s=this._getTimeQueryAvailability(e._endTimeQuery):e._timeElapsedQuery&&(s=this._getTimeQueryAvailability(e._timeElapsedQuery)),s&&!r){let i=0;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery||!e._endTimeQuery)return-1;const t=this._getTimeQueryResult(e._startTimeQuery);i=this._getTimeQueryResult(e._endTimeQuery)-t,this._deleteTimeQuery(e._startTimeQuery),this._deleteTimeQuery(e._endTimeQuery),e._startTimeQuery=null,e._endTimeQuery=null}else{if(!e._timeElapsedQuery)return-1;i=this._getTimeQueryResult(e._timeElapsedQuery),this._deleteTimeQuery(e._timeElapsedQuery),e._timeElapsedQuery=null,e._timeElapsedQueryEnded=!1}return i}return-1},an.prototype._captureGPUFrameTime=!1,an.prototype._gpuFrameTime=new on.A,an.prototype.getGPUFrameTimeCounter=function(){return this._gpuFrameTime},an.prototype.captureGPUFrameTime=function(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,e?(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))},an.prototype._getGlAlgorithmType=function(e){return e===Nt.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED};var kl,Ul=!0;function Gl(e){if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some((t=>{const i="\\b"+t+"\\b";return e&&(e===t||e.match(new RegExp(i,"g")))})))return e;const t=e.lastIndexOf("."),i=e.lastIndexOf("?"),r=i>-1?e.substring(i,e.length):"";return(t>-1?e.substring(0,t):e)+this._textureFormatInUse+r}an.prototype.createTransformFeedback=function(){const e=this._gl.createTransformFeedback();if(!e)throw new Error("Unable to create Transform Feedback");return e},an.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},an.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},an.prototype.beginTransformFeedback=function(e=!0){this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},an.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},an.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},an.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)},an.prototype.readTransformFeedbackBuffer=function(e){this._gl.getBufferSubData(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e)},Ls.ThinEngine.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;const r=this._getInternalFormat(e.format),s=this._getRGBABufferInternalSizedFormat(0,e.format),n=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=this.createCanvas(e.width,e.height);const t=e._workingCanvas.getContext("2d");if(!t)throw new Error("Unable to get 2d context");e._workingContext=t,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.clearRect(0,0,e.width,e.height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),n||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}},Ls.ThinEngine.prototype.restoreSingleAttachment=function(){const e=this._gl;this.bindAttachments([e.BACK])},Ls.ThinEngine.prototype.restoreSingleAttachmentForRenderTarget=function(){const e=this._gl;this.bindAttachments([e.COLOR_ATTACHMENT0])},Ls.ThinEngine.prototype.buildTextureLayout=function(e){const t=this._gl,i=[];for(let r=0;r1?"COLOR_ATTACHMENT"+t:"COLOR_ATTACHMENT"+t+"_WEBGL"],r.readBuffer(s[t]),r.drawBuffers(s),r.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,r.COLOR_BUFFER_BIT,r.NEAREST)}for(let e=0;e1?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];r.drawBuffers(s)}for(let i=0;i1&&(13===t.depthTextureFormat||17===t.depthTextureFormat||16===t.depthTextureFormat||14===t.depthTextureFormat||18===t.depthTextureFormat)&&(a=t.depthTextureFormat));const b=this._gl,S=b.createFramebuffer();this._bindUnboundFramebuffer(S);const T=e.width??e,C=e.height??e,y=[],E=[],P=this.webGLVersion>1&&(13===a||17===a||18===a);x.label=t?.label??"MultiRenderTargetWrapper",x._framebuffer=S,x._generateDepthBuffer=o||s,x._generateStencilBuffer=o?P:n,x._depthStencilBuffer=this._setupFramebufferDepthAttachments(x._generateStencilBuffer,x._generateDepthBuffer,T,C,1,a),x._attachments=E;for(let e=0;e1||this.isWebGPU);const h=this.webGLVersion>1,_=b[h?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];if(E.push(_),-1===o)continue;const m=new Fs.h(this,6);y[e]=m,b.activeTexture(b["TEXTURE"+e]),b.bindTexture(o,m._hardwareTexture.underlyingResource),b.texParameteri(o,b.TEXTURE_MAG_FILTER,l.mag),b.texParameteri(o,b.TEXTURE_MIN_FILTER,l.min),b.texParameteri(o,b.TEXTURE_WRAP_S,b.CLAMP_TO_EDGE),b.texParameteri(o,b.TEXTURE_WRAP_T,b.CLAMP_TO_EDGE);const S=this._getRGBABufferInternalSizedFormat(i,n,s),P=this._getInternalFormat(n),A=this._getWebGLTextureType(i);if(!h||35866!==o&&32879!==o)if(34067===o){for(let e=0;e<6;e++)b.texImage2D(b.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,S,T,C,0,P,A,null);m.isCube=!0}else b.texImage2D(b.TEXTURE_2D,0,S,T,C,0,P,A,null);else 35866===o?m.is2DArray=!0:m.is3D=!0,m.baseDepth=m.depth=a,b.texImage3D(o,0,S,T,C,a,0,P,A,null);r&&b.generateMipmap(o),this._bindTextureDirectly(o,null),m.baseWidth=T,m.baseHeight=C,m.width=T,m.height=C,m.isReady=!0,m.samples=1,m.generateMipMaps=r,m.samplingMode=t,m.type=i,m._useSRGBBuffer=s,m.format=n,m.label=v[e]??x.label+"-Texture"+e,this._internalTexturesCache.push(m)}if(o&&this._caps.depthTextureExtension){const e=new Fs.h(this,14);let t=5,i=b.DEPTH_COMPONENT16,s=b.DEPTH_COMPONENT,n=b.UNSIGNED_SHORT,o=b.DEPTH_ATTACHMENT;this.webGLVersion<2?i=b.DEPTH_COMPONENT:14===a?(t=1,n=b.FLOAT,i=b.DEPTH_COMPONENT32F):18===a?(t=0,n=b.FLOAT_32_UNSIGNED_INT_24_8_REV,i=b.DEPTH32F_STENCIL8,s=b.DEPTH_STENCIL,o=b.DEPTH_STENCIL_ATTACHMENT):16===a?(t=0,n=b.UNSIGNED_INT,i=b.DEPTH_COMPONENT24,o=b.DEPTH_ATTACHMENT):13!==a&&17!==a||(t=12,n=b.UNSIGNED_INT_24_8,i=b.DEPTH24_STENCIL8,s=b.DEPTH_STENCIL,o=b.DEPTH_STENCIL_ATTACHMENT),this._bindTextureDirectly(b.TEXTURE_2D,e,!0),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MAG_FILTER,b.NEAREST),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MIN_FILTER,b.NEAREST),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_S,b.CLAMP_TO_EDGE),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_T,b.CLAMP_TO_EDGE),b.texImage2D(b.TEXTURE_2D,0,i,T,C,0,s,n,null),b.framebufferTexture2D(b.FRAMEBUFFER,o,b.TEXTURE_2D,e._hardwareTexture.underlyingResource,0),this._bindTextureDirectly(b.TEXTURE_2D,null),x._depthStencilTexture=e,x._depthStencilTextureWithStencil=P,e.baseWidth=T,e.baseHeight=C,e.width=T,e.height=C,e.isReady=!0,e.samples=1,e.generateMipMaps=r,e.samplingMode=1,e.format=a,e.type=t,e.label=x.label+"-DepthStencil",y[l]=e,this._internalTexturesCache.push(e)}return x.setTextures(y),i&&b.drawBuffers(E),this._bindUnboundFramebuffer(null),x.setLayerAndFaceIndices(m,_),this.resetTextureCache(),this.updateMultipleRenderTargetTextureSampleCount(x,h,i),x},Ls.ThinEngine.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t,i=!0){if(this.webGLVersion<2||!e)return 1;if(e.samples===t)return t;const r=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(r.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(r.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null);const s=e._attachments.length;for(let t=0;t1&&"function"==typeof r.renderbufferStorageMultisample){const n=r.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=n,this._bindUnboundFramebuffer(n);const o=[];for(let i=0;i1?"COLOR_ATTACHMENT"+i:"COLOR_ATTACHMENT"+i+"_WEBGL"],l=this._createRenderBuffer(s.width,s.height,t,-1,this._getRGBABufferInternalSizedFormat(s.type,s.format,s._useSRGBBuffer),a);if(!l)throw new Error("Unable to create multi sampled framebuffer");n.addMSAARenderBuffer(l),s.samples=t,o.push(a)}i&&r.drawBuffers(o)}else this._bindUnboundFramebuffer(e._framebuffer);const n=e._depthStencilTexture?e._depthStencilTexture.format:void 0;return e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.width,e.height,t,n),this._bindUnboundFramebuffer(null),e._samples=t,t},function(e){e[e.Texture=0]="Texture",e[e.StorageTexture=1]="StorageTexture",e[e.UniformBuffer=2]="UniformBuffer",e[e.StorageBuffer=3]="StorageBuffer",e[e.TextureWithoutSampler=4]="TextureWithoutSampler",e[e.Sampler=5]="Sampler",e[e.ExternalTexture=6]="ExternalTexture",e[e.DataBuffer=7]="DataBuffer"}(kl||(kl={})),Ls.ThinEngine.prototype.createComputeEffect=function(e,t){throw new Error("createComputeEffect: This engine does not support compute shaders!")},Ls.ThinEngine.prototype.createComputePipelineContext=function(){throw new Error("createComputePipelineContext: This engine does not support compute shaders!")},Ls.ThinEngine.prototype.createComputeContext=function(){},Ls.ThinEngine.prototype.computeDispatch=function(e,t,i,r,s,n,o){throw new Error("computeDispatch: This engine does not support compute shaders!")},Ls.ThinEngine.prototype.computeDispatchIndirect=function(e,t,i,r,s,n){throw new Error("computeDispatchIndirect: This engine does not support compute shaders!")},Ls.ThinEngine.prototype.areAllComputeEffectsReady=function(){return!0},Ls.ThinEngine.prototype.releaseComputeEffects=function(){},Ls.ThinEngine.prototype._prepareComputePipelineContext=function(e,t,i,r,s){},Ls.ThinEngine.prototype._rebuildComputeEffects=function(){},Ot.$.prototype._executeWhenComputeStateIsCompiled=function(e,t){t(null)},Ls.ThinEngine.prototype._releaseComputeEffect=function(e){},Ls.ThinEngine.prototype._deleteComputePipelineContext=function(e){},Object.defineProperty(an.prototype,"texturesSupported",{get:function(){const e=[];return this._caps.astc&&e.push("-astc.ktx"),this._caps.s3tc&&e.push("-dxt.ktx"),this._caps.pvrtc&&e.push("-pvrtc.ktx"),this._caps.etc2&&e.push("-etc2.ktx"),this._caps.etc1&&e.push("-etc1.ktx"),e},enumerable:!0,configurable:!0}),Object.defineProperty(an.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0}),an.prototype.setCompressedTextureExclusions=function(e){this._excludedCompressedTextures=e},an.prototype.setTextureFormatToUse=function(e){const t=this.texturesSupported;for(let i=0,r=t.length;i{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}}zl.DEFAULT_BUFFER_SIZE=65536;var Wl=i(48195);function Hl(e,t,i,r){let s=r,n=0,o="";for(;s=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95==t}function Yl(e){let t=0,i="",r=!1;const s=[];for(;t=0&&e.charAt(t)!==i&&(!r||e.charAt(t)!==r);)t--;return t}function jl(e,t,i,r){let s=e.indexOf(t);if(s<0)return e;if(i){for(;s++=0&&d.push(t.substring(i+1))}"void"!==s&&d.push("return"),this._functionDescr.push({name:n,type:s,parameters:d,body:c,callIndex:0}),e=h+1;const f=t>0?this._sourceCode.substring(0,t):"",p=h+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&Z.V.Log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(const t of this._functionDescr){const{name:i,type:r,parameters:s,body:n}=t;let o=0;for(;o{const t=[];let i=0,r=0;for(;i0?this._sourceCode.substring(0,a):"";const g=h+1{const a=s[0];return ql(e.charAt(a-1))||ql(e.charAt(a+n))?t[r]:o}))}return e}}$l._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;const Ql=/(flat\s)?\s*varying\s*.*/;class Zl{constructor(){this.shaderLanguage=0}initializeShaders(e){this._nativeProcessingContext=e,this._nativeProcessingContext&&(this._nativeProcessingContext.remappedAttributeNames={},this._nativeProcessingContext.injectInVertexMain="")}attributeProcessor(e){if(!this._nativeProcessingContext)return e.replace("attribute","in");const t=/\s*(?:attribute|in)\s+(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==t){const i=t[1],r=t[2],s=this._nativeProcessingContext.vertexBufferKindToNumberOfComponents[r];if(void 0!==s){const n=s<0?-1===s?"int":"ivec"+-s:1===s?"uint":"uvec"+s,o=`_int_${r}_`;e=e.replace(t[0],`in ${n} ${o}; ${i} ${r};`),this._nativeProcessingContext.injectInVertexMain+=`${r} = ${i}(${o});\n`,this._nativeProcessingContext.remappedAttributeNames[r]=o}else e=e.replace(t[0],`in ${i} ${r};`)}return e}varyingCheck(e,t){return Ql.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const r=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){const t=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(r||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else if(this._nativeProcessingContext?.injectInVertexMain&&(e=jl(e,"void main",this._nativeProcessingContext.injectInVertexMain)),-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e}}class Jl{get isReady(){if(this.compilationError){const e=this.compilationError.message;throw new Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}return this.isCompiled}_getVertexShaderCode(){return null}_getFragmentShaderCode(){return null}constructor(e,t,i){this.isCompiled=!1,this.vertexBufferKindToType={},this._valueCache={},this._engine=e,this.isAsync=t,this.shaderProcessingContext=i}_fillEffectInformation(e,t,i,r,s,n,o,a){const l=this._engine;if(l.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let h;for(this._engine.getUniforms(this,i).forEach(((e,t)=>{r[i[t]]=e})),this._uniforms=r,h=0;h{n[e]=t})),a.push(...l.getAttributes(this,o))}setEngine(e){this._engine=e}dispose(){this._uniforms={}}_cacheMatrix(e,t){const i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s)return s=[t,i,r],this._valueCache[e]=s,!0;let n=!1;return s[0]!==t&&(s[0]=t,n=!0),s[1]!==i&&(s[1]=i,n=!0),s[2]!==r&&(s[2]=r,n=!0),n}_cacheFloat4(e,t,i,r,s){let n=this._valueCache[e];if(!n)return n=[t,i,r,s],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]!==r&&(n[2]=r,o=!0),n[3]!==s&&(n[3]=s,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this._engine.setInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this._engine.setInt4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this._engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this._engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this._engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this._engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this._engine.setUInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this._engine.setUInt4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this._engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this._engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this._engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this._engine.setUIntArray4(this._uniforms[e],t)}setFloatArray(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)}setFloatArray2(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)}setFloatArray3(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)}setFloatArray4(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this._engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this._engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this._engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this._engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this._engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this._engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this._engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this._engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this._engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this._engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this._engine.setFloat3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this._engine.setFloat4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this._engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}}class eh extends qs{get _framebuffer(){return this.__framebuffer}set _framebuffer(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e}get _framebufferDepthStencil(){return this.__framebufferDepthStencil}set _framebufferDepthStencil(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e}constructor(e,t,i,r){super(e,t,i,r),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=r}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}}class th{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 ih(e,t){switch(e){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: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(t){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(t){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(t){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(t){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:if(0===t)return _native.Engine.TEXTURE_FORMAT_BGRA8}throw new nt.bu(`Unsupported texture format or type: format ${e}, type ${t}.`,nt.tG.UnsupportedTextureError)}function rh(e){switch(e){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: ${e}.`)}}function sh(e){switch(e){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: "+e+".")}}function nh(e){switch(e){case st.R.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case st.R.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case st.R.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case st.R.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case st.R.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error(`Unsupported attribute type: ${e}.`)}}const oh={[st.R.PositionKind]:!0,[st.R.NormalKind]:!0,[st.R.TangentKind]:!0,[st.R.UVKind]:!0,[st.R.UV2Kind]:!0,[st.R.UV3Kind]:!0,[st.R.UV4Kind]:!0,[st.R.UV5Kind]:!0,[st.R.UV6Kind]:!0,[st.R.ColorKind]:!0,[st.R.ColorInstanceKind]:!0,[st.R.MatricesIndicesKind]:!0,[st.R.MatricesWeightsKind]:!0,[st.R.MatricesIndicesExtraKind]:!0,[st.R.MatricesWeightsExtraKind]:!0};function ah(e){switch(e){case st.R.BYTE:case st.R.SHORT:case st.R.INT:case st.R.FLOAT:return!0;case st.R.UNSIGNED_BYTE:case st.R.UNSIGNED_SHORT:case st.R.UNSIGNED_INT:return!1;default:throw new Error(`Invalid type '${e}'`)}}function lh(e,t){const i=t.getEngine(),r=t._pipelineContext;if(!r?.vertexBufferKindToType)return;let s=null;for(const n in e){const o=e[n];if(!o||!oh[n])continue;const a=o.normalized?st.R.FLOAT:o.type,l=r.vertexBufferKindToType[n];(a!==st.R.FLOAT&&void 0===l||void 0!==l&&l!==a)&&(s||(s=i._getShaderProcessingContext(t.shaderLanguage,!1)),r.vertexBufferKindToType[n]=a,a!==st.R.FLOAT&&(s.vertexBufferKindToNumberOfComponents[n]=st.R.DeduceStride(n),ah(a)&&(s.vertexBufferKindToNumberOfComponents[n]*=-1)))}if(s){const e=i._caps.parallelShaderCompile;i._caps.parallelShaderCompile=void 0,t._processShaderCodeAsync(null,i._features._checkNonFloatVertexBuffersDontRecreatePipelineContext,s),i._caps.parallelShaderCompile=e}}class hh{constructor(){this.vertexBufferKindToNumberOfComponents={},this.remappedAttributeNames={},this.injectInVertexMain=""}}var ch=i(47221);const uh=new z.cP;if("undefined"!=typeof self&&!Object.prototype.hasOwnProperty.call(self,"_native")){let e;Object.defineProperty(self,"_native",{get:()=>e,set:t=>{e=t,e&&uh.notifyObservers(e)}})}function dh(){return new Promise((e=>{"undefined"==typeof _native?uh.addOnce((t=>e(t))):e(_native)}))}async function fh(e,t){(await dh())[e]=t}class ph extends pr.n{}class _h{constructor(e){this._engine=e,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=gh._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}beginCommandScope(){if(this._isCommandBufferScopeActive)throw new Error("Command scope already active.");this._isCommandBufferScopeActive=!0}endCommandScope(){if(!this._isCommandBufferScopeActive)throw new Error("Command scope is not active.");this._isCommandBufferScopeActive=!1,this._submit()}startEncodingCommand(e){this._commandStream.writeNativeData(e)}encodeCommandArgAsUInt32(e){this._commandStream.writeUint32(e)}encodeCommandArgAsUInt32s(e){this._commandStream.writeUint32Array(e)}encodeCommandArgAsInt32(e){this._commandStream.writeInt32(e)}encodeCommandArgAsInt32s(e){this._commandStream.writeInt32Array(e)}encodeCommandArgAsFloat32(e){this._commandStream.writeFloat32(e)}encodeCommandArgAsFloat32s(e){this._commandStream.writeFloat32Array(e)}encodeCommandArgAsNativeData(e){this._commandStream.writeNativeData(e),this._pending.push(e)}finishEncodingCommand(){this._isCommandBufferScopeActive||this._submit()}_submit(){this._engine.submitCommands(),this._pending.length=0}}const mh=[];class gh extends an{setHardwareScalingLevel(e){super.setHardwareScalingLevel(e),this._engine.setHardwareScalingLevel(e)}constructor(e={}){if(super(null,!1,void 0,e.adaptToDeviceRatio),this._engine=new _native.Engine({version:an.Version,nonFloatVertexBuffers:!0}),this._camera=_native.Camera?new _native.Camera:null,this._commandBufferEncoder=new _h(this._engine),this._boundBuffersVertexArray=null,this._currentDepthTest=_native.Engine.DEPTH_TEST_LEQUAL,this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=519,this._stencilFuncRef=0,this._stencilFuncMask=255,this._stencilOpStencilFail=7680,this._stencilOpDepthFail=7680,this._stencilOpStencilDepthPass=7681,this._zOffset=0,this._zOffsetUnits=0,this._depthWrite=!0,this._fillModeWarningDisplayed=!1,_native.Engine.PROTOCOL_VERSION!==gh.PROTOCOL_VERSION)throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${gh.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,maxDrawBuffers:8,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!0,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!0,textureFloatLinearFiltering:!0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:16,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1,parallelShaderCompile:{COMPLETION_STATUS_KHR:0}},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!0,supportSSAO2:!1,supportIBLShadows:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!1,_collectUbosUpdatedInFrame:!1},Ue.S0.Log("Babylon Native (v"+an.Version+") launched"),Ue.S0.LoadScript=function(e,t,i,r){Ue.S0.LoadFile(e,(e=>{Function(e).apply(null),t&&t()}),void 0,void 0,!1,((e,t)=>{i&&i("LoadScript Error",t)}))},"undefined"==typeof URL&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(window.Blob=function(e){return e}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function e(){const t=isNaN(arguments[0])?1:Number(arguments[0]);return t?Array.prototype.reduce.call(this,(function(i,r){return Array.isArray(r)?i.push.apply(i,e.call(r,t-1)):i.push(r),i}),[]):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 Zl,this.onNewSceneAddedObservable.add((e=>{const t=e.render;e.render=(...i)=>{this._commandBufferEncoder.beginCommandScope(),t.apply(e,i),this._commandBufferEncoder.endCommandScope()}}))}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new zl}_queueNewFrame(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0}_restoreEngineAfterContextLost(){this._clearEmptyResources();const e=this._depthCullingState.depthTest,t=this._depthCullingState.depthFunc,i=this._depthCullingState.depthMask,r=this._stencilState.stencilTest;this._rebuildGraphicsResources(),this._depthCullingState.depthTest=e,this._depthCullingState.depthFunc=t,this._depthCullingState.depthMask=i,this._stencilState.stencilTest=r,this._flagContextRestored()}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),this._commandBufferEncoder.finishEncodingCommand()),e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()),this._currentFramebuffer=e)}getHostDocument(){return null}clear(e,t,i,r=!1){if(this.useReverseDepthBuffer)throw new Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(r?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t,i){const r=this._normalizeIndexData(e),s=new ph;return s.references=1,s.is32Bits=4===r.BYTES_PER_ELEMENT,r.byteLength&&(s.nativeIndexBuffer=this._engine.createIndexBuffer(r.buffer,r.byteOffset,r.byteLength,s.is32Bits,t??!1)),s}createVertexBuffer(e,t,i){const r=ArrayBuffer.isView(e)?e:new Float32Array(e),s=new ph;return s.references=1,r.byteLength&&(s.nativeVertexBuffer=this._engine.createVertexBuffer(r.buffer,r.byteOffset,r.byteLength,t??!1)),s}_recordVertexArrayObject(e,t,i,r,s){r._checkedNonFloatVertexBuffers||(lh(t,r),r._checkedNonFloatVertexBuffers=!0),i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);const n=r.getAttributesNames();for(let i=0;i=0){const r=n[i];let a=null;if(s&&(a=s[r]),a||(a=t[r]),a){const t=a.effectiveBuffer;t&&t.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,t.nativeVertexBuffer,o,a.effectiveByteOffset,a.effectiveByteStride,a.getSize(),nh(a.type),a.normalized,a.getInstanceDivisor())}}}}bindBuffers(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)}recordVertexArrayObject(e,t,i,r){const s=this._engine.createVertexArray();return this._recordVertexArrayObject(s,e,t,i,r),s}_deleteVertexArray(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}bindVertexArrayObject(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}releaseVertexArrayObject(e){this._deleteVertexArray(e)}getAttributes(e,t){const i=e,r=i.shaderProcessingContext;mh.length=0;for(let e=0;e{e(),t()}}else i.onCompiled=t;else t()}createRawShaderProgram(){throw new Error("Not Supported")}createShaderProgram(e,t,i,r){const s=e;this.onBeforeShaderCompilationObservable.notifyObservers(this);const n=new $l(t);n.processCode(),t=n.code;const o=new $l(i);o.processCode(),i=o.code,t=Ls.ThinEngine._ConcatenateShader(t,r),i=Ls.ThinEngine._ConcatenateShader(i,r);const a=()=>{s.isCompiled=!0,s.onCompiled?.(),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(e.isAsync)s.program=this._engine.createProgramAsync(t,i,a,(e=>{s.compilationError=e}));else try{s.program=this._engine.createProgram(t,i),a()}catch(e){const t=e?.message;throw new Error("SHADER ERROR"+("string"==typeof t?"\n"+t:""))}return s.program}inlineShaderCode(e){const t=new $l(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 t=0;t{}}}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}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,function(e){switch(e){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: ${e}.`)}}(this._stencilOpStencilFail),function(e){switch(e){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: ${e}.`)}}(this._stencilOpDepthFail),function(e){switch(e){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: ${e}.`)}}(this._stencilOpStencilDepthPass),function(e){switch(e){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: ${e}.`)}}(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,r,s,n){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),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,r){throw new Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;const i=function(e){switch(e){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: ${e}.`)}}(e);this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t||this.setDepthWrite(0===e),this._alphaMode=e}setInt(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setArray(e,t){return!!e&&this.setFloatArray(e,new Float32Array(t))}setArray2(e,t){return!!e&&this.setFloatArray2(e,new Float32Array(t))}setArray3(e,t){return!!e&&this.setFloatArray3(e,new Float32Array(t))}setArray4(e,t){return!!e&&this.setFloatArray4(e,new Float32Array(t))}setMatrices(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix3x3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix2x2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}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)}setFloat3(e,t,i,r){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat4(e,t,i,r,s){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0)}setColor3(e,t){return!!e&&(this.setFloat3(e,t.r,t.g,t.b),!0)}setColor4(e,t,i){return!!e&&(this.setFloat4(e,t.r,t.g,t.b,i),!0)}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}_createTexture(){return this._engine.createTexture()}_deleteTexture(e){e&&this._engine.deleteTexture(e.underlyingResource)}updateDynamicTexture(e,t,i,r=!1,s){if(void 0===r&&(r=!1),e&&e._hardwareTexture){const i=t.getCanvasTexture(),r=e._hardwareTexture.underlyingResource;this._engine.copyTexture(r,i),e.isReady=!0}}createDynamicTexture(e,t,i,r){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,r)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){const r=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(r,t,i)}}createRawTexture(e,t,i,r,s,n,o,a=null,l=0,h=0,c=!1){const u=new Fs.h(this,3);if(u.format=r,u.generateMipMaps=s,u.samplingMode=o,u.invertY=n,u.baseWidth=t,u.baseHeight=i,u.width=u.baseWidth,u.height=u.baseHeight,u._compression=a,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!s),this.updateRawTexture(u,e,r,n,a,l,u._useSRGBBuffer),u._hardwareTexture){const e=u._hardwareTexture.underlyingResource,t=rh(o);this._setTextureSampling(e,t)}return this._internalTexturesCache.push(u),u}createRawTexture2DArray(e,t,i,r,s,n,o,a,l=null,h=0){const c=new Fs.h(this,11);if(c.baseWidth=t,c.baseHeight=i,c.baseDepth=r,c.width=t,c.height=i,c.depth=r,c.format=s,c.type=h,c.generateMipMaps=n,c.samplingMode=a,c.is2DArray=!0,c._hardwareTexture){const l=c._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(l,e,t,i,r,ih(s,h),n,o);const u=rh(a);this._setTextureSampling(l,u)}return c.isReady=!0,this._internalTexturesCache.push(c),c}updateRawTexture(e,t,i,r,s=null,n=0,o=!1){if(e){if(t&&e._hardwareTexture){const r=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(r,t,e.width,e.height,ih(i,n),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,r,s=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,f,p=!1){const _="data:"===(e=e||"").substring(0,5),m=_&&-1!==e.indexOf(";base64,"),g=l||new Fs.h(this,1),v=e;!this._transformTextureUrl||m||l||a||(e=this._transformTextureUrl(e));const x=e.lastIndexOf("."),b=c||(x>-1?e.substring(x).toLowerCase():"");let S=null;(b.endsWith(".basis")||b.endsWith(".ktx")||b.endsWith(".ktx2")||"image/ktx"===u||"image/ktx2"===u)&&(S=(0,ch.gT)(b)),r&&r.addPendingData(g),g.url=e,g.generateMipMaps=!t,g.samplingMode=s,g.invertY=i,g._useSRGBBuffer=this._getUseSRGBBuffer(p,t),this.doNotHandleContextLost||(g._buffer=a);let T=null;n&&!l&&(T=g.onLoadedObservable.add(n)),l||this._internalTexturesCache.push(g);const C=(i,l)=>{r&&r.removePendingData(g),e===v?(T&&g.onLoadedObservable.remove(T),he.q.UseFallbackTexture&&this.createTexture(he.q.FallbackTexture,t,g.invertY,r,s,null,o,a,g),o&&o((i||"Unknown error")+(he.q.UseFallbackTexture?" - Fallback texture was used":""),l)):(Z.V.Warn(`Failed to load ${e}, falling back to ${v}`),this.createTexture(v,t,g.invertY,r,s,n,o,a,g,h,c,u,d))};if(S)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");{const n=e=>{if(!g._hardwareTexture)return void(r&&r.removePendingData(g));const n=g._hardwareTexture.underlyingResource;this._engine.loadTexture(n,e,!t,i,g._useSRGBBuffer,(()=>{g.baseWidth=this._engine.getTextureWidth(n),g.baseHeight=this._engine.getTextureHeight(n),g.width=g.baseWidth,g.height=g.baseHeight,g.isReady=!0;const e=rh(s);this._setTextureSampling(n,e),r&&r.removePendingData(g),g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear()}),(()=>{throw new Error("Could not load a native texture.")}))};if(_&&a)if(a instanceof ArrayBuffer)n(new Uint8Array(a));else if(ArrayBuffer.isView(a))n(a);else{if("string"!=typeof a)throw new Error("Unsupported buffer type");n(new Uint8Array(Ue.S0.DecodeBase64(a)))}else m?n(new Uint8Array(Ue.S0.DecodeBase64(e))):this._loadFile(e,(e=>n(new Uint8Array(e))),void 0,void 0,!0,((e,t)=>{C("Unable to load "+(e&&e.responseURL,t))}))}return g}wrapNativeTexture(e,t=!1,i=3){const r=new th(e,this._engine),s=new Fs.h(this,0,!0);return s._hardwareTexture=r,s.baseWidth=this._engine.getTextureWidth(e),s.baseHeight=this._engine.getTextureHeight(e),s.width=s.baseWidth,s.height=s.baseHeight,s.isReady=!0,s.useMipMaps=t,this.updateTextureSamplingMode(i,s),s}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){const r=t.generateStencil||!1,s=t.samples||1,n=i,o=new Fs.h(this,12),a=e.width??e,l=e.height??e,h=this._engine.createFrameBuffer(o._hardwareTexture.underlyingResource,a,l,r,!0,s);return n._framebufferDepthStencil=h,o}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){const i=new Promise(((t,i)=>{const r=this.createCanvasImage();r.onload=()=>{try{const e=this._engine.createImageBitmap(r);t(e)}catch(e){i(`Error loading image ${r.src} with exception: ${e}`)}},r.onerror=e=>{i(`Error loading image ${r.src} with exception: ${e}`)},r.src=e}));return i}createImageBitmap(e,t){return new Promise(((t,i)=>{if(Array.isArray(e)){const i=e;if(i.length){const e=this._engine.createImageBitmap(i[0]);if(e)return void t(e)}}i("Unsupported data for createImageBitmap.")}))}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,r,s=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d,f=!1,p=null){const _=u||new Fs.h(this,7);_.isCube=!0,_.url=e,_.generateMipMaps=!r,_._lodGenerationScale=h,_._lodGenerationOffset=c,_._useSRGBBuffer=this._getUseSRGBBuffer(f,!!r),this._doNotHandleContextLost||(_._extension=a,_._files=i,_._buffer=p);const m=e.lastIndexOf(".");if(".env"===(a||(m>-1?e.substring(m).toLowerCase():""))){const t=e=>{const t=(0,Wl.cU)(e);_.width=t.width,_.height=t.width,(0,Wl.ow)(_,t);const i=t.specular;if(!i)throw new Error("Nothing else parsed so far");_._lodGenerationScale=i.lodGenerationScale;const r=(0,Wl.$h)(e,t);_.format=5,_.type=0,_.generateMipMaps=!0,_.getEngine().updateTextureSamplingMode(vi.g.TRILINEAR_SAMPLINGMODE,_),_._isRGBD=!0,_.invertY=!0,this._engine.loadCubeTextureWithMips(_._hardwareTexture.underlyingResource,r,!1,_._useSRGBBuffer,(()=>{_.isReady=!0,s&&s()}),(()=>{throw new Error("Could not load a native cube texture.")}))};if(p)t(p);else{if(i&&6===i.length)throw new Error("Multi-file loading not allowed on env files.");{const i=(e,t)=>{n&&e&&n(e.status+" "+e.statusText,t)};this._loadFile(e,(e=>{t(new Uint8Array(e,0,e.byteLength))}),void 0,void 0,!0,i)}}}else{if(!i||6!==i.length)throw new Error("Cannot load cubemap because 6 files were not defined");const e=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(e.map((e=>this._loadFileAsync(e,void 0,!0).then((e=>new Uint8Array(e,0,e.byteLength)))))).then((e=>new Promise(((t,i)=>{this._engine.loadCubeTexture(_._hardwareTexture.underlyingResource,e,!r,!0,_._useSRGBBuffer,t,i)})))).then((()=>{_.isReady=!0,s&&s()}),(e=>{n&&n(`Failed to load cubemap: ${e.message}`,e)}))}return this._internalTexturesCache.push(_),_}_createHardwareTexture(){return new th(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){const r=new eh(e,t,i,this);return this._renderTargetWrapperCache.push(r),r}_createInternalTexture(e,t,i=!0,r=0){let s,n=!1,o=0,a=3,l=5,h=!1,c=1;void 0!==t&&"object"==typeof t?(n=!!t.generateMipMaps,o=void 0===t.type?0:t.type,a=void 0===t.samplingMode?3:t.samplingMode,l=void 0===t.format?5:t.format,h=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,c=t.samples??1,s=t.label):n=!!t,h=this._getUseSRGBBuffer(h,!n),(1!==o||this._caps.textureFloatLinearFiltering)&&(2!==o||this._caps.textureHalfFloatLinearFiltering)||(a=1),1!==o||this._caps.textureFloat||(o=0,Z.V.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=new Fs.h(this,r),d=e.width??e,f=e.height??e,p=e.layers||0;if(0!==p)throw new Error("Texture layers are not supported in Babylon Native");const _=u._hardwareTexture.underlyingResource,m=ih(l,o);return this._engine.initializeTexture(_,d,f,n,m,!0,h,c),this._setTextureSampling(_,rh(a)),u._useSRGBBuffer=h,u.baseWidth=d,u.baseHeight=f,u.width=d,u.height=f,u.depth=p,u.isReady=!0,u.samples=c,u.generateMipMaps=n,u.samplingMode=a,u.type=o,u.format=l,u.label=s,this._internalTexturesCache.push(u),u}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e);let r,s=!0,n=!1,o=!1,a=1;void 0!==t&&"object"==typeof t&&(s=t.generateDepthBuffer??!0,n=!!t.generateStencilBuffer,o=!!t.noColorAttachment,r=t.colorAttachment,a=t.samples??1);const l=r||(o?null:this._createInternalTexture(e,t,!0,5)),h=e.width??e,c=e.height??e,u=this._engine.createFrameBuffer(l?l._hardwareTexture.underlyingResource:null,h,c,n,s,a);return i._framebuffer=u,i._generateDepthBuffer=s,i._generateStencilBuffer=n,i._samples=a,i.setTextures(l),i}updateRenderTargetTextureSampleCount(e,t){return Z.V.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){const i=rh(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,r,s){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||r)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 r=e,s=this._normalizeIndexData(t);r.is32Bits=4===s.BYTES_PER_ELEMENT,this._engine.updateDynamicIndexBuffer(r.nativeIndexBuffer,s.buffer,s.byteOffset,s.byteLength,i)}updateDynamicVertexBuffer(e,t,i=0,r){const s=e,n=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,o=new Uint8Array(n.buffer,n.byteOffset,r??n.byteLength);this._engine.updateDynamicVertexBuffer(s.nativeVertexBuffer,o.buffer,o.byteOffset,o.byteLength,i)}_setTexture(e,t,i=!1,r=!1){const s=this._boundUniforms[e];if(!s)return!1;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._boundTexturesCache[e]=null,this._unsetNativeTexture(s)),!1;if(t.video)this._activeChannel=e,t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;let n;return n=r?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!(!n||!n._hardwareTexture||(this._setTextureWrapMode(n._hardwareTexture.underlyingResource,sh(t.wrapU),sh(t.wrapV),sh(t.wrapR)),this._updateAnisotropicLevel(t),this._setNativeTexture(s,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,r){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.finishEncodingCommand()}_setNativeTexture(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()}_unsetNativeTexture(e){_native.Engine.COMMAND_UNSETTEXTURE&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNSETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_updateAnisotropicLevel(e){const t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;t&&t._hardwareTexture&&t._cachedAnisotropicFilteringLevel!==i&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(t._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t._cachedAnisotropicFilteringLevel=i)}_bindTexture(e,t){const i=this._boundUniforms[e];if(i)if(t&&t._hardwareTexture){const e=t._hardwareTexture.underlyingResource;this._setNativeTexture(i,e)}else this._unsetNativeTexture(i)}unbindAllTextures(){_native.Engine.COMMAND_DISCARDALLTEXTURES&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DISCARDALLTEXTURES),this._commandBufferEncoder.finishEncodingCommand())}_deleteBuffer(e){e.nativeIndexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeIndexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeVertexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeVertexBuffer)}createCanvas(e,t){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");const i=new _native.Canvas;return i.width=e,i.height=t,i}createCanvasImage(){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");return new _native.Image}updateTextureData(e,t,i,r,s,n,o=0,a=0,l=!1){throw new Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,n=0,o=0){throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,r=0){throw new Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,r=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}getFontOffset(e){return{ascent:0,height:0,descent:0}}flushFramebuffer(){}_readTexturePixels(e,t,i,r,s,n,o,a,l,h){if(void 0!==r&&-1!==r)throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${r}.`);return this._engine.readTexture(e._hardwareTexture?.underlyingResource,s??0,l??0,h??0,t,i,n?.buffer??null,n?.byteOffset??0,n?.byteLength??0).then((e=>(n||(n=new Uint8Array(e)),n)))}}gh.PROTOCOL_VERSION=8,gh._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new vh:new zl};class vh extends zl{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)}}class xh{static ComputeNumMipmapLevels(e,t){return(0,ar.ILog2)(Math.max(e,t))+1}static GetTextureTypeFromFormat(e){switch(e){case"r8unorm":case"r8uint":case"rg8unorm":case"rg8uint":case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8uint":case"bgra8unorm":case"bgra8unorm-srgb":case"rgb10a2uint":case"rgb10a2unorm":case"rgb9e5ufloat":case"rg11b10ufloat":case"bc7-rgba-unorm":case"bc7-rgba-unorm-srgb":case"bc6h-rgb-ufloat":case"bc5-rg-unorm":case"bc3-rgba-unorm":case"bc3-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc2-rgba-unorm-srgb":case"bc4-r-unorm":case"bc1-rgba-unorm":case"bc1-rgba-unorm-srgb":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"eac-r11unorm":case"eac-rg11unorm":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":case"stencil8":return 0;case"r8snorm":case"r8sint":case"rg8snorm":case"rg8sint":case"rgba8snorm":case"rgba8sint":case"bc6h-rgb-float":case"bc5-rg-snorm":case"bc4-r-snorm":case"eac-r11snorm":case"eac-rg11snorm":return 3;case"r16uint":case"rg16uint":case"rgba16uint":case"depth16unorm":return 5;case"r16sint":case"rg16sint":case"rgba16sint":return 4;case"r16float":case"rg16float":case"rgba16float":return 2;case"r32uint":case"rg32uint":case"rgba32uint":case"r32sint":case"rg32sint":case"rgba32sint":return 7;case"r32float":case"rg32float":case"rgba32float":case"depth32float":case"depth32float-stencil8":case"depth24plus":case"depth24plus-stencil8":return 1}return 0}static GetBlockInformationFromFormat(e){switch(e){case"r8unorm":case"r8snorm":case"r8uint":case"r8sint":return{width:1,height:1,length:1};case"r16uint":case"r16sint":case"r16float":case"rg8unorm":case"rg8snorm":case"rg8uint":case"rg8sint":case"depth16unorm":return{width:1,height:1,length:2};case"r32uint":case"r32sint":case"r32float":case"rg16uint":case"rg16sint":case"rg16float":case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8snorm":case"rgba8uint":case"rgba8sint":case"bgra8unorm":case"bgra8unorm-srgb":case"rgb9e5ufloat":case"rgb10a2uint":case"rgb10a2unorm":case"rg11b10ufloat":case"depth32float":return{width:1,height:1,length:4};case"rg32uint":case"rg32sint":case"rg32float":case"rgba16uint":case"rgba16sint":case"rgba16float":return{width:1,height:1,length:8};case"rgba32uint":case"rgba32sint":case"rgba32float":return{width:1,height:1,length:16};case"stencil8":throw"No fixed size for Stencil8 format!";case"depth24plus":throw"No fixed size for Depth24Plus format!";case"depth24plus-stencil8":throw"No fixed size for Depth24PlusStencil8 format!";case"depth32float-stencil8":return{width:1,height:1,length:5};case"bc7-rgba-unorm":case"bc7-rgba-unorm-srgb":case"bc6h-rgb-ufloat":case"bc6h-rgb-float":case"bc5-rg-unorm":case"bc5-rg-snorm":case"bc3-rgba-unorm":case"bc3-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc2-rgba-unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"eac-rg11unorm":case"eac-rg11snorm":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":return{width:4,height:4,length:16};case"bc4-r-unorm":case"bc4-r-snorm":case"bc1-rgba-unorm":case"bc1-rgba-unorm-srgb":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"eac-r11unorm":case"eac-r11snorm":return{width:4,height:4,length:8};case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":return{width:5,height:4,length:16};case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":return{width:5,height:5,length:16};case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":return{width:6,height:5,length:16};case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":return{width:6,height:6,length:16};case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":return{width:8,height:5,length:16};case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":return{width:8,height:6,length:16};case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":return{width:8,height:8,length:16};case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":return{width:10,height:5,length:16};case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":return{width:10,height:6,length:16};case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":return{width:10,height:8,length:16};case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":return{width:10,height:10,length:16};case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":return{width:12,height:10,length:16};case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":return{width:12,height:12,length:16}}return{width:1,height:1,length:4}}static IsHardwareTexture(e){return!!e.release}static IsInternalTexture(e){return!!e.dispose}static IsImageBitmap(e){return void 0!==e.close}static IsImageBitmapArray(e){return Array.isArray(e)&&void 0!==e[0].close}static IsCompressedFormat(e){switch(e){case"bc7-rgba-unorm-srgb":case"bc7-rgba-unorm":case"bc6h-rgb-float":case"bc6h-rgb-ufloat":case"bc5-rg-snorm":case"bc5-rg-unorm":case"bc4-r-snorm":case"bc4-r-unorm":case"bc3-rgba-unorm-srgb":case"bc3-rgba-unorm":case"bc2-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc1-rgba-unorm-srgb":case"bc1-rgba-unorm":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"eac-r11unorm":case"eac-r11snorm":case"eac-rg11unorm":case"eac-rg11snorm":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return"depth16unorm";case 16:return"depth24plus";case 13:return"depth24plus-stencil8";case 14:return"depth32float";case 18:return"depth32float-stencil8";case 19:return"stencil8";case 36492:return i?"bc7-rgba-unorm-srgb":"bc7-rgba-unorm";case 36495:return"bc6h-rgb-ufloat";case 36494:return"bc6h-rgb-float";case 33779:return i?"bc3-rgba-unorm-srgb":"bc3-rgba-unorm";case 33778:return i?"bc2-rgba-unorm-srgb":"bc2-rgba-unorm";case 33777:case 33776:return i?"bc1-rgba-unorm-srgb":"bc1-rgba-unorm";case 37808:return i?"astc-4x4-unorm-srgb":"astc-4x4-unorm";case 36196:case 37492:return i?"etc2-rgb8unorm-srgb":"etc2-rgb8unorm";case 37496:return i?"etc2-rgba8unorm-srgb":"etc2-rgba8unorm"}switch(e){case 3:switch(t){case 6:return"r8snorm";case 7:return"rg8snorm";case 4:throw"RGB format not supported in WebGPU";case 8:return"r8sint";case 9:return"rg8sint";case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return"rgba8sint";default:return"rgba8snorm"}case 0:switch(t){case 6:return"r8unorm";case 7:return"rg8unorm";case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?"rgba8unorm-srgb":"rgba8unorm";case 12:return i?"bgra8unorm-srgb":"bgra8unorm";case 8:return"r8uint";case 9:return"rg8uint";case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return"rgba8uint";case 0:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case 1:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case 2:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return"rgba8unorm"}case 4:switch(t){case 8:return"r16sint";case 9:return"rg16sint";case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return"rgba16sint"}case 5:switch(t){case 8:return"r16uint";case 9:return"rg16uint";case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return"rgba16uint"}case 6:switch(t){case 8:return"r32sint";case 9:return"rg32sint";case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return"rgba32sint"}case 7:switch(t){case 8:return"r32uint";case 9:return"rg32uint";case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return"rgba32uint"}case 1:switch(t){case 6:return"r32float";case 7:return"rg32float";case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return"rgba32float"}case 2:switch(t){case 6:return"r16float";case 7:return"rg16float";case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return"rgba16float"}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:default:return"rg11b10ufloat";case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV"}case 14:switch(t){case 5:default:return"rgb9e5ufloat";case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV"}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:default:return"rgb10a2unorm";case 11:return"rgb10a2uint"}}return i?"rgba8unorm-srgb":"rgba8unorm"}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case"r8unorm":case"r8snorm":case"r8uint":case"r8sint":case"bc4-r-unorm":case"bc4-r-snorm":case"r16uint":case"r16sint":case"depth16unorm":case"r16float":case"r32uint":case"r32sint":case"r32float":case"depth32float":case"stencil8":case"depth24plus":case"eac-r11unorm":case"eac-r11snorm":return 1;case"rg8unorm":case"rg8snorm":case"rg8uint":case"rg8sint":case"depth32float-stencil8":case"bc5-rg-unorm":case"bc5-rg-snorm":case"rg16uint":case"rg16sint":case"rg16float":case"rg32uint":case"rg32sint":case"rg32float":case"depth24plus-stencil8":case"eac-rg11unorm":case"eac-rg11snorm":return 2;case"rgb9e5ufloat":case"rg11b10ufloat":case"bc6h-rgb-ufloat":case"bc6h-rgb-float":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":return 3;case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8snorm":case"rgba8uint":case"rgba8sint":case"bgra8unorm":case"bgra8unorm-srgb":case"rgb10a2uint":case"rgb10a2unorm":case"bc7-rgba-unorm":case"bc7-rgba-unorm-srgb":case"bc3-rgba-unorm":case"bc3-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc2-rgba-unorm-srgb":case"bc1-rgba-unorm":case"bc1-rgba-unorm-srgb":case"rgba16uint":case"rgba16sint":case"rgba16float":case"rgba32uint":case"rgba32sint":case"rgba32float":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case"stencil8":case"depth32float-stencil8":case"depth24plus-stencil8":return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case"depth32float-stencil8":case"depth24plus-stencil8":return!0}return!1}static GetDepthFormatOnly(e){switch(e){case"depth16unorm":return"depth16unorm";case"depth24plus":case"depth24plus-stencil8":return"depth24plus";case"depth32float":case"depth32float-stencil8":return"depth32float"}return e}static GetSample(e){return e>1?4:1}}var bh=i(89237);class Sh extends Ot.${constructor(){super(...arguments),this.dbgShowShaderCode=!1,this.dbgSanityChecks=!0,this.dbgVerboseLogsNumFrames=10,this.dbgLogIfNotDrawWrapper=!0,this.dbgShowEmptyEnableEffectCalls=!0,this.dbgVerboseLogsForFirstFrames=!1,this._currentRenderPass=null,this._snapshotRenderingMode=0,this._timestampIndex=0}get enableGPUTimingMeasurements(){return this._timestampQuery.enable}set enableGPUTimingMeasurements(e){this._timestampQuery.enable!==e&&(this.gpuTimeInFrameForMainPass=e?new bh.e:void 0,this._timestampQuery.enable=e)}_currentPassIsMainPass(){return null===this._currentRenderTarget}_endCurrentRenderPass(){if(!this._currentRenderPass)return 0;const e=this._currentPassIsMainPass()?2:1;return this._snapshotRendering.endRenderPass(this._currentRenderPass)||this.compatibilityMode||(this._bundleList.run(this._currentRenderPass),this._bundleList.reset()),this._currentRenderPass.end(),this._timestampQuery.endPass(this._timestampIndex,this._currentRenderTarget&&this._currentRenderTarget.gpuTimeInFrame?this._currentRenderTarget.gpuTimeInFrame:this.gpuTimeInFrameForMainPass),this._timestampIndex+=2,this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count=0&&(u.push(o[c]),d.push(e))}this.shaderProcessingContext.attributeNamesFromEffect=u,this.shaderProcessingContext.attributeLocationsFromEffect=d}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer?.dispose(),this.uniformBuffer=new Rt.D(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=cc.UniformSizes[t];this.uniformBuffer.addUniform(e.name,i,e.length),this._leftOverUniformsByName[e.name]=e.type}this.uniformBuffer.create()}}setEngine(e){this.engine=e}dispose(){this.uniformBuffer&&this.uniformBuffer.dispose()}setInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt(e,t)}setInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt2(e,t,i)}setInt3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt3(e,t,i,r)}setInt4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt4(e,t,i,r,s)}setIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt3(e,t,i,r)}setUInt4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt4(e,t,i,r,s)}setUIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat3(e,t,i,r)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat4(e,t,i,r,s)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){return this.sources?.vertex}_getFragmentShaderCode(){return this.sources?.fragment}}const dc={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class fc{static get KnownUBOs(){return fc._SimplifiedKnownBindings?fc._SimplifiedKnownUBOs:fc._KnownUBOs}constructor(e,t=!1){this.vertexBufferKindToNumberOfComponents={},this.shaderLanguage=e,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],t||this._findStartingGroupBinding()}_findStartingGroupBinding(){const e=fc.KnownUBOs,t=[];for(const i in e){const r=e[i].binding;-1!==r.groupIndex&&(void 0===t[r.groupIndex]?t[r.groupIndex]=r.bindingIndex:t[r.groupIndex]=Math.max(t[r.groupIndex],r.bindingIndex))}this.freeGroupIndex=t.length-1,0===this.freeGroupIndex?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){const i=this._attributeNextLocation;return this._attributeNextLocation+=(dc[e]??1)*(t||1),i}getVaryingNextLocation(e,t=0){const i=this._varyingNextLocation;return this._varyingNextLocation+=(dc[e]??1)*(t||1),i}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>65536-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),4===this.freeGroupIndex)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}}fc._SimplifiedKnownBindings=!0,fc._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}}},fc._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 pc extends cc{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=0,this.parseGLES3=!0}_getArraySize(e,t,i){let r=0;const s=e.indexOf("["),n=e.indexOf("]");if(s>0&&n>0){const t=e.substring(s+1,n);r=+t,isNaN(r)&&(r=+i[t.trim()]),e=e.substring(0,s)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){const i=`// Internals UBO\nuniform ${cc.InternalsUBOName} {\nfloat yFactor_;\nfloat textureOutputHeight_;\n};\n`,r=-1!==e.indexOf("// Internals UBO");return t?(this._fragmentIsGLES3=-1!==e.indexOf("#version 3"),this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),r?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=-1!==e.indexOf("#version 3"),this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),r?e:i+e)}varyingCheck(e,t){return(t&&this._fragmentIsGLES3?/(flat\s)?\s*\bin\b/:!t&&this._vertexIsGLES3?/(flat\s)?\s*\bout\b/:/(flat\s)?\s*\bvarying\b/).test(e)}varyingProcessor(e,t,i){this._preProcessors=i;const r=(t&&this._fragmentIsGLES3?/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:!t&&this._vertexIsGLES3?/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==r){const s=r[1]??"",n=r[2],o=r[3];let a;t?(a=this._webgpuProcessingContext.availableVaryings[o],this._missingVaryings[a]="",void 0===a&&Z.V.Warn(`Invalid fragment shader: The varying named "${o}" is not declared in the vertex shader! This declaration will be ignored.`)):(a=this._webgpuProcessingContext.getVaryingNextLocation(n,this._getArraySize(o,n,i)[2]),this._webgpuProcessingContext.availableVaryings[o]=a,this._missingVaryings[a]=`layout(location = ${a}) ${s} in ${n} ${o};`),e=e.replace(r[0],void 0===a?"":`layout(location = ${a}) ${s} ${t?"in":"out"} ${n} ${o};`)}return e}attributeProcessor(e,t){this._preProcessors=t;const i=(this._vertexIsGLES3?/\s*in\s+(\S+)\s+(\S+)\s*;/gm:/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==i){const r=i[1],s=i[2],n=this._webgpuProcessingContext.getAttributeNextLocation(r,this._getArraySize(s,r,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=n,this._webgpuProcessingContext.orderedAttributes[n]=s;const o=this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[s];if(void 0!==o){const t=o<0?-1===o?"int":"ivec"+-o:1===o?"uint":"uvec"+o,a=`_int_${s}_`;e=e.replace(i[0],`layout(location = ${n}) in ${t} ${a}; ${r} ${s} = ${r}(${a});`)}else e=e.replace(i[0],`layout(location = ${n}) in ${r} ${s};`)}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(null!==r){let s=r[1],n=r[2];if(0===s.indexOf("sampler")||1===s.indexOf("sampler")){let r=0;[n,s,r]=this._getArraySize(n,s,i);let o=this._webgpuProcessingContext.availableTextures[n];if(!o){o={autoBindSampler:!0,isTextureArray:r>0,isStorageTexture:!1,textures:[],sampleType:"float"};for(let e=0;e<(r||1);++e)o.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const a=cc._SamplerTypeByWebGLSamplerType[s]??"sampler",l=!!cc._IsComparisonSamplerByWebGPUSamplerType[a],h=l?"comparison":"filtering",c=n+"Sampler";let u=this._webgpuProcessingContext.availableSamplers[c];u||(u={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:h});const d="u"===s.charAt(0)?"u":"i"===s.charAt(0)?"i":"";d&&(s=s.substring(1));const f=l?"depth":"u"===d?"uint":"i"===d?"sint":"float";o.sampleType=f;const p=r>0,_=u.binding.groupIndex,m=u.binding.bindingIndex,g=cc._SamplerFunctionByWebGLSamplerType[s],v=cc._TextureTypeByWebGLSamplerType[s],x=cc._GpuTextureViewDimensionByWebGPUTextureType[v];if(p){const t=[];t.push(`layout(set = ${_}, binding = ${m}) uniform ${d}${a} ${c};`),e="\n";for(let i=0;i0?"\n":""}#define ${n}${i} ${d}${g}(${n}Texture${i}, ${c})`}e=t.join("\n")+e,this._textureArrayProcessing.push(n)}else r=1,e=`layout(set = ${_}, binding = ${m}) uniform ${a} ${c};\n layout(set = ${o.textures[0].groupIndex}, binding = ${o.textures[0].bindingIndex}) uniform ${d}${v} ${n}Texture;\n #define ${n} ${d}${g}(${n}Texture, ${c})`;this._webgpuProcessingContext.availableTextures[n]=o,this._webgpuProcessingContext.availableSamplers[c]=u,this._addSamplerBindingDescription(c,u,!t);for(let e=0;e=0,i="\n glFragCoord_ = gl_FragCoord;\n if (yFactor_ == 1.) {\n glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y;\n }\n ",r=t?"vec4 glFragCoord_;\n":"",s=-1!==e.search(/layout *\(location *= *0\) *out/g);if(e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/gl_FragCoord/g,"glFragCoord_"),this._fragmentIsGLES3){const t=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);null!==t&&(e=e.substring(0,t.index)+"layout(location = 0) "+e.substring(t.index))}else e=e.replace(/void\s+?main\s*\(/g,(n||s?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");e=(e=e.replace(/dFdy/g,"(-yFactor_)*dFdy")).replace("##INJECTCODE##",r),t&&(e=jl(e,"void main",i))}else if(e=(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex")).replace(/gl_VertexID/g,"gl_VertexIndex"),-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;if(!i){const t=e.lastIndexOf("}");e=e.substring(0,t),e+="gl_Position.y *= yFactor_;\n",e+="}"}return e}_applyTextureArrayProcessing(e,t){const i=new RegExp(t+"\\s*\\[(.+)?\\]","gm");let r=i.exec(e);for(;null!==r;){const s=r[1];let n=+s;this._preProcessors&&isNaN(n)&&(n=+this._preProcessors[s.trim()]),e=e.replace(r[0],t+n),r=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} {\n `;for(const e of this._webgpuProcessingContext.leftOverUniforms)e.length>0?i+=` ${e.type} ${e.name}[${e.length}];\n`:i+=` ${e.type} ${e.name};\n`;return i+="};\n\n",i}finalizeShaders(e,t){for(let i=0;i0&&(t=i+"\n"+t)}const i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}}i(68273),i(71281),i(41416),i(32764);var _c=i(87647);i(27493),i(10598),i(14910),i(17327);const mc={texture_1d:"1d",texture_2d:"2d",texture_2d_array:"2d-array",texture_3d:"3d",texture_cube:"cube",texture_cube_array:"cube-array",texture_multisampled_2d:"2d",texture_depth_2d:"2d",texture_depth_2d_array:"2d-array",texture_depth_cube:"cube",texture_depth_cube_array:"cube-array",texture_depth_multisampled_2d:"2d",texture_storage_1d:"1d",texture_storage_2d:"2d",texture_storage_2d_array:"2d-array",texture_storage_3d:"3d",texture_external:null};class gc extends cc{constructor(){super(...arguments),this.shaderLanguage=1,this.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,this.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,this.noPrecision=!0,this.pureMode=!1}preProcessor(e,t,i,r,s){for(const t in i){if("__VERSION__"===t)continue;const r=i[t];isNaN(parseInt(r))&&isNaN(parseFloat(r))||(e=`const ${t} = ${r};\n`+e)}return e}_getArraySize(e,t,i){let r=0;const s=t.lastIndexOf(">");if(t.indexOf("array")>=0&&s>0){let e=s;for(;e>0&&" "!==t.charAt(e)&&","!==t.charAt(e);)e--;const n=t.substring(e+1,s);for(r=+n,isNaN(r)&&(r=+i[n.trim()]);e>0&&(" "===t.charAt(e)||","===t.charAt(e));)e--;t=t.substring(t.indexOf("<")+1,e+1)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){const t=this.pureMode?"":`struct ${cc.InternalsUBOName} {\n yFactor_: f32,\n textureOutputHeight_: f32,\n};\nvar internals : ${cc.InternalsUBOName};\n`;return-1!==e.indexOf(t)?e:t+Yl(e)}varyingCheck(e){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(null!==r){const s=r[1]??"perspective",n=r[2]??"center",o=r[4],a=r[3],l="flat"===s?`@interpolate(${s})`:`@interpolate(${s}, ${n})`;let h;t?(h=this._webgpuProcessingContext.availableVaryings[a],void 0===h&&Z.V.Warn(`Invalid fragment shader: The varying named "${a}" is not declared in the vertex shader! This declaration will be ignored.`)):(h=this._webgpuProcessingContext.getVaryingNextLocation(o,this._getArraySize(a,o,i)[2]),this._webgpuProcessingContext.availableVaryings[a]=h,this._varyingsWGSL.push(` @location(${h}) ${l} ${a} : ${o},`),this._varyingNamesWGSL.push(a)),e=""}return e}attributeProcessor(e,t){const i=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==i){const r=i[2],s=i[1],n=this._webgpuProcessingContext.getAttributeNextLocation(r,this._getArraySize(s,r,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=n,this._webgpuProcessingContext.orderedAttributes[n]=s;const o=this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[s];if(void 0!==o){const e=o<0?-1===o?"i32":"vec"+-o+"":1===o?"u32":"vec"+o+"",t=`_int_${s}_`;this._attributesInputWGSL.push(`@location(${n}) ${t} : ${e},`),this._attributesWGSL.push(`${s} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${s} = ${r}(vertexInputs_.${t});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${n}) ${s} : ${r},`),this._attributesWGSL.push(`${s} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${s} = vertexInputs_.${s};`);e=""}return e}uniformProcessor(e,t,i){const r=this.uniformRegexp.exec(e);if(null!==r){const t=r[2],s=r[1];this._addUniformToLeftOverUBO(s,t,i),e=""}return e}textureProcessor(e,t,i){const r=this.textureRegexp.exec(e);if(null!==r){const s=r[1],n=r[2],o=!!r[3],a=r[4],l=a.indexOf("storage")>0,h=r[6],c=l?h.substring(0,h.indexOf(",")).trim():null;let u=o?this._getArraySize(s,n,i)[2]:0,d=this._webgpuProcessingContext.availableTextures[s];if(d)u=d.textures.length;else{d={isTextureArray:u>0,isStorageTexture:l,textures:[],sampleType:"float"},u=u||1;for(let e=0;e0,p=mc[a],_=f?"depth":"u32"===h?"uint":"i32"===h?"sint":"float";if(d.sampleType=_,void 0===p)throw`Can't get the texture dimension corresponding to the texture function "${a}"!`;for(let i=0;i=0&&!this.pureMode?"\n if (internals.yFactor_ == 1.) {\n fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y;\n }\n ":"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);const r=this._buildLeftOverUBO();t=r+t,e=(e=(e=r+e).replace(/#define (\w+)\s+(\d+\.?\d*)/g,"const $1 = $2;")).replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let s="struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n";this._attributesInputWGSL.length>0&&(s+=this._attributesInputWGSL.join("\n")),s+="\n};\nvar vertexInputs"+(this._hasNonFloatAttribute?"_":"")+" : VertexInputs;\n",this._hasNonFloatAttribute&&(s+="struct VertexInputs_ {\n vertexIndex : u32, instanceIndex : u32,\n",s+=this._attributesWGSL.join("\n"),s+="\n};\nvar vertexInputs : VertexInputs_;\n");let n="struct FragmentInputs {\n @builtin(position) position : vec4,\n";this._varyingsWGSL.length>0&&(n+=this._varyingsWGSL.join("\n")),n+="\n};\nvar vertexOutputs : FragmentInputs;\n",e=s+n+e;let o=`\n vertexInputs${this._hasNonFloatAttribute?"_":""} = input;\n`;this._hasNonFloatAttribute&&(o+="vertexInputs.vertexIndex = vertexInputs_.vertexIndex;\nvertexInputs.instanceIndex = vertexInputs_.instanceIndex;\n",o+=this._attributesConversionCodeWGSL.join("\n"),o+="\n");const a=this.pureMode?" return vertexOutputs;":" vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;\n return vertexOutputs;";let l=-1!==e.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS");e=(l?"diagnostic(off, derivative_uniformity);\n":"")+"diagnostic(off, chromium.unreachable_code);\n"+jl(e,"fn main",o,a),t=(t=t.replace(/#define (\w+)\s+(\d+\.?\d*)/g,"const $1 = $2;")).replace(/#define /g,"//#define "),t=this._processStridedUniformArrays(t),this.pureMode||(t=t.replace(/dpdy/g,"(-internals.yFactor_)*dpdy"));let h="struct FragmentInputs {\n @builtin(position) position : vec4,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(h+=this._varyingsWGSL.join("\n")),h+="\n};\nvar fragmentInputs : FragmentInputs;\n";let c="struct FragmentOutputs {\n";const u="fragmentOutputs\\.fragData";let d=t.match(new RegExp(u+"0","g")),f=0;if(d){c+=` @location(${f}) fragData0 : vec4,\n`,f++;for(let e=1;e<8;e++)d=t.match(new RegExp(u+e,"g")),d&&(c+=` @location(${f}) fragData${f} : vec4,\n`,f++);-1!==t.indexOf("MRT_AND_COLOR")&&(c+=` @location(${f}) color : vec4,\n`,f++)}d=t.match(/oitDepthSampler/),d&&(c+=` @location(${f++}) depth : vec2,\n`,c+=` @location(${f++}) frontColor : vec4,\n`,c+=` @location(${f++}) backColor : vec4,\n`),0===f&&(c+=" @location(0) color : vec4,\n",f++);let p=!1,_=0;for(;!(p||(_=t.indexOf("fragmentOutputs.fragDepth",_),_<0));){const e=_;for(p=!0;_>1&&"\n"!==t.charAt(_);){if("/"===t.charAt(_)&&"/"===t.charAt(_-1)){p=!1;break}_--}_=e+25}p&&(c+=" @builtin(frag_depth) fragDepth: f32,\n"),c+="};\nvar fragmentOutputs : FragmentOutputs;\n";const m=" fragmentInputs = input;\n "+i;return l=-1!==(t=h+c+t).indexOf("#define DISABLE_UNIFORMITY_ANALYSIS"),t=(l?"diagnostic(off, derivative_uniformity);\n":"")+"diagnostic(off, chromium.unreachable_code);\n"+jl(t,"fn main",m," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",r=`struct ${e} {\n`;for(const t of this._webgpuProcessingContext.leftOverUniforms){const s=t.type.replace(/^(.*?)(<.*>)?$/,"$1"),n=cc.UniformSizes[s];if(t.length>0)if(n<=2){const n=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${n} {\n @size(16)\n el: ${s},\n }`,this._stridedUniformArrays.push(t.name),r+=` @align(16) ${t.name} : array<${n}, ${t.length}>,\n`}else r+=` ${t.name} : array<${t.type}, ${t.length}>,\n`;else r+=` ${t.name} : ${t.type},\n`}return r+="};\n",r=`${i}\n${r}`,r+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var uniforms : ${e};\n`,r}_processSamplers(e,t){const i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){const r=i.exec(e);if(null===r)break;const s=r[1],n=r[2],o=s.length-7,a=s.lastIndexOf("Sampler")===o?s.substring(0,o):null,l="sampler_comparison"===n?"comparison":"filtering";if(a){const e=this._webgpuProcessingContext.availableTextures[a];e&&(e.autoBindSampler=!0)}let h=this._webgpuProcessingContext.availableSamplers[s];h||(h={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:l},this._webgpuProcessingContext.availableSamplers[s]=h),this._addSamplerBindingDescription(s,h,t);const c=e.substring(0,r.index),u=`@group(${h.binding.groupIndex}) @binding(${h.binding.bindingIndex}) `,d=e.substring(r.index);e=c+u+d,i.lastIndex+=u.length}return e}_processCustomBuffers(e,t){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(null===r)break;const s=r[1],n=r[3];let o=r[4];const a=r[5];let l=this._webgpuProcessingContext.availableBuffers[o];if(!l){const e="uniform"===s?fc.KnownUBOs[a]:null;let t;e?(o=a,t=e.binding,-1===t.groupIndex&&(t=this._webgpuProcessingContext.availableBuffers[o]?.binding,t||(t=this._webgpuProcessingContext.getNextFreeUBOBinding()))):t=this._webgpuProcessingContext.getNextFreeUBOBinding(),l={binding:t},this._webgpuProcessingContext.availableBuffers[o]=l}this._addBufferBindingDescription(o,this._webgpuProcessingContext.availableBuffers[o],"read_write"===n?"storage":"storage"===s?"read-only-storage":"uniform",t);const h=l.binding.groupIndex,c=l.binding.bindingIndex,u=e.substring(0,r.index),d=`@group(${h}) @binding(${c}) `,f=e.substring(r.index);e=u+d+f,i.lastIndex+=d.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 vc{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e){return this._webgpuMSAATexture?.[e]??null}setMSAATexture(e,t){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),this._webgpuMSAATexture[t]=e}releaseMSAATexture(e){if(this._webgpuMSAATexture)if(e)this._webgpuMSAATexture[e]?.destroy(),delete this._webgpuMSAATexture[e];else{for(const e of this._webgpuMSAATexture)e?.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this._originalFormatIsRGB=!1,this.format="rgba8unorm",this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,r,s,n,o,a){let l="2d",h=1;r?(l=i?"cube-array":"cube",h=6*(a||1)):s?(l="3d",h=1):i&&(l="2d-array",h=a);const c=xh.GetDepthFormatOnly(this.format),u=xh.HasDepthAndStencilAspects(this.format)?"depth-only":"all";this.createView({label:`TextureView${s?"3D":r?"Cube":"2D"}${i?"_Array"+h:""}_${n}x${o}_${t?"wmips":"womips"}_${this.format}_${l}`,format:c,dimension:l,mipLevelCount:t?(0,ar.ILog2)(Math.max(n,o))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:h,aspect:u})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){const t=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=t}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}release(){this._webgpuTexture?.destroy(),this.releaseMSAATexture(),this._copyInvertYTempTexture?.destroy(),this.reset()}}const xc="\n const pos = array, 4>( vec2f(-1.0f, 1.0f), vec2f(1.0f, 1.0f), vec2f(-1.0f, -1.0f), vec2f(1.0f, -1.0f));\n const tex = array, 4>( vec2f(0.0f, 0.0f), vec2f(1.0f, 0.0f), vec2f(0.0f, 1.0f), vec2f(1.0f, 1.0f));\n\n var img: texture_2d;\n\n #ifdef INVERTY\n varying vTextureSize: vec2f;\n #endif\n\n @vertex\n fn main(input : VertexInputs) -> FragmentInputs {\n #ifdef INVERTY\n vertexOutputs.vTextureSize = vec2f(textureDimensions(img, 0));\n #endif\n vertexOutputs.position = vec4f(pos[input.vertexIndex], 0.0, 1.0);\n }\n ",bc=xc;var Sc,Tc;!function(e){e[e.MipMap=0]="MipMap",e[e.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",e[e.Clear=2]="Clear",e[e.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"}(Sc||(Sc={})),function(e){e[e.DontInvertY=0]="DontInvertY",e[e.InvertY=1]="InvertY"}(Tc||(Tc={}));const Cc=[{vertex:"\n const pos = array, 4>( vec2f(-1.0f, 1.0f), vec2f(1.0f, 1.0f), vec2f(-1.0f, -1.0f), vec2f(1.0f, -1.0f));\n const tex = array, 4>( vec2f(0.0f, 0.0f), vec2f(1.0f, 0.0f), vec2f(0.0f, 1.0f), vec2f(1.0f, 1.0f));\n\n varying vTex: vec2f;\n\n @vertex\n fn main(input : VertexInputs) -> FragmentInputs {\n vertexOutputs.vTex = tex[input.vertexIndex];\n vertexOutputs.position = vec4f(pos[input.vertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n var imgSampler: sampler;\n var img: texture_2d;\n\n varying vTex: vec2f;\n\n @fragment\n fn main(input: FragmentInputs) -> FragmentOutputs {\n fragmentOutputs.color = textureSample(img, imgSampler, input.vTex);\n }\n "},{vertex:xc,fragment:"\n var img: texture_2d;\n\n #ifdef INVERTY\n varying vTextureSize: vec2f;\n #endif\n\n @fragment\n fn main(input: FragmentInputs) -> FragmentOutputs {\n #ifdef INVERTY\n var color: vec4f = textureLoad(img, vec2i(i32(input.position.x), i32(input.vTextureSize.y - input.position.y)), 0);\n #else\n var color: vec4f = textureLoad(img, vec2i(input.position.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n fragmentOutputs.color = vec4f(color.rgb * color.a, color.a);\n #endif\n fragmentOutputs.color = color;\n }\n "},{vertex:"\n const pos = array, 4>( vec2f(-1.0f, 1.0f), vec2f(1.0f, 1.0f), vec2f(-1.0f, -1.0f), vec2f(1.0f, -1.0f));\n\n @vertex\n fn main(input : VertexInputs) -> FragmentInputs {\n vertexOutputs.position = vec4f(pos[input.vertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n uniform color: vec4f;\n\n\n @fragment\n fn main(input: FragmentInputs) -> FragmentOutputs {\n fragmentOutputs.color = uniforms.color;\n }\n "},{vertex:bc,fragment:"\n var img: texture_2d;\n uniform ofstX: f32;\n uniform ofstY: f32;\n uniform width: f32;\n uniform height: f32;\n\n #ifdef INVERTY\n varying vTextureSize: vec2f;\n #endif\n\n @fragment\n fn main(input: FragmentInputs) -> FragmentOutputs {\n if (input.position.x < uniforms.ofstX || input.position.x >= uniforms.ofstX + uniforms.width) {\n discard;\n }\n if (input.position.y < uniforms.ofstY || input.position.y >= uniforms.ofstY + uniforms.height) {\n discard;\n }\n #ifdef INVERTY\n var color: vec4f = textureLoad(img, vec2i(i32(input.position.x), i32(uniforms.ofstY + uniforms.height - (input.position.y - uniforms.ofstY))), 0);\n #else\n var color: vec4f = textureLoad(img, vec2i(input.position.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color = vec4f(color.rgb * color.a, color.a);\n #endif\n fragmentOutputs.color = color;\n }\n "}],yc={"":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 Ec{constructor(e,t,i,r){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._engine=e,this._device=t,this._bufferManager=i,-1!==r.indexOf("rg11b10ufloat-renderable")){const e=Object.keys(yc);yc.rg11b10ufloat=yc[e[e.length-1]]+1}this._mipmapSampler=t.createSampler({minFilter:"linear"}),this._videoSampler=t.createSampler({minFilter:"linear"}),this._ubCopyWithOfst=this._bufferManager.createBuffer(16,Eh.Uniform|Eh.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline("rgba8unorm"),this._getVideoPipeline("rgba8unorm")}_getPipeline(e,t=Sc.MipMap,i){const r=t===Sc.MipMap?1:t===Sc.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===Sc.Clear?8:t===Sc.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let s=this._pipelines[e][r];if(!s){let n="";t!==Sc.InvertYPremultiplyAlpha&&t!==Sc.InvertYPremultiplyAlphaWithOfst||(i.invertY&&(n+="#define INVERTY\n"),i.premultiplyAlpha&&(n+="#define PREMULTIPLYALPHA\n"));let o=this._compiledShaders[r];if(!o){let e=Cc[t].vertex,i=Cc[t].fragment;const s={defines:n.split("\n"),indexParameters:null,isFragment:!1,shouldUseHighPrecisionShader:!0,processor:this._engine._getShaderProcessor(1),supportsUniformBuffers:!0,shadersRepository:"",includesShadersStore:{},version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._engine._getShaderProcessingContext(1,!0),isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};(0,Cn.pB)(s),s.processor.pureMode=!0,(0,Cn.M0)(e,s,(t=>{e=t}),this._engine),s.isFragment=!0,(0,Cn.M0)(i,s,(e=>{i=e}),this._engine);const a=(0,Cn.nO)(e,i,s);s.processor.pureMode=!1;const l=this._device.createShaderModule({code:a.vertexCode}),h=this._device.createShaderModule({code:a.fragmentCode});o=this._compiledShaders[r]=[l,h]}const a=this._device.createRenderPipeline({layout:"auto",vertex:{module:o[0],entryPoint:"main"},fragment:{module:o[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:"triangle-strip",stripIndexFormat:"uint16"}});s=this._pipelines[e][r]=[a,a.getBindGroupLayout(0)]}return s}_getVideoPipeline(e,t=Tc.DontInvertY){const i=t===Tc.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let r=this._videoPipelines[e][i];if(!r){let t=this._videoCompiledShaders[i];if(!t){const e=this._device.createShaderModule({code:"\n struct VertexOutput {\n @builtin(position) Position : vec4,\n @location(0) fragUV : vec2\n }\n\n @vertex\n fn main(\n @builtin(vertex_index) VertexIndex : u32\n ) -> VertexOutput {\n var pos = array, 4>(\n vec2(-1.0, 1.0),\n vec2( 1.0, 1.0),\n vec2(-1.0, -1.0),\n vec2( 1.0, -1.0)\n );\n var tex = array, 4>(\n vec2(0.0, 0.0),\n vec2(1.0, 0.0),\n vec2(0.0, 1.0),\n vec2(1.0, 1.0)\n );\n\n var output: VertexOutput;\n\n output.Position = vec4(pos[VertexIndex], 0.0, 1.0);\n output.fragUV = tex[VertexIndex];\n\n return output;\n }\n "}),r=this._device.createShaderModule({code:0===i?"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV);\n }\n ":"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y));\n }\n "});t=this._videoCompiledShaders[i]=[e,r]}const s=this._device.createRenderPipeline({label:`BabylonWebGPUDevice${this._engine.uniqueId}_CopyVideoToTexture_${e}_${0===i?"DontInvertY":"InvertY"}`,layout:"auto",vertex:{module:t[0],entryPoint:"main"},fragment:{module:t[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:"triangle-strip",stripIndexFormat:"uint16"}});r=this._videoPipelines[e][i]=[s,s.getBindGroupLayout(0)]}return r}setCommandEncoder(e){this._commandEncoderForCreation=e}copyVideoToTexture(e,t,i,r=!1,s){const n=void 0===s,[o,a]=this._getVideoPipeline(i,r?Tc.InvertY:Tc.DontInvertY);n&&(s=this._device.createCommandEncoder({})),s.pushDebugGroup?.(`copy video to texture - invertY=${r}`);const l=t._hardwareTexture,h={label:`BabylonWebGPUDevice${this._engine.uniqueId}_copyVideoToTexture_${i}_${r?"InvertY":"DontInvertY"}${t.label?"_"+t.label:""}`,colorAttachments:[{view:l.underlyingResource.createView({format:i,dimension:"2d",mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:"all"}),loadOp:"load",storeOp:"store"}]},c=s.beginRenderPass(h),u={layout:a,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},d=this._device.createBindGroup(u);c.setPipeline(o),c.setBindGroup(0,d),c.draw(4,1,0,0),c.end(),s.popDebugGroup?.(),n&&(this._device.queue.submit([s.finish()]),s=null)}invertYPreMultiplyAlpha(e,t,i,r,s=!1,n=!1,o=0,a=0,l=1,h=0,c=0,u=0,d=0,f,p){const _=0!==u,m=void 0===f,[g,v]=this._getPipeline(r,_?Sc.InvertYPremultiplyAlphaWithOfst:Sc.InvertYPremultiplyAlpha,{invertY:s,premultiplyAlpha:n});let x;if(o=Math.max(o,0),m&&(f=this._device.createCommandEncoder({})),f.pushDebugGroup?.(`internal process texture - invertY=${s} premultiplyAlpha=${n}`),xh.IsHardwareTexture(e)?(x=e.underlyingResource,s&&!n&&1===l&&0===o||(e=void 0)):(x=e,e=void 0),!x)return;_&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([h,c,u,d]),0,16);const b=e,S=b?._copyInvertYTempTexture??this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,r,1,f,21,void 0,"TempTextureForCopyWithInvertY"),T=b?._copyInvertYRenderPassDescr??{label:`BabylonWebGPUDevice${this._engine.uniqueId}_invertYPreMultiplyAlpha_${r}_${s?"InvertY":"DontInvertY"}_${n?"PremultiplyAlpha":"DontPremultiplyAlpha"}`,colorAttachments:[{view:S.createView({format:r,dimension:"2d",baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:"load",storeOp:"store"}]},C=f.beginRenderPass(T);let y=_?b?._copyInvertYBindGroupWithOfst:b?._copyInvertYBindGroup;if(!y){const e={layout:v,entries:[{binding:0,resource:x.createView({format:r,dimension:"2d",baseMipLevel:a,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:o})}]};_&&e.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),y=this._device.createBindGroup(e)}C.setPipeline(g),C.setBindGroup(0,y),C.draw(4,1,0,0),C.end(),f.copyTextureToTexture({texture:S},{texture:x,mipLevel:a,origin:{x:0,y:0,z:o}},{width:t,height:i,depthOrArrayLayers:1}),b?(b._copyInvertYTempTexture=S,b._copyInvertYRenderPassDescr=T,_?b._copyInvertYBindGroupWithOfst=y:b._copyInvertYBindGroup=y):this._deferredReleaseTextures.push([S,null]),f.popDebugGroup?.(),m&&(this._device.queue.submit([f.finish()]),f=null)}copyWithInvertY(e,t,i,r){const s=void 0===r,[n,o]=this._getPipeline(t,Sc.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});s&&(r=this._device.createCommandEncoder({})),r.pushDebugGroup?.("internal copy texture with invertY");const a=r.beginRenderPass(i),l=this._device.createBindGroup({layout:o,entries:[{binding:0,resource:e}]});a.setPipeline(n),a.setBindGroup(0,l),a.draw(4,1,0,0),a.end(),r.popDebugGroup?.(),s&&(this._device.queue.submit([r.finish()]),r=null)}createTexture(e,t=!1,i=!1,r=!1,s=!1,n=!1,o="rgba8unorm",a=1,l,h=-1,c=0,u){a=xh.GetSample(a);const d=e.layers||1,f={width:e.width,height:e.height,depthOrArrayLayers:d},p=yc[o]?16:0,_=xh.IsCompressedFormat(o),m=t?xh.ComputeNumMipmapLevels(e.width,e.height):1,g=h>=0?h:7;c|=t&&!_?1|p:0,_||n||(c|=2|p);const v=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_Texture${n?"3D":"2D"}_${u?u+"_":""}${f.width}x${f.height}x${f.depthOrArrayLayers}_${t?"wmips":"womips"}_${o}_samples${a}`,size:f,dimension:n?"3d":"2d",format:o,usage:g|c,sampleCount:a,mipLevelCount:m});return xh.IsImageBitmap(e)&&(this.updateTexture(e,v,e.width,e.height,d,o,0,0,r,s,0,0),t&&i&&this.generateMipmaps(v,o,m,0,n,l)),v}createCubeTexture(e,t=!1,i=!1,r=!1,s=!1,n="rgba8unorm",o=1,a,l=-1,h=0,c){o=xh.GetSample(o);const u=xh.IsImageBitmapArray(e)?e[0].width:e.width,d=xh.IsImageBitmapArray(e)?e[0].height:e.height,f=yc[n]?16:0,p=xh.IsCompressedFormat(n),_=t?xh.ComputeNumMipmapLevels(u,d):1,m=l>=0?l:7;h|=t&&!p?1|f:0,p||(h|=2|f);const g=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_TextureCube_${c?c+"_":""}${u}x${d}x6_${t?"wmips":"womips"}_${n}_samples${o}`,size:{width:u,height:d,depthOrArrayLayers:6},dimension:"2d",format:n,usage:m|h,sampleCount:o,mipLevelCount:_});return xh.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,g,u,d,n,r,s,0,0),t&&i&&this.generateCubeMipmaps(g,n,_,a)),g}generateCubeMipmaps(e,t,i,r){const s=void 0===r;s&&(r=this._device.createCommandEncoder({})),r.pushDebugGroup?.(`create cube mipmaps - ${i} levels`);for(let s=0;s<6;++s)this.generateMipmaps(e,t,i,s,!1,r);r.popDebugGroup?.(),s&&(this._device.queue.submit([r.finish()]),r=null)}generateMipmaps(e,t,i,r=0,s=!1,n){const o=void 0===n,[a,l]=this._getPipeline(t);let h;if(r=Math.max(r,0),o&&(n=this._device.createCommandEncoder({})),n.pushDebugGroup?.(`create mipmaps for face #${r} - ${i} levels`),xh.IsHardwareTexture(e)?(h=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(h=e,e=void 0),!h)return;const c=e;for(let e=1;eh;)this._device.queue.writeBuffer(n,t+c,i.buffer,o+c,h),c+=h;this._device.queue.writeBuffer(n,t+c,i.buffer,o+c,s-c)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const r=new Uint16Array(t);for(;e--;)i[e]=(0,Ac.SX)(r[e]);return i}readDataFromBuffer(e,t,i,r,s,n,o=0,a=0,l=null,h=!0,c=!1){const u=1===o?2:2===o?1:0,d=this._engine.uniqueId;return new Promise(((i,f)=>{e.mapAsync(1,a,t).then((()=>{const d=e.getMappedRange(a,t);let f=l;if(c)f=null===f?(0,Xs.kZ)(o,t,!0,d):(0,Xs.kZ)(o,f.buffer,void 0,d);else if(null===f)switch(u){case 0:f=new Uint8Array(t),f.set(new Uint8Array(d));break;case 1:f=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d);break;case 2:f=new Float32Array(t/4),f.set(new Float32Array(d))}else switch(u){case 0:f=new Uint8Array(f.buffer),f.set(new Uint8Array(d));break;case 1:f=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d,l);break;case 2:f=new Float32Array(f.buffer),f.set(new Float32Array(d))}if(s!==n){1!==u||c||(s*=2,n*=2);const e=new Uint8Array(f.buffer);let t=s,i=0;for(let o=1;o{this._engine.isDisposed||this._engine.uniqueId!==d?i(new Uint8Array):f(e)}))}))}releaseBuffer(e){return Rc._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,0===e.references&&(this._deferredReleaseBuffers.push(e.underlyingResource),!0))}destroyDeferredBuffers(){for(let e=0;e1&&(0!==n||0!==o)&&"nearest"!==s?{magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",anisotropyEnabled:!0}:{magFilter:i,minFilter:r,mipmapFilter:s,lodMinClamp:n,lodMaxClamp:o}}static _GetWrappingMode(e){switch(e){case 1:return"repeat";case 0:return"clamp-to-edge";case 2:return"mirror-repeat"}return"repeat"}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e,t){const i=e.useMipMaps&&e._cachedAnisotropicFilteringLevel?e._cachedAnisotropicFilteringLevel:1,r=this._GetSamplerFilterDescriptor(e,i);return{label:t,...r,...this._GetSamplerWrappingDescriptor(e),compare:e._comparisonFunction?Dc.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:r.anisotropyEnabled?i:1}}static GetCompareFunction(e){switch(e){case 519:return"always";case 514:return"equal";case 516:return"greater";case 518:return"greater-equal";case 513:default:return"less";case 515:return"less-equal";case 512:return"never";case 517:return"not-equal"}}getSampler(e,t=!1,i=0,r){if(this.disabled)return this._device.createSampler(Dc._GetSamplerDescriptor(e,r));t?i=0:0===i&&(i=Dc.GetSamplerHashCode(e));let s=t?void 0:this._samplers[i];return s||(s=this._device.createSampler(Dc._GetSamplerDescriptor(e,r)),t||(this._samplers[i]=s)),s}}var wc;!function(e){e[e.StencilReadMask=0]="StencilReadMask",e[e.StencilWriteMask=1]="StencilWriteMask",e[e.DepthBias=2]="DepthBias",e[e.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",e[e.DepthStencilState=4]="DepthStencilState",e[e.MRTAttachments1=5]="MRTAttachments1",e[e.MRTAttachments2=6]="MRTAttachments2",e[e.RasterizationState=7]="RasterizationState",e[e.ColorStates=8]="ColorStates",e[e.ShaderStage=9]="ShaderStage",e[e.TextureStage=10]="TextureStage",e[e.VertexState=11]="VertexState",e[e.NumStates=12]="NumStates"}(wc||(wc={}));const Nc={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},Fc={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7};class Lc{constructor(e,t){this.mrtTextureCount=0,this._device=e,this._useTextureStage=!0,this._states=new Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}reset(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=["bgra8unorm"],this.setColorFormat("bgra8unorm"),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat("depth24plus-stencil8"),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)}get colorFormats(){return this._mrtAttachments1>0?this._mrtFormats:this._webgpuColorFormat}getRenderPipeline(e,t,i,r=0){if(i=xh.GetSample(i),this.disabled){const s=Lc._GetTopology(e);return this._setVertexState(t),this._setTextureState(r),this._parameter.pipeline=this._createRenderPipeline(t,s,i),Lc.NumCacheMiss++,Lc._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(r),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,Lc.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return Lc.NumCacheHitWithHash++,this._parameter.pipeline;const s=Lc._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,s,i),this._setRenderPipeline(this._parameter),Lc.NumCacheMiss++,Lc._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){Lc.NumPipelineCreationLastFrame=Lc._NumPipelineCreationCurrentFrame,Lc._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,r,s,n,o,a){this._depthWriteEnabled=o,this._depthTestEnabled=n,this._depthCompare=(a??519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(r),this.setDepthBias(s)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[wc.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,wc.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[wc.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,wc.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=yc[e??""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;const i=[0,0];let r=0,s=0,n=0;for(let o=0;o=32&&(s=0,r++)}this._mrtFormats.length=n,this._mrtAttachments1===i[0]&&this._mrtAttachments2===i[1]||(this._mrtAttachments1=i[0],this._mrtAttachments2=i[1],this._states[wc.MRTAttachments1]=i[0],this._states[wc.MRTAttachments2]=i[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,wc.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=void 0===e?0:yc[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=null===e?1:Fc[e]}setStencilPassOp(e){this._stencilFrontPassOp=null===e?2:Fc[e]}setStencilFailOp(e){this._stencilFrontFailOp=null===e?1:Fc[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[wc.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,wc.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[wc.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,wc.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,r,s,n,o){this._stencilEnabled=e,this._stencilFrontCompare=(t??519)-512,this._stencilFrontDepthFailOp=null===i?1:Fc[i],this._stencilFrontPassOp=null===r?2:Fc[r],this._stencilFrontFailOp=null===s?1:Fc[s],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:default:return"triangle-list";case 2:case 3:return"point-list";case 1:case 4:return"line-list";case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return"line-strip";case 7:return"triangle-strip";case 8:throw"TriangleFan is an unsupported fillmode in WebGPU"}}static _GetAphaBlendOperation(e){switch(e){case 32774:default:return"add";case 32778:return"subtract";case 32779:return"reverse-subtract";case 32775:return"min";case 32776:return"max"}}static _GetAphaBlendFactor(e){switch(e){case 0:return"zero";case 1:default:return"one";case 768:return"src";case 769:return"one-minus-src";case 770:return"src-alpha";case 771:return"one-minus-src-alpha";case 772:return"dst-alpha";case 773:return"one-minus-dst-alpha";case 774:return"dst";case 775:return"one-minus-dst";case 776:return"src-alpha-saturated";case 32769:case 32771:return"constant";case 32770:case 32772:return"one-minus-constant";case 35065:return"src1";case 35066:return"one-minus-src1";case 34185:return"src1-alpha";case 35067:return"one-minus-src1-alpha"}}static _GetCompareFunction(e){switch(e){case 0:return"never";case 1:return"less";case 2:return"equal";case 3:return"less-equal";case 4:return"greater";case 5:return"not-equal";case 6:return"greater-equal";case 7:return"always"}return"never"}static _GetStencilOpFunction(e){switch(e){case 0:return"zero";case 1:return"keep";case 2:return"replace";case 3:return"increment-clamp";case 4:return"decrement-clamp";case 5:return"invert";case 6:return"increment-wrap";case 7:return"decrement-wrap"}return"keep"}static _GetVertexInputDescriptorFormat(e){const t=e.type,i=e.normalized,r=e.getSize();switch(t){case st.R.BYTE:switch(r){case 1:case 2:return i?"snorm8x2":"sint8x2";case 3:case 4:return i?"snorm8x4":"sint8x4"}break;case st.R.UNSIGNED_BYTE:switch(r){case 1:case 2:return i?"unorm8x2":"uint8x2";case 3:case 4:return i?"unorm8x4":"uint8x4"}break;case st.R.SHORT:switch(r){case 1:case 2:return i?"snorm16x2":"sint16x2";case 3:case 4:return i?"snorm16x4":"sint16x4"}break;case st.R.UNSIGNED_SHORT:switch(r){case 1:case 2:return i?"unorm16x2":"uint16x2";case 3:case 4:return i?"unorm16x4":"uint16x4"}break;case st.R.INT:switch(r){case 1:return"sint32";case 2:return"sint32x2";case 3:return"sint32x3";case 4:return"sint32x4"}break;case st.R.UNSIGNED_INT:switch(r){case 1:return"uint32";case 2:return"uint32x2";case 3:return"uint32x3";case 4:return"uint32x4"}break;case st.R.FLOAT:switch(r){case 1:return"float32";case 2:return"float32x2";case 3:return"float32x3";case 4:return"float32x4"}}throw new Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${r}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:Lc._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:Lc._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:Lc._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:Lc._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:Lc._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:Lc._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[wc.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,wc.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace-1+((this._cullEnabled?this._cullFace:0)<<1)+((this._clampDepth?1:0)<<3)+((this._alphaToCoverageEnabled?1:0)<<4)+(e<<5)+(t<<8);this._rasterizationState!==i&&(this._rasterizationState=i,this._states[wc.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,wc.RasterizationState))}_setColorStates(){let e=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(e+=(0|(null===this._alphaBlendFuncParams[0]?2:Nc[this._alphaBlendFuncParams[0]]))+((null===this._alphaBlendFuncParams[1]?2:Nc[this._alphaBlendFuncParams[1]])<<4)+((null===this._alphaBlendFuncParams[2]?2:Nc[this._alphaBlendFuncParams[2]])<<8)+((null===this._alphaBlendFuncParams[3]?2:Nc[this._alphaBlendFuncParams[3]])<<12)+((null===this._alphaBlendEqParams[0]?1:this._alphaBlendEqParams[0]-32773)<<16)+((null===this._alphaBlendEqParams[1]?1:this._alphaBlendEqParams[1]-32773)<<19)),e!==this._colorStates&&(this._colorStates=e,this._states[wc.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,wc.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[wc.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,wc.DepthStencilState))}_setVertexState(e){const t=this._statesLength;let i=wc.VertexState;const r=e._pipelineContext,s=r.shaderProcessingContext.attributeNamesFromEffect,n=r.shaderProcessingContext.attributeLocationsFromEffect;let o,a=0;for(let e=0;e0)for(let e=0;e=this._video.HAVE_CURRENT_DATA}dispose(){}}class Hc{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatOrDepthTextures(){return this._numFloatOrDepthTextures>0}constructor(){this.uniqueId=Hc._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatOrDepthTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],r=-1;i?r=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?Dc.GetSamplerHashCode(t):0;const s=r!==i.hashCode;s&&this.updateId++,this.isDirty||(this.isDirty=s)}setTexture(e,t){let i=this.textures[e],r=-1;i?r=i.texture?.uniqueId??-1:this.textures[e]=i={texture:t,isFloatOrDepthTexture:!1,isExternalTexture:!1},i.isExternalTexture&&this._numExternalTextures--,i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures--,t?(i.isFloatOrDepthTexture=1===t.type||t.format>=13&&t.format<=18,i.isExternalTexture=Wc.IsExternalTexture(t),i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,i.isExternalTexture&&this._numExternalTextures++):(i.isFloatOrDepthTexture=!1,i.isExternalTexture=!1),i.texture=t;const s=r!==(t?.uniqueId??-1);s&&this.updateId++,this.isDirty||(this.isDirty=s)}}Hc._Counter=0;class Xc{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,Eh.CopyDst|Eh.Indirect|Eh.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=Xc._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){this._isDirty||(this._isDirty=t?.uniqueId!==this.buffers[e]?.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}}Xc._Counter=0;const qc=2**35;class Yc{constructor(){this.values={}}}class Kc{static get Statistics(){return{totalCreated:Kc.NumBindGroupsCreatedTotal,lastFrameCreated:Kc.NumBindGroupsCreatedLastFrame,lookupLastFrame:Kc.NumBindGroupsLookupLastFrame,noLookupLastFrame:Kc.NumBindGroupsNoLookupLastFrame}}static ResetCache(){Kc._Cache=new Yc,Kc.NumBindGroupsCreatedTotal=0,Kc.NumBindGroupsCreatedLastFrame=0,Kc.NumBindGroupsLookupLastFrame=0,Kc.NumBindGroupsNoLookupLastFrame=0,Kc._NumBindGroupsCreatedCurrentFrame=0,Kc._NumBindGroupsLookupCurrentFrame=0,Kc._NumBindGroupsNoLookupCurrentFrame=0}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){Kc.NumBindGroupsCreatedLastFrame=Kc._NumBindGroupsCreatedCurrentFrame,Kc.NumBindGroupsLookupLastFrame=Kc._NumBindGroupsLookupCurrentFrame,Kc.NumBindGroupsNoLookupLastFrame=Kc._NumBindGroupsNoLookupCurrentFrame,Kc._NumBindGroupsCreatedCurrentFrame=0,Kc._NumBindGroupsLookupCurrentFrame=0,Kc._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){let r,s=Kc._Cache;const n=this.disabled||i.forceBindGroupCreation;if(!n){if(!t.isDirty(i.updateId)&&!i.isDirty)return Kc._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const i of e.shaderProcessingContext.bufferNames){const e=(t.buffers[i]?.uniqueId??0)+1048576;let r=s.values[e];r||(r=new Yc,s.values[e]=r),s=r}for(const t of e.shaderProcessingContext.samplerNames){const e=i.samplers[t]?.hashCode??0;let r=s.values[e];r||(r=new Yc,s.values[e]=r),s=r}for(const t of e.shaderProcessingContext.textureNames){const e=(i.textures[t]?.texture?.uniqueId??0)+qc;let r=s.values[e];r||(r=new Yc,s.values[e]=r),s=r}r=s.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,r)return t.bindGroups=r,Kc._NumBindGroupsLookupCurrentFrame++,r;r=[],t.bindGroups=r,n||(s.bindGroups=r),Kc.NumBindGroupsCreatedTotal++,Kc._NumBindGroupsCreatedCurrentFrame++;const o=e.bindGroupLayouts[i.textureState];for(let s=0;s"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[r].resource=this._cacheSampler.getSampler(t,!1,e.hashCode,t.label)}else Z.V.Error(`Sampler "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.texture||n.storageTexture){const e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){Z.V.Error(`Trying to bind a null texture! entry=${JSON.stringify(n)}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!t||n.texture&&!t.view||n.storageTexture&&!t.viewForWriting)){Z.V.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, isReady=${e.texture?.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[r].resource=n.storageTexture?t.viewForWriting:t.view}else Z.V.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.externalTexture){const e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){Z.V.Error(`Trying to bind a null external texture! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!t){Z.V.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, isReady=${e.texture?.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[r].resource=this._device.importExternalTexture({source:t})}else Z.V.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.buffer){const e=t.buffers[l];if(e){const t=e.underlyingResource;a[r].resource.buffer=t,a[r].resource.size=e.capacity}else Z.V.Error(`Can't find buffer "${l}". entry=${JSON.stringify(n)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}const l=o[s];r[s]=this._device.createBindGroup({layout:l,entries:a})}return r}}Kc.NumBindGroupsCreatedTotal=0,Kc.NumBindGroupsCreatedLastFrame=0,Kc.NumBindGroupsLookupLastFrame=0,Kc.NumBindGroupsNoLookupLastFrame=0,Kc._Cache=new Yc,Kc._NumBindGroupsCreatedCurrentFrame=0,Kc._NumBindGroupsLookupCurrentFrame=0,Kc._NumBindGroupsNoLookupCurrentFrame=0;Cs.l.ShadersStoreWGSL.clearQuadVertexShader="uniform depthValue: f32;const pos=array(\nvec2f(-1.0,1.0),\nvec2f(1.0,1.0),\nvec2f(-1.0,-1.0),\nvec2f(1.0,-1.0)\n);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.position=vec4f(pos[input.vertexIndex],uniforms.depthValue,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";Cs.l.ShadersStoreWGSL.clearQuadPixelShader="uniform color: vec4f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=uniforms.color;}\n";class jc{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 Vc(this._device,i),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"],void 0,void 0,void 0,void 0,void 0,void 0,1)}clear(e,t,i,r,s=1){let n,o,a=null;const l=!!this._engine._currentRenderTarget;if(e)n=e;else{let e=0;this._keyTemp.length=0;for(let t=0;t1?2**36:0)+h*2**37,o=this._keyTemp.join("_"),a=this._bundleCache[o],a)return a;n=this._device.createRenderBundleEncoder({label:"clearQuadRenderBundle",colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:xh.GetSample(s)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!r&&!!this._depthTextureFormat&&xh.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(r?255:0),this._cacheRenderPipeline.setStencilCompare(r?519:512),this._cacheRenderPipeline.setStencilPassOp(r?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);const h=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,s),c=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),c.uniformBuffer.update();const u=l?this._engine._ubInvertY:this._engine._ubDontInvertY,d=c.uniformBuffer.getBuffer(),f=d.uniqueId+"-"+u.uniqueId;let p=this._bindGroups[f];if(!p){const e=c.bindGroupLayouts[0];p=this._bindGroups[f]=[],p.push(this._device.createBindGroup({label:`clearQuadBindGroup0-${f}`,layout:e[0],entries:[]})),fc._SimplifiedKnownBindings||p.push(this._device.createBindGroup({label:`clearQuadBindGroup1-${f}`,layout:e[1],entries:[]})),p.push(this._device.createBindGroup({label:`clearQuadBindGroup${fc._SimplifiedKnownBindings?1:2}-${f}`,layout:e[fc._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:u.underlyingResource,size:u.capacity}},{binding:1,resource:{buffer:d.underlyingResource,size:d.capacity}}]}))}n.setPipeline(h);for(let e=0;e{const e=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,e}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==r)return null;throw e}))}async readValue(e=0){const t=this._getBuffer(e,1);if(null===t)return null;const i=this._engine.uniqueId;return t.mapAsync(1).then((()=>{const e=new BigUint64Array(t.getMappedRange()),i=Number(e[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,i}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw e}))}async readTwoValuesAndSubtract(e=0){const t=this._getBuffer(e,2);if(null===t)return null;const i=this._engine.uniqueId;return t.mapAsync(1).then((()=>{const e=new BigUint64Array(t.getMappedRange()),i=Number(e[1]-e[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,i}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw e}))}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e{null!==e&&e>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(e,!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((e=>{t._addDuration(i,null!==e&&e>0?e:0)}))}dispose(){this._measureDuration?.dispose()}}class ou{constructor(e,t,i,r=2,s){this._count=r,this._querySet=new su(e,r,"timestamp",t,i,!0,s)}start(e){e.writeTimestamp?.(this._querySet.querySet,0)}async stop(e){return e.writeTimestamp?.(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 au{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=void 0!==this._engine._getCurrentRenderPassWrapper().renderPassDescriptor.occlusionQuerySet;return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,i,r=50,s=100){this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=s,this._allocateNewIndices(r)}createQuery(){0===this._availableIndices.length&&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(){this._querySet?.dispose(),this._availableIndices.length=0}}class lu{async initTwgsl(e){if(!lu._Twgsl)return e=e||{},(e={...lu._TWgslDefaultOptions,...e}).twgsl?(lu._Twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await Ue.S0.LoadBabylonScriptAsync(e.jsPath),self.twgsl?(lu._Twgsl=await self.twgsl(Ue.S0.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=lu._Twgsl.convertSpirV2WGSL(e,lu.DisableUniformityAnalysis||t);return lu.ShowWGSLShaderCode&&(Z.V.Log(i),Z.V.Log("***********************************************")),lu.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}}lu._TWgslDefaultOptions={jsPath:`${Ue.S0._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${Ue.S0._DefaultCdnUrl}/twgsl/twgsl.wasm`},lu.ShowWGSLShaderCode=!1,lu.DisableUniformityAnalysis=!1,lu._Twgsl=null;class hu{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),1===this._mode&&this._engine._reportDrawCall(t.numDrawCalls),!0}endFrame(){this._record&&(this._record=!1,this._play=!0,this._mode=this._modeSaved),this._playBundleListIndex=0}reset(){this._record&&(this._mode=this._modeSaved),this.enabled=!1,this.enabled=!0}}var cu=i(73010);class uu extends Wc{constructor(e){super(e)}}function du(e,t,i,r){let s,n=1;1===r?s=new Float32Array(t*i*4):2===r?(s=new Uint16Array(t*i*4),n=15360):s=7===r?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let r=0;r{const i=d.width,n=o(e);if(n){if(a){const e=4===r,t=a(n),o=d._hardwareTexture,l=[0,1,2,3,4,5];for(let r=0;r>r,a=[];for(let i=0;i<6;i++){let o=t[r][l[i]];e&&(o=du(o,n,n,s)),a.push(new Uint8Array(o.buffer,o.byteOffset,o.byteLength))}this._textureHelper.updateCubeTextures(a,o.underlyingResource,n,n,o.format,u,!1,0,0)}}else this.updateRawCubeTexture(d,n,r,s,u);d.isReady=!0,t?.removePendingData(d),l&&l()}};return this._loadFile(e,(e=>{f(e)}),void 0,t?.offlineProvider,!0,((e,i)=>{t?.removePendingData(d),h&&e&&h(e.status+" "+e.statusText,i)})),d},Sh.prototype.createRawTexture3D=function(e,t,i,r,s,n,o,a,l=null,h=0,c=0){const u=new Fs.h(this,10);return u.baseWidth=t,u.baseHeight=i,u.baseDepth=r,u.width=t,u.height=i,u.depth=r,u.format=s,u.type=h,u.generateMipMaps=n,u.samplingMode=a,u.is3D=!0,u._creationFlags=c,this._doNotHandleContextLost||(u._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(u,t,i,void 0,c),this.updateRawTexture3D(u,e,s,o,l,h),this._internalTexturesCache.push(u),u},Sh.prototype.updateRawTexture3D=function(e,t,i,r,s=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s),t){const s=e._hardwareTexture;4===i&&(t=du(t,e.width,e.height,n));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},Sh.prototype.createRawTexture2DArray=function(e,t,i,r,s,n,o,a,l=null,h=0,c=0){const u=new Fs.h(this,11);return u.baseWidth=t,u.baseHeight=i,u.baseDepth=r,u.width=t,u.height=i,u.depth=r,u.format=s,u.type=h,u.generateMipMaps=n,u.samplingMode=a,u.is2DArray=!0,u._creationFlags=c,this._doNotHandleContextLost||(u._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(u,t,i,r,c),this.updateRawTexture2DArray(u,e,s,o,l,h),this._internalTexturesCache.push(u),u},Sh.prototype.updateRawTexture2DArray=function(e,t,i,r,s=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s),t){const s=e._hardwareTexture;4===i&&(t=du(t,e.width,e.height,n));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},Sh.prototype._readTexturePixels=function(e,t,i,r=-1,s=0,n=null,o=!0,a=!1,l=0,h=0){const c=e._hardwareTexture;return o&&this.flushFramebuffer(),this._textureHelper.readPixels(c.underlyingResource,l,h,t,i,c.format,r,s,n,a)},Sh.prototype._readTexturePixelsSync=function(){throw"_readTexturePixelsSync is unsupported in WebGPU!"},Sh.prototype._createDepthStencilCubeTexture=function(e,t){const i=new Fs.h(this,t.generateStencil?12:14);i.isCube=!0,i.label=t.label;const r={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14,...t};i.format=r.depthTextureFormat,this._setupDepthStencilTexture(i,e,r.bilinearFiltering,r.comparisonFunction,r.samples),this._textureHelper.createGPUTextureForInternalTexture(i);const s=i._hardwareTexture;return i.type=xh.GetTextureTypeFromFormat(s.format),this._internalTexturesCache.push(i),i},Sh.prototype.createCubeTexture=function(e,t,i,r,s=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d,f=!1,p=null){return this.createCubeTextureBase(e,t,i,!!r,s,n,o,a,l,h,c,u,null,((e,t)=>{const i=t,n=i[0].width,a=n;this._setCubeMapTextureParams(e,!r),e.format=o??-1;const l=this._textureHelper.createGPUTextureForInternalTexture(e,n,a);this._textureHelper.updateCubeTextures(i,l.underlyingResource,n,a,l.format,!1,!1,0,0),r||this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),s&&s()}),!!f,p)},Sh.prototype._setCubeMapTextureParams=function(e,t,i){e.samplingMode=t?3:2,e._cachedWrapU=0,e._cachedWrapV=0,i&&(e._maxLodLevel=i)},Sh.prototype.generateMipMapsForCubemap=function(e){if(e.generateMipMaps){const t=e._hardwareTexture?.underlyingResource;t||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e)}};class fu extends qs{constructor(e,t,i,r,s){super(e,t,i,r,s),r.enableGPUTimingMeasurements&&(this.gpuTimeInFrame=new bh.e)}}Sh.prototype._createHardwareRenderTargetWrapper=function(e,t,i){const r=new fu(e,t,i,this);return this._renderTargetWrapperCache.push(r),r},Sh.prototype.createRenderTargetTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e),r={};void 0!==t&&"object"==typeof t?(r.generateMipMaps=t.generateMipMaps,r.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,r.generateStencilBuffer=r.generateDepthBuffer&&t.generateStencilBuffer,r.samplingMode=void 0===t.samplingMode?3:t.samplingMode,r.creationFlags=t.creationFlags??0,r.noColorAttachment=!!t.noColorAttachment,r.colorAttachment=t.colorAttachment,r.samples=t.samples,r.label=t.label,r.format=t.format,r.type=t.type):(r.generateMipMaps=t,r.generateDepthBuffer=!0,r.generateStencilBuffer=!1,r.samplingMode=3,r.creationFlags=0,r.noColorAttachment=!1);const s=r.colorAttachment||(r.noColorAttachment?null:this._createInternalTexture(e,r,!0,5));return i.label=r.label??"RenderTargetWrapper",i._samples=r.colorAttachment?.samples??r.samples??1,i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=!!r.generateStencilBuffer,i.setTextures(s),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,!1,i._generateStencilBuffer,i.samples,r.generateStencilBuffer?13:14,r.label?r.label+"-DepthStencil":void 0),s&&!r.colorAttachment&&(void 0!==t&&"object"==typeof t&&t.createMipMaps&&!r.generateMipMaps&&(s.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(s,void 0,void 0,void 0,r.creationFlags),void 0!==t&&"object"==typeof t&&t.createMipMaps&&!r.generateMipMaps&&(s.generateMipMaps=!1)),i},Sh.prototype._createDepthStencilTexture=function(e,t,i){const r={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14,...t},s=17===r.depthTextureFormat||13===r.depthTextureFormat||18===r.depthTextureFormat;i._depthStencilTextureWithStencil=s;const n=new Fs.h(this,s?12:14);n.label=t.label,n.format=r.depthTextureFormat,this._setupDepthStencilTexture(n,e,r.bilinearFiltering,r.comparisonFunction,r.samples),this._textureHelper.createGPUTextureForInternalTexture(n);const o=n._hardwareTexture;return n.type=xh.GetTextureTypeFromFormat(o.format),this._internalTexturesCache.push(n),n},Sh.prototype._setupDepthStencilTexture=function(e,t,i,r,s=1){const n=t.width??t,o=t.height??t,a=t.layers||0,l=t.depth||0;e.baseWidth=n,e.baseHeight=o,e.width=n,e.height=o,e.is2DArray=a>0,e.is3D=l>0,e.depth=a||l,e.isReady=!0,e.samples=s,e.generateMipMaps=!1,e.samplingMode=i?2:1,e.type=1,e._comparisonFunction=r,e._cachedWrapU=0,e._cachedWrapV=0},Sh.prototype.updateRenderTargetTextureSampleCount=function(e,t){return e&&e.texture&&e.samples!==t?(t=Math.min(t,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(e.texture,t),e._depthStencilTexture&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),e._samples=t,e.texture.samples=t,t):t},Sh.prototype.setDepthStencilTexture=function(e,t,i,r){i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,r):this._setTexture(e,null,void 0,void 0,r)},Sh.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),r={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1,...t};r.generateStencilBuffer=r.generateDepthBuffer&&r.generateStencilBuffer,i.label=r.label??"RenderTargetWrapper",i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=r.generateStencilBuffer;const s=new Fs.h(this,5);return s.width=e,s.height=e,s.depth=0,s.isReady=!0,s.isCube=!0,s.samples=r.samples,s.generateMipMaps=r.generateMipMaps,s.samplingMode=r.samplingMode,s.type=r.type,s.format=r.format,this._internalTexturesCache.push(s),i.setTextures(s),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,void 0===r.samplingMode||2===r.samplingMode||2===r.samplingMode||3===r.samplingMode||3===r.samplingMode||5===r.samplingMode||6===r.samplingMode||7===r.samplingMode||11===r.samplingMode,i._generateStencilBuffer,i.samples),t&&t.createMipMaps&&!r.generateMipMaps&&(s.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(s),t&&t.createMipMaps&&!r.generateMipMaps&&(s.generateMipMaps=!1),i},Sh.prototype.getGPUFrameTimeCounter=function(){return this._timestampQuery.gpuFrameTimeCounter},Sh.prototype.captureGPUFrameTime=function(e){this._timestampQuery.enable=e&&!!this._caps.timerQuery},Sh.prototype.createQuery=function(){return this._occlusionQuery.createQuery()},Sh.prototype.deleteQuery=function(e){return this._occlusionQuery.deleteQuery(e),this},Sh.prototype.isQueryResultAvailable=function(e){return this._occlusionQuery.isQueryResultAvailable(e)},Sh.prototype.getQueryResult=function(e){return this._occlusionQuery.getQueryResult(e)},Sh.prototype.beginOcclusionQuery=function(e,t){return this.compatibilityMode?!!this._occlusionQuery.canBeginQuery(t)&&(this._currentRenderPass?.beginOcclusionQuery(t),!0):(this._bundleList.addItem(new eu(t)),!0)},Sh.prototype.endOcclusionQuery=function(){return this.compatibilityMode?this._currentRenderPass?.endOcclusionQuery():this._bundleList.addItem(new tu),this};const pu={label:"TextureView_SwapChain_ResolveTarget",dimension:"2d",format:void 0,mipLevelCount:1,arrayLayerCount:1},_u={label:"TextureView_SwapChain",dimension:"2d",format:void 0,mipLevelCount:1,arrayLayerCount:1},mu=new hc.ov;class gu extends Sh{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}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return!!this._cacheRenderPipeline&&this._cacheRenderPipeline.disabled}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return!!this._cacheBindGroups&&this._cacheBindGroups.disabled}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}areAllEffectsReady(){return!0}getFontOffset(e){return Zs(e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then((e=>!!e),(()=>!1)).catch((()=>!1)):Promise.resolve(!1)}static get IsSupported(){return Z.V.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 currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const i=new gu(e,t);return new Promise((e=>{i.initAsync(t.glslangOptions,t.twgslOptions).then((()=>e(i)))}))}constructor(e,t={}){super(t.antialias??!0,t),this.uniqueId=-1,this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._clearDepthValue=1,this._clearReverseDepthValue=0,this._clearStencilValue=0,this._defaultSampleCount=4,this._glslang=null,this._tintWASM=null,this._glslangAndTintAreFullyLoaded=!1,this._adapterInfo={vendor:"",architecture:"",device:"",description:""},this._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._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._debugStackRenderPass=[],this._currentOverrideVertexBuffers=null,this._currentIndexBuffer=null,this._colorWriteLocal=!0,this._forceEnableEffect=!1,this.isNDCHalfZRange=!0,this.hasOriginBottomLeft=!1,this._workingGlslangAndTintPromise=null,this._viewportsCurrent={x:0,y:0,w:0,h:0},this._scissorsCurrent={x:0,y:0,w:0,h:0},this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=-1,this._blendColorsCurrent=[null,null,null,null],this._performanceMonitor=new Bs,this._name="WebGPU",this._drawCalls=new on.A,t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=t.enableGPUDebugMarkers??!1,Z.V.Log(`Babylon.js v${Ot.$.Version} - ${this.description} engine`),navigator.gpu?(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 pc,this._shaderProcessorWGSL=new gc):Z.V.Error("WebGPU is not supported by your browser.")}prepareGlslangAndTintAsync(){return this._workingGlslangAndTintPromise||(this._workingGlslangAndTintPromise=new Promise((e=>{this._initGlslang(this._glslangOptions??this._options?.glslangOptions).then((t=>{this._glslang=t,this._tintWASM=new lu,this._tintWASM.initTwgsl(this._twgslOptions??this._options?.twgslOptions).then((()=>{this._glslangAndTintAreFullyLoaded=!0,e()}))}))}))),this._workingGlslangAndTintPromise}initAsync(e,t){return this.uniqueId=gu._InstanceId++,this._glslangOptions=e,this._twgslOptions=t,navigator.gpu.requestAdapter(this._options).then((e=>{if(e){this._adapter=e,this._adapterSupportedExtensions=[],this._adapter.features?.forEach((e=>this._adapterSupportedExtensions.push(e))),this._adapterSupportedLimits=this._adapter.limits,this._adapterInfo=this._adapter.info;const t=this._options.deviceDescriptor??{},i=t?.requiredFeatures??(this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0);if(i){const e=i,r=[];for(const t of e)-1!==this._adapterSupportedExtensions.indexOf(t)&&r.push(t);t.requiredFeatures=r}if(this._options.setMaximumLimits&&!t.requiredLimits){t.requiredLimits={};for(const e in this._adapterSupportedLimits)"minSubgroupSize"!==e&&"maxSubgroupSize"!==e&&(t.requiredLimits[e]=this._adapterSupportedLimits[e])}return t.label=`BabylonWebGPUDevice${this.uniqueId}`,this._adapter.requestDevice(t)}throw"Could not retrieve a WebGPU adapter (adapter is null)."})).then((e=>{this._device=e,this._deviceEnabledExtensions=[],this._device.features?.forEach((e=>this._deviceEnabledExtensions.push(e))),this._deviceLimits=e.limits;let t=-1;this._device.addEventListener("uncapturederror",(e=>{++t{this._isDisposed||(this._contextWasLost=!0,Z.V.Warn("WebGPU context lost. "+e),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost((async()=>{const e=this.snapshotRenderingMode,t=this.snapshotRendering,i=this.disableCacheSamplers,r=this.disableCacheRenderPipelines,s=this.disableCacheBindGroups,n=this.enableGPUTimingMeasurements;await this.initAsync(this._glslangOptions??this._options?.glslangOptions,this._twgslOptions??this._options?.twgslOptions),this.snapshotRenderingMode=e,this.snapshotRendering=t,this.disableCacheSamplers=i,this.disableCacheRenderPipelines=r,this.disableCacheBindGroups=s,this.enableGPUTimingMeasurements=n,this._currentRenderPass=null})))}))})).then((()=>{this._initializeLimits(),this._bufferManager=new Rc(this,this._device),this._textureHelper=new Ec(this,this._device,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new Dc(this._device),this._cacheBindGroups=new Kc(this._device,this._cacheSampler,this),this._timestampQuery=new nu(this,this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new au(this,this._device,this._bufferManager):void 0,this._bundleList=new ru(this._device),this._snapshotRendering=new hu(this,this._snapshotRenderingMode,this._bundleList),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),Eh.Uniform|Eh.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),Eh.Uniform|Eh.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&void 0===this._count&&(this._count=0,Z.V.Log(["%c frame #"+this._count+" - begin","background: #ffff00"])),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._emptyVertexBuffer=new st.R(this,[0],"",{stride:1,offset:0,size:1,label:"EmptyVertexBuffer"}),this._cacheRenderPipeline=new Vc(this._device,this._emptyVertexBuffer),this._depthCullingState=new zc(this._cacheRenderPipeline),this._stencilStateComposer=new Uc(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 jc(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((e=>{throw Z.V.Error("A fatal error occurred during WebGPU creation/initialization."),e}))}_initGlslang(e){return e=e||{},(e={...gu._GlslangDefaultOptions,...e}).glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?Ue.S0.LoadBabylonScriptAsync(e.jsPath).then((()=>self.glslang(Ue.S0.GetBabylonScriptURL(e.wasmPath)))):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:2*this._deviceLimits.maxSampledTexturesPerShaderStage,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxDrawBuffers:8,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf("texture-compression-astc")>=0||void 0,s3tc:this._deviceEnabledExtensions.indexOf("texture-compression-bc")>=0||void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf("texture-compression-etc2")>=0||void 0,bptc:this._deviceEnabledExtensions.indexOf("texture-compression-bc")>=0||void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:this._deviceEnabledExtensions.indexOf("rg11b10ufloat-renderable")>=0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf("float32-filterable")>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:"undefined"!=typeof BigUint64Array&&-1!==this._deviceEnabledExtensions.indexOf("timestamp-query")||void 0,supportOcclusionQuery:"undefined"!=typeof BigUint64Array,canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportIBLShadows:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!0,_collectUbosUpdatedInFrame:!1}}_initializeContextAndSwapChain(){if(!this._renderingCanvas)throw"The rendering canvas has not been set!";this._context=this._renderingCanvas.getContext("webgpu"),this._configureContext(),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new vc],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)]);let t;if(this._bufferManager.setSubData(this._ubInvertY,4,e),this._bufferManager.setSubData(this._ubDontInvertY,4,e),this._options.antialias){const e={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:"2d",format:this._options.swapChainFormat,usage:16};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(e),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:"2d",format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new hc.ov(0,0,0,1),loadOp:"clear",storeOp:"store"}]}else t=[{view:void 0,clearValue:new hc.ov(0,0,0,1),loadOp:"clear",storeOp:"store"}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?"depth24plus-stencil8":"depth32float",this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper);const i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:"2d",format:this._mainRenderPassWrapper.depthTextureFormat,usage:16};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);const r={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:"2d",format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:"clear",depthStoreOp:"store",stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?"clear":void 0,stencilStoreOp:this.isStencilEnable?"store":void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:t,depthStencilAttachment:r}}_sharedInit(e){super._sharedInit(e),$s(this,e,this._creationOptions)}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:17,alphaMode:this.premultipliedAlpha?"premultiplied":"opaque"})}resizeImageBitmap(e,t,i){return en(this,e,t,i)}_createImageBitmapFromSource(e,t){return Js(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&tn(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&rn()}enterPointerlock(){this._renderingCanvas&&sn(this._renderingCanvas)}exitPointerlock(){nn()}_rebuildBuffers(){super._rebuildBuffers();for(const e of this._storageBuffers)e.getBuffer().engineId!==this.uniqueId&&e._rebuild()}_restoreEngineAfterContextLost(e){Vc.ResetCache(),Kc.ResetCache();const t=e=>{for(const t of e){for(const e of t.meshes){const t=e.subMeshes;if(t)for(const e of t)e._drawWrappers=[]}for(const e of t.materials)e._materialContext?.reset()}};t(this.scenes),t(this._virtualScenes);const i=[];for(const e of this._uniformBuffers)e.name.indexOf("leftOver")<0&&i.push(e);this._uniformBuffers=i,super._restoreEngineAfterContextLost(e)}setSize(e,t,i=!1){return!!super.setSize(e,t,i)&&(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count=0,s=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,n=0===i?this._compileRawShaderToSpirV(e,"vertex"):e,o=0===i?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(n,o,i,r,s)}_compilePipelineStageDescriptor(e,t,i,r){this.onBeforeShaderCompilationObservable.notifyObservers(this);const s=e.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,n=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,o="#version 450\n",a=0===r?this._compileShaderToSpirV(e,"vertex",i,o):this._getWGSLShader(e,"vertex",i),l=0===r?this._compileShaderToSpirV(t,"fragment",i,o):this._getWGSLShader(t,"fragment",i),h=this._createPipelineStageDescriptor(a,l,r,s,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){const t=new $l(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new uc(e,this)}createMaterialContext(){return new Hc}createDrawContext(){return new Xc(this._bufferManager)}async _preparePipelineContext(e,t,i,r,s,n,o,a,l,h,c){const u=e,d=u.shaderProcessingContext.shaderLanguage;0!==d||this._glslangAndTintAreFullyLoaded||await this.prepareGlslangAndTintAsync(),this.dbgShowShaderCode&&(Z.V.Log(["defines",a]),Z.V.Log(t),Z.V.Log(i),Z.V.Log("***********************************************")),u.sources={fragment:i,vertex:t,rawVertex:s,rawFragment:n},u.stages=r?this._compileRawPipelineStageDescriptor(t,i,d):this._compilePipelineStageDescriptor(t,i,a,d),c()}getAttributes(e,t){const i=new Array(t.length),r=e;for(let e=0;e0,n.is3D=l>0,n._cachedWrapU=0,n._cachedWrapV=0,n._useSRGBBuffer=s.useSRGBBuffer,n.label=s.label,this._internalTexturesCache.push(n),i||this._textureHelper.createGPUTextureForInternalTexture(n,o,a,h||1,s.creationFlags),n}createTexture(e,t,i,r,s=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,f,p){return this._createTextureBase(e,t,i,r,s,n,o,((e,t,i,r,s,n,o,a)=>{const l=r;if(e.baseWidth=l.width,e.baseHeight=l.height,e.width=l.width,e.height=l.height,e.format=-1!==e.format?e.format:h??5,e.type=-1!==e.type?e.type:0,e._creationFlags=f??0,a(e.width,e.height,l,t,e,(()=>{})),e._hardwareTexture?.underlyingResource)n||o||this._generateMipmaps(e,this._uploadEncoder);else{const t=this._textureHelper.createGPUTextureForInternalTexture(e,l.width,l.height,void 0,f);xh.IsImageBitmap(l)&&(this._textureHelper.updateTexture(l,e,l.width,l.height,e.depth,t.format,0,0,s,!1,0,0),n||o||this._generateMipmaps(e,this._uploadEncoder))}i&&i.removePendingData(e),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}),(()=>!1),a,l,h,c,u,d,p)}wrapWebGPUTexture(e){const t=new vc(e),i=new Fs.h(this,0,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers}_unpackFlipY(e){}updateTextureSamplingMode(e,t,i=!1){i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,i=null,r=null){null!==t&&(e._cachedWrapU=t),null!==i&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==r&&(e._cachedWrapR=r)}updateTextureDimensions(e,t,i,r=1){if(!e._hardwareTexture)return;if(e.width===t&&e.height===i&&e.depth===r)return;const s=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,r,s)}_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 e=i+"Sampler";this._currentMaterialContext.setSampler(e,t)}}}createPrefilteredCubeTexture(e,t,i,r,s=null,n=null,o,a=null,l=!0){return this.createCubeTexture(e,t,null,!1,(e=>{if(!e)return void(s&&s(null));const t=e.texture;l?e.info.sphericalPolynomial&&(t._sphericalPolynomial=e.info.sphericalPolynomial):t._sphericalPolynomial=new Ks.Q,t._source=9,s&&s(t)}),n,o,a,l,i,r)}setTexture(e,t,i,r){this._setTexture(e,i,!1,!1,r,r)}setTextureArray(e,t,i,r){for(let e=0;e{const o=()=>{e.mapAsync(1,0,t).then((()=>{const r=e.getMappedRange(0,t);let n=i;if(void 0===n)n=new Uint8Array(t),n.set(new Uint8Array(r));else{const e=n.constructor;n=new e(n.buffer),n.set(new e(r))}e.unmap(),this._bufferManager.releaseBuffer(e),s(n)}),(e=>{this.isDisposed?s(new Uint8Array):n(e)}))};r?(this.flushFramebuffer(),o()):this.onEndFrameObservable.addOnce((()=>{o()}))}))}readFromStorageBuffer(e,t,i,r,s){i=i||e.capacity;const n=this._bufferManager.createRawBuffer(i,Eh.MapRead|Eh.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderEncoder.copyBufferToBuffer(e.underlyingResource,t??0,n,0,i),this._readFromGPUBuffer(n,i,r,s)}readFromMultipleStorageBuffers(e,t,i,r,s){i=i||e[0].capacity;const n=this._bufferManager.createRawBuffer(i*e.length,Eh.MapRead|Eh.CopyDst,void 0,"TempReadFromMultipleStorageBuffers");for(let r=0;r0;for(const t in e){const s=e[t],n=i[t],o=n.group,a=n.binding,l=s.type,h=s.object;let c=s.indexInGroupEntries,u=this._bindGroupEntries[o];switch(u||(u=this._bindGroupEntries[o]=[]),l){case 5:{const e=h;void 0!==c&&r?u[c].resource=this._cacheSampler.getSampler(e):(s.indexInGroupEntries=u.length,u.push({binding:a,resource:this._cacheSampler.getSampler(e)}));break}case 0:case 4:{const e=h,t=e._texture._hardwareTexture;void 0!==c&&r?(0===l&&(u[c++].resource=this._cacheSampler.getSampler(e._texture)),u[c].resource=t.view):(s.indexInGroupEntries=u.length,0===l&&u.push({binding:a-1,resource:this._cacheSampler.getSampler(e._texture)}),u.push({binding:a,resource:t.view}));break}case 1:{const e=h,t=e._texture._hardwareTexture;8&t.textureAdditionalUsages||Z.V.Error(`computeDispatch: The texture (name=${e.name}, uniqueId=${e.uniqueId}) is not a storage texture!`,50),void 0!==c&&r?u[c].resource=t.viewForWriting:(s.indexInGroupEntries=u.length,u.push({binding:a,resource:t.viewForWriting}));break}case 6:{const e=h.underlyingResource;void 0!==c&&r?u[c].resource=this._device.importExternalTexture({source:e}):(s.indexInGroupEntries=u.length,u.push({binding:a,resource:this._device.importExternalTexture({source:e})}));break}case 2:case 3:case 7:{const e=7===l?h:h.getBuffer(),t=e.underlyingResource;void 0!==c&&r?(u[c].resource.buffer=t,u[c].resource.size=e.capacity):(s.indexInGroupEntries=u.length,u.push({binding:a,resource:{buffer:t,offset:0,size:e.capacity}}));break}}}for(let e=0;e0&&d.dispatchWorkgroups(r,s,n),d.end(),h&&(this._timestampQuery.endPass(this._timestampIndex,h),this._timestampIndex+=2)},gu.prototype.releaseComputeEffects=function(){for(const e in this._compiledComputeEffects){const t=this._compiledComputeEffects[e].getPipelineContext();this._deleteComputePipelineContext(t)}this._compiledComputeEffects={}},gu.prototype._prepareComputePipelineContext=function(e,t,i,r,s){const n=e;this.dbgShowShaderCode&&(Z.V.Log(r),Z.V.Log(t)),n.sources={compute:t,rawCompute:i},n.stage=this._createComputePipelineStageDescriptor(t,r,s)},gu.prototype._releaseComputeEffect=function(e){this._compiledComputeEffects[e._key]&&(delete this._compiledComputeEffects[e._key],this._deleteComputePipelineContext(e.getPipelineContext()))},gu.prototype._rebuildComputeEffects=function(){for(const e in this._compiledComputeEffects){const t=this._compiledComputeEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}},gu.prototype._executeWhenComputeStateIsCompiled=function(e,t){e.stage.module.getCompilationInfo().then((e=>{const i={numErrors:0,messages:[]};for(const t of e.messages)"error"===t.type&&i.numErrors++,i.messages.push({type:t.type,text:t.message,line:t.lineNum,column:t.linePos,length:t.length,offset:t.offset});t(i)}))},gu.prototype._deleteComputePipelineContext=function(e){e&&e.dispose()},gu.prototype._createComputePipelineStageDescriptor=function(e,t,i){return t=t?"//"+t.split("\n").join("\n//")+"\n":"",{module:this._device.createShaderModule({code:t+e}),entryPoint:i}},gu.prototype._debugPushGroup=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?(1===t&&(this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._endCurrentRenderPass()),this._renderEncoder.pushDebugGroup(e)):this._currentRenderPass?(this._currentRenderPass.pushDebugGroup(e),this._debugStackRenderPass.push(e)):this._pendingDebugCommands.push(["push",e,t]))},gu.prototype._debugPopGroup=function(e){this._options.enableGPUDebugMarkers&&(0===e||1===e?(1===e&&(this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._endCurrentRenderPass()),this._renderEncoder.popDebugGroup()):this._currentRenderPass?(this._currentRenderPass.popDebugGroup(),this._debugStackRenderPass.pop()):this._pendingDebugCommands.push(["pop",null,e]))},gu.prototype._debugInsertMarker=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?(1===t&&(this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._endCurrentRenderPass()),this._renderEncoder.insertDebugMarker(e)):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(e):this._pendingDebugCommands.push(["insert",e,t]))},gu.prototype._debugFlushPendingCommands=function(){if(0!==this._debugStackRenderPass.length){const e=this._debugStackRenderPass.slice();this._debugStackRenderPass.length=0;for(let t=0;t{this._textureHelper.updateTexture(t,e,e.width,e.height,e.depth,r.format,0,0,!i,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e),e.isReady=!0})).catch((()=>{e.isReady=!0}))};var Su=i(42167),Tu=i(16964);class Cu{static async CreateAsync(e,t){return await gu.IsSupportedAsync?gu.CreateAsync(e,t):an.IsSupported?new an(e,void 0,t):new wl(t)}}class yu{}yu.COPY=1,yu.CUT=2,yu.PASTE=3;class Eu{constructor(e,t){this.type=e,this.event=t}static GetTypeFromCharacter(e){switch(e){case 67:return yu.COPY;case 86:return yu.PASTE;case 88:return yu.CUT;default:return-1}}}var Pu,Au=i(71627);!function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(Pu||(Pu={}));class Ru{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=(0,Au.z)(),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=new(Ue.S0.Instantiate(e.className))(e.name,e._connectionType,t);return i.deserialize(e),i}}class Iu{constructor(e){this.value=this._toInt(e)}_toInt(e){return 0|e}add(e){return new Iu(this.value+e.value)}subtract(e){return new Iu(this.value-e.value)}multiply(e){return new Iu(Math.imul(this.value,e.value))}divide(e){return new Iu(this.value/e.value)}getClassName(){return Iu.ClassName}equals(e){return this.value===e.value}static Parse(e){return new Iu(e.value)}}Iu.ClassName="FlowGraphInteger",(0,X.Y5)("FlowGraphInteger",Iu);class Mu{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new Mu(e.typeName,e.defaultValue)}}const Ou=new Mu("any",void 0),Du=new Mu("string",""),wu=new Mu("number",0),Nu=new Mu("boolean",!1),Fu=new Mu("Vector2",W.I9.Zero()),Lu=new Mu("Vector3",W.Pq.Zero()),Bu=new Mu("Vector4",W.IU.Zero()),Vu=new Mu("Matrix",W.uq.Identity()),ku=new Mu("Color3",H.v9.Black()),Uu=new Mu("Color4",new H.ov(0,0,0,0)),Gu=new Mu("Quaternion",W.PT.Identity()),zu=new Mu("FlowGraphInteger",new Iu(0));function Wu(e){switch(typeof e){case"string":return Du;case"number":return wu;case"boolean":return Nu;case"object":return e instanceof W.I9?Fu:e instanceof W.Pq?Lu:e instanceof W.IU?Bu:e instanceof H.v9?ku:e instanceof H.ov?Uu:e instanceof W.PT?Gu:e instanceof Iu?zu:Ou;default:return Ou}}class Hu extends Ru{constructor(e,t,i,r){super(e,t,i),this.richType=r}_isSingularConnection(){return 0===this.connectionType}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 1===this.connectionType?(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=Ru.Parse(e,t);return i.richType=Mu.Parse(e.richType),i}}function Xu(e){return"Mesh"===e||"AbstractMesh"===e||"GroundMesh"===e||"InstanceMesh"===e||"LinesMesh"===e||"GoldbergMesh"===e||"GreasedLineMesh"===e||"TrailMesh"===e}function qu(e){return"Vector2"===e||"Vector3"===e||"Vector4"===e||"Quaternion"===e||"Color3"===e||"Color4"===e}function Yu(e,t,i){const r=t?.getClassName?.()??"";Xu(r)?i[e]={name:t.name,className:r}:qu(r)?i[e]={value:t.asArray(),className:r}:i[e]=t}function Ku(e,t,i){const r=t[e];let s;const n=r?.className;return s=Xu(n)?i.getMeshByName(r.name):qu(n)?function(e,t){if("Vector2"===e)return W.I9.FromArray(t);if("Vector3"===e)return W.Pq.FromArray(t);if("Vector4"===e)return W.IU.FromArray(t);if("Quaternion"===e)return W.PT.FromArray(t);if("Color3"===e)return new H.v9(t[0],t[1],t[2]);if("Color4"===e)return new H.ov(t[0],t[1],t[2],t[3]);throw new Error(`Unknown vector class name ${e}`)}(n,r.value):"Matrix"===n?W.uq.FromArray(r.value):n===Iu.ClassName?Iu.Parse(r):r&&void 0!==r.value?r.value:r,s}(0,X.Y5)("FGDataConnection",Hu);class ju{constructor(e){this.config=e,this.uniqueId=(0,Au.z)(),this.name=this.config?.name??this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){const i=new Hu(e,0,this,t);return this.dataInputs.push(i),i}registerDataOutput(e,t){const i=new Hu(e,1,this,t);return this.dataOutputs.push(i),i}getDataInput(e){return this.dataInputs.find((t=>t.name===e))}getDataOutput(e){return this.dataOutputs.find((t=>t.name===e))}serialize(e={},t=Yu){e.uniqueId=this.uniqueId,e.config={},this.config&&(e.config.name=this.config.name),e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName();for(const t of this.dataInputs){const i={};t.serialize(i),e.dataInputs.push(i)}for(const t of this.dataOutputs){const i={};t.serialize(i),e.dataOutputs.push(i)}}getClassName(){return"FGBlock"}static Parse(e,t){const i=Ue.S0.Instantiate(e.className),r={},s=t.valueParseFunction??Ku;if(e.config)for(const i in e.config)r[i]=s(i,e.config,t.scene);var n;("FGSetPropertyBlock"===(n=e.className)||"FGGetPropertyBlock"===n||"FGPlayAnimationBlock"===n||"FGMeshPickEventBlock"===n)&&(r.pathConverter=t.pathConverter);const o=new i(r);o.uniqueId=e.uniqueId;for(let t=0;tt.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{t.type===yi.Zp.POINTERPICK&&t.pickInfo?.pickedMesh&&(t.pickInfo?.pickedMesh===i||td(t.pickInfo?.pickedMesh,i))&&this._execute(e)}));const r=i.onDisposeObservable.add((()=>this._onDispose));e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",r)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"mesh"),i=e._getExecutionVariable(this,"meshPickObserver"),r=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(r),e._deleteExecutionVariable(this,"mesh"),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return id.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path}}var rd;id.ClassName="FGMeshPickEventBlock",(0,X.Y5)(id.ClassName,id),function(e){e[e.Stopped=0]="Stopped",e[e.Started=1]="Started"}(rd||(rd={}));class sd{constructor(e){this._eventBlocks=[],this._executionContexts=[],this.state=0,this._scene=e.scene,this._coordinator=e.coordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add((()=>this.dispose()))}createContext(){const e=new ed({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(1!==this.state){this.state=1,0===this._executionContexts.length&&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()===id.ClassName){const i=t._getReferencedMesh();let r=0;for(;r0;){const r=t.pop();e(r);for(const e of r.dataInputs)for(const r of e._connectedPoint)i.has(r._ownerBlock.uniqueId)||(t.push(r._ownerBlock),i.add(r._ownerBlock.uniqueId));if(r instanceof Qu)for(const e of r.signalOutputs)for(const r of e._connectedPoint)i.has(r._ownerBlock.uniqueId)||(t.push(r._ownerBlock),i.add(r._ownerBlock.uniqueId))}}serialize(e={},t){e.allBlocks=[],this.visitAllBlocks((t=>{const i={};t.serialize(i),e.allBlocks.push(i)})),e.executionContexts=[];for(const i of this._executionContexts){const r={};i.serialize(r,t),e.executionContexts.push(r)}}static GetDataOutConnectionByUniqueId(e,t){for(const i of e)for(const e of i.dataOutputs)if(e.uniqueId===t)return e;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 Qu)for(const e of i.signalInputs)if(e.uniqueId===t)return e;throw new Error("Could not find signal in connection with unique id "+t)}static Parse(e,t){const i=t.coordinator.createGraph(),r=[],s=t.valueParseFunction??Ku;for(const n of e.allBlocks){const e=ju.Parse(n,{scene:t.coordinator.config.scene,pathConverter:t.pathConverter,valueParseFunction:s});r.push(e),e instanceof Ju&&i.addEventBlock(e)}for(const e of r){for(const t of e.dataInputs)for(const e of t.connectedPointIds){const i=sd.GetDataOutConnectionByUniqueId(r,e);t.connectTo(i)}if(e instanceof Qu)for(const t of e.signalOutputs)for(const e of t.connectedPointIds){const i=sd.GetSignalInConnectionByUniqueId(r,e);t.connectTo(i)}}for(const t of e.executionContexts)ed.Parse(t,{graph:i,valueParseFunction:s});return i}}class nd{constructor(e){this.config=e,this._flowGraphs=[],this._customEventsMap=new Map,this.config.scene.onDisposeObservable.add((()=>{this.dispose()})),(nd.SceneCoordinators.get(this.config.scene)??[]).push(this)}createGraph(){const e=new sd({scene:this.config.scene,coordinator:this});return this._flowGraphs.push(e),e}removeGraph(e){const t=this._flowGraphs.indexOf(e);-1!==t&&(e.dispose(),this._flowGraphs.splice(t,1))}start(){this._flowGraphs.forEach((e=>e.start()))}dispose(){this._flowGraphs.forEach((e=>e.dispose())),this._flowGraphs.length=0;const e=nd.SceneCoordinators.get(this.config.scene)??[],t=e.indexOf(this);-1!==t&&e.splice(t,1)}serialize(e,t){e._flowGraphs=[],this._flowGraphs.forEach((i=>{const r={};i.serialize(r,t),e._flowGraphs.push(r)}))}static Parse(e,t){const i=t.valueParseFunction??Ku,r=new nd({scene:t.scene});return e._flowGraphs?.forEach((e=>{sd.Parse(e,{coordinator:r,valueParseFunction:i,pathConverter:t.pathConverter})})),r}get flowGraphs(){return this._flowGraphs}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new z.cP,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){const i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}}nd.SceneCoordinators=new Map;class od{constructor(e){this._context=e,this._context.onNodeExecutedObservable.add((e=>{Ue.S0.Log(`Node executed: ${e.getClassName()}`)}))}}class ad extends Qu{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class ld extends ad{constructor(e){super(e),this.message=this.registerDataInput("message",Ou)}_execute(e){const t=this.message.getValue(e);Z.V.Log(t),this.out._activateSignal(e)}getClassName(){return ld.ClassName}}ld.ClassName="FGConsoleLogBlock",(0,X.Y5)(ld.ClassName,ld);class hd extends ad{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,Ou)}_execute(e){const t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)}getClassName(){return hd.ClassName}}hd.ClassName="FGSetVariableBlock",(0,X.Y5)(hd.ClassName,hd);const cd=new RegExp(/\{(\w+)\}/g);class ud{constructor(e,t){this.path=e,this.ownerBlock=t,this.templatedInputs=[];let i=cd.exec(e);for(;i;){const[,r]=i;this.templatedInputs.push(t.registerDataInput(r,zu)),i=cd.exec(e)}}getAccessor(e,t){let i=this.path;for(const e of this.templatedInputs){const r=e.getValue(t).value;i=i.replace(`{${e.name}}`,r.toString())}return e.convert(i)}}class dd extends ad{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",Ou),this.templateComponent=new ud(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 dd.ClassName}}dd.ClassName="FGSetPropertyBlock",(0,X.Y5)("FGSetPropertyBlock",dd);class fd extends ad{constructor(e){super(e),this.config=e;for(let e=0;et.getValue(e)));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)}getClassName(){return fd.ClassName}}fd.ClassName="FGSendCustomEventBlock",(0,X.Y5)("FGSendCustomEventBlock",fd);class pd extends Qu{constructor(e){super(e),this.condition=this.registerDataInput("condition",Nu),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"}}(0,X.Y5)("FGBranchBlock",pd);class _d extends ad{constructor(e={startIndex:new Iu(0)}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",zu),this.value=this.registerDataOutput("value",zu)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{const t=this.value.getValue(e);t.valuer)this.timeRemaining.setValue(0,e),this.out._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",s);else{const t=r-(s-i);this.timeRemaining.setValue(t,e)}}getClassName(){return"FGThrottleBlock"}}var vd;function xd(e){let t=0;const i=Date.now();e.observableParameters=e.observableParameters??{};const r=e.contextObservable.add((s=>{const n=Date.now();t=n-i;const o={startTime:i,currentTime:n,deltaTime:t,completeRate:t/e.timeout,payload:s};e.onTick&&e.onTick(o),e.breakCondition&&e.breakCondition()&&(e.contextObservable.remove(r),e.onAborted&&e.onAborted(o)),t>=e.timeout&&(e.contextObservable.remove(r),e.onEnded&&e.onEnded(o))}),e.observableParameters.mask,e.observableParameters.insertFirst,e.observableParameters.scope);return r}(0,X.Y5)("FGThrottleBlock",gd),function(e){e[e.INIT=0]="INIT",e[e.STARTED=1]="STARTED",e[e.ENDED=2]="ENDED"}(vd||(vd={}));class bd{constructor(e){this.onEachCountObservable=new z.cP,this.onTimerAbortedObservable=new z.cP,this.onTimerEndedObservable=new z.cP,this.onStateChangedObservable=new z.cP,this._observer=null,this._breakOnNextTick=!1,this._tick=e=>{const t=Date.now();this._timer=t-this._startTime;const i={startTime:this._startTime,currentTime:t,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:e},r=this._breakOnNextTick||this._breakCondition(i);r||this._timer>=this._timeToEnd?this._stop(i,r):this.onEachCountObservable.notifyObservers(i)},this._setState(0),this._contextObservable=e.contextObservable,this._observableParameters=e.observableParameters??{},this._breakCondition=e.breakCondition??(()=>!1),this._timeToEnd=e.timeout,e.onEnded&&this.onTimerEndedObservable.add(e.onEnded),e.onTick&&this.onEachCountObservable.add(e.onTick),e.onAborted&&this.onTimerAbortedObservable.add(e.onAborted)}set breakCondition(e){this._breakCondition=e}clearObservables(){this.onEachCountObservable.clear(),this.onTimerAbortedObservable.clear(),this.onTimerEndedObservable.clear(),this.onStateChangedObservable.clear()}start(e=this._timeToEnd){if(1===this._state)throw new Error("Timer already started. Please stop it before starting again");this._timeToEnd=e,this._startTime=Date.now(),this._timer=0,this._observer=this._contextObservable.add(this._tick,this._observableParameters.mask,this._observableParameters.insertFirst,this._observableParameters.scope),this._setState(1)}stop(){1===this._state&&(this._breakOnNextTick=!0)}dispose(){this._observer&&this._contextObservable.remove(this._observer),this.clearObservables()}_setState(e){this._state=e,this.onStateChangedObservable.notifyObservers(this._state)}_stop(e,t=!1){this._contextObservable.remove(this._observer),this._setState(2),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}}class Sd extends Zu{constructor(e){super(e),this.timeout=this.registerDataInput("timeout",wu)}_preparePendingTasks(e){const t=this.timeout.getValue(e);if(void 0!==t&&t>=0){const i=e._getExecutionVariable(this,"runningTimers")||[],r=e.configuration.scene,s=new bd({timeout:t,contextObservable:r.onBeforeRenderObservable,onEnded:()=>this._onEnded(s,e)});s.start(),i.push(s),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onEnded(e,t){const i=t._getExecutionVariable(this,"runningTimers")||[],r=i.indexOf(e);-1!==r?i.splice(r,1):Ue.S0.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 e of t)e.dispose();e._deleteExecutionVariable(this,"runningTimers")}getClassName(){return Sd.ClassName}}Sd.ClassName="FGTimerBlock",(0,X.Y5)("FGTimerBlock",Sd);class Td extends Qu{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this.registerDataOutput("currentIndex",wu),this.config.startIndex=void 0!==this.config.startIndex?this.config.startIndex:0,this.config.startIndex=Math.max(0,Math.min(this.config.startIndex,this.config.numberOutputFlows-1)),this.outFlows=[];for(let e=0;e=this.config.numberOutputFlows&&this.config.loop)s=0;else if(s>=this.config.numberOutputFlows&&!this.config.loop)return;if(r=r.filter((e=>e!==s)),0===r.length)for(let e=0;e=0&&(i[e+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every((e=>e))){this.out._activateSignal(e);for(let e=0;e=i&&(this.out._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}}(0,X.Y5)("FGDebounceBlock",Ad);class Rd extends Qu{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this.registerDataOutput("isOn",Nu)}_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"}}(0,X.Y5)("FGFlipFlopBlock",Rd);class Id extends Qu{constructor(e){super(e),this.config=e,this.outFlows=[];for(let e=0;ethis._onAnimationEnd(t,e)));this.runningAnimatable.setValue(t,e),n.push(t)}e._setExecutionVariable(this,"runningAnimatables",n)}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onAnimationEnd(e,t){const i=t._getExecutionVariable(this,"runningAnimatables")??[],r=i.indexOf(e);-1!==r&&i.splice(r,1),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningAnimatables")??[];for(const e of t)e.stop();e._deleteExecutionVariable(this,"runningAnimatables")}getClassName(){return Md.ClassName}serialize(e={}){super.serialize(e),e.config.targetPath=this.config.targetPath,e.config.animationPath=this.config.animationPath}}Md.ClassName="FGPlayAnimationBlock",(0,X.Y5)(Md.ClassName,Md);class Od extends ad{constructor(e){super(e),this.animationToStop=this.registerDataInput("animationToStop",Ou)}_execute(e){this.animationToStop.getValue(e).stop(),this.out._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}}(0,X.Y5)("FGStopAnimationBlock",Od);class Dd extends ad{constructor(e){super(e),this.animationToPause=this.registerDataInput("animationToPause",Ou)}_execute(e){this.animationToPause.getValue(e).pause(),this.out._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}}(0,X.Y5)("FGPauseAnimationBlock",Dd);class wd extends ju{constructor(e){super(e),this.condition=this.registerDataInput("condition",Nu),this.trueValue=this.registerDataInput("trueValue",Ou),this.falseValue=this.registerDataInput("falseValue",Ou),this.output=this.registerDataOutput("output",Ou)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}}(0,X.Y5)("FGConditionalDataBlock",wd);class Nd extends ju{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,Ou)}_updateOutputs(e){const t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return Nd.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}Nd.ClassName="FGGetVariableBlock",(0,X.Y5)(Nd.ClassName,Nd);class Fd extends ju{constructor(e){super(e),this.sourceSystem=this.registerDataInput("sourceSystem",Ou),this.destinationSystem=this.registerDataInput("destinationSystem",Ou),this.inputCoordinates=this.registerDataInput("inputCoordinates",Lu),this.outputCoordinates=this.registerDataOutput("outputCoordinates",Lu)}_updateOutputs(e){const t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),r=this.inputCoordinates.getValue(e),s=t.getWorldMatrix(),n=i.getWorldMatrix(),o=W.AA.Matrix[0].copyFrom(n);o.invert();const a=W.AA.Matrix[1];o.multiplyToRef(s,a);const l=this.outputCoordinates.getValue(e);W.Pq.TransformCoordinatesToRef(r,a,l)}getClassName(){return"FGCoordinateTransformBlock"}}(0,X.Y5)("FGCoordinateTransformBlock",Fd);class Ld extends ju{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput("output",Wu(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}serialize(e={},t=Yu){super.serialize(e),t("value",this.config.value,e.config)}}(0,X.Y5)("FGConstantBlock",Ld);class Bd extends ju{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",Ou),this.templateComponent=new ud(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 Bd.ClassName}serialize(e={}){super.serialize(e),e.config.path=this.config.path}}Bd.ClassName="FGGetPropertyBlock",(0,X.Y5)(Bd.ClassName,Bd);const Vd="cachedOperationValue",kd="cachedExecutionId";class Ud extends ju{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){const t=e._getExecutionVariable(this,kd),i=e._getExecutionVariable(this,Vd);if(void 0!==i&&t===e.executionId)this.value.setValue(i,e);else{const t=this._doOperation(e);e._setExecutionVariable(this,Vd,t),e._setExecutionVariable(this,kd,e.executionId),this.value.setValue(t,e)}}}class Gd extends Ud{constructor(e,t,i,r,s,n){super(i,n),this._operation=r,this._className=s,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e))}getClassName(){return this._className}}class zd extends Ud{constructor(e,t,i,r,s){super(t,s),this._operation=i,this._className=r,this.a=this.registerDataInput("a",e)}_doOperation(e){return this._operation(this.a.getValue(e))}getClassName(){return this._className}}const Wd="FGLogic",Hd="AndBlock",Xd="OrBlock",qd="NotBlock";class Yd extends Gd{constructor(e){super(Nu,Nu,Nu,((e,t)=>e&&t),`${Wd}${Hd}`,e)}}(0,X.Y5)(`${Wd}${Hd}`,Yd);class Kd extends Gd{constructor(e){super(Nu,Nu,Nu,((e,t)=>e||t),`${Wd}${Xd}`,e)}}(0,X.Y5)(`${Wd}${Xd}`,Kd);class jd extends zd{constructor(e){super(Nu,Nu,(e=>!e),`${Wd}${qd}`,e)}}(0,X.Y5)(`${Wd}${qd}`,jd);class $d extends Ud{constructor(e,t,i,r){super(e,r),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}}class Qd extends Ud{constructor(e,t,i,r,s,n,o){super(r,o),this._operation=s,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 Zd(e){return e.getClassName?e.getClassName():""}function Jd(e,t){return"Vector2"===e&&"Vector2"===t||"Vector3"===e&&"Vector3"===t||"Vector4"===e&&"Vector4"===t}function ef(e,t){return"Matrix"===e&&"Matrix"===t}function tf(e,t){return"FlowGraphInteger"===e&&"FlowGraphInteger"===t}class rf extends Gd{constructor(e){super(Ou,Ou,Ou,((e,t)=>this._polymorphicAdd(e,t)),rf.ClassName,e)}_polymorphicAdd(e,t){const i=Zd(e),r=Zd(t);return Jd(i,r)||ef(i,r)||tf(i,r)?e.add(t):e+t}}rf.ClassName="FGAddBlock",(0,X.Y5)(rf.ClassName,rf);class sf extends Gd{constructor(e){super(Ou,Ou,Ou,((e,t)=>this._polymorphicAdd(e,t)),sf.ClassName,e)}_polymorphicAdd(e,t){const i=Zd(e),r=Zd(t);return Jd(i,r)||tf(i,r)?e.subtract(t):ef(i,r)?e.add(t.scale(-1)):e-t}}sf.ClassName="FGSubBlock",(0,X.Y5)(sf.ClassName,sf);class nf extends Gd{constructor(e){super(Ou,Ou,Ou,((e,t)=>this._polymorphicMultiply(e,t)),nf.ClassName,e)}_polymorphicMultiply(e,t){const i=Zd(e),r=Zd(t);return Jd(i,r)||tf(i,r)?e.multiply(t):ef(i,r)?W.uq.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}}nf.ClassName="FGMultiplyBlock",(0,X.Y5)(nf.ClassName,nf);class of extends Gd{constructor(e){super(Ou,Ou,Ou,((e,t)=>this._polymorphicDivide(e,t)),of.ClassName,e)}_polymorphicDivide(e,t){const i=Zd(e),r=Zd(t);return Jd(i,r)||tf(i,r)?e.divide(t):ef(i,r)?W.uq.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}}of.ClassName="FGDivideBlock",(0,X.Y5)(of.ClassName,of);class af extends $d{constructor(e){super(wu,(()=>Math.random()),af.ClassName,e)}}af.ClassName="FGRandomBlock",(0,X.Y5)(af.ClassName,af);class lf extends Gd{constructor(e){super(Ou,Ou,wu,((e,t)=>this._polymorphicDot(e,t)),lf.ClassName,e)}_polymorphicDot(e,t){switch(Zd(e)){case"Vector2":return W.I9.Dot(e,t);case"Vector3":return W.Pq.Dot(e,t);case"Vector4":return W.IU.Dot(e,t);default:throw new Error(`Cannot get dot product of ${e} and ${t}`)}}}lf.ClassName="FGDotBlock",(0,X.Y5)(lf.ClassName,lf);class hf extends $d{constructor(e){super(wu,(()=>Math.E),hf.ClassName,e)}}hf.ClassName="FGEBlock",(0,X.Y5)(hf.ClassName,hf);class cf extends $d{constructor(e){super(wu,(()=>Math.PI),cf.ClassName,e)}}cf.ClassName="FGPIBlock",(0,X.Y5)(cf.ClassName,cf);class uf extends $d{constructor(e){super(wu,(()=>Number.POSITIVE_INFINITY),uf.ClassName,e)}}uf.ClassName="FGInfBlock",(0,X.Y5)(uf.ClassName,uf);class df extends $d{constructor(e){super(wu,(()=>Number.NaN),df.ClassName,e)}}function ff(e,t){switch(Zd(e)){case"FlowGraphInteger":return new Iu(t(e.value));case"Vector2":return new W.I9(t(e.x),t(e.y));case"Vector3":return new W.Pq(t(e.x),t(e.y),t(e.z));case"Vector4":return new W.IU(t(e.x),t(e.y),t(e.z),t(e.w));case"Matrix":return W.uq.FromValues(t(e.m[0]),t(e.m[4]),t(e.m[8]),t(e.m[12]),t(e.m[1]),t(e.m[5]),t(e.m[9]),t(e.m[13]),t(e.m[2]),t(e.m[6]),t(e.m[10]),t(e.m[14]),t(e.m[3]),t(e.m[7]),t(e.m[11]),t(e.m[15]));default:return t(e)}}df.ClassName="FGNaNBlock",(0,X.Y5)(df.ClassName,df);class pf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicAbs(e)),pf.ClassName,e)}_polymorphicAbs(e){return ff(e,Math.abs)}}pf.ClassName="FGAbsBlock",(0,X.Y5)(pf.ClassName,pf);class _f extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicSign(e)),_f.ClassName,e)}_polymorphicSign(e){return ff(e,Math.sign)}}_f.ClassName="FGSignBlock",(0,X.Y5)(_f.ClassName,_f);class mf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicTrunc(e)),mf.ClassName,e)}_polymorphicTrunc(e){return ff(e,Math.trunc)}}mf.ClassName="FGTruncBlock",(0,X.Y5)(mf.ClassName,mf);class gf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicFloor(e)),gf.ClassName,e)}_polymorphicFloor(e){return ff(e,Math.floor)}}gf.ClassName="FGFloorBlock",(0,X.Y5)(gf.ClassName,gf);class vf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicCeiling(e)),vf.ClassName,e)}_polymorphicCeiling(e){return ff(e,Math.ceil)}}vf.ClassName="FGCeilBlock",(0,X.Y5)(vf.ClassName,vf);class xf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicFract(e)),xf.ClassName,e)}_polymorphicFract(e){return ff(e,(e=>e-Math.floor(e)))}}xf.ClassName="FGFractBlock",(0,X.Y5)(xf.ClassName,xf);class bf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicNeg(e)),bf.ClassName,e)}_polymorphicNeg(e){return ff(e,(e=>-e))}}function Sf(e,t,i){switch(Zd(e)){case"FlowGraphInteger":return new Iu(i(e.value,t.value));case"Vector2":return new W.I9(i(e.x,t.x),i(e.y,t.y));case"Vector3":return new W.Pq(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z));case"Vector4":return new W.IU(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z),i(e.w,t.w));case"Matrix":return W.uq.FromValues(i(e.m[0],t.m[0]),i(e.m[4],t.m[4]),i(e.m[8],t.m[8]),i(e.m[12],t.m[12]),i(e.m[1],t.m[1]),i(e.m[5],t.m[5]),i(e.m[9],t.m[9]),i(e.m[13],t.m[13]),i(e.m[2],t.m[2]),i(e.m[6],t.m[6]),i(e.m[10],t.m[10]),i(e.m[14],t.m[14]),i(e.m[3],t.m[3]),i(e.m[7],t.m[7]),i(e.m[11],t.m[11]),i(e.m[15],t.m[15]));default:return i(e,t)}}bf.ClassName="FGNegBlock",(0,X.Y5)(bf.ClassName,bf);class Tf extends Gd{constructor(e){super(Ou,Ou,Ou,((e,t)=>this._polymorphicRemainder(e,t)),Tf.ClassName,e)}_polymorphicRemainder(e,t){return Sf(e,t,((e,t)=>e%t))}}Tf.ClassName="FGRemainderBlock",(0,X.Y5)(Tf.ClassName,Tf);class Cf extends Gd{constructor(e){super(Ou,Ou,Ou,((e,t)=>this._polymorphicMin(e,t)),Cf.ClassName,e)}_polymorphicMin(e,t){return Sf(e,t,Math.min)}}Cf.ClassName="FGMinBlock",(0,X.Y5)(Cf.ClassName,Cf);class yf extends Gd{constructor(e){super(Ou,Ou,Ou,((e,t)=>this._polymorphicMax(e,t)),yf.ClassName,e)}_polymorphicMax(e,t){return Sf(e,t,Math.max)}}function Ef(e,t,i){return Math.min(Math.max(e,Math.min(t,i)),Math.max(t,i))}function Pf(e,t,i,r){switch(Zd(e)){case"FlowGraphInteger":return new Iu(r(e.value,t.value,i.value));case"Vector2":return new W.I9(r(e.x,t.x,i.x),r(e.y,t.y,i.y));case"Vector3":return new W.Pq(r(e.x,t.x,i.x),r(e.y,t.y,i.y),r(e.z,t.z,i.z));case"Vector4":return new W.IU(r(e.x,t.x,i.x),r(e.y,t.y,i.y),r(e.z,t.z,i.z),r(e.w,t.w,i.w));case"Matrix":return W.uq.FromValues(r(e.m[0],t.m[0],i.m[0]),r(e.m[4],t.m[4],i.m[4]),r(e.m[8],t.m[8],i.m[8]),r(e.m[12],t.m[12],i.m[12]),r(e.m[1],t.m[1],i.m[1]),r(e.m[5],t.m[5],i.m[5]),r(e.m[9],t.m[9],i.m[9]),r(e.m[13],t.m[13],i.m[13]),r(e.m[2],t.m[2],i.m[2]),r(e.m[6],t.m[6],i.m[6]),r(e.m[10],t.m[10],i.m[10]),r(e.m[14],t.m[14],i.m[14]),r(e.m[3],t.m[3],i.m[3]),r(e.m[7],t.m[7],i.m[7]),r(e.m[11],t.m[11],i.m[11]),r(e.m[15],t.m[15],i.m[15]));default:return r(e,t,i)}}yf.ClassName="FGMaxBlock",(0,X.Y5)(yf.ClassName,yf);class Af extends Qd{constructor(e){super(Ou,Ou,Ou,Ou,((e,t,i)=>this._polymorphicClamp(e,t,i)),Af.ClassName,e)}_polymorphicClamp(e,t,i){return Pf(e,t,i,Ef)}}function Rf(e){return Math.min(Math.max(e,0),1)}Af.ClassName="FGClampBlock",(0,X.Y5)(Af.ClassName,Af);class If extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicSaturate(e)),If.ClassName,e)}_polymorphicSaturate(e){return ff(e,Rf)}}If.ClassName="FGSaturateBlock",(0,X.Y5)(If.ClassName,If);class Mf extends Qd{constructor(e){super(Ou,Ou,Ou,Ou,((e,t,i)=>this._polymorphicInterpolate(e,t,i)),Mf.ClassName,e)}_interpolate(e,t,i){return(1-i)*e+i*t}_polymorphicInterpolate(e,t,i){return Pf(e,t,i,this._interpolate)}}Mf.ClassName="FGInterpolateBlock",(0,X.Y5)(Mf.ClassName,Mf);class Of extends Gd{constructor(e){super(Ou,Ou,Nu,((e,t)=>this._polymorphicEq(e,t)),Of.ClassName,e)}_polymorphicEq(e,t){const i=Zd(e),r=Zd(t);return Jd(i,r)||ef(i,r)||tf(i,r)?e.equals(t):e===t}}function Df(e,t,i){const r=Zd(e);if(r===Zd(t)){if(""===r)return i(e,t);if("FlowGraphInteger"===r)return i(e.value,t.value);throw new Error(`Cannot compare ${e} and ${t}`)}throw new Error(`${e} and ${t} are of different types.`)}Of.ClassName="FGEqBlock",(0,X.Y5)(Of.ClassName,Of);class wf extends Gd{constructor(e){super(Ou,Ou,Nu,((e,t)=>this._polymorphicLessThan(e,t)),wf.ClassName,e)}_polymorphicLessThan(e,t){return Df(e,t,((e,t)=>ethis._polymorphicLessThanOrEqual(e,t)),Nf.ClassName,e)}_polymorphicLessThanOrEqual(e,t){return Df(e,t,((e,t)=>e<=t))}}Nf.ClassName="FGLessThanOrEqualBlock";class Ff extends Gd{constructor(e){super(Ou,Ou,Nu,((e,t)=>this._polymorphicGreaterThan(e,t)),Ff.ClassName,e)}_polymorphicGreaterThan(e,t){return Df(e,t,((e,t)=>e>t))}}Ff.ClassName="FGGreaterThanBlock",(0,X.Y5)(Ff.ClassName,Ff);class Lf extends Gd{constructor(e){super(Ou,Ou,Nu,((e,t)=>this._polymorphicGreaterThanOrEqual(e,t)),Lf.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){return Df(e,t,((e,t)=>e>=t))}}Lf.ClassName="FGGreaterThanOrEqualBlock",(0,X.Y5)(Lf.ClassName,Lf);class Bf extends zd{constructor(e){super(Ou,Nu,(e=>this._polymorphicIsNan(e)),Bf.ClassName,e)}_polymorphicIsNan(e){const t=Zd(e);if(""===t)return isNaN(e);if("FlowGraphInteger"===t)return isNaN(e.value);throw new Error(`Cannot get NaN of ${e}`)}}Bf.ClassName="FGIsNanBlock",(0,X.Y5)(Bf.ClassName,Bf);class Vf extends zd{constructor(e){super(Ou,Nu,(e=>this._polymorphicIsInf(e)),Vf.ClassName,e)}_polymorphicIsInf(e){const t=Zd(e);if(""===t)return!isFinite(e);if("FlowGraphInteger"===t)return!isFinite(e.value);throw new Error(`Cannot get isInf of ${e}`)}}Vf.ClassName="FGIsInfBlock";class kf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicDegToRad(e)),kf.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return ff(e,this._degToRad)}}kf.ClassName="FGDegToRadBlock",(0,X.Y5)(kf.ClassName,kf);class Uf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicRadToDeg(e)),Uf.ClassName,e)}_radToDeg(e){return 180*e/Math.PI}_polymorphicRadToDeg(e){return ff(e,this._radToDeg)}}Uf.ClassName="FGRadToDegBlock",(0,X.Y5)(Uf.ClassName,Uf);class Gf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicSin(e)),Gf.ClassName,e)}_polymorphicSin(e){return ff(e,Math.sin)}}Gf.ClassName="FGSinBlock",(0,X.Y5)(Gf.ClassName,Gf);class zf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicCos(e)),zf.ClassName,e)}_polymorphicCos(e){return ff(e,Math.cos)}}zf.ClassName="FGCosBlock",(0,X.Y5)(zf.ClassName,zf);class Wf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicTan(e)),Wf.ClassName,e)}_polymorphicTan(e){return ff(e,Math.tan)}}Wf.ClassName="FGTanBlock",(0,X.Y5)(Wf.ClassName,Wf);class Hf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicAsin(e)),Hf.ClassName,e)}_polymorphicAsin(e){return ff(e,Math.asin)}}Hf.ClassName="FGAsinBlock",(0,X.Y5)(Hf.ClassName,Hf);class Xf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicAcos(e)),Xf.ClassName,e)}_polymorphicAcos(e){return ff(e,Math.acos)}}Xf.ClassName="FGAcosBlock",(0,X.Y5)(Xf.ClassName,Xf);class qf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicAtan(e)),qf.ClassName,e)}_polymorphicAtan(e){return ff(e,Math.atan)}}qf.ClassName="FGAtanBlock",(0,X.Y5)(qf.ClassName,qf);class Yf extends Gd{constructor(e){super(Ou,Ou,Ou,((e,t)=>this._polymorphicAtan2(e,t)),Yf.ClassName,e)}_polymorphicAtan2(e,t){return Sf(e,t,Math.atan2)}}Yf.ClassName="FGAtan2Block",(0,X.Y5)(Yf.ClassName,Yf);class Kf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicSinh(e)),Kf.ClassName,e)}_polymorphicSinh(e){return ff(e,Math.sinh)}}Kf.ClassName="FGSinhBlock",(0,X.Y5)(Kf.ClassName,Kf);class jf extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicCosh(e)),jf.ClassName,e)}_polymorphicCosh(e){return ff(e,Math.cosh)}}jf.ClassName="FGCoshBlock",(0,X.Y5)(jf.ClassName,jf);class $f extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicTanh(e)),$f.ClassName,e)}_polymorphicTanh(e){return ff(e,Math.tanh)}}$f.ClassName="FGTanhBlock",(0,X.Y5)($f.ClassName,$f);class Qf extends zd{constructor(e){super(Ou,wu,(e=>this._polymorphicAsinh(e)),Qf.ClassName,e)}_polymorphicAsinh(e){return ff(e,Math.asinh)}}Qf.ClassName="FGAsinhBlock",(0,X.Y5)(Qf.ClassName,Qf);class Zf extends zd{constructor(e){super(Ou,wu,(e=>this._polymorphicAcosh(e)),Zf.ClassName,e)}_polymorphicAcosh(e){return ff(e,Math.acosh)}}Zf.ClassName="FGAcoshBlock",(0,X.Y5)(Zf.ClassName,Zf);class Jf extends zd{constructor(e){super(Ou,wu,(e=>this._polymorphicAtanh(e)),Jf.ClassName,e)}_polymorphicAtanh(e){return ff(e,Math.atanh)}}Jf.ClassName="FGAtanhBlock",(0,X.Y5)(Jf.ClassName,Jf);class ep extends zd{constructor(e){super(Ou,wu,(e=>this._polymorphicExp(e)),ep.ClassName,e)}_polymorphicExp(e){return ff(e,Math.exp)}}ep.ClassName="FGExpBlock",(0,X.Y5)(ep.ClassName,ep);class tp extends zd{constructor(e){super(Ou,wu,(e=>this._polymorphicLog(e)),tp.ClassName,e)}_polymorphicLog(e){return ff(e,Math.log)}}tp.ClassName="FGLogBlock",(0,X.Y5)(tp.ClassName,tp);class ip extends zd{constructor(e){super(Ou,wu,(e=>this._polymorphicLog2(e)),ip.ClassName,e)}_polymorphicLog2(e){return ff(e,Math.log2)}}ip.ClassName="FGLog2Block",(0,X.Y5)(ip.ClassName,ip);class rp extends zd{constructor(e){super(Ou,wu,(e=>this._polymorphicLog10(e)),rp.ClassName,e)}_polymorphicLog10(e){return ff(e,Math.log10)}}rp.ClassName="FGLog10Block",(0,X.Y5)(rp.ClassName,rp);class sp extends zd{constructor(e){super(Ou,wu,(e=>this._polymorphicSqrt(e)),sp.ClassName,e)}_polymorphicSqrt(e){return ff(e,Math.sqrt)}}sp.ClassName="FGSqrtBlock",(0,X.Y5)(sp.ClassName,sp);class np extends zd{constructor(e){super(Ou,wu,(e=>this._polymorphicCubeRoot(e)),np.ClassName,e)}_polymorphicCubeRoot(e){return ff(e,Math.cbrt)}}np.ClassName="FGCubeRootBlock",(0,X.Y5)(np.ClassName,np);class op extends Gd{constructor(e){super(Ou,wu,wu,((e,t)=>this._polymorphicPow(e,t)),op.ClassName,e)}_polymorphicPow(e,t){return Sf(e,t,Math.pow)}}op.ClassName="FGPowBlock",(0,X.Y5)(op.ClassName,op);class ap extends zd{constructor(e){super(Ou,wu,(e=>this._polymorphicLength(e)),ap.ClassName,e)}_polymorphicLength(e){switch(Zd(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw new Error(`Cannot compute length of value ${e}`)}}}ap.ClassName="FGLengthBlock",(0,X.Y5)(ap.ClassName,ap);class lp extends zd{constructor(e){super(Ou,Ou,(e=>this._polymorphicNormalize(e)),lp.ClassName,e)}_polymorphicNormalize(e){switch(Zd(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw new Error(`Cannot normalize value ${e}`)}}}lp.ClassName="FGNormalizeBlock",(0,X.Y5)(lp.ClassName,lp);class hp extends Gd{constructor(e){super(Lu,Lu,Lu,((e,t)=>W.Pq.Cross(e,t)),hp.ClassName,e)}}hp.ClassName="FGCrossBlock",(0,X.Y5)(hp.ClassName,hp);class cp extends Gd{constructor(e){super(Fu,wu,Fu,((e,t)=>W.I9.Transform(e,W.uq.RotationZ(t))),cp.ClassName,e)}}cp.ClassName="FGRotate2DBlock",(0,X.Y5)(cp.ClassName,cp);class up extends Qd{constructor(e){super(Lu,Lu,wu,Lu,((e,t,i)=>W.Pq.TransformCoordinates(e,W.uq.RotationAxis(t,i))),up.ClassName,e)}}up.ClassName="FGRotate3DBlock",(0,X.Y5)(up.ClassName,up);class dp extends zd{constructor(e){super(Vu,Vu,(e=>W.uq.Transpose(e)),dp.ClassName,e)}}dp.ClassName="FGTransposeBlock",(0,X.Y5)(dp.ClassName,dp);class fp extends zd{constructor(e){super(Vu,wu,(e=>e.determinant()),fp.ClassName,e)}}fp.ClassName="FGDeterminantBlock",(0,X.Y5)(fp.ClassName,fp);class pp extends zd{constructor(e){super(Vu,Vu,(e=>W.uq.Invert(e)),pp.ClassName,e)}}pp.ClassName="FGInvertMatrixBlock",(0,X.Y5)(pp.ClassName,pp);class _p extends Gd{constructor(e){super(Vu,Vu,Vu,((e,t)=>t.multiply(e)),_p.ClassName,e)}}_p.ClassName="FGMatMulBlock",(0,X.Y5)(_p.ClassName,_p);class mp extends zd{constructor(e){super(zu,zu,(e=>new Iu(~e.value)),mp.ClassName,e)}}mp.ClassName="FGBitwiseNotBlock",(0,X.Y5)(mp.ClassName,mp);class gp extends Gd{constructor(e){super(zu,zu,zu,((e,t)=>new Iu(e.value&t.value)),gp.ClassName,e)}}gp.ClassName="FGBitwiseAndBlock",(0,X.Y5)(gp.ClassName,gp);class vp extends Gd{constructor(e){super(zu,zu,zu,((e,t)=>new Iu(e.value|t.value)),vp.ClassName,e)}}vp.ClassName="FGBitwiseOrBlock",(0,X.Y5)(vp.ClassName,vp);class xp extends Gd{constructor(e){super(zu,zu,zu,((e,t)=>new Iu(e.value^t.value)),xp.ClassName,e)}}xp.ClassName="FGBitwiseXorBlock",(0,X.Y5)(xp.ClassName,xp);class bp extends Gd{constructor(e){super(zu,zu,zu,((e,t)=>new Iu(e.value<new Iu(e.value>>t.value)),Sp.ClassName,e)}}Sp.ClassName="FGBitwiseRightShiftBlock",(0,X.Y5)(Sp.ClassName,Sp);class Tp extends zd{constructor(e){super(zu,zu,(e=>new Iu(Math.clz32(e.value))),Tp.ClassName,e)}}Tp.ClassName="FGCountLeadingZerosBlock",(0,X.Y5)(Tp.ClassName,Tp);class Cp extends zd{constructor(e){super(zu,zu,(e=>new Iu(e.value?31-Math.clz32(e.value&-e.value):32)),Cp.ClassName,e)}}Cp.ClassName="FGCountTrailingZerosBlock",(0,X.Y5)(Cp.ClassName,Cp);class yp extends zd{constructor(e){super(zu,zu,(e=>new Iu(function(e){let t=0;for(;e;)t+=1&e,e>>=1;return t}(e.value))),yp.ClassName,e)}}yp.ClassName="FGCountOneBitsBlock",(0,X.Y5)(yp.ClassName,yp);class Ep extends Ju{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){const t=e.configuration.scene.onReadyObservable.add((()=>{this._execute(e)}));e._setExecutionVariable(this,"sceneReadyObserver",t)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneReadyObserver");e.configuration.scene.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return Ep.ClassName}}Ep.ClassName="FGSceneReadyEventBlock",(0,X.Y5)("FGSceneReadyEventBlock",Ep);class Pp extends Ju{constructor(e){super(e),this.config=e;for(let e=0;e{for(let i=0;i{this._execute(e)}));e._setExecutionVariable(this,"sceneBeforeRender",t)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneBeforeRender");e.configuration.scene.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}getClassName(){return Ap.ClassName}}Ap.ClassName="FGSceneTickEventBlock",(0,X.Y5)(Ap.ClassName,Ap);var Rp,Ip,Mp,Op=i(83839);!function(e){e[e.Texture=1]="Texture",e[e.TextureBackBuffer=2]="TextureBackBuffer",e[e.TextureBackBufferDepthStencilAttachment=4]="TextureBackBufferDepthStencilAttachment",e[e.TextureDepthStencilAttachment=8]="TextureDepthStencilAttachment",e[e.TextureViewDepth=16]="TextureViewDepth",e[e.TextureViewNormal=32]="TextureViewNormal",e[e.TextureAlbedo=64]="TextureAlbedo",e[e.TextureReflectivity=128]="TextureReflectivity",e[e.TextureWorldPosition=256]="TextureWorldPosition",e[e.TextureVelocity=512]="TextureVelocity",e[e.TextureIrradiance=1024]="TextureIrradiance",e[e.TextureAlbedoSqrt=2048]="TextureAlbedoSqrt",e[e.TextureScreenDepth=4096]="TextureScreenDepth",e[e.TextureWorldNormal=8192]="TextureWorldNormal",e[e.TextureLocalPosition=16384]="TextureLocalPosition",e[e.TextureLinearVelocity=32768]="TextureLinearVelocity",e[e.TextureAllButBackBufferDepthStencil=16777211]="TextureAllButBackBufferDepthStencil",e[e.TextureAllButBackBuffer=16777209]="TextureAllButBackBuffer",e[e.TextureAll=16777215]="TextureAll",e[e.Camera=16777216]="Camera",e[e.ObjectList=33554432]="ObjectList",e[e.AutoDetect=268435456]="AutoDetect",e[e.BasedOnInput=536870912]="BasedOnInput",e[e.Undefined=1073741824]="Undefined",e[e.All=4294967295]="All"}(Rp||(Rp={})),function(e){e[e.Compatible=0]="Compatible",e[e.TypeIncompatible=1]="TypeIncompatible",e[e.HierarchyIssue=2]="HierarchyIssue"}(Ip||(Ip={})),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(Mp||(Mp={}));class Dp{get direction(){return this._direction}get type(){if(this._type===Rp.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.type}if(this._type===Rp.BasedOnInput){if(this._typeConnectionSource){const e="function"==typeof this._typeConnectionSource?this._typeConnectionSource():this._typeConnectionSource;return e.isConnected?e._connectedPoint.type:this._defaultConnectionPointType??e.type}if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type}set type(e){this._type=e}get isConnected(){return null!==this.connectedPoint||this.hasEndpoints}get connectedPoint(){return this._connectedPoint}get ownerBlock(){return this._ownerBlock}get sourceBlock(){return this._connectedPoint?this._connectedPoint.ownerBlock:null}get connectedBlocks(){return 0===this._endpoints.length?[]:this._endpoints.map((e=>e.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}constructor(e,t,i){this._connectedPoint=null,this._acceptedConnectionPointType=null,this._endpoints=new Array,this._type=Rp.Undefined,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new z.cP,this.onDisconnectionObservable=new z.cP,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeRenderGraphConnectionPoint"}canConnectTo(e){return 0===this.checkCompatibilityState(e)}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==Rp.AutoDetect)return e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)?0:1;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return 1;let r=i,s=t;return 0===this.direction&&(r=t,s=i),r.isAnAncestorOf(s)?2:0}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this)),this}addExcludedConnectionPointFromAllowedTypes(e){let t=0,i=2**t;for(;i=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear(),this.onDisconnectionObservable.clear()}}class wp{get disabled(){return!!this._frameGraphTask?.disabled}set disabled(e){this._frameGraphTask&&(this._frameGraphTask.disabled=e)}get task(){return this._frameGraphTask}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"NodeRenderGraphBlock"}_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)return!0;if(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 t=i.ownerBlock.getDescendantOfPredicate(e);if(t)return t}return null}constructor(e,t,i,...r){this._name="",this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._isDebug=!1,this._isUnique=!1,this.onBuildObservable=new z.cP,this._inputs=new Array,this._outputs=new Array,this._codeVariableName="",this._additionalConstructionParameters=null,this.visibleOnFrame=!1,this._name=e,this._frameGraph=t,this._scene=i,this._engine=i.getEngine(),this.uniqueId=Op.K.UniqueId}registerInput(e,t,i=!1,r){return(r=r??new Dp(e,this,0)).type=t,r.isOptional=i,this._inputs.push(r),this}registerOutput(e,t,i){return(i=i??new Dp(e,this,1)).type=t,this._outputs.push(i),this}_buildBlock(e){}_customBuildStep(e){}_propagateInputValueToOutput(e,t){e.connectedPoint&&(t.value=e.connectedPoint.value)}build(e){if(this._buildId===e.buildId)return!0;this._buildId=e.buildId;for(const t of this._inputs){if(!t.connectedPoint){t.isOptional||e._notConnectedNonOptionalInputs.push(t);continue}const i=t.connectedPoint.ownerBlock;i&&i!==this&&i.build(e)}return this._customBuildStep(e),e.verbose&&Z.V.Log(`Building ${this.name} [${this.getClassName()}]`),this._buildBlock(e),this._frameGraphTask&&this._frameGraph.addTask(this._frameGraphTask),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((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.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.disabled=this.disabled,this._additionalConstructionParameters&&(e.additionalConstructionParameters=this._additionalConstructionParameters),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.disabled=e.disabled,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach((e=>{const t=this.inputs.find((t=>t.name===e.name));t&&(e.displayName&&(t.displayName=e.displayName),e.isExposedOnFrame&&(t.isExposedOnFrame=e.isExposedOnFrame,t.exposedPortPosition=e.exposedPortPosition))})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}_dumpPropertiesCode(){const e=this._codeVariableName;return`${e}.visibleOnFrame = ${this.visibleOnFrame};\n${e}.disabled = ${this.disabled};\n`}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e),t+=`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\n`}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}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=i+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let r=`\n// ${this.getClassName()}\n`;this.comments&&(r+=`// ${this.comments}\n`);const s=this.getClassName();if("RenderGraphInputBlock"===s){const e=this.type;r+=`var ${this._codeVariableName} = new BABYLON.NodeRenderGraphInputBlock("${this.name}", nodeRenderGraph.frameGraph, scene, BABYLON.NodeRenderGraphBlockConnectionPointTypes.${Rp[e]});\n`}else this._additionalConstructionParameters?r+=`var ${this._codeVariableName} = new BABYLON.${s}("${this.name}", nodeRenderGraph.frameGraph, scene, ...${JSON.stringify(this._additionalConstructionParameters)});\n`:r+=`var ${this._codeVariableName} = new BABYLON.${s}("${this.name}", nodeRenderGraph.frameGraph, scene);\n`;r+=this._dumpPropertiesCode()+"\n";for(const i of this.inputs){if(!i.isConnected)continue;const s=i.connectedPoint.ownerBlock;-1===t.indexOf(s)&&(r+=s._dumpCode(e,t))}for(const i of this.outputs)if(i.hasEndpoints)for(const s of i.endpoints){const i=s.ownerBlock;i&&-1===t.indexOf(i)&&(r+=i._dumpCode(e,t))}return r}clone(){const e=this.serialize(),t=(0,X.n9)(e.customType);if(t){const i=e.additionalConstructionParameters,r=i?new t("",this._frameGraph,this._scene,...i):new t("",this._frameGraph,this._scene);return r._deserialize(e),r}return null}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose();this._frameGraphTask?.dispose(),this._frameGraphTask=void 0,this.onBuildObservable.clear()}}(0,je.Cg)([(0,$e.lK)("comment")],wp.prototype,"comments",void 0);const Np=0,Fp=1;class Lp{constructor(e,t,i){this.name=e,this._parentTask=t,this._context=i}setExecuteFunc(e){this._executeFunc=e}_execute(){this._executeFunc(this._context)}_isValid(){return void 0!==this._executeFunc?null:"Execute function is not set (call setExecuteFunc to set it)"}}class Bp extends Lp{static IsCullPass(e){return void 0!==e.setObjectList}get objectList(){return this._objectList}setObjectList(e){this._objectList=e}constructor(e,t,i,r){super(e,t,i),this._engine=r}_isValid(){return super._isValid()||(void 0!==this._objectList?null:"Object list is not set (call setObjectList to set it)")}}class Vp extends Lp{static IsRenderPass(e){return void 0!==e.setRenderTarget}get renderTarget(){return this._renderTarget}get renderTargetDepth(){return this._renderTargetDepth}constructor(e,t,i,r){super(e,t,i),this._usedTextures=[],this._depthShared=!1,this._engine=r}useTexture(e){this._usedTextures.push(e)}setRenderTarget(e){this._renderTarget=e}setRenderTargetDepth(e){this._renderTargetDepth=e}_execute(){this._renderTargetDepth&&!this._depthShared&&(this._context._shareDepth(this._renderTargetDepth,this._renderTarget),this._depthShared=!0),this._context.bindRenderTarget(this._renderTarget,`frame graph - render pass '${this.name}'`),super._execute(),this._context._flushDebugMessages()}_isValid(){return super._isValid()||(void 0!==this._renderTarget?null:"Render target is not set (call setRenderTarget to set it)")}}class kp{get name(){return this._name}set name(e){this._name=e}get disabled(){return this._disabled}set disabled(e){this._disabled=e}isReady(){return!0}dispose(){this._reset()}constructor(e,t){this._passes=[],this._passesDisabled=[],this._disabled=!1,this.name=e,this._frameGraph=t,this._reset()}_reset(){this._passes.length=0,this._passesDisabled.length=0}_addPass(e,t){t?this._passesDisabled.push(e):this._passes.push(e)}_checkTask(){let e,t=null,i=null;for(const r of this._passes){const s=r._isValid();if(s)throw new Error(`Pass "${r.name}" is not valid. ${s}`);Vp.IsRenderPass(r)?(t=this._frameGraph.getTexture(r.renderTarget),i=void 0!==r.renderTargetDepth?this._frameGraph.getTexture(r.renderTargetDepth):null):Bp.IsCullPass(r)&&(e=r.objectList)}let r,s=null,n=-1,o=null;for(const e of this._passesDisabled){const t=e._isValid();if(t)throw new Error(`Pass "${e.name}" is not valid. ${t}`);Vp.IsRenderPass(e)?(s=this._frameGraph.getTexture(e.renderTarget),n=e.renderTarget,o=void 0!==e.renderTargetDepth?this._frameGraph.getTexture(e.renderTargetDepth):null):Bp.IsCullPass(e)&&(r=e.objectList)}if(this._passesDisabled.length>0){if(t!==s&&!this._frameGraph.isHistoryTexture(n))throw new Error(`The output texture of the task "${this.name}" is different when it is enabled or disabled.`);if(i!==o)throw new Error(`The output depth texture of the task "${this.name}" is different when it is enabled or disabled.`);if(e!==r)throw new Error(`The output object list of the task "${this.name}" is different when it is enabled or disabled.`)}}_getPasses(){return this.disabled&&this._passesDisabled.length>0?this._passesDisabled:this._passes}}class Up extends kp{record(){if(void 0===this.sourceTexture)throw new Error(`FrameGraphCopyToBackbufferColorTask "${this.name}": sourceTexture is required`);const e=this._frameGraph.addRenderPass(this.name);e.setRenderTarget(Np),e.setExecuteFunc((e=>{e.isBackbuffer(this.sourceTexture)||e.copyTexture(this.sourceTexture)}));const t=this._frameGraph.addRenderPass(this.name+"_disabled",!0);t.setRenderTarget(Np),t.setExecuteFunc((e=>{}))}}class Gp extends wp{get task(){return this._frameGraphTask}constructor(e,t,i){super(e,t,i),this._isUnique=!0,this.registerInput("texture",Rp.Texture),this.texture.addAcceptedConnectionPointTypes(Rp.TextureAll),this._frameGraphTask=new Up(e,t)}getClassName(){return"NodeRenderGraphOutputBlock"}get texture(){return this._inputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name;const t=this.texture.connectedPoint;t&&(this._frameGraphTask.sourceTexture=t.value)}}(0,X.Y5)("BABYLON.NodeRenderGraphOutputBlock",Gp);var zp,Wp,Hp,Xp,qp,Yp=i(50606);!function(e){e[e.None=0]="None",e[e.ToLinearSpace=1]="ToLinearSpace",e[e.ToGammaSpace=2]="ToGammaSpace"}(zp||(zp={}));class Kp{get shaderLanguage(){return this._shaderLanguage}_textureIsInternal(e){return void 0===e.getInternalTexture}constructor(e,t=!1){this._shaderLanguage=0,this._shadersLoaded=!1,this._engine=e,this._isDepthTexture=t,this._renderer=new Yp.J(e),this._initShaderSourceAsync(t)}async _initShaderSourceAsync(e){const t=this._engine;t.isWebGPU?(this._shaderLanguage=1,await Promise.resolve().then(i.bind(i,89517))):await Promise.resolve().then(i.bind(i,92224)),this._shadersLoaded=!0,this._effectWrapper=new Yp.$({engine:t,name:"CopyTextureToTexture",fragmentShader:"copyTextureToTexture",useShaderStore:!0,uniformNames:["conversion"],samplerNames:["textureSampler"],defines:e?["#define DEPTH_TEXTURE"]:[],shaderLanguage:this._shaderLanguage}),this._effectWrapper.onApplyObservable.add((()=>{e?(t.setState(!1),t.setDepthBuffer(!0),t.depthCullingState.depthMask=!0,t.depthCullingState.depthFunc=519):t.depthCullingState.depthMask=!1,this._textureIsInternal(this._source)?this._effectWrapper.effect._bindTexture("textureSampler",this._source):this._effectWrapper.effect.setTexture("textureSampler",this._source),this._effectWrapper.effect.setFloat("conversion",this._conversion)}))}isReady(){return this._shadersLoaded&&this._effectWrapper.effect.isReady()}copy(e,t=null,i=0){if(!this.isReady())return!1;this._source=e,this._conversion=i;const r=this._engine.getDepthFunction(),s=this._engine.getDepthWrite();return this._renderer.render(this._effectWrapper,t),this._engine.setDepthWrite(s),this._isDepthTexture&&r&&this._engine.setDepthFunction(r),!0}dispose(){this._effectWrapper?.dispose(),this._renderer.dispose()}}class jp{}class $p extends jp{static _IsObjectRenderer(e){return void 0!==e.initRender}constructor(e,t,i){super(),this._engine=e,this._textureManager=t,this._scene=i,this._debugMessageHasBeenPushed=!1,this._renderTargetIsBound=!0,this._effectRenderer=new Yp.J(this._engine),this._copyTexture=new Kp(this._engine),this._currentRenderTargetHandle=Np}isBackbuffer(e){return this._textureManager.isBackbuffer(e)}isBackbufferColor(e){return this._textureManager.isBackbufferColor(e)}isBackbufferDepthStencil(e){return this._textureManager.isBackbufferDepthStencil(e)}clear(e,t,i,r){this._applyRenderTarget(),this._engine.clear(e,t,i,r)}clearColorAttachments(e,t){this._applyRenderTarget(),this._engine.bindAttachments(t),this._engine.clear(e,!0,!1,!1)}bindAttachments(e){this._applyRenderTarget(),this._engine.bindAttachments(e)}generateMipMaps(){const e=this._textureManager.getTextureFromHandle(this._currentRenderTargetHandle);e&&(this._renderTargetIsBound&&(this._flushDebugMessages(),this._engine.unBindFramebuffer(e),this._renderTargetIsBound=!1),this._engine.generateMipmaps(e.texture))}setTextureSamplingMode(e,t){const i=this._textureManager.getTextureFromHandle(e)?.texture;i&&i.samplingMode!==t&&this._engine.updateTextureSamplingMode(t,i)}bindTextureHandle(e,t,i){const r=this._textureManager.getTextureFromHandle(i);r&&e._bindTexture(t,r.texture)}setDepthStates(e,t){this._engine.setDepthBuffer(e),this._engine.setDepthWrite(t)}applyFullScreenEffect(e,t){if(!e.effect?.isReady())return!1;this._applyRenderTarget();const i=this._engine.getDepthWrite();return this._effectRenderer.saveStates(),this._effectRenderer.setViewport(),this._engine.enableEffect(e),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._effectRenderer.bindBuffers(e.effect),t?.(),this._effectRenderer.draw(),this._effectRenderer.restoreStates(),this._engine.setDepthWrite(i),this._engine.setAlphaMode(0),!0}copyTexture(e,t=!1){t&&this.bindRenderTarget(),this._applyRenderTarget(),this._copyTexture.copy(this._textureManager.getTextureFromHandle(e).texture)}render(e,t,i){$p._IsObjectRenderer(e)?e.shouldRender()&&(this._scene?.incrementRenderId(),this._scene?.resetCachedMaterial(),e.prepareRenderList(),e.initRender(t,i),this._applyRenderTarget(),e.render(),e.finishRender()):(this._applyRenderTarget(),e.render())}bindRenderTarget(e=Np,t){if(e===this._currentRenderTargetHandle)return this._flushDebugMessages(),void(void 0!==t&&(this._engine._debugPushGroup?.(t,2),this._debugMessageWhenTargetBound=void 0,this._debugMessageHasBeenPushed=!0));this._currentRenderTargetHandle=e,this._debugMessageWhenTargetBound=t,this._renderTargetIsBound=!1}_flushDebugMessages(){this._debugMessageHasBeenPushed&&(this._engine._debugPopGroup?.(2),this._debugMessageHasBeenPushed=!1)}_shareDepth(e,t){const i=this._textureManager.getTextureFromHandle(e),r=this._textureManager.getTextureFromHandle(t);i&&r&&i.shareDepth(r)}_applyRenderTarget(){if(this._renderTargetIsBound)return;const e=this._currentRenderTargetHandle,t=this._textureManager._textures.get(e);let i=t.texture;if(t.creationOptions.isHistoryTexture){const r=this._textureManager._historyTextures.get(t.refHandle??e);i=r.textures[r.index]}this._flushDebugMessages(),i?this._engine.bindFramebuffer(i):e===Np||t.refHandle===Np?this._engine.restoreDefaultFramebuffer():e!==Fp&&t.refHandle!==Fp||this._engine.restoreDefaultFramebuffer(),void 0!==this._debugMessageWhenTargetBound&&(this._engine._debugPushGroup?.(this._debugMessageWhenTargetBound,2),this._debugMessageWhenTargetBound=void 0,this._debugMessageHasBeenPushed=!0),this._renderTargetIsBound=!0}_dispose(){this._effectRenderer.dispose(),this._copyTexture.dispose()}}function Qp(e){return void 0!==e.width}function Zp(e){return Qp(e)?{width:e.width,height:e.height}:{width:e,height:e}}!function(e){e[e.Task=0]="Task",e[e.Graph=1]="Graph",e[e.External=2]="External"}(Wp||(Wp={}));class Jp{constructor(e,t=!1,i){this._engine=e,this._debugTextures=t,this._scene=i,this._textures=new Map,this._historyTextures=new Map,this._addSystemTextures()}isBackbuffer(e){if(e===Np||e===Fp)return!0;const t=this._textures.get(e);return!!t&&(t.refHandle===Np||t.refHandle===Fp)}isBackbufferColor(e){if(e===Np)return!0;const t=this._textures.get(e);return!!t&&t.refHandle===Np}isBackbufferDepthStencil(e){if(e===Fp)return!0;const t=this._textures.get(e);return!!t&&t.refHandle===Fp}getTextureCreationOptions(e){return this._textures.get(e).creationOptions}getTextureFromHandle(e){const t=this._historyTextures.get(e);return t?t.textures[1^t.index]:this._textures.get(e).texture}importTexture(e,t,i){const r=t.texture;if(!r)throw new Error("importTexture: Texture must have an internal texture to be imported");void 0!==i&&this._freeEntry(i);const s={size:{width:t.width,height:t.height},options:{generateMipMaps:r.generateMipMaps,generateDepthBuffer:t._generateDepthBuffer,generateStencilBuffer:t._generateStencilBuffer,samples:r.samples,label:r.label,types:[r.type],samplingModes:[r.samplingMode],formats:[r.format],targetTypes:[r.isCube?34067:r.is3D?32879:r.is2DArray?35866:3553],useSRGBBuffers:[r._useSRGBBuffer],labels:r.label?[r.label]:void 0},sizeIsPercentage:!1};return this._createHandleForTexture(e,t,s,Wp.External,!1,i)}createRenderTargetTexture(e,t,i,r=!1,s){return this._createHandleForTexture(e,null,i,t?Wp.Task:Wp.Graph,r,s)}getAbsoluteDimensions(e,t=this._engine.getRenderWidth(!0),i=this._engine.getRenderHeight(!0)){const{width:r,height:s}=Zp(e);return{width:Math.floor(r*t/100),height:Math.floor(s*i/100)}}updateHistoryTextures(){this._historyTextures.forEach((e=>{e.index=1^e.index;for(const t of e.refHandles)this._textures.get(t).texture=e.textures[e.index]}))}dispose(){this.releaseTextures()}allocateTextures(){this._textures.forEach((e=>{if(!e.texture)if(void 0!==e.refHandle){const t=this._textures.get(e.refHandle);e.texture=t.texture,e.texture?.texture?.incrementReferences(),t.refHandle===Np&&(e.refHandle=Np),t.refHandle===Fp&&(e.refHandle=Fp)}else if(e.namespace!==Wp.External)if(void 0!==e.parentHandle){const t=e.creationOptions,i=t.sizeIsPercentage?this.getAbsoluteDimensions(t.size):t.size,r=this._textures.get(e.parentHandle).texture.textures[e.parentTextureIndex],s={createMipMaps:t.options.createMipMaps,generateMipMaps:t.options.generateMipMaps,generateDepthBuffer:t.options.generateDepthBuffer,generateStencilBuffer:t.options.generateStencilBuffer,samples:t.options.samples,type:t.options.types[0],format:t.options.formats[0],useSRGBBuffer:t.options.useSRGBBuffers[0],colorAttachment:r,label:t.options.label};e.texture=this._engine.createRenderTargetTexture(i,s),r.incrementReferences()}else{const t=e.creationOptions,i=t.sizeIsPercentage?this.getAbsoluteDimensions(t.size):t.size;e.texture=this._engine.createMultipleRenderTarget(i,t.options,!1)}e.texture&&void 0===e.refHandle&&(e.debug?.dispose(),e.debug=this._createDebugTexture(e.name,e.texture))})),this._historyTextures.forEach((e=>{for(let t=0;t{(e||t.namespace!==Wp.External)&&(t.debug?.dispose(),t.debug=void 0),t.namespace!==Wp.External&&(t.texture?.dispose(),t.texture=null,(e||t.namespace===Wp.Task)&&this._textures.delete(i))})),this._historyTextures.forEach((e=>{for(let t=0;tt.name===e))}addTask(e){if(null!==this._currentProcessedTask)throw new Error(`FrameGraph.addTask: Can't add the task "${e.name}" while another task is currently building (task: ${this._currentProcessedTask.name}).`);this._tasks.push(e)}addRenderPass(e,t=!1){return this._addPass(e,Hp.Render,t)}addCullPass(e,t=!1){return this._addPass(e,Hp.Cull,t)}_addPass(e,t,i=!1){if(!this._currentProcessedTask)throw new Error("FrameGraph: A pass must be created during a Task.record execution only.");let r;switch(t){case Hp.Render:r=new Vp(e,this._currentProcessedTask,this._renderContext,this._engine);break;case Hp.Cull:r=new Bp(e,this._currentProcessedTask,this._passContext,this._engine);break;default:r=new Lp(e,this._currentProcessedTask,this._passContext)}return this._currentProcessedTask._addPass(r,i),r}build(){this._textureManager.releaseTextures(!1);for(const e of this._tasks)e._reset(),this._currentProcessedTask=e,e.record(),this._currentProcessedTask=null;this._textureManager.allocateTextures();for(const e of this._tasks)e._checkTask();this.onBuildObservable.notifyObservers(this)}whenReadyAsync(e=16){return new Promise((t=>{const i=()=>{let r=!0;for(const e of this._tasks)r&&(r=e.isReady());r?t():setTimeout(i,e)};i()}))}execute(){this._renderContext.bindRenderTarget(),this._textureManager.updateHistoryTextures();for(const e of this._tasks){const t=e._getPasses();for(const e of t)e._execute()}}importTexture(e,t,i){return this._textureManager.importTexture(e,t,i)}getTextureCreationOptions(e,t=!1){const i=this._textureManager.getTextureCreationOptions(e);return t?{size:Zp(i.size),options:{...i.options},sizeIsPercentage:i.sizeIsPercentage}:i}getTextureDescription(e){const t=this.getTextureCreationOptions(e);return{size:t.sizeIsPercentage?this._textureManager.getAbsoluteDimensions(t.size):Qp(t.size)?{width:t.size.width,height:t.size.height}:{width:t.size,height:t.size},options:{...t.options}}}getTextureHandleOrCreateTexture(e,t,i){if(void 0===e){if(void 0===t||void 0===i)throw new Error("getTextureHandleOrCreateTexture: Either handle or newTextureName and creationOptions must be provided.");return this.createRenderTargetTexture(t,i)}return e}getTexture(e){return this._textureManager.getTextureFromHandle(e)}createRenderTargetTexture(e,t,i=!1){return this._textureManager.createRenderTargetTexture(e,!!this._currentProcessedTask,t,i)}createDanglingHandle(){return this._textureManager.createDanglingHandle()}resolveDanglingHandle(e,t,i,r){if(void 0!==t)this._textureManager.resolveDanglingHandle(e,t);else{if(void 0===i||void 0===r)throw new Error("resolveDanglingHandle: Either handle or newTextureName and creationOptions must be provided.");this._textureManager.createRenderTargetTexture(i,!!this._currentProcessedTask,r,!1,e)}}isHistoryTexture(e){const t=this._textureManager._textures.get(e);return!!t&&(e=t.refHandle??e,this._textureManager._historyTextures.has(e))}clear(){for(const e of this._tasks)e._reset();this._tasks.length=0,this._textureManager.releaseTextures(),this._currentProcessedTask=null}dispose(){this.clear(),this._textureManager.dispose(),this._renderContext._dispose()}}function t_(e,t=0,i="PROPERTIES",r){return(s,n)=>{let o=s._propStore;o||(o=[],s._propStore=o),o.push({propertyName:n,displayName:e,type:t,groupName:i,options:r??{},className:s.constructor.name})}}!function(e){e[e.Boolean=0]="Boolean",e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=3]="Vector2",e[e.List=4]="List",e[e.Color4=5]="Color4",e[e.SamplingMode=6]="SamplingMode",e[e.TextureFormat=7]="TextureFormat",e[e.TextureType=8]="TextureType"}(Xp||(Xp={}));class i_ extends wp{get type(){return this._type}constructor(e,t,i,r=Rp.Undefined){super(e,t,i),this._storedValue=null,this._type=Rp.Undefined,this.onValueChangedObservable=new z.cP,this.isExternal=!1,this._type=r,this._isInput=!0,this.registerOutput("output",r),this.setDefaultValue()}setDefaultValue(){switch(this.type){case Rp.Texture:case Rp.TextureViewDepth:case Rp.TextureScreenDepth:case Rp.TextureViewNormal:case Rp.TextureWorldNormal:case Rp.TextureAlbedo:case Rp.TextureReflectivity:case Rp.TextureLocalPosition:case Rp.TextureWorldPosition:case Rp.TextureVelocity:case Rp.TextureLinearVelocity:case Rp.TextureIrradiance:case Rp.TextureAlbedoSqrt:{const e={size:{width:100,height:100},options:{createMipMaps:!1,generateMipMaps:!1,types:[0],formats:[5],samples:1,useSRGBBuffers:[!1],generateDepthBuffer:!1},sizeIsPercentage:!0};this.creationOptions=e;break}case Rp.TextureDepthStencilAttachment:{const e={size:{width:100,height:100},options:{createMipMaps:!1,generateMipMaps:!1,depthTextureFormat:13,textureCount:0,samples:1,generateDepthTexture:!0,generateDepthBuffer:!0,generateStencilBuffer:!0},sizeIsPercentage:!0};this.creationOptions=e;break}case Rp.ObjectList:this.value={meshes:[],particleSystems:[]},this.isExternal=!0;break;case Rp.Camera:this.value=this._scene.cameras[0],this.isExternal=!0;break;default:this.isExternal=!0}}get value(){return this._storedValue}set value(e){this._storedValue=e,this.output.value=void 0,this.onValueChangedObservable.notifyObservers(this)}getTypedValue(){return this._storedValue}getValueAsRenderTargetWrapper(){return this._storedValue.shareDepth?this._storedValue:null}getInternalTextureFromValue(){return this._storedValue.shareDepth?this._storedValue.texture:null}getClassName(){return"NodeRenderGraphInputBlock"}get output(){return this._outputs[0]}isAnyTexture(){return!!(this.type&Rp.TextureAll)}isBackBuffer(){return!!(this.type&Rp.TextureBackBuffer)}isBackBufferDepthStencilAttachment(){return!!(this.type&Rp.TextureBackBufferDepthStencilAttachment)}isCamera(){return!!(this.type&Rp.Camera)}isObjectList(){return!!(this.type&Rp.ObjectList)}_buildBlock(e){if(super._buildBlock(e),this.isExternal)if(this.isBackBuffer())this.output.value=Np;else if(this.isBackBufferDepthStencilAttachment())this.output.value=Fp;else if(this.isCamera())this.output.value=this.getTypedValue();else if(this.isObjectList())this.output.value=this.getTypedValue();else{if(void 0===this._storedValue||null===this._storedValue)throw new Error(`NodeRenderGraphInputBlock: External input "${this.name}" is not set`);const e=this.getValueAsRenderTargetWrapper();e&&(this.output.value=this._frameGraph.importTexture(this.name,e,this.output.value))}else if(this.type&Rp.TextureAllButBackBuffer){const e=this.creationOptions;if(!e)throw new Error(`NodeRenderGraphInputBlock: Creation options are missing for texture "${this.name}"`);this.output.value=this._frameGraph.createRenderTargetTexture(this.name,e)}}dispose(){this._storedValue=null,this.onValueChangedObservable.clear(),super.dispose()}_dumpPropertiesCode(){const e=[];return e.push(`${this._codeVariableName}.isExternal = ${this.isExternal};`),this.isAnyTexture()?this.isExternal?e.push(`${this._codeVariableName}.value = EXTERNAL_TEXTURE; // TODO: set the external texture`):e.push(`${this._codeVariableName}.creationOptions = ${JSON.stringify(this.creationOptions)};`):this.isCamera()?e.push(`${this._codeVariableName}.value = EXTERNAL_CAMERA; // TODO: set the external camera`):this.isObjectList()&&e.push(`${this._codeVariableName}.value = EXTERNAL_OBJECT_LIST; // TODO: set the external object list`),super._dumpPropertiesCode()+e.join("\n")}serialize(){const e=super.serialize();return e.type=this.type,e.isExternal=this.isExternal,this.creationOptions&&(e.creationOptions=this.creationOptions),e}_deserialize(e){super._deserialize(e),this._type=e.type,this.output.type=this._type,this.isExternal=e.isExternal,e.creationOptions&&(this.creationOptions=e.creationOptions)}}(0,je.Cg)([t_("Is external",0,"PROPERTIES")],i_.prototype,"isExternal",void 0),(0,X.Y5)("BABYLON.NodeRenderGraphInputBlock",i_);class r_ extends kp{constructor(e,t){super(e,t),this.color=new H.ov(.2,.2,.3,1),this.clearColor=!0,this.clearDepth=!1,this.clearStencil=!1,this.outputTexture=this._frameGraph.createDanglingHandle()}record(){if(void 0===this.destinationTexture)throw new Error(`FrameGraphClearTextureTask ${this.name}: destinationTexture is required`);this._frameGraph.resolveDanglingHandle(this.outputTexture,this.destinationTexture);const e=this._frameGraph.addRenderPass(this.name);e.setRenderTarget(this.destinationTexture),e.setExecuteFunc((e=>{e.clear(this.color,!!this.clearColor,!!this.clearDepth,!!this.clearStencil)}));const t=this._frameGraph.addRenderPass(this.name+"_disabled",!0);t.setRenderTarget(this.destinationTexture),t.setExecuteFunc((e=>{}))}}class s_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i){super(e,t,i),this.registerInput("texture",Rp.Texture),this.registerOutput("output",Rp.BasedOnInput),this.texture.addAcceptedConnectionPointTypes(Rp.TextureAll),this.output._typeConnectionSource=this.texture,this._frameGraphTask=new r_(e,t)}get color(){return this._frameGraphTask.color}set color(e){this._frameGraphTask.color=e}get clearColor(){return!!this._frameGraphTask.clearColor}set clearColor(e){this._frameGraphTask.clearColor=e}get clearDepth(){return!!this._frameGraphTask.clearDepth}set clearDepth(e){this._frameGraphTask.clearDepth=e}get clearStencil(){return!!this._frameGraphTask.clearStencil}set clearStencil(e){this._frameGraphTask.clearStencil=e}getClassName(){return"NodeRenderGraphClearBlock"}get texture(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this._propagateInputValueToOutput(this.texture,this.output);const t=this.texture.connectedPoint;t&&(this._frameGraphTask.destinationTexture=t.value)}_dumpPropertiesCode(){const e=[];return e.push(`${this._codeVariableName}.color = new BABYLON.Color4(${this.color.r}, ${this.color.g}, ${this.color.b}, ${this.color.a});`),e.push(`${this._codeVariableName}.clearColor = ${this.clearColor};`),e.push(`${this._codeVariableName}.clearDepth = ${this.clearDepth};`),e.push(`${this._codeVariableName}.clearStencil = ${this.clearStencil};`),super._dumpPropertiesCode()+e.join("\n")}serialize(){const e=super.serialize();return e.color=this.color.asArray(),e.clearColor=this.clearColor,e.clearDepth=this.clearDepth,e.clearStencil=this.clearStencil,e}_deserialize(e){super._deserialize(e),this.color=H.ov.FromArray(e.color),this.clearColor=e.clearColor,this.clearDepth=e.clearDepth,this.clearStencil=e.clearStencil}}(0,je.Cg)([t_("Color",5)],s_.prototype,"color",null),(0,je.Cg)([t_("Clear color",0,void 0,{embedded:!0})],s_.prototype,"clearColor",null),(0,je.Cg)([t_("Clear depth",0,void 0,{embedded:!0})],s_.prototype,"clearDepth",null),(0,je.Cg)([t_("Clear stencil",0,void 0,{embedded:!0})],s_.prototype,"clearStencil",null),(0,X.Y5)("BABYLON.NodeRenderGraphClearBlock",s_);class n_{constructor(){this.verbose=!1,this._notConnectedNonOptionalInputs=[]}emitErrors(e=null){let t="";for(const e of this._notConnectedNonOptionalInputs)t+=`input "${e.name}" from block "${e.ownerBlock.name}"[${e.ownerBlock.getClassName()}] is not connected and is not optional.\n`;return!t||(e&&e.notifyObservers(t),Z.V.Error("Build of node render graph failed:\n"+t),!1)}}class o_{_getGlobalNodeRenderGraphEditor(){return"undefined"!=typeof NODERENDERGRAPHEDITOR?NODERENDERGRAPHEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeRenderGraphEditor?BABYLON:void 0}get frameGraph(){return this._frameGraph}getScene(){return this._scene}constructor(e,t,i){this._buildId=o_._BuildIdGenerator++,this.BJSNODERENDERGRAPHEDITOR=this._getGlobalNodeRenderGraphEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new z.cP,this.onBuildErrorObservable=new z.cP,this.outputBlock=null,this._resizeObserver=null,this.name=e,this._scene=t,this._engine=t.getEngine(),i={debugTextures:!1,autoConfigure:!1,verbose:!1,rebuildGraphOnEngineResize:!0,autoFillExternalInputs:!0,...i},this._options=i,this._frameGraph=new e_(this._engine,i.debugTextures,this._scene),i.rebuildGraphOnEngineResize&&(this._resizeObserver=this._engine.onResizeObservable.add((()=>{this.build()})))}getClassName(){return"NodeRenderGraph"}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e){if(t)return Ue.S0.Warn("More than one block was found with the name `"+e+"`"),t;t=i}return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getBlocksByPredicate(e){const t=[];for(const i of this.attachedBlocks)e(i)&&t.push(i);return t}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}edit(e){return new Promise((t=>{if(this.BJSNODERENDERGRAPHEDITOR=this.BJSNODERENDERGRAPHEDITOR||this._getGlobalNodeRenderGraphEditor(),void 0===this.BJSNODERENDERGRAPHEDITOR){const i=e&&e.editorURL?e.editorURL:o_.EditorURL;Ue.S0.LoadBabylonScript(i,(()=>{this.BJSNODERENDERGRAPHEDITOR=this.BJSNODERENDERGRAPHEDITOR||this._getGlobalNodeRenderGraphEditor(),this._createNodeEditor(e?.nodeRenderGraphEditorConfig),t()}))}else this._createNodeEditor(e?.nodeRenderGraphEditorConfig),t()}))}_createNodeEditor(e){const t={nodeRenderGraph:this,...e};this.BJSNODERENDERGRAPHEDITOR.NodeRenderGraphEditor.Show(t)}build(){if(!this.outputBlock)throw new Error("You must define the outputBlock property before building the node render graph");this._initializeBlock(this.outputBlock),this._frameGraph.clear();const e=new n_;e.buildId=this._buildId,e.verbose=this._options.verbose,this._options.autoFillExternalInputs&&this._autoFillExternalInputs(),this.outputBlock.build(e),this._frameGraph.build(),this._buildId=o_._BuildIdGenerator++,e.emitErrors(this.onBuildErrorObservable)&&this.onBuildObservable.notifyObservers(this)}_autoFillExternalInputs(){const e=this.getInputBlocks();let t=0;for(const i of e)if(i.isExternal&&i.isAnAncestorOfType("NodeRenderGraphOutputBlock"))if(i.type&Rp.TextureAllButBackBuffer);else if(i.isCamera()){const e=this._scene.cameras[t++]||this._scene.cameras[0];this._scene.cameraToUseForPointers||(this._scene.cameraToUseForPointers=e),i.value=e}else i.isObjectList()&&(i.value={meshes:this._scene.meshes,particleSystems:this._scene.particleSystems})}whenReadyAsync(e=16){return this._frameGraph.whenReadyAsync(e)}execute(){this._frameGraph.execute()}_initializeBlock(e){e.initialize(),this._options.autoConfigure&&e.autoConfigure(),-1===this.attachedBlocks.indexOf(e)&&this.attachedBlocks.push(e);for(const t of e.inputs){const i=t.connectedPoint;if(i){const t=i.ownerBlock;t!==e&&this._initializeBlock(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 t of e.blocks){const e=(0,X.n9)(t.customType);if(e){const r=t.additionalConstructionParameters,s=r?new e("",this._frameGraph,this._scene,...r):new e("",this._frameGraph,this._scene);s._deserialize(t),i[t.id]=s,this.attachedBlocks.push(s)}}for(const e of this.attachedBlocks)if(e.isTeleportOut){const t=e,r=t._tempEntryPointUniqueId;if(r){const e=i[r];e&&e.attachToEndpoint(t)}}for(let r=0;re.targetConnectionName))&&!t||this._restoreConnections(n,e,i))}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){const r=e.locations||e.editorData.locations;for(const e of r)i[e.blockId]&&(e.blockId=i[e.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&r.concat(this.editorData.locations),e.locations?this.editorData={locations:r}:(this.editorData=e.editorData,this.editorData.locations=r);const s=[];for(const e in i)s[e]=i[e].uniqueId;this.editorData.map=s}this.comment=e.comment}_restoreConnections(e,t,i){for(const r of e.outputs)for(const s of t.blocks){const n=i[s.id];if(n)for(const o of s.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==r.name);else{const e=n.getInputByName(o.inputName);if(!e||e.isConnected)continue;r.connectTo(e,!0),this._restoreConnections(n,t,i)}}}generateCode(){let e=[];const t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);const r=JSON.stringify(this._options);let s=`let nodeRenderGraph = new BABYLON.NodeRenderGraph("${this.name||"render graph"}", scene, ${r});\n`;for(const r of t)r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e)+"\n");return this.outputBlock&&(e=[],s+="// Connections\n",s+=this.outputBlock._dumpCodeForOutputConnections(e),s+="// Output nodes\n",s+=`nodeRenderGraph.outputBlock = ${this.outputBlock._codeVariableName};\n`,s+="nodeRenderGraph.build();\n"),s}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const r=i.connectedPoint;if(r){const i=r.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}setToDefault(){this.clear(),this.editorData=null;const e=new i_("BackBuffer color",this._frameGraph,this._scene,Rp.TextureBackBuffer),t=new s_("Clear",this._frameGraph,this._scene);e.output.connectTo(t.texture);const i=new Gp("Output",this._frameGraph,this._scene);t.output.connectTo(i.texture),this.outputBlock=i}clone(e){const t=this.serialize(),i=it.p.Clone((()=>new o_(e,this._scene)),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(),i}serialize(e){const t=e?{}:it.p.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];e?i=e:(t.customType="BABYLON.NodeRenderGraph",this.outputBlock&&(t.outputNodeId=this.outputBlock.uniqueId)),t.blocks=[];for(const e of i)t.blocks.push(e.serialize());if(!e)for(const e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}dispose(){for(const e of this.attachedBlocks)e.dispose();this._frameGraph.dispose(),this._frameGraph=void 0,this._engine.onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null,this.attachedBlocks.length=0,this.onBuildObservable.clear(),this.onBuildErrorObservable.clear()}static CreateDefault(e,t,i){const r=new o_(e,t,i);return r.setToDefault(),r.build(),r}static Parse(e,t,i,r=!0){const s=it.p.Parse((()=>new o_(e.name,t,i)),e,null);return s.parseSerializedObject(e),r||s.build(),s}static ParseFromSnippetAsync(e,t,i,r,s=!0){return"_BLANK"===e?Promise.resolve(o_.CreateDefault("blank",t,i)):new Promise(((n,o)=>{const a=new go.u;a.addEventListener("readystatechange",(()=>{if(4==a.readyState)if(200==a.status){const l=JSON.parse(JSON.parse(a.responseText).jsonPayload),h=JSON.parse(l.nodeRenderGraph);r||(r=it.p.Parse((()=>new o_(e,t,i)),h,null)),r.parseSerializedObject(h),r.snippetId=e;try{s||r.build(),n(r)}catch(e){o(e)}}else o("Unable to load the snippet "+e)})),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()}))}}o_._BuildIdGenerator=0,o_.EditorURL=`${Ue.S0._DefaultCdnUrl}/v${an.Version}/NodeRenderGraph/babylon.nodeRenderGraph.js`,o_.SnippetUrl="https://snippet.babylonjs.com",(0,je.Cg)([(0,$e.lK)()],o_.prototype,"name",void 0),(0,je.Cg)([(0,$e.lK)("comment")],o_.prototype,"comment",void 0);class a_ extends wp{constructor(e,t,i){super(e,t,i),this.registerInput("input",Rp.AutoDetect),this.registerOutput("output",Rp.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NodeRenderGraphElbowBlock"}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];this._propagateInputValueToOutput(i,t)}}(0,X.Y5)("BABYLON.NodeRenderGraphElbowBlock",a_);class l_ extends Yp.${_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(i.bind(i,31162)))):t.push(Promise.resolve().then(i.bind(i,27897)))}constructor(e,t=null,i){super({...i,name:e,engine:t||an.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:l_.FragmentUrl,uniforms:l_.Uniforms}),this.degree=1}bind(){super.bind(),this._drawWrapper.effect.setFloat("degree",this.degree)}}l_.FragmentUrl="blackAndWhite",l_.Uniforms=["degree"];class h_ extends kp{constructor(e,t,i){super(e,t),this.sourceSamplingMode=2,this.postProcess=i,this._postProcessDrawWrapper=this.postProcess.drawWrapper,this.outputTexture=this._frameGraph.createDanglingHandle()}isReady(){return this.postProcess.isReady()}record(e=!1,t,i){if(void 0===this.sourceTexture)throw new Error(`FrameGraphPostProcessTask "${this.name}": sourceTexture is required`);const r=this._frameGraph.getTextureCreationOptions(this.sourceTexture,!0);r.options.generateDepthBuffer=!1,r.options.generateStencilBuffer=!1,r.options.samples=1,this._frameGraph.resolveDanglingHandle(this.outputTexture,this.destinationTexture,this.name,r);const s=this._frameGraph.getTextureDescription(this.outputTexture);this._outputWidth=s.size.width,this._outputHeight=s.size.height;const n=this._frameGraph.addRenderPass(this.name);if(n.useTexture(this.sourceTexture),n.setRenderTarget(this.outputTexture),n.setExecuteFunc((e=>{e.setTextureSamplingMode(this.sourceTexture,this.sourceSamplingMode),t?.(e),e.applyFullScreenEffect(this._postProcessDrawWrapper,(()=>{e.bindTextureHandle(this._postProcessDrawWrapper.effect,"textureSampler",this.sourceTexture),i?.(e),this.postProcess.bind()}))})),!e){const e=this._frameGraph.addRenderPass(this.name+"_disabled",!0);e.setRenderTarget(this.outputTexture),e.setExecuteFunc((e=>{e.copyTexture(this.sourceTexture)}))}return n}dispose(){this.postProcess.dispose(),super.dispose()}}class c_ extends h_{constructor(e,t,i){super(e,t,i||new l_(e,t.engine))}}class u_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i){super(e,t,i),this.registerInput("source",Rp.Texture),this.registerInput("destination",Rp.Texture,!0),this.registerOutput("output",Rp.BasedOnInput),this.source.addAcceptedConnectionPointTypes(Rp.TextureAllButBackBuffer),this.destination.addAcceptedConnectionPointTypes(Rp.TextureAll),this.output._typeConnectionSource=()=>this.destination.isConnected?this.destination:this.source,this._frameGraphTask=new c_(this.name,t,new l_(e,i.getEngine()))}get sourceSamplingMode(){return this._frameGraphTask.sourceSamplingMode}set sourceSamplingMode(e){this._frameGraphTask.sourceSamplingMode=e}get degree(){return this._frameGraphTask.postProcess.degree}set degree(e){this._frameGraphTask.postProcess.degree=e}getClassName(){return"NodeRenderGraphBlackAndWhitePostProcessBlock"}get source(){return this._inputs[0]}get destination(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this.output.value=this._frameGraphTask.outputTexture;const t=this.source.connectedPoint;t&&(this._frameGraphTask.sourceTexture=t.value);const i=this.destination.connectedPoint;i&&(this._frameGraphTask.destinationTexture=i.value)}_dumpPropertiesCode(){const e=[];return e.push(`${this._codeVariableName}.degree = ${this.degree};`),e.push(`${this._codeVariableName}.sourceSamplingMode = ${this.sourceSamplingMode};`),super._dumpPropertiesCode()+e.join("\n")}serialize(){const e=super.serialize();return e.degree=this.degree,e.sourceSamplingMode=this.sourceSamplingMode,e}_deserialize(e){super._deserialize(e),this.degree=e.degree,this.sourceSamplingMode=e.sourceSamplingMode}}(0,je.Cg)([t_("Source sampling mode",6,"PROPERTIES")],u_.prototype,"sourceSamplingMode",null),(0,je.Cg)([t_("Degree",1,"PROPERTIES",{min:0,max:1})],u_.prototype,"degree",null),(0,X.Y5)("BABYLON.NodeRenderGraphBlackAndWhitePostProcessBlock",u_);class d_ extends Yp.${_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(i.bind(i,63186)))):t.push(Promise.resolve().then(i.bind(i,94811)))}constructor(e,t=null,i){super({...i,name:e,engine:t||an.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:d_.FragmentUrl,uniforms:d_.Uniforms,samplers:d_.Samplers}),this.weight=1}bind(){super.bind(),this._drawWrapper.effect.setFloat("bloomWeight",this.weight)}}d_.FragmentUrl="bloomMerge",d_.Uniforms=["bloomWeight"],d_.Samplers=["bloomBlur"];class f_ extends h_{constructor(e,t,i){super(e,t,i||new d_(e,t.engine))}record(e=!1){if(void 0===this.sourceTexture||void 0===this.blurTexture)throw new Error(`FrameGraphBloomMergeTask "${this.name}": sourceTexture and blurTexture are required`);const t=super.record(e,void 0,(e=>{e.bindTextureHandle(this._postProcessDrawWrapper.effect,"bloomBlur",this.blurTexture)}));return t.useTexture(this.blurTexture),t}}class p_ extends Yp.${_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,56558)),Promise.resolve().then(i.bind(i,42876))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,45245)),Promise.resolve().then(i.bind(i,95527))]))}constructor(e,t=null,i,r,s){const n=!!s?.blockCompilation;super({...s,name:e,engine:t||an.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:p_.FragmentUrl,uniforms:p_.Uniforms,samplers:p_.Samplers,vertexUrl:p_.VertexUrl,blockCompilation:!0}),this._packedFloat=!1,this._staticDefines="",this.textureWidth=0,this.textureHeight=0,this.options.blockCompilation=n,void 0!==i&&(this.direction=i),void 0!==r&&(this.kernel=r)}set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this.options.blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this.options.blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}bind(){super.bind(),this._drawWrapper.effect.setFloat2("delta",1/this.textureWidth*this.direction.x,1/this.textureHeight*this.direction.y)}_updateParameters(e,t){const i=this._kernel,r=(i-1)/2;let s=[],n=[],o=0;for(let e=0;e0)return Math.max(e,3);return Math.max(t,3)}_gaussianWeight(e){const t=1/3,i=-e*e/(2*t*t);return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(i)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}}p_.VertexUrl="kernelBlur",p_.FragmentUrl="kernelBlur",p_.Uniforms=["delta","direction"],p_.Samplers=["circleOfConfusionSampler"];class __ extends Yp.${_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(i.bind(i,9574)))):t.push(Promise.resolve().then(i.bind(i,83062)))}constructor(e,t=null,i){super({...i,name:e,engine:t||an.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:__.FragmentUrl,uniforms:__.Uniforms}),this.threshold=.9,this._exposure=1}bind(){super.bind();const e=this._drawWrapper.effect;e.setFloat("threshold",Math.pow(this.threshold,lt.rv)),e.setFloat("exposure",this._exposure)}}__.FragmentUrl="extractHighlights",__.Uniforms=["threshold","exposure"];class m_{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.scale}set kernel(e){this._blurX.kernel=e*this.scale,this._blurY.kernel=e*this.scale}constructor(e,t,i,r=!1){this.scale=i,this._downscale=new __(e+"_downscale",t,{blockCompilation:r}),this._blurX=new p_(e+"_blurX",t,new W.I9(1,0),10,{blockCompilation:r}),this._blurY=new p_(e+"_blurY",t,new W.I9(0,1),10,{blockCompilation:r}),this._merge=new d_(e+"_merge",t,{blockCompilation:r})}isReady(){return this._downscale.isReady()&&this._blurX.isReady()&&this._blurY.isReady()&&this._merge.isReady()}}class g_ extends h_{constructor(e,t,i){super(e,t,i||new __(e,t.engine))}}class v_ extends h_{constructor(e,t,i){super(e,t,i||new p_(e,t.engine,new W.I9(1,0),10))}record(e=!1,t,i){const r=super.record(e,t,i);return this.postProcess.textureWidth=this._outputWidth,this.postProcess.textureHeight=this._outputHeight,r}}class x_ extends kp{constructor(e,t,i,r,s,n,o=!1,a=.5){if(super(e,t),this.sourceSamplingMode=2,this.hdr=o,this._defaultPipelineTextureType=0,o){const e=i.getCaps();e.textureHalfFloatRender?this._defaultPipelineTextureType=2:e.textureFloatRender&&(this._defaultPipelineTextureType=1)}this.bloom=new m_(e,i,a),this.bloom.threshold=n,this.bloom.kernel=s,this.bloom.weight=r,this._downscale=new g_(`${e} Downscale`,this._frameGraph,this.bloom._downscale),this._blurX=new v_(`${e} Blur X`,this._frameGraph,this.bloom._blurX),this._blurY=new v_(`${e} Blur Y`,this._frameGraph,this.bloom._blurY),this._merge=new f_(`${e} Merge`,this._frameGraph,this.bloom._merge),this.outputTexture=this._frameGraph.createDanglingHandle()}isReady(){return this.bloom.isReady()}record(){if(void 0===this.sourceTexture)throw new Error("FrameGraphBloomTask: sourceTexture is required");const e=this._frameGraph.getTextureDescription(this.sourceTexture),t={size:{width:Math.floor(e.size.width*this.bloom.scale),height:Math.floor(e.size.height*this.bloom.scale)},options:{createMipMaps:!1,generateMipMaps:!1,types:[this._defaultPipelineTextureType],samplingModes:[2],formats:[5],samples:1,useSRGBBuffers:[!1],generateDepthBuffer:!1,generateStencilBuffer:!1,label:""},sizeIsPercentage:!1},i=this._frameGraph.createRenderTargetTexture(this._downscale.name,t);this._downscale.sourceTexture=this.sourceTexture,this._downscale.sourceSamplingMode=2,this._downscale.destinationTexture=i,this._downscale.record(!0);const r=this._frameGraph.createRenderTargetTexture(this._blurX.name,t);this._blurX.sourceTexture=i,this._blurX.sourceSamplingMode=2,this._blurX.destinationTexture=r,this._blurX.record(!0);const s=this._frameGraph.createRenderTargetTexture(this._blurY.name,t);this._blurY.sourceTexture=r,this._blurY.sourceSamplingMode=2,this._blurY.destinationTexture=s,this._blurY.record(!0);const n=this._frameGraph.getTextureCreationOptions(this.sourceTexture,!0);n.options.generateDepthBuffer=!1,n.options.generateStencilBuffer=!1,this._frameGraph.resolveDanglingHandle(this.outputTexture,this.destinationTexture,this._merge.name,n),this._merge.sourceTexture=this.sourceTexture,this._merge.sourceSamplingMode=this.sourceSamplingMode,this._merge.blurTexture=s,this._merge.destinationTexture=this.outputTexture,this._merge.record(!0);const o=this._frameGraph.addRenderPass(this.name+"_disabled",!0);o.setRenderTarget(this.outputTexture),o.setExecuteFunc((e=>{e.copyTexture(this.sourceTexture)}))}dispose(){this._downscale.dispose(),this._blurX.dispose(),this._blurY.dispose(),this._merge.dispose(),super.dispose()}}class b_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i,r=!1,s=.5){super(e,t,i),this._additionalConstructionParameters=[r,s],this.registerInput("source",Rp.Texture),this.registerInput("destination",Rp.Texture,!0),this.registerOutput("output",Rp.BasedOnInput),this.source.addAcceptedConnectionPointTypes(Rp.TextureAllButBackBuffer),this.destination.addAcceptedConnectionPointTypes(Rp.TextureAll),this.output._typeConnectionSource=()=>this.destination.isConnected?this.destination:this.source,this._frameGraphTask=new x_(this.name,t,i.getEngine(),.75,64,.2,r,s)}_createTask(e,t){const i=this._frameGraphTask.sourceSamplingMode,r=this._frameGraphTask.bloom.threshold,s=this._frameGraphTask.bloom.weight,n=this._frameGraphTask.bloom.kernel;this._frameGraphTask.dispose(),this._frameGraphTask=new x_(this.name,this._frameGraph,this._scene.getEngine(),s,n,r,t,e),this._frameGraphTask.sourceSamplingMode=i,this._additionalConstructionParameters=[t,e]}get bloomScale(){return this._frameGraphTask.bloom.scale}set bloomScale(e){this._createTask(e,this._frameGraphTask.hdr)}get hdr(){return this._frameGraphTask.hdr}set hdr(e){this._createTask(this._frameGraphTask.bloom.scale,e)}get sourceSamplingMode(){return this._frameGraphTask.sourceSamplingMode}set sourceSamplingMode(e){this._frameGraphTask.sourceSamplingMode=e}get threshold(){return this._frameGraphTask.bloom.threshold}set threshold(e){this._frameGraphTask.bloom.threshold=e}get weight(){return this._frameGraphTask.bloom.weight}set weight(e){this._frameGraphTask.bloom.weight=e}get kernel(){return this._frameGraphTask.bloom.kernel}set kernel(e){this._frameGraphTask.bloom.kernel=e}getClassName(){return"NodeRenderGraphBloomPostProcessBlock"}get source(){return this._inputs[0]}get destination(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this.output.value=this._frameGraphTask.outputTexture;const t=this.source.connectedPoint;t&&(this._frameGraphTask.sourceTexture=t.value);const i=this.destination.connectedPoint;i&&(this._frameGraphTask.destinationTexture=i.value)}_dumpPropertiesCode(){const e=[];return e.push(`${this._codeVariableName}.threshold = ${this.threshold};`),e.push(`${this._codeVariableName}.weight = ${this.weight};`),e.push(`${this._codeVariableName}.kernel = ${this.kernel};`),e.push(`${this._codeVariableName}.sourceSamplingMode = ${this.sourceSamplingMode};`),super._dumpPropertiesCode()+e.join("\n")}serialize(){const e=super.serialize();return e.threshold=this.threshold,e.weight=this.weight,e.kernel=this.kernel,e.sourceSamplingMode=this.sourceSamplingMode,e}_deserialize(e){super._deserialize(e),this.threshold=e.threshold,this.weight=e.weight,this.kernel=e.kernel,this.sourceSamplingMode=e.sourceSamplingMode}}(0,je.Cg)([t_("Bloom scale",1,"PROPERTIES")],b_.prototype,"bloomScale",null),(0,je.Cg)([t_("HDR",0,"PROPERTIES")],b_.prototype,"hdr",null),(0,je.Cg)([t_("Source sampling mode",6)],b_.prototype,"sourceSamplingMode",null),(0,je.Cg)([t_("Threshold",1,"PROPERTIES",{min:0,max:2})],b_.prototype,"threshold",null),(0,je.Cg)([t_("Weight",1,"PROPERTIES",{min:0,max:3})],b_.prototype,"weight",null),(0,je.Cg)([t_("Kernel",2,"PROPERTIES",{min:1,max:128})],b_.prototype,"kernel",null),(0,X.Y5)("BABYLON.NodeRenderGraphBloomPostProcessBlock",b_);class S_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i){super(e,t,i),this.registerInput("source",Rp.Texture),this.registerInput("destination",Rp.Texture,!0),this.registerOutput("output",Rp.BasedOnInput),this.source.addAcceptedConnectionPointTypes(Rp.TextureAllButBackBuffer),this.destination.addAcceptedConnectionPointTypes(Rp.TextureAll),this.output._typeConnectionSource=()=>this.destination.isConnected?this.destination:this.source,this._frameGraphTask=new v_(this.name,t,new p_(e,i.getEngine(),new W.I9(1,0),32))}get sourceSamplingMode(){return this._frameGraphTask.sourceSamplingMode}set sourceSamplingMode(e){this._frameGraphTask.sourceSamplingMode=e}get direction(){return this._frameGraphTask.postProcess.direction}set direction(e){this._frameGraphTask.postProcess.direction=e}get kernel(){return this._frameGraphTask.postProcess.kernel}set kernel(e){this._frameGraphTask.postProcess.kernel=e}getClassName(){return"NodeRenderGraphBlurPostProcessBlock"}get source(){return this._inputs[0]}get destination(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this.output.value=this._frameGraphTask.outputTexture;const t=this.source.connectedPoint;t&&(this._frameGraphTask.sourceTexture=t.value);const i=this.destination.connectedPoint;i&&(this._frameGraphTask.destinationTexture=i.value)}_dumpPropertiesCode(){const e=[];return e.push(`${this._codeVariableName}.direction = new BABYLON.Vector2(${this.direction.x}, ${this.direction.y});`),e.push(`${this._codeVariableName}.kernel = ${this.kernel};`),e.push(`${this._codeVariableName}.sourceSamplingMode = ${this.sourceSamplingMode};`),super._dumpPropertiesCode()+e.join("\n")}serialize(){const e=super.serialize();return e.direction=this.direction.asArray(),e.kernel=this.kernel,e.sourceSamplingMode=this.sourceSamplingMode,e}_deserialize(e){super._deserialize(e),this.direction.fromArray(e.direction),this.kernel=e.kernel,this.sourceSamplingMode=e.sourceSamplingMode}}(0,je.Cg)([t_("Source sampling mode",6,"PROPERTIES")],S_.prototype,"sourceSamplingMode",null),(0,je.Cg)([t_("Direction",3,"PROPERTIES")],S_.prototype,"direction",null),(0,je.Cg)([t_("Kernel",2,"PROPERTIES",{min:1,max:256})],S_.prototype,"kernel",null),(0,X.Y5)("BABYLON.NodeRenderGraphBlurPostProcessBlock",S_);class T_ extends Yp.${_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(i.bind(i,89328)))):t.push(Promise.resolve().then(i.bind(i,29743)))}constructor(e,t=null,i){super({...i,name:e,engine:t||an.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:T_.FragmentUrl,uniforms:T_.Uniforms,samplers:T_.Samplers,defines:i?.depthNotNormalized?T_.DefinesDepthNotNormalized:void 0}),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50}bind(){super.bind();const e=this.options,t=this._drawWrapper.effect;e.depthNotNormalized||t.setFloat2("cameraMinMaxZ",this.camera.minZ,this.camera.maxZ-this.camera.minZ);const i=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);t.setFloat("focusDistance",this.focusDistance),t.setFloat("cocPrecalculation",i)}}T_.FragmentUrl="circleOfConfusion",T_.Uniforms=["cameraMinMaxZ","focusDistance","cocPrecalculation"],T_.Samplers=["depthSampler"],T_.DefinesDepthNotNormalized="#define COC_DEPTH_NOT_NORMALIZED";class C_ extends h_{constructor(e,t,i){super(e,t,i||new T_(e,t.engine)),this.depthSamplingMode=2}record(e=!1){if(void 0===this.sourceTexture||void 0===this.depthTexture||void 0===this.camera)throw new Error(`FrameGraphCircleOfConfusionTask "${this.name}": sourceTexture, depthTexture and camera are required`);const t=super.record(e,(e=>{e.setTextureSamplingMode(this.depthTexture,this.depthSamplingMode)}),(e=>{this.postProcess.camera=this.camera,e.bindTextureHandle(this._postProcessDrawWrapper.effect,"depthSampler",this.depthTexture)}));return t.useTexture(this.depthTexture),t}}class y_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i){super(e,t,i),this.registerInput("source",Rp.Texture),this.registerInput("geomViewDepth",Rp.TextureViewDepth),this.registerInput("destination",Rp.Texture,!0),this.registerInput("camera",Rp.Camera),this.registerOutput("output",Rp.BasedOnInput),this.source.addAcceptedConnectionPointTypes(Rp.TextureAllButBackBuffer),this.destination.addAcceptedConnectionPointTypes(Rp.TextureAll),this.output._typeConnectionSource=()=>this.destination.isConnected?this.destination:this.source,this._frameGraphTask=new C_(this.name,t,new T_(e,i.getEngine(),{depthNotNormalized:!0}))}get sourceSamplingMode(){return this._frameGraphTask.sourceSamplingMode}set sourceSamplingMode(e){this._frameGraphTask.sourceSamplingMode=e}get depthSamplingMode(){return this._frameGraphTask.depthSamplingMode}set depthSamplingMode(e){this._frameGraphTask.depthSamplingMode=e}get lensSize(){return this._frameGraphTask.postProcess.lensSize}set lensSize(e){this._frameGraphTask.postProcess.lensSize=e}get fStop(){return this._frameGraphTask.postProcess.fStop}set fStop(e){this._frameGraphTask.postProcess.fStop=e}get focusDistance(){return this._frameGraphTask.postProcess.focusDistance}set focusDistance(e){this._frameGraphTask.postProcess.focusDistance=e}get focalLength(){return this._frameGraphTask.postProcess.focalLength}set focalLength(e){this._frameGraphTask.postProcess.focalLength=e}getClassName(){return"NodeRenderGraphCircleOfConfusionPostProcessBlock"}get source(){return this._inputs[0]}get geomViewDepth(){return this._inputs[1]}get destination(){return this._inputs[2]}get camera(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this.output.value=this._frameGraphTask.outputTexture;const t=this.source.connectedPoint;t&&(this._frameGraphTask.sourceTexture=t.value);const i=this.geomViewDepth.connectedPoint;i&&(this._frameGraphTask.depthTexture=i.value);const r=this.destination.connectedPoint;r&&(this._frameGraphTask.destinationTexture=r.value);const s=this.camera.connectedPoint;s&&(this._frameGraphTask.camera=s.value)}_dumpPropertiesCode(){const e=[];return e.push(`${this._codeVariableName}.lensSize = ${this.lensSize};`),e.push(`${this._codeVariableName}.fStop = ${this.fStop};`),e.push(`${this._codeVariableName}.focusDistance = ${this.focusDistance};`),e.push(`${this._codeVariableName}.focalLength = ${this.focalLength};`),e.push(`${this._codeVariableName}.sourceSamplingMode = ${this.sourceSamplingMode};`),e.push(`${this._codeVariableName}.depthSamplingMode = ${this.depthSamplingMode};`),super._dumpPropertiesCode()+e.join("\n")}serialize(){const e=super.serialize();return e.lensSize=this.lensSize,e.fStop=this.fStop,e.focusDistance=this.focusDistance,e.focalLength=this.focalLength,e.sourceSamplingMode=this.sourceSamplingMode,e.depthSamplingMode=this.depthSamplingMode,e}_deserialize(e){super._deserialize(e),this.lensSize=e.lensSize,this.fStop=e.fStop,this.focusDistance=e.focusDistance,this.focalLength=e.focalLength,this.sourceSamplingMode=e.sourceSamplingMode,this.depthSamplingMode=e.depthSamplingMode}}(0,je.Cg)([t_("Source sampling mode",6,"PROPERTIES")],y_.prototype,"sourceSamplingMode",null),(0,je.Cg)([t_("Depth sampling mode",6,"PROPERTIES")],y_.prototype,"depthSamplingMode",null),(0,je.Cg)([t_("Lens size",1,"PROPERTIES")],y_.prototype,"lensSize",null),(0,je.Cg)([t_("F-Stop",1,"PROPERTIES")],y_.prototype,"fStop",null),(0,je.Cg)([t_("Focus distance",1,"PROPERTIES")],y_.prototype,"focusDistance",null),(0,je.Cg)([t_("Focal length",1,"PROPERTIES")],y_.prototype,"focalLength",null),(0,X.Y5)("BABYLON.NodeRenderGraphCircleOfConfusionPostProcessBlock",y_);class E_ extends Yp.${_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(i.bind(i,41289)))):t.push(Promise.resolve().then(i.bind(i,95610)))}constructor(e,t=null,i){super({...i,name:e,engine:t||an.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:E_.FragmentUrl,samplers:E_.Samplers})}}E_.FragmentUrl="depthOfFieldMerge",E_.Samplers=["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"];class P_ extends h_{constructor(e,t,i){super(e,t,i||new E_(e,t.engine)),this.blurSteps=[]}record(e=!1){if(void 0===this.sourceTexture||void 0===this.circleOfConfusionTexture||0===this.blurSteps.length)throw new Error(`FrameGraphBloomMergeTask "${this.name}": sourceTexture, circleOfConfusionTexture and blurSteps are required`);this.postProcess.updateEffect("#define BLUR_LEVEL "+(this.blurSteps.length-1)+"\n");const t=super.record(e,void 0,(e=>{e.bindTextureHandle(this._postProcessDrawWrapper.effect,"circleOfConfusionSampler",this.circleOfConfusionTexture),this.blurSteps.forEach(((t,i)=>{e.bindTextureHandle(this._postProcessDrawWrapper.effect,"blurStep"+(this.blurSteps.length-i-1),t)}))}));t.useTexture(this.circleOfConfusionTexture);for(const e of this.blurSteps)t.useTexture(e);return t}}class A_ extends p_{constructor(e,t=null,i,r,s){super(e,t,i,r,{...s,defines:"#define DOF 1\n"})}}class R_ extends v_{constructor(e,t,i){super(e,t,i||new A_(e,t.engine,new W.I9(1,0),10)),this.circleOfConfusionSamplingMode=2}record(e=!1){if(void 0===this.sourceTexture||void 0===this.circleOfConfusionTexture)throw new Error(`FrameGraphDepthOfFieldBlurTask "${this.name}": sourceTexture and circleOfConfusionTexture are required`);const t=super.record(e,(e=>{e.setTextureSamplingMode(this.circleOfConfusionTexture,this.circleOfConfusionSamplingMode)}),(e=>{e.bindTextureHandle(this._postProcessDrawWrapper.effect,"circleOfConfusionSampler",this.circleOfConfusionTexture)}));return t.useTexture(this.circleOfConfusionTexture),t}}!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(qp||(qp={}));class I_{set focalLength(e){this._circleOfConfusion.focalLength=e}get focalLength(){return this._circleOfConfusion.focalLength}set fStop(e){this._circleOfConfusion.fStop=e}get fStop(){return this._circleOfConfusion.fStop}set focusDistance(e){this._circleOfConfusion.focusDistance=e}get focusDistance(){return this._circleOfConfusion.focusDistance}set lensSize(e){this._circleOfConfusion.lensSize=e}get lensSize(){return this._circleOfConfusion.lensSize}constructor(e,t,i=0,r=!1,s=!1){this._depthOfFieldBlurX=[],this._depthOfFieldBlurY=[],this._circleOfConfusion=new T_(e,t,{depthNotNormalized:r,blockCompilation:s}),this.blurLevel=i;let n=1,o=15;switch(i){case 2:n=3,o=51;break;case 1:n=2,o=31;break;default:o=15,n=1}const a=o/Math.pow(2,n-1);let l=1;for(let i=0;i1?6:5,r={size:t,options:{createMipMaps:!1,generateMipMaps:!1,types:[this._defaultPipelineTextureType],formats:[i],samples:1,useSRGBBuffers:[!1],generateDepthBuffer:!1,generateStencilBuffer:!1,label:""},sizeIsPercentage:!1},s=this._frameGraph.createRenderTargetTexture(this._circleOfConfusion.name,r);this._circleOfConfusion.sourceTexture=this.sourceTexture,this._circleOfConfusion.depthTexture=this.depthTexture,this._circleOfConfusion.depthSamplingMode=this.depthSamplingMode,this._circleOfConfusion.camera=this.camera,this._circleOfConfusion.destinationTexture=s,this._circleOfConfusion.record(!0),r.options.formats=[5];const n=[];for(let i=0;i{e.copyTexture(this.sourceTexture)}))}dispose(){this._circleOfConfusion.dispose();for(let e=0;ethis.destination.isConnected?this.destination:this.source,this._frameGraphTask=new M_(this.name,t,i.getEngine(),r,s)}_createTask(e,t){const i=this._frameGraphTask.sourceSamplingMode,r=this._frameGraphTask.depthSamplingMode,s=this._frameGraphTask.depthOfField.focalLength,n=this._frameGraphTask.depthOfField.fStop,o=this._frameGraphTask.depthOfField.focusDistance,a=this._frameGraphTask.depthOfField.lensSize;this._frameGraphTask.dispose(),this._frameGraphTask=new M_(this.name,this._frameGraph,this._scene.getEngine(),e,t),this._frameGraphTask.sourceSamplingMode=i,this._frameGraphTask.depthSamplingMode=r,this._frameGraphTask.depthOfField.focalLength=s,this._frameGraphTask.depthOfField.fStop=n,this._frameGraphTask.depthOfField.focusDistance=o,this._frameGraphTask.depthOfField.lensSize=a,this._additionalConstructionParameters=[e,t]}get blurLevel(){return this._frameGraphTask.depthOfField.blurLevel}set blurLevel(e){this._createTask(e,this._frameGraphTask.hdr)}get hdr(){return this._frameGraphTask.hdr}set hdr(e){this._createTask(this._frameGraphTask.depthOfField.blurLevel,e)}get sourceSamplingMode(){return this._frameGraphTask.sourceSamplingMode}set sourceSamplingMode(e){this._frameGraphTask.sourceSamplingMode=e}get depthSamplingMode(){return this._frameGraphTask.depthSamplingMode}set depthSamplingMode(e){this._frameGraphTask.depthSamplingMode=e}get focalLength(){return this._frameGraphTask.depthOfField.focalLength}set focalLength(e){this._frameGraphTask.depthOfField.focalLength=e}get fStop(){return this._frameGraphTask.depthOfField.fStop}set fStop(e){this._frameGraphTask.depthOfField.fStop=e}get focusDistance(){return this._frameGraphTask.depthOfField.focusDistance}set focusDistance(e){this._frameGraphTask.depthOfField.focusDistance=e}get lensSize(){return this._frameGraphTask.depthOfField.lensSize}set lensSize(e){this._frameGraphTask.depthOfField.lensSize=e}getClassName(){return"NodeRenderGraphDepthOfFieldPostProcessBlock"}get source(){return this._inputs[0]}get geomViewDepth(){return this._inputs[1]}get destination(){return this._inputs[2]}get camera(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this.output.value=this._frameGraphTask.outputTexture;const t=this.source.connectedPoint;t&&(this._frameGraphTask.sourceTexture=t.value);const i=this.geomViewDepth.connectedPoint;i&&(this._frameGraphTask.depthTexture=i.value);const r=this.destination.connectedPoint;r&&(this._frameGraphTask.destinationTexture=r.value);const s=this.camera.connectedPoint;s&&(this._frameGraphTask.camera=s.value)}_dumpPropertiesCode(){const e=[];return e.push(`${this._codeVariableName}.lensSize = ${this.lensSize};`),e.push(`${this._codeVariableName}.fStop = ${this.fStop};`),e.push(`${this._codeVariableName}.focusDistance = ${this.focusDistance};`),e.push(`${this._codeVariableName}.focalLength = ${this.focalLength};`),e.push(`${this._codeVariableName}.sourceSamplingMode = ${this.sourceSamplingMode};`),e.push(`${this._codeVariableName}.depthSamplingMode = ${this.depthSamplingMode};`),super._dumpPropertiesCode()+e.join("\n")}serialize(){const e=super.serialize();return e.lensSize=this.lensSize,e.fStop=this.fStop,e.focusDistance=this.focusDistance,e.focalLength=this.focalLength,e.sourceSamplingMode=this.sourceSamplingMode,e.depthSamplingMode=this.depthSamplingMode,e}_deserialize(e){super._deserialize(e),this.lensSize=e.lensSize,this.fStop=e.fStop,this.focusDistance=e.focusDistance,this.focalLength=e.focalLength,this.sourceSamplingMode=e.sourceSamplingMode,this.depthSamplingMode=e.depthSamplingMode}}(0,je.Cg)([t_("Blur level",4,"PROPERTIES",{options:[{label:"Low",value:0},{label:"Medium",value:1},{label:"High",value:2}]})],O_.prototype,"blurLevel",null),(0,je.Cg)([t_("HDR",0,"PROPERTIES")],O_.prototype,"hdr",null),(0,je.Cg)([t_("Source sampling mode",6,"PROPERTIES")],O_.prototype,"sourceSamplingMode",null),(0,je.Cg)([t_("Depth sampling mode",6,"PROPERTIES")],O_.prototype,"depthSamplingMode",null),(0,je.Cg)([t_("Focal length",1,"PROPERTIES")],O_.prototype,"focalLength",null),(0,je.Cg)([t_("F-Stop",1,"PROPERTIES")],O_.prototype,"fStop",null),(0,je.Cg)([t_("Focus distance",1,"PROPERTIES")],O_.prototype,"focusDistance",null),(0,je.Cg)([t_("Lens size",1,"PROPERTIES")],O_.prototype,"lensSize",null),(0,X.Y5)("BABYLON.NodeRenderGraphDepthOfFieldPostProcessBlock",O_);class D_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i){super(e,t,i),this.registerInput("source",Rp.Texture),this.registerInput("destination",Rp.Texture,!0),this.registerOutput("output",Rp.BasedOnInput),this.source.addAcceptedConnectionPointTypes(Rp.TextureAllButBackBuffer),this.destination.addAcceptedConnectionPointTypes(Rp.TextureAll),this.output._typeConnectionSource=()=>this.destination.isConnected?this.destination:this.source,this._frameGraphTask=new g_(this.name,t,new __(e,i.getEngine()))}get sourceSamplingMode(){return this._frameGraphTask.sourceSamplingMode}set sourceSamplingMode(e){this._frameGraphTask.sourceSamplingMode=e}get threshold(){return this._frameGraphTask.postProcess.threshold}set threshold(e){this._frameGraphTask.postProcess.threshold=e}getClassName(){return"NodeRenderGraphExtractHighlightsPostProcessBlock"}get source(){return this._inputs[0]}get destination(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this.output.value=this._frameGraphTask.outputTexture;const t=this.source.connectedPoint;t&&(this._frameGraphTask.sourceTexture=t.value);const i=this.destination.connectedPoint;i&&(this._frameGraphTask.destinationTexture=i.value)}_dumpPropertiesCode(){const e=[];return e.push(`${this._codeVariableName}.threshold = ${this.threshold};`),e.push(`${this._codeVariableName}.sourceSamplingMode = ${this.sourceSamplingMode};`),super._dumpPropertiesCode()+e.join("\n")}serialize(){const e=super.serialize();return e.threshold=this.threshold,e.sourceSamplingMode=this.sourceSamplingMode,e}_deserialize(e){super._deserialize(e),this.threshold=e.threshold,this.sourceSamplingMode=e.sourceSamplingMode}}(0,je.Cg)([t_("Source sampling mode",6,"PROPERTIES")],D_.prototype,"sourceSamplingMode",null),(0,je.Cg)([t_("Threshold",1,"PROPERTIES",{min:0,max:1})],D_.prototype,"threshold",null),(0,X.Y5)("BABYLON.NodeRenderGraphExtractHighlightsPostProcessBlock",D_);class w_ extends kp{constructor(e,t,i){super(e,t),this._scene=i,this.outputObjectList={meshes:[],particleSystems:[]}}record(){if(void 0===this.objectList||void 0===this.camera)throw new Error(`FrameGraphCullObjectsTask ${this.name}: objectList and camera are required`);const e=this._frameGraph.addCullPass(this.name);e.setObjectList(this.outputObjectList),e.setExecuteFunc((e=>{this.outputObjectList.meshes=[],this.camera._updateFrustumPlanes();const t=this.camera._frustumPlanes,i=this.objectList.meshes||this._scene.meshes;for(let e=0;e0&&r.layerMask&this.camera.layerMask&&(this._scene.skipFrustumClipping||r.alwaysSelectAsActiveMesh||r.isInFrustum(t))&&this.outputObjectList.meshes.push(r)}}));const t=this._frameGraph.addCullPass(this.name+"_disabled",!0);t.setObjectList(this.outputObjectList),t.setExecuteFunc((e=>{this.outputObjectList.meshes=this.objectList.meshes,this.outputObjectList.particleSystems=this.objectList.particleSystems}))}}class N_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i){super(e,t,i),this.registerInput("camera",Rp.Camera),this.registerInput("objects",Rp.ObjectList),this.registerOutput("output",Rp.ObjectList),this._frameGraphTask=new w_(this.name,t,i)}getClassName(){return"NodeRenderGraphCullObjectsBlock"}get camera(){return this._inputs[0]}get objects(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this.output.value=this._frameGraphTask.outputObjectList;const t=this.camera.connectedPoint;t&&(this._frameGraphTask.camera=t.value);const i=this.objects.connectedPoint;i&&(this._frameGraphTask.objectList=i.value)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+[].join("\n")}serialize(){return super.serialize()}_deserialize(e){super._deserialize(e)}}(0,X.Y5)("BABYLON.NodeRenderGraphCullObjectsBlock",N_);var F_=i(25266);const L_=[new H.ov(0,0,0,0),new H.ov(1,1,1,1),new H.ov(1e8,1e8,1e8,1e8)];class B_ extends kp{get camera(){return this._camera}set camera(e){this._camera=e,this._renderer.activeCamera=this.camera}get objectRenderer(){return this._renderer}get name(){return this._name}set name(e){this._name=e,this._renderer&&(this._renderer.name=e)}constructor(e,t,i,r){super(e,t),this.depthTest=!0,this.depthWrite=!0,this.size={width:100,height:100},this.sizeIsPercentage=!0,this.samples=1,this.textureDescriptions=[],this._scene=i,this._engine=this._scene.getEngine(),this._renderer=new F_.P(e,i,r),this._renderer.renderSprites=!1,this._renderer.renderParticles=!1,this._renderer.onBeforeRenderingManagerRenderObservable.add((()=>{this._renderer.options.doNotChangeAspectRatio||i.updateTransformMatrix(!0)})),this.name=e,this._clearAttachmentsLayout=new Map,this._allAttachmentsLayout=[],this.outputDepthTexture=this._frameGraph.createDanglingHandle(),this.geometryViewDepthTexture=this._frameGraph.createDanglingHandle(),this.geometryScreenDepthTexture=this._frameGraph.createDanglingHandle(),this.geometryViewNormalTexture=this._frameGraph.createDanglingHandle(),this.geometryWorldNormalTexture=this._frameGraph.createDanglingHandle(),this.geometryLocalPositionTexture=this._frameGraph.createDanglingHandle(),this.geometryWorldPositionTexture=this._frameGraph.createDanglingHandle(),this.geometryAlbedoTexture=this._frameGraph.createDanglingHandle(),this.geometryReflectivityTexture=this._frameGraph.createDanglingHandle(),this.geometryVelocityTexture=this._frameGraph.createDanglingHandle(),this.geometryLinearVelocityTexture=this._frameGraph.createDanglingHandle()}get excludedSkinnedMeshFromVelocityTexture(){return Bn.GetConfiguration(this._renderer.renderPassId).excludedSkinnedMesh}isReady(){return this._renderer.isReadyForRendering(this._textureWidth,this._textureHeight)}record(){if(0===this.textureDescriptions.length||void 0===this.objectList)throw new Error(`FrameGraphGeometryRendererTask ${this.name}: object list and at least one geometry texture description must be provided`);const e=this._createMultiRenderTargetTexture(),t=this._checkDepthTextureCompatibility();this._buildClearAttachmentsLayout(),this._registerForRenderPassId(this._renderer.renderPassId);const i=this._frameGraph.getTextureDescription(e);this._textureWidth=i.size.width,this._textureHeight=i.size.height,Bn.MarkAsDirty(this._renderer.renderPassId,this.objectList.meshes||this._scene.meshes);const r=this._frameGraph.addRenderPass(this.name);r.setRenderTarget(e);let s=e+1;for(let e=0;ee.type===t.type));switch(Bn.GeometryTextureDescriptions[i].type){case 5:this._frameGraph.resolveDanglingHandle(this.geometryViewDepthTexture,s++);break;case 10:this._frameGraph.resolveDanglingHandle(this.geometryScreenDepthTexture,s++);break;case 6:this._frameGraph.resolveDanglingHandle(this.geometryViewNormalTexture,s++);break;case 8:this._frameGraph.resolveDanglingHandle(this.geometryWorldNormalTexture,s++);break;case 9:this._frameGraph.resolveDanglingHandle(this.geometryLocalPositionTexture,s++);break;case 1:this._frameGraph.resolveDanglingHandle(this.geometryWorldPositionTexture,s++);break;case 12:this._frameGraph.resolveDanglingHandle(this.geometryAlbedoTexture,s++);break;case 3:this._frameGraph.resolveDanglingHandle(this.geometryReflectivityTexture,s++);break;case 2:this._frameGraph.resolveDanglingHandle(this.geometryVelocityTexture,s++);break;case 11:this._frameGraph.resolveDanglingHandle(this.geometryLinearVelocityTexture,s++)}}void 0!==this.depthTexture&&r.setRenderTargetDepth(this.depthTexture),r.setExecuteFunc((e=>{this._renderer.renderList=this.objectList.meshes,this._renderer.particleSystemList=this.objectList.particleSystems,e.setDepthStates(this.depthTest&&t,this.depthWrite&&t),this._clearAttachmentsLayout.forEach(((t,i)=>{e.clearColorAttachments(L_[i],t)})),e.bindAttachments(this._allAttachmentsLayout),e.render(this._renderer,this._textureWidth,this._textureHeight)}))}dispose(){Bn.DeleteConfiguration(this._renderer.renderPassId),this._renderer.dispose(),super.dispose()}_createMultiRenderTargetTexture(){const e=[],t=[],i=[],r=[];for(let s=0;se.type===n.type));if(-1===o)throw new Error(`FrameGraphGeometryRendererTask ${this.name}: unknown texture type ${n.type}`);e[s]=n.textureType,t[s]=n.textureFormat,i[s]=Bn.GeometryTextureDescriptions[o].name,r[s]=!1}return this._frameGraph.createRenderTargetTexture(this.name,{size:this.size,sizeIsPercentage:this.sizeIsPercentage,options:{createMipMaps:!1,generateDepthBuffer:!1,textureCount:this.textureDescriptions.length,samples:this.samples,types:e,formats:t,useSRGBBuffers:r,labels:i}},!0)}_checkDepthTextureCompatibility(){let e=!1;if(void 0!==this.depthTexture){if(this.depthTexture===Fp)throw new Error(`FrameGraphGeometryRendererTask ${this.name}: the depth/stencil back buffer is not allowed as a depth texture`);if(this._frameGraph.getTextureDescription(this.depthTexture).options.samples!==this.samples)throw new Error(`FrameGraphGeometryRendererTask ${this.name}: the depth texture and the output texture must have the same number of samples`);this._frameGraph.resolveDanglingHandle(this.outputDepthTexture,this.depthTexture),e=!0}return e}_buildClearAttachmentsLayout(){const e=new Map,t=[];for(let i=0;ie.type===r.type)),n=Bn.GeometryTextureDescriptions[s];let o=e.get(n.clearType);if(void 0===o){o=[],e.set(n.clearType,o);for(let e=0;e{e.push(t===n.clearType)})),t.push(!0)}this._clearAttachmentsLayout=new Map,e.forEach(((e,t)=>{this._clearAttachmentsLayout.set(t,this._engine.buildTextureLayout(e))})),this._allAttachmentsLayout=this._engine.buildTextureLayout(t)}_registerForRenderPassId(e){const t=Bn.CreateConfiguration(e);for(let e=0;ee.type===i.type)),s=Bn.GeometryTextureDescriptions[r];t.defines[s.defineIndex]=e}}}class V_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i,r=!0){super(e,t,i),this.viewDepthFormat=6,this.viewDepthType=2,this.screenDepthFormat=6,this.screenDepthType=2,this.viewNormalFormat=5,this.viewNormalType=0,this.worldNormalFormat=5,this.worldNormalType=0,this.localPositionFormat=5,this.localPositionType=2,this.worldPositionFormat=5,this.worldPositionType=2,this.albedoFormat=5,this.albedoType=0,this.reflectivityFormat=5,this.reflectivityType=0,this.velocityFormat=5,this.velocityType=0,this.linearVelocityFormat=5,this.linearVelocityType=0,this._additionalConstructionParameters=[r],this.registerInput("depth",Rp.TextureBackBufferDepthStencilAttachment,!0),this.registerInput("camera",Rp.Camera),this.registerInput("objects",Rp.ObjectList),this.registerOutput("outputDepth",Rp.BasedOnInput),this.registerOutput("geomViewDepth",Rp.TextureViewDepth),this.registerOutput("geomScreenDepth",Rp.TextureScreenDepth),this.registerOutput("geomViewNormal",Rp.TextureViewNormal),this.registerOutput("geomWorldNormal",Rp.TextureViewNormal),this.registerOutput("geomLocalPosition",Rp.TextureLocalPosition),this.registerOutput("geomWorldPosition",Rp.TextureWorldPosition),this.registerOutput("geomAlbedo",Rp.TextureAlbedo),this.registerOutput("geomReflectivity",Rp.TextureReflectivity),this.registerOutput("geomVelocity",Rp.TextureVelocity),this.registerOutput("geomLinearVelocity",Rp.TextureLinearVelocity),this.depth.addAcceptedConnectionPointTypes(Rp.TextureDepthStencilAttachment),this.outputDepth._typeConnectionSource=this.depth,this._frameGraphTask=new B_(this.name,t,i,{doNotChangeAspectRatio:r})}get depthTest(){return this._frameGraphTask.depthTest}set depthTest(e){this._frameGraphTask.depthTest=e}get depthWrite(){return this._frameGraphTask.depthWrite}set depthWrite(e){this._frameGraphTask.depthWrite=e}get doNotChangeAspectRatio(){return this._frameGraphTask.objectRenderer.options.doNotChangeAspectRatio}set doNotChangeAspectRatio(e){this._frameGraphTask.dispose(),this._frameGraphTask=new B_(this.name,this._frameGraph,this._scene,{doNotChangeAspectRatio:e}),this._additionalConstructionParameters=[e]}get width(){return this._frameGraphTask.size.width}set width(e){this._frameGraphTask.size.width=e}get height(){return this._frameGraphTask.size.height}set height(e){this._frameGraphTask.size.height=e}get sizeInPercentage(){return this._frameGraphTask.sizeIsPercentage}set sizeInPercentage(e){this._frameGraphTask.sizeIsPercentage=e}get samples(){return this._frameGraphTask.samples}set samples(e){this._frameGraphTask.samples=e}getClassName(){return"NodeRenderGraphGeometryRendererBlock"}get depth(){return this._inputs[0]}get camera(){return this._inputs[1]}get objects(){return this._inputs[2]}get outputDepth(){return this._outputs[0]}get geomViewDepth(){return this._outputs[1]}get geomScreenDepth(){return this._outputs[2]}get geomViewNormal(){return this._outputs[3]}get geomWorldNormal(){return this._outputs[4]}get geomLocalPosition(){return this._outputs[5]}get geomWorldPosition(){return this._outputs[6]}get geomAlbedo(){return this._outputs[7]}get geomReflectivity(){return this._outputs[8]}get geomVelocity(){return this._outputs[9]}get geomLinearVelocity(){return this._outputs[10]}_buildBlock(e){super._buildBlock(e);const t=[this.geomViewDepth.isConnected,this.geomScreenDepth.isConnected,this.geomViewNormal.isConnected,this.geomWorldNormal.isConnected,this.geomLocalPosition.isConnected,this.geomWorldPosition.isConnected,this.geomAlbedo.isConnected,this.geomReflectivity.isConnected,this.geomVelocity.isConnected,this.geomLinearVelocity.isConnected];if(t.every((e=>!e)))throw new Error("NodeRenderGraphGeometryRendererBlock: At least one output geometry buffer must be connected");this._frameGraphTask.name=this.name,this.outputDepth.value=this._frameGraphTask.outputDepthTexture,this.geomViewDepth.value=this._frameGraphTask.geometryViewDepthTexture,this.geomScreenDepth.value=this._frameGraphTask.geometryScreenDepthTexture,this.geomViewNormal.value=this._frameGraphTask.geometryViewNormalTexture,this.geomWorldNormal.value=this._frameGraphTask.geometryWorldNormalTexture,this.geomLocalPosition.value=this._frameGraphTask.geometryLocalPositionTexture,this.geomWorldPosition.value=this._frameGraphTask.geometryWorldPositionTexture,this.geomAlbedo.value=this._frameGraphTask.geometryAlbedoTexture,this.geomReflectivity.value=this._frameGraphTask.geometryReflectivityTexture,this.geomVelocity.value=this._frameGraphTask.geometryVelocityTexture,this.geomLinearVelocity.value=this._frameGraphTask.geometryLinearVelocityTexture;const i=this.depth.connectedPoint;i&&(this._frameGraphTask.depthTexture=i.value);const r=this.camera.connectedPoint;r&&(this._frameGraphTask.camera=r.value);const s=this.objects.connectedPoint;s&&(this._frameGraphTask.objectList=s.value),this._frameGraphTask.textureDescriptions=[];const n=[this.viewDepthFormat,this.screenDepthFormat,this.viewNormalFormat,this.worldNormalFormat,this.localPositionFormat,this.worldPositionFormat,this.albedoFormat,this.reflectivityFormat,this.velocityFormat,this.linearVelocityFormat],o=[this.viewDepthType,this.screenDepthType,this.viewNormalType,this.worldNormalType,this.localPositionType,this.worldPositionType,this.albedoType,this.reflectivityType,this.velocityType,this.linearVelocityType],a=[5,10,6,8,9,1,12,3,2,11];for(let e=0;e{this._renderer.options.doNotChangeAspectRatio||i.updateTransformMatrix(!0)})),this.outputTexture=this._frameGraph.createDanglingHandle(),this.outputDepthTexture=this._frameGraph.createDanglingHandle()}isReady(){return this._renderer.isReadyForRendering(this._textureWidth,this._textureHeight)}record(e=!1,t){if(void 0===this.destinationTexture||void 0===this.objectList)throw new Error(`FrameGraphObjectRendererTask ${this.name}: destinationTexture and objectList are required`);const i=this._frameGraph.getTextureDescription(this.destinationTexture);let r=!1;if(void 0!==this.depthTexture){if(this.depthTexture===Fp&&this.destinationTexture!==Np)throw new Error(`FrameGraphObjectRendererTask ${this.name}: the back buffer color texture is the only color texture allowed when the depth is the back buffer depth/stencil`);if(this.depthTexture!==Fp&&this.destinationTexture===Np)throw new Error(`FrameGraphObjectRendererTask ${this.name}: the back buffer depth/stencil texture is the only depth texture allowed when the destination is the back buffer color`);if(this._frameGraph.getTextureDescription(this.depthTexture).options.samples!==i.options.samples)throw new Error(`FrameGraphObjectRendererTask ${this.name}: the depth texture and the output texture must have the same number of samples`);r=!0}this._frameGraph.resolveDanglingHandle(this.outputTexture,this.destinationTexture),void 0!==this.depthTexture&&this._frameGraph.resolveDanglingHandle(this.outputDepthTexture,this.depthTexture),this._textureWidth=i.size.width,this._textureHeight=i.size.height;const s=this._frameGraph.addRenderPass(this.name);if(s.setRenderTarget(this.destinationTexture),void 0!==this.depthTexture&&s.setRenderTargetDepth(this.depthTexture),s.setExecuteFunc((e=>{this._renderer.renderList=this.objectList.meshes,this._renderer.particleSystemList=this.objectList.particleSystems,e.setDepthStates(this.depthTest&&r,this.depthWrite&&r),e.render(this._renderer,this._textureWidth,this._textureHeight),t?.(e)})),void 0!==this.dependencies)for(const e of this.dependencies)s.useTexture(e);if(!e){const e=this._frameGraph.addRenderPass(this.name+"_disabled",!0);if(e.setRenderTarget(this.destinationTexture),void 0!==this.depthTexture&&e.setRenderTargetDepth(this.depthTexture),e.setExecuteFunc((e=>{})),void 0!==this.dependencies)for(const t of this.dependencies)e.useTexture(t)}}dispose(){this._renderer.dispose(),super.dispose()}}class U_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i){super(e,t,i),this.registerInput("destination",Rp.Texture),this.registerInput("depth",Rp.TextureBackBufferDepthStencilAttachment,!0),this.registerInput("camera",Rp.Camera),this.registerInput("objects",Rp.ObjectList),this.registerInput("dependencies",Rp.Texture,!0),this.registerOutput("output",Rp.BasedOnInput),this.registerOutput("outputDepth",Rp.BasedOnInput),this.destination.addAcceptedConnectionPointTypes(Rp.TextureAllButBackBufferDepthStencil),this.depth.addAcceptedConnectionPointTypes(Rp.TextureDepthStencilAttachment),this.dependencies.addAcceptedConnectionPointTypes(Rp.TextureAllButBackBuffer),this.output._typeConnectionSource=this.destination,this.outputDepth._typeConnectionSource=this.depth}get depthTest(){return this._frameGraphTask.depthTest}set depthTest(e){this._frameGraphTask.depthTest=e}get depthWrite(){return this._frameGraphTask.depthWrite}set depthWrite(e){this._frameGraphTask.depthWrite=e}getClassName(){return"NodeRenderGraphBaseObjectRendererBlock"}get destination(){return this._inputs[0]}get depth(){return this._inputs[1]}get camera(){return this._inputs[2]}get objects(){return this._inputs[3]}get dependencies(){return this._inputs[4]}get output(){return this._outputs[0]}get outputDepth(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this.output.value=this._frameGraphTask.outputTexture,this.outputDepth.value=this._frameGraphTask.outputDepthTexture;const t=this.destination.connectedPoint;t&&(this._frameGraphTask.destinationTexture=t.value);const i=this.depth.connectedPoint;i&&(this._frameGraphTask.depthTexture=i.value);const r=this.camera.connectedPoint;r&&(this._frameGraphTask.camera=r.value);const s=this.objects.connectedPoint;s&&(this._frameGraphTask.objectList=s.value),this._frameGraphTask.dependencies=[];const n=this.dependencies.connectedPoint;n&&(this._frameGraphTask.dependencies[0]=n.value)}_dumpPropertiesCode(){const e=[];return e.push(`${this._codeVariableName}.depthTest = ${this.depthTest};`),e.push(`${this._codeVariableName}.depthWrite = ${this.depthWrite};`),super._dumpPropertiesCode()+e.join("\n")}serialize(){const e=super.serialize();return e.depthTest=this.depthTest,e.depthWrite=this.depthWrite,e}_deserialize(e){super._deserialize(e),this.depthTest=e.depthTest,this.depthWrite=e.depthWrite}}(0,je.Cg)([t_("Depth test",0,"PROPERTIES")],U_.prototype,"depthTest",null),(0,je.Cg)([t_("Depth write",0,"PROPERTIES")],U_.prototype,"depthWrite",null);class G_ extends U_{constructor(e,t,i,r=!0){super(e,t,i),this._additionalConstructionParameters=[r],this._frameGraphTask=new k_(this.name,t,i,{doNotChangeAspectRatio:r})}get doNotChangeAspectRatio(){return this._frameGraphTask.objectRenderer.options.doNotChangeAspectRatio}set doNotChangeAspectRatio(e){this._frameGraphTask.dispose(),this._frameGraphTask=new k_(this.name,this._frameGraph,this._scene,{doNotChangeAspectRatio:e}),this._additionalConstructionParameters=[e]}getClassName(){return"NodeRenderGraphObjectRendererBlock"}}(0,je.Cg)([t_("Do not change aspect ratio",0,"PROPERTIES")],G_.prototype,"doNotChangeAspectRatio",null),(0,X.Y5)("BABYLON.NodeRenderGraphObjectRendererBlock",G_);class z_{constructor(e,t=2,i=3,r=1,s=1){this._curIndex=0,this._sequence=[],this._numSamples=0,this.x=0,this.y=0,this._width=r,this._height=s,this._baseX=t,this._baseY=i,this._generateSequence(e),this.next()}regenerate(e){this._generateSequence(e),this.next()}setDimensions(e,t){this._width=e,this._height=t}next(){this.x=this._sequence[this._curIndex]/this._width,this.y=this._sequence[this._curIndex+1]/this._height,this._curIndex+=2,this._curIndex>=2*this._numSamples&&(this._curIndex=0)}_generateSequence(e){this._sequence=[],this._curIndex=0,this._numSamples=e;for(let t=1;t<=e;++t)this._sequence.push(this._halton(t,this._baseX)-.5,this._halton(t,this._baseY)-.5)}_halton(e,t){let i=1,r=0;for(;e>0;)i/=t,r+=i*(e%t),e=~~(e/t);return r}}class W_ extends Yp.${_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(i.bind(i,88559)))):t.push(Promise.resolve().then(i.bind(i,7672)))}set samples(e){this._samples!==e&&(this._samples=e,this._hs.regenerate(e))}get samples(){return this._samples}get disabled(){return this._disabled}set disabled(e){this._disabled!==e&&(this._disabled=e,this._reset())}get textureWidth(){return this._textureWidth}set textureWidth(e){this._textureWidth!==e&&(this._textureWidth=e,this._reset())}get textureHeight(){return this._textureHeight}set textureHeight(e){this._textureHeight!==e&&(this._textureHeight=e,this._reset())}constructor(e,t=null,i){super({...i,name:e,engine:t||an.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:W_.FragmentUrl,uniforms:W_.Uniforms,samplers:W_.Samplers}),this._samples=8,this.factor=.05,this._disabled=!1,this._textureWidth=0,this._textureHeight=0,this.disableOnCameraMove=!0,this._firstUpdate=!0,this._hs=new z_(this.samples)}_reset(){this._hs.setDimensions(this._textureWidth/2,this._textureHeight/2),this._hs.next(),this._firstUpdate=!0}updateProjectionMatrix(){if(!this.disabled){if(this.camera&&!this.camera.hasMoved)if(this.camera.mode===rt.PERSPECTIVE_CAMERA){const e=this.camera.getProjectionMatrix();e.setRowFromFloats(2,this._hs.x,this._hs.y,e.m[10],e.m[11])}else{const e=this.camera.getProjectionMatrix(!0);e.setRowFromFloats(3,this._hs.x+e.m[12],this._hs.y+e.m[13],e.m[14],e.m[15])}this._hs.next()}}bind(){super.bind(),this.disabled||(this._drawWrapper.effect.setFloat("factor",this.camera?.hasMoved&&this.disableOnCameraMove||this._firstUpdate?1:this.factor),this._firstUpdate=!1)}}W_.FragmentUrl="taa",W_.Uniforms=["factor"],W_.Samplers=["historySampler"];class H_ extends k_{constructor(e,t,i,r){super(e,t,i,r),this.postProcess=new W_(`${e} post-process`,i.getEngine()),this._postProcessDrawWrapper=this.postProcess.drawWrapper}record(){if(void 0===this.destinationTexture||void 0===this.objectList)throw new Error(`FrameGraphTAAObjectRendererTask ${this.name}: destinationTexture and objectList are required`);if(this.destinationTexture===Np||this.depthTexture===Fp)throw new Error(`FrameGraphTAAObjectRendererTask ${this.name}: the back buffer color/depth textures are not allowed. Use regular textures instead.`);const e=this._frameGraph.getTextureDescription(this.destinationTexture);let t=!1;if(void 0!==this.depthTexture){if(this._frameGraph.getTextureDescription(this.depthTexture).options.samples!==e.options.samples)throw new Error(`FrameGraphTAAObjectRendererTask ${this.name}: the depth texture and the output texture must have the same number of samples`);t=!0}this.postProcess.camera=this.camera,this.postProcess.textureWidth=e.size.width,this.postProcess.textureHeight=e.size.height;const i={size:e.size,options:{createMipMaps:!1,generateMipMaps:!1,types:[2],samplingModes:[1],formats:[5],samples:1,useSRGBBuffers:[!1],generateDepthBuffer:!1,generateStencilBuffer:!1,label:""},sizeIsPercentage:!1,isHistoryTexture:!0},r=this._frameGraph.createRenderTargetTexture(`${this.name} history`,i);this._frameGraph.resolveDanglingHandle(this.outputTexture,r),void 0!==this.depthTexture&&this._frameGraph.resolveDanglingHandle(this.outputDepthTexture,this.depthTexture),this._textureWidth=e.size.width,this._textureHeight=e.size.height;const s=this._frameGraph.addRenderPass(this.name);s.setRenderTarget(this.destinationTexture),void 0!==this.depthTexture&&s.setRenderTargetDepth(this.depthTexture),s.setExecuteFunc((e=>{this._renderer.renderList=this.objectList.meshes,this._renderer.particleSystemList=this.objectList.particleSystems,this.postProcess.updateProjectionMatrix(),e.setDepthStates(this.depthTest&&t,this.depthWrite&&t),this.postProcess.disabled||(this._scene.activeCamera=this.camera,this._scene.setTransformMatrix(this.camera.getViewMatrix(),this.camera.getProjectionMatrix())),e.render(this._renderer,this._textureWidth,this._textureHeight),this._scene.activeCamera=null,e.bindRenderTarget(r,"frame graph - TAA merge with history texture"),this.postProcess.disabled?e.copyTexture(this.destinationTexture):e.applyFullScreenEffect(this._postProcessDrawWrapper,(()=>{this.postProcess.bind(),e.bindTextureHandle(this._postProcessDrawWrapper.effect,"textureSampler",this.destinationTexture),e.bindTextureHandle(this._postProcessDrawWrapper.effect,"historySampler",r)}))}));const n=this._frameGraph.addRenderPass(this.name+"_disabled",!0);if(n.setRenderTarget(this.outputTexture),void 0!==this.depthTexture&&n.setRenderTargetDepth(this.depthTexture),n.setExecuteFunc((e=>{e.copyTexture(this.destinationTexture)})),void 0!==this.dependencies)for(const e of this.dependencies)s.useTexture(e),n.useTexture(e)}}class X_ extends U_{get task(){return this._frameGraphTask}constructor(e,t,i,r=!0){super(e,t,i),this._additionalConstructionParameters=[r],this._frameGraphTask=new H_(this.name,t,i,{doNotChangeAspectRatio:r})}get doNotChangeAspectRatio(){return this._frameGraphTask.objectRenderer.options.doNotChangeAspectRatio}set doNotChangeAspectRatio(e){this._frameGraphTask.dispose(),this._frameGraphTask=new H_(this.name,this._frameGraph,this._scene,{doNotChangeAspectRatio:e}),this._additionalConstructionParameters=[e]}get samples(){return this._frameGraphTask.postProcess.samples}set samples(e){this._frameGraphTask.postProcess.samples=e}get factor(){return this._frameGraphTask.postProcess.factor}set factor(e){this._frameGraphTask.postProcess.factor=e}get disableOnCameraMove(){return this._frameGraphTask.postProcess.disableOnCameraMove}set disableOnCameraMove(e){this._frameGraphTask.postProcess.disableOnCameraMove=e}get disableTAA(){return this._frameGraphTask.postProcess.disabled}set disableTAA(e){this._frameGraphTask.postProcess.disabled=e}getClassName(){return"NodeRenderGraphTAAObjectRendererBlock"}_dumpPropertiesCode(){const e=[];return e.push(`${this._codeVariableName}.samples = ${this.samples};`),e.push(`${this._codeVariableName}.factor = ${this.factor};`),e.push(`${this._codeVariableName}.disableOnCameraMove = ${this.disableOnCameraMove};`),e.push(`${this._codeVariableName}.disableTAA = ${this.disableTAA};`),super._dumpPropertiesCode()+e.join("\n")}serialize(){const e=super.serialize();return e.samples=this.samples,e.factor=this.factor,e.disableOnCameraMove=this.disableOnCameraMove,e.disableTAA=this.disableTAA,e}_deserialize(e){super._deserialize(e),this.samples=e.samples,this.factor=e.factor,this.disableOnCameraMove=e.disableOnCameraMove,this.disableTAA=e.disableTAA}}(0,je.Cg)([t_("Do not change aspect ratio",0,"PROPERTIES")],X_.prototype,"doNotChangeAspectRatio",null),(0,je.Cg)([t_("Samples",2,"TEMPORAL ANTI-ALIASING")],X_.prototype,"samples",null),(0,je.Cg)([t_("Factor",1,"TEMPORAL ANTI-ALIASING")],X_.prototype,"factor",null),(0,je.Cg)([t_("Disable on camera move",0,"TEMPORAL ANTI-ALIASING")],X_.prototype,"disableOnCameraMove",null),(0,je.Cg)([t_("Disable TAA",0,"TEMPORAL ANTI-ALIASING")],X_.prototype,"disableTAA",null),(0,X.Y5)("BABYLON.NodeRenderGraphTAAObjectRendererBlock",X_);class q_ extends wp{get endpoints(){return this._endpoints}constructor(e,t,i){super(e,t,i),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",Rp.AutoDetect)}getClassName(){return"NodeRenderGraphTeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const r of this.endpoints)-1===t.indexOf(r)&&(i+=r._dumpCode(e,t));return i}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(const t of this.endpoints)if(t.isAnAncestorOfType(e))return!0;return!1}isAnAncestorOf(e){for(const t of this.endpoints){if(t===e)return!0;if(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);-1!==t&&(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=[]}}(0,X.Y5)("BABYLON.NodeRenderGraphTeleportInBlock",q_);class Y_ extends wp{constructor(e,t,i){super(e,t,i),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",Rp.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"NodeRenderGraphTeleportOutBlock"}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&&-1===t.indexOf(this.entryPoint)&&(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});\n`),e}serialize(){const e=super.serialize();return e.entryPoint=this.entryPoint?.uniqueId??"",e}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}}(0,X.Y5)("BABYLON.NodeRenderGraphTeleportOutBlock",Y_);class K_ extends kp{constructor(e,t){super(e,t),this.outputTexture=this._frameGraph.createDanglingHandle()}record(){if(void 0===this.sourceTexture||void 0===this.destinationTexture)throw new Error(`FrameGraphCopyToTextureTask "${this.name}": sourceTexture and destinationTexture are required`);this._frameGraph.resolveDanglingHandle(this.outputTexture,this.destinationTexture);const e=this._frameGraph.addRenderPass(this.name);e.useTexture(this.sourceTexture),e.setRenderTarget(this.outputTexture),e.setExecuteFunc((e=>{e.copyTexture(this.sourceTexture)}));const t=this._frameGraph.addRenderPass(this.name+"_disabled",!0);t.setRenderTarget(this.outputTexture),t.setExecuteFunc((e=>{}))}}class j_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i){super(e,t,i),this.registerInput("source",Rp.Texture),this.registerInput("destination",Rp.Texture),this.registerOutput("output",Rp.BasedOnInput),this.source.addAcceptedConnectionPointTypes(Rp.TextureAllButBackBuffer),this.destination.addAcceptedConnectionPointTypes(Rp.TextureAll),this.output._typeConnectionSource=this.destination,this._frameGraphTask=new K_(e,t)}getClassName(){return"NodeRenderGraphCopyTextureBlock"}get source(){return this._inputs[0]}get destination(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this.output.value=this._frameGraphTask.outputTexture;const t=this.source.connectedPoint;t&&(this._frameGraphTask.sourceTexture=t.value);const i=this.destination.connectedPoint;i&&(this._frameGraphTask.destinationTexture=i.value)}}(0,X.Y5)("BABYLON.NodeRenderGraphCopyTextureBlock",j_);class $_ extends kp{constructor(e,t){super(e,t),this.outputTexture=this._frameGraph.createDanglingHandle()}record(){if(void 0===this.destinationTexture)throw new Error(`FrameGraphGenerateMipMapsTask ${this.name}: destinationTexture is required`);if(this._frameGraph.resolveDanglingHandle(this.outputTexture,this.destinationTexture),!this._frameGraph.getTextureDescription(this.destinationTexture).options.createMipMaps)throw new Error(`FrameGraphGenerateMipMapsTask ${this.name}: destinationTexture must have createMipMaps set to true`);const e=this._frameGraph.addRenderPass(this.name);e.setRenderTarget(this.outputTexture),e.setExecuteFunc((e=>{e.generateMipMaps()}));const t=this._frameGraph.addRenderPass(this.name+"_disabled",!0);t.setRenderTarget(this.outputTexture),t.setExecuteFunc((e=>{}))}}class Q_ extends wp{get task(){return this._frameGraphTask}constructor(e,t,i){super(e,t,i),this.registerInput("texture",Rp.Texture),this.registerOutput("output",Rp.BasedOnInput),this.texture.addAcceptedConnectionPointTypes(Rp.TextureAllButBackBuffer),this.output._typeConnectionSource=this.texture,this._frameGraphTask=new $_(e,t)}getClassName(){return"NodeRenderGraphGenerateMipmapsBlock"}get texture(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this._propagateInputValueToOutput(this.texture,this.output);const t=this.texture.connectedPoint;t&&(this._frameGraphTask.destinationTexture=t.value)}}(0,X.Y5)("BABYLON.NodeRenderGraphGenerateMipmapsBlock",Q_);class Z_{}class J_ extends Go{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=H.v9.Gray(),i=Bo.DefaultUtilityLayer,r=null,s=1,n=H.v9.Yellow(),o=H.v9.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new z.cP,this.uniformScaling=!1,this.sensitivity=1,this.dragScale=1,this.incrementalSnap=!1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._tmpVector=new W.Pq(0,0,0),this._incrementalStartupValue=W.Pq.Zero(),this._parent=r,this._coloredMaterial=new Un("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new H.v9(.1,.1,.1)),this._hoverMaterial=new Un("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=n,this._disableMaterial=new Un("",i.utilityLayerScene),this._disableMaterial.diffuseColor=o,this._disableMaterial.alpha=.4,this._gizmoMesh=new Yt("axis",i.utilityLayerScene);const{arrowMesh:a,arrowTail:l}=this._createGizmoMesh(this._gizmoMesh,s),h=this._createGizmoMesh(this._gizmoMesh,s+4,!0);this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,Go.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3);const c=a.position.clone(),u=l.position.clone(),d=l.scaling.clone(),f=e=>{const t=e*(3/this._rootMesh.scaling.length())*6;a.position.z+=t/3.5,l.scaling.y+=t,this.dragScale=l.scaling.y,l.position.z=a.position.z/2},p=()=>{a.position.set(c.x,c.y,c.z),l.position.set(u.x,u.y,u.z),l.scaling.set(d.x,d.y,d.z),this.dragScale=l.scaling.y,this._dragging=!1};this.dragBehavior=new Ji({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior);let _=0,m=0;const g={snapDistance:0};this.dragBehavior.onDragObservable.add((t=>{if(this.attachedNode){const i=this.sensitivity*t.dragDistance*(3*this.scaleRatio/this._rootMesh.scaling.length()),r=this._tmpVector;let s=!1,n=0;if(this.uniformScaling?r.setAll(.57735):r.copyFrom(e),0==this.snapDistance)r.scaleToRef(i,r);else{_+=i,m+=i;const e=this.incrementalSnap?m:_;Math.abs(e)>this.snapDistance?(n=Math.floor(Math.abs(e)/this.snapDistance),e<0&&(n*=-1),_%=this.snapDistance,r.scaleToRef(this.snapDistance*n,r),s=!0):r.scaleInPlace(0)}r.addInPlaceFromFloats(1,1,1),r.x=Math.abs(r.x)0&&this.incrementalSnap?(this.attachedNode.getWorldMatrix().decompose(void 0,W.AA.Quaternion[0],W.AA.Vector3[2],Go.PreserveScaling?o:void 0),r.addInPlace(this._incrementalStartupValue),r.addInPlaceFromFloats(-1,-1,-1),r.x=Math.abs(r.x)*(this._incrementalStartupValue.x>0?1:-1),r.y=Math.abs(r.y)*(this._incrementalStartupValue.y>0?1:-1),r.z=Math.abs(r.z)*(this._incrementalStartupValue.z>0?1:-1),W.uq.ComposeToRef(r,W.AA.Quaternion[0],W.AA.Vector3[2],W.AA.Matrix[1])):(W.uq.ScalingToRef(r.x,r.y,r.z,W.AA.Matrix[2]),W.AA.Matrix[2].multiplyToRef(this.attachedNode.getWorldMatrix(),W.AA.Matrix[1])),W.AA.Matrix[1].decompose(W.AA.Vector3[1],void 0,void 0,Go.PreserveScaling?o:void 0);const a=1e5;Math.abs(W.AA.Vector3[1].x){this._dragging=!0;const e=this.attachedNode._isMesh?this.attachedNode:void 0;this.attachedNode?.getWorldMatrix().decompose(this._incrementalStartupValue,void 0,void 0,Go.PreserveScaling?e:void 0),_=0,m=0})),this.dragBehavior.onDragObservable.add((e=>f(e.dragDistance))),this.dragBehavior.onDragEndObservable.add(p),r?.uniformScaleGizmo?.dragBehavior?.onDragObservable?.add((e=>f(e.delta.y))),r?.uniformScaleGizmo?.dragBehavior?.onDragEndObservable?.add(p);const v={gizmoMeshes:[a,l],colliderMeshes:[h.arrowMesh,h.arrowTail],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,v),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(this._customMeshSet)return;let t=this._parent?.getAxisCache(this._gizmoMesh);if(this._isHovered=!(!t||-1==t.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),t=this._parent?.getAxisCache(this._rootMesh),this._isHovered||(this._isHovered=!(!t||-1==t.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh))),!this._parent){const e=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(v.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(v.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}));const x=i._getSharedGizmoLight();x.includedOnlyMeshes=x.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes())}_createGizmoMesh(e,t,i=!1){const r=Ko("yPosMesh",{size:.4*(1+(t-1)/4)},this.gizmoLayer.utilityLayerScene),s=No("cylinder",{diameterTop:.005*t,height:.275,diameterBottom:.005*t,tessellation:96},this.gizmoLayer.utilityLayerScene);return r.scaling.scaleInPlace(.1),r.material=this._coloredMaterial,r.rotation.x=Math.PI/2,r.position.z+=.3,s.material=this._coloredMaterial,s.position.z+=.1375,s.rotation.x=Math.PI/2,i&&(r.visibility=0,s.visibility=0),e.addChild(r),e.addChild(s),{arrowMesh:r,arrowTail:s}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}setCustomMesh(e,t=!1){super.setCustomMesh(e),t&&(this._rootMesh.getChildMeshes().forEach((e=>{e.material=this._coloredMaterial,e.color&&(e.color=this._coloredMaterial.diffuseColor)})),this._customMeshSet=!1)}}var em;J_.MinimumAbsoluteScale=lt.bH,function(e){e[e.Rotation=0]="Rotation",e[e.Scaling=1]="Scaling"}(em||(em={}));class tm extends Go{set axisFactor(e){this._axisFactor=e;const t=this._scaleBoxesParent.getChildMeshes();let i=0;for(let e=0;e<3;e++)for(let r=0;r<3;r++)for(let s=0;s<3;s++){const n=(1===e?1:0)+(1===r?1:0)+(1===s?1:0);if(1!==n&&3!==n){if(t[i]){const n=new W.Pq(e-1,r-1,s-1);n.multiplyInPlace(this._axisFactor),t[i].setEnabled(n.lengthSquared()>lt.bH)}i++}}}get axisFactor(){return this._axisFactor}set scaleDragSpeed(e){this._scaleDragSpeed=e}get scaleDragSpeed(){return this._scaleDragSpeed}get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverColoredMaterial}get pointerDragBehavior(){return this._pointerDragBehavior}get isDragging(){return this._dragging||this._pointerDragBehavior.dragging}setColor(e){this._coloredMaterial.emissiveColor=e,this._hoverColoredMaterial.emissiveColor=e.clone().add(new H.v9(.3,.3,.3)),this._lineBoundingBox.getChildren().forEach((t=>{t.color&&(t.color=e)}))}constructor(e=H.v9.Gray(),t=Bo.DefaultKeepDepthUtilityLayer){super(t),this._boundingDimensions=new W.Pq(1,1,1),this._renderObserver=null,this._pointerObserver=null,this._scaleDragSpeed=.2,this._rotateAnchorsDragBehaviors=[],this._scaleBoxesDragBehaviors=[],this._dragging=!1,this._tmpQuaternion=new W.PT,this._tmpVector=new W.Pq(0,0,0),this._tmpRotationMatrix=new W.uq,this._incrementalStartupValue=W.Pq.Zero(),this._incrementalAnchorStartupValue=W.Pq.Zero(),this.ignoreChildren=!1,this.includeChildPredicate=null,this.rotationSphereSize=.1,this.scaleBoxSize=.1,this.fixedDragMeshScreenSize=!1,this.fixedDragMeshBoundsSize=!1,this.fixedDragMeshScreenSizeDistanceFactor=10,this.scalingSnapDistance=0,this.rotationSnapDistance=0,this.onDragStartObservable=new z.cP,this.onHoverStartObservable=new z.cP,this.onHoverEndObservable=new z.cP,this.onScaleBoxDragObservable=new z.cP,this.onScaleBoxDragEndObservable=new z.cP,this.onRotationSphereDragObservable=new z.cP,this.onRotationSphereDragEndObservable=new z.cP,this.scalePivot=null,this._axisFactor=new W.Pq(1,1,1),this.incrementalSnap=!1,this._existingMeshScale=new W.Pq,this._dragMesh=null,this._pointerDragBehavior=new Ji,this._cornerMesh=null,this.updateScale=!1,this._anchorMesh=new Pt("anchor",t.utilityLayerScene),this._coloredMaterial=new Un("",t.utilityLayerScene),this._coloredMaterial.disableLighting=!0,this._hoverColoredMaterial=new Un("",t.utilityLayerScene),this._hoverColoredMaterial.disableLighting=!0,this._lineBoundingBox=new Pt("",t.utilityLayerScene),this._lineBoundingBox.rotationQuaternion=new W.PT;const i=[];i.push(Ra("lines",{points:[new W.Pq(0,0,0),new W.Pq(this._boundingDimensions.x,0,0)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(0,0,0),new W.Pq(0,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(0,0,0),new W.Pq(0,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(this._boundingDimensions.x,0,0),new W.Pq(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(this._boundingDimensions.x,0,0),new W.Pq(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(0,this._boundingDimensions.y,0),new W.Pq(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(0,this._boundingDimensions.y,0),new W.Pq(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(0,0,this._boundingDimensions.z),new W.Pq(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(0,0,this._boundingDimensions.z),new W.Pq(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new W.Pq(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new W.Pq(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ra("lines",{points:[new W.Pq(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new W.Pq(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.forEach((t=>{t.color=e,t.position.addInPlace(new W.Pq(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),t.isPickable=!1,this._lineBoundingBox.addChild(t)})),this._rootMesh.addChild(this._lineBoundingBox),this.setColor(e),this._rotateAnchorsParent=new Pt("",t.utilityLayerScene),this._rotateAnchorsParent.rotationQuaternion=new W.PT;for(let e=0;e<12;e++){const i=Ko("",{width:e<4||e>=8?1.6:.4,height:e>=4&&e<8?1.6:.4,depth:.4},t.utilityLayerScene);i.rotation.x=e<4||e>=8?.25*Math.PI:0,i.rotation.y=e>=4&&e<8?.25*Math.PI:0,i.bakeTransformIntoVertices(i.computeWorldMatrix(!0)),i.rotationQuaternion=new W.PT,i.material=this._coloredMaterial,i.isNearGrabbable=!0;const r=new Ji({});r.moveAttached=!1,r.updateDragPlane=!1,i.addBehavior(r);const s=new W.Pq(1,0,0);let n=0,o=0;r.onDragStartObservable.add((()=>{s.copyFrom(i.forward),n=0,o=0}));const a=function(){const t=Math.floor(e/4);return W.AA.Vector3[0].set(0==t?1:0,1==t?1:0,2==t?1:0),W.AA.Vector3[0]};r.onDragObservable.add((t=>{if(this.onRotationSphereDragObservable.notifyObservers({dragOperation:0,dragAxis:a().clone()}),this.attachedMesh){const i=this.attachedMesh.parent;if(i&&i.scaling&&i.scaling.isNonUniformWithinEpsilon(.001))return void Z.V.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");ji._RemoveAndStorePivotPoint(this.attachedMesh);const r=s,a=t.dragPlaneNormal.scale(W.Pq.Dot(t.dragPlaneNormal,r)),l=r.subtract(a).normalizeToNew();let h=W.Pq.Dot(l,t.delta)<0?Math.abs(t.delta.length()):-Math.abs(t.delta.length());if(h=h/this._boundingDimensions.length()*this._anchorMesh.scaling.length(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=W.PT.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=W.PT.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),n+=h,Math.abs(n)<=2*Math.PI){if(this.rotationSnapDistance>0){const e=Math.floor(Math.abs(n)/this.rotationSnapDistance)*(n<0?-1:1),t=this.rotationSnapDistance*e;h=t-o,o=t}e>=8?W.PT.RotationYawPitchRollToRef(0,0,h,this._tmpQuaternion):e>=4?W.PT.RotationYawPitchRollToRef(h,0,0,this._tmpQuaternion):W.PT.RotationYawPitchRollToRef(0,h,0,this._tmpQuaternion),this.attachedMesh.isUsingPivotMatrix()&&this._anchorMesh.position.copyFrom(this.attachedMesh.position),this._anchorMesh.addChild(this.attachedMesh),this._anchorMesh.getScene().useRightHandedSystem&&this._tmpQuaternion.conjugateInPlace(),this._tmpQuaternion.normalize(),this._anchorMesh.rotationQuaternion.multiplyToRef(this._tmpQuaternion,this._anchorMesh.rotationQuaternion),this._anchorMesh.rotationQuaternion.normalize(),this._anchorMesh.removeChild(this.attachedMesh),this.attachedMesh.setParent(i)}this.updateBoundingBox(),ji._RestorePivotPoint(this.attachedMesh)}this._updateDummy()})),r.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({dragOperation:0,dragAxis:a().clone()}),this._dragging=!0,this._selectNode(i)})),r.onDragEndObservable.add((e=>{this.onRotationSphereDragEndObservable.notifyObservers({dragOperation:0,dragAxis:a().clone()}),this._dragging=!1,this._selectNode(null),this._updateDummy(),this._unhoverMeshOnTouchUp(e.pointerInfo,i)})),this._rotateAnchorsDragBehaviors.push(r),this._rotateAnchorsParent.addChild(i)}this._rootMesh.addChild(this._rotateAnchorsParent),this._scaleBoxesParent=new Pt("",t.utilityLayerScene),this._scaleBoxesParent.rotationQuaternion=new W.PT;for(let e=0;e<3;e++)for(let i=0;i<3;i++)for(let r=0;r<3;r++){const s=(1===e?1:0)+(1===i?1:0)+(1===r?1:0);if(1===s||3===s)continue;const n=2===s?Ko("",{size:1},t.utilityLayerScene):this._getCornerMesh(t);0===s&&(n.rotationQuaternion=W.PT.FromEulerAngles(.25*i*Math.PI,.25*(r+3*e-e*r)*Math.PI,0)),n.material=this._coloredMaterial,n._internalMetadata=2===s,n.isNearGrabbable=!0,W.AA.Vector3[0].set(e-1,i-1,r-1),W.AA.Vector3[0].normalize(),n.computeWorldMatrix(!0).invertToRef(W.AA.Matrix[0]);const o=W.Pq.TransformCoordinates(W.AA.Vector3[0],W.AA.Matrix[0]);o.normalize();const a=new Ji({dragAxis:o});a.updateDragPlane=!1,a.moveAttached=!1;let l=0,h=0;n.addBehavior(a),a.onDragObservable.add((t=>{if(this.onScaleBoxDragObservable.notifyObservers({dragOperation:1,dragAxis:new W.Pq(e-1,i-1,r-1)}),this.attachedMesh){const e=this.attachedMesh.parent;if(e&&e.scaling&&e.scaling.isNonUniformWithinEpsilon(.001))return void Z.V.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");ji._RemoveAndStorePivotPoint(this.attachedMesh);let i=t.dragDistance/this._boundingDimensions.length()*this._anchorMesh.scaling.length();if(l+=i,this.scalingSnapDistance>0){const e=Math.floor(Math.abs(l)/this.scalingSnapDistance)*(l<0?-1:1),t=this.scalingSnapDistance*e;i=t-h,h=t}const r=new W.Pq(i,i,i),a=new W.Pq(h,h,h);2===s&&(r.x*=Math.abs(o.x),r.y*=Math.abs(o.y),r.z*=Math.abs(o.z)),r.scaleInPlace(this._scaleDragSpeed),r.multiplyInPlace(this._axisFactor),a.scaleInPlace(this._scaleDragSpeed),a.multiplyInPlace(this._axisFactor),a.addInPlace(this._incrementalStartupValue),this.updateBoundingBox(),this.scalePivot?(this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(this._tmpRotationMatrix),this._boundingDimensions.scaleToRef(.5,this._tmpVector),W.Pq.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector),this._boundingDimensions.multiplyToRef(this.scalePivot,this._tmpVector),W.Pq.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.addInPlace(this._tmpVector)):(n.absolutePosition.subtractToRef(this._anchorMesh.position,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector),this.attachedMesh.isUsingPivotMatrix()&&this._anchorMesh.position.subtractInPlace(this.attachedMesh.getPivotPoint())),this._anchorMesh.addChild(this.attachedMesh),this.incrementalSnap?(a.x/=Math.abs(this._incrementalStartupValue.x){this.onDragStartObservable.notifyObservers({dragOperation:1,dragAxis:new W.Pq(e-1,i-1,r-1)}),this._dragging=!0,this._selectNode(n),l=0,h=0,this._incrementalStartupValue.copyFrom(this.attachedMesh.scaling),this._incrementalAnchorStartupValue.copyFrom(this._anchorMesh.scaling)})),a.onDragEndObservable.add((t=>{this.onScaleBoxDragEndObservable.notifyObservers({dragOperation:1,dragAxis:new W.Pq(e-1,i-1,r-1)}),this._dragging=!1,this._selectNode(null),this._updateDummy(),this._unhoverMeshOnTouchUp(t.pointerInfo,n)})),this._scaleBoxesParent.addChild(n),this._scaleBoxesDragBehaviors.push(a)}this._rootMesh.addChild(this._scaleBoxesParent);const r=[];this._pointerObserver=t.utilityLayerScene.onPointerObservable.add((e=>{r[e.event.pointerId]?e.pickInfo&&e.pickInfo.pickedMesh!=r[e.event.pointerId]&&(r[e.event.pointerId].material=this._coloredMaterial,delete r[e.event.pointerId],this.onHoverEndObservable.notifyObservers(),this._isHovered=!1):this._rotateAnchorsParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach((t=>{e.pickInfo&&e.pickInfo.pickedMesh==t&&(r[e.event.pointerId]=t,t.material=this._hoverColoredMaterial,this.onHoverStartObservable.notifyObservers(),this._isHovered=!0)}))})),this._renderObserver=this.gizmoLayer.originalScene.onBeforeRenderObservable.add((()=>{this.attachedMesh&&!this._existingMeshScale.equals(this.attachedMesh.scaling)?this.updateBoundingBox():(this.fixedDragMeshScreenSize||this.fixedDragMeshBoundsSize)&&(this._updateRotationAnchors(),this._updateScaleBoxes()),this._dragMesh&&this.attachedMesh&&this._pointerDragBehavior.dragging&&(this._lineBoundingBox.position.rotateByQuaternionToRef(this._rootMesh.rotationQuaternion,this._tmpVector),this.attachedMesh.setAbsolutePosition(this._dragMesh.position.add(this._tmpVector.scale(-1))))})),this.updateBoundingBox()}_getCornerMesh(e){if(!this._cornerMesh){const t=Ko("",{width:.4,height:.4,depth:1.6},e.utilityLayerScene);t.position.z=.6;const i=Ko("",{width:.4,height:1.6,depth:.4},e.utilityLayerScene);i.position.y=.6;const r=Ko("",{width:1.6,height:.4,depth:.4},e.utilityLayerScene);return r.position.x=.6,this._cornerMesh=Yt.MergeMeshes([r,i,t],!0),this._cornerMesh}return this._cornerMesh.clone()}_attachedNodeChanged(e){if(e){this._anchorMesh.scaling.setAll(1),ji._RemoveAndStorePivotPoint(e);const t=e.parent;this._anchorMesh.addChild(e),this._anchorMesh.removeChild(e),e.setParent(t),ji._RestorePivotPoint(e),this.updateBoundingBox(),e.getChildMeshes(!1).forEach((e=>{e.markAsDirty("scaling")})),this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce((()=>{this._updateDummy()}))}}_selectNode(e){this._rotateAnchorsParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach((t=>{t.isVisible=!e||t==e}))}_unhoverMeshOnTouchUp(e,t){e?.event instanceof PointerEvent&&"touch"===e?.event.pointerType&&(t.material=this._coloredMaterial)}getScaleBoxes(){return this._scaleBoxesParent.getChildMeshes()}updateBoundingBox(){if(this.attachedMesh){ji._RemoveAndStorePivotPoint(this.attachedMesh);const e=this.attachedMesh.parent;this.attachedMesh.setParent(null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=W.PT.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=W.PT.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);const t=this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren,this.includeChildPredicate);t.max.subtractToRef(t.min,this._boundingDimensions),this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions),this._lineBoundingBox.position.set((t.max.x+t.min.x)/2,(t.max.y+t.min.y)/2,(t.max.z+t.min.z)/2),this._rotateAnchorsParent.position.copyFrom(this._lineBoundingBox.position),this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position),this._lineBoundingBox.computeWorldMatrix(),this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),this.attachedMesh.setParent(e)}this._updateRotationAnchors(),this._updateScaleBoxes(),this.attachedMesh&&(this._existingMeshScale.copyFrom(this.attachedMesh.scaling),ji._RestorePivotPoint(this.attachedMesh))}_updateRotationAnchors(){const e=this._rotateAnchorsParent.getChildMeshes();for(let t=0;t<3;t++)for(let i=0;i<2;i++)for(let r=0;r<2;r++){const s=4*t+2*i+r;e[s].position.normalizeToRef(W.AA.Vector3[0]),0==t&&(e[s].position.set(0,this._boundingDimensions.y*(i-.5),this._boundingDimensions.z*(r-.5)),W.AA.Vector3[1].set(1,0,0)),1==t&&(e[s].position.set(this._boundingDimensions.x*(i-.5),0,this._boundingDimensions.z*(r-.5)),W.AA.Vector3[1].set(0,1,0)),2==t&&(e[s].position.set(this._boundingDimensions.x*(i-.5),this._boundingDimensions.y*(r-.5),0),W.AA.Vector3[1].set(0,0,1));const n=W.AA.Vector3[2];if(W.Pq.CrossToRef(W.AA.Vector3[0],W.AA.Vector3[1],n),n.normalize(),n.addInPlace(e[s].position),e[s].lookAt(n),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[s].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);const t=this.rotationSphereSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[s].scaling.set(t,t,t)}else this.fixedDragMeshBoundsSize?e[s].scaling.set(this.rotationSphereSize*this._boundingDimensions.x,this.rotationSphereSize*this._boundingDimensions.y,this.rotationSphereSize*this._boundingDimensions.z):e[s].scaling.set(this.rotationSphereSize,this.rotationSphereSize,this.rotationSphereSize)}}_updateScaleBoxes(){const e=this._scaleBoxesParent.getChildMeshes();let t=0;for(let i=0;i<3;i++)for(let r=0;r<3;r++)for(let s=0;s<3;s++){const n=(1===i?1:0)+(1===r?1:0)+(1===s?1:0);if(1!==n&&3!==n){if(e[t])if(e[t].position.set(this._boundingDimensions.x*(i/2),this._boundingDimensions.y*(r/2),this._boundingDimensions.z*(s/2)),e[t].position.addInPlace(new W.Pq(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[t].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.globalPosition,this._tmpVector);const i=this.scaleBoxSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[t].scaling.set(i,i,i)}else this.fixedDragMeshBoundsSize?e[t].scaling.set(this.scaleBoxSize*this._boundingDimensions.x,this.scaleBoxSize*this._boundingDimensions.y,this.scaleBoxSize*this._boundingDimensions.z):e[t].scaling.set(this.scaleBoxSize,this.scaleBoxSize,this.scaleBoxSize);t++}}}setEnabledRotationAxis(e){this._rotateAnchorsParent.getChildMeshes().forEach(((t,i)=>{i<4?t.setEnabled(-1!=e.indexOf("x")):i<8?t.setEnabled(-1!=e.indexOf("y")):t.setEnabled(-1!=e.indexOf("z"))}))}setEnabledScaling(e,t=!1){this._scaleBoxesParent.getChildMeshes().forEach((i=>{let r=e;t&&!0===i._internalMetadata&&(r=!1),i.setEnabled(r)}))}_updateDummy(){this._dragMesh&&(this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition()),this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling),this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion))}enableDragBehavior(){this._dragMesh=Ko("dummy",{size:1},this.gizmoLayer.utilityLayerScene),this._dragMesh.visibility=0,this._dragMesh.rotationQuaternion=new W.PT,this._pointerDragBehavior.useObjectOrientationForDragging=!1,this._dragMesh.addBehavior(this._pointerDragBehavior)}releaseDrag(){this._scaleBoxesDragBehaviors.forEach((e=>{e.releaseDrag()})),this._rotateAnchorsDragBehaviors.forEach((e=>{e.releaseDrag()})),this._pointerDragBehavior.releaseDrag()}dispose(){this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver),this._lineBoundingBox.dispose(),this._rotateAnchorsParent.dispose(),this._scaleBoxesParent.dispose(),this._dragMesh&&this._dragMesh.dispose(),this._scaleBoxesDragBehaviors.length=0,this._rotateAnchorsDragBehaviors.length=0,this.onDragStartObservable.clear(),this.onHoverStartObservable.clear(),this.onHoverEndObservable.clear(),this.onScaleBoxDragObservable.clear(),this.onScaleBoxDragEndObservable.clear(),this.onRotationSphereDragObservable.clear(),this.onRotationSphereDragEndObservable.clear(),super.dispose()}static MakeNotPickableAndWrapInBoundingBox(e){const t=e=>{e.isPickable=!1,e.getChildMeshes().forEach((e=>{t(e)}))};t(e),e.rotationQuaternion||(e.rotationQuaternion=W.PT.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z));const i=e.position.clone(),r=e.rotationQuaternion.clone();e.rotationQuaternion.set(0,0,0,1),e.position.set(0,0,0);const s=Ko("box",{size:1},e.getScene()),n=e.getHierarchyBoundingVectors();return n.max.subtractToRef(n.min,s.scaling),0===s.scaling.y&&(s.scaling.y=lt.bH),0===s.scaling.x&&(s.scaling.x=lt.bH),0===s.scaling.z&&(s.scaling.z=lt.bH),s.position.set((n.max.x+n.min.x)/2,(n.max.y+n.min.y)/2,(n.max.z+n.min.z)/2),e.addChild(s),e.rotationQuaternion.copyFrom(r),e.position.copyFrom(i),e.removeChild(s),s.addChild(e),s.visibility=0,s}setCustomMesh(){Z.V.Error("Custom meshes are not supported on this gizmo")}}class im extends Go{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}set rotationColor(e){this._rotationShaderMaterial.setColor3("rotationColor",e)}get disableMaterial(){return this._disableMaterial}constructor(e,t=H.v9.Gray(),i=Bo.DefaultUtilityLayer,r=32,s=null,n=!1,o=1,a=H.v9.Yellow(),l=H.v9.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new z.cP,this.angle=0,this.sensitivity=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new W.Pq,this._parent=s,this._coloredMaterial=new Un("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new H.v9(.1,.1,.1)),this._hoverMaterial=new Un("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=a,this._hoverMaterial.specularColor=a,this._disableMaterial=new Un("",i.utilityLayerScene),this._disableMaterial.diffuseColor=l,this._disableMaterial.alpha=.4,this._gizmoMesh=new Yt("",i.utilityLayerScene);const{rotationMesh:h,collider:c}=this._createGizmoMesh(this._gizmoMesh,o,r);this._rotationDisplayPlane=Qi("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=.5*Math.PI,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),Cl.M.ShadersStore.rotationGizmoVertexShader=im._RotationGizmoVertexShader,Cl.M.ShadersStore.rotationGizmoFragmentShader=im._RotationGizmoFragmentShader,this._rotationShaderMaterial=new xo("shader",this.gizmoLayer.utilityLayerScene,{vertex:"rotationGizmo",fragment:"rotationGizmo"},{attributes:["position","uv"],uniforms:["worldViewProjection","angles","rotationColor"]}),this._rotationShaderMaterial.backFaceCulling=!1,this.rotationColor=a,this._rotationDisplayPlane.material=this._rotationShaderMaterial,this._rotationDisplayPlane.visibility=.999,this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,Go.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new Ji({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=im.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);const u=new W.Pq,d=new W.uq,f=new W.Pq;let p=new W.Pq;this.dragBehavior.onDragStartObservable.add((e=>{this.attachedNode&&(u.copyFrom(e.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(d),W.Pq.TransformCoordinatesToRef(e.dragPlanePoint,d,u),this._angles.x=Math.atan2(u.y,u.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,u.copyFrom(e.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)}));const _={snapDistance:0};let m=0;const g=new W.uq,v=new W.PT;this.dragBehavior.onDragObservable.add((t=>{if(this.attachedNode){const r=new W.Pq(1,1,1),s=new W.PT(0,0,0,1),n=new W.Pq(0,0,0);if(this.attachedNode.getWorldMatrix().decompose(r,s,n),!(Math.abs(Math.abs(r.x)-Math.abs(r.y))<=lt.bH&&Math.abs(Math.abs(r.x)-Math.abs(r.z))<=lt.bH)&&this.updateGizmoRotationToMatchAttachedMesh)return void Z.V.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");s.normalize();const o=this.updateGizmoPositionToMatchAttachedMesh?n:this._rootMesh.absolutePosition,a=t.dragPlanePoint.subtract(o).normalize(),l=u.subtract(o).normalize(),h=W.Pq.Cross(a,l),c=W.Pq.Dot(a,l);let x=Math.atan2(h.length(),c)*this.sensitivity;f.copyFrom(e),p.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(s.toRotationMatrix(d),p=W.Pq.TransformCoordinates(f,d));let b=!1;if(i.utilityLayerScene.activeCamera){const e=i.utilityLayerScene.activeCamera.position.subtract(o).normalize();W.Pq.Dot(e,p)>0&&(f.scaleInPlace(-1),p.scaleInPlace(-1),b=!0)}W.Pq.Dot(p,h)>0&&(x=-x),W.AA.Vector3[0].set(x,0,0),this.dragBehavior.validateDrag(W.AA.Vector3[0])||(x=0);let S=!1;if(0!=this.snapDistance)if(m+=x,Math.abs(m)>this.snapDistance){let e=Math.floor(Math.abs(m)/this.snapDistance);m<0&&(e*=-1),m%=this.snapDistance,x=this.snapDistance*e,S=!0}else x=0;const T=Math.sin(x/2);if(v.set(f.x*T,f.y*T,f.z*T,Math.cos(x/2)),g.determinant()>0){const e=new W.Pq;v.toEulerAnglesToRef(e),W.PT.RotationYawPitchRollToRef(e.y,-e.x,-e.z,v)}if(this.updateGizmoRotationToMatchAttachedMesh)s.multiplyToRef(v,s),s.normalize(),W.uq.ComposeToRef(r,s,n,this.attachedNode.getWorldMatrix());else{v.toRotationMatrix(W.AA.Matrix[0]);const e=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(W.AA.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(e)}u.copyFrom(t.dragPlanePoint),S&&(_.snapDistance=x,this.onSnapObservable.notifyObservers(_)),this._angles.y+=x,this.angle+=b?-x:x,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}}));const x=i._getSharedGizmoLight();x.includedOnlyMeshes=x.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const b={colliderMeshes:[c],gizmoMeshes:[h],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,b),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=im.MaxDragAngle,this._isHovered=!(-1==b.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),!this._parent)){const e=b.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(b.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(b.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}))}_createGizmoMesh(e,t,i){const r=ao("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);r.visibility=0;const s=ao("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,r.rotation.x=Math.PI/2,e.addChild(s,Go.PreserveScaling),e.addChild(r,Go.PreserveScaling),{rotationMesh:s,collider:r}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}}im.MaxDragAngle=9*Math.PI/20,im._RotationGizmoVertexShader="\n precision highp float;\n attribute vec3 position;\n attribute vec2 uv;\n uniform mat4 worldViewProjection;\n varying vec3 vPosition;\n varying vec2 vUV;\n\n void main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n vUV = uv;\n }",im._RotationGizmoFragmentShader="\n precision highp float;\n varying vec2 vUV;\n varying vec3 vPosition;\n uniform vec3 angles;\n uniform vec3 rotationColor;\n\n #define twopi 6.283185307\n\n void main(void) {\n vec2 uv = vUV - vec2(0.5);\n float angle = atan(uv.y, uv.x) + 3.141592;\n float delta = gl_FrontFacing ? angles.y : -angles.y;\n float begin = angles.x - delta * angles.z;\n float start = (begin < (begin + delta)) ? begin : (begin + delta);\n float end = (begin > (begin + delta)) ? begin : (begin + delta);\n float len = sqrt(dot(uv,uv));\n float opacity = 1. - step(0.5, len);\n\n float base = abs(floor(start / twopi)) * twopi;\n start += base;\n end += base;\n\n float intensity = 0.;\n for (int i = 0; i < 5; i++)\n {\n intensity += max(step(start, angle) - step(end, angle), 0.);\n angle += twopi;\n }\n gl_FragColor = vec4(rotationColor, min(intensity * 0.25, 0.8)) * opacity;\n }\n ";class rm extends Go{get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}_checkBillboardTransform(){this._nodeAttached&&this._nodeAttached.billboardMode&&Z.V.Log("Rotation Gizmo will not work with transforms in billboard mode.")}set sensitivity(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t&&(t.sensitivity=e)}))}get sensitivity(){return this._sensitivity}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.additionalTransformNode=e}))}constructor(e=Bo.DefaultUtilityLayer,t=32,i=!1,r=1,s,n){super(e),this.onDragStartObservable=new z.cP,this.onDragObservable=new z.cP,this.onDragEndObservable=new z.cP,this._observables=[],this._sensitivity=1,this._gizmoAxisCache=new Map;const o=n&&n.xOptions&&n.xOptions.color?n.xOptions.color:H.v9.Red().scale(.5),a=n&&n.yOptions&&n.yOptions.color?n.yOptions.color:H.v9.Green().scale(.5),l=n&&n.zOptions&&n.zOptions.color?n.zOptions.color:H.v9.Blue().scale(.5);this.xGizmo=new im(new W.Pq(1,0,0),o,e,t,this,i,r),this.yGizmo=new im(new W.Pq(0,1,0),a,e,t,this,i,r),this.zGizmo=new im(new W.Pq(0,0,1),l,e,t,this,i,r),this.additionalTransformNode=n?.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((e=>{n&&null!=n.updateScale&&(e.updateScale=n.updateScale),e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((()=>{this.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,this.attachedNode=null,s?s.addToAxisCache(this._gizmoAxisCache):Go.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}set updateGizmoRotationToMatchAttachedMesh(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)}get updateGizmoRotationToMatchAttachedMesh(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this.xGizmo&&(this.xGizmo.updateGizmoPositionToMatchAttachedMesh=e,this.yGizmo.updateGizmoPositionToMatchAttachedMesh=e,this.zGizmo.updateGizmoPositionToMatchAttachedMesh=e)}get updateGizmoPositionToMatchAttachedMesh(){return this.xGizmo.updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.anchorPoint=e}))}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.coordinatesMode=e}))}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}set snapDistance(e){this.xGizmo&&(this.xGizmo.snapDistance=e,this.yGizmo.snapDistance=e,this.zGizmo.snapDistance=e)}get snapDistance(){return this.xGizmo.snapDistance}set scaleRatio(e){this.xGizmo&&(this.xGizmo.scaleRatio=e,this.yGizmo.scaleRatio=e,this.zGizmo.scaleRatio=e)}get scaleRatio(){return this.xGizmo.scaleRatio}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t&&(t.customRotationQuaternion=e)}))}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag()}dispose(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose(),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear(),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)})),super.dispose()}setCustomMesh(){Z.V.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)")}}class sm extends Go{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreatePlane(e,t){const i=new Pt("plane",e),r=Qi("dragPlane",{width:.1375,height:.1375,sideOrientation:2},e);return r.material=t,r.parent=i,i}constructor(e,t=H.v9.Gray(),i=Bo.DefaultUtilityLayer,r=null,s=H.v9.Yellow(),n=H.v9.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new z.cP,this._isEnabled=!1,this._parent=null,this._dragging=!1,this._parent=r,this._coloredMaterial=new Un("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new H.v9(.1,.1,.1)),this._hoverMaterial=new Un("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=s,this._disableMaterial=new Un("",i.utilityLayerScene),this._disableMaterial.diffuseColor=n,this._disableMaterial.alpha=.4,this._gizmoMesh=sm._CreatePlane(i.utilityLayerScene,this._coloredMaterial),this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._gizmoMesh.scaling.scaleInPlace(1/3),this._gizmoMesh.parent=this._rootMesh;let o=0;const a=new W.Pq,l={snapDistance:0};this.dragBehavior=new Ji({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add((e=>{if(this.attachedNode){if(0==this.snapDistance)this.attachedNode.getWorldMatrix().getTranslationToRef(W.AA.Vector3[0]),W.AA.Vector3[0].addToRef(e.delta,W.AA.Vector3[0]),this.dragBehavior.validateDrag(W.AA.Vector3[0])&&this.attachedNode.getWorldMatrix().addTranslationFromFloats(e.delta.x,e.delta.y,e.delta.z);else if(o+=e.dragDistance,Math.abs(o)>this.snapDistance){const t=Math.floor(Math.abs(o)/this.snapDistance);o%=this.snapDistance,e.delta.normalizeToRef(a),a.scaleInPlace(this.snapDistance*t),this.attachedNode.getWorldMatrix().getTranslationToRef(W.AA.Vector3[0]),W.AA.Vector3[0].addToRef(a,W.AA.Vector3[0]),this.dragBehavior.validateDrag(W.AA.Vector3[0])&&(this.attachedNode.getWorldMatrix().addTranslationFromFloats(a.x,a.y,a.z),l.snapDistance=this.snapDistance*t,this.onSnapObservable.notifyObservers(l))}this._matrixChanged()}})),this.dragBehavior.onDragStartObservable.add((()=>{this._dragging=!0})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1}));const h=i._getSharedGizmoLight();h.includedOnlyMeshes=h.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const c={gizmoMeshes:this._gizmoMesh.getChildMeshes(),colliderMeshes:this._gizmoMesh.getChildMeshes(),material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,c),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(!this._customMeshSet&&(this._isHovered=!(-1==c.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),!this._parent)){const e=c.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(c.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(c.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}))}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedNode=this._parent.attachedNode):this.attachedNode=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),super.dispose(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()}))}}class nm extends Go{get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered||this.xPlaneGizmo.isHovered||this.yPlaneGizmo.isHovered||this.zPlaneGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging||this.xPlaneGizmo.dragBehavior.dragging||this.yPlaneGizmo.dragBehavior.dragging||this.zPlaneGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.additionalTransformNode=e}))}constructor(e=Bo.DefaultUtilityLayer,t=1,i,r){super(e),this._meshAttached=null,this._nodeAttached=null,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new z.cP,this.onDragObservable=new z.cP,this.onDragEndObservable=new z.cP,this._planarGizmoEnabled=!1,this.xGizmo=new zo(new W.Pq(1,0,0),H.v9.Red().scale(.5),e,this,t),this.yGizmo=new zo(new W.Pq(0,1,0),H.v9.Green().scale(.5),e,this,t),this.zGizmo=new zo(new W.Pq(0,0,1),H.v9.Blue().scale(.5),e,this,t),this.xPlaneGizmo=new sm(new W.Pq(1,0,0),H.v9.Red().scale(.5),this.gizmoLayer,this),this.yPlaneGizmo=new sm(new W.Pq(0,1,0),H.v9.Green().scale(.5),this.gizmoLayer,this),this.zPlaneGizmo=new sm(new W.Pq(0,0,1),H.v9.Blue().scale(.5),this.gizmoLayer,this),this.additionalTransformNode=r?.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((e=>{e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((()=>{this.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,i?i.addToAxisCache(this._gizmoAxisCache):Go.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}set planarGizmoEnabled(e){this._planarGizmoEnabled=e,[this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.isEnabled=e,e&&(t.attachedMesh?t.attachedMesh=this.attachedMesh:t.attachedNode=this.attachedNode))}),this)}get planarGizmoEnabled(){return this._planarGizmoEnabled}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.customRotationQuaternion=e)}))}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.updateGizmoRotationToMatchAttachedMesh=e)}))}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.updateGizmoPositionToMatchAttachedMesh=e)}))}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.anchorPoint=e}))}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.coordinatesMode=e}))}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}set snapDistance(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.snapDistance=e)}))}get snapDistance(){return this._snapDistance}set scaleRatio(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag(),this.xPlaneGizmo.dragBehavior.releaseDrag(),this.yPlaneGizmo.dragBehavior.releaseDrag(),this.zPlaneGizmo.dragBehavior.releaseDrag()}dispose(){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((e=>{e&&e.dispose()})),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)})),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear(),super.dispose()}setCustomMesh(){Z.V.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo,gizmo.xPlaneGizmo, gizmo.yPlaneGizmo, gizmo.zPlaneGizmo)")}}class om extends Go{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered||this.uniformScaleGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging||this.uniformScaleGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t.additionalTransformNode=e}))}constructor(e=Bo.DefaultUtilityLayer,t=1,i,r){super(e),this._meshAttached=null,this._nodeAttached=null,this._incrementalSnap=!1,this._sensitivity=1,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new z.cP,this.onDragObservable=new z.cP,this.onDragEndObservable=new z.cP,this.uniformScaleGizmo=this._createUniformScaleMesh(),this.xGizmo=new J_(new W.Pq(1,0,0),H.v9.Red().scale(.5),e,this,t),this.yGizmo=new J_(new W.Pq(0,1,0),H.v9.Green().scale(.5),e,this,t),this.zGizmo=new J_(new W.Pq(0,0,1),H.v9.Blue().scale(.5),e,this,t),this.additionalTransformNode=r?.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((e=>{e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((()=>{this.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,this.attachedNode=null,i?i.addToAxisCache(this._gizmoAxisCache):Go.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}_createUniformScaleMesh(){this._coloredMaterial=new Un("",this.gizmoLayer.utilityLayerScene),this._coloredMaterial.diffuseColor=H.v9.Gray(),this._hoverMaterial=new Un("",this.gizmoLayer.utilityLayerScene),this._hoverMaterial.diffuseColor=H.v9.Yellow(),this._disableMaterial=new Un("",this.gizmoLayer.utilityLayerScene),this._disableMaterial.diffuseColor=H.v9.Gray(),this._disableMaterial.alpha=.4;const e=new J_(new W.Pq(0,1,0),H.v9.Gray().scale(.5),this.gizmoLayer,this);e.updateGizmoRotationToMatchAttachedMesh=!1,e.uniformScaling=!0,this._uniformScalingMesh=Ka("uniform",{type:1},e.gizmoLayer.utilityLayerScene),this._uniformScalingMesh.scaling.scaleInPlace(.01),this._uniformScalingMesh.visibility=0,this._octahedron=Ka("",{type:1},e.gizmoLayer.utilityLayerScene),this._octahedron.scaling.scaleInPlace(.007),this._uniformScalingMesh.addChild(this._octahedron),e.setCustomMesh(this._uniformScalingMesh,!0);const t=this.gizmoLayer._getSharedGizmoLight();t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._octahedron);const i={gizmoMeshes:[this._octahedron,this._uniformScalingMesh],colliderMeshes:[this._octahedron,this._uniformScalingMesh],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:e.dragBehavior};return this.addToAxisCache(e._rootMesh,i),e}set updateGizmoRotationToMatchAttachedMesh(e){e?(this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.updateGizmoRotationToMatchAttachedMesh=e)}))):Z.V.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.")}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.anchorPoint=e)}))}get anchorPoint(){return this._anchorPoint}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.customRotationQuaternion=e)}))}set coordinatesMode(e){0==e&&Z.V.Warn("Setting coordinates Mode to world on scaling gizmo is not supported."),[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((e=>{e.coordinatesMode=1}))}set snapDistance(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.snapDistance=e)}))}get snapDistance(){return this._snapDistance}set incrementalSnap(e){this._incrementalSnap=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.incrementalSnap=e)}))}get incrementalSnap(){return this._incrementalSnap}set scaleRatio(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}set sensitivity(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.sensitivity=e)}))}get sensitivity(){return this._sensitivity}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}getAxisCache(e){return this._gizmoAxisCache.get(e)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag(),this.uniformScaleGizmo.dragBehavior.releaseDrag()}dispose(){[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((e=>{e&&e.dispose()})),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)})),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear(),[this._uniformScalingMesh,this._octahedron].forEach((e=>{e&&e.dispose()})),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()}))}}class am{get keepDepthUtilityLayer(){return this._defaultKeepDepthUtilityLayer}get utilityLayer(){return this._defaultUtilityLayer}get isHovered(){let e=!1;for(const t in this.gizmos){const i=this.gizmos[t];if(i&&i.isHovered){e=!0;break}}return e}get isDragging(){let e=!1;return[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo,this.gizmos.boundingBoxGizmo].forEach((t=>{t&&t.isDragging&&(e=!0)})),e}set scaleRatio(e){this._scaleRatio=e,[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}set coordinatesMode(e){this._coordinatesMode=e,[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo].forEach((t=>{t&&(t.coordinatesMode=e)}))}get coordinatesMode(){return this._coordinatesMode}get attachedMesh(){return this._attachedMesh}get attachedNode(){return this._attachedNode}get additionalTransformNode(){return this._additionalTransformNode}constructor(e,t=1,i=Bo.DefaultUtilityLayer,r=Bo.DefaultKeepDepthUtilityLayer){this._scene=e,this.clearGizmoOnEmptyPointerEvent=!1,this.enableAutoPicking=!0,this.onAttachedToMeshObservable=new z.cP,this.onAttachedToNodeObservable=new z.cP,this._gizmosEnabled={positionGizmo:!1,rotationGizmo:!1,scaleGizmo:!1,boundingBoxGizmo:!1},this._pointerObservers=[],this._attachedMesh=null,this._attachedNode=null,this._boundingBoxColor=H.v9.FromHexString("#0984e3"),this._thickness=1,this._scaleRatio=1,this._coordinatesMode=1,this._gizmoAxisCache=new Map,this.boundingBoxDragBehavior=new ir,this.attachableMeshes=null,this.attachableNodes=null,this.usePointerToAttachGizmos=!0,this._defaultUtilityLayer=i,this._defaultKeepDepthUtilityLayer=r,this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,this._thickness=t,this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null};const s=this._attachToMeshPointerObserver(e),n=Go.GizmoAxisPointerObserver(this._defaultUtilityLayer,this._gizmoAxisCache);this._pointerObservers=[s,n]}_attachToMeshPointerObserver(e){const t=e.onPointerObservable.add((e=>{if(this.usePointerToAttachGizmos&&e.type==yi.Zp.POINTERDOWN)if(e.pickInfo&&e.pickInfo.pickedMesh){if(this.enableAutoPicking){let t=e.pickInfo.pickedMesh;if(null==this.attachableMeshes)for(;t&&null!=t.parent;)t=t.parent;else{let e=!1;this.attachableMeshes.forEach((i=>{t&&(t==i||t.isDescendantOf(i))&&(t=i,e=!0)})),e||(t=null)}t instanceof Nt?this._attachedMesh!=t&&this.attachToMesh(t):this.clearGizmoOnEmptyPointerEvent&&this.attachToMesh(null)}}else this.clearGizmoOnEmptyPointerEvent&&this.attachToMesh(null)}));return t}attachToMesh(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=e,this._attachedNode=null;for(const t in this.gizmos){const i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedMesh=e)}this.boundingBoxGizmoEnabled&&this._attachedMesh&&this._attachedMesh.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToMeshObservable.notifyObservers(e)}attachToNode(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=null,this._attachedNode=e;for(const t in this.gizmos){const i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedNode=e)}this.boundingBoxGizmoEnabled&&this._attachedNode&&this._attachedNode.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToNodeObservable.notifyObservers(e)}set positionGizmoEnabled(e){e?(this.gizmos.positionGizmo||(this.gizmos.positionGizmo=new nm(this._defaultUtilityLayer,this._thickness,this)),this._attachedNode?this.gizmos.positionGizmo.attachedNode=this._attachedNode:this.gizmos.positionGizmo.attachedMesh=this._attachedMesh):this.gizmos.positionGizmo&&(this.gizmos.positionGizmo.attachedNode=null),this._gizmosEnabled.positionGizmo=e,this._setAdditionalTransformNode()}get positionGizmoEnabled(){return this._gizmosEnabled.positionGizmo}set rotationGizmoEnabled(e){e?(this.gizmos.rotationGizmo||(this.gizmos.rotationGizmo=new rm(this._defaultUtilityLayer,32,!1,this._thickness,this)),this._attachedNode?this.gizmos.rotationGizmo.attachedNode=this._attachedNode:this.gizmos.rotationGizmo.attachedMesh=this._attachedMesh):this.gizmos.rotationGizmo&&(this.gizmos.rotationGizmo.attachedNode=null),this._gizmosEnabled.rotationGizmo=e,this._setAdditionalTransformNode()}get rotationGizmoEnabled(){return this._gizmosEnabled.rotationGizmo}set scaleGizmoEnabled(e){e?(this.gizmos.scaleGizmo=this.gizmos.scaleGizmo||new om(this._defaultUtilityLayer,this._thickness,this),this._attachedNode?this.gizmos.scaleGizmo.attachedNode=this._attachedNode:this.gizmos.scaleGizmo.attachedMesh=this._attachedMesh):this.gizmos.scaleGizmo&&(this.gizmos.scaleGizmo.attachedNode=null),this._gizmosEnabled.scaleGizmo=e,this._setAdditionalTransformNode()}get scaleGizmoEnabled(){return this._gizmosEnabled.scaleGizmo}set boundingBoxGizmoEnabled(e){e?(this.gizmos.boundingBoxGizmo=this.gizmos.boundingBoxGizmo||new tm(this._boundingBoxColor,this._defaultKeepDepthUtilityLayer),this._attachedMesh?this.gizmos.boundingBoxGizmo.attachedMesh=this._attachedMesh:this.gizmos.boundingBoxGizmo.attachedNode=this._attachedNode,this._attachedMesh?(this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh.addBehavior(this.boundingBoxDragBehavior)):this._attachedNode&&(this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode.addBehavior(this.boundingBoxDragBehavior))):this.gizmos.boundingBoxGizmo&&(this._attachedMesh?this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior):this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this.gizmos.boundingBoxGizmo.attachedNode=null),this._gizmosEnabled.boundingBoxGizmo=e,this._setAdditionalTransformNode()}get boundingBoxGizmoEnabled(){return this._gizmosEnabled.boundingBoxGizmo}set additionalTransformNode(e){this._additionalTransformNode=e,this._setAdditionalTransformNode()}_setAdditionalTransformNode(){for(const e in this.gizmos){const t=this.gizmos[e];t&&this._gizmosEnabled[e]&&(t.additionalTransformNode=this._additionalTransformNode)}}addToAxisCache(e){e.size>0&&e.forEach(((e,t)=>{this._gizmoAxisCache.set(t,e)}))}releaseDrag(){[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo,this.gizmos.boundingBoxGizmo].forEach((e=>{e?.releaseDrag()}))}dispose(){this._pointerObservers.forEach((e=>{this._scene.onPointerObservable.remove(e)}));for(const e in this.gizmos){const t=this.gizmos[e];t&&t.dispose()}this._defaultKeepDepthUtilityLayer!==Bo._DefaultKeepDepthUtilityLayer&&this._defaultKeepDepthUtilityLayer?.dispose(),this._defaultUtilityLayer!==Bo._DefaultUtilityLayer&&this._defaultUtilityLayer?.dispose(),this.boundingBoxDragBehavior.detach(),this.onAttachedToMeshObservable.clear()}}class lm extends $t{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=W.uq.Identity(),this._projectionMatrix=W.uq.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=W.Pq.Zero()),W.Pq.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=W.Pq.Zero()),W.Pq.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),0))}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=W.Pq.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=W.Pq.Cross(this.direction,Mt._0.Y),t=W.Pq.Cross(e,this.direction);return W.Pq.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=W.Pq.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=W.uq.Identity()),W.uq.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 void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ}getDepthMaxZ(e){return void 0!==this.shadowMaxZ?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.AA.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),W.Pq.NormalizeToRef(this.getShadowDirection(e),t),1===Math.abs(W.Pq.Dot(t,W.Pq.Up()))&&(t.z=1e-13);const r=W.AA.Vector3[1];return i.addToRef(t,r),W.uq.LookAtLHToRef(i,r,W.Pq.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}(0,je.Cg)([(0,$e.P_)()],lm.prototype,"position",null),(0,je.Cg)([(0,$e.P_)()],lm.prototype,"direction",null),(0,je.Cg)([(0,$e.lK)()],lm.prototype,"shadowMinZ",null),(0,je.Cg)([(0,$e.lK)()],lm.prototype,"shadowMaxZ",null),Ze.b.AddNodeConstructor("Light_Type_1",((e,t)=>()=>new hm(e,W.Pq.Zero(),t)));class hm extends lm{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 $t.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&&W.uq.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:t.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:t.maxZ,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,i){const r=this.getScene().activeCamera;if(!r)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const e=W.Pq.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let r=Number.MAX_VALUE,s=-Number.MAX_VALUE;for(let n=0;nthis._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.zs&&(s=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=r,this._shadowMaxZ=s)}const s=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,o=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;W.uq.OrthoOffCenterLHToRef(this._orthoLeft-s*this.shadowOrthoScale,this._orthoRight+s*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,l?a:o,l?o:a,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}}function cm(e,t={},i){t.diameter||(t.diameter=1),t.segments||(t.segments=16);const r=Qo("",{slice:.5,diameter:t.diameter,segments:t.segments},i),s=da("",{radius:t.diameter/2,tessellation:3*t.segments+(4-t.segments)},i);s.rotation.x=-Math.PI/2,s.parent=r;const n=Yt.MergeMeshes([s,r],!0);return n.name=e,n}(0,je.Cg)([(0,$e.lK)()],hm.prototype,"shadowFrustumSize",null),(0,je.Cg)([(0,$e.lK)()],hm.prototype,"shadowOrthoScale",null),(0,je.Cg)([(0,$e.lK)()],hm.prototype,"autoUpdateExtends",void 0),(0,je.Cg)([(0,$e.lK)()],hm.prototype,"autoCalcShadowZBounds",void 0),(0,je.Cg)([(0,$e.lK)("orthoLeft")],hm.prototype,"_orthoLeft",void 0),(0,je.Cg)([(0,$e.lK)("orthoRight")],hm.prototype,"_orthoRight",void 0),(0,je.Cg)([(0,$e.lK)("orthoTop")],hm.prototype,"_orthoTop",void 0),(0,je.Cg)([(0,$e.lK)("orthoBottom")],hm.prototype,"_orthoBottom",void 0),(0,X.Y5)("BABYLON.DirectionalLight",hm);const um={CreateHemisphere:cm};Yt.CreateHemisphere=(e,t,i,r)=>cm(e,{segments:t,diameter:i},r),Ze.b.AddNodeConstructor("Light_Type_2",((e,t)=>()=>new dm(e,W.Pq.Zero(),W.Pq.Zero(),0,0,t)));class dm extends lm{get angle(){return this._angle}set angle(e){this._angle=e,this._cosHalfAngle=Math.cos(.5*e),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()&&(dm._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled((()=>{this._markMeshesAsLightDirty()})):dm._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce((()=>{this._markMeshesAsLightDirty()}))))}static _IsProceduralTexture(e){return void 0!==e.onGeneratedObservable}static _IsTexture(e){return void 0!==e.onLoadObservable}get projectionTextureProjectionLightMatrix(){return this._projectionTextureProjectionLightMatrix}set projectionTextureProjectionLightMatrix(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0}constructor(e,t,i,r,s,n){super(e,n),this._innerAngle=0,this._projectionTextureMatrix=W.uq.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=W.Pq.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=W.Pq.Zero(),this._projectionTextureViewLightMatrix=W.uq.Zero(),this._projectionTextureProjectionLightMatrix=W.uq.Zero(),this._projectionTextureScalingMatrix=W.uq.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=r,this.exponent=s}getClassName(){return"SpotLight"}getTypeID(){return $t.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const r=this.getScene().activeCamera;if(!r)return;this._shadowAngleScale=this._shadowAngleScale||1;const s=this._shadowAngleScale*this._angle,n=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;W.uq.PerspectiveFovLHToRef(s,1,a?o:n,a?n:o,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,a)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.getShadowDirection(),this._projectionTextureViewTargetVector),W.uq.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;const e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),r=-i*t,s=1/Math.tan(this._angle/2);W.uq.FromValuesToRef(s/1,0,0,0,0,s,0,0,0,0,i,1,0,0,r,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof vi.g){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;W.uq.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(.5*this._innerAngle)-this._cosHalfAngle),this._lightAngleOffset=-this._cosHalfAngle*this._lightAngleScale}transferTexturesToEffect(e,t){return this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+t,this._projectionTextureMatrix),e.setTexture("projectionLightTexture"+t,this.projectionTexture)),this}transferToEffect(e,t){let i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=W.Pq.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=W.Pq.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 i=this.computeTransformedInformation()?W.Pq.Normalize(this.transformedDirection):W.Pq.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=void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMaxZ?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())}}(0,je.Cg)([(0,$e.lK)()],dm.prototype,"angle",null),(0,je.Cg)([(0,$e.lK)()],dm.prototype,"innerAngle",null),(0,je.Cg)([(0,$e.lK)()],dm.prototype,"shadowAngleScale",null),(0,je.Cg)([(0,$e.lK)()],dm.prototype,"exponent",void 0),(0,je.Cg)([(0,$e.lK)()],dm.prototype,"projectionTextureLightNear",null),(0,je.Cg)([(0,$e.lK)()],dm.prototype,"projectionTextureLightFar",null),(0,je.Cg)([(0,$e.lK)()],dm.prototype,"projectionTextureUpDirection",null),(0,je.Cg)([(0,$e.uM)("projectedLightTexture")],dm.prototype,"_projectionTexture",void 0),(0,X.Y5)("BABYLON.SpotLight",dm);class fm extends Go{constructor(e=Bo.DefaultUtilityLayer){super(e),this._cachedPosition=new W.Pq,this._cachedForward=new W.Pq(0,0,1),this._pointerObserver=null,this.onClickedObservable=new z.cP,this._light=null,this.attachedMesh=new Yt("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new Pt("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new Un("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new H.v9(.5,.5,.5),this._material.specularColor=new H.v9(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._light&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._light))}),yi.Zp.POINTERDOWN)}get attachedNode(){return this.attachedMesh}set attachedNode(e){Z.V.Warn("Nodes cannot be attached to LightGizmo. Attach to a mesh instead.")}set light(e){if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),this._lightMesh=e instanceof Lo?fm._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof hm?fm._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof dm?fm._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):fm._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._lightMesh.parent=this._rootMesh;const t=this.gizmoLayer._getSharedGizmoLight();if(t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new W.PT,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.parent&&this._attachedMeshParent.freezeWorldMatrix(e.parent.getWorldMatrix()),e.position&&(this.attachedMesh.position.copyFrom(e.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)),e.direction){this.attachedMesh.setDirection(e.direction),this.attachedMesh.computeWorldMatrix(!0);const t=this._getMeshForward();this._cachedForward.copyFrom(t)}this._update()}}get light(){return this._light}get material(){return this._material}_getMeshForward(){let e=this.attachedMesh.forward;return this.attachedMesh.getScene().useRightHandedSystem&&(e.negateToRef(W.AA.Vector3[0]),e=W.AA.Vector3[0]),e}_update(){if(super._update(),this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position)if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{const e=this.attachedMesh.position;this._light.position=new W.Pq(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}if(this._light.direction){const e=this._getMeshForward();if(W.Pq.DistanceSquared(e,this._cachedForward)>1e-4){const t=e;this._light.direction=new W.Pq(t.x,t.y,t.z),this._cachedForward.copyFrom(e)}else W.Pq.DistanceSquared(e,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(e))}}}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),super.dispose(),this._attachedMeshParent.dispose()}static _CreateHemisphericLightMesh(e){const t=new Yt("hemisphereLight",e),i=cm(t.name,{segments:10,diameter:1},e);return i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(3,e).parent=t,t.scaling.scaleInPlace(fm._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){const t=new Yt("pointLight",e),i=Qo(t.name,{segments:10,diameter:1},e);return i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(5,e).parent=t,t.scaling.scaleInPlace(fm._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){const t=new Yt("spotLight",e);Qo(t.name,{segments:10,diameter:1},e).parent=t;const i=cm(t.name,{segments:10,diameter:2},e);return i.parent=t,i.rotation.x=-Math.PI/2,this._CreateLightLines(2,e).parent=t,t.scaling.scaleInPlace(fm._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){const t=new Yt("directionalLight",e),i=new Yt(t.name,e);i.parent=t,Qo(t.name,{diameter:1.2,segments:10},e).parent=i;const r=No(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);r.parent=i;let s=r.clone(t.name);s.scaling.y=.5,s.position.x+=1.25;let n=r.clone(t.name);n.scaling.y=.5,n.position.x+=-1.25;const o=No(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return o.position.y+=3,o.parent=i,s=o.clone(t.name),s.position.y=1.5,s.position.x+=1.25,n=o.clone(t.name),n.position.y=1.5,n.position.x+=-1.25,i.scaling.scaleInPlace(fm._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}}fm._Scale=.007,fm._CreateLightLines=(e,t)=>{const i=new Yt("root",t);i.rotation.x=Math.PI/2;const r=new Yt("linePivot",t);r.parent=i;const s=No("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},t);if(s.position.y=s.scaling.y/2+1.2,s.parent=r,e<2)return r;for(let e=0;e<4;e++){const t=r.clone("lineParentClone");t.rotation.z=Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(let e=0;e<4;e++){const t=r.clone("linePivotClone");t.rotation.z=Math.PI/2,t.rotation.y=Math.PI/2*e}if(e<4)return i;for(let e=0;e<4;e++){const t=r.clone("linePivotClone");t.rotation.z=Math.PI+Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}return e<5||(r.clone("linePivotClone").rotation.z=Math.PI),i};class pm extends Go{constructor(e=Bo.DefaultUtilityLayer,t,i){super(e),this._pointerObserver=null,this.onClickedObservable=new z.cP,this._camera=null,this._invProjection=new hc.uq,this._material=new Un("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._frustumLinesColor=i,this._material.diffuseColor=t??new H.v9(.5,.5,.5),this._material.specularColor=new H.v9(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._camera&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._camera))}),yi.Zp.POINTERDOWN)}get displayFrustum(){return this._cameraLinesMesh.isEnabled()}set displayFrustum(e){this._cameraLinesMesh.setEnabled(e)}set camera(e){if(this._camera=e,this.attachedNode=e,e){this._customMeshSet||(this._cameraMesh&&this._cameraMesh.dispose(),this._cameraMesh=pm._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._cameraMesh.parent=this._rootMesh),this._cameraLinesMesh&&this._cameraLinesMesh.dispose();const t=this._frustumLinesColor?.toColor4(1)??new H.ov(1,1,1,1);this._cameraLinesMesh=pm._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene,t),this._cameraLinesMesh.parent=this._rootMesh,this.gizmoLayer.utilityLayerScene.activeCamera&&this.gizmoLayer.utilityLayerScene.activeCamera.maxZ<1.5*e.maxZ&&(this.gizmoLayer.utilityLayerScene.activeCamera.maxZ=1.5*e.maxZ),this.attachedNode.reservedDataStore||(this.attachedNode.reservedDataStore={}),this.attachedNode.reservedDataStore.cameraGizmo=this;const i=this.gizmoLayer._getSharedGizmoLight();i.includedOnlyMeshes=i.includedOnlyMeshes.concat(this._cameraMesh.getChildMeshes(!1)),this._update()}}get camera(){return this._camera}get material(){return this._material}_update(){super._update(),this._camera&&(this._camera.getProjectionMatrix().invertToRef(this._invProjection),this._cameraLinesMesh.setPivotMatrix(this._invProjection,!1),this._cameraLinesMesh.scaling.x=1/this._rootMesh.scaling.x,this._cameraLinesMesh.scaling.y=1/this._rootMesh.scaling.y,this._cameraLinesMesh.scaling.z=1/this._rootMesh.scaling.z,this._cameraMesh.parent=null,this._cameraMesh.rotation.y=.5*Math.PI*(this._camera.getScene().useRightHandedSystem?1:-1),this._cameraMesh.parent=this._rootMesh)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._cameraMesh&&this._cameraMesh.dispose(),this._cameraMesh=e,this._cameraMesh.parent=this._rootMesh,this._customMeshSet=!0}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._material.dispose(),super.dispose()}static _CreateCameraMesh(e){const t=new Yt("rootCameraGizmo",e),i=new Yt(t.name,e);i.parent=t,Ko(t.name,{width:1,height:.8,depth:.5},e).parent=i;const r=No(t.name,{height:.5,diameterTop:.8,diameterBottom:.8},e);r.parent=i,r.position.y=.3,r.position.x=-.6,r.rotation.x=.5*Math.PI;const s=No(t.name,{height:.5,diameterTop:.6,diameterBottom:.6},e);s.parent=i,s.position.y=.5,s.position.x=.4,s.rotation.x=.5*Math.PI;const n=No(t.name,{height:.5,diameterTop:.5,diameterBottom:.5},e);return n.parent=i,n.position.y=0,n.position.x=.6,n.rotation.z=.5*Math.PI,t.scaling.scaleInPlace(pm._Scale),i.position.x=-.9,t}static _CreateCameraFrustum(e,t){const i=new Yt("rootCameraGizmo",e),r=new Yt(i.name,e);r.parent=i;for(let i=0;i<4;i+=2)for(let s=0;s<4;s+=2){let n=Ra("lines",{points:[new W.Pq(-1+s,-1+i,-1),new W.Pq(-1+s,-1+i,1)],colors:[t,t]},e);n.parent=r,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1,n=Ra("lines",{points:[new W.Pq(-1,-1+s,-1+i),new W.Pq(1,-1+s,-1+i)],colors:[t,t]},e),n.parent=r,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1,n=Ra("lines",{points:[new W.Pq(-1+s,-1,-1+i),new W.Pq(-1+s,1,-1+i)],colors:[t,t]},e),n.parent=r,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1}return i}}pm._Scale=.05;class _m extends ms.w{get direction(){return this._effectWrapper.direction}set direction(e){this._effectWrapper.direction=e}set kernel(e){this._effectWrapper.kernel=e}get kernel(){return this._effectWrapper.kernel}set packedFloat(e){this._effectWrapper.packedFloat=e}get packedFloat(){return this._effectWrapper.packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,r,s=null,n=vi.g.BILINEAR_SAMPLINGMODE,o,a,l=0,h="",c=!1,u=5){const d="number"==typeof r?c:!!r.blockCompilation,f={uniforms:p_.Uniforms,samplers:p_.Samplers,size:"number"==typeof r?r:void 0,camera:s,samplingMode:n,engine:o,reusable:a,textureType:l,vertexUrl:p_.VertexUrl,indexParameters:{varyingCount:0,depCount:0},textureFormat:u,defines:h,...r,blockCompilation:!0};super(e,p_.FragmentUrl,{effectWrapper:"number"!=typeof r&&r.effectWrapper?void 0:new p_(e,o,void 0,void 0,f),...f}),this._effectWrapper.options.blockCompilation=d,this.direction=t,this.onApplyObservable.add((()=>{this._effectWrapper.textureWidth=this._outputTexture?this._outputTexture.width:this.width,this._effectWrapper.textureHeight=this._outputTexture?this._outputTexture.height:this.height})),this.kernel=i}updateEffect(e=null,t=null,i=null,r,s,n){this._effectWrapper._updateParameters(s,n)}static _Parse(e,t,i,r){return it.p.Parse((()=>new _m(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1)),e,i,r)}}(0,je.Cg)([(0,$e.WM)()],_m.prototype,"direction",null),(0,je.Cg)([(0,$e.lK)()],_m.prototype,"kernel",null),(0,je.Cg)([(0,$e.lK)()],_m.prototype,"packedFloat",null),(0,X.Y5)("BABYLON.BlurPostProcess",_m);class mm extends ln.${set blurRatio(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())}get blurRatio(){return this._blurRatio}set adaptiveBlurKernel(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()}set blurKernel(e){this.blurKernelX=e,this.blurKernelY=e}set blurKernelX(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())}get blurKernelX(){return this._blurKernelX}set blurKernelY(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())}get blurKernelY(){return this._blurKernelY}_autoComputeBlurKernel(){const e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i}_onRatioRescale(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()}_updateGammaSpace(){const e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}constructor(e,t,i,r,s=0,n=vi.g.BILINEAR_SAMPLINGMODE,o=!0){if(super(e,t,i,r,!0,s,!1,n,o),this.mirrorPlane=new Ft.Z(0,1,0,1),this._transformMatrix=W.uq.Zero(),this._mirrorMatrix=W.uq.Zero(),this._adaptiveBlurKernel=0,this._blurKernelX=0,this._blurKernelY=0,this._blurRatio=1,!(i=this.getScene()))return this;let a;this.ignoreCameraViewport=!0,this._updateGammaSpace(),this._imageProcessingConfigChangeObserver=i.imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateGammaSpace()})),i.getEngine().supportsUniformBuffers&&(this._sceneUBO=i.createSceneUniformBuffer(`Scene for Mirror Texture (name "${e}")`)),this.onBeforeRenderObservable.add((()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),W.uq.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),a=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=W.Pq.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)})),this.onAfterRenderObservable.add((()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=a}))}_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 _m("horizontal blur",new W.I9(1,0),this._blurKernelX,this._blurRatio,null,vi.g.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new _m("vertical blur",new W.I9(0,1),this._blurKernelY,this._blurRatio,null,vi.g.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,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 mm(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(){super.dispose();const e=this.getScene();e&&e.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),this._sceneUBO?.dispose()}}vi.g._CreateMirror=(e,t,i,r)=>new mm(e,t,i,r);class gm extends js.t{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(W.uq.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let r="";return e.forEach((e=>r+=e)),new gm(r,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,r=!0){const s=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const n=new gm(e,t,null,!1,null,null,null,void 0,!0,i,r);return t.useDelayedTextureLoading=s,n}constructor(e,t,i=null,r=!1,s=null,n=null,o=null,a=5,l=!1,h=null,c=!1,u=.8,d=0,f,p){super(t),this.onLoadObservable=new z.cP,this.boundingBoxPosition=W.Pq.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new W.uq,this._buffer=null,this.name=e,this.url=e,this._noMipmap=r,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=W.uq.Identity(),this.coordinatesMode=vi.g.CUBIC_MODE;let _=null,m=null;null===i||Array.isArray(i)?(this._noMipmap=r,this._format=a,this._createPolynomials=c,_=i,this._loaderOptions=f,this._useSRGBBuffer=p,this._lodScale=u,this._lodOffset=d):(_=i.extensions??null,this._noMipmap=i.noMipmap??!1,s=i.files??null,m=i.buffer??null,this._format=i.format??5,l=i.prefiltered??!1,h=i.forcedExtension??null,this._createPolynomials=i.createPolynomials??!1,this._lodScale=i.lodScale??.8,this._lodOffset=i.lodOffset??0,this._loaderOptions=i.loaderOptions,this._useSRGBBuffer=i.useSRGBBuffer,n=i.onLoad??null,o=i.onError??null),(e||s)&&this.updateURL(e,h,n,l,o,_,this.getScene()?.useDelayedTextureLoading,s,m)}getClassName(){return"CubeTexture"}updateURL(e,t=null,i=null,r=!1,s=null,n=null,o=!1,a=null,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=0===c.indexOf(".dds"),d=0===c.indexOf(".env"),f=0===c.indexOf(".basis");if(d?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=r,r&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),a)this._files=a;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 t=0;t-1!==e.getActiveTextures().indexOf(this))),this._textureMatrix=e,!this.getScene()?.useRightHandedSystem)return;const t=W.AA.Vector3[0],i=W.AA.Quaternion[0],r=W.AA.Vector3[1];this._textureMatrix.decompose(t,i,r),i.z*=-1,i.w*=-1,W.uq.ComposeToRef(t,i,r,this._textureMatrixRefraction)}getRefractionTextureMatrix(){return this.getScene()?.useRightHandedSystem?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){const i=this.getScene(),r=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const s=()=>{this.onLoadObservable.notifyObservers(this),r&&(r.dispose(),this.getScene()?.markAllMaterialsAsDirty(1)),e&&e()},n=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),vi.g.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?Ue.S0.SetImmediate((()=>s())):this._texture.onLoadedObservable.add((()=>s())):(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,this._buffer),this._texture?.onLoadedObservable.add((()=>this.onLoadObservable.notifyObservers(this))))}static Parse(e,t,i){const r=it.p.Parse((()=>{let r=!1;return e.prefiltered&&(r=e.prefiltered),new gm(i+(e.url??e.name),t,e.extensions,!1,e.files||null,null,null,void 0,r,e.forcedExtension)}),e,t);if(e.boundingBoxPosition&&(r.boundingBoxPosition=W.Pq.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=W.Pq.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t{const t=new gm(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t}),this);return t.uniqueId=e,t}}(0,je.Cg)([(0,$e.lK)()],gm.prototype,"url",void 0),(0,je.Cg)([(0,$e.P_)()],gm.prototype,"boundingBoxPosition",void 0),(0,je.Cg)([(0,$e.P_)()],gm.prototype,"boundingBoxSize",null),(0,je.Cg)([(0,$e.lK)("rotationY")],gm.prototype,"rotationY",null),(0,je.Cg)([(0,$e.lK)("files")],gm.prototype,"_files",void 0),(0,je.Cg)([(0,$e.lK)("forcedExtension")],gm.prototype,"_forcedExtension",void 0),(0,je.Cg)([(0,$e.lK)("extensions")],gm.prototype,"_extensions",void 0),(0,je.Cg)([(0,$e.GG)("textureMatrix")],gm.prototype,"_textureMatrix",void 0),(0,je.Cg)([(0,$e.GG)("textureMatrixRefraction")],gm.prototype,"_textureMatrixRefraction",void 0),vi.g._CubeTextureParser=gm.Parse,(0,X.Y5)("BABYLON.CubeTexture",gm);class vm extends xn{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 xm extends bn{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*=2,this.reflectionReflectance0=xm.StandardReflectance0*t,this.reflectionReflectance90=xm.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=xm.StandardReflectance0+(1-xm.StandardReflectance0)*t,this.reflectionReflectance90=xm.StandardReflectance90+(1-xm.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),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()}))))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this.imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this.imageProcessingConfiguration.colorCurves=e}constructor(e,t,i=!1){super(e,t,void 0,i),this.primaryColor=H.v9.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=W.Pq.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 Qe.L(16),this._reflectionControls=W.IU.Zero(),this._white=H.v9.White(),this._primaryShadowColor=H.v9.Black(),this._primaryHighlightColor=H.v9.Black(),this._shadersLoaded=!1,this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._renderTargets.push(this._diffuseTexture),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._renderTargets)}get hasRenderTargetTextures(){return!(!this._diffuseTexture||!this._diffuseTexture.isRenderTarget)||!(!this._reflectionTexture||!this._reflectionTexture.isRenderTarget)}needAlphaTesting(){return!0}needAlphaBlending(){return this.alpha<1||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||this._shadowOnly}isReadyForSubMesh(e,t,r=!1){const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===r)return!0;t.materialDefines||(t.materialDefines=new vm);const n=this.getScene(),o=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const a=n.getEngine();if((0,Bt.az)(n,e,o,!1,this._maxSimultaneousLights),o._needNormals=!0,(0,Bt.VO)(n,o),o._areTexturesDirty){if(o._needUVs=!1,n.texturesEnabled){if(n.getEngine().getCaps().textureLOD&&(o.TEXTURELODSUPPORT=!0),this._diffuseTexture&&Sn.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;(0,Bt.YT)(this._diffuseTexture,o,"DIFFUSE"),o.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,o.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,o.OPACITYFRESNEL=this._opacityFresnel}else o.DIFFUSE=!1,o.DIFFUSEDIRECTUV=0,o.DIFFUSEHASALPHA=!1,o.GAMMADIFFUSE=!1,o.OPACITYFRESNEL=!1;const e=this._reflectionTexture;if(e&&Sn.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;switch(o.REFLECTION=!0,o.GAMMAREFLECTION=e.gammaSpace,o.RGBDREFLECTION=e.isRGBD,o.REFLECTIONBLUR=this._reflectionBlur>0,o.LODINREFLECTIONALPHA=e.lodLevelInAlpha,o.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,o.REFLECTIONBGR=this.switchToBGR,e.coordinatesMode===vi.g.INVCUBIC_MODE&&(o.INVERTCUBICMAP=!0),o.REFLECTIONMAP_3D=e.isCube,o.REFLECTIONMAP_OPPOSITEZ=o.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,e.coordinatesMode){case vi.g.EXPLICIT_MODE:o.REFLECTIONMAP_EXPLICIT=!0;break;case vi.g.PLANAR_MODE:o.REFLECTIONMAP_PLANAR=!0;break;case vi.g.PROJECTION_MODE:o.REFLECTIONMAP_PROJECTION=!0;break;case vi.g.SKYBOX_MODE:o.REFLECTIONMAP_SKYBOX=!0;break;case vi.g.SPHERICAL_MODE:o.REFLECTIONMAP_SPHERICAL=!0;break;case vi.g.EQUIRECTANGULAR_MODE:o.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case vi.g.FIXED_EQUIRECTANGULAR_MODE:o.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case vi.g.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:o.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case vi.g.CUBIC_MODE:case vi.g.INVCUBIC_MODE:default:o.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(o.REFLECTIONFRESNEL=!0,o.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):(o.REFLECTIONFRESNEL=!1,o.REFLECTIONFALLOFF=!1)}else o.REFLECTION=!1,o.REFLECTIONFRESNEL=!1,o.REFLECTIONFALLOFF=!1,o.REFLECTIONBLUR=!1,o.REFLECTIONMAP_3D=!1,o.REFLECTIONMAP_SPHERICAL=!1,o.REFLECTIONMAP_PLANAR=!1,o.REFLECTIONMAP_CUBIC=!1,o.REFLECTIONMAP_PROJECTION=!1,o.REFLECTIONMAP_SKYBOX=!1,o.REFLECTIONMAP_EXPLICIT=!1,o.REFLECTIONMAP_EQUIRECTANGULAR=!1,o.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,o.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,o.INVERTCUBICMAP=!1,o.REFLECTIONMAP_OPPOSITEZ=!1,o.LODINREFLECTIONALPHA=!1,o.GAMMAREFLECTION=!1,o.RGBDREFLECTION=!1}o.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,o.USERGBCOLOR=this._useRGBColor,o.NOISE=this._enableNoise}if(o._areLightsDirty&&(o.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel),o.BACKMAT_SHADOWONLY=this._shadowOnly),o._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(o)}if(o._areMiscDirty&&(o.REFLECTIONMAP_3D&&this._enableGroundProjection?(o.PROJECTED_GROUND=!0,o.REFLECTIONMAP_SKYBOX=!0):o.PROJECTED_GROUND=!1),(0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),o),(0,Bt.OR)(n,a,this,o,r,null,t.getRenderingMesh().hasThinInstances),(0,Bt.qB)(e,o,!1,!0,!1)&&e&&(n.getEngine().getCaps().standardDerivatives||e.isVerticesDataPresent(st.R.NormalKind)||(e.createNormals(!0),Z.V.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name))),o.isDirty){o.markAsProcessed(),n.resetCachedMaterial();const r=new Tn;o.FOG&&r.addFallback(0,"FOG"),o.POINTSIZE&&r.addFallback(1,"POINTSIZE"),o.MULTIVIEW&&r.addFallback(0,"MULTIVIEW"),(0,Bt.c4)(o,r,this._maxSimultaneousLights);const s=[st.R.PositionKind];o.NORMAL&&s.push(st.R.NormalKind),o.UV1&&s.push(st.R.UVKind),o.UV2&&s.push(st.R.UV2Kind),(0,Bt.ni)(s,e,o,r),(0,Bt.ER)(s,o);const l=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos","logarithmicDepthConstant"];(0,Ln.TV)(l);const h=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],c=["Material","Scene"];gn.p&&(gn.p.PrepareUniforms(l,o),gn.p.PrepareSamplers(h,o)),(0,Bt.Bb)({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:o,maxSimultaneousLights:this._maxSimultaneousLights});const u=o.toString(),d=n.getEngine().createEffect("background",{attributes:s,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:u,fallbacks:r,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights},shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{1===this.shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,18135)),Promise.resolve().then(i.bind(i,61853))]):await Promise.all([Promise.resolve().then(i.bind(i,80723)),Promise.resolve().then(i.bind(i,91341))]),this._shadersLoaded=!0}},a);t.setEffect(d,o,this._materialContext),this.buildUniformLayout()}return!(!t.effect||!t.effect.isReady()||(o._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=r,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(){0===this._primaryColorShadowLevel&&0===this._primaryColorHighlightLevel||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))}buildUniformLayout(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.addUniform("projectedGroundInfos",2),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),(0,Bt.f$)(t,this._activeEffect);const o=this._mustRebind(r,n,i,t.visibility);if(o){this._uniformBuffer.bindToEffect(n,"Material"),this.bindViewProjection(n);const e=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync&&!i._drawWrapper._forceRebindOnNextCall||(r.texturesEnabled&&(this._diffuseTexture&&Sn.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),(0,Bt.mA)(this._diffuseTexture,this._uniformBuffer,"diffuse")),e&&Sn.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",e.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",e.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",e.getSize().width,e.lodGenerationScale,e.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),s.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),r.texturesEnabled&&(this._diffuseTexture&&Sn.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),e&&Sn.ReflectionTextureEnabled&&(s.REFLECTIONBLUR&&s.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",e):s.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",e._lodTextureMid||e),this._uniformBuffer.setTexture("reflectionSamplerLow",e._lodTextureLow||e),this._uniformBuffer.setTexture("reflectionSamplerHigh",e._lodTextureHigh||e)):this._uniformBuffer.setTexture("reflectionSampler",e),s.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w))),s.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),(0,Ln.gS)(this._activeEffect,this,r),r.bindEyePosition(n)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(n,"Material"),this._needToBindSceneUbo=!0);!o&&this.isFrozen||(r.lightsEnabled&&(0,Bt.RL)(r,t,this._activeEffect,s,this._maxSimultaneousLights),this.bindView(n),(0,Bt.Yy)(r,t,this._activeEffect,!0),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),this._uniformBuffer.update()}hasTexture(e){return!!super.hasTexture(e)||this._reflectionTexture===e||this._diffuseTexture===e}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return it.p.Clone((()=>new xm(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new xm(e.name,t)),e,t,i)}}xm.StandardReflectance0=.05,xm.StandardReflectance90=.5,(0,je.Cg)([(0,$e.jT)()],xm.prototype,"_primaryColor",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],xm.prototype,"primaryColor",void 0),(0,je.Cg)([(0,$e.jT)()],xm.prototype,"__perceptualColor",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_primaryColorShadowLevel",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_primaryColorHighlightLevel",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],xm.prototype,"primaryColorHighlightLevel",null),(0,je.Cg)([(0,$e.uM)()],xm.prototype,"_reflectionTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"reflectionTexture",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_reflectionBlur",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"reflectionBlur",void 0),(0,je.Cg)([(0,$e.uM)()],xm.prototype,"_diffuseTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"diffuseTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"shadowLights",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_shadowLevel",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"shadowLevel",void 0),(0,je.Cg)([(0,$e.P_)()],xm.prototype,"_sceneCenter",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"sceneCenter",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_opacityFresnel",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"opacityFresnel",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_reflectionFresnel",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"reflectionFresnel",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_reflectionFalloffDistance",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"reflectionFalloffDistance",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_reflectionAmount",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"reflectionAmount",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_reflectionReflectance0",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"reflectionReflectance0",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_reflectionReflectance90",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"reflectionReflectance90",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_useRGBColor",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"useRGBColor",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_enableNoise",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"enableNoise",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xm.prototype,"maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"_shadowOnly",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],xm.prototype,"shadowOnly",void 0),(0,je.Cg)([(0,$e.n1)()],xm.prototype,"_imageProcessingConfiguration",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],xm.prototype,"enableGroundProjection",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"projectedGroundRadius",void 0),(0,je.Cg)([(0,$e.lK)()],xm.prototype,"projectedGroundHeight",void 0),(0,X.Y5)("BABYLON.BackgroundMaterial",xm);class bm{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new H.v9(.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 H.v9(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:W.Pq.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=(e,t)=>{this.onErrorObservable.notifyObservers({message:e,exception:t})},this._options={...bm._GetDefaultOptions(t),...e},this._scene=t,this.onErrorObservable=new z.cP,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 H.ov(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 js.t)return void(this._scene.environmentTexture=this._options.environmentTexture);const e=gm.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new Yt("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||1===this._scene.meshes.length)return{groundSize:e,skyboxSize:t,rootPosition:i};const r=this._scene.getWorldExtends((e=>e!==this._ground&&e!==this._rootMesh&&e!==this._skybox)),s=r.max.subtract(r.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof is&&this._scene.activeCamera.upperRadiusLimit&&(e=2*this._scene.activeCamera.upperRadiusLimit,t=e);const n=s.length();n>e&&(e=2*n,t=e),e*=1.1,t*=1.5,i=r.min.add(s.scale(.5)),i.y=r.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){this._ground&&!this._ground.isDisposed()||(this._ground=Qi("BackgroundPlane",{size:e.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.isPickable=!1,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add((()=>{this._ground=null}))),this._ground.receiveShadows=this._options.enableGroundShadow}_setupGroundMaterial(){this._groundMaterial||(this._groundMaterial=new xm("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(){this._groundMaterial&&(this._groundTexture||(this._options.groundTexture instanceof js.t?this._groundMaterial.diffuseTexture=this._options.groundTexture:(this._groundTexture=new vi.g(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=vi.g.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new mm("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,vi.g.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new Ft.Z(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let e=0;e{this._skybox=null}))),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new xm("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){this._skyboxMaterial&&(this._skyboxTexture||(this._options.skyboxTexture instanceof js.t?this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture:(this._skyboxTexture=new gm(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=vi.g.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)}}bm._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",bm._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",bm._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class Sm extends Pt{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=vi.g.CLAMP_ADDRESSMODE,this._texture.wrapV=vi.g.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=vi.g.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=vi.g.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}constructor(e,t,i,r,s=null){super(e,r),this.onError=s,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=Sm.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new z.cP,this.onLoadObservable=new z.cP,r=this.getScene(),e=e||"textureDome",i.resolution=0|Math.abs(i.resolution)||32,i.clickToPlay=Boolean(i.clickToPlay),i.autoPlay=void 0===i.autoPlay||Boolean(i.autoPlay),i.loop=void 0===i.loop||Boolean(i.loop),i.size=Math.abs(i.size)||(r.activeCamera?.48*r.activeCamera.maxZ:1e3),void 0===i.useDirectMapping?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,void 0===i.faceForward&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=Qo(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:Yt.BACKSIDE},r);const n=this._material=new xm(e+"_material",r);n.useEquirectangularFOV=!0,n.fovMultiplier=1,n.opacityFresnel=!1;const o=this._initTexture(t,r,i);if(this.texture=o,this._mesh.material=n,this._mesh.parent=this,this._halfDomeMask=Qo("",{slice:.5,diameter:.98*i.size,segments:2*i.resolution,sideOrientation:Yt.BACKSIDE},r),this._halfDomeMask.rotate(hc._0.X,-Math.PI/2),this._halfDomeMask.parent=this._mesh,this._halfDome=!!i.halfDomeMode,this._halfDomeMask.setEnabled(this._halfDome),this._crossEye=!!i.crossEyeMode,this._texture.anisotropicFilteringLevel=1,this._texture.onLoadObservable.addOnce((()=>{this._setReady(!0)})),i.faceForward&&r.activeCamera){const e=r.activeCamera,t=W.Pq.Forward(),i=W.Pq.TransformNormal(t,e.getViewMatrix());i.normalize(),this.rotation.y=Math.acos(W.Pq.Dot(t,i))}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 Sm.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case Sm.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;const e=this._halfDome?0:.5,t=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((i=>{let r=i.isRightCamera;this._crossEye&&(r=!r),this._texture.uOffset=r?e:t}));break}case Sm.MODE_TOPBOTTOM:this._texture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((e=>{let t=e.isRightCamera;this._crossEye&&(t=!t),this._texture.vOffset=t?.5:0}))}}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)}}Sm.MODE_MONOSCOPIC=0,Sm.MODE_TOPBOTTOM=1,Sm.MODE_SIDEBYSIDE=2;class Tm extends Sm{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 vi.g(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,(()=>{this.onLoadObservable.notifyObservers()}),((e,t)=>{this.onLoadErrorObservable.notifyObservers(e||"Unknown error occured"),this.onError&&this.onError(e,t)}))}}Tm.MODE_MONOSCOPIC=Sm.MODE_MONOSCOPIC,Tm.MODE_TOPBOTTOM=Sm.MODE_TOPBOTTOM,Tm.MODE_SIDEBYSIDE=Sm.MODE_SIDEBYSIDE;var Cm=i(2069);let ym=0;const Em=e=>{if(!e.environmentBRDFTexture){const t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;const i=e._blockEntityCollection;e._blockEntityCollection=!1;const r=vi.g.CreateFromBase64String("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==","EnvironmentBRDFTexture"+ym++,e,!0,!1,vi.g.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;const s=e.getEngine().getLoadedTexturesCache(),n=s.indexOf(r.getInternalTexture());-1!==n&&s.splice(n,1),r.isRGBD=!0,r.wrapU=vi.g.CLAMP_ADDRESSMODE,r.wrapV=vi.g.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=r,e.useDelayedTextureLoading=t,Cm.G.ExpandRGBDTexture(r);const o=e.getEngine().onContextRestoredObservable.add((()=>{r.isRGBD=!0;const t=e.onBeforeRenderObservable.add((()=>{r.isReady()&&(e.onBeforeRenderObservable.remove(t),Cm.G.ExpandRGBDTexture(r))}))}));e.onDisposeObservable.add((()=>{e.getEngine().onContextRestoredObservable.remove(o)}))}return e.environmentBRDFTexture},Pm={GetEnvironmentBRDFTexture:Em};class Am extends xn{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 Rm extends Dn{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRBRDF",90,new Am,t),this._useEnergyConservation=Rm.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=Rm.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=Rm.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=Rm.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=Rm.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=Rm.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=Rm.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=Rm.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"}}Rm.DEFAULT_USE_ENERGY_CONSERVATION=!0,Rm.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,Rm.DEFAULT_USE_SPHERICAL_HARMONICS=!0,Rm.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],Rm.prototype,"useEnergyConservation",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],Rm.prototype,"useSmithVisibilityHeightCorrelated",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],Rm.prototype,"useSphericalHarmonics",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],Rm.prototype,"useSpecularGlossinessInputEnergyConservation",void 0),i(54699);class Im extends xn{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 Mm extends Dn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRClearCoat",100,new Im,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=Mm._DefaultIndexOfRefraction,this.indexOfRefraction=Mm._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=H.v9.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){if(!this._isEnabled)return!0;const r=this._material._disableBumpMap;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&Sn.ClearCoatTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&Sn.ClearCoatTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1;if(i.getCaps().standardDerivatives&&this._bumpTexture&&Sn.ClearCoatBumpTextureEnabled&&!r&&!this._bumpTexture.isReady())return!1;if(this._isTintEnabled&&this._tintTexture&&Sn.ClearCoatTintTextureEnabled&&!this._tintTexture.isReadyOrNotBlocking())return!1}return!0}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&&Sn.ClearCoatTextureEnabled?(0,Bt.YT)(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&Sn.ClearCoatTextureEnabled?(0,Bt.YT)(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&Sn.ClearCoatBumpTextureEnabled?(0,Bt.YT)(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===Mm._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&Sn.ClearCoatTintTextureEnabled?((0,Bt.YT)(this._tintTexture,e,"CLEARCOAT_TINT_TEXTURE"),e.CLEARCOAT_TINT_GAMMATEXTURE=this._tintTexture.gammaSpace):e.CLEARCOAT_TINT_TEXTURE=!1):(e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1))):(e.CLEARCOAT=!1,e.CLEARCOAT_TEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.CLEARCOAT_DEFAULTIOR=!1,e.CLEARCOAT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,e.CLEARCOAT_BUMPDIRECTUV=0,e.CLEARCOAT_REMAP_F0=!1,e.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TINT_GAMMATEXTURE=!1)}bindForSubMesh(e,t,i,r){if(!this._isEnabled)return;const s=r.materialDefines,n=this._material.isFrozen,o=this._material._disableBumpMap,a=this._material._invertNormalMapX,l=this._material._invertNormalMapY;if(!e.useUbo||!n||!e.isSync){(this._texture||this._textureRoughness)&&Sn.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._textureRoughness?.coordinatesIndex??0,this._textureRoughness?.level??0),this._texture&&(0,Bt.mA)(this._texture,e,"clearCoat"),this._textureRoughness&&!s.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&(0,Bt.mA)(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&Sn.ClearCoatTextureEnabled&&!o&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),(0,Bt.mA)(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",a?1:-1,l?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",a?-1:1,l?-1:1)),this._tintTexture&&Sn.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),(0,Bt.mA)(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);const r=1-this._indexOfRefraction,n=1+this._indexOfRefraction,h=Math.pow(-r/n,2),c=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",h,c,r,n),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&&Sn.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!s.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&Sn.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&Sn.ClearCoatBumpTextureEnabled&&!o&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&Sn.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){e&&(this._texture?.dispose(),this._textureRoughness?.dispose(),this._bumpTexture?.dispose(),this._tintTexture?.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"}]}}}Mm._DefaultIndexOfRefraction=1.5,(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"isEnabled",void 0),(0,je.Cg)([(0,$e.lK)()],Mm.prototype,"intensity",void 0),(0,je.Cg)([(0,$e.lK)()],Mm.prototype,"roughness",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"indexOfRefraction",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"texture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"useRoughnessFromMainTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"textureRoughness",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"remapF0OnInterfaceChange",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"bumpTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"isTintEnabled",void 0),(0,je.Cg)([(0,$e.jT)()],Mm.prototype,"tintColor",void 0),(0,je.Cg)([(0,$e.lK)()],Mm.prototype,"tintColorAtDistance",void 0),(0,je.Cg)([(0,$e.lK)()],Mm.prototype,"tintThickness",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Mm.prototype,"tintTexture",void 0);class Om extends xn{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 Dm extends Dn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRIridescence",110,new Om,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=Dm._DefaultMinimumThickness,this.maximumThickness=Dm._DefaultMaximumThickness,this.indexOfRefraction=Dm._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&Sn.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._thicknessTexture&&Sn.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.IRIDESCENCE=!0,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Sn.IridescenceTextureEnabled?(0,Bt.YT)(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,this._thicknessTexture&&Sn.IridescenceTextureEnabled?(0,Bt.YT)(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){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||((this._texture||this._thicknessTexture)&&Sn.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._thicknessTexture?.coordinatesIndex??0,this._thicknessTexture?.level??0),this._texture&&(0,Bt.mA)(this._texture,e,"iridescence"),this._thicknessTexture&&(0,Bt.mA)(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&Sn.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&Sn.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){e&&(this._texture?.dispose(),this._thicknessTexture?.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"}]}}}Dm._DefaultMinimumThickness=100,Dm._DefaultMaximumThickness=400,Dm._DefaultIndexOfRefraction=1.3,(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Dm.prototype,"isEnabled",void 0),(0,je.Cg)([(0,$e.lK)()],Dm.prototype,"intensity",void 0),(0,je.Cg)([(0,$e.lK)()],Dm.prototype,"minimumThickness",void 0),(0,je.Cg)([(0,$e.lK)()],Dm.prototype,"maximumThickness",void 0),(0,je.Cg)([(0,$e.lK)()],Dm.prototype,"indexOfRefraction",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Dm.prototype,"texture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Dm.prototype,"thicknessTexture",void 0);class wm extends xn{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class Nm extends Dn{set angle(e){this.direction.x=Math.cos(e),this.direction.y=Math.sin(e)}get angle(){return Math.atan2(this.direction.y,this.direction.x)}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markAllSubMeshesAsMiscDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsMiscDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new wm,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new W.I9(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&&Sn.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(st.R.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Sn.AnisotropicTextureEnabled?(0,Bt.YT)(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&&Sn.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),(0,Bt.mA)(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&Sn.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),void 0===e.legacy&&(this.legacy=!0)}}(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Nm.prototype,"isEnabled",void 0),(0,je.Cg)([(0,$e.lK)()],Nm.prototype,"intensity",void 0),(0,je.Cg)([(0,$e.WM)()],Nm.prototype,"direction",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Nm.prototype,"texture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],Nm.prototype,"legacy",void 0);class Fm extends xn{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 Lm extends Dn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"Sheen",120,new Fm,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=H.v9.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){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&Sn.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&Sn.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.SHEEN=!0,e.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,e.SHEEN_ROUGHNESS=null!==this._roughness,e.SHEEN_ALBEDOSCALING=this._albedoScaling,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Sn.SheenTextureEnabled?((0,Bt.YT)(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&Sn.SheenTextureEnabled?(0,Bt.YT)(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,r){if(!this._isEnabled)return;const s=r.materialDefines,n=this._material.isFrozen;e.useUbo&&n&&e.isSync||((this._texture||this._textureRoughness)&&Sn.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._textureRoughness?.coordinatesIndex??0,this._textureRoughness?.level??0),this._texture&&(0,Bt.mA)(this._texture,e,"sheen"),this._textureRoughness&&!s.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&(0,Bt.mA)(this._textureRoughness,e,"sheenRoughness")),e.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity),null!==this._roughness&&e.updateFloat("vSheenRoughness",this._roughness)),t.texturesEnabled&&(this._texture&&Sn.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!s.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&Sn.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){e&&(this._texture?.dispose(),this._textureRoughness?.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"}]}}}(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Lm.prototype,"isEnabled",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Lm.prototype,"linkSheenWithAlbedo",void 0),(0,je.Cg)([(0,$e.lK)()],Lm.prototype,"intensity",void 0),(0,je.Cg)([(0,$e.jT)()],Lm.prototype,"color",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Lm.prototype,"texture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Lm.prototype,"useRoughnessFromMainTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Lm.prototype,"roughness",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Lm.prototype,"textureRoughness",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Lm.prototype,"albedoScaling",void 0);class Bm extends xn{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 Vm extends Dn{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){this._volumeIndexOfRefraction=e>=1?e:-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRSubSurface",130,new Bm,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=H.v9.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=H.v9.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&&Sn.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;if(this._translucencyColorTexture&&Sn.TranslucencyColorTextureEnabled&&!this._translucencyColorTexture.isReadyOrNotBlocking())return!1;if(this._translucencyIntensityTexture&&Sn.TranslucencyIntensityTextureEnabled&&!this._translucencyIntensityTexture.isReadyOrNotBlocking())return!1;const e=this._getRefractionTexture(t);if(e&&Sn.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return 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,void(e.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0);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&&Sn.ThicknessTextureEnabled&&(0,Bt.YT)(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&Sn.RefractionIntensityTextureEnabled&&(0,Bt.YT)(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&Sn.TranslucencyIntensityTextureEnabled&&(0,Bt.YT)(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE"),this._translucencyColorTexture&&Sn.TranslucencyColorTextureEnabled&&(0,Bt.YT)(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&&Sn.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,r){if(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled)if(0===this.maximumThickness&&0===this.minimumThickness)e.updateFloat2("vThicknessParam",0,0);else{r.getRenderingMesh().getWorldMatrix().decompose(W.AA.Vector3[0]);const t=Math.max(Math.abs(W.AA.Vector3[0].x),Math.abs(W.AA.Vector3[0].y),Math.abs(W.AA.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*t,(this.maximumThickness-this.minimumThickness)*t)}}bindForSubMesh(e,t,i,r){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const s=r.materialDefines,n=this._material.isFrozen,o=this._material.realTimeFiltering,a=s.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&Sn.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),(0,Bt.mA)(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&Sn.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),(0,Bt.mA)(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyColorTexture&&Sn.TranslucencyColorTextureEnabled&&s.SS_TRANSLUCENCYCOLOR_TEXTURE&&(e.updateFloat2("vTranslucencyColorInfos",this._translucencyColorTexture.coordinatesIndex,this._translucencyColorTexture.level),(0,Bt.mA)(this._translucencyColorTexture,e,"translucencyColor")),this._translucencyIntensityTexture&&Sn.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),(0,Bt.mA)(this._translucencyIntensityTexture,e,"translucencyIntensity")),l&&Sn.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",l.getRefractionTextureMatrix());let t=1;l.isCube||l.depth&&(t=l.depth);const i=l.getSize().width,r=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",l.level,1/r,t,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",i,l.lodGenerationScale,l.lodGenerationOffset,1/this.indexOfRefraction),o&&e.updateFloat2("vRefractionFilteringInfo",i,Math.log2(i)),l.boundingBoxSize){const t=l;e.updateVector3("vRefractionPosition",t.boundingBoxPosition),e.updateVector3("vRefractionSize",t.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&&Sn.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&Sn.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&Sn.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),this._translucencyColorTexture&&Sn.TranslucencyColorTextureEnabled&&s.SS_TRANSLUCENCYCOLOR_TEXTURE&&e.setTexture("translucencyColorSampler",this._translucencyColorTexture),l&&Sn.RefractionTextureEnabled&&(a?e.setTexture("refractionSampler",l):(e.setTexture("refractionSampler",l._lodTextureMid||l),e.setTexture("refractionSamplerLow",l._lodTextureLow||l),e.setTexture("refractionSamplerHigh",l._lodTextureHigh||l))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){Sn.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!!(Sn.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture),this._translucencyColorTexture&&e.push(this._translucencyColorTexture),this._translucencyIntensityTexture&&e.push(this._translucencyIntensityTexture)}getAnimatables(e){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),this._translucencyColorTexture&&this._translucencyColorTexture.animations&&this._translucencyColorTexture.animations.length>0&&e.push(this._translucencyColorTexture),this._translucencyIntensityTexture&&this._translucencyIntensityTexture.animations&&this._translucencyIntensityTexture.animations.length>0&&e.push(this._translucencyIntensityTexture)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose(),this._translucencyColorTexture&&this._translucencyColorTexture.dispose(),this._translucencyIntensityTexture&&this._translucencyIntensityTexture.dispose())}getClassName(){return"PBRSubSurfaceConfiguration"}addFallbacks(e,t,i){return e.SS_SCATTERING&&t.addFallback(i++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i}getSamplers(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh","translucencyColorSampler")}getUniforms(){return{ubo:[{name:"vRefractionMicrosurfaceInfos",size:4,type:"vec4"},{name:"vRefractionFilteringInfo",size:2,type:"vec2"},{name:"vTranslucencyIntensityInfos",size:2,type:"vec2"},{name:"vRefractionInfos",size:4,type:"vec4"},{name:"refractionMatrix",size:16,type:"mat4"},{name:"vThicknessInfos",size:2,type:"vec2"},{name:"vRefractionIntensityInfos",size:2,type:"vec2"},{name:"thicknessMatrix",size:16,type:"mat4"},{name:"refractionIntensityMatrix",size:16,type:"mat4"},{name:"translucencyIntensityMatrix",size:16,type:"mat4"},{name:"vThicknessParam",size:2,type:"vec2"},{name:"vDiffusionDistance",size:3,type:"vec3"},{name:"vTintColor",size:4,type:"vec4"},{name:"vSubSurfaceIntensity",size:3,type:"vec3"},{name:"vRefractionPosition",size:3,type:"vec3"},{name:"vRefractionSize",size:3,type:"vec3"},{name:"scatteringDiffusionProfile",size:1,type:"float"},{name:"dispersion",size:1,type:"float"},{name:"vTranslucencyColor",size:4,type:"vec4"},{name:"vTranslucencyColorInfos",size:2,type:"vec2"},{name:"translucencyColorMatrix",size:16,type:"mat4"}]}}}(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"isRefractionEnabled",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"isTranslucencyEnabled",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"isDispersionEnabled",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markScenePrePassDirty")],Vm.prototype,"isScatteringEnabled",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"_scatteringDiffusionProfileIndex",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"refractionIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"translucencyIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"useAlbedoToTintRefraction",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"useAlbedoToTintTranslucency",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"thicknessTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"refractionTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"indexOfRefraction",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"_volumeIndexOfRefraction",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"volumeIndexOfRefraction",null),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"invertRefractionY",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"linkRefractionWithTransparency",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"minimumThickness",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"maximumThickness",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"useThicknessAsDepth",void 0),(0,je.Cg)([(0,$e.jT)()],Vm.prototype,"tintColor",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"tintColorAtDistance",void 0),(0,je.Cg)([(0,$e.lK)()],Vm.prototype,"dispersion",void 0),(0,je.Cg)([(0,$e.jT)()],Vm.prototype,"diffusionDistance",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"useMaskFromThicknessTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"refractionIntensityTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"translucencyIntensityTexture",void 0),(0,je.Cg)([(0,$e.jT)()],Vm.prototype,"translucencyColor",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"translucencyColorTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vm.prototype,"useGltfStyleTextures",void 0);const km={effect:null,subMesh:null};class Um extends xn{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_COLOR=!1,this.PREPASS_COLOR_INDEX=-1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO=!1,this.PREPASS_ALBEDO_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_SCREENSPACE_DEPTH=!1,this.PREPASS_SCREENSPACE_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_WORLD_NORMAL=!1,this.PREPASS_WORLD_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_LOCAL_POSITION=!1,this.PREPASS_LOCAL_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_VELOCITY_LINEAR=!1,this.PREPASS_VELOCITY_LINEAR_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}}class Gm extends bn{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),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}constructor(e,t,i=!1){super(e,t,void 0,i||Gm.ForceGLSL),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new W.IU(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=Gm.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=H.v9.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new H.v9(0,0,0),this._albedoColor=new H.v9(1,1,1),this._reflectivityColor=new H.v9(1,1,1),this._reflectionColor=new H.v9(1,1,1),this._emissiveColor=new H.v9(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=Gm.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 Qe.L(16),this._globalAmbientColor=new H.v9(0,0,0),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this._shadersLoaded=!1,this._breakShaderLoadedCheck=!1,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new Rm(this),this.clearCoat=new Mm(this),this.iridescence=new Dm(this),this.anisotropy=new Nm(this),this.sheen=new Lm(this),this.subSurface=new Vm(this),this.detailMap=new Nn(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),Sn.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=Em(this.getScene()),this.prePassConfiguration=new vn}get hasRenderTargetTextures(){return!!(Sn.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){return this._transparencyMode===Gm.PBRMATERIAL_OPAQUE||this._transparencyMode===Gm.PBRMATERIAL_ALPHATEST||this.subSurface?.disableAlphaBlending}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromAlbedoTexture())}needAlphaTesting(){return!!this._forceAlphaTest||!this.subSurface?.disableAlphaBlending&&this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===Gm.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==Gm.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new Um(this._eventInfo.defineNames));const s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=this.getScene(),o=n.getEngine();if(s._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n.texturesEnabled)){if(this._albedoTexture&&Sn.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking())return!1;if(this._ambientTexture&&Sn.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking())return!1;if(this._opacityTexture&&Sn.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const e=this._getReflectionTexture();if(e&&Sn.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture){if(!e.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!e.sphericalPolynomial&&e.getInternalTexture()?._sphericalPolynomialPromise)return!1}if(this._lightmapTexture&&Sn.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking())return!1;if(this._emissiveTexture&&Sn.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(Sn.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())return!1;if(this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking())return!1;if(this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(o.getCaps().standardDerivatives&&this._bumpTexture&&Sn.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady())return!1;if(this._environmentBRDFTexture&&Sn.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(s._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;o.getCaps().standardDerivatives||e.isVerticesDataPresent(st.R.NormalKind)||(e.createNormals(!0),Z.V.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const a=t.effect,l=s._areLightsDisposed;let h=this._prepareEffect(e,s,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),c=!1;if(h)if(this._onEffectCreatedObservable&&(km.effect=h,km.subMesh=t,this._onEffectCreatedObservable.notifyObservers(km)),this.allowShaderHotSwapping&&a&&!h.isReady()){if(h=a,s.markAsUnprocessed(),c=this.isFrozen,l)return s._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(h,s,this._materialContext);return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!c,r._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),0))}isMetallicWorkflow(){return!(null==this._metallic&&null==this._roughness&&!this._metallicTexture)}_prepareEffect(e,t,r=null,s=null,n=null,o=null,a){if(this._prepareDefines(e,t,n,o,a),!t.isDirty)return null;t.markAsProcessed();const l=this.getScene().getEngine(),h=new Tn;let c=0;t.USESPHERICALINVERTEX&&h.addFallback(c++,"USESPHERICALINVERTEX"),t.FOG&&h.addFallback(c,"FOG"),t.SPECULARAA&&h.addFallback(c,"SPECULARAA"),t.POINTSIZE&&h.addFallback(c,"POINTSIZE"),t.LOGARITHMICDEPTH&&h.addFallback(c,"LOGARITHMICDEPTH"),t.PARALLAX&&h.addFallback(c,"PARALLAX"),t.PARALLAX_RHS&&h.addFallback(c,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&h.addFallback(c++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&h.addFallback(c++,"ENVIRONMENTBRDF"),t.TANGENT&&h.addFallback(c++,"TANGENT"),t.BUMP&&h.addFallback(c++,"BUMP"),c=(0,Bt.c4)(t,h,this._maxSimultaneousLights,c++),t.SPECULARTERM&&h.addFallback(c++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&h.addFallback(c++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&h.addFallback(c++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&h.addFallback(c++,"LIGHTMAP"),t.NORMAL&&h.addFallback(c++,"NORMAL"),t.AMBIENT&&h.addFallback(c++,"AMBIENT"),t.EMISSIVE&&h.addFallback(c++,"EMISSIVE"),t.VERTEXCOLOR&&h.addFallback(c++,"VERTEXCOLOR"),t.MORPHTARGETS&&h.addFallback(c++,"MORPHTARGETS"),t.MULTIVIEW&&h.addFallback(0,"MULTIVIEW");const u=[st.R.PositionKind];t.NORMAL&&u.push(st.R.NormalKind),t.TANGENT&&u.push(st.R.TangentKind);for(let e=1;e<=6;++e)t["UV"+e]&&u.push(`uv${1===e?"":e}`);t.VERTEXCOLOR&&u.push(st.R.ColorKind),(0,Bt.ni)(u,e,t,h),(0,Bt.ER)(u,t),(0,Bt.IF)(u,e,t),(0,Bt.J2)(u,e,t);let d="pbr";const f=["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"],p=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],_=["Material","Scene","Mesh"],m={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=h,this._eventInfo.fallbackRank=c,this._eventInfo.defines=t,this._eventInfo.uniforms=f,this._eventInfo.attributes=u,this._eventInfo.samplers=p,this._eventInfo.uniformBuffersNames=_,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=m,this._callbackPluginEventGeneric(128,this._eventInfo),Bn.AddUniformsAndSamplers(f,p),vn.AddUniforms(f),vn.AddSamplers(p),(0,Ln.TV)(f),gn.p&&(gn.p.PrepareUniforms(f,t),gn.p.PrepareSamplers(p,t)),(0,Bt.Bb)({uniformsNames:f,uniformBuffersNames:_,samplers:p,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const g={};this.customShaderNameResolve&&(d=this.customShaderNameResolve(d,f,_,p,t,u,g));const v=t.toString(),x=l.createEffect(d,{attributes:u,uniformsNames:f,uniformBuffersNames:_,samplers:p,defines:v,fallbacks:h,onCompiled:r,onError:s,indexParameters:m,processFinalCode:g.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{1===this.shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,431)),Promise.resolve().then(i.bind(i,66854))]):await Promise.all([Promise.resolve().then(i.bind(i,60693)),Promise.resolve().then(i.bind(i,43004))]),this._shadersLoaded=!0}},l);return this._eventInfo.customCode=void 0,x}_prepareDefines(e,t,i=null,r=null,s=!1){const n=this.getScene(),o=n.getEngine();(0,Bt.az)(n,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,(0,Bt.VO)(n,t);const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if((0,Bt.N4)(n,t,this.canRenderToMRT&&!a),(0,Bt.Nc)(n,t,a),Bn.PrepareDefines(o.currentRenderPassId,e,t),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=6;++e)t["MAINUV"+e]=!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&&Sn.DiffuseTextureEnabled?((0,Bt.YT)(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&Sn.AmbientTextureEnabled?((0,Bt.YT)(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&Sn.OpacityTextureEnabled?((0,Bt.YT)(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const e=this._getReflectionTexture();if(e&&Sn.ReflectionTextureEnabled){switch(t.REFLECTION=!0,t.GAMMAREFLECTION=e.gammaSpace,t.RGBDREFLECTION=e.isRGBD,t.LODINREFLECTIONALPHA=e.lodLevelInAlpha,t.LINEARSPECULARREFLECTION=e.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=e.coordinatesMode===vi.g.INVCUBIC_MODE,t.REFLECTIONMAP_3D=e.isCube,t.REFLECTIONMAP_OPPOSITEZ=t.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.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,e.coordinatesMode){case vi.g.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case vi.g.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case vi.g.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case vi.g.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case vi.g.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case vi.g.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case vi.g.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case vi.g.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case vi.g.CUBIC_MODE:case vi.g.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==vi.g.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.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&&Sn.LightmapTextureEnabled?((0,Bt.YT)(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&Sn.EmissiveTextureEnabled?((0,Bt.YT)(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,Sn.SpecularTextureEnabled?(this._metallicTexture?((0,Bt.YT)(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?((0,Bt.YT)(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?((0,Bt.YT)(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?((0,Bt.YT)(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1):(t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1),this._microSurfaceTexture?(0,Bt.YT)(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1):(t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1),o.getCaps().standardDerivatives&&this._bumpTexture&&Sn.BumpTextureEnabled&&!this._disableBumpMap?((0,Bt.YT)(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&Sn.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&&Sn.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===Gm.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===Gm.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=7===this.alphaMode||8===this.alphaMode,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&&((0,Bt.fm)(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(st.R.NormalKind),t.DEBUGMODE=this._debugMode),(0,Bt.OR)(n,o,this,t,!!i,r,s),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),(0,Bt.qB)(e,t,!0,!0,!0,this._transparencyMode!==Gm.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const r={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(4,this._eventInfo),(()=>{if(this._breakShaderLoadedCheck)return;const i=new Um(this._eventInfo.defineNames),s=this._prepareEffect(e,i,void 0,void 0,r.useInstances,r.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(km.effect=s,km.subMesh=null,this._onEffectCreatedObservable.notifyObservers(km)),s.isReady()?t&&t(this):s.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){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e);const o=r.getEngine();this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,r,t,e,this.isFrozen),Bn.Bind(o.currentRenderPassId,this._activeEffect,t,e),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),s.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const a=this._mustRebind(r,n,i,t.visibility);(0,Bt.f$)(t,this._activeEffect,this.prePassConfiguration);let l=null;const h=this._uniformBuffer;if(a){if(this.bindViewProjection(n),l=this._getReflectionTexture(),!h.useUbo||!this.isFrozen||!h.isSync||i._drawWrapper._forceRebindOnNextCall){if(r.texturesEnabled){if(this._albedoTexture&&Sn.DiffuseTextureEnabled&&(h.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),(0,Bt.mA)(this._albedoTexture,h,"albedo")),this._ambientTexture&&Sn.AmbientTextureEnabled&&(h.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),(0,Bt.mA)(this._ambientTexture,h,"ambient")),this._opacityTexture&&Sn.OpacityTextureEnabled&&(h.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),(0,Bt.mA)(this._opacityTexture,h,"opacity")),l&&Sn.ReflectionTextureEnabled){if(h.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),h.updateFloat2("vReflectionInfos",l.level,0),l.boundingBoxSize){const e=l;h.updateVector3("vReflectionPosition",e.boundingBoxPosition),h.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){const e=l.getSize().width;h.updateFloat2("vReflectionFilteringInfo",e,Math.log2(e))}if(!s.USEIRRADIANCEMAP){const e=l.sphericalPolynomial;if(s.USESPHERICALFROMREFLECTIONMAP&&e)if(s.SPHERICAL_HARMONICS){const t=e.preScaledHarmonics;h.updateVector3("vSphericalL00",t.l00),h.updateVector3("vSphericalL1_1",t.l1_1),h.updateVector3("vSphericalL10",t.l10),h.updateVector3("vSphericalL11",t.l11),h.updateVector3("vSphericalL2_2",t.l2_2),h.updateVector3("vSphericalL2_1",t.l2_1),h.updateVector3("vSphericalL20",t.l20),h.updateVector3("vSphericalL21",t.l21),h.updateVector3("vSphericalL22",t.l22)}else h.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),h.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),h.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),h.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),h.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),h.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),h.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),h.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),h.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}h.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset)}this._emissiveTexture&&Sn.EmissiveTextureEnabled&&(h.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),(0,Bt.mA)(this._emissiveTexture,h,"emissive")),this._lightmapTexture&&Sn.LightmapTextureEnabled&&(h.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),(0,Bt.mA)(this._lightmapTexture,h,"lightmap")),Sn.SpecularTextureEnabled&&(this._metallicTexture?(h.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),(0,Bt.mA)(this._metallicTexture,h,"reflectivity")):this._reflectivityTexture&&(h.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),(0,Bt.mA)(this._reflectivityTexture,h,"reflectivity")),this._metallicReflectanceTexture&&(h.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),(0,Bt.mA)(this._metallicReflectanceTexture,h,"metallicReflectance")),this._reflectanceTexture&&s.REFLECTANCE&&(h.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),(0,Bt.mA)(this._reflectanceTexture,h,"reflectance")),this._microSurfaceTexture&&(h.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),(0,Bt.mA)(this._microSurfaceTexture,h,"microSurfaceSampler"))),this._bumpTexture&&o.getCaps().standardDerivatives&&Sn.BumpTextureEnabled&&!this._disableBumpMap&&(h.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),(0,Bt.mA)(this._bumpTexture,h,"bump"),r._mirroredCameraPosition?h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&h.updateFloat("pointSize",this.pointSize),s.METALLICWORKFLOW){H.IG.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,H.IG.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,h.updateColor4("vReflectivityColor",H.IG.Color3[0],1);const e=this.subSurface?._indexOfRefraction??1.5,t=1,i=Math.pow((e-t)/(e+t),2);this._metallicReflectanceColor.scaleToRef(i*this._metallicF0Factor,H.IG.Color3[0]);const r=this._metallicF0Factor;h.updateColor4("vMetallicReflectanceFactors",H.IG.Color3[0],r)}else h.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);h.updateColor3("vEmissiveColor",Sn.EmissiveTextureEnabled?this._emissiveColor:H.v9.BlackReadOnly),h.updateColor3("vReflectionColor",this._reflectionColor),!s.SS_REFRACTION&&this.subSurface?._linkRefractionWithTransparency?h.updateColor4("vAlbedoColor",this._albedoColor,1):h.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*r.environmentIntensity,this._lightingInfos.w=this._specularIntensity,h.updateVector4("vLightingIntensity",this._lightingInfos),r.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),h.updateColor3("vAmbientColor",this._globalAmbientColor),h.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}r.texturesEnabled&&(this._albedoTexture&&Sn.DiffuseTextureEnabled&&h.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&Sn.AmbientTextureEnabled&&h.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&Sn.OpacityTextureEnabled&&h.setTexture("opacitySampler",this._opacityTexture),l&&Sn.ReflectionTextureEnabled&&(s.LODBASEDMICROSFURACE?h.setTexture("reflectionSampler",l):(h.setTexture("reflectionSampler",l._lodTextureMid||l),h.setTexture("reflectionSamplerLow",l._lodTextureLow||l),h.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l)),s.USEIRRADIANCEMAP&&h.setTexture("irradianceSampler",l.irradianceTexture)),s.ENVIRONMENTBRDF&&h.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&Sn.EmissiveTextureEnabled&&h.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&Sn.LightmapTextureEnabled&&h.setTexture("lightmapSampler",this._lightmapTexture),Sn.SpecularTextureEnabled&&(this._metallicTexture?h.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&h.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&h.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&s.REFLECTANCE&&h.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&h.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&o.getCaps().standardDerivatives&&Sn.BumpTextureEnabled&&!this._disableBumpMap&&h.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),(0,Ln.gS)(this._activeEffect,this,r),this.bindEyePosition(n)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!a&&this.isFrozen||(r.lightsEnabled&&!this._disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s,this._maxSimultaneousLights),(r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE||l||this.subSurface.refractionTexture||t.receiveShadows||s.PREPASS)&&this.bindView(n),(0,Bt.Yy)(r,t,this._activeEffect,!0),s.NUM_MORPH_INFLUENCERS&&(0,Bt.nR)(t,this._activeEffect),s.BAKED_VERTEX_ANIMATION_TEXTURE&&t.bakedVertexAnimationManager?.bind(n,s.INSTANCES),this._imageProcessingConfiguration.bind(this._activeEffect),(0,Bt.DL)(s,this._activeEffect,r)),this._afterBind(t,this._activeEffect,i),h.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(){if(!this.subSurface?.isScatteringEnabled)return!1;const e=this.getScene().enableSubSurfaceForPrePass();return e&&(e.enabled=!0),!0}dispose(e,t){this._breakShaderLoadedCheck=!0,t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),this._albedoTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._metallicTexture?.dispose(),this._reflectivityTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._metallicReflectanceTexture?.dispose(),this._reflectanceTexture?.dispose(),this._microSurfaceTexture?.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}Gm.PBRMATERIAL_OPAQUE=Vt.MATERIAL_OPAQUE,Gm.PBRMATERIAL_ALPHATEST=Vt.MATERIAL_ALPHATEST,Gm.PBRMATERIAL_ALPHABLEND=Vt.MATERIAL_ALPHABLEND,Gm.PBRMATERIAL_ALPHATESTANDBLEND=Vt.MATERIAL_ALPHATESTANDBLEND,Gm.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,Gm.LIGHTFALLOFF_PHYSICAL=0,Gm.LIGHTFALLOFF_GLTF=1,Gm.LIGHTFALLOFF_STANDARD=2,Gm.ForceGLSL=!1,(0,je.Cg)([(0,$e.n1)()],Gm.prototype,"_imageProcessingConfiguration",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],Gm.prototype,"debugMode",void 0);class zm extends Gm{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===Gm.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Gm.LIGHTFALLOFF_PHYSICAL:Gm.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===Gm.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Gm.LIGHTFALLOFF_GLTF:Gm.LIGHTFALLOFF_STANDARD)}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}constructor(e,t,i=!1){super(e,t,i),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=zm.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=H.v9.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new H.v9(0,0,0),this.albedoColor=new H.v9(1,1,1),this.reflectivityColor=new H.v9(1,1,1),this.reflectionColor=new H.v9(1,1,1),this.emissiveColor=new H.v9(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=Em(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){const r=it.p.Clone((()=>new zm(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return r.id=e,r.name=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}serialize(){const e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){const r=it.p.Parse((()=>new zm(e.name,t)),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),Vt._ParsePlugins(e,r,t,i),e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}zm.PBRMATERIAL_OPAQUE=Gm.PBRMATERIAL_OPAQUE,zm.PBRMATERIAL_ALPHATEST=Gm.PBRMATERIAL_ALPHATEST,zm.PBRMATERIAL_ALPHABLEND=Gm.PBRMATERIAL_ALPHABLEND,zm.PBRMATERIAL_ALPHATESTANDBLEND=Gm.PBRMATERIAL_ALPHATESTANDBLEND,zm.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=Gm.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"directIntensity",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"emissiveIntensity",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"environmentIntensity",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"specularIntensity",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"disableBumpMap",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"albedoTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"ambientTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"ambientTextureStrength",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesAndMiscDirty")],zm.prototype,"opacityTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"reflectionTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"emissiveTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"reflectivityTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"metallicTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"metallic",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"roughness",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"metallicF0Factor",void 0),(0,je.Cg)([(0,$e.jT)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"metallicReflectanceColor",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"metallicReflectanceTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"reflectanceTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"microSurfaceTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"bumpTexture",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty",null)],zm.prototype,"lightmapTexture",void 0),(0,je.Cg)([(0,$e.jT)("ambient"),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"ambientColor",void 0),(0,je.Cg)([(0,$e.jT)("albedo"),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"albedoColor",void 0),(0,je.Cg)([(0,$e.jT)("reflectivity"),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"reflectivityColor",void 0),(0,je.Cg)([(0,$e.jT)("reflection"),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"reflectionColor",void 0),(0,je.Cg)([(0,$e.jT)("emissive"),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"emissiveColor",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"microSurface",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useLightmapAsShadowmap",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesAndMiscDirty")],zm.prototype,"useAlphaFromAlbedoTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesAndMiscDirty")],zm.prototype,"forceAlphaTest",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesAndMiscDirty")],zm.prototype,"alphaCutOff",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useSpecularOverAlpha",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useRoughnessFromMetallicTextureGreen",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useMetallnessFromMetallicTextureBlue",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useAmbientInGrayScale",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),(0,je.Cg)([(0,$e.lK)()],zm.prototype,"usePhysicalLightFalloff",null),(0,je.Cg)([(0,$e.lK)()],zm.prototype,"useGLTFLightFalloff",null),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useRadianceOverAlpha",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useObjectSpaceNormalMap",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useParallax",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useParallaxOcclusion",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"parallaxScaleBias",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],zm.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"forceIrradianceInFragment",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],zm.prototype,"maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"invertNormalMapX",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"invertNormalMapY",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"twoSidedLighting",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useAlphaFresnel",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useLinearAlphaFresnel",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"environmentBRDFTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"forceNormalForward",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"enableSpecularAntiAliasing",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useHorizonOcclusion",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],zm.prototype,"useRadianceOcclusion",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],zm.prototype,"unlit",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],zm.prototype,"applyDecalMapAfterDetailMap",void 0),(0,X.Y5)("BABYLON.PBRMaterial",zm);var Wm=i(50153),Hm=i(33815),Xm=i(53797);class qm extends es{constructor(e,t,i){super(e,W.Pq.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=W.PT.Identity(),this._referencedPosition=new W.Pq,this._trackingState=0,this.onXRCameraInitializedObservable=new z.cP,this.onBeforeCameraTeleport=new z.cP,this.onAfterCameraTeleport=new z.cP,this.onTrackingStateChanged=new z.cP,this.compensateOnFirstFrame=!0,this._rotate180=new W.PT(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new W.PT,this.cameraRigMode=rt.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 et.L(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new et.L(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){e&&e!==this&&(e.computeWorldMatrix().decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,W.PT.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace())}getClassName(){return"WebXRCamera"}setTarget(e){const t=W.AA.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();const i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),W.PT.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0,this.onTrackingStateChanged.clear()}_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)return void this._setTrackingState(0);const t=e.emulatedPosition?1:2;if(this._setTrackingState(t),this.minZ===this._cache.minZ&&this.maxZ===this._cache.maxZ||this._updateDepthNearFar(),e.transform){const t=e.transform.orientation;if(void 0===e.transform.orientation.x)return;const i=e.transform.position;this._referencedPosition.set(i.x,i.y,i.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._referenceQuaternion.set(t.x,t.y,t.z,t.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(((e,t)=>{const i=this.rigCameras[t];i.isLeftCamera||i.isRightCamera||("right"===e.eye?i._isRightCamera=!0:"left"===e.eye&&(i._isLeftCamera=!0));const r=this.getScene().customRenderTargets;for(let e=0;ee;){const e=this.rigCameras.pop();e&&e.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){const e=W.AA.Matrix[0],t=W.AA.Matrix[1],i=W.AA.Matrix[2];W.uq.ComposeToRef(qm._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),W.uq.ComposeToRef(qm._ScaleReadOnly,this.rotationQuaternion,this.position,t),e.invert().multiplyToRef(t,i),i.invert(),this._scene.useRightHandedSystem||i.toggleModelMatrixHandInPlace(),i.decompose(void 0,this._referenceQuaternion,this._referencedPosition);const r=new XRRigidTransform({x:this._referencedPosition.x/this._xrSessionManager.worldScalingFactor,y:this._referencedPosition.y/this._xrSessionManager.worldScalingFactor,z:this._referencedPosition.z/this._xrSessionManager.worldScalingFactor},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(r)}}}qm._ScaleReadOnly=W.Pq.One();class Ym{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 z.cP,this.onStateChangedObservable=new z.cP,this.state=3,this.sessionManager=new Qn(e),this.camera=new qm("webxr",e,this.sessionManager),this.featuresManager=new cr(this.sessionManager),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}static CreateAsync(e){const t=new Ym(e);return t.sessionManager.initializeAsync().then((()=>(t._supported=!0,t))).catch((e=>{throw t._setState(3),t.dispose(),e}))}dispose(){this.exitXRAsync(),this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),this._spectatorCamera?.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),r={}){if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(0),"viewer"!==t&&"local"!==t&&(r.optionalFeatures=r.optionalFeatures||[],r.optionalFeatures.push(t)),r=await this.featuresManager._extendXRSessionInitObject(r),"immersive-ar"===e&&"unbounded"!==t&&Z.V.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,r),await this.sessionManager.setReferenceSpaceTypeAsync(t);const s={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};if(!this.featuresManager.getEnabledFeature(hr.LAYERS)){const e=await i.initializeXRLayerAsync(this.sessionManager.session);s.baseLayer=e}return this.sessionManager.updateRenderState(s),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!this._nonVRCamera?.inputs?.attachedToElement,this._nonVRCamera?.detachControl(),this._scene.activeCamera=this.camera,"immersive-ar"!==e?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)),Ot.$.audioEngine?._resumeAudioContextOnStateChange(),this.sessionManager.onXRSessionEnded.addOnce((()=>{1!==this.state&&this._setState(1),this.camera.rigCameras.forEach((e=>{e.outputRenderTarget=null})),this._scene.autoClear=this._originalSceneAutoClear,this._scene.activeCamera=this._nonVRCamera,this._attachedToElement&&this._nonVRCamera&&this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault),"immersive-ar"!==e&&this.camera.compensateOnFirstFrame&&(this._nonVRCamera.setPosition?this._nonVRCamera.setPosition(this.camera.position):this._nonVRCamera.position.copyFrom(this.camera.position)),this._setState(3)})),this.sessionManager.onXRFrameObservable.addOnce((()=>{this._setState(2)})),this.sessionManager}catch(e){throw Z.V.Log(e),Z.V.Log(e.message),this._setState(3),e}}exitXRAsync(){return 2!==this.state?Promise.resolve():(this._setState(1),this.sessionManager.exitXRAsync())}enableSpectatorMode(e){this._spectatorMode||(this._spectatorMode=!0,this._switchSpectatorMode(e))}disableSpecatatorMode(){this._spectatorMode&&(this._spectatorMode=!1,this._switchSpectatorMode())}_switchSpectatorMode(e){const t=1/(e?.fps?e.fps:1e3)*1e3,i=e?.preferredCameraIndex?e?.preferredCameraIndex:0,r=()=>{this._spectatorCamera&&this.sessionManager.currentTimestamp-this._lastTimestamp>=t&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[i].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[i].absoluteRotation))};if(this._spectatorMode){if(i>=this.camera.rigCameras.length)throw new Error("the preferred camera index is beyond the length of rig camera array.");const e=()=>{2===this.state?(this._spectatorCamera=new fs("webxr-spectator",W.Pq.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new W.PT,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(r),this._scene.onAfterRenderCameraObservable.add((e=>{e===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)}))):1===this.state&&(this.sessionManager.onXRFrameObservable.removeCallback(r),this._scene.activeCameras=null)};this.onStateChangedObservable.add(e),e()}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 Km{constructor(e,t,i=-1,r=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=r,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new z.cP,this.onButtonStateChangedObservable=new z.cP}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 0!==this._axesIndices.length}isButton(){return-1!==this._buttonIndex}update(e){let t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){const i=e.buttons[this._buttonIndex];if(!i)return;this._currentValue!==i.value&&(this.changes.value={current:i.value,previous:this._currentValue},t=!0,this._currentValue=i.value),this._touched!==i.touched&&(this.changes.touched={current:i.touched,previous:this._touched},t=!0,this._touched=i.touched),this._pressed!==i.pressed&&(this.changes.pressed={current:i.pressed,previous:this._pressed},t=!0,this._pressed=i.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))}}Km.BUTTON_TYPE="button",Km.SQUEEZE_TYPE="squeeze",Km.THUMBSTICK_TYPE="thumbstick",Km.TOUCHPAD_TYPE="touchpad",Km.TRIGGER_TYPE="trigger";var jm,$m=i(28909);!function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(jm||(jm={}));const Qm=new z.cP,Zm={};let Jm=!1;function eg(){return Zm[".babylon"]}function tg(e,t){return Zm[e]||(Z.V.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"),t?eg():void 0)}function ig(e,t,i){let r="Unable to load from "+(e.rawData?"binary data":e.url);return t?r+=`: ${t}`:i&&(r+=`: ${i}`),r}async function rg(e,t,i,r,s,n,o,a,l){const h="data:"===(c=e.url).substring(0,5)?c.substring(5):null;var c;if(e.rawData&&!o)throw"When using ArrayBufferView to load data the file extension must be provided.";const u=h||o?"":function(e){const t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));const i=e.lastIndexOf(".");return e.substring(i,e.length).toLowerCase()}(e.url);let d=o?tg(o,!0):h?function(e){for(const t in Zm){const i=Zm[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return Zm[t]}return eg()}(e.url):tg(u,!1);if(!d&&u){if(e.url&&!e.url.startsWith("blob:")){const t=await function(e,t){const i=t.method||"GET";return new Promise(((r,s)=>{const n=new go.u;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const e={};if(t.responseHeaders)for(const i of t.responseHeaders)e[i]=n.getResponseHeader(i)||"";r({response:n.response,headerValues:e})}else s(`Unable to fetch data from ${e}. Error code: ${n.status}`)})),n.open(i,e),n.send()}))}(e.url,{method:"HEAD",responseHeaders:["Content-Type"]}),i=t.headerValues?t.headerValues["Content-Type"]:"";i&&(d=function(e){for(const t in Zm){const i=Zm[t];if(i.mimeType===e)return i}}(i))}d||(d=eg())}if(!d)throw new Error(`No plugin or fallback for ${o??e.url}`);if(!1===l?.[d.plugin.name]?.enabled)throw new Error(`The '${d.plugin.name}' plugin is disabled via the loader options passed to the loading operation.`);if(e.rawData&&!d.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";return(e=>{if(d.plugin.createPlugin){const t=d.plugin.createPlugin(l??{});return t instanceof Promise?(t.then(e).catch((e=>{s("Error instantiating plugin.",e)})),null):(e(t),t)}return e(d.plugin),d.plugin})((l=>{if(!l)throw`The loader plugin corresponding to the '${o}' file type has not been found. If using es6, please import the plugin you wish to use before.`;if(Qm.notifyObservers(l),h&&(l.canDirectLoad&&l.canDirectLoad(e.url)||!(0,$m.f2)(e.url))){if(l.directLoad){const e=l.directLoad(t,h);e instanceof Promise?e.then((e=>{i(l,e)})).catch((e=>{s("Error in directLoad of _loadData: "+e,e)})):i(l,e)}else i(l,h);return}const c=d.isBinary,u=(e,r)=>{t.isDisposed?s("Scene has been disposed"):i(l,e,r)};let f=null,p=!1;l.onDisposeObservable?.add((()=>{p=!0,f&&(f.abort(),f=null),n()}));const _=()=>{if(p)return;const i=(e,t)=>{s(e?.statusText,t)};if(!l.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";f=l.loadFile?l.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,u,r,c,i,a):t._loadFile(e.file||e.url,u,r,!0,c,i)},m=t.getEngine();let g=m.enableOfflineSupport;if(g){let i=!1;for(const r of t.disableOfflineSupportExceptionRules)if(r.test(e.url)){i=!0;break}g=!i}g&&Ot.$.OfflineProviderFactory?t.offlineProvider=Ot.$.OfflineProviderFactory(e.url,_,m.disableManifestCheck):_()}))}function sg(e,t){let i,r,s=null,n=null;if(t)if(t.name)i=`file:${t.name}`,r=t.name,s=t;else if(ArrayBuffer.isView(t))i="",r=(0,Au.z)(),n=t;else if(t.startsWith("data:"))i=t,r="";else if(e){const s=t;if("/"===s.substring(0,1))return Ue.S0.Error("Wrong sceneFilename parameter"),null;i=e+s,r=s}else i=t,r=Ue.S0.GetFilename(t),e=Ue.S0.GetFolderPath(t);else i=e,r=Ue.S0.GetFilename(e),e=Ue.S0.GetFolderPath(e);return{url:i,rootUrl:e,name:r,file:s,rawData:n}}function ng(e){if("string"==typeof e.extensions){const t=e.extensions;Zm[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach((i=>{Zm[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary,mimeType:t[i].mimeType}}))}}async function og(e,t,i="",r=he.q.LastCreatedScene,s=null,n=null,o=null,a=null,l="",h={}){if(!r)return Z.V.Error("No scene available to import mesh to"),null;const c=sg(t,i);if(!c)return null;const u={};r.addPendingData(u);const d=()=>{r.removePendingData(u)},f=(e,t)=>{const i=ig(c,e,t);o?o(r,i,new nt.bu(i,nt.tG.SceneLoaderError,t)):Z.V.Error(i),d()},p=n?e=>{try{n(e)}catch(e){f("Error in onProgress callback: "+e,e)}}:void 0,_=(e,t,i,n,o,a,l,h)=>{if(r.importedMeshesFiles.push(c.url),s)try{s(e,t,i,n,o,a,l,h)}catch(e){f("Error in onSuccess callback: "+e,e)}r.removePendingData(u)};return await rg(c,r,((t,i,s)=>{if(t.rewriteRootURL&&(c.rootUrl=t.rewriteRootURL(c.rootUrl,s)),t.importMesh){const s=[],n=[],o=[];if(!t.importMesh(e,r,i,c.rootUrl,s,n,o,f))return;r.loadingPluginName=t.name,_(s,n,o,[],[],[],[],[])}else t.importMeshAsync(e,r,i,c.rootUrl,p,c.name).then((e=>{r.loadingPluginName=t.name,_(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights,e.spriteManagers)})).catch((e=>{f(e.message,e)}))}),p,f,d,a,l,h)}function ag(e,t="",i=he.q.LastCreatedEngine,r=null,s=null,n=null,o=null,a="",l={}){i?cg(e,t,new oi.Z(i),r,s,n,o,a,l):Ue.S0.Error("No engine available")}function lg(e,t,i){const{rootUrl:r="",onProgress:s,pluginExtension:n,name:o,pluginOptions:a}=i??{};return hg(r,e,t,s,n,o,a)}function hg(e,t,i,r,s,n,o){return new Promise(((a,l)=>{ag(e,t,i,(e=>{a(e)}),r,((e,t,i)=>{l(i||new Error(t))}),s,n,o)}))}async function cg(e,t="",i=he.q.LastCreatedScene,r=null,s=null,n=null,o=null,a="",l={}){if(!i)return Z.V.Error("No scene available to append to"),null;const h=sg(e,t);if(!h)return null;const c={};i.addPendingData(c);const u=()=>{i.removePendingData(c)};St.ShowLoadingScreen&&!Jm&&(Jm=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady((()=>{i.getEngine().hideLoadingUI(),Jm=!1})));const d=(e,t)=>{const r=ig(h,e,t);n?n(i,r,new nt.bu(r,nt.tG.SceneLoaderError,t)):Z.V.Error(r),u()},f=s?e=>{try{s(e)}catch(e){d("Error in onProgress callback",e)}}:void 0,p=()=>{if(r)try{r(i)}catch(e){d("Error in onSuccess callback",e)}i.removePendingData(c)};return await rg(h,i,((e,t)=>{if(e.load){if(!e.load(i,t,h.rootUrl,d))return;i.loadingPluginName=e.name,p()}else e.loadAsync(i,t,h.rootUrl,f,h.name).then((()=>{i.loadingPluginName=e.name,p()})).catch((e=>{d(e.message,e)}))}),f,d,u,o,a,l)}async function ug(e,t,i){const{rootUrl:r="",onProgress:s,pluginExtension:n,name:o,pluginOptions:a}=i??{};await dg(r,e,t,s,n,o,a)}function dg(e,t,i,r,s,n,o){return new Promise(((a,l)=>{cg(e,t,i,(e=>{a(e)}),r,((e,t,i)=>{l(i||new Error(t))}),s,n,o)}))}async function fg(e,t="",i=he.q.LastCreatedScene,r=null,s=null,n=null,o=null,a="",l={}){if(!i)return Z.V.Error("No scene available to load asset container to"),null;const h=sg(e,t);if(!h)return null;const c={};i.addPendingData(c);const u=()=>{i.removePendingData(c)},d=(e,t)=>{const r=ig(h,e,t);n?n(i,r,new nt.bu(r,nt.tG.SceneLoaderError,t)):Z.V.Error(r),u()},f=s?e=>{try{s(e)}catch(e){d("Error in onProgress callback",e)}}:void 0,p=e=>{if(r)try{r(e)}catch(e){d("Error in onSuccess callback",e)}i.removePendingData(c)};return await rg(h,i,((e,t)=>{if(e.loadAssetContainer){const r=e.loadAssetContainer(i,t,h.rootUrl,d);if(!r)return;r.populateRootNodes(),i.loadingPluginName=e.name,p(r)}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(i,t,h.rootUrl,f,h.name).then((t=>{t.populateRootNodes(),i.loadingPluginName=e.name,p(t)})).catch((e=>{d(e.message,e)})):d("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")}),f,d,u,o,a,l)}function pg(e,t,i){const{rootUrl:r="",onProgress:s,pluginExtension:n,name:o,pluginOptions:a}=i??{};return _g(r,e,t,s,n,o,a)}function _g(e,t,i,r,s,n,o){return new Promise(((a,l)=>{fg(e,t,i,(e=>{a(e)}),r,((e,t,i)=>{l(i||new Error(t))}),s,n,o)}))}function mg(e,t="",i=he.q.LastCreatedScene,r=!0,s=0,n=null,o=null,a=null,l=null,h=null,c="",u={}){if(!i)return void Z.V.Error("No scene available to load animations to");if(r){for(const e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach((e=>{e.dispose()})),i.getNodes().forEach((e=>{e.animations&&(e.animations=[])}))}else switch(s){case 0:i.animationGroups.slice().forEach((e=>{e.dispose()}));break;case 1:i.animationGroups.forEach((e=>{e.stop()}));break;case 2:i.animationGroups.forEach((e=>{e.reset(),e.restart()}));break;case 3:break;default:return void Z.V.Error("Unknown animation group loading mode value '"+s+"'")}const d=i.animatables.length;fg(e,t,i,(e=>{e.mergeAnimationsTo(i,i.animatables.slice(d),n),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),o&&o(i)}),a,l,h,c,u)}async function gg(e,t,i){const{rootUrl:r="",overwriteAnimations:s,animationGroupLoadingMode:n,targetConverter:o,onProgress:a,pluginExtension:l,name:h,pluginOptions:c}=i??{};await vg(r,e,t,s,n,o,a,l,h,c)}function vg(e,t,i,r,s,n,o,a,l,h){return new Promise(((c,u)=>{mg(e,t,i,r,s,n,(e=>{c(e)}),o,((e,t,i)=>{u(i||new Error(t))}),a,l,h)}))}class xg{static get ForceFullSceneLoadingForIncremental(){return St.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){St.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return St.ShowLoadingScreen}static set ShowLoadingScreen(e){St.ShowLoadingScreen=e}static get loggingLevel(){return St.loggingLevel}static set loggingLevel(e){St.loggingLevel=e}static get CleanBoneMatrixWeights(){return St.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){St.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return eg()}static GetPluginForExtension(e){return tg(e,!0)?.plugin}static IsPluginForExtensionAvailable(e){return function(e){return!!Zm[e]}(e)}static RegisterPlugin(e){ng(e)}static ImportMesh(e,t,i,r,s,n,o,a,l){og(e,t,i,r,s,n,o,a,l)}static ImportMeshAsync(e,t,i,r,s,n,o){return function(e,t,i,r,s,n,o,a){return new Promise(((a,l)=>{og(e,t,i,r,((e,t,i,r,s,n,o,l)=>{a({meshes:e,particleSystems:t,skeletons:i,animationGroups:r,transformNodes:s,geometries:n,lights:o,spriteManagers:l})}),s,((e,t,i)=>{l(i||new Error(t))}),n,o,undefined)}))}(e,t,i,r,s,n,o)}static Load(e,t,i,r,s,n,o,a){ag(e,t,i,r,s,n,o,a)}static LoadAsync(e,t,i,r,s,n){return hg(e,t,i,r,s,n)}static Append(e,t,i,r,s,n,o,a){cg(e,t,i,r,s,n,o,a)}static AppendAsync(e,t,i,r,s,n){return dg(e,t,i,r,s,n)}static LoadAssetContainer(e,t,i,r,s,n,o,a){fg(e,t,i,r,s,n,o,a)}static LoadAssetContainerAsync(e,t,i,r,s,n){return _g(e,t,i,r,s,n)}static ImportAnimations(e,t,i,r,s,n,o,a,l,h,c){mg(e,t,i,r,s,n,o,a,l,h,c)}static ImportAnimationsAsync(e,t,i,r,s,n,o,a,l,h,c){return vg(e,t,i,r,s,n,a,h,c)}}xg.NO_LOGGING=0,xg.MINIMAL_LOGGING=1,xg.SUMMARY_LOGGING=2,xg.DETAILED_LOGGING=3,xg.OnPluginActivatedObservable=Qm;class bg{constructor(e,t,i,r,s=!1,n){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=r,this._doNotLoadControllerMesh=s,this._controllerCache=n,this._initComponent=e=>{if(!e)return;const t=this.layout.components[e],i=t.type,r=t.gamepadIndices.button,s=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&s.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),this.components[e]=new Km(e,i,r,s)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new z.cP,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)),this.onModelLoadedObservable.clear()}getAllComponentsOfType(e){return this.getComponentIds().map((e=>this.components[e])).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?Z.V.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise(((i,r)=>{const s=t=>{e?this._getGenericParentMesh(t):this._setRootMesh(t),this._processLoadedModel(t),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){const e=this._controllerCache.filter((e=>e.filename===t.filename&&e.path===t.path));if(e[0])return e[0].meshes.forEach((e=>e.setEnabled(!0))),void s(e[0].meshes)}xg.ImportMesh("",t.path,t.filename,this.scene,(e=>{this._controllerCache&&this._controllerCache.push({...t,meshes:e}),s(e)}),null,((e,i)=>{Z.V.Log(i),Z.V.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),r(i)}))}))}updateFromXRFrame(e){this.getComponentIds().forEach((e=>this.getComponent(e).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((e=>e.name===t),!1)[0]}_getImmediateChildByName(e,t){return e.getChildren((e=>e.name==t),!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh)return;if(!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;const r=i?.5*t+.5:t;W.PT.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,r,e.valueMesh.rotationQuaternion),W.Pq.LerpToRef(e.minMesh.position,e.maxMesh.position,r,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new Yt(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.parent||(e.isPickable=!1,e.setParent(this.rootMesh))})),this.rootMesh.rotationQuaternion=W.PT.FromEulerAngles(0,Math.PI,0)}}class Sg extends bg{constructor(e,t,i){super(e,Tg[i],t,i),this.profileId=Sg.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new Yt(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1,e.parent||e.setParent(this.rootMesh)})),this.rootMesh.rotationQuaternion=W.PT.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}Sg.ProfileId="generic-trigger";const Tg={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 Cg extends bg{constructor(e,t,i,r,s){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,s),this._repositoryUrl=r,this.controllerCache=s,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach((e=>{this._touchDots[e].dispose()}))}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){const e=xg.IsPluginForExtensionAvailable(".glb");return e||Z.V.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=this.layout.components[e];this._buttonMeshMapping[e]={mainMesh:this._getChildByName(this.rootMesh,t.rootNodeName),states:{}},Object.keys(t.visualResponses).forEach((i=>{const r=t.visualResponses[i];if("transform"===r.valueNodeProperty)this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,r.valueNodeName),minMesh:this._getChildByName(this.rootMesh,r.minNodeName),maxMesh:this._getChildByName(this.rootMesh,r.maxNodeName)};else{const s=t.type===Km.TOUCHPAD_TYPE&&t.touchPointNodeName?t.touchPointNodeName:r.valueNodeName;if(this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,s)},t.type===Km.TOUCHPAD_TYPE&&!this._touchDots[i]){const t=Qo(i+"dot",{diameter:.0015,segments:8},this.scene);t.material=new Un(i+"mat",this.scene),t.material.diffuseColor=H.v9.Red(),t.parent=this._buttonMeshMapping[e].states[i].valueMesh||null,t.isVisible=!1,this._touchDots[i]=t}}}))}))}_setRootMesh(e){let t;this.rootMesh=new Yt(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i{const t=this.getComponent(e);if(!t.hasChanges)return;const i=this._buttonMeshMapping[e],r=this.layout.components[e];Object.keys(r.visualResponses).forEach((e=>{const s=r.visualResponses[e];let n=t.value;if("xAxis"===s.componentProperty?n=t.axes.x:"yAxis"===s.componentProperty&&(n=t.axes.y),"transform"===s.valueNodeProperty)this._lerpTransform(i.states[e],n,"button"!==s.componentProperty);else{const r=i.states[e].valueMesh;r&&(r.isVisible=t.touched||t.pressed),this._touchDots[e]&&(this._touchDots[e].isVisible=t.touched||t.pressed)}}))}))}}const yg=[];class Eg{static ClearProfilesCache(){this._ProfilesList=null,this._ProfileLoadingPromises={}}static DefaultFallbacks(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])}static FindFallbackWithProfileId(e){const t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){const r=[];i&&r.push(i),r.push(...e.profiles||[]),r.length&&!r[0]&&r.pop(),e.gamepad&&e.gamepad.id&&e.gamepad.id===(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0)&&r.push("oculus-touch-v2");const s=r.indexOf("windows-mixed-reality");if(-1!==s&&r.splice(s,0,"microsoft-mixed-reality"),r.length||r.push("generic-trigger"),this.UseOnlineRepository){const i=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,s=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return i.call(this,r,e,t).catch((()=>s.call(this,r,e,t)))}return this._LoadProfilesFromAvailableControllers(r,e,t)}static RegisterController(e,t){this._AvailableControllers[e]=t}static RegisterFallbacksForProfileId(e,t){this._Fallbacks[e]?this._Fallbacks[e].push(...t):this._Fallbacks[e]=t}static UpdateProfilesList(){return this._ProfilesList=Ue.S0.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then((e=>JSON.parse(e))),this._ProfilesList}static ClearControllerCache(){yg.forEach((e=>{e.meshes.forEach((e=>{e.dispose(!1,!0)}))})),yg.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then((()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList())).then((t=>{for(let i=0;i(this._ProfileLoadingPromises[e]||(this._ProfileLoadingPromises[e]=Ue.S0.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${e}/profile.json`,!1).then((e=>JSON.parse(e)))),this._ProfileLoadingPromises[e]))).then((e=>new Cg(i,t,e,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:yg)))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let r=0;rnew Sg(t,e.gamepad,e.handedness))),Eg.DefaultFallbacks();let Pg=0;class Ag{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new W.Pq,this._disposed=!1,this.onDisposeObservable=new z.cP,this.onMeshLoadedObservable=new z.cP,this.onMotionControllerInitObservable=new z.cP,this._uniqueId=`controller-${Pg++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new Yt(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new W.PT,this.inputSource.gripSpace&&(this.grip=new Yt(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new W.PT),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&"tracked-pointer"===this.inputSource.targetRayMode&&Eg.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then((e=>{this.motionController=e,this.onMotionControllerInitObservable.notifyObservers(e),this._options.doNotLoadControllerMesh||this.motionController._doNotLoadControllerMesh||this.motionController.loadModel().then((e=>{e&&this.motionController&&this.motionController.rootMesh&&(this._options.renderingGroupId&&(this.motionController.rootMesh.renderingGroupId=this._options.renderingGroupId,this.motionController.rootMesh.getChildMeshes(!1).forEach((e=>e.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&&this.motionController?.dispose()}))}),(()=>{Ue.S0.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;W.Pq.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i,r){const s=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=s,s){const e=s.transform.position;this.pointer.position.set(e.x,e.y,e.z).scaleInPlace(r.worldScalingFactor);const t=s.transform.orientation;this.pointer.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent,this.pointer.scaling.setAll(r.worldScalingFactor)}if(this.inputSource.gripSpace&&this.grip){const s=e.getPose(this.inputSource.gripSpace,t);if(s){const e=s.transform.position,t=s.transform.orientation;this.grip.position.set(e.x,e.y,e.z).scaleInPlace(r.worldScalingFactor),this.grip.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent,this.grip.scaling.setAll(r.worldScalingFactor)}this.motionController&&this.motionController.updateFromXRFrame(e)}}class Rg{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new z.cP,this.onControllerRemovedObservable=new z.cP,this._onInputSourcesChange=e=>{this._addAndRemoveControllers(e.added,e.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add((()=>{this._addAndRemoveControllers([],this.controllers.map((e=>e.inputSource)))})),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add((e=>{e.addEventListener("inputsourceschange",this._onInputSourcesChange)})),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add((e=>{this.controllers.forEach((t=>{t.updateFromXRFrame(e,this.xrSessionManager.referenceSpace,this.xrCamera,this.xrSessionManager)}))})),this._options.customControllersRepositoryURL&&(Eg.BaseRepositoryUrl=this._options.customControllersRepositoryURL),Eg.UseOnlineRepository=!this._options.disableOnlineControllerRepository,Eg.UseOnlineRepository)try{Eg.UpdateProfilesList().catch((()=>{Eg.UseOnlineRepository=!1}))}catch(e){Eg.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){const i=this.controllers.map((e=>e.inputSource));for(const t of e)if(-1===i.indexOf(t)){const e=new Ag(this.xrSessionManager.scene,t,{...this._options.controllerOptions||{},forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation});this.controllers.push(e),this.onControllerAddedObservable.notifyObservers(e)}const r=[],s=[];this.controllers.forEach((e=>{-1===t.indexOf(e.inputSource)?r.push(e):s.push(e)})),this.controllers=r,s.forEach((e=>{this.onControllerRemovedObservable.notifyObservers(e),e.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(),Eg.ClearControllerCache()}}class Ig{get xrNativeFeatureName(){return this._xrNativeFeatureName}set xrNativeFeatureName(e){!this._xrSessionManager.isNative&&e&&this._xrSessionManager.inXRSession&&-1===this._xrSessionManager.enabledFeatures?.indexOf(e)&&Z.V.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 z.cP,this.onFeatureDetachObservable=new z.cP}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){if(!this._xrSessionManager.isNative&&this.xrNativeFeatureName&&-1===this._xrSessionManager.enabledFeatures.indexOf(this.xrNativeFeatureName))return!1}else Z.V.Warn("session.enabledFeatures is not available on this device. It is possible that this feature is not supported.");return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,(e=>this._onXRFrame(e))),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 Mg extends Ig{constructor(e,t){super(e),this._options=t,this._attachController=e=>{if(this._controllers[e.uniqueId])return;const{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(this._options.forceGripIfAvailable&&e.grip?e.grip:e.pointer);switch(this._controllers[e.uniqueId]={xrController:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new wi(new W.Pq,new W.Pq),disabledByNearInteraction:!1,id:Mg._IdCounter++},this._attachedController?!this._options.enablePointerSelectionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enablePointerSelectionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachTrackedPointerRayMode(e);case"gaze":return this._attachGazeMode(e);case"screen":case"transient-pointer":return this._attachScreenRayMode(e)}},this._controllers={},this._tmpVectorForPickCompare=new W.Pq,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new H.v9(.9,.9,.9),this.laserPointerDefaultColor=new H.v9(.7,.7,.7),this.selectionMeshDefaultColor=new H.v9(.8,.8,.8),this.selectionMeshPickedColor=new H.v9(.3,.3,1),this._identityMatrix=W.uq.Identity(),this._screenCoordinatesRef=W.Pq.Zero(),this._viewportRef=new et.L(0,0,0,0),this._scene=this._xrSessionManager.scene,void 0===this._options.lookAndPickMode&&(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 wi(new W.Pq,new W.Pq),disabledByNearInteraction:!1,id:Mg._IdCounter++},this._attachGazeMode()}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;i{const t=this._controllers[e];if(this._options.lookAndPickMode&&"transient-pointer"!==t.xrController?.inputSource.targetRayMode)return;if(!this._options.enablePointerSelectionOnAllControllers&&e!==this._attachedController||t.disabledByNearInteraction)return t.selectionMesh.isVisible=!1,t.laserPointer.isVisible=!1,void(t.pick=null);let i;if(t.laserPointer.isVisible=this.displayLaserPointer,t.xrController)i=this._options.forceGripIfAvailable&&t.xrController.grip?t.xrController.grip.position:t.xrController.pointer.position,t.xrController.getWorldPointerRayToRef(t.tmpRay,this._options.forceGripIfAvailable);else{if(!t.webXRCamera)return;i=t.webXRCamera.position,t.webXRCamera.getForwardRayToRef(t.tmpRay)}if(this._options.maxPointerDistance&&(t.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&i){const e=this._xrSessionManager.scene,r=this._options.xrInput.xrCamera;r&&(r.viewport.toGlobalToRef(e.getEngine().getRenderWidth()/r.rigCameras.length,e.getEngine().getRenderHeight(),this._viewportRef),W.Pq.ProjectToRef(i,this._identityMatrix,r.getTransformationMatrix(),this._viewportRef,this._screenCoordinatesRef),"number"!=typeof this._screenCoordinatesRef.x||"number"!=typeof this._screenCoordinatesRef.y||isNaN(this._screenCoordinatesRef.x)||isNaN(this._screenCoordinatesRef.y)||this._screenCoordinatesRef.x===1/0||this._screenCoordinatesRef.y===1/0||(e.pointerX=this._screenCoordinatesRef.x,e.pointerY=this._screenCoordinatesRef.y,t.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let r=null;this._utilityLayerScene&&(r=this._utilityLayerScene.pickWithRay(t.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));const s=this._scene.pickWithRay(t.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);r&&r.hit?s&&s.hit?r.distance{if(t.pick){if(this._augmentPointerInit(l,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,n.isVisible=!1,t.pick.hit)if(this._pickingMoved(s,t.pick))a&&(this._options.disablePointerUpOnTouchOut||this._scene.simulatePointerUp(t.pick,l)),a=!1,o=0;else if(o>i/10&&(n.isVisible=!0),o+=this._scene.getEngine().getDeltaTime(),o>=i)this._scene.simulatePointerDown(t.pick,l),a=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),n.isVisible=!1;else{const e=1-o/i;n.scaling.set(e,e,e)}else a=!1,o=0;this._scene.simulatePointerMove(t.pick,l),s=t.pick}})),void 0!==this._options.renderingGroupId&&(n.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce((()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&a&&(this._scene.simulatePointerUp(t.pick,l),t.finalPointerUpTriggered=!0),n.dispose()}))}_attachScreenRayMode(e){const t=this._controllers[e.uniqueId];let i=!1;const r={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),!t.pick||this._options.disablePointerUpOnTouchOut&&i||(i?this._scene.simulatePointerMove(t.pick,r):(this._scene.simulatePointerDown(t.pick,r),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,r)))})),e.onDisposeObservable.addOnce((()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame((()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,r),t.finalPointerUpTriggered=!0)}))}))}_attachTrackedPointerRayMode(e){const t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);const i={pointerId:t.id,pointerType:"xr"};if(t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{t.laserPointer.material.disableLighting=this.disablePointerLighting,t.selectionMesh.material.disableLighting=this.disableSelectionMeshLighting,t.pick&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerMove(t.pick,i))})),e.inputSource.gamepad){const r=r=>{this._options.overrideButtonId&&(t.selectionComponent=r.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=r.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((r=>{if(r.changes.pressed){const s=r.changes.pressed.current;if(t.pick)(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),s?(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(s&&!this._options.enablePointerSelectionOnAllControllers&&!this._options.disableSwitchOnClick){const t=this._controllers[this._attachedController];t&&t.pointerDownTriggered&&!t.finalPointerUpTriggered&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerUp(new At.G,{pointerId:t.id,pointerType:"xr"}),t.finalPointerUpTriggered=!0),this._attachedController=e.uniqueId}}}))};e.motionController?r(e.motionController):e.onMotionControllerInitObservable.add(r)}else{const e=e=>{this._xrSessionManager.onXRFrameObservable.addOnce((()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.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=e=>{this._xrSessionManager.onXRFrameObservable.addOnce((()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.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:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",r)}}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(W.Pq.Dot(e,t.direction)){const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),!t.finalPointerUpTriggered&&t.pointerDownTriggered){const e={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame((()=>{this._augmentPointerInit(e,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new At.G,e),t.finalPointerUpTriggered=!0}))}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce((()=>{try{if(t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e],this._attachedController===e){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}catch(e){Ue.S0.Warn("controller already detached.")}}))}}_generateNewMeshPair(e){const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Bo.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():No("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;const r=new Un("laserPointerMat",t);r.emissiveColor=this.laserPointerDefaultColor,r.alpha=.7,i.material=r,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;const s=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():ao("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);s.bakeCurrentTransformIntoVertices(),s.isPickable=!1,s.isVisible=!1;const n=new Un("targetMat",t);return n.specularColor=H.v9.Black(),n.emissiveColor=this.selectionMeshDefaultColor,n.backFaceCulling=!1,s.material=n,void 0!==this._options.renderingGroupId&&(i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:s}}_pickingMoved(e,t){if(!e.hit||!t.hit)return!0;if(!(e.pickedMesh&&e.pickedPoint&&t.pickedMesh&&t.pickedPoint))return!0;if(e.pickedMesh!==t.pickedMesh)return!0;e.pickedPoint?.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=.01*(this._options.gazeModePointerMovedFactor||1)*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}}var Og,Dg,wg,Ng,Fg,Lg,Bg;Mg._IdCounter=200,Mg.Name=hr.POINTER_SELECTION,Mg.Version=1,cr.AddWebXRFeature(Mg.Name,((e,t)=>()=>new Mg(e,t)),Mg.Version,!0),function(e){e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=4]="Vector2",e[e.Vector3=8]="Vector3",e[e.Vector4=16]="Vector4",e[e.Color3=32]="Color3",e[e.Color4=64]="Color4",e[e.Matrix=128]="Matrix",e[e.Object=256]="Object",e[e.AutoDetect=1024]="AutoDetect",e[e.BasedOnInput=2048]="BasedOnInput",e[e.All=4095]="All"}(Og||(Og={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Neutral=4]="Neutral",e[e.VertexAndFragment=3]="VertexAndFragment"}(Dg||(Dg={}));class Vg{constructor(){this.supportUniformBuffers=!1,this.attributes=[],this.uniforms=[],this.constants=[],this.samplers=[],this.functions={},this.extensions={},this.prePassOutput={},this.counters={},this._terminalBlocks=new Set,this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}get shaderLanguage(){return this.sharedData.nodeMaterial.shaderLanguage}get fSuffix(){return 1===this.shaderLanguage?"f":""}finalize(e){const t=e.sharedData.emitComments,i=this.target===Dg.Fragment;1===this.shaderLanguage?this.compilationString=i?`\n${t?"//Entry point\n":""}@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${this.compilationString}`:`\n${t?"//Entry point\n":""}@vertex\nfn main(input: VertexInputs) -> FragmentInputs{\n${this.compilationString}`:this.compilationString=`\n${t?"//Entry point\n":""}void main(void) {\n${this.compilationString}`,this._constantDeclaration&&(this.compilationString=`\n${t?"//Constants\n":""}${this._constantDeclaration}\n${this.compilationString}`);let r="";for(const e in this.functions)r+=this.functions[e]+"\n";if(this.compilationString=`\n${r}\n${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString}\n${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString}\n${this._injectAtEnd}`),this.compilationString=`${this.compilationString}\n}`,this.sharedData.varyingDeclaration&&(this.compilationString=`\n${t?"//Varyings\n":""}${this.sharedData.varyingDeclaration}\n${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=`\n${t?"//Samplers\n":""}${this._samplerDeclaration}\n${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=`\n${t?"//Uniforms\n":""}${this._uniformDeclaration}\n${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=`\n${t?"//Attributes\n":""}${this._attributeDeclaration}\n${this.compilationString}`),1!==this.shaderLanguage){this.compilationString="precision highp float;\n"+this.compilationString,this.compilationString="#if defined(WEBGL2) || defined(WEBGPU)\nprecision highp sampler2DArray;\n#endif\n"+this.compilationString,i&&(this.compilationString="#if defined(PREPASS)\r\n#extension GL_EXT_draw_buffers : require\r\nlayout(location = 0) out highp vec4 glFragData[SCENE_MRT_COUNT];\r\nhighp vec4 gl_FragColor;\r\n#endif\r\n"+this.compilationString);for(const e in this.extensions){const t=this.extensions[e];this.compilationString=`\n${t}\n${this.compilationString}`}}this._builtCompilationString=this.compilationString}get _repeatableContentAnchor(){return`###___ANCHOR${this._repeatableContentAnchorIndex++}___###`}_getFreeVariableName(e){return e=e.replace(/[^a-zA-Z_]+/g,""),void 0===this.sharedData.variableNames[e]?(this.sharedData.variableNames[e]=0,"output"===e||"texture"===e?e+this.sharedData.variableNames[e]:e):(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])}_getFreeDefineName(e){return void 0===this.sharedData.defineNames[e]?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]}_excludeVariableName(e){this.sharedData.variableNames[e]=0}_emit2DSampler(e,t="",i=!1){(this.samplers.indexOf(e)<0||i)&&(t&&(this._samplerDeclaration+=`#if ${t}\n`),1===this.shaderLanguage?(this._samplerDeclaration+=`var ${e+"Sampler"}: sampler;\n`,this._samplerDeclaration+=`var ${e}: texture_2d;\n`):this._samplerDeclaration+=`uniform sampler2D ${e};\n`,t&&(this._samplerDeclaration+="#endif\n"),i||this.samplers.push(e))}_emitCubeSampler(e,t="",i=!1){(this.samplers.indexOf(e)<0||i)&&(t&&(this._samplerDeclaration+=`#if ${t}\n`),1===this.shaderLanguage?(this._samplerDeclaration+=`var ${e+"Sampler"}: sampler;\n`,this._samplerDeclaration+=`var ${e}: texture_cube;\n`):this._samplerDeclaration+=`uniform samplerCube ${e};\n`,t&&(this._samplerDeclaration+="#endif\n"),i||this.samplers.push(e))}_emit2DArraySampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2DArray ${e};\n`,this.samplers.push(e))}_getGLType(e){switch(e){case Og.Float:return"float";case Og.Int:return"int";case Og.Vector2:return"vec2";case Og.Color3:case Og.Vector3:return"vec3";case Og.Color4:case Og.Vector4:return"vec4";case Og.Matrix:return"mat4"}return""}_getShaderType(e){const t=1===this.shaderLanguage;switch(e){case Og.Float:return t?"f32":"float";case Og.Int:return t?"i32":"int";case Og.Vector2:return t?"vec2f":"vec2";case Og.Color3:case Og.Vector3:return t?"vec3f":"vec3";case Og.Color4:case Og.Vector4:return t?"vec4f":"vec4";case Og.Matrix:return t?"mat4x4f":"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i}\n${t}\n#endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+"\n"+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){const r=Cs.l.GetIncludesShadersStore(this.shaderLanguage);if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\n`;let s=r[e]+"\n";if(this.sharedData.emitComments&&(s=t+"\n"+s),!i)return s;if(i.replaceStrings)for(let e=0;e${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\n`:this.functions[s]=`#include<${e}>${i?.substitutionVars?"("+i?.substitutionVars+")":""}\n`,void(this.sharedData.emitComments&&(this.functions[s]=t+"\n"+this.functions[s]));if(this.functions[s]=n[e],this.sharedData.emitComments&&(this.functions[s]=t+"\n"+this.functions[s]),i.removeIfDef&&(this.functions[s]=this.functions[s].replace(/^\s*?#ifdef.+$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#endif.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#else.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[s]=this.functions[s].replace(/\s*?attribute .+?;/g,"\n")),i.removeUniforms&&(this.functions[s]=this.functions[s].replace(/\s*?uniform .*?;/g,"\n")),i.removeVaryings&&(this.functions[s]=this.functions[s].replace(/\s*?(varying|in) .+?;/g,"\n")),i.replaceStrings)for(let e=0;e")}_convertTernaryOperandsToWGSL(e){return e.replace(new RegExp("\\[(.*?)\\?(.*?):(.*)\\]","g"),((e,t,i,r)=>`select(${r}, ${i}, ${t})`))}_convertModOperatorsToWGSL(e){return e.replace(new RegExp("mod\\((.+?),\\s*(.+?)\\)","g"),((e,t,i)=>`((${t})%(${i}))`))}_convertConstToWGSL(e){return e.replace(new RegExp("const var","g"),"const")}_convertInnerFunctionsToWGSL(e){return e.replace(new RegExp("inversesqrt","g"),"inverseSqrt")}_convertFunctionsToWGSL(e){const t=/var\s+(\w+)\s*:\s*(\w+)\((.*)\)/g;let i;for(;null!==(i=t.exec(e));){const t=i[1],r=i[2],s=i[3].replace(/var\s/g,"");e=e.replace(i[0],`fn ${t}(${s}) -> ${r}`)}return e}_babylonSLtoWGSL(e){return e=this._convertVariableDeclarationToWGSL("void","voidnull",e),e=this._convertVariableDeclarationToWGSL("bool","bool",e),e=this._convertVariableDeclarationToWGSL("int","i32",e),e=this._convertVariableDeclarationToWGSL("uint","u32",e),e=this._convertVariableDeclarationToWGSL("float","f32",e),e=this._convertVariableDeclarationToWGSL("vec2","vec2f",e),e=this._convertVariableDeclarationToWGSL("vec3","vec3f",e),e=this._convertVariableDeclarationToWGSL("vec4","vec4f",e),e=this._convertVariableDeclarationToWGSL("mat2","mat2x2f",e),e=this._convertVariableDeclarationToWGSL("mat3","mat3x3f",e),e=this._convertVariableDeclarationToWGSL("mat4","mat4x4f",e),e=this._convertVariableConstructorsToWGSL("float","f32",e),e=this._convertVariableConstructorsToWGSL("vec2","vec2f",e),e=this._convertVariableConstructorsToWGSL("vec3","vec3f",e),e=this._convertVariableConstructorsToWGSL("vec4","vec4f",e),e=this._convertVariableConstructorsToWGSL("mat2","mat2x2f",e),e=this._convertVariableConstructorsToWGSL("mat3","mat3x3f",e),e=this._convertVariableConstructorsToWGSL("mat4","mat4x4f",e),e=this._convertTernaryOperandsToWGSL(e),e=this._convertModOperatorsToWGSL(e),e=this._convertConstToWGSL(e),e=this._convertInnerFunctionsToWGSL(e),e=(e=this._convertOutParametersToWGSL(e)).replace(/\[\*\]/g,"*"),(e=(e=(e=this._convertFunctionsToWGSL(e)).replace(/\s->\svoidnull/g,"")).replace(/dFdx/g,"dpdx")).replace(/dFdy/g,"dpdy")}_convertTernaryOperandsToGLSL(e){return e.replace(new RegExp("\\[(.+?)\\?(.+?):(.+)\\]","g"),((e,t,i,r)=>`${t} ? ${i} : ${r}`))}_babylonSLtoGLSL(e){return e=e.replace(/\[\*\]/g,""),this._convertTernaryOperandsToGLSL(e)}}class kg{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(e=null){let t="";this.checks.emitVertex||this.allowEmptyVertexProgram||(t+="NodeMaterial does not have a vertex output. You need to at least add a block that generates a position value.\n"),this.checks.emitFragment||(t+="NodeMaterial does not have a fragment output. You need to at least add a block that generates a color value.\n");for(const e of this.checks.notConnectedNonOptionalInputs)t+=`input ${e.name} from block ${e.ownerBlock.name}[${e.ownerBlock.getClassName()}] is not connected and is not optional.\n`;return!t||(e&&e.notifyObservers(t),Z.V.Error("Build of NodeMaterial failed:\n"+t),!1)}}!function(e){e[e.Compatible=0]="Compatible",e[e.TypeIncompatible=1]="TypeIncompatible",e[e.TargetIncompatible=2]="TargetIncompatible",e[e.HierarchyIssue=3]="HierarchyIssue"}(wg||(wg={})),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(Ng||(Ng={}));class Ug{static AreEquivalentTypes(e,t){switch(e){case Og.Vector3:if(t===Og.Color3)return!0;break;case Og.Vector4:if(t===Og.Color4)return!0;break;case Og.Color3:if(t===Og.Vector3)return!0;break;case Og.Color4:if(t===Og.Vector4)return!0}return!1}get _connectedPoint(){return this._connectedPointBackingField}set _connectedPoint(e){this._connectedPointBackingField!==e&&(this._connectedPointTypeChangedObserver?.remove(),this._updateTypeDependentState((()=>this._connectedPointBackingField=e)),this._connectedPointBackingField&&(this._connectedPointTypeChangedObserver=this._connectedPointBackingField.onTypeChangedObservable.add((()=>{this._notifyTypeChanged()}))))}get _typeConnectionSource(){return this._typeConnectionSourceBackingField}set _typeConnectionSource(e){this._typeConnectionSourceBackingField!==e&&(this._typeConnectionSourceTypeChangedObserver?.remove(),this._updateTypeDependentState((()=>this._typeConnectionSourceBackingField=e)),this._typeConnectionSourceBackingField&&(this._typeConnectionSourceTypeChangedObserver=this._typeConnectionSourceBackingField.onTypeChangedObservable.add((()=>{this._notifyTypeChanged()}))))}get _defaultConnectionPointType(){return this._defaultConnectionPointTypeBackingField}set _defaultConnectionPointType(e){this._updateTypeDependentState((()=>this._defaultConnectionPointTypeBackingField=e))}get _linkedConnectionSource(){return this._linkedConnectionSourceBackingField}set _linkedConnectionSource(e){this._linkedConnectionSourceBackingField!==e&&(this._linkedConnectionSourceTypeChangedObserver?.remove(),this._updateTypeDependentState((()=>this._linkedConnectionSourceBackingField=e)),this._linkedConnectionSourceBackingField&&(this._linkedConnectionSourceTypeChangedObserver=this._linkedConnectionSourceBackingField.onTypeChangedObservable.add((()=>{this._notifyTypeChanged()}))))}get direction(){return this._direction}get declarationVariableName(){return this._ownerBlock.isInput?this._ownerBlock.declarationVariableName:this._enforceAssociatedVariableName&&this._associatedVariableName||!this._connectedPoint?this._associatedVariableName:this._connectedPoint.declarationVariableName}get associatedVariableName(){return this._ownerBlock.isInput?this._ownerBlock.associatedVariableName:this._enforceAssociatedVariableName&&this._associatedVariableName||!this._connectedPoint?this._associatedVariableName:this._connectedPoint.associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}get type(){if(this._type===Og.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.connectedPoint._redirectedSource&&this._linkedConnectionSource.connectedPoint._redirectedSource.isConnected?this._linkedConnectionSource.connectedPoint._redirectedSource.type:this._linkedConnectionSource.type}if(this._type===Og.BasedOnInput){if(this._typeConnectionSource)return!this._typeConnectionSource.isConnected&&this._defaultConnectionPointType?this._defaultConnectionPointType:this._typeConnectionSource.type;if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type}set type(e){this._updateTypeDependentState((()=>this._type=e))}get target(){return this._prioritizeVertex&&this._ownerBlock?this._target!==Dg.VertexAndFragment?this._target:this._ownerBlock.target===Dg.Fragment?Dg.Fragment:Dg.Vertex:this._target}set target(e){this._target=e}get isConnected(){return null!==this.connectedPoint||this.hasEndpoints}get isConnectedToInputBlock(){return null!==this.connectedPoint&&this.connectedPoint.ownerBlock.isInput}get connectInputBlock(){return this.isConnectedToInputBlock?this.connectedPoint.ownerBlock:null}get connectedPoint(){return this._connectedPoint}get ownerBlock(){return this._ownerBlock}get sourceBlock(){return this._connectedPoint?this._connectedPoint.ownerBlock:null}get connectedBlocks(){return 0===this._endpoints.length?[]:this._endpoints.map((e=>e.ownerBlock))}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===Dg.Vertex)return!0;if((e.ownerBlock.target===Dg.Neutral||e.ownerBlock.target===Dg.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isDirectlyConnectedToVertexOutput)))return!0}return!1}get isConnectedInVertexShader(){if(this.target===Dg.Vertex)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===Dg.Vertex)return!0;if(e.target===Dg.Vertex)return!0;if((e.ownerBlock.target===Dg.Neutral||e.ownerBlock.target===Dg.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isConnectedInVertexShader)))return!0}return!1}get isConnectedInFragmentShader(){if(this.target===Dg.Fragment)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===Dg.Fragment)return!0;if((e.ownerBlock.target===Dg.Neutral||e.ownerBlock.target===Dg.VertexAndFragment)&&e.ownerBlock.isConnectedInFragmentShader())return!0}return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._preventBubbleUp=!1,this._connectedPointBackingField=null,this._endpoints=new Array,this._redirectedSource=null,this._typeConnectionSourceBackingField=null,this._defaultConnectionPointTypeBackingField=null,this._linkedConnectionSourceBackingField=null,this._acceptedConnectionPointType=null,this._type=Og.Float,this._enforceAssociatedVariableName=!1,this._forPostBuild=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new z.cP,this.onDisconnectionObservable=new z.cP,this.onTypeChangedObservable=new z.cP,this._isTypeChangeObservableNotifying=!1,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=Dg.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return 0===this.checkCompatibilityState(e)}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(t.target===Dg.Fragment){if(i.target===Dg.Vertex)return 2;for(const e of i.outputs)if(e.ownerBlock.target!=Dg.Neutral&&e.isConnectedInVertexShader)return 2}if(this.type!==e.type&&e.innerType!==Og.AutoDetect)return Ug.AreEquivalentTypes(this.type,e.type)||e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)||e._acceptedConnectionPointType&&Ug.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?0:1;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return 1;let r=i,s=t;return 0===this.direction&&(r=t,s=i),r.isAnAncestorOf(s)?3:0}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this)),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear(),this.onDisconnectionObservable.clear(),this.onTypeChangedObservable.clear(),this._connectedPoint=null,this._typeConnectionSource=null,this._linkedConnectionSource=null}_updateTypeDependentState(e){const t=this.type;e(),this.type!==t&&this._notifyTypeChanged()}_notifyTypeChanged(){this._isTypeChangeObservableNotifying||(this._isTypeChangeObservableNotifying=!0,this.onTypeChangedObservable.notifyObservers(this.type),this._isTypeChangeObservableNotifying=!1)}}class Gg{get name(){return this._name}get codeIsReady(){return this._codeIsReady}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get isLoop(){return this._isLoop}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((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.name===e));return t.length?t[0]:null}constructor(e,t=Dg.Vertex,i=!1){switch(this._isFinalMerger=!1,this._isInput=!1,this._isLoop=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._name="",this._isUnique=!1,this._codeIsReady=!0,this.onCodeIsReadyObservable=new z.cP,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===Dg.Neutral,this._isFinalMerger=i,this.getClassName()){case"InputBlock":this._isInput=!0;break;case"NodeMaterialTeleportOutBlock":this._isTeleportOut=!0;break;case"NodeMaterialTeleportInBlock":this._isTeleportIn=!0;break;case"LoopBlock":this._isLoop=!0}this._name=e,this.uniqueId=Op.K.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===Dg.Neutral}initialize(e){}bind(e,t,i,r){}_writeVariable(e){return e.connectedPoint?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return-1===t.indexOf(".")&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}isConnectedInFragmentShader(){return this.outputs.some((e=>e.isConnectedInFragmentShader))}registerInput(e,t,i=!1,r,s){return(s=s??new Ug(e,this,0)).type=t,s.isOptional=i,r&&(s.target=r),this._inputs.push(s),this}registerOutput(e,t,i,r){return(r=r??new Ug(e,this,1)).type=t,i&&(r.target=i),this._outputs.push(r),this}getFirstAvailableInput(e=null){for(const t of this._inputs)if(!(t.connectedPoint||e&&e.type!==t.type&&t.type!==Og.AutoDetect&&-1===t.acceptedConnectionPointTypes.indexOf(e.type)))return t;return null}getFirstAvailableOutput(e=null){for(const t of this._outputs)if(!e||!e.target||e.target===Dg.Neutral||e.target&t.target)return t;return null}getSiblingOutput(e){const t=this._outputs.indexOf(e);return-1===t||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)return!0;if(i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(0===this._outputs.length)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),r=!0;for(;r;){const s=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&s&&i.canConnectTo(s))i.connectTo(s),r=!1;else{if(!i)throw"Unable to find a compatible match";i=this.getSiblingOutput(i)}}return this}_buildBlock(e){}_postBuildBlock(e){}updateUniformsAndSamples(e,t,i,r){}provideFallbacks(e,t){}initializeDefines(e,t,i,r=!1){}prepareDefines(e,t,i,r=!1,s){}autoConfigure(e,t=(()=>!0)){}replaceRepeatableContent(e,t,i,r){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return!(this.isInput||this.isFinalMerger||this._outputs.some((e=>e.isDirectlyConnectedToVertexOutput))||this.target===Dg.Vertex||this.target!==Dg.VertexAndFragment&&this.target!==Dg.Neutral||!this._outputs.some((e=>e.isConnectedInVertexShader)))}isReady(e,t,i,r=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,r){e.build(t,r);const s=null!=t._vertexState,n=e._buildTarget===Dg.Vertex&&e.target!==Dg.VertexAndFragment;if(s&&(!(e.target&e._buildTarget)||!(e.target&i.target)||this.target!==Dg.VertexAndFragment&&n)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){const e=i.connectedPoint;if(t._vertexState._emitVaryingFromString("v_"+e.declarationVariableName,e.type)){const i=1===t.shaderLanguage?"vertexOutputs.":"";t._vertexState.compilationString+=`${i}${"v_"+e.declarationVariableName} = ${e.associatedVariableName};\n`}const r=1===t.shaderLanguage?"fragmentInputs.":"";i.associatedVariableName=r+"v_"+e.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 t of this._outputs)t.associatedVariableName||(t.associatedVariableName=e._getFreeVariableName(t.name));for(const i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==Dg.Neutral){if(!(i.target&this.target))continue;if(!(i.target&e.target))continue}const r=i.connectedPoint.ownerBlock;r&&r!==this&&this._processBuild(r,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&Z.V.Log(`${e.target===Dg.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case Dg.Vertex:e.sharedData.checks.emitVertex=!0;break;case Dg.Fragment:e.sharedData.checks.emitFragment=!0}!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=`\n//${this.name}\n`),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target;for(const i of this._outputs)if(!i._forPostBuild&&i.target&e.target)for(const r of i.endpoints){const i=r.ownerBlock;i&&(i.target&e.target&&-1!==t.indexOf(i)||e._terminalBlocks.has(i))&&this._processBuild(i,e,r,t)}this._postBuildBlock(e);for(const i of this._outputs)if(i._forPostBuild&&i.target&e.target)for(const r of i.endpoints){const i=r.ownerBlock;i&&i.target&e.target&&-1!==t.indexOf(i)&&this._processBuild(i,e,r,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){const e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector};\n${e}.visibleOnFrame = ${this.visibleOnFrame};\n${e}.target = ${this.target};\n`}_dumpCode(e,t){t.push(this);const i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=i+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let r=`\n// ${this.getClassName()}\n`;this.comments&&(r+=`// ${this.comments}\n`),r+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}");\n`,r+=this._dumpPropertiesCode();for(const i of this.inputs){if(!i.isConnected)continue;const s=i.connectedPoint.ownerBlock;-1===t.indexOf(s)&&(r+=s._dumpCode(e,t))}for(const i of this.outputs)if(i.hasEndpoints)for(const s of i.endpoints){const i=s.ownerBlock;i&&-1===t.indexOf(i)&&(r+=i._dumpCode(e,t))}return r}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e),t+=`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\n`}return t}clone(e,t=""){const i=this.serialize(),r=(0,X.n9)(i.customType);if(r){const s=new r;return s._deserialize(i,e,t),s}return null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.visibleInInspector=this.visibleInInspector,e.visibleOnFrame=this.visibleOnFrame,e.target=this.target,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i,r){this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=e.target??this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach(((e,t)=>{e.displayName&&(this.inputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.inputs[t].isExposedOnFrame=e.isExposedOnFrame,this.inputs[t].exposedPortPosition=e.exposedPortPosition)})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}dispose(){this.onCodeIsReadyObservable.clear();for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose()}}class zg extends Gg{get transformAsDirection(){return 0===this.complementW}set transformAsDirection(e){this.complementW=e?0:1}constructor(e){super(e,Dg.Neutral),this.complementW=1,this.complementZ=0,this.target=Dg.Vertex,this.registerInput("vector",Og.AutoDetect),this.registerInput("transform",Og.Matrix),this.registerOutput("output",Og.Vector4),this.registerOutput("xyz",Og.Vector3),this._inputs[0].onConnectionObservable.add((e=>{if(e.ownerBlock.isInput){const t=e.ownerBlock;"normal"!==t.name&&"tangent"!==t.name||(this.complementW=0)}}))}getClassName(){return"TransformBlock"}get vector(){return this._inputs[0]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}get transform(){return this._inputs[1]}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.transform,r=e._getShaderType(Og.Vector4),s=e._getShaderType(Og.Vector3);if(t.connectedPoint){if(0===this.complementW||this.transformAsDirection){const n=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",n),e.sharedData.blocksWithDefines.push(this);const o=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(1===e.shaderLanguage?e.compilationString+=`var ${o}: mat3x3f = mat3x3f(${i.associatedVariableName}[0].xyz, ${i.associatedVariableName}[1].xyz, ${i.associatedVariableName}[2].xyz);\n`:e.compilationString+=`mat3 ${o} = mat3(${i.associatedVariableName});\n`,e.compilationString+="#ifdef NONUNIFORMSCALING\n",e.compilationString+=`${o} = transposeMat3(inverseMat3(${o}));\n`,e.compilationString+="#endif\n",t.connectedPoint.type){case Og.Vector2:e.compilationString+=e._declareOutput(this.output)+` = ${r}(${o} * ${s}(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)});\n`;break;case Og.Vector3:case Og.Color3:e.compilationString+=e._declareOutput(this.output)+` = ${r}(${o} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\n`;break;default:e.compilationString+=e._declareOutput(this.output)+` = ${r}(${o} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)});\n`}}else{const s=i.associatedVariableName;switch(t.connectedPoint.type){case Og.Vector2:e.compilationString+=e._declareOutput(this.output)+` = ${s} * ${r}(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)});\n`;break;case Og.Vector3:case Og.Color3:e.compilationString+=e._declareOutput(this.output)+` = ${s} * ${r}(${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\n`;break;default:e.compilationString+=e._declareOutput(this.output)+` = ${s} * ${t.associatedVariableName};\n`}}this.xyz.hasEndpoints&&(e.compilationString+=e._declareOutput(this.xyz)+` = ${this.output.associatedVariableName}.xyz;\n`)}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=void 0!==e.complementZ?e.complementZ:0,this.complementW=void 0!==e.complementW?e.complementW:1}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ};\n`;return e+=`${this._codeVariableName}.complementW = ${this.complementW};\n`,e}}(0,je.Cg)([t_("Transform as direction",0,void 0,{embedded:!0})],zg.prototype,"transformAsDirection",null),(0,X.Y5)("BABYLON.TransformBlock",zg);class Wg extends Gg{constructor(e){super(e,Dg.Vertex,!0),this.registerInput("vector",Og.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e,t){if(t)return!0;for(const t of e)if(t.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=1===e.shaderLanguage;if(1===e.shaderLanguage?e.compilationString+=`vertexOutputs.position = ${t.associatedVariableName};\n`:e.compilationString+=`gl_Position = ${t.associatedVariableName};\n`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes,e.sharedData.nodeMaterial.useLogarithmicDepth)){e._emitUniformFromString("logarithmicDepthConstant",Og.Float),e._emitVaryingFromString("vFragmentDepth",Og.Float);const t=i?"vertexOutputs.vFragmentDepth":"vFragmentDepth",r=i?"uniforms.":"",s=i?"vertexOutputs.position":"gl_Position";e.compilationString+=`${t} = 1.0 + ${s}.w;\n`,e.compilationString+=`${s}.z = log2(max(0.000001, ${t})) * ${r}logarithmicDepthConstant;\n`}return this}}(0,X.Y5)("BABYLON.VertexOutputBlock",Wg),function(e){e[e.NoColorSpace=0]="NoColorSpace",e[e.Gamma=1]="Gamma",e[e.Linear=2]="Linear"}(Fg||(Fg={}));class Hg extends Gg{constructor(e){super(e,Dg.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",Og.Color4,!0),this.registerInput("rgb",Og.Color3,!0),this.registerInput("a",Og.Float,!0),this.rgb.acceptedConnectionPointTypes.push(Og.Vector3),this.rgb.acceptedConnectionPointTypes.push(Og.Float)}get colorSpace(){return this.convertToGammaSpace?Fg.Gamma:this.convertToLinearSpace?Fg.Linear:Fg.NoColorSpace}set colorSpace(e){this.convertToGammaSpace=e===Fg.Gamma,this.convertToLinearSpace=e===Fg.Linear}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&&(0,Bt.DL)(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=this.rgba,i=this.rgb,r=this.a,s=1===e.shaderLanguage;e.sharedData.hints.needAlphaBlending=t.isConnected||r.isConnected,e.sharedData.blocksWithDefines.push(this),(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant",Og.Float),e._emitVaryingFromString("vFragmentDepth",Og.Float),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");const n=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",n);let o="gl_FragColor";1===e.shaderLanguage&&(e.compilationString+="var fragmentOutputsColor : vec4;\r\n",o="fragmentOutputsColor");const a=e._getShaderType(Og.Vector4);if(t.connectedPoint)r.isConnected?e.compilationString+=`${o} = ${a}(${t.associatedVariableName}.rgb, ${r.associatedVariableName});\n`:e.compilationString+=`${o} = ${t.associatedVariableName};\n`;else if(i.connectedPoint){let t="1.0";r.connectedPoint&&(t=r.associatedVariableName),i.connectedPoint.type===Og.Float?e.compilationString+=`${o} = ${a}(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${t});\n`:e.compilationString+=`${o} = ${a}(${i.associatedVariableName}, ${t});\n`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);if(e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${o} = toLinearSpace(${o});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${o} = toGammaSpace(${o});\n`,e.compilationString+="#endif\n",1===e.shaderLanguage&&(e.compilationString+="#if !defined(PREPASS)\r\n",e.compilationString+="fragmentOutputs.color = fragmentOutputsColor;\r\n",e.compilationString+="#endif\r\n"),this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth){const t=s?"input.vFragmentDepth":"vFragmentDepth",i=s?"uniforms.":"",r=s?"fragmentOutputs.fragDepth":"gl_FragDepthEXT";e.compilationString+=`${r} = log2(${t}) * ${i}logarithmicDepthConstant * 0.5;\n`}return e.compilationString+="#if defined(PREPASS)\r\n",e.compilationString+=`${s?"fragmentOutputs.fragData0":"gl_FragData[0]"} = ${o};\r\n`,e.compilationString+="#endif\r\n",this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth};\n`,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}}(0,je.Cg)([t_("Use logarithmic depth",0,"PROPERTIES",{embedded:!0})],Hg.prototype,"useLogarithmicDepth",void 0),(0,je.Cg)([t_("Color space",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"No color space",value:Fg.NoColorSpace},{label:"Gamma",value:Fg.Gamma},{label:"Linear",value:Fg.Linear}]})],Hg.prototype,"colorSpace",null),(0,X.Y5)("BABYLON.FragmentOutputBlock",Hg),function(e){e[e.World=1]="World",e[e.View=2]="View",e[e.Projection=3]="Projection",e[e.ViewProjection=4]="ViewProjection",e[e.WorldView=5]="WorldView",e[e.WorldViewProjection=6]="WorldViewProjection",e[e.CameraPosition=7]="CameraPosition",e[e.FogColor=8]="FogColor",e[e.DeltaTime=9]="DeltaTime",e[e.CameraParameters=10]="CameraParameters",e[e.MaterialAlpha=11]="MaterialAlpha"}(Lg||(Lg={})),function(e){e[e.None=0]="None",e[e.Time=1]="Time",e[e.RealTime=2]="RealTime",e[e.MouseInfo=3]="MouseInfo"}(Bg||(Bg={}));const Xg={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},qg={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},Yg={particle_texturemask:!0};class Kg extends Gg{get type(){if(this._type===Og.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=Og.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=Og.Vector2,this._type;case"Vector3":return this._type=Og.Vector3,this._type;case"Vector4":return this._type=Og.Vector4,this._type;case"Color3":return this._type=Og.Color3,this._type;case"Color4":return this._type=Og.Color4,this._type;case"Matrix":return this._type=Og.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"splatIndex":return this._type=Og.Float,this._type;case"position":case"normal":case"particle_positionw":case"splatPosition":return this._type=Og.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":case"splatScale":return this._type=Og.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=Og.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":case"splatColor":return this._type=Og.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case Lg.World:case Lg.WorldView:case Lg.WorldViewProjection:case Lg.View:case Lg.ViewProjection:case Lg.Projection:return this._type=Og.Matrix,this._type;case Lg.CameraPosition:return this._type=Og.Vector3,this._type;case Lg.FogColor:return this._type=Og.Color3,this._type;case Lg.DeltaTime:case Lg.MaterialAlpha:return this._type=Og.Float,this._type;case Lg.CameraParameters:return this._type=Og.Vector4,this._type}}return this._type}constructor(e,t=Dg.Vertex,i=Og.AutoDetect){super(e,t,!1),this._mode=3,this._animationType=Bg.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 z.cP,this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._type=i,this.setDefaultValue(),this.registerOutput("output",i)}validateBlockName(e){return!!this.isAttribute||super.validateBlockName(e)}get output(){return this._outputs[0]}setAsAttribute(e){return this._mode=1,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===Og.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=0,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=0}get declarationVariableName(){return this._associatedVariableName}get associatedVariableName(){return this._prefix+this._associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get animationType(){return this._animationType}set animationType(e){this._animationType=e}get isUndefined(){return 3===this._mode}get isUniform(){return 0===this._mode}set isUniform(e){this._mode=e?0:3,this.associatedVariableName=""}get isAttribute(){return 1===this._mode}set isAttribute(e){this._mode=e?1:3,this.associatedVariableName=""}get isVarying(){return 2===this._mode}set isVarying(e){this._mode=e?2:3,this.associatedVariableName=""}get isSystemValue(){return null!=this._systemValue}get systemValue(){return this._systemValue}set systemValue(e){this._mode=0,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case Bg.Time:this.type===Og.Float&&(this.value+=.01*e.getAnimationRatio());break;case Bg.RealTime:this.type===Og.Float&&(this.value=(ai.j.Now-e.getEngine().startTime)/1e3);break;case Bg.MouseInfo:if(this.type===Og.Vector4){const t=e._inputManager._originMouseEvent;if(t){const e=t.offsetX,i=t.offsetY,r=1&t.buttons?1:0,s=2&t.buttons?1:0;this.value=new W.IU(e,i,r,s)}else this.value=new W.IU(0,0,0,0)}}}_emitDefine(e){return"!"===e[0]?`#ifndef ${e.substring(1)}\n`:`#ifdef ${e}\n`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case Og.Float:this.value=0;break;case Og.Vector2:this.value=W.I9.Zero();break;case Og.Vector3:this.value=W.Pq.Zero();break;case Og.Vector4:this.value=W.IU.Zero();break;case Og.Color3:this.value=hc.v9.White();break;case Og.Color4:this.value=new hc.ov(1,1,1,1);break;case Og.Matrix:this.value=W.uq.Identity()}}_emitConstant(e){switch(this.type){case Og.Float:return`${e._emitFloat(this.value)}`;case Og.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case Og.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case Og.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case Og.Color3:return hc.IG.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&hc.IG.Color3[0].toGammaSpaceToRef(hc.IG.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&hc.IG.Color3[0].toLinearSpaceToRef(hc.IG.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${hc.IG.Color3[0].r}, ${hc.IG.Color3[0].g}, ${hc.IG.Color3[0].b})`;case Og.Color4:return hc.IG.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&hc.IG.Color4[0].toGammaSpaceToRef(hc.IG.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&hc.IG.Color4[0].toLinearSpaceToRef(hc.IG.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${hc.IG.Color4[0].r}, ${hc.IG.Color4[0].g}, ${hc.IG.Color4[0].b}, ${hc.IG.Color4[0].a})`}return""}get _noContextSwitch(){return qg[this.name]}_emit(e,t){if(this.isUniform){if(this._associatedVariableName||(this._associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(-1!==e.constants.indexOf(this.associatedVariableName))return;return e.constants.push(this.associatedVariableName),void(e._constantDeclaration+=e._declareOutput(this.output,!0)+` = ${this._emitConstant(e)};\n`)}if(-1!==e.uniforms.indexOf(this.associatedVariableName))return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t));const i=e._getShaderType(this.type);1===e.shaderLanguage?(e._uniformDeclaration+=`uniform ${this._associatedVariableName}: ${i};\n`,this._prefix="uniforms."):e._uniformDeclaration+=`uniform ${i} ${this.associatedVariableName};\n`,t&&(e._uniformDeclaration+="#endif\n");const r=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case Lg.WorldView:r.needWorldViewMatrix=!0;break;case Lg.WorldViewProjection:r.needWorldViewProjectionMatrix=!0}else this._animationType!==Bg.None&&e.sharedData.animatedInputs.push(this)}else if(this.isAttribute){if(this.associatedVariableName=Xg[this.name]??this.name,this.target===Dg.Vertex&&e._vertexState)return void(qg[this.name]?Yg[this.name]?(e._emitUniformFromString(this.declarationVariableName,this.type,t),1===e.shaderLanguage&&(this._prefix="vertexInputs.")):e._emitVaryingFromString(this.declarationVariableName,this.type,t):this._emit(e._vertexState,t));const i=-1!==e.attributes.indexOf(this.declarationVariableName);i||e.attributes.push(this.declarationVariableName),qg[this.name]?Yg[this.name]?(i||e._emitUniformFromString(this.declarationVariableName,this.type,t),1===e.shaderLanguage&&(this._prefix="uniforms.")):(i||e._emitVaryingFromString(this.declarationVariableName,this.type,t),1===e.shaderLanguage&&(this._prefix="fragmentInputs.")):(t&&!i&&(e._attributeDeclaration+=this._emitDefine(t)),1===e.shaderLanguage?(i||(e._attributeDeclaration+=`attribute ${this.declarationVariableName}: ${e._getShaderType(this.type)};\n`),this._prefix="vertexInputs."):i||(e._attributeDeclaration+=`attribute ${e._getShaderType(this.type)} ${this.declarationVariableName};\n`),t&&!i&&(e._attributeDeclaration+="#endif\n"))}}_transmitWorld(e,t,i,r){if(!this._systemValue)return;const s=this._associatedVariableName;switch(this._systemValue){case Lg.World:e.setMatrix(s,t);break;case Lg.WorldView:e.setMatrix(s,i);break;case Lg.WorldViewProjection:e.setMatrix(s,r)}}_transmit(e,t,i){if(this.isAttribute)return;const r=this._associatedVariableName;if(this._systemValue){switch(this._systemValue){case Lg.World:case Lg.WorldView:case Lg.WorldViewProjection:return;case Lg.View:e.setMatrix(r,t.getViewMatrix());break;case Lg.Projection:e.setMatrix(r,t.getProjectionMatrix());break;case Lg.ViewProjection:e.setMatrix(r,t.getTransformMatrix());break;case Lg.CameraPosition:t.bindEyePosition(e,r,!0);break;case Lg.FogColor:e.setColor3(r,t.fogColor);break;case Lg.DeltaTime:e.setFloat(r,t.deltaTime/1e3);break;case Lg.CameraParameters:t.activeCamera&&e.setFloat4(r,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case Lg.MaterialAlpha:e.setFloat(r,i.alpha)}return}const s=this._valueCallback?this._valueCallback():this._storedValue;if(null!==s)switch(this.type){case Og.Float:e.setFloat(r,s);break;case Og.Int:e.setInt(r,s);break;case Og.Color3:hc.IG.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&hc.IG.Color3[0].toGammaSpaceToRef(hc.IG.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&hc.IG.Color3[0].toLinearSpaceToRef(hc.IG.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(r,hc.IG.Color3[0]);break;case Og.Color4:hc.IG.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&hc.IG.Color4[0].toGammaSpaceToRef(hc.IG.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&hc.IG.Color4[0].toLinearSpaceToRef(hc.IG.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(r,hc.IG.Color4[0]);break;case Og.Vector2:e.setVector2(r,s);break;case Og.Vector3:e.setVector3(r,s);break;case Og.Vector4:e.setVector4(r,s);break;case Og.Matrix:e.setMatrix(r,s)}}_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}");\n`;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${Lg[this._systemValue]});\n`;if(this.isUniform){const t=[];let i="";switch(this.type){case Og.Float:i=`${this.value}`;break;case Og.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case Og.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case Og.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case Og.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case Og.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 Og.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`}return t.push(`${e}.value = ${i}`),this.type===Og.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${Bg[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}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,null!=this._storedValue&&0===this._mode&&(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,"tangent"===e.name&&1===e.mode&&e.type===Og.Vector3&&(this._type=Og.Vector4),e.valueType)if("number"===e.valueType)this._storedValue=e.value;else{const t=(0,X.n9)(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}(0,X.Y5)("BABYLON.InputBlock",Kg);class jg extends Gg{constructor(e){super(e,Dg.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",Og.AutoDetect,!1,Dg.VertexAndFragment),this.registerOutput("rgba",Og.Color4,Dg.Neutral),this.registerOutput("rgb",Og.Color3,Dg.Neutral),this.registerOutput("r",Og.Float,Dg.Neutral),this.registerOutput("g",Og.Float,Dg.Neutral),this.registerOutput("b",Og.Float,Dg.Neutral),this.registerOutput("a",Og.Float,Dg.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(Og.Vector2|Og.Vector3|Og.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"CurrentScreenBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName(this._samplerName)}get target(){return this.uv.isConnected?this.uv.sourceBlock.isInput?Dg.VertexAndFragment:Dg.Fragment:Dg.VertexAndFragment}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,Og.Vector2)),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,Og.Vector2),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name,!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===Dg.Fragment)return;const t=0===e.shaderLanguage?`texture2D(${this._samplerName},`:`textureSampleLevel(${this._samplerName}, ${this._samplerName+"Sampler"},`,r=0===e.shaderLanguage?"":", 0";return void(e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = ${t} ${i.associatedVariableName}${r});\n`)}const r=0===e.shaderLanguage?`texture2D(${this._samplerName},`:`textureSample(${this._samplerName}, ${this._samplerName+"Sampler"},`;this.uv.ownerBlock.target!==Dg.Fragment?e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = ${r} ${this._mainUVName});\n`:e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = ${r} ${i.associatedVariableName});\n`}_writeOutput(e,t,i,r=!1){if(r){if(e.target===Dg.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}else this.uv.ownerBlock.target!==Dg.Fragment?(e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n"):e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}_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!==Dg.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(!this._outputs.some((e=>e.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 t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.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=0===e.texture.url.indexOf("data:")?"":i,this.texture=vi.g.Parse(e.texture,t,i))}}(0,X.Y5)("BABYLON.CurrentScreenBlock",jg);class $g extends Gg{constructor(e){super(e,Dg.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",Og.AutoDetect,!1,Dg.VertexAndFragment),this.registerOutput("rgba",Og.Color4,Dg.Neutral),this.registerOutput("rgb",Og.Color3,Dg.Neutral),this.registerOutput("r",Og.Float,Dg.Neutral),this.registerOutput("g",Og.Float,Dg.Neutral),this.registerOutput("b",Og.Float,Dg.Neutral),this.registerOutput("a",Og.Float,Dg.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(Og.Vector2|Og.Vector3|Og.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((e=>e.isAttribute&&"particle_uv"===e.name&&t(e)));i||(i=new Kg("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};\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n"}_buildBlock(e){if(super._buildBlock(e),e.target===Dg.Vertex)return;this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e._emit2DSampler(this._samplerName),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = ${e._generateTextureSample(this.uv.associatedVariableName,this._samplerName)};\n`;for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.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=0===e.texture.url.indexOf("data:")?"":i,this.texture=vi.g.Parse(e.texture,t,i))}}(0,X.Y5)("BABYLON.ParticleTextureBlock",$g);class Qg extends Gg{constructor(e){super(e,Dg.Fragment),this._isUnique=!0,this.registerInput("color",Og.Color4,!1,Dg.Fragment),this.registerOutput("rampColor",Og.Color4,Dg.Fragment)}getClassName(){return"ParticleRampGradientBlock"}get color(){return this._inputs[0]}get rampColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("remapRanges"),e._excludeVariableName("rampSampler"),e._excludeVariableName("baseColor"),e._excludeVariableName("alpha"),e._excludeVariableName("remappedColorIndex"),e._excludeVariableName("rampColor")}_buildBlock(e){if(super._buildBlock(e),e.target!==Dg.Vertex)return e._emit2DSampler("rampSampler","RAMPGRADIENT"),e._emitVaryingFromString("remapRanges",Og.Vector4,"RAMPGRADIENT"),e.compilationString+=`\n #ifdef RAMPGRADIENT\n ${e._declareLocalVar("baseColor",Og.Vector4)} = ${this.color.associatedVariableName};\n ${e._declareLocalVar("alpha",Og.Float)} = ${this.color.associatedVariableName}.a;\n\n ${e._declareLocalVar("remappedColorIndex",Og.Float)} = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0);\n\n ${e._declareLocalVar("rampColor",Og.Vector4)} = ${e._generateTextureSample("vec2(1.0 - remappedColorIndex, 0.)","rampSampler")};\n\n // Remapped alpha\n ${e._declareOutput(this.rampColor)} = vec4${e.fSuffix}(baseColor.rgb * rampColor.rgb, clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0));\n #else\n ${e._declareOutput(this.rampColor)} = ${this.color.associatedVariableName};\n #endif\n `,this}}(0,X.Y5)("BABYLON.ParticleRampGradientBlock",Qg);class Zg extends Gg{constructor(e){super(e,Dg.Fragment),this._isUnique=!0,this.registerInput("color",Og.Color4,!1,Dg.Fragment),this.registerInput("alphaTexture",Og.Float,!1,Dg.Fragment),this.registerInput("alphaColor",Og.Float,!1,Dg.Fragment),this.registerOutput("blendColor",Og.Color4,Dg.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!==Dg.Vertex)return e.compilationString+=`\n #ifdef BLENDMULTIPLYMODE\n ${e._declareOutput(this.blendColor)};\n ${e._declareLocalVar("sourceAlpha",Og.Float)} = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName};\n ${this.blendColor.associatedVariableName} = vec4${e.fSuffix}(${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha), ${this.color.associatedVariableName}.a);\n #else\n ${e._declareOutput(this.blendColor)} = ${this.color.associatedVariableName};\n #endif\n `,this}}(0,X.Y5)("BABYLON.ParticleBlendMultiplyBlock",Zg);class Jg extends Gg{constructor(e){super(e,Dg.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",Og.Vector4,!0),this.registerInput("xyz ",Og.Vector3,!0),this.registerInput("xy ",Og.Vector2,!0),this.registerInput("zw ",Og.Vector2,!0),this.registerInput("x",Og.Float,!0),this.registerInput("y",Og.Float,!0),this.registerInput("z",Og.Float,!0),this.registerInput("w",Og.Float,!0),this.registerOutput("xyzw",Og.Vector4),this.registerOutput("xyz",Og.Vector3),this.registerOutput("xy",Og.Vector2),this.registerOutput("zw",Og.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"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":e}_buildSwizzle(e){return"."+(this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle).substring(0,e)}_buildBlock(e){super._buildBlock(e);const t=this.x,i=this.y,r=this.z,s=this.w,n=this.xyIn,o=this.zwIn,a=this.xyzIn,l=this.xyzwIn,h=this._outputs[0],c=this._outputs[1],u=this._outputs[2],d=this._outputs[3],f=e._getShaderType(Og.Vector4),p=e._getShaderType(Og.Vector3),_=e._getShaderType(Og.Vector2);return l.isConnected?(h.hasEndpoints&&(e.compilationString+=e._declareOutput(h)+` = ${l.associatedVariableName}${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${l.associatedVariableName}${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${l.associatedVariableName}${this._buildSwizzle(2)};\n`)):a.isConnected?(h.hasEndpoints&&(e.compilationString+=e._declareOutput(h)+` = ${f}(${a.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${a.associatedVariableName}${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${a.associatedVariableName}${this._buildSwizzle(2)};\n`)):n.isConnected?(h.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(h)+` = ${f}(${n.associatedVariableName}, ${o.associatedVariableName})${this._buildSwizzle(4)};\n`:e.compilationString+=e._declareOutput(h)+` = ${f}(${n.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${p}(${n.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${n.associatedVariableName}${this._buildSwizzle(2)};\n`),d.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(d)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\n`:e.compilationString+=e._declareOutput(d)+` = ${_}(${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(2)};\n`)):(h.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(h)+` = ${f}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${o.associatedVariableName})${this._buildSwizzle(4)};\n`:e.compilationString+=e._declareOutput(h)+` = ${f}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${p}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${_}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)};\n`),d.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(d)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\n`:e.compilationString+=e._declareOutput(d)+` = ${_}(${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(2)};\n`)),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}";\n`,e+=`${this._codeVariableName}.ySwizzle = "${this.ySwizzle}";\n`,e+=`${this._codeVariableName}.zSwizzle = "${this.zSwizzle}";\n`,e+=`${this._codeVariableName}.wSwizzle = "${this.wSwizzle}";\n`,e}}(0,X.Y5)("BABYLON.VectorMergerBlock",Jg);class ev extends Gg{constructor(e){super(e,Dg.Neutral),this.sourceRange=new W.I9(-1,1),this.targetRange=new W.I9(0,1),this.registerInput("input",Og.AutoDetect),this.registerInput("sourceMin",Og.Float,!0),this.registerInput("sourceMax",Og.Float,!0),this.registerInput("targetMin",Og.Float,!0),this.registerInput("targetMax",Og.Float,!0),this.registerOutput("output",Og.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"RemapBlock"}get input(){return this._inputs[0]}get sourceMin(){return this._inputs[1]}get sourceMax(){return this._inputs[2]}get targetMin(){return this._inputs[3]}get targetMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),r=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),s=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)+` = ${s} + (${this._inputs[0].associatedVariableName} - ${i}) * (${n} - ${s}) / (${r} - ${i});\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y});\n`;return e+=`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y});\n`,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=W.I9.FromArray(e.sourceRange),this.targetRange=W.I9.FromArray(e.targetRange)}}(0,je.Cg)([t_("From",3)],ev.prototype,"sourceRange",void 0),(0,je.Cg)([t_("To",3)],ev.prototype,"targetRange",void 0),(0,X.Y5)("BABYLON.RemapBlock",ev);class tv extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("left",Og.AutoDetect),this.registerInput("right",Og.AutoDetect),this.registerOutput("output",Og.BasedOnInput),this.output._typeConnectionSource=this.left,this._linkConnectionTypes(0,1,!0),this.left.acceptedConnectionPointTypes.push(Og.Float),this.right.acceptedConnectionPointTypes.push(Og.Float),this._connectionObservers=[this.left.onTypeChangedObservable.add((()=>this._updateInputOutputTypes())),this.right.onTypeChangedObservable.add((()=>this._updateInputOutputTypes()))]}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_updateInputOutputTypes(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===Og.Int||this.left.type===Og.Float&&this.right.type!==Og.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=[Og.Int,Og.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),t.type!==Og.Int&&t.type!==Og.Float||e.acceptedConnectionPointTypes.push(Og.Vector2,Og.Vector3,Og.Vector4,Og.Color3,Og.Color4,Og.Matrix))}dispose(){super.dispose(),this._connectionObservers.forEach((e=>e.remove())),this._connectionObservers.length=0}}class iv extends tv{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};\n`,this}}var rv;(0,X.Y5)("BABYLON.MultiplyBlock",iv),function(e){e[e.Material=0]="Material",e[e.PostProcess=1]="PostProcess",e[e.Particle=2]="Particle",e[e.ProceduralTexture=3]="ProceduralTexture",e[e.GaussianSplatting=4]="GaussianSplatting"}(rv||(rv={}));class sv extends xn{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 nv{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:W.Pq.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:W.Pq.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:W.Pq.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:W.Pq.Zero()}set maxEmitBox(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())}get isBillboardBased(){return this._isBillboardBased}set isBillboardBased(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)}_reset(){}_removeGradientAndTexture(e,t,i){if(!t)return this;let r=0;for(const i of t){if(i.gradient===e){t.splice(r,1);break}r++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=W.Pq.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 W.Pq(10,10,10),this.onAnimationEnd=null,this.blendMode=nv.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 W.I9(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new W.Pq(0,0,0),this._useLogarithmicDepth=!1,this.gravity=W.Pq.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 H.ov(1,1,1,1),this.color2=new H.ov(1,1,1,1),this.colorDead=new H.ov(0,0,0,1),this.textureMask=new H.ov(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new sv,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 W.Pq(0,1,0),i=new W.Pq(0,1,0)){throw new Error("Method not implemented.")}createCylinderEmitter(e=1,t=1,i=1,r=0){throw new Error("Method not implemented.")}createDirectedCylinderEmitter(e=1,t=1,i=1,r=new W.Pq(0,1,0),s=new W.Pq(0,1,0)){throw new Error("Method not implemented.")}createConeEmitter(e=1,t=Math.PI/4){throw new Error("Method not implemented.")}createDirectedConeEmitter(e=1,t=Math.PI/4,i=new W.Pq(0,1,0),r=new W.Pq(0,1,0)){throw new Error("Method not implemented.")}createBoxEmitter(e,t,i,r){throw new Error("Method not implemented.")}}nv.BLENDMODE_ONEONE=0,nv.BLENDMODE_STANDARD=1,nv.BLENDMODE_ADD=2,nv.BLENDMODE_MULTIPLY=3,nv.BLENDMODE_MULTIPLYADD=4,(0,X.Y5)("BABYLON.BaseParticleSystem",nv);class ov extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("rgba",Og.Color4,!0),this.registerInput("rgb ",Og.Color3,!0),this.registerOutput("rgb",Og.Color3),this.registerOutput("r",Og.Float),this.registerOutput("g",Og.Float),this.registerOutput("b",Og.Float),this.registerOutput("a",Og.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"rgb "===e?"rgbIn":e}_outputRename(e){return"rgb"===e?"rgbOut":e}_buildBlock(e){super._buildBlock(e);const t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;const i=this._outputs[0],r=this._outputs[1],s=this._outputs[2],n=this._outputs[3],o=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=e._declareOutput(i)+` = ${t.associatedVariableName}.rgb;\n`),r.hasEndpoints&&(e.compilationString+=e._declareOutput(r)+` = ${t.associatedVariableName}.r;\n`),s.hasEndpoints&&(e.compilationString+=e._declareOutput(s)+` = ${t.associatedVariableName}.g;\n`),n.hasEndpoints&&(e.compilationString+=e._declareOutput(n)+` = ${t.associatedVariableName}.b;\n`),o.hasEndpoints&&(e.compilationString+=e._declareOutput(o)+` = ${t.associatedVariableName}.a;\n`),this}}(0,X.Y5)("BABYLON.ColorSplitterBlock",ov);var av,lv=i(72649);class hv{constructor(e){this.name=Ut.v.NAME_PROCEDURALTEXTURE,this.scene=e}register(){this.scene._beforeClearStage.registerStep(Ut.v.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){Ue.S0.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}}class cv extends vi.g{get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,r,s=null,n=!0,o=!1,a=0){super(null,r,!n),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new z.cP,this.onBeforeGenerationObservable=new z.cP,this.nodeMaterialSource=null,this.defines="",this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=new Array,this._samplers=new Array,this._floats={},this._ints={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._vectors4={},this._matrices={},this._fallbackTextureUsed=!1,this._cachedDefines=null,this._contentUpdateId=-1,this._rtWrapper=null,null===s||s instanceof vi.g?(this._options={},this._fallbackTexture=s):(this._options=s,this._fallbackTexture=s.fallbackTexture??null),this._shaderLanguage=this._options.shaderLanguage??0;let l=(r=this.getScene()||he.q.LastCreatedScene)._getComponent(Ut.v.NAME_PROCEDURALTEXTURE);l||(l=new hv(r),r._addComponent(l)),r.proceduralTextures.push(this),this._fullEngine=r.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=a,this._generateMipMaps=n,this._drawWrapper=new gt.E(this._fullEngine),this.setFragment(i);const h=this._createRtWrapper(o,t,n,a);this._texture=h.texture;const c=[];c.push(1,1),c.push(-1,1),c.push(-1,-1),c.push(1,-1),this._vertexBuffers[st.R.PositionKind]=new st.R(this._fullEngine,c,st.R.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,r){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r,...this._options}),this.setFloat("face",0)):(this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r,...this._options}),this._rtWrapper.is3D&&(this.setFloat("layer",0),this.setInt("layerNum",0))),this._rtWrapper}getEffect(){return this._drawWrapper.effect}_setEffect(e){this._drawWrapper.effect=e}getContent(){return this._contentData&&this._frameId===this._contentUpdateId||(this._contentData?this._contentData.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[st.R.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===ln.$.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=ln.$.REFRESHRATE_RENDER_ONCE)}reset(){this._drawWrapper.effect?.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null}_getDefines(){return this.defines}executeWhenReady(e){if(this.isReady())return void e(this);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 r={vertex:"procedural",fragmentElement:this._fragment.fragmentElement,fragmentSource:this._fragment.fragmentSource,fragment:"string"==typeof this._fragment?this._fragment:void 0};return this._cachedDefines!==t&&(this._cachedDefines=t,this._drawWrapper.effect=e.createEffect(r,[st.R.PositionKind],this._uniforms,this._samplers,t,void 0,void 0,(()=>{this._rtWrapper?.dispose(),this._rtWrapper=this._texture=null,this._fallbackTexture&&(this._texture=this._fallbackTexture._texture,this._texture&&this._texture.incrementReferences()),this._fallbackTextureUsed=!0}),void 0,this._shaderLanguage,(async()=>{this._options.extraInitializationsAsync?1===this.shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,67402)),this._options.extraInitializationsAsync()]):await Promise.all([Promise.resolve().then(i.bind(i,92911)),this._options.extraInitializationsAsync()]):1===this.shaderLanguage?await Promise.resolve().then(i.bind(i,67402)):await Promise.resolve().then(i.bind(i,92911))}))),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._fallbackTextureUsed&&(-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)):(this._texture&&(this._texture.isReady=!1),!1)}getRenderSize(){return this._size}resize(e,t){if(this._fallbackTextureUsed||!this._rtWrapper||!this._texture)return;const i=this._texture.isCube;this._rtWrapper.dispose();const r=this._createRtWrapper(i,e,t,this._textureType);this._texture=r.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)}setTexture(e,t){return-1===this._samplers.indexOf(e)&&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){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 e in this._textures)this._drawWrapper.effect.setTexture(e,this._textures[e]);for(const e in this._ints)this._drawWrapper.effect.setInt(e,this._ints[e]);for(const e in this._floats)this._drawWrapper.effect.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)this._drawWrapper.effect.setArray(e,this._floatsArrays[e]);for(const e in this._colors3)this._drawWrapper.effect.setColor3(e,this._colors3[e]);for(const e in this._colors4){const t=this._colors4[e];this._drawWrapper.effect.setFloat4(e,t.r,t.g,t.b,t.a)}for(const e in this._vectors2)this._drawWrapper.effect.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)this._drawWrapper.effect.setVector3(e,this._vectors3[e]);for(const e in this._vectors4)this._drawWrapper.effect.setVector4(e,this._vectors4[e]);for(const e in this._matrices)this._drawWrapper.effect.setMatrix(e,this._matrices[e])}if(!this._texture||!this._rtWrapper)return;i._debugPushGroup?.(`procedural texture generation for ${this.name}`,1);const r=i.currentViewport;if(this.isCube)for(let e=0;e<6;e++)i.bindFramebuffer(this._rtWrapper,e,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",e),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(Vt.TriangleFillMode,0,6),i.unBindFramebuffer(this._rtWrapper,!0);else{let e=1;this._rtWrapper.is3D?e=this._rtWrapper.depth:this._rtWrapper.is2DArray&&(e=this._rtWrapper.layers);for(let r=0;r=0&&e.proceduralTextures.splice(t,1);const i=this._vertexBuffers[st.R.PositionKind];i&&(i.dispose(),this._vertexBuffers[st.R.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}(0,je.Cg)([(0,$e.lK)()],cv.prototype,"isEnabled",void 0),(0,je.Cg)([(0,$e.lK)()],cv.prototype,"autoClear",void 0),(0,je.Cg)([(0,$e.lK)()],cv.prototype,"_generateMipMaps",void 0),(0,je.Cg)([(0,$e.lK)()],cv.prototype,"_size",void 0),(0,je.Cg)([(0,$e.lK)()],cv.prototype,"refreshRate",null),(0,X.Y5)("BABYLON.ProceduralTexture",cv),function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Exp2=4]="Exp2",e[e.Round=5]="Round",e[e.Floor=6]="Floor",e[e.Ceiling=7]="Ceiling",e[e.Sqrt=8]="Sqrt",e[e.Log=9]="Log",e[e.Tan=10]="Tan",e[e.ArcTan=11]="ArcTan",e[e.ArcCos=12]="ArcCos",e[e.ArcSin=13]="ArcSin",e[e.Fract=14]="Fract",e[e.Sign=15]="Sign",e[e.Radians=16]="Radians",e[e.Degrees=17]="Degrees",e[e.Set=18]="Set"}(av||(av={}));class uv extends Gg{constructor(e){super(e,Dg.Neutral),this.operation=av.Cos,this.registerInput("input",Og.AutoDetect),this.registerOutput("output",Og.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 av.Cos:i="cos";break;case av.Sin:i="sin";break;case av.Abs:i="abs";break;case av.Exp:i="exp";break;case av.Exp2:i="exp2";break;case av.Round:i="round";break;case av.Floor:i="floor";break;case av.Ceiling:i="ceil";break;case av.Sqrt:i="sqrt";break;case av.Log:i="log";break;case av.Tan:i="tan";break;case av.ArcTan:i="atan";break;case av.ArcCos:i="acos";break;case av.ArcSin:i="asin";break;case av.Fract:i="fract";break;case av.Sign:i="sign";break;case av.Radians:i="radians";break;case av.Degrees:i="degrees";break;case av.Set:i=""}return e.compilationString+=e._declareOutput(t)+` = ${i}(${this.input.associatedVariableName});\n`,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.${av[this.operation]};\n`}}(0,je.Cg)([t_("Operation",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"Cos",value:av.Cos},{label:"Sin",value:av.Sin},{label:"Abs",value:av.Abs},{label:"Exp",value:av.Exp},{label:"Exp2",value:av.Exp2},{label:"Round",value:av.Round},{label:"Floor",value:av.Floor},{label:"Ceiling",value:av.Ceiling},{label:"Sqrt",value:av.Sqrt},{label:"Log",value:av.Log},{label:"Tan",value:av.Tan},{label:"ArcTan",value:av.ArcTan},{label:"ArcCos",value:av.ArcCos},{label:"ArcSin",value:av.ArcSin},{label:"Fract",value:av.Fract},{label:"Sign",value:av.Sign},{label:"Radians",value:av.Radians},{label:"Degrees",value:av.Degrees},{label:"Set",value:av.Set}]})],uv.prototype,"operation",void 0),(0,X.Y5)("BABYLON.TrigonometryBlock",uv);const dv={effect:null,subMesh:null};class fv extends xn{constructor(){super(),this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR_NME=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.PREPASS=!1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_WORLD_NORMAL=!1,this.PREPASS_WORLD_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_LOCAL_POSITION=!1,this.PREPASS_LOCAL_POSITION_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_SCREENSPACE_DEPTH=!1,this.PREPASS_SCREENSPACE_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){void 0===this[e]&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t}}class pv extends bn{static _BlockIsTextureBlock(e){return"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"===e.getClassName()}_getGlobalNodeMaterialEditor(){return"undefined"!=typeof NODEEDITOR?NODEEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeEditor?BABYLON:void 0}get shaderLanguage(){return this._options.shaderLanguage}set shaderLanguage(e){this._options.shaderLanguage=e}get options(){return this._options}set options(e){this._options=e}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get mode(){return this._mode}set mode(e){this._mode=e}get buildId(){return this._buildId}set buildId(e){this._buildId=e}constructor(e,t,i={}){if(super(e,t||he.q.LastCreatedScene),this._buildId=pv._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new W.uq,this._cachedWorldViewProjectionMatrix=new W.uq,this._optimizers=new Array,this._animationFrame=-1,this._buildIsInProgress=!1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new z.cP,this.onBuildErrorObservable=new z.cP,this._vertexOutputNodes=new Array,this._fragmentOutputNodes=new Array,this.attachedBlocks=[],this._mode=rv.Material,this.forceAlphaBlending=!1,i&&1===i.shaderLanguage&&!this.getScene().getEngine().isWebGPU)throw new Error("WebGPU shader language is only supported with WebGPU engine");this._options={emitComments:!1,shaderLanguage:pv.DefaultShaderLanguage,...i},this._attachImageProcessingConfiguration(null)}getClassName(){return"NodeMaterial"}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||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)return Ue.S0.Warn("More than one block was found with the name `"+e+"`"),t;t=i}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(-1!==t)return this._optimizers.splice(t,1),this}addOutputNode(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return e.target&Dg.Vertex&&this._addVertexOutputNode(e),e.target&Dg.Fragment&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return null===e.target||(e.target&Dg.Vertex&&this._removeVertexOutputNode(e),e.target&Dg.Fragment&&this._removeFragmentOutputNode(e)),this}_addVertexOutputNode(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=Dg.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){const t=this._vertexOutputNodes.indexOf(e);if(-1!==t)return this._vertexOutputNodes.splice(t,1),this}_addFragmentOutputNode(e){if(-1===this._fragmentOutputNodes.indexOf(e))return e.target=Dg.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){const t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return!this.ignoreAlpha&&(this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_processInitializeOnLink(e,t,i,r=!0){(e.target===Dg.VertexAndFragment||t.target===Dg.Fragment&&e.target===Dg.Vertex&&e._preparationId!==this._buildId)&&i.push(e),this._initializeBlock(e,t,i,r)}_attachBlock(e){if(-1===this.attachedBlocks.indexOf(e)){if(e.isUnique){const t=e.getClassName();for(const e of this.attachedBlocks)if(e.getClassName()===t)throw`Cannot have multiple blocks of type ${t} in the same NodeMaterial`}this.attachedBlocks.push(e)}}_initializeBlock(e,t,i,r=!0){e.initialize(t),r&&e.autoConfigure(this),e._preparationId=this._buildId,this._attachBlock(e);for(const s of e.inputs){s.associatedVariableName="";const n=s.connectedPoint;if(n&&!n._preventBubbleUp){const s=n.ownerBlock;s!==e&&this._processInitializeOnLink(s,t,i,r)}}if(e.isLoop){const s=e;if(s.loopID.hasEndpoints)for(const e of s.loopID.endpoints){const s=e.ownerBlock;0===s.outputs.length&&(t._terminalBlocks.add(s),this._processInitializeOnLink(s,t,i,r))}}else if(e.isTeleportOut){const s=e;s.entryPoint&&this._processInitializeOnLink(s.entryPoint,t,i,r)}for(const t of e.outputs)t.associatedVariableName=""}_resetDualBlocks(e,t){e.target===Dg.VertexAndFragment&&(e.buildId=t);for(const i of e.inputs){const r=i.connectedPoint;if(r&&!r._preventBubbleUp){const i=r.ownerBlock;i!==e&&this._resetDualBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._resetDualBlocks(i.entryPoint,t)}else if(e.isLoop){const i=e;if(i.loopID.hasEndpoints)for(const e of i.loopID.endpoints){const i=e.ownerBlock;0===i.outputs.length&&this._resetDualBlocks(i,t)}}}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!1){if(this._buildIsInProgress)return void Z.V.Warn("Build is already in progress, You can use NodeMaterial.onBuildObservable to determine when the build is completed.");this._buildIsInProgress=!0,this._vertexCompilationState||i||(i=!0),this._buildWasSuccessful=!1;const r=this.getScene().getEngine(),s=this._mode===rv.Particle;if(0===this._vertexOutputNodes.length&&!s)throw"You must define at least one vertexOutputNode";if(0===this._fragmentOutputNodes.length)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new Vg,this._vertexCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._vertexCompilationState.target=Dg.Vertex,this._fragmentCompilationState=new Vg,this._fragmentCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._fragmentCompilationState.target=Dg.Fragment,this._sharedData=new kg,this._sharedData.nodeMaterial=this,this._sharedData.fragmentOutputNodes=this._fragmentOutputNodes,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene(),this._sharedData.allowEmptyVertexProgram=s;const n=[],o=[];for(const e of this._vertexOutputNodes)n.push(e),this._initializeBlock(e,this._vertexCompilationState,o,i);for(const e of this._fragmentOutputNodes)o.push(e),this._initializeBlock(e,this._fragmentCompilationState,n,i);let a=0;for(const i of this.attachedBlocks)i.codeIsReady||(a++,i.onCodeIsReadyObservable.addOnce((()=>{a--,0===a&&this._finishBuildProcess(e,t,n,o)})));0===a&&this._finishBuildProcess(e,t,n,o)}_finishBuildProcess(e=!1,t=!0,i,r){this.optimize();for(const e of i)e.build(this._vertexCompilationState,i);this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState;for(const e of r)this._resetDualBlocks(e,this._buildId-1);for(const e of r)e.build(this._fragmentCompilationState,r);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=pv._BuildIdGenerator++);const s=this._sharedData.emitErrors(this.onBuildErrorObservable);e&&(Z.V.Log("Vertex shader:"),Z.V.Log(this._vertexCompilationState.compilationString),Z.V.Log("Fragment shader:"),Z.V.Log(this._fragmentCompilationState.compilationString)),this._buildIsInProgress=!1,this._buildWasSuccessful=!0,s&&this.onBuildObservable.notifyObservers(this);const n=this.getScene().meshes;for(const e of n)if(e.subMeshes)for(const t of e.subMeshes){if(t.getMaterial()!==this)continue;if(!t.materialDefines)continue;const e=t.materialDefines;e.markAllAsDirty(),e.reset()}this.prePassTextureInputs.length&&this.getScene().enablePrePassRenderer();const o=this.getScene().prePassRenderer;o&&o.markAsDirty()}optimize(){for(const e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){const i=t.NORMAL,r=t.TANGENT,s=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(st.R.NormalKind),t.TANGENT=e.isVerticesDataPresent(st.R.TangentKind);const n=e.useVertexColors&&e.isVerticesDataPresent(st.R.ColorKind);t.VERTEXCOLOR_NME=n;let o=!1;for(let i=1;i<=6;++i){const r=t["UV"+i];t["UV"+i]=e.isVerticesDataPresent(`uv${1===i?"":i}`),o=o||t["UV"+i]!==r}const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;(0,Bt.N4)(this.getScene(),t,!a),(i!==t.NORMAL||r!==t.TANGENT||s!==t.VERTEXCOLOR_NME||o)&&t.markAsAttributesDirty()}get isPrePassCapable(){return!0}get prePassTextureOutputs(){const e=this.getBlockByPredicate((e=>"PrePassOutputBlock"===e.getClassName())),t=[4];return e?(this.prePassTextureInputs.length||(e.viewDepth.isConnected&&t.push(5),e.screenDepth.isConnected&&t.push(10),e.viewNormal.isConnected&&t.push(6),e.worldNormal.isConnected&&t.push(8),e.worldPosition.isConnected&&t.push(1)),t):t}get prePassTextureInputs(){const e=this.getAllTextureBlocks().filter((e=>"PrePassTextureBlock"===e.getClassName())),t=[];for(const i of e)i.position.isConnected&&!t.includes(1)&&t.push(1),i.localPosition.isConnected&&!t.includes(9)&&t.push(9),i.depth.isConnected&&!t.includes(5)&&t.push(5),i.screenDepth.isConnected&&!t.includes(10)&&t.push(10),i.normal.isConnected&&!t.includes(6)&&t.push(6),i.worldNormal.isConnected&&!t.includes(8)&&t.push(8);return t}setPrePassRenderer(e){const t=this.prePassTextureInputs.concat(this.prePassTextureOutputs);if(e&&t.length>1){let i=e.getEffectConfiguration("nodeMaterial");i||(i=e.addEffectConfiguration({enabled:!0,needsImageProcessing:!1,name:"nodeMaterial",texturesRequired:[]}));for(const e of t)i.texturesRequired.includes(e)||i.texturesRequired.push(e);i.enabled=!0}return t.length>1}createPostProcess(e,t=1,i=1,r,s,n=0,o=5){return this.mode!==rv.PostProcess?(Z.V.Log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,r,s,n,o)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,r=1,s,n,o=0,a=5){let l=this.name+this._buildId;const h=new fv,c=new Yt(l+"PostProcess",this.getScene());let u=this._buildId;return this._processDefines(c,h),Cl.M.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString,this.shaderLanguage),e?e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l):e=new ms.w(this.name+"PostProcess",l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,r,s,n,h.toString(),o,l,{maxSimultaneousLights:this.maxSimultaneousLights},!1,a,this.shaderLanguage),e.nodeMaterialSource=this,e.onApplyObservable.add((t=>{u!==this._buildId&&(delete Cl.M.ShadersStore[l+"VertexShader"],delete Cl.M.ShadersStore[l+"PixelShader"],l=this.name+this._buildId,h.markAllAsDirty(),u=this._buildId),this._processDefines(c,h)&&(Cl.M.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),lv._.SetImmediate((()=>e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l)))),this._checkInternals(t)})),e}createProceduralTexture(e,t){if(this.mode!==rv.ProceduralTexture)return Z.V.Log("Incompatible material mode"),null;let i=this.name+this._buildId;const r=new cv(i,e,null,t),s=new Yt(i+"Procedural",this.getScene());s.reservedDataStore={hidden:!0};const n=new fv,o=this._processDefines(s,n);Cl.M.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString,this.shaderLanguage);let a=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[st.R.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),o?.fallbacks,void 0,void 0,void 0,this.shaderLanguage);r.nodeMaterialSource=this,r._setEffect(a);let l=this._buildId;const h=()=>{l!==this._buildId&&(delete Cl.M.ShadersStore[i+"VertexShader"],delete Cl.M.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,n.markAllAsDirty(),l=this._buildId);const e=this._processDefines(s,n);e&&(Cl.M.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString,this.shaderLanguage),lv._.SetImmediate((()=>{a=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[st.R.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),e?.fallbacks,void 0),r._setEffect(a)}))),this._checkInternals(a)};return r.onBeforeGenerationObservable.add((()=>{h()})),this.onBuildObservable.add((()=>{h()})),r}_createEffectForParticles(e,t,i,r,s,n,o,a=""){let l=this.name+this._buildId+"_"+t;n||(n=new fv),o||(o=this.getScene().getMeshByName(this.name+"Particle"))||((o=new Yt(this.name+"Particle",this.getScene())).reservedDataStore={hidden:!0});let h=this._buildId;const c=[];let u=a;if(!s){const a=this._processDefines(o,n);Cl.M.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,void 0,this.shaderLanguage),e.fillDefines(c,t,!1),u=c.join("\n"),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+u,a?.fallbacks,i,r,e,this.shaderLanguage),e.setCustomEffect(s,t)}s.onBindObservable.add((s=>{h!==this._buildId&&(delete Cl.M.ShadersStore[l+"PixelShader"],l=this.name+this._buildId+"_"+t,n.markAllAsDirty(),h=this._buildId),c.length=0,e.fillDefines(c,t,!1);const d=c.join("\n");d!==u&&(n.markAllAsDirty(),u=d);const f=this._processDefines(o,n);if(f)return Cl.M.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,void 0,this.shaderLanguage),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+u,f?.fallbacks,i,r,e),e.setCustomEffect(s,t),void this._createEffectForParticles(e,t,i,r,s,n,o,a);this._checkInternals(s)}))}_checkInternals(e){if(this._sharedData.animatedInputs){const e=this.getScene(),t=e.getFrameId();if(this._animationFrame!==t){for(const t of this._sharedData.animatedInputs)t.animate(e);this._animationFrame=t}}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){this.mode===rv.Particle?(this._createEffectForParticles(e,nv.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,nv.BLENDMODE_MULTIPLY,t,i)):Z.V.Log("Incompatible material mode")}createAsShadowDepthWrapper(e){this.mode===rv.Material?e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene()):Z.V.Log("Incompatible material mode")}_processDefines(e,t,i=!1,r){let s=null;const n=this.getScene();if((0,Bt.Y7)(n,t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach((r=>{r.initializeDefines(e,this,t,i)})),this._sharedData.blocksWithDefines.forEach((s=>{s.prepareDefines(e,this,t,i,r)})),t.isDirty){const i=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach((i=>{i.replaceRepeatableContent(this._vertexCompilationState,this._fragmentCompilationState,e,t)}));const r=[];this._sharedData.dynamicUniformBlocks.forEach((e=>{e.updateUniformsAndSamples(this._vertexCompilationState,this,t,r)}));const n=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach((e=>{-1===n.indexOf(e)&&n.push(e)}));const o=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach((e=>{-1===o.indexOf(e)&&o.push(e)}));const a=new Tn;this._sharedData.blocksWithFallbacks.forEach((t=>{t.provideFallbacks(e,a)})),s={lightDisposed:i,uniformBuffers:r,mergedUniforms:n,mergedSamplers:o,fallbacks:a}}return s}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;const r=this.getScene();if(this._sharedData.animatedInputs){const e=r.getFrameId();if(this._animationFrame!==e){for(const e of this._sharedData.animatedInputs)e.animate(r);this._animationFrame=e}}const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new fv);const n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();if(this._prepareDefinesForAttributes(e,n),this._sharedData.blockingBlocks.some((t=>!t.isReady(e,this,n,i))))return!1;const a=this._processDefines(e,n,i,t);if(a){const e=t.effect,i=n.toString();let s=o.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:a.mergedUniforms,uniformBuffersNames:a.uniformBuffers,samplers:a.mergedSamplers,defines:i,fallbacks:a.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:n.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS},shaderLanguage:this.shaderLanguage},o);if(s)if(this._onEffectCreatedObservable&&(dv.effect=s,dv.subMesh=t,this._onEffectCreatedObservable.notifyObservers(dv)),this.allowShaderHotSwapping&&e&&!s.isReady()){if(s=e,n.markAsUnprocessed(),a.lightDisposed)return n._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(s,n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}get compiledShaders(){return this._buildWasSuccessful||this.build(),`// Vertex shader\n${this._vertexCompilationState.compilationString}\n\n// Fragment shader\n${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 t of this._sharedData.inputBlocks)t._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.effect;if(!s)return;this._activeEffect=s,this.bindOnlyWorldMatrix(e);const n=this._mustRebind(r,s,i,t.visibility),o=this._sharedData;if(n){for(const e of o.bindableBlocks)e.bind(s,this,t,i);for(const e of o.forcedBindableBlocks)e.bind(s,this,t,i);for(const e of o.inputBlocks)e._transmit(s,r,this)}else if(!this.isFrozen)for(const e of o.forcedBindableBlocks)e.bind(s,this,t,i);this._afterBind(t,this._activeEffect,i)}getActiveTextures(){const e=super.getActiveTextures();return this._sharedData&&e.push(...this._sharedData.textureBlocks.filter((e=>e.texture)).map((e=>e.texture))),e}getTextureBlocks(){return this._sharedData?this._sharedData.textureBlocks:[]}getAllTextureBlocks(){const e=[];for(const t of this.attachedBlocks)pv._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 e of this.getTextureBlocks().filter((e=>e.texture)).map((e=>e.texture)))e.dispose();for(const e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this.onBuildErrorObservable.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(),void 0===this.BJSNODEMATERIALEDITOR){const i=e&&e.editorURL?e.editorURL:pv.EditorURL;Ue.S0.LoadBabylonScript(i,(()=>{this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this._createNodeEditor(e?.nodeEditorConfig),t()}))}else this._createNodeEditor(e?.nodeEditorConfig),t()}))}clear(){this._vertexOutputNodes.length=0,this._fragmentOutputNodes.length=0,this.attachedBlocks.length=0,this._buildIsInProgress=!1}setToDefault(){this.clear(),this.editorData=null;const e=new Kg("Position");e.setAsAttribute("position");const t=new Kg("World");t.setAsSystemValue(Lg.World);const i=new zg("WorldPos");e.connectTo(i),t.connectTo(i);const r=new Kg("ViewProjection");r.setAsSystemValue(Lg.ViewProjection);const s=new zg("WorldPos * ViewProjectionTransform");i.connectTo(s),r.connectTo(s);const n=new Wg("VertexOutput");s.connectTo(n);const o=new Kg("color");o.value=new H.ov(.8,.8,.8,1);const a=new Hg("FragmentOutput");o.connectTo(a),this.addOutputNode(n),this.addOutputNode(a),this._mode=rv.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;const e=new Kg("Position");e.setAsAttribute("position2d");const t=new Kg("Constant1");t.isConstant=!0,t.value=1;const i=new Jg("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const r=new Wg("VertexOutput");i.connectTo(r);const s=new Kg("Scale");s.visibleInInspector=!0,s.value=new W.I9(1,1);const n=new ev("uv0");e.connectTo(n);const o=new iv("UV scale");n.connectTo(o),s.connectTo(o);const a=new jg("CurrentScreen");o.connectTo(a),a.texture=new vi.g("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());const l=new Hg("FragmentOutput");a.connectTo(l,{output:"rgba"}),this.addOutputNode(r),this.addOutputNode(l),this._mode=rv.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;const e=new Kg("Position");e.setAsAttribute("position2d");const t=new Kg("Constant1");t.isConstant=!0,t.value=1;const i=new Jg("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const r=new Wg("VertexOutput");i.connectTo(r);const s=new Kg("Time");s.value=0,s.min=0,s.max=0,s.isBoolean=!1,s.matrixMode=0,s.animationType=Bg.Time,s.isConstant=!1;const n=new Kg("Color3");n.value=new H.v9(1,1,1),n.isConstant=!1;const o=new Hg("FragmentOutput"),a=new Jg("VectorMerger");a.visibleInInspector=!1;const l=new uv("Cos");l.operation=av.Cos,e.connectTo(a),s.output.connectTo(l.input),l.output.connectTo(a.z),a.xyzOut.connectTo(o.rgb),this.addOutputNode(r),this.addOutputNode(o),this._mode=rv.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;const e=new Kg("uv");e.setAsAttribute("particle_uv");const t=new $g("ParticleTexture");e.connectTo(t);const i=new Kg("Color");i.setAsAttribute("particle_color");const r=new iv("Texture * Color");t.connectTo(r),i.connectTo(r);const s=new Qg("ParticleRampGradient");r.connectTo(s);const n=new ov("ColorSplitter");i.connectTo(n);const o=new Zg("ParticleBlendMultiply");s.connectTo(o),t.connectTo(o,{output:"a"}),n.connectTo(o,{output:"a"});const a=new Hg("FragmentOutput");o.connectTo(a),this.addOutputNode(a),this._mode=rv.Particle}async loadAsync(e,t=""){return pv.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const r=i.connectedPoint;if(r){const i=r.ownerBlock;i!==e&&this._gatherBlocks(i,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 e of this._vertexOutputNodes)this._gatherBlocks(e,t);const r=[];for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,r);let s=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}");\n`;s+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${rv[this.mode]};\n`;for(const r of t)r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e));for(const t of r)t.isInput&&-1===e.indexOf(t)&&(s+=t._dumpCode(i,e));e=[],s+="\n// Connections\n";for(const t of this._vertexOutputNodes)s+=t._dumpCodeForOutputConnections(e);for(const t of this._fragmentOutputNodes)s+=t._dumpCodeForOutputConnections(e);s+="\n// Output nodes\n";for(const e of this._vertexOutputNodes)s+=`nodeMaterial.addOutputNode(${e._codeVariableName});\n`;for(const e of this._fragmentOutputNodes)s+=`nodeMaterial.addOutputNode(${e._codeVariableName});\n`;return s+="nodeMaterial.build();\n",s}serialize(e){const t=e?{}:it.p.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 e of this._vertexOutputNodes)this._gatherBlocks(e,i),t.outputNodes.push(e.uniqueId);for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,i),-1===t.outputNodes.indexOf(e.uniqueId)&&t.outputNodes.push(e.uniqueId)}t.blocks=[];for(const e of i)t.blocks.push(e.serialize());if(!e)for(const e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t.uniqueId=this.uniqueId,t}_restoreConnections(e,t,i){for(const r of e.outputs)for(const s of t.blocks){const n=i[s.id];if(n)for(const o of s.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==r.name);else{const e=n.getInputByName(o.inputName);if(!e||e.isConnected)continue;r.connectTo(e,!0),this._restoreConnections(n,t,i)}}}parseSerializedObject(e,t="",i=!1,r){i||this.clear();const s={};for(const i of e.blocks){const e=(0,X.n9)(i.customType);if(e){const n=new e;n._deserialize(i,this.getScene(),t,r),s[i.id]=n,this.attachedBlocks.push(n)}}for(const e of this.attachedBlocks)if(e.isTeleportOut){const t=e,i=t._tempEntryPointUniqueId;i&&s[i].attachToEndpoint(t)}for(let t=0;tnew pv(e,this.getScene(),this.options)),this);return r.id=e,r.name=e,r.parseSerializedObject(i),r._buildId=this._buildId,r.build(!1,!t),r}whenTexturesReadyAsync(){const e=[];return this.getActiveTextures().forEach((t=>{const i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise(((e,t)=>{i.onLoadedObservable.addOnce((()=>{e()})),i.onErrorObservable.addOnce((e=>{t(e)}))})))})),Promise.all(e)}static Parse(e,t,i="",r=0){const s=it.p.Parse((()=>new pv(e.name,t,{shaderLanguage:r})),e,t,i);return s.parseSerializedObject(e,i),s.build(),s}static async ParseFromFileAsync(e,t,i,r="",s=!1,n,o){const a=n??new pv(e,i),l=await i._loadFileAsync(t),h=JSON.parse(l);return a.parseSerializedObject(h,r,void 0,o),s||a.build(),a}static ParseFromSnippetAsync(e,t=he.q.LastCreatedScene,i="",r,s=!1,n=!1,o){return"_BLANK"===e?Promise.resolve(pv.CreateDefault("blank",t)):new Promise(((a,l)=>{const h=new go.u;h.addEventListener("readystatechange",(()=>{if(4==h.readyState)if(200==h.status){const c=JSON.parse(JSON.parse(h.responseText).jsonPayload),u=JSON.parse(c.nodeMaterial);r||((r=it.p.Parse((()=>new pv(e,t)),u,t,i)).uniqueId=t.getUniqueId()),r.parseSerializedObject(u,void 0,void 0,o),r.snippetId=e,r.sideOrientation=null;try{s||r.build()}catch(e){l(e)}n?r.whenTexturesReadyAsync().then((()=>{a(r)})).catch((e=>{l(e)})):a(r)}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 pv(e,t);return i.setToDefault(),i.build(),i}}var _v,mv,gv,vv;pv._BuildIdGenerator=0,pv.EditorURL=`${Ue.S0._DefaultCdnUrl}/v${Ot.$.Version}/nodeEditor/babylon.nodeEditor.js`,pv.SnippetUrl="https://snippet.babylonjs.com",pv.IgnoreTexturesAtLoadTime=!1,pv.DefaultShaderLanguage=0,(0,je.Cg)([(0,$e.lK)()],pv.prototype,"ignoreAlpha",void 0),(0,je.Cg)([(0,$e.lK)()],pv.prototype,"maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.lK)("mode")],pv.prototype,"_mode",void 0),(0,je.Cg)([(0,$e.lK)("comment")],pv.prototype,"comment",void 0),(0,je.Cg)([(0,$e.lK)()],pv.prototype,"forceAlphaBlending",void 0),(0,X.Y5)("BABYLON.NodeMaterial",pv),vt.prototype._projectOnTrianglesToRef=function(e,t,i,r,s,n){const o=W.AA.Vector3[0],a=W.AA.Vector3[1];let l=1/0;for(let n=this.indexStart;n{if(this._controllers[e.uniqueId])return;const{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:r}=this._generateNewTouchPointMesh(),s=this._generateVisualCue();switch(this._controllers[e.uniqueId]={xrController:e,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:r,currentAnimationState:_v.DEHYDRATED,grabRay:new wi(new W.Pq,new W.Pq),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,downTriggered:!1,id:xv._IdCounter++,pickedPointVisualCue:s},this._controllers[e.uniqueId]._worldScaleObserver=this._controllers[e.uniqueId]._worldScaleObserver||this._xrSessionManager.onWorldScaleFactorChangedObservable.add((t=>{if(t.newScaleFactor!==t.previousScaleFactor){this._controllers[e.uniqueId].touchCollisionMesh.dispose(),this._controllers[e.uniqueId].pickedPointVisualCue.dispose();const{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:r}=this._generateNewTouchPointMesh();this._controllers[e.uniqueId].touchCollisionMesh=t,this._controllers[e.uniqueId].touchCollisionMeshFunction=i,this._controllers[e.uniqueId].hydrateCollisionMeshFunction=r,this._controllers[e.uniqueId].pickedPointVisualCue=this._generateVisualCue()}})),this._attachedController?!this._options.enableNearInteractionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enableNearInteractionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachNearInteractionMode(e);case"gaze":case"screen":return null}},this._controllers={},this._farInteractionFeature=null,this.selectionMeshDefaultColor=new H.v9(.8,.8,.8),this.selectionMeshPickedColor=new H.v9(.3,.3,1),this._hoverRadius=.1,this._pickRadius=.02,this._controllerPickRadius=.03,this._nearGrabLengthScale=5,this._scene=this._xrSessionManager.scene,void 0===this._options.nearInteractionControllerMode&&(this._options.nearInteractionControllerMode=2),this._options.farInteractionFeature&&(this._farInteractionFeature=this._options.farInteractionFeature)}attach(){return!!super.attach()&&(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._scene.constantlyUpdateMeshUnderPointer=!0,!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}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 _v.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===_v.HOVER)break;case _v.HOVER:if(e.touchCollisionMeshFunction(!0),t===_v.TOUCH)break}else switch(e.currentAnimationState){case _v.TOUCH:if(e.touchCollisionMeshFunction(!1),t===_v.HOVER)break;case _v.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===_v.DEHYDRATED)break}e.currentAnimationState=t}}_processTouchPoint(e,t,i){const r=this._controllers[e];r.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(W.AA.Vector3[0]),r.grabRay.direction.copyFrom(W.AA.Vector3[0]),2!==this._options.nearInteractionControllerMode||r.xrController?.inputSource.hand||(r.xrController.getWorldPointerRayToRef(this._tmpRay),r.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),r.grabRay.length=this._nearGrabLengthScale*this._hoverRadius*this._xrSessionManager.worldScalingFactor,r.touchCollisionMesh.position.copyFrom(r.grabRay.origin).scaleInPlace(this._xrSessionManager.worldScalingFactor)}_onXRFrame(e){Object.keys(this._controllers).forEach((t=>{const i=this._controllers[t],r=i.xrController?.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!i.xrController||!r&&(!this._options.nearInteractionControllerMode||!i.xrController.inputSource.gamepad))return void(i.pick=null);if(i.hoverInteraction=!1,i.nearInteraction=!1,!i.xrController)return;if(r){const i=r.get("index-finger-tip");if(i){const r=e.getJointPose(i,this._xrSessionManager.referenceSpace);if(r&&r.transform){const e=this._scene.useRightHandedSystem?1:-1;W.AA.Vector3[0].set(r.transform.position.x,r.transform.position.y,r.transform.position.z*e),W.AA.Quaternion[0].set(r.transform.orientation.x,r.transform.orientation.y,r.transform.orientation.z*e,r.transform.orientation.w*e),this._processTouchPoint(t,W.AA.Vector3[0],W.AA.Quaternion[0])}}}else if(i.xrController.inputSource.gamepad&&0!==this._options.nearInteractionControllerMode){let e=i.xrController.pointer;i.xrController.grip&&1===this._options.nearInteractionControllerMode&&(e=i.xrController.grip),this._processTouchPoint(t,e.position,e.rotationQuaternion)}const s=(e,t)=>{let i=null;return i=t&&t.hit?e&&e.hit?t.distance{let t=new At.G,i=!1;const r=e&&e.pickedPoint&&e.hit;return e?.pickedPoint&&(i=0===e.pickedPoint.x&&0===e.pickedPoint.y&&0===e.pickedPoint.z),r&&!i&&(t=e),t};if(!i.grabInteraction){let e=null,t=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._utilityLayerScene,(e=>this._nearInteractionPredicate(e))));const o=s(this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._scene,(e=>this._nearInteractionPredicate(e))),t);if(o&&o.hit&&(e=n(o),e.hit&&(i.hoverInteraction=!0)),i.hoverInteraction){let t=null;const o=(r?this._pickRadius:this._controllerPickRadius)*this._xrSessionManager.worldScalingFactor;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(i,o,this._utilityLayerScene,(e=>this._nearPickPredicate(e))));const a=n(s(this._pickWithSphere(i,o,this._scene,(e=>this._nearPickPredicate(e))),t));a.hit&&(e=a,i.nearInteraction=!0)}i.stalePick=i.pick,i.pick=e,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=_v.DEHYDRATED;i.grabInteraction||i.nearInteraction?o=_v.TOUCH:i.hoverInteraction&&(o=_v.HOVER),this._handleTransitionAnimation(i,o)}))}get _utilityLayerScene(){return this._options.customUtilityLayerScene||Bo.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Bo.DefaultUtilityLayer.utilityLayerScene:this._scene,t=Qo("nearInteraction",{diameter:.0105*this._xrSessionManager.worldScalingFactor},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=W.PT.Identity();const i=new Un("targetMat",e);return i.specularColor=H.v9.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return!this._farInteractionFeature||this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e)}_attachNearInteractionMode(e){const t=this._controllers[e.uniqueId],i={pointerId:t.id,pointerType:"xr-near"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{(this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController)&&t.xrController&&(t.xrController.inputSource.hand||this._options.nearInteractionControllerMode&&t.xrController.inputSource.gamepad)&&(t.pick&&(t.pick.ray=t.grabRay),t.pick&&this._isControllerReadyForNearInteraction(t.id)&&this._scene.simulatePointerMove(t.pick,i),t.nearInteraction&&t.pick&&t.pick.hit?t.nearInteractionTargetMesh||(this._scene.simulatePointerDown(t.pick,i),t.nearInteractionTargetMesh=t.meshUnderPointer,t.downTriggered=!0):t.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.downTriggered=!1,t.nearInteractionTargetMesh=null))}));const r=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 i=e=>{t.squeezeComponent=e.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;r(t)}})):(t.selectionComponent=e.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;r(t)}})))};e.motionController?i(e.motionController):e.onMotionControllerInitObservable.add(i)}else{const e=e=>{t.xrController&&e.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)},r=e=>{t.xrController&&e.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:r,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",r)}}_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((e=>{const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame((()=>{if(!t.downTriggered)return;const e={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new At.G,e)})),t._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(t._worldScaleObserver),delete this._controllers[e],this._attachedController===e)){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}_generateNewTouchPointMesh(){const e=this._xrSessionManager.worldScalingFactor,t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Bo.DefaultUtilityLayer.utilityLayerScene:this._scene,i=Qo("PickSphere",{diameter:1*e},t);if(i.isVisible=!1,this._options.motionControllerOrbMaterial)i.material=this._options.motionControllerOrbMaterial;else{let e;e=this._options.motionControllerTouchMaterialSnippetUrl?pv.ParseFromFileAsync("motionControllerTouchMaterial",this._options.motionControllerTouchMaterialSnippetUrl,t):pv.ParseFromSnippetAsync("8RUNKL#3",t),e.then((e=>{i.material=e})).catch((e=>{Z.V.Warn(`Error creating touch material in WebXRNearInteraction: ${e}`)}))}const r=new Ae;r.setEasingMode(xe.EASINGMODE_EASEINOUT);const s=new W.Pq(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius).scaleInPlace(e),n=this._controllerPickRadius*(4/3),o=new W.Pq(n,n,n).scaleInPlace(e),a=this._controllerPickRadius*(7/6),l=new W.Pq(a,a,a).scaleInPlace(e),h=.8*this._controllerPickRadius,c=new W.Pq(h,h,h).scaleInPlace(e),u=1.5*this._controllerPickRadius,d=[{frame:0,value:s},{frame:10,value:new W.Pq(u,u,u).scaleInPlace(e)},{frame:18,value:o}],f=[{frame:0,value:o},{frame:10,value:c},{frame:18,value:s}],p=[{frame:0,value:W.Pq.ZeroReadOnly},{frame:12,value:l},{frame:15,value:s}],_=[{frame:0,value:s},{frame:10,value:W.Pq.ZeroReadOnly},{frame:15,value:W.Pq.ZeroReadOnly}],m=new pe.X5("touch","scaling",60,pe.X5.ANIMATIONTYPE_VECTOR3,pe.X5.ANIMATIONLOOPMODE_CONSTANT),g=new pe.X5("release","scaling",60,pe.X5.ANIMATIONTYPE_VECTOR3,pe.X5.ANIMATIONLOOPMODE_CONSTANT),v=new pe.X5("hydrate","scaling",60,pe.X5.ANIMATIONTYPE_VECTOR3,pe.X5.ANIMATIONLOOPMODE_CONSTANT),x=new pe.X5("dehydrate","scaling",60,pe.X5.ANIMATIONTYPE_VECTOR3,pe.X5.ANIMATIONLOOPMODE_CONSTANT);return m.setEasingFunction(r),g.setEasingFunction(r),v.setEasingFunction(r),x.setEasingFunction(r),m.setKeys(d),g.setKeys(f),v.setKeys(p),x.setKeys(_),{touchCollisionMesh:i,touchCollisionMeshFunction:e=>{const r=e?m:g;t.beginDirectAnimation(i,[r],0,18,!1,1)},hydrateCollisionMeshFunction:e=>{const r=e?v:x;e&&(i.isVisible=!0),t.beginDirectAnimation(i,[r],0,15,!1,1,(()=>{e||(i.isVisible=!1)}))}}}_pickWithSphere(e,t,i,r){const s=new At.G;if(s.distance=1/0,e.touchCollisionMesh&&e.xrController){const n=e.touchCollisionMesh.position,o=ct.CreateFromCenterAndRadius(n,t);for(let t=0;tc&&(h=0,a.copyFrom(t.center)),-1!==h&&h()=>new xv(e,t)),xv.Version,!0);class bv{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class Sv{}class Tv{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new z.cP,this._onSessionGranted=e=>{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),"undefined"!=typeof window&&window.location&&"http:"===window.location.protocol&&"localhost"!==window.location.hostname)throw Ue.S0.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 e=t.sessionMode||"immersive-vr",i=t.referenceSpaceType||"local-floor";let r=".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("+("undefined"==typeof SVGSVGElement?"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) }";r+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';const s=document.createElement("style");s.appendChild(document.createTextNode(r)),document.getElementsByTagName("head")[0].appendChild(s);const n=document.createElement("button");n.className="babylonVRicon",n.title=`${e} - ${i}`,this._buttons.push(new bv(n,e,i)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",n.className="babylonVRicon"+(e===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((t=>e.sessionManager.isSessionSupportedAsync(t.sessionMode)));e.onStateChangedObservable.add((e=>{3==e&&this._updateButtons(null)})),(await Promise.all(i)).forEach(((e,t)=>{e?(this.overlay.appendChild(this._buttons[t].element),this._buttons[t].element.onclick=this._enterXRWithButtonIndex.bind(this,t)):Ue.S0.Warn(`Session mode "${this._buttons[t].sessionMode}" not supported in browser`)}))}static async CreateAsync(e,t,i){const r=new Tv(e,i);return await r.setHelperAsync(t,i.renderTarget||void 0),r}async _enterXRWithButtonIndex(e=0){if(2==this._helper.state)await this._helper.exitXRAsync(),this._updateButtons(null);else if(3==this._helper.state)try{await this._helper.enterXRAsync(this._buttons[e].sessionMode,this._buttons[e].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures}),this._updateButtons(this._buttons[e])}catch(t){this._updateButtons(null);const i=this._buttons[e].element,r=i.title;i.title="Error entering XR session : "+r,i.classList.add("xr-error"),this.options.onError&&this.options.onError(t)}}dispose(){const e=this._scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this.overlay)&&e.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)}_updateButtons(e){this._activeButton=e,this._buttons.forEach((e=>{e.update(this._activeButton)})),this.activeButtonChangedObservable.notifyObservers(this._activeButton)}}!function(e){e.WRIST="wrist",e.THUMB="thumb",e.INDEX="index",e.MIDDLE="middle",e.RING="ring",e.LITTLE="little"}(gv||(gv={})),function(e){e.WRIST="wrist",e.THUMB_METACARPAL="thumb-metacarpal",e.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",e.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",e.THUMB_TIP="thumb-tip",e.INDEX_FINGER_METACARPAL="index-finger-metacarpal",e.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",e.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",e.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",e.INDEX_FINGER_TIP="index-finger-tip",e.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",e.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",e.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",e.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",e.MIDDLE_FINGER_TIP="middle-finger-tip",e.RING_FINGER_METACARPAL="ring-finger-metacarpal",e.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",e.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",e.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",e.RING_FINGER_TIP="ring-finger-tip",e.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",e.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",e.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",e.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",e.PINKY_FINGER_TIP="pinky-finger-tip"}(vv||(vv={}));const Cv=["wrist","thumb-metacarpal","thumb-phalanx-proximal","thumb-phalanx-distal","thumb-tip","index-finger-metacarpal","index-finger-phalanx-proximal","index-finger-phalanx-intermediate","index-finger-phalanx-distal","index-finger-tip","middle-finger-metacarpal","middle-finger-phalanx-proximal","middle-finger-phalanx-intermediate","middle-finger-phalanx-distal","middle-finger-tip","ring-finger-metacarpal","ring-finger-phalanx-proximal","ring-finger-phalanx-intermediate","ring-finger-phalanx-distal","ring-finger-tip","pinky-finger-metacarpal","pinky-finger-phalanx-proximal","pinky-finger-phalanx-intermediate","pinky-finger-phalanx-distal","pinky-finger-tip"],yv={wrist:["wrist"],thumb:["thumb-metacarpal","thumb-phalanx-proximal","thumb-phalanx-distal","thumb-tip"],index:["index-finger-metacarpal","index-finger-phalanx-proximal","index-finger-phalanx-intermediate","index-finger-phalanx-distal","index-finger-tip"],middle:["middle-finger-metacarpal","middle-finger-phalanx-proximal","middle-finger-phalanx-intermediate","middle-finger-phalanx-distal","middle-finger-tip"],ring:["ring-finger-metacarpal","ring-finger-phalanx-proximal","ring-finger-phalanx-intermediate","ring-finger-phalanx-distal","ring-finger-tip"],little:["pinky-finger-metacarpal","pinky-finger-phalanx-proximal","pinky-finger-phalanx-intermediate","pinky-finger-phalanx-distal","pinky-finger-tip"]};class Ev{get handMesh(){return this._handMesh}getHandPartMeshes(e){return yv[e].map((e=>this._jointMeshes[Cv.indexOf(e)]))}getJointMesh(e){return this._jointMeshes[Cv.indexOf(e)]}constructor(e,t,i,r,s=!1,n=!1,o=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=r,this._leftHandedMeshes=s,this._jointsInvisible=n,this._jointScaleFactor=o,this.onHandMeshSetObservable=new z.cP,this._jointTransforms=new Array(Cv.length),this._jointTransformMatrices=new Float32Array(16*Cv.length),this._tempJointMatrix=new W.uq,this._jointRadii=new Float32Array(Cv.length),this._scene=t[0].getScene();for(let e=0;e{e._doNotLoadControllerMesh=!0}))}setHandMesh(e,t,i){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach((e=>{e.alwaysSelectAsActiveMesh=!0})),this._handMesh.skeleton){const e=this._handMesh.skeleton;Cv.forEach(((i,r)=>{const s=e.getBoneIndexByName(t?t[i]:i);-1!==s&&e.bones[s].linkTransformNode(this._jointTransforms[r])}))}this.onHandMeshSetObservable.notifyObservers(this)}updateFromXRFrame(e,t){const i=this.xrController.inputSource.hand;if(!i)return;const r=i,s=Cv.map((e=>r[e]||i.get(e)));let n=!1;if(e.fillPoses&&e.fillJointRadii)n=e.fillPoses(s,t,this._jointTransformMatrices)&&e.fillJointRadii(s,this._jointRadii);else if(e.getJointPose){n=!0;for(let i=0;i{const i=this._jointTransforms[t];W.uq.FromArrayToRef(this._jointTransformMatrices,16*t,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,i.rotationQuaternion,i.position);const r=this._jointRadii[t]*this._jointScaleFactor,s=this._jointMeshes[t];s.isVisible=!this._handMesh&&!this._jointsInvisible,s.position.copyFrom(i.position),s.rotationQuaternion.copyFrom(i.rotationQuaternion),s.scaling.setAll(r),this._scene.useRightHandedSystem||(s.position.z*=-1,s.rotationQuaternion.z*=-1,s.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(i.position.z*=-1,i.rotationQuaternion.z*=-1,i.rotationQuaternion.w*=-1))})),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(e=!1){this._handMesh&&(e?(this._handMesh.skeleton?.dispose(),this._handMesh.dispose(!1,!0)):this._handMesh.isVisible=!1),this._jointTransforms.forEach((e=>e.dispose())),this._jointTransforms.length=0,this.onHandMeshSetObservable.clear()}}class Pv extends Ig{static _GenerateTrackedJointMeshes(e,t=Qa("jointParent",Pv._ICOSPHERE_PARAMS)){const i={};return["left","right"].map((r=>{const s=[];t.isVisible=!!e.jointMeshes?.keepOriginalVisible;for(let i=0;i{const s={};Pv._RightHandGLB?.meshes[1]?.isDisposed()&&(Pv._RightHandGLB=null),Pv._LeftHandGLB?.meshes[1]?.isDisposed()&&(Pv._LeftHandGLB=null);const n=!(!Pv._RightHandGLB||!Pv._LeftHandGLB),o=await Promise.all([Pv._RightHandGLB||xg.ImportMeshAsync("",Pv.DEFAULT_HAND_MODEL_BASE_URL,Pv.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),Pv._LeftHandGLB||xg.ImportMeshAsync("",Pv.DEFAULT_HAND_MODEL_BASE_URL,Pv.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);Pv._RightHandGLB=o[0],Pv._LeftHandGLB=o[1];const a=await pv.ParseFromFileAsync("handShader",Pv.DEFAULT_HAND_MODEL_SHADER_URL,e,void 0,!0);a.needDepthPrePass=!0,a.transparencyMode=Vt.MATERIAL_ALPHABLEND,a.alphaMode=2,a.build(!1);const l={base:H.v9.FromInts(116,63,203),fresnel:H.v9.FromInts(149,102,229),fingerColor:H.v9.FromInts(177,130,255),tipFresnel:H.v9.FromInts(220,200,255),...i?.handMeshes?.customColors},h={base:a.getBlockByName("baseColor"),fresnel:a.getBlockByName("fresnelColor"),fingerColor:a.getBlockByName("fingerColor"),tipFresnel:a.getBlockByName("tipFresnelColor")};h.base.value=l.base,h.fresnel.value=l.fresnel,h.fingerColor.value=l.fingerColor,h.tipFresnel.value=l.tipFresnel;const c=t._getBaseLayerWrapper()?.isMultiview;["left","right"].forEach((t=>{const r="left"==t?Pv._LeftHandGLB:Pv._RightHandGLB;if(!r)throw new Error("Could not load hand model");const o=r.meshes[1];o._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,c||i?.handMeshes?.disableHandShader||(o.material=a.clone(`${t}HandShaderClone`,!0)),o.isVisible=!1,s[t]=o,n||e.useRightHandedSystem||r.meshes[1].rotate(Mt._0.Y,Math.PI)})),a.dispose(),r({left:s.left,right:s.right})}))}static _GenerateDefaultHandMeshRigMapping(e){const t="right"==e?"R":"L";return{wrist:`wrist_${t}`,"thumb-metacarpal":`thumb_metacarpal_${t}`,"thumb-phalanx-proximal":`thumb_proxPhalanx_${t}`,"thumb-phalanx-distal":`thumb_distPhalanx_${t}`,"thumb-tip":`thumb_tip_${t}`,"index-finger-metacarpal":`index_metacarpal_${t}`,"index-finger-phalanx-proximal":`index_proxPhalanx_${t}`,"index-finger-phalanx-intermediate":`index_intPhalanx_${t}`,"index-finger-phalanx-distal":`index_distPhalanx_${t}`,"index-finger-tip":`index_tip_${t}`,"middle-finger-metacarpal":`middle_metacarpal_${t}`,"middle-finger-phalanx-proximal":`middle_proxPhalanx_${t}`,"middle-finger-phalanx-intermediate":`middle_intPhalanx_${t}`,"middle-finger-phalanx-distal":`middle_distPhalanx_${t}`,"middle-finger-tip":`middle_tip_${t}`,"ring-finger-metacarpal":`ring_metacarpal_${t}`,"ring-finger-phalanx-proximal":`ring_proxPhalanx_${t}`,"ring-finger-phalanx-intermediate":`ring_intPhalanx_${t}`,"ring-finger-phalanx-distal":`ring_distPhalanx_${t}`,"ring-finger-tip":`ring_tip_${t}`,"pinky-finger-metacarpal":`little_metacarpal_${t}`,"pinky-finger-phalanx-proximal":`little_proxPhalanx_${t}`,"pinky-finger-phalanx-intermediate":`little_intPhalanx_${t}`,"pinky-finger-phalanx-distal":`little_distPhalanx_${t}`,"pinky-finger-tip":`little_tip_${t}`}}isCompatible(){return"undefined"!=typeof XRHand}getHandByControllerId(e){return this._attachedHands[e]}getHandByHandedness(e){return"none"==e?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 z.cP,this.onHandRemovedObservable=new z.cP,this._attachHand=e=>{if(!e.inputSource.hand||"none"==e.inputSource.handedness||!this._handResources.jointMeshes)return;const t=e.inputSource.handedness,i=new Ev(e,this._handResources.jointMeshes[t],this._handResources.handMeshes&&this._handResources.handMeshes[t],this._handResources.rigMappings&&this._handResources.rigMappings[t],this.options.handMeshes?.meshesUseLeftHandedCoordinates,this.options.jointMeshes?.invisible,this.options.jointMeshes?.scaleFactor);this._attachedHands[e.uniqueId]=i,this._trackingHands[t]=i,this.onHandAddedObservable.notifyObservers(i)},this._detachHand=e=>{this._detachHandById(e.uniqueId)},this.xrNativeFeatureName="hand-tracking";const i=t.jointMeshes;if(i&&(void 0!==i.disableDefaultHandMesh&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=i.disableDefaultHandMesh),void 0!==i.handMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=i.handMeshes),void 0!==i.leftHandedSystemMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=i.leftHandedSystemMeshes),void 0!==i.rigMapping)){t.handMeshes=t.handMeshes||{};const e={},r={};[[i.rigMapping.left,e],[i.rigMapping.right,r]].forEach((e=>{const t=e[0],i=e[1];t.forEach(((e,t)=>{i[Cv[t]]=e}))})),t.handMeshes.customRigMappings={left:e,right:r}}}attach(){return!!super.attach()&&(this._handResources.jointMeshes||(this._originalMesh=this._originalMesh||this.options.jointMeshes?.sourceMesh||Qa("jointParent",Pv._ICOSPHERE_PARAMS),this._originalMesh.isVisible=!1,this._handResources.jointMeshes=Pv._GenerateTrackedJointMeshes(this.options,this._originalMesh)),this._handResources.handMeshes=this.options.handMeshes?.customMeshes||null,this._handResources.rigMappings=this.options.handMeshes?.customRigMappings||null,this.options.handMeshes?.customMeshes||this.options.handMeshes?.disableDefaultMeshes||(Pv._GenerateDefaultHandMeshesAsync(he.q.LastCreatedScene,this._xrSessionManager,this.options).then((e=>{this._handResources.handMeshes=e,this._handResources.rigMappings={left:Pv._GenerateDefaultHandMeshRigMapping("left"),right:Pv._GenerateDefaultHandMeshRigMapping("right")},this._trackingHands.left?.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left,this._xrSessionManager),this._trackingHands.right?.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((e=>{this._handResources.handMeshes&&(this._handResources.handMeshes.left.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor),this._handResources.handMeshes.right.scaling.scaleInPlace(e.newScaleFactor/e.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)}_onXRFrame(e){this._trackingHands.left?.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),this._trackingHands.right?.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e,t){const i=this.getHandByControllerId(e);if(i){const r="left"==i.xrController.inputSource.handedness?"left":"right";this._trackingHands[r]?.xrController.uniqueId===e&&(this._trackingHands[r]=null),this.onHandRemovedObservable.notifyObservers(i),i.dispose(t),delete this._attachedHands[e]}}detach(){return!!super.detach()&&(Object.keys(this._attachedHands).forEach((e=>this._detachHandById(e,this.options.handMeshes?.disposeOnSessionEnd))),this.options.handMeshes?.disposeOnSessionEnd&&(this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((e=>e.dispose())),this._handResources.jointMeshes.right.forEach((e=>e.dispose())),this._handResources.jointMeshes=null),this._handResources.handMeshes&&(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),this._handResources.handMeshes=null),Pv._RightHandGLB?.meshes.forEach((e=>e.dispose())),Pv._LeftHandGLB?.meshes.forEach((e=>e.dispose())),Pv._RightHandGLB=null,Pv._LeftHandGLB=null,this._originalMesh?.dispose(),this._originalMesh=void 0),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver),!0)}dispose(){super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),this._handResources.handMeshes&&!this.options.handMeshes?.customMeshes&&(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),Pv._RightHandGLB?.meshes.forEach((e=>e.dispose())),Pv._LeftHandGLB?.meshes.forEach((e=>e.dispose())),Pv._RightHandGLB=null,Pv._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((e=>e.dispose())),this._handResources.jointMeshes.right.forEach((e=>e.dispose())))}}Pv.Name=hr.HAND_TRACKING,Pv.Version=1,Pv.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/",Pv.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb",Pv.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb",Pv.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json",Pv._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2},Pv._RightHandGLB=null,Pv._LeftHandGLB=null,cr.AddWebXRFeature(Pv.Name,((e,t)=>()=>new Pv(e,t)),Pv.Version,!1);class Av extends Ig{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){const t=this._options.teleportationTargetMesh.getChildMeshes(!1,(e=>"rotationCone"===e.name));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 H.ov(1,1,1,1),this._tmpRay=new wi(new W.Pq,new W.Pq),this._tmpVector=new W.Pq,this._tmpQuaternion=new W.PT,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 z.cP,this.teleportationEnabled=!0,this._rotationEnabled=!0,this.onBeforeCameraTeleportRotation=new z.cP,this.onAfterCameraTeleportRotation=new z.cP,this._attachController=e=>{if(this._controllers[e.uniqueId]||this._options.forceHandedness&&e.inputSource.handedness!==this._options.forceHandedness)return;this._controllers[e.uniqueId]={xrController:e,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0,blocked:!1,initialHit:!1,mainComponentUsed:!1}};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController){const i=e.motionController.getComponentOfType(Km.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(Km.TOUCHPAD_TYPE);if(!i||this._options.useMainComponentOnly){const i=e.motionController.getMainComponent();if(!i)return;t.teleportationState.mainComponentUsed=!0,t.teleportationComponent=i,t.onButtonChangedObserver=i.onButtonStateChangedObservable.add((()=>{if(!this.teleportationEnabled)return;const r=()=>{t.teleportationState.forward=!0,t.teleportationState.initialHit=!1,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,xd({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!i.pressed,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})};i.changes.pressed&&(i.changes.pressed.current?this._options.timeToTeleportStart?xd({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{i.pressed&&r()}}):r():(t.teleportationState.forward=!1,this._currentTeleportationControllerId=""))}))}else t.teleportationComponent=i,t.onAxisChangedObserver=i.onAxisValueChangedObservable.add((i=>{if(i.y<=.7&&t.teleportationState.backwards&&(t.teleportationState.backwards=!1),i.y>.7&&!t.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!t.teleportationState.backwards){t.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,W.PT.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 e=this._xrSessionManager.scene.pickWithRay(this._tmpRay,(e=>-1!==this._floorMeshes.indexOf(e)));e&&e.pickedPoint&&(this._options.xrInput.xrCamera.position.x=e.pickedPoint.x,this._options.xrInput.xrCamera.position.z=e.pickedPoint.z)}if(i.y<-.7&&!this._currentTeleportationControllerId&&!t.teleportationState.rotating&&this.teleportationEnabled&&(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),i.x){if(t.teleportationState.forward)this._currentTeleportationControllerId===t.xrController.uniqueId&&(this.rotationEnabled?setTimeout((()=>{t.teleportationState.currentRotation=Math.atan2(i.x,i.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))})):t.teleportationState.currentRotation=0);else if(!t.teleportationState.rotating&&Math.abs(i.x)>.7){t.teleportationState.rotating=!0;const e=this.rotationAngle*(i.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this.onBeforeCameraTeleportRotation.notifyObservers(e),W.PT.FromEulerAngles(0,e,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleportRotation.notifyObservers(this._options.xrInput.xrCamera.rotationQuaternion)}}else t.teleportationState.rotating=!1;0===i.x&&0===i.y&&(t.teleportationState.blocked&&(t.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),t.teleportationState.forward&&this._teleportForward(e.uniqueId))}))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}else{t.teleportationState.mainComponentUsed=!0;let i=!1;const r=()=>{this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.forward=!0,t.teleportationState.initialHit=!1,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,xd({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})};this._xrSessionManager.scene.onPointerObservable.add((e=>{e.type===yi.Zp.POINTERDOWN?(i=!1,this._options.timeToTeleportStart?xd({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&r()},breakCondition:()=>!!i&&(i=!1,!0)}):r()):e.type===yi.Zp.POINTERUP&&(i=!0,t.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 H.ov(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((e=>{this.parabolicCheckRadius=this.parabolicCheckRadius/e.previousScaleFactor*e.newScaleFactor,this._options.teleportationTargetMesh?.scaling.scaleInPlace(e.newScaleFactor/e.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)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0)}dispose(){super.dispose(),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver),this.onTargetMeshPositionUpdatedObservable.clear(),this.onTargetMeshPositionUpdatedObservable.clear(),this.onBeforeCameraTeleportRotation.clear(),this.onAfterCameraTeleportRotation.clear(),this.onBeforeCameraTeleport.clear(),this.onAfterCameraTeleport.clear()}removeFloorMesh(e){const t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];const t=this._options.pickBlockerMeshes.indexOf(e);-1!==t&&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(-1===t)for(let i=0;i{if(this._options.blockerMeshesPredicate&&this._options.blockerMeshesPredicate(e))return!0;if(this._options.blockAllPickableMeshes&&e.isPickable)return!0;if(this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e))return!0;const t=this._floorMeshes.indexOf(e);return-1!==t&&this._floorMeshes[t].absolutePosition.y!(!this._options.blockerMeshesPredicate||!this._options.blockerMeshesPredicate(e))||!(!this._options.blockAllPickableMeshes||!e.isPickable)||!(!this._options.pickBlockerMeshes||-1===this._options.pickBlockerMeshes.indexOf(e))||-1!==this._floorMeshes.indexOf(e))),l=a&&a.pickedMesh&&-1!==this._floorMeshes.indexOf(a.pickedMesh);if(a&&a.pickedMesh&&!l)return e.teleportationState.mainComponentUsed&&!e.teleportationState.initialHit?void(e.teleportationState.forward=!1):(e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1,!1,s),void this._showParabolicPath(a));a&&a.pickedPoint&&(e.teleportationState.initialHit=!0,e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(a),this._setTargetMeshVisibility(!0,!1,s),this._showParabolicPath(a))}this._setTargetMeshVisibility(t,!1,s)}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||Bo.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=io("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{const i=512,r=new Gn("teleportationPlaneDynamicTexture",i,e,!0);r.hasAlpha=!0;const s=r.getContext(),n=i/2,o=i/2,a=200;s.beginPath(),s.arc(n,o,a,0,2*Math.PI,!1),s.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",s.fill(),s.lineWidth=10,s.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",s.stroke(),s.closePath(),r.update();const l=new Un("teleportationPlaneMaterial",e);l.diffuseTexture=r,t.material=l}const i=ao("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){const t=new pe.X5("animationInnerCircle","position.y",30,pe.X5.ANIMATIONTYPE_FLOAT,pe.X5.ANIMATIONLOOPMODE_CYCLE),r=[];r.push({frame:0,value:0}),r.push({frame:30,value:.4}),r.push({frame:60,value:0}),t.setKeys(r);const s=new Me;s.setEasingMode(xe.EASINGMODE_EASEINOUT),t.setEasingFunction(s),i.animations=[],i.animations.push(t),e.beginAnimation(i,0,60,!0)}const r=No("rotationCone",{diameterTop:0,tessellation:4},e);if(r.isPickable=!1,r.scaling.set(.5,.12,.2),r.rotate(Mt._0.X,Math.PI/2),r.position.z=.6,r.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,r.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{const t=new Un("torusConsMat",e);t.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,t.disableLighting?t.emissiveColor=new H.v9(.3,.3,1):t.diffuseColor=new H.v9(.3,.3,1),t.alpha=.9,i.material=t,r.material=t,this._teleportationRingMaterial=t}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._options.teleportationTargetMesh.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._setTargetMeshVisibility(!1)}_detachController(e){const t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,r=Number.MAX_VALUE;if(this._snapToPositions.length){const s=t*t;this._snapToPositions.forEach((t=>{const n=W.Pq.DistanceSquared(t,e);n<=s&&n{t.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||Bo.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],r=ve.jj.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),s=i.teleportationState.blocked?this._blockedRayColor:void 0,n=this._colorArray.fill(s||this._cachedColor4White),o=r.getPoints();o.shift(),o.shift(),this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(r.getPoints(),e):this._quadraticBezierCurve=Ra("teleportation path line",{points:o,instance:this._quadraticBezierCurve,updatable:!0,colors:n},t),this._quadraticBezierCurve.isPickable=!1,void 0!==this._options.renderingGroupId&&(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;else if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){const e=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+=e,W.PT.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)}}}Av.Name=hr.TELEPORTATION,Av.Version=1,cr.AddWebXRFeature(Av.Name,((e,t)=>()=>new Av(e,t)),Av.Version,!0);class Rv{}class Iv{constructor(){}static CreateAsync(e,t={}){const i=new Iv;if(e.onDisposeObservable.addOnce((()=>{i.dispose()})),!t.disableDefaultUI){const r={renderTarget:i.renderTarget,...t.uiOptions||{}};t.optionalFeatures&&("boolean"==typeof t.optionalFeatures?r.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:r.optionalFeatures=t.optionalFeatures),i.enterExitUI=new Tv(e,r)}return Ym.CreateAsync(e).then((e=>{if(i.baseExperience=e,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new Rg(e.sessionManager,e.camera,{controllerOptions:{renderingGroupId:t.renderingGroupId},...t.inputOptions||{}}),!t.disablePointerSelection){const e={...t.pointerSelectionOptions,xrInput:i.input,renderingGroupId:t.renderingGroupId};i.pointerSelection=i.baseExperience.featuresManager.enableFeature(Mg.Name,t.useStablePlugins?"stable":"latest",e),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(Av.Name,t.useStablePlugins?"stable":"latest",{floorMeshes:t.floorMeshes,xrInput:i.input,renderingGroupId:t.renderingGroupId,...t.teleportationOptions}),i.teleportation.setSelectionFeature(i.pointerSelection))}return t.disableNearInteraction||(i.nearInteraction=i.baseExperience.featuresManager.enableFeature(xv.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(Pv.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,...t.handSupportOptions},void 0,!1),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),t.disableDefaultUI?void 0:i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)})).then((()=>i)).catch((e=>(Z.V.Error("Error initializing XR"),Z.V.Error(e),i)))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}var Mv=!0;function Ov(e){for(;e.firstChild;)e.removeChild(e.firstChild);e.srcObject=null,e.src="",e.removeAttribute("src")}oi.Z.prototype.createDefaultLight=function(e=!1){if(e&&this.lights)for(let e=0;ee.isVisible&&e.isEnabled())),r=t.max.subtract(t.min),s=t.min.add(r.scale(.5));let n,o=1.5*r.length();if(isFinite(o)||(o=1,s.copyFromFloats(0,0,0)),e){const e=new is("default camera",-Math.PI/2,Math.PI/2,o,s,this);e.lowerRadiusLimit=.01*o,e.wheelPrecision=100/o,n=e}else{const e=new es("default camera",new W.Pq(s.x,s.y,-o),this);e.setTarget(s),n=e}n.minZ=.01*o,n.maxZ=1e3*o,n.speed=.2*o,this.activeCamera=n,i&&n.attachControl()}},oi.Z.prototype.createDefaultCameraOrLight=function(e=!1,t=!1,i=!1){this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},oi.Z.prototype.createDefaultSkybox=function(e,t=!1,i=1e3,r=0,s=!0){if(!e)return Z.V.Warn("Can not create default skybox without environment texture."),null;s&&e&&(this.environmentTexture=e);const n=Ko("hdrSkyBox",{size:i},this);if(t){const t=new zm("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=vi.g.SKYBOX_MODE),t.microSurface=1-r,t.disableLighting=!0,t.twoSidedLighting=!0,n.material=t}else{const t=new Un("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=vi.g.SKYBOX_MODE),t.disableLighting=!0,n.material=t}return n.isPickable=!1,n.infiniteDistance=!0,n.ignoreCameraMaxZ=!0,n},oi.Z.prototype.createDefaultEnvironment=function(e){return bm?new bm(e,this):null},oi.Z.prototype.createDefaultVRExperience=function(e={}){return new fo(this,e)},oi.Z.prototype.createDefaultXRExperienceAsync=function(e={}){return Iv.CreateAsync(this,e).then((e=>e))};class Dv extends vi.g{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new z.cP),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(e?.message):Z.V.Error(e?.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch((e=>{if("NotAllowedError"===e?.name){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers())return void this._onUserActionRequestedObservable.notifyObservers(this);if(!this.video.muted)return Z.V.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,void this.video.play().catch((e=>{this._processError(e)}))}this._processError(e)}))}constructor(e,t,i,r=!1,s=!1,n=vi.g.TRILINEAR_SAMPLINGMODE,o={},a,l=5){super(null,i,!r,s),this._externalTexture=null,this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this.isVideo=!0,this._resizeInternalTexture=()=>{null!=this._texture&&this._texture.dispose(),!this._getEngine().needPOTTextures||Ue.S0.IsExponentOfTwo(this.video.videoWidth)&&Ue.S0.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=vi.g.WRAP_ADDRESSMODE,this.wrapV=vi.g.WRAP_ADDRESSMODE):(this.wrapU=vi.g.CLAMP_ADDRESSMODE,this.wrapV=vi.g.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(null!=this._texture){if(!this._displayingPosterTexture)return;this._displayingPosterTexture=!1}if(this.video.addEventListener("resize",this._resizeInternalTexture),this._resizeInternalTexture(),this.video.autoplay||this._settings.poster||this._settings.independentVideoSource)this._updateInternalTexture(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this);else{const e=this.video.onplaying,t=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=t,this.video.onplaying=e,this._updateInternalTexture(),this._errorFound||this.video.pause(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._handlePlay()}},this._reset=()=>{null!=this._texture&&(this._displayingPosterTexture||(this._texture.dispose(),this._texture=null))},this._updateInternalTexture=()=>{if(null==this._texture)return;if(this.video.readyState=this.video.HAVE_CURRENT_DATA;!this._settings.poster||this._settings.autoPlay&&u?u&&this._createInternalTexture():(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0)}getClassName(){return"VideoTexture"}_getName(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e}_getVideo(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return Ue.S0.SetCorsBehavior(e.currentSrc,e),e;const t=document.createElement("video");return"string"==typeof e?(Ue.S0.SetCorsBehavior(e,t),t.src=e):(Ue.S0.SetCorsBehavior(e[0],t),e.forEach((e=>{const i=document.createElement("source");i.src=e,t.appendChild(i)}))),this.onDisposeObservable.addOnce((()=>{Ov(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 Dv(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)}dispose(){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()),this._externalTexture?.dispose()}static CreateFromStreamAsync(e,t,i,r=!0){const s=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(s),s.style.transform="scale(0.0001, 0.0001)",s.style.opacity="0",s.style.position="fixed",s.style.bottom="0px",s.style.right="0px"),s.setAttribute("autoplay",""),s.setAttribute("muted","true"),s.setAttribute("playsinline",""),s.muted=!0,s.isNative||("object"==typeof s.srcObject?s.srcObject=t:s.src=window.URL&&window.URL.createObjectURL(t)),new Promise((t=>{const i=()=>{const n=new Dv("video",s,e,!0,r,void 0,void 0,void 0,4);e.getEngine()._badOS&&n.onDisposeObservable.addOnce((()=>{s.remove()})),n.onDisposeObservable.addOnce((()=>{Ov(s)})),t(n),s.removeEventListener("playing",i)};s.addEventListener("playing",i),s.play()}))}static async CreateFromWebCamAsync(e,t,i=!1,r=!0){if(navigator.mediaDevices){const s=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),n=await this.CreateFromStreamAsync(e,s,t,r);return n.onDisposeObservable.addOnce((()=>{s.getTracks().forEach((e=>{e.stop()}))})),n}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,r=!1,s=!0){this.CreateFromWebCamAsync(e,i,r,s).then((function(e){t&&t(e)})).catch((function(e){Z.V.Error(e.name)}))}}(0,je.Cg)([(0,$e.lK)("settings")],Dv.prototype,"_settings",void 0),(0,je.Cg)([(0,$e.lK)("src")],Dv.prototype,"_currentSrc",void 0),(0,je.Cg)([(0,$e.lK)()],Dv.prototype,"isVideo",void 0),vi.g._CreateVideoTexture=(e,t,i,r=!1,s=!1,n=vi.g.TRILINEAR_SAMPLINGMODE,o={},a,l=5)=>new Dv(e,t,i,r,s,n,o,a,l),(0,X.Y5)("BABYLON.VideoTexture",Dv);class wv extends Sm{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){const r={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},s=new Dv((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,vi.g.TRILINEAR_SAMPLINGMODE,r);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add((e=>{e.pickInfo?.pickedMesh===this.mesh&&this._texture.video.play()}),yi.Zp.POINTERDOWN)),this._textureObserver=s.onLoadObservable.add((()=>{this.onLoadObservable.notifyObservers()})),s}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}}wv.MODE_MONOSCOPIC=Sm.MODE_MONOSCOPIC,wv.MODE_TOPBOTTOM=Sm.MODE_TOPBOTTOM,wv.MODE_SIDEBYSIDE=Sm.MODE_SIDEBYSIDE;class Nv{get gpuFrameTimeCounter(){return this.engine.getGPUFrameTimeCounter()}get captureGPUFrameTime(){return this._captureGPUFrameTime}set captureGPUFrameTime(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,this.engine.captureGPUFrameTime(e))}get shaderCompilationTimeCounter(){return this._shaderCompilationTime}get captureShaderCompilationTime(){return this._captureShaderCompilationTime}set captureShaderCompilationTime(e){e!==this._captureShaderCompilationTime&&(this._captureShaderCompilationTime=e,e?(this._onBeforeShaderCompilationObserver=this.engine.onBeforeShaderCompilationObservable.add((()=>{this._shaderCompilationTime.fetchNewFrame(),this._shaderCompilationTime.beginMonitoring()})),this._onAfterShaderCompilationObserver=this.engine.onAfterShaderCompilationObservable.add((()=>{this._shaderCompilationTime.endMonitoring()}))):(this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null))}constructor(e){this.engine=e,this._captureGPUFrameTime=!1,this._captureShaderCompilationTime=!1,this._shaderCompilationTime=new on.A,this._onBeginFrameObserver=null,this._onEndFrameObserver=null,this._onBeforeShaderCompilationObserver=null,this._onAfterShaderCompilationObserver=null}dispose(){this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null,this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null,this.engine=null}}class Fv{get activeMeshesEvaluationTimeCounter(){return this._activeMeshesEvaluationTime}get captureActiveMeshesEvaluationTime(){return this._captureActiveMeshesEvaluationTime}set captureActiveMeshesEvaluationTime(e){e!==this._captureActiveMeshesEvaluationTime&&(this._captureActiveMeshesEvaluationTime=e,e?(this._onBeforeActiveMeshesEvaluationObserver=this.scene.onBeforeActiveMeshesEvaluationObservable.add((()=>{Ue.S0.StartPerformanceCounter("Active meshes evaluation"),this._activeMeshesEvaluationTime.beginMonitoring()})),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add((()=>{Ue.S0.EndPerformanceCounter("Active meshes evaluation"),this._activeMeshesEvaluationTime.endMonitoring(!1)}))):(this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null))}get renderTargetsRenderTimeCounter(){return this._renderTargetsRenderTime}get captureRenderTargetsRenderTime(){return this._captureRenderTargetsRenderTime}set captureRenderTargetsRenderTime(e){e!==this._captureRenderTargetsRenderTime&&(this._captureRenderTargetsRenderTime=e,e?(this._onBeforeRenderTargetsRenderObserver=this.scene.onBeforeRenderTargetsRenderObservable.add((()=>{Ue.S0.StartPerformanceCounter("Render targets rendering"),this._renderTargetsRenderTime.beginMonitoring()})),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add((()=>{Ue.S0.EndPerformanceCounter("Render targets rendering"),this._renderTargetsRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null))}get particlesRenderTimeCounter(){return this._particlesRenderTime}get captureParticlesRenderTime(){return this._captureParticlesRenderTime}set captureParticlesRenderTime(e){e!==this._captureParticlesRenderTime&&(this._captureParticlesRenderTime=e,e?(this._onBeforeParticlesRenderingObserver=this.scene.onBeforeParticlesRenderingObservable.add((()=>{Ue.S0.StartPerformanceCounter("Particles"),this._particlesRenderTime.beginMonitoring()})),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add((()=>{Ue.S0.EndPerformanceCounter("Particles"),this._particlesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null))}get spritesRenderTimeCounter(){return this._spritesRenderTime}get captureSpritesRenderTime(){return this._captureSpritesRenderTime}set captureSpritesRenderTime(e){e!==this._captureSpritesRenderTime&&(this._captureSpritesRenderTime=e,this.scene.spriteManagers&&(e?(this._onBeforeSpritesRenderingObserver=this.scene.onBeforeSpritesRenderingObservable.add((()=>{Ue.S0.StartPerformanceCounter("Sprites"),this._spritesRenderTime.beginMonitoring()})),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add((()=>{Ue.S0.EndPerformanceCounter("Sprites"),this._spritesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null)))}get physicsTimeCounter(){return this._physicsTime}get capturePhysicsTime(){return this._capturePhysicsTime}set capturePhysicsTime(e){e!==this._capturePhysicsTime&&this.scene.onBeforePhysicsObservable&&(this._capturePhysicsTime=e,e?(this._onBeforePhysicsObserver=this.scene.onBeforePhysicsObservable.add((()=>{Ue.S0.StartPerformanceCounter("Physics"),this._physicsTime.beginMonitoring()})),this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add((()=>{Ue.S0.EndPerformanceCounter("Physics"),this._physicsTime.endMonitoring()}))):(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null))}get animationsTimeCounter(){return this._animationsTime}get captureAnimationsTime(){return this._captureAnimationsTime}set captureAnimationsTime(e){e!==this._captureAnimationsTime&&(this._captureAnimationsTime=e,e?this._onAfterAnimationsObserver=this.scene.onAfterAnimationsObservable.add((()=>{this._animationsTime.endMonitoring()})):(this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null))}get frameTimeCounter(){return this._frameTime}get captureFrameTime(){return this._captureFrameTime}set captureFrameTime(e){this._captureFrameTime=e}get interFrameTimeCounter(){return this._interFrameTime}get captureInterFrameTime(){return this._captureInterFrameTime}set captureInterFrameTime(e){this._captureInterFrameTime=e}get renderTimeCounter(){return this._renderTime}get captureRenderTime(){return this._captureRenderTime}set captureRenderTime(e){e!==this._captureRenderTime&&(this._captureRenderTime=e,e?(this._onBeforeDrawPhaseObserver=this.scene.onBeforeDrawPhaseObservable.add((()=>{this._renderTime.beginMonitoring(),Ue.S0.StartPerformanceCounter("Main render")})),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add((()=>{this._renderTime.endMonitoring(!1),Ue.S0.EndPerformanceCounter("Main render")}))):(this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null))}get cameraRenderTimeCounter(){return this._cameraRenderTime}get captureCameraRenderTime(){return this._captureCameraRenderTime}set captureCameraRenderTime(e){e!==this._captureCameraRenderTime&&(this._captureCameraRenderTime=e,e?(this._onBeforeCameraRenderObserver=this.scene.onBeforeCameraRenderObservable.add((e=>{this._cameraRenderTime.beginMonitoring(),Ue.S0.StartPerformanceCounter(`Rendering camera ${e.name}`)})),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add((e=>{this._cameraRenderTime.endMonitoring(!1),Ue.S0.EndPerformanceCounter(`Rendering camera ${e.name}`)}))):(this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null))}get drawCallsCounter(){return this.scene.getEngine()._drawCalls}constructor(e){this.scene=e,this._captureActiveMeshesEvaluationTime=!1,this._activeMeshesEvaluationTime=new on.A,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new on.A,this._captureFrameTime=!1,this._frameTime=new on.A,this._captureRenderTime=!1,this._renderTime=new on.A,this._captureInterFrameTime=!1,this._interFrameTime=new on.A,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new on.A,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new on.A,this._capturePhysicsTime=!1,this._physicsTime=new on.A,this._captureAnimationsTime=!1,this._animationsTime=new on.A,this._captureCameraRenderTime=!1,this._cameraRenderTime=new on.A,this._onBeforeActiveMeshesEvaluationObserver=null,this._onAfterActiveMeshesEvaluationObserver=null,this._onBeforeRenderTargetsRenderObserver=null,this._onAfterRenderTargetsRenderObserver=null,this._onAfterRenderObserver=null,this._onBeforeDrawPhaseObserver=null,this._onAfterDrawPhaseObserver=null,this._onBeforeAnimationsObserver=null,this._onBeforeParticlesRenderingObserver=null,this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver=null,this._onAfterSpritesRenderingObserver=null,this._onBeforePhysicsObserver=null,this._onAfterPhysicsObserver=null,this._onAfterAnimationsObserver=null,this._onBeforeCameraRenderObserver=null,this._onAfterCameraRenderObserver=null,this._onBeforeAnimationsObserver=e.onBeforeAnimationsObservable.add((()=>{this._captureActiveMeshesEvaluationTime&&this._activeMeshesEvaluationTime.fetchNewFrame(),this._captureRenderTargetsRenderTime&&this._renderTargetsRenderTime.fetchNewFrame(),this._captureFrameTime&&(Ue.S0.StartPerformanceCounter("Scene rendering"),this._frameTime.beginMonitoring()),this._captureInterFrameTime&&this._interFrameTime.endMonitoring(),this._captureParticlesRenderTime&&this._particlesRenderTime.fetchNewFrame(),this._captureSpritesRenderTime&&this._spritesRenderTime.fetchNewFrame(),this._captureAnimationsTime&&this._animationsTime.beginMonitoring(),this._captureRenderTime&&this._renderTime.fetchNewFrame(),this._captureCameraRenderTime&&this._cameraRenderTime.fetchNewFrame(),this.scene.getEngine()._drawCalls.fetchNewFrame()})),this._onAfterRenderObserver=e.onAfterRenderObservable.add((()=>{this._captureFrameTime&&(Ue.S0.EndPerformanceCounter("Scene rendering"),this._frameTime.endMonitoring()),this._captureRenderTime&&this._renderTime.endMonitoring(!1),this._captureInterFrameTime&&this._interFrameTime.beginMonitoring(),this._captureActiveMeshesEvaluationTime&&this._activeMeshesEvaluationTime.endFrame(),this._captureRenderTargetsRenderTime&&this._renderTargetsRenderTime.endFrame(),this._captureParticlesRenderTime&&this._particlesRenderTime.endFrame(),this._captureSpritesRenderTime&&this._spritesRenderTime.endFrame(),this._captureRenderTime&&this._renderTime.endFrame(),this._captureCameraRenderTime&&this._cameraRenderTime.endFrame()}))}dispose(){this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=null,this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null,this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null,this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver),this._onBeforeAnimationsObserver=null,this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver&&(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null),this._onAfterSpritesRenderingObserver&&(this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null),this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null,this._onBeforePhysicsObserver&&(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null),this._onAfterPhysicsObserver&&(this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null),this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null,this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null,this.scene=null}}class Lv{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}get shaderLanguage(){return this._shaderLanguage}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i{if((i||0===t)&&e.subMeshes)for(let t=0;t{let s;this.onBeforeRenderMainTextureObservable.notifyObservers(this);const n=this._scene.getEngine();if(r.length){for(n.setColorWrite(!1),s=0;s{e.clear(this.neutralColor,!0,!0,!0)})),this._scene.getBoundingBoxRenderer){const e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e})),this._mainTexture.onAfterUnbindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=e}))}}_addCustomEffectDefines(e){}_isReady(e,t,i){const r=this._scene.getEngine(),s=e.getMesh(),n=s._internalAbstractMeshDataInfo._materialForRenderPass?.[r.currentRenderPassId];if(n)return n.isReadyForSubMesh(s,e,t);const o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);const a=[],l=[st.R.PositionKind];let h=!1,c=!1;if(o){const e=o.needAlphaTesting(),t=o.getAlphaTestTexture(),i=t&&t.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);t&&(e||i)&&(a.push("#define DIFFUSE"),s.isVerticesDataPresent(st.R.UV2Kind)&&1===t.coordinatesIndex?(a.push("#define DIFFUSEUV2"),c=!0):s.isVerticesDataPresent(st.R.UVKind)&&(a.push("#define DIFFUSEUV1"),h=!0),e&&(a.push("#define ALPHATEST"),a.push("#define ALPHATESTVALUE 0.4")),t.gammaSpace||a.push("#define DIFFUSE_ISLINEAR"));const r=o.opacityTexture;r&&(a.push("#define OPACITY"),s.isVerticesDataPresent(st.R.UV2Kind)&&1===r.coordinatesIndex?(a.push("#define OPACITYUV2"),c=!0):s.isVerticesDataPresent(st.R.UVKind)&&(a.push("#define OPACITYUV1"),h=!0))}i&&(a.push("#define EMISSIVE"),s.isVerticesDataPresent(st.R.UV2Kind)&&1===i.coordinatesIndex?(a.push("#define EMISSIVEUV2"),c=!0):s.isVerticesDataPresent(st.R.UVKind)&&(a.push("#define EMISSIVEUV1"),h=!0),i.gammaSpace||a.push("#define EMISSIVE_ISLINEAR")),s.useVertexColors&&s.isVerticesDataPresent(st.R.ColorKind)&&s.hasVertexAlpha&&o.transparencyMode!==Vt.MATERIAL_OPAQUE&&(l.push(st.R.ColorKind),a.push("#define VERTEXALPHA")),h&&(l.push(st.R.UVKind),a.push("#define UV1")),c&&(l.push(st.R.UV2Kind),a.push("#define UV2"));const u=new Tn;if(s.useBones&&s.computeBonesUsingShaders){l.push(st.R.MatricesIndicesKind),l.push(st.R.MatricesWeightsKind),s.numBoneInfluencers>4&&(l.push(st.R.MatricesIndicesExtraKind),l.push(st.R.MatricesWeightsExtraKind)),a.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers);const e=s.skeleton;e&&e.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(e?e.bones.length+1:0)),s.numBoneInfluencers>0&&u.addCPUSkinningFallback(0,s)}else a.push("#define NUM_BONE_INFLUENCERS 0");const d=s.morphTargetManager;let f=0;d&&(f=d.numMaxInfluencers||d.numInfluencers,f>0&&(a.push("#define MORPHTARGETS"),a.push("#define NUM_MORPH_INFLUENCERS "+f),d.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),(0,Bt.MF)(l,s,f))),t&&(a.push("#define INSTANCES"),(0,Bt.te)(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),(0,Ln.tv)(o,this._scene,a),this._addCustomEffectDefines(a);const p=e._getDrawWrapper(void 0,!0),_=p.defines,m=a.join("\n");if(_!==m){const e=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];(0,Ln.TV)(e),p.setEffect(this._engine.createEffect("glowMapGeneration",l,e,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],m,u,void 0,void 0,{maxSimultaneousMorphTargets:f},this._shaderLanguage,this._shadersLoaded?void 0:async()=>{await this._importShadersAsync(),this._shadersLoaded=!0}),m)}const g=p.effect.isReady();return this._arePostProcessAndMergeReady()&&g}async _importShadersAsync(){1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,58186)),Promise.resolve().then(i.bind(i,69276))]):await Promise.all([Promise.resolve().then(i.bind(i,91337)),Promise.resolve().then(i.bind(i,42591))])}_arePostProcessAndMergeReady(){let e=!0;for(let t=0;th.setMatrix("world",t)))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(r)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[st.R.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 Ue.S0.Instantiate(e.customType).Parse(e,t,i)}}Lv.ForceGLSL=!1,Lv._SceneComponentInitialization=e=>{throw(0,Je.n)("EffectLayerSceneComponent")},(0,je.Cg)([(0,$e.lK)()],Lv.prototype,"name",void 0),(0,je.Cg)([(0,$e.qK)()],Lv.prototype,"neutralColor",void 0),(0,je.Cg)([(0,$e.lK)()],Lv.prototype,"isEnabled",void 0),(0,je.Cg)([(0,$e.fW)()],Lv.prototype,"camera",null),(0,je.Cg)([(0,$e.lK)()],Lv.prototype,"renderingGroupId",null),(0,je.Cg)([(0,$e.lK)()],Lv.prototype,"disableBoundingBoxesFromEffectLayer",void 0),ci(Ut.v.NAME_EFFECTLAYER,((e,t,i,r)=>{if(e.effectLayers){i.effectLayers||(i.effectLayers=[]);for(let s=0;s{this.scene.addEffectLayer(e)}))}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach((e=>{this.scene.removeEffectLayer(e),t&&e.dispose()}))}dispose(){const e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){const i=this._engine.currentRenderPassId,r=this.scene.effectLayers;for(const s of r){if(!s.hasMesh(e))continue;const r=s._mainTexture;this._engine.currentRenderPassId=r.renderPassId;for(const r of e.subMeshes)if(!s.isReady(r,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1;const i=this.scene.effectLayers;if(i&&i.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(const r of i)if(r.shouldRender()&&(!r.camera||r.camera.cameraRigMode===rt.RIG_MODE_NONE&&e===r.camera||r.camera.cameraRigMode!==rt.RIG_MODE_NONE&&r.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||r.needStencil();const e=r._mainTexture;e._shouldRender()&&(this.scene.incrementRenderId(),e.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 t=e._getComponent(Ut.v.NAME_EFFECTLAYER);t||(t=new Bv(e),e._addComponent(t))},oi.Z.prototype.getGlowLayerByName=function(e){for(let t=0;t{await this._importShadersAsync(),this._shadersLoaded=!0})}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width,t=this._mainTextureDesiredSize.height;e=this._engine.needPOTTextures?(0,Gs.R)(e,this._maxSize):e,t=this._engine.needPOTTextures?(0,Gs.R)(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture1=new ln.$("GlowLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture1.wrapU=vi.g.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=vi.g.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(vi.g.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;const r=Math.floor(e/2),s=Math.floor(t/2);this._blurTexture2=new ln.$("GlowLayerBlurRTT2",{width:r,height:s},this._scene,!1,!0,i),this._blurTexture2.wrapU=vi.g.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=vi.g.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(vi.g.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2];const n=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new _m("GlowLayerHBP1",new W.I9(1,0),n,{width:e,height:t},null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess1.width=e,this._horizontalBlurPostprocess1.height=t,this._horizontalBlurPostprocess1.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess1.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess1=new _m("GlowLayerVBP1",new W.I9(0,1),n,{width:e,height:t},null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new _m("GlowLayerHBP2",new W.I9(1,0),n,{width:r,height:s},null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=r,this._horizontalBlurPostprocess2.height=s,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._blurTexture1)})),this._verticalBlurPostprocess2=new _m("GlowLayerVBP2",new W.I9(0,1),n,{width:r,height:s},null,vi.g.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 e=this._blurTexture1.renderTarget;if(e){this._scene.postProcessManager.directRender(this._postProcesses1,e,!0);const t=this._blurTexture2.renderTarget;t&&this._scene.postProcessManager.directRender(this._postProcesses2,t,!0),this._engine.unBindFramebuffer(t??e,!0)}})),this._postProcesses.map((e=>{e.autoClear=!1}))}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){const i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r)return!1;const s=i.emissiveTexture;return super._isReady(e,t,s)}needStencil(){return!1}_canRenderMesh(e,t){return!0}_internalRender(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);const t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(Vt.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){let r=1;this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(r=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector?this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color):i.emissiveColor?(r*=i.emissiveIntensity??1,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*r,i.emissiveColor.g*r,i.emissiveColor.b*r,i.alpha)):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){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){-1===this._includedOnlyMeshes.indexOf(e.uniqueId)&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){const t=this._includedOnlyMeshes.indexOf(e.uniqueId);-1!==t&&this._includedOnlyMeshes.splice(t,1)}hasMesh(e){return!!super.hasMesh(e)&&(this._includedOnlyMeshes.length?-1!==this._includedOnlyMeshes.indexOf(e.uniqueId):!this._excludedMeshes.length||-1===this._excludedMeshes.indexOf(e.uniqueId))}_useMeshMaterial(e){return 0!=this._meshesUsingTheirOwnMaterials.length&&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=it.p.Serialize(this);let t;if(e.customType="BABYLON.GlowLayer",e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;tnew Vv(e.name,t,e.options)),e,t,i);let s;for(s=0;s{e.setFloat2("screenSize",this.width,this.height),e.setVector2("direction",this.direction),e.setFloat("blurWidth",this.kernel)}))}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(i.bind(i,41368)))):t.push(Promise.resolve().then(i.bind(i,16655))),super._gatherImports(e,t)}}class Uv extends Lv{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,void 0!==i&&!!i.forceGLSL),this.name=e,this.innerGlow=!0,this.outerGlow=!0,this.onBeforeBlurObservable=new z.cP,this.onAfterBlurObservable=new z.cP,this._instanceGlowingMeshStencilReference=Uv.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=Uv.NeutralColor,this._engine.isStencilEnable||Z.V.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options={mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,forceGLSL:!1,...i},this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}async _importShadersAsync(){1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,68940)),Promise.resolve().then(i.bind(i,86010)),Promise.resolve().then(i.bind(i,41368))]):await Promise.all([Promise.resolve().then(i.bind(i,74969)),Promise.resolve().then(i.bind(i,99347)),Promise.resolve().then(i.bind(i,16655))]),await super._importShadersAsync()}getEffectName(){return Uv.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[st.R.PositionKind],["offset"],["textureSampler"],this._options.isStroke?"#define STROKE \n":void 0,void 0,void 0,void 0,void 0,this._shaderLanguage,this._shadersLoaded?void 0:async()=>{await this._importShadersAsync(),this._shadersLoaded=!0})}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?(0,Gs.R)(e,this._maxSize):e,t=this._engine.needPOTTextures?(0,Gs.R)(t,this._maxSize):t;let i=0;if(i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture=new ln.$("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=vi.g.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=vi.g.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(vi.g.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],2===this._options.alphaBlendingMode)this._downSamplePostprocess=new _s.v("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._horizontalBlurPostprocess=new kv("HighlightLayerHBP",new W.I9(1,0),this._options.blurHorizontalSize,1,null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._verticalBlurPostprocess=new kv("HighlightLayerVBP",new W.I9(0,1),this._options.blurVerticalSize,1,null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess];else{this._horizontalBlurPostprocess=new _m("HighlightLayerHBP",new W.I9(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i);const r=this._horizontalBlurPostprocess;r.width=e,r.height=t,r.externalTextureSamplerBinding=!0,r.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess=new _m("HighlightLayerVBP",new W.I9(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]}this._mainTexture.onAfterUnbindObservable.add((()=>{this.onBeforeBlurObservable.notifyObservers(this);const e=this._blurTexture.renderTarget;e&&(this._scene.postProcessManager.directRender(this._postProcesses,e,!0),this._engine.unBindFramebuffer(e,!0)),this.onAfterBlurObservable.notifyObservers(this)})),this._postProcesses.map((e=>{e.autoClear=!1}))}needStencil(){return!0}isReady(e,t){const i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r||!this._meshes)return!1;let s=null;const n=this._meshes[r.uniqueId];return n&&n.glowEmissiveOnly&&i&&(s=i.emissiveTexture),super._isReady(e,t,s)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);const i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&0===t&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(Vt.TriangleFillMode,0,6)),this.innerGlow&&1===t&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(Vt.TriangleFillMode,0,6)),i.restoreStencilState()}shouldRender(){return!!super.shouldRender()&&!!this._meshes}_shouldRenderMesh(e){return!(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]||!super.hasMesh(e))}_canRenderMesh(e,t){return!0}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}_setEmissiveTextureAndColor(e,t,i){const r=this._meshes[e.uniqueId];r?this._emissiveTextureAndColor.color.set(r.color.r,r.color.g,r.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),r&&r.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(this._excludedMeshes&&!this._excludedMeshes[e.uniqueId]){const t={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};t.beforeBind=e.onBeforeBindObservable.add((e=>{t.stencilState=e.getEngine().getStencilBuffer(),e.getEngine().setStencilBuffer(!1)})),t.afterRender=e.onAfterRenderObservable.add((e=>{e.getEngine().setStencilBuffer(t.stencilState)})),this._excludedMeshes[e.uniqueId]=t}}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)&&void 0!==this._meshes[e.uniqueId]&&null!==this._meshes[e.uniqueId]}addMesh(e,t,i=!1){if(!this._meshes)return;const r=this._meshes[e.uniqueId];r?r.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add((e=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?this._defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))})),observerDefault:e.onAfterRenderObservable.add((e=>{this.isEnabled&&this._defaultStencilReference(e)})),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 e in this._meshes)if(this._meshes[e]){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(Uv.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=it.p.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(const t in this._meshes){const i=this._meshes[t];i&&e.meshes.push({glowEmissiveOnly:i.glowEmissiveOnly,color:i.color.asArray(),meshId:i.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(const t in this._excludedMeshes){const i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){const r=it.p.Parse((()=>new Uv(e.name,t,e.options)),e,t,i);let s;for(s=0;sthis._drawCameraPredicate(t,!0,!0,e.layerMask)))}_drawCameraForegroundWithPostProcessing(e){this._draw((t=>this._drawCameraPredicate(t,!1,!0,e.layerMask)))}_drawCameraForegroundWithoutPostProcessing(e){this._draw((t=>this._drawCameraPredicate(t,!1,!1,e.layerMask)))}_drawRenderTargetPredicate(e,t,i,r,s){return e.renderTargetTextures.length>0&&e.isBackground===t&&e.applyPostProcess===i&&e.renderTargetTextures.indexOf(s)>-1&&!!(e.layerMask&r)}_drawRenderTargetBackground(e){this._draw((t=>this._drawRenderTargetPredicate(t,!0,!0,this.scene.activeCamera.layerMask,e)))}_drawRenderTargetForegroundWithPostProcessing(e){this._draw((t=>this._drawRenderTargetPredicate(t,!1,!0,this.scene.activeCamera.layerMask,e)))}_drawRenderTargetForegroundWithoutPostProcessing(e){this._draw((t=>this._drawRenderTargetPredicate(t,!1,!1,this.scene.activeCamera.layerMask,e)))}addFromContainer(e){e.layers&&e.layers.forEach((e=>{this.scene.layers.push(e)}))}removeFromContainer(e,t=!1){e.layers&&e.layers.forEach((e=>{const i=this.scene.layers.indexOf(e);-1!==i&&this.scene.layers.splice(i,1),t&&e.dispose()}))}}class zv{set applyPostProcess(e){this._applyPostProcess=e}get applyPostProcess(){return this.isBackground||this._applyPostProcess}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,r,s,n=!1){this.name=e,this._applyPostProcess=!0,this.scale=new W.I9(1,1),this.offset=new W.I9(0,0),this.alphaBlendingMode=2,this.layerMask=268435455,this.renderTargetTextures=[],this.renderOnlyInRenderTargetTextures=!1,this.convertToLinearSpace=!1,this.isEnabled=!0,this._vertexBuffers={},this.onDisposeObservable=new z.cP,this.onBeforeRenderObservable=new z.cP,this.onAfterRenderObservable=new z.cP,this._shaderLanguage=0,this._shadersLoaded=!1,this.texture=t?new vi.g(t,i,!0):null,this.isBackground=void 0===r||r,this.color=void 0===s?new H.ov(1,1,1,1):s,this._scene=i||he.q.LastCreatedScene;const o=this._scene.getEngine();!o.isWebGPU||n||zv.ForceGLSL||(this._shaderLanguage=1);let a=this._scene._getComponent(Ut.v.NAME_LAYER);a||(a=new Gv(this._scene),this._scene._addComponent(a)),this._scene.layers.push(this),this._drawWrapper=new gt.E(o);const l=[];l.push(1,1),l.push(-1,1),l.push(-1,-1),l.push(1,-1);const h=new st.R(o,l,st.R.PositionKind,!1,!1,2);this._vertexBuffers[st.R.PositionKind]=h,this._createIndexBuffer()}_createIndexBuffer(){const e=this._scene.getEngine(),t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[st.R.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}isReady(){const e=this._scene.getEngine();let t="";this.alphaTest&&(t="#define ALPHATEST"),this.texture&&(this.texture.gammaSpace?this.convertToLinearSpace&&(t+="\n#define CONVERT_TO_LINEAR"):this.convertToLinearSpace||(t+="\n#define CONVERT_TO_GAMMA")),this._previousDefines!==t&&(this._previousDefines=t,this._drawWrapper.effect=e.createEffect("layer",[st.R.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],t,void 0,void 0,void 0,void 0,this._shaderLanguage,this._shadersLoaded?void 0:async()=>{1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,56028)),Promise.resolve().then(i.bind(i,28246))]):await Promise.all([Promise.resolve().then(i.bind(i,11115)),Promise.resolve().then(i.bind(i,59329))]),this._shadersLoaded=!0}));const r=this._drawWrapper.effect;return!!r?.isReady()&&(!this.texture||this.texture.isReady())}render(){if(!this.isEnabled)return;const e=this._scene.getEngine();if(!this.isReady())return;const t=this._drawWrapper.effect;this.onBeforeRenderObservable.notifyObservers(this),e.enableEffect(this._drawWrapper),e.setState(!1),this.texture&&(t.setTexture("textureSampler",this.texture),t.setMatrix("textureMatrix",this.texture.getTextureMatrix())),t.setFloat4("color",this.color.r,this.color.g,this.color.b,this.color.a),t.setVector2("offset",this.offset),t.setVector2("scale",this.scale),e.bindBuffers(this._vertexBuffers,this._indexBuffer,t),this.alphaTest?e.drawElementsType(Vt.TriangleFillMode,0,6):(e.setAlphaMode(this.alphaBlendingMode),e.drawElementsType(Vt.TriangleFillMode,0,6),e.setAlphaMode(0)),this.onAfterRenderObservable.notifyObservers(this)}dispose(){const e=this._vertexBuffers[st.R.PositionKind];e&&(e.dispose(),this._vertexBuffers[st.R.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.texture&&(this.texture.dispose(),this.texture=null),this.renderTargetTextures=[];const t=this._scene.layers.indexOf(this);this._scene.layers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderObservable.clear()}}zv.ForceGLSL=!1;var Wv=i(42591),Hv=i(91337),Xv=i(69276),qv=i(58186),Yv=i(74969),Kv=i(99347),jv=i(16655),$v=i(68940),Qv=i(86010),Zv=i(41368),Jv=i(59329),ex=i(11115),tx=i(28246),ix=i(56028);class rx{static AddFlare(e,t,i,r,s){return new rx(e,t,i,r,s)}constructor(e,t,i,r,s){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new H.v9(1,1,1),this.texture=r?new vi.g(r,s.getScene(),!0):null,this._system=s;const n=s.scene.getEngine();s._onShadersLoaded.addOnce((()=>{this._drawWrapper=new gt.E(n),this._drawWrapper.effect=n.createEffect("lensFlare",[st.R.PositionKind],["color","viewportMatrix"],["textureSampler"],"",void 0,void 0,void 0,void 0,s.shaderLanguage)})),s.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();const e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}}class sx{get scene(){return this._scene}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i){this.name=e,this.lensFlares=[],this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._shaderLanguage=0,this._vertexBuffers={},this._isEnabled=!0,this._onShadersLoaded=new z.cP(void 0,!0),this._shadersLoaded=!1,this._scene=i||he.q.LastCreatedScene,sx._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=e=>i.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&!!(e.layerMask&i.activeCamera.layerMask);const r=i.getEngine(),s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1),this._vertexBuffers[st.R.PositionKind]=new st.R(r,s,st.R.PositionKind,!1,!1,2),this._createIndexBuffer(),this._initShaderSourceAsync()}async _initShaderSourceAsync(){this._scene.getEngine().isWebGPU&&!sx.ForceGLSL?(this._shaderLanguage=1,await Promise.all([Promise.resolve().then(i.bind(i,19121)),Promise.resolve().then(i.bind(i,72987))])):await Promise.all([Promise.resolve().then(i.bind(i,54262)),Promise.resolve().then(i.bind(i,45980))]),this._shadersLoaded=!0,this._onShadersLoaded.notifyObservers()}_createIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled=e}getScene(){return this._scene}getEmitter(){return this._emitter}setEmitter(e){this._emitter=e}getEmitterPosition(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position}computeEffectivePosition(e){let t=this.getEmitterPosition();t=W.Pq.Project(t,W.uq.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=W.Pq.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=2*this.viewportBorder,e.height+=2*this.viewportBorder,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._positionY,e.y,e.height),!0)}_isVisible(){if(!this._isEnabled||!this._scene.activeCamera)return!1;const e=this.getEmitterPosition().subtract(this._scene.activeCamera.globalPosition),t=e.length();e.normalize();const i=new wi(this._scene.activeCamera.globalPosition,e),r=this._scene.pickWithRay(i,this.meshesSelectionPredicate,!0);return!r||!r.hit||r.distance>t}render(){if(!this._scene.activeCamera||!this._shadersLoaded)return!1;const e=this._scene.getEngine(),t=this._scene.activeCamera.viewport.toGlobal(e.getRenderWidth(!0),e.getRenderHeight(!0));if(!this.computeEffectivePosition(t))return!1;if(!this._isVisible())return!1;let i,r;i=this._positionXt.x+t.width-this.borderLimit?this._positionX-t.x-t.width+this.borderLimit:0,r=this._positionYt.y+t.height-this.borderLimit?this._positionY-t.y-t.height+this.borderLimit:0;let s=i>r?i:r;s-=this.viewportBorder,s>this.borderLimit&&(s=this.borderLimit);let n=1-(0,ar.Clamp)(s/this.borderLimit,0,1);if(n<0)return!1;n>1&&(n=1),this.viewportBorder>0&&(t.x+=this.viewportBorder,t.y+=this.viewportBorder,t.width-=2*this.viewportBorder,t.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);const o=t.x+t.width/2,a=t.y+t.height/2,l=o-this._positionX,h=a-this._positionY;e.setState(!1),e.setDepthBuffer(!1);for(let i=0;i{throw(0,Je.n)("LensFlareSystemSceneComponent")},ci(Ut.v.NAME_LENSFLARESYSTEM,((e,t,i,r)=>{if(void 0!==e.lensFlareSystems&&null!==e.lensFlareSystems){i.lensFlareSystems||(i.lensFlareSystems=[]);for(let s=0,n=e.lensFlareSystems.length;s{this.scene.addLensFlareSystem(e)}))}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach((e=>{this.scene.removeLensFlareSystem(e),t&&e.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;Ue.S0.StartPerformanceCounter("Lens flares",t.length>0);for(const i of t)e.layerMask&i.layerMask&&i.render();Ue.S0.EndPerformanceCounter("Lens flares",t.length>0)}}}sx._SceneComponentInitialization=e=>{let t=e._getComponent(Ut.v.NAME_LENSFLARESYSTEM);t||(t=new nx(e),e._addComponent(t))};var ox=i(54262),ax=i(45980),lx=i(19121),hx=i(72987),cx=i(75653);class ux{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 void 0!==this._depthScale?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===ux.FILTER_BLUREXPONENTIALSHADOWMAP)return void(this.useExponentialShadowMap=!0);if(e===ux.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)return void(this.useCloseExponentialShadowMap=!0);if(e===ux.FILTER_PCF||e===ux.FILTER_PCSS)return void(this.usePoissonSampling=!0)}e!==ux.FILTER_PCF&&e!==ux.FILTER_PCSS||this._scene.getEngine()._features.supportShadowSamplers?this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty()):this.usePoissonSampling=!0}get usePoissonSampling(){return this.filter===ux.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(ux.FILTER_POISSONSAMPLING);(e||this.filter===ux.FILTER_POISSONSAMPLING)&&(this.filter=e?t:ux.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===ux.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(ux.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===ux.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:ux.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===ux.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(ux.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===ux.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:ux.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===ux.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(ux.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===ux.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:ux.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===ux.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(ux.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===ux.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:ux.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===ux.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(ux.FILTER_PCF);(e||this.filter===ux.FILTER_PCF)&&(this.filter=e?t:ux.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===ux.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(ux.FILTER_PCSS);(e||this.filter===ux.FILTER_PCSS)&&(this.filter=e?t:ux.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 this._darkness=e>=1?1:e<=0?0: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 ux.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),-1===this._shadowMap.renderList.indexOf(e)&&this._shadowMap.renderList.push(e),t)for(const t of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(t)&&this._shadowMap.renderList.push(t);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;const i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(const t of e.getChildren())this.removeShadowCaster(t);return this}getLight(){return this._light}get shaderLanguage(){return this._shaderLanguage}_getCamera(){return this._camera??this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,r,s,n=!1){this.onBeforeShadowMapRenderObservable=new z.cP,this.onAfterShadowMapRenderObservable=new z.cP,this.onBeforeShadowMapRenderMeshObservable=new z.cP,this.onAfterShadowMapRenderMeshObservable=new z.cP,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=ux.FILTER_NONE,this._filteringQuality=ux.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this._shaderLanguage=0,this.forceBackFacesOnly=!1,this._lightDirection=W.Pq.Zero(),this._viewMatrix=W.uq.Zero(),this._projectionMatrix=W.uq.Zero(),this._transformMatrix=W.uq.Zero(),this._cachedPosition=new W.Pq(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new W.Pq(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=W.uq.Identity(),this._shadersLoaded=!1,this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=r??null,this._useRedTextureType=!!s,this._initShaderSourceAsync(n);let o=t._shadowGenerators;o||(o=t._shadowGenerators=new Map),o.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),ux._SceneComponentInitialization(this._scene);const a=this._scene.getEngine().getCaps();i?a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:a.textureFloatRender&&a.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 ln.$(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 ln.$(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),null===this._shadowMap)return;this._shadowMap.wrapU=vi.g.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=vi.g.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(vi.g.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(e,t,i,r)=>this._renderForShadowMap(e,t,i,r),this._shadowMap.customIsReadyFunction=()=>!0;const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add((()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._debugPushGroup?.(`shadow map generation for pass id ${e.currentRenderPassId}`,1)})),this._shadowMap.onBeforeRenderObservable.add((t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=t,this._filter===ux.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((()=>{if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===ux.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap)return void e._debugPopGroup?.(1);const t=this.getShadowMapForRendering();t&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,t.renderTarget,!0),e.unBindFramebuffer(t.renderTarget,!0)),e._debugPopGroup?.(1)}));const t=new H.ov(0,0,0,0),i=new H.ov(1,1,1,1);this._shadowMap.onClearObservable.add((e=>{this._filter===ux.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)})),this._shadowMap.onResizeObservable.add((e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}));for(let e=cx.m.MIN_RENDERINGGROUPS;e{e.setTexture("textureSampler",this._shadowMap)})),this._kernelBlurYPostprocess=new _m(this._light.name+"KernelBlurY",new W.I9(0,1),this.blurKernel,1,null,vi.g.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,0===this._textureType&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new ms.w(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,vi.g.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType,void 0,void 0,void 0,void 0,this._shaderLanguage),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add((e=>{e.setFloat2("screenSize",t,t),e.setTexture("textureSampler",this._shadowMap)})),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,r){let s;if(r.length)for(s=0;s{r===i||e?(r.getMeshUniformBuffer().bindToEffect(h,"Mesh"),r.transferToEffect(e?t:f)):(i.getMeshUniformBuffer().bindToEffect(h,"Mesh"),i.transferToEffect(t))})),this.forceBackFacesOnly&&n.setState(!0,0,!1,!1,o.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(h),this.onAfterShadowMapRenderMeshObservable.notifyObservers(i)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===ux.FILTER_NONE||this.filter===ux.FILTER_PCSS?this._shadowMap.updateSamplingMode(vi.g.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(vi.g.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i={useInstances:!1,...t},r=this.getShadowMap();if(!r)return void(e&&e(this));const s=r.renderList;if(!s)return void(e&&e(this));const n=[];for(const e of s)n.push(...e.subMeshes);if(0===n.length)return void(e&&e(this));let o=0;const a=()=>{if(this._scene&&this._scene.getEngine()){for(;this.isReady(n[o],i.useInstances,n[o].getMaterial()?.needAlphaBlendingForMesh(n[o].getMesh())??!1);)if(o++,o>=n.length)return void(e&&e(this));setTimeout(a,16)}};a()}forceCompilationAsync(e){return new Promise((t=>{this.forceCompilation((()=>{t()}),e)}))}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,r){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));const s=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&s.isVerticesDataPresent(st.R.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===$t.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&r?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){if(!this._shadersLoaded)return!1;const r=e.getMaterial(),s=r?.shadowDepthWrapper;if(this._opacityTexture=null,!r)return!1;const n=[];if(this._prepareShadowDefines(e,t,n,i),s){if(!s.isReadyForSubMesh(e,n,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const i=e._getDrawWrapper(void 0,!0);let s=i.effect,o=i.defines;const a=[st.R.PositionKind],l=e.getMesh();this.normalBias&&l.isVerticesDataPresent(st.R.NormalKind)&&(a.push(st.R.NormalKind),n.push("#define NORMAL"),l.nonUniformScaling&&n.push("#define NONUNIFORMSCALING"));const h=r.needAlphaTesting();if((h||r.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=r.opacityTexture:this._opacityTexture=r.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const e=r.alphaCutOff??ux.DEFAULT_ALPHA_CUTOFF;n.push("#define ALPHATEXTURE"),h&&n.push(`#define ALPHATESTVALUE ${e}${e%1==0?".":""}`),l.isVerticesDataPresent(st.R.UVKind)&&(a.push(st.R.UVKind),n.push("#define UV1")),l.isVerticesDataPresent(st.R.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(a.push(st.R.UV2Kind),n.push("#define UV2"))}const c=new Tn;if(l.useBones&&l.computeBonesUsingShaders&&l.skeleton){a.push(st.R.MatricesIndicesKind),a.push(st.R.MatricesWeightsKind),l.numBoneInfluencers>4&&(a.push(st.R.MatricesIndicesExtraKind),a.push(st.R.MatricesWeightsExtraKind));const e=l.skeleton;n.push("#define NUM_BONE_INFLUENCERS "+l.numBoneInfluencers),l.numBoneInfluencers>0&&c.addCPUSkinningFallback(0,l),e.isUsingTextureForMatrices?n.push("#define BONETEXTURE"):n.push("#define BonesPerMesh "+(e.bones.length+1))}else n.push("#define NUM_BONE_INFLUENCERS 0");const u=l.morphTargetManager;let d=0;if(u&&(d=u.numMaxInfluencers||u.numInfluencers,d>0&&(n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+d),u.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),(0,Bt.MF)(a,l,d))),(0,Ln.tv)(r,this._scene,n),t&&(n.push("#define INSTANCES"),(0,Bt.te)(a),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const e of this.customShaderOptions.defines)-1===n.indexOf(e)&&n.push(e);const f=l.bakedVertexAnimationManager;f&&f.isEnabled&&(n.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&a.push("bakedVertexAnimationSettingsInstanced"));const p=n.join("\n");if(o!==p){o=p;let e="shadowMap";const t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","morphTargetCount","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],r=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"],n=["Scene","Mesh"];if((0,Ln.TV)(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const e of this.customShaderOptions.attributes)-1===a.indexOf(e)&&a.push(e);if(this.customShaderOptions.uniforms)for(const e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(const e of this.customShaderOptions.samplers)-1===r.indexOf(e)&&r.push(e)}const l=this._scene.getEngine();s=l.createEffect(e,{attributes:a,uniformsNames:t,uniformBuffersNames:n,samplers:r,defines:p,fallbacks:c,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:d},shaderLanguage:this._shaderLanguage},l),i.setEffect(s,o)}if(!s.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(this._blurPostProcesses&&this._blurPostProcesses.length||this._initializeBlurRTTAndPostProcesses()),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady()||this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady()||this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){const i=this._scene,r=this._light;i.shadowsEnabled&&r.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===ux.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===ux.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===ux.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===ux.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),r.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const r=this._getCamera();if(!r)return;const s=this.getShadowMap();if(!s)return;i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix());const n=this.getShadowMapForRendering();this._filter===ux.FILTER_PCF?(t.setDepthStencilTexture("shadowTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),s.getSize().width,1/s.getSize().width,this.frustumEdgeFalloff,e)):this._filter===ux.FILTER_PCSS?(t.setDepthStencilTexture("shadowTexture"+e,n),t.setTexture("depthTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/s.getSize().width,this._contactHardeningLightSizeUVRatio*s.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/s.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),W.Pq.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(W.Pq.Dot(this._lightDirection,W.Pq.Up()))&&(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),W.uq.LookAtLHToRef(t,t.add(this._lightDirection),W.Pq.Up(),this._viewMatrix);const e=this.getShadowMap();if(e){const t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}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 e of t)this._shadowMap.renderList.push(e)}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();!0!==t.done;t=e.next()){const[e,i]=t.value;i===this&&this._light._shadowGenerators.delete(e)}0===this._light._shadowGenerators.size&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()}serialize(){const e={},t=this.getShadowMap();if(!t)return e;if(e.className=this.getClassName(),e.lightId=this._light.id,e.cameraId=this._camera?.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 i=0;i{throw(0,Je.n)("ShadowGeneratorSceneComponent")};var dx=i(2297),fx=i(6069);class px{get shaderLanguage(){return this._shaderLanguage}setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,r=!1,s=vi.g.TRILINEAR_SAMPLINGMODE,n=!1,o){this._shaderLanguage=0,this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._shadersLoaded=!1,this._scene=e,this._storeNonLinearDepth=r,this._storeCameraSpaceZ=n,this.isPacked=0===t,this.isPacked?this.clearColor=new H.ov(1,1,1,1):this.clearColor=new H.ov(n?1e8:1,0,0,1),this._initShaderSourceAsync(),px._SceneComponentInitialization(this._scene);const a=e.getEngine();this._camera=i,s!==vi.g.NEAREST_SAMPLINGMODE&&(1!==t||a._caps.textureFloatLinearFiltering||(s=vi.g.NEAREST_SAMPLINGMODE),2!==t||a._caps.textureHalfFloatLinearFiltering||(s=vi.g.NEAREST_SAMPLINGMODE));const l=this.isPacked||!a._features.supportExtendedTextureFormats?5:6;this._depthMap=new ln.$(o??"DepthRenderer",{width:a.getRenderWidth(),height:a.getRenderHeight()},this._scene,!1,!0,t,!1,s,void 0,void 0,void 0,l),this._depthMap.wrapU=vi.g.CLAMP_ADDRESSMODE,this._depthMap.wrapV=vi.g.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((e=>{e.clear(this.clearColor,!0,!0,!0)})),this._depthMap.onBeforeBindObservable.add((()=>{a._debugPushGroup?.("depth renderer",1)})),this._depthMap.onAfterUnbindObservable.add((()=>{a._debugPopGroup?.(1)})),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),r=this._scene,s=r.getEngine(),n=e.getMaterial();if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!n||i.infiniteDistance||n.disableDepthWrite||0===e.verticesCount||e._renderId===r.getRenderId())return;const o=i._getWorldMatrixDeterminant()<0;let a=n._getEffectiveOrientation(t);o&&(a=0===a?1:0);const l=0===a;s.setState(n.backFaceCulling,0,!1,l,this.reverseCulling?!n.cullBackFaces:n.cullBackFaces);const h=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(h.mustReturn)return;const c=s.getCaps().instancedArrays&&(null!==h.visibleInstances[e._id]&&void 0!==h.visibleInstances[e._id]||t.hasThinInstances),u=this._camera||r.activeCamera;if(this.isReady(e,c)&&u){e._renderId=r.getRenderId();const o=i._internalAbstractMeshDataInfo._materialForRenderPass?.[s.currentRenderPassId];let a=e._getDrawWrapper();!a&&o&&(a=o._getDrawWrapper());const l=u.mode===rt.ORTHOGRAPHIC_CAMERA;if(!a)return;const d=a.effect;let f,p;if(s.enableEffect(a),c||t._bind(e,d,n.fillMode),o?o.bindForSubMesh(i.getWorldMatrix(),i,e):(d.setMatrix("viewProjection",r.getTransformMatrix()),d.setMatrix("world",i.getWorldMatrix()),this._storeCameraSpaceZ&&d.setMatrix("view",r.getViewMatrix())),l?(f=!s.useReverseDepthBuffer&&s.isNDCHalfZRange?0:1,p=s.useReverseDepthBuffer&&s.isNDCHalfZRange?0:1):(f=s.useReverseDepthBuffer&&s.isNDCHalfZRange?u.minZ:s.isNDCHalfZRange?0:u.minZ,p=s.useReverseDepthBuffer&&s.isNDCHalfZRange?0:u.maxZ),d.setFloat2("depthValues",f,f+p),!o){if(n.needAlphaTesting()){const e=n.getAlphaTestTexture();e&&(d.setTexture("diffuseSampler",e),d.setMatrix("diffuseMatrix",e.getTextureMatrix()))}(0,Bt.f$)(t,d),(0,Ln.gS)(d,n,r),(0,Bt.nR)(t,d),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(d);const i=e.getMesh().bakedVertexAnimationManager;i&&i.isEnabled&&i.bind(d,c),n.pointsCloud&&d.setFloat("pointSize",n.pointSize)}t._processRendering(i,e,d,n.fillMode,h,c,((e,t)=>d.setMatrix("world",t)))}};this._depthMap.customRenderFunction=(e,t,i,r)=>{let s;if(r.length)for(s=0;s4&&(l.push(st.R.MatricesIndicesExtraKind),l.push(st.R.MatricesWeightsExtraKind)),a.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),r.numBoneInfluencers>0&&h.addCPUSkinningFallback(0,r);const e=r.skeleton;e.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(e.bones.length+1))}else a.push("#define NUM_BONE_INFLUENCERS 0");const c=r.morphTargetManager;let u=0;c&&(u=c.numMaxInfluencers||c.numInfluencers,u>0&&(a.push("#define MORPHTARGETS"),a.push("#define NUM_MORPH_INFLUENCERS "+u),c.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),(0,Bt.MF)(l,r,u))),o.pointsCloud&&a.push("#define POINTSIZE"),t&&(a.push("#define INSTANCES"),(0,Bt.te)(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES"));const d=r.bakedVertexAnimationManager;d&&d.isEnabled&&(a.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&l.push("bakedVertexAnimationSettingsInstanced")),this._storeNonLinearDepth&&a.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&a.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&a.push("#define PACKED"),(0,Ln.tv)(o,s,a);const f=e._getDrawWrapper(void 0,!0),p=f.defines,_=a.join("\n");if(p!==_){const e=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],t=["diffuseSampler","morphTargets","boneSampler","bakedVertexAnimationTexture"];(0,Ln.TV)(e),f.setEffect(i.createEffect("depth",{attributes:l,uniformsNames:e,uniformBuffersNames:[],samplers:t,defines:_,fallbacks:h,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:u},shaderLanguage:this._shaderLanguage},i))}return f.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]}}}px.ForceGLSL=!1,px._SceneComponentInitialization=e=>{throw(0,Je.n)("DepthRendererSceneComponent")};var _x=i(2449);Cs.l.ShadersStore.minmaxReduxPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#if defined(INITIAL)\nuniform sampler2D sourceTexture;uniform vec2 texSize;void main(void)\n{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);\n#ifdef DEPTH_REDUX\nfloat maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);\n#else\nfloat maxz=max(max(max(f1,f2),f3),f4);\n#endif\nglFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(MAIN)\nuniform vec2 texSize;void main(void)\n{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.);}\n#elif defined(ONEBEFORELAST)\nuniform ivec2 texSize;void main(void)\n{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.);}\n#elif defined(LAST)\nvoid main(void)\n{glFragColor=vec4(0.);if (true) { \ndiscard;}}\n#endif\n";class mx{constructor(e){this.onAfterReductionPerformed=new z.cP,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new _x.X(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{this._postProcessManager._rebuild()}))}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,r=!0){if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=r;const s=this._camera.getScene(),n=new ms.w("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,s.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,7);n.autoClear=!1,n.forceFullscreenViewport=r;let o=this._sourceTexture.getRenderWidth(),a=this._sourceTexture.getRenderHeight();n.onApply=((e,t)=>i=>{i.setTexture("sourceTexture",this._sourceTexture),i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(n);let l=1;for(;o>1||a>1;){o=Math.max(Math.round(o/2),1),a=Math.max(Math.round(a/2),1);const e=new ms.w("Reduction phase "+l,"minmaxRedux",["texSize"],null,{width:o,height:a},null,1,s.getEngine(),!1,"#define "+(1==o&&1==a?"LAST":1==o||1==a?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(e.autoClear=!1,e.forceFullscreenViewport=r,e.onApply=((e,t)=>i=>{1==e||1==t?i.setInt2("texSize",e,t):i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(e),l++,1==o&&1==a){const t=(e,t,i)=>{const r=new Float32Array(4*e*t),n={min:0,max:0};return()=>{s.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,r,!1),n.min=r[0],n.max=r[1],this.onAfterReductionPerformed.notifyObservers(n)}};e.onAfterRenderObservable.add(t(o,a,e))}}}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((()=>{const e=this._camera.getScene().getEngine();e._debugPushGroup?.("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),e._debugPopGroup?.(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 e=0;ethis._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 t=0;tt&&(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 Cx.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ&&0!==t.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0):this._shadowMaxZ=e}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 t=e.min,i=e.max;t>=i&&(t=0,i=1),t==this._minDistance&&i==this._maxDistance||this.setMinMaxDistance(t,i)})),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){return this._depthReducer?.depthRenderer?.getDepthMap().refreshRate??-1}set autoCalcDepthBoundsRefreshRate(e){this._depthReducer?.depthRenderer&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){const e=this._getCamera();if(!e)return;const t=e.minZ,i=e.maxZ||this._shadowMaxZ,r=i-t,s=this._minDistance,n=t+s*r,o=t+(this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance)*r,a=o-n,l=o/n;for(let e=0;e{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===ux.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((()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._debugPushGroup?.(`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!==ux.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,r=this._light;if(!i.shadowsEnabled||!r.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const s=this._getCamera();s&&this._shadowMaxZ<=(s.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),0===this.cascadeBlendPercentage&&(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 s=this.getShadowMap();if(!s)return;const n=s.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,0===this.cascadeBlendPercentage?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===ux.FILTER_PCF)t.setDepthStencilTexture("shadowTexture"+e,s),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n,1/n,this.frustumEdgeFalloff,e);else if(this._filter===ux.FILTER_PCSS){for(let e=0;enew Cx(e,t,void 0,i)));return void 0!==e.numCascades&&(i.numCascades=e.numCascades),void 0!==e.debug&&(i.debug=e.debug),void 0!==e.stabilizeCascades&&(i.stabilizeCascades=e.stabilizeCascades),void 0!==e.lambda&&(i.lambda=e.lambda),void 0!==e.cascadeBlendPercentage&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),void 0!==e.depthClamp&&(i.depthClamp=e.depthClamp),void 0!==e.autoCalcDepthBounds&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),void 0!==e.shadowMaxZ&&(i.shadowMaxZ=e.shadowMaxZ),void 0!==e.penumbraDarkness&&(i.penumbraDarkness=e.penumbraDarkness),void 0!==e.freezeShadowCastersBoundingInfo&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),void 0!==e.minDistance&&void 0!==e.maxDistance&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}}Cx._FrustumCornersNDCSpace=[new W.Pq(-1,1,-1),new W.Pq(1,1,-1),new W.Pq(1,-1,-1),new W.Pq(-1,-1,-1),new W.Pq(-1,1,1),new W.Pq(1,1,1),new W.Pq(1,-1,1),new W.Pq(-1,-1,1)],Cx.CLASSNAME="CascadedShadowGenerator",Cx.DEFAULT_CASCADES_COUNT=4,Cx.MIN_CASCADES_COUNT=2,Cx.MAX_CASCADES_COUNT=4,Cx._SceneComponentInitialization=e=>{throw(0,Je.n)("ShadowGeneratorSceneComponent")},ci(Ut.v.NAME_SHADOWGENERATOR,((e,t)=>{if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(let i=0,r=e.shadowGenerators.length;i{let t=e._getComponent(Ut.v.NAME_SHADOWGENERATOR);t||(t=new yx(e),e._addComponent(t))};var Ex=i(89778),Px=i(90396),Ax=i(32472),Rx=i(17836),Ix=i(42451),Mx=i(32166),Ox=i(16845),Dx=i(19893);Ze.b.AddNodeConstructor("Light_Type_0",((e,t)=>()=>new wx(e,W.Pq.Zero(),t)));class wx extends lm{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 e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.recreateShadowMap()}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return $t.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new W.Pq(1,0,0);case 1:return new W.Pq(-1,0,0);case 2:return new W.Pq(0,-1,0);case 3:return new W.Pq(0,1,0);case 4:return new W.Pq(0,0,1);case 5:return new W.Pq(0,0,-1)}return W.Pq.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const r=this.getScene().activeCamera;if(!r)return;const s=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,n=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;W.uq.PerspectiveFovLHToRef(this.shadowAngle,1,o?n:s,o?s: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}}(0,je.Cg)([(0,$e.lK)()],wx.prototype,"shadowAngle",null),(0,X.Y5)("BABYLON.PointLight",wx);class Nx{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{const e=this._renderingCanvas.getBoundingClientRect(),t=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position="fixed"===t?"fixed":"absolute",this._loadingDiv.style.left=e.left+"px",this._loadingDiv.style.top=e.top+"px",this._loadingDiv.style.width=e.width+"px",this._loadingDiv.style.height=e.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",this._style.innerHTML="@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }",document.getElementsByTagName("head")[0].appendChild(this._style);const e=!!window.SVGSVGElement,t=new Image;Nx.DefaultLogoUrl?t.src=Nx.DefaultLogoUrl:t.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",t.style.width="150px",t.style.gridColumn="1",t.style.gridRow="1",t.style.top="50%",t.style.left="50%",t.style.transform="translate(-50%, -50%)",t.style.position="absolute";const i=document.createElement("div");i.style.width="300px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";const r=new Image;if(Nx.DefaultSpinnerUrl?r.src=Nx.DefaultSpinnerUrl:r.src=e?"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.transformOrigin="50% 50%",!e){const e={w:16,h:18.5},i={w:30,h:30};t.style.width=`${e.w}vh`,t.style.height=`${e.h}vh`,t.style.left=`calc(50% - ${e.w/2}vh)`,t.style.top=`calc(50% - ${e.h/2}vh)`,r.style.width=`${i.w}vh`,r.style.height=`${i.h}vh`,r.style.left=`calc(50% - ${i.w/2}vh)`,r.style.top=`calc(50% - ${i.h/2}vh)`}i.appendChild(r),this._loadingDiv.appendChild(t),this._loadingDiv.appendChild(i),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){this._loadingDiv&&(this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",(()=>{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)})))}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)}}Nx.DefaultLogoUrl="",Nx.DefaultSpinnerUrl="",Ot.$.DefaultLoadingScreenFactory=e=>new Nx(e);var Fx=i(22377),Lx=i(82266);class Bx{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=(0,ar.ILog2)(t)+1,r=this._effectWrapper.effect,s=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 hc.Pq(0,0,-1),new hc.Pq(0,-1,0),new hc.Pq(1,0,0)],[new hc.Pq(0,0,1),new hc.Pq(0,-1,0),new hc.Pq(-1,0,0)],[new hc.Pq(1,0,0),new hc.Pq(0,0,1),new hc.Pq(0,1,0)],[new hc.Pq(1,0,0),new hc.Pq(0,0,-1),new hc.Pq(0,-1,0)],[new hc.Pq(1,0,0),new hc.Pq(0,-1,0),new hc.Pq(0,0,1)],[new hc.Pq(-1,0,0),new hc.Pq(0,-1,0),new hc.Pq(0,0,-1)]];r.setFloat("hdrScale",this.hdrScale),r.setFloat2("vFilteringInfo",e.getSize().width,i),r.setTexture("inputTexture",e);for(let e=0;e<6;e++){r.setVector3("up",o[e][0]),r.setVector3("right",o[e][1]),r.setVector3("front",o[e][2]);for(let n=0;n{s?await Promise.all([Promise.resolve().then(i.bind(i,44623)),Promise.resolve().then(i.bind(i,17477))]):await Promise.all([Promise.resolve().then(i.bind(i,77318)),Promise.resolve().then(i.bind(i,80424))])}})}isReady(e){return e.isReady()&&this._effectWrapper.effect.isReady()}prefilter(e,t=null){return this._engine._features.allowTexturePrefiltering?new Promise((i=>{this._effectRenderer=new Yp.J(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled((()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()}))})):(Z.V.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 Vx extends js.t{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(W.uq.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,r=!1,s=!0,n=!1,o=!1,a=null,l=null,h=!1){super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=W.Pq.Zero(),this.onLoadObservable=new z.cP,e&&(this._coordinatesMode=vi.g.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=W.uq.Identity(),this._prefilterOnLoad=o,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),a&&a()},this._onError=l,this.gammaSpace=n,this._noMipmap=r,this._size=i,this._supersample=h,this._generateHarmonics=s,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?Ue.S0.SetImmediate((()=>this._onLoad())):this._texture.onLoadedObservable.add(this._onLoad):this.getScene()?.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture())}getClassName(){return"HDRCubeTexture"}_loadTexture(){const e=this._getEngine(),t=e.getCaps();let i=0;if(t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2),e._features.allowTexturePrefiltering&&this._prefilterOnLoad){const t=this._onLoad,i=new Bx(e);this._onLoad=()=>{i.prefilter(this,t)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,(e=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;const t=(0,Fx.VH)(e,this._size,this._supersample);if(this._generateHarmonics){const e=Lx.d.ConvertCubeMapToSphericalPolynomial(t);this.sphericalPolynomial=e}const r=[];let s=null,n=null;for(let e=0;e<6;e++){2===i?n=new Uint16Array(this._size*this._size*3):0===i&&(s=new Uint8Array(this._size*this._size*3));const o=t[Vx._FacesMapping[e]];if(this.gammaSpace||n||s)for(let e=0;e255){const e=255/n;t*=e,i*=e,r*=e}s[3*e+0]=t,s[3*e+1]=i,s[3*e+2]=r}n?r.push(n):s?r.push(s):r.push(o)}return r}),null,this._onLoad,this._onError)}clone(){const e=new Vx(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(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this._loadTexture())}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&this.getScene()?.markAllMaterialsAsDirty(1,(e=>-1!==e.getActiveTextures().indexOf(this)))}dispose(){this.onLoadObservable.clear(),super.dispose()}static Parse(e,t,i){let r=null;return e.name&&!e.isRenderTarget&&(r=new Vx(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace),r.name=e.name,r.hasAlpha=e.hasAlpha,r.level=e.level,r.coordinatesMode=e.coordinatesMode,r.isBlocking=e.isBlocking),r&&(e.boundingBoxPosition&&(r.boundingBoxPosition=W.Pq.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=W.Pq.FromArray(e.boundingBoxSize)),e.rotationY&&(r.rotationY=e.rotationY)),r}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e}}Vx._FacesMapping=["right","left","up","down","front","back"],(0,X.Y5)("BABYLON.HDRCubeTexture",Vx);class kx{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(0===t||0===e)}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 z.cP,this._onDataLayoutChanged=new z.cP,this._animationPropertiesOverride=null,this.id=e,this._scene=i||he.q.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=it.p.Clone((()=>new kx(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()),null!=this.id&&(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())),it.p.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new kx(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(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 t=0;t0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new Qe.L(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._numMaxInfluencers=0,this._useTextureToStoreTargets=!0,e||(e=he.q.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();const e=this._scene.getEngine().getCaps();this._canUseTextureForTargets=e.canUseGLVertexID&&e.textureFloat&&e.maxVertexTextureImageUnits>0&&e.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(){return Gx.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!this._scene?.getEngine().getCaps().disableMorphTargetTexture}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}getTargetByName(e){for(const t of this._targets)if(t.name===e)return t;return null}addTarget(e){this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add((e=>{this._syncActiveTargets(e)}))),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 Gx(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 e of this._targets){if(i++,0===e.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=Gx.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(e),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=e.influence,this._supportsNormals=this._supportsNormals&&e.hasNormals,this._supportsTangents=this._supportsTangents&&e.hasTangents,this._supportsUVs=this._supportsUVs&&e.hasUVs;const r=e.getPositions();if(r){const e=r.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e)return void Z.V.Error("Incompatible target. Targets must all have the same vertices count.")}}this._morphTargetTextureIndices.length!==t&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,t)),this._influences&&this._influences.length===t||(this._influences=new Float32Array(t));for(let e=0;e0)){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 e=this._targetStoreTexture.getSize();e.width===this._textureWidth&&e.height===this._textureHeight&&this._targetStoreTexture.depth===this._targets.length&&(t=!1)}if(t){this._targetStoreTexture&&this._targetStoreTexture.dispose();const e=this._targets.length,t=new Float32Array(e*this._textureWidth*this._textureHeight*4);let i=0;for(let r=0;r-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 Gx(t);for(const r of e.targets)i.addTarget(kx.Parse(r,t));return i}}Gx.EnableTextureStorage=!0,Gx.MaxActiveMorphTargetsInVertexAttributeMode=8;class zx{constructor(){this._hasHit=!1,this._hitNormal=W.Pq.Zero(),this._hitPoint=W.Pq.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 Wx extends zx{constructor(){super(...arguments),this._hitDistance=0,this._rayFromWorld=W.Pq.Zero(),this._rayToWorld=W.Pq.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=W.Pq.Distance(this._rayFromWorld,this._hitPoint)}reset(e=W.Pq.Zero(),t=W.Pq.Zero()){super.reset(),this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hitDistance=0}}class Hx{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw(0,Je.n)("CannonJSPlugin")}constructor(e,t=Hx.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 W.Pq(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._impostors.forEach((function(e){e.dispose()})),this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}addImpostor(e){this._impostors.push(e),e.uniqueId=this._uniqueIdCounter++,e.parent||this._physicsPlugin.generatePhysicsBody(e)}removeImpostor(e){const t=this._impostors.indexOf(e);t>-1&&this._impostors.splice(t,1).length&&this.getPhysicsPlugin().removePhysicsBody(e)}addJoint(e,t,i){const r={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(r),this._physicsPlugin.generateJoint(r)}removeJoint(e,t,i){const r=this._joints.filter((function(r){return r.connectedImpostor===t&&r.joint===i&&r.mainImpostor===e}));r.length&&this._physicsPlugin.removeJoint(r[0])}_step(e){this._impostors.forEach((e=>{e.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(e)})),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=>{"function"==typeof this.world.removeBody?this.world.removeBody(e):this.world.remove(e)})),this._physicsBodiesToRemoveAfterStep.length=0)}applyImpulse(e,t,i){const r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(s,r)}applyForce(e,t,i){const r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(s,r)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){const t=this._createShape(e);if(!t)return void Z.V.Warn("It was not possible to create a physics body for this object.");const i=e.physicsBody;i&&this.removePhysicsBody(e);const r=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),s={mass:e.getParam("mass"),material:r},n=e.getParam("nativeOptions");for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(s[e]=n[e]);e.physicsBody=new this.BJSCANNON.Body(s),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),"function"==typeof this.world.addBody?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach((function(t){const r=i[t];e.physicsBody[t].set(r.x,r.y,r.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 i=t=>{if(!t.rotationQuaternion)return;const r=t.getPhysicsImpostor();if(r&&r.parent!==e&&t.parent){const i=t.getAbsolutePosition().subtract(t.parent.getAbsolutePosition()),s=t.rotationQuaternion.multiply(this._tmpQuaternion);r.physicsBody&&(this.removePhysicsBody(r),r.physicsBody=null),r.parent=e,r.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(r),new this.BJSCANNON.Vec3(i.x,i.y,i.z),new this.BJSCANNON.Quaternion(s.x,s.y,s.z,s.w)),e.physicsBody.mass+=r.getParam("mass")}t.getChildMeshes(!0).filter((e=>!!e.physicsImpostor)).forEach(i)};t.filter((e=>!!e.physicsImpostor)).forEach(i)}}removePhysicsBody(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),-1===this._physicsBodiesToRemoveAfterStep.indexOf(e.physicsBody)&&this._physicsBodiesToRemoveAfterStep.push(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;let r;const s=e.joint.jointData,n={pivotA:s.mainPivot?(new this.BJSCANNON.Vec3).set(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z):null,pivotB:s.connectedPivot?(new this.BJSCANNON.Vec3).set(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z):null,axisA:s.mainAxis?(new this.BJSCANNON.Vec3).set(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z):null,axisB:s.connectedAxis?(new this.BJSCANNON.Vec3).set(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z):null,maxForce:s.nativeParams.maxForce,collideConnected:!!s.collision};switch(e.joint.type){case Jo.HingeJoint:case Jo.Hinge2Joint:r=new this.BJSCANNON.HingeConstraint(t,i,n);break;case Jo.DistanceJoint:r=new this.BJSCANNON.DistanceConstraint(t,i,s.maxDistance||2);break;case Jo.SpringJoint:{const e=s;r=new this.BJSCANNON.Spring(t,i,{restLength:e.length,stiffness:e.stiffness,damping:e.damping,localAnchorA:n.pivotA,localAnchorB:n.pivotB});break}case Jo.LockJoint:r=new this.BJSCANNON.LockConstraint(t,i,n);break;case Jo.PointToPointJoint:case Jo.BallAndSocketJoint:default:r=new this.BJSCANNON.PointToPointConstraint(t,n.pivotA,i,n.pivotB,n.maxForce)}r.collideConnected=!!s.collision,e.joint.physicsJoint=r,e.joint.type!==Jo.SpringJoint?this.world.addConstraint(r):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){r.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==Jo.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let r,s;for(r=0;r1e3*i));e++);this.time+=r;const a=this.time%i/i,l=e,h=this.bodies;for(let e=0;e!==h.length;e++){const i=h[e];i.type!==t.Body.STATIC&&i.sleepState!==t.Body.SLEEPING?(i.position.vsub(i.previousPosition,l),l.scale(a,l),i.position.vadd(l,i.interpolatedPosition)):(i.interpolatedPosition.set(i.position.x,i.position.y,i.position.z),i.interpolatedQuaternion.set(i.quaternion.x,i.quaternion.y,i.quaternion.z,i.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))}}Hx.DefaultPluginFactory=()=>new Xx;class qx{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=W.Pq.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new Wx}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(e){e.beforeStep()})),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach((e=>{e.afterStep(),this._tmpImpostorsArray[e.uniqueId]=e}));let i=this.world.contacts;for(;null!==i;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}const e=this._tmpImpostorsArray[+i.body1.name],t=this._tmpImpostorsArray[+i.body2.name];e&&t?(e.onCollide({body:t.physicsBody,point:null,distance:0,impulse:0,normal:null}),t.onCollide({body:e.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next):i=i.next}}applyImpulse(e,t,i){const r=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*r))}applyForce(e,t,i){Z.V.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());else{if(e.isBodyInitRequired()){const i={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},r=[e];(t=e.object).getChildMeshes&&t.getChildMeshes().forEach((function(e){e.physicsImpostor&&r.push(e.physicsImpostor)}));const s=e=>Math.max(e,lt.bH),n=new W.PT;r.forEach((t=>{if(!t.object.rotationQuaternion)return;const r=t.object.rotationQuaternion;n.copyFrom(r),t.object.rotationQuaternion.set(0,0,0,1),t.object.computeWorldMatrix(!0);const o=n.toEulerAngles(),a=t.getObjectExtents(),l=57.29577951308232;if(t===e){const t=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(t,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),i.pos.push(t.x),i.pos.push(t.y),i.pos.push(t.z),i.posShape.push(0,0,0),i.rotShape.push(0,0,0)}else{const e=t.object.position.clone();i.posShape.push(e.x),i.posShape.push(e.y),i.posShape.push(e.z),i.rotShape.push(o.x*l,o.y*l,o.z*l)}switch(t.object.rotationQuaternion.copyFrom(n),t.type){case sa.ParticleImpostor:Z.V.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case sa.SphereImpostor:{const e=a.x,t=a.y,r=a.z,n=Math.max(s(e),s(t),s(r))/2;i.type.push("sphere"),i.size.push(n),i.size.push(n),i.size.push(n);break}case sa.CylinderImpostor:{const e=s(a.x)/2,t=s(a.y);i.type.push("cylinder"),i.size.push(e),i.size.push(t),i.size.push(t);break}case sa.PlaneImpostor:case sa.BoxImpostor:default:{const e=s(a.x),t=s(a.y),r=s(a.z);i.type.push("box"),i.size.push(e),i.size.push(t),i.size.push(r);break}}t.object.rotationQuaternion=r})),e.physicsBody=this.world.add(i),e.physicsBody.resetQuaternion(n),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpPositionVector)}var t}removePhysicsBody(e){this.world.removeRigidBody(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const r=e.joint.jointData,s=r.nativeParams||{};let n;const o={body1:t,body2:i,axe1:s.axe1||(r.mainAxis?r.mainAxis.asArray():null),axe2:s.axe2||(r.connectedAxis?r.connectedAxis.asArray():null),pos1:s.pos1||(r.mainPivot?r.mainPivot.asArray():null),pos2:s.pos2||(r.connectedPivot?r.connectedPivot.asArray():null),min:s.min,max:s.max,collision:s.collision||r.collision,spring:s.spring,world:this.world};switch(e.joint.type){case Jo.BallAndSocketJoint:n="jointBall";break;case Jo.SpringJoint:{Z.V.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");const e=r;o.min=e.length||o.min,o.max=Math.max(o.min,o.max)}case Jo.DistanceJoint:n="jointDistance",o.max=r.maxDistance;break;case Jo.PrismaticJoint:n="jointPrisme";break;case Jo.SliderJoint:n="jointSlide";break;case Jo.WheelJoint:n="jointWheel";break;case Jo.HingeJoint:default:n="jointHinge"}o.type=n,e.joint.physicsJoint=this.world.add(o)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(e){Z.V.Warn(e)}}isSupported(){return void 0!==this.BJSOIMO}setTransformationFromPhysicsBody(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){let t=e.physicsBody.shapes;for(;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{const t=e.physicsBody.getPosition();e.object.position.set(t.x,t.y,t.z)}if(e.object.rotationQuaternion){const t=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}}setPhysicsBodyTransformation(e,t,i){const r=e.physicsBody;e.physicsBody.shapes.next||(r.position.set(t.x,t.y,t.z),r.orientation.set(i.x,i.y,i.z,i.w),r.syncShapes(),r.awake())}setLinearVelocity(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){const t=e.physicsBody.linearVelocity;return t?new W.Pq(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new W.Pq(t.x,t.y,t.z):null}setBodyMass(e,t){const i=0===t;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,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,r){void 0!==i?Z.V.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;const s=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setMotor(t,i)}setLimit(e,t,i,r){const s=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setLimit(t,void 0===i?-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=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth}dispose(){this.world.clear()}raycast(e,t){return Z.V.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){Z.V.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class Yx{constructor(e=!0,t=Ammo,i=null){this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new W.PT,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new W.Pq,this._tmpContactNormal=new W.Pq,this._tmpVec3=new W.Pq,this._tmpMatrix=new W.uq,"function"!=typeof t?(this.bjsAMMO=t,this.isSupported()?(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=e=>{const t=(e=this.bjsAMMO.wrapPointer(e,this.bjsAMMO.btManifoldPoint)).getPositionWorldOnA(),i=e.m_normalWorldOnB;this._tmpContactPoint.x=t.x(),this._tmpContactPoint.y=t.y(),this._tmpContactPoint.z=t.z(),this._tmpContactNormal.x=i.x(),this._tmpContactNormal.y=i.y(),this._tmpContactNormal.z=i.z(),this._tmpContactImpulse=e.getAppliedImpulse(),this._tmpContactDistance=e.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new Wx,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)):Z.V.Error("AmmoJS is not available. Please make sure you included the js file.")):Z.V.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.")}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(0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i0&&this._isImpostorInContact(e))for(const t of e._onPhysicsCollideCallbacks)for(const i of t.otherImpostors)(e.physicsBody.isActive()||i.physicsBody.isActive())&&this._isImpostorPairInContact(e,i)&&(e.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),i.onCollide({body:e.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===sa.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){const t=e.physicsBody.get_m_nodes(),i=t.size();let r,s,n,o,a;const l=new Array;for(let e=0;e{this.bjsAMMO.destroy(e)})),e._pluginData.toDispose=[]))}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;if(e.joint.physicsJoint)return;const r=e.joint.jointData;let s;switch(r.mainPivot||(r.mainPivot=new W.Pq(0,0,0)),r.connectedPivot||(r.connectedPivot=new W.Pq(0,0,0)),e.joint.type){case Jo.DistanceJoint:{const e=r.maxDistance;e&&(r.mainPivot=new W.Pq(0,-e/2,0),r.connectedPivot=new W.Pq(0,e/2,0));const n=this._tmpAmmoVectorA;n.setValue(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z);const o=this._tmpAmmoVectorB;o.setValue(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z),s=new this.bjsAMMO.btPoint2PointConstraint(t,i,n,o);break}case Jo.HingeJoint:{r.mainAxis||(r.mainAxis=new W.Pq(0,0,0)),r.connectedAxis||(r.connectedAxis=new W.Pq(0,0,0));const e=this._tmpAmmoVectorA;e.setValue(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z);const n=this._tmpAmmoVectorB;n.setValue(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z);const o=this._tmpAmmoVectorC;o.setValue(r.mainAxis.x,r.mainAxis.y,r.mainAxis.z);const a=this._tmpAmmoVectorD;a.setValue(r.connectedAxis.x,r.connectedAxis.y,r.connectedAxis.z),s=new this.bjsAMMO.btHingeConstraint(t,i,e,n,o,a);break}case Jo.BallAndSocketJoint:{const e=this._tmpAmmoVectorA;e.setValue(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z);const n=this._tmpAmmoVectorB;n.setValue(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z),s=new this.bjsAMMO.btPoint2PointConstraint(t,i,e,n);break}default:{Z.V.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint");const e=this._tmpAmmoVectorA;e.setValue(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z);const n=this._tmpAmmoVectorB;n.setValue(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z),s=new this.bjsAMMO.btPoint2PointConstraint(t,i,e,n);break}}this.world.addConstraint(s,!e.joint.jointData.collision),e.joint.physicsJoint=s}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint),this.bjsAMMO.destroy(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let n,o=i.getVerticesData(st.R.PositionKind);if(o||(o=[]),t&&t!==i){let e;e=t.rotationQuaternion?t.rotationQuaternion:t.rotation?W.PT.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):W.PT.Identity(),W.uq.Compose(W.Pq.One(),e,t.position).invertToRef(this._tmpMatrix),n=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else W.uq.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),n=this._tmpMatrix;const a=s.length/3;for(let t=0;t{r+=this._addMeshVerts(e,t,i)}))}return r}_softVertexData(e){const t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){let e=t.getIndices();e||(e=[]);let i=t.getVerticesData(st.R.PositionKind);i||(i=[]);let r=t.getVerticesData(st.R.NormalKind);r||(r=[]),t.computeWorldMatrix(!1);const s=[],n=[];for(let e=0;ee*e)).reduce(((e,t)=>e+t)))t=s.length,i=t/3-1,this._tmpAmmoVectorA.setValue(s[0],s[1],s[2]),this._tmpAmmoVectorB.setValue(s[t-3],s[t-2],s[t-1]);else{e._isFromLine=!1;const r=e.getParam("path");if(null===e.getParam("shape"))return Z.V.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;t=r.length,i=t-1,this._tmpAmmoVectorA.setValue(r[0].x,r[0].y,r[0].z),this._tmpAmmoVectorB.setValue(r[t-1].x,r[t-1].y,r[t-1].z)}e.segments=i;let o=e.getParam("fixedPoints");o=o>3?3:o;const a=(new this.bjsAMMO.btSoftBodyHelpers).CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,o);return a.get_m_cfg().set_collisions(17),a}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),null==t&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let n=i.getVerticesData(st.R.PositionKind);n||(n=[]),i.computeWorldMatrix(!1);const o=s.length/3;for(let t=0;t{r+=this._addHullVerts(e,t,i)}))}return r}_createShape(e,t=!1){const i=e.object;let r;const s=e.getObjectExtents();if(!t){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];r=new this.bjsAMMO.btCompoundShape;let i=0;if(t.forEach((e=>{const t=e.getPhysicsImpostor();if(t){if(t.type==sa.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";const s=this._createShape(t),n=e.parent.getWorldMatrix().clone(),o=new W.Pq;n.decompose(o),this._tmpAmmoTransform.getOrigin().setValue(e.position.x*o.x,e.position.y*o.y,e.position.z*o.z),this._tmpAmmoQuaternion.setValue(e.rotationQuaternion.x,e.rotationQuaternion.y,e.rotationQuaternion.z,e.rotationQuaternion.w),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),r.addChildShape(this._tmpAmmoTransform,s),t.dispose(),i++}})),i>0){if(e.type!=sa.NoImpostor){const t=this._createShape(e,!0);t&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),r.addChildShape(this._tmpAmmoTransform,t))}return r}this.bjsAMMO.destroy(r),r=null}switch(e.type){case sa.SphereImpostor:if((0,ar.WithinEpsilon)(s.x,s.y,1e-4)&&(0,ar.WithinEpsilon)(s.x,s.z,1e-4))r=new this.bjsAMMO.btSphereShape(s.x/2);else{this._tmpAmmoVectorA.setValue(0,0,0);const e=[this._tmpAmmoVectorA],t=[1];r=new this.bjsAMMO.btMultiSphereShape(e,t,1),this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),r.setLocalScaling(this._tmpAmmoVectorA)}break;case sa.CapsuleImpostor:{const e=s.x/2;r=new this.bjsAMMO.btCapsuleShape(e,s.y-2*e)}break;case sa.CylinderImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),r=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case sa.PlaneImpostor:case sa.BoxImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),r=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case sa.MeshImpostor:if(0==e.getParam("mass")){if(this.onCreateCustomMeshImpostor)r=this.onCreateCustomMeshImpostor(e);else{const t=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(t);const s=this._addMeshVerts(t,i,i);r=0==s?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(t)}break}case sa.ConvexHullImpostor:if(this.onCreateCustomConvexHullImpostor)r=this.onCreateCustomConvexHullImpostor(e);else{const t=new this.bjsAMMO.btConvexHullShape;0==this._addHullVerts(t,i,i)?(e._pluginData.toDispose.push(t),r=new this.bjsAMMO.btCompoundShape):r=t}break;case sa.NoImpostor:r=new this.bjsAMMO.btSphereShape(s.x/2);break;case sa.CustomImpostor:r=this._createCustom(e);break;case sa.SoftbodyImpostor:r=this._createSoftbody(e);break;case sa.ClothImpostor:r=this._createCloth(e);break;case sa.RopeImpostor:r=this._createRope(e);break;default:Z.V.Warn("The impostor type is not currently supported by the ammo plugin.")}return r}setTransformationFromPhysicsBody(e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),e.object.rotationQuaternion?e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):e.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))}setPhysicsBodyTransformation(e,t,i){const r=e.physicsBody.getWorldTransform();if(Math.abs(r.getOrigin().x()-t.x)>lt.bH||Math.abs(r.getOrigin().y()-t.y)>lt.bH||Math.abs(r.getOrigin().z()-t.z)>lt.bH||Math.abs(r.getRotation().x()-i.x)>lt.bH||Math.abs(r.getRotation().y()-i.y)>lt.bH||Math.abs(r.getRotation().z()-i.z)>lt.bH||Math.abs(r.getRotation().w()-i.w)>lt.bH)if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),r.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),r.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(r),0==e.mass){const t=e.physicsBody.getMotionState();t&&t.setWorldTransform(r)}else e.physicsBody.activate()}isSupported(){return void 0!==this.bjsAMMO}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(t=e.soft?e.physicsBody.linearVelocity():e.physicsBody.getLinearVelocity(),!t)return null;const i=new W.Pq(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}getAngularVelocity(e){let t;if(t=e.soft?e.physicsBody.angularVelocity():e.physicsBody.getAngularVelocity(),!t)return null;const i=new W.Pq(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:(Z.V.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===sa.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):Z.V.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(Z.V.Warn("Stiffness is not a property of a rigid body"),0)}setBodyStiffness(e,t){e.soft?(t=(t=t<0?0:t)>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):Z.V.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(Z.V.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):Z.V.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(Z.V.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):Z.V.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,r,s=1,n=!1){const o=e.segments,a=Math.round((o-1)*i)+o*(o-1-Math.round((o-1)*r));e.physicsBody.appendAnchor(a,t.physicsBody,n,s)}appendHook(e,t,i,r=1,s=!1){const n=Math.round(e.segments*i);e.physicsBody.appendAnchor(n,t.physicsBody,s,r)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){Z.V.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){Z.V.Warn("setLimit is not currently supported by the Ammo physics plugin")}syncMeshWithImpostor(e,t){t.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.position.x=this._tmpAmmoTransform.getOrigin().x(),e.position.y=this._tmpAmmoTransform.getOrigin().y(),e.position.z=this._tmpAmmoTransform.getOrigin().z(),e.rotationQuaternion&&(e.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),e.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),e.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),e.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())}getRadius(e){return e.getObjectExtents().x/2}getBoxSizeToRef(e,t){const i=e.getObjectExtents();t.x=i.x,t.y=i.y,t.z=i.z}dispose(){this.bjsAMMO.destroy(this.world),this.bjsAMMO.destroy(this._softBodySolver),this.bjsAMMO.destroy(this._solver),this.bjsAMMO.destroy(this._overlappingPairCache),this.bjsAMMO.destroy(this._dispatcher),this.bjsAMMO.destroy(this._collisionConfiguration),this.bjsAMMO.destroy(this._tmpAmmoVectorA),this.bjsAMMO.destroy(this._tmpAmmoVectorB),this.bjsAMMO.destroy(this._tmpAmmoVectorC),this.bjsAMMO.destroy(this._tmpAmmoVectorD),this.bjsAMMO.destroy(this._tmpAmmoTransform),this.bjsAMMO.destroy(this._tmpAmmoQuaternion),this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null}raycast(e,t){return this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(e.x,e.y,e.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(t.x,t.y,t.z);const r=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,r),i.reset(e,t),r.hasHit()&&(i.setHitData({x:r.get_m_hitNormalWorld().x(),y:r.get_m_hitNormalWorld().y(),z:r.get_m_hitNormalWorld().z()},{x:r.get_m_hitPointWorld().x(),y:r.get_m_hitPointWorld().y(),z:r.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(r),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}}Yx._DISABLE_COLLISION_FLAG=4,Yx._KINEMATIC_FLAG=2,Yx._DISABLE_DEACTIVATION_FLAG=4,oi.Z.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return-1;const t=this.reflectionProbes.indexOf(e);return-1!==t&&this.reflectionProbes.splice(t,1),t},oi.Z.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};class Kx{constructor(e,t,i,r=!0,s=!1,n=!1){if(this.name=e,this._viewMatrix=W.uq.Identity(),this._target=W.Pq.Zero(),this._add=W.Pq.Zero(),this._invertYAxis=!1,this.position=W.Pq.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(let t=0;t<6;++t)this._sceneUBOs.push(i.createSceneUniformBuffer(`Scene for Reflection Probe (name "${e}") face #${t}`))}this._scene.reflectionProbes||(this._scene.reflectionProbes=[]),this._scene.reflectionProbes.push(this);let o=0;if(s){const e=this._scene.getEngine().getCaps();e.textureHalfFloatRender?o=2:e.textureFloatRender&&(o=1)}this._renderTargetTexture=new ln.$(e,t,i,r,!0,o,!0),this._renderTargetTexture.gammaSpace=!n,this._renderTargetTexture.invertZ=i.useRightHandedSystem;const a=i.getEngine().useReverseDepthBuffer;let l;this._renderTargetTexture.onBeforeRenderObservable.add((e=>{switch(this._sceneUBOs&&(i.setSceneUniformBuffer(this._sceneUBOs[e]),i.getSceneUniformBuffer().unbindEffect()),e){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)}this._attachedMesh&&this.position.copyFrom(this._attachedMesh.getAbsolutePosition()),this.position.addToRef(this._add,this._target);const t=i.useRightHandedSystem?W.uq.LookAtRHToRef:W.uq.LookAtLHToRef,r=i.useRightHandedSystem?W.uq.PerspectiveFovRH:W.uq.PerspectiveFovLH;t(this.position,this._target,W.Pq.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=r(Math.PI/2,1,a?i.activeCamera.maxZ:i.activeCamera.minZ,a?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})),this._renderTargetTexture.onBeforeBindObservable.add((()=>{this._currentSceneUBO=i.getSceneUniformBuffer(),i.getEngine()._debugPushGroup?.(`reflection probe generation for ${e}`,1),l=this._scene.imageProcessingConfiguration.applyByPostProcess,n&&(i.imageProcessingConfiguration.applyByPostProcess=!0)})),this._renderTargetTexture.onAfterUnbindObservable.add((()=>{i.imageProcessingConfiguration.applyByPostProcess=l,i._forcedViewPosition=null,this._sceneUBOs&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(!0),i.getEngine()._debugPopGroup?.(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(-1!==e&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){const e=this._parentContainer.reflectionProbes.indexOf(this);e>-1&&this._parentContainer.reflectionProbes.splice(e,1),this._parentContainer=null}if(this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null),this._sceneUBOs){for(const e of this._sceneUBOs)e.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=it.p.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let r=null;if(t.reflectionProbes)for(let i=0;ir||new Kx(e.name,e.renderTargetSize,t,e._generateMipMaps)),e,t,i),r.cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&r.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(r.metadata=e.metadata),r}}(0,je.Cg)([(0,$e.xG)()],Kx.prototype,"_attachedMesh",void 0),(0,je.Cg)([(0,$e.P_)()],Kx.prototype,"position",void 0);class jx{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,r,s){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=r||1,this._animationStarted=!0,this._onBaseAnimationEnd=s,ethis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}}class $x extends jx{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 z.cP,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new H.ov(1,1,1,1),this.position=W.Pq.Zero(),this._manager=t,this._manager.sprites.push(this),this.uniqueId=this._manager.scene.getUniqueId()}getClassName(){return"Sprite"}get fromIndex(){return this._fromIndex}set fromIndex(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)}get toIndex(){return this._toIndex}set toIndex(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)}get delay(){return Math.max(this._delay,1)}set delay(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)}playAnimation(e,t,i,r,s=null){this._onAnimationEnd=s,super.playAnimation(e,t,i,r,this._endAnimation)}dispose(){for(let e=0;e0)for(let n=0;n=s.distance))&&(s=a,i))break}return s||new At.G},oi.Z.prototype._internalMultiPickSprites=function(e,t,i){if(!At.G)return null;let r=[];if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let s=0;s!!e.actionManager&&e.isPickable&&e.actionManager.hasPointerTriggers}register(){this.scene._pointerMoveStage.registerStep(Ut.v.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(Ut.v.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(Ut.v.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();const e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,r,s){const n=this.scene.pickSprite(t,i,this._spritePredicate,r,s);return n&&(n.ray=e?e.ray:null),n}_pointerMove(e,t,i,r,s){const n=this.scene;return r?n.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,n.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(n.setPointerOverSprite(i.pickedSprite),!n.doNotHandleCursors&&s&&(n._pointerOverSprite&&n._pointerOverSprite.actionManager&&n._pointerOverSprite.actionManager.hoverCursor?s.style.cursor=n._pointerOverSprite.actionManager.hoverCursor:s.style.cursor=n.hoverCursor)):n.setPointerOverSprite(null),i}_pointerDown(e,t,i,r){const s=this.scene;if(s._pickedDownSprite=null,s.spriteManagers&&s.spriteManagers.length>0&&(i=s.pickSprite(e,t,this._spritePredicate,!1,s.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(s._pickedDownSprite=i.pickedSprite,r.button){case 0:i.pickedSprite.actionManager.processTrigger(2,Y.X.CreateNewFromSprite(i.pickedSprite,s,r));break;case 1:i.pickedSprite.actionManager.processTrigger(4,Y.X.CreateNewFromSprite(i.pickedSprite,s,r));break;case 2:i.pickedSprite.actionManager.processTrigger(3,Y.X.CreateNewFromSprite(i.pickedSprite,s,r))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,Y.X.CreateNewFromSprite(i.pickedSprite,s,r))}return i}_pointerUp(e,t,i,r,s){const n=this.scene;if(n.spriteManagers&&n.spriteManagers.length>0){const i=n.pickSprite(e,t,this._spritePredicate,!1,n.cameraToUseForPointers||void 0);i&&(i.hit&&i.pickedSprite&&i.pickedSprite.actionManager&&(i.pickedSprite.actionManager.processTrigger(7,Y.X.CreateNewFromSprite(i.pickedSprite,n,r)),i.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||i.pickedSprite.actionManager.processTrigger(1,Y.X.CreateNewFromSprite(i.pickedSprite,n,r)),s&&i.pickedSprite.actionManager.processTrigger(6,Y.X.CreateNewFromSprite(i.pickedSprite,n,r)))),n._pickedDownSprite&&n._pickedDownSprite.actionManager&&n._pickedDownSprite!==i.pickedSprite&&n._pickedDownSprite.actionManager.processTrigger(16,Y.X.CreateNewFromSprite(n._pickedDownSprite,n,r)))}return i}}class Zx{get fogEnabled(){return this._fogEnabled}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this._createEffects())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){const t=!!this._scene?.getEngine().getCaps().fragmentDepthSupported;e&&!t&&Z.V.Warn("Logarithmic depth has been requested for a sprite renderer on a device that doesn't support it."),this._useLogarithmicDepth=e&&t,this._createEffects()}get capacity(){return this._capacity}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(e){this._pixelPerfect!==e&&(this._pixelPerfect=e,this._createEffects())}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i=.01,r=null,s){this.blendMode=2,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this._fogEnabled=!0,this._pixelPerfect=!1,this._shaderLanguage=0,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._isDisposed=!1,this._shadersLoaded=!1,this._pixelPerfect=s?.pixelPerfect??!1,this._capacity=t,this._epsilon=i,this._engine=e,this._useInstancing=e.getCaps().instancedArrays&&e._features.supportSpriteInstancing,this._useVAO=e.getCaps().vertexArrayObject&&!e.disableVertexArrayObjects,this._scene=r,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new st.h(e,this._vertexData,!0,this._vertexBufferSize);const n=this._buffer.createVertexBuffer(st.R.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),o=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing);let a,l=6;if(this._useInstancing){const t=new Float32Array([this._epsilon,this._epsilon,1-this._epsilon,this._epsilon,this._epsilon,1-this._epsilon,1-this._epsilon,1-this._epsilon]);this._spriteBuffer=new st.h(e,t,!1,2),a=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else a=this._buffer.createVertexBuffer("offsets",l,2,this._vertexBufferSize,this._useInstancing),l+=2;const h=this._buffer.createVertexBuffer("inverts",l,2,this._vertexBufferSize,this._useInstancing),c=this._buffer.createVertexBuffer("cellInfo",l+2,4,this._vertexBufferSize,this._useInstancing),u=this._buffer.createVertexBuffer(st.R.ColorKind,l+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[st.R.PositionKind]=n,this._vertexBuffers.options=o,this._vertexBuffers.offsets=a,this._vertexBuffers.inverts=h,this._vertexBuffers.cellInfo=c,this._vertexBuffers[st.R.ColorKind]=u,this._initShaderSourceAsync()}async _initShaderSourceAsync(){this._engine.isWebGPU&&!Zx.ForceGLSL?(this._shaderLanguage=1,await Promise.all([Promise.resolve().then(i.bind(i,56029)),Promise.resolve().then(i.bind(i,25151))])):await Promise.all([Promise.resolve().then(i.bind(i,3290)),Promise.resolve().then(i.bind(i,3916))]),this._shadersLoaded=!0,this._createEffects()}_createEffects(){if(this._isDisposed||!this._shadersLoaded)return;this._drawWrapperBase?.dispose(),this._drawWrapperDepth?.dispose(),this._drawWrapperBase=new gt.E(this._engine),this._drawWrapperDepth=new gt.E(this._engine,!1),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing);let e="";this._pixelPerfect&&(e+="#define PIXEL_PERFECT\n"),this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode&&this._fogEnabled&&(e+="#define FOG\n"),this._useLogarithmicDepth&&(e+="#define LOGARITHMICDEPTH\n"),this._drawWrapperBase.effect=this._engine.createEffect("sprites",[st.R.PositionKind,"options","offsets","inverts","cellInfo",st.R.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor","logarithmicDepthConstant"],["diffuseSampler"],e,void 0,void 0,void 0,void 0,this._shaderLanguage),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext}render(e,t,i,r,s=null){if(!(this._shadersLoaded&&this.texture&&this.texture.isReady()&&e.length))return;const n=this._drawWrapperBase,o=this._drawWrapperDepth,a=this.fogEnabled&&this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode,l=n.effect;if(!l.isReady())return;const h=this._engine,c=!(!this._scene||!this._scene.useRightHandedSystem),u=Math.min(this._capacity,e.length);let d=0,f=!0;for(let i=0;i{e.cellRef||(e.cellIndex=0);const i=e.cellIndex;"number"==typeof i&&isFinite(i)&&Math.floor(i)===i&&(e.cellRef=this._spriteMap[e.cellIndex]),e._xOffset=this._cellData[e.cellRef].frame.x/t.width,e._yOffset=this._cellData[e.cellRef].frame.y/t.height,e._xSize=this._cellData[e.cellRef].frame.w,e._ySize=this._cellData[e.cellRef].frame.h},s||(s=he.q.LastCreatedScene),s._getComponent(Ut.v.NAME_SPRITE)||s._addComponent(new Qx(s)),this._fromPacked=a,this._scene=s;const c=this._scene.getEngine();if(this._spriteRenderer=new Zx(c,i,n,s,h?.spriteRendererOptions),r.width&&r.height)this.cellWidth=r.width,this.cellHeight=r.height;else{if(void 0===r)return void(this._spriteRenderer=null);this.cellWidth=r,this.cellHeight=r}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new vi.g(t,s,!0,!1,o)),this._fromPacked&&this._makePacked(t,l)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(null!==t)try{let e;if(e="string"==typeof t?JSON.parse(t):t,e.frames.length){const t={};for(let i=0;i0);const r=e.substring(0,i-1)+".json",s=()=>{Z.V.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1},n=e=>{try{const t=JSON.parse(e),i=Reflect.ownKeys(t.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=t.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON format. Please check documentation for format specifications.")}};Ue.S0.LoadFile(r,n,void 0,void 0,!1,s)}}_checkTextureAlpha(e,t,i,r,s){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.AA.Vector3[0];o.copyFrom(t.direction),o.normalize(),o.scaleInPlace(i),o.addInPlace(t.origin);const a=(o.x-r.x)/(s.x-r.x),l=1-(o.y-r.y)/(s.y-r.y),h=e._xOffset*n.width+a*e._xSize|0,c=e._yOffset*n.height+l*e._ySize|0;return this._textureContent[4*(h+c*n.width)+3]>.5}intersects(e,t,i,r){const s=Math.min(this.capacity,this.sprites.length),n=W.Pq.Zero(),o=W.Pq.Zero();let a=Number.MAX_VALUE,l=null;const h=W.AA.Vector3[0],c=W.AA.Vector3[1],u=t.getViewMatrix();let d=e,f=e;for(let t=0;te){if(!this._checkTextureAlpha(s,d,e,n,o))continue;if(f=d,a=e,l=s,r)break}}}}if(l){const e=new At.G;u.invertToRef(W.AA.Matrix[0]),e.hit=!0,e.pickedSprite=l,e.distance=a;const t=W.AA.Vector3[2];return t.copyFrom(f.direction),t.normalize(),t.scaleInPlace(a),f.origin.addToRef(t,h),e.pickedPoint=W.Pq.TransformCoordinates(h,W.AA.Matrix[0]),e}return null}multiIntersects(e,t,i){const r=Math.min(this.capacity,this.sprites.length),s=W.Pq.Zero(),n=W.Pq.Zero();let o;const a=[],l=W.AA.Vector3[0].copyFromFloats(0,0,0),h=W.AA.Vector3[1].copyFromFloats(0,0,0),c=t.getViewMatrix();for(let t=0;t{const o=new go.u;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),n=Jx.Parse(t,i||he.q.LastCreatedScene,r);e&&(n.name=e),s(n)}else n("Unable to load the sprite manager")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return"_BLANK"===e?Promise.resolve(new Jx("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise(((r,s)=>{const n=new go.u;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const s=JSON.parse(JSON.parse(n.responseText).jsonPayload),o=JSON.parse(s.spriteManager),a=Jx.Parse(o,t||he.q.LastCreatedScene,i);a.snippetId=e,r(a)}else s("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}Jx.SnippetUrl="https://snippet.babylonjs.com",Jx.CreateFromSnippetAsync=Jx.ParseFromSnippetAsync;var eb=!0;class tb{}tb.LoaderInjectedPhysicsEngine=void 0;let ib={},rb={},sb={};const nb=(e,t,i,r)=>{if(!t.materials)return null;for(let s=0,n=t.materials.length;s{for(const r in t)if(e.name===t[r])return i.push(e.id),!0;return void 0!==e.parentId&&-1!==i.indexOf(e.parentId)&&(i.push(e.id),!0)},ab=(e,t)=>e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown"),lb=(e,t)=>{const i=t;if(t._waitingData.lods){if(t._waitingData.lods.ids&&t._waitingData.lods.ids.length>0){const r=t._waitingData.lods.ids,s=i.isEnabled(!1);if(t._waitingData.lods.distances){const n=t._waitingData.lods.distances;if(n.length>=r.length){const t=n.length>r.length?n[n.length-1]:0;i.setEnabled(!1);for(let t=0;t0&&i.addLODLevel(t,null),!0===s&&i.setEnabled(!0)}else Ue.S0.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},hb=(e,t,i)=>{if("number"!=typeof e){const r=i.getLastEntryById(e);return r&&null!=t?r.instances[parseInt(t)]:r}const r=ib[e];return r&&null!=t?r.instances[parseInt(t)]:r},cb=(e,t)=>"number"!=typeof e?t.getLastMaterialById(e,!0):rb[e],ub=(e,t,i,r,s=!1)=>{const n=new ei(e);let o="importScene has failed JSON parse";try{var a=JSON.parse(t);o="";const r=xg.loggingLevel===xg.DETAILED_LOGGING;let s,l;if(void 0!==a.environmentTexture&&null!==a.environmentTexture){const t=void 0===a.isPBR||a.isPBR;if(a.environmentTextureType&&"BABYLON.HDRCubeTexture"===a.environmentTextureType){const r=a.environmentTextureSize?a.environmentTextureSize:128,s=new Vx((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,r,!0,!t,void 0,a.environmentTexturePrefilterOnLoad);a.environmentTextureRotationY&&(s.rotationY=a.environmentTextureRotationY),e.environmentTexture=s}else if("object"==typeof a.environmentTexture){const t=gm.Parse(a.environmentTexture,e,i);e.environmentTexture=t}else if(a.environmentTexture.endsWith(".env")){const t=new gm((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,a.environmentTextureForcedExtension);a.environmentTextureRotationY&&(t.rotationY=a.environmentTextureRotationY),e.environmentTexture=t}else{const t=gm.CreateFromPrefilteredData((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,a.environmentTextureForcedExtension);a.environmentTextureRotationY&&(t.rotationY=a.environmentTextureRotationY),e.environmentTexture=t}if(!0===a.createDefaultSkybox){const i=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,r=a.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,t,i,r)}n.environmentTexture=e.environmentTexture}if(void 0!==a.environmentIntensity&&null!==a.environmentIntensity&&(e.environmentIntensity=a.environmentIntensity),void 0!==a.lights&&null!==a.lights)for(s=0,l=a.lights.length;s{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)})))}if(void 0!==a.multiMaterials&&null!==a.multiMaterials)for(s=0,l=a.multiMaterials.length;s{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)}))}if(void 0!==a.morphTargetManagers&&null!==a.morphTargetManagers)for(const t of a.morphTargetManagers){const i=Gx.Parse(t,e);sb[t.id]=i,n.morphTargetManagers.push(i),i._parentContainer=n}if(void 0!==a.skeletons&&null!==a.skeletons)for(s=0,l=a.skeletons.length;s{e&&(n.geometries.push(e),e._parentContainer=n)}))}if(void 0!==a.transformNodes&&null!==a.transformNodes)for(s=0,l=a.transformNodes.length;s{t._waitingSubMaterialsUniqueIds.forEach((i=>{t.subMaterials.push(cb(i,e))})),t._waitingSubMaterialsUniqueIds=[]})),e.meshes.forEach((t=>{null!==t._waitingMaterialId&&(t.material=cb(t._waitingMaterialId,e),t._waitingMaterialId=null)})),e.meshes.forEach((e=>{null!==e._waitingMorphTargetManagerId&&(e.morphTargetManager=sb[e._waitingMorphTargetManagerId],e._waitingMorphTargetManagerId=null)})),s=0,l=e.skeletons.length;s{if(t._waitingTransformNodeId){const i=e.getLastEntryById(t._waitingTransformNodeId);i&&t.linkTransformNode(i),t._waitingTransformNodeId=null}})),t._hasWaitingData=null)}for(s=0,l=e.meshes.length;s0){for(let i=0;i0){for(let i=0;i{e._loadedUniqueId=""})),pi(a,e,n,i),s=0,l=e.meshes.length;s-1!==e.indexOf("babylon"),importMesh:(e,t,i,r,s,n,o,a)=>{let l="importMesh has failed JSON parse";try{var h=JSON.parse(i);l="";const a=xg.loggingLevel===xg.DETAILED_LOGGING;e?Array.isArray(e)||(e=[e]):e=null;const c=[],u=new Map,d=[];if(void 0!==h.transformNodes&&null!==h.transformNodes)for(let e=0,i=h.transformNodes.length;e{!0!==e&&h.geometries[i]&&Array.isArray(h.geometries[i])&&h.geometries[i].forEach((s=>{s.id===_.geometryId&&("vertexData"===i&&yt.Parse(s,t,r),e=!0)}))})),!1===e&&Z.V.Warn("Geometry not found for mesh "+_.id)}if(_.materialUniqueId||_.materialId){const e=_.materialUniqueId?f:n;let i=-1!==e.indexOf(_.materialUniqueId||_.materialId);if(!1===i&&void 0!==h.multiMaterials&&null!==h.multiMaterials){const s=(i,s)=>{e.push(i);const n=nb(s,h,t,r);n&&n.material&&(rb[n.parsedMaterial.uniqueId||n.parsedMaterial.id]=n.material,l+="\n\tMaterial "+n.material.toString(a))};for(let r=0,n=h.multiMaterials.length;rs(e,(t=>t.uniqueId===e)))):n.materials.forEach((e=>s(e,(t=>t.id===e)))),e.push(n.uniqueId||n.id);const r=kt.ParseMultiMaterial(n,t);rb[n.uniqueId||n.id]=r,r&&(i=!0,l+="\n\tMulti-Material "+r.toString(a));break}}}if(!1===i){e.push(_.materialUniqueId||_.materialId);const i=nb((e=>_.materialUniqueId&&e.uniqueId===_.materialUniqueId||e.id===_.materialId),h,t,r);i&&i.material?(rb[i.parsedMaterial.uniqueId||i.parsedMaterial.id]=i.material,l+="\n\tMaterial "+i.material.toString(a)):Z.V.Warn("Material not found for mesh "+_.id)}}if(null!==_.skeletonId&&void 0!==_.skeletonId&&-1!==h.skeletonId&&void 0!==h.skeletons&&null!==h.skeletons&&!(i.indexOf(_.skeletonId)>-1))for(let e=0,r=h.skeletons.length;e-1&&void 0!==h.morphTargetManagers&&null!==h.morphTargetManagers&&!(p.indexOf(_.morphTargetManagerId)>-1))for(let e=0;e{e._waitingSubMaterialsUniqueIds.forEach((i=>{e.subMaterials.push(cb(i,t))})),e._waitingSubMaterialsUniqueIds=[]})),t.meshes.forEach((e=>{null!==e._waitingMaterialId&&(e.material=cb(e._waitingMaterialId,t),e._waitingMaterialId=null)})),t.meshes.forEach((e=>{null!==e._waitingMorphTargetManagerId&&(e.morphTargetManager=sb[e._waitingMorphTargetManagerId],e._waitingMorphTargetManagerId=null)}));for(let e=0,i=t.transformNodes.length;e{if(e._waitingTransformNodeId){const i=t.getLastEntryById(e._waitingTransformNodeId);i&&e.linkTransformNode(i),e._waitingTransformNodeId=null}})),i._hasWaitingData=null)}for(let e=0,i=t.meshes.length;e{e._loadedUniqueId=""})),!0}catch(e){const t=ab("importMesh",h?h.producer:"Unknown")+l;if(!a)throw Z.V.Log(t),e;a(t,e)}finally{null!==l&&xg.loggingLevel!==xg.NO_LOGGING&&Z.V.Log(ab("importMesh",h?h.producer:"Unknown")+(xg.loggingLevel!==xg.MINIMAL_LOGGING?l:"")),rb={},sb={}}return!1},load:(e,t,i,r)=>{let s="importScene has failed JSON parse";try{var n=JSON.parse(t);switch(s="",void 0!==n.useDelayedTextureLoading&&null!==n.useDelayedTextureLoading&&(e.useDelayedTextureLoading=n.useDelayedTextureLoading&&!xg.ForceFullSceneLoadingForIncremental),void 0!==n.autoClear&&null!==n.autoClear&&(e.autoClear=n.autoClear),void 0!==n.clearColor&&null!==n.clearColor&&(e.clearColor=H.ov.FromArray(n.clearColor)),void 0!==n.ambientColor&&null!==n.ambientColor&&(e.ambientColor=H.v9.FromArray(n.ambientColor)),void 0!==n.gravity&&null!==n.gravity&&(e.gravity=W.Pq.FromArray(n.gravity)),void 0!==n.useRightHandedSystem&&(e.useRightHandedSystem=!!n.useRightHandedSystem),void 0!==n.fogMode&&null!==n.fogMode&&(e.fogMode=n.fogMode),void 0!==n.fogColor&&null!==n.fogColor&&(e.fogColor=H.v9.FromArray(n.fogColor)),void 0!==n.fogStart&&null!==n.fogStart&&(e.fogStart=n.fogStart),void 0!==n.fogEnd&&null!==n.fogEnd&&(e.fogEnd=n.fogEnd),void 0!==n.fogDensity&&null!==n.fogDensity&&(e.fogDensity=n.fogDensity),s+="\tFog mode for scene: ",e.fogMode){case 0:s+="none\n";break;case 1:s+="exp\n";break;case 2:s+="exp2\n";break;case 3:s+="linear\n"}if(n.physicsEnabled){let t;"cannon"===n.physicsEngine||n.physicsEngine===Xx.name?t=new Xx(void 0,void 0,tb.LoaderInjectedPhysicsEngine):"oimo"===n.physicsEngine||n.physicsEngine===qx.name?t=new qx(void 0,tb.LoaderInjectedPhysicsEngine):"ammo"!==n.physicsEngine&&n.physicsEngine!==Yx.name||(t=new Yx(void 0,tb.LoaderInjectedPhysicsEngine,void 0)),s="\tPhysics engine "+(n.physicsEngine?n.physicsEngine:"oimo")+" enabled\n";const i=n.gravity?W.Pq.FromArray(n.gravity):n.physicsGravity?W.Pq.FromArray(n.physicsGravity):null;e.enablePhysics(i,t)}return void 0!==n.metadata&&null!==n.metadata&&(e.metadata=n.metadata),void 0!==n.collisionsEnabled&&null!==n.collisionsEnabled&&(e.collisionsEnabled=n.collisionsEnabled),!!ub(e,t,i,r,!0)&&(n.autoAnimate&&e.beginAnimation(e,n.autoAnimateFrom,n.autoAnimateTo,n.autoAnimateLoop,n.autoAnimateSpeed||1),void 0!==n.activeCameraID&&null!==n.activeCameraID&&e.setActiveCameraById(n.activeCameraID),!0)}catch(e){const t=ab("importScene",n?n.producer:"Unknown")+s;if(!r)throw Z.V.Log(t),e;r(t,e)}finally{null!==s&&xg.loggingLevel!==xg.NO_LOGGING&&Z.V.Log(ab("importScene",n?n.producer:"Unknown")+(xg.loggingLevel!==xg.MINIMAL_LOGGING?s:""))}return!1},loadAssetContainer:(e,t,i,r)=>ub(e,t,i,r)});var db=i(18135),fb=i(61853),pb=i(80723),_b=i(91341),mb=i(87741);class gb{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,Ot.$.MarkAllMaterialsAsDirty(20))}constructor(e={}){this._isEnabled=!0,this.bias=void 0===e.bias?0:e.bias,this.power=void 0===e.power?1:e.power,this.leftColor=e.leftColor||H.v9.White(),this.rightColor=e.rightColor||H.v9.Black(),!1===e.isEnabled&&(this.isEnabled=!1)}clone(){const e=new gb;return ce.r.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 gb({isEnabled:e.isEnabled,leftColor:H.v9.FromArray(e.leftColor),rightColor:H.v9.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}it.p._FresnelParametersParser=gb.Parse;class vb{}vb.BindSceneUniformBuffer=Bt._8,vb.PrepareDefinesForMergedUV=Bt.YT,vb.BindTextureMatrix=Bt.mA,vb.GetFogState=Bt.qL,vb.PrepareDefinesForMisc=Bt.fm,vb.PrepareDefinesForCamera=Bt.Y7,vb.PrepareDefinesForFrameBoundValues=Bt.OR,vb.PrepareDefinesForBones=Bt.IC,vb.PrepareDefinesForMorphTargets=Bt.Jz,vb.PrepareDefinesForBakedVertexAnimation=Bt.wu,vb.PrepareDefinesForAttributes=Bt.qB,vb.PrepareDefinesForMultiview=Bt.VO,vb.PrepareDefinesForOIT=Bt.Nc,vb.PrepareDefinesForPrePass=Bt.N4,vb.PrepareDefinesForLight=Bt.lo,vb.PrepareDefinesForLights=Bt.az,vb.PrepareUniformsAndSamplersForLight=Bt.GD,vb.PrepareUniformsAndSamplersList=Bt.Bb,vb.HandleFallbacksForShadows=Bt.c4,vb.PrepareAttributesForMorphTargetsInfluencers=Bt.MF,vb.PrepareAttributesForMorphTargets=Bt.IF,vb.PrepareAttributesForBakedVertexAnimation=Bt.J2,vb.PrepareAttributesForBones=Bt.ni,vb.PrepareAttributesForInstances=Bt.ER,vb.PushAttributesForInstances=Bt.te,vb.BindLightProperties=Bt.L0,vb.BindLight=Bt.Kd,vb.BindLights=Bt.RL,vb.BindFogParameters=Bt.Yy,vb.BindBonesParameters=Bt.f$,vb.BindMorphTargetParameters=Bt.nR,vb.BindLogDepth=Bt.DL;var xb=i(27683),bb=i(53501);class Sb extends xo{constructor(e,t){super(e,t,"color",{attributes:["position"],uniforms:["world","viewProjection","color"]}),this.disableColorWrite=!0,this.forceDepthWrite=!0,this.setColor4("color",new H.ov(0,0,0,1))}}class Tb extends Gm{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 H.v9(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],Tb.prototype,"maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],Tb.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],Tb.prototype,"environmentTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Tb.prototype,"invertNormalMapX",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Tb.prototype,"invertNormalMapY",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],Tb.prototype,"normalTexture",void 0),(0,je.Cg)([(0,$e.jT)("emissive"),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Tb.prototype,"emissiveColor",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Tb.prototype,"emissiveTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],Tb.prototype,"occlusionStrength",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],Tb.prototype,"occlusionTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],Tb.prototype,"alphaCutOff",void 0),(0,je.Cg)([(0,$e.lK)()],Tb.prototype,"doubleSided",null),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty",null)],Tb.prototype,"lightmapTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Tb.prototype,"useLightmapAsShadowmap",void 0);class Cb extends Tb{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=it.p.Clone((()=>new Cb(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=it.p.Serialize(this);return e.customType="BABYLON.PBRMetallicRoughnessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const r=it.p.Parse((()=>new Cb(e.name,t)),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}(0,je.Cg)([(0,$e.jT)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_albedoColor")],Cb.prototype,"baseColor",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],Cb.prototype,"baseTexture",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Cb.prototype,"metallic",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Cb.prototype,"roughness",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],Cb.prototype,"metallicRoughnessTexture",void 0),(0,X.Y5)("BABYLON.PBRMetallicRoughnessMaterial",Cb);class yb extends Tb{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){const t=it.p.Clone((()=>new yb(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=it.p.Serialize(this);return e.customType="BABYLON.PBRSpecularGlossinessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const r=it.p.Parse((()=>new yb(e.name,t)),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}(0,je.Cg)([(0,$e.jT)("diffuse"),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_albedoColor")],yb.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],yb.prototype,"diffuseTexture",void 0),(0,je.Cg)([(0,$e.jT)("specular"),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],yb.prototype,"specularColor",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_microSurface")],yb.prototype,"glossiness",void 0),(0,je.Cg)([(0,$e.uM)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],yb.prototype,"specularGlossinessTexture",void 0),(0,X.Y5)("BABYLON.PBRSpecularGlossinessMaterial",yb);var Eb,Pb=i(431),Ab=i(66854),Rb=i(60693),Ib=i(43004);!function(e){e[e.GLSL=0]="GLSL",e[e.WGSL=1]="WGSL"}(Eb||(Eb={}));class Mb extends js.t{constructor(e,t,i=null){if(super(t),e)if(this._textureMatrix=W.uq.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{const e=this.getScene();e&&e.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){const e=this._getEngine();let t;t=e._features.support3DTextures?e.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):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=i=>{if("string"!=typeof i)return;let r,s=null,n=null;const o=i.split("\n");let a=0,l=0,h=0,c=0,u=0;for(let e=0;e0&&(e+1)%4==0)s[e]=255;else{const t=n[e];s[e]=t/u*255}t.is3D?(t.updateSize(a,a,a),e.updateRawTexture3D(t,s,5,!1)):(t.updateSize(a*a,a),e.updateRawTexture(t,s,5,!1)),t.isReady=!0,this._triggerOnLoad()},r=this.getScene();return r?r._loadFile(this.url,i):e._loadFile(this.url,i),this._texture}_loadTexture(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()}clone(){const e=new Mb(this.url,this.getScene()||this._getEngine());return e.level=this.level,e}delayLoad(){4===this.delayLoadState&&(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 Mb(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}}Mb._NoneEmptyLineRegex=/\S+/,(0,X.Y5)("BABYLON.ColorGradingTexture",Mb);var Ob=i(5060);class Db extends js.t{constructor(e,t,i,r=!1,s=!0,n=null,o=null,a=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw new Error("Image url is not set");this._coordinatesMode=vi.g.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=a,this._noMipmap=r,this.gammaSpace=s,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?Ue.S0.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 r=i.getEngine().createRawCubeTexture(null,this._size,4,i.getEngine().getCaps().textureFloat?1:7,!this._noMipmap,!1,3);r.generateMipMaps=!this._noMipmap,i.addPendingData(r),r.url=this.url,r.isReady=!1,i.getEngine()._internalTexturesCache.push(r),this._texture=r,(0,$m.W$)(this.url,(t=>{let i;this._width=t.width,this._height=t.height,(0,ii.Nf)()?(i=document.createElement("canvas"),i.width=this._width,i.height=this._height):i=new OffscreenCanvas(this._width,this._height);const r=i.getContext("2d");r.drawImage(t,0,0);const s=r.getImageData(0,0,t.width,t.height);this._buffer=s.data.buffer,i.remove&&i.remove(),e()}),((e,s)=>{i.removePendingData(r),t&&t(`${this.getClassName()} could not be loaded`,s)}),i?i.offlineProvider:null)}_loadTexture(){const e=this.getScene();if(!e)return;const t=(()=>{const e=this._getFloat32ArrayFromArrayBuffer(this._buffer),t=Ob.D.ConvertPanoramaToCubemap(e,this._width,this._height,this._size,this._supersample),i=[];for(let e=0;e<6;e++){const r=t[Db._FacesMapping[e]];i.push(r)}return i})(),i=this._texture;e.getEngine().updateRawCubeTexture(i,t,i.format,i.type,i.invertY),i.isReady=!0,e.removePendingData(i),i.onLoadedObservable.notifyObservers(i),i.onLoadedObservable.clear(),this._onLoad&&this._onLoad()}_getFloat32ArrayFromArrayBuffer(e){const t=new DataView(e),i=new Float32Array(3*e.byteLength/4);let r=0;for(let s=0;s0&&(this._createInternalTextures(),this._createTextures(n))}_initTypes(e,t,i,r,s,n,o,a,l,h){for(let c=0;c{this.onAfterRenderObservable.notifyObservers(t)}))}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){const e=this._renderTarget?.textures;if(e){for(let t=e.length-1;t>=0;t--)this._textures[t]._texture=null;this._renderTarget?.dispose(),this._renderTarget=null}}}class qb{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}}class Yb{constructor(e,t,i,r){return this.name=e,this.meshes=t,this.scene=r,this.options=i,this.options.map=this.options.map??["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=this.options.uvsIn??st.R.UVKind,this.options.uvsOut=this.options.uvsOut??st.R.UVKind,this.options.layout=this.options.layout??Yb.LAYOUT_STRIP,this.options.layout===Yb.LAYOUT_COLNUM&&(this.options.colnum=this.options.colnum??8),this.options.updateInputMeshes=this.options.updateInputMeshes??!0,this.options.disposeSources=this.options.disposeSources??!0,this._expecting=0,this.options.fillBlanks=this.options.fillBlanks??!0,!0===this.options.fillBlanks&&(this.options.customFillColor=this.options.customFillColor??"black"),this.options.frameSize=this.options.frameSize??256,this.options.paddingRatio=this.options.paddingRatio??.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!=0&&this._paddingValue++,this.options.paddingMode=this.options.paddingMode??Yb.SUBUV_WRAP,this.options.paddingMode===Yb.SUBUV_COLOR&&(this.options.paddingColor=this.options.paddingColor??new H.ov(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){const t=this._calculateSize(),i=new W.I9(1,1).divide(t);let r=0;const s=this._expecting,n=this.meshes.length,o=Object.keys(this.sets);for(let e=0;e{this._calculateMeshUVFrames(a,l,t,i,this.options.updateInputMeshes||!1)};for(let i=0;i{r++,d.update(!1);const i=f.getImageData(0,0,h,h),n=this.sets[m];if(n.getContext().putImageData(i,t.x*p.x,t.y*p.y),d.dispose(),n.update(!1),r==s)return c(),void e()},m=o[u]||"_blank";if(n&&null!==n[m]){const e=n[m],t=new Image;t.src=e instanceof Gn?e.getContext().canvas.toDataURL("image/png"):e.url,Ue.S0.SetCorsBehavior(t.src,t),t.onload=()=>{f.fillStyle="rgba(0,0,0,0)",f.fillRect(0,0,h,h),d.update(!1),f.setTransform(1,0,0,-1,0,0);const e=[0,0,1,0,1,1,0,1,-1,1,-1,0,-2,0,-1,1,-1];switch(this.options.paddingMode){case 0:for(let i=0;i<9;i++)f.drawImage(t,0,0,t.width,t.height,l+a*e[i],l+a*e[i+1]-h,a,a);break;case 1:for(let i=0;i{e.dispose&&e.dispose()};for(let e=0;e{try{if(0===this.meshes.length)return void e();let t=0;const i=i=>{if(t++,this.options.map){for(let e=0;e{i(n)}));else if(t++,t===this.meshes.length)return this._createFrames(e)}}catch(e){return t(e)}}))}dispose(){const e=Object.keys(this.sets);for(let t=0;t{const i={name:this.name,sets:{},options:{},frames:[]},r=Object.keys(this.sets),s=Object.keys(this.options);try{for(let s=0;s{try{this.setFragment(this._texturePath)}catch(e){Z.V.Log("No json or ShaderStore or DOM element found for CustomProceduralTexture")}},i=e+"/config.json",r=new go.u;r.open("GET",i),r.addEventListener("load",(()=>{if(200===r.status||r.responseText&&r.responseText.length>0)try{this._config=JSON.parse(r.response),this.updateShaderUniforms(),this.updateTextures(),this.setFragment(this._texturePath+"/custom"),this._animate=this._config.animate,this.refreshRate=this._config.refreshrate}catch(e){t()}else t()}),!1),r.addEventListener("error",(()=>{t()}),!1);try{r.send()}catch(e){Z.V.Error("CustomProceduralTexture: Error on XHR send request.")}}isReady(){if(!super.isReady())return!1;for(const e in this._textures)if(!this._textures[e].isReady())return!1;return!0}render(e){const t=this.getScene();this._animate&&t&&(this._time+=.03*t.getAnimationRatio(),this.updateShaderUniforms()),super.render(e)}updateTextures(){for(let e=0;e{}))}clone(){return it.p.Clone((()=>{const e=this.getScene(),t=this._texture,i=new $b(e,t._bufferViewArray,t.width,t.format,t.type,t.generateMipMaps,t.invertY,t.samplingMode,t._compression);return 13===t.source&&i.updateRGBDAsync(t._bufferViewArrayArray,t._sphericalPolynomial,t._lodGenerationScale,t._lodGenerationOffset),i}),this)}}class Qb extends vi.g{get width(){return this._texture?this._texture.width:0}get height(){return this._texture?this._texture.height:0}get depth(){return this._texture?this._texture.depth:0}constructor(e,t,i,r,s,n,o=!0,a=!1,l=vi.g.TRILINEAR_SAMPLINGMODE,h=0,c){super(null,n,!o,a),this.format=s,this._texture=n.getEngine().createRawTexture3D(e,t,i,r,s,o,a,l,null,h,c),this.is3D=!0}update(e){this._texture&&this._getEngine().updateRawTexture3D(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)}}class Zb extends ln.${constructor(e,t,i,r){super(e,t,i,r,!0),this.refractionPlane=new Ft.Z(0,1,0,1),this.depth=2,this.onBeforeRenderObservable.add((()=>{this.getScene().clipPlane=this.refractionPlane})),this.onAfterRenderObservable.add((()=>{this.getScene().clipPlane=null}))}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Zb(this.name,t.width,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.refractionPlane=this.refractionPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i.depth=this.depth,i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.refractionPlane.asArray(),e.depth=this.depth,e}}var Jb=i(18310),eS=i(29305);class tS extends eS.D{get renderTarget(){return this._renderTarget}constructor(e,t,i){super(null),this._renderTarget=null,this._engine=e,this._renderTargetOptions=i,this.resize(t)}resize(e){this._renderTarget?.dispose(),this._renderTarget=null,this._texture=null,this._size=e,this._engine&&(this._renderTarget=this._engine.createRenderTargetTexture(this._size,this._renderTargetOptions)),this._texture=this.renderTarget.texture}getInternalTexture(){return this._texture}getClassName(){return"ThinRenderTargetTexture"}dispose(e=!1){this._renderTarget?.dispose(!0),this._renderTarget=null,e||super.dispose()}}var iS,rS=i(63199),sS=i(67402),nS=i(92911),oS=i(77318),aS=i(80424),lS=i(44623),hS=i(17477);!function(e){e[e.Uniform=0]="Uniform",e[e.Attribute=1]="Attribute",e[e.Varying=2]="Varying",e[e.Undefined=3]="Undefined"}(iS||(iS={}));class cS extends Ug{constructor(e,t,i,r,s){super(e,t,i),this._blockType=r,this._blockName=s,this.needDualDirectionValidation=!0}checkCompatibilityState(e){return e instanceof cS&&e._blockName===this._blockName?0:1}createCustomInputBlock(){return[new this._blockType(this._blockName),this.name]}}class uS extends Gg{constructor(e){super(e,Dg.Vertex),this._isUnique=!0,this.registerInput("splatPosition",Og.Vector3,!1,Dg.Vertex),this.registerInput("splatScale",Og.Vector2,!0,Dg.Vertex),this.registerInput("world",Og.Matrix,!1,Dg.Vertex),this.registerInput("view",Og.Matrix,!1,Dg.Vertex),this.registerInput("projection",Og.Matrix,!1,Dg.Vertex),this.registerOutput("splatVertex",Og.Vector4,Dg.Vertex)}getClassName(){return"GaussianSplattingBlock"}get splatPosition(){return this._inputs[0]}get splatScale(){return this._inputs[1]}get world(){return this._inputs[2]}get view(){return this._inputs[3]}get projection(){return this._inputs[4]}get splatVertex(){return this._outputs[0]}initialize(e){e._excludeVariableName("focal"),e._excludeVariableName("invViewport")}_buildBlock(e){if(super._buildBlock(e),e.target===Dg.Fragment)return;const t=`//${this.name}`;e._emitFunctionFromInclude("gaussianSplattingVertexDeclaration",t),e._emitFunctionFromInclude("gaussianSplatting",t),e._emitUniformFromString("focal",Og.Vector2),e._emitUniformFromString("invViewport",Og.Vector2),e.attributes.push(st.R.PositionKind),e.sharedData.nodeMaterial.backFaceCulling=!1;const i=this.splatPosition,r=this.splatScale,s=this.world,n=this.view,o=this.projection,a=this.splatVertex;let l=`vec2${e.fSuffix}(1.,1.)`;r.isConnected&&(l=r.associatedVariableName);let h="position",c="";return 1===e.shaderLanguage&&(h="input.position",c=", uniforms.focal, uniforms.invViewport"),e.compilationString+=`${e._declareOutput(a)} = gaussianSplatting(${h}, ${i.associatedVariableName}, ${l}, covA, covB, ${s.associatedVariableName}, ${n.associatedVariableName}, ${o.associatedVariableName}${c});\n`,this}}(0,X.Y5)("BABYLON.GaussianSplattingBlock",uS);class dS extends Gg{constructor(e){super(e,Dg.Fragment),this._isUnique=!1,this.registerInput("splatColor",Og.Color4,!1,Dg.Fragment),this.registerOutput("rgba",Og.Color4,Dg.Fragment)}getClassName(){return"GaussianBlock"}get splatColor(){return this._inputs[0]}get rgba(){return this._outputs[0]}initialize(e){e._excludeVariableName("vPosition")}_buildBlock(e){if(super._buildBlock(e),e.target===Dg.Vertex)return;const t=`//${this.name}`;e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e._emitFunctionFromInclude("logDepthDeclaration",t),e._emitFunctionFromInclude("fogFragmentDeclaration",t),e._emitFunctionFromInclude("gaussianSplattingFragmentDeclaration",t),e._emitVaryingFromString("vPosition",Og.Vector2);const i=this.splatColor,r=this._outputs[0];return 1===e.shaderLanguage?e.compilationString+=`${e._declareOutput(r)} = gaussianColor(${i.associatedVariableName}, input.vPosition);\n`:e.compilationString+=`${e._declareOutput(r)} = gaussianColor(${i.associatedVariableName});\n`,this}}(0,X.Y5)("BABYLON.GaussianBlock",dS),i(67058),i(21325),i(99407),i(92026);class fS extends xn{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 pS extends bn{constructor(e,t){super(e,t),this.backFaceCulling=!1}get hasRenderTargetTextures(){return!1}needAlphaTesting(){return!1}needAlphaBlending(){return!0}isReadyForSubMesh(e,t){const r=!0,s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===r)return!0;t.materialDefines||(t.materialDefines=new fS);const n=this.getScene(),o=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const a=n.getEngine();if((0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,!1,o),(0,Bt.OR)(n,a,this,o,r,null,!0),(0,Bt.qB)(e,o,!1,!1),o.isDirty){o.markAsProcessed(),n.resetCachedMaterial();const e=[st.R.PositionKind,"splatIndex"];(0,Bt.ER)(e,o);const r=["world","view","projection","vFogInfos","vFogColor","logarithmicDepthConstant","invViewport","dataTextureSize","focal"],s=["covariancesATexture","covariancesBTexture","centersTexture","colorsTexture"],l=["Scene","Mesh"];(0,Bt.Bb)({uniformsNames:r,uniformBuffersNames:l,samplers:s,defines:o}),(0,Ln.TV)(r);const h=o.toString(),c=n.getEngine().createEffect("gaussianSplatting",{attributes:e,uniformsNames:r,uniformBuffersNames:l,samplers:s,defines:h,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{},shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,99407)),Promise.resolve().then(i.bind(i,92026))]):await Promise.all([Promise.resolve().then(i.bind(i,67058)),Promise.resolve().then(i.bind(i,21325))])}},a);t.setEffect(c,o,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(o._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=r,0))}static BindEffect(e,t,i){const r=i.getEngine(),s=i.activeCamera,n=r.getRenderWidth(),o=r.getRenderHeight(),a=s?.rigParent?.rigCameras.length||1;t.setFloat2("invViewport",1/(n/a),1/o);let l=1e3;if(s){const e=s.getProjectionMatrix().m[5];l=s.fovMode==rt.FOVMODE_VERTICAL_FIXED?o*e/2:n*e/2}t.setFloat2("focal",l,l);const h=e;if(h.covariancesATexture){const e=h.covariancesATexture.getSize();t.setFloat2("dataTextureSize",e.width,e.height),t.setTexture("covariancesATexture",h.covariancesATexture),t.setTexture("covariancesBTexture",h.covariancesBTexture),t.setTexture("centersTexture",h.centersTexture),t.setTexture("colorsTexture",h.colorsTexture)}}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e),this._mustRebind(r,n,i,t.visibility)?(this.bindView(n),this.bindViewProjection(n),pS.BindEffect(t,this._activeEffect,r),(0,Ln.gS)(n,this,r)):r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0),(0,Bt.Yy)(r,t,n),this.useLogarithmicDepth&&(0,Bt.DL)(s,n,r),this._afterBind(t,this._activeEffect,i))}clone(e){return it.p.Clone((()=>new pS(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GaussianSplattingMaterial",e}getClassName(){return"GaussianSplattingMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new pS(e.name,t)),e,t,i)}}(0,X.Y5)("BABYLON.GaussianSplattingMaterial",pS);class _S extends Gg{constructor(e){super(e,Dg.Vertex),this._isUnique=!0,this.registerInput("splatIndex",Og.Float,!1,Dg.Vertex),this.registerOutput("splatPosition",Og.Vector3,Dg.Vertex),this.registerOutput("splatColor",Og.Color4,Dg.Vertex)}getClassName(){return"SplatReaderBlock"}get splatIndex(){return this._inputs[0]}get splatPosition(){return this._outputs[0]}get splatColor(){return this._outputs[1]}initialize(e){e._excludeVariableName("covA"),e._excludeVariableName("covB"),e._excludeVariableName("vPosition"),e._excludeVariableName("covariancesATexture"),e._excludeVariableName("covariancesBTexture"),e._excludeVariableName("centersTexture"),e._excludeVariableName("colorsTexture"),e._excludeVariableName("dataTextureSize")}bind(e,t,i){if(!i)return;const r=i.getScene();pS.BindEffect(i,e,r)}_buildBlock(e){if(super._buildBlock(e),e.target===Dg.Fragment)return;e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emit2DSampler("covariancesATexture"),e._emit2DSampler("covariancesBTexture"),e._emit2DSampler("centersTexture"),e._emit2DSampler("colorsTexture"),e._emitFunctionFromInclude("gaussianSplattingVertexDeclaration",t),e._emitFunctionFromInclude("gaussianSplatting",t),e._emitVaryingFromString("vPosition",Og.Vector2),e._emitUniformFromString("dataTextureSize",Og.Vector2);const i=this.splatIndex,r=this.splatPosition,s=this.splatColor,n=e._getFreeVariableName("splat");return 1===e.shaderLanguage?(e.compilationString+=`var ${n}: Splat = readSplat(${i.associatedVariableName}, uniforms.dataTextureSize);\n`,e.compilationString+="var covA: vec3f = splat.covA.xyz; var covB: vec3f = vec3f(splat.covA.w, splat.covB.xy);\n",e.compilationString+="vertexOutputs.vPosition = input.position;\n"):(e.compilationString+=`Splat ${n} = readSplat(${i.associatedVariableName});\n`,e.compilationString+="vec3 covA = splat.covA.xyz; vec3 covB = vec3(splat.covA.w, splat.covB.xy);\n",e.compilationString+="vPosition = position;\n"),e.compilationString+=`${e._declareOutput(r)} = ${n}.center.xyz;\n`,e.compilationString+=`${e._declareOutput(s)} = ${n}.color;\n`,this}}function mS(e){e.clear(),e.editorData=null;const t=new Kg("SplatIndex");t.setAsAttribute("splatIndex");const i=new _S("SplatReader");t.connectTo(i);const r=new uS("GaussianSplatting");i.connectTo(r);const s=new Kg("World");s.setAsSystemValue(Lg.World);const n=new zg("WorldPos");i.connectTo(n),s.connectTo(n),n.connectTo(r,{output:"xyz",input:"splatPosition"});const o=new Kg("view");o.setAsSystemValue(Lg.View);const a=new Kg("Projection");a.setAsSystemValue(Lg.Projection),s.connectTo(r,{input:"world"}),o.connectTo(r,{input:"view"}),a.connectTo(r,{input:"projection"});const l=new dS("Gaussian");i.connectTo(l,{input:"splatColor",output:"splatColor"});const h=new Hg("FragmentOutput");l.connectTo(h);const c=new Wg("VertexOutput");r.connectTo(c),e.addOutputNode(c),e.addOutputNode(h),e._mode=rv.GaussianSplatting}(0,X.Y5)("BABYLON.SplatReaderBlock",_S);class gS extends Gg{constructor(e){super(e,Dg.Vertex),this.registerInput("matricesIndices",Og.Vector4),this.registerInput("matricesWeights",Og.Vector4),this.registerInput("matricesIndicesExtra",Og.Vector4,!0),this.registerInput("matricesWeightsExtra",Og.Vector4,!0),this.registerInput("world",Og.Matrix),this.registerOutput("output",Og.Matrix)}initialize(e){e._excludeVariableName("boneSampler"),e._excludeVariableName("boneTextureWidth"),e._excludeVariableName("mBones"),e._excludeVariableName("BonesPerMesh"),this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,1===e?await Promise.all([Promise.resolve().then(i.bind(i,25589)),Promise.resolve().then(i.bind(i,40903))]):await Promise.all([Promise.resolve().then(i.bind(i,39948)),Promise.resolve().then(i.bind(i,78792))]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}getClassName(){return"BonesBlock"}get matricesIndices(){return this._inputs[0]}get matricesWeights(){return this._inputs[1]}get matricesIndicesExtra(){return this._inputs[2]}get matricesWeightsExtra(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}autoConfigure(e,t=(()=>!0)){if(!this.matricesIndices.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesIndices"===e.name&&t(e)));i||(i=new Kg("matricesIndices"),i.setAsAttribute("matricesIndices")),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesWeights"===e.name&&t(e)));i||(i=new Kg("matricesWeights"),i.setAsAttribute("matricesWeights")),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Lg.World&&t(e)));i||(i=new Kg("world"),i.setAsSystemValue(Lg.World)),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){(0,Bt.f$)(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&(0,Bt.IC)(e,i)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithFallbacks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.uniforms.push("boneTextureWidth"),e.uniforms.push("mBones"),e.samplers.push("boneSampler");const t=`//${this.name}`;e._emitFunctionFromInclude("bonesDeclaration",t,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});const i=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",t,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:i}]});const r=this._outputs[0],s=this.world;return e.compilationString+="#if NUM_BONE_INFLUENCERS>0\n",e.compilationString+=e._declareOutput(r)+` = ${s.associatedVariableName} * ${i};\n`,e.compilationString+="#else\n",e.compilationString+=e._declareOutput(r)+` = ${s.associatedVariableName};\n`,e.compilationString+="#endif\n",this}}(0,X.Y5)("BABYLON.BonesBlock",gS);class vS extends Gg{constructor(e){super(e,Dg.Vertex),this.registerInput("world0",Og.Vector4),this.registerInput("world1",Og.Vector4),this.registerInput("world2",Og.Vector4),this.registerInput("world3",Og.Vector4),this.registerInput("world",Og.Matrix,!0),this.registerOutput("output",Og.Matrix),this.registerOutput("instanceID",Og.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((e=>e.isAttribute&&"world0"===e.name&&t(e)));i||(i=new Kg("world0"),i.setAsAttribute("world0")),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world1"===e.name&&t(e)));i||(i=new Kg("world1"),i.setAsAttribute("world1")),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world2"===e.name&&t(e)));i||(i=new Kg("world2"),i.setAsAttribute("world2")),i.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world3"===e.name&&t(e)));i||(i=new Kg("world3"),i.setAsAttribute("world3")),i.output.connectTo(this.world3)}if(!this.world.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world"===e.name&&t(e)));i||(i=new Kg("world"),i.setAsSystemValue(Lg.World)),i.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,r=!1,s){let n=!1;i.INSTANCES!==r&&(i.setValue("INSTANCES",r),n=!0),s&&i.THIN_INSTANCES!==!!s?.getRenderingMesh().hasThinInstances&&(i.setValue("THIN_INSTANCES",!!s?.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],r=this._outputs[1],s=this.world0,n=this.world1,o=this.world2,a=this.world3;let l="mat4",h="gl_InstanceID",c="float";return 1===e.shaderLanguage&&(l="mat4x4f",h="vertexInputs.instanceIndex",c="f32"),e.compilationString+="#ifdef INSTANCES\n",e.compilationString+=e._declareOutput(i)+` = ${l}(${s.associatedVariableName}, ${n.associatedVariableName}, ${o.associatedVariableName}, ${a.associatedVariableName});\n`,e.compilationString+="#ifdef THIN_INSTANCES\n",e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName};\n`,e.compilationString+="#endif\n",t._caps.canUseGLInstanceID?e.compilationString+=e._declareOutput(r)+` = ${c}(${h});\n`:e.compilationString+=e._declareOutput(r)+" = 0.0;\n",e.compilationString+="#else\n",e.compilationString+=e._declareOutput(i)+` = ${this.world.associatedVariableName};\n`,e.compilationString+=e._declareOutput(r)+" = 0.0;\n",e.compilationString+="#endif\n",this}}(0,X.Y5)("BABYLON.InstancesBlock",vS);class xS extends Gg{constructor(e){super(e,Dg.Vertex),this.registerInput("position",Og.Vector3),this.registerInput("normal",Og.Vector3),this.registerInput("tangent",Og.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(Og.Color4|Og.Vector4|Og.Vector3),this.registerInput("uv",Og.Vector2),this.registerOutput("positionOutput",Og.Vector3),this.registerOutput("normalOutput",Og.Vector3),this.registerOutput("tangentOutput",Og.Vector4),this.registerOutput("uvOutput",Og.Vector2)}getClassName(){return"MorphTargetsBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get tangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get positionOutput(){return this._outputs[0]}get normalOutput(){return this._outputs[1]}get tangentOutput(){return this._outputs[2]}get uvOutput(){return this._outputs[3]}initialize(e){e._excludeVariableName("morphTargetInfluences"),this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,1===e?await Promise.all([Promise.resolve().then(i.bind(i,43610)),Promise.resolve().then(i.bind(i,51148)),Promise.resolve().then(i.bind(i,8573)),Promise.resolve().then(i.bind(i,47381))]):await Promise.all([Promise.resolve().then(i.bind(i,44219)),Promise.resolve().then(i.bind(i,11783)),Promise.resolve().then(i.bind(i,99216)),Promise.resolve().then(i.bind(i,9158))]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}autoConfigure(e,t=(()=>!0)){if(!this.position.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name&&t(e)));i||(i=new Kg("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name&&t(e)));i||(i=new Kg("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name&&t(e)));i||(i=new Kg("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name&&t(e)));i||(i=new Kg("uv"),i.setAsAttribute("uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){const t=e.morphTargetManager;t?.isUsingTextureForTargets&&(t.numMaxInfluencers||t.numInfluencers)!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&(0,Bt.Jz)(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&((0,Bt.nR)(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,r){const s=this.position,n=this.normal,o=this.tangent,a=this.uv,l=this.positionOutput,h=this.normalOutput,c=this.tangentOutput,u=this.uvOutput,d=e,f=r.NUM_MORPH_INFLUENCERS,p=i.morphTargetManager,_=p&&p.supportsNormals&&r.NORMAL,m=p&&p.supportsTangents&&r.TANGENT,g=p&&p.supportsUVs&&r.UV1;let v="";p?.isUsingTextureForTargets&&f>0&&(v+=`${d._declareLocalVar("vertexID",Og.Float)};\n`),v+="#ifdef MORPHTARGETS\n";const x=1===d.shaderLanguage,b=x?"uniforms.":"";if(p?.isUsingTextureForTargets)v+=`for (${x?"var":"int"} i = 0; i < NUM_MORPH_INFLUENCERS; i++) {\n`,v+=`if (i >= ${b}morphTargetCount) { break; }\n`,v+=`vertexID = ${x?"f32(vertexInputs.vertexIndex":"float(gl_VertexID"}) * ${b}morphTargetTextureInfo.x;\n`,v+=`${l.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${s.associatedVariableName}) * ${b}morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",_&&(v+="#ifdef MORPHTARGETS_NORMAL\n",v+=`${h.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${n.associatedVariableName}) * ${b}morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",v+="#endif\n"),g&&(v+="#ifdef MORPHTARGETS_UV\n",v+=`${u.associatedVariableName} += (readVector3FromRawSampler(i, vertexID).xy - ${a.associatedVariableName}) * ${b}morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",v+="#endif\n"),m&&(v+="#ifdef MORPHTARGETS_TANGENT\n",v+=`${c.associatedVariableName}.xyz += (readVector3FromRawSampler(i, vertexID) - ${o.associatedVariableName}.xyz) * ${b}morphTargetInfluences[i];\n`,o.type===Og.Vector4?v+=`${c.associatedVariableName}.w = ${o.associatedVariableName}.w;\n`:v+=`${c.associatedVariableName}.w = 1.;\n`,v+="#endif\n"),v+="}\n";else for(let e=0;e0)for(let e=0;e!0)){if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.isSystemValue&&e.systemValue===Lg.World&&t(e)));i||(i=new Kg("world"),i.setAsSystemValue(Lg.World)),i.output.connectTo(this.world)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name&&t(e)));i||(i=new Kg("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name&&e.type===Og.Vector4&&t(e)));i||(i=new Kg("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){const r=this.normal,s=this.tangent;let n=r.isConnected;r.connectInputBlock?.isAttribute&&!e.isVerticesDataPresent(r.connectInputBlock?.name)&&(n=!1);let o=s.isConnected;s.connectInputBlock?.isAttribute&&!e.isVerticesDataPresent(s.connectInputBlock?.name)&&(o=!1);const a=n&&o;i.setValue("TBNBLOCK",a,!0)}_buildBlock(e){super._buildBlock(e);const t=this.normal,i=this.tangent,r=this.world,s=this.TBN,n=this.row0,o=this.row1,a=this.row2,l=1===e.shaderLanguage,h=l?"mat3x3f":"mat3",c=l?"f":"";return e.target===Dg.Fragment&&(e.compilationString+=`\n // ${this.name}\n ${e._declareLocalVar("tbnNormal",Og.Vector3)} = normalize(${t.associatedVariableName}).xyz;\n ${e._declareLocalVar("tbnTangent",Og.Vector3)} = normalize(${i.associatedVariableName}.xyz);\n ${e._declareLocalVar("tbnBitangent",Og.Vector3)} = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w;\n ${l?"var":"mat3"} ${s.associatedVariableName} = ${h}(${r.associatedVariableName}[0].xyz, ${r.associatedVariableName}[1].xyz, ${r.associatedVariableName}[2].xyz) * ${h}(tbnTangent, tbnBitangent, tbnNormal);\n `,n.hasEndpoints&&(e.compilationString+=e._declareOutput(n)+` = vec3${c}(${s.associatedVariableName}[0][0], ${s.associatedVariableName}[0][1], ${s.associatedVariableName}[0][2]);\n`),o.hasEndpoints&&(e.compilationString+=e._declareOutput(o)+` = vec3${c}(${s.associatedVariableName}[1[0], ${s.associatedVariableName}[1][1], ${s.associatedVariableName}[1][2]);\n`),a.hasEndpoints&&(e.compilationString+=e._declareOutput(a)+` = vec3${c}(${s.associatedVariableName}[2][0], ${s.associatedVariableName}[2][1], ${s.associatedVariableName}[2][2]);\n`),e.sharedData.blocksWithDefines.push(this)),this}}(0,X.Y5)("BABYLON.TBNBlock",NS);class FS extends Gg{constructor(e){super(e,Dg.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",Og.Vector4,!1),this.registerInput("worldNormal",Og.Vector4,!1),this.registerInput("worldTangent",Og.Vector4,!0),this.registerInput("uv",Og.Vector2,!1),this.registerInput("normalMapColor",Og.Color3,!1),this.registerInput("strength",Og.Float,!1),this.registerInput("viewDirection",Og.Vector3,!0),this.registerInput("parallaxScale",Og.Float,!0),this.registerInput("parallaxHeight",Og.Float,!0),this.registerInput("TBN",Og.Object,!0,Dg.VertexAndFragment,new cS("TBN",this,0,NS,"TBNBlock")),this.registerInput("world",Og.Matrix,!0),this.registerOutput("output",Og.Vector4),this.registerOutput("uvOffset",Og.Vector2)}getClassName(){return"PerturbNormalBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get worldTangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get normalMapColor(){return this._inputs[4]}get strength(){return this._inputs[5]}get viewDirection(){return this._inputs[6]}get parallaxScale(){return this._inputs[7]}get parallaxHeight(){return this._inputs[8]}get TBN(){return this._inputs[9]}get world(){return this._inputs[10]}get output(){return this._outputs[0]}get uvOffset(){return this._outputs[1]}initialize(e){this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,1===e?await Promise.all([Promise.resolve().then(i.bind(i,99312)),Promise.resolve().then(i.bind(i,56332)),Promise.resolve().then(i.bind(i,87087))]):await Promise.all([Promise.resolve().then(i.bind(i,90249)),Promise.resolve().then(i.bind(i,82267)),Promise.resolve().then(i.bind(i,29424))]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}prepareDefines(e,t,i){const r=this.normalMapColor.connectedPoint._ownerBlock.samplerName,s=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&r||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",s,!0),i.setValue("PARALLAX_RHS",t.getScene().useRightHandedSystem,!0),i.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0),i.setValue("OBJECTSPACE_NORMALMAP",this.useObjectSpaceNormalMap,!0)}bind(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1),i&&(e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1),this.useObjectSpaceNormalMap&&!this.world.isConnected&&e.setMatrix(this._worldMatrixName,i.getWorldMatrix()))}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name&&t(e)));i||(i=new Kg("uv"),i.setAsAttribute()),i.output.connectTo(this.uv)}if(!this.strength.isConnected){const e=new Kg("strength");e.value=1,e.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`,i=this.uv,r=this.worldPosition,s=this.worldNormal,n=this.worldTangent,o=1===e.shaderLanguage,a=o?"mat3x3f":"mat3",l=o?"f":"",h=o?"uniforms.":"";e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=e._getFreeDefineName("tangentSpaceParameter"),e._emitUniformFromString(this._tangentSpaceParameterName,Og.Vector2),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,Og.Float),this._worldMatrixName=e._getFreeDefineName("perturbNormalWorldMatrix"),e._emitUniformFromString(this._worldMatrixName,Og.Matrix);let c=null;this.normalMapColor.connectedPoint&&(c=this.normalMapColor.connectedPoint._ownerBlock.samplerName);const u=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&c||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),d=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?e._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",f=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?`\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n${e._emitFloat(this.strength.connectInputBlock.value)}`:`\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n${this.strength.associatedVariableName}`;o||e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const p={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},_=this.TBN;_.isConnected?e.compilationString+=`\n #ifdef TBNBLOCK\n ${o?"var":"mat3"} vTBN = ${_.associatedVariableName};\n #endif\n `:n.isConnected&&(e.compilationString+=`${e._declareLocalVar("tbnNormal",Og.Vector3)} = normalize(${s.associatedVariableName}.xyz);\n`,e.compilationString+=`${e._declareLocalVar("tbnTangent",Og.Vector3)} = normalize(${n.associatedVariableName}.xyz);\n`,e.compilationString+=`${e._declareLocalVar("tbnBitangent",Og.Vector3)} = cross(tbnNormal, tbnTangent) * ${o?"uniforms.":""}${this._tangentCorrectionFactorName};\n`,e.compilationString+=`${o?"var":"mat3"} vTBN = ${a}(tbnTangent, tbnBitangent, tbnNormal);\n`);let m=[p,{search:/varying mat3 vTBN;/g,replace:""},{search:/uniform mat4 normalMatrix;/g,replace:""}];o&&(m.push({search:/varying vTBN0: vec3f;/g,replace:""}),m.push({search:/varying vTBN1: vec3f;/g,replace:""}),m.push({search:/varying vTBN2: vec3f;/g,replace:""})),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:m});const g=o?"fn parallaxOcclusion(vViewDirCoT: vec3f, vNormalCoT: vec3f, texCoord: vec2f, parallaxScale:f32, bump: texture_2d, bumpSampler: sampler)":"#define inline\nvec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)",v=o?/fn parallaxOcclusion\(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32\)/g:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,x=o?"fn parallaxOffset(viewDir: vec3f, heightScale: f32, height_: f32)":"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)",b=o?/fn parallaxOffset\(viewDir: vec3f,heightScale: f32\)/g:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g;e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:v,replace:g},{search:b,replace:x},{search:/texture.+?bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});const S=u&&c?`${o?`textureSample(${c}, ${c+"Sampler"}`:`texture2D(${c}`}, ${i.associatedVariableName} + uvOffset).xyz`:this.normalMapColor.associatedVariableName,T=e._getFreeVariableName("tempOutput");return e.compilationString+=e._declareLocalVar(T,Og.Vector3)+` = vec3${l}(0.);\n`,m=[{search:new RegExp(`texture.+?bumpSampler${o?"Sampler,fragmentInputs.":","}vBumpUV\\)`,"g"),replace:`${S}`},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:`${e._declareLocalVar("normalMatrix",Og.Matrix)} = toNormalMatrix(${this.world.isConnected?this.world.associatedVariableName:this._worldMatrixName});`},{search:new RegExp(`perturbNormal\\(TBN,texture.+?bumpSampler${o?"Sampler,fragmentInputs.":","}vBumpUV\\+uvOffset\\).xyz,${o?"uniforms.":""}vBumpInfos.y\\)`,"g"),replace:`perturbNormal(TBN, ${S}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${o?u&&this.useParallaxOcclusion?`${c}, ${c+"Sampler"}`:"bump, bumpSampler":u&&this.useParallaxOcclusion?c:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${u?this.parallaxHeight.associatedVariableName:"0."})`},{search:/vBumpInfos.y/g,replace:f},{search:/vBumpInfos.z/g,replace:d},{search:/normalW=/g,replace:T+" = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:`${a}(normalMatrix) * `+T},{search:/normalW/g,replace:s.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:u?this.viewDirection.associatedVariableName:`vec3${l}(0.)`},p],o?(m.push({search:/fragmentInputs.vBumpUV/g,replace:i.associatedVariableName}),m.push({search:/input.vPositionW/g,replace:r.associatedVariableName+".xyz"}),m.push({search:/uniforms.vTangentSpaceParams/g,replace:h+this._tangentSpaceParameterName}),m.push({search:/var TBN: mat3x3f=mat3x3\(input.vTBN0,input.vTBN1,input.vTBN2\);/g,replace:"var TBN = vTBN;"})):(m.push({search:/vBumpUV/g,replace:i.associatedVariableName}),m.push({search:/vPositionW/g,replace:r.associatedVariableName+".xyz"}),m.push({search:/vTangentSpaceParams/g,replace:h+this._tangentSpaceParameterName})),e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:m}),e.compilationString+=e._declareOutput(this.output)+` = vec4${l}(${T}, 0.);\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX};\n`;return e+=`${this._codeVariableName}.invertY = ${this.invertY};\n`,e+=`${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion};\n`,e+=`${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap};\n`,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}}(0,je.Cg)([t_("Invert X axis",0,"PROPERTIES",{embedded:!0,notifiers:{update:!1}})],FS.prototype,"invertX",void 0),(0,je.Cg)([t_("Invert Y axis",0,"PROPERTIES",{embedded:!0,notifiers:{update:!1}})],FS.prototype,"invertY",void 0),(0,je.Cg)([t_("Use parallax occlusion",0,void 0,{embedded:!0,notifiers:{update:!1}})],FS.prototype,"useParallaxOcclusion",void 0),(0,je.Cg)([t_("Object Space Mode",0,"PROPERTIES",{embedded:!0,notifiers:{update:!1}})],FS.prototype,"useObjectSpaceNormalMap",void 0),(0,X.Y5)("BABYLON.PerturbNormalBlock",FS);class LS extends Gg{constructor(e){super(e,Dg.Fragment,!0),this.registerInput("value",Og.Float,!0),this.registerInput("cutoff",Og.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; }\n`,this}}(0,X.Y5)("BABYLON.DiscardBlock",LS);class BS extends Gg{constructor(e){super(e,Dg.Fragment),this.registerOutput("output",Og.Float,Dg.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===Dg.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary("1.0","0.0",0===e.shaderLanguage?"gl_FrontFacing":"fragmentInputs.frontFacing")};\n`,this}}(0,X.Y5)("BABYLON.FrontFacingBlock",BS);class VS extends Gg{constructor(e){super(e,Dg.Fragment),this.registerInput("input",Og.AutoDetect,!1),this.registerOutput("dx",Og.BasedOnInput),this.registerOutput("dy",Og.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[1]._typeConnectionSource=this._inputs[0]}getClassName(){return"DerivativeBlock"}get input(){return this._inputs[0]}get dx(){return this._outputs[0]}get dy(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._outputs[1];e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let r="dFdx",s="dFdy";return 1===e.shaderLanguage&&(r="dpdx",s="dpdy"),t.hasEndpoints&&(e.compilationString+=e._declareOutput(t)+` = ${r}(${this.input.associatedVariableName});\n`),i.hasEndpoints&&(e.compilationString+=e._declareOutput(i)+` = ${s}(${this.input.associatedVariableName});\n`),this}}(0,X.Y5)("BABYLON.DerivativeBlock",VS);class kS extends Gg{constructor(e){super(e,Dg.Fragment),this.registerOutput("xy",Og.Vector2,Dg.Fragment),this.registerOutput("xyz",Og.Vector3,Dg.Fragment),this.registerOutput("xyzw",Og.Vector4,Dg.Fragment),this.registerOutput("x",Og.Float,Dg.Fragment),this.registerOutput("y",Og.Float,Dg.Fragment),this.registerOutput("z",Og.Float,Dg.Fragment),this.registerOutput("w",Og.Float,Dg.Fragment)}getClassName(){return"FragCoordBlock"}get xy(){return this._outputs[0]}get xyz(){return this._outputs[1]}get xyzw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get output(){return this._outputs[6]}writeOutputs(e){let t="";const i=1===e.shaderLanguage?"fragmentInputs.position":"gl_FragCoord";for(const r of this._outputs)r.hasEndpoints&&(t+=`${e._declareOutput(r)} = ${i}.${r.name};\n`);return t}_buildBlock(e){if(super._buildBlock(e),e.target===Dg.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}}(0,X.Y5)("BABYLON.FragCoordBlock",kS);class US extends Gg{constructor(e){super(e,Dg.Fragment),this.registerOutput("xy",Og.Vector2,Dg.Fragment),this.registerOutput("x",Og.Float,Dg.Fragment),this.registerOutput("y",Og.Float,Dg.Fragment)}getClassName(){return"ScreenSizeBlock"}get xy(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}bind(e){const t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())}writeOutputs(e,t){let i="";for(const r of this._outputs)r.hasEndpoints&&(i+=`${e._declareOutput(r)} = ${t}.${r.name};\n`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===Dg.Vertex)throw"ScreenSizeBlock must only be used in a fragment shader";e.sharedData.bindableBlocks.push(this),this._varName=e._getFreeVariableName("screenSize"),e._emitUniformFromString(this._varName,Og.Vector2);const t=1===e.shaderLanguage?"uniforms.":"";return e.compilationString+=this.writeOutputs(e,t+this._varName),this}}(0,X.Y5)("BABYLON.ScreenSizeBlock",US);class GS extends Gg{constructor(e){super(e,Dg.Fragment),this.registerInput("vector",Og.AutoDetect),this.registerInput("worldViewProjection",Og.Matrix),this.registerOutput("output",Og.Vector2),this.registerOutput("x",Og.Float),this.registerOutput("y",Og.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(Og.Color3|Og.Vector3|Og.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((e=>e.systemValue===Lg.WorldViewProjection&&t(e)));i||(i=new Kg("worldViewProjection"),i.setAsSystemValue(Lg.WorldViewProjection)),i.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;const r=i.associatedVariableName,s=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case Og.Vector3:e.compilationString+=`${e._declareLocalVar(s,Og.Vector4)} = ${r} * vec4${e.fSuffix}(${t.associatedVariableName}, 1.0);\n`;break;case Og.Vector4:e.compilationString+=`${e._declareLocalVar(s,Og.Vector4)} = ${r} * ${t.associatedVariableName};\n`}return e.compilationString+=`${s} = vec4${e.fSuffix}(${s}.xy / ${s}.w, ${s}.zw);`,e.compilationString+=`${s} = vec4${e.fSuffix}(${s}.xy * 0.5 + vec2${e.fSuffix}(0.5, 0.5), ${s}.zw);`,this.output.hasEndpoints&&(e.compilationString+=e._declareOutput(this.output)+` = ${s}.xy;\n`),this.x.hasEndpoints&&(e.compilationString+=e._declareOutput(this.x)+` = ${s}.x;\n`),this.y.hasEndpoints&&(e.compilationString+=e._declareOutput(this.y)+` = ${s}.y;\n`),this}}(0,X.Y5)("BABYLON.ScreenSpaceBlock",GS);class zS extends Gg{constructor(e){super(e,Dg.Fragment),this.registerInput("input",Og.Vector2),this.registerInput("strength",Og.Float),this.registerInput("center",Og.Vector2),this.registerInput("offset",Og.Vector2),this.registerOutput("output",Og.Vector2),this.registerOutput("x",Og.Float),this.registerOutput("y",Og.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 Kg("center");e.value=new W.I9(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){const e=new Kg("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){const e=new Kg("offset");e.value=new W.I9(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);const t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),r=e._getFreeVariableName("x"),s=e._getFreeVariableName("y"),n=e._getFreeVariableName("result");return e.compilationString+=` \n ${e._declareLocalVar(t,Og.Vector2)} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName};\n ${e._declareLocalVar(i,Og.Float)} = ${this.strength.associatedVariableName} * length(${t});\n ${e._declareLocalVar(r,Og.Float)} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y;\n ${e._declareLocalVar(s,Og.Float)} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y;\n ${e._declareLocalVar(n,Og.Vector2)} = vec2(${r} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${s} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y);\n `,this.output.hasEndpoints&&(e.compilationString+=e._declareOutput(this.output)+` = ${n};\n`),this.x.hasEndpoints&&(e.compilationString+=e._declareOutput(this.x)+` = ${n}.x;\n`),this.y.hasEndpoints&&(e.compilationString+=e._declareOutput(this.y)+` = ${n}.y;\n`),this}}(0,X.Y5)("BABYLON.TwirlBlock",zS);class WS extends Gg{constructor(e){super(e,Dg.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",Og.Float),this.registerInput("worldPosition",Og.Vector3),this.registerInput("worldNormal",Og.Vector3),this.registerInput("worldTangent",Og.AutoDetect,!0),this.registerOutput("output",Og.Vector4),this.registerOutput("xyz",Og.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(Og.Color3|Og.Vector3|Og.Vector4)}getClassName(){return"HeightToNormalBlock"}get input(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=1===e.shaderLanguage,r=e.fSuffix;this.generateInWorldSpace||this.worldTangent.isConnected||Z.V.Error(`You must connect the 'worldTangent' input of the ${this.name} block!`);const s=this.generateInWorldSpace?"":"\n vec3 biTangent = cross(norm, tgt);\n mat3 TBN = mat3(tgt, biTangent, norm);\n ",n=this.generateInWorldSpace?"":"\n result = TBN * result;\n result = result * vec3(0.5) + vec3(0.5);\n ";let o=`\n vec4 heightToNormal(float height, vec3 position, vec3 tangent, vec3 normal) {\n vec3 tgt = ${this.automaticNormalizationTangent?"normalize(tangent);":"tangent;"}\n vec3 norm = ${this.automaticNormalizationNormal?"normalize(normal);":"normal;"}\n ${s}\n vec3 worlddX = dFdx(position);\n vec3 worlddY = dFdy(position);\n vec3 crossX = cross(norm, worlddX);\n vec3 crossY = cross(worlddY, norm);\n float d = abs(dot(crossY, worlddX));\n vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d));\n inToNormal.y *= -1.0;\n vec3 result = normalize((d * norm) - inToNormal);\n ${n}\n return vec4(result, 0.);\n }`;return i?o=e._babylonSLtoWGSL(o):e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitFunction("heightToNormal",o,"// heightToNormal"),e.compilationString+=e._declareOutput(t)+` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected?this.worldTangent.associatedVariableName:`vec3${r}(0.)`}.xyz, ${this.worldNormal.associatedVariableName});\n`,this.xyz.hasEndpoints&&(e.compilationString+=e._declareOutput(this.xyz)+` = ${this.output.associatedVariableName}.xyz;\n`),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace};\n`,e+=`${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal};\n`,e+=`${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent};\n`,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}}(0,je.Cg)([t_("Generate in world space instead of tangent space",0,"PROPERTIES",{notifiers:{update:!0}})],WS.prototype,"generateInWorldSpace",void 0),(0,je.Cg)([t_("Force normalization for the worldNormal input",0,"PROPERTIES",{notifiers:{update:!0}})],WS.prototype,"automaticNormalizationNormal",void 0),(0,je.Cg)([t_("Force normalization for the worldTangent input",0,"PROPERTIES",{notifiers:{update:!0}})],WS.prototype,"automaticNormalizationTangent",void 0),(0,X.Y5)("BABYLON.HeightToNormalBlock",WS);class HS extends Gg{constructor(e){super(e,Dg.Fragment,!0),this.registerInput("depth",Og.Float,!0),this.registerInput("worldPos",Og.Vector4,!0),this.registerInput("viewProjection",Og.Matrix,!0)}getClassName(){return"FragDepthBlock"}get depth(){return this._inputs[0]}get worldPos(){return this._inputs[1]}get viewProjection(){return this._inputs[2]}_buildBlock(e){super._buildBlock(e);const t=0===e.shaderLanguage?"gl_FragDepth":"fragmentOutputs.fragDepth";return this.depth.isConnected?e.compilationString+=`${t} = ${this.depth.associatedVariableName};\n`:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=`\n ${e._declareLocalVar("p",Og.Vector4)} = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName};\n ${e._declareLocalVar("v",Og.Float)} = p.z / p.w;\n #ifndef IS_NDC_HALF_ZRANGE\n v = v * 0.5 + 0.5;\n #endif\n ${t} = v;\n \n `:Z.V.Warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}}(0,X.Y5)("BABYLON.FragDepthBlock",HS);class XS extends Gg{constructor(e){super(e,Dg.Fragment),this.registerInput("worldPosition",Og.Vector4,!1),this.registerInput("viewProjection",Og.Matrix,!1),this.registerInput("worldNormal",Og.AutoDetect,!0),this.registerOutput("depth",Og.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(Og.Color3|Og.Vector3|Og.Vector4)}getClassName(){return"ShadowMapBlock"}initialize(e){e._excludeVariableName("vPositionWSM"),e._excludeVariableName("lightDataSM"),e._excludeVariableName("biasAndScaleSM"),e._excludeVariableName("depthValuesSM"),e._excludeVariableName("clipPos"),e._excludeVariableName("worldPos"),e._excludeVariableName("zSM"),this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,1===e?await Promise.all([Promise.resolve().then(i.bind(i,18902)),Promise.resolve().then(i.bind(i,2456)),Promise.resolve().then(i.bind(i,43140))]):await Promise.all([Promise.resolve().then(i.bind(i,94949)),Promise.resolve().then(i.bind(i,72693)),Promise.resolve().then(i.bind(i,73391))]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}get worldPosition(){return this._inputs[0]}get viewProjection(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get depth(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`,i=1===e.shaderLanguage;e._emitUniformFromString("biasAndScaleSM",Og.Vector3),e._emitUniformFromString("lightDataSM",Og.Vector3),e._emitUniformFromString("depthValuesSM",Og.Vector2),e._emitFunctionFromInclude("packingFunctions",t),e.compilationString+=`${e._declareLocalVar("worldPos",Og.Vector4)} = ${this.worldPosition.associatedVariableName};\n`,e.compilationString+=`${e._declareLocalVar("vPositionWSM",Og.Vector3)};\n`,e.compilationString+=`${e._declareLocalVar("vDepthMetricSM",Og.Float)} = 0.0;\n`,e.compilationString+=`${e._declareLocalVar("zSM",Og.Float)};\n`,this.worldNormal.isConnected&&(e.compilationString+=`${e._declareLocalVar("vNormalW",Og.Vector3)} = ${this.worldNormal.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`${e._declareLocalVar("clipPos",Og.Vector4)} = ${this.viewProjection.associatedVariableName} * worldPos;\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"},{search:/vertexOutputs.position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]});const r=i?"fragmentOutputs.fragDepth":"gl_FragDepth";return e.compilationString+=`\n #if SM_DEPTHTEXTURE == 1\n #ifdef IS_NDC_HALF_ZRANGE\n ${r} = (clipPos.z / clipPos.w);\n #else\n ${r} = (clipPos.z / clipPos.w) * 0.5 + 0.5;\n #endif\n #endif\n `,e.compilationString+=`${e._declareOutput(this.depth)} = vec3${e.fSuffix}(depthSM, 1., 1.);\n`,this}}(0,X.Y5)("BABYLON.ShadowMapBlock",XS);class qS extends Gg{constructor(e){super(e,Dg.Fragment,!0),this.registerInput("viewDepth",Og.Float,!0),this.registerInput("screenDepth",Og.Float,!0),this.registerInput("worldPosition",Og.AutoDetect,!0),this.registerInput("localPosition",Og.AutoDetect,!0),this.registerInput("viewNormal",Og.AutoDetect,!0),this.registerInput("worldNormal",Og.AutoDetect,!0),this.registerInput("reflectivity",Og.AutoDetect,!0),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(Og.Vector3|Og.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(Og.Vector3|Og.Vector4),this.inputs[4].addExcludedConnectionPointFromAllowedTypes(Og.Vector3|Og.Vector4),this.inputs[5].addExcludedConnectionPointFromAllowedTypes(Og.Vector3|Og.Vector4),this.inputs[6].addExcludedConnectionPointFromAllowedTypes(Og.Vector3|Og.Vector4|Og.Color3|Og.Color4)}getClassName(){return"PrePassOutputBlock"}get viewDepth(){return this._inputs[0]}get screenDepth(){return this._inputs[1]}get worldPosition(){return this._inputs[2]}get localPosition(){return this._inputs[3]}get viewNormal(){return this._inputs[4]}get worldNormal(){return this._inputs[5]}get reflectivity(){return this._inputs[6]}_getFragData(e,t){return e?`fragmentOutputs.fragData${t}`:`gl_FragData[${t}]`}_buildBlock(e){super._buildBlock(e);const t=this.worldPosition,i=this.localPosition,r=this.viewNormal,s=this.worldNormal,n=this.viewDepth,o=this.reflectivity,a=this.screenDepth;e.sharedData.blocksWithDefines.push(this);const l=`//${this.name}`,h=e._getShaderType(Og.Vector4),c=1===e.shaderLanguage;return e._emitFunctionFromInclude("helperFunctions",l),e.compilationString+="#if defined(PREPASS)\r\n",e.compilationString+=c?"var fragData: array, SCENE_MRT_COUNT>;\r\n":"vec4 fragData[SCENE_MRT_COUNT];\r\n",e.compilationString+="#ifdef PREPASS_DEPTH\r\n",n.connectedPoint?e.compilationString+=` fragData[PREPASS_DEPTH_INDEX] = ${h}(${n.associatedVariableName}, 0.0, 0.0, 1.0);\r\n`:e.compilationString+=` fragData[PREPASS_DEPTH_INDEX] = ${h}(0.0, 0.0, 0.0, 0.0);\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_SCREENSPACE_DEPTH\r\n",a.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_SCREENSPACE_DEPTH_INDEX] = vec4(${a.associatedVariableName}, 0.0, 0.0, 1.0);\r\n`:e.compilationString+=" gl_FragData[PREPASS_SCREENSPACE_DEPTH_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_POSITION\r\n",t.connectedPoint?e.compilationString+=`fragData[PREPASS_POSITION_INDEX] = ${h}(${t.associatedVariableName}.rgb, ${t.connectedPoint.type===Og.Vector4?t.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=` fragData[PREPASS_POSITION_INDEX] = ${h}(0.0, 0.0, 0.0, 0.0);\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_LOCAL_POSITION\r\n",i.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_LOCAL_POSITION_INDEX] = vec4(${i.associatedVariableName}.rgb, ${i.connectedPoint.type===Og.Vector4?i.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_LOCAL_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_NORMAL\r\n",r.connectedPoint?e.compilationString+=` fragData[PREPASS_NORMAL_INDEX] = ${h}(${r.associatedVariableName}.rgb, ${r.connectedPoint.type===Og.Vector4?r.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=` fragData[PREPASS_NORMAL_INDEX] = ${h}(0.0, 0.0, 0.0, 0.0);\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_WORLD_NORMAL\r\n",s.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_WORLD_NORMAL_INDEX] = vec4(${s.associatedVariableName}.rgb, ${s.connectedPoint.type===Og.Vector4?s.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_WORLD_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_REFLECTIVITY\r\n",o.connectedPoint?e.compilationString+=` fragData[PREPASS_REFLECTIVITY_INDEX] = ${h}(${o.associatedVariableName}.rgb, ${o.connectedPoint.type===Og.Vector4?o.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=` fragData[PREPASS_REFLECTIVITY_INDEX] = ${h}(0.0, 0.0, 0.0, 1.0);\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#if SCENE_MRT_COUNT > 1\r\n",e.compilationString+=`${this._getFragData(c,1)} = fragData[1];\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#if SCENE_MRT_COUNT > 2\r\n",e.compilationString+=`${this._getFragData(c,2)} = fragData[2];\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#if SCENE_MRT_COUNT > 3\r\n",e.compilationString+=`${this._getFragData(c,3)} = fragData[3];\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#if SCENE_MRT_COUNT > 4\r\n",e.compilationString+=`${this._getFragData(c,4)} = fragData[4];\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#if SCENE_MRT_COUNT > 5\r\n",e.compilationString+=`${this._getFragData(c,5)} = fragData[5];\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#if SCENE_MRT_COUNT > 6\r\n",e.compilationString+=`${this._getFragData(c,6)} = fragData[6];\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#if SCENE_MRT_COUNT > 7\r\n",e.compilationString+=`${this._getFragData(c,7)} = fragData[7];\r\n`,e.compilationString+="#endif\r\n",e.compilationString+="#endif\r\n",this}}(0,X.Y5)("BABYLON.PrePassOutputBlock",qS);var YS=i(33882),KS=i(33731),jS=i(94388),$S=i(75651),QS=i(88658),ZS=i(99312),JS=i(56332),eT=i(87087),tT=i(90249),iT=i(82267),rT=i(29424),sT=i(18902),nT=i(2456),oT=i(43140),aT=i(94949),lT=i(72693),hT=i(73391);class cT extends Gg{constructor(e){super(e,Dg.VertexAndFragment,!1),this.registerInput("worldPosition",Og.Vector4,!1,Dg.Vertex),this.registerInput("view",Og.Matrix,!1,Dg.Vertex),this.registerInput("input",Og.AutoDetect,!1,Dg.Fragment),this.registerInput("fogColor",Og.AutoDetect,!1,Dg.Fragment),this.registerOutput("output",Og.Color3,Dg.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(Og.Color3|Og.Vector3|Og.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(Og.Color3|Og.Vector3|Og.Color4)}getClassName(){return"FogBlock"}get worldPosition(){return this._inputs[0]}get view(){return this._inputs[1]}get input(){return this._inputs[2]}get fogColor(){return this._inputs[3]}get output(){return this._outputs[0]}initialize(e){this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,1===e?await Promise.resolve().then(i.bind(i,10668)):await Promise.resolve().then(i.bind(i,64657)),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}autoConfigure(e,t=(()=>!0)){if(!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Lg.View&&t(e)));i||(i=new Kg("view"),i.setAsSystemValue(Lg.View)),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Lg.FogColor&&t(e)));i||(i=new Kg("fogColor",void 0,Og.Color3),i.setAsSystemValue(Lg.FogColor)),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){const r=e.getScene();i.setValue("FOG",t.fogEnabled&&(0,Bt.qL)(e,r))}bind(e,t,i){if(!i)return;const r=i.getScene();e.setFloat4(this._fogParameters,r.fogMode,r.fogStart,r.fogEnd,r.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===Dg.Fragment){e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);let t=[],i="",r="";1===e.shaderLanguage?(t=[{search:/fn CalcFogFactor\(\)/,replace:"fn CalcFogFactor(vFogDistance: vec3f, vFogInfos: vec4f)"},{search:/uniforms.vFogInfos/g,replace:"vFogInfos"},{search:/fragmentInputs.vFogDistance/g,replace:"vFogDistance"}],i="fragmentInputs.",r="uniforms."):t=[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}],e._emitFunctionFromInclude("fogFragmentDeclaration",`//${this.name}`,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:t});const s=e._getFreeVariableName("fog"),n=this.input,o=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");const a=this._outputs[0];e._emitUniformFromString(this._fogParameters,Og.Vector4),e.compilationString+="#ifdef FOG\n",e.compilationString+=`${e._declareLocalVar(s,Og.Float)} = CalcFogFactor(${i}${this._fogDistanceName}, ${r}${this._fogParameters});\n`,e.compilationString+=e._declareOutput(a)+` = ${s} * ${n.associatedVariableName}.rgb + (1.0 - ${s}) * ${o.associatedVariableName}.rgb;\n`,e.compilationString+=`#else\n${e._declareOutput(a)} = ${n.associatedVariableName}.rgb;\n`,e.compilationString+="#endif\n"}else{const t=this.worldPosition,i=this.view;this._fogDistanceName=e._getFreeVariableName("vFogDistance"),e._emitVaryingFromString(this._fogDistanceName,Og.Vector3);const r=1===e.shaderLanguage?"vertexOutputs.":"";e.compilationString+=`${r}${this._fogDistanceName} = (${i.associatedVariableName} * ${t.associatedVariableName}).xyz;\n`}return this}}(0,X.Y5)("BABYLON.FogBlock",cT);class uT extends Gg{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,Z.V.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?Dg.Fragment:Dg.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?Dg.Fragment:Dg.Vertex}constructor(e){super(e,Dg.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",Og.Vector4,!1,Dg.Vertex),this.registerInput("worldNormal",Og.Vector4,!1,Dg.Fragment),this.registerInput("cameraPosition",Og.Vector3,!1,Dg.Fragment),this.registerInput("glossiness",Og.Float,!0,Dg.Fragment),this.registerInput("glossPower",Og.Float,!0,Dg.Fragment),this.registerInput("diffuseColor",Og.Color3,!0,Dg.Fragment),this.registerInput("specularColor",Og.Color3,!0,Dg.Fragment),this.registerInput("view",Og.Matrix,!0),this.registerOutput("diffuseOutput",Og.Color3,Dg.Fragment),this.registerOutput("specularOutput",Og.Color3,Dg.Fragment),this.registerOutput("shadow",Og.Float,Dg.Fragment)}getClassName(){return"LightBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get cameraPosition(){return this._inputs[2]}get glossiness(){return this._inputs[3]}get glossPower(){return this._inputs[4]}get diffuseColor(){return this._inputs[5]}get specularColor(){return this._inputs[6]}get view(){return this._inputs[7]}get diffuseOutput(){return this._outputs[0]}get specularOutput(){return this._outputs[1]}get shadow(){return this._outputs[2]}initialize(e){this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,1===e?await Promise.all([Promise.resolve().then(i.bind(i,55090)),Promise.resolve().then(i.bind(i,71426)),Promise.resolve().then(i.bind(i,85188)),Promise.resolve().then(i.bind(i,87647)),Promise.resolve().then(i.bind(i,34992)),Promise.resolve().then(i.bind(i,94662)),Promise.resolve().then(i.bind(i,48453))]):await Promise.all([Promise.resolve().then(i.bind(i,23133)),Promise.resolve().then(i.bind(i,81749)),Promise.resolve().then(i.bind(i,58769)),Promise.resolve().then(i.bind(i,19215)),Promise.resolve().then(i.bind(i,96951)),Promise.resolve().then(i.bind(i,94388)),Promise.resolve().then(i.bind(i,97295)),Promise.resolve().then(i.bind(i,34091)),Promise.resolve().then(i.bind(i,2946))]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}autoConfigure(e,t=(()=>!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Lg.CameraPosition&&t(e)));i||(i=new Kg("cameraPosition"),i.setAsSystemValue(Lg.CameraPosition)),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;const r=e.getScene();if(this.light){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};(0,Bt.lo)(r,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else(0,Bt.az)(r,e,i,!0,t.maxSimultaneousLights)}updateUniformsAndSamples(e,t,i,r){for(let s=0;s=0;(0,Bt.GD)(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],r,t)}}bind(e,t,i){if(!i)return;const r=i.getScene();this.light?(0,Bt.Kd)(this.light,this._lightId,r,e,!0):(0,Bt.RL)(r,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const r="v_"+t.associatedVariableName;e._emitVaryingFromString(r,Og.Vector4)&&(e.compilationString+=(1===e.shaderLanguage?"vertexOutputs.":"")+`${r} = ${t.associatedVariableName};\n`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`${e._declareLocalVar("worldPos",Og.Vector4)} = ${t.associatedVariableName};\n`,this.view.isConnected&&(e.compilationString+=`${e._declareLocalVar("view",Og.Matrix)} = ${this.view.associatedVariableName};\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_injectUBODeclaration(e){const t=`//${this.name}`;this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0})}_buildBlock(e){super._buildBlock(e);const t=1===e.shaderLanguage,i=t?"f":"",r=`//${this.name}`;if(e.target!==Dg.Fragment)return void this._injectVertexCode(e);this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const s=t?"fragmentInputs.":"";e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const n=this.worldPosition;let o=n.associatedVariableName;this.generateOnlyFragmentCode?(o=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`${e._declareLocalVar(o,Og.Vector3)};\n`,r),e.compilationString+=`${o} = ${n.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",r,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${n.associatedVariableName}`:void 0})):o=s+"v_"+o+".xyz",e._emitFunctionFromInclude("helperFunctions",r);let a={search:/vPositionW/g,replace:o};if(t&&(a={search:/fragmentInputs\.vPositionW/g,replace:o}),e._emitFunctionFromInclude("lightsFragmentFunctions",r,{replaceStrings:[a]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",r,{replaceStrings:[a]}),this._injectUBODeclaration(e),0===this._lightId&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`${e._declareLocalVar("viewDirectionW",Og.Vector3)} = normalize(${this.cameraPosition.associatedVariableName} - ${o});\n`),e.compilationString+=t?"var info: lightingInfo;\n":"lightingInfo info;\n",e.compilationString+=`${e._declareLocalVar("shadow",Og.Float)} = 1.;\n`,e.compilationString+=`${e._declareLocalVar("aggShadow",Og.Float)} = 0.;\n`,e.compilationString+=`${e._declareLocalVar("numLights",Og.Float)} = 0.;\n`,e.compilationString+=`${e._declareLocalVar("glossiness",Og.Float)} = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"};\n`,e.compilationString+=`${e._declareLocalVar("diffuseBase",Og.Vector3)} = vec3${i}(0., 0., 0.);\n`,e.compilationString+=`${e._declareLocalVar("specularBase",Og.Vector3)} = vec3${i}(0., 0., 0.);\n`,e.compilationString+=`${e._declareLocalVar("normalW",Og.Vector3)} = ${this.worldNormal.associatedVariableName}.xyz;\n`),this.light){let i={search:/vPositionW/g,replace:o+".xyz"};t&&(i={search:/fragmentInputs\.vPositionW/g,replace:o+".xyz"}),e.compilationString+=e._emitCodeFromInclude("lightFragment",r,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},i]})}else{let i=`vPositionW,${o}.xyz`;t&&(i=`fragmentInputs.vPositionW,${o}.xyz`),e.compilationString+=e._emitCodeFromInclude("lightFragment",r,{repeatKey:"maxSimultaneousLights",substitutionVars:i})}0===this._lightId&&(e.compilationString+="aggShadow = aggShadow / numLights;\n");const l=this.diffuseOutput,h=this.specularOutput;return e.compilationString+=e._declareOutput(l)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""};\n`,h.hasEndpoints&&(e.compilationString+=e._declareOutput(h)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""};\n`),this.shadow.hasEndpoints&&(e.compilationString+=e._declareOutput(this.shadow)+" = aggShadow;\n"),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()}}(0,je.Cg)([t_("Generate only fragment code",0,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:uT._OnGenerateOnlyFragmentCodeChanged}})],uT.prototype,"generateOnlyFragmentCode",void 0),(0,X.Y5)("BABYLON.LightBlock",uT);class dT extends Gg{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??he.q.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get samplerName(){return this._samplerName}constructor(e){super(e,Dg.VertexAndFragment),this.registerOutput("source",Og.Object,Dg.VertexAndFragment,new cS("source",this,1,dT,"ImageSourceBlock")),this.registerOutput("dimensions",Og.Vector2)}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]}get dimensions(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),e.target===Dg.Vertex&&(this._samplerName=e._getFreeVariableName(this.name+"Texture"),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this)),this.dimensions.isConnected){let t="";t=1===e.shaderLanguage?`vec2f(textureDimensions(${this._samplerName}, 0).xy)`:`vec2(textureSize(${this._samplerName}, 0).xy)`,e.compilationString+=`${e._declareOutput(this.dimensions)} = ${t};\n`}return 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});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&"VideoTexture"!==this.texture.getClassName()&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i,r){super._deserialize(e,t,i,r),e.texture&&!pv.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(0===e.texture.url.indexOf("data:")?i="":r&&(e.texture.url=r(e.texture.url),e.texture.name=e.texture.url),this.texture=vi.g.Parse(e.texture,t,i))}}(0,X.Y5)("BABYLON.ImageSourceBlock",dT);class fT extends Gg{get texture(){return this.source.isConnected?(this.source.connectedPoint?.ownerBlock).texture:this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??he.q.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}static _IsPrePassTextureBlock(e){return"PrePassTextureBlock"===e?.getClassName()}get _isSourcePrePass(){return fT._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!fT._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 e=this.texture.getScene()??he.q.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=this.texture.getScene()??he.q.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?Dg.Fragment:Dg.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",Og.AutoDetect,!1,Dg.VertexAndFragment),this.registerInput("source",Og.Object,!0,Dg.VertexAndFragment,new cS("source",this,0,dT,"ImageSourceBlock")),this.registerInput("layer",Og.Float,!0),this.registerInput("lod",Og.Float,!0),this.registerOutput("rgba",Og.Color4,Dg.Neutral),this.registerOutput("rgb",Og.Color3,Dg.Neutral),this.registerOutput("r",Og.Float,Dg.Neutral),this.registerOutput("g",Og.Float,Dg.Neutral),this.registerOutput("b",Og.Float,Dg.Neutral),this.registerOutput("a",Og.Float,Dg.Neutral),this.registerOutput("level",Og.Float,Dg.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(Og.Vector2|Og.Vector3|Og.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]}_isTiedToFragment(e){if(e.target===Dg.Fragment)return!0;if(e.target===Dg.Vertex)return!1;if(e.target===Dg.Neutral||e.target===Dg.VertexAndFragment){const t=e.ownerBlock;if(t.target===Dg.Fragment)return!0;for(const e of t.inputs)if(e.isConnected&&this._isTiedToFragment(e.connectedPoint))return!0}return!1}_getEffectiveTarget(){return this._fragmentOnly?Dg.Fragment:this.uv.isConnected?this.uv.sourceBlock.isInput?Dg.VertexAndFragment:this._isTiedToFragment(this.uv.connectedPoint)?Dg.Fragment:Dg.VertexAndFragment:Dg.VertexAndFragment}get target(){return this._getEffectiveTarget()}set target(e){}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected)if(e.mode===rv.PostProcess){const i=e.getBlockByPredicate((e=>"uv"===e.name&&t(e)));i&&i.connectTo(this)}else if(e.mode!==rv.ProceduralTexture){const i=e.mode===rv.Particle?"particle_uv":"uv";let r=e.getInputBlockByPredicate((e=>e.isAttribute&&e.name===i&&t(e)));r||(r=new Kg("uv"),r.setAsAttribute(i)),r.output.connectTo(this.uv)}}initializeDefines(e,t,i){i._areTexturesDirty&&void 0!==this._mainUVDefineName&&i.setValue(this._mainUVDefineName,!1,!0)}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;if(!this.texture||!this.texture.getTextureMatrix)return void(this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)));const r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,s,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),null==i[this._mainUVDefineName]&&i.setValue(this._mainUVDefineName,!1,!0)))}isReady(){return!!this._isSourcePrePass||!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this._isSourcePrePass&&e.setFloat(this._textureInfoName,1),this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),this._imageSource||e.setTexture(this._samplerName,this.texture))}get _isMixed(){return this.target!==Dg.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,Og.Vector2,this._defineName),e._emitVaryingFromString(this._mainUVName,Og.Vector2,this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,Og.Matrix,this._defineName);const i=e._getShaderType(Og.Vector4),r=e._getShaderType(Og.Vector2);e.compilationString+=`#ifdef ${this._defineName}\n`,e.compilationString+=`${e._getVaryingName(this._transformedUVName)} = ${r}(${this._textureTransformName} * ${i}(${t.associatedVariableName}.xy, 1.0, 0.0));\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\n`;let s="";if(1===e.shaderLanguage&&t.isConnectedToInputBlock&&-1===t.associatedVariableName.indexOf("vertexInputs.")&&(s="vertexInputs."),e.compilationString+=`${e._getVaryingName(this._mainUVName)} = ${s}${t.associatedVariableName}.xy;\n`,e.compilationString+="#endif\n",this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name,!0)}}_getUVW(e){let t=e;const i=this._texture?._texture?.is2DArray??!1,r=this._texture?._texture?.is3D??!1;return(i||r)&&(t=`vec3(${e}, ${this.layer.isConnected?this.layer.associatedVariableName:"0"})`),t}_samplerFunc(e){return 1===e.shaderLanguage?e.target===Dg.Vertex?"textureSampleLevel":"textureSample":this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureSample(e,t){if(1===t.shaderLanguage){const i=t.target===Dg.Vertex;return`${this._samplerFunc(t)}(${this.samplerName},${this.samplerName+"Sampler"}, ${this._getUVW(e)}${this._samplerLodSuffix}${i?", 0":""})`}return`${this._samplerFunc(t)}(${this.samplerName}, ${this._getUVW(e)}${this._samplerLodSuffix})`}_generateTextureLookup(e){e.compilationString+=`#ifdef ${this._defineName}\n`,e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = ${this._generateTextureSample(e._getVaryingName(this._transformedUVName),e)};\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\n`,e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = ${this._generateTextureSample(this._mainUVName?e._getVaryingName(this._mainUVName):this.uv.associatedVariableName,e)}${this._samplerLodSuffix};\n`,e.compilationString+="#endif\n"}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===Dg.Fragment)return;this._generateTextureLookup(e)}else this.uv.ownerBlock.target!==Dg.Fragment?this._generateTextureLookup(e):e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = ${this._generateTextureSample(i.associatedVariableName,e)}${this._samplerLodSuffix};\n`}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = ${e._toLinearSpace(t)};\n #endif\n `)}_writeOutput(e,t,i,r=!1){if(r){if(e.target===Dg.Fragment)return;return e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,void this._generateConversionCode(e,t,i)}if(this.uv.ownerBlock.target===Dg.Fragment)return e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,void this._generateConversionCode(e,t,i);let s="";this.disableLevelMultiplication||(s=" * "+(1===e.shaderLanguage?"uniforms.":"")+this._textureInfoName),e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}${s};\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===Dg.Vertex||this._fragmentOnly||e.target===Dg.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),!this._isMixed&&e.target===Dg.Fragment||this._isMixed&&e.target===Dg.Vertex){if(!this._imageSource){const t=e._getFreeVariableName(this.name);this._samplerName=t+"Texture",this._texture?._texture?.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName)}e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this)}if(e.target!==Dg.Fragment)return void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;this._isMixed&&!this._imageSource&&(this._texture?._texture?.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._isMixed&&e._emitUniformFromString(this._textureInfoName,Og.Float),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):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||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i,r){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this._fragmentOnly=!!e.fragmentOnly,this.disableLevelMultiplication=!!e.disableLevelMultiplication,e.texture&&!pv.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(0===e.texture.url.indexOf("data:")?i="":r&&(e.texture.url=r(e.texture.url),e.texture.name=e.texture.url),this.texture=vi.g.Parse(e.texture,t,i))}}(0,X.Y5)("BABYLON.TextureBlock",fT);class pT extends Gg{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??he.q.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?Dg.Fragment:Dg.VertexAndFragment)}constructor(e){super(e,Dg.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}initialize(e){this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,1===e?await Promise.resolve().then(i.bind(i,7769)):await Promise.resolve().then(i.bind(i,51068)),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}autoConfigure(e,t=(()=>!0)){if(!this.position.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name&&t(e)));i||(i=new Kg("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Lg.World&&t(e)));i||(i=new Kg("world"),i.setAsSystemValue(Lg.World)),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Lg.View&&t(e)));i||(i=new Kg("view"),i.setAsSystemValue(Lg.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const r=this._getTexture();r&&r.getTextureMatrix&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLocalCubicName,!!r.boundingBoxSize,!0),i.setValue(this._defineExplicitName,0===r.coordinatesMode,!0),i.setValue(this._defineSkyboxName,5===r.coordinatesMode,!0),i.setValue(this._defineCubicName,3===r.coordinatesMode||6===r.coordinatesMode,!0),i.setValue("INVERTCUBICMAP",6===r.coordinatesMode,!0),i.setValue(this._defineSphericalName,1===r.coordinatesMode,!0),i.setValue(this._definePlanarName,2===r.coordinatesMode,!0),i.setValue(this._defineProjectionName,4===r.coordinatesMode,!0),i.setValue(this._defineEquirectangularName,7===r.coordinatesMode,!0),i.setValue(this._defineEquirectangularFixedName,8===r.coordinatesMode,!0),i.setValue(this._defineMirroredEquirectangularFixedName,9===r.coordinatesMode,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i,r){const s=this._getTexture();if(i&&s&&(e.setMatrix(this._reflectionMatrixName,s.getReflectionTextureMatrix()),s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s),s.boundingBoxSize)){const t=s;e.setVector3(this._reflectionPositionName,t.boundingBoxPosition),e.setVector3(this._reflectionSizeName,t.boundingBoxSize)}}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===Dg.Vertex)return"";const t=1===e.shaderLanguage;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,Og.Matrix);let i="";this._worldPositionNameInFragmentOnlyMode=e._getFreeVariableName("worldPosition");const r=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(r,Og.Vector4))&&(this.generateOnlyFragmentCode?i+=`${e._declareLocalVar(r,Og.Vector4)} = ${this.worldPosition.associatedVariableName};\n`:i+=`${t?"vertexOutputs.":""}${r} = ${this.worldPosition.associatedVariableName};\n`),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,Og.Vector3,this._defineSkyboxName))&&(i+=`#ifdef ${this._defineSkyboxName}\n`,this.generateOnlyFragmentCode?i+=`${e._declareLocalVar(this._positionUVWName,Og.Vector3)} = ${this.position.associatedVariableName}.xyz;\n`:i+=`${t?"vertexOutputs.":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz;\n`,i+="#endif\n"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,Og.Vector3,`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(i+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})\n`,this.generateOnlyFragmentCode?i+=`${e._declareLocalVar(this._directionWName,Og.Vector3)} = normalize(vec3${e.fSuffix}(${this.world.associatedVariableName} * vec4${e.fSuffix}(${this.position.associatedVariableName}.xyz, 0.0)));\n`:i+=`${t?"vertexOutputs.":""}${this._directionWName} = normalize(vec3${e.fSuffix}(${this.world.associatedVariableName} * vec4${e.fSuffix}(${this.position.associatedVariableName}.xyz, 0.0)));\n`,i+="#endif\n"),i}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName}\n`,e._emitCubeSampler(this._cubeSamplerName,"",!0),e._samplerDeclaration+="#else\n",e._emit2DSampler(this._2DSamplerName,"",!0),e._samplerDeclaration+="#endif\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"},{search:/fn computeReflectionCoords\(worldPos: vec4f,worldNormal: vec3f\)->vec3f/g,replace:"fn DUMMYFUNC()"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,Og.Vector3),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,Og.Vector3)}handleFragmentSideCodeReflectionCoords(e,t,i,r=!1,s=!1){i||(i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);const n=(1===e.shaderLanguage?"uniforms.":"")+this._reflectionMatrixName,o=`normalize(${this._directionWName})`,a=`${this._positionUVWName}`,l=`${this.cameraPosition.associatedVariableName}`,h=`${this.view.associatedVariableName}`;t+=".xyz";let c=`\n #ifdef ${this._defineMirroredEquirectangularFixedName}\n ${e._declareLocalVar(this._reflectionVectorName,Og.Vector3)} = computeMirroredFixedEquirectangularCoords(${i}, ${t}, ${o});\n #endif\n\n #ifdef ${this._defineEquirectangularFixedName}\n ${e._declareLocalVar(this._reflectionVectorName,Og.Vector3)} = computeFixedEquirectangularCoords(${i}, ${t}, ${o});\n #endif\n\n #ifdef ${this._defineEquirectangularName}\n ${e._declareLocalVar(this._reflectionVectorName,Og.Vector3)} = computeEquirectangularCoords(${i}, ${t}, ${l}.xyz, ${n});\n #endif\n\n #ifdef ${this._defineSphericalName}\n ${e._declareLocalVar(this._reflectionVectorName,Og.Vector3)} = computeSphericalCoords(${i}, ${t}, ${h}, ${n});\n #endif\n\n #ifdef ${this._definePlanarName}\n ${e._declareLocalVar(this._reflectionVectorName,Og.Vector3)} = computePlanarCoords(${i}, ${t}, ${l}.xyz, ${n});\n #endif\n\n #ifdef ${this._defineCubicName}\n #ifdef ${this._defineLocalCubicName}\n ${e._declareLocalVar(this._reflectionVectorName,Og.Vector3)} = computeCubicLocalCoords(${i}, ${t}, ${l}.xyz, ${n}, ${this._reflectionSizeName}, ${this._reflectionPositionName});\n #else\n ${e._declareLocalVar(this._reflectionVectorName,Og.Vector3)} = computeCubicCoords(${i}, ${t}, ${l}.xyz, ${n});\n #endif\n #endif\n\n #ifdef ${this._defineProjectionName}\n ${e._declareLocalVar(this._reflectionVectorName,Og.Vector3)} = computeProjectionCoords(${i}, ${h}, ${n});\n #endif\n\n #ifdef ${this._defineSkyboxName}\n ${e._declareLocalVar(this._reflectionVectorName,Og.Vector3)} = computeSkyBoxCoords(${a}, ${n});\n #endif\n\n #ifdef ${this._defineExplicitName}\n ${e._declareLocalVar(this._reflectionVectorName,Og.Vector3)} = vec3(0, 0, 0);\n #endif\n`;return s||(c+=`#ifdef ${this._defineOppositeZ}\n ${this._reflectionVectorName}.z *= -1.0;\n #endif\n`),r||(c+=`\n #ifdef ${this._define3DName}\n ${e._declareLocalVar(this._reflectionCoordsName,Og.Vector3)} = ${this._reflectionVectorName};\n #else\n ${e._declareLocalVar(this._reflectionCoordsName,Og.Vector2)} = ${this._reflectionVectorName}.xy;\n #ifdef ${this._defineProjectionName}\n ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z;\n #endif\n ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y;\n #endif\n`),c}handleFragmentSideCodeReflectionColor(e,t,i=".rgb"){let r=Og.Vector4;3===i.length&&(r=Og.Vector3);let s=`${e._declareLocalVar(this._reflectionColorName,r)};\n #ifdef ${this._define3DName}\n`;return s+=t?`${this._reflectionColorName} = ${e._generateTextureSampleCubeLOD(this._reflectionVectorName,this._cubeSamplerName,t)}${i};\n`:`${this._reflectionColorName} = ${e._generateTextureSampleCube(this._reflectionVectorName,this._cubeSamplerName)}${i};\n`,s+="\n #else\n",s+=t?`${this._reflectionColorName} =${e._generateTextureSampleLOD(this._reflectionCoordsName,this._2DSamplerName,t)}${i};\n`:`${this._reflectionColorName} = ${e._generateTextureSample(this._reflectionCoordsName,this._2DSamplerName)}${i};\n`,s+="#endif\n",s}writeOutputs(e,t){let i="";if(e.target===Dg.Fragment)for(const r of this._outputs)r.hasEndpoints&&(i+=`${e._declareOutput(r)} = ${t}.${r.name};\n`);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"});\n`}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null);\n`;return e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,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&&!pv.IgnoreTexturesAtLoadTime&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=gm.Parse(e.texture,t,i):this.texture=vi.g.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}(0,je.Cg)([t_("Generate only fragment code",0,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:pT._OnGenerateOnlyFragmentCodeChanged}})],pT.prototype,"generateOnlyFragmentCode",void 0),(0,X.Y5)("BABYLON.ReflectionTextureBaseBlock",pT);class _T extends pT{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,Z.V.Error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,Z.V.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?Dg.Fragment:Dg.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?Dg.Fragment:Dg.Vertex}constructor(e){super(e),this.registerInput("position",Og.AutoDetect,!1,Dg.Vertex),this.registerInput("worldPosition",Og.Vector4,!1,Dg.Vertex),this.registerInput("worldNormal",Og.Vector4,!1,Dg.Fragment),this.registerInput("world",Og.Matrix,!1,Dg.Vertex),this.registerInput("cameraPosition",Og.Vector3,!1,Dg.Fragment),this.registerInput("view",Og.Matrix,!1,Dg.Fragment),this.registerOutput("rgb",Og.Color3,Dg.Fragment),this.registerOutput("rgba",Og.Color4,Dg.Fragment),this.registerOutput("r",Og.Float,Dg.Fragment),this.registerOutput("g",Og.Float,Dg.Fragment),this.registerOutput("b",Og.Float,Dg.Fragment),this.registerOutput("a",Og.Float,Dg.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(Og.Color3|Og.Vector3|Og.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((e=>e.systemValue===Lg.CameraPosition&&t(e)));i||(i=new Kg("cameraPosition"),i.setAsSystemValue(Lg.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,`vec4${e.fSuffix}(0.)`),this;if(e.target!==Dg.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.generateOnlyFragmentCode&&(e.compilationString+=this.handleVertexSide(e)),this.handleFragmentSideInits(e);const t=e._getFreeVariableName("normalWUnit");return e.compilationString+=`${e._declareLocalVar(t,Og.Vector4)} = normalize(${this.worldNormal.associatedVariableName});\n`,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(e,t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(e,void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}}(0,X.Y5)("BABYLON.ReflectionTextureBlock",_T);class mT extends Gg{constructor(e){super(e,Dg.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",Og.AutoDetect,!1,Dg.VertexAndFragment),this.registerOutput("depth",Og.Float,Dg.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(Og.Vector2|Og.Vector3|Og.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?Dg.VertexAndFragment:Dg.Fragment:Dg.VertexAndFragment}_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===Og.Vector3?Og.Vector3:t.type===Og.Vector4?Og.Vector4:Og.Vector2)),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,Og.Vector2),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r",!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===Dg.Fragment)return;const t=0===e.shaderLanguage?`texture2D(${this._samplerName},`:`textureSampleLevel(${this._samplerName}, ${this._samplerName+"Sampler"},`,r=0===e.shaderLanguage?"":", 0";return void(e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,Og.Vector4)}= ${t} ${i.associatedVariableName}.xy${r});\n`)}const r=0===e.shaderLanguage?`texture2D(${this._samplerName},`:`textureSample(${this._samplerName}, ${this._samplerName+"Sampler"},`;this.uv.ownerBlock.target!==Dg.Fragment?e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = ${r} ${this._mainUVName});\n`:e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = ${r} ${i.associatedVariableName}.xy);\n`}_writeOutput(e,t,i,r=!1){if(r){if(e.target===Dg.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}else this.uv.ownerBlock.target,Dg.Fragment,e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}_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!==Dg.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(this._outputs.some((e=>e.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}}(0,je.Cg)([t_("Use non linear depth",0,"ADVANCED",{embedded:!0,notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let r=!1;return i.useNonLinearDepth&&(i.storeCameraSpaceZ=!1,r=!0),e&&e.disableDepthRenderer(),r}}})],mT.prototype,"useNonLinearDepth",void 0),(0,je.Cg)([t_("Store Camera space Z",0,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let r=!1;return i.storeCameraSpaceZ&&(i.useNonLinearDepth=!1,r=!0),e&&e.disableDepthRenderer(),r}}})],mT.prototype,"storeCameraSpaceZ",void 0),(0,je.Cg)([t_("Force 32 bits float",0,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:e=>e?.disableDepthRenderer()}})],mT.prototype,"force32itsFloat",void 0),(0,X.Y5)("BABYLON.SceneDepthBlock",mT);class gT extends Gg{constructor(e){super(e,Dg.VertexAndFragment,!0),this.registerInput("worldPosition",Og.Vector4,!1)}getClassName(){return"ClipPlanesBlock"}initialize(e){e._excludeVariableName("vClipPlane"),e._excludeVariableName("fClipDistance"),e._excludeVariableName("vClipPlane2"),e._excludeVariableName("fClipDistance2"),e._excludeVariableName("vClipPlane3"),e._excludeVariableName("fClipDistance3"),e._excludeVariableName("vClipPlane4"),e._excludeVariableName("fClipDistance4"),e._excludeVariableName("vClipPlane5"),e._excludeVariableName("fClipDistance5"),e._excludeVariableName("vClipPlane6"),e._excludeVariableName("fClipDistance6"),this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,1===e?await Promise.all([Promise.resolve().then(i.bind(i,76794)),Promise.resolve().then(i.bind(i,96140)),Promise.resolve().then(i.bind(i,57728)),Promise.resolve().then(i.bind(i,30486))]):await Promise.all([Promise.resolve().then(i.bind(i,89797)),Promise.resolve().then(i.bind(i,77165)),Promise.resolve().then(i.bind(i,71471)),Promise.resolve().then(i.bind(i,18355))]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}get worldPosition(){return this._inputs[0]}get target(){return Dg.VertexAndFragment}set target(e){}prepareDefines(e,t,i){const r=e.getScene(),s=!!(t.clipPlane??r.clipPlane),n=!!(t.clipPlane2??r.clipPlane2),o=!!(t.clipPlane3??r.clipPlane3),a=!!(t.clipPlane4??r.clipPlane4),l=!!(t.clipPlane5??r.clipPlane5),h=!!(t.clipPlane6??r.clipPlane6);i.setValue("CLIPPLANE",s,!0),i.setValue("CLIPPLANE2",n,!0),i.setValue("CLIPPLANE3",o,!0),i.setValue("CLIPPLANE4",a,!0),i.setValue("CLIPPLANE5",l,!0),i.setValue("CLIPPLANE6",h,!0)}bind(e,t,i){if(!i)return;const r=i.getScene();(0,Ln.gS)(e,t,r)}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;if(e.target!==Dg.Fragment){const i=this.worldPosition;return 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",Og.Vector4),e._emitUniformFromString("vClipPlane2",Og.Vector4),e._emitUniformFromString("vClipPlane3",Og.Vector4),e._emitUniformFromString("vClipPlane4",Og.Vector4),e._emitUniformFromString("vClipPlane5",Og.Vector4),void e._emitUniformFromString("vClipPlane6",Og.Vector4)}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}}(0,X.Y5)("BABYLON.ClipPlanesBlock",gT);var vT,xT=i(76794),bT=i(96140),ST=i(57728),TT=i(30486),CT=i(89797),yT=i(77165),ET=i(71471),PT=i(18355),AT=i(10668),RT=i(64657),IT=i(55090),MT=i(71426),OT=i(85188),DT=i(34992),wT=i(94662),NT=i(48453),FT=i(23133),LT=i(81749),BT=i(58769),VT=i(19215),kT=i(96951),UT=i(97295),GT=i(34091),zT=i(2946),WT=i(7769),HT=i(51068);class XT extends Gg{get texture(){return null}set texture(e){}constructor(e,t=Dg.VertexAndFragment){super(e,t,!1),this.registerOutput("position",Og.Object,Dg.VertexAndFragment,new cS("position",this,1,dT,"ImageSourceBlock")),this.registerOutput("localPosition",Og.Object,Dg.VertexAndFragment,new cS("localPosition",this,1,dT,"ImageSourceBlock")),this.registerOutput("depth",Og.Object,Dg.VertexAndFragment,new cS("depth",this,1,dT,"ImageSourceBlock")),this.registerOutput("screenDepth",Og.Object,Dg.VertexAndFragment,new cS("screenDepth",this,1,dT,"ImageSourceBlock")),this.registerOutput("normal",Og.Object,Dg.VertexAndFragment,new cS("normal",this,1,dT,"ImageSourceBlock")),this.registerOutput("worldNormal",Og.Object,Dg.VertexAndFragment,new cS("worldNormal",this,1,dT,"ImageSourceBlock"))}getSamplerName(e){return e===this._outputs[0]?this._positionSamplerName:e===this._outputs[1]?this._localPositionSamplerName:e===this._outputs[2]?this._depthSamplerName:e===this._outputs[3]?this._screenSpaceDepthSamplerName:e===this._outputs[4]?this._normalSamplerName:e===this._outputs[5]?this._worldNormalSamplerName:""}get position(){return this._outputs[0]}get localPosition(){return this._outputs[1]}get depth(){return this._outputs[2]}get screenDepth(){return this._outputs[3]}get normal(){return this._outputs[4]}get worldNormal(){return this._outputs[5]}get positionSamplerName(){return this._positionSamplerName}get localPositionSamplerName(){return this._localPositionSamplerName}get normalSamplerName(){return this._normalSamplerName}get worldNormalSamplerName(){return this._worldNormalSamplerName}get depthSamplerName(){return this._depthSamplerName}get linearDepthSamplerName(){return this._screenSpaceDepthSamplerName}getClassName(){return"PrePassTextureBlock"}_buildBlock(e){if(super._buildBlock(e),e.target!==Dg.Vertex)return this._positionSamplerName="prepassPositionSampler",this._depthSamplerName="prepassDepthSampler",this._normalSamplerName="prepassNormalSampler",this._worldNormalSamplerName="prepassWorldNormalSampler",this._localPositionSamplerName="prepassLocalPositionSampler",this._screenSpaceDepthSamplerName="prepassScreenSpaceDepthSampler",e.sharedData.variableNames.prepassPositionSampler=0,e.sharedData.variableNames.prepassDepthSampler=0,e.sharedData.variableNames.prepassNormalSampler=0,e.sharedData.variableNames.prepassWorldNormalSampler=0,e.sharedData.variableNames.prepassLocalPositionSampler=0,e.sharedData.variableNames.prepassScreenSpaceDepthSampler=0,e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this),this.position.isConnected&&e._emit2DSampler(this._positionSamplerName),this.depth.isConnected&&e._emit2DSampler(this._depthSamplerName),this.normal.isConnected&&e._emit2DSampler(this._normalSamplerName),this.worldNormal.isConnected&&e._emit2DSampler(this._worldNormalSamplerName),this.localPosition.isConnected&&e._emit2DSampler(this._localPositionSamplerName),this.screenDepth.isConnected&&e._emit2DSampler(this._screenSpaceDepthSamplerName),this}bind(e,t){const i=t.getScene().enablePrePassRenderer();if(!i)return;const r=i.defaultRT;r.textures&&(this.position.isConnected&&e.setTexture(this._positionSamplerName,r.textures[i.getIndex(1)]),this.localPosition.isConnected&&e.setTexture(this._localPositionSamplerName,r.textures[i.getIndex(9)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,r.textures[i.getIndex(5)]),this.screenDepth.isConnected&&e.setTexture(this._screenSpaceDepthSamplerName,r.textures[i.getIndex(10)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,r.textures[i.getIndex(6)]),this.worldNormal.isConnected&&e.setTexture(this._worldNormalSamplerName,r.textures[i.getIndex(8)]))}}(0,X.Y5)("BABYLON.PrePassTextureBlock",XT);class qT extends Gg{get endpoints(){return this._endpoints}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==Dg.VertexAndFragment)return t.target;if(e.connectedPoint.target!==Dg.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){this._target&e||(this._target=e)}constructor(e){super(e,Dg.Neutral),this._endpoints=[],this.registerInput("input",Og.AutoDetect)}getClassName(){return"NodeMaterialTeleportInBlock"}get input(){return this._inputs[0]}isConnectedInFragmentShader(){return this.endpoints.some((e=>e.output.isConnectedInFragmentShader))}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const r of this.endpoints)-1===t.indexOf(r)&&(i+=r._dumpCode(e,t));return i}isAnAncestorOf(e){for(const t of this.endpoints){if(t===e)return!0;if(t.isAnAncestorOf(e))return!0}return!1}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name,this._outputs=this._endpoints.map((e=>e.output))}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null,this._outputs=this._endpoints.map((e=>e.output)))}dispose(){super.dispose();for(const e of this._endpoints)this.detachFromEndpoint(e);this._endpoints=[]}}(0,X.Y5)("BABYLON.NodeMaterialTeleportInBlock",qT);class YT extends Gg{constructor(e){super(e,Dg.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",Og.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};\n`)}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&&-1===t.indexOf(this.entryPoint)&&(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});\n`),e}serialize(){const e=super.serialize();return e.entryPoint=this.entryPoint?.uniqueId??"",e}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}}(0,X.Y5)("BABYLON.NodeMaterialTeleportOutBlock",YT);class KT extends tv{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};\n`,this}}(0,X.Y5)("BABYLON.AddBlock",KT);class jT extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("input",Og.AutoDetect),this.registerInput("factor",Og.Float),this.registerOutput("output",Og.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};\n`,this}}(0,X.Y5)("BABYLON.ScaleBlock",jT);class $T extends Gg{constructor(e){super(e,Dg.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",Og.AutoDetect),this.registerOutput("output",Og.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=1===e.shaderLanguage?e._getShaderType(this.value.type):"";return e.compilationString+=e._declareOutput(t)+` = clamp(${this.value.associatedVariableName}, ${i}(${this._writeFloat(this.minimum)}), ${i}(${this._writeFloat(this.maximum)}));\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};\n`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};\n`,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}}(0,je.Cg)([t_("Minimum",1,void 0,{embedded:!0})],$T.prototype,"minimum",void 0),(0,je.Cg)([t_("Maximum",1,void 0,{embedded:!0})],$T.prototype,"maximum",void 0),(0,X.Y5)("BABYLON.ClampBlock",$T);class QT extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("left",Og.AutoDetect),this.registerInput("right",Og.AutoDetect),this.registerOutput("output",Og.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Og.Float),this._inputs[0].excludedConnectionPointTypes.push(Og.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Og.Vector2),this._inputs[1].excludedConnectionPointTypes.push(Og.Float),this._inputs[1].excludedConnectionPointTypes.push(Og.Matrix),this._inputs[1].excludedConnectionPointTypes.push(Og.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);\n`,this}}(0,X.Y5)("BABYLON.CrossBlock",QT);class ZT extends Gg{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 s=new RegExp("\\{TYPE_"+r.name+"\\}","gm"),n=e._getGLType(r.type);t=t.replace(s,n),i=i.replace(s,n)})),this._outputs.forEach((r=>{const s=new RegExp("\\{TYPE_"+r.name+"\\}","gm"),n=e._getGLType(r.type);t=t.replace(s,n),i=i.replace(s,n)})),e._emitFunction(i,t,""),this._outputs.forEach((t=>{e.compilationString+=e._declareOutput(t)+";\n"})),e.compilationString+=i+"(";let r=!1;return this._inputs.forEach(((t,i)=>{i>0&&(e.compilationString+=", "),this._inputSamplers&&-1!==this._inputSamplers.indexOf(t.name)?e.compilationString+=t.connectedPoint?.ownerBlock?.samplerName??t.associatedVariableName:e.compilationString+=t.associatedVariableName,r=!0})),this._outputs.forEach(((t,i)=>{(i>0||r)&&(e.compilationString+=", "),e.compilationString+=t.associatedVariableName})),e.compilationString+=");\n",this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.options = ${JSON.stringify(this._options)};\n`,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){this._options=e,this._code=e.code.join("\n")+"\n",this.name=this.name||e.name,this.target=Dg[e.target],e.inParameters?.forEach(((e,t)=>{const i=Og[e.type];"sampler2D"===e.type||"samplerCube"===e.type?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(e.name),this.registerInput(e.name,Og.Object,!0,Dg.VertexAndFragment,new cS(e.name,this,0,dT,"ImageSourceBlock"))):this.registerInput(e.name,i),Object.defineProperty(this,e.name,{get:function(){return this._inputs[t]},enumerable:!0,configurable:!0})})),e.outParameters?.forEach(((e,t)=>{this.registerOutput(e.name,Og[e.type]),Object.defineProperty(this,e.name,{get:function(){return this._outputs[t]},enumerable:!0,configurable:!0}),"BasedOnInput"===e.type&&(this._outputs[t]._typeConnectionSource=this._findInputByName(e.typeFromInput)[0])})),e.inLinkedConnectionTypes?.forEach((e=>{this._linkConnectionTypes(this._findInputByName(e.input1)[1],this._findInputByName(e.input2)[1])}))}_findInputByName(e){if(!e)return null;for(let t=0;t!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Lg.CameraPosition&&t(e)));i||(i=new Kg("cameraPosition"),i.setAsSystemValue(Lg.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);\n`,this}}(0,X.Y5)("BABYLON.ViewDirectionBlock",lC),i(49046);class hC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("worldNormal",Og.Vector4),this.registerInput("viewDirection",Og.Vector3),this.registerInput("bias",Og.Float),this.registerInput("power",Og.Float),this.registerOutput("fresnel",Og.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 lC("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){const e=new Kg("bias");e.value=0,e.output.connectTo(this.bias)}if(!this.power.isConnected){const e=new Kg("power");e.value=1,e.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});\n`,this}}(0,X.Y5)("BABYLON.FresnelBlock",hC);class cC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("left",Og.AutoDetect),this.registerInput("right",Og.AutoDetect),this.registerOutput("output",Og.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});\n`,this}}(0,X.Y5)("BABYLON.MaxBlock",cC);class uC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("left",Og.AutoDetect),this.registerInput("right",Og.AutoDetect),this.registerOutput("output",Og.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});\n`,this}}(0,X.Y5)("BABYLON.MinBlock",uC);class dC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("left",Og.AutoDetect),this.registerInput("right",Og.AutoDetect),this.registerOutput("output",Og.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Og.Float),this._inputs[0].excludedConnectionPointTypes.push(Og.Matrix),this._inputs[1].excludedConnectionPointTypes.push(Og.Float),this._inputs[1].excludedConnectionPointTypes.push(Og.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});\n`,this}}(0,X.Y5)("BABYLON.DistanceBlock",dC);class fC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("value",Og.AutoDetect),this.registerOutput("output",Og.Float),this._inputs[0].excludedConnectionPointTypes.push(Og.Float),this._inputs[0].excludedConnectionPointTypes.push(Og.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});\n`,this}}(0,X.Y5)("BABYLON.LengthBlock",fC);class pC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("value",Og.AutoDetect),this.registerOutput("output",Og.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};\n`,this}}(0,X.Y5)("BABYLON.NegateBlock",pC);class _C extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("value",Og.AutoDetect),this.registerInput("power",Og.AutoDetect),this.registerOutput("output",Og.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(max(${this.value.associatedVariableName}, 0.), ${this.power.associatedVariableName});\n`,this}}(0,X.Y5)("BABYLON.PowBlock",_C);class mC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("seed",Og.AutoDetect),this.registerOutput("output",Og.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(Og.Vector2|Og.Vector3|Og.Vector4|Og.Color3|Og.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);\n`,this}}(0,X.Y5)("BABYLON.RandomNumberBlock",mC);class gC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("x",Og.Float),this.registerInput("y",Og.Float),this.registerOutput("output",Og.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=1===e.shaderLanguage?"atan2":"atan";return e.compilationString+=e._declareOutput(t)+` = ${i}(${this.x.associatedVariableName}, ${this.y.associatedVariableName});\n`,this}}(0,X.Y5)("BABYLON.ArcTan2Block",gC);class vC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("value",Og.AutoDetect),this.registerInput("edge0",Og.Float),this.registerInput("edge1",Og.Float),this.registerOutput("output",Og.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});\n`,this}}(0,X.Y5)("BABYLON.SmoothStepBlock",vC);class xC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("input",Og.AutoDetect),this.registerOutput("output",Og.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===Og.Matrix?e.compilationString+=e._declareOutput(t)+` = inverse(${this.input.associatedVariableName});\n`:e.compilationString+=e._declareOutput(t)+` = 1. / ${this.input.associatedVariableName};\n`,this}}(0,X.Y5)("BABYLON.ReciprocalBlock",xC);class bC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("value",Og.AutoDetect),this.registerInput("reference",Og.AutoDetect),this.registerInput("distance",Og.Float),this.registerInput("replacement",Og.AutoDetect),this.registerOutput("output",Og.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(Og.Float),this._inputs[0].excludedConnectionPointTypes.push(Og.Matrix),this._inputs[1].excludedConnectionPointTypes.push(Og.Float),this._inputs[1].excludedConnectionPointTypes.push(Og.Matrix),this._inputs[3].excludedConnectionPointTypes.push(Og.Float),this._inputs[3].excludedConnectionPointTypes.push(Og.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)+";\n",e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) {\n`,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName};\n`,e.compilationString+="} else {\n",e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName};\n`,e.compilationString+="}\n",this}}(0,X.Y5)("BABYLON.ReplaceColorBlock",bC);class SC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("value",Og.AutoDetect),this.registerInput("steps",Og.AutoDetect),this.registerOutput("output",Og.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Og.Matrix),this._inputs[1].excludedConnectionPointTypes.push(Og.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(Og.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});\n`,this}}(0,X.Y5)("BABYLON.PosterizeBlock",SC),function(e){e[e.SawTooth=0]="SawTooth",e[e.Square=1]="Square",e[e.Triangle=2]="Triangle"}(vT||(vT={}));class TC extends Gg{constructor(e){super(e,Dg.Neutral),this.kind=0,this.registerInput("input",Og.AutoDetect),this.registerOutput("output",Og.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Og.Matrix)}getClassName(){return"WaveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];switch(this.kind){case 0:e.compilationString+=e._declareOutput(t)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName});\n`;break;case 1:e.compilationString+=e._declareOutput(t)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName}));\n`;break;case 2:e.compilationString+=e._declareOutput(t)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0;\n`}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}}(0,je.Cg)([t_("Kind",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"SawTooth",value:0},{label:"Square",value:1},{label:"Triangle",value:2}]})],TC.prototype,"kind",void 0),(0,X.Y5)("BABYLON.WaveBlock",TC);class CC{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 yC extends Gg{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,Dg.Neutral),this.colorSteps=[new CC(0,H.v9.Black()),new CC(1,H.v9.White())],this.onValueChangedObservable=new z.cP,this.registerInput("gradient",Og.AutoDetect),this.registerOutput("output",Og.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(Og.Float|Og.Vector2|Og.Vector3|Og.Vector4|Og.Color3|Og.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(Og.Vector3);if(!this.colorSteps.length||!this.gradient.connectedPoint)return void(e.compilationString+=e._declareOutput(t)+` = ${i}(0., 0., 0.);\n`);const r=e._getFreeVariableName("gradientTempColor"),s=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`${e._declareLocalVar(r,Og.Vector3)} = ${this._writeColorConstant(0,i)};\n`,e.compilationString+=`${e._declareLocalVar(s,Og.Float)};\n`;let n=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==Og.Float&&(n+=".x");for(let t=1;t vec3f {\n ${this.handleFragmentSideCodeReflectionCoords(e,"worldNormal","worldPos",!0,!0)}\n return ${this._reflectionVectorName};\n }\n`:`\n vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) {\n ${this.handleFragmentSideCodeReflectionCoords(e,"worldNormal","worldPos",!0,!0)}\n return ${this._reflectionVectorName};\n }\n`;return e._emitFunction("computeReflectionCoordsPBR",s,`//${this.name}`),this._vReflectionMicrosurfaceInfosName=e._getFreeVariableName("vReflectionMicrosurfaceInfos"),e._emitUniformFromString(this._vReflectionMicrosurfaceInfosName,Og.Vector3),this._vReflectionInfosName=e._getFreeVariableName("vReflectionInfos"),this._vReflectionFilteringInfoName=e._getFreeVariableName("vReflectionFilteringInfo"),e._emitUniformFromString(this._vReflectionFilteringInfoName,Og.Vector2),i+=`#ifdef REFLECTION\n ${e._declareLocalVar(this._vReflectionInfosName,Og.Vector2)} = vec2${e.fSuffix}(1., 0.);\n\n ${r?"var reflectionOut: reflectionOutParams":"reflectionOutParams reflectionOut"};\n\n reflectionOut = reflectionBlock(\n ${this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:(r?"input.":"")+"v_"+this.worldPosition.associatedVariableName}.xyz\n , ${t}\n , alphaG\n , ${(r?"uniforms.":"")+this._vReflectionMicrosurfaceInfosName}\n , ${this._vReflectionInfosName}\n , ${this.reflectionColor}\n #ifdef ANISOTROPIC\n ,anisotropicOut\n #endif\n #if defined(${this._defineLODReflectionAlpha}) && !defined(${this._defineSkyboxName})\n ,NdotVUnclamped\n #endif\n #ifdef ${this._defineLinearSpecularReflection}\n , roughness\n #endif\n #ifdef ${this._define3DName}\n , ${this._cubeSamplerName}\n ${r?`, ${this._cubeSamplerName}Sampler`:""}\n #else\n , ${this._2DSamplerName}\n ${r?`, ${this._2DSamplerName}Sampler`:""}\n #endif\n #if defined(NORMAL) && defined(USESPHERICALINVERTEX)\n , ${r?"input.":""}${this._vEnvironmentIrradianceName}\n #endif\n #ifdef USESPHERICALFROMREFLECTIONMAP\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n , ${this._reflectionMatrixName}\n #endif\n #endif\n #ifdef USEIRRADIANCEMAP\n , irradianceSampler // ** not handled **\n ${r?", irradianceSamplerSampler":""}\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef ${this._define3DName}\n , ${this._cubeSamplerName}\n ${r?`, ${this._cubeSamplerName}Sampler`:""}\n , ${this._cubeSamplerName}\n ${r?`, ${this._cubeSamplerName}Sampler`:""}\n #else\n , ${this._2DSamplerName}\n ${r?`, ${this._2DSamplerName}Sampler`:""}\n , ${this._2DSamplerName} \n ${r?`, ${this._2DSamplerName}Sampler`:""}\n #endif\n #endif\n #ifdef REALTIME_FILTERING\n , ${this._vReflectionFilteringInfoName}\n #endif\n );\n #endif\n`,i}_buildBlock(e){return this._scene=e.sharedData.scene,e.target!==Dg.Fragment&&(this._defineLODReflectionAlpha=e._getFreeDefineName("LODINREFLECTIONALPHA"),this._defineLinearSpecularReflection=e._getFreeDefineName("LINEARSPECULARREFLECTION")),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e+=`${this._codeVariableName}.texture.gammaSpace = ${this.texture.gammaSpace};\n`),e+=`${this._codeVariableName}.useSphericalHarmonics = ${this.useSphericalHarmonics};\n`,e+=`${this._codeVariableName}.forceIrradianceInFragment = ${this.forceIrradianceInFragment};\n`,e}serialize(){const e=super.serialize();return e.useSphericalHarmonics=this.useSphericalHarmonics,e.forceIrradianceInFragment=this.forceIrradianceInFragment,e.gammaSpace=this.texture?.gammaSpace??!0,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.useSphericalHarmonics=e.useSphericalHarmonics,this.forceIrradianceInFragment=e.forceIrradianceInFragment,this.texture&&(this.texture.gammaSpace=e.gammaSpace)}}(0,je.Cg)([t_("Spherical Harmonics",0,"ADVANCED",{embedded:!0,notifiers:{update:!0}})],FC.prototype,"useSphericalHarmonics",void 0),(0,je.Cg)([t_("Force irradiance in fragment",0,"ADVANCED",{embedded:!0,notifiers:{update:!0}})],FC.prototype,"forceIrradianceInFragment",void 0),(0,X.Y5)("BABYLON.ReflectionBlock",FC);class LC extends Gg{constructor(e){super(e,Dg.Fragment),this._tangentCorrectionFactorName="",this.remapF0OnInterfaceChange=!0,this._isUnique=!0,this.registerInput("intensity",Og.Float,!1,Dg.Fragment),this.registerInput("roughness",Og.Float,!0,Dg.Fragment),this.registerInput("indexOfRefraction",Og.Float,!0,Dg.Fragment),this.registerInput("normalMapColor",Og.Color3,!0,Dg.Fragment),this.registerInput("uv",Og.Vector2,!0,Dg.Fragment),this.registerInput("tintColor",Og.Color3,!0,Dg.Fragment),this.registerInput("tintAtDistance",Og.Float,!0,Dg.Fragment),this.registerInput("tintThickness",Og.Float,!0,Dg.Fragment),this.registerInput("worldTangent",Og.Vector4,!0),this.registerInput("worldNormal",Og.AutoDetect,!0),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(Og.Color4|Og.Vector4|Og.Vector3),this.registerInput("TBN",Og.Object,!0,Dg.VertexAndFragment,new cS("TBN",this,0,NS,"TBNBlock")),this.registerOutput("clearcoat",Og.Object,Dg.Fragment,new cS("clearcoat",this,1,LC,"ClearCoatBlock"))}initialize(e){e._excludeVariableName("clearcoatOut"),e._excludeVariableName("vClearCoatParams"),e._excludeVariableName("vClearCoatTintParams"),e._excludeVariableName("vClearCoatRefractionParams"),e._excludeVariableName("vClearCoatTangentSpaceParams"),e._excludeVariableName("vGeometricNormaClearCoatW")}getClassName(){return"ClearCoatBlock"}get intensity(){return this._inputs[0]}get roughness(){return this._inputs[1]}get indexOfRefraction(){return this._inputs[2]}get normalMapColor(){return this._inputs[3]}get uv(){return this._inputs[4]}get tintColor(){return this._inputs[5]}get tintAtDistance(){return this._inputs[6]}get tintThickness(){return this._inputs[7]}get worldTangent(){return this._inputs[8]}get worldNormal(){return this._inputs[9]}get TBN(){return this._inputs[10]}get clearcoat(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){const e=new Kg("ClearCoat intensity",Dg.Fragment,Og.Float);e.value=1,e.output.connectTo(this.intensity)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("CLEARCOAT",!0),i.setValue("CLEARCOAT_TEXTURE",!1,!0),i.setValue("CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),i.setValue("CLEARCOAT_TINT",this.tintColor.isConnected||this.tintThickness.isConnected||this.tintAtDistance.isConnected,!0),i.setValue("CLEARCOAT_BUMP",this.normalMapColor.isConnected,!0),i.setValue("CLEARCOAT_DEFAULTIOR",!this.indexOfRefraction.isConnected||this.indexOfRefraction.connectInputBlock.value===Mm._DefaultIndexOfRefraction,!0),i.setValue("CLEARCOAT_REMAP_F0",this.remapF0OnInterfaceChange,!0)}bind(e,t,i){super.bind(e,t,i);const r=this.indexOfRefraction.connectInputBlock?.value??Mm._DefaultIndexOfRefraction,s=1-r,n=1+r,o=Math.pow(-s/n,2),a=1/r;e.setFloat4("vClearCoatRefractionParams",o,a,s,n);const l=this.clearcoat.hasEndpoints?this.clearcoat.endpoints[0].ownerBlock:null,h=l?.perturbedNormal.isConnected?l.perturbedNormal.connectedPoint.ownerBlock:null;this._scene._mirroredCameraPosition?e.setFloat2("vClearCoatTangentSpaceParams",h?.invertX?1:-1,h?.invertY?1:-1):e.setFloat2("vClearCoatTangentSpaceParams",h?.invertX?-1:1,h?.invertY?-1:1),i&&e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1)}_generateTBNSpace(e,t,i){let r="";const s=`//${this.name}`,n=this.worldTangent,o=1===e.shaderLanguage;o||e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const a={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},l=this.TBN;return l.isConnected?e.compilationString+=`\n #ifdef TBNBLOCK\n ${o?"var TBN":"mat3 TBN"} = ${l.associatedVariableName};\n #endif\n `:n.isConnected&&(r+=`${e._declareLocalVar("tbnNormal",Og.Vector3)} = normalize(${i}.xyz);\n`,r+=`${e._declareLocalVar("tbnTangent",Og.Vector3)} = normalize(${n.associatedVariableName}.xyz);\n`,r+=`${e._declareLocalVar("tbnBitangent",Og.Vector3)} = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\n`,r+=`${o?"var vTBN":"mat3 vTBN"} = ${o?"mat3x3f":"mat3"}(tbnTangent, tbnBitangent, tbnNormal);\n`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",s,{replaceStrings:[a]}),r}static GetCode(e,t,i,r,s,n,o){let a="";const l=t?.intensity.isConnected?t.intensity.associatedVariableName:"1.",h=t?.roughness.isConnected?t.roughness.associatedVariableName:"0.",c=t?.normalMapColor.isConnected?t.normalMapColor.associatedVariableName:`vec3${e.fSuffix}(0.)`,u=t?.uv.isConnected?t.uv.associatedVariableName:`vec2${e.fSuffix}(0.)`,d=t?.tintColor.isConnected?t.tintColor.associatedVariableName:`vec3${e.fSuffix}(1.)`,f=t?.tintThickness.isConnected?t.tintThickness.associatedVariableName:"1.",p=t?.tintAtDistance.isConnected?t.tintAtDistance.associatedVariableName:"1.",_=`vec4${e.fSuffix}(0.)`;if(t){e._emitUniformFromString("vClearCoatRefractionParams",Og.Vector4),e._emitUniformFromString("vClearCoatTangentSpaceParams",Og.Vector2);const i=t.worldNormal;a+=`${e._declareLocalVar("vGeometricNormaClearCoatW",Og.Vector3)} = ${i.isConnected?"normalize("+i.associatedVariableName+".xyz)":"geometricNormalW"};\n`}else a+=`${e._declareLocalVar("vGeometricNormaClearCoatW",Og.Vector3)} = geometricNormalW;\n`;s&&t&&(a+=t._generateTBNSpace(e,r,o),n=t.worldTangent.isConnected);const m=1===e.shaderLanguage;return a+=`${m?"var clearcoatOut: clearcoatOutParams":"clearcoatOutParams clearcoatOut"};\n\n #ifdef CLEARCOAT\n ${e._declareLocalVar("vClearCoatParams",Og.Vector2)} = vec2${e.fSuffix}(${l}, ${h});\n ${e._declareLocalVar("vClearCoatTintParams",Og.Vector4)} = vec4${e.fSuffix}(${d}, ${f});\n\n clearcoatOut = clearcoatBlock(\n ${r}.xyz\n , vGeometricNormaClearCoatW\n , viewDirectionW\n , vClearCoatParams\n , specularEnvironmentR0\n #ifdef CLEARCOAT_TEXTURE\n , vec2${e.fSuffix}(0.)\n #endif\n #ifdef CLEARCOAT_TINT\n , vClearCoatTintParams\n , ${p}\n , ${m?"uniforms.":""}vClearCoatRefractionParams\n #ifdef CLEARCOAT_TINT_TEXTURE\n , ${_}\n #endif\n #endif\n #ifdef CLEARCOAT_BUMP\n , vec2${e.fSuffix}(0., 1.)\n , vec4${e.fSuffix}(${c}, 0.)\n , ${u}\n #if defined(${n?"TANGENT":"IGNORE"}) && defined(NORMAL)\n , vTBN\n #else\n , ${m?"uniforms.":""}vClearCoatTangentSpaceParams\n #endif\n #ifdef OBJECTSPACE_NORMALMAP\n , normalMatrix\n #endif\n #endif\n #if defined(FORCENORMALFORWARD) && defined(NORMAL)\n , faceNormal\n #endif\n #ifdef REFLECTION\n , ${m?"uniforms.":""}${i?._vReflectionMicrosurfaceInfosName}\n , ${i?._vReflectionInfosName}\n , ${i?.reflectionColor}\n , ${m?"uniforms.":""}vLightingIntensity\n #ifdef ${i?._define3DName}\n , ${i?._cubeSamplerName} \n ${m?`, ${i?._cubeSamplerName}Sampler`:""}\n #else\n , ${i?._2DSamplerName} \n ${m?`, ${i?._2DSamplerName}Sampler`:""}\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef ${i?._define3DName}\n , ${i?._cubeSamplerName} \n ${m?`, ${i?._cubeSamplerName}Sampler`:""}\n , ${i?._cubeSamplerName}\n ${m?`, ${i?._cubeSamplerName}Sampler`:""}\n #else\n , ${i?._2DSamplerName}\n ${m?`, ${i?._2DSamplerName}Sampler`:""}\n , ${i?._2DSamplerName}\n ${m?`, ${i?._2DSamplerName}Sampler`:""} \n #endif\n #endif\n #endif\n #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)\n , (${e._generateTernary("1.","-1.",m?"fragmentInputs.frontFacing":"gl_FrontFacing")})\n #endif\n );\n #else\n clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0;\n #endif\n`,a}_buildBlock(e){return this._scene=e.sharedData.scene,e.target===Dg.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,Og.Float)),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.remapF0OnInterfaceChange = ${this.remapF0OnInterfaceChange};\n`,e}serialize(){const e=super.serialize();return e.remapF0OnInterfaceChange=this.remapF0OnInterfaceChange,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.remapF0OnInterfaceChange=e.remapF0OnInterfaceChange??!0}}(0,je.Cg)([t_("Remap F0 on interface change",0,"ADVANCED",{embedded:!0})],LC.prototype,"remapF0OnInterfaceChange",void 0),(0,X.Y5)("BABYLON.ClearCoatBlock",LC);class BC extends Gg{constructor(e){super(e,Dg.Fragment),this._isUnique=!0,this.registerInput("intensity",Og.Float,!0,Dg.Fragment),this.registerInput("indexOfRefraction",Og.Float,!0,Dg.Fragment),this.registerInput("thickness",Og.Float,!0,Dg.Fragment),this.registerOutput("iridescence",Og.Object,Dg.Fragment,new cS("iridescence",this,1,BC,"IridescenceBlock"))}initialize(e){e._excludeVariableName("iridescenceOut"),e._excludeVariableName("vIridescenceParams")}getClassName(){return"IridescenceBlock"}get intensity(){return this._inputs[0]}get indexOfRefraction(){return this._inputs[1]}get thickness(){return this._inputs[2]}get iridescence(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){const e=new Kg("Iridescence intensity",Dg.Fragment,Og.Float);e.value=1,e.output.connectTo(this.intensity);const t=new Kg("Iridescence ior",Dg.Fragment,Og.Float);t.value=1.3,t.output.connectTo(this.indexOfRefraction);const i=new Kg("Iridescence thickness",Dg.Fragment,Og.Float);i.value=400,i.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("IRIDESCENCE",!0,!0),i.setValue("IRIDESCENCE_TEXTURE",!1,!0),i.setValue("IRIDESCENCE_THICKNESS_TEXTURE",!1,!0)}static GetCode(e,t){let i="";const r=e?.intensity.isConnected?e.intensity.associatedVariableName:"1.",s=e?.indexOfRefraction.isConnected?e.indexOfRefraction.associatedVariableName:Dm._DefaultIndexOfRefraction,n=e?.thickness.isConnected?e.thickness.associatedVariableName:Dm._DefaultMaximumThickness;return i+=`${1===t.shaderLanguage?"var iridescenceOut: iridescenceOutParams":"iridescenceOutParams iridescenceOut"};\n\n #ifdef IRIDESCENCE\n iridescenceOut = iridescenceBlock(\n vec4(${r}, ${s}, 1., ${n})\n , NdotV\n , specularEnvironmentR0\n #ifdef CLEARCOAT\n , NdotVUnclamped\n #endif \n );\n\n float iridescenceIntensity = iridescenceOut.iridescenceIntensity;\n specularEnvironmentR0 = iridescenceOut.specularEnvironmentR0;\n #endif\n`,i}_buildBlock(e){return e.target===Dg.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this)),this}serialize(){return super.serialize()}_deserialize(e,t,i){super._deserialize(e,t,i)}}(0,X.Y5)("BABYLON.IridescenceBlock",BC);class VC extends Gg{constructor(e){super(e,Dg.Fragment),this.linkRefractionWithTransparency=!1,this.invertRefractionY=!1,this.useThicknessAsDepth=!1,this._isUnique=!0,this.registerInput("intensity",Og.Float,!1,Dg.Fragment),this.registerInput("tintAtDistance",Og.Float,!0,Dg.Fragment),this.registerInput("volumeIndexOfRefraction",Og.Float,!0,Dg.Fragment),this.registerOutput("refraction",Og.Object,Dg.Fragment,new cS("refraction",this,1,VC,"RefractionBlock"))}initialize(e){e._excludeVariableName("vRefractionPosition"),e._excludeVariableName("vRefractionSize")}getClassName(){return"RefractionBlock"}get intensity(){return this._inputs[0]}get tintAtDistance(){return this._inputs[1]}get volumeIndexOfRefraction(){return this._inputs[2]}get view(){return this.viewConnectionPoint}get refraction(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}autoConfigure(e,t=(()=>!0)){if(!this.intensity.isConnected){const e=new Kg("Refraction intensity",Dg.Fragment,Og.Float);e.value=1,e.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Lg.View&&t(e)));i||(i=new Kg("view"),i.setAsSystemValue(Lg.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const r=this._getTexture(),s=r&&r.getTextureMatrix;i.setValue("SS_REFRACTION",s,!0),s&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLODRefractionAlpha,r.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,r.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&r.isCube?!r.invertZ:r.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",r.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",r.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!r.boundingBoxSize,!0),i.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i){super.bind(e,t,i);const r=this._getTexture();if(!r)return;r.isCube?e.setTexture(this._cubeSamplerName,r):e.setTexture(this._2DSamplerName,r),e.setMatrix(this._refractionMatrixName,r.getRefractionTextureMatrix());let s=1;r.isCube||r.depth&&(s=r.depth);const n=this.volumeIndexOfRefraction.connectInputBlock?.value??this.indexOfRefractionConnectionPoint.connectInputBlock?.value??1.5;e.setFloat4(this._vRefractionInfosName,r.level,1/n,s,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,r.getSize().width,r.lodGenerationScale,r.lodGenerationOffset,1/n);const o=r.getSize().width;if(e.setFloat2(this._vRefractionFilteringInfoName,o,Math.log2(o)),r.boundingBoxSize){const t=r;e.setVector3("vRefractionPosition",t.boundingBoxPosition),e.setVector3("vRefractionSize",t.boundingBoxSize)}}getCode(e){return e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),this._define3DName=e._getFreeDefineName("SS_REFRACTIONMAP_3D"),this._getTexture()&&(e._samplerDeclaration+=`#ifdef ${this._define3DName}\n`,e._emitCubeSampler(this._cubeSamplerName,void 0,!0),e._samplerDeclaration+="#else\n",e._emit2DSampler(this._2DSamplerName,void 0,!0),e._samplerDeclaration+="#endif\n"),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,Og.Matrix),1!==e.shaderLanguage&&(e._emitFunction("sampleRefraction",`\n #ifdef ${this._define3DName}\n #define sampleRefraction(s, c) textureCube(s, c)\n #else\n #define sampleRefraction(s, c) texture2D(s, c)\n #endif\n`,`//${this.name}`),e._emitFunction("sampleRefractionLod",`\n #ifdef ${this._define3DName}\n #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l)\n #else\n #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l)\n #endif\n`,`//${this.name}`)),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,Og.Vector4),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,Og.Vector4),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,Og.Vector2),e._emitUniformFromString("vRefractionPosition",Og.Vector3),e._emitUniformFromString("vRefractionSize",Og.Vector3),""}_buildBlock(e){return this._scene=e.sharedData.scene,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e=this.texture.isCube?`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}");\n`:`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}");\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency};\n`,e+=`${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY};\n`,e+=`${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth};\n`,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=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=gm.Parse(e.texture,t,i):this.texture=vi.g.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}(0,je.Cg)([t_("Link refraction to transparency",0,"ADVANCED",{embedded:!0,notifiers:{update:!0}})],VC.prototype,"linkRefractionWithTransparency",void 0),(0,je.Cg)([t_("Invert refraction Y",0,"ADVANCED",{embedded:!0,notifiers:{update:!0}})],VC.prototype,"invertRefractionY",void 0),(0,je.Cg)([t_("Use thickness as depth",0,"ADVANCED",{embedded:!0,notifiers:{update:!0}})],VC.prototype,"useThicknessAsDepth",void 0),(0,X.Y5)("BABYLON.RefractionBlock",VC);class kC extends Gg{constructor(e){super(e,Dg.Fragment),this._isUnique=!0,this.registerInput("thickness",Og.Float,!1,Dg.Fragment),this.registerInput("tintColor",Og.Color3,!0,Dg.Fragment),this.registerInput("translucencyIntensity",Og.Float,!0,Dg.Fragment),this.registerInput("translucencyDiffusionDist",Og.Color3,!0,Dg.Fragment),this.registerInput("refraction",Og.Object,!0,Dg.Fragment,new cS("refraction",this,0,VC,"RefractionBlock")),this.registerInput("dispersion",Og.Float,!0,Dg.Fragment),this.registerOutput("subsurface",Og.Object,Dg.Fragment,new cS("subsurface",this,1,kC,"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 Kg("SubSurface thickness",Dg.Fragment,Og.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const r=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",r||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",r,!0),i.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),i.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),i.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),i.setValue("SS_USE_GLTF_TEXTURES",!1,!0),i.setValue("SS_DISPERSION",this.dispersion.isConnected,!0)}static GetCode(e,t,i,r){let s="";const n=t?.thickness.isConnected?t.thickness.associatedVariableName:"0.",o=t?.tintColor.isConnected?t.tintColor.associatedVariableName:"vec3(1.)",a=t?.translucencyIntensity.isConnected?t?.translucencyIntensity.associatedVariableName:"1.",l=t?.translucencyDiffusionDist.isConnected?t?.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",h=t?.refraction.isConnected?t?.refraction.connectedPoint?.ownerBlock:null,c=h?.tintAtDistance.isConnected?h.tintAtDistance.associatedVariableName:"1.",u=h?.intensity.isConnected?h.intensity.associatedVariableName:"1.",d=h?.view.isConnected?h.view.associatedVariableName:"",f=t?.dispersion.isConnected?t?.dispersion.associatedVariableName:"0.0",p=1===e.shaderLanguage;return s+=h?.getCode(e)??"",s+=`${p?"var subSurfaceOut: subSurfaceOutParams":"subSurfaceOutParams subSurfaceOut"};\n\n #ifdef SUBSURFACE\n ${e._declareLocalVar("vThicknessParam",Og.Vector2)} = vec2${e.fSuffix}(0., ${n});\n ${e._declareLocalVar("vTintColor",Og.Vector4)} = vec4${e.fSuffix}(${o}, ${c});\n ${e._declareLocalVar("vSubSurfaceIntensity",Og.Vector3)} = vec3(${u}, ${a}, 0.);\n ${e._declareLocalVar("dispersion",Og.Float)} = ${f};\n subSurfaceOut = subSurfaceBlock(\n vSubSurfaceIntensity\n , vThicknessParam\n , vTintColor\n , normalW\n , specularEnvironmentReflectance\n #ifdef SS_THICKNESSANDMASK_TEXTURE\n , vec4${e.fSuffix}(0.)\n #endif\n #ifdef REFLECTION\n #ifdef SS_TRANSLUCENCY\n , ${(p?"uniforms.":"")+i?._reflectionMatrixName}\n #ifdef USESPHERICALFROMREFLECTIONMAP\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n , reflectionOut.irradianceVector\n #endif\n #if defined(REALTIME_FILTERING)\n , ${i?._cubeSamplerName}\n ${p?`, ${i?._cubeSamplerName}Sampler`:""}\n , ${i?._vReflectionFilteringInfoName}\n #endif\n #endif\n #ifdef USEIRRADIANCEMAP\n , irradianceSampler\n ${p?", irradianceSamplerSampler":""}\n #endif\n #endif\n #endif\n #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\n , surfaceAlbedo\n #endif\n #ifdef SS_REFRACTION\n , ${r}.xyz\n , viewDirectionW\n , ${d}\n , ${(p?"uniforms.":"")+h?._vRefractionInfosName??""}\n , ${(p?"uniforms.":"")+h?._refractionMatrixName??""}\n , ${(p?"uniforms.":"")+h?._vRefractionMicrosurfaceInfosName??""}\n , ${p?"uniforms.":""}vLightingIntensity\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n , alpha\n #endif\n #ifdef ${h?._defineLODRefractionAlpha??"IGNORE"}\n , NdotVUnclamped\n #endif\n #ifdef ${h?._defineLinearSpecularRefraction??"IGNORE"}\n , roughness\n #endif\n , alphaG\n #ifdef ${h?._define3DName??"IGNORE"}\n , ${h?._cubeSamplerName??""}\n ${p?`, ${h?._cubeSamplerName}Sampler`:""}\n #else\n , ${h?._2DSamplerName??""}\n ${p?`, ${h?._2DSamplerName}Sampler`:""}\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef ${h?._define3DName??"IGNORE"}\n , ${h?._cubeSamplerName??""} \n ${p?`, ${h?._cubeSamplerName}Sampler`:""}\n , ${h?._cubeSamplerName??""} \n ${p?`, ${h?._cubeSamplerName}Sampler`:""}\n #else\n , ${h?._2DSamplerName??""}\n ${p?`, ${h?._2DSamplerName}Sampler`:""}\n , ${h?._2DSamplerName??""}\n ${p?`, ${h?._2DSamplerName}Sampler`:""}\n #endif\n #endif\n #ifdef ANISOTROPIC\n , anisotropicOut\n #endif\n #ifdef REALTIME_FILTERING\n , ${h?._vRefractionFilteringInfoName??""}\n #endif\n #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n , vRefractionPosition\n , vRefractionSize\n #endif\n #ifdef SS_DISPERSION\n , dispersion\n #endif\n #endif\n #ifdef SS_TRANSLUCENCY\n , ${l}\n , vTintColor\n #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\n , vec4${e.fSuffix}(0.)\n #endif\n #endif \n );\n\n #ifdef SS_REFRACTION\n surfaceAlbedo = subSurfaceOut.surfaceAlbedo;\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha = subSurfaceOut.alpha;\n #endif\n #endif\n #else\n subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance;\n #endif\n`,s}_buildBlock(e){return e.target===Dg.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}(0,X.Y5)("BABYLON.SubSurfaceBlock",kC);const UC={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 GC extends Gg{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,Z.V.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?Dg.Fragment:Dg.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?Dg.Fragment:Dg.Vertex}constructor(e){super(e,Dg.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=H.v9.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",Og.Vector4,!1,Dg.Vertex),this.registerInput("worldNormal",Og.Vector4,!1,Dg.Vertex),this.registerInput("view",Og.Matrix,!1),this.registerInput("cameraPosition",Og.Vector3,!1,Dg.Fragment),this.registerInput("perturbedNormal",Og.Vector4,!0,Dg.Fragment),this.registerInput("baseColor",Og.Color3,!0,Dg.Fragment),this.registerInput("metallic",Og.Float,!1,Dg.Fragment),this.registerInput("roughness",Og.Float,!1,Dg.Fragment),this.registerInput("ambientOcc",Og.Float,!0,Dg.Fragment),this.registerInput("opacity",Og.Float,!0,Dg.Fragment),this.registerInput("indexOfRefraction",Og.Float,!0,Dg.Fragment),this.registerInput("ambientColor",Og.Color3,!0,Dg.Fragment),this.registerInput("reflection",Og.Object,!0,Dg.Fragment,new cS("reflection",this,0,FC,"ReflectionBlock")),this.registerInput("clearcoat",Og.Object,!0,Dg.Fragment,new cS("clearcoat",this,0,LC,"ClearCoatBlock")),this.registerInput("sheen",Og.Object,!0,Dg.Fragment,new cS("sheen",this,0,wC,"SheenBlock")),this.registerInput("subsurface",Og.Object,!0,Dg.Fragment,new cS("subsurface",this,0,kC,"SubSurfaceBlock")),this.registerInput("anisotropy",Og.Object,!0,Dg.Fragment,new cS("anisotropy",this,0,NC,"AnisotropyBlock")),this.registerInput("iridescence",Og.Object,!0,Dg.Fragment,new cS("iridescence",this,0,BC,"IridescenceBlock")),this.registerOutput("ambientClr",Og.Color3,Dg.Fragment),this.registerOutput("diffuseDir",Og.Color3,Dg.Fragment),this.registerOutput("specularDir",Og.Color3,Dg.Fragment),this.registerOutput("clearcoatDir",Og.Color3,Dg.Fragment),this.registerOutput("sheenDir",Og.Color3,Dg.Fragment),this.registerOutput("diffuseInd",Og.Color3,Dg.Fragment),this.registerOutput("specularInd",Og.Color3,Dg.Fragment),this.registerOutput("clearcoatInd",Og.Color3,Dg.Fragment),this.registerOutput("sheenInd",Og.Color3,Dg.Fragment),this.registerOutput("refraction",Og.Color3,Dg.Fragment),this.registerOutput("lighting",Og.Color3,Dg.Fragment),this.registerOutput("shadow",Og.Float,Dg.Fragment),this.registerOutput("alpha",Og.Float,Dg.Fragment)}initialize(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode"),this._initShaderSourceAsync(e.shaderLanguage)}async _initShaderSourceAsync(e){this._codeIsReady=!1,1===e?await Promise.all([Promise.resolve().then(i.bind(i,431)),Promise.resolve().then(i.bind(i,66854))]):await Promise.all([Promise.resolve().then(i.bind(i,60693)),Promise.resolve().then(i.bind(i,43004))]),this._codeIsReady=!0,this.onCodeIsReadyObservable.notifyObservers(this)}getClassName(){return"PBRMetallicRoughnessBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get view(){return this._inputs[2]}get cameraPosition(){return this._inputs[3]}get perturbedNormal(){return this._inputs[4]}get baseColor(){return this._inputs[5]}get metallic(){return this._inputs[6]}get roughness(){return this._inputs[7]}get ambientOcc(){return this._inputs[8]}get opacity(){return this._inputs[9]}get indexOfRefraction(){return this._inputs[10]}get ambientColor(){return this._inputs[11]}get reflection(){return this._inputs[12]}get clearcoat(){return this._inputs[13]}get sheen(){return this._inputs[14]}get subsurface(){return this._inputs[15]}get anisotropy(){return this._inputs[16]}get iridescence(){return this._inputs[17]}get ambientClr(){return this._outputs[0]}get diffuseDir(){return this._outputs[1]}get specularDir(){return this._outputs[2]}get clearcoatDir(){return this._outputs[3]}get sheenDir(){return this._outputs[4]}get diffuseInd(){return this._outputs[5]}get specularInd(){return this._outputs[6]}get clearcoatInd(){return this._outputs[7]}get sheenInd(){return this._outputs[8]}get refraction(){return this._outputs[9]}get lighting(){return this._outputs[10]}get shadow(){return this._outputs[11]}get alpha(){return this._outputs[12]}autoConfigure(e,t=(()=>!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Lg.CameraPosition&&t(e)));i||(i=new Kg("cameraPosition"),i.setAsSystemValue(Lg.CameraPosition)),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===Lg.View&&t(e)));i||(i=new Kg("view"),i.setAsSystemValue(Lg.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===Gm.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===Gm.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));const r=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",r.indexOf(".")<0?r+".":r,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);const s=e.getScene();if(s.getEngine()._features.needTypeSuffixInShaderConstants?i.setValue("NUM_SAMPLES",this.realTimeFilteringQuality+"u",!0):i.setValue("NUM_SAMPLES",""+this.realTimeFilteringQuality,!0),i.setValue("BRDF_V_HEIGHT_CORRELATED",!0),i.setValue("MS_BRDF_ENERGY_CONSERVATION",this.useEnergyConservation,!0),i.setValue("RADIANCEOCCLUSION",this.useRadianceOcclusion,!0),i.setValue("HORIZONOCCLUSION",this.useHorizonOcclusion,!0),i.setValue("UNLIT",this.unlit,!0),i.setValue("FORCENORMALFORWARD",this.forceNormalForward,!0),this._environmentBRDFTexture&&Sn.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){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};(0,Bt.lo)(s,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else(0,Bt.az)(s,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,(0,Bt.VO)(s,i)}updateUniformsAndSamples(e,t,i,r){for(let s=0;s=0;(0,Bt.GD)(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],r,t)}}isReady(e,t,i){return!(this._environmentBRDFTexture&&!this._environmentBRDFTexture.isReady()||i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}bind(e,t,i){if(!i)return;const r=i.getScene();this.light?(0,Bt.Kd)(this.light,this._lightId,r,e,!0):(0,Bt.RL)(r,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);const s=this._scene.ambientColor;s&&e.setColor3("ambientFromScene",s);const n=r.useRightHandedSystem===(null!=r._mirroredCameraPosition);e.setFloat(this._invertNormalName,n?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);const o=this.indexOfRefraction.connectInputBlock?.value??1.5,a=Math.pow((o-1)/(o+1),2);this._metallicReflectanceColor.scaleToRef(a*this._metallicF0Factor,H.IG.Color3[0]);const l=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,H.IG.Color3[0],l),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){const t=this.worldPosition,i=this.worldNormal,r=`//${this.name}`,s=1===e.shaderLanguage;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",r,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",r,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const n="v_"+t.associatedVariableName;e._emitVaryingFromString(n,Og.Vector4)&&(e.compilationString+=(s?"vertexOutputs.":"")+`${n} = ${t.associatedVariableName};\n`);const o="v_"+i.associatedVariableName;e._emitVaryingFromString(o,Og.Vector4)&&(e.compilationString+=(s?"vertexOutputs.":"")+`${o} = ${i.associatedVariableName};\n`);const a=this.reflection.isConnected?this.reflection.connectedPoint?.ownerBlock:null;a&&(a.viewConnectionPoint=this.view),e.compilationString+=a?.handleVertexSide(e)??"",e._emitVaryingFromString("vClipSpacePosition",Og.Vector4,"defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+="#if DEBUGMODE > 0\n",e._injectAtEnd+=(s?"vertexOutputs.":"")+`vClipSpacePosition = ${s?"vertexOutputs.position":"gl_Position"};\n`,e._injectAtEnd+="#endif\n"),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",r,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`${e._declareLocalVar("worldPos",Og.Vector4)} = ${t.associatedVariableName};\n`,this.view.isConnected&&(e.compilationString+=`${e._declareLocalVar("view",Og.Matrix)} = ${this.view.associatedVariableName};\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",r,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(e){let t=1===e.shaderLanguage?"var albedoOpacityOut: albedoOpacityOutParams;\n":"albedoOpacityOutParams albedoOpacityOut;\n";const i=this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)",r=this.opacity.isConnected?this.opacity.associatedVariableName:"1.";return t+=`albedoOpacityOut = albedoOpacityBlock(\n vec4${e.fSuffix}(${i}, 1.)\n #ifdef ALBEDO\n ,vec4${e.fSuffix}(1.)\n ,vec2${e.fSuffix}(1., 1.)\n #endif\n #ifdef OPACITY\n ,vec4${e.fSuffix}(${r})\n ,vec2${e.fSuffix}(1., 1.)\n #endif \n );\n\n ${e._declareLocalVar("surfaceAlbedo",Og.Vector3)} = albedoOpacityOut.surfaceAlbedo;\n ${e._declareLocalVar("alpha",Og.Float)} = albedoOpacityOut.alpha;\n`,t}_getAmbientOcclusionCode(e){let t=1===e.shaderLanguage?"var aoOut: ambientOcclusionOutParams;\n":"ambientOcclusionOutParams aoOut;\n";const i=this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1.";return t+=`aoOut = ambientOcclusionBlock(\n #ifdef AMBIENT\n vec3${e.fSuffix}(${i}),\n vec4${e.fSuffix}(0., 1.0, 1.0, 0.)\n #endif\n );\n`,t}_getReflectivityCode(e){const t=1===e.shaderLanguage;let i=t?"var reflectivityOut: reflectivityOutParams;\n":"reflectivityOutParams reflectivityOut;\n";return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,Og.Vector4),i+=`${e._declareLocalVar("baseColor",Og.Vector3)} = surfaceAlbedo;\n\n reflectivityOut = reflectivityBlock(\n vec4${e.fSuffix}(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.)\n #ifdef METALLICWORKFLOW\n , surfaceAlbedo\n , ${(t?"uniforms.":"")+this._vMetallicReflectanceFactorsName}\n #endif\n #ifdef REFLECTIVITY\n , vec3${e.fSuffix}(0., 0., 1.)\n , vec4${e.fSuffix}(1.)\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n , aoOut.ambientOcclusionColor\n #endif\n #ifdef MICROSURFACEMAP\n , microSurfaceTexel <== not handled!\n #endif\n );\n\n ${e._declareLocalVar("microSurface",Og.Float)} = reflectivityOut.microSurface;\n ${e._declareLocalVar("roughness",Og.Float)} = reflectivityOut.roughness;\n\n #ifdef METALLICWORKFLOW\n surfaceAlbedo = reflectivityOut.surfaceAlbedo;\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor;\n #endif\n`,i}_buildBlock(e){super._buildBlock(e),this._scene=e.sharedData.scene;const t=1===e.shaderLanguage;this._environmentBRDFTexture||(this._environmentBRDFTexture=Em(this._scene));const i=this.reflection.isConnected?this.reflection.connectedPoint?.ownerBlock:null;if(i&&(i.worldPositionConnectionPoint=this.worldPosition,i.cameraPositionConnectionPoint=this.cameraPosition,i.worldNormalConnectionPoint=this.worldNormal,i.viewConnectionPoint=this.view),e.target!==Dg.Fragment)return this._injectVertexCode(e),this;e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const r=`//${this.name}`,s=this.perturbedNormal;let n=this.worldPosition.associatedVariableName,o=this.worldNormal.associatedVariableName;this.generateOnlyFragmentCode?(n=e._getFreeVariableName("globalWorldPos"),e.compilationString+=`${n} = ${this.worldPosition.associatedVariableName}.xyz;\n`,o=e._getFreeVariableName("globalWorldNormal"),e.compilationString+=`${o} = ${this.worldNormal.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",r,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+="#if DEBUGMODE > 0\n",e.compilationString+=`${e._declareLocalVar("vClipSpacePosition",Og.Vector4)} = vec4${e.fSuffix}((vec2${e.fSuffix}(${t?"fragmentInputs.position":"gl_FragCoord.xy"}) / vec2${e.fSuffix}(1.0)) * 2.0 - 1.0, 0.0, 1.0);\n`,e.compilationString+="#endif\n"):(n=(t?"input.":"")+"v_"+n,o=(t?"input.":"")+"v_"+o),this._environmentBrdfSamplerName=e._getFreeVariableName("environmentBrdfSampler"),e._emit2DSampler(this._environmentBrdfSamplerName),e.sharedData.hints.needAlphaBlending=e.sharedData.hints.needAlphaBlending||this.useAlphaBlending,e.sharedData.hints.needAlphaTesting=e.sharedData.hints.needAlphaTesting||this.useAlphaTest,e._emitExtension("lod","#extension GL_EXT_shader_texture_lod : enable","defined(LODBASEDMICROSFURACE)"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitUniformFromString("vDebugMode",Og.Vector2,"defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene",Og.Vector3),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity"),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",r,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",r,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",r),e._emitFunctionFromInclude("importanceSampling",r),e._emitFunctionFromInclude("pbrHelperFunctions",r),e._emitFunctionFromInclude("imageProcessingDeclaration",r),e._emitFunctionFromInclude("imageProcessingFunctions",r),e._emitFunctionFromInclude("shadowsFragmentFunctions",r),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",r),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",r),e._emitFunctionFromInclude("pbrBRDFFunctions",r,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:i?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",r),e._emitFunctionFromInclude("pbrDirectLightingFunctions",r),e._emitFunctionFromInclude("pbrIBLFunctions",r),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",r),e._emitFunctionFromInclude("pbrBlockReflectivity",r),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",r),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",r),e._emitFunctionFromInclude("pbrBlockAnisotropic",r),e._emitUniformFromString("vLightingIntensity",Og.Vector4),i?.generateOnlyFragmentCode&&(e.compilationString+=i.handleVertexSide(e)),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+=`${e._declareLocalVar(this._vNormalWName,Og.Vector4)} = normalize(${o});\n`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`${e._declareLocalVar("viewDirectionW",Og.Vector3)} = normalize(${this.cameraPosition.associatedVariableName} - ${n}.xyz);\n`),e.compilationString+=`${e._declareLocalVar("geometricNormalW",Og.Vector3)} = ${this._vNormalWName}.xyz;\n`,e.compilationString+=`${e._declareLocalVar("normalW",Og.Vector3)} = ${s.isConnected?"normalize("+s.associatedVariableName+".xyz)":"geometricNormalW"};\n`,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,Og.Float),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",r,{replaceStrings:[{search:/vPositionW/g,replace:n+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(e),e.compilationString+=e._emitCodeFromInclude("depthPrePass",r),e.compilationString+=this._getAmbientOcclusionCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",r),e.compilationString+=`#ifdef UNLIT\n ${e._declareLocalVar("diffuseBase",Og.Vector3)} = vec3${e.fSuffix}(1., 1., 1.);\n #else\n`,e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",r,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:i?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:i?._define3DName??"REFLECTIONMAP_3D"}]});const a=this.anisotropy.isConnected?this.anisotropy.connectedPoint?.ownerBlock:null;a&&(a.worldPositionConnectionPoint=this.worldPosition,a.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=a.getCode(e,!this.perturbedNormal.isConnected)),i&&i.hasTexture&&(e.compilationString+=i.getCode(e,a?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",r,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:i?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:i?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:i?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:i?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:i?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:i?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:i?._vReflectionFilteringInfoName??"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",r,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:(t?"uniforms.":"")+this._vMetallicReflectanceFactorsName}]});const l=this.sheen.isConnected?this.sheen.connectedPoint?.ownerBlock:null;l&&(e.compilationString+=l.getCode(i,e)),e._emitFunctionFromInclude("pbrBlockSheen",r,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:i?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:i?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:i?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:i?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"}]});const h=this.iridescence.isConnected?this.iridescence.connectedPoint?.ownerBlock:null;e.compilationString+=BC.GetCode(h,e),e._emitFunctionFromInclude("pbrBlockIridescence",r,{replaceStrings:[]});const c=this.clearcoat.isConnected?this.clearcoat.connectedPoint?.ownerBlock:null,u=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,d=this.perturbedNormal.isConnected&&(this.perturbedNormal.connectedPoint?.ownerBlock).worldTangent?.isConnected,f=this.anisotropy.isConnected&&(this.anisotropy.connectedPoint?.ownerBlock).worldTangent.isConnected;let p=d||!this.perturbedNormal.isConnected&&f;e.compilationString+=LC.GetCode(e,c,i,n,u,p,o),u&&(p=c?.worldTangent.isConnected??!1),e._emitFunctionFromInclude("pbrBlockClearcoat",r,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:i?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:i?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:i?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:i?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:i?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:i?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:p?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",r,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:i?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:i?._define3DName??"REFLECTIONMAP_3D"}]});const _=this.subsurface.isConnected?this.subsurface.connectedPoint?.ownerBlock:null,m=this.subsurface.isConnected?(this.subsurface.connectedPoint?.ownerBlock).refraction.connectedPoint?.ownerBlock:null;m&&(m.viewConnectionPoint=this.view,m.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=kC.GetCode(e,_,i,n),e._emitFunctionFromInclude("pbrBlockSubSurface",r,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:i?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:i?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:i?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:m?._define3DName??"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:m?._defineLODRefractionAlpha??"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:m?._defineLinearSpecularRefraction??"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:m?._defineOppositeZ??"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",r),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",r,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:new RegExp((t?"fragmentInputs.":"")+"vPositionW","g"),replace:n+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",r,{repeatKey:"maxSimultaneousLights",substitutionVars:`${t?"fragmentInputs.":""}vPositionW,${n}.xyz`}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",r),e.compilationString+="#endif\n";const g=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:`vec3${e.fSuffix}(0., 0., 0.)`;let v=Gm.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();-1===v.indexOf(".")&&(v+=".");let x=[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:new RegExp((t?"uniforms.":"")+"vAmbientColor","g"),replace:g+` * ${t?"uniforms.":""}ambientFromScene`},{search:new RegExp((t?"uniforms.":"")+"vAmbientInfos.w","g"),replace:v}];t&&(x[0]={search:/var finalEmissive[\s\S]*?finalEmissive\*=uniforms.vLightingIntensity\.y;/g,replace:""}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",r,{replaceStrings:x}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",r,{replaceStrings:[{search:/finalEmissive/g,replace:`vec3${e.fSuffix}(0.)`}]}),x=t?[{search:/mesh.visibility/g,replace:"1."}]:[{search:/visibility/g,replace:"1."}],e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",r,{replaceStrings:x});const b=t?"fragmentOutputs.color":"gl_FragColor";x=[{search:new RegExp((t?"fragmentInputs.":"")+"vNormalW","g"),replace:this._vNormalWName},{search:new RegExp((t?"fragmentInputs.":"")+"vPositionW","g"),replace:n},{search:/albedoTexture\.rgb;/g,replace:`vec3${e.fSuffix}(1.);\n${b}.rgb = toGammaSpace(${b}.rgb);\n`}],e.compilationString+=e._emitCodeFromInclude("pbrDebug",r,{replaceStrings:x});for(const t of this._outputs)if(t.hasEndpoints){const i=UC[t.name];if(i){const[r,s]=i;s&&(e.compilationString+=`#if ${s}\n`),e.compilationString+=`${e._declareOutput(t)} = ${r};\n`,s&&(e.compilationString+="#else\n",e.compilationString+=`${e._declareOutput(t)} = vec3${e.fSuffix}(0.);\n`,e.compilationString+="#endif\n")}else Z.V.Error(`There's no remapping for the ${t.name} end point! No code generated`)}return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.lightFalloff = ${this.lightFalloff};\n`,e+=`${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest};\n`,e+=`${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff};\n`,e+=`${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending};\n`,e+=`${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha};\n`,e+=`${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha};\n`,e+=`${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing};\n`,e+=`${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering};\n`,e+=`${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality};\n`,e+=`${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation};\n`,e+=`${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion};\n`,e+=`${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion};\n`,e+=`${this._codeVariableName}.unlit = ${this.unlit};\n`,e+=`${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward};\n`,e+=`${this._codeVariableName}.debugMode = ${this.debugMode};\n`,e+=`${this._codeVariableName}.debugLimit = ${this.debugLimit};\n`,e+=`${this._codeVariableName}.debugFactor = ${this.debugFactor};\n`,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()}}(0,je.Cg)([t_("Direct lights",1,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],GC.prototype,"directIntensity",void 0),(0,je.Cg)([t_("Environment lights",1,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],GC.prototype,"environmentIntensity",void 0),(0,je.Cg)([t_("Specular highlights",1,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],GC.prototype,"specularIntensity",void 0),(0,je.Cg)([t_("Light falloff",4,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:Gm.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:Gm.LIGHTFALLOFF_GLTF},{label:"Standard",value:Gm.LIGHTFALLOFF_STANDARD}]})],GC.prototype,"lightFalloff",void 0),(0,je.Cg)([t_("Alpha Testing",0,"OPACITY")],GC.prototype,"useAlphaTest",void 0),(0,je.Cg)([t_("Alpha CutOff",1,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],GC.prototype,"alphaTestCutoff",void 0),(0,je.Cg)([t_("Alpha blending",0,"OPACITY")],GC.prototype,"useAlphaBlending",void 0),(0,je.Cg)([t_("Radiance over alpha",0,"RENDERING",{notifiers:{update:!0}})],GC.prototype,"useRadianceOverAlpha",void 0),(0,je.Cg)([t_("Specular over alpha",0,"RENDERING",{notifiers:{update:!0}})],GC.prototype,"useSpecularOverAlpha",void 0),(0,je.Cg)([t_("Specular anti-aliasing",0,"RENDERING",{notifiers:{update:!0}})],GC.prototype,"enableSpecularAntiAliasing",void 0),(0,je.Cg)([t_("Realtime filtering",0,"RENDERING",{notifiers:{update:!0}})],GC.prototype,"realTimeFiltering",void 0),(0,je.Cg)([t_("Realtime filtering quality",4,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],GC.prototype,"realTimeFilteringQuality",void 0),(0,je.Cg)([t_("Energy Conservation",0,"ADVANCED",{notifiers:{update:!0}})],GC.prototype,"useEnergyConservation",void 0),(0,je.Cg)([t_("Radiance occlusion",0,"ADVANCED",{notifiers:{update:!0}})],GC.prototype,"useRadianceOcclusion",void 0),(0,je.Cg)([t_("Horizon occlusion",0,"ADVANCED",{notifiers:{update:!0}})],GC.prototype,"useHorizonOcclusion",void 0),(0,je.Cg)([t_("Unlit",0,"ADVANCED",{notifiers:{update:!0}})],GC.prototype,"unlit",void 0),(0,je.Cg)([t_("Force normal forward",0,"ADVANCED",{notifiers:{update:!0}})],GC.prototype,"forceNormalForward",void 0),(0,je.Cg)([t_("Generate only fragment code",0,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:GC._OnGenerateOnlyFragmentCodeChanged}})],GC.prototype,"generateOnlyFragmentCode",void 0),(0,je.Cg)([t_("Debug mode",4,"DEBUG",{notifiers:{update:!0},options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87},{label:"Albedo color",value:88},{label:"Ambient occlusion color",value:89}]})],GC.prototype,"debugMode",void 0),(0,je.Cg)([t_("Split position",1,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],GC.prototype,"debugLimit",void 0),(0,je.Cg)([t_("Output factor",1,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],GC.prototype,"debugFactor",void 0),(0,X.Y5)("BABYLON.PBRMetallicRoughnessBlock",GC);class zC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("left",Og.AutoDetect),this.registerInput("right",Og.AutoDetect),this.registerOutput("output",Og.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[1].acceptedConnectionPointTypes.push(Og.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 0===e.shaderLanguage?e.compilationString+=e._declareOutput(t)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`:e.compilationString+=e._declareOutput(t)+` = (${this.left.associatedVariableName} % ${this.right.associatedVariableName});\n`,this}}(0,X.Y5)("BABYLON.ModBlock",zC);class WC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("row0",Og.Vector4),this.registerInput("row1",Og.Vector4),this.registerInput("row2",Og.Vector4),this.registerInput("row3",Og.Vector4),this.registerOutput("output",Og.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 Kg("row0");e.value=new W.IU(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){const e=new Kg("row1");e.value=new W.IU(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){const e=new Kg("row2");e.value=new W.IU(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){const e=new Kg("row3");e.value=new W.IU(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.row0,r=this.row1,s=this.row2,n=this.row3,o=1===e.shaderLanguage?"mat4x4f":"mat4";return e.compilationString+=e._declareOutput(t)+` = ${o}(${i.associatedVariableName}, ${r.associatedVariableName}, ${s.associatedVariableName}, ${n.associatedVariableName});\n`,this}}var HC,XC,qC;(0,X.Y5)("BABYLON.MatrixBuilder",WC),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(HC||(HC={}));class YC extends Gg{constructor(e){super(e,Dg.Neutral),this.condition=HC.LessThan,this.registerInput("a",Og.Float),this.registerInput("b",Og.Float),this.registerInput("true",Og.AutoDetect,!0),this.registerInput("false",Og.AutoDetect,!0),this.registerOutput("output",Og.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=Og.Float}getClassName(){return"ConditionalBlock"}get a(){return this._inputs[0]}get b(){return this._inputs[1]}get true(){return this._inputs[2]}get false(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.true.isConnected?this.true.associatedVariableName:"1.0",r=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case HC.Equal:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`${this.a.associatedVariableName} == ${this.b.associatedVariableName}`)};\n`;break;case HC.NotEqual:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`${this.a.associatedVariableName} != ${this.b.associatedVariableName}`)};\n`;break;case HC.LessThan:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`${this.a.associatedVariableName} < ${this.b.associatedVariableName}`)};\n`;break;case HC.LessOrEqual:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`${this.a.associatedVariableName} <= ${this.b.associatedVariableName}`)};\n`;break;case HC.GreaterThan:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`${this.a.associatedVariableName} > ${this.b.associatedVariableName}`)};\n`;break;case HC.GreaterOrEqual:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`${this.a.associatedVariableName} >= ${this.b.associatedVariableName}`)};\n`;break;case HC.Xor:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`(((${this.a.associatedVariableName} + ${this.b.associatedVariableName}) % 2.0) > 0.0)`)};\n`;break;case HC.Or:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`(min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0)`)};\n`;break;case HC.And:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,r,`(${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0)`)};\n`}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.${HC[this.condition]};\n`}}(0,je.Cg)([t_("Condition",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"Equal",value:HC.Equal},{label:"NotEqual",value:HC.NotEqual},{label:"LessThan",value:HC.LessThan},{label:"GreaterThan",value:HC.GreaterThan},{label:"LessOrEqual",value:HC.LessOrEqual},{label:"GreaterOrEqual",value:HC.GreaterOrEqual},{label:"Xor",value:HC.Xor},{label:"And",value:HC.And},{label:"Or",value:HC.Or}]})],YC.prototype,"condition",void 0),(0,X.Y5)("BABYLON.ConditionalBlock",YC);class KC extends Gg{constructor(e){super(e,Dg.Neutral),this.octaves=6,this.registerInput("seed",Og.AutoDetect),this.registerInput("chaos",Og.AutoDetect,!0),this.registerInput("offsetX",Og.Float,!0),this.registerInput("offsetY",Og.Float,!0),this.registerInput("offsetZ",Og.Float,!0),this.registerOutput("output",Og.Float),this._inputs[0].acceptedConnectionPointTypes.push(Og.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(Og.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){if(super._buildBlock(e),!this.seed.isConnected)return;if(!this._outputs[0].hasEndpoints)return;let t="\n\n float cloudRandom(float p) { \n float temp = fract(p * 0.011); \n temp *= temp + 7.5; \n temp *= temp + temp; \n return fract(temp); \n }\n\n // Based on Morgan McGuire @morgan3d\n // https://www.shadertoy.com/view/4dS3Wd\n float cloudNoise2(vec2 x, vec2 chaos) {\n vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.);\n\n vec2 i = floor(x);\n vec2 f = fract(x);\n\n float n = dot(i, step);\n\n vec2 u = f * f * (3.0 - 2.0 * f);\n return mix(\n mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x),\n mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x),\n u.y\n );\n }\n\n float cloudNoise3(vec3 x, vec3 chaos) {\n vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.);\n\n vec3 i = floor(x);\n vec3 f = fract(x);\n\n float n = dot(i, step);\n\n vec3 u = f * f * (3.0 - 2.0 * f);\n return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y),\n mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z);\n }",i="\n float fbm2(vec2 st, vec2 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = .5;\n float frequency = 0.;\n\n // Loop of octaves\n vec2 tempST = st;\n for (int i = 0; i < OCTAVES; i++) {\n value += amplitude * cloudNoise2(tempST, chaos);\n tempST *= 2.0;\n amplitude *= 0.5;\n }\n return value;\n }\n\n float fbm3(vec3 x, vec3 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = 0.5;\n vec3 tempX = x;\n for (int i = 0; i < OCTAVES; i++) {\n value += amplitude * cloudNoise3(tempX, chaos);\n tempX = tempX * 2.0;\n amplitude *= 0.5;\n }\n return value;\n }";1===e.shaderLanguage&&(t=e._babylonSLtoWGSL(t),i=e._babylonSLtoWGSL(i));const r=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode",t,"// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,i.replace(/fbm/gi,r).replace(/OCTAVES/gi,(0|this.octaves).toString()),"// CloudBlockCode FBM");const s=e._getFreeVariableName("st"),n=this.seed.connectedPoint?.type||Og.Vector3;e.compilationString+=`${e._declareLocalVar(s,n)} = ${this.seed.associatedVariableName};\n`,this.offsetX.isConnected&&(e.compilationString+=`${s}.x += 0.1 * ${this.offsetX.associatedVariableName};\n`),this.offsetY.isConnected&&(e.compilationString+=`${s}.y += 0.1 * ${this.offsetY.associatedVariableName};\n`),this.offsetZ.isConnected&&n===Og.Vector3&&(e.compilationString+=`${s}.z += 0.1 * ${this.offsetZ.associatedVariableName};\n`);let o="";if(this.chaos.isConnected)o=this.chaos.associatedVariableName;else{const t=e.fSuffix;o=this.seed.connectedPoint?.type===Og.Vector2?`vec2${t}(0., 0.)`:`vec3${t}(0., 0., 0.)`}return e.compilationString+=e._declareOutput(this._outputs[0])+` = ${r}${this.seed.connectedPoint?.type===Og.Vector2?"2":"3"}(${s}, ${o});\n`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves};\n`}serialize(){const e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}}(0,je.Cg)([t_("Octaves",2,void 0,{embedded:!0})],KC.prototype,"octaves",void 0),(0,X.Y5)("BABYLON.CloudBlock",KC);class jC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("seed",Og.Vector2),this.registerInput("offset",Og.Float),this.registerInput("density",Og.Float),this.registerOutput("output",Og.Float),this.registerOutput("cells",Og.Float)}getClassName(){return"VoronoiNoiseBlock"}get seed(){return this._inputs[0]}get offset(){return this._inputs[1]}get density(){return this._inputs[2]}get output(){return this._outputs[0]}get cells(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;let t="vec2 voronoiRandom(vec2 p){\n p = vec2(dot(p,vec2(127.1,311.7)),dot(p,vec2(269.5,183.3)));\n return fract(sin(p)*18.5453);\n }\n ";1===e.shaderLanguage&&(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){\n vec2 n = floor(seed * density);\n vec2 f = fract(seed * density);\n vec3 m = vec3( 8.0 );\n for( int j=-1; j<=1; j++ ){\n for( int i=-1; i<=1; i++ ){\n vec2 g = vec2( float(i), float(j) );\n vec2 o = voronoiRandom( n + g);\n vec2 r = g - f + (0.5+0.5*sin(offset+6.2831*o));\n float d = dot( r, r );\n if( de.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get textureY(){return this.sourceY.isConnected?(this.sourceY.connectedPoint?.ownerBlock).texture:null}get textureZ(){return this.sourceZ?.isConnected?(this.sourceY.connectedPoint?.ownerBlock).texture:null}_getImageSourceBlock(e){return e?.isConnected?e.connectedPoint.ownerBlock:null}get samplerName(){const e=this._getImageSourceBlock(this.source);return e?e.samplerName:this._samplerName}get samplerYName(){return this._getImageSourceBlock(this.sourceY)?.samplerName??null}get samplerZName(){return this._getImageSourceBlock(this.sourceZ)?.samplerName??null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const e=this.texture.getScene()??he.q.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=this.texture.getScene()??he.q.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,Dg.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",Og.AutoDetect,!1),this.registerInput("normal",Og.AutoDetect,!1),this.registerInput("sharpness",Og.Float,!0),this.registerInput("source",Og.Object,!0,Dg.VertexAndFragment,new cS("source",this,0,dT,"ImageSourceBlock")),this.registerInput("sourceY",Og.Object,!0,Dg.VertexAndFragment,new cS("sourceY",this,0,dT,"ImageSourceBlock")),t||this.registerInput("sourceZ",Og.Object,!0,Dg.VertexAndFragment,new cS("sourceZ",this,0,dT,"ImageSourceBlock")),this.registerOutput("rgba",Og.Color4,Dg.Neutral),this.registerOutput("rgb",Og.Color3,Dg.Neutral),this.registerOutput("r",Og.Float,Dg.Neutral),this.registerOutput("g",Og.Float,Dg.Neutral),this.registerOutput("b",Og.Float,Dg.Neutral),this.registerOutput("a",Og.Float,Dg.Neutral),this.registerOutput("level",Og.Float,Dg.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(Og.Color3|Og.Vector3|Og.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(Og.Color3|Og.Vector3|Og.Vector4)}getClassName(){return"TriPlanarBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get sharpness(){return this._inputs[2]}get source(){return this._inputs[3]}get sourceY(){return this._inputs[4]}get sourceZ(){return this._inputs[5]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,s,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))}_samplerFunc(e){return 1===e.shaderLanguage?"textureSample":"texture2D"}_generateTextureSample(e,t,i){return 1===i.shaderLanguage?`${this._samplerFunc(i)}(${e},${e+"Sampler"}, ${t})`:`${this._samplerFunc(i)}(${e}, ${t})`}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??t,r=this.samplerZName??t,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",n=e._getFreeVariableName("x"),o=e._getFreeVariableName("y"),a=e._getFreeVariableName("z"),l=e._getFreeVariableName("w"),h=e._getFreeVariableName("n"),c=e._getFreeVariableName("uvx"),u=e._getFreeVariableName("uvy"),d=e._getFreeVariableName("uvz");e.compilationString+=`\n ${e._declareLocalVar(h,Og.Vector3)} = ${this.normal.associatedVariableName}.xyz;\n\n ${e._declareLocalVar(c,Og.Vector2)} = ${this.position.associatedVariableName}.yz;\n ${e._declareLocalVar(u,Og.Vector2)} = ${this.position.associatedVariableName}.zx;\n ${e._declareLocalVar(d,Og.Vector2)} = ${this.position.associatedVariableName}.xy;\n `,this.projectAsCube&&(e.compilationString+=`\n ${c}.xy = ${c}.yx;\n\n if (${h}.x >= 0.0) {\n ${c}.x = -${c}.x;\n }\n if (${h}.y < 0.0) {\n ${u}.y = -${u}.y;\n }\n if (${h}.z < 0.0) {\n ${d}.x = -${d}.x;\n }\n `);const f=e.fSuffix;e.compilationString+=`\n ${e._declareLocalVar(n,Og.Vector4)} = ${this._generateTextureSample(t,c,e)};\n ${e._declareLocalVar(o,Og.Vector4)} = ${this._generateTextureSample(i,u,e)};\n ${e._declareLocalVar(a,Og.Vector4)} = ${this._generateTextureSample(r,d,e)};\n \n // blend weights\n ${e._declareLocalVar(l,Og.Vector3)} = pow(abs(${h}), vec3${f}(${s}));\n\n // blend and return\n ${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = (${n}*${l}.x + ${o}*${l}.y + ${a}*${l}.z) / (${l}.x + ${l}.y + ${l}.z); \n `}_generateConversionCode(e,t,i){let r="";1!==e.shaderLanguage||t.type!==Og.Vector3&&t.type!==Og.Color3||(r="Vec3"),"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace${r}(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = toLinearSpace${r}(${t.associatedVariableName});\n #endif\n `)}_writeOutput(e,t,i){let r="";this.disableLevelMultiplication||(r=` * ${1===e.shaderLanguage?"uniforms.":""}${this._textureInfoName}`),e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}${r};\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=(1===e.shaderLanguage?"uniforms.":"")+this._textureInfoName,this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA"),this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Texture"),e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,Og.Float),this._generateTextureLookup(e);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\n`,e+=`${this._codeVariableName}.projectAsCube = ${this.projectAsCube};\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):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||"VideoTexture"===this.texture.getClassName()||(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&&!pv.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=vi.g.Parse(e.texture,t,i))}}(0,je.Cg)([t_("Project as cube",0,"ADVANCED",{embedded:!0,notifiers:{update:!0}})],QC.prototype,"projectAsCube",void 0),(0,X.Y5)("BABYLON.TriPlanarBlock",QC);class ZC extends QC{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_declareLocalVarAsVec3I(e,t){return 1===t.shaderLanguage?`var ${e}: vec3`:`ivec3 ${e}`}_getTextureGrad(e,t){return 1===e.shaderLanguage?`textureSampleGrad(${t},${t+"Sampler"}`:`textureGrad(${t}`}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??this.samplerName,r=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",s=e._getFreeVariableName("dxValue"),n=e._getFreeVariableName("dyValue"),o=e._getFreeVariableName("n"),a=e._getFreeVariableName("ma"),l=e._getFreeVariableName("mi"),h=e._getFreeVariableName("me"),c=e._getFreeVariableName("x"),u=e._getFreeVariableName("y"),d=e._getFreeVariableName("w");let f="ivec3",p="dFdx",_="dFdy";const m=e.fSuffix;1===e.shaderLanguage&&(f="vec3",p="dpdx",_="dpdy"),e.compilationString+=`\n // grab coord derivatives for texturing\n ${e._declareLocalVar(s,Og.Vector3)} = ${p}(${this.position.associatedVariableName}.xyz);\n ${e._declareLocalVar(n,Og.Vector3)} = ${_}(${this.position.associatedVariableName}.xyz);\n ${e._declareLocalVar(o,Og.Vector3)} = abs(${this.normal.associatedVariableName}.xyz);\n \n // determine major axis (in x; yz are following axis)\n ${this._declareLocalVarAsVec3I(a,e)} = ${e._generateTernary(`${f}(0,1,2)`,`${e._generateTernary(`${f}(1,2,0)`,`${f}(2,0,1)`,`(${o}.y>${o}.z)`)}`,`(${o}.x>${o}.y && ${o}.x>${o}.z)`)}; \n\n // determine minor axis (in x; yz are following axis)\n ${this._declareLocalVarAsVec3I(l,e)} = ${e._generateTernary(`${f}(0,1,2)`,`${e._generateTernary(`${f}(1,2,0)`,`${f}(2,0,1)`,`(${o}.y<${o}.z)`)}`,`(${o}.x<${o}.y && ${o}.x<${o}.z)`)}; \n \n // determine median axis (in x; yz are following axis)\n ${this._declareLocalVarAsVec3I(h,e)} = ${f}(3) - ${l} - ${a};\n \n // project+fetch\n ${e._declareLocalVar(c,Og.Vector4)} = ${this._getTextureGrad(e,t)}, vec2${m}(${this.position.associatedVariableName}[${a}.y], ${this.position.associatedVariableName}[${a}.z]), \n vec2${m}(${s}[${a}.y],${s}[${a}.z]), \n vec2${m}(${n}[${a}.y],${n}[${a}.z]));\n ${e._declareLocalVar(u,Og.Vector4)} = ${this._getTextureGrad(e,i)}, vec2${m}(${this.position.associatedVariableName}[${h}.y], ${this.position.associatedVariableName}[${h}.z]), \n vec2${m}(${s}[${h}.y],${s}[${h}.z]),\n vec2${m}(${n}[${h}.y],${n}[${h}.z]));\n \n // blend factors\n ${e._declareLocalVar(d,Og.Vector2)} = vec2${m}(${o}[${a}.x],${o}[${h}.x]);\n // make local support\n ${d} = clamp( (${d}-0.5773)/(1.0-0.5773), vec2${m}(0.0), vec2${m}(1.0) );\n // shape transition\n ${d} = pow( ${d}, vec2${m}(${r}/8.0) );\n // blend and return\n ${e._declareLocalVar(this._tempTextureRead,Og.Vector4)} = (${c}*${d}.x + ${u}*${d}.y) / (${d}.x + ${d}.y);\n `}}(0,X.Y5)("BABYLON.BiPlanarBlock",ZC);class JC extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("input",Og.Matrix),this.registerOutput("output",Og.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});\n`,this}}(0,X.Y5)("BABYLON.MatrixDeterminantBlock",JC);class ey extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("input",Og.Matrix),this.registerOutput("output",Og.Matrix)}getClassName(){return"MatrixTransposeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=e._declareOutput(t)+` = transpose(${i.associatedVariableName});\n`,this}}(0,X.Y5)("BABYLON.MatrixTransposeBlock",ey),function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Tangent=2]="Tangent",e[e.VertexColor=3]="VertexColor",e[e.UV1=4]="UV1",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6"}(XC||(XC={}));class ty extends Gg{constructor(e){super(e,Dg.Neutral),this.attributeType=0,this.registerInput("input",Og.AutoDetect),this.registerInput("fallback",Og.AutoDetect),this.registerOutput("output",Og.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add((e=>{if(this.attributeType)return;const t=e.ownerBlock;if(t instanceof Kg&&t.isAttribute)switch(t.name){case"color":this.attributeType=3;break;case"normal":this.attributeType=1;break;case"tangent":this.attributeType=2;break;case"uv":this.attributeType=4;break;case"uv2":this.attributeType=5;break;case"uv3":this.attributeType=6;break;case"uv4":this.attributeType=7;break;case"uv5":this.attributeType=8;break;case"uv6":this.attributeType=9}else if(t instanceof xS)switch(this.input.connectedPoint?.name){case"normalOutput":this.attributeType=1;break;case"tangentOutput":this.attributeType=2;break;case"uvOutput":this.attributeType=4}}))}getClassName(){return"MeshAttributeExistsBlock"}get input(){return this._inputs[0]}get fallback(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.attributeType){case 3:t="VERTEXCOLOR_NME";break;case 1:t="NORMAL";break;case 2:t="TANGENT";break;case 4:t="UV1";break;case 5:t="UV2";break;case 6:t="UV3";break;case 7:t="UV4";break;case 8:t="UV5";break;case 9:t="UV6"}const i=e._declareOutput(this.output);return t&&(e.compilationString+=`#ifdef ${t}\n`),e.compilationString+=`${i} = ${this.input.associatedVariableName};\n`,t&&(e.compilationString+="#else\n",e.compilationString+=`${i} = ${this.fallback.associatedVariableName};\n`,e.compilationString+="#endif\n"),this}serialize(){const e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.attributeType=e.attributeType??0}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.attributeType = ${this.attributeType};\n`,e}}(0,je.Cg)([t_("Attribute lookup",4,void 0,{notifiers:{update:!0},embedded:!0,options:[{label:"(None)",value:0},{label:"Normal",value:1},{label:"Tangent",value:2},{label:"Vertex Color",value:3},{label:"UV1",value:4},{label:"UV2",value:5},{label:"UV3",value:6},{label:"UV4",value:7},{label:"UV5",value:8},{label:"UV6",value:9}]})],ty.prototype,"attributeType",void 0),(0,X.Y5)("BABYLON.MeshAttributeExistsBlock",ty),function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(qC||(qC={}));class iy extends Gg{constructor(e){super(e,Dg.Neutral),this.type=qC.EaseInOutSine,this.registerInput("input",Og.AutoDetect),this.registerOutput("output",Og.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Og.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Og.Object),this._inputs[0].excludedConnectionPointTypes.push(Og.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("float"===t||"f32"===t)return this._duplicateEntryDirect(e);const r=parseInt(t.replace("vec",""));let s=i?`\n var ret: vec${r}f = vec${r}f(0.0);\n `:`\n vec${r} ret = vec${r}(0.0);\n `;for(let t=1;t<=r;t++)s+=this._duplicateEntry(e,1===t?"x":2===t?"y":3===t?"z":"w")+";\n";return s+="return ret;\n",s}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="",r="";const s=e._getShaderType(this.input.type),n=1===e.shaderLanguage;switch(r=qC[this.type]+"_"+s.replace("<","").replace(">",""),this.type){case qC.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case qC.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case qC.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case qC.EaseInQuad:i="return v * v";break;case qC.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case qC.EaseInOutQuad:{const t=e._generateTernary("2.0 * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,s,n);break}case qC.EaseInCubic:i="return v * v * v";break;case qC.EaseOutCubic:{const e="1.0 - pow(1.0 - VAL, 3.0)";i=this._duplicateVector(e,s,n);break}case qC.EaseInOutCubic:{const t=e._generateTernary("4.0 * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,s,n);break}case qC.EaseInQuart:i="return v * v * v * v";break;case qC.EaseOutQuart:{const e="1.0 - pow(1.0 - VAL, 4.0)";i=this._duplicateVector(e,s,n);break}case qC.EaseInOutQuart:{const t=e._generateTernary("8.0 * VAL * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,s,n);break}case qC.EaseInQuint:i="return v * v * v * v * v";break;case qC.EaseOutQuint:{const e="1.0 - pow(1.0 - VAL, 5.0)";i=this._duplicateVector(e,s,n);break}case qC.EaseInOutQuint:{const t=e._generateTernary("16.0 * VAL * VAL * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,s,n);break}case qC.EaseInExpo:{const t=e._generateTernary("0.0","pow(2.0, 10.0 * VAL - 10.0)","VAL == 0.0");i=this._duplicateVector(t,s,n);break}case qC.EaseOutExpo:{const t=e._generateTernary("1.0","1.0 - pow(2.0, -10.0 * VAL)","VAL == 1.0");i=this._duplicateVector(t,s,n);break}case qC.EaseInOutExpo:{const t=e._generateTernary("0.0",e._generateTernary("1.0",e._generateTernary("pow(2.0, 20.0 * VAL - 10.0) / 2.0","(2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0","VAL < 0.5"),"VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,s,n);break}case qC.EaseInCirc:{const e="1.0 - sqrt(1.0 - pow(VAL, 2.0))";i=this._duplicateVector(e,s,n);break}case qC.EaseOutCirc:{const e="sqrt(1.0 - pow(VAL - 1.0, 2.0))";i=this._duplicateVector(e,s,n);break}case qC.EaseInOutCirc:{const t=e._generateTernary("(1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0","(sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,s,n);break}case qC.EaseInBack:i="return 2.70158 * v * v * v - 1.70158 * v * v";break;case qC.EaseOutBack:{const e="2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)";i=this._duplicateVector(e,s,n);break}case qC.EaseInOutBack:{const t=e._generateTernary("(pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0","(pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,s,n);break}case qC.EaseInElastic:{const t=e._generateTernary("0.0",e._generateTernary("1.0","-pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))","VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,s,n);break}case qC.EaseOutElastic:{const t=e._generateTernary("0.0",e._generateTernary("1.0","pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0","VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,s,n);break}case qC.EaseInOutElastic:{const t=e._generateTernary("0.0",e._generateTernary("1.0",e._generateTernary("-(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0","(pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0","VAL < 0.5"),"VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,s,n);break}}return n?e._emitFunction(r,`fn ${r}(v: ${s}) -> ${s} {${i};}\n`,""):e._emitFunction(r,`${s} ${r}(${s} v) {${i};}\n`,""),e.compilationString+=e._declareOutput(t)+` = ${r}(${this.input.associatedVariableName});\n`,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.${qC[this.type]};\n`}}(0,je.Cg)([t_("Type",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"EaseInSine",value:qC.EaseInSine},{label:"EaseOutSine",value:qC.EaseOutSine},{label:"EaseInOutSine",value:qC.EaseInOutSine},{label:"EaseInQuad",value:qC.EaseInQuad},{label:"EaseOutQuad",value:qC.EaseOutQuad},{label:"EaseInOutQuad",value:qC.EaseInOutQuad},{label:"EaseInCubic",value:qC.EaseInCubic},{label:"EaseOutCubic",value:qC.EaseOutCubic},{label:"EaseInOutCubic",value:qC.EaseInOutCubic},{label:"EaseInQuart",value:qC.EaseInQuart},{label:"EaseOutQuart",value:qC.EaseOutQuart},{label:"EaseInOutQuart",value:qC.EaseInOutQuart},{label:"EaseInQuint",value:qC.EaseInQuint},{label:"EaseOutQuint",value:qC.EaseOutQuint},{label:"EaseInOutQuint",value:qC.EaseInOutQuint},{label:"EaseInExpo",value:qC.EaseInExpo},{label:"EaseOutExpo",value:qC.EaseOutExpo},{label:"EaseInOutExpo",value:qC.EaseInOutExpo},{label:"EaseInCirc",value:qC.EaseInCirc},{label:"EaseOutCirc",value:qC.EaseOutCirc},{label:"EaseInOutCirc",value:qC.EaseInOutCirc},{label:"EaseInBack",value:qC.EaseInBack},{label:"EaseOutBack",value:qC.EaseOutBack},{label:"EaseInOutBack",value:qC.EaseInOutBack},{label:"EaseInElastic",value:qC.EaseInElastic},{label:"EaseOutElastic",value:qC.EaseOutElastic},{label:"EaseInOutElastic",value:qC.EaseInOutElastic}]})],iy.prototype,"type",void 0),(0,X.Y5)("BABYLON.CurveBlock",iy);class ry extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("rgb ",Og.Color3,!0),this.registerInput("hsl ",Og.Color3,!0),this.registerOutput("rgb",Og.Color3),this.registerOutput("hsl",Og.Color3)}getClassName(){return"ColorConverterBlock"}get rgbIn(){return this._inputs[0]}get hslIn(){return this._inputs[1]}get rgbOut(){return this._outputs[0]}get hslOut(){return this._outputs[1]}_inputRename(e){return"rgb "===e?"rgbIn":"hsl "===e?"hslIn":e}_buildBlock(e){super._buildBlock(e);const t=this.rgbIn,i=this.hslIn,r=this._outputs[0],s=this._outputs[1],n=e._getShaderType(Og.Vector3);let o="\n vec3 rgb2hsl(vec3 color) {\n float r = color.r;\n float g = color.g;\n float b = color.b;\n\n float maxc = max(r, max(g, b));\n float minc = min(r, min(g, b));\n float h = 0.0;\n float s = 0.0;\n float l = (maxc + minc) / 2.0;\n\n if (maxc != minc) {\n float d = maxc - minc;\n if (l > 0.5) {\n s = d / (2.0 - maxc - minc);\n } else {\n s = d / (maxc + minc);\n }\n\n if (maxc == r) {\n float add = 0.0;\n if (g < b) {\n add = 6.0;\n }\n h = (g - b) / d + add;\n } else if (maxc == g) {\n h = (b - r) / d + 2.0;\n } else if (maxc == b) {\n h = (r - g) / d + 4.0;\n }\n h /= 6.0;\n }\n\n return vec3(h, s, l);\n }",a="\n float hue2rgb(float p, float q, float tt) {\n float t = tt;\n if (t < 0.0) {\n t += 1.0;\n }\n if (t > 1.0) {\n t -= 1.0;\n }\n if (t < 1.0/6.0) {\n return p + (q - p) * 6.0 * t;\n }\n if (t < 1.0/2.0) {\n return q;\n }\n if (t < 2.0/3.0) {\n return p + (q - p) * (2.0/3.0 - t) * 6.0;\n }\n return p;\n }",l="\n vec3 hsl2rgb(vec3 hsl) {\n float h = hsl.x;\n float s = hsl.y;\n float l = hsl.z;\n\n float r;\n float g;\n float b;\n\n if (s == 0.0) {\n // Achromatic (grey)\n r = l;\n g = l;\n b = l; \n } else {\n float q;\n \n if (l < 0.5) {\n q = l * (1.0 + s);\n } else {\n q = (l + s - l * s);\n }\n\n float p = 2.0 * l - q;\n\n r = hue2rgb(p, q, h + 1.0/3.0);\n g = hue2rgb(p, q, h);\n b = hue2rgb(p, q, h - 1.0/3.0);\n }\n\n return vec3(r, g, b);\n }";return 1===e.shaderLanguage&&(o=e._babylonSLtoWGSL(o),a=e._babylonSLtoWGSL(a),l=e._babylonSLtoWGSL(l)),e._emitFunction("rgb2hsl",o,""),e._emitFunction("hue2rgb",a,""),e._emitFunction("hsl2rgb",l,""),t.isConnected?(r.hasEndpoints&&(e.compilationString+=e._declareOutput(r)+` = ${t.associatedVariableName};\n`),s.hasEndpoints&&(e.compilationString+=e._declareOutput(s)+` = rgb2hsl(${t.associatedVariableName});\n`)):i.isConnected?(r.hasEndpoints&&(e.compilationString+=e._declareOutput(r)+` = hsl2rgb(${i.associatedVariableName});\n`),s.hasEndpoints&&(e.compilationString+=e._declareOutput(s)+` = ${i.associatedVariableName};\n`)):(r.hasEndpoints&&(e.compilationString+=e._declareOutput(r)+` = ${n}(0.);\n`),s.hasEndpoints&&(e.compilationString+=e._declareOutput(s)+` = ${n}(0.);\n`)),this}}(0,X.Y5)("BABYLON.ColorConverterBlock",ry);class sy extends Gg{constructor(e){super(e,Dg.Neutral),this.iterations=4,this.registerInput("input",Og.AutoDetect),this.registerInput("iterations",Og.Float,!0),this.registerOutput("output",Og.BasedOnInput),this.registerOutput("index",Og.Float,Dg.Fragment),this.registerOutput("loopID",Og.Object,void 0,new cS("loopID",this,1,sy,"LoopBlock")),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[0]._forPostBuild=!0,this._outputs[2]._redirectedSource=this._inputs[0],this._outputs[1]._preventBubbleUp=!0,this._outputs[2]._preventBubbleUp=!0}getClassName(){return"LoopBlock"}get input(){return this._inputs[0]}get iterationsInput(){return this._inputs[1]}get output(){return this._outputs[0]}get index(){return this._outputs[1]}get loopID(){return this._outputs[2]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._outputs[1],r=e._getFreeVariableName("index"),s=1===e.shaderLanguage?"var":"int",n=1===e.shaderLanguage?"f32":"float",o=1===e.shaderLanguage?"i32":"int";e.compilationString+=e._declareOutput(t)+` = ${this.input.associatedVariableName};\n`;const a=this.iterationsInput.isConnected?`${o}(${this.iterationsInput.associatedVariableName})`:this.iterations;return e.compilationString+=`for (${s} ${r} = 0; ${r} < ${a}; ${r}++){\n`,e.compilationString+=`${e._declareOutput(i)} = ${n}(${r});\n`,this}_postBuildBlock(e){return super._postBuildBlock(e),e.compilationString+="}\n",this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.iterations = ${this.iterations};\n`}serialize(){const e=super.serialize();return e.iterations=this.iterations,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.iterations=e.iterations}}(0,je.Cg)([t_("Iterations",2,void 0,{embedded:!0})],sy.prototype,"iterations",void 0),(0,X.Y5)("BABYLON.LoopBlock",sy);class ny extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("loopID",Og.Object,!1,void 0,new cS("loopID",this,0,sy,"LoopBlock")),this.registerOutput("value",Og.AutoDetect),this._outputs[0]._linkedConnectionSource=this._inputs[0]}getClassName(){return"StorageReadBlock"}get loopID(){return this._inputs[0]}get value(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.value;if(!this.loopID.isConnected)return this;const i=this.loopID.connectedPoint.ownerBlock;return e.compilationString+=e._declareOutput(t)+` = ${i.output.associatedVariableName};\n`,this}}(0,X.Y5)("BABYLON.StorageReadBlock",ny);class oy extends Gg{constructor(e){super(e,Dg.Neutral),this.registerInput("loopID",Og.Object,!1,void 0,new cS("loopID",this,0,sy,"LoopBlock")),this.registerInput("value",Og.AutoDetect),this._linkConnectionTypes(0,1)}getClassName(){return"StorageWriteBlock"}get loopID(){return this._inputs[0]}get value(){return this._inputs[1]}isConnectedInFragmentShader(){return!!this.loopID.isConnected&&this.loopID.connectedPoint.ownerBlock.output.isConnectedInFragmentShader}_buildBlock(e){super._buildBlock(e);const t=this.value;if(!this.loopID.isConnected)return this;const i=this.loopID.connectedPoint.ownerBlock;return e.compilationString+=`${i.output.associatedVariableName} = ${t.associatedVariableName};\n`,this}}(0,X.Y5)("BABYLON.StorageWriteBlock",oy);const ay="gaussianSplattingVertexDeclaration",ly="attribute position: vec2f;\n";Cs.l.IncludesShadersStoreWGSL[ay]=ly;const hy={name:ay,shader:ly};var cy,uy=i(93784);class dy{optimize(e,t){}}class fy{constructor(){this.mm=new Map}get(e,t){const i=this.mm.get(e);if(void 0!==i)return i.get(t)}set(e,t,i){let r=this.mm.get(e);void 0===r&&this.mm.set(e,r=new Map),r.set(t,i)}}class py{get standalone(){return this._options?.standalone??!1}get baseMaterial(){return this._baseMaterial}get doNotInjectCode(){return this._options?.doNotInjectCode??!1}constructor(e,t,i){this._baseMaterial=e,this._scene=t??he.q.LastCreatedScene,this._options=i,this._subMeshToEffect=new Map,this._subMeshToDepthWrapper=new fy,this._meshes=new Map,this._onEffectCreatedObserver=this._baseMaterial.onEffectCreatedObservable.add((e=>{const t=e.subMesh?.getMesh();t&&!this._meshes.has(t)&&this._meshes.set(t,t.onDisposeObservable.add((e=>{const t=this._subMeshToEffect.keys();for(let i=t.next();!0!==i.done;i=t.next()){const t=i.value;t?.getMesh()===e&&(this._subMeshToEffect.delete(t),this._deleteDepthWrapperEffect(t))}}))),this._subMeshToEffect.get(e.subMesh)?.[0]!==e.effect&&(this._subMeshToEffect.set(e.subMesh,[e.effect,this._scene.getEngine().currentRenderPassId]),this._deleteDepthWrapperEffect(e.subMesh))}))}_deleteDepthWrapperEffect(e){const t=this._subMeshToDepthWrapper.mm.get(e);t&&(t.forEach((e=>{e.mainDrawWrapper.effect?.dispose()})),this._subMeshToDepthWrapper.mm.delete(e))}getEffect(e,t,i){const r=this._subMeshToDepthWrapper.mm.get(e)?.get(t);if(!r)return null;let s=r.drawWrapper[i];return s||(s=r.drawWrapper[i]=new gt.E(this._scene.getEngine()),s.setEffect(r.mainDrawWrapper.effect,r.mainDrawWrapper.defines)),s}isReadyForSubMesh(e,t,i,r,s){return!(this.standalone&&!this._baseMaterial.isReadyForSubMesh(e.getMesh(),e,r))&&(this._makeEffect(e,t,i,s)?.isReady()??!1)}dispose(){this._baseMaterial.onEffectCreatedObservable.remove(this._onEffectCreatedObserver),this._onEffectCreatedObserver=null;const e=this._meshes.entries();for(let t=e.next();!0!==t.done;t=e.next()){const[e,i]=t.value;e.onDisposeObservable.remove(i)}}_makeEffect(e,t,i,r){const s=this._scene.getEngine(),n=this._subMeshToEffect.get(e);if(!n)return null;const[o,a]=n;let l=this._subMeshToDepthWrapper.get(e,i);if(!l){const t=new gt.E(s);t.defines=e._getDrawWrapper(a)?.defines??null,l={drawWrapper:[],mainDrawWrapper:t,depthDefines:"",token:(0,Au.z)()},l.drawWrapper[r]=t,this._subMeshToDepthWrapper.set(e,i,l)}const h=t.join("\n");if(l.mainDrawWrapper.effect&&h===l.depthDefines)return l.mainDrawWrapper.effect;l.depthDefines=h;const c=o.getUniformNames().slice();let u=o.vertexSourceCodeBeforeMigration,d=o.fragmentSourceCodeBeforeMigration;if(!this.doNotInjectCode){const e=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",t=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",i=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",r="#include",s="#include";u=0===o.shaderLanguage?u.replace(/void\s+?main/g,`\n${s}\nvoid main`):u.replace(/@vertex/g,`\n${s}\n@vertex`),u=u.replace(/#define SHADOWDEPTH_NORMALBIAS|#define CUSTOM_VERTEX_UPDATE_WORLDPOS/g,e),u=-1!==u.indexOf("#define SHADOWDEPTH_METRIC")?u.replace(/#define SHADOWDEPTH_METRIC/g,t):u.replace(/}\s*$/g,t+"\n}"),u=u.replace(/#define SHADER_NAME.*?\n|out vec4 glFragColor;\n/g,"");const n=d.indexOf("#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW")>=0||d.indexOf("#define CUSTOM_FRAGMENT_BEFORE_FOG")>=0,a=-1!==d.indexOf("#define SHADOWDEPTH_FRAGMENT");let l="";n?d=d.replace(/#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW|#define CUSTOM_FRAGMENT_BEFORE_FOG/g,i):l=i+"\n",d=d.replace(/void\s+?main/g,Cl.M.IncludesShadersStore.shadowMapFragmentExtraDeclaration+"\nvoid main"),a?d=d.replace(/#define SHADOWDEPTH_FRAGMENT/g,r):l+=r+"\n",l&&(d=d.replace(/}\s*$/g,l+"}")),c.push("biasAndScaleSM","depthValuesSM","lightDataSM","softTransparentShadowSM")}l.mainDrawWrapper.effect=s.createEffect({vertexSource:u,fragmentSource:d,vertexToken:l.token,fragmentToken:l.token},{attributes:o.getAttributesNames(),uniformsNames:c,uniformBuffersNames:o.getUniformBuffersNames(),samplers:o.getSamplers(),defines:h+"\n"+o.defines.replace("#define SHADOWS","").replace(/#define SHADOW\d/g,""),indexParameters:o.getIndexParameters(),shaderLanguage:o.shaderLanguage},s);for(let e=0;e0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof W.Pq){const t=[];return e.forEach((e=>{t.push(e.flatMap((e=>[e.x,e.y,e.z])))})),t}if(e instanceof Float32Array){if(t?.floatArrayStride){const i=[],r=3*t.floatArrayStride;for(let t=0;t{t.push(Array.from(e))})),t}return[]}static OmitZeroLengthPredicate(e,t,i){const r=[];return t.subtract(e).lengthSquared()>0&&r.push([e,t]),i.subtract(t).lengthSquared()>0&&r.push([t,i]),e.subtract(i).lengthSquared()>0&&r.push([i,e]),0===r.length?null:r}static OmitDuplicatesPredicate(e,t,i,r){const s=[];return Ey._SearchInPoints(e,t,r)||s.push([e,t]),Ey._SearchInPoints(t,i,r)||s.push([t,i]),Ey._SearchInPoints(i,e,r)||s.push([i,e]),0===s.length?null:s}static _SearchInPoints(e,t,i){for(const r of i)for(let i=0;i{const s=e.getVerticesData(st.R.PositionKind),n=e.getIndices();if(s&&n)for(let o=0,a=0;o[e.x,e.y,e.z]))}static GetPointsCountInfo(e){const t=new Array(e.length);let i=0;for(let r=e.length;r--;)t[r]=e[r].length/3,i+=t[r];return{total:i,counts:t}}static GetLineLength(e){if(0===e.length)return 0;let t;t="number"==typeof e[0]?Ey.ToVector3Array(e):e;const i=W.AA.Vector3[0];let r=0;for(let e=0;e{e.length>t?Ey.SegmentizeSegmentByCount(e.point1,e.point2,Math.ceil(e.length/t)).forEach((e=>{r.push(e)})):(r.push(e.point1),r.push(e.point2))})),r}static SegmentizeLineBySegmentCount(e,t){const i="number"==typeof e[0]?Ey.ToVector3Array(e):e,r=Ey.GetLineLength(i)/t;return Ey.SegmentizeLineBySegmentLength(i,r)}static GetLineSegments(e){const t=[];for(let i=0;ie.length));return{min:t[0].length,max:t[t.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,r=!1){const s=t*i;let n=0,o=0;const a=e.length;for(let t=0;t[e.x,e.y,e.z]))}static GetArrowCap(e,t,i,r,s,n=0,o=0){return{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[r,s,n,o]}}static GetPointsFromText(e,t,i,r,s=0,n=!0){const o=[],a=vl(e,t,i,r);for(const e of a){for(const t of e.paths){const e=[],i=t.getPoints();for(const t of i)e.push(t.x,t.y,s);o.push(e)}if(n)for(const t of e.holes){const e=[],i=t.getPoints();for(const t of i)e.push(t.x,t.y,s);o.push(e)}}return o}static Color3toRGBAUint8(e){const t=new Uint8Array(4*e.length);for(let i=0,r=0;is?s:t.length,o=Math.ceil(t.length/s);o>1&&(t=[...t,...Array(n*o-t.length).fill(t[0])]);const a=Ey.Color3toRGBAUint8(t),l=new xi(a,n,o,an.TEXTUREFORMAT_RGBA,r,!1,!0,i);return l.name=e,l}static PrepareEmptyColorsTexture(e){if(!yy.EmptyColorsTexture){const t=new Uint8Array(4);yy.EmptyColorsTexture=new xi(t,1,1,an.TEXTUREFORMAT_RGBA,e,!1,!1,xi.NEAREST_NEAREST),yy.EmptyColorsTexture.name="grlEmptyColorsTexture"}return yy.EmptyColorsTexture}static DisposeEmptyColorsTexture(){yy.EmptyColorsTexture?.dispose(),yy.EmptyColorsTexture=null}static BooleanToNumber(e){return e?1:0}}class Py extends xn{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 Ay extends Dn{constructor(e,t,i){i=i||{color:yy.DEFAULT_COLOR};const r=new Py;r.GREASED_LINE_HAS_COLOR=!!i.color&&!i.useColors,r.GREASED_LINE_SIZE_ATTENUATION=i.sizeAttenuation??!1,r.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=1===i.colorDistributionType,r.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=(t??e.getScene()).useRightHandedSystem,r.GREASED_LINE_CAMERA_FACING=i.cameraFacing??!0,super(e,Ay.GREASED_LINE_MATERIAL_NAME,200,r),this.colorsTexture=null,this._scene=t??e.getScene(),this._engine=this._scene.getEngine(),this._cameraFacing=i.cameraFacing??!0,this.visibility=i.visibility??1,this.useDash=i.useDash??!1,this.dashRatio=i.dashRatio??.5,this.dashOffset=i.dashOffset??0,this.width=i.width?i.width:i.sizeAttenuation?yy.DEFAULT_WIDTH_ATTENUATED:yy.DEFAULT_WIDTH,this._sizeAttenuation=i.sizeAttenuation??!1,this.colorMode=i.colorMode??0,this._color=i.color??null,this.useColors=i.useColors??!1,this._colorsDistributionType=i.colorDistributionType??0,this.colorsSampling=i.colorsSampling??xi.NEAREST_NEAREST,this._colors=i.colors??null,this.dashCount=i.dashCount??1,this.resolution=i.resolution??new W.I9(this._engine.getRenderWidth(),this._engine.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this._colors?this.colorsTexture=Ey.CreateColorsTexture(`${e.name}-colors-texture`,this._colors,this.colorsSampling,this._scene):(this._color=this._color??yy.DEFAULT_COLOR,Ey.PrepareEmptyColorsTexture(this._scene)),this._engine.onDisposeObservable.add((()=>{Ey.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?"\n uniform vec4 grl_aspect_resolution_lineWidth;\n uniform mat4 grl_projection;\n ":"",fragment:"\n uniform vec4 grl_dashOptions;\n uniform vec2 grl_textureSize;\n uniform vec4 grl_colorMode_visibility_colorsWidth_useColors;\n uniform vec3 grl_singleColor;\n "}}get isEnabled(){return!0}bindForSubMesh(e){if(this._cameraFacing){const t=this._scene.activeCamera;if(!t)throw Error("GreasedLinePluginMaterial requires an active camera.");{const i=t.getProjectionMatrix();e.updateMatrix("grl_projection",i)}const i=W.AA.Vector4[0];i.x=this._aspect,i.y=this._resolution.x,i.z=this._resolution.y,i.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",i)}const t=W.AA.Vector4[0];t.x=Ey.BooleanToNumber(this.useDash),t.y=this._dashArray,t.z=this.dashOffset,t.w=this.dashRatio,e.updateVector4("grl_dashOptions",t);const i=W.AA.Vector4[1];i.x=this.colorMode,i.y=this.visibility,i.z=this.colorsTexture?this.colorsTexture.getSize().width:0,i.w=Ey.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",i),this._color&&e.updateColor3("grl_singleColor",this._color);const r=this.colorsTexture??yy.EmptyColorsTexture;e.setTexture("grl_colors",r),e.updateFloat2("grl_textureSize",r?.getSize().width??1,r?.getSize().height??1)}prepareDefines(e,t,i){e.GREASED_LINE_HAS_COLOR=!!this.color&&!this.useColors,e.GREASED_LINE_SIZE_ATTENUATION=this._sizeAttenuation,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=1===this._colorsDistributionType,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing}getClassName(){return Ay.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){if("vertex"===e){const e={CUSTOM_VERTEX_DEFINITIONS:"\n attribute float grl_widths;\n attribute vec3 grl_offsets;\n attribute float grl_colorPointers;\n varying float grlCounters;\n varying float grlColorPointer;\n\n #ifdef GREASED_LINE_CAMERA_FACING\n attribute vec4 grl_previousAndSide;\n attribute vec4 grl_nextAndCounters;\n\n vec2 grlFix( vec4 i, float aspect ) {\n vec2 res = i.xy / i.w;\n res.x *= aspect;\n return res;\n }\n #else\n attribute vec3 grl_slopes;\n attribute float grl_counters;\n #endif\n ",CUSTOM_VERTEX_UPDATE_POSITION:"\n #ifdef GREASED_LINE_CAMERA_FACING\n vec3 grlPositionOffset = grl_offsets;\n positionUpdated += grlPositionOffset;\n #else\n positionUpdated = (positionUpdated + grl_offsets) + (grl_slopes * grl_widths);\n #endif\n ",CUSTOM_VERTEX_MAIN_END:"\n grlColorPointer = grl_colorPointers;\n\n #ifdef GREASED_LINE_CAMERA_FACING\n\n float grlAspect = grl_aspect_resolution_lineWidth.x;\n float grlBaseWidth = grl_aspect_resolution_lineWidth.w;\n\n\n vec3 grlPrevious = grl_previousAndSide.xyz;\n float grlSide = grl_previousAndSide.w;\n\n vec3 grlNext = grl_nextAndCounters.xyz;\n grlCounters = grl_nextAndCounters.w;\n\n mat4 grlMatrix = viewProjection * finalWorld;\n vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 );\n vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 );\n vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 );\n\n vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect );\n vec2 grlPrevP = grlFix( grlPrevPos, grlAspect );\n vec2 grlNextP = grlFix( grlNextPos, grlAspect );\n\n float grlWidth = grlBaseWidth * grl_widths;\n\n vec2 grlDir;\n if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP );\n else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP );\n else {\n vec2 grlDir1 = normalize( grlCurrentP - grlPrevP );\n vec2 grlDir2 = normalize( grlNextP - grlCurrentP );\n grlDir = normalize( grlDir1 + grlDir2 );\n }\n vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. );\n #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM\n grlNormal.xy *= -.5 * grlWidth;\n #else\n grlNormal.xy *= .5 * grlWidth;\n #endif\n\n grlNormal *= grl_projection;\n\n #ifdef GREASED_LINE_SIZE_ATTENUATION\n grlNormal.xy *= grlFinalPosition.w;\n grlNormal.xy /= ( vec4( grl_aspect_resolution_lineWidth.yz, 0., 1. ) * grl_projection ).xy;\n #endif\n\n grlFinalPosition.xy += grlNormal.xy * grlSide;\n gl_Position = grlFinalPosition;\n\n vPositionW = vec3(grlFinalPosition);\n #else\n grlCounters = grl_counters;\n #endif\n "};return this._cameraFacing&&(e["!gl_Position\\=viewProjection\\*worldPos;"]="//"),e}return"fragment"===e?{CUSTOM_FRAGMENT_DEFINITIONS:"\n varying float grlCounters;\n varying float grlColorPointer;\n uniform sampler2D grl_colors;\n ",CUSTOM_FRAGMENT_MAIN_END:"\n float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x;\n float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y;\n float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z;\n float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w;\n\n float grlUseDash = grl_dashOptions.x;\n float grlDashArray = grl_dashOptions.y;\n float grlDashOffset = grl_dashOptions.z;\n float grlDashRatio = grl_dashOptions.w;\n\n gl_FragColor.a *= step(grlCounters, grlVisibility);\n if( gl_FragColor.a == 0. ) discard;\n\n if(grlUseDash == 1.){\n gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio));\n if (gl_FragColor.a == 0.) discard;\n }\n\n #ifdef GREASED_LINE_HAS_COLOR\n if (grlColorMode == 0.) {\n gl_FragColor.rgb = grl_singleColor;\n } else if (grlColorMode == 1.) {\n gl_FragColor.rgb += grl_singleColor;\n } else if (grlColorMode == 2.) {\n gl_FragColor.rgb *= grl_singleColor;\n }\n #else\n if (grlUseColors == 1.) {\n #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE\n vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.);\n #else\n vec2 lookup = vec2(fract(grlColorPointer / grl_textureSize.x), 1.0 - floor(grlColorPointer / grl_textureSize.x) / max(grl_textureSize.y - 1.0, 1.0));\n vec4 grlColor = texture2D(grl_colors, lookup, 0.0);\n #endif\n if (grlColorMode == 0.) {\n gl_FragColor = grlColor;\n } else if (grlColorMode == 1.) {\n gl_FragColor += grlColor;\n } else if (grlColorMode == 2.) {\n gl_FragColor *= grlColor;\n }\n }\n #endif\n\n "}:null}dispose(){this.colorsTexture?.dispose(),super.dispose()}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){const r=this._colors?.length??0;if(this._colors=e,null!==e&&0!==e.length){if(!t||i)if(this.colorsTexture&&r===e.length&&!i){const t=Ey.Color3toRGBAUint8(e);this.colorsTexture.update(t)}else this.colorsTexture?.dispose(),this.colorsTexture=Ey.CreateColorsTexture(`${this._material.name}-colors-texture`,e,this.colorsSampling,this._scene)}else this.colorsTexture?.dispose()}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){null===this._color&&null!==e||null!==this._color&&null===e?(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){super.parse(e,t,i);const r=e.greasedLineMaterialOptions;this.colorsTexture?.dispose(),r.color&&this.setColor(r.color,!0),r.colorDistributionType&&(this.colorsDistributionType=r.colorDistributionType),r.colors&&(this.colors=r.colors),r.colorsSampling&&(this.colorsSampling=r.colorsSampling),r.colorMode&&(this.colorMode=r.colorMode),r.useColors&&(this.useColors=r.useColors),r.visibility&&(this.visibility=r.visibility),r.useDash&&(this.useDash=r.useDash),r.dashCount&&(this.dashCount=r.dashCount),r.dashRatio&&(this.dashRatio=r.dashRatio),r.dashOffset&&(this.dashOffset=r.dashOffset),r.width&&(this.width=r.width),r.sizeAttenuation&&(this.sizeAttenuation=r.sizeAttenuation),r.resolution&&(this.resolution=r.resolution),this.colors?this.colorsTexture=Ey.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):Ey.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){const t=e;t.colorsTexture?.dispose(),this._colors&&(t.colorsTexture=Ey.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()}}Ay.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial",(0,X.Y5)(`BABYLON.${Ay.GREASED_LINE_MATERIAL_NAME}`,Ay);Cs.l.ShadersStore.greasedLinePixelShader="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;}\nif (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==COLOR_DISTRIBUTION_TYPE_LINE) { \ntextureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);}\nif (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;}}}\n",i(56865),i(18411);Cs.l.ShadersStore.greasedLineVertexShader="precision highp float;\n#include\nattribute 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;\n#ifdef GREASED_LINE_CAMERA_FACING\nattribute 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;}\n#else\nattribute vec3 grl_slopes;attribute float grl_counters;\n#endif\nvoid main() {\n#include\ngrlColorPointer=grl_colorPointers;mat4 grlMatrix=viewProjection*finalWorld ;\n#ifdef GREASED_LINE_CAMERA_FACING\nfloat 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 );}\nvec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. );\n#ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM\ngrlNormal.xy*=-.5*grlWidth;\n#else\ngrlNormal.xy*=.5*grlWidth;\n#endif\ngrlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;}\ngrlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition;\n#else\ngrlCounters=grl_counters;vec4 grlFinalPosition=grlMatrix*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition;\n#endif\n}\n";class Ry extends xo{constructor(e,t,i){const r=["COLOR_DISTRIBUTION_TYPE_LINE 1.","COLOR_DISTRIBUTION_TYPE_SEGMENT 0.","COLOR_MODE_SET 0.","COLOR_MODE_ADD 1.","COLOR_MODE_MULTIPLY 2."],s=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&r.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(r.push("GREASED_LINE_CAMERA_FACING"),s.push("grl_previousAndSide","grl_nextAndCounters")):(s.push("grl_slopes"),s.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:s,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:r}),this._color=H.v9.White(),this._colorsDistributionType=0,this._colorsTexture=null,i=i||{color:yy.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?yy.DEFAULT_WIDTH_ATTENUATED:yy.DEFAULT_WIDTH,this.sizeAttenuation=i.sizeAttenuation??!1,this.color=i.color??H.v9.White(),this.useColors=i.useColors??!1,this.colorsDistributionType=i.colorDistributionType??0,this.colorsSampling=i.colorsSampling??xi.NEAREST_NEAREST,this.colorMode=i.colorMode??0,this._colors=i.colors??null,this._cameraFacing=i.cameraFacing??!0,this.resolution=i.resolution??new W.I9(n.getRenderWidth(),n.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this.colorsTexture=Ey.PrepareEmptyColorsTexture(t),this._colors&&this.useColors&&(this.colorsTexture=Ey.CreateColorsTexture(`${this.name}-colors-texture`,this._colors,this.colorsSampling,t)),n.onDisposeObservable.add((()=>{Ey.DisposeEmptyColorsTexture()}))}dispose(){this._colorsTexture?.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new W.I9(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){const r=this._colors?.length??0;if(this._colors=e,null!==e&&0!==e.length){if(!t||i)if(this._colorsTexture&&r===e.length&&!i){const t=Ey.Color3toRGBAUint8(e);this._colorsTexture.update(t)}else this._colorsTexture?.dispose(),this.colorsTexture=Ey.CreateColorsTexture(`${this.name}-colors-texture`,e,this.colorsSampling,this.getScene())}else this._colorsTexture?.dispose()}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",Ey.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",Ey.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",Ey.BooleanToNumber(e))}get color(){return this._color}set color(e){this.setColor(e)}setColor(e){e=e??yy.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){const r=e.greasedLineMaterialOptions;this._colorsTexture?.dispose(),r.color&&(this.color=r.color),r.colorDistributionType&&(this.colorsDistributionType=r.colorDistributionType),r.colorsSampling&&(this.colorsSampling=r.colorsSampling),r.colorMode&&(this.colorMode=r.colorMode),r.useColors&&(this.useColors=r.useColors),r.visibility&&(this.visibility=r.visibility),r.useDash&&(this.useDash=r.useDash),r.dashCount&&(this.dashCount=r.dashCount),r.dashRatio&&(this.dashRatio=r.dashRatio),r.dashOffset&&(this.dashOffset=r.dashOffset),r.width&&(this.width=r.width),r.sizeAttenuation&&(this.sizeAttenuation=r.sizeAttenuation),r.resolution&&(this.resolution=r.resolution),r.colors?this.colorsTexture=Ey.CreateColorsTexture(`${this.name}-colors-texture`,r.colors,this.colorsSampling,this.getScene()):this.colorsTexture=Ey.PrepareEmptyColorsTexture(t),this._cameraFacing=r.cameraFacing??!0,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}}var Iy,My,Oy;!function(e){e[e.MATERIAL_TYPE_STANDARD=0]="MATERIAL_TYPE_STANDARD",e[e.MATERIAL_TYPE_PBR=1]="MATERIAL_TYPE_PBR",e[e.MATERIAL_TYPE_SIMPLE=2]="MATERIAL_TYPE_SIMPLE"}(Iy||(Iy={})),function(e){e[e.COLOR_MODE_SET=0]="COLOR_MODE_SET",e[e.COLOR_MODE_ADD=1]="COLOR_MODE_ADD",e[e.COLOR_MODE_MULTIPLY=2]="COLOR_MODE_MULTIPLY"}(My||(My={})),function(e){e[e.COLOR_DISTRIBUTION_TYPE_SEGMENT=0]="COLOR_DISTRIBUTION_TYPE_SEGMENT",e[e.COLOR_DISTRIBUTION_TYPE_LINE=1]="COLOR_DISTRIBUTION_TYPE_LINE"}(Oy||(Oy={}));const Dy=[new hc.v9(.98,.26,.38),new hc.v9(.47,.75,.3),new hc.v9(0,.26,.77),new hc.v9(.97,.6,.76),new hc.v9(.19,.63,.78),new hc.v9(.98,.8,.6),new hc.v9(.65,.43,.15),new hc.v9(.15,.47,.22),new hc.v9(.67,.71,.86),new hc.v9(.09,.46,.56),new hc.v9(.8,.98,.02),new hc.v9(.39,.29,.13),new hc.v9(.53,.63,.06),new hc.v9(.95,.96,.41),new hc.v9(1,.72,.94),new hc.v9(.63,.08,.31),new hc.v9(.66,.96,.95),new hc.v9(.22,.14,.19),new hc.v9(.14,.65,.59),new hc.v9(.93,1,.68),new hc.v9(.93,.14,.44),new hc.v9(.47,.86,.67),new hc.v9(.85,.07,.78),new hc.v9(.53,.64,.98),new hc.v9(.43,.37,.56),new hc.v9(.71,.65,.25),new hc.v9(.66,.19,.01),new hc.v9(.94,.53,.12),new hc.v9(.41,.44,.44),new hc.v9(.24,.71,.96),new hc.v9(.57,.28,.56),new hc.v9(.44,.98,.42)];var wy;!function(e){e[e.NONE=0]="NONE",e[e.TRIANGLES=1]="TRIANGLES",e[e.VERTICES=2]="VERTICES",e[e.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",e[e.UV0=4]="UV0",e[e.UV1=5]="UV1",e[e.VERTEXCOLORS=6]="VERTEXCOLORS",e[e.MATERIALIDS=7]="MATERIALIDS"}(wy||(wy={}));class Ny extends xn{constructor(){super(...arguments),this.DBG_MODE=0,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}}class Fy extends Dn{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}isCompatible(e){switch(e){case 0:case 1:return!0;default:return!1}}constructor(e,t={}){const i=new Ny;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 hc.v9(1,1,1),this.shadedSpecularColor=t.shadedSpecularColor??new hc.v9(.8,.8,.8),this.shadedSpecularPower=t.shadedSpecularPower??10,this.wireframeThickness=t.wireframeThickness??.7,this.wireframeTrianglesColor=t.wireframeTrianglesColor??new hc.v9(0,0,0),this.wireframeVerticesColor=t.wireframeVerticesColor??new hc.v9(.8,.8,.8),this.vertexColor=t.vertexColor??new hc.v9(0,0,0),this.vertexRadius=t.vertexRadius??1.2,this.uvScale=t.uvScale??20,this.uvPrimaryColor=t.uvPrimaryColor??new hc.v9(1,1,1),this.uvSecondaryColor=t.uvSecondaryColor??new hc.v9(.5,.5,.5),this._materialColor=Fy.MaterialColors[Fy._PluginCount++%Fy.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&&1==this._material.getScene().getEngine().version)return Z.V.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),void(this._isEnabled=!1);this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){2!=this._mode&&1!=this._mode&&3!=this._mode||i.isVerticesDataPresent("dbg_initialPass")||Z.V.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.",1),e.DBG_MODE=this._mode,e.DBG_MULTIPLY=this._multiply,e.DBG_ENABLED=this._isEnabled}getAttributes(e){e.push("dbg_initialPass")}getUniforms(e=0){return{ubo:[{name:"dbg_shadedDiffuseColor",size:3,type:"vec3"},{name:"dbg_shadedSpecularColorPower",size:4,type:"vec4"},{name:"dbg_thicknessRadiusScale",size:3,type:"vec3"},{name:"dbg_wireframeTrianglesColor",size:3,type:"vec3"},{name:"dbg_wireframeVerticesColor",size:3,type:"vec3"},{name:"dbg_vertexColor",size:3,type:"vec3"},{name:"dbg_uvPrimaryColor",size:3,type:"vec3"},{name:"dbg_uvSecondaryColor",size:3,type:"vec3"},{name:"dbg_materialColor",size:3,type:"vec3"}],fragment:0===e?"#if defined(DBG_ENABLED)\nuniform vec3 dbg_shadedDiffuseColor;\nuniform vec4 dbg_shadedSpecularColorPower;\nuniform vec3 dbg_thicknessRadiusScale;\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n uniform vec3 dbg_vertexColor;\n#endif\n\n#if DBG_MODE == 1\n uniform vec3 dbg_wireframeTrianglesColor;\n#elif DBG_MODE == 3\n uniform vec3 dbg_wireframeVerticesColor;\n#elif DBG_MODE == 4 || DBG_MODE == 5\n uniform vec3 dbg_uvPrimaryColor;\n uniform vec3 dbg_uvSecondaryColor;\n#elif DBG_MODE == 7\n uniform vec3 dbg_materialColor;\n#endif\n#endif":"#if defined(DBG_ENABLED)\nuniform dbg_shadedDiffuseColor: vec3f;\nuniform dbg_shadedSpecularColorPower: vec4f;\nuniform dbg_thicknessRadiusScale: vec3f;\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n uniform dbg_vertexColor: vec3f;\n#endif\n\n#if DBG_MODE == 1\n uniform dbg_wireframeTrianglesColor: vec3f;\n#elif DBG_MODE == 3\n uniform dbg_wireframeVerticesColor: vec3f;\n#elif DBG_MODE == 4 || DBG_MODE == 5\n uniform dbg_uvPrimaryColor: vec3f;\n uniform dbg_uvSecondaryColor: vec3f;\n#elif DBG_MODE == 7\n uniform dbg_materialColor: vec3f;\n#endif\n#endif"}}bindForSubMesh(e){this._isEnabled&&(e.updateFloat3("dbg_shadedDiffuseColor",this.shadedDiffuseColor.r,this.shadedDiffuseColor.g,this.shadedDiffuseColor.b),e.updateFloat4("dbg_shadedSpecularColorPower",this.shadedSpecularColor.r,this.shadedSpecularColor.g,this.shadedSpecularColor.b,this.shadedSpecularPower),e.updateFloat3("dbg_thicknessRadiusScale",this.wireframeThickness,this.vertexRadius,this.uvScale),e.updateColor3("dbg_wireframeTrianglesColor",this.wireframeTrianglesColor),e.updateColor3("dbg_wireframeVerticesColor",this.wireframeVerticesColor),e.updateColor3("dbg_vertexColor",this.vertexColor),e.updateColor3("dbg_uvPrimaryColor",this.uvPrimaryColor),e.updateColor3("dbg_uvSecondaryColor",this.uvSecondaryColor),e.updateColor3("dbg_materialColor",this._materialColor))}getCustomCode(e,t=0){return 1===t?"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:"#if defined(DBG_ENABLED)\nattribute dbg_initialPass: f32;\nvarying dbg_vBarycentric: vec3f;\nvarying dbg_vVertexWorldPos: vec3f;\nvarying dbg_vPass: f32;\n#endif",CUSTOM_VERTEX_MAIN_END:"#if defined(DBG_ENABLED)\nvar dbg_vertexIndex = f32(input.vertexIndex) % 3.;\nif (dbg_vertexIndex == 0.0) { \n vertexOutputs.dbg_vBarycentric = vec3f(1.,0.,0.); \n}\nelse if (dbg_vertexIndex == 1.0) { \n vertexOutputs.dbg_vBarycentric = vec3f(0.,1.,0.); \n}\nelse { \n vertexOutputs.dbg_vBarycentric = vec3f(0.,0.,1.); \n}\n\nvertexOutputs.dbg_vVertexWorldPos = vertexOutputs.vPositionW;\nvertexOutputs.dbg_vPass = input.dbg_initialPass;\n#endif"}:{CUSTOM_FRAGMENT_DEFINITIONS:"#if defined(DBG_ENABLED)\nvarying dbg_vBarycentric: vec3f;\nvarying dbg_vVertexWorldPos: vec3f;\nvarying dbg_vPass: f32;\n\n#if !defined(DBG_MULTIPLY)\n fn dbg_applyShading(color: vec3f) -> vec3f {\n var N = fragmentInputs.vNormalW.xyz;\n var L = normalize(scene.vEyePosition.xyz - fragmentInputs.vPositionW.xyz);\n var H = normalize(L + L);\n var LdotN = clamp(dot(L,N), 0., 1.);\n var HdotN = clamp(dot(H,N), 0., 1.);\n var specTerm = pow(HdotN, uniforms.dbg_shadedSpecularColorPower.w);\n var result = color * (LdotN / PI);\n result += uniforms.dbg_shadedSpecularColorPower.rgb * (specTerm / PI);\n return result;\n }\n#endif\n\n#if DBG_MODE == 1 || DBG_MODE == 3\n fn dbg_edgeFactor() -> f32 {\n var d = fwidth(fragmentInputs.dbg_vBarycentric);\n var a3 = smoothstep(vec3f(0.), d * uniforms.dbg_thicknessRadiusScale.x, fragmentInputs.dbg_vBarycentric);\n return min(min(a3.x, a3.y), a3.z);\n }\n#endif\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n fn dbg_cornerFactor() -> f32 {\n var worldPos = fragmentInputs.vPositionW;\n float dist = length(worldPos - fragmentInputs.dbg_vVertexWorldPos);\n float camDist = length(worldPos - scene.vEyePosition.xyz);\n float d = sqrt(camDist) * .001;\n return smoothstep((uniforms.dbg_thicknessRadiusScale.y * d), ((uniforms.dbg_thicknessRadiusScale.y * 1.01) * d), dist);\n }\n#endif\n\n#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2))\n fn dbg_checkerboardFactor(uv: vec2f) -> f32 {\n var f = fract(uv * uniforms.dbg_thicknessRadiusScale.z);\n f -= .5;\n return (f.x * f.y) > 0. ? 1. : 0.;\n }\n#endif\n#endif",CUSTOM_FRAGMENT_MAIN_END:"#if defined(DBG_ENABLED)\nvar dbg_color = vec3f(1.);\n#if DBG_MODE == 1\n dbg_color = mix(uniforms.dbg_wireframeTrianglesColor, vec3f(1.), dbg_edgeFactor());\n#elif DBG_MODE == 2 || DBG_MODE == 3\n var dbg_cornerFactor = dbg_cornerFactor();\n if (fragmentInputs.dbg_vPass == 0. && dbg_cornerFactor == 1.) discard;\n dbg_color = mix(uniforms.dbg_vertexColor, vec3(1.), dbg_cornerFactor);\n #if DBG_MODE == 3\n dbg_color *= mix(uniforms.dbg_wireframeVerticesColor, vec3f(1.), dbg_edgeFactor());\n #endif\n#elif DBG_MODE == 4 && defined(MAINUV1)\n dbg_color = mix(uniforms.dbg_uvPrimaryColor, uniforms.dbg_uvSecondaryColor, dbg_checkerboardFactor(fragmentInputs.vMainUV1));\n#elif DBG_MODE == 5 && defined(MAINUV2)\n dbg_color = mix(uniforms.dbg_uvPrimaryColor, uniforms.dbg_uvSecondaryColor, dbg_checkerboardFactor(fragmentInputs.vMainUV2));\n#elif DBG_MODE == 6 && defined(VERTEXCOLOR)\n dbg_color = fragmentInputs.vColor.rgb;\n#elif DBG_MODE == 7\n dbg_color = uniforms.dbg_materialColor;\n#endif\n\n#if defined(DBG_MULTIPLY)\n fragmentOutputs.color *= vec4f(dbg_color, 1.);\n#else\n #if DBG_MODE != 6\n fragmentOutputs.color = vec4f(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.);\n #else\n fragmentOutputs.color = vec4f(dbg_color, 1.);\n #endif\n#endif\n#endif"}:"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:"#if defined(DBG_ENABLED)\nattribute float dbg_initialPass;\nvarying vec3 dbg_vBarycentric;\nflat varying vec3 dbg_vVertexWorldPos;\nflat varying float dbg_vPass;\n#endif",CUSTOM_VERTEX_MAIN_END:"#if defined(DBG_ENABLED)\nfloat dbg_vertexIndex = mod(float(gl_VertexID), 3.);\nif (dbg_vertexIndex == 0.0) { \n dbg_vBarycentric = vec3(1.,0.,0.); \n}\nelse if (dbg_vertexIndex == 1.0) { \n dbg_vBarycentric = vec3(0.,1.,0.); \n}\nelse { \n dbg_vBarycentric = vec3(0.,0.,1.); \n}\n\ndbg_vVertexWorldPos = vPositionW;\ndbg_vPass = dbg_initialPass;\n#endif"}:{CUSTOM_FRAGMENT_DEFINITIONS:"#if defined(DBG_ENABLED)\nvarying vec3 dbg_vBarycentric;\nflat varying vec3 dbg_vVertexWorldPos;\nflat varying float dbg_vPass;\n\n#if !defined(DBG_MULTIPLY)\n vec3 dbg_applyShading(vec3 color) {\n vec3 N = vNormalW.xyz;\n vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz);\n vec3 H = normalize(L + L);\n float LdotN = clamp(dot(L,N), 0., 1.);\n float HdotN = clamp(dot(H,N), 0., 1.);\n float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w);\n color *= (LdotN / PI);\n color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI);\n return color;\n }\n#endif\n\n#if DBG_MODE == 1 || DBG_MODE == 3\n float dbg_edgeFactor() {\n vec3 d = fwidth(dbg_vBarycentric);\n vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric);\n return min(min(a3.x, a3.y), a3.z);\n }\n#endif\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n float dbg_cornerFactor() {\n vec3 worldPos = vPositionW;\n float dist = length(worldPos - dbg_vVertexWorldPos);\n float camDist = length(worldPos - vEyePosition.xyz);\n float d = sqrt(camDist) * .001;\n return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist);\n }\n#endif\n\n#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2))\n float dbg_checkerboardFactor(vec2 uv) {\n vec2 f = fract(uv * dbg_thicknessRadiusScale.z);\n f -= .5;\n return (f.x * f.y) > 0. ? 1. : 0.;\n }\n#endif\n#endif",CUSTOM_FRAGMENT_MAIN_END:"#if defined(DBG_ENABLED)\nvec3 dbg_color = vec3(1.);\n#if DBG_MODE == 1\n dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor());\n#elif DBG_MODE == 2 || DBG_MODE == 3\n float dbg_cornerFactor = dbg_cornerFactor();\n if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard;\n dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor);\n #if DBG_MODE == 3\n dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor());\n #endif\n#elif DBG_MODE == 4 && defined(MAINUV1)\n dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1));\n#elif DBG_MODE == 5 && defined(MAINUV2)\n dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2));\n#elif DBG_MODE == 6 && defined(VERTEXCOLOR)\n dbg_color = vColor.rgb;\n#elif DBG_MODE == 7\n dbg_color = dbg_materialColor;\n#endif\n\n#if defined(DBG_MULTIPLY)\n gl_FragColor *= vec4(dbg_color, 1.);\n#else\n #if DBG_MODE != 6\n gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.);\n #else\n gl_FragColor = vec4(dbg_color, 1.);\n #endif\n#endif\n#endif"}}static Reset(){this._PluginCount=0,this.MaterialColors=Dy}static PrepareMeshForTrianglesAndVerticesMode(e,t=!1){let i=()=>{};if(0==e.getTotalIndices())return i;if(t){const t=e.getVerticesDataKinds(),r=e.getIndices(),s={};for(const i of t)s[i]=e.getVerticesData(i);i=function(){e.setIndices(r);for(const i of t){const t=e.getVertexBuffer(i).getStrideSize();e.setVerticesData(i,s[i],void 0,t)}e.removeVerticesData("dbg_initialPass")}}let r=Array.from(e.getIndices());const s=[];for(let e=0;eisNaN(e??Number.NaN))))return!1;if(e.morphTargetManager)for(let t=0;t<3;t++){let i=n[t];for(let n=0;n4,a=o?e.getVerticesData(st.R.MatricesIndicesExtraKind):null,l=o?e.getVerticesData(st.R.MatricesWeightsExtraKind):null,h=e.skeleton.getTransformMatrices(e),c=W.AA.Matrix[0],u=W.AA.Matrix[1];c.reset();const d=4*t;let f,p;for(f=0;f<4;f++)p=s[d+f],p>0&&(W.uq.FromFloat32ArrayToRefScaled(h,Math.floor(16*r[d+f]),p,u),c.addToSelf(u));if(a&&l)for(f=0;f<4;f++)p=l[d+f],p>0&&(W.uq.FromFloat32ArrayToRefScaled(h,Math.floor(16*a[d+f]),p,u),c.addToSelf(u));W.Pq.TransformCoordinatesFromFloatsToRef(n[0],n[1],n[2],c,i)}}return!0}function Ky(e,t,i,r){i.set(0,0,0);for(let r=0;r<3;r++){if(!Yy(e,t.pointIndex[r],W.AA.Vector3[r]))return!1;W.AA.Vector3[r].scaleAndAddToRef(t.barycentric[r],i)}if(W.Pq.TransformCoordinatesToRef(i,e.getWorldMatrix(),i),r){const t=W.AA.Vector3[0],i=W.AA.Vector3[1],s=W.AA.Vector3[2],n=W.AA.Vector3[3],o=W.AA.Vector3[4];n.copyFrom(i),n.subtractInPlace(t),o.copyFrom(s),o.subtractInPlace(t),n.normalize(),o.normalize(),W.Pq.CrossToRef(n,o,r),e.material&&e.material.sideOrientation===(e.getScene().useRightHandedSystem?0:1)&&r.scaleInPlace(-1),W.Pq.TransformNormalToRef(r,e.getWorldMatrix(),r),r.normalize()}return!0}var jy=i(28382);function $y(e,t,i,r,s){let n=null,o=null,a=null;try{let l;n=new e.Decoder,o=new e.DecoderBuffer,o.Init(t,t.byteLength);const h=n.GetEncodedGeometryType(o);switch(h){case e.TRIANGULAR_MESH:{const t=new e.Mesh;if(l=n.DecodeBufferToMesh(o,t),!l.ok()||0===t.ptr)throw new Error(l.error_msg());const i=3*t.num_faces(),s=4*i,h=e._malloc(s);try{n.GetTrianglesUInt32Array(t,s,h);const o=new Uint32Array(i);o.set(new Uint32Array(e.HEAPF32.buffer,h,i)),r(o)}finally{e._free(h)}a=t;break}case e.POINT_CLOUD:{const t=new e.PointCloud;if(l=n.DecodeBufferToPointCloud(o,t),!l.ok()||!t.ptr)throw new Error(l.error_msg());a=t;break}default:throw new Error(`Invalid geometry type ${h}`)}const c=a.num_points(),u=(t,i,r,n)=>{const o=n.data_type(),a=n.num_components(),l=n.normalized(),h=n.byte_stride(),u=n.byte_offset(),d={[e.DT_FLOAT32]:{typedArrayConstructor:Float32Array,heap:e.HEAPF32},[e.DT_INT8]:{typedArrayConstructor:Int8Array,heap:e.HEAP8},[e.DT_INT16]:{typedArrayConstructor:Int16Array,heap:e.HEAP16},[e.DT_INT32]:{typedArrayConstructor:Int32Array,heap:e.HEAP32},[e.DT_UINT8]:{typedArrayConstructor:Uint8Array,heap:e.HEAPU8},[e.DT_UINT16]:{typedArrayConstructor:Uint16Array,heap:e.HEAPU16},[e.DT_UINT32]:{typedArrayConstructor:Uint32Array,heap:e.HEAPU32}}[o];if(!d)throw new Error(`Invalid data type ${o}`);const f=c*a,p=f*d.typedArrayConstructor.BYTES_PER_ELEMENT,_=e._malloc(p);try{t.GetAttributeDataArrayForAllPoints(i,n,o,p,_);const e=new d.typedArrayConstructor(d.heap.buffer,_,f);s(r,e.slice(),a,u,h,l)}finally{e._free(_)}};if(i)for(const e in i){const t=i[e],r=n.GetAttributeByUniqueId(a,t);u(n,a,e,r)}else{const t={position:e.POSITION,normal:e.NORMAL,color:e.COLOR,uv:e.TEX_COORD};for(const e in t){const i=n.GetAttributeId(a,t[e]);if(-1!==i){const t=n.GetAttribute(a,i);u(n,a,e,t)}}}return c}finally{a&&e.destroy(a),o&&e.destroy(o),n&&e.destroy(n)}}function Qy(){let e;onmessage=t=>{const i=t.data;switch(i.id){case"init":{const t=i.decoder;t.url&&importScripts(t.url);const r=t.wasmBinary?{wasmBinary:t.wasmBinary}:{};e=DracoDecoderModule(r),postMessage({id:"initDone"});break}case"decodeMesh":if(!e)throw new Error("Draco decoder module is not available");e.then((e=>{const t=$y(e,i.dataView,i.attributes,(e=>{postMessage({id:"indices",data:e},[e.buffer])}),((e,t,i,r,s,n)=>{postMessage({id:"attribute",kind:e,data:t,size:i,byteOffset:r,byteStride:s,normalized:n},[t.buffer])}));postMessage({id:"decodeMeshDone",totalVertices:t})}))}}}class Zy{static get DecoderAvailable(){const e=Zy.Configuration.decoder;return!!(e.wasmUrl&&e.wasmBinaryUrl&&"object"==typeof WebAssembly||e.fallbackUrl)}static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static get Default(){return Zy._Default||(Zy._Default=new Zy),Zy._Default}static ResetDefault(e){Zy._Default&&(e||Zy._Default.dispose(),Zy._Default=null)}constructor(e=Zy.DefaultNumWorkers){const t=Zy.Configuration.decoder;if(t.workerPool||"object"==typeof e&&e.workerPool)this._workerPoolPromise=Promise.resolve(t.workerPool||e.workerPool);else{const i=t.wasmBinary||"object"==typeof e&&e.wasmBinary,r="number"==typeof e?e:e.numWorkers,s=r&&"function"==typeof Worker&&"function"==typeof URL,n=s||!s&&!t.jsModule,o=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:n?Ue.S0.GetBabylonScriptURL(t.wasmUrl,!0):"",wasmBinaryPromise:i?Promise.resolve(i):Ue.S0.LoadFileAsync(Ue.S0.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:n?Ue.S0.GetBabylonScriptURL(t.fallbackUrl):"",wasmBinaryPromise:Promise.resolve(void 0)};s?this._workerPoolPromise=o.wasmBinaryPromise.then((e=>{const t=`${$y}(${Qy})()`,i=URL.createObjectURL(new Blob([t],{type:"application/javascript"}));return new jy.h(r,(()=>function(e,t,i){return new Promise(((r,s)=>{const n=t=>{e.removeEventListener("error",n),e.removeEventListener("message",o),s(t)},o=t=>{"initDone"===t.data.id&&(e.removeEventListener("error",n),e.removeEventListener("message",o),r(e))};if(e.addEventListener("error",n),e.addEventListener("message",o),t){const r=t.slice(0);e.postMessage({id:"init",decoder:{url:i,wasmBinary:r}},[r])}else e.postMessage({id:"init",decoder:{url:i}})}))}(new Worker(i),e,o.url)))})):this._decoderModulePromise=o.wasmBinaryPromise.then((async e=>{if("undefined"==typeof DracoDecoderModule&&!t.jsModule){if(!o.url)throw new Error("Draco decoder module is not available");await Ue.S0.LoadBabylonScriptAsync(o.url)}return await(i=e,r=t.jsModule,new Promise((e=>{(r||DracoDecoderModule)({wasmBinary:i}).then((t=>{e({module:t})}))})));var i,r}))}}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then((e=>{e.dispose()})),delete this._workerPoolPromise,delete this._decoderModulePromise}async whenReadyAsync(){this._workerPoolPromise?await this._workerPoolPromise:this._decoderModulePromise&&await this._decoderModulePromise}decodeMeshToMeshDataAsync(e,t,i){const r=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength);if(this._workerPoolPromise)return this._workerPoolPromise.then((e=>new Promise(((s,n)=>{e.push(((e,o)=>{let a=null;const l=[],h=t=>{e.removeEventListener("error",h),e.removeEventListener("message",c),n(t),o()},c=t=>{const r=t.data;switch(r.id){case"decodeMeshDone":e.removeEventListener("error",h),e.removeEventListener("message",c),s({indices:a,attributes:l,totalVertices:r.totalVertices}),o();break;case"indices":a=r.data;break;case"attribute":l.push({kind:r.kind,data:r.data,size:r.size,byteOffset:r.byteOffset,byteStride:r.byteStride,normalized:(n=r.kind,u=r.normalized,i&&void 0!==i[n]?(u!==i[n]&&Z.V.Warn(`Normalized flag from Draco data (${u}) does not match normalized flag from glTF accessor (${i[n]}). Using flag from glTF accessor.`),i[n]):u)})}var n,u};e.addEventListener("error",h),e.addEventListener("message",c);const u=r.slice();e.postMessage({id:"decodeMesh",dataView:u,attributes:t},[u.buffer])}))}))));if(this._decoderModulePromise)return this._decoderModulePromise.then((e=>{let i=null;const s=[],n=$y(e.module,r,t,(e=>{i=e}),((e,t,i,r,n,o)=>{s.push({kind:e,data:t,size:i,byteOffset:r,byteStride:n,normalized:o})}));return{indices:i,attributes:s,totalVertices:n}}));throw new Error("Draco decoder module is not available")}async decodeMeshToGeometryAsync(e,t,i,r){const s=await this.decodeMeshToMeshDataAsync(i,r),n=new yt(e,t);s.indices&&n.setIndices(s.indices);for(const e of s.attributes)n.setVerticesBuffer(new st.R(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),s.totalVertices);return n}async _decodeMeshToGeometryForGltfAsync(e,t,i,r,s){const n=await this.decodeMeshToMeshDataAsync(i,r,s),o=new yt(e,t);n.indices&&o.setIndices(n.indices);for(const e of n.attributes)o.setVerticesBuffer(new st.R(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),n.totalVertices);return o}async decodeMeshAsync(e,t){const i=await this.decodeMeshToMeshDataAsync(e,t),r=new bt;i.indices&&(r.indices=i.indices);for(const e of i.attributes){const t=st.R.GetFloatData(e.data,e.size,st.R.GetDataType(e.data),e.byteOffset,e.byteStride,e.normalized,i.totalVertices);r.set(t,e.kind)}return r}}Zy.Configuration={decoder:{wasmUrl:`${Ue.S0._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${Ue.S0._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${Ue.S0._DefaultCdnUrl}/draco_decoder_gltf.js`}},Zy.DefaultNumWorkers=Zy.GetDefaultNumWorkers(),Zy._Default=null;class Jy{static get Default(){return Jy._Default||(Jy._Default=new Jy),Jy._Default}constructor(){const e=Jy.Configuration.decoder;this._decoderModulePromise=Ue.S0.LoadBabylonScriptAsync(e.url).then((()=>MeshoptDecoder.ready))}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,r,s){return this._decoderModulePromise.then((async()=>{MeshoptDecoder.useWorkers(1);const n=await MeshoptDecoder.decodeGltfBufferAsync(t,i,e,r,s);return MeshoptDecoder.useWorkers(0),n}))}}Jy.Configuration={decoder:{url:`${Ue.S0._DefaultCdnUrl}/meshopt_decoder.js`}},Jy._Default=null;let eE=0;class tE{constructor(e,t,i,r){this.pos=e,this.normal=t,this.uv=i,this.vertColor=r}clone(){return new tE(this.pos.clone(),this.normal.clone(),this.uv?.clone(),this.vertColor?.clone())}flip(){this.normal=this.normal.scale(-1)}interpolate(e,t){return new tE(W.Pq.Lerp(this.pos,e.pos,t),W.Pq.Lerp(this.normal,e.normal,t),this.uv&&e.uv?W.I9.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?H.ov.Lerp(this.vertColor,e.vertColor,t):void 0)}}class iE{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){const r=i.subtract(e),s=t.subtract(e);if(0===r.lengthSquared()||0===s.lengthSquared())return null;const n=W.Pq.Normalize(W.Pq.Cross(r,s));return new iE(n,W.Pq.Dot(n,e))}clone(){return new iE(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,r,s){let n=0;const o=[];let a,l;for(a=0;aiE.EPSILON?1:0;n|=t,o.push(t)}switch(n){case 0:(W.Pq.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:r.push(e);break;case 2:s.push(e);break;case 3:{const t=[],i=[];for(a=0;a=3&&(n=new rE(t,e.shared),n.plane&&r.push(n)),i.length>=3&&(n=new rE(i,e.shared),n.plane&&s.push(n));break}}}}iE.EPSILON=1e-5;class rE{constructor(e,t){this.vertices=e,this.shared=t,this.plane=iE.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=this.vertices.map((e=>e.clone()));return new rE(e,this.shared)}flip(){this.vertices.reverse().map((e=>{e.flip()})),this.plane.flip()}}class sE{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=new Array,e&&this.build(e)}clone(){const e=new sE;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((e=>e.clone())),e}invert(){for(let e=0;ee.clone())),e.copyTransformAttributes(this),e}union(e){const t=new sE(this.clone()._polygons),i=new sE(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),nE._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){const t=new sE(this._polygons),i=new sE(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 sE(this.clone()._polygons),i=new sE(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(),nE._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){const t=new sE(this._polygons),i=new sE(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 sE(this.clone()._polygons),i=new sE(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),nE._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){const t=new sE(this._polygons),i=new sE(e._polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}inverse(){const e=this.clone();return e.inverseInPlace(),e}inverseInPlace(){this._polygons.map((e=>{e.flip()}))}copyTransformAttributes(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this}toVertexData(e=null,t=null){const i=this.matrix.clone();i.invert();const r=this._polygons,s=[],n=[],o=[];let a=null,l=null;const h=W.Pq.Zero(),c=W.Pq.Zero(),u=W.I9.Zero(),d=new H.ov(0,0,0,0),f=[0,0,0],p={};let _;for(let m=0,g=r.length;me.shared.meshId===t.shared.meshId?e.shared.subMeshId-t.shared.subMeshId:e.shared.meshId-t.shared.meshId)),this.toVertexData((e=>{o[e.shared.meshId]||(o[e.shared.meshId]={}),o[e.shared.meshId][e.shared.subMeshId]||(o[e.shared.meshId][e.shared.subMeshId]={indexStart:1/0,indexEnd:-1/0,materialIndex:e.shared.materialIndex}),a=o[e.shared.meshId][e.shared.subMeshId]}),(()=>{a.indexStart=Math.min(n,a.indexStart),a.indexEnd=Math.max(n,a.indexEnd),n++})).applyToMesh(r),i){let e,t=0;r.subMeshes=[];for(const i in o){e=-1;for(const s in o[i])a=o[i][s],vt.CreateFromIndices(a.materialIndex+t,a.indexStart,a.indexEnd-a.indexStart+1,r),e=Math.max(a.materialIndex,e);t+=++e}}return r}toMesh(e,t=null,i,r){const s=this.buildMeshGeometry(e,i,r);return s.material=t,s.position.copyFrom(this.position),s.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(s.rotationQuaternion=this.rotationQuaternion.clone()),s.scaling.copyFrom(this.scaling),s.computeWorldMatrix(!0),s}}class oE{static _GetShader(e,t){if(!e._meshUVSpaceRendererShader){const i=new xo("meshUVSpaceRendererShader",e,{vertex:"meshUVSpaceRenderer",fragment:"meshUVSpaceRenderer"},{attributes:["position","normal","uv"],uniforms:["world","projMatrix"],samplers:["textureSampler"],needAlphaBlending:!0,shaderLanguage:t});i.backFaceCulling=!1,i.alphaMode=2,e.onDisposeObservable.add((()=>{e._meshUVSpaceRendererShader?.dispose(),e._meshUVSpaceRendererShader=null})),e._meshUVSpaceRendererShader=i}return e._meshUVSpaceRendererShader}static _GetMaskShader(e,t){if(!e._meshUVSpaceRendererMaskShader){const i=new xo("meshUVSpaceRendererMaskShader",e,{vertex:"meshUVSpaceRendererMasker",fragment:"meshUVSpaceRendererMasker"},{attributes:["position","uv"],uniforms:["worldViewProjection"],shaderLanguage:t});i.backFaceCulling=!1,i.alphaMode=2,e.onDisposeObservable.add((()=>{e._meshUVSpaceRendererMaskShader?.dispose(),e._meshUVSpaceRendererMaskShader=null})),e._meshUVSpaceRendererMaskShader=i}return e._meshUVSpaceRendererMaskShader}static _IsRenderTargetTexture(e){return void 0!==e.renderList}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i){this._textureCreatedInternally=!1,this._configureUserCreatedTexture=!0,this._maskTexture=null,this._finalPostProcess=null,this._shadersLoaded=!1,this._isDisposed=!1,this.clearColor=new H.ov(0,0,0,0),this.texture=null,this._shaderLanguage=0,this._mesh=e,this._scene=t,this._options={width:1024,height:1024,textureType:0,generateMipMaps:!0,optimizeUVAllocation:!0,uvEdgeBlending:!1,...i},this._initShaderSourceAsync()}async _initShaderSourceAsync(){this._scene.getEngine().isWebGPU?(this._shaderLanguage=1,await Promise.all([Promise.resolve().then(i.bind(i,4830)),Promise.resolve().then(i.bind(i,49584)),Promise.resolve().then(i.bind(i,72919)),Promise.resolve().then(i.bind(i,49373)),Promise.resolve().then(i.bind(i,55153)),Promise.resolve().then(i.bind(i,83479))])):await Promise.all([Promise.resolve().then(i.bind(i,82017)),Promise.resolve().then(i.bind(i,33287)),Promise.resolve().then(i.bind(i,96924)),Promise.resolve().then(i.bind(i,99990)),Promise.resolve().then(i.bind(i,13460)),Promise.resolve().then(i.bind(i,33534))]),this._isDisposed||(this._shadersLoaded=!0)}isReady(){if(!this._shadersLoaded)return!1;this.texture?this._configureUserCreatedTexture&&this._configureUserCreatedRTT():this._createDiffuseRTT();const e=oE._IsRenderTargetTexture(this.texture)?this.texture.isReadyForRendering():this.texture.isReady(),t=this._maskTexture?.isReadyForRendering()??!0,i=this._finalPostProcess?.isReady()??!0;return e&&t&&i}renderTexture(e,t,i,r,s=0,n=!0){if(!n||this.isReady()){if(this.texture?this._configureUserCreatedTexture&&this._configureUserCreatedRTT():this._createDiffuseRTT(),oE._IsRenderTargetTexture(this.texture)){const n=this._createProjectionMatrix(t,i,r,s),o=oE._GetShader(this._scene,this._shaderLanguage);o.setTexture("textureSampler",e),o.setMatrix("projMatrix",n),this.texture.render(),o.removeTexture("textureSampler")}}else setTimeout((()=>{this.renderTexture(e,t,i,r,s,n)}),16)}clear(){if(this.texture&&oE._IsRenderTargetTexture(this.texture)&&this.texture.renderTarget){const e=this._scene.getEngine();e.bindFramebuffer(this.texture.renderTarget),e.clear(this.clearColor,!0,!0,!0),e.unBindFramebuffer(this.texture.renderTarget)}if(this._finalPostProcess?.inputTexture){const e=this._scene.getEngine();e.bindFramebuffer(this._finalPostProcess?.inputTexture),e.clear(this.clearColor,!0,!0,!0),e.unBindFramebuffer(this._finalPostProcess?.inputTexture)}}dispose(){this._textureCreatedInternally&&(this.texture?.dispose(),this._textureCreatedInternally=!1),this._configureUserCreatedTexture=!0,this._maskTexture?.dispose(),this._maskTexture=null,this._finalPostProcess?.dispose(),this._finalPostProcess=null,this._isDisposed=!0}_configureUserCreatedRTT(){this._configureUserCreatedTexture=!1,this.texture&&oE._IsRenderTargetTexture(this.texture)&&(this.texture.setMaterialForRendering(this._mesh,oE._GetShader(this._scene,this._shaderLanguage)),this.texture.onClearObservable.add((()=>{})),this.texture.renderList=[this._mesh],this._options.uvEdgeBlending&&(this._createMaskTexture(),this._createPostProcess(),this.texture.addPostProcess(this._finalPostProcess)))}_createDiffuseRTT(){this._textureCreatedInternally=!0;const e=this._createRenderTargetTexture(this._options.width,this._options.height);e.setMaterialForRendering(this._mesh,oE._GetShader(this._scene,this._shaderLanguage)),this.texture=e,this._configureUserCreatedTexture=!1,this._options.uvEdgeBlending&&(this._createMaskTexture(),this._createPostProcess(),e.addPostProcess(this._finalPostProcess))}_createMaskTexture(){this._maskTexture||(this._maskTexture=new ln.$(this._mesh.name+"_maskTexture",{width:this._options.width,height:this._options.height},this._scene,!1,!0,0,!1,2,void 0,void 0,void 0,6),this._maskTexture.clearColor=new H.ov(0,0,0,0),this._maskTexture.renderList.push(this._mesh),this._maskTexture.setMaterialForRendering(this._mesh,oE._GetMaskShader(this._scene,this._shaderLanguage)),this._maskTexture.refreshRate=ln.$.REFRESHRATE_RENDER_ONCE,this._scene.customRenderTargets.push(this._maskTexture))}_createPostProcess(){this._finalPostProcess||(this._finalPostProcess=new ms.w(this._mesh.name+"_fixSeamsPostProcess","meshUVSpaceRendererFinaliser",["textureSize"],["textureSampler","maskTextureSampler"],1,null,1,this._scene.getEngine(),!1,null,this._options.textureType,void 0,void 0,void 0,void 0,this._shaderLanguage),this._finalPostProcess.onApplyObservable.add((e=>{e.setTexture("maskTextureSampler",this._maskTexture),e.setFloat2("textureSize",this._options.width,this._options.height)})))}_createRenderTargetTexture(e,t){const i=new ln.$(this._mesh.name+"_uvspaceTexture",{width:e,height:t},this._scene,this._options.generateMipMaps,!0,this._options.textureType,!1,this._options.generateMipMaps?3:2,!1,!1,!1,5);return i.renderParticles=!1,i.optimizeUVAllocation=!!this._options.optimizeUVAllocation,i.onClearObservable.addOnce((()=>{this._scene.getEngine().clear(this.clearColor,!0,!0,!0),i.onClearObservable.add((()=>{}))})),i.renderList=[this._mesh],i}_createProjectionMatrix(e,t,i,r=0){const s=-Math.atan2(t.z,t.x)-Math.PI/2,n=Math.sqrt(t.x*t.x+t.z*t.z),o=Math.atan2(t.y,n),a=e.add(t.scale(.5*i.z)),l=W.uq.RotationYawPitchRoll(s,o,r).multiply(W.uq.Translation(a.x,a.y,a.z)),h=W.uq.Invert(l),c=W.uq.FromArray([2/i.x,0,0,0,0,2/i.y,0,0,0,0,1/i.z,0,0,0,0,1]),u=W.uq.FromArray([.5,0,0,0,0,.5,0,0,0,0,1,0,.5,.5,0,1]);return h.multiply(c).multiply(u)}}Yt._TrailMeshParser=(e,t)=>aE.Parse(e,t);class aE extends Yt{constructor(e,t,i,r,s=60,n=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._generator=t,"object"==typeof r&&null!==r?(this.diameter=r.diameter||1,this._length=r.length||60,this._segments=r.segments?r.segments>this._length?this._length:r.segments:this._length,this._sectionPolygonPointsCount=r.sections||4,this._doNotTaper=r.doNotTaper||!1,this._autoStart=r.autoStart||!0):(this.diameter=r||1,this._length=s,this._segments=this._length,this._doNotTaper=!1,this._autoStart=n),this._sectionVectors=[],this._sectionNormalVectors=[];for(let e=0;e<=this._sectionPolygonPointsCount;e++)this._sectionVectors[e]=W.Pq.Zero(),this._sectionNormalVectors[e]=W.Pq.Zero();this._createMesh()}getClassName(){return"TrailMesh"}_createMesh(){const e=new bt,t=[],i=[],r=[],s=[];let n=W.Pq.Zero();n=this._generator instanceof Nt&&this._generator.hasBoundingInfo?this._generator.getBoundingInfo().boundingBox.centerWorld:this._generator.absolutePosition;const o=2*Math.PI/this._sectionPolygonPointsCount;for(let e=0;e<=this._sectionPolygonPointsCount;e++){const i=e!==this._sectionPolygonPointsCount?e*o:0;t.push(n.x+Math.cos(i)*this.diameter,n.y+Math.sin(i)*this.diameter,n.z),s.push(e/this._sectionPolygonPointsCount,0)}for(let e=1;e<=this._segments;e++){for(let i=0;i<=this._sectionPolygonPointsCount;i++){const r=i!==this._sectionPolygonPointsCount?i*o:0;t.push(n.x+Math.cos(r)*this.diameter,n.y+Math.sin(r)*this.diameter,n.z),s.push(i/this._sectionPolygonPointsCount,e/this._segments)}const i=t.length/3-2*(this._sectionPolygonPointsCount+1);for(let e=0;e<=this._sectionPolygonPointsCount;e++)r.push(i+e,i+e+this._sectionPolygonPointsCount,i+e+this._sectionPolygonPointsCount+1),r.push(i+e,i+e+this._sectionPolygonPointsCount+1,i+e+1)}bt.ComputeNormals(t,r,i),e.positions=t,e.normals=i,e.indices=r,e.uvs=s,e.applyToMesh(this,!0),this._autoStart&&this.start()}_updateSectionVectors(){const e=this._generator.getWorldMatrix(),t=2*Math.PI/this._sectionPolygonPointsCount;for(let i=0;i<=this._sectionPolygonPointsCount;i++){const r=i!==this._sectionPolygonPointsCount?i*t:0;this._sectionVectors[i].copyFromFloats(Math.cos(r)*this.diameter,Math.sin(r)*this.diameter,0),this._sectionNormalVectors[i].copyFromFloats(Math.cos(r),Math.sin(r),0),W.Pq.TransformCoordinatesToRef(this._sectionVectors[i],e,this._sectionVectors[i]),W.Pq.TransformNormalToRef(this._sectionNormalVectors[i],e,this._sectionNormalVectors[i])}}start(){this._running||(this._running=!0,this._beforeRenderObserver=this.getScene().onBeforeRenderObservable.add((()=>{this.update()})))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){const e=this.getVerticesData(st.R.PositionKind),t=this.getVerticesData(st.R.NormalKind),i=3*(this._sectionPolygonPointsCount+1);if(e&&t){if(this._doNotTaper)for(let t=i;t{this._getSimplifier(e).simplify(t,(i=>{void 0!==t.distance&&e.mesh.addLODLevel(t.distance,i),i.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()}))}));else{const t=this._getSimplifier(e),i=(i,r)=>{t.simplify(i,(t=>{void 0!==i.distance&&e.mesh.addLODLevel(i.distance,t),t.isVisible=!0,r()}))};Ue.LV.Run(e.settings.length,(t=>{i(e.settings[t.index],(()=>{t.executeNext()}))}),(()=>{e.successCallback&&e.successCallback(),this.executeNext()}))}}_getSimplifier(e){return e.simplificationType,new bE(e.mesh)}}var cE,uE,dE,fE,pE,_E;!function(e){e[e.QUADRATIC=0]="QUADRATIC"}(cE||(cE={}));class mE{constructor(e){this._vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class gE{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new vE,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class vE{constructor(e){this.data=new Array(10);for(let t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}det(e,t,i,r,s,n,o,a,l){return this.data[e]*this.data[s]*this.data[l]+this.data[i]*this.data[r]*this.data[a]+this.data[t]*this.data[n]*this.data[o]-this.data[i]*this.data[s]*this.data[o]-this.data[e]*this.data[n]*this.data[a]-this.data[t]*this.data[r]*this.data[l]}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 vE;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,r){return new vE(vE.DataFromNumbers(e,t,i,r))}static DataFromNumbers(e,t,i,r){return[e*e,e*t,e*i,e*r,t*t,t*i,t*r,i*i,i*r,r*r]}}class xE{constructor(e,t){this.vertexId=e,this.triangleId=t}}class bE{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=lt.bH}simplify(e,t){this._initDecimatedMesh(),Ue.LV.Run(this._mesh.subMeshes.length,(t=>{this._initWithMesh(t.index,(()=>{this._runDecimation(e,t.index,(()=>{t.executeNext()}))}),e.optimizeMesh)}),(()=>{setTimeout((()=>{t(this._reconstructedMesh)}),0)}))}_runDecimation(e,t,i){const r=~~(this._triangles.length*e.quality);let s=0;const n=this._triangles.length,o=(e,t)=>{setTimeout((()=>{e%5==0&&this._updateMesh(0===e);for(let e=0;e{const t=~~((this._triangles.length/2+e)%this._triangles.length),r=this._triangles[t];if(r&&!(r.error[3]>i||r.deleted||r.isDirty))for(let e=0;e<3;++e)if(r.error[e]{-1===h.indexOf(e)&&(e.deletePending=!0,h.push(e))})),h.length%2!=0)continue;n.q=o.q.add(n.q),n.updatePosition(a);const c=this._references.length;s=this._updateTriangles(n,n,t,s),s=this._updateTriangles(n,o,i,s);const u=this._references.length-c;if(u<=n.triangleCount){if(u)for(let e=0;en-s<=r))}),0)};Ue.LV.Run(this.decimationIterations,(e=>{n-s<=r?e.breakLoop():o(e.index,(()=>{e.executeNext()}))}),(()=>{setTimeout((()=>{this._reconstructMesh(t),i()}),0)}))}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];const r=this._mesh.getVerticesData(st.R.PositionKind),s=this._mesh.getIndices(),n=this._mesh.subMeshes[e],o=e=>{if(i)for(let t=0;t{if(!r)return;const t=e+n.verticesStart,i=W.Pq.FromArray(r,3*t),s=o(i)||new gE(i,this._vertices.length);s.originalOffsets.push(t),s.id===this._vertices.length&&this._vertices.push(s),a.push(s.id)}),(()=>{Ue.LV.SyncAsyncForLoop(n.indexCount/3,this.syncIterations,(e=>{if(!s)return;const t=3*(n.indexStart/3+e),i=s[t+0],r=s[t+1],o=s[t+2],l=this._vertices[a[i-n.verticesStart]],h=this._vertices[a[r-n.verticesStart]],c=this._vertices[a[o-n.verticesStart]],u=new mE([l,h,c]);u.originalOffset=t,this._triangles.push(u)}),(()=>{this._init(t)}))}))}_init(e){Ue.LV.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];t.normal=W.Pq.Cross(t._vertices[1].position.subtract(t._vertices[0].position),t._vertices[2].position.subtract(t._vertices[0].position)).normalize();for(let e=0;e<3;e++)t._vertices[e].q.addArrayInPlace(vE.DataFromNumbers(t.normal.x,t.normal.y,t.normal.z,-W.Pq.Dot(t.normal,t._vertices[0].position)))}),(()=>{Ue.LV.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];for(let e=0;e<3;++e)t.error[e]=this._calculateError(t._vertices[e],t._vertices[(e+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])}),(()=>{e()}))}))}_reconstructMesh(e){const t=[];let i,r,s;for(i=0;i{n.push(e.position.x),n.push(e.position.y),n.push(e.position.z),h&&h.length&&(o.push(h[3*t]),o.push(h[3*t+1]),o.push(h[3*t+2])),c&&c.length&&(a.push(c[2*t]),a.push(c[2*t+1])),u&&u.length&&(l.push(u[4*t]),l.push(u[4*t+1]),l.push(u[4*t+2]),l.push(u[4*t+3])),++d}))}const f=this._reconstructedMesh.getTotalIndices(),p=this._reconstructedMesh.getTotalVertices(),_=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];const m=this._reconstructedMesh.getIndices(),g=this._mesh.getIndices();for(i=0;i{const t=g[r.originalOffset+e];let i=r._vertices[e].originalOffsets.indexOf(t);i<0&&(i=0),m.push(r._vertices[e].id+i+p)}));this._reconstructedMesh.setIndices(m),this._reconstructedMesh.setVerticesData(st.R.PositionKind,n),o.length>0&&this._reconstructedMesh.setVerticesData(st.R.NormalKind,o),a.length>0&&this._reconstructedMesh.setVerticesData(st.R.UVKind,a),l.length>0&&this._reconstructedMesh.setVerticesData(st.R.ColorKind,l);const v=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],_.forEach((e=>{vt.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())})),vt.AddToMesh(v.materialIndex,p,d,f,3*t.length,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new Yt(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId}_isFlipped(e,t,i,r,s){for(let n=0;n.999)return!0;const d=W.Pq.Cross(c,u).normalize();if(r[n]=!1,W.Pq.Dot(d,o.normal)<.2)return!0}return!1}_updateTriangles(e,t,i,r){let s=r;for(let r=0;rMath.max(e,t.getTotalVertices())),0),a=Array.from({length:o},(()=>new W.Pq)),l=Array.from({length:o},(()=>new W.Pq));for(const t of e){const e=t.getVerticesData(st.R.PositionKind);if(!e)continue;const i=t.getTotalVertices();a.length=Math.max(a.length,i),l.length=Math.max(a.length,i);for(let t=0,s=0;t4,r=e?t.getVerticesData(st.R.MatricesWeightsExtraKind):null,s=e?t.getVerticesData(st.R.MatricesIndicesExtraKind):null,o=n.get(t.uniqueId)||new Map;n.set(t.uniqueId,o);const h=(e,t,i,r)=>{for(let s=t;s0){const t=r[s],i=o.get(t);i?(i.minimum.minimizeInPlace(a[e]),i.maximum.maximizeInPlace(l[e])):o.set(t,{minimum:a[e].clone(),maximum:l[e].clone()})}};for(let e=0,t=0;e{const s=TE(e),n=i[t].getAbsoluteInverseBindMatrix();for(const e of s)W.Pq.TransformCoordinatesToRef(e,n,e);r.set(t,s)}))}}}const u=Array.from({length:e.length},(()=>({minimum:(new W.Pq).setAll(Number.POSITIVE_INFINITY),maximum:(new W.Pq).setAll(Number.NEGATIVE_INFINITY)}))),d=()=>{for(let t=0;t{for(const o of i){const i=e[n].getFinalMatrix().multiplyToRef(s,W.AA.Matrix[0]);W.Pq.TransformCoordinatesToRef(o,i,r),u[t].minimum.minimizeInPlace(r),u[t].maximum.maximizeInPlace(r)}}))}else for(const e of h.get(i.uniqueId))W.Pq.TransformCoordinatesToRef(e,s,r),u[t].minimum.minimizeInPlace(r),u[t].maximum.maximizeInPlace(r)}};if(t&&t.isStarted){const e=t.getCurrentFrame(),r=i/t.getLength(0,1);for(let e=t.from;e<=t.to;e+=r)t.goToFrame(e),d();t.goToFrame(e)}else d();return u}class yE{getClassName(){return"Lattice"}get resolutionX(){return this._resolutionX}get resolutionY(){return this._resolutionY}get resolutionZ(){return this._resolutionZ}get size(){return this._size}get position(){return this._position}get data(){return this._data}get cellSize(){return this._cellSize}get min(){return this._min}get max(){return this._max}constructor(e){this._cellSize=new W.Pq,this._min=new W.Pq(-.5,-.5,-.5),this._max=new W.Pq(.5,.5,.5),this._localPos=new W.Pq,this._tmpVector=new W.Pq,this._lerpVector0=new W.Pq,this._lerpVector1=new W.Pq,this._lerpVector2=new W.Pq,this._lerpVector3=new W.Pq,this._lerpVector4=new W.Pq,this._lerpVector5=new W.Pq;const t={resolutionX:3,resolutionY:3,resolutionZ:3,position:W.Pq.Zero(),size:W.Pq.One(),...e};this._resolutionX=t.resolutionX,this._resolutionY=t.resolutionY,this._resolutionZ=t.resolutionZ,this._position=t.position,this._size=t.autoAdaptToMesh?t.autoAdaptToMesh.getBoundingInfo().boundingBox.extendSize.scale(2):t.size,this._allocateData(),this.update()}_allocateData(){this._data=new Array(this.resolutionX);for(let e=0;eo.x||l.yo.y||l.zo.z){t&&l.toArray(t,a);continue}const h=this._localPos.set((l.x-n.x)/this._cellSize.x,(l.y-n.y)/this._cellSize.y,(l.z-n.z)/this._cellSize.z),c=Math.floor(h.x),u=Math.floor(h.y),d=Math.floor(h.z),f=Math.min(c+1,i-1),p=Math.min(u+1,r-1),_=Math.min(d+1,s-1),m=h.x-c,g=h.y-u,v=h.z-d,x=(0,ar.Clamp)(c,0,i-1),b=(0,ar.Clamp)(u,0,r-1),S=(0,ar.Clamp)(d,0,s-1),T=(0,ar.Clamp)(f,0,i-1),C=(0,ar.Clamp)(p,0,r-1),y=(0,ar.Clamp)(_,0,s-1),E=this._data[x][b][S],P=this._data[T][b][S],A=this._data[x][C][S],R=this._data[T][C][S],I=this._data[x][b][y],M=this._data[T][b][y],O=this._data[x][C][y],D=this._data[T][C][y],w=W.Pq.LerpToRef(E,P,m,this._lerpVector0),N=W.Pq.LerpToRef(I,M,m,this._lerpVector1),F=W.Pq.LerpToRef(A,R,m,this._lerpVector2),L=W.Pq.LerpToRef(O,D,m,this._lerpVector3),B=W.Pq.LerpToRef(w,F,g,this._lerpVector4),V=W.Pq.LerpToRef(N,L,g,this._lerpVector5),k=W.Pq.LerpToRef(B,V,v,this._lerpVector0);k.addInPlace(this.position),k.toArray(t||e,a)}}}class EE extends Dn{constructor(e,t){super(t,"Lattice",200),this._lattice=e,this.refreshData(),this._enable(!0)}getClassName(){return"LatticePluginMaterial"}isCompatible(e){switch(e){case 0:case 1:return!0;default:return!1}}refreshData(){const e=this._lattice.resolutionX*this._lattice.resolutionY*this._lattice.resolutionZ*4;this._latticeData&&this._latticeData.length===e||(this._latticeData=new Float32Array(e));for(let e=0;e;\n ",CUSTOM_VERTEX_UPDATE_POSITION:this._prepareCode(t)}:{CUSTOM_VERTEX_DEFINITIONS:"\n precision highp sampler3D;\n uniform sampler3D latticeData;\n ",CUSTOM_VERTEX_UPDATE_POSITION:this._prepareCode(t)}:null}dispose(){this._latticeDataTexture&&(this._latticeDataTexture.dispose(),this._latticeDataTexture=null)}}!function(e){e[e.POINTS_MODE_POINTS=0]="POINTS_MODE_POINTS",e[e.POINTS_MODE_PATHS=1]="POINTS_MODE_PATHS"}(uE||(uE={})),function(e){e[e.FACES_MODE_SINGLE_SIDED=0]="FACES_MODE_SINGLE_SIDED",e[e.FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING=1]="FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING",e[e.FACES_MODE_DOUBLE_SIDED=2]="FACES_MODE_DOUBLE_SIDED"}(dE||(dE={})),function(e){e[e.AUTO_DIRECTIONS_FROM_FIRST_SEGMENT=0]="AUTO_DIRECTIONS_FROM_FIRST_SEGMENT",e[e.AUTO_DIRECTIONS_FROM_ALL_SEGMENTS=1]="AUTO_DIRECTIONS_FROM_ALL_SEGMENTS",e[e.AUTO_DIRECTIONS_ENHANCED=2]="AUTO_DIRECTIONS_ENHANCED",e[e.AUTO_DIRECTIONS_FACE_TO=3]="AUTO_DIRECTIONS_FACE_TO",e[e.AUTO_DIRECTIONS_NONE=99]="AUTO_DIRECTIONS_NONE"}(fE||(fE={}));class PE extends Yt{constructor(e,t,i){super(e,t,null,null,!1,!1),this.name=e,this._options=i,this._lazy=!1,this._updatable=!1,this._engine=t.getEngine(),this._lazy=i.lazy??!1,this._updatable=i.updatable??!1,this._vertexPositions=[],this._indices=[],this._uvs=[],this._points=[],this._colorPointers=i.colorPointers??[],this._widths=i.widths??new Array(i.points.length).fill(1)}getClassName(){return"GreasedLineMesh"}_updateWidthsWithValue(e){let t=0;for(const e of this._points)t+=e.length;const i=t/3*2-this._widths.length;for(let t=0;tAE.Parse(e,t);class AE extends PE{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(Ey.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+=2*e.length,r+=2*(e.length-3),s+=4*e.length/3,n+=8*e.length/3}));const o=new Float32Array(i),a=i>65535?new Uint32Array(r):new Uint16Array(r),l=new Float32Array(s),h=new Float32Array(n),c=new Float32Array(n);let u=0,d=0,f=0,p=0,_=0;e.forEach((e=>{const i=Ey.GetLineLengthArray(e),r=i[i.length-1];for(let i=0,r=0;r>1]/r;if(this._options.uvs)for(let e=0;eRE.Parse(e,t);class RE extends PE{constructor(e,t,i,r){if(super(e,t,i),this.name=e,!i.ribbonOptions)throw"'GreasedLineMeshOptions.ribbonOptions' is not set.";this._paths=[],this._counters=[],this._slopes=[],this._widths=i.widths??[],this._ribbonWidths=[],this._pathsOptions=r??[],i.points&&this.addPoints(Ey.ConvertPoints(i.points),i,!!r)}addPoints(e,t,i=!1){if(!t.ribbonOptions)throw"addPoints() on GreasedLineRibbonMesh instance requires 'GreasedLineMeshOptions.ribbonOptions'.";i||this._pathsOptions.push({options:t,pathCount:e.length}),super.addPoints(e,t)}getClassName(){return"GreasedLineRibbonMesh"}get isFlatLine(){return this._paths.length<3}get slopes(){return this._slopes}set slopes(e){this._slopes=e}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[];for(let t=0;t{const s=RE._ConvertToRibbonPath(e,n.ribbonOptions,this._scene.useRightHandedSystem,i?i[t]:i);r=this._preprocess(s,r,n)}))}}this._lazy||(this._createVertexBuffers(),!this.doNotSyncBoundingInfo&&this.refreshBoundingInfo())}static _GetDirectionPlanesFromDirectionsOption(e,t){return Array.isArray(t)?t:new Array(e).fill(t)}static _CreateRibbonVertexData(e,t){const i=e.length;if(i<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";const r=[],s=[],n=e[0];for(let t=0;t2)for(let e=0;e0&&(o[0]+=1,o[1]+=1),s.push(o[1]+(e%2!=0?i:0),o[0],o[2]),a&&s.push(o[0],o[1]+(e%2!=0?i:0),o[2])}else for(let e=0;ee.y&&e.x>e.z?i?RE._RightHandedForwardReadOnlyQuaternion:RE._LeftHandedForwardReadOnlyQuaternion:RE._LeftReadOnlyQuaternion),l=e.normalize()}h=l.multiplyByFloats(o,o,o),s.push(c.add(h)),n.push(c.subtract(h))}r||(s.push(a[a.length-1].add(h)),n.push(a[a.length-1].subtract(h)))}return[s,n]}static _GetDirectionFromPoints(e,t,i){return e.x!==t.x||i&&1!==i?.x?e.y===t.y?RE.DIRECTION_XZ:e.z===t.z?RE.DIRECTION_XY:RE.DIRECTION_XZ:RE.DIRECTION_YZ}clone(e=`${this.name}-cloned`,t){const i=this._createLineOptions(),r={},s=[];ce.r.DeepCopy(this._pathsOptions,s,void 0,void 0,!0),ce.r.DeepCopy(i,r,["instance"],void 0,!0);const n=new RE(e,this._scene,r,s);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,r=e.name,s=e.pathOptions;return new RE(r,t,i,s)}_initGreasedLine(){super._initGreasedLine(),this._paths=[],this._counters=[],this._slopes=[],this._ribbonWidths=[]}_calculateSegmentLengths(e){const t=e.length;this._vSegmentLengths=new Array(t),this._vTotalLengths=new Array(t);let i=0;for(let r=0;r0){if(t.length%2!=0&&t.push(r),5===i){const e=Math.floor(t.length/2);for(let i=0,r=0;i0){if(5===i){const e=Math.floor(t.length/2);for(let i=0;ie.kind===st.R.NormalKind)),s=this._manifold.getMesh(t.rebuildNormals&&r?[3,4,5]:void 0);i.indices=s.triVerts.length>65535?new Uint32Array(s.triVerts):new Uint16Array(s.triVerts);for(let e=0;ee.kind===st.R.NormalKind)),o=this._manifold.getMesh(r.rebuildNormals&&n?[3,4,5]:void 0),a=o.vertProperties.length/o.numProp,l=new Yt(e,t);if(s.applyToMesh(l),r.centerMesh){const e=l.getBoundingInfo().boundingSphere.center;l.position.set(-e.x,-e.y,-e.z),l.bakeCurrentTransformIntoVertices()}let h=o.runOriginalID[0],c=o.runIndex[0],u=0;const d=[];t=l.getScene();for(let e=0;e1){const i=new kt(e,t);i.subMaterials=d,l.material=i}else l.material=d[0];return l}dispose(){this._manifold&&(this._manifold.delete(),this._manifold=null)}static _ProcessData(e,t,i,r,s,n){const o=new Float32Array(e*i.reduce(((e,t)=>e+t.stride),0));for(let t=0;te.subMeshes[i].indexStart)),o=e.material||e.getScene().defaultMaterial,a="MultiMaterial"===o.getClassName(),l=[...Array(e.subMeshes.length)].map(((t,i)=>a?LE+o.subMaterials[e.subMeshes[i].materialIndex].uniqueId:LE+o.uniqueId)),h=Array.from(n.keys());h.sort(((e,t)=>n[e]-n[t]));const c=new Uint32Array(h.map((e=>n[e]))),u=new Uint32Array(h.map((e=>l[e]))),d={positions:i,indices:r,normals:e.getVerticesData(st.R.NormalKind),colors:e.getVerticesData(st.R.ColorKind),uvs:e.getVerticesData(st.R.UVKind),uvs2:e.getVerticesData(st.R.UV2Kind),uvs3:e.getVerticesData(st.R.UV3Kind),uvs4:e.getVerticesData(st.R.UV4Kind),uvs5:e.getVerticesData(st.R.UV5Kind),uvs6:e.getVerticesData(st.R.UV6Kind)};return this._Construct(d,t?null:s,c,u)}}function kE(){return void 0!==NE}async function UE(e){const t={manifoldUrl:"https://unpkg.com/manifold-3d@3.0.0",...e};if(t.manifoldInstance)NE=t.manifoldInstance,FE=t.manifoldMeshInstance;else{const e=await(i=`\n import Module from '${t.manifoldUrl}/manifold.js';\n const wasm = await Module();\n wasm.setup();\n const {Manifold, Mesh} = wasm;\n const returnedValue = {Manifold, Mesh};\n `,new Promise(((e,t)=>{let r,s;if((0,ii.BA)())r=window,s="window";else{if("undefined"==typeof self)return void t(new Error("Cannot load script module outside of a window or a worker"));r=self,s="self"}r._LoadScriptModuleResolve||(r._LoadScriptModuleResolve={}),r._LoadScriptModuleResolve[BE]=e,i+=`\n ${s}._LoadScriptModuleResolve[${BE}](returnedValue);\n ${s}._LoadScriptModuleResolve[${BE}] = undefined;\n `,BE++,Ue.S0.LoadScript(i,void 0,((e,i)=>{t(i||new Error(e))}),undefined,!0)})));NE=e.Manifold,FE=e.Mesh}var i;LE=NE.reserveIDs(65536)}var GE,zE,WE,HE,XE,qE,YE,KE,jE,$E,QE,ZE;Yt.prototype.thinInstanceAdd=function(e,t=!0){if(!this.getScene().getEngine().getCaps().instancedArrays)return Z.V.Error("Thin Instances are not supported on this device as Instanced Array extension not supported"),-1;this._thinInstanceUpdateBufferSize("matrix",Array.isArray(e)?e.length:1);const i=this._thinInstanceDataStorage.instancesCount;if(Array.isArray(e))for(let i=0;i=this._thinInstanceDataStorage.instancesCount)return!1;const r=this._thinInstanceDataStorage.matrixData;return t.copyToArray(r,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),i&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},Yt.prototype.thinInstanceSetAttributeAt=function(e,t,i,r=!0){return e===st.R.ColorKind&&(e=st.R.ColorInstanceKind),!(!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[e]||t>=this._thinInstanceDataStorage.instancesCount||(this._thinInstanceUpdateBufferSize(e,0),this._userThinInstanceBuffersStorage.data[e].set(i,t*this._userThinInstanceBuffersStorage.strides[e]),r&&this.thinInstanceBufferUpdated(e),0))},Object.defineProperty(Yt.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){const t=this._thinInstanceDataStorage.matrixData??this.source?._thinInstanceDataStorage.matrixData;e<=(t?t.length/16:0)&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),Yt.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!0){const r=new st.h(this.getEngine(),t,!i,16,!1,!0);for(let t=0;t<4;t++)this.setVerticesBuffer(r.createVertexBuffer(e+t,4*t,4));return r},Yt.prototype.thinInstanceSetBuffer=function(e,t,i=0,r=!0){i=i||16,"matrix"===e?(this._thinInstanceDataStorage.matrixBuffer?.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=t?t.length:32*i,this._thinInstanceDataStorage.matrixData=t,this._thinInstanceDataStorage.worldMatrices=null,null!==t?(this._thinInstanceDataStorage.instancesCount=t.length/i,this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",t,r),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):"previousMatrix"===e?(this._thinInstanceDataStorage.previousMatrixBuffer?.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,r))):(e===st.R.ColorKind&&(e=st.R.ColorInstanceKind),null===t?this._userThinInstanceBuffersStorage?.data[e]&&(this.removeVerticesData(e),delete this._userThinInstanceBuffersStorage.data[e],delete this._userThinInstanceBuffersStorage.strides[e],delete this._userThinInstanceBuffersStorage.sizes[e],delete this._userThinInstanceBuffersStorage.vertexBuffers[e]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[e]=t,this._userThinInstanceBuffersStorage.strides[e]=i,this._userThinInstanceBuffersStorage.sizes[e]=t.length,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new st.R(this.getEngine(),t,e,!r,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},Yt.prototype.thinInstanceBufferUpdated=function(e){"matrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.matrixBuffer&&!this._thinInstanceDataStorage.matrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._thinInstanceDataStorage.matrixBuffer?.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount)):"previousMatrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.previousMatrixBuffer&&!this._thinInstanceDataStorage.previousMatrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._thinInstanceDataStorage.previousMatrixBuffer?.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount)):(e===st.R.ColorKind&&(e=st.R.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&(this.thinInstanceAllowAutomaticStaticBufferRecreation&&!this._userThinInstanceBuffersStorage.vertexBuffers[e].isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0)))},Yt.prototype.thinInstancePartialBufferUpdate=function(e,t,i){"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===st.R.ColorKind&&(e=st.R.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},Yt.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let t=0;te.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){return this.isConnected?this._connectedPoint?._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=GE.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new z.cP,this.onDisconnectionObservable=new z.cP,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 0===this.checkCompatibilityState(e)}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==GE.AutoDetect)return e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)?0:1;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return 1;let r=i,s=t;return 0===this.direction&&(r=t,s=i),r.isAnAncestorOf(s)?2:0}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(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 eP{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)return!0;if(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 t=i.ownerBlock.getDescendantOfPredicate(e);if(t)return t}return null}get _isReadyState(){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 z.cP,this._inputs=new Array,this._outputs=new Array,this._codeVariableName="",this.visibleOnFrame=!1,this._name=e,this.uniqueId=Op.K.UniqueId}registerInput(e,t,i=!1,r,s,n){const o=new JE(e,this,0);return o.type=t,o.isOptional=i,o.defaultValue=r,o.value=r,o.valueMin=s,o.valueMax=n,this._inputs.push(o),this}registerOutput(e,t,i){return(i=i??new JE(e,this,1)).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((e=>e.hasEndpoints))&&!this.isDebug)return!1;this.outputs.forEach((e=>e._resetCounters()))}this._buildId=e.buildId;for(const t of this._inputs){if(!t.connectedPoint){t.isOptional||e.notConnectedNonOptionalInputs.push(t);continue}const i=t.connectedPoint.ownerBlock;i&&i!==this&&i.build(e)}this._customBuildStep(e),e.verbose&&Z.V.Log(`Building ${this.name} [${this.getClassName()}]`);const t=ai.j.Now;return this._buildBlock(e),this._buildExecutionTime=ai.j.Now-t,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((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.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((e=>{const t=this.inputs.find((t=>t.name===e.name));if(t&&(e.displayName&&(t.displayName=e.displayName),e.isExposedOnFrame&&(t.isExposedOnFrame=e.isExposedOnFrame,t.exposedPortPosition=e.exposedPortPosition),void 0!==e.value&&null!==e.value))if("number"===e.valueType)t.value=e.value;else{const i=(0,X.n9)(e.valueType);i&&(t.value=i.FromArray(e.value))}})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}_dumpPropertiesCode(){return`${this._codeVariableName}.visibleOnFrame = ${this.visibleOnFrame};\n`}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e),t+=`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\n`}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}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=i+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let r=`\n// ${this.getClassName()}\n`;this.comments&&(r+=`// ${this.comments}\n`);const s=this.getClassName();if("GeometryInputBlock"===s){const e=this.type;r+=`var ${this._codeVariableName} = new BABYLON.GeometryInputBlock("${this.name}", ${e});\n`}else r+=`var ${this._codeVariableName} = new BABYLON.${s}("${this.name}");\n`;r+=this._dumpPropertiesCode();for(const i of this.inputs){if(!i.isConnected)continue;const s=i.connectedPoint.ownerBlock;-1===t.indexOf(s)&&(r+=s._dumpCode(e,t))}for(const i of this.outputs)if(i.hasEndpoints)for(const s of i.endpoints){const i=s.ownerBlock;i&&-1===t.indexOf(i)&&(r+=i._dumpCode(e,t))}return r}clone(){const e=this.serialize(),t=(0,X.n9)(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()}}(0,je.Cg)([(0,$e.lK)("comment")],eP.prototype,"comments",void 0);class tP extends eP{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",GE.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}}(0,X.Y5)("BABYLON.GeometryOutputBlock",tP),function(e){e[e.None=0]="None",e[e.Positions=1]="Positions",e[e.Normals=2]="Normals",e[e.Tangents=3]="Tangents",e[e.UV=4]="UV",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6",e[e.Colors=10]="Colors",e[e.VertexID=11]="VertexID",e[e.FaceID=12]="FaceID",e[e.GeometryID=13]="GeometryID",e[e.CollectionID=14]="CollectionID",e[e.LoopID=15]="LoopID",e[e.InstanceID=16]="InstanceID",e[e.LatticeID=17]="LatticeID",e[e.LatticeControl=18]="LatticeControl"}(HE||(HE={}));class iP{constructor(){this._rotationMatrix=new W.uq,this._scalingMatrix=new W.uq,this._positionMatrix=new W.uq,this._scalingRotationMatrix=new W.uq,this._transformMatrix=new W.uq,this._tempVector3=new W.Pq,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 HE.Positions:return this.executionContext.getOverridePositionsContextualValue?this.executionContext.getOverridePositionsContextualValue():this.geometryContext&&this.geometryContext.positions?W.Pq.FromArray(this.geometryContext.positions,3*i):W.Pq.Zero();case HE.Normals:return this.executionContext.getOverrideNormalsContextualValue?this.executionContext.getOverrideNormalsContextualValue():this.geometryContext&&this.geometryContext.normals?W.Pq.FromArray(this.geometryContext.normals,3*i):W.Pq.Zero();case HE.Colors:return this.geometryContext&&this.geometryContext.colors?W.IU.FromArray(this.geometryContext.colors,4*i):W.IU.Zero();case HE.Tangents:return this.geometryContext&&this.geometryContext.tangents?W.IU.FromArray(this.geometryContext.tangents,4*i):W.IU.Zero();case HE.UV:return this.executionContext.getOverrideUVs1ContextualValue?this.executionContext.getOverrideUVs1ContextualValue():this.geometryContext&&this.geometryContext.uvs?W.I9.FromArray(this.geometryContext.uvs,2*i):W.I9.Zero();case HE.UV2:return this.geometryContext&&this.geometryContext.uvs2?W.I9.FromArray(this.geometryContext.uvs2,2*i):W.I9.Zero();case HE.UV3:return this.geometryContext&&this.geometryContext.uvs3?W.I9.FromArray(this.geometryContext.uvs3,2*i):W.I9.Zero();case HE.UV4:return this.geometryContext&&this.geometryContext.uvs4?W.I9.FromArray(this.geometryContext.uvs4,2*i):W.I9.Zero();case HE.UV5:return this.geometryContext&&this.geometryContext.uvs5?W.I9.FromArray(this.geometryContext.uvs5,2*i):W.I9.Zero();case HE.UV6:return this.geometryContext&&this.geometryContext.uvs6?W.I9.FromArray(this.geometryContext.uvs6,2*i):W.I9.Zero();case HE.VertexID:return i;case HE.FaceID:return this.executionContext.getExecutionFaceIndex();case HE.LoopID:return this.executionContext.getExecutionLoopIndex();case HE.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case HE.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case HE.CollectionID:return this.geometryContext&&this.geometryContext.metadata&&this.geometryContext.metadata.collectionId||0;case HE.LatticeID:return this.executionContext.getOverridePositionsContextualValue?this.executionContext.getOverridePositionsContextualValue():W.Pq.Zero();case HE.LatticeControl:return this.executionContext.getOverrideNormalsContextualValue?this.executionContext.getOverrideNormalsContextualValue():W.Pq.Zero()}return null}adapt(e,t){const i=e.getConnectedValue(this)||0;if(e.type===t)return i;switch(t){case GE.Vector2:return new W.I9(i,i);case GE.Vector3:return new W.Pq(i,i,i);case GE.Vector4:return new W.IU(i,i,i,i)}return null}adaptInput(e,t,i){if(!e.isConnected)return e.value||i;const r=e.getConnectedValue(this);if(e._connectedPoint?.type===t)return r;switch(t){case GE.Vector2:return new W.I9(r,r);case GE.Vector3:return new W.Pq(r,r,r);case GE.Vector4:return new W.IU(r,r,r,r)}return null}emitErrors(){let e="";for(const t of this.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional.\n`;for(const t of this.noContextualData)e+=`Contextual input ${HE[t]} has no context to pull data from (must be connected to a setXXX block or a instantiateXXX block).\n`;if(e)throw"Build of NodeGeometry failed:\n"+e}_instantiate(e,t,i,r,s){W.uq.ScalingToRef(r.x,r.y,r.z,this._scalingMatrix),W.uq.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),W.uq.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 t=0;te.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.${HE[this._contextualSource]};\n`;const t=[];let i="";switch(this.type){case GE.Float:case GE.Int:i=`${this.value}`;break;case GE.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case GE.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case GE.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`}return t.push(`${e}.value = ${i}`),this.type!==GE.Float&&this.type!==GE.Int||t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}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,null===this._storedValue||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("number"===e.valueType)this._storedValue=e.value;else{const t=(0,X.n9)(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}(0,X.Y5)("BABYLON.GeometryInputBlock",rP);class sP extends eP{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",GE.Float,!0,1),this.registerInput("width",GE.Float,!0,0),this.registerInput("height",GE.Float,!0,0),this.registerInput("depth",GE.Float,!0,0),this.registerInput("subdivisions",GE.Int,!0,1),this.registerInput("subdivisionsX",GE.Int,!0,0),this.registerInput("subdivisionsY",GE.Int,!0,0),this.registerInput("subdivisionsZ",GE.Int,!0,0),this.registerOutput("geometry",GE.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 rP("Size");return e.value=1,void e.output.connectTo(this.size)}if(!this.width.isConnected){const e=new rP("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new rP("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){const e=new rP("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){const t={},i=e=>{t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.depth=this.depth.getConnectedValue(e);const i=this.subdivisions.getConnectedValue(e),r=this.subdivisionsX.getConnectedValue(e),s=this.subdivisionsY.getConnectedValue(e),n=this.subdivisionsZ.getConnectedValue(e);return i&&(t.segments=i),r&&(t.widthSegments=r),s&&(t.heightSegments=s),n&&(t.depthSegments=n),Yo(t)};if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],sP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.BoxBlock",sP);class nP{_getGlobalNodeGeometryEditor(){return"undefined"!=typeof NODEGEOMETRYEDITOR?NODEGEOMETRYEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeGeometryEditor?BABYLON:void 0}get buildExecutionTime(){return this._buildExecutionTime}constructor(e){this._buildId=nP._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new z.cP,this.outputBlock=null,this.name=e}getClassName(){return"NodeGeometry"}get vertexData(){return this._vertexData}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e){if(t)return Ue.S0.Warn("More than one block was found with the name `"+e+"`"),t;t=i}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(),void 0===this.BJSNODEGEOMETRYEDITOR){const i=e&&e.editorURL?e.editorURL:nP.EditorURL;Ue.S0.LoadBabylonScript(i,(()=>{this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),this._createNodeEditor(e?.nodeGeometryEditorConfig),t()}))}else this._createNodeEditor(e?.nodeGeometryEditorConfig),t()}))}_createNodeEditor(e){const t={nodeGeometry:this,...e};this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(t)}build(e=!1,t=!0,i=!1){if(this._buildWasSuccessful=!1,!this.outputBlock)throw"You must define the outputBlock property before building the geometry";const r=ai.j.Now;this._initializeBlock(this.outputBlock,i);const s=[];for(const e of this.attachedBlocks)e._isReadyState&&s.push(e._isReadyState);if(s.length)return void Promise.all(s).then((()=>{this.build(e,t,i)}));const n=new iP;n.buildId=this._buildId,n.verbose=e;try{this.outputBlock.build(n)}finally{t&&(this._buildId=nP._BuildIdGenerator++)}this._buildExecutionTime=ai.j.Now-r,n.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=n.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;const i=new Yt(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)}_initializeBlock(e,t=!0){e.initialize(),t&&e.autoConfigure(),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)&&this.attachedBlocks.push(e);for(const i of e.inputs){const r=i.connectedPoint;if(r){const i=r.ownerBlock;i!==e&&this._initializeBlock(i,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 t of e.blocks){const e=(0,X.n9)(t.customType);if(e){const r=new e;r._deserialize(t),i[t.id]=r,this.attachedBlocks.push(r)}}for(const e of this.attachedBlocks)if(e.isTeleportOut){const t=e,r=t._tempEntryPointUniqueId;if(r){const e=i[r];e&&e.attachToEndpoint(t)}}for(let r=0;re.targetConnectionName))&&!t||this._restoreConnections(n,e,i))}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){const r=e.locations||e.editorData.locations;for(const e of r)i[e.blockId]&&(e.blockId=i[e.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&r.concat(this.editorData.locations),e.locations?this.editorData={locations:r}:(this.editorData=e.editorData,this.editorData.locations=r);const s=[];for(const e in i)s[e]=i[e].uniqueId;this.editorData.map=s}this.comment=e.comment}_restoreConnections(e,t,i){for(const r of e.outputs)for(const s of t.blocks){const n=i[s.id];if(n)for(const o of s.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==r.name);else{const e=n.getInputByName(o.inputName);if(!e||e.isConnected)continue;r.connectTo(e,!0),this._restoreConnections(n,t,i)}}}generateCode(){let e=[];const t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);let r=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}");\n`;for(const s of t)s.isInput&&-1===e.indexOf(s)&&(r+=s._dumpCode(i,e));return this.outputBlock&&(e=[],r+="// Connections\n",r+=this.outputBlock._dumpCodeForOutputConnections(e),r+="// Output nodes\n",r+=`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName};\n`,r+="nodeGeometry.build();\n"),r}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const r=i.connectedPoint;if(r){const i=r.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}setToDefault(){this.clear(),this.editorData=null;const e=new sP("Box");e.autoConfigure();const t=new tP("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){const t=this.serialize(),i=it.p.Clone((()=>new nP(e)),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){const t=e?{}:it.p.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 e of i)t.blocks.push(e.serialize());if(!e)for(const e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.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 nP(e);return t.setToDefault(),t.build(),t}static Parse(e){const t=it.p.Parse((()=>new nP(e.name)),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return"_BLANK"===e?Promise.resolve(nP.CreateDefault("blank")):new Promise(((r,s)=>{const n=new go.u;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const o=JSON.parse(JSON.parse(n.responseText).jsonPayload),a=JSON.parse(o.nodeGeometry);t||(t=it.p.Parse((()=>new nP(e)),a,null)),t.parseSerializedObject(a),t.snippetId=e;try{i||t.build(),r(t)}catch(e){s(e)}}else s("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}nP._BuildIdGenerator=0,nP.EditorURL=`${Ue.S0._DefaultCdnUrl}/v${Ot.$.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`,nP.SnippetUrl="https://snippet.babylonjs.com",(0,je.Cg)([(0,$e.lK)()],nP.prototype,"name",void 0),(0,je.Cg)([(0,$e.lK)("comment")],nP.prototype,"comment",void 0);class oP extends eP{getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}constructor(e){super(e),this.evaluateContext=!0,this.epsilon=lt.bH,this.optimizeFaces=!1,this.registerInput("geometry",GE.Geometry),this.registerInput("selector",GE.Int,!0),this.registerOutput("output",GE.Geometry)}getClassName(){return"GeometryOptimizeBlock"}get geometry(){return this._inputs[0]}get selector(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(!this.geometry.isConnected)return null;const t=this.geometry.getConnectedValue(e),i=[],r={};e.pushExecutionContext(this),e.pushGeometryContext(t);for(let s=0;sr[e])),o=[];if(this.optimizeFaces){for(let e=0;e{t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e);const i=this.subdivisions.getConnectedValue(e),r=this.subdivisionsX.getConnectedValue(e),s=this.subdivisionsY.getConnectedValue(e);i&&(t.subdivisions=i),r&&(t.subdivisionsX=r),s&&(t.subdivisionsY=s);const n=Jn(t);return W.uq.RotationYawPitchRollToRef(-Math.PI/2,0,Math.PI/2,this._rotationMatrix),n.transform(this._rotationMatrix),n};if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],aP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.PlaneBlock",aP);class lP extends eP{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",GE.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)return void(this._cachedVertexData?this.geometry._storedValue=this._cachedVertexData.clone():this.geometry._storedValue=null);const e=bt.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=bt.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=bt.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}}(0,je.Cg)([t_("Serialize cached data",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],lP.prototype,"serializedCachedData",void 0),(0,X.Y5)("BABYLON.MeshBlock",lP);class hP extends eP{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",GE.Float,!0,1),this.registerInput("radiusX",GE.Float,!0,0),this.registerInput("radiusY",GE.Float,!0,0),this.registerInput("radiusZ",GE.Float,!0,0),this.registerInput("subdivisions",GE.Int,!0,4),this.registerOutput("geometry",GE.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 rP("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.radiusX=this.radiusX.getConnectedValue(e),t.radiusY=this.radiusY.getConnectedValue(e),t.radiusZ=this.radiusZ.getConnectedValue(e),$a(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],hP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.IcoSphereBlock",hP);class cP extends eP{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",GE.Int,!0,32),this.registerInput("diameter",GE.Float,!0,1),this.registerInput("diameterX",GE.Float,!0,0),this.registerInput("diameterY",GE.Float,!0,0),this.registerInput("diameterZ",GE.Float,!0,0),this.registerInput("arc",GE.Float,!0,1),this.registerInput("slice",GE.Float,!0,1),this.registerOutput("geometry",GE.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 rP("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=e=>(t.segments=this.segments.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterX=this.diameterX.getConnectedValue(e),t.diameterY=this.diameterY.getConnectedValue(e),t.diameterZ=this.diameterZ.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),t.slice=this.slice.getConnectedValue(e),$o(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],cP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.SphereBlock",cP);class uP extends eP{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",GE.Float,!0,1),this.registerInput("height",GE.Float,!0,1),this.registerInput("subdivisions",GE.Int,!0,1),this.registerInput("subdivisionsX",GE.Int,!0,0),this.registerInput("subdivisionsY",GE.Int,!0,0),this.registerOutput("geometry",GE.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 rP("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new rP("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=e=>(t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.subdivisionsX=this.subdivisionsX.getConnectedValue(e),t.subdivisionsY=this.subdivisionsY.getConnectedValue(e),Jn(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],uP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.GridBlock",uP);class dP extends eP{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",GE.Float,!0,1),this.registerInput("thickness",GE.Float,!0,.5),this.registerInput("tessellation",GE.Int,!0,16),this.registerOutput("geometry",GE.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 rP("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=e=>(t.thickness=this.thickness.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),oo(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],dP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.TorusBlock",dP);class fP extends eP{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",GE.Float,!0,25),this.registerInput("diameter",GE.Float,!0,1),this.registerInput("diameterTop",GE.Float,!0,-1),this.registerInput("diameterBottom",GE.Float,!0,-1),this.registerInput("subdivisions",GE.Int,!0,1),this.registerInput("tessellation",GE.Int,!0,24),this.registerInput("arc",GE.Float,!0,1),this.registerOutput("geometry",GE.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 rP("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){const e=new rP("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=e=>(t.height=this.height.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterTop=this.diameterTop.getConnectedValue(e),t.diameterBottom=this.diameterBottom.getConnectedValue(e),-1===t.diameterTop&&(t.diameterTop=t.diameter),-1===t.diameterBottom&&(t.diameterBottom=t.diameter),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),wo(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],fP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.CylinderBlock",fP);class pP extends eP{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",GE.Float,!0,1),this.registerInput("radius",GE.Float,!0,.25),this.registerInput("tessellation",GE.Int,!0,16),this.registerInput("subdivisions",GE.Int,!0,2),this.registerOutput("geometry",GE.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 rP("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){const e=new rP("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.height=this.height.getConnectedValue(e),t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),na(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],pP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.CapsuleBlock",pP);class _P extends eP{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",GE.Float,!0,.5),this.registerInput("tessellation",GE.Int,!0,64),this.registerInput("arc",GE.Float,!0,1),this.registerOutput("geometry",GE.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 rP("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),ua(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],_P.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.DiscBlock",_P);class mP extends eP{constructor(e){super(e),this.registerOutput("geometry",GE.Geometry),this.registerOutput("vector",GE.Vector3)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}get vector(){return this._outputs[1]}_buildBlock(){this.geometry._storedValue=null,this.vector._storedValue=null}}(0,X.Y5)("BABYLON.NullBlock",mP);class gP extends eP{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",GE.Geometry),this.registerInput("positions",GE.Vector3),this.registerOutput("output",GE.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]}_remapVector3Data(e,t){const i=[];for(let r=0;r{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.positions.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);const t={},i=this._vertexData.positions.length/3,r=[];let s=0,n=!1;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.normals.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.normals||(this._vertexData.normals=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.uvs.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);const t=[],i=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.colors.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.colors||(this._vertexData.colors=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.tangents.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.tangents||(this._vertexData.tangents=[]);const t=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)return this.output._storedFunction=null,void(this.output._storedValue=null);const r=t.type===GE.Float||t.type===GE.Int,s=i.type===GE.Float||i.type===GE.Int,n=r&&s;switch(this.operation){case XE.Add:e=n?e=>t.getConnectedValue(e)+i.getConnectedValue(e):r?e=>e.adapt(t,i.type).add(i.getConnectedValue(e)):e=>t.getConnectedValue(e).add(e.adapt(i,t.type));break;case XE.Subtract:e=n?e=>t.getConnectedValue(e)-i.getConnectedValue(e):r?e=>e.adapt(t,i.type).subtract(i.getConnectedValue(e)):e=>t.getConnectedValue(e).subtract(e.adapt(i,t.type));break;case XE.Multiply:e=n?e=>t.getConnectedValue(e)*i.getConnectedValue(e):r?e=>e.adapt(t,i.type).multiply(i.getConnectedValue(e)):e=>t.getConnectedValue(e).multiply(e.adapt(i,t.type));break;case XE.Divide:e=n?e=>t.getConnectedValue(e)/i.getConnectedValue(e):r?e=>e.adapt(t,i.type).divide(i.getConnectedValue(e)):e=>t.getConnectedValue(e).divide(e.adapt(i,t.type));break;case XE.Min:if(n)e=e=>Math.min(t.getConnectedValue(e),i.getConnectedValue(e));else{const[s,n]=r?[i,t]:[t,i];switch(s.type){case GE.Vector2:e=e=>W.I9.Minimize(s.getConnectedValue(e),e.adapt(n,s.type));break;case GE.Vector3:e=e=>W.Pq.Minimize(s.getConnectedValue(e),e.adapt(n,s.type));break;case GE.Vector4:e=e=>W.IU.Minimize(s.getConnectedValue(e),e.adapt(n,s.type))}}break;case XE.Max:if(!n){const[s,n]=r?[i,t]:[t,i];switch(s.type){case GE.Vector2:e=e=>W.I9.Maximize(s.getConnectedValue(e),e.adapt(n,s.type));break;case GE.Vector3:e=e=>W.Pq.Maximize(s.getConnectedValue(e),e.adapt(n,s.type));break;case GE.Vector4:e=e=>W.IU.Maximize(s.getConnectedValue(e),e.adapt(n,s.type))}break}e=e=>Math.max(t.getConnectedValue(e),i.getConnectedValue(e))}this.output._storedFunction=i=>t.type===GE.Int?0|e(i):e(i)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${XE[this.operation]};\n`}_updateInputOutputTypes(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===GE.Int||this.left.type===GE.Float&&this.right.type!==GE.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=[GE.Int,GE.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),t.type!==GE.Int&&t.type!==GE.Float||e.acceptedConnectionPointTypes.push(GE.Vector2,GE.Vector3,GE.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}}(0,je.Cg)([t_("Operation",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"Add",value:XE.Add},{label:"Subtract",value:XE.Subtract},{label:"Multiply",value:XE.Multiply},{label:"Divide",value:XE.Divide},{label:"Max",value:XE.Max},{label:"Min",value:XE.Min}]})],TP.prototype,"operation",void 0),(0,X.Y5)("BABYLON.MathBlock",TP);class CP extends eP{constructor(e){super(e),this.registerInput("value",GE.AutoDetect),this.registerInput("fromMin",GE.Float,!0,0),this.registerInput("fromMax",GE.Float,!0,1),this.registerInput("toMin",GE.Float,!0,0),this.registerInput("toMax",GE.Float,!0,1),this.registerOutput("output",GE.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(GE.Vector2),this._inputs[0].excludedConnectionPointTypes.push(GE.Vector3),this._inputs[0].excludedConnectionPointTypes.push(GE.Vector4),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.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)return this.output._storedFunction=null,void(this.output._storedValue=null);this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.fromMin.getConnectedValue(e),r=this.fromMax.getConnectedValue(e),s=this.toMin.getConnectedValue(e),n=(t-i)/(r-i)*(this.toMax.getConnectedValue(e)-s)+s;return this.output.type===GE.Int?Math.floor(n):n}}}(0,X.Y5)("BABYLON.MapRangeBlock",CP),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(qE||(qE={}));class yP extends eP{constructor(e){super(e),this.test=qE.Equal,this.registerInput("left",GE.Float),this.registerInput("right",GE.Float,!0,0),this.registerInput("ifTrue",GE.AutoDetect,!0,1),this.registerInput("ifFalse",GE.AutoDetect,!0,0),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=GE.Float,this._inputs[0].acceptedConnectionPointTypes.push(GE.Int),this._inputs[1].acceptedConnectionPointTypes.push(GE.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)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);let r=!1;switch(this.test){case qE.Equal:r=(0,ar.WithinEpsilon)(t,i,lt.bH);break;case qE.NotEqual:r=t!==i;break;case qE.LessThan:r=ti;break;case qE.LessOrEqual:r=t<=i;break;case qE.GreaterOrEqual:r=t>=i;break;case qE.Xor:r=!!t&&!i||!t&&!!i;break;case qE.Or:r=!!t||!!i;break;case qE.And:r=!!t&&!!i}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.${qE[this.test]};\n`}serialize(){const e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}}(0,je.Cg)([t_("Test",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"Equal",value:qE.Equal},{label:"NotEqual",value:qE.NotEqual},{label:"LessThan",value:qE.LessThan},{label:"GreaterThan",value:qE.GreaterThan},{label:"LessOrEqual",value:qE.LessOrEqual},{label:"GreaterOrEqual",value:qE.GreaterOrEqual},{label:"Xor",value:qE.Xor},{label:"Or",value:qE.Or},{label:"And",value:qE.And}]})],yP.prototype,"test",void 0),(0,X.Y5)("BABYLON.ConditionBlock",yP),function(e){e[e.None=0]="None",e[e.LoopID=1]="LoopID",e[e.InstanceID=2]="InstanceID",e[e.Once=3]="Once"}(YE||(YE={}));class EP extends eP{constructor(e){super(e),this._currentLockId=-1,this.lockMode=YE.None,this.registerInput("min",GE.AutoDetect),this.registerInput("max",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.Texture),this._inputs[1].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[1].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[1].excludedConnectionPointTypes.push(GE.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 rP("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){const e=new rP("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case GE.Int:case GE.Float:e=e=>{const t=this.min.getConnectedValue(e)||0,i=this.max.getConnectedValue(e)||0;return t+Math.random()*(i-t)};break;case GE.Vector2:e=e=>{const t=this.min.getConnectedValue(e)||W.I9.Zero(),i=this.max.getConnectedValue(e)||W.I9.Zero();return new W.I9(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y))};break;case GE.Vector3:e=e=>{const t=this.min.getConnectedValue(e)||W.Pq.Zero(),i=this.max.getConnectedValue(e)||W.Pq.Zero();return new W.Pq(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z))};break;case GE.Vector4:e=e=>{const t=this.min.getConnectedValue(e)||W.IU.Zero(),i=this.max.getConnectedValue(e)||W.IU.Zero();return new W.IU(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z),t.w+Math.random()*(i.w-t.w))}}this.lockMode!==YE.None&&e?this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case YE.InstanceID:i=t.getContextualValue(HE.InstanceID,!0)||0;break;case YE.LoopID:i=t.getContextualValue(HE.LoopID,!0)||0;break;case YE.Once:i=t.buildId||0}return this._currentLockId===i&&this.lockMode!==YE.None||(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}:this.output._storedFunction=e}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${YE[this.lockMode]};\n`}serialize(){const e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}}(0,je.Cg)([t_("LockMode",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"None",value:YE.None},{label:"LoopID",value:YE.LoopID},{label:"InstanceID",value:YE.InstanceID},{label:"Once",value:YE.Once}]})],EP.prototype,"lockMode",void 0),(0,X.Y5)("BABYLON.RandomBlock",EP);class PP extends eP{constructor(e){super(e),this.registerInput("offset",GE.Vector3,!0,W.Pq.Zero()),this.registerInput("scale",GE.Float,!0,1),this.registerInput("octaves",GE.Float,!0,2,0,16),this.registerInput("roughness",GE.Float,!0,.5,0,1),this.registerOutput("output",GE.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 0!==t?-e:e}_noiseGrad(e,t,i,r){const s=15&e,n=s<8?t:i,o=s<4?i:12===s||14==s?t:r;return this._negateIf(n,s&n)+this._negateIf(o,2&s)}_fade(e){return e*e*e*(e*(6*e-15)+10)}_hashBitRotate(e,t){return e<>32-t}_hash(e,t,i){let r,s,n;return r=s=n=3735928584,n+=i,s+=t,r+=e,n^=s,n-=this._hashBitRotate(s,14),r^=n,r-=this._hashBitRotate(n,11),s^=r,s-=this._hashBitRotate(r,25),n^=s,n-=this._hashBitRotate(s,16),r^=n,r-=this._hashBitRotate(n,4),s^=r,s-=this._hashBitRotate(r,14),n^=s,n-=this._hashBitRotate(s,24),n}_mix(e,t,i,r,s,n,o,a,l,h,c){const u=1-l,d=1-h;return(1-c)*(d*(e*u+t*l)+h*(i*u+r*l))+c*(d*(s*u+n*l)+h*(o*u+a*l))}_perlinNoise(e){const t=(0|e.x)-(e.x<0?1:0),i=(0|e.y)-(e.y<0?1:0),r=(0|e.z)-(e.z<0?1:0),s=e.x-t,n=e.y-i,o=e.z-r,a=this._fade(s),l=this._fade(n),h=this._fade(o);return this._mix(this._noiseGrad(this._hash(t,i,r),s,n,o),this._noiseGrad(this._hash(t+1,i,r),s-1,n,o),this._noiseGrad(this._hash(t,i+1,r),s,n-1,o),this._noiseGrad(this._hash(t+1,i+1,r),s-1,n-1,o),this._noiseGrad(this._hash(t,i,r+1),s,n,o-1),this._noiseGrad(this._hash(t+1,i,r+1),s-1,n,o-1),this._noiseGrad(this._hash(t,i+1,r+1),s,n-1,o-1),this._noiseGrad(this._hash(t+1,i+1,r+1),s-1,n-1,o-1),a,l,h)}_perlinSigned(e){return.982*this._perlinNoise(e)}_perlin(e){return this._perlinSigned(e)/2+.5}noise(e,t,i,r,s){const n=new W.Pq(i.x*s+r.x,i.y*s+r.y,i.z*s+r.z);let o=1,a=1,l=0,h=0;const c=0|(e=(0,ar.Clamp)(e,0,15));for(let e=0;e<=c;e++)h+=this._perlin(n.scale(o))*a,l+=a,a*=(0,ar.Clamp)(t,0,1),o*=2;const u=e-Math.floor(e);if(0==u)return h/l;let d=h+this._perlin(n.scale(o))*a;return h/=l,d/=l+a,(1-u)*h+u*d}_buildBlock(){this.output._storedFunction=e=>{const t=e.getContextualValue(HE.Positions),i=this.octaves.getConnectedValue(e),r=this.roughness.getConnectedValue(e),s=this.offset.getConnectedValue(e),n=this.scale.getConnectedValue(e);return this.noise(i,r,t,s,n)}}}(0,X.Y5)("BABYLON.NoiseBlock",PP);class AP extends eP{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",GE.Geometry),this.registerInput("geometry1",GE.Geometry,!0),this.registerInput("geometry2",GE.Geometry,!0),this.registerInput("geometry3",GE.Geometry,!0),this.registerInput("geometry4",GE.Geometry,!0),this.registerOutput("output",GE.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=e=>{const t=[];if(this.geometry0.isConnected){const i=this.geometry0.getConnectedValue(e);i&&t.push(i)}if(this.geometry1.isConnected){const i=this.geometry1.getConnectedValue(e);i&&t.push(i)}if(this.geometry2.isConnected){const i=this.geometry2.getConnectedValue(e);i&&t.push(i)}if(this.geometry3.isConnected){const i=this.geometry3.getConnectedValue(e);i&&t.push(i)}if(this.geometry4.isConnected){const i=this.geometry4.getConnectedValue(e);i&&t.push(i)}if(0===t.length)return null;let i=t[0].clone();const r=t.slice(1);return r.length&&i&&(i=i.merge(r,!0,!1,!0,!0)),i};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"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],AP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.MergeGeometryBlock",AP);class RP extends eP{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",GE.Geometry,!0),this.registerInput("geometry1",GE.Geometry,!0),this.registerInput("geometry2",GE.Geometry,!0),this.registerInput("geometry3",GE.Geometry,!0),this.registerInput("geometry4",GE.Geometry,!0),this.registerInput("geometry5",GE.Geometry,!0),this.registerInput("geometry6",GE.Geometry,!0),this.registerInput("geometry7",GE.Geometry,!0),this.registerInput("geometry8",GE.Geometry,!0),this.registerInput("geometry9",GE.Geometry,!0),this.registerOutput("output",GE.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"GeometryCollectionBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get geometry5(){return this._inputs[5]}get geometry6(){return this._inputs[6]}get geometry7(){return this._inputs[7]}get geometry8(){return this._inputs[8]}get geometry9(){return this._inputs[9]}get output(){return this._outputs[0]}_storeGeometry(e,t,i,r){if(e.isConnected){const s=e.getConnectedValue(t);if(!s)return;s.metadata=s.metadata||{},s.metadata.collectionId=i,r.push(s)}}_buildBlock(e){const t=e=>{const t=[];return this._storeGeometry(this.geometry0,e,0,t),this._storeGeometry(this.geometry1,e,1,t),this._storeGeometry(this.geometry2,e,2,t),this._storeGeometry(this.geometry3,e,3,t),this._storeGeometry(this.geometry4,e,4,t),this._storeGeometry(this.geometry5,e,5,t),this._storeGeometry(this.geometry6,e,6,t),this._storeGeometry(this.geometry7,e,7,t),this._storeGeometry(this.geometry8,e,8,t),this._storeGeometry(this.geometry9,e,9,t),t.length?t[Math.round(Math.random()*(t.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"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],RP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.GeometryCollectionBlock",RP);class IP extends eP{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",GE.Geometry),this.registerOutput("output",GE.Geometry)}getClassName(){return"CleanGeometryBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(!this.geometry.isConnected)return null;const t=this.geometry.getConnectedValue(e).clone();if(!t.positions||!t.indices||!t.normals)return t;const i=t.indices,r=t.positions;return(0,mt.Y4)(r,i),t};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"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],IP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.CleanGeometryBlock",IP);class MP extends eP{constructor(e){super(e),this.registerInput("input",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}get buildExecutionTime(){return-1}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=e=>i.getConnectedValue(e)}}(0,X.Y5)("BABYLON.GeometryElbowBlock",MP);class OP extends eP{constructor(e){super(e),this.registerInput("geometry",GE.Geometry),this.registerOutput("output",GE.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=[]),bt.ComputeNormals(t.positions,t.indices,t.normals),t}}}(0,X.Y5)("BABYLON.ComputeNormalsBlock",OP);class DP extends eP{constructor(e){super(e),this.registerInput("xyzw ",GE.Vector4,!0),this.registerInput("xyz ",GE.Vector3,!0),this.registerInput("xy ",GE.Vector2,!0),this.registerInput("zw ",GE.Vector2,!0),this.registerInput("x ",GE.Float,!0),this.registerInput("y ",GE.Float,!0),this.registerInput("z ",GE.Float,!0),this.registerInput("w ",GE.Float,!0),this.registerOutput("xyzw",GE.Vector4),this.registerOutput("xyz",GE.Vector3),this.registerOutput("xy",GE.Vector2),this.registerOutput("zw",GE.Vector2),this.registerOutput("x",GE.Float),this.registerOutput("y",GE.Float),this.registerOutput("z",GE.Float),this.registerOutput("w",GE.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"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":"x "===e?"xIn":"y "===e?"yIn":"z "===e?"zIn":"w "===e?"wIn":e}_outputRename(e){switch(e){case"x":return"xOut";case"y":return"yOut";case"z":return"zOut";case"w":return"wOut";case"xy":return"xyOut";case"zw":return"zwOut";case"xyz":return"xyzOut";case"xyzw":return"xyzwOut";default:return e}}_buildBlock(e){super._buildBlock(e);const t=this.xIn,i=this.yIn,r=this.zIn,s=this.wIn,n=this.xyIn,o=this.zwIn,a=this.xyzIn,l=this.xyzwIn,h=this.xyzwOut,c=this.xyzOut,u=this.xyOut,d=this.zwOut,f=this.xOut,p=this.yOut,_=this.zOut,m=this.wOut,g=e=>{if(l.isConnected)return l.getConnectedValue(e);let h=0,c=0,u=0,d=0;if(t.isConnected&&(h=t.getConnectedValue(e)),i.isConnected&&(c=i.getConnectedValue(e)),r.isConnected&&(u=r.getConnectedValue(e)),s.isConnected&&(d=s.getConnectedValue(e)),n.isConnected){const t=n.getConnectedValue(e);t&&(h=t.x,c=t.y)}if(o.isConnected){const t=o.getConnectedValue(e);t&&(u=t.x,d=t.y)}if(a.isConnected){const t=a.getConnectedValue(e);t&&(h=t.x,c=t.y,u=t.z)}return new W.IU(h,c,u,d)};h._storedFunction=e=>g(e),c._storedFunction=e=>{const t=g(e);return new W.Pq(t.x,t.y,t.z)},u._storedFunction=e=>{const t=g(e);return new W.I9(t.x,t.y)},d._storedFunction=e=>{const t=g(e);return new W.I9(t.z,t.w)},f._storedFunction=e=>g(e).x,p._storedFunction=e=>g(e).y,_._storedFunction=e=>g(e).z,m._storedFunction=e=>g(e).w}}(0,X.Y5)("BABYLON.VectorConverterBlock",DP);class wP extends eP{constructor(e){super(e),this.registerInput("input",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(GE.Float),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.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){super._buildBlock(e),this.output._storedFunction=null,this.input.isConnected?this.output._storedFunction=e=>this.input.getConnectedValue(e).normalize():this.output._storedValue=null}}(0,X.Y5)("BABYLON.NormalizeVectorBlock",wP);class NP extends eP{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",GE.Geometry),this.registerInput("id",GE.Int,!0,0),this.registerOutput("output",GE.Geometry),this.id.acceptedConnectionPointTypes.push(GE.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)return this.output._storedFunction=null,void(this.output._storedValue=null);const t=e=>{const t=this.geometry.getConnectedValue(e);if(!t||!t.indices||!t.positions)return t;const i=new xt;return i.materialIndex=0|this.id.getConnectedValue(e),i.indexStart=0,i.indexCount=t.indices.length,i.verticesStart=0,i.verticesCount=t.positions.length/3,t.materialInfos=[i],t};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"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],NP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.SetMaterialIDBlock",NP);class FP extends eP{constructor(e){super(e),this._indexVector3=new W.Pq,this._currentControl=new W.Pq,this.evaluateContext=!0,this.resolutionX=3,this.resolutionY=3,this.resolutionZ=3,this.registerInput("geometry",GE.Geometry),this.registerInput("controls",GE.Vector3),this.registerOutput("output",GE.Geometry)}getExecutionIndex(){return this._currentIndexX+this.resolutionX*(this._currentIndexY+this.resolutionY*this._currentIndexZ)}getExecutionLoopIndex(){return this.getExecutionIndex()}getExecutionFaceIndex(){return 0}getClassName(){return"LatticeBlock"}get geometry(){return this._inputs[0]}get controls(){return this._inputs[1]}get output(){return this._outputs[0]}getOverridePositionsContextualValue(){return this._indexVector3}getOverrideNormalsContextualValue(){return this._currentControl}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),!this._vertexData||!this._vertexData.positions)return e.restoreExecutionContext(),void(this.output._storedValue=null);const t=this._vertexData.positions,i=(0,mt.b8)(t,0,t.length/3);for(this._lattice=new yE({resolutionX:this.resolutionX,resolutionY:this.resolutionY,resolutionZ:this.resolutionZ,size:i.maximum.subtract(i.minimum)}),this._currentIndexX=0;this._currentIndexXMath.cos(e);break;case KE.Sin:t=e=>Math.sin(e);break;case KE.Abs:t=e=>Math.abs(e);break;case KE.Exp:t=e=>Math.exp(e);break;case KE.Exp2:t=e=>Math.pow(2,e);break;case KE.Round:t=e=>Math.round(e);break;case KE.Floor:t=e=>Math.floor(e);break;case KE.Ceiling:t=e=>Math.ceil(e);break;case KE.Sqrt:t=e=>Math.sqrt(e);break;case KE.Log:t=e=>Math.log(e);break;case KE.Tan:t=e=>Math.tan(e);break;case KE.ArcTan:t=e=>Math.atan(e);break;case KE.ArcCos:t=e=>Math.acos(e);break;case KE.ArcSin:t=e=>Math.asin(e);break;case KE.Sign:t=e=>Math.sign(e);break;case KE.Negate:t=e=>-e;break;case KE.OneMinus:t=e=>1-e;break;case KE.Reciprocal:t=e=>1/e;break;case KE.ToRadians:t=e=>e*Math.PI/180;break;case KE.ToDegrees:t=e=>180*e/Math.PI;break;case KE.Fract:t=e=>e>=0?e-Math.floor(e):e-Math.ceil(e)}if(!t)return this.output._storedFunction=null,void(this.output._storedValue=null);switch(this.input.type){case GE.Int:case GE.Float:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return t(i)};break;case GE.Vector2:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new W.I9(t(i.x),t(i.y))};break;case GE.Vector3:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new W.Pq(t(i.x),t(i.y),t(i.z))};break;case GE.Vector4:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new W.IU(t(i.x),t(i.y),t(i.z),t(i.w))}}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.${KE[this.operation]};\n`}}(0,je.Cg)([t_("Operation",4,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0},options:[{label:"Cos",value:KE.Cos},{label:"Sin",value:KE.Sin},{label:"Abs",value:KE.Abs},{label:"Exp",value:KE.Exp},{label:"Exp2",value:KE.Exp2},{label:"Round",value:KE.Round},{label:"Floor",value:KE.Floor},{label:"Ceiling",value:KE.Ceiling},{label:"Sqrt",value:KE.Sqrt},{label:"Log",value:KE.Log},{label:"Tan",value:KE.Tan},{label:"ArcTan",value:KE.ArcTan},{label:"ArcCos",value:KE.ArcCos},{label:"ArcSin",value:KE.ArcSin},{label:"Sign",value:KE.Sign},{label:"Negate",value:KE.Negate},{label:"OneMinus",value:KE.OneMinus},{label:"Reciprocal",value:KE.Reciprocal},{label:"ToDegrees",value:KE.ToDegrees},{label:"ToRadians",value:KE.ToRadians},{label:"Fract",value:KE.Fract}]})],LP.prototype,"operation",void 0),(0,X.Y5)("BABYLON.GeometryTrigonometryBlock",LP);class BP extends eP{constructor(e){super(e),this._rotationMatrix=new W.uq,this._scalingMatrix=new W.uq,this._translationMatrix=new W.uq,this._scalingRotationMatrix=new W.uq,this._pivotMatrix=new W.uq,this._backPivotMatrix=new W.uq,this._transformMatrix=new W.uq,this.evaluateContext=!0,this.registerInput("value",GE.AutoDetect),this.registerInput("matrix",GE.Matrix,!0),this.registerInput("translation",GE.Vector3,!0,W.Pq.Zero()),this.registerInput("rotation",GE.Vector3,!0,W.Pq.Zero()),this.registerInput("scaling",GE.Vector3,!0,W.Pq.One()),this.registerInput("pivot",GE.Vector3,!0,W.Pq.Zero()),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(GE.Float),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.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 pivot(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const t=e=>{const t=this.value.getConnectedValue(e);if(!t)return null;let i;if(this.matrix.isConnected)i=this.matrix.getConnectedValue(e);else{const t=this.scaling.getConnectedValue(e)||W.Pq.OneReadOnly,r=this.rotation.getConnectedValue(e)||W.Pq.ZeroReadOnly,s=this.translation.getConnectedValue(e)||W.Pq.ZeroReadOnly,n=this.pivot.getConnectedValue(e)||W.Pq.ZeroReadOnly;W.uq.TranslationToRef(-n.x,-n.y,-n.z,this._pivotMatrix),W.uq.ScalingToRef(t.x,t.y,t.z,this._scalingMatrix),W.uq.RotationYawPitchRollToRef(r.y,r.x,r.z,this._rotationMatrix),W.uq.TranslationToRef(s.x+n.x,s.y+n.y,s.z+n.z,this._translationMatrix),this._pivotMatrix.multiplyToRef(this._scalingMatrix,this._backPivotMatrix),this._backPivotMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),i=this._transformMatrix}switch(this.value.type){case GE.Geometry:{const e=t.clone();return e.transform(i),e}case GE.Vector2:return W.I9.Transform(t,i);case GE.Vector3:return W.Pq.TransformCoordinates(t,i);case GE.Vector4:return W.IU.TransformCoordinates(t,i)}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"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],BP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.GeometryTransformBlock",BP);class VP extends eP{constructor(e){super(e),this.registerInput("angle",GE.Float,!1,0),this.registerOutput("matrix",GE.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new rP("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>W.uq.RotationX(this.angle.getConnectedValue(e))}}(0,X.Y5)("BABYLON.RotationXBlock",VP);class kP extends eP{constructor(e){super(e),this.registerInput("angle",GE.Float,!1,0),this.registerOutput("matrix",GE.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new rP("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>W.uq.RotationY(this.angle.getConnectedValue(e))}}(0,X.Y5)("BABYLON.RotationYBlock",kP);class UP extends eP{constructor(e){super(e),this.registerInput("angle",GE.Float,!1,0),this.registerOutput("matrix",GE.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new rP("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>W.uq.RotationZ(this.angle.getConnectedValue(e))}}(0,X.Y5)("BABYLON.RotationZBlock",UP);class GP extends eP{constructor(e){super(e),this.registerInput("scale",GE.Vector3,!1,W.Pq.One()),this.registerOutput("matrix",GE.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){const e=new rP("Scale");e.value=new W.Pq(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.scale.getConnectedValue(e);return W.uq.Scaling(t.x,t.y,t.z)}}}(0,X.Y5)("BABYLON.ScalingBlock",GP);class zP extends eP{constructor(e){super(e),this.registerInput("source",GE.Vector3,!0,W.Pq.Up()),this.registerInput("target",GE.Vector3,!0,W.Pq.Left()),this.registerOutput("matrix",GE.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=e=>{const t=this.source.getConnectedValue(e).clone(),i=this.target.getConnectedValue(e).clone(),r=new W.uq;return t.normalize(),i.normalize(),W.uq.RotationAlignToRef(t,i,r,!0),r}}}(0,X.Y5)("BABYLON.AlignBlock",zP);class WP extends eP{constructor(e){super(e),this.registerInput("translation",GE.Vector3,!1,W.Pq.Zero()),this.registerOutput("matrix",GE.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){const e=new rP("Translation");e.value=new W.Pq(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.translation.getConnectedValue(e);return W.uq.Translation(t.x,t.y,t.z)}}}(0,X.Y5)("BABYLON.TranslationBlock",WP);class HP extends eP{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",GE.Geometry),this.registerInput("instance",GE.Geometry,!0),this.registerInput("density",GE.Float,!0,1,0,1),this.registerInput("matrix",GE.Matrix,!0),this.registerInput("rotation",GE.Vector3,!0,W.Pq.Zero()),this.registerInput("scaling",GE.Vector3,!0,W.Pq.One()),this.scaling.acceptedConnectionPointTypes.push(GE.Float),this.registerOutput("output",GE.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=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.instance.isConnected)return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=this._vertexData.positions.length/3;const i=[],r=new W.Pq,s=[];let n=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndexs)continue;r.fromArray(n,3*this._currentIndex);const o=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(o,r,t,i)}else{const t=e.adaptInput(this.scaling,GE.Vector3,W.Pq.OneReadOnly),s=this.rotation.getConnectedValue(e)||W.Pq.ZeroReadOnly;e._instantiate(o,r,s,t,i)}this._currentLoopIndex++}if(e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),!i.length)return null;if(1===i.length)this._vertexData=i[0];else{const e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}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"};\n`;return e+=`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`,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,void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],HP.prototype,"evaluateContext",void 0),(0,je.Cg)([t_("Remove duplicated positions",0,"ADVANCED",{notifiers:{update:!0}})],HP.prototype,"removeDuplicatedPositions",void 0),(0,X.Y5)("BABYLON.InstantiateOnVerticesBlock",HP);class XP extends eP{constructor(e){super(e),this._currentPosition=new W.Pq,this._currentUV=new W.I9,this._vertex0=new W.Pq,this._vertex1=new W.Pq,this._vertex2=new W.Pq,this._tempVector0=new W.Pq,this._tempVector1=new W.Pq,this._uv0=new W.I9,this._uv1=new W.I9,this._uv2=new W.I9,this.evaluateContext=!0,this.registerInput("geometry",GE.Geometry),this.registerInput("instance",GE.Geometry,!0),this.registerInput("count",GE.Int,!0,256),this.registerInput("matrix",GE.Matrix,!0),this.registerInput("rotation",GE.Vector3,!0,W.Pq.Zero()),this.registerInput("scaling",GE.Vector3,!0,W.Pq.One()),this.scaling.acceptedConnectionPointTypes.push(GE.Float),this.registerOutput("output",GE.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(),W.Pq.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=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!(this._vertexData&&this._vertexData.positions&&this._vertexData.indices&&this.instance.isConnected))return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=null;const i=this.count.getConnectedValue(e),r=this._vertexData.indices.length/3,s=i/r;let n=0;const o=[];let a=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex=i);l++){let i=Math.random(),r=Math.random();if(i>r){const e=i;i=r,r=e}const l=i,h=r-i,c=1-l-h;if(this._currentPosition.set(l*this._vertex0.x+h*this._vertex1.x+c*this._vertex2.x,l*this._vertex0.y+h*this._vertex1.y+c*this._vertex2.y,l*this._vertex0.z+h*this._vertex1.z+c*this._vertex2.z),this._vertexData.uvs&&this._currentUV.set(l*this._uv0.x+h*this._uv1.x+c*this._uv2.x,l*this._uv0.y+h*this._uv1.y+c*this._uv2.y),t=this.instance.getConnectedValue(e),!t||!t.positions||0===t.positions.length){n-=s;continue}const u=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(u,this._currentPosition,t,o)}else{const t=e.adaptInput(this.scaling,GE.Vector3,W.Pq.OneReadOnly),i=this.rotation.getConnectedValue(e)||W.Pq.ZeroReadOnly;e._instantiate(u,this._currentPosition,i,t,o)}a++,this._currentLoopIndex++}}if(o.length)if(1===o.length)this._vertexData=o[0];else{const e=o.splice(0,1)[0];this._vertexData=e.merge(o,!0,!1,!0,!0)}return e.restoreExecutionContext(),e.restoreInstancingContext(),e.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"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],XP.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.InstantiateOnFacesBlock",XP);class qP extends eP{constructor(e){super(e),this._currentPosition=new W.Pq,this._vertex0=new W.Pq,this._vertex1=new W.Pq,this._vertex2=new W.Pq,this.evaluateContext=!0,this.gridMode=!1,this.registerInput("geometry",GE.Geometry),this.registerInput("instance",GE.Geometry,!0),this.registerInput("count",GE.Int,!0,256),this.registerInput("matrix",GE.Matrix,!0),this.registerInput("rotation",GE.Vector3,!0,W.Pq.Zero()),this.registerInput("scaling",GE.Vector3,!0,W.Pq.One()),this.registerInput("gridSize",GE.Int,!0,10),this.scaling.acceptedConnectionPointTypes.push(GE.Float),this.registerOutput("output",GE.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return 0}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getClassName(){return"InstantiateOnVolumeBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get gridSize(){return this._inputs[6]}get output(){return this._outputs[0]}_getValueOnGrid(e,t,i,r){const s=(r-i)/t;return i+s/2+e*s}_getIndexinGrid(e,t,i,r){return e+t*r+i*r*r}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!(this._vertexData&&this._vertexData.positions&&this._vertexData.indices&&this.instance.isConnected))return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=null;const i=this.count.getConnectedValue(e),r=[],s=(0,mt.b8)(this._vertexData.positions,0,this._vertexData.positions.length/3),n=s.minimum,o=s.maximum,a=new W.Pq(.5,.8,.2),l=this._vertexData.indices.length/3,h=this.gridSize.getConnectedValue(e);let c;if(this._currentLoopIndex=0,this.gridMode){c=[];for(let e=0;e0&&u++}if(u%2==0){s--;continue}if(t=this.instance.getConnectedValue(e),!t||!t.positions||0===t.positions.length)continue;const d=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(d,this._currentPosition,t,r)}else{const t=e.adaptInput(this.scaling,GE.Vector3,W.Pq.OneReadOnly),i=this.rotation.getConnectedValue(e)||W.Pq.ZeroReadOnly;e._instantiate(d,this._currentPosition,i,t,r)}this._currentLoopIndex++}if(r.length)if(1===r.length)this._vertexData=r[0];else{const e=r.splice(0,1)[0];this._vertexData=e.merge(r,!0,!1,!0,!0)}return e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`;return e+=`${this._codeVariableName}.gridMode = ${this.gridMode?"true":"false"};\n`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.gridMode=this.gridMode,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext),void 0!==e.gridMode&&(this.gridMode=e.gridMode)}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],qP.prototype,"evaluateContext",void 0),(0,je.Cg)([t_("Grid mode",0,"MODES",{notifiers:{rebuild:!0}})],qP.prototype,"gridMode",void 0),(0,X.Y5)("BABYLON.InstantiateOnVolumeBlock",qP);class YP extends eP{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",GE.Geometry,!0),this.registerInput("count",GE.Int,!0,1),this.registerOutput("output",GE.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"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],YP.prototype,"evaluateContext",void 0);class KP extends YP{constructor(e){super(e),this.registerInput("matrix",GE.Matrix,!0),this.registerInput("position",GE.Vector3,!0,W.Pq.Zero()),this.registerInput("rotation",GE.Vector3,!0,W.Pq.Zero()),this.registerInput("scaling",GE.Vector3,!0,W.Pq.One()),this.scaling.acceptedConnectionPointTypes.push(GE.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=e=>{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[];for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[],r=W.uq.Identity(),s=W.Pq.Zero(),n=W.Pq.Zero(),o=W.Pq.Zero();for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[],r=W.uq.Identity(),s=W.uq.Identity(),n=W.uq.Identity(),o=W.Pq.Zero(),a=W.Pq.Zero(),l=W.Pq.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}}(0,X.Y5)("BABYLON.IntFloatConverterBlock",QP);class ZP extends eP{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.Texture)}get buildExecutionTime(){return-1}getClassName(){return"DebugBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.input.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);this.log=[];const t=e=>{const t=this.input.getConnectedValue(e);if(null==t)return this.log.push(["null",""]),t;switch(this.input.type){case GE.Vector2:this.log.push([Hy(t,4),t.toString()]);break;case GE.Vector3:this.log.push([Xy(t,4),t.toString()]);break;case GE.Vector4:this.log.push([qy(t,4),t.toString()]);break;default:this.log.push([t.toString(),t.toString()])}return t};this.output.isConnected?this.output._storedFunction=t:this.output._storedValue=t(e)}}(0,X.Y5)("BABYLON.DebugBlock",ZP);class JP extends eP{constructor(e){super(e),this.registerInput("geometry",GE.Geometry),this.registerOutput("output",GE.Geometry),this.registerOutput("id",GE.Int),this.registerOutput("collectionId",GE.Int),this.registerOutput("verticesCount",GE.Int),this.registerOutput("facesCount",GE.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)return 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,void(this.output._storedFunction=null);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)}}(0,X.Y5)("BABYLON.GeometryInfoBlock",JP),function(e){e[e.Spherical=0]="Spherical",e[e.Cylindrical=1]="Cylindrical",e[e.Cubic=2]="Cubic"}(jE||(jE={}));class eA extends eP{constructor(e){super(e),this.mapping=jE.Spherical,this.registerInput("position",GE.Vector3),this.registerInput("normal",GE.Vector3),this.registerInput("center",GE.Vector3,!0,W.Pq.Zero()),this.registerOutput("uv",GE.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)return this.uv._storedFunction=null,void(this.uv._storedValue=null);const e=W.Pq.Zero(),t=t=>{const i=this.position.getConnectedValue(t)||W.Pq.Zero(),r=this.normal.getConnectedValue(t)||W.Pq.Zero(),s=this.center.getConnectedValue(t),n=W.I9.Zero();switch(this.mapping){case jE.Spherical:{i.subtractToRef(s,e);const t=e.length();t>0&&(n.x=Math.acos(e.y/t)/Math.PI,0===e.x&&0===e.z||(n.y=Math.atan2(e.x,e.z)/(2*Math.PI)));break}case jE.Cylindrical:{i.subtractToRef(s,e);const t=e.length();t>0&&(n.x=Math.atan2(e.x/t,e.z/t)/(2*Math.PI),n.y=(e.y+1)/2);break}case jE.Cubic:{const e=Math.abs(r.x),t=Math.abs(r.y),o=Math.abs(r.z),a=Math.max(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z));let l=0,h=0;e>=t&&e>=o?(l=i.y/a-s.y,h=i.z/a-s.z):t>=e&&t>=o?(l=i.x/a-s.x,h=i.z/a-s.z):(l=i.x/a-s.x,h=i.y/a-s.y),n.x=(l+1)/2,n.y=(h+1)/2}}return n};this.uv._storedFunction=e=>t(e)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.mapping = BABYLON.MappingTypes.${jE[this.mapping]};\n`}serialize(){const e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}}(0,je.Cg)([t_("Mapping",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"Spherical",value:jE.Spherical},{label:"Cylindrical",value:jE.Cylindrical},{label:"Cubic",value:jE.Cubic}]})],eA.prototype,"mapping",void 0),(0,X.Y5)("BABYLON.MappingBlock",eA);class tA extends eP{constructor(e){super(e),this.registerInput("matrix0",GE.Matrix),this.registerInput("matrix1",GE.Matrix),this.registerOutput("output",GE.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?t.multiply(i):null}}}(0,X.Y5)("BABYLON.MatrixComposeBlock",tA);class iA extends eP{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",GE.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const r of this.endpoints)-1===t.indexOf(r)&&(i+=r._dumpCode(e,t));return i}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(const t of this.endpoints)if(t.isAnAncestorOfType(e))return!0;return!1}isAnAncestorOf(e){for(const t of this.endpoints){if(t===e)return!0;if(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);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}_buildBlock(){for(const e of this._endpoints)e.output._storedFunction=e=>this.input.getConnectedValue(e)}}(0,X.Y5)("BABYLON.TeleportInBlock",iA);class rA extends eP{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",GE.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&&-1===t.indexOf(this.entryPoint)&&(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});\n`),e}serialize(){const e=super.serialize();return e.entryPoint=this.entryPoint?.uniqueId??"",e}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}}(0,X.Y5)("BABYLON.TeleportOutBlock",rA);class sA extends eP{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",GE.Texture)}getClassName(){return"GeometryTextureBlock"}get texture(){return this._outputs[0]}_prepareImgToLoadAsync(e){return new Promise(((t,i)=>{const r=new Image,s=document.createElement("canvas"),n=s.getContext("2d");r.onload=()=>{s.width=r.width,s.height=r.height,n.drawImage(r,0,0);const e=n.getImageData(0,0,r.width,r.height).data,i=new Float32Array(e.length);for(let t=0;t{this._data=null,i()},r.src=e}))}cleanData(){this._data=null}loadTextureFromFileAsync(e){return this._prepareImgToLoadAsync(URL.createObjectURL(e))}loadTextureFromUrlAsync(e){return this._prepareImgToLoadAsync(e)}extractFromTextureAsync(e){return new Promise(((t,i)=>{if(!e.isReady())return void e.onLoadObservable.addOnce((()=>this.extractFromTextureAsync(e).then(t).catch(i)));const r=e.getSize();Ac.LO.GetTextureDataAsync(e,r.width,r.height).then((async e=>{const i=new Float32Array(e.length);for(let t=0;t=0?e%1:1-Math.abs(e)%1}_buildBlock(){const e=e=>{const t=this.texture.getConnectedValue(e);if(!t||!t.data)return null;const i=this.coordinates.getConnectedValue(e);if(!i)return null;const r=this.clampCoordinates?Math.max(0,Math.min(i.x,1)):this._repeatClamp(i.x),s=this.clampCoordinates?Math.max(0,Math.min(i.y,1)):this._repeatClamp(i.y),n=Math.floor(r*(t.width-1)),o=Math.floor(s*(t.height-1)),a=n+t.width*o;return W.IU.FromArray(t.data,4*a)};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};\n`}serialize(){const e=super.serialize();return e.clampCoordinates=this.clampCoordinates,e}_deserialize(e){super._deserialize(e),this.clampCoordinates=e.clampCoordinates}}(0,je.Cg)([t_("Clamp Coordinates",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],nA.prototype,"clampCoordinates",void 0),(0,X.Y5)("BABYLON.GeometryTextureFetchBlock",nA);class oA extends eP{constructor(e){super(e),this.registerInput("geometry",GE.Geometry),this.registerOutput("min",GE.Vector3),this.registerOutput("max",GE.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?(0,mt.b8)(t.positions,0,t.positions.length/3).minimum:null},this.max._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?(0,mt.b8)(t.positions,0,t.positions.length/3).maximum:null}}}(0,X.Y5)("BABYLON.BoundingBlock",oA),function(e){e[e.Intersect=0]="Intersect",e[e.Subtract=1]="Subtract",e[e.Union=2]="Union"}($E||($E={}));class aA extends eP{get _isReadyState(){return kE()?null:(this._csg2LoadingPromise||(this._csg2LoadingPromise=UE()),this._csg2LoadingPromise)}constructor(e){super(e),this.evaluateContext=!1,this.operation=$E.Intersect,this.useOldCSGEngine=!1,this.registerInput("geometry0",GE.Geometry),this.registerInput("geometry1",GE.Geometry),this.registerOutput("output",GE.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=e=>{const t=this.geometry0.getConnectedValue(e),i=this.geometry1.getConnectedValue(e);if(!t||!i)return null;const r=t.positions.length/3;let s;if(!t.normals&&i.normals&&(t.normals=new Array(t.positions.length)),!i.normals&&t.normals&&(i.normals=new Array(i.positions.length)),!t.uvs&&i.uvs&&(t.uvs=new Array(2*r)),!i.uvs&&t.uvs&&(i.uvs=new Array(2*r)),!t.colors&&i.colors&&(t.colors=new Array(4*r)),!i.colors&&t.colors&&(i.colors=new Array(4*r)),this.useOldCSGEngine){const e=nE.FromVertexData(t),r=nE.FromVertexData(i);switch(this.operation){case $E.Intersect:s=e.intersect(r);break;case $E.Subtract:s=e.subtract(r);break;case $E.Union:s=e.union(r)}}else{const e=VE.FromVertexData(t),r=VE.FromVertexData(i);switch(this.operation){case $E.Intersect:s=e.intersect(r);break;case $E.Subtract:s=e.subtract(r);break;case $E.Union:s=e.add(r)}}return s.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"};\n`;return e+=`${this._codeVariableName}.operation = BABYLON.BooleanGeometryOperations.${$E[this.operation]};\n`,e+=`${this._codeVariableName}.useOldCSGEngine = ${this.useOldCSGEngine?"true":"false"};\n`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.operation=this.operation,e.useOldCSGEngine=this.useOldCSGEngine,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,e.operation&&(this.operation=e.operation),this.useOldCSGEngine=!!e.useOldCSGEngine}}(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],aA.prototype,"evaluateContext",void 0),(0,je.Cg)([t_("Operation",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"Intersect",value:$E.Intersect},{label:"Subtract",value:$E.Subtract},{label:"Union",value:$E.Union}]})],aA.prototype,"operation",void 0),(0,je.Cg)([t_("Use old CSG engine",0,"ADVANCED",{embedded:!0,notifiers:{rebuild:!0}})],aA.prototype,"useOldCSGEngine",void 0),(0,X.Y5)("BABYLON.BooleanGeometryBlock",aA);class lA extends eP{constructor(e){super(e),this.registerInput("x",GE.AutoDetect),this.registerInput("y",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.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)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>Math.atan2(e,t);this.output._storedFunction=t=>{const i=this.x.getConnectedValue(t),r=this.y.getConnectedValue(t);switch(this.x.type){case GE.Int:case GE.Float:return e(i,r);case GE.Vector2:return new W.I9(e(i.x,r.x),e(i.y,r.y));case GE.Vector3:return new W.Pq(e(i.x,r.x),e(i.y,r.y),e(i.z,r.z));case GE.Vector4:return new W.IU(e(i.x,r.x),e(i.y,r.y),e(i.z,r.z),e(i.w,r.w))}return 0}}}(0,X.Y5)("BABYLON.GeometryArcTan2Block",lA);class hA extends eP{constructor(e){super(e),this.registerInput("left",GE.AutoDetect),this.registerInput("right",GE.AutoDetect),this.registerInput("gradient",GE.Float),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.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)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>(1-e)*t+e*i;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),r=this.right.getConnectedValue(t),s=this.gradient.getConnectedValue(t);switch(this.left.type){case GE.Int:case GE.Float:return e(s,i,r);case GE.Vector2:return new W.I9(e(s,i.x,r.x),e(s,i.y,r.y));case GE.Vector3:return new W.Pq(e(s,i.x,r.x),e(s,i.y,r.y),e(s,i.z,r.z));case GE.Vector4:return new W.IU(e(s,i.x,r.x),e(s,i.y,r.y),e(s,i.z,r.z),e(s,i.w,r.w))}return 0},this}}(0,X.Y5)("BABYLON.GeometryLerpBlock",hA);class cA extends eP{constructor(e){super(e),this.registerInput("left",GE.AutoDetect),this.registerInput("right",GE.AutoDetect),this.registerInput("gradient",GE.Float),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.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)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>(1-e)*t+e*i;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),r=this.right.getConnectedValue(t),s=this.gradient.getConnectedValue(t);switch(this.left.type){case GE.Int:case GE.Float:return e(s,i,r);case GE.Vector2:{const t=new W.I9(e(s,i.x,r.x),e(s,i.y,r.y));return t.normalize(),t}case GE.Vector3:{const t=new W.Pq(e(s,i.x,r.x),e(s,i.y,r.y),e(s,i.z,r.z));return t.normalize(),t}case GE.Vector4:{const t=new W.IU(e(s,i.x,r.x),e(s,i.y,r.y),e(s,i.z,r.z),e(s,i.w,r.w));return t.normalize(),t}}return 0},this}}(0,X.Y5)("BABYLON.GeometryNLerpBlock",cA);class uA extends eP{constructor(e){super(e),this.registerInput("value",GE.AutoDetect),this.registerInput("edge",GE.Float),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.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)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>e{const i=this.value.getConnectedValue(t),r=this.edge.getConnectedValue(t);switch(this.value.type){case GE.Int:case GE.Float:return e(i,r);case GE.Vector2:return new W.I9(e(i.x,r),e(i.y,r));case GE.Vector3:return new W.Pq(e(i.x,r),e(i.y,r),e(i.z,r));case GE.Vector4:return new W.IU(e(i.x,r),e(i.y,r),e(i.z,r),e(i.w,r))}return 0},this}}(0,X.Y5)("BABYLON.GeometryStepBlock",uA);class dA extends eP{constructor(e){super(e),this.registerInput("value",GE.AutoDetect),this.registerInput("edge0",GE.Float),this.registerInput("edge1",GE.Float),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.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)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>{const r=Math.max(0,Math.min((e-t)/(i-t),1));return r*r*(3-2*r)};return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),r=this.edge0.getConnectedValue(t),s=this.edge1.getConnectedValue(t);switch(this.value.type){case GE.Int:case GE.Float:return e(i,r,s);case GE.Vector2:return new W.I9(e(i.x,r,s),e(i.y,r,s));case GE.Vector3:return new W.Pq(e(i.x,r,s),e(i.y,r,s),e(i.z,r,s));case GE.Vector4:return new W.IU(e(i.x,r,s),e(i.y,r,s),e(i.z,r,s),e(i.w,r,s))}return 0},this}}(0,X.Y5)("BABYLON.GeometrySmoothStepBlock",dA);class fA extends eP{constructor(e){super(e),this.registerInput("left",GE.AutoDetect),this.registerInput("right",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.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)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>e-Math.floor(e/t)*t;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),r=this.right.getConnectedValue(t);switch(this.left.type){case GE.Int:case GE.Float:return e(i,r);case GE.Vector2:return new W.I9(e(i.x,r.x),e(i.y,r.y));case GE.Vector3:return new W.Pq(e(i.x,r.x),e(i.y,r.y),e(i.z,r.z));case GE.Vector4:return new W.IU(e(i.x,r.x),e(i.y,r.y),e(i.z,r.z),e(i.w,r.w))}return 0},this}}(0,X.Y5)("BABYLON.GeometryModBlock",fA);class pA extends eP{constructor(e){super(e),this.registerInput("value",GE.AutoDetect),this.registerInput("power",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.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)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>Math.pow(e,t);return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),r=this.power.getConnectedValue(t);switch(this.value.type){case GE.Int:case GE.Float:return e(i,r);case GE.Vector2:return new W.I9(e(i.x,r),e(i.y,r));case GE.Vector3:return new W.Pq(e(i.x,r),e(i.y,r),e(i.z,r));case GE.Vector4:return new W.IU(e(i.x,r),e(i.y,r),e(i.z,r),e(i.w,r))}return 0},this}}(0,X.Y5)("BABYLON.GeometryPowBlock",pA);class _A extends eP{constructor(e){super(e),this.minimum=0,this.maximum=1,this.registerInput("value",GE.AutoDetect),this.registerInput("min",GE.Float,!0),this.registerInput("max",GE.Float,!0),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),this._inputs[0].excludedConnectionPointTypes.push(GE.Texture)}getClassName(){return"GeometryClampBlock"}get value(){return this._inputs[0]}get min(){return this._inputs[1]}get max(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>Math.max(t,Math.min(e,i));return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),r=this.min.isConnected?this.min.getConnectedValue(t):this.minimum,s=this.max.isConnected?this.max.getConnectedValue(t):this.maximum;switch(this.value.type){case GE.Int:case GE.Float:return e(i,r,s);case GE.Vector2:return new W.I9(e(i.x,r,s),e(i.y,r,s));case GE.Vector3:return new W.Pq(e(i.x,r,s),e(i.y,r,s),e(i.z,r,s));case GE.Vector4:return new W.IU(e(i.x,r,s),e(i.y,r,s),e(i.z,r,s),e(i.w,r,s))}return 0},this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};\n`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};\n`,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}}(0,je.Cg)([t_("Minimum",1,void 0,{embedded:!0})],_A.prototype,"minimum",void 0),(0,je.Cg)([t_("Maximum",1,void 0,{embedded:!0})],_A.prototype,"maximum",void 0),(0,X.Y5)("BABYLON.GeometryClampBlock",_A);class mA extends eP{constructor(e){super(e),this.registerInput("left",GE.AutoDetect),this.registerInput("right",GE.AutoDetect),this.registerOutput("output",GE.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(GE.Int),this._inputs[0].excludedConnectionPointTypes.push(GE.Float),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Vector2),this._inputs[1].excludedConnectionPointTypes.push(GE.Int),this._inputs[1].excludedConnectionPointTypes.push(GE.Float),this._inputs[1].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[1].excludedConnectionPointTypes.push(GE.Vector2)}getClassName(){return"GeometryCrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.left.isConnected&&this.right.isConnected?(this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);switch(this.left.type){case GE.Vector3:return W.Pq.Cross(t,i);case GE.Vector4:return W.Pq.Cross(t.toVector3(),i.toVector3())}return 0},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}(0,X.Y5)("BABYLON.GeometryCrossBlock",mA),function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(QE||(QE={}));class gA extends eP{constructor(e){super(e),this.type=QE.EaseInOutSine,this.registerInput("input",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[0].excludedConnectionPointTypes.push(GE.Int)}getClassName(){return"GeometryCurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.input.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);let e;switch(this.type){case QE.EaseInSine:e=e=>1-Math.cos(3.1415*e/2);break;case QE.EaseOutSine:e=e=>Math.sin(3.1415*e/2);break;case QE.EaseInOutSine:e=e=>-(Math.cos(3.1415*e)-1)/2;break;case QE.EaseInQuad:e=e=>e*e;break;case QE.EaseOutQuad:e=e=>(1-e)*(1-e);break;case QE.EaseInOutQuad:e=e=>e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;break;case QE.EaseInCubic:e=e=>e*e*e;break;case QE.EaseOutCubic:e=e=>1-Math.pow(1-e,3);break;case QE.EaseInOutCubic:e=e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;break;case QE.EaseInQuart:e=e=>e*e*e*e;break;case QE.EaseOutQuart:e=e=>1-Math.pow(1-e,4);break;case QE.EaseInOutQuart:e=e=>e<.5?8*e*e*e*e:1-Math.pow(-2*e+2,4)/2;break;case QE.EaseInQuint:e=e=>e*e*e*e*e;break;case QE.EaseOutQuint:e=e=>1-Math.pow(1-e,5);break;case QE.EaseInOutQuint:e=e=>e<.5?16*e*e*e*e*e:1-Math.pow(-2*e+2,5)/2;break;case QE.EaseInExpo:e=e=>0===e?0:Math.pow(2,10*e-10);break;case QE.EaseOutExpo:e=e=>1===e?1:1-Math.pow(2,-10*e);break;case QE.EaseInOutExpo:e=e=>0===e?0:1===e?1:e<.5?Math.pow(2,20*e-10)/2:(2-Math.pow(2,-20*e+10))/2;break;case QE.EaseInCirc:e=e=>1-Math.sqrt(1-Math.pow(e,2));break;case QE.EaseOutCirc:e=e=>Math.sqrt(1-Math.pow(e-1,2));break;case QE.EaseInOutCirc:e=e=>e<.5?(1-Math.sqrt(1-Math.pow(2*e,2)))/2:(Math.sqrt(1-Math.pow(-2*e+2,2))+1)/2;break;case QE.EaseInBack:e=e=>2.70158*e*e*e-1.70158*e*e;break;case QE.EaseOutBack:e=e=>2.70158*Math.pow(e-1,3)+1.70158*Math.pow(e-1,2);break;case QE.EaseInOutBack:e=e=>e<.5?Math.pow(2*e,2)*(7.189819*e-2.5949095)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+3.5949095)+2)/2;break;case QE.EaseInElastic:e=e=>0===e?0:1===e?1:-Math.pow(2,10*e-10)*Math.sin(6.283/3*(10*e-10.75));break;case QE.EaseOutElastic:e=e=>0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin(6.283/3*(10*e-.75))+1;break;case QE.EaseInOutElastic:e=e=>0===e?0:1==e?1:e<.5?-Math.pow(2,20*e-10)*Math.sin(6.283/4.5*(20*e-11.125))/2:Math.pow(2,-20*e+10)*Math.sin(6.283/4.5*(20*e-11.125))/2+1}return this.output._storedFunction=t=>{const i=this.input.getConnectedValue(t);switch(this.input.type){case GE.Float:return e(i);case GE.Vector2:return new W.I9(e(i.x),e(i.y));case GE.Vector3:return new W.Pq(e(i.x),e(i.y),e(i.z));case GE.Vector4:return new W.IU(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.${QE[this.type]};\n`}}(0,je.Cg)([t_("Type",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"EaseInSine",value:QE.EaseInSine},{label:"EaseOutSine",value:QE.EaseOutSine},{label:"EaseInOutSine",value:QE.EaseInOutSine},{label:"EaseInQuad",value:QE.EaseInQuad},{label:"EaseOutQuad",value:QE.EaseOutQuad},{label:"EaseInOutQuad",value:QE.EaseInOutQuad},{label:"EaseInCubic",value:QE.EaseInCubic},{label:"EaseOutCubic",value:QE.EaseOutCubic},{label:"EaseInOutCubic",value:QE.EaseInOutCubic},{label:"EaseInQuart",value:QE.EaseInQuart},{label:"EaseOutQuart",value:QE.EaseOutQuart},{label:"EaseInOutQuart",value:QE.EaseInOutQuart},{label:"EaseInQuint",value:QE.EaseInQuint},{label:"EaseOutQuint",value:QE.EaseOutQuint},{label:"EaseInOutQuint",value:QE.EaseInOutQuint},{label:"EaseInExpo",value:QE.EaseInExpo},{label:"EaseOutExpo",value:QE.EaseOutExpo},{label:"EaseInOutExpo",value:QE.EaseInOutExpo},{label:"EaseInCirc",value:QE.EaseInCirc},{label:"EaseOutCirc",value:QE.EaseOutCirc},{label:"EaseInOutCirc",value:QE.EaseInOutCirc},{label:"EaseInBack",value:QE.EaseInBack},{label:"EaseOutBack",value:QE.EaseOutBack},{label:"EaseInOutBack",value:QE.EaseInOutBack},{label:"EaseInElastic",value:QE.EaseInElastic},{label:"EaseOutElastic",value:QE.EaseOutElastic},{label:"EaseInOutElastic",value:QE.EaseInOutElastic}]})],gA.prototype,"type",void 0),(0,X.Y5)("BABYLON.GeometryCurveBlock",gA);class vA extends eP{constructor(e){super(e),this.registerInput("color",GE.Vector3),this.registerInput("level",GE.Float,!0,0),this.registerOutput("output",GE.Vector3)}getClassName(){return"GeometryDesaturateBlock"}get color(){return this._inputs[0]}get level(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.color.isConnected?(this.output._storedFunction=e=>{const t=this.color.getConnectedValue(e),i=this.level.getConnectedValue(e),r=.5*(Math.min(t.x,t.y,t.z)+Math.max(t.x,t.y,t.z));return new W.Pq(t.x*(1-i)+r*i,t.y*(1-i)+r*i,t.z*(1-i)+r*i)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}(0,X.Y5)("BABYLON.GeometryDesaturateBlock",vA);class xA extends eP{constructor(e){super(e),this.registerInput("value",GE.AutoDetect),this.registerInput("steps",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[1].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(GE.Float)}getClassName(){return"GeometryPosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected&&this.steps.isConnected?(this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.steps.getConnectedValue(e);let r=i;if(this.steps.type===GE.Float)switch(this.value.type){case GE.Vector2:r=new W.I9(i,i);break;case GE.Vector3:r=new W.Pq(i,i,i);break;case GE.Vector4:r=new W.IU(i,i,i,i)}switch(this.value.type){case GE.Vector2:return new W.I9(t.x/(1/r.x)*(1/r.x),t.y/(1/r.y)*(1/r.y));case GE.Vector3:return new W.Pq(t.x/(1/r.x)*(1/r.x),t.y/(1/r.y)*(1/r.y),t.z/(1/r.z)*(1/r.z));case GE.Vector4:return new W.IU(t.x/(1/r.x)*(1/r.x),t.y/(1/r.y)*(1/r.y),t.z/(1/r.z)*(1/r.z),t.w/(1/r.w)*(1/r.w));default:return Math.floor(t/(1/i)*(1/i))}},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}(0,X.Y5)("BABYLON.GeometryPosterizeBlock",xA);class bA extends eP{constructor(e){super(e),this.registerInput("value",GE.AutoDetect),this.registerInput("reference",GE.AutoDetect),this.registerInput("distance",GE.Float),this.registerInput("replacement",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(GE.Float),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[1].excludedConnectionPointTypes.push(GE.Float),this._inputs[1].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[3].excludedConnectionPointTypes.push(GE.Float),this._inputs[3].excludedConnectionPointTypes.push(GE.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(){return this.value.isConnected&&this.reference.isConnected&&this.distance.isConnected&&this.replacement.isConnected?(this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.reference.getConnectedValue(e),r=this.distance.getConnectedValue(e),s=this.replacement.getConnectedValue(e);return t.subtract(i).length(){const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.subtract(i).length()},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}(0,X.Y5)("BABYLON.GeometryDistanceBlock",SA);class TA extends eP{constructor(e){super(e),this.registerInput("left",GE.AutoDetect),this.registerInput("right",GE.AutoDetect),this.registerOutput("output",GE.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(GE.Int),this._inputs[0].excludedConnectionPointTypes.push(GE.Float),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),this._inputs[1].excludedConnectionPointTypes.push(GE.Float),this._inputs[1].excludedConnectionPointTypes.push(GE.Matrix)}getClassName(){return"GeometryDotBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.left.isConnected&&this.right.isConnected?(this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.dot(i)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}(0,X.Y5)("BABYLON.GeometryDotBlock",TA);class CA extends eP{constructor(e){super(e),this.registerInput("value",GE.AutoDetect),this.registerOutput("output",GE.Float),this._inputs[0].excludedConnectionPointTypes.push(GE.Int),this._inputs[0].excludedConnectionPointTypes.push(GE.Float),this._inputs[0].excludedConnectionPointTypes.push(GE.Matrix)}getClassName(){return"GeometryLengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected?(this.output._storedFunction=e=>this.value.getConnectedValue(e).length(),this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}(0,X.Y5)("BABYLON.GeometryLengthBlock",CA);class yA extends eP{constructor(e){super(e),this.registerInput("input",GE.Vector2),this.registerInput("angle",GE.Float),this.registerOutput("output",GE.Vector2)}getClassName(){return"GeometryRotate2dBlock"}get input(){return this._inputs[0]}get angle(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.angle.isConnected&&this.input.isConnected?(this.output._storedFunction=e=>{const t=this.input.getConnectedValue(e),i=this.angle.getConnectedValue(e);return new W.I9(Math.cos(i)*t.x-Math.sin(i)*t.y,Math.sin(i)*t.x+Math.cos(i)*t.y)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}(0,X.Y5)("BABYLON.GeometryRotate2dBlock",yA);class EA extends eP{constructor(e){super(e),this.onInterceptionObservable=new z.cP(void 0,!0),this.registerInput("input",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}get buildExecutionTime(){return-1}getClassName(){return"GeometryInterceptorBlock"}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=e=>{let t=i.getConnectedValue(e);return this.customFunction&&(t=this.customFunction(t,e)),this.onInterceptionObservable.notifyObservers(t),t}}}(0,X.Y5)("BABYLON.GeometryInterceptorBlock",EA),function(e){e[e.Max=0]="Max",e[e.Min=1]="Min",e[e.Sum=2]="Sum"}(ZE||(ZE={}));class PA extends eP{constructor(e){super(e),this.aggregation=ZE.Sum,this.evaluateContext=!0,this.registerInput("geometry",GE.Geometry),this.registerInput("source",GE.AutoDetect),this.registerOutput("output",GE.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[1]}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"AggregatorBlock"}get geometry(){return this._inputs[0]}get source(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.source.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);const t=this._vertexData.positions.length/3,i=[];for(this._currentIndex=0;this._currentIndexMath.max(e,t);break;case ZE.Min:s=(e,t)=>Math.min(e,t);break;case ZE.Sum:s=(e,t)=>e+t}if(!s)return e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedFunction=null,void(this.output._storedValue=null);switch(this.source.type){case GE.Int:case GE.Float:r=i.reduce(s);break;case GE.Vector2:{const e=i.map((e=>e.x)).reduce(s),t=i.map((e=>e.y)).reduce(s);r=new W.I9(e,t);break}case GE.Vector3:{const e=i.map((e=>e.x)).reduce(s),t=i.map((e=>e.y)).reduce(s),n=i.map((e=>e.z)).reduce(s);r=new W.Pq(e,t,n);break}case GE.Vector4:{const e=i.map((e=>e.x)).reduce(s),t=i.map((e=>e.y)).reduce(s),n=i.map((e=>e.z)).reduce(s),o=i.map((e=>e.w)).reduce(s);r=new W.IU(e,t,n,o);break}}return e.restoreGeometryContext(),e.restoreExecutionContext(),r};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"};\n`;return e+=`${this._codeVariableName}.aggregation = BABYLON.Aggregations.${ZE[this.aggregation]};\n`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.aggregation=this.aggregation,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext),void 0!==e.aggregation&&(this.aggregation=e.aggregation)}}(0,je.Cg)([t_("Aggregation",4,"ADVANCED",{notifiers:{rebuild:!0},embedded:!0,options:[{label:"Max",value:ZE.Max},{label:"Min",value:ZE.Min},{label:"Sum",value:ZE.Sum}]})],PA.prototype,"aggregation",void 0),(0,je.Cg)([t_("Evaluate context",0,"ADVANCED",{notifiers:{rebuild:!0}})],PA.prototype,"evaluateContext",void 0),(0,X.Y5)("BABYLON.AggregatorBlock",PA);const AA=(e,t)=>{const i=(1<{t.x=AA(e>>>21,11),t.y=AA(e>>>11,10),t.z=AA(e,11)},IA=(e,t)=>{t[0]=255*AA(e>>>24,8),t[1]=255*AA(e>>>16,8),t[2]=255*AA(e>>>8,8),t[3]=255*AA(e,8)},MA=(e,t)=>{const i=1/(.5*Math.sqrt(2)),r=(AA(e>>>20,10)-.5)*i,s=(AA(e>>>10,10)-.5)*i,n=(AA(e,10)-.5)*i,o=Math.sqrt(1-(r*r+s*s+n*n));switch(e>>>30){case 0:t.set(o,r,s,n);break;case 1:t.set(r,o,s,n);break;case 2:t.set(r,s,o,n);break;case 3:t.set(r,s,n,o)}};var OA,DA;!function(e){e[e.FLOAT=0]="FLOAT",e[e.INT=1]="INT",e[e.UINT=2]="UINT",e[e.DOUBLE=3]="DOUBLE",e[e.UCHAR=4]="UCHAR",e[e.UNDEFINED=5]="UNDEFINED"}(OA||(OA={})),function(e){e[e.MIN_X=0]="MIN_X",e[e.MIN_Y=1]="MIN_Y",e[e.MIN_Z=2]="MIN_Z",e[e.MAX_X=3]="MAX_X",e[e.MAX_Y=4]="MAX_Y",e[e.MAX_Z=5]="MAX_Z",e[e.MIN_SCALE_X=6]="MIN_SCALE_X",e[e.MIN_SCALE_Y=7]="MIN_SCALE_Y",e[e.MIN_SCALE_Z=8]="MIN_SCALE_Z",e[e.MAX_SCALE_X=9]="MAX_SCALE_X",e[e.MAX_SCALE_Y=10]="MAX_SCALE_Y",e[e.MAX_SCALE_Z=11]="MAX_SCALE_Z",e[e.PACKED_POSITION=12]="PACKED_POSITION",e[e.PACKED_ROTATION=13]="PACKED_ROTATION",e[e.PACKED_SCALE=14]="PACKED_SCALE",e[e.PACKED_COLOR=15]="PACKED_COLOR",e[e.X=16]="X",e[e.Y=17]="Y",e[e.Z=18]="Z",e[e.SCALE_0=19]="SCALE_0",e[e.SCALE_1=20]="SCALE_1",e[e.SCALE_2=21]="SCALE_2",e[e.DIFFUSE_RED=22]="DIFFUSE_RED",e[e.DIFFUSE_GREEN=23]="DIFFUSE_GREEN",e[e.DIFFUSE_BLUE=24]="DIFFUSE_BLUE",e[e.OPACITY=25]="OPACITY",e[e.F_DC_0=26]="F_DC_0",e[e.F_DC_1=27]="F_DC_1",e[e.F_DC_2=28]="F_DC_2",e[e.F_DC_3=29]="F_DC_3",e[e.ROT_0=30]="ROT_0",e[e.ROT_1=31]="ROT_1",e[e.ROT_2=32]="ROT_2",e[e.ROT_3=33]="ROT_3",e[e.UNDEFINED=34]="UNDEFINED"}(DA||(DA={}));class wA extends Yt{get covariancesATexture(){return this._covariancesATexture}get covariancesBTexture(){return this._covariancesBTexture}get centersTexture(){return this._centersTexture}get colorsTexture(){return this._colorsTexture}set material(e){this._material=e,this._material.backFaceCulling=!0,this._material.cullBackFaces=!1,e.resetDrawCache()}get material(){return this._material}constructor(e,t=null,i=null,r=!1){super(e,i),this._vertexCount=0,this._worker=null,this._frameIdLastUpdate=-1,this._modelViewMatrix=W.uq.Identity(),this._canPostToWorker=!0,this._readyToDisplay=!1,this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,this._splatPositions=null,this._splatIndex=null,this._covariancesA=null,this._covariancesB=null,this._colors=null,this._keepInRam=!1,this._delayedTextureUpdate=null,this._oldDirection=new W.Pq,this._useRGBACovariants=!1,this._material=null,this._tmpCovariances=[0,0,0,0,0,0],this._sortIsDirty=!1;const s=new bt;s.positions=[-3,-2,0,3,-2,0,0,4,0],s.indices=[0,1,2],s.applyToMesh(this),this.subMeshes=[],new vt(0,0,3,0,3,this),this.setEnabled(!1),this._useRGBACovariants=!this.getEngine().isWebGPU&&1===this.getEngine().version,this._keepInRam=r,t&&this.loadFileAsync(t),this._material=new pS(this.name+"_material",this._scene)}getClassName(){return"GaussianSplattingMesh"}getTotalVertices(){return this._vertexCount}isReady(e=!1){return!(!super.isReady(e,!0)||!this._readyToDisplay&&(this._postToWorker(!0),1))}_postToWorker(e=!1){const t=this.getScene().getFrameId();if((e||t!==this._frameIdLastUpdate)&&this._worker&&this._scene.activeCamera&&this._canPostToWorker){const i=this._scene.activeCamera.getViewMatrix();this.getWorldMatrix().multiplyToRef(i,this._modelViewMatrix),i.invertToRef(W.AA.Matrix[0]),this.getWorldMatrix().multiplyToRef(W.AA.Matrix[0],W.AA.Matrix[1]),W.Pq.TransformNormalToRef(W.Pq.Forward(this._scene.useRightHandedSystem),W.AA.Matrix[1],W.AA.Vector3[2]),W.AA.Vector3[2].normalize();const r=W.Pq.Dot(W.AA.Vector3[2],this._oldDirection);(e||Math.abs(r-1)>=.01)&&(this._oldDirection.copyFrom(W.AA.Vector3[2]),this._frameIdLastUpdate=t,this._canPostToWorker=!1,this._worker.postMessage({view:this._modelViewMatrix.m,depthMix:this._depthMix,useRightHandedSystem:this._scene.useRightHandedSystem},[this._depthMix.buffer]))}}render(e,t,i){return this._postToWorker(),super.render(e,t,i)}static _TypeNameToEnum(e){switch(e){case"float":return 0;case"int":return 1;case"uint":return 2;case"double":return 3;case"uchar":return 4}return 5}static _ValueNameToEnum(e){switch(e){case"min_x":return 0;case"min_y":return 1;case"min_z":return 2;case"max_x":return 3;case"max_y":return 4;case"max_z":return 5;case"min_scale_x":return 6;case"min_scale_y":return 7;case"min_scale_z":return 8;case"max_scale_x":return 9;case"max_scale_y":return 10;case"max_scale_z":return 11;case"packed_position":return 12;case"packed_rotation":return 13;case"packed_scale":return 14;case"packed_color":return 15;case"x":return 16;case"y":return 17;case"z":return 18;case"scale_0":return 19;case"scale_1":return 20;case"scale_2":return 21;case"diffuse_red":case"red":return 22;case"diffuse_green":case"green":return 23;case"diffuse_blue":case"blue":return 24;case"f_dc_0":return 26;case"f_dc_1":return 27;case"f_dc_2":return 28;case"f_dc_3":return 29;case"opacity":return 25;case"rot_0":return 30;case"rot_1":return 31;case"rot_2":return 32;case"rot_3":return 33}return 34}static ParseHeader(e){const t=new Uint8Array(e),i=(new TextDecoder).decode(t.slice(0,10240)),r=i.indexOf("end_header\n");if(r<0||!i)return null;const s=parseInt(/element vertex (\d+)\n/.exec(i)[1]),n=/element chunk (\d+)\n/.exec(i);let o=0;n&&(o=parseInt(n[1]));let a=0,l=0;const h={double:8,int:4,uint:4,float:4,short:2,ushort:2,uchar:1,list:0};let c;!function(e){e[e.Vertex=0]="Vertex",e[e.Chunk=1]="Chunk"}(c||(c={}));let u=1;const d=[],f=[],p=i.slice(0,r).split("\n");for(const e of p)if(e.startsWith("property ")){const[,t,i]=e.split(" "),r=wA._ValueNameToEnum(i),s=wA._TypeNameToEnum(t);1==u?(f.push({value:r,type:s,offset:l}),l+=h[t]):0==u&&(d.push({value:r,type:s,offset:a}),a+=h[t]),h[t]||Z.V.Warn(`Unsupported property type: ${t}.`)}else if(e.startsWith("element ")){const[,t]=e.split(" ");"chunk"==t?u=1:"vertex"==t&&(u=0)}return{vertexCount:s,chunkCount:o,rowVertexLength:a,rowChunkLength:l,vertexProperties:d,chunkProperties:f,dataView:new DataView(e,r+11),buffer:new ArrayBuffer(wA._RowOutputLength*s)}}static _GetCompressedChunks(e,t){if(!e.chunkCount)return null;const i=e.dataView,r=new Array(e.chunkCount);for(let s=0;s>8;let p=255,_=0,m=0,g=0;for(let t=0;t{wA.ConvertPLYToSplatAsync(e).then((e=>{this.updateDataAsync(e)}))}))}dispose(e){this._covariancesATexture?.dispose(),this._covariancesBTexture?.dispose(),this._centersTexture?.dispose(),this._colorsTexture?.dispose(),this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,this._worker?.terminate(),this._worker=null,super.dispose(e,!0)}_copyTextures(e){this._covariancesATexture=e.covariancesATexture?.clone(),this._covariancesBTexture=e.covariancesBTexture?.clone(),this._centersTexture=e.centersTexture?.clone(),this._colorsTexture=e.colorsTexture?.clone()}clone(e=""){const t=new wA(e,void 0,this.getScene());t._copySource(this),t.makeGeometryUnique(),t._vertexCount=this._vertexCount,t._copyTextures(this),t._modelViewMatrix=W.uq.Identity(),t._splatPositions=this._splatPositions,t._readyToDisplay=!1,t._instanciateWorker();const i=this.getBoundingInfo();return t.getBoundingInfo().reConstruct(i.minimum,i.maximum,this.getWorldMatrix()),t.forcedInstanceCount=t._vertexCount,t.setEnabled(!0),t}_makeSplat(e,t,i,r,s,n,o,a,l){const h=W.AA.Matrix[0],c=W.AA.Matrix[1],u=W.AA.Quaternion[0],d=this._useRGBACovariants?4:2,f=i[8*e+0],p=-i[8*e+1],_=i[8*e+2];this._splatPositions[4*e+0]=f,this._splatPositions[4*e+1]=p,this._splatPositions[4*e+2]=_,a.minimizeInPlaceFromFloats(f,p,_),l.maximizeInPlaceFromFloats(f,p,_),u.set((r[32*e+28+1]-128)/128,(r[32*e+28+2]-128)/128,(r[32*e+28+3]-128)/128,-(r[32*e+28+0]-128)/128),u.toRotationMatrix(h),W.uq.ScalingToRef(2*i[8*e+3+0],2*i[8*e+3+1],2*i[8*e+3+2],c);const m=h.multiplyToRef(c,W.AA.Matrix[0]).m,g=this._tmpCovariances;g[0]=m[0]*m[0]+m[1]*m[1]+m[2]*m[2],g[1]=m[0]*m[4]+m[1]*m[5]+m[2]*m[6],g[2]=m[0]*m[8]+m[1]*m[9]+m[2]*m[10],g[3]=m[4]*m[4]+m[5]*m[5]+m[6]*m[6],g[4]=m[4]*m[8]+m[5]*m[9]+m[6]*m[10],g[5]=m[8]*m[8]+m[9]*m[9]+m[10]*m[10];let v=-1e4;for(let e=0;e<6;e++)v=Math.max(v,Math.abs(g[e]));this._splatPositions[4*e+3]=v;const x=v;s[4*t+0]=(0,Ac.LZ)(g[0]/x),s[4*t+1]=(0,Ac.LZ)(g[1]/x),s[4*t+2]=(0,Ac.LZ)(g[2]/x),s[4*t+3]=(0,Ac.LZ)(g[3]/x),n[t*d+0]=(0,Ac.LZ)(g[4]/x),n[t*d+1]=(0,Ac.LZ)(g[5]/x),o[4*t+0]=r[32*e+24+0],o[4*t+1]=r[32*e+24+1],o[4*t+2]=r[32*e+24+2],o[4*t+3]=r[32*e+24+3]}_updateTextures(e,t,i){const r=this._getTextureSize(this._vertexCount),s=(e,t,i,r)=>new xi(e,t,i,r,this._scene,!1,!1,2,2);if(this._keepInRam&&(this._covariancesA=e,this._covariancesB=t,this._colors=i),this._covariancesATexture){this._delayedTextureUpdate={covA:e,covB:t,colors:i,centers:this._splatPositions};const r=Float32Array.from(this._splatPositions),s=this._vertexCount;this._worker.postMessage({positions:r,vertexCount:s},[r.buffer]),this._postToWorker(!0)}else this._covariancesATexture=s(e,r.x,r.y,5),this._covariancesBTexture=s(t,r.x,r.y,this._useRGBACovariants?5:7),this._centersTexture=((e,t,i,r)=>new xi(e,t,i,r,this._scene,!1,!1,2,1))(this._splatPositions,r.x,r.y,5),this._colorsTexture=((e,t,i,r)=>new xi(e,t,i,r,this._scene,!1,!1,2,0))(i,r.x,r.y,5),this._instanciateWorker()}*_updateData(e,t){this._covariancesATexture||(this._readyToDisplay=!1);const i=new Uint8Array(e),r=new Float32Array(i.buffer),s=i.length/wA._RowOutputLength;s!=this._vertexCount&&this._updateSplatIndexBuffer(s),this._vertexCount=s;const n=this._getTextureSize(s),o=n.x*n.y,a=wA.ProgressiveUpdateAmount??n.y,l=n.x*a;this._splatPositions=new Float32Array(4*o);const h=new Uint16Array(4*o),c=new Uint16Array((this._useRGBACovariants?4:2)*o),u=new Uint8Array(4*o),d=new W.Pq(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),f=new W.Pq(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);if(wA.ProgressiveUpdateAmount){this._updateTextures(h,c,u),this.setEnabled(!0);const e=Math.ceil(n.y/a);for(let s=0;sthis._splatIndex.length)&&(this._splatIndex=new Float32Array(e),this.thinInstanceSetBuffer("splatIndex",this._splatIndex,1,!1)),this.forcedInstanceCount=e}_updateSubTextures(e,t,i,r,s,n){const o=(e,t,i,r,s)=>{this.getEngine().updateTextureData(e.getInternalTexture(),t,0,r,i,s,0,0,!1)},a=this._getTextureSize(this._vertexCount),l=this._useRGBACovariants?4:2,h=s*a.x,c=n*a.x,u=new Uint16Array(t.buffer,4*h*Uint16Array.BYTES_PER_ELEMENT,4*c),d=new Uint16Array(i.buffer,h*l*Uint16Array.BYTES_PER_ELEMENT,c*l),f=new Uint8Array(r.buffer,4*h,4*c),p=new Float32Array(e.buffer,4*h*Float32Array.BYTES_PER_ELEMENT,4*c);o(this._covariancesATexture,u,a.x,s,n),o(this._covariancesBTexture,d,a.x,s,n),((e,t,i,r,s)=>{this.getEngine().updateTextureData(e.getInternalTexture(),t,0,r,i,s,0,0,!1)})(this._centersTexture,p,a.x,s,n),((e,t,i,r,s)=>{this.getEngine().updateTextureData(e.getInternalTexture(),t,0,r,i,s,0,0,!1)})(this._colorsTexture,f,a.x,s,n)}_instanciateWorker(){if(!this._vertexCount)return;this._updateSplatIndexBuffer(this._vertexCount),this._worker?.terminate(),this._worker=new Worker(URL.createObjectURL(new Blob(["(",wA._CreateWorker.toString(),")(self)"],{type:"application/javascript"}))),this._depthMix=new BigInt64Array(this._vertexCount);const e=Float32Array.from(this._splatPositions),t=this._vertexCount;this._worker.postMessage({positions:e,vertexCount:t},[e.buffer]),this._worker.onmessage=e=>{this._depthMix=e.data.depthMix;const i=new Uint32Array(e.data.depthMix.buffer);if(this._splatIndex)for(let e=0;ei&&(Z.V.Error("GaussianSplatting texture size: ("+i+", "+r+"), maxTextureSize: "+i),r=i),new W.I9(i,r)}}wA._RowOutputLength=32,wA._SH_C0=.28209479177387814,wA._SplatBatchSize=327680,wA._PlyConversionBatchSize=32768,wA.ProgressiveUpdateAmount=0,wA._CreateWorker=function(e){let t,i,r,s,n=0;e.onmessage=o=>{if(o.data.positions)t=o.data.positions,n=o.data.vertexCount;else{const a=o.data.view;if(!t||!a)throw new Error("positions or view is not defined!");i=o.data.depthMix,r=new Uint32Array(i.buffer),s=new Float32Array(i.buffer);for(let e=0;e{this._onDoneCallback(t,i)}),((e,t)=>{this._onErrorCallback(i,e,t)}))}runTask(e,t,i){throw new Error("runTask is not implemented")}reset(){this._taskState=0}_onErrorCallback(e,t,i){this._taskState=3,this._errorObject={message:t,exception:i},this.onError&&this.onError(this,t,i),e()}_onDoneCallback(e,t){try{this._taskState=2,this._isCompleted=!0,this.onSuccess&&this.onSuccess(this),e()}catch(e){this._onErrorCallback(t,"Task is done, error executing success callback(s)",e)}}}class QA{constructor(e,t,i){this.remainingCount=e,this.totalCount=t,this.task=i}}class ZA extends $A{constructor(e,t,i,r,s){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=r,this.extension=s}runTask(e,t,i){xg.LoadAssetContainer(this.rootUrl,this.sceneFilename,e,(e=>{this.loadedContainer=e,this.loadedMeshes=e.meshes,this.loadedTransformNodes=e.transformNodes,this.loadedParticleSystems=e.particleSystems,this.loadedSkeletons=e.skeletons,this.loadedAnimationGroups=e.animationGroups,t()}),null,((e,t,r)=>{i(t,r)}),this.extension)}}class JA extends $A{constructor(e,t,i,r,s){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=r,this.extension=s}runTask(e,t,i){xg.ImportMesh(this.meshesNames,this.rootUrl,this.sceneFilename,e,((e,i,r,s,n)=>{this.loadedMeshes=e,this.loadedTransformNodes=n,this.loadedParticleSystems=i,this.loadedSkeletons=r,this.loadedAnimationGroups=s,t()}),null,((e,t,r)=>{i(t,r)}),this.extension)}}class eR extends $A{constructor(e,t,i,r,s){super(e),this.name=e,this.rootUrl=t,this.filename=i,this.targetConverter=r,this.extension=s}runTask(e,t,i){const r=e.animatables.length,s=e.animationGroups.length;this.loadedAnimatables=[],this.loadedAnimationGroups=[],xg.ImportAnimations(this.rootUrl,this.filename,e,!1,3,this.targetConverter,(()=>{this.loadedAnimatables=e.animatables.slice(r),this.loadedAnimationGroups=e.animationGroups.slice(s),t()}),null,((e,t,r)=>{i(t,r)}),this.extension)}}class tR extends $A{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,(e=>{this.text=e,t()}),void 0,!1,!1,((e,t)=>{e&&i(e.status+" "+e.statusText,t)}))}}class iR extends $A{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,(e=>{this.data=e,t()}),void 0,!0,!0,((e,t)=>{e&&i(e.status+" "+e.statusText,t)}))}}class rR extends $A{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){const r=new Image;Ue.S0.SetCorsBehavior(this.url,r),r.onload=()=>{this.image=r,t()},r.onerror=e=>{i("Error loading image",e)},r.src=this.url}}class sR extends $A{constructor(e,t,i,r=!0,s=vi.g.TRILINEAR_SAMPLINGMODE){super(e),this.name=e,this.url=t,this.noMipmap=i,this.invertY=r,this.samplingMode=s}runTask(e,t,i){this.texture=new vi.g(this.url,e,this.noMipmap,this.invertY,this.samplingMode,(()=>{t()}),((e,t)=>{i(e,t)}))}}class nR extends $A{constructor(e,t,i,r,s,n){super(e),this.name=e,this.url=t,this.extensions=i,this.noMipmap=r,this.files=s,this.prefiltered=n}runTask(e,t,i){this.texture=new gm(this.url,e,this.extensions,this.noMipmap,this.files,(()=>{t()}),((e,t)=>{i(e,t)}),void 0,this.prefiltered)}}class oR extends $A{constructor(e,t,i,r=!1,s=!0,n=!1,o=!1){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=r,this.generateHarmonics=s,this.gammaSpace=n,this.reserved=o}runTask(e,t,i){this.texture=new Vx(this.url,e,this.size,this.noMipmap,this.generateHarmonics,this.gammaSpace,this.reserved,(()=>{t()}),((e,t)=>{i(e,t)}))}}class aR extends $A{constructor(e,t,i,r=!1,s=!0){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=r,this.gammaSpace=s}runTask(e,t,i){this.texture=new Db(this.url,e,this.size,this.noMipmap,this.gammaSpace,(()=>{t()}),((e,t)=>{i(e,t)}))}}class lR{constructor(e){this._isLoading=!1,this._tasks=new Array,this._waitingTasksCount=0,this._totalTasksCount=0,this.onTaskSuccessObservable=new z.cP,this.onTaskErrorObservable=new z.cP,this.onTasksDoneObservable=new z.cP,this.onProgressObservable=new z.cP,this.useDefaultLoadingScreen=!0,this.autoHideLoadingUI=!0,this._scene=e||he.q.LastCreatedScene}addContainerTask(e,t,i,r,s){const n=new ZA(e,t,i,r,s);return this._tasks.push(n),n}addMeshTask(e,t,i,r,s){const n=new JA(e,t,i,r,s);return this._tasks.push(n),n}addTextFileTask(e,t){const i=new tR(e,t);return this._tasks.push(i),i}addBinaryFileTask(e,t){const i=new iR(e,t);return this._tasks.push(i),i}addImageTask(e,t){const i=new rR(e,t);return this._tasks.push(i),i}addTextureTask(e,t,i,r,s=vi.g.TRILINEAR_SAMPLINGMODE){const n=new sR(e,t,i,r,s);return this._tasks.push(n),n}addCubeTextureTask(e,t,i,r,s,n){const o=new nR(e,t,i,r,s,n);return this._tasks.push(o),o}addHDRCubeTextureTask(e,t,i,r=!1,s=!0,n=!1,o=!1){const a=new oR(e,t,i,r,s,n,o);return this._tasks.push(a),a}addEquiRectangularCubeTextureAssetTask(e,t,i,r=!1,s=!0){const n=new aR(e,t,i,r,s);return this._tasks.push(n),n}removeTask(e){const t=this._tasks.indexOf(e);t>-1&&this._tasks.splice(t,1)}_decreaseWaitingTasksCount(e){this._waitingTasksCount--;try{this.onProgress&&this.onProgress(this._waitingTasksCount,this._totalTasksCount,e),this.onProgressObservable.notifyObservers(new QA(this._waitingTasksCount,this._totalTasksCount,e))}catch(e){Z.V.Error("Error running progress callbacks."),Z.V.Log(e)}if(0===this._waitingTasksCount){try{const e=this._tasks.slice();this.onFinish&&this.onFinish(e);for(const t of e)if(2===t.taskState){const e=this._tasks.indexOf(t);e>-1&&this._tasks.splice(e,1)}this.onTasksDoneObservable.notifyObservers(this._tasks)}catch(e){Z.V.Error("Error running tasks-done callbacks."),Z.V.Log(e)}this._isLoading=!1,this.autoHideLoadingUI&&this._scene.getEngine().hideLoadingUI()}}_runTask(e){const t=(t,i)=>{e._setErrorObject(t,i),this.onTaskError?this.onTaskError(e):e.onError||Z.V.Error(this._formatTaskErrorMessage(e)),this.onTaskErrorObservable.notifyObservers(e),this._decreaseWaitingTasksCount(e)};e.run(this._scene,(()=>{try{this.onTaskSuccess&&this.onTaskSuccess(e),this.onTaskSuccessObservable.notifyObservers(e),this._decreaseWaitingTasksCount(e)}catch(e){t("Error executing task success callbacks",e)}}),t)}_formatTaskErrorMessage(e){let t="Unable to complete task "+e.name;return e.errorObject.message&&(t+=`: ${e.errorObject.message}`),e.errorObject.exception&&(t+=`: ${e.errorObject.exception}`),t}reset(){return this._isLoading=!1,this._tasks=new Array,this}load(){if(this._isLoading)return this;if(this._isLoading=!0,this._waitingTasksCount=this._tasks.length,this._totalTasksCount=this._tasks.length,0===this._waitingTasksCount)return this._isLoading=!1,this.onFinish&&this.onFinish(this._tasks),this.onTasksDoneObservable.notifyObservers(this._tasks),this;this.useDefaultLoadingScreen&&this._scene.getEngine().displayLoadingUI();for(let e=0;e{this._isLoading?e():(this.onTasksDoneObservable.addOnce((i=>{i&&i.length?t(i):e()})),this.load())}))}}var hR=i(68622),cR=i(26589);class uR{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}}class dR{constructor(e,t){this._meshesOrigins=[],this._toCenterVectors=[],this._scaledDirection=new W.Pq(1,1,1),this._newPosition=W.Pq.Zero(),this._centerPosition=W.Pq.Zero(),this._meshes=e.slice(),t?this._centerMesh=t:this._setCenterMesh(),this._centerMesh.computeWorldMatrix(!0);const i=this._meshes.indexOf(this._centerMesh);i>=0&&this._meshes.splice(i,1),this._centerPosition=this._centerMesh.getAbsolutePosition().clone();for(let e=0;e!0,this.displayLoadingUI=!0,this.loadAsync=(e,t)=>this.useAppend?xg.AppendAsync("file:",e,this._currentScene,t):xg.LoadAsync("file:",e,this._engine,t),this._engine=e,this._currentScene=t,this._sceneLoadedCallback=i,this._progressCallback=r,this._additionalRenderLoopLogicCallback=s,this._textureLoadingCallback=n,this._startingProcessingFilesCallback=o,this._onReloadCallback=a,this._errorCallback=l}monitorElementForDragNDrop(e){e&&(this._elementToMonitor=e,this._dragEnterHandler=e=>{this._drag(e)},this._dragOverHandler=e=>{this._drag(e)},this._dropHandler=e=>{this._drop(e)},this._elementToMonitor.addEventListener("dragenter",this._dragEnterHandler,!1),this._elementToMonitor.addEventListener("dragover",this._dragOverHandler,!1),this._elementToMonitor.addEventListener("drop",this._dropHandler,!1))}get filesToLoad(){return this._filesToLoad}dispose(){this._elementToMonitor&&(this._elementToMonitor.removeEventListener("dragenter",this._dragEnterHandler),this._elementToMonitor.removeEventListener("dragover",this._dragOverHandler),this._elementToMonitor.removeEventListener("drop",this._dropHandler))}_renderFunction(){if(this._additionalRenderLoopLogicCallback&&this._additionalRenderLoopLogicCallback(),this._currentScene){if(this._textureLoadingCallback){const e=this._currentScene.getWaitingItemsCount();e>0&&this._textureLoadingCallback(e)}this._currentScene.render()}}_drag(e){e.stopPropagation(),e.preventDefault()}_drop(e){e.stopPropagation(),e.preventDefault(),this.loadFiles(e)}_traverseFolder(e,t,i,r){const s=e.createReader(),n=e.fullPath.replace(/^\//,"").replace(/(.+?)\/?$/,"$1/");s.readEntries((e=>{i.count+=e.length;for(const s of e)s.isFile?s.file((e=>{e.correctName=n+e.name,t.push(e),0==--i.count&&r()})):s.isDirectory&&this._traverseFolder(s,t,i,r);0==--i.count&&r()}))}_processFiles(e){for(let t=0;tthis._sceneFileToLoad=e))&&(xg.IsPluginForExtensionAvailable("."+r)&&(this._sceneFileToLoad=e[t]),pR.FilesToLoad[i]=e[t])}}loadFiles(e){if(e&&e.dataTransfer&&e.dataTransfer.files&&(this._filesToLoad=e.dataTransfer.files),e&&e.target&&e.target.files&&(this._filesToLoad=e.target.files),this._filesToLoad&&0!==this._filesToLoad.length&&(this._startingProcessingFilesCallback&&this._startingProcessingFilesCallback(this._filesToLoad),this._filesToLoad&&this._filesToLoad.length>0)){const t=[],i=[],r=e.dataTransfer?e.dataTransfer.items:null;for(let e=0;e{this._processFiles(t),0===e.count&&this._processReload()}))}}}_processReload(){this._onReloadCallback?this._onReloadCallback(this._sceneFileToLoad):this.reload()}reload(){if(this._sceneFileToLoad)this.useAppend||this._currentScene&&(Z.V.errorsCount>0&&Z.V.ClearLogCache(),this._engine.stopRenderLoop()),xg.ShowLoadingScreen=!1,this.displayLoadingUI&&this._engine.displayLoadingUI(),this.loadAsync(this._sceneFileToLoad,this._progressCallback).then((e=>{this.useAppend?this.displayLoadingUI&&this._engine.hideLoadingUI():(this._currentScene&&this._currentScene.dispose(),this._currentScene=e,this._currentScene.executeWhenReady((()=>{this.displayLoadingUI&&this._engine.hideLoadingUI(),this._engine.runRenderLoop((()=>{this._renderFunction()}))}))),this._sceneLoadedCallback&&this._currentScene&&this._sceneLoadedCallback(this._sceneFileToLoad,this._currentScene)})).catch((e=>{this.displayLoadingUI&&this._engine.hideLoadingUI(),this._errorCallback&&this._errorCallback(this._sceneFileToLoad,this._currentScene,e.message)}));else{if(1===this._filesToLoad.length){const e=this._filesToLoad[0].name.toLowerCase().split(".").pop();if(e)switch(e.toLowerCase()){case"dds":case"env":case"hdr":return}}Z.V.Error("Please provide a valid .babylon file.")}}}var _R=i(52710);class mR{dispose(){if(this._observers&&this._observables)for(let e=0;e{o.skipNextObservers||i._willBeUnregistered||i.mask&t&&(n=i.scope?n.then((t=>(o.lastReturnValue=t,i.callback.apply(i.scope,[e,o])))):n.then((t=>(o.lastReturnValue=t,i.callback(e,o)))),i.unregisterOnNextCall&&this._deferUnregister(i))})),await n,e};class gR{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}}class vR extends gR{getDescription(){return"Reducing render target texture size to "+this.maximumSize}constructor(e=0,t=1024,i=.5){super(e),this.priority=e,this.maximumSize=t,this.step=i}apply(e,t){let i=!0;for(let t=0;tthis.maximumSize&&(r.scale(this.step),i=!1)}return i}}class xR extends gR{getDescription(){return"Setting hardware scaling level to "+this._currentScale}constructor(e=0,t=2,i=.25){super(e),this.priority=e,this.maximumScale=t,this.step=i,this._currentScale=-1,this._directionOffset=1}apply(e,t){return-1===this._currentScale&&(this._currentScale=e.getEngine().getHardwareScalingLevel(),this._currentScale>this.maximumScale&&(this._directionOffset=-1)),this._currentScale+=this._directionOffset*this.step,e.getEngine().setHardwareScalingLevel(this._currentScale),1===this._directionOffset?this._currentScale>=this.maximumScale:this._currentScale<=this.maximumScale}}class bR extends gR{getDescription(){return"Turning shadows on/off"}apply(e,t){return e.shadowsEnabled=t.isInImprovementMode,!0}}class SR extends gR{getDescription(){return"Turning post-processes on/off"}apply(e,t){return e.postProcessesEnabled=t.isInImprovementMode,!0}}class TR extends gR{getDescription(){return"Turning lens flares on/off"}apply(e,t){return e.lensFlaresEnabled=t.isInImprovementMode,!0}}class CR extends gR{getDescription(){return this.onGetDescription?this.onGetDescription():"Running user defined callback"}apply(e,t){return!this.onApply||this.onApply(e,t)}}class yR extends gR{getDescription(){return"Turning particles on/off"}apply(e,t){return e.particlesEnabled=t.isInImprovementMode,!0}}class ER extends gR{getDescription(){return"Turning render targets off"}apply(e,t){return e.renderTargetsEnabled=t.isInImprovementMode,!0}}class PR extends gR{constructor(){super(...arguments),this._canBeMerged=e=>{if(!(e instanceof Yt))return!1;const t=e;return!(t.isDisposed()||!t.isVisible||!t.isEnabled()||t.instances.length>0||t.skeleton||t.hasLODLevels||0===t.getTotalVertices())}}static get UpdateSelectionTree(){return PR._UpdateSelectionTree}static set UpdateSelectionTree(e){PR._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){const r=e.meshes.slice(0);let s=r.length;for(let e=0;e{this._sceneDisposeObserver=null,this.dispose()}))}stop(){this._isRunning=!1}reset(){this._currentPriorityLevel=0}start(){this._isRunning||(this._isRunning=!0,this._scene.executeWhenReady((()=>{setTimeout((()=>{this._checkCurrentState()}),this._trackerDuration)})))}_checkCurrentState(){if(!this._isRunning)return;const e=this._scene,t=this._options;if(this._currentFrameRate=Math.round(e.getEngine().getFps()),this._improvementMode&&this._currentFrameRate<=this._targetFrameRate||!this._improvementMode&&this._currentFrameRate>=this._targetFrameRate)return this._isRunning=!1,void this.onSuccessObservable.notifyObservers(this);let i=!0,r=!0;for(let s=0;s{setTimeout((()=>{this._checkCurrentState()}),this._trackerDuration)}))}dispose(){this.stop(),this.onSuccessObservable.clear(),this.onFailureObservable.clear(),this.onNewOptimizationAppliedObservable.clear(),this._sceneDisposeObserver&&this._scene.onDisposeObservable.remove(this._sceneDisposeObserver)}static OptimizeAsync(e,t,i,r){const s=new RR(e,t||AR.ModerateDegradationAllowed(),!1);return i&&s.onSuccessObservable.add((()=>{i()})),r&&s.onFailureObservable.add((()=>{r()})),s.start(),s}}let IR=[];const MR=(e,t)=>{e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),IR[e.id]=!0)},OR=(e,t)=>{const i={},r=e._geometry;return r&&(e.getScene().getGeometryById(r.id)||MR(r,t.geometries)),e.serialize&&e.serialize(i),i};class DR{static ClearCache(){IR=[]}static Serialize(e){return DR._Serialize(e)}static _Serialize(e,t=!0){const i={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&vi.g.ForceSerializeBuffers&&Z.V.Warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),DR.ClearCache(),i.useDelayedTextureLoading=e.useDelayedTextureLoading,i.autoClear=e.autoClear,i.clearColor=e.clearColor.asArray(),i.ambientColor=e.ambientColor.asArray(),i.gravity=e.gravity.asArray(),i.collisionsEnabled=e.collisionsEnabled,i.useRightHandedSystem=e.useRightHandedSystem,void 0!==e.fogMode&&null!==e.fogMode&&(i.fogMode=e.fogMode),void 0!==e.fogColor&&null!==e.fogColor&&(i.fogColor=e.fogColor.asArray()),void 0!==e.fogStart&&null!==e.fogStart&&(i.fogStart=e.fogStart),void 0!==e.fogEnd&&null!==e.fogEnd&&(i.fogEnd=e.fogEnd),void 0!==e.fogDensity&&null!==e.fogDensity&&(i.fogDensity=e.fogDensity),e.isPhysicsEnabled&&e.isPhysicsEnabled()){const t=e.getPhysicsEngine();t&&(i.physicsEnabled=!0,i.physicsGravity=t.gravity.asArray(),i.physicsEngine=t.getPhysicsPluginName())}e.metadata&&(i.metadata=e.metadata),i.morphTargetManagers=[];for(const t of e.meshes){const e=t.morphTargetManager;e&&i.morphTargetManagers.push(e.serialize())}let r,s,n;for(i.lights=[],r=0;r0){i.animationGroups=[];for(let t=0;t0)for(i.reflectionProbes=[],r=0;rt))}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;ie[i]=t))):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}else if(e instanceof Object)for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const r=e[i];r instanceof Promise?t.push(r.then((t=>e[i]=t))):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}}static SerializeMesh(e,t=!1,i=!1){const r={meshes:[],transformNodes:[],cameras:[],lights:[]};if(DR.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let r=0;r{e.indexOf(t)<0&&!t.doNotSerialize&&e.push(t)})),t&&e[r].parent&&e.indexOf(e[r].parent)<0&&!e[r].parent.doNotSerialize&&e.push(e[r].parent);return e.forEach((e=>{((e,t)=>{if(e._isMesh){const i=e;if(1===i.delayLoadState||0===i.delayLoadState){const e=e=>{t.materials=t.materials||[],i.material&&!t.materials.some((e=>e.id===i.material.id))&&t.materials.push(e.serialize())};if(i.material&&!i.material.doNotSerialize)if(i.material instanceof kt){if(t.multiMaterials=t.multiMaterials||[],!t.multiMaterials.some((e=>e.id===i.material.id))){t.multiMaterials.push(i.material.serialize());for(const t of i.material.subMaterials)t&&e(t)}}else e(i.material);else i.material||e(i.getScene().defaultMaterial);const r=i._geometry;r&&(t.geometries||(t.geometries={},t.geometries.boxes=[],t.geometries.spheres=[],t.geometries.cylinders=[],t.geometries.toruses=[],t.geometries.grounds=[],t.geometries.planes=[],t.geometries.torusKnots=[],t.geometries.vertexData=[]),MR(r,t.geometries)),i.skeleton&&!i.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(i.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(OR(i,t))}}else if("TransformNode"===e.getClassName()){const i=e;t.transformNodes.push(i.serialize())}else if(-1!==e.getClassName().indexOf("Camera")){const i=e;t.cameras.push(i.serialize())}else if(-1!==e.getClassName().indexOf("Light")){const i=e;t.lights.push(i.serialize())}})(e,r)})),r}}var wR=i(47084),NR=i(46143),FR=i(61951),LR=i(58316),BR=i(96172);class VR{static IsSupported(e,t){const i=t??e.getRenderingCanvas();return!!i&&"function"==typeof i.captureStream}get isRecording(){return!!this._canvas&&this._isRecording}constructor(e,t={}){if(!VR.IsSupported(e,t.canvas))throw"Your browser does not support recording so far.";const i=t.canvas??e.getRenderingCanvas();if(!i)throw"The babylon engine must have a canvas to be recorded";this._canvas=i,this._isRecording=!1,this._options={...VR._DefaultOptions,...t};const r=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(const e of this._options.audioTracks)r.addTrack(e);this._mediaRecorder=new MediaRecorder(r,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=e=>this._handleDataAvailable(e),this._mediaRecorder.onerror=e=>this._handleError(e),this._mediaRecorder.onstop=()=>this._handleStop()}stopRecording(){this._canvas&&this._mediaRecorder&&this.isRecording&&(this._isRecording=!1,this._mediaRecorder.stop())}startRecording(e="babylonjs.webm",t=7){if(!this._canvas||!this._mediaRecorder)throw"Recorder has already been disposed";if(this.isRecording)throw"Recording already in progress";return t>0&&setTimeout((()=>{this.stopRecording()}),1e3*t),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}dispose(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null}_handleDataAvailable(e){e.data.size>0&&this._recordedChunks.push(e.data)}_handleError(e){if(this.stopRecording(),!this._reject)throw new e.error;this._reject(e.error)}_handleStop(){this.stopRecording();const e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&Ue.S0.Download(e,this._fileName)}}VR._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};class kR extends ms.w{getClassName(){return"FxaaPostProcess"}constructor(e,t,i=null,r,s,n,o=0){super(e,"fxaa",["texelSize"],null,t,i,r||vi.g.BILINEAR_SAMPLINGMODE,s,n,null,o,"fxaa",void 0,!0);const a=this._getDefines();this.updateEffect(a),this.onApplyObservable.add((e=>{const t=this.texelSize;e.setFloat2("texelSize",t.x,t.y)}))}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,54525)),Promise.resolve().then(i.bind(i,32439))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,75424)),Promise.resolve().then(i.bind(i,84014))])),super._gatherImports(e,t)}_getDefines(){const e=this.getEngine();return e&&e.extractDriverInfo().toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null}static _Parse(e,t,i,r){return it.p.Parse((()=>new kR(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,r)}}(0,X.Y5)("BABYLON.FxaaPostProcess",kR);var UR=i(465);let GR=null;function zR(e,t,i,r,s="image/png",n=!1,o){const{height:a,width:l}=YR(e,t,i);if(!a||!l)return void Z.V.Error("Invalid 'size' parameter !");GR||(GR=document.createElement("canvas")),GR.width=l,GR.height=a;const h=GR.getContext("2d"),c=e.getRenderWidth()/e.getRenderHeight();let u=l,d=u/c;d>a&&(d=a,u=d*c);const f=Math.max(0,l-u)/2,p=Math.max(0,a-d)/2;t.getScene().activeCamera!==t?XR(e,t,i,(e=>{if(n){const t=new Blob([e]);Ue.S0.DownloadBlob(t),r&&r("")}else r&&r(e)}),s,1,e.getCreationOptions().antialias,void 0,void 0,void 0,void 0,o):e.onEndFrameObservable.addOnce((()=>{const t=e.getRenderingCanvas();h&&t&&h.drawImage(t,f,p,u,d),GR&&(n?(Ue.S0.EncodeScreenshotCanvasData(GR,void 0,s,void 0,o),r&&r("")):Ue.S0.EncodeScreenshotCanvasData(GR,r,s,void 0,o))}))}function WR(e,t,i,r="image/png",s){return new Promise(((n,o)=>{zR(e,t,i,(e=>{void 0!==e?n(e):o(new Error("Data is undefined"))}),r,void 0,s)}))}function HR(e,t,i,r,s="image/png",n){return new Promise((o=>{zR(e,t,{width:i,height:r},(()=>{o()}),s,!0,n)}))}function XR(e,t,r,s,n="image/png",o=1,a=!1,l,h=!1,c=!1,u=!0,d,f){const{height:p,width:_,finalWidth:m,finalHeight:g}=YR(e,t,r),v={width:_,height:p};if(!p||!_)return void Z.V.Error("Invalid 'size' parameter !");const x={width:e.getRenderWidth(),height:e.getRenderHeight()};e.setSize(_,p);const b=t.getScene(),S=new ln.$("screenShot",v,b,!1,!1,0,!1,vi.g.BILINEAR_SAMPLINGMODE,void 0,c,void 0,void 0,void 0,o);S.renderList=b.meshes.slice(),S.samples=o,S.renderSprites=h,S.activeCamera=t,S.forceLayerMaskCheck=u,f?.(S);const T=()=>{S.isReadyForRendering()&&t.isReady(!0)?(e.onEndFrameObservable.addOnce((()=>{m===_&&g===p?S.readPixels(void 0,void 0,void 0,!1).then((e=>{(0,UR.DumpData)(_,p,e,s,n,l,!0,void 0,d),S.dispose()})):(e.isWebGPU?Promise.resolve().then(i.bind(i,418)):Promise.resolve().then(i.bind(i,30927))).then((()=>(0,Ac.Qs)("pass",S.getInternalTexture(),b,void 0,void 0,void 0,m,g).then((t=>{e._readTexturePixels(t,m,g,-1,0,null,!0,!1,0,0).then((e=>{(0,UR.DumpData)(m,g,e,s,n,l,!0,void 0,d),t.dispose()}))}))))})),b.incrementRenderId(),b.resetCachedMaterial(),S.render(!0),e.setSize(x.width,x.height),t.getProjectionMatrix(!0)):setTimeout(T,16)},C=()=>{b.incrementRenderId(),b.resetCachedMaterial(),T()};if(a){const e=new kR("antialiasing",1,b.activeCamera);S.addPostProcess(e),e.onEffectCreatedObservable.addOnce((e=>{e.isReady()?C():e.onCompiled=()=>{C()}}))}else C()}function qR(e,t,i,r="image/png",s=1,n=!1,o,a=!1,l=!1,h=!0,c,u){return new Promise(((d,f)=>{XR(e,t,i,(e=>{void 0!==e?d(e):f(new Error("Data is undefined"))}),r,s,n,o,a,l,h,c,u)}))}function YR(e,t,i){let r=0,s=0,n=0,o=0;if("object"==typeof i){const a=i.precision?Math.abs(i.precision):1;i.width&&i.height?(r=i.height*a,s=i.width*a):i.width&&!i.height?(s=i.width*a,r=Math.round(s/e.getAspectRatio(t))):i.height&&!i.width?(r=i.height*a,s=Math.round(r*e.getAspectRatio(t))):(s=Math.round(e.getRenderWidth()*a),r=Math.round(s/e.getAspectRatio(t))),i.finalWidth&&i.finalHeight?(o=i.finalHeight,n=i.finalWidth):i.finalWidth&&!i.finalHeight?(n=i.finalWidth,o=Math.round(n/e.getAspectRatio(t))):i.finalHeight&&!i.finalWidth?(o=i.finalHeight,n=Math.round(o*e.getAspectRatio(t))):(n=s,o=r)}else isNaN(i)||(r=i,s=i,n=i,o=i);return s&&(s=Math.floor(s)),r&&(r=Math.floor(r)),n&&(n=Math.floor(n)),o&&(o=Math.floor(o)),{height:0|r,width:0|s,finalWidth:0|n,finalHeight:0|o}}const KR={CreateScreenshot:zR,CreateScreenshotAsync:WR,CreateScreenshotWithResizeAsync:HR,CreateScreenshotUsingRenderTarget:XR,CreateScreenshotUsingRenderTargetAsync:qR};var jR;Ue.S0.CreateScreenshot=zR,Ue.S0.CreateScreenshotAsync=WR,Ue.S0.CreateScreenshotUsingRenderTarget=XR,Ue.S0.CreateScreenshotUsingRenderTargetAsync=qR,function(e){e[e.Checkbox=0]="Checkbox",e[e.Slider=1]="Slider",e[e.Vector3=2]="Vector3",e[e.Quaternion=3]="Quaternion",e[e.Color3=4]="Color3",e[e.String=5]="String",e[e.Button=6]="Button",e[e.Options=7]="Options",e[e.Tab=8]="Tab",e[e.FileButton=9]="FileButton",e[e.Vector2=10]="Vector2"}(jR||(jR={}));class $R{constructor(e,t,i){this.gradient=e,this.color1=t,this.color2=i}getColorToRef(e){this.color2?H.ov.LerpToRef(this.color1,this.color2,Math.random(),e):e.copyFrom(this.color1)}}class QR{constructor(e,t){this.gradient=e,this.color=t}}class ZR{constructor(e,t,i){this.gradient=e,this.factor1=t,this.factor2=i}getFactor(){return void 0===this.factor2||this.factor2===this.factor1?this.factor1:this.factor1+(this.factor2-this.factor1)*Math.random()}}class JR{static GetCurrentGradient(e,t,i){if(t[0].gradient>e)return void i(t[0],t[0],1);for(let r=0;r=s.gradient&&e<=n.gradient)return void i(s,n,(e-s.gradient)/(n.gradient-s.gradient))}const r=t.length-1;i(t[r],t[r],1)}}var eI=i(56703);class tI{constructor(e){this.byteOffset=0,this.buffer=e}loadAsync(e){return this.buffer.readAsync(this.byteOffset,e).then((e=>{this._dataView=new DataView(e.buffer,e.byteOffset,e.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(0,bi.Tq)(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}class iI{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch{const e={};return{getItem:t=>{const i=e[t];return void 0===i?null:i},setItem:(t,i)=>{e[t]=i}}}}static ReadString(e,t){const i=this._Storage.getItem(e);return null!==i?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){const i=this._Storage.getItem(e);return null!==i?"true"===i:t}static WriteBoolean(e,t){this._Storage.setItem(e,t?"true":"false")}static ReadNumber(e,t){const i=this._Storage.getItem(e);return null!==i?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}}iI._Storage=iI._GetStorage();class rI{constructor(e){this.particleSystem=e,this.position=W.Pq.Zero(),this.direction=W.Pq.Zero(),this.color=new H.ov(0,0,0,0),this.colorStep=new H.ov(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new W.I9(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new H.ov(0,0,0,0),this._currentColor2=new H.ov(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=rI._Count++,this.particleSystem.isAnimationSheetEnabled&&this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e=this.age,t=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===t?(t=1,e=this._randomCellOffset):e+=this._randomCellOffset);const i=this._initialEndSpriteCellID-this._initialStartSpriteCellID+1;let r;r=this._initialSpriteCellLoop?(0,ar.Clamp)(e*t%this.lifeTime/this.lifeTime):(0,ar.Clamp)(e*t/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+r*i|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){const t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){const e=W.AA.Vector3[0];this.direction.normalizeToRef(e),t.setDirection(e,0,Math.PI/2)}}else e.particleSystem.emitter.copyFrom(this.position);this.direction.scaleToRef(e.inheritedVelocityAmount/2,W.AA.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(W.AA.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach((e=>{this._inheritParticleInfoToSubEmitter(e)}))}_reset(){this.age=0,this.id=rI._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 W.IU(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()))}}rI._Count=0;class sI{constructor(){this.direction1=new W.Pq(0,1,0),this.direction2=new W.Pq(0,1,0),this.minEmitBox=new W.Pq(-.5,-.5,-.5),this.maxEmitBox=new W.Pq(.5,.5,.5)}startDirectionFunction(e,t,i,r){const s=(0,ar.RandomRange)(this.direction1.x,this.direction2.x),n=(0,ar.RandomRange)(this.direction1.y,this.direction2.y),o=(0,ar.RandomRange)(this.direction1.z,this.direction2.z);if(r)return t.x=s,t.y=n,void(t.z=o);W.Pq.TransformNormalFromFloatsToRef(s,n,o,e,t)}startPositionFunction(e,t,i,r){const s=(0,ar.RandomRange)(this.minEmitBox.x,this.maxEmitBox.x),n=(0,ar.RandomRange)(this.minEmitBox.y,this.maxEmitBox.y),o=(0,ar.RandomRange)(this.minEmitBox.z,this.maxEmitBox.z);if(r)return t.x=s,t.y=n,void(t.z=o);W.Pq.TransformCoordinatesFromFloatsToRef(s,n,o,e,t)}clone(){const e=new sI;return ce.r.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){W.Pq.FromArrayToRef(e.direction1,0,this.direction1),W.Pq.FromArrayToRef(e.direction2,0,this.direction2),W.Pq.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),W.Pq.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}var nI,oI=i(61923);class aI extends nv{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get useRampGradients(){return this._useRampGradients}set useRampGradients(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())}get particles(){return this._particles}get shaderLanguage(){return this._shaderLanguage}getActiveCount(){return this._particles.length}getClassName(){return"ParticleSystem"}isStopping(){return this._stopped&&this.isAlive()}getCustomEffect(e=0){return this._customWrappers[e]?.effect??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new gt.E(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 z.cP),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,r=null,s=!1,n=.01){super(e),this._emitterInverseWorldMatrix=W.uq.Identity(),this._inheritedVelocityOffset=new W.Pq,this.onDisposeObservable=new z.cP,this.onStoppedObservable=new z.cP,this._particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new H.ov(0,0,0,0),this._colorDiff=new H.ov(0,0,0,0),this._scaledDirection=W.Pq.Zero(),this._scaledGravity=W.Pq.Zero(),this._currentRenderId=-1,this._useInstancing=!1,this._started=!1,this._stopped=!1,this._actualFrame=0,this._currentEmitRate1=0,this._currentEmitRate2=0,this._currentStartSize1=0,this._currentStartSize2=0,this.updateInAnimate=!0,this._rawTextureWidth=256,this._useRampGradients=!1,this.isLocal=!1,this.isGPU=!1,this._shaderLanguage=0,this._onBeforeDrawParticlesObservable=null,this._emitFromParticle=e=>{},this.recycleParticle=e=>{const t=this._particles.pop();t!==e&&t.copyTo(e),this._stockParticles.push(t)},this._createParticle=()=>{let e;return 0!==this._stockParticles.length?(e=this._stockParticles.pop(),e._reset()):e=new rI(this),this._prepareParticle(e),e},this._shadersLoaded=!1,this._capacity=t,this._epsilon=n,this._isAnimationSheetEnabled=s,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=W.uq.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||he.q.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._initShaderSourceAsync(),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new gt.E(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new sI;let o=null;this.updateFunction=e=>{let t=null;this.noiseTexture&&(t=this.noiseTexture.getSize(),this.noiseTexture.getContent()?.then((e=>{o=e})));const i=e===this._particles;for(let r=0;rs.lifeTime){const e=s.age-a;n=(s.lifeTime-a)*n/e,s.age=s.lifeTime}const l=s.age/s.lifeTime;this._colorGradients&&this._colorGradients.length>0?JR.GetCurrentGradient(l,this._colorGradients,((e,t,i)=>{e!==s._currentColorGradient&&(s._currentColor1.copyFrom(s._currentColor2),t.getColorToRef(s._currentColor2),s._currentColorGradient=e),H.ov.LerpToRef(s._currentColor1,s._currentColor2,i,s.color)})):(s.colorStep.scaleToRef(n,this._scaledColorStep),s.color.addInPlace(this._scaledColorStep),s.color.a<0&&(s.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&JR.GetCurrentGradient(l,this._angularSpeedGradients,((e,t,i)=>{e!==s._currentAngularSpeedGradient&&(s._currentAngularSpeed1=s._currentAngularSpeed2,s._currentAngularSpeed2=t.getFactor(),s._currentAngularSpeedGradient=e),s.angularSpeed=(0,ar.Lerp)(s._currentAngularSpeed1,s._currentAngularSpeed2,i)})),s.angle+=s.angularSpeed*n;let h=n;if(this._velocityGradients&&this._velocityGradients.length>0&&JR.GetCurrentGradient(l,this._velocityGradients,((e,t,i)=>{e!==s._currentVelocityGradient&&(s._currentVelocity1=s._currentVelocity2,s._currentVelocity2=t.getFactor(),s._currentVelocityGradient=e),h*=(0,ar.Lerp)(s._currentVelocity1,s._currentVelocity2,i)})),s.direction.scaleToRef(h,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&JR.GetCurrentGradient(l,this._limitVelocityGradients,((e,t,i)=>{e!==s._currentLimitVelocityGradient&&(s._currentLimitVelocity1=s._currentLimitVelocity2,s._currentLimitVelocity2=t.getFactor(),s._currentLimitVelocityGradient=e);const r=(0,ar.Lerp)(s._currentLimitVelocity1,s._currentLimitVelocity2,i);s.direction.length()>r&&s.direction.scaleInPlace(this.limitVelocityDamping)})),this._dragGradients&&this._dragGradients.length>0&&JR.GetCurrentGradient(l,this._dragGradients,((e,t,i)=>{e!==s._currentDragGradient&&(s._currentDrag1=s._currentDrag2,s._currentDrag2=t.getFactor(),s._currentDragGradient=e);const r=(0,ar.Lerp)(s._currentDrag1,s._currentDrag2,i);this._scaledDirection.scaleInPlace(1-r)})),this.isLocal&&s._localPosition?(s._localPosition.addInPlace(this._scaledDirection),W.Pq.TransformCoordinatesToRef(s._localPosition,this._emitterWorldMatrix,s.position)):s.position.addInPlace(this._scaledDirection),o&&t&&s._randomNoiseCoordinates1){const e=this._fetchR(s._randomNoiseCoordinates1.x,s._randomNoiseCoordinates1.y,t.width,t.height,o),i=this._fetchR(s._randomNoiseCoordinates1.z,s._randomNoiseCoordinates2.x,t.width,t.height,o),r=this._fetchR(s._randomNoiseCoordinates2.y,s._randomNoiseCoordinates2.z,t.width,t.height,o),a=W.AA.Vector3[0],l=W.AA.Vector3[1];a.copyFromFloats((2*e-1)*this.noiseStrength.x,(2*i-1)*this.noiseStrength.y,(2*r-1)*this.noiseStrength.z),a.scaleToRef(n,l),s.direction.addInPlace(l)}this.gravity.scaleToRef(n,this._scaledGravity),s.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&JR.GetCurrentGradient(l,this._sizeGradients,((e,t,i)=>{e!==s._currentSizeGradient&&(s._currentSize1=s._currentSize2,s._currentSize2=t.getFactor(),s._currentSizeGradient=e),s.size=(0,ar.Lerp)(s._currentSize1,s._currentSize2,i)})),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&JR.GetCurrentGradient(l,this._colorRemapGradients,((e,t,i)=>{const r=(0,ar.Lerp)(e.factor1,t.factor1,i),n=(0,ar.Lerp)(e.factor2,t.factor2,i);s.remapData.x=r,s.remapData.y=n-r})),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&JR.GetCurrentGradient(l,this._alphaRemapGradients,((e,t,i)=>{const r=(0,ar.Lerp)(e.factor1,t.factor1,i),n=(0,ar.Lerp)(e.factor2,t.factor2,i);s.remapData.z=r,s.remapData.w=n-r}))),this._isAnimationSheetEnabled&&s.updateCellIndex(),s._inheritParticleInfoToSubEmitters(),s.age>=s.lifeTime&&(this._emitFromParticle(s),s._attachedSubEmitters&&(s._attachedSubEmitters.forEach((e=>{e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()})),s._attachedSubEmitters=null),this.recycleParticle(s),i&&r--)}}}serialize(e){throw new Error("Method not implemented.")}clone(e,t,i=!1){throw new Error("Method not implemented.")}_addFactorGradient(e,t,i,r){const s=new ZR(t,i,r);e.push(s),e.sort(((e,t)=>e.gradientt.gradient?1:0))}_removeFactorGradient(e,t){if(!e)return;let i=0;for(const r of e){if(r.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;const e=new Uint8Array(4*this._rawTextureWidth),t=H.IG.Color3[0];for(let i=0;i{H.v9.LerpToRef(r.color,s.color,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255}))}this._rampGradientsTexture=xi.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 QR(e,t);return this._rampGradients.push(i),this._syncRampGradientTexture(),this}removeRampGradient(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this}addColorGradient(e,t,i){this._colorGradients||(this._colorGradients=[]);const r=new $R(e,t,i);return this._colorGradients.push(r),this._colorGradients.sort(((e,t)=>e.gradientt.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?.dispose();this._drawWrappers=[]}_fetchR(e,t,i,r,s){return s[4*(((e=.5*Math.abs(e)+.5)*i%i|0)+((t=.5*Math.abs(t)+.5)*r%r|0)*i)]/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&&8!==this.billboardMode&&9!==this.billboardMode||(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 st.h(e,this._vertexData,!0,t);let i=0;const r=this._vertexBuffer.createVertexBuffer(st.R.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[st.R.PositionKind]=r,i+=3;const s=this._vertexBuffer.createVertexBuffer(st.R.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[st.R.ColorKind]=s,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 e=this._vertexBuffer.createVertexBuffer("cellIndex",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=e,i+=1}if(!this._isBillboardBased||8===this.billboardMode||9===this.billboardMode){const e=this._vertexBuffer.createVertexBuffer("direction",i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=e,i+=3}if(this._useRampGradients){const e=this._vertexBuffer.createVertexBuffer("remapData",i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=e,i+=4}let a;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new st.h(e,t,!1,2),a=this._spriteBuffer.createVertexBuffer("offset",0,2)}else a=this._vertexBuffer.createVertexBuffer("offset",i,2,this._vertexBufferSize,this._useInstancing),i+=2;this._vertexBuffers.offset=a,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing)return void(this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3])));const e=[],t=[];let i=0;for(let r=0;r{this.start(0)}),e);else{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){-1!==this.emitter?.getClassName().indexOf("Mesh")&&this.emitter.computeWorldMatrix(!0);const e=this.noiseTexture;if(e&&e.onGeneratedObservable)e.onGeneratedObservable.addOnce((()=>{setTimeout((()=>{for(let t=0;t0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}}stop(e=!0){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,this._postStop(e))}_postStop(e){}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,r){let s=e*this._vertexBufferSize;if(this._vertexData[s++]=t.position.x+this.worldOffset.x,this._vertexData[s++]=t.position.y+this.worldOffset.y,this._vertexData[s++]=t.position.z+this.worldOffset.z,this._vertexData[s++]=t.color.r,this._vertexData[s++]=t.color.g,this._vertexData[s++]=t.color.b,this._vertexData[s++]=t.color.a,this._vertexData[s++]=t.angle,this._vertexData[s++]=t.scale.x*t.size,this._vertexData[s++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[s++]=t.cellIndex),this._isBillboardBased)8!==this.billboardMode&&9!==this.billboardMode||(this._vertexData[s++]=t.direction.x,this._vertexData[s++]=t.direction.y,this._vertexData[s++]=t.direction.z);else if(t._initialDirection){let e=t._initialDirection;this.isLocal&&(W.Pq.TransformNormalToRef(e,this._emitterWorldMatrix,W.AA.Vector3[0]),e=W.AA.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}else{let e=t.direction;this.isLocal&&(W.Pq.TransformNormalToRef(e,this._emitterWorldMatrix,W.AA.Vector3[0]),e=W.AA.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}this._useRampGradients&&t.remapData&&(this._vertexData[s++]=t.remapData.x,this._vertexData[s++]=t.remapData.y,this._vertexData[s++]=t.remapData.z,this._vertexData[s++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===r?r=this._epsilon:1===r&&(r=1-this._epsilon)),this._vertexData[s++]=i,this._vertexData[s++]=r)}_prepareParticle(e){}_update(e){if(this._alive=this._particles.length>0,this.emitter.position){const e=this.emitter;this._emitterWorldMatrix=e.getWorldMatrix()}else{const e=this.emitter;this._emitterWorldMatrix=W.uq.Translation(e.x,e.y,e.z)}let t;this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(let i=0;i0){const e=(0,ar.Clamp)(this._actualFrame/this.targetStopDuration);JR.GetCurrentGradient(e,this._lifeTimeGradients,((i,r)=>{const s=i,n=r,o=s.getFactor(),a=n.getFactor(),l=(e-s.gradient)/(n.gradient-s.gradient);t.lifeTime=(0,ar.Lerp)(o,a,l)}))}else t.lifeTime=(0,ar.RandomRange)(this.minLifeTime,this.maxLifeTime);const e=(0,ar.RandomRange)(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(),W.Pq.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),0===e?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(e),this._sizeGradients&&0!==this._sizeGradients.length?(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.size=(0,ar.RandomRange)(this.minSize,this.maxSize),t.scale.copyFromFloats((0,ar.RandomRange)(this.minScaleX,this.maxScaleX),(0,ar.RandomRange)(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){const e=this._actualFrame/this.targetStopDuration;JR.GetCurrentGradient(e,this._startSizeGradients,((e,i,r)=>{e!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=i.getFactor(),this._currentStartSizeGradient=e);const s=(0,ar.Lerp)(this._currentStartSize1,this._currentStartSize2,r);t.scale.scaleInPlace(s)}))}if(this._angularSpeedGradients&&0!==this._angularSpeedGradients.length?(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.angularSpeed=(0,ar.RandomRange)(this.minAngularSpeed,this.maxAngularSpeed),t.angle=(0,ar.RandomRange)(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&&0!==this._colorGradients.length)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);else{const e=(0,ar.RandomRange)(0,1);H.ov.LerpToRef(this.color1,this.color2,e,t.color),this.colorDead.subtractToRef(t.color,this._colorDiff),this._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)}this._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=this.startSpriteCellID,t._initialEndSpriteCellID=this.endSpriteCellID,t._initialSpriteCellLoop=this.spriteCellLoop),t.direction.addInPlace(this._inheritedVelocityOffset),this._useRampGradients&&(t.remapData=new W.IU(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 W.Pq(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new W.Pq(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){const r=[st.R.PositionKind,st.R.ColorKind,"angle","offset","size"];return e&&r.push("cellIndex"),t||r.push("direction"),i&&r.push("remapData"),r}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const r=["invView","view","projection","textureMask","translationPivot","eyePosition"];return(0,Ln.TV)(r),e&&r.push("particlesInfos"),t&&r.push("logarithmicDepthConstant"),i&&(r.push("vFogInfos"),r.push("vFogColor")),r}fillDefines(e,t,i=!0){if(this._scene&&((0,Ln.tv)(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&0!==this._scene.fogMode&&e.push("#define FOG")),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===nv.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"),9===this.billboardMode&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case 7:e.push("#define BILLBOARDMODE_ALL")}i&&this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...aI._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&8!==this.billboardMode&&9!==this.billboardMode,this._useRampGradients)),e.push(...aI._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&((0,oI._)(e,this._imageProcessingConfigurationDefines),(0,oI.C)(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t?.effect)return t;const i=[];this.fillDefines(i,e);const r=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0;let s=this._drawWrappers[r];s||(s=this._drawWrappers[r]=[]);let n=s[e];n||(n=new gt.E(this._engine),n.drawContext&&(n.drawContext.useInstancing=this._useInstancing),s[e]=n);const o=i.join("\n");if(n.defines!==o){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),n.setEffect(this._engine.createEffect("particles",e,t,i,o,void 0,void 0,void 0,void 0,this._shaderLanguage),o)}return n}animate(e=!1){if(!this._started)return;if(!e&&this._scene){if(!this.isReady())return;if(this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}let t;if(this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:this._scene?.getAnimationRatio()||1),this.manualEmitCount>-1)t=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{let e=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){const t=this._actualFrame/this.targetStopDuration;JR.GetCurrentGradient(t,this._emitRateGradients,((t,i,r)=>{t!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=i.getFactor(),this._currentEmitRateGradient=t),e=(0,ar.Lerp)(this._currentEmitRate1,this._currentEmitRate2,r)}))}t=e*this._scaledUpdateSpeed|0,this._newPartsExcess+=e*this._scaledUpdateSpeed-t}if(this._newPartsExcess>1&&(t+=0|this._newPartsExcess,this._newPartsExcess-=0|this._newPartsExcess),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 e=0;for(let t=0;t=0&&(s.invertToRef(W.AA.Matrix[0]),i.setMatrix("invView",W.AA.Matrix[0])),void 0!==this._vertexArrayObject?this._scene?.forceWireframe?r.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,i):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,i)),this._engine.bindVertexArrayObject(this._vertexArrayObject,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?r.bindBuffers(this._vertexBuffers,this._scene?.forceWireframe?this._linesIndexBuffer:this._indexBuffer,i):r.bindBuffers(this._vertexBuffers,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:null,i),this.useLogarithmicDepth&&this._scene&&(0,Bt.DL)(n,i,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(i),e){case nv.BLENDMODE_ADD:r.setAlphaMode(1);break;case nv.BLENDMODE_ONEONE:r.setAlphaMode(6);break;case nv.BLENDMODE_STANDARD:r.setAlphaMode(2);break;case nv.BLENDMODE_MULTIPLY:r.setAlphaMode(4)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(i),this._useInstancing?this._scene?.forceWireframe?r.drawElementsType(6,0,10,this._particles.length):r.drawArraysType(7,0,4,this._particles.length):this._scene?.forceWireframe?r.drawElementsType(1,0,10*this._particles.length):r.drawElementsType(0,0,6*this._particles.length),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 t=this.blendMode===nv.BLENDMODE_MULTIPLYADD?this._render(nv.BLENDMODE_MULTIPLY)+this._render(nv.BLENDMODE_ADD):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 e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}}aI.ForceGLSL=!1,function(e){e[e.ATTACHED=0]="ATTACHED",e[e.END=1]="END"}(nI||(nI={}));class lI{constructor(e){if(this.particleSystem=e,this.type=1,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){const t=(0,X.n9)("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;e?e instanceof W.Pq?e=e.clone():-1!==e.getClassName().indexOf("Mesh")&&(e=new((0,X.n9)("BABYLON.Mesh"))("",e.getScene()),e.isVisible=!1):e=new W.Pq;const t=new lI(this.particleSystem.clone(this.particleSystem.name,e));return t.particleSystem.name+="Clone",t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem._disposeEmitterOnDispose=!0,t.particleSystem.disposeOnStop=!0,t}serialize(e=!1){const t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,r=!1){throw(0,Je.n)("ParseParticle")}static Parse(e,t,i){const r=e.particleSystem,s=new lI(lI._ParseParticleSystem(r,t,i,!0));return s.type=e.type,s.inheritDirection=e.inheritDirection,s.inheritedVelocityAmount=e.inheritedVelocityAmount,s.particleSystem._isSubEmitter=!0,s}dispose(){this.particleSystem.dispose()}}class hI{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(st.R.PositionKind),this._normals=e.getVerticesData(st.R.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=W.Pq.Zero(),this._mesh=null,this.direction1=new W.Pq(0,1,0),this.direction2=new W.Pq(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,r){if(this.useMeshNormalsForDirection&&this._normals)return void W.Pq.TransformNormalToRef(this._storedNormal,e,t);const s=(0,ar.RandomRange)(this.direction1.x,this.direction2.x),n=(0,ar.RandomRange)(this.direction1.y,this.direction2.y),o=(0,ar.RandomRange)(this.direction1.z,this.direction2.z);r?t.copyFromFloats(s,n,o):W.Pq.TransformNormalFromFloatsToRef(s,n,o,e,t)}startPositionFunction(e,t,i,r){if(!this._indices||!this._positions)return;const s=3*Math.random()*(this._indices.length/3)|0,n=Math.random(),o=Math.random()*(1-n),a=1-n-o,l=this._indices[s],h=this._indices[s+1],c=this._indices[s+2],u=W.AA.Vector3[0],d=W.AA.Vector3[1],f=W.AA.Vector3[2],p=W.AA.Vector3[3];W.Pq.FromArrayToRef(this._positions,3*l,u),W.Pq.FromArrayToRef(this._positions,3*h,d),W.Pq.FromArrayToRef(this._positions,3*c,f),p.x=n*u.x+o*d.x+a*f.x,p.y=n*u.y+o*d.y+a*f.y,p.z=n*u.z+o*d.z+a*f.z,r?t.copyFromFloats(p.x,p.y,p.z):W.Pq.TransformCoordinatesFromFloatsToRef(p.x,p.y,p.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(W.Pq.FromArrayToRef(this._normals,3*l,u),W.Pq.FromArrayToRef(this._normals,3*h,d),W.Pq.FromArrayToRef(this._normals,3*c,f),this._storedNormal.x=n*u.x+o*d.x+a*f.x,this._storedNormal.y=n*u.y+o*d.y+a*f.y,this._storedNormal.z=n*u.z+o*d.z+a*f.z)}clone(){const e=new hI(this.mesh);return ce.r.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(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.meshId=this.mesh?.id,e.useMeshNormalsForDirection=this.useMeshNormalsForDirection,e}parse(e,t){W.Pq.FromArrayToRef(e.direction1,0,this.direction1),W.Pq.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}class cI{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,r){const s=W.AA.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,s);const e=W.AA.Vector3[1];s.subtractToRef(i.position,e),e.scaleToRef(1/i.lifeTime,s)}else s.set(0,0,0);r?t.copyFrom(s):W.Pq.TransformNormalToRef(s,e,t)}startPositionFunction(e,t,i,r){const s=W.AA.Vector3[0];this.particlePositionGenerator?this.particlePositionGenerator(-1,i,s):s.set(0,0,0),r?t.copyFrom(s):W.Pq.TransformCoordinatesToRef(s,e,t)}clone(){const e=new cI;return ce.r.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 uI{constructor(){this.direction1=new W.Pq(0,1,0),this.direction2=new W.Pq(0,1,0)}startDirectionFunction(e,t,i,r){const s=(0,ar.RandomRange)(this.direction1.x,this.direction2.x),n=(0,ar.RandomRange)(this.direction1.y,this.direction2.y),o=(0,ar.RandomRange)(this.direction1.z,this.direction2.z);r?t.copyFromFloats(s,n,o):W.Pq.TransformNormalFromFloatsToRef(s,n,o,e,t)}startPositionFunction(e,t,i,r){r?t.copyFromFloats(0,0,0):W.Pq.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){const e=new uI;return ce.r.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){W.Pq.FromArrayToRef(e.direction1,0,this.direction1),W.Pq.FromArrayToRef(e.direction2,0,this.direction2)}}class dI{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){const s=i.position.subtract(e.getTranslation()).normalize(),n=(0,ar.RandomRange)(0,this.directionRandomizer),o=(0,ar.RandomRange)(0,this.directionRandomizer),a=(0,ar.RandomRange)(0,this.directionRandomizer);s.x+=n,s.y+=o,s.z+=a,s.normalize(),r?t.copyFrom(s):W.Pq.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,r){const s=this.radius-(0,ar.RandomRange)(0,this.radius*this.radiusRange),n=(0,ar.RandomRange)(0,1),o=(0,ar.RandomRange)(0,2*Math.PI),a=Math.acos(2*n-1),l=s*Math.cos(o)*Math.sin(a),h=s*Math.cos(a),c=s*Math.sin(o)*Math.sin(a);r?t.copyFromFloats(l,Math.abs(h),c):W.Pq.TransformCoordinatesFromFloatsToRef(l,Math.abs(h),c,e,t)}clone(){const e=new dI(this.radius,this.directionRandomizer);return ce.r.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 fI{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){const s=i.position.subtract(e.getTranslation()).normalize(),n=(0,ar.RandomRange)(0,this.directionRandomizer),o=(0,ar.RandomRange)(0,this.directionRandomizer),a=(0,ar.RandomRange)(0,this.directionRandomizer);s.x+=n,s.y+=o,s.z+=a,s.normalize(),r?t.copyFrom(s):W.Pq.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,r){const s=this.radius-(0,ar.RandomRange)(0,this.radius*this.radiusRange),n=(0,ar.RandomRange)(0,1),o=(0,ar.RandomRange)(0,2*Math.PI),a=Math.acos(2*n-1),l=s*Math.cos(o)*Math.sin(a),h=s*Math.cos(a),c=s*Math.sin(o)*Math.sin(a);r?t.copyFromFloats(l,h,c):W.Pq.TransformCoordinatesFromFloatsToRef(l,h,c,e,t)}clone(){const e=new fI(this.radius,this.directionRandomizer);return ce.r.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 pI extends fI{constructor(e=1,t=new W.Pq(0,1,0),i=new W.Pq(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){const i=(0,ar.RandomRange)(this.direction1.x,this.direction2.x),r=(0,ar.RandomRange)(this.direction1.y,this.direction2.y),s=(0,ar.RandomRange)(this.direction1.z,this.direction2.z);W.Pq.TransformNormalFromFloatsToRef(i,r,s,e,t)}clone(){const e=new pI(this.radius,this.direction1,this.direction2);return ce.r.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\n#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 _I{constructor(e=1,t=1,i=1,r=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=r,this._tempVector=W.Pq.Zero()}startDirectionFunction(e,t,i,r,s){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),W.Pq.TransformNormalToRef(this._tempVector,s,this._tempVector);const n=(0,ar.RandomRange)(-this.directionRandomizer/2,this.directionRandomizer/2);let o=Math.atan2(this._tempVector.x,this._tempVector.z);o+=(0,ar.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(),r?t.copyFrom(this._tempVector):W.Pq.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,r){const s=(0,ar.RandomRange)(-this.height/2,this.height/2),n=(0,ar.RandomRange)(0,2*Math.PI),o=(0,ar.RandomRange)((1-this.radiusRange)*(1-this.radiusRange),1),a=Math.sqrt(o)*this.radius,l=a*Math.cos(n),h=a*Math.sin(n);r?t.copyFromFloats(l,s,h):W.Pq.TransformCoordinatesFromFloatsToRef(l,s,h,e,t)}clone(){const e=new _I(this.radius,this.directionRandomizer);return ce.r.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 mI extends _I{constructor(e=1,t=1,i=1,r=new W.Pq(0,1,0),s=new W.Pq(0,1,0)){super(e,t,i),this.direction1=r,this.direction2=s}startDirectionFunction(e,t,i,r){const s=(0,ar.RandomRange)(this.direction1.x,this.direction2.x),n=(0,ar.RandomRange)(this.direction1.y,this.direction2.y),o=(0,ar.RandomRange)(this.direction1.z,this.direction2.z);r?t.copyFromFloats(s,n,o):W.Pq.TransformNormalFromFloatsToRef(s,n,o,e,t)}clone(){const e=new mI(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return ce.r.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\n#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),W.Pq.FromArrayToRef(e.direction1,0,this.direction1),W.Pq.FromArrayToRef(e.direction2,0,this.direction2)}}class gI{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(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,r){r?W.AA.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),W.AA.Vector3[0]).normalize();const s=(0,ar.RandomRange)(0,this.directionRandomizer),n=(0,ar.RandomRange)(0,this.directionRandomizer),o=(0,ar.RandomRange)(0,this.directionRandomizer);t.x=W.AA.Vector3[0].x+s,t.y=W.AA.Vector3[0].y+n,t.z=W.AA.Vector3[0].z+o,t.normalize()}startPositionFunction(e,t,i,r){const s=(0,ar.RandomRange)(0,2*Math.PI);let n;this.emitFromSpawnPointOnly?n=1e-4:(n=(0,ar.RandomRange)(0,this.heightRange),n=1-n*n);let o=this._radius-(0,ar.RandomRange)(0,this._radius*this.radiusRange);o*=n;const a=o*Math.sin(s),l=o*Math.cos(s),h=n*this._height;if(r)return t.x=a,t.y=h,void(t.z=l);W.Pq.TransformCoordinatesFromFloatsToRef(a,h,l,e,t)}clone(){const e=new gI(this._radius,this._angle,this.directionRandomizer);return ce.r.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+="\n#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=void 0!==e.radiusRange?e.radiusRange:1,this.heightRange=void 0!==e.radiusRange?e.heightRange:1,this.emitFromSpawnPointOnly=void 0!==e.emitFromSpawnPointOnly&&e.emitFromSpawnPointOnly}}class vI extends gI{constructor(e=1,t=Math.PI,i=new W.Pq(0,1,0),r=new W.Pq(0,1,0)){super(e,t),this.direction1=i,this.direction2=r}startDirectionFunction(e,t){const i=(0,ar.RandomRange)(this.direction1.x,this.direction2.x),r=(0,ar.RandomRange)(this.direction1.y,this.direction2.y),s=(0,ar.RandomRange)(this.direction1.z,this.direction2.z);W.Pq.TransformNormalFromFloatsToRef(i,r,s,e,t)}clone(){const e=new vI(this.radius,this.angle,this.direction1,this.direction2);return ce.r.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define CONEEMITTER\n#define DIRECTEDCONEEMITTER"}getClassName(){return"ConeDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}function xI(e,t){const i=new uI;return i.direction1=e,i.direction2=t,i}function bI(e=1,t=1){return new dI(e,t)}function SI(e=1,t=1){return new fI(e,t)}function TI(e=1,t=new W.Pq(0,1,0),i=new W.Pq(0,1,0)){return new pI(e,t,i)}function CI(e=1,t=1,i=1,r=0){return new _I(e,t,i,r)}function yI(e=1,t=1,i=1,r=new W.Pq(0,1,0),s=new W.Pq(0,1,0)){return new mI(e,t,i,r,s)}function EI(e=1,t=Math.PI/4){return new gI(e,t)}function PI(e=1,t=Math.PI/4,i=new W.Pq(0,1,0),r=new W.Pq(0,1,0)){return new vI(e,t,i,r)}class AI extends aI{constructor(){super(...arguments),this._disposeEmitterOnDispose=!1,this._emitFromParticle=e=>{if(!this._subEmitters||0===this._subEmitters.length)return;const t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach((t=>{if(1===t.type){const i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}}))}}createPointEmitter(e,t){const i=xI(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=bI(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=SI(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new W.Pq(0,1,0),i=new W.Pq(0,1,0)){const r=TI(e,t,i);return this.particleEmitterType=r,r}createCylinderEmitter(e=1,t=1,i=1,r=0){const s=CI(e,t,i,r);return this.particleEmitterType=s,s}createDirectedCylinderEmitter(e=1,t=1,i=1,r=new W.Pq(0,1,0),s=new W.Pq(0,1,0)){const n=yI(e,t,i,r,s);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=EI(e,t);return this.particleEmitterType=i,i}createDirectedConeEmitter(e=1,t=Math.PI/4,i=new W.Pq(0,1,0),r=new W.Pq(0,1,0)){const s=PI(e,t,i,r);return this.particleEmitterType=s,s}createBoxEmitter(e,t,i,r){const s=new sI;return this.particleEmitterType=s,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=r,s}_prepareSubEmitterInternalArray(){this._subEmitters=new Array,this.subEmitters&&this.subEmitters.forEach((e=>{e instanceof AI?this._subEmitters.push([new lI(e)]):e instanceof lI?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);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_preStart(){this._prepareSubEmitterInternalArray(),this._subEmitters&&0!=this._subEmitters.length&&(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((t=>{if(0===t.type){const i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}}))}}_onDispose(e=!1,t=!1){if(this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),e&&this.particles?.forEach((e=>{if(e._attachedSubEmitters)for(let t=e._attachedSubEmitters.length-1;t>=0;t-=1)e._attachedSubEmitters[t].dispose()})),t&&this.activeSubSystems)for(let e=this.activeSubSystems.length-1;e>=0;e-=1)this.activeSubSystems[e].dispose();if(this._subEmitters&&this._subEmitters.length){for(let e=0;e0?h.shaderOptions.defines.join("\n"):"";l=o.createEffectForParticles(h.shaderPath.fragmentElement,h.shaderOptions.uniforms,h.shaderOptions.samplers,t)}const c=new AI(n,s||e.capacity,t,l,e.isAnimationSheetEnabled);if(c.customShader=h,c._rootUrl=i,e.id&&(c.id=e.id),e.subEmitters){c.subEmitters=[];for(const r of e.subEmitters){const e=[];for(const s of r)e.push(lI.Parse(s,t,i));c.subEmitters.push(e)}}return AI._Parse(e,c,t,i),e.textureMask&&(c.textureMask=H.ov.FromArray(e.textureMask)),e.worldOffset&&(c.worldOffset=W.Pq.FromArray(e.worldOffset)),e.preventAutoStart&&(c.preventAutoStart=e.preventAutoStart),r||c.preventAutoStart||c.start(),c}serialize(e=!1){const t={};if(AI._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,t.worldOffset=this.worldOffset.asArray(),this.subEmitters){t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(const i of this._subEmitters){const r=[];for(const t of i)r.push(t.serialize(e));t.subEmitters.push(r)}}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){const i=t.emitter;e.emitterId=i.id}else{const i=t.emitter;e.emitter=i.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,it.p.AppendSerializedAnimations(t,e),e.beginAnimationOnStart=t.beginAnimationOnStart,e.beginAnimationFrom=t.beginAnimationFrom,e.beginAnimationTo=t.beginAnimationTo,e.beginAnimationLoop=t.beginAnimationLoop,e.startDelay=t.startDelay,e.renderingGroupId=t.renderingGroupId,e.isBillboardBased=t.isBillboardBased,e.billboardMode=t.billboardMode,e.minAngularSpeed=t.minAngularSpeed,e.maxAngularSpeed=t.maxAngularSpeed,e.minSize=t.minSize,e.maxSize=t.maxSize,e.minScaleX=t.minScaleX,e.maxScaleX=t.maxScaleX,e.minScaleY=t.minScaleY,e.maxScaleY=t.maxScaleY,e.minEmitPower=t.minEmitPower,e.maxEmitPower=t.maxEmitPower,e.minLifeTime=t.minLifeTime,e.maxLifeTime=t.maxLifeTime,e.emitRate=t.emitRate,e.gravity=t.gravity.asArray(),e.noiseStrength=t.noiseStrength.asArray(),e.color1=t.color1.asArray(),e.color2=t.color2.asArray(),e.colorDead=t.colorDead.asArray(),e.updateSpeed=t.updateSpeed,e.targetStopDuration=t.targetStopDuration,e.blendMode=t.blendMode,e.preWarmCycles=t.preWarmCycles,e.preWarmStepOffset=t.preWarmStepOffset,e.minInitialRotation=t.minInitialRotation,e.maxInitialRotation=t.maxInitialRotation,e.startSpriteCellID=t.startSpriteCellID,e.spriteCellLoop=t.spriteCellLoop,e.endSpriteCellID=t.endSpriteCellID,e.spriteCellChangeSpeed=t.spriteCellChangeSpeed,e.spriteCellWidth=t.spriteCellWidth,e.spriteCellHeight=t.spriteCellHeight,e.spriteRandomStartCell=t.spriteRandomStartCell,e.isAnimationSheetEnabled=t.isAnimationSheetEnabled,e.useLogarithmicDepth=t.useLogarithmicDepth;const r=t.getColorGradients();if(r){e.colorGradients=[];for(const t of r){const i={gradient:t.gradient,color1:t.color1.asArray()};t.color2?i.color2=t.color2.asArray():i.color2=t.color1.asArray(),e.colorGradients.push(i)}}const s=t.getRampGradients();if(s){e.rampGradients=[];for(const t of s){const i={gradient:t.gradient,color:t.color.asArray()};e.rampGradients.push(i)}e.useRampGradients=t.useRampGradients}const n=t.getColorRemapGradients();if(n){e.colorRemapGradients=[];for(const t of n){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.colorRemapGradients.push(i)}}const o=t.getAlphaRemapGradients();if(o){e.alphaRemapGradients=[];for(const t of o){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.alphaRemapGradients.push(i)}}const a=t.getSizeGradients();if(a){e.sizeGradients=[];for(const t of a){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.sizeGradients.push(i)}}const l=t.getAngularSpeedGradients();if(l){e.angularSpeedGradients=[];for(const t of l){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.angularSpeedGradients.push(i)}}const h=t.getVelocityGradients();if(h){e.velocityGradients=[];for(const t of h){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.velocityGradients.push(i)}}const c=t.getDragGradients();if(c){e.dragGradients=[];for(const t of c){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.dragGradients.push(i)}}const u=t.getEmitRateGradients();if(u){e.emitRateGradients=[];for(const t of u){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.emitRateGradients.push(i)}}const d=t.getStartSizeGradients();if(d){e.startSizeGradients=[];for(const t of d){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.startSizeGradients.push(i)}}const f=t.getLifeTimeGradients();if(f){e.lifeTimeGradients=[];for(const t of f){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.lifeTimeGradients.push(i)}}const p=t.getLimitVelocityGradients();if(p){e.limitVelocityGradients=[];for(const t of p){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.limitVelocityGradients.push(i)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}clone(e,t,i=!1){const r={...this._customWrappers};let s=null;const n=this._engine;if(n.createEffectForParticles&&null!=this.customShader){s=this.customShader;const e=s.shaderOptions.defines.length>0?s.shaderOptions.defines.join("\n"):"",t=n.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e);r[0]?r[0].effect=t:this.setCustomEffect(t,0)}const o=this.serialize(i),a=AI.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=s,a._customWrappers=r,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,this.preventAutoStart||a.start(),a}}AI.BILLBOARDMODE_Y=2,AI.BILLBOARDMODE_ALL=7,AI.BILLBOARDMODE_STRETCHED=8,AI.BILLBOARDMODE_STRETCHED_LOCAL=9,lI._ParseParticleSystem=AI.Parse;class RI{constructor(){this._trackedScene=null}track(e){this._trackedScene=e,it.p.AllowLoadingUniqueId=!0,this._savedJSON=DR.Serialize(e),it.p.AllowLoadingUniqueId=!1}getDelta(){if(!this._trackedScene)return null;const e=vi.g.ForceSerializeBuffers;vi.g.ForceSerializeBuffers=!1,it.p.AllowLoadingUniqueId=!0;const t=DR.Serialize(this._trackedScene);it.p.AllowLoadingUniqueId=!1;const i={};for(const e in t)this._compareCollections(e,this._savedJSON[e],t[e],i);return vi.g.ForceSerializeBuffers=e,i}_compareArray(e,t,i,r){if(0===t.length&&0===i.length)return!0;if(t.length&&!isNaN(t[0])||i.length&&!isNaN(i[0])){if(t.length!==i.length)return!1;if(0===t.length)return!0;for(let s=0;se.uniqueId===a));if(l.length){const t=l[0],i={};this._compareObjects(o,t,i)||(r[e]||(r[e]=[]),i.__state={id:t.id||t.name},r[e].push(i))}else{const t={__state:{deleteId:o.id||o.name}};r[e]||(r[e]=[]),r[e].push(t)}}for(let t=0;te.getShadowGenerators()));for(const e of i)if(e){const i=e.values();for(let e=i.next();!0!==e.done;e=i.next()){const i=e.value;if(i&&i.id===t)return i}}return null}static ApplyDelta(e,t){"string"==typeof e&&(e=JSON.parse(e));const i=t;for(const r in e){const s=e[r],n=i[r];if(Array.isArray(n)||"shadowGenerators"===r)switch(r){case"cameras":this._ApplyDeltaForEntity(s,t,t.getCameraById.bind(t),(e=>rt.Parse(e,t)));break;case"lights":this._ApplyDeltaForEntity(s,t,t.getLightById.bind(t),(e=>$t.Parse(e,t)));break;case"shadowGenerators":this._ApplyDeltaForEntity(s,t,(e=>this.GetShadowGeneratorById(t,e)),(e=>ux.Parse(e,t)));break;case"meshes":this._ApplyDeltaForEntity(s,t,t.getMeshById.bind(t),(e=>Yt.Parse(e,t,"")));break;case"skeletons":this._ApplyDeltaForEntity(s,t,t.getSkeletonById.bind(t),(e=>Ti.Parse(e,t)));break;case"materials":this._ApplyDeltaForEntity(s,t,t.getMaterialById.bind(t),(e=>Vt.Parse(e,t,"")));break;case"multiMaterials":this._ApplyDeltaForEntity(s,t,t.getMaterialById.bind(t),(e=>kt.Parse(e,t,"")));break;case"transformNodes":this._ApplyDeltaForEntity(s,t,t.getTransformNodeById.bind(t),(e=>Pt.Parse(e,t,"")));break;case"particleSystems":this._ApplyDeltaForEntity(s,t,t.getParticleSystemById.bind(t),(e=>AI.Parse(e,t,"")));break;case"morphTargetManagers":this._ApplyDeltaForEntity(s,t,t.getMorphTargetById.bind(t),(e=>Gx.Parse(e,t)));break;case"postProcesses":this._ApplyDeltaForEntity(s,t,t.getPostProcessByName.bind(t),(e=>ms.w.Parse(e,t,"")))}else isNaN(n)?n.fromArray&&n.fromArray(s):i[r]=s}}static _ApplyPropertiesToEntity(e,t){for(const i in e){const r=e[i],s=t[i];void 0!==s&&(!isNaN(s)||Array.isArray(s)?t[i]=r:s.fromArray?s.fromArray(r):"object"==typeof s&&null!==s&&this._ApplyPropertiesToEntity(r,s))}}static _ApplyDeltaForEntity(e,t,i,r){for(const s of e)if(s.__state&&void 0!==s.__state.id){const e=i(s.__state.id);e&&(this._ApplyPropertiesToEntity(s,e),it.p.ParseProperties(s,e,t,null))}else if(s.__state&&void 0!==s.__state.deleteId){const e=i(s.__state.deleteId);e?.dispose()}else r(s)}}var II,MI=i(27606);!function(e){class t{serialize(){const e={},t=new Array(this._characterToIdx.size);return this._characterToIdx.forEach(((e,i)=>{t[e]=i})),e.characters=t,e.insertionCosts=this._insertionCosts,e.deletionCosts=this._deletionCosts,e.substitutionCosts=this._substitutionCosts,JSON.stringify(e)}static Deserialize(e){const i=JSON.parse(e),r=new t(i.characters);return r._insertionCosts=i.insertionCosts,r._deletionCosts=i.deletionCosts,r._substitutionCosts=i.substitutionCosts,r}constructor(e,t=null,i=null,r=null){let s;t=t??(()=>1),i=i??(()=>1),r=r??((e,t)=>e===t?0:1),this._characterToIdx=new Map,this._insertionCosts=new Array(e.length),this._deletionCosts=new Array(e.length),this._substitutionCosts=new Array(e.length);for(let n=0;ni._MAX_SEQUENCE_LENGTH)throw new Error("Sequences longer than "+i._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=t,this._characters=e.map((e=>this._alphabet.getCharacterIdx(e)))}distance(e){return i._Distance(this,e)}static _Distance(e,t){const r=e._alphabet;if(r!==t._alphabet)throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");const s=e._characters,n=t._characters,o=s.length,a=n.length,l=i._CostMatrix;l[0][0]=0;for(let e=0;enew Array(i._MAX_SEQUENCE_LENGTH+1))),e.Sequence=i}(II||(II={}));class OI{serialize(){return JSON.stringify(this)}static Deserialize(e){const t=JSON.parse(e),i=new OI(t._segmentLength);return i._points=t._points.map((e=>new W.Pq(e._x,e._y,e._z))),i}constructor(e=.01){this._points=[],this._segmentLength=e}getLength(){return this._points.length*this._segmentLength}add(e){let t=this._points.length;if(0===t)this._points.push(e.clone());else{const i=()=>this._segmentLength/W.Pq.Distance(this._points[t-1],e);for(let r=i();r<=1;r=i()){const i=this._points[t-1].scale(1-r);e.scaleAndAddToRef(r,i),this._points.push(i),++t}}}resampleAtTargetResolution(e){const t=new OI(this.getLength()/e);return this._points.forEach((e=>{t.add(e)})),t}tokenize(e){const t=[],i=new W.Pq;for(let r=2;r.98||(W.Pq.CrossToRef(OI._ForwardDir,OI._InverseFromVec,OI._UpDir),OI._UpDir.normalize(),W.uq.LookAtLHToRef(e,t,OI._UpDir,OI._LookMatrix),i.subtractToRef(t,OI._FromToVec),OI._FromToVec.normalize(),W.Pq.TransformNormalToRef(OI._FromToVec,OI._LookMatrix,r),0))}static _TokenizeSegment(e,t){OI._BestMatch=0,OI._Score=W.Pq.Dot(e,t[0]),OI._BestScore=OI._Score;for(let i=1;iOI._BestScore&&(OI._BestMatch=i,OI._BestScore=OI._Score);return OI._BestMatch}}OI._ForwardDir=new W.Pq,OI._InverseFromVec=new W.Pq,OI._UpDir=new W.Pq,OI._FromToVec=new W.Pq,OI._LookMatrix=new W.uq;class DI{static Generate(e=64,t=256,i=.1,r=.001,s=[]){const n=new DI(e);for(let t=0;t{n.chars[e].subtractToRef(t,h),a=h.lengthSquared(),a>1e-6&&h.scaleAndAddToRef(1/(h.lengthSquared()*a),l)})),l.scaleInPlace(o),n.chars[e].addInPlace(l),n.chars[e].normalize()}var c;return n}serialize(){return JSON.stringify(this.chars)}static Deserialize(e){const t=JSON.parse(e),i=new DI(t.length);for(let e=0;ee.serialize())))}static Deserialize(e,t){const i=new wI;return i._sequences=JSON.parse(e).map((e=>II.Sequence.Deserialize(e,t))),i}static CreateFromTrajectory(e,t,i){return wI.CreateFromTokenizationPyramid(wI._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){const i=new wI;return i._sequences=e.map((e=>new II.Sequence(e,t))),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=wI._FINEST_DESCRIPTOR_RESOLUTION){const r=[];for(let s=i;s>4;s=Math.floor(s/2))r.push(e.resampleAtTargetResolution(s).tokenize(t.chars));return r}distance(e){let t,i=0;for(let r=0;re.serialize())),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){const i=JSON.parse(e),r=new NI;return r._descriptors=i.descriptors.map((e=>wI.Deserialize(e,t))),r._centroidIdx=i.centroidIdx,r._averageDistance=i.averageDistance,r}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map((t=>t.distance(e))))}_refreshDescription(){let e;this._centroidIdx=-1;const t=this._descriptors.map((t=>(e=0,this._descriptors.forEach((i=>{e+=t.distance(i)})),e)));for(let e=0;e{this._averageDistance+=e.distance(this._descriptors[this._centroidIdx])})),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,NI._MIN_AVERAGE_DISTANCE))}}NI._MIN_AVERAGE_DISTANCE=1;class FI{serialize(){const e={};return e.maximumAllowableMatchCost=this._maximumAllowableMatchCost,e.vector3Alphabet=this._vector3Alphabet.serialize(),e.levenshteinAlphabet=this._levenshteinAlphabet.serialize(),e.nameToDescribedTrajectory=[],this._nameToDescribedTrajectory.forEach(((t,i)=>{e.nameToDescribedTrajectory.push(i),e.nameToDescribedTrajectory.push(t.serialize())})),JSON.stringify(e)}static Deserialize(e){const t=JSON.parse(e),i=new FI;i._maximumAllowableMatchCost=t.maximumAllowableMatchCost,i._vector3Alphabet=DI.Deserialize(t.vector3Alphabet),i._levenshteinAlphabet=II.Alphabet.Deserialize(t.levenshteinAlphabet);for(let e=0;e0===e?0:1),(e=>0===e?0:1),((t,i)=>Math.min(1-W.Pq.Dot(e.chars[t],e.chars[i]),1))),r=new FI;return r._vector3Alphabet=e,r._levenshteinAlphabet=i,r}constructor(){this._maximumAllowableMatchCost=4,this._nameToDescribedTrajectory=new Map}addTrajectoryToClassification(e,t){this._nameToDescribedTrajectory.has(t)||this._nameToDescribedTrajectory.set(t,new NI),this._nameToDescribedTrajectory.get(t).add(wI.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet))}deleteClassification(e){return this._nameToDescribedTrajectory.delete(e)}classifyTrajectory(e){const t=wI.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet),i=[];if(this._nameToDescribedTrajectory.forEach(((e,r)=>{e.getMatchCost(t){const t=e.data;if(t.startsWith(BI._SERVER_PREFIX)){const e=t.substring(BI._SERVER_PREFIX.length);return Z.V.Log(`[Reflector] Received server message: ${e.substring(0,64)}`),void this._handleServerMessage(e)}Z.V.Log(`[Reflector] Received client message: ${t.substring(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=e=>{Z.V.Log(`[Reflector] Disconnected ${e.code} ${e.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){"connected"===e&&DR.SerializeAsync(this._scene).then((e=>{this._webSocket.send(`load|${JSON.stringify(e)}`)}))}_handleClientMessage(){}}BI._SERVER_PREFIX="$$";class VI{constructor(e){this._observer=null,this._currentState=[],this.onPressureChanged=new z.cP,VI.IsAvailable&&(this._observer=new PressureObserver((e=>{this._currentState=e,this.onPressureChanged.notifyObservers(e)}),e))}static get IsAvailable(){return"undefined"!=typeof PressureObserver&&PressureObserver.knownSources&&PressureObserver.knownSources.includes("cpu")}observe(e){try{this._observer?.observe(e),this.onPressureChanged.notifyObservers(this._currentState)}catch{}}unobserve(e){try{this._observer?.unobserve(e)}catch{}}dispose(){this._observer?.disconnect(),this._observer=null,this.onPressureChanged.clear()}}class kI{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(1.5*this._view.length),t=new Float32Array(e);t.set(this._view),this._view=t}}const UI=1800,GI="timestamp",zI="numPoints",WI=/\r/g;class HI{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{const e=ai.j.Now-this._startingTimestamp,t=this.datasets.ids.length,i=this.datasets.startingIndices.itemLength;let r=0;if(i>0){const e=this.datasets.startingIndices.at(i-1);r=e+this.datasets.data.at(e+HI.NumberOfPointsOffset)+HI.SliceDataOffset}if(this.datasets.startingIndices.push(r),this.datasets.data.push(e),this.datasets.data.push(t),this.datasets.ids.forEach((e=>{const t=this._strategies.get(e);t&&this.datasets.data.push(t.getData())})),this.datasetObservable.hasObservers()){const i=[e,t];for(let e=0;ee.callback(this._datasetMeta,new z.qO(0)))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){if(this._strategies.has(e)&&!t)return;this._strategies.has(e)&&t&&(this._strategies.get(e)?.dispose(),this._strategies.delete(e));const r={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:t=>{let i=0,r=0;const s=t.onAfterRenderObservable.add((()=>{r=i,i=0})),n=this._customEventObservable.add((t=>{e===t.name&&(void 0!==t.value?i=t.value:i++)}));return{id:e,getData:()=>r,dispose:()=>{t.onAfterRenderObservable.remove(s),this._customEventObservable.remove(n)}}},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:r}of e){const e=t(this._scene);this._strategies.has(e.id)?e.dispose():(this.datasets.ids.push(e.id),i&&(i=i.replace(new RegExp("@","g"),"")),this._datasetMeta.set(e.id,{color:this._getHexColorFromId(e.id),category:i,hidden:r}),this._strategies.set(e.id,e))}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let i=0;i>e&255).toString(16);i+=r.substring(r.length-2)}return i}getCurrentSlice(){const e=[ai.j.Now-this._startingTimestamp,this.datasets.ids.length];this.datasets.ids.forEach((t=>{const i=this._strategies.get(t);i&&this.datasetObservable.hasObservers()&&e.push(i.getData())})),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(e)}updateMetadata(e,t,i){const r=this._datasetMeta.get(e);r&&(r[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new kI(UI),this.datasets.ids.length=0,this.datasets.startingIndices=new kI(UI),this._datasetMeta.clear(),this._strategies.forEach((e=>e.dispose())),this._strategies.clear(),e||this._eventRestoreSet.clear(),this._hasLoadedData=!1}get hasLoadedData(){return this._hasLoadedData}loadFromFileData(e,t){const i=e.replace(WI,"").split("\n").map((e=>e.split(",").filter((e=>e.length>0)))).filter((e=>e.length>0)),r=HI.NumberOfPointsOffset;if(i.length<2)return!1;const s={ids:[],data:new kI(UI),startingIndices:new kI(UI)},[n,...o]=i;if(n.length<2||n[0]!==GI||n[r]!==zI)return!1;const a=new Map;for(let e=HI.SliceDataOffset;ee.dispose())),this._strategies.clear(),!t)for(const e of this.datasets.ids){const t=a.get(e);this._datasetMeta.set(e,{category:t,color:this._getHexColorFromId(e)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${GI},${zI}`;for(let t=0;t{e.dispose()})),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}const XI=()=>{};class qI{static FpsStrategy(){return e=>{const t=e.getEngine();return{id:"FPS",getData:()=>t.getFps(),dispose:XI}}}static ThermalStrategy(){return this._PressureStrategy("Thermal utilization","thermal")}static PowerSupplyStrategy(){return this._PressureStrategy("Power supply utilization","power-supply")}static PressureStrategy(){return this._PressureStrategy("Pressure")}static _PressureStrategy(e,t=null){return()=>{let i=0;const r=new VI;return r.observe("cpu"),r.onPressureChanged.add((e=>{for(const r of e)if(t&&r.factors.includes(t)||!t&&0===(r.factors?.length??0))switch(r.state){case"nominal":i=0;break;case"fair":i=.25;break;case"serious":i=.5;break;case"critical":i=1}})),{id:e,getData:()=>i,dispose:()=>r.dispose()}}}static TotalMeshesStrategy(){return e=>({id:"Total meshes",getData:()=>e.meshes.length,dispose:XI})}static ActiveMeshesStrategy(){return e=>({id:"Active meshes",getData:()=>e.getActiveMeshes().length,dispose:XI})}static ActiveIndicesStrategy(){return e=>({id:"Active indices",getData:()=>e.getActiveIndices(),dispose:XI})}static ActiveFacesStrategy(){return e=>({id:"Active faces",getData:()=>e.getActiveIndices()/3,dispose:XI})}static ActiveBonesStrategy(){return e=>({id:"Active bones",getData:()=>e.getActiveBones(),dispose:XI})}static ActiveParticlesStrategy(){return e=>({id:"Active particles",getData:()=>e.getActiveParticles(),dispose:XI})}static DrawCallsStrategy(){return e=>{let t=0;const i=e.onBeforeAnimationsObservable.add((()=>{e.getEngine()._drawCalls.fetchNewFrame()})),r=e.onAfterRenderObservable.add((()=>{t=e.getEngine()._drawCalls.current}));return{id:"Draw calls",getData:()=>t,dispose:()=>{e.onBeforeAnimationsObservable.remove(i),e.onAfterRenderObservable.remove(r)}}}}static TotalLightsStrategy(){return e=>({id:"Total lights",getData:()=>e.lights.length,dispose:XI})}static TotalVerticesStrategy(){return e=>({id:"Total vertices",getData:()=>e.getTotalVertices(),dispose:XI})}static TotalMaterialsStrategy(){return e=>({id:"Total materials",getData:()=>e.materials.length,dispose:XI})}static TotalTexturesStrategy(){return e=>({id:"Total textures",getData:()=>e.textures.length,dispose:XI})}static AbsoluteFpsStrategy(){return e=>{const t=new Fv(e);return t.captureFrameTime=!0,{id:"Absolute FPS",getData:()=>1e3/t.frameTimeCounter.lastSecAverage,dispose:XI}}}static MeshesSelectionStrategy(){return e=>{let t=ai.j.Now,i=0;const r=e.onBeforeActiveMeshesEvaluationObservable.add((()=>{t=ai.j.Now})),s=e.onAfterActiveMeshesEvaluationObservable.add((()=>{i=ai.j.Now-t}));return{id:"Meshes Selection",getData:()=>i,dispose:()=>{e.onBeforeActiveMeshesEvaluationObservable.remove(r),e.onAfterActiveMeshesEvaluationObservable.remove(s)}}}}static RenderTargetsStrategy(){return e=>{let t=ai.j.Now,i=0;const r=e.onBeforeRenderTargetsRenderObservable.add((()=>{t=ai.j.Now})),s=e.onAfterRenderTargetsRenderObservable.add((()=>{i=ai.j.Now-t}));return{id:"Render Targets",getData:()=>i,dispose:()=>{e.onBeforeRenderTargetsRenderObservable.remove(r),e.onAfterRenderTargetsRenderObservable.remove(s)}}}}static ParticlesStrategy(){return e=>{let t=ai.j.Now,i=0;const r=e.onBeforeParticlesRenderingObservable.add((()=>{t=ai.j.Now})),s=e.onAfterParticlesRenderingObservable.add((()=>{i=ai.j.Now-t}));return{id:"Particles",getData:()=>i,dispose:()=>{e.onBeforeParticlesRenderingObservable.remove(r),e.onAfterParticlesRenderingObservable.remove(s)}}}}static SpritesStrategy(){return e=>{let t=ai.j.Now,i=0;const r=e.onBeforeSpritesRenderingObservable?.add((()=>{t=ai.j.Now})),s=e.onAfterSpritesRenderingObservable?.add((()=>{i=ai.j.Now-t}));return{id:"Sprites",getData:()=>i,dispose:()=>{e.onBeforeSpritesRenderingObservable?.remove(r),e.onAfterSpritesRenderingObservable?.remove(s)}}}}static AnimationsStrategy(){return e=>{let t=ai.j.Now,i=0;const r=e.onBeforeAnimationsObservable.add((()=>{t=ai.j.Now})),s=e.onAfterAnimationsObservable.add((()=>{i=ai.j.Now-t}));return{id:"Animations",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(r),e.onAfterAnimationsObservable.remove(s)}}}}static PhysicsStrategy(){return e=>{let t=ai.j.Now,i=0;const r=e.onBeforePhysicsObservable?.add((()=>{t=ai.j.Now})),s=e.onAfterPhysicsObservable?.add((()=>{i=ai.j.Now-t}));return{id:"Physics",getData:()=>i,dispose:()=>{e.onBeforePhysicsObservable?.remove(r),e.onAfterPhysicsObservable?.remove(s)}}}}static RenderStrategy(){return e=>{let t=ai.j.Now,i=0;const r=e.onBeforeDrawPhaseObservable.add((()=>{t=ai.j.Now})),s=e.onAfterDrawPhaseObservable.add((()=>{i=ai.j.Now-t}));return{id:"Render",getData:()=>i,dispose:()=>{e.onBeforeDrawPhaseObservable.remove(r),e.onAfterDrawPhaseObservable.remove(s)}}}}static FrameTotalStrategy(){return e=>{let t=ai.j.Now,i=0;const r=e.onBeforeAnimationsObservable.add((()=>{t=ai.j.Now})),s=e.onAfterRenderObservable.add((()=>{i=ai.j.Now-t}));return{id:"Frame Total",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(r),e.onAfterRenderObservable.remove(s)}}}}static InterFrameStrategy(){return e=>{let t=ai.j.Now,i=0;const r=e.onBeforeAnimationsObservable.add((()=>{i=ai.j.Now-t})),s=e.onAfterRenderObservable.add((()=>{t=ai.j.Now}));return{id:"Inter-frame",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(r),e.onAfterRenderObservable.remove(s)}}}}static GpuFrameTimeStrategy(){return e=>{const t=new Nv(e.getEngine());return t.captureGPUFrameTime=!0,{id:"GPU frame time",getData:()=>Math.max(1e-6*t.gpuFrameTimeCounter.current,0),dispose:()=>{t.dispose()}}}}}oi.Z.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new HI(this)),this._perfCollector};class YI{constructor(e,t){this._disableRenderingRefCount=0,this._currentPerformancePriorityMode=0,this._scene=e,this._engine=e.getEngine(),this._engine.isWebGPU&&(this._options={morphTargetsNumMaxInfluences:20,...t},this._engine.snapshotRenderingMode=1,this.fixMeshes(),this._onResizeObserver=this._engine.onResizeObservable.add((()=>{this.disableSnapshotRendering(),this.enableSnapshotRendering()})),this._scene.onBeforeRenderObservable.add((()=>{if(this._fastSnapshotRenderingEnabled){e.skeletons.forEach((e=>e.prepare(!0)));for(const t of e.meshes)if(t.infiniteDistance&&t.transferToEffect(t.computeWorldMatrix(!0)),t.skeleton&&t.transferToEffect(t.computeWorldMatrix(!0)),t.morphTargetManager&&t.subMeshes)for(const e of t.subMeshes){const i=e._drawWrapper,r=i.effect;if(r){const e=i.drawContext.buffers.LeftOver,s=r._pipelineContext?.uniformBuffer;e&&s&&s.setDataBuffer(e)&&(t.morphTargetManager._bind(r),(0,Bt.nR)(t,r),s.update())}}}})))}enableSnapshotRendering(){this._engine.isWebGPU&&(--this._disableRenderingRefCount>0||(this._disableRenderingRefCount=0,this._currentPerformancePriorityMode=this._pendingCurrentPerformancePriorityMode??this._scene.performancePriority,this._pendingCurrentPerformancePriorityMode=void 0,this._scene.performancePriority=0,this._scene.executeWhenReady((()=>{this._disableRenderingRefCount>0||this._executeAtFrame(this._engine.frameId+2,(()=>{this._engine.snapshotRendering=!0}))}))))}disableSnapshotRendering(){this._engine.isWebGPU&&(0===this._disableRenderingRefCount&&(this._scene.performancePriority=0,0!==this._currentPerformancePriorityMode&&(this._pendingCurrentPerformancePriorityMode=this._currentPerformancePriorityMode,this._scene.executeWhenReady((()=>{this._executeAtFrame(this._engine.frameId+2,(()=>{this._disableRenderingRefCount>0&&void 0!==this._pendingCurrentPerformancePriorityMode&&(this._scene.performancePriority=this._pendingCurrentPerformancePriorityMode),this._pendingCurrentPerformancePriorityMode=void 0}),!0)})))),this._engine.snapshotRendering=!1,this._disableRenderingRefCount++)}fixMeshes(e){if(this._engine.isWebGPU){e=e||this._scene.meshes;for(const t of e)t.ignoreCameraMaxZ=!1,t.morphTargetManager&&(t.morphTargetManager.numMaxInfluencers=Math.min(t.morphTargetManager.numTargets,this._options.morphTargetsNumMaxInfluences))}}updateMesh(e){if(this._fastSnapshotRenderingEnabled)if(Array.isArray(e))for(const t of e)t.transferToEffect(t.computeWorldMatrix(!0));else e.transferToEffect(e.computeWorldMatrix(!0))}updateMeshesForEffectLayer(e,t=!0){if(!this._engine.isWebGPU)return;const i=e.mainTexture.renderPassId;t?this._onBeforeRenderObserverUpdateLayer=this._scene.onBeforeRenderObservable.add((()=>{this._updateMeshMatricesForRenderPassId(i)})):this._updateMeshMatricesForRenderPassId(i)}dispose(){this._engine.isWebGPU&&(this._scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserverUpdateLayer),this._engine.onResizeObservable.remove(this._onResizeObserver))}get _fastSnapshotRenderingEnabled(){return this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode}_updateMeshMatricesForRenderPassId(e){if(!this._fastSnapshotRenderingEnabled)return;const t=this._scene.getTransformMatrix();for(let i=0;i{this._disableRenderingRefCount>0&&!i||0===this._disableRenderingRefCount&&i?this._engine.onEndFrameObservable.remove(r):this._engine.frameId>=e&&(this._engine.onEndFrameObservable.remove(r),t())}))}}z.cP.prototype.runCoroutineAsync=function(e){if(!this._coroutineScheduler){const e=function(e){const t=new Array,i=new Array,r=new Array,s=e.add((()=>{const e=t.length;for(let s=0;s{t.push(e),i.push(s),r.push(n)},dispose:()=>{e.remove(s)}}}(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return qe(e,this._coroutineScheduler)},z.cP.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};async function KI(e,t){const i=t.probe??new Kx("tempProbe",t.size,e),r=!!t.probe;r||(t.position?i.position=t.position.clone():e.activeCamera&&(i.position=e.activeCamera.position.clone()));const s=t.meshesFilter?e.meshes.filter(t.meshesFilter):e.meshes;i.renderList?.push(...s),i.refreshRate=ln.$.REFRESHRATE_RENDER_ONCE,i.cubeTexture.render();const n=new Kb("tempProceduralTexture","equirectangularPanorama",{width:2*t.size,height:t.size},e);return n.setTexture("cubeMap",i.cubeTexture),new Promise(((e,s)=>{n.onGeneratedObservable.addOnce((()=>{const o=n.readPixels();if(!o)return s(new Error("No Pixel Data found on procedural texture")),n.dispose(),void(r||i.dispose());o.then((s=>{n.dispose(),r||i.dispose(),t.filename?((0,UR.DumpData)(2*t.size,t.size,s,void 0,"image/png",t.filename),e(null)):e(s)}))}))}))}Cs.l.ShadersStore.equirectangularPanoramaPixelShader="#ifdef GL_ES\nprecision highp float;\n#endif\n#define M_PI 3.1415926535897932384626433832795\nvarying 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(\n- sin( longitude )*sin( latitude ),\ncos( latitude ),\n- cos( longitude )*sin( latitude )\n);normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}";class jI{constructor(){this._currentOperation=Promise.resolve()}lockAsync(e,t){t?.throwIfAborted();const i=t?()=>(t.throwIfAborted(),e()):e,r=this._currentOperation.then(i);return this._currentOperation=new Promise((e=>r.then((()=>e()),e))),r}static async LockAsync(e,t,i){if(i?.throwIfAborted(),0===t.length)return await e();const r=new uR;let s=0;return t.forEach((n=>n.lockAsync((async()=>(s++,s===t.length&&r.resolve(await e()),r.promise)),i).catch((e=>r.reject(e))))),r.promise}}var $I=i(64849),QI=i(32957),ZI=i(79388),JI=i(41572),eM=i(92224),tM=i(89517);class iM{constructor(e=Recast){this.bjsRECAST={},this.name="RecastJSPlugin",this._maximumSubStepCount=10,this._timeStep=1/60,this._timeFactor=1,this._worker=null,"function"==typeof e?Z.V.Error("RecastJS is not ready. Please make sure you await Recast() before using the plugin."):this.bjsRECAST=e,this.isSupported()?(this.setTimeStep(),this._tempVec1=new this.bjsRECAST.Vec3,this._tempVec2=new this.bjsRECAST.Vec3):Z.V.Error("RecastJS is not available. Please make sure you included the js file.")}setWorkerURL(e){return!(!window||!window.Worker||(this._worker=new Worker(e),0))}setTimeStep(e=1/60){this._timeStep=e}getTimeStep(){return this._timeStep}setMaximumSubStepCount(e=10){this._maximumSubStepCount=e}getMaximumSubStepCount(){return this._maximumSubStepCount}set timeFactor(e){this._timeFactor=Math.max(e,0)}get timeFactor(){return this._timeFactor}createNavMesh(e,t,i){let r,s,n;this._worker&&!i?Z.V.Warn("A worker is avaible but no completion callback. Defaulting to blocking navmesh creation"):!this._worker&&i&&Z.V.Warn("A completion callback is avaible but no worker. Defaulting to blocking navmesh creation"),this.navMesh=new this.bjsRECAST.NavMesh;const o=[],a=[];let l=0;for(r=0;r{this.update(.001*r.getEngine().getDeltaTime()*e.timeFactor)}))}addAgent(e,t,i){const r=new this.bjsRECASTPlugin.bjsRECAST.dtCrowdAgentParams;r.radius=t.radius,r.height=t.height,r.maxAcceleration=t.maxAcceleration,r.maxSpeed=t.maxSpeed,r.collisionQueryRange=t.collisionQueryRange,r.pathOptimizationRange=t.pathOptimizationRange,r.separationWeight=t.separationWeight,r.updateFlags=7,r.obstacleAvoidanceType=0,r.queryFilterType=0,r.userData=0;const s=this.recastCrowd.addAgent(new this.bjsRECASTPlugin.bjsRECAST.Vec3(e.x,e.y,e.z),r);return this.transforms.push(i),this.agents.push(s),this.reachRadii.push(t.reachRadius?t.reachRadius:t.radius),this._agentDestinationArmed.push(!1),this._agentDestination.push(new hc.Pq(0,0,0)),s}getAgentPosition(e){const t=this.recastCrowd.getAgentPosition(e);return new hc.Pq(t.x,t.y,t.z)}getAgentPositionToRef(e,t){const i=this.recastCrowd.getAgentPosition(e);t.set(i.x,i.y,i.z)}getAgentVelocity(e){const t=this.recastCrowd.getAgentVelocity(e);return new hc.Pq(t.x,t.y,t.z)}getAgentVelocityToRef(e,t){const i=this.recastCrowd.getAgentVelocity(e);t.set(i.x,i.y,i.z)}getAgentNextTargetPath(e){const t=this.recastCrowd.getAgentNextTargetPath(e);return new hc.Pq(t.x,t.y,t.z)}getAgentNextTargetPathToRef(e,t){const i=this.recastCrowd.getAgentNextTargetPath(e);t.set(i.x,i.y,i.z)}getAgentState(e){return this.recastCrowd.getAgentState(e)}overOffmeshConnection(e){return this.recastCrowd.overOffmeshConnection(e)}agentGoto(e,t){this.recastCrowd.agentGoto(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z));const i=this.agents.indexOf(e);i>-1&&(this._agentDestinationArmed[i]=!0,this._agentDestination[i].set(t.x,t.y,t.z))}agentTeleport(e,t){this.recastCrowd.agentTeleport(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z))}updateAgentParameters(e,t){const i=this.recastCrowd.getAgentParameters(e);void 0!==t.radius&&(i.radius=t.radius),void 0!==t.height&&(i.height=t.height),void 0!==t.maxAcceleration&&(i.maxAcceleration=t.maxAcceleration),void 0!==t.maxSpeed&&(i.maxSpeed=t.maxSpeed),void 0!==t.collisionQueryRange&&(i.collisionQueryRange=t.collisionQueryRange),void 0!==t.pathOptimizationRange&&(i.pathOptimizationRange=t.pathOptimizationRange),void 0!==t.separationWeight&&(i.separationWeight=t.separationWeight),this.recastCrowd.setAgentParameters(e,i)}removeAgent(e){this.recastCrowd.removeAgent(e);const t=this.agents.indexOf(e);t>-1&&(this.agents.splice(t,1),this.transforms.splice(t,1),this.reachRadii.splice(t,1),this._agentDestinationArmed.splice(t,1),this._agentDestination.splice(t,1))}getAgents(){return this.agents}update(e){if(this.bjsRECASTPlugin.navMesh.update(),e<=hc.bH)return;const t=this.bjsRECASTPlugin.getTimeStep(),i=this.bjsRECASTPlugin.getMaximumSubStepCount();if(t<=hc.bH)this.recastCrowd.update(e);else{let r=Math.floor(e/t);i&&r>i&&(r=i),r<1&&(r=1);const s=e/r;for(let e=0;eo&&i.ynew sM(e,t,i);class sM{get enableSceneOffline(){return this._enableSceneOffline}get enableTexturesOffline(){return this._enableTexturesOffline}constructor(e,t,i=!1){this._idbFactory="undefined"!=typeof indexedDB?indexedDB:void 0,this._currentSceneUrl=sM._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,sM.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,Ue.S0.SetImmediate((()=>{t(!0)}))):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){const t=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},i=()=>{try{if("function"==typeof URL&&0===this._currentSceneUrl.indexOf("http")){const e=new URL(this._currentSceneUrl);return e.pathname+=".manifest",e.toString()}}catch(e){}return`${this._currentSceneUrl}.manifest`};let r=!1,s=i();const n=new go.u;navigator.onLine&&(r=!0,s=s+(null==s.match(/\?/)?"?":"&")+Date.now()),n.open("GET",s),n.addEventListener("load",(()=>{if(200===n.status||sM._ValidateXHRData(n,1))try{const t=JSON.parse(n.response);this._enableSceneOffline=t.enableSceneOffline,this._enableTexturesOffline=t.enableTexturesOffline&&sM._IsUASupportingBlobStorage,t.version&&!isNaN(parseInt(t.version))&&(this._manifestVersionFound=t.version),e(!0)}catch(e){t()}else t()}),!1),n.addEventListener("error",(()=>{if(r){r=!1;const e=i();n.open("GET",e),n.send()}else t()}),!1);try{n.send()}catch(t){Z.V.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))if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;const t=this._idbFactory.open("babylonjs",1);t.onerror=()=>{i()},t.onblocked=()=>{Z.V.Error("IDB request blocked. Please reload the page."),i()},t.onsuccess=()=>{this._db=t.result,e()},t.onupgradeneeded=e=>{if(this._db=e.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(e){Z.V.Error("Error while creating object stores. Exception: "+e.message),i()}}}else this._isSupported=!1,t&&t()}loadImage(e,t){const i=sM._ReturnFullUrlLocation(e),r=()=>{this._hasReachedQuota||null===this._db?t.src=e:this._saveImageIntoDBAsync(i,t)};this._mustUpdateRessources?r():this._loadImageFromDBAsync(i,t,r)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&null!==this._db){let r;const s=this._db.transaction(["textures"]);s.onabort=()=>{t.src=e},s.oncomplete=()=>{let s;r&&"function"==typeof URL?(s=URL.createObjectURL(r.data),t.onerror=()=>{Z.V.Error("Error loading image from blob URL: "+s+" switching back to web url: "+e),t.src=e},t.src=s):i()};const n=s.objectStore("textures").get(e);n.onsuccess=e=>{r=e.target.result},n.onerror=()=>{Z.V.Error("Error loading texture "+e+" from DB."),t.src=e}}else Z.V.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t.src=e}_saveImageIntoDBAsync(e,t){let i;if(this._isSupported){const r=()=>{let e;if(i&&"function"==typeof URL)try{e=URL.createObjectURL(i)}catch(t){e=URL.createObjectURL(i)}e&&(t.src=e)};if(sM._IsUASupportingBlobStorage){const s=new go.u;s.open("GET",e),s.responseType="blob",s.addEventListener("load",(()=>{if(200===s.status&&this._db){i=s.response;const n=this._db.transaction(["textures"],"readwrite");n.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}r()},n.oncomplete=()=>{r()};const o={textureUrl:e,data:i};try{const e=n.objectStore("textures").put(o);e.onsuccess=()=>{},e.onerror=()=>{r()}}catch(i){25===i.code&&(sM._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e}),!1),s.addEventListener("error",(()=>{Z.V.Error("Error in XHR request in BABYLON.Database."),t.src=e}),!1),s.send()}else t.src=e}else Z.V.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t.src=e}_checkVersionFromDB(e,t){this._loadVersionFromDBAsync(e,t,(()=>{this._saveVersionIntoDBAsync(e,t)}))}_loadVersionFromDBAsync(e,t,i){if(this._isSupported&&this._db){let r;try{const s=this._db.transaction(["versions"]);s.oncomplete=()=>{r?this._manifestVersionFound!==r.data?(this._mustUpdateRessources=!0,i()):t(r.data):(this._mustUpdateRessources=!0,i())},s.onabort=()=>{t(-1)};const n=s.objectStore("versions").get(e);n.onsuccess=e=>{r=e.target.result},n.onerror=()=>{Z.V.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(e){Z.V.Error("Error while accessing 'versions' object store (READ OP). Exception: "+e.message),t(-1)}}else Z.V.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=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};const r={sceneUrl:e,data:this._manifestVersionFound},s=i.objectStore("versions").put(r);s.onsuccess=()=>{},s.onerror=()=>{Z.V.Error("Error in DB add version request in BABYLON.Database.")}}catch(e){Z.V.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+e.message),t(-1)}else t(-1)}loadFile(e,t,i,r,s){const n=sM._ReturnFullUrlLocation(e),o=()=>{this._saveFileAsync(n,t,i,s,r)};this._checkVersionFromDB(n,(e=>{-1!==e?this._mustUpdateRessources?this._saveFileAsync(n,t,i,s,r):this._loadFileAsync(n,t,o,i):r&&r()}))}_loadFileAsync(e,t,i,r){if(this._isSupported&&this._db){let s,n;s=-1!==e.indexOf(".babylon")?"scenes":"textures";const o=this._db.transaction([s]);o.oncomplete=()=>{if(n){if(r){const e=n.data?.byteLength||0;r({total:e,loaded:e,lengthComputable:!0})}t(n.data)}else i()},o.onabort=()=>{i()};const a=o.objectStore(s).get(e);a.onsuccess=e=>{n=e.target.result},a.onerror=()=>{Z.V.Error("Error loading file "+e+" from DB."),i()}}else Z.V.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,r,s){if(this._isSupported){let n;n=-1!==e.indexOf(".babylon")?"scenes":"textures";const o=new go.u;let a;o.open("GET",e+(null==e.match(/\?/)?"?":"&")+Date.now()),r&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",(()=>{if(200===o.status||o.status<400&&sM._ValidateXHRData(o,r?6:1))if(a=r?o.response:o.responseText,!this._hasReachedQuota&&this._db){const i=this._db.transaction([n],"readwrite");let r;i.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(a)},i.oncomplete=()=>{t(a)},r="scenes"===n?{sceneUrl:e,data:a,version:this._manifestVersionFound}:{textureUrl:e,data:a};try{const e=i.objectStore(n).put(r);e.onsuccess=()=>{},e.onerror=()=>{Z.V.Error("Error in DB add file request in BABYLON.Database.")}}catch(e){t(a)}}else t(a);else o.status>=400&&s?s(o):t()}),!1),o.addEventListener("error",(()=>{Z.V.Error("error on XHR request."),s&&s()}),!1),o.send()}else Z.V.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),s&&s()}static _ValidateXHRData(e,t=7){try{if(1&t){if(e.responseText&&e.responseText.length>0)return!0;if(1===t)return!1}if(2&t){const i=(0,BR.O_)(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){const t=new Uint8Array(e.response,0,3);return 68===t[0]&&68===t[1]&&83===t[2]}}catch(e){}return!1}}sM._IsUASupportingBlobStorage=!0,sM.IDBStorageEnabled=!1,sM._ParseURL=e=>{document.createElement("a").href=e;const t=e.substring(0,e.lastIndexOf("#")),i=e.substring(t.lastIndexOf("/")+1,e.length);return e.substring(0,e.indexOf(i,0))},sM._ReturnFullUrlLocation=e=>-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")&&"undefined"!=typeof window?sM._ParseURL(window.location.href)+e:e;class nM{_isUbo(e){return void 0!==e.addUniform}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))}}Cs.l.ShadersStore.gpuUpdateParticlesPixelShader="#version 300 es\nvoid main() {discard;}\n";Cs.l.ShadersStore.gpuUpdateParticlesVertexShader="#version 300 es\n#define PI 3.14159\nuniform float currentCount;uniform float timeDelta;uniform float stopFactor;\n#ifndef LOCAL\nuniform mat4 emitterWM;\n#endif\nuniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;uniform vec4 color2;\n#endif\nuniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;uniform float radiusRange;uniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;uniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;uniform float height;uniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;uniform float coneAngle;uniform vec2 height;\n#ifdef DIRECTEDCONEEMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\nin vec3 position;\n#ifdef CUSTOMEMITTER\nin vec3 initialPosition;\n#endif\nin float age;in float life;in vec4 seed;in vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;in vec3 noiseCoordinates2;\n#endif\nout vec3 outPosition;\n#ifdef CUSTOMEMITTER\nout vec3 outInitialPosition;\n#endif\nout float outAge;out float outLife;out vec4 outSeed;out vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;uniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec4 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;}\nvec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));}\nvoid main() {float newAge=age+timeDelta; \nif (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;\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 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; \n#elif defined(SPHEREEMITTER)\nvec3 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);\n#ifdef DIRECTEDSPHEREEMITTER\nnewDirection=normalize(direction1+(direction2-direction1)*randoms3);\n#else\nnewDirection=normalize(newPosition+directionRandomizer*randoms3);\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 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);\n#ifdef DIRECTEDCYLINDEREMITTER\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#else\nangle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.0001;\n#else\nfloat h=randoms2.y*height.y;h=1.-h*h; \n#endif\nfloat 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); \nvec3 randoms3=getRandomVec3(seed.z);\n#ifdef DIRECTEDCONEEMITTER\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#else\nif (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {newDirection=normalize(newPosition+directionRandomizer*randoms3); }\n#endif\n#elif defined(CUSTOMEMITTER)\nnewPosition=initialPosition;outInitialPosition=initialPosition;\n#else \nnewPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\n#ifdef LOCAL\noutPosition=newPosition;\n#else\noutPosition=(emitterWM*vec4(newPosition,1.)).xyz;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#ifndef BILLBOARD \noutInitialDirection=direction;\n#endif\n#else\n#ifdef LOCAL\nvec3 initial=newDirection;\n#else \nvec3 initial=(emitterWM*vec4(newDirection,0.)).xyz;\n#endif\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#if defined(CUSTOMEMITTER)\noutPosition=position+(direction-position)*ageGradient; \noutInitialPosition=initialPosition;\n#else\noutPosition=position+direction*directionScale;\n#endif\noutLife=life;outSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#else\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nfloat 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;\n#endif \n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;float dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset;\n#else\nfloat cellStartOffset=0.;\n#endif \nfloat ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);}\nelse {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);}\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}}";class oM{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(){return this._updateEffect?.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 cI&&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 Cl.M("gpuUpdateParticles",this._updateEffectOptions,this._engine),new nM(this._updateEffect)}createVertexBuffers(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null),this._renderVertexBuffers=t}createParticleBuffer(e){return e}bindDrawBuffers(e,t,i){i?this._engine.bindBuffers(this._renderVertexBuffers,i,t):this._engine.bindVertexArrayObject(this._renderVAO[e],null)}preUpdateParticleBuffer(){const e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw new Error("GPU particles cannot work without a full Engine. ThinEngine is not supported")}updateParticleBuffer(e,t,i){this._updateEffect.setTexture("randomSampler",this._parent._randomTexture),this._updateEffect.setTexture("randomSampler2",this._parent._randomTexture2),this._parent._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateEffect.setTexture("limitVelocityGradientSampler",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateEffect.setTexture("dragGradientSampler",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateEffect.setTexture("noiseSampler",this._parent.noiseTexture),this._engine.bindVertexArrayObject(this._updateVAO[e],null);const r=this._engine;r.bindTransformFeedbackBuffer(t.getBuffer()),r.setRasterizerState(!1),r.beginTransformFeedback(!0),r.drawArraysType(3,0,i),r.endTransformFeedback(),r.setRasterizerState(!0),r.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;e{this.start(0)}),e):(this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop))}stop(){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0)}reset(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0}getClassName(){return"GPUParticleSystem"}getCustomEffect(e=0){return this._customWrappers[e]?.effect??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new gt.E(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new z.cP),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"gpuRenderParticles"}get vertexBuffers(){return this._renderVertexBuffers[1^this._targetIndex]}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 $R(e,t);return this._colorGradients.push(i),this._refreshColorGradient(!0),this._releaseBuffers(),this}_refreshColorGradient(e=!1){this._colorGradients&&(e&&this._colorGradients.sort(((e,t)=>e.gradientt.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(){for(const e in this._drawWrappers){const t=this._drawWrappers[e];t.drawContext?.reset()}}_addFactorGradient(e,t,i){const r=new ZR(t,i);e.push(r),this._releaseBuffers()}addSizeGradient(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this}removeSizeGradient(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this}_refreshFactorGradient(e,t,i=!1){if(!e)return;i&&e.sort(((e,t)=>e.gradientt.gradient?1:0));const r=this;r[t]&&(r[t].dispose(),r[t]=null)}addAngularSpeedGradient(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this}removeAngularSpeedGradient(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this}addVelocityGradient(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this}removeVelocityGradient(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this}addLimitVelocityGradient(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this}removeLimitVelocityGradient(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this}addDragGradient(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this}removeDragGradient(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this}addEmitRateGradient(){return this}removeEmitRateGradient(){return this}addStartSizeGradient(){return this}removeStartSizeGradient(){return this}addColorRemapGradient(){return this}removeColorRemapGradient(){return this}addAlphaRemapGradient(){return this}removeAlphaRemapGradient(){return this}addRampGradient(){return this}removeRampGradient(){return this}getRampGradients(){return null}get useRampGradients(){return!1}set useRampGradients(e){}addLifeTimeGradient(){return this}removeLifeTimeGradient(){return this}constructor(e,t,i,r=null,s=!1){if(super(e),this.layerMask=268435455,this._accumulatedCount=0,this._renderVertexBuffers=[],this._targetIndex=0,this._currentRenderId=-1,this._currentRenderingCameraUniqueId=-1,this._started=!1,this._stopped=!1,this._timeDelta=0,this.updateInAnimate=!1,this._actualFrame=0,this._rawTextureWidth=256,this._rebuildingAfterContextLost=!1,this.onDisposeObservable=new z.cP,this.onStoppedObservable=new z.cP,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=W.uq.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||he.q.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().supportComputeShaders){if(!(0,X.n9)("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new((0,X.n9)("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!(0,X.n9)("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new((0,X.n9)("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new gt.E(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers={0:new gt.E(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._createIndexBuffer(),this._attachImageProcessingConfiguration(null),(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=s,this.particleEmitterType=new sI;const a=Math.min(this._engine.getCaps().maxTextureSize,n.randomTextureSize);let l=[];for(let e=0;e0;)i.push(0)}const o=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),a=this._platform.createParticleBuffer(i),l=this._platform.createParticleBuffer(i);this._buffer0=new st.h(t,a,!1,this._attributesStrideSize),this._buffer1=new st.h(t,l,!1,this._attributesStrideSize),this._spriteBuffer=new st.h(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+="\n#define BILLBOARD"),this._colorGradientsTexture&&(e+="\n#define COLORGRADIENTS"),this._sizeGradientsTexture&&(e+="\n#define SIZEGRADIENTS"),this._angularSpeedGradientsTexture&&(e+="\n#define ANGULARSPEEDGRADIENTS"),this._velocityGradientsTexture&&(e+="\n#define VELOCITYGRADIENTS"),this._limitVelocityGradientsTexture&&(e+="\n#define LIMITVELOCITYGRADIENTS"),this._dragGradientsTexture&&(e+="\n#define DRAGGRADIENTS"),this.isAnimationSheetEnabled&&(e+="\n#define ANIMATESHEET",this.spriteRandomStartCell&&(e+="\n#define ANIMATESHEETRANDOMSTART")),this.noiseTexture&&(e+="\n#define NOISE"),this.isLocal&&(e+="\n#define LOCAL"),this._platform.isUpdateBufferCreated()&&this._cachedUpdateDefines===e||(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e)),this._platform.isUpdateBufferReady()}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t?.effect)return t;const i=[];this.fillDefines(i,e);let r=this._drawWrappers[e];r||(r=new gt.E(this._engine),r.drawContext&&(r.drawContext.useInstancing=!0),this._drawWrappers[e]=r);const s=i.join("\n");if(r.defines!==s){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),r.setEffect(this._engine.createEffect("gpuRenderParticles",e,t,i,s),s)}return r}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,r=!1){const s=[st.R.PositionKind,"age","life","size","angle"];return e||s.push(st.R.ColorKind),t&&s.push("cellIndex"),i||s.push("initialDirection"),r&&s.push("direction"),s.push("offset",st.R.UVKind),s}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const r=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return(0,Ln.TV)(r),e&&r.push("sheetInfos"),t&&r.push("logarithmicDepthConstant"),i&&(r.push("vFogInfos"),r.push("vFogColor")),r}fillDefines(e,t=0,i=!0){if(this._scene&&((0,Ln.tv)(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&this._scene.fogMode!==oi.Z.FOGMODE_NONE&&e.push("#define FOG")),t===AI.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 AI.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case AI.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case AI.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._colorGradientsTexture&&e.push("#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),i&&this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(""+this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...lM._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===AI.BILLBOARDMODE_STRETCHED)),e.push(...lM._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(gn.p.PrepareUniforms(e,this._imageProcessingConfigurationDefines),gn.p.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:this._scene?.getAnimationRatio()||1),this._actualFrame+=this._timeDelta,this._stopped||this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop(),this.updateInAnimate&&this._update()}_createFactorGradientTexture(e,t){const i=this[t];if(!e||!e.length||i)return;const r=new Float32Array(this._rawTextureWidth);for(let t=0;t{r[t]=(0,ar.Lerp)(e.factor1,i.factor1,s)}))}this[t]=xi.CreateRTexture(r,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1),this[t].name=t.substring(1)}_createSizeGradientTexture(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")}_createAngularSpeedGradientTexture(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")}_createVelocityGradientTexture(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")}_createLimitVelocityGradientTexture(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")}_createDragGradientTexture(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")}_createColorGradientTexture(){if(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)return;const e=new Uint8Array(4*this._rawTextureWidth),t=H.IG.Color4[0];for(let i=0;i{H.ov.LerpToRef(r.color1,s.color1,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255*t.a}))}this._colorGradientsTexture=xi.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){const i=this._getWrapper(e),r=i.effect;this._engine.enableEffect(i);const s=this._scene?.getViewMatrix()||W.uq.IdentityReadOnly;if(r.setMatrix("view",s),r.setMatrix("projection",this.defaultProjectionMatrix??this._scene.getProjectionMatrix()),r.setTexture("diffuseSampler",this.particleTexture),r.setVector2("translationPivot",this.translationPivot),r.setVector3("worldOffset",this.worldOffset),this.isLocal&&r.setMatrix("emitterWM",t),this._colorGradientsTexture?r.setTexture("colorGradientSampler",this._colorGradientsTexture):r.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){const e=this.particleTexture.getBaseSize();r.setFloat3("sheetInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,e.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){const e=this._scene.activeCamera;r.setVector3("eyePosition",e.globalPosition)}const n=r.defines;if(this._scene&&((0,Ln.gS)(r,this,this._scene),this.applyFog&&(0,Bt.Yy)(this._scene,void 0,r)),n.indexOf("#define BILLBOARDMODE_ALL")>=0){const e=s.clone();e.invert(),r.setMatrix("invView",e)}switch(this.useLogarithmicDepth&&this._scene&&(0,Bt.DL)(n,r,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(r),e){case AI.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case AI.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case AI.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case AI.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4)}return this._platform.bindDrawBuffers(this._targetIndex,r,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(r),this._scene?.forceWireframe?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),this._scene?.forceWireframe&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer)return;if(!this._recreateUpdateEffect()||this._rebuildingAfterContextLost)return;if(!e)if(this.emitter.position)e=this.emitter.getWorldMatrix();else{const t=this.emitter;e=W.AA.Matrix[0],W.uq.TranslationToRef(t.x,t.y,t.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++,2===this._targetIndex&&(this._targetIndex=0);const t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){if(!this._started)return 0;if(!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let e=0;e1){const e=0|this._accumulatedCount;this._accumulatedCount-=e,this._currentActiveCount+=e}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 e=this.emitter;i=W.AA.Matrix[0],W.uq.TranslationToRef(e.x,e.y,e.z,i)}const r=this._engine;this.updateInAnimate||this._update(i);let s=0;return e||t||(r.setState(!1),this.forceDepthWrite&&r.setDepthWrite(!0),s=this.blendMode===AI.BLENDMODE_MULTIPLYADD?this._render(AI.BLENDMODE_MULTIPLY,i)+this._render(AI.BLENDMODE_ADD,i):this._render(this.blendMode,i),this._engine.setAlphaMode(0)),s}rebuild(){const e=()=>{this._recreateUpdateEffect()&&this._platform.isUpdateBufferReady()?(this._initialize(!0),this._rebuildingAfterContextLost=!1):setTimeout(e,10)};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 e in this._drawWrappers)this._drawWrappers[e].dispose();if(this._drawWrappers={},this._scene){const e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let e=0;e0?s.shaderOptions.defines.join("\n"):"";r[0]=n.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e,void 0,void 0,void 0,this)}const o=this.serialize(i),a=lM.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=s,a._customWrappers=r,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,a}serialize(e=!1){const t={};return AI._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,r=!1,s){const n=e.name;let o,a;t instanceof Ot.$?o=t:(a=t,o=a.getEngine());const l=new lM(n,{capacity:s||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(l._rootUrl=i,e.customShader&&o.createEffectForParticles){const t=e.customShader,i=t.shaderOptions.defines.length>0?t.shaderOptions.defines.join("\n"):"",r=o.createEffectForParticles(t.shaderPath.fragmentElement,t.shaderOptions.uniforms,t.shaderOptions.samplers,i,void 0,void 0,void 0,l);l.setCustomEffect(r,0),l.customShader=t}return e.id&&(l.id=e.id),e.activeParticleCount&&(l.activeParticleCount=e.activeParticleCount),AI._Parse(e,l,t,i),e.preventAutoStart&&(l.preventAutoStart=e.preventAutoStart),r||l.preventAutoStart||l.start(),l}}class hM{constructor(){this._emitterNodeIsOwned=!0,this.systems=[]}get emitterNode(){return this._emitterNode}set emitterNode(e){this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1);for(const t of this.systems)t.emitter=e;this._emitterNode=e}setEmitterAsSphere(e,t,i){this._emitterNodeIsOwned&&this._emitterNode&&this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!0,this._emitterCreationOptions={kind:"Sphere",options:e,renderingGroupId:t};const r=Qo("emitterSphere",{diameter:e.diameter,segments:e.segments},i);r.renderingGroupId=t;const s=new Un("emitterSphereMaterial",i);s.emissiveColor=e.color,r.material=s;for(const e of this.systems)e.emitter=r;this._emitterNode=r}start(e){for(const t of this.systems)e&&(t.emitter=e),t.start()}dispose(){for(const e of this.systems)e.dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)}serialize(e=!1){const t={systems:[]};for(const i of this.systems)t.systems.push(i.serialize(e));return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t}static Parse(e,t,i=!1,r){const s=new hM,n=this.BaseAssetsUrl+"/textures/";t=t||he.q.LastCreatedScene;for(const o of e.systems)s.systems.push(i?lM.Parse(o,t,n,!0,r):AI.Parse(o,t,n,!0,r));if(e.emitter){const i=e.emitter.options;"Sphere"===e.emitter.kind&&s.setEmitterAsSphere({diameter:i.diameter,segments:i.segments,color:H.v9.FromArray(i.color)},e.emitter.renderingGroupId,t)}return s}}hM.BaseAssetsUrl="https://assets.babylonjs.com/particles";class cM{static CreateDefault(e,t=500,i,r=!1){let s;return s=r?new lM("default system",{capacity:t},i):new AI("default system",t,i),s.emitter=e,s.particleTexture=new vi.g("https://assets.babylonjs.com/textures/flare.png",s.getScene()),s.createConeEmitter(.1,Math.PI/4),s.color1=new H.ov(1,1,1,1),s.color2=new H.ov(1,1,1,1),s.colorDead=new H.ov(1,1,1,0),s.minSize=.1,s.maxSize=.1,s.minEmitPower=2,s.maxEmitPower=2,s.updateSpeed=1/60,s.emitRate=30,s}static CreateAsync(e,t,i=!1,r){t||(t=he.q.LastCreatedScene);const s={};return t.addPendingData(s),new Promise(((n,o)=>{if(i&&!lM.IsSupported)return t.removePendingData(s),o("Particle system with GPU is not supported.");Ue.S0.LoadFile(`${cM.BaseAssetsUrl}/systems/${e}.json`,(e=>{t.removePendingData(s);const o=JSON.parse(e.toString());return n(hM.Parse(o,t,i,r))}),void 0,void 0,void 0,(()=>(t.removePendingData(s),o(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`))))}))}static ExportSet(e){const t=new hM;for(const i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,r=!1,s="",n){return new Promise(((o,a)=>{const l=new go.u;l.addEventListener("readystatechange",(()=>{if(4==l.readyState)if(200==l.status){const t=JSON.parse(l.responseText);let a;a=r?lM.Parse(t,i,s,!1,n):AI.Parse(t,i,s,!1,n),e&&(a.name=e),o(a)}else a("Unable to load the particle system")})),l.open("GET",t),l.send()}))}static ParseFromSnippetAsync(e,t,i=!1,r="",s){if("_BLANK"===e){const e=this.CreateDefault(null);return e.start(),Promise.resolve(e)}return new Promise(((n,o)=>{const a=new go.u;a.addEventListener("readystatechange",(()=>{if(4==a.readyState)if(200==a.status){const o=JSON.parse(JSON.parse(a.responseText).jsonPayload),l=JSON.parse(o.particleSystem);let h;h=i?lM.Parse(l,t,r,!1,s):AI.Parse(l,t,r,!1,s),h.snippetId=e,n(h)}else o("Unable to load the snippet "+e)})),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()}))}}cM.BaseAssetsUrl=hM.BaseAssetsUrl,cM.SnippetUrl="https://snippet.babylonjs.com",cM.CreateFromSnippetAsync=cM.ParseFromSnippetAsync,ci(Ut.v.NAME_PARTICLESYSTEM,((e,t,i,r)=>{const s=fi(Ut.v.NAME_PARTICLESYSTEM);if(s&&void 0!==e.particleSystems&&null!==e.particleSystems)for(let n=0,o=e.particleSystems.length;ne.activeParticleCount?lM.Parse(e,t,i):AI.Parse(e,t,i))),Ot.$.prototype.createEffectForParticles=function(e,t=[],r=[],s="",n,o,a,l,h=0){let c=[],u=[];const d=[];return l?l.fillUniformsAttributesAndSamplerNames(u,c,d):(c=AI._GetAttributeNamesOrOptions(),u=AI._GetEffectCreationOptions()),-1===s.indexOf(" BILLBOARD")&&(s+="\n#define BILLBOARD\n"),l?.isAnimationSheetEnabled&&-1===s.indexOf(" ANIMATESHEET")&&(s+="\n#define ANIMATESHEET\n"),-1===r.indexOf("diffuseSampler")&&r.push("diffuseSampler"),this.createEffect({vertex:l?.vertexShaderName??"particles",fragmentElement:e},c,u.concat(t),d.concat(r),s,n,o,a,void 0,h,(async()=>{0===h?await Promise.resolve().then(i.bind(i,70917)):await Promise.resolve().then(i.bind(i,25806))}))},Yt.prototype.getEmittedParticleSystems=function(){const e=[];for(let t=0;tt.sqDistance-e.sqDistance,this._materialSortFunction=(e,t)=>e.materialIndex-t.materialIndex,this._autoUpdateSubMeshes=!1,this._recomputeInvisibles=!1,this.name=e,this._scene=t||he.q.LastCreatedScene,this._camera=t.activeCamera,this._pickable=!!i&&i.isPickable,this._depthSort=!!i&&i.enableDepthSort,this._multimaterialEnabled=!!i&&i.enableMultiMaterial,this._useModelMaterial=!!i&&i.useModelMaterial,this._multimaterialEnabled=!!this._useModelMaterial||this._multimaterialEnabled,this._expandable=!!i&&i.expandable,this._particlesIntersect=!!i&&i.particleIntersection,this._bSphereOnly=!!i&&i.boundingSphereOnly,this._bSphereRadiusFactor=i&&i.bSphereRadiusFactor?i.bSphereRadiusFactor:1,this._computeBoundingBox=!!i?.computeBoundingBox&&i.computeBoundingBox,this._autoFixFaceOrientation=!!i?.autoFixFaceOrientation&&i.autoFixFaceOrientation,i&&void 0!==i.updatable?this._updatable=i.updatable:this._updatable=!0,this._pickable&&(this.pickedBySubMesh=[[]],this.pickedParticles=this.pickedBySubMesh[0]),(this._depthSort||this._multimaterialEnabled)&&(this.depthSortedParticles=[]),this._multimaterialEnabled&&(this._multimaterial=new kt(this.name+"MultiMaterial",this._scene),this._materials=[],this._materialIndexesById={}),this._tmpVertex=new pM}buildMesh(){if(!this._isNotBuilt&&this.mesh)return this.mesh;if(0===this.nbParticles&&!this.mesh){const e=da("",{radius:1,tessellation:3},this._scene);this.addShape(e,1),e.dispose()}if(this._indices32=this._needs32Bits?new Uint32Array(this._indices):new Uint16Array(this._indices),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors),!this.mesh){const e=new Yt(this.name,this._scene);this.mesh=e}!this._updatable&&this._multimaterialEnabled&&this._sortParticlesByMaterial(),this.recomputeNormals&&bt.ComputeNormals(this._positions32,this._indices32,this._normals),this._normals32=new Float32Array(this._normals),this._fixedNormal32=new Float32Array(this._normals),this._mustUnrotateFixedNormals&&this._unrotateFixedNormals();const e=new bt;if(e.indices=this._depthSort?this._indices:this._indices32,e.set(this._positions32,st.R.PositionKind),e.set(this._normals32,st.R.NormalKind),this._uvs32.length>0&&e.set(this._uvs32,st.R.UVKind),this._colors32.length>0&&e.set(this._colors32,st.R.ColorKind),e.applyToMesh(this.mesh,this._updatable),this.mesh.isPickable=this._pickable,this._pickable){let e=0;for(let t=0;td?d:r,i=Math.round(d/r),s=0):i=i>d?d:i;const f=[],p=[],_=[],m=[],g=[],v=W.Pq.Zero(),x=i;for(;ud-i&&(i=d-u),f.length=0,p.length=0,_.length=0,m.length=0,g.length=0;let t=0;for(let e=3*u;e<3*(u+i);e++){_.push(t);const i=o[e],r=3*i;if(f.push(n[r],n[r+1],n[r+2]),p.push(h[r],h[r+1],h[r+2]),a){const e=2*i;m.push(a[e],a[e+1])}if(l){const e=4*i;g.push(l[e],l[e+1],l[e+2],l[e+3])}t++}let r=this.nbParticles;const b=this._posToShape(f),S=this._uvsToShapeUV(m),T=_.slice(),C=g.slice(),y=p.slice();let E;for(v.copyFromFloats(0,0,0),E=0;E65535&&(this._needs32Bits=!0)}if(this._depthSort||this._multimaterialEnabled){const e=null!==b.materialIndex?b.materialIndex:0;this.depthSortedParticles.push(new fM(d,t,s.length,e))}return b}_posToShape(e){const t=[];for(let i=0;i=this.nbParticles||!this._updatable)return[];const r=this.particles,s=this.nbParticles;if(t=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(0!=e||t!=this.nbParticles-1)){const e=this.mesh.getBoundingInfo();e&&(v.copyFrom(e.minimum),x.copyFrom(e.maximum))}P=this.particles[e]._pos;const D=P/3|0;R=4*D,M=2*D;for(let i=e;i<=t;i++){const e=this.particles[i];this.updateParticle(e);const t=e._model._shape,s=e._model._shapeUV,c=e._rotationMatrix,u=e.position,D=e.rotation,w=e.scaling,N=e._globalPosition;if(f){const t=this.depthSortedParticles[i];t.idx=e.idx,t.ind=e._ind,t.indicesLength=e._model._indicesLength,t.sqDistance=W.Pq.DistanceSquared(e.position,b)}if(e.alive&&(!e._stillInvisible||e.isVisible||this._recomputeInvisibles)){if(e.isVisible){e._stillInvisible=!1;const i=p[12];if(e.pivot.multiplyToRef(w,i),this.billboard&&(D.x=0,D.y=0),(this._computeParticleRotation||this.billboard)&&e.getRotationMatrix(r),null!==e.parentId){const t=this.getParticleById(e.parentId);if(t){const e=t._rotationMatrix,i=t._globalPosition,s=u.x*e[1]+u.y*e[4]+u.z*e[7],n=u.x*e[0]+u.y*e[3]+u.z*e[6],o=u.x*e[2]+u.y*e[5]+u.z*e[8];if(N.x=i.x+n,N.y=i.y+s,N.z=i.z+o,this._computeParticleRotation||this.billboard){const t=r.m;c[0]=t[0]*e[0]+t[1]*e[3]+t[2]*e[6],c[1]=t[0]*e[1]+t[1]*e[4]+t[2]*e[7],c[2]=t[0]*e[2]+t[1]*e[5]+t[2]*e[8],c[3]=t[4]*e[0]+t[5]*e[3]+t[6]*e[6],c[4]=t[4]*e[1]+t[5]*e[4]+t[6]*e[7],c[5]=t[4]*e[2]+t[5]*e[5]+t[6]*e[8],c[6]=t[8]*e[0]+t[9]*e[3]+t[10]*e[6],c[7]=t[8]*e[1]+t[9]*e[4]+t[10]*e[7],c[8]=t[8]*e[2]+t[9]*e[5]+t[10]*e[8]}}else e.parentId=null}else if(N.x=u.x,N.y=u.y,N.z=u.z,this._computeParticleRotation||this.billboard){const e=r.m;c[0]=e[0],c[1]=e[1],c[2]=e[2],c[3]=e[4],c[4]=e[5],c[5]=e[6],c[6]=e[8],c[7]=e[9],c[8]=e[10]}const n=p[11];for(e.translateFromPivot?n.setAll(0):n.copyFrom(i),O=0;O0)for(let t=0;t(this._isReady=!0,this._buildMesh(e))))}_buildMesh(e){0===this.nbParticles&&this.addPoints(1),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors);const t=new bt;t.set(this._positions32,st.R.PositionKind),this._uvs32.length>0&&t.set(this._uvs32,st.R.UVKind);let i=0;this._colors32.length>0&&(i=1,t.set(this._colors32,st.R.ColorKind));const r=new Yt(this.name,this._scene);t.applyToMesh(r,this._updatable),this.mesh=r,this._positions=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0);let s=e;return s||(s=new Un("point cloud material",this._scene),s.emissiveColor=new hc.v9(i,i,i),s.disableLighting=!0,s.pointsCloud=!0,s.pointSize=this._size),r.material=s,new Promise((e=>e(r)))}_addParticle(e,t,i,r){const s=new mM(e,t,i,r,this);return this.particles.push(s),s}_randomUnitVector(e){e.position=new W.Pq(Math.random(),Math.random(),Math.random()),e.color=new hc.ov(1,1,1,1)}_getColorIndicesForCoord(e,t,i,r){const s=e._groupImageData,n=i*(4*r)+4*t,o=[n,n+1,n+2,n+3],a=o[1],l=o[2],h=o[3],c=s[o[0]],u=s[a],d=s[l],f=s[h];return new hc.ov(c/255,u/255,d/255,f)}_setPointsColorOrUV(e,t,i,r,s,n,o,a){a=a??0,i&&e.updateFacetData();const l=2*e.getBoundingInfo().boundingSphere.radius;let h=e.getVerticesData(st.R.PositionKind);const c=e.getIndices(),u=e.getVerticesData(st.R.UVKind+(a?a+1:"")),d=e.getVerticesData(st.R.ColorKind),f=W.Pq.Zero();e.computeWorldMatrix();const p=e.getWorldMatrix();if(!p.isIdentity()){h=h.slice(0);for(let e=0;e1&&(Pe=1),Ae<0&&(Ae=0),Ae>1&&(Ae=1),hc.v9.HSVtoRGBToRef(Ee,Pe,Ae,Me),de.set(Me.r,Me.g,Me.b,1)):de=re.set(Math.random(),Math.random(),Math.random(),1),De.color=new hc.ov(de.x,de.y,de.z,de.w),this._colors.push(de.x,de.y,de.z,de.w))}}_colorFromTexture(e,t,i){if(null===e.material)return Z.V.Warn(e.name+"has no material."),t._groupImageData=null,void this._setPointsColorOrUV(e,t,i,!0,!1);const r=e.material.getActiveTextures();if(0===r.length)return Z.V.Warn(e.name+"has no usable texture."),t._groupImageData=null,void this._setPointsColorOrUV(e,t,i,!0,!1);const s=e.clone();s.setEnabled(!1),this._promises.push(new Promise((e=>{js.t.WhenAllReady(r,(()=>{let n=t._textureNb;n<0&&(n=0),n>r.length-1&&(n=r.length-1);const o=()=>{t._groupImgWidth=r[n].getSize().width,t._groupImgHeight=r[n].getSize().height,this._setPointsColorOrUV(s,t,i,!0,!0,void 0,void 0,r[n].coordinatesIndex),s.dispose(),e()};t._groupImageData=null;const a=r[n].readPixels();a?a.then((e=>{t._groupImageData=e,o()})):o()}))})))}_calculateDensity(e,t,i){let r,s,n,o,a,l,h,c,u,d,f,p;const _=W.Pq.Zero(),m=W.Pq.Zero(),g=W.Pq.Zero(),v=W.Pq.Zero(),x=W.Pq.Zero(),b=W.Pq.Zero();let S;const T=[];let C=0;const y=i.length/3;for(let e=0;e0;e--){const t=T[e];if(0===t)E[e]=0;else{const i=(t-T[e-1])/t*P,r=Math.floor(i),s=i-r,n=r+Number(Math.random()3)&&(n=0);const o=e.getVerticesData(st.R.PositionKind),a=e.getIndices();this._groups.push(this._groupCounter);const l=new gM(this._groupCounter,null);switch(l._groupDensity=this._calculateDensity(t,o,a),2===n?l._textureNb=r||0:r=r||new hc.ov(1,1,1,1),n){case 2:this._colorFromTexture(e,l,!1);break;case 1:this._setPointsColorOrUV(e,l,!1,!1,!1);break;case 0:this._setPointsColorOrUV(e,l,!1);break;case 3:this._setPointsColorOrUV(e,l,!1,void 0,void 0,r,s)}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}addVolumePoints(e,t,i,r,s){let n=i||0;(isNaN(n)||n<0||n>3)&&(n=0);const o=e.getVerticesData(st.R.PositionKind),a=e.getIndices();this._groups.push(this._groupCounter);const l=new gM(this._groupCounter,null);switch(l._groupDensity=this._calculateDensity(t,o,a),2===n?l._textureNb=r||0:r=r||new hc.ov(1,1,1,1),n){case 2:this._colorFromTexture(e,l,!0);break;case 1:this._setPointsColorOrUV(e,l,!0,!1,!1);break;case 0:this._setPointsColorOrUV(e,l,!0);break;case 3:this._setPointsColorOrUV(e,l,!0,void 0,void 0,r,s)}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}setParticles(e=0,t=this.nbParticles-1,i=!0){if(!this._updatable||!this._isReady)return this;this.beforeUpdateParticles(e,t,i);const r=W.AA.Matrix[0],s=this.mesh,n=this._colors32,o=this._positions32,a=this._uvs32,l=W.AA.Vector3,h=l[5].copyFromFloats(1,0,0),c=l[6].copyFromFloats(0,1,0),u=l[7].copyFromFloats(0,0,1),d=l[8].setAll(Number.MAX_VALUE),f=l[9].setAll(-Number.MAX_VALUE);W.uq.IdentityToRef(r);let p=0;if(this.mesh?.isFacetDataEnabled&&(this._computeBoundingBox=!0),t=t>=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(0!=e||t!=this.nbParticles-1)){const e=this.mesh?.getBoundingInfo();e&&(d.copyFrom(e.minimum),f.copyFrom(e.maximum))}p=0;let _=0,m=0,g=0;for(let i=e;i<=t;i++){const e=this.particles[i];p=e.idx,_=3*p,m=4*p,g=2*p,this.updateParticle(e);const t=e._rotationMatrix,s=e.position,n=e._globalPosition;if(this._computeParticleRotation&&e.getRotationMatrix(r),null!==e.parentId){const i=this.particles[e.parentId],o=i._rotationMatrix,a=i._globalPosition,l=s.x*o[1]+s.y*o[4]+s.z*o[7],h=s.x*o[0]+s.y*o[3]+s.z*o[6],c=s.x*o[2]+s.y*o[5]+s.z*o[8];if(n.x=a.x+h,n.y=a.y+l,n.z=a.z+c,this._computeParticleRotation){const e=r.m;t[0]=e[0]*o[0]+e[1]*o[3]+e[2]*o[6],t[1]=e[0]*o[1]+e[1]*o[4]+e[2]*o[7],t[2]=e[0]*o[2]+e[1]*o[5]+e[2]*o[8],t[3]=e[4]*o[0]+e[5]*o[3]+e[6]*o[6],t[4]=e[4]*o[1]+e[5]*o[4]+e[6]*o[7],t[5]=e[4]*o[2]+e[5]*o[5]+e[6]*o[8],t[6]=e[8]*o[0]+e[9]*o[3]+e[10]*o[6],t[7]=e[8]*o[1]+e[9]*o[4]+e[10]*o[7],t[8]=e[8]*o[2]+e[9]*o[5]+e[10]*o[8]}}else if(n.x=0,n.y=0,n.z=0,this._computeParticleRotation){const e=r.m;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[4],t[4]=e[5],t[5]=e[6],t[6]=e[8],t[7]=e[9],t[8]=e[10]}const a=l[11];e.translateFromPivot?a.setAll(0):a.copyFrom(e.pivot);const v=l[0];v.copyFrom(e.position);const x=v.x-e.pivot.x,b=v.y-e.pivot.y,S=v.z-e.pivot.z;let T=x*t[0]+b*t[3]+S*t[6],C=x*t[1]+b*t[4]+S*t[7],y=x*t[2]+b*t[5]+S*t[8];T+=a.x,C+=a.y,y+=a.z;const E=o[_]=n.x+h.x*T+c.x*C+u.x*y,P=o[_+1]=n.y+h.y*T+c.y*C+u.y*y,A=o[_+2]=n.z+h.z*T+c.z*C+u.z*y;if(this._computeBoundingBox&&(d.minimizeInPlaceFromFloats(E,P,A),f.maximizeInPlaceFromFloats(E,P,A)),this._computeParticleColor&&e.color){const t=e.color,i=this._colors32;i[m]=t.r,i[m+1]=t.g,i[m+2]=t.b,i[m+3]=t.a}if(this._computeParticleTexture&&e.uv){const t=e.uv,i=this._uvs32;i[g]=t.x,i[g+1]=t.y}}return s&&(i&&(this._computeParticleColor&&s.updateVerticesData(st.R.ColorKind,n,!1,!1),this._computeParticleTexture&&s.updateVerticesData(st.R.UVKind,a,!1,!1),s.updateVerticesData(st.R.PositionKind,o,!1,!1)),this._computeBoundingBox&&(s.hasBoundingInfo?s.getBoundingInfo().reConstruct(d,f,s._worldMatrix):s.buildBoundingInfo(d,f,s._worldMatrix))),this.afterUpdateParticles(e,t,i),this}dispose(){this.mesh?.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(){return this._isVisibilityBoxLocked||this.mesh?.refreshBoundingInfo(),this}setVisibilityBox(e){if(!this.mesh)return;const t=e/2;this.mesh.buildBoundingInfo(new W.Pq(-t,-t,-t),new W.Pq(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){}}var bM,SM,TM,CM,yM,EM,PM,AM,RM,IM,MM,OM,DM,wM=i(50619),NM=i(70917),FM=i(86144),LM=i(25806);Object.defineProperty(Nt.prototype,"physicsImpostor",{get:function(){return this._physicsImpostor},set:function(e){this._physicsImpostor!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsImpostor=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add((()=>{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)}))))},enumerable:!0,configurable:!0}),Nt.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},Nt.prototype.applyImpulse=function(e,t){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(e,t),this):this},Nt.prototype.setPhysicsLinkWith=function(e,t,i,r){return this.physicsImpostor&&e.physicsImpostor?(this.physicsImpostor.createJoint(e.physicsImpostor,Jo.HingeJoint,{mainPivot:t,connectedPivot:i,nativeParams:r}),this):this};class BM{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw(0,Je.n)("")}constructor(e,t=BM.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new W.Pq(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}setVelocityLimits(e,t){this._physicsPlugin.setVelocityLimits(e,t)}getMaxLinearVelocity(){return this._physicsPlugin.getMaxLinearVelocity()}getMaxAngularVelocity(){return this._physicsPlugin.getMaxAngularVelocity()}_step(e){e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._physicsBodies)}addBody(e){this._physicsBodies.push(e)}removeBody(e){const t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)}getBodies(){return this._physicsBodies}getPhysicsPlugin(){return this._physicsPlugin}raycastToRef(e,t,i,r){this._physicsPlugin.raycast(e,t,i,r)}raycast(e,t,i){const r=new Wx;return this._physicsPlugin.raycast(e,t,r,i),r}}!function(e){e[e.FREE=0]="FREE",e[e.LIMITED=1]="LIMITED",e[e.LOCKED=2]="LOCKED"}(bM||(bM={})),function(e){e[e.LINEAR_X=0]="LINEAR_X",e[e.LINEAR_Y=1]="LINEAR_Y",e[e.LINEAR_Z=2]="LINEAR_Z",e[e.ANGULAR_X=3]="ANGULAR_X",e[e.ANGULAR_Y=4]="ANGULAR_Y",e[e.ANGULAR_Z=5]="ANGULAR_Z",e[e.LINEAR_DISTANCE=6]="LINEAR_DISTANCE"}(SM||(SM={})),function(e){e[e.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",e[e.DISTANCE=2]="DISTANCE",e[e.HINGE=3]="HINGE",e[e.SLIDER=4]="SLIDER",e[e.LOCK=5]="LOCK",e[e.PRISMATIC=6]="PRISMATIC",e[e.SIX_DOF=7]="SIX_DOF"}(TM||(TM={})),function(e){e[e.SPHERE=0]="SPHERE",e[e.CAPSULE=1]="CAPSULE",e[e.CYLINDER=2]="CYLINDER",e[e.BOX=3]="BOX",e[e.CONVEX_HULL=4]="CONVEX_HULL",e[e.CONTAINER=5]="CONTAINER",e[e.MESH=6]="MESH",e[e.HEIGHTFIELD=7]="HEIGHTFIELD"}(CM||(CM={})),function(e){e[e.NONE=0]="NONE",e[e.VELOCITY=1]="VELOCITY",e[e.POSITION=2]="POSITION"}(yM||(yM={})),function(e){e.COLLISION_STARTED="COLLISION_STARTED",e.COLLISION_CONTINUED="COLLISION_CONTINUED",e.COLLISION_FINISHED="COLLISION_FINISHED",e.TRIGGER_ENTERED="TRIGGER_ENTERED",e.TRIGGER_EXITED="TRIGGER_EXITED"}(EM||(EM={})),function(e){e[e.STATIC=0]="STATIC",e[e.ANIMATED=1]="ANIMATED",e[e.DYNAMIC=2]="DYNAMIC"}(PM||(PM={})),function(e){e[e.DISABLED=0]="DISABLED",e[e.TELEPORT=1]="TELEPORT",e[e.ACTION=2]="ACTION"}(AM||(AM={})),function(e){e[e.SIMULATION_CONTROLLED=0]="SIMULATION_CONTROLLED",e[e.ALWAYS_ACTIVE=1]="ALWAYS_ACTIVE",e[e.ALWAYS_INACTIVE=2]="ALWAYS_INACTIVE"}(RM||(RM={}));class VM{get disablePreStep(){return this._prestepType==AM.DISABLED}set disablePreStep(e){this._prestepType=e?AM.DISABLED:AM.TELEPORT}constructor(e,t,i,r){if(this._pluginData=void 0,this._pluginDataInstances=[],this._collisionCBEnabled=!1,this._collisionEndedCBEnabled=!1,this.disableSync=!1,this._isDisposed=!1,this._shape=null,this._prestepType=AM.DISABLED,!r)return;const s=r.getPhysicsEngine();if(!s)throw new Error("No Physics Engine available.");if(this._physicsEngine=s,2!=s.getPluginVersion())throw new Error("Plugin version is incorrect. Expected version 2.");const n=s.getPhysicsPlugin();if(!n)throw new Error("No Physics Plugin available.");this._physicsPlugin=n,e.rotationQuaternion||(e.rotationQuaternion=W.PT.FromEulerAngles(e.rotation.x,e.rotation.y,e.rotation.z)),this.startAsleep=i,this._motionType=t,this.disableSync=0==t;const o=e;o.hasThinInstances?this._physicsPlugin.initBodyInstances(this,t,o):(e.parent&&e.computeWorldMatrix(!0),this._physicsPlugin.initBody(this,t,e.absolutePosition,e.absoluteRotationQuaternion)),this.transformNode=e,e.physicsBody=this,s.addBody(this),this._nodeDisposeObserver=e.onDisposeObservable.add((()=>{this.dispose()}))}getClassName(){return"PhysicsBody"}clone(e){const t=new VM(e,this.getMotionType(),this.startAsleep,this.transformNode.getScene());return t.shape=this.shape,t.setMassProperties(this.getMassProperties()),t.setLinearDamping(this.getLinearDamping()),t.setAngularDamping(this.getAngularDamping()),t}updateBodyInstances(){const e=this.transformNode;e.hasThinInstances&&this._physicsPlugin.updateBodyInstances(this,e)}get numInstances(){return this._pluginDataInstances.length}get motionType(){return this._motionType}set shape(e){this._shape=e,e&&this._physicsPlugin.setShape(this,e)}get shape(){return this._shape}getBoundingBox(){return this._physicsPlugin.getBodyBoundingBox(this)}setEventMask(e,t){this._physicsPlugin.setEventMask(this,e,t)}getEventMask(e){return this._physicsPlugin.getEventMask(this,e)}setMotionType(e,t){this.disableSync=0==e,this._physicsPlugin.setMotionType(this,e,t)}getMotionType(e){return this._physicsPlugin.getMotionType(this,e)}setPrestepType(e){this._prestepType=e}getPrestepType(){return this._prestepType}computeMassProperties(e){return this._physicsPlugin.computeMassProperties(this,e)}setMassProperties(e,t){this._physicsPlugin.setMassProperties(this,e,t)}getMassProperties(e){return this._physicsPlugin.getMassProperties(this,e)}setLinearDamping(e,t){this._physicsPlugin.setLinearDamping(this,e,t)}getLinearDamping(e){return this._physicsPlugin.getLinearDamping(this,e)}setAngularDamping(e,t){this._physicsPlugin.setAngularDamping(this,e,t)}getAngularDamping(e){return this._physicsPlugin.getAngularDamping(this,e)}setLinearVelocity(e,t){this._physicsPlugin.setLinearVelocity(this,e,t)}getLinearVelocityToRef(e,t){this._physicsPlugin.getLinearVelocityToRef(this,e,t)}getLinearVelocity(e){const t=new W.Pq;return this.getLinearVelocityToRef(t,e),t}setAngularVelocity(e,t){this._physicsPlugin.setAngularVelocity(this,e,t)}getAngularVelocityToRef(e,t){this._physicsPlugin.getAngularVelocityToRef(this,e,t)}getAngularVelocity(e){const t=new W.Pq;return this.getAngularVelocityToRef(t,e),t}applyImpulse(e,t,i){this._physicsPlugin.applyImpulse(this,e,t,i)}applyAngularImpulse(e,t){this._physicsPlugin.applyAngularImpulse(this,e,t)}applyForce(e,t,i){this._physicsPlugin.applyForce(this,e,t,i)}getGeometry(){return this._physicsPlugin.getBodyGeometry(this)}getCollisionObservable(){return this._physicsPlugin.getCollisionObservable(this)}getCollisionEndedObservable(){return this._physicsPlugin.getCollisionEndedObservable(this)}setCollisionCallbackEnabled(e){this._collisionCBEnabled=e,this._physicsPlugin.setCollisionCallbackEnabled(this,e)}setCollisionEndedCallbackEnabled(e){this._collisionEndedCBEnabled=e,this._physicsPlugin.setCollisionEndedCallbackEnabled(this,e)}getObjectCenterWorld(e){const t=new W.Pq;return this.getObjectCenterWorldToRef(t,e)}getObjectCenterWorldToRef(e,t){if(this._pluginDataInstances?.length>0){const i=t||0,r=this.transformNode._thinInstanceDataStorage.matrixData;r&&e.set(r[16*i+12],r[16*i+13],r[16*i+14])}else e.copyFrom(this.transformNode.position);return e}addConstraint(e,t,i,r){this._physicsPlugin.addConstraint(this,e,t,i,r)}syncWithBone(e,t,i,r,s,n){const o=this.transformNode;if(o.rotationQuaternion)if(s){const i=W.AA.Quaternion[0];e.getRotationQuaternionToRef(1,t,i),i.multiplyToRef(s,o.rotationQuaternion)}else e.getRotationQuaternionToRef(1,t,o.rotationQuaternion);const a=W.AA.Vector3[0],l=W.AA.Vector3[1];n||((n=W.AA.Vector3[2]).x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,l),e.getAbsolutePositionToRef(t,a),null==r&&i&&(r=i.length()),null!=r&&(a.x+=l.x*r,a.y+=l.y*r,a.z+=l.z*r),o.setAbsolutePosition(a)}iterateOverAllInstances(e){if(this._pluginDataInstances?.length>0)for(let t=0;t{this.dispose()}))}_getObjectBoundingBox(){return this.transformNode.getRawBoundingInfo?this.transformNode.getRawBoundingInfo().boundingBox:new ht(new W.Pq(-.5,-.5,-.5),new W.Pq(.5,.5,.5))}_hasVertices(e){return e?.getTotalVertices()>0}_addSizeOptions(){this.transformNode.computeWorldMatrix(!0);const e=this._getObjectBoundingBox(),t=W.AA.Vector3[0];t.copyFrom(e.extendSize),t.scaleInPlace(2),t.multiplyInPlace(this.transformNode.absoluteScaling),t.x=Math.abs(t.x),t.y=Math.abs(t.y),t.z=Math.abs(t.z);const i=W.AA.Vector3[1];if(i.copyFrom(e.minimum),i.multiplyInPlace(this.transformNode.absoluteScaling),!this._options.center){const t=new W.Pq;t.copyFrom(e.center),t.multiplyInPlace(this.transformNode.absoluteScaling),this._options.center=t}switch(this.type){case 0:!this._options.radius&&(0,ar.WithinEpsilon)(t.x,t.y,1e-4)&&(0,ar.WithinEpsilon)(t.x,t.z,1e-4)?this._options.radius=t.x/2:this._options.radius||(Z.V.Warn("Non uniform scaling is unsupported for sphere shapes. Setting the radius to the biggest bounding box extent."),this._options.radius=Math.max(t.x,t.y,t.z)/2);break;case 1:{const e=t.x/2;this._options.radius=this._options.radius??e,this._options.pointA=this._options.pointA??new W.Pq(0,i.y+e,0),this._options.pointB=this._options.pointB??new W.Pq(0,i.y+t.y-e,0)}break;case 2:{const e=t.x/2;this._options.radius=this._options.radius??e,this._options.pointA=this._options.pointA??new W.Pq(0,i.y,0),this._options.pointB=this._options.pointB??new W.Pq(0,i.y+t.y,0)}break;case 6:case 4:case 7:if(!this._options.mesh&&this._hasVertices(this.transformNode))this._options.mesh=this.transformNode;else if(!this._options.mesh||!this._hasVertices(this._options.mesh))throw new Error("No valid mesh was provided for mesh or convex hull shape parameter. Please provide a mesh with valid geometry (number of vertices greater than 0).");break;case 3:this._options.extents=this._options.extents??new W.Pq(t.x,t.y,t.z),this._options.rotation=this._options.rotation??W.PT.Identity()}}dispose(){this._nodeDisposeObserver&&(this.body.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver),this._nodeDisposeObserver=null),this.body.dispose(),this._disposeShapeWhenDisposed&&this.shape.dispose()}}class oO{}class aO{constructor(e,t,i){this._boxConfigs=new Array,this._joints=new Array,this._bones=new Array,this._initialRotation=new Array,this._initialRotation2=new Array,this._boneNames=[],this._transforms=new Array,this._aggregates=new Array,this._ragdollMode=!1,this._rootBoneName="",this._rootBoneIndex=-1,this._mass=10,this._restitution=0,this.pauseSync=!1,this._defaultJoint=3,this._defaultJointMin=-90,this._defaultJointMax=90,this._skeleton=e,this._scene=e.getScene(),this._rootTransformNode=t,this._config=i,this._boxConfigs=[],this._putBoxesInBoneCenter=!1,this._defaultJoint=3,this._init()}getAggregate(e){return e<0||e>=this._aggregates.length?this._aggregates[this._rootBoneIndex]:this._aggregates[e]}_createColliders(){this._rootTransformNode.computeWorldMatrix(),this._skeleton.computeAbsoluteMatrices(!0),this._skeleton.prepare(!0);const e=this._config;for(let t=0;t{this._syncBonesAndBoxes()})),this._syncBonesToPhysics())}ragdoll(){this._ragdollMode=!0,this._skeleton.bones.forEach((e=>{e.linkTransformNode(null)}));for(let e=0;e{e.dispose()}))}}class lO{constructor(e,t,i){this._vertices=[],this._indices=[],this._isRightHanded=i.useRightHandedSystem,this._collectIndices=t}addNodeMeshes(e,t){e.computeWorldMatrix(!0);const i=W.AA.Matrix[0];if(W.uq.ScalingToRef(e.absoluteScaling.x,e.absoluteScaling.y,e.absoluteScaling.z,i),e instanceof Yt?this._addMesh(e,i):e instanceof Kt&&this._addMesh(e.sourceMesh,i),t){const t=W.AA.Matrix[1];e.computeWorldMatrix().invertToRef(t);const r=W.AA.Matrix[2];t.multiplyToRef(i,r),e.getChildMeshes(!1).filter((e=>!e.physicsBody)).forEach((e=>{const t=e.computeWorldMatrix(),i=W.AA.Matrix[3];t.multiplyToRef(r,i),e instanceof Yt?this._addMesh(e,i):e instanceof Kt&&this._addMesh(e.sourceMesh,i)}))}}_addMesh(e,t){const i=e.getVerticesData(st.R.PositionKind)||[],r=i.length/3,s=this._vertices.length;for(let e=0;e0)for(const t of e._pluginDataInstances)this._bodyCollisionObservable.delete(t.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,t.hpBodyId),this._bodies.delete(t.hpBodyId[0]);e._pluginData&&(this._bodyCollisionObservable.delete(e._pluginData.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,e._pluginData.hpBodyId),this._bodies.delete(e._pluginData.hpBodyId[0]))}initBodyInstances(e,t,i){const r=i._thinInstanceDataStorage?.instancesCount??0,s=i._thinInstanceDataStorage.matrixData;s&&(this._createOrUpdateBodyInstances(e,t,s,0,r,!1),e._pluginDataInstances.forEach(((t,i)=>{this._bodies.set(t.hpBodyId[0],{body:e,index:i})})))}_createOrUpdateBodyInstances(e,t,i,r,s,n){const o=W.AA.Quaternion[0],a=W.uq.Identity();for(let l=r;ls){this._createOrUpdateBodyInstances(e,n,r,s,i,!1);const t=this._hknp.HP_Body_GetShape(e._pluginDataInstances[0].hpBodyId)[1];t[0]||(t[0]=e.shape?._pluginData[0]);for(let r=s;r{this._hknp.HP_Body_SetEventMask(e.hpBodyId,t)}),i)}getEventMask(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetEventMask(i.hpBodyId)[1]}_fromMassPropertiesTuple(e){return{centerOfMass:W.Pq.FromArray(e[0]),mass:e[1],inertia:W.Pq.FromArray(e[2]),inertiaOrientation:W.PT.FromArray(e[3])}}_internalUpdateMassProperties(e){const t=this._internalComputeMassProperties(e),i=e.userMassProps;i.centerOfMass&&(t[0]=i.centerOfMass.asArray()),null!=i.mass&&(t[1]=i.mass),i.inertia&&(t[2]=i.inertia.asArray()),i.inertiaOrientation&&(t[3]=i.inertiaOrientation.asArray()),this._hknp.HP_Body_SetMassProperties(e.hpBodyId,t)}_internalSetMotionType(e,t){switch(t){case 0:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.STATIC);break;case 1:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.KINEMATIC);break;case 2:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.DYNAMIC)}}setMotionType(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._internalSetMotionType(e,t)}),i)}getMotionType(e,t){const i=this._getPluginReference(e,t),r=this._hknp.HP_Body_GetMotionType(i.hpBodyId)[1];switch(r){case this._hknp.MotionType.STATIC:return 0;case this._hknp.MotionType.KINEMATIC:return 1;case this._hknp.MotionType.DYNAMIC:return 2}throw new Error("Unknown motion type: "+r)}setActivationControl(e,t){switch(t){case 1:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.ALWAYS_ACTIVE);break;case 2:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.ALWAYS_INACTIVE);break;case 0:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.SIMULATION_CONTROLLED)}}_internalComputeMassProperties(e){const t=this._hknp.HP_Body_GetShape(e.hpBodyId);if(t[0]==this._hknp.Result.RESULT_OK){const e=this._hknp.HP_Shape_BuildMassProperties(t[1]);if(e[0]==this._hknp.Result.RESULT_OK)return e[1]}return[[0,0,0],1,[1,1,1],[0,0,0,1]]}computeMassProperties(e,t){const i=this._getPluginReference(e,t),r=this._internalComputeMassProperties(i);return this._fromMassPropertiesTuple(r)}setMassProperties(e,t,i){this._applyToBodyOrInstances(e,(e=>{e.userMassProps=t,this._internalUpdateMassProperties(e)}),i)}getMassProperties(e,t){const i=this._getPluginReference(e,t),r=this._hknp.HP_Body_GetMassProperties(i.hpBodyId)[1];return this._fromMassPropertiesTuple(r)}setLinearDamping(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetLinearDamping(e.hpBodyId,t)}),i)}getLinearDamping(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetLinearDamping(i.hpBodyId)[1]}setAngularDamping(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetAngularDamping(e.hpBodyId,t)}),i)}getAngularDamping(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetAngularDamping(i.hpBodyId)[1]}setLinearVelocity(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetLinearVelocity(e.hpBodyId,this._bVecToV3(t))}),i)}getLinearVelocityToRef(e,t,i){const r=this._getPluginReference(e,i),s=this._hknp.HP_Body_GetLinearVelocity(r.hpBodyId)[1];this._v3ToBvecRef(s,t)}_applyToBodyOrInstances(e,t,i){if(e._pluginDataInstances?.length>0&&void 0===i)for(let i=0;i{this._hknp.HP_Body_ApplyImpulse(e.hpBodyId,this._bVecToV3(i),this._bVecToV3(t))}),r)}applyAngularImpulse(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_ApplyAngularImpulse(e.hpBodyId,this._bVecToV3(t))}),i)}applyForce(e,t,i,r){t.scaleToRef(this.getTimeStep(),this._tmpVec3[0]),this.applyImpulse(e,this._tmpVec3[0],i,r)}setAngularVelocity(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetAngularVelocity(e.hpBodyId,this._bVecToV3(t))}),i)}getAngularVelocityToRef(e,t,i){const r=this._getPluginReference(e,i),s=this._hknp.HP_Body_GetAngularVelocity(r.hpBodyId)[1];this._v3ToBvecRef(s,t)}setPhysicsBodyTransformation(e,t){if(e.getPrestepType()==AM.TELEPORT){const i=e.transformNode;if(e.numInstances>0){const t=i._thinInstanceDataStorage.matrixData;if(!t)return;const r=e.numInstances;this._createOrUpdateBodyInstances(e,e.getMotionType(),t,0,r,!0)}else this._hknp.HP_Body_SetQTransform(e._pluginData.hpBodyId,this._getTransformInfos(t))}else e.getPrestepType()==AM.ACTION?this.setTargetTransform(e,t.absolutePosition,t.absoluteRotationQuaternion):e.getPrestepType()==AM.DISABLED?Z.V.Warn("Prestep type is set to DISABLED. Unable to set physics body transformation."):Z.V.Warn("Invalid prestep type set to physics body.")}setTargetTransform(e,t,i,r){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetTargetQTransform(e.hpBodyId,[this._bVecToV3(t),this._bQuatToV4(i)])}),r)}setGravityFactor(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetGravityFactor(e.hpBodyId,t)}),i)}getGravityFactor(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetGravityFactor(i.hpBodyId)[1]}disposeBody(e){if(e._pluginDataInstances&&e._pluginDataInstances.length>0)for(const t of e._pluginDataInstances)this._hknp.HP_Body_Release(t.hpBodyId),t.hpBodyId=void 0;e._pluginData&&(this._hknp.HP_Body_Release(e._pluginData.hpBodyId),e._pluginData.hpBodyId=void 0)}_createOptionsFromGroundMesh(e){const t=e.groundMesh;if(!t)return;let i=t.getVerticesData(st.R.PositionKind);const r=t.computeWorldMatrix(!0),s=[];let n;for(n=0;n0?e._pluginDataInstances[0]:e._pluginData,i=this._hknp.HP_Body_GetShape(t.hpBodyId)[1],r=this._hknp.HP_Shape_CreateDebugDisplayGeometry(i);if(r[0]!=this._hknp.Result.RESULT_OK)return{positions:[],indices:[]};const s=this._hknp.HP_DebugGeometry_GetInfo(r[1])[1],n=new Float32Array(this._hknp.HEAPU8.buffer,s[0],3*s[1]),o=new Uint32Array(this._hknp.HEAPU8.buffer,s[2],3*s[3]),a=n.slice(0),l=o.slice(0);return this._hknp.HP_DebugGeometry_Release(r[1]),{positions:a,indices:l}}disposeShape(e){this._hknp.HP_Shape_Release(e._pluginData),e._pluginData=void 0}initConstraint(e,t,i,r,s){const n=e.type,o=e.options;if(!n||!o)return void Z.V.Warn("No constraint type or options. Constraint is invalid.");if(t._pluginDataInstances.length>0&&void 0===r||i._pluginDataInstances.length>0&&void 0===s)return void Z.V.Warn("Body is instanced but no instance index was specified. Constraint will not be applied.");e._pluginData=e._pluginData??[];const a=this._hknp.HP_Constraint_Create()[1];e._pluginData.push(a);const l=this._getPluginReference(t,r).hpBodyId,h=this._getPluginReference(i,s).hpBodyId;this._hknp.HP_Constraint_SetParentBody(a,l),this._hknp.HP_Constraint_SetChildBody(a,h),this._constraintToBodyIdPair.set(a[0],[l[0],h[0]]);const c=o.pivotA?this._bVecToV3(o.pivotA):this._bVecToV3(W.Pq.Zero()),u=o.axisA??new W.Pq(1,0,0),d=this._tmpVec3[0];o.perpAxisA?d.copyFrom(o.perpAxisA):u.getNormalToRef(d),this._hknp.HP_Constraint_SetAnchorInParent(a,c,this._bVecToV3(u),this._bVecToV3(d));const f=o.pivotB?this._bVecToV3(o.pivotB):this._bVecToV3(W.Pq.Zero()),p=o.axisB??new W.Pq(1,0,0),_=this._tmpVec3[0];if(o.perpAxisB?_.copyFrom(o.perpAxisB):p.getNormalToRef(_),this._hknp.HP_Constraint_SetAnchorInChild(a,f,this._bVecToV3(p),this._bVecToV3(_)),e._initOptions||(e._initOptions={axisA:u.clone(),axisB:p.clone(),perpAxisA:d.clone(),perpAxisB:_.clone(),pivotA:new W.Pq(c[0],c[1],c[2]),pivotB:new W.Pq(f[0],f[1],f[2])}),5==n)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(2==n){const e=o.maxDistance||0,t=this._hknp.ConstraintAxis.LINEAR_DISTANCE;this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(a,t,e),this._hknp.HP_Constraint_SetAxisMaxLimit(a,t,e)}else if(3==n)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(6==n)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(4==n)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(1==n)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else{if(7!=n)throw new Error("Unsupported Constraint Type.");{const t=e;for(const e of t.limits){const t=this._constraintAxisToNative(e.axis);0==(e.minLimit??-1)&&0==(e.maxLimit??-1)?this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LOCKED):(null!=e.minLimit&&(this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(a,t,e.minLimit)),null!=e.maxLimit&&(this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMaxLimit(a,t,e.maxLimit))),e.stiffness&&this._hknp.HP_Constraint_SetAxisStiffness(a,t,e.stiffness),e.damping&&this._hknp.HP_Constraint_SetAxisDamping(a,t,e.damping)}}}const m=!!o.collision;this._hknp.HP_Constraint_SetCollisionsEnabled(a,m),this._hknp.HP_Constraint_SetEnabled(a,!0)}getBodiesUsingConstraint(e){const t=[];for(const i of e._pluginData){const e=this._constraintToBodyIdPair.get(i[0]);if(e){const i=this._bodies.get(e[0]),r=this._bodies.get(e[1]);i&&r&&t.push({parentBody:i.body,parentBodyIndex:i.index,childBody:r.body,childBodyIndex:r.index})}}return t}addConstraint(e,t,i,r,s){this.initConstraint(i,e,t,r,s)}setEnabled(e,t){for(const i of e._pluginData)this._hknp.HP_Constraint_SetEnabled(i,t)}getEnabled(e){const t=e._pluginData&&e._pluginData[0];return!!t&&this._hknp.HP_Constraint_GetEnabled(t)[1]}setCollisionsEnabled(e,t){for(const i of e._pluginData)this._hknp.HP_Constraint_SetCollisionsEnabled(i,t)}getCollisionsEnabled(e){const t=e._pluginData&&e._pluginData[0];return!!t&&this._hknp.HP_Constraint_GetCollisionsEnabled(t)[1]}setAxisFriction(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisFriction(r,this._constraintAxisToNative(t),i)}getAxisFriction(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisFriction(i,this._constraintAxisToNative(t))[1]:null}setAxisMode(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMode(r,this._constraintAxisToNative(t),this._limitModeToNative(i))}getAxisMode(e,t){const i=e._pluginData&&e._pluginData[0];if(i){const e=this._hknp.HP_Constraint_GetAxisMode(i,this._constraintAxisToNative(t))[1];return this._nativeToLimitMode(e)}return null}setAxisMinLimit(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMinLimit(r,this._constraintAxisToNative(t),i)}getAxisMinLimit(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMinLimit(i,this._constraintAxisToNative(t))[1]:null}setAxisMaxLimit(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMaxLimit(r,this._constraintAxisToNative(t),i)}getAxisMaxLimit(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMaxLimit(i,this._constraintAxisToNative(t))[1]:null}setAxisMotorType(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorType(r,this._constraintAxisToNative(t),this._constraintMotorTypeToNative(i))}getAxisMotorType(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._nativeToMotorType(this._hknp.HP_Constraint_GetAxisMotorType(i,this._constraintAxisToNative(t))[1]):null}setAxisMotorTarget(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorTarget(r,this._constraintAxisToNative(t),i)}getAxisMotorTarget(e,t){return e._pluginData&&e._pluginData[0]?this._hknp.HP_Constraint_GetAxisMotorTarget(e._pluginData,this._constraintAxisToNative(t))[1]:null}setAxisMotorMaxForce(e,t,i){for(const r of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorMaxForce(r,this._constraintAxisToNative(t),i)}getAxisMotorMaxForce(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMotorMaxForce(i,this._constraintAxisToNative(t))[1]:null}disposeConstraint(e){for(const t of e._pluginData)this._hknp.HP_Constraint_SetEnabled(t,!1),this._hknp.HP_Constraint_Release(t);e._pluginData.length=0}_populateHitData(e,t){const i=this._bodies.get(e[0][0]);t.body=i?.body,t.bodyIndex=i?.index;const r=this._shapes.get(e[1][0]);t.shape=r;const s=e[3],n=e[4],o=e[5];t.setHitData({x:n[0],y:n[1],z:n[2]},{x:s[0],y:s[1],z:s[2]},o)}raycast(e,t,i,r){const s=r?.membership??-1,n=r?.collideWith??-1,o=r?.shouldHitTriggers??!1;i.reset(e,t);const a=[BigInt(0)],l=[this._bVecToV3(e),this._bVecToV3(t),[s,n],o,a];if(this._hknp.HP_World_CastRayWithCollector(this.world,this._queryCollector,l),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[,e]=this._hknp.HP_QueryCollector_GetCastRayResult(this._queryCollector,0)[1];this._populateHitData(e,i),i.calculateHitDistance()}}pointProximity(e,t){const i=e?.collisionFilter?.membership??-1,r=e?.collisionFilter?.collideWith??-1;t.reset();const s=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],n=[this._bVecToV3(e.position),e.maxDistance,[i,r],e.shouldHitTriggers,s];if(this._hknp.HP_World_PointProximityWithCollector(this.world,this._queryCollector,n),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[e,i]=this._hknp.HP_QueryCollector_GetPointProximityResult(this._queryCollector,0)[1];this._populateHitData(i,t),t.setHitDistance(e)}}shapeProximity(e,t,i){t.reset(),i.reset();const r=e.shape._pluginData,s=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],n=[r,this._bVecToV3(e.position),this._bQuatToV4(e.rotation),e.maxDistance,e.shouldHitTriggers,s];if(this._hknp.HP_World_ShapeProximityWithCollector(this.world,this._queryCollector,n),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[e,r,s]=this._hknp.HP_QueryCollector_GetShapeProximityResult(this._queryCollector,0)[1];this._populateHitData(r,t),this._populateHitData(s,i),t.setHitDistance(e),i.setHitDistance(e)}}shapeCast(e,t,i){t.reset(),i.reset();const r=e.shape._pluginData,s=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],n=[r,this._bQuatToV4(e.rotation),this._bVecToV3(e.startPosition),this._bVecToV3(e.endPosition),e.shouldHitTriggers,s];if(this._hknp.HP_World_ShapeCastWithCollector(this.world,this._queryCollector,n),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[e,r,s]=this._hknp.HP_QueryCollector_GetShapeCastResult(this._queryCollector,0)[1];this._populateHitData(r,t),this._populateHitData(s,i),t.setHitFraction(e),i.setHitFraction(e)}}getCollisionObservable(e){const t=e._pluginData.hpBodyId[0];let i=this._bodyCollisionObservable.get(t);return i||(i=new z.cP,this._bodyCollisionObservable.set(t,i)),i}getCollisionEndedObservable(e){const t=e._pluginData.hpBodyId[0];let i=this._bodyCollisionEndedObservable.get(t);return i||(i=new z.cP,this._bodyCollisionEndedObservable.set(t,i)),i}setCollisionCallbackEnabled(e,t){const i=this._hknp.EventType.COLLISION_STARTED.value|this._hknp.EventType.COLLISION_CONTINUED.value|this._hknp.EventType.COLLISION_FINISHED.value;e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach((e=>{this._hknp.HP_Body_SetEventMask(e.hpBodyId,t?i:0)})):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,t?i:0)}setCollisionEndedCallbackEnabled(e,t){const i=this._getPluginReference(e);let r=this._hknp.HP_Body_GetEventMask(i.hpBodyId)[1];r=t?r|this._hknp.EventType.COLLISION_FINISHED.value:r&~this._hknp.EventType.COLLISION_FINISHED.value,e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach((e=>{this._hknp.HP_Body_SetEventMask(e.hpBodyId,r)})):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,r)}_notifyTriggers(){let e=this._hknp.HP_World_GetTriggerEvents(this.world)[1];const t=new dO;for(;e;){dO.readToRef(this._hknp.HEAPU8.buffer,e,t);const i=this._bodies.get(t.bodyIdA),r=this._bodies.get(t.bodyIdB);if(i&&r){const e={collider:i.body,colliderIndex:i.index,collidedAgainst:r.body,collidedAgainstIndex:r.index,type:this._nativeTriggerCollisionValueToCollisionType(t.type)};this.onTriggerCollisionObservable.notifyObservers(e)}e=this._hknp.HP_World_GetNextTriggerEvent(this.world,e)}}_notifyCollisions(){let e=this._hknp.HP_World_GetCollisionEvents(this.world)[1];const t=new uO,i=Number(this.world);for(;e;){uO.readToRef(this._hknp.HEAPU8.buffer,e,t);const r=this._bodies.get(t.contactOnA.bodyId),s=this._bodies.get(t.contactOnB.bodyId);if(r&&s){const e={collider:r.body,colliderIndex:r.index,collidedAgainst:s.body,collidedAgainstIndex:s.index,type:this._nativeCollisionValueToCollisionType(t.type)};if("COLLISION_FINISHED"===e.type)this.onCollisionEndedObservable.notifyObservers(e);else{t.contactOnB.position.subtractToRef(t.contactOnA.position,this._tmpVec3[0]);const i=W.Pq.Dot(this._tmpVec3[0],t.contactOnA.normal);e.point=t.contactOnA.position,e.distance=i,e.impulse=t.impulseApplied,e.normal=t.contactOnA.normal,this.onCollisionObservable.notifyObservers(e)}if(this._bodyCollisionObservable.size&&"COLLISION_FINISHED"!==e.type){const i=this._bodyCollisionObservable.get(t.contactOnA.bodyId),n=this._bodyCollisionObservable.get(t.contactOnB.bodyId);t.contactOnA.position.subtractToRef(t.contactOnB.position,this._tmpVec3[0]);const o=W.Pq.Dot(this._tmpVec3[0],t.contactOnB.normal);if(i&&i.notifyObservers(e),n){const e={collider:s.body,colliderIndex:s.index,collidedAgainst:r.body,collidedAgainstIndex:r.index,point:t.contactOnB.position,distance:o,impulse:t.impulseApplied,normal:t.contactOnB.normal,type:this._nativeCollisionValueToCollisionType(t.type)};n.notifyObservers(e)}}else if(this._bodyCollisionEndedObservable.size){const i=this._bodyCollisionEndedObservable.get(t.contactOnA.bodyId),n=this._bodyCollisionEndedObservable.get(t.contactOnB.bodyId);t.contactOnA.position.subtractToRef(t.contactOnB.position,this._tmpVec3[0]);const o=W.Pq.Dot(this._tmpVec3[0],t.contactOnB.normal);if(i&&i.notifyObservers(e),n){const e={collider:s.body,colliderIndex:s.index,collidedAgainst:r.body,collidedAgainstIndex:r.index,point:t.contactOnB.position,distance:o,impulse:t.impulseApplied,normal:t.contactOnB.normal,type:this._nativeCollisionValueToCollisionType(t.type)};n.notifyObservers(e)}}}e=this._hknp.HP_World_GetNextCollisionEvent(i,e)}}get numBodies(){return this._hknp.HP_World_GetNumBodies(this.world)[1]}dispose(){this._queryCollector&&(this._hknp.HP_QueryCollector_Release(this._queryCollector),this._queryCollector=void 0),this.world&&(this._hknp.HP_World_Release(this.world),this.world=void 0)}_v3ToBvecRef(e,t){t.set(e[0],e[1],e[2])}_bVecToV3(e){return[e._x,e._y,e._z]}_bQuatToV4(e){return[e._x,e._y,e._z,e._w]}_constraintMotorTypeToNative(e){switch(e){case 2:return this._hknp.ConstraintMotorType.POSITION;case 1:return this._hknp.ConstraintMotorType.VELOCITY}return this._hknp.ConstraintMotorType.NONE}_nativeToMotorType(e){switch(e){case this._hknp.ConstraintMotorType.POSITION:return 2;case this._hknp.ConstraintMotorType.VELOCITY:return 1}return 0}_materialCombineToNative(e){switch(e){case 0:return this._hknp.MaterialCombine.GEOMETRIC_MEAN;case 1:return this._hknp.MaterialCombine.MINIMUM;case 2:return this._hknp.MaterialCombine.MAXIMUM;case 3:return this._hknp.MaterialCombine.ARITHMETIC_MEAN;case 4:return this._hknp.MaterialCombine.MULTIPLY}}_nativeToMaterialCombine(e){switch(e){case this._hknp.MaterialCombine.GEOMETRIC_MEAN:return 0;case this._hknp.MaterialCombine.MINIMUM:return 1;case this._hknp.MaterialCombine.MAXIMUM:return 2;case this._hknp.MaterialCombine.ARITHMETIC_MEAN:return 3;case this._hknp.MaterialCombine.MULTIPLY:return 4;default:return}}_constraintAxisToNative(e){switch(e){case 0:return this._hknp.ConstraintAxis.LINEAR_X;case 1:return this._hknp.ConstraintAxis.LINEAR_Y;case 2:return this._hknp.ConstraintAxis.LINEAR_Z;case 3:return this._hknp.ConstraintAxis.ANGULAR_X;case 4:return this._hknp.ConstraintAxis.ANGULAR_Y;case 5:return this._hknp.ConstraintAxis.ANGULAR_Z;case 6:return this._hknp.ConstraintAxis.LINEAR_DISTANCE}}_nativeToLimitMode(e){switch(e){case this._hknp.ConstraintAxisLimitMode.FREE:return 0;case this._hknp.ConstraintAxisLimitMode.LIMITED:return 1;case this._hknp.ConstraintAxisLimitMode.LOCKED:return 2}return 0}_limitModeToNative(e){switch(e){case 0:return this._hknp.ConstraintAxisLimitMode.FREE;case 1:return this._hknp.ConstraintAxisLimitMode.LIMITED;case 2:return this._hknp.ConstraintAxisLimitMode.LOCKED}}_nativeCollisionValueToCollisionType(e){switch(e){case this._hknp.EventType.COLLISION_STARTED.value:return"COLLISION_STARTED";case this._hknp.EventType.COLLISION_FINISHED.value:return"COLLISION_FINISHED";case this._hknp.EventType.COLLISION_CONTINUED.value:return"COLLISION_CONTINUED"}return"COLLISION_STARTED"}_nativeTriggerCollisionValueToCollisionType(e){switch(e){case 8:return"TRIGGER_ENTERED";case 16:return"TRIGGER_EXITED"}return"TRIGGER_ENTERED"}}oi.Z.prototype.getPhysicsEngine=function(){return this._physicsEngine},oi.Z.prototype.enablePhysics=function(e=null,t){if(this._physicsEngine)return!0;let i=this._getComponent(Ut.v.NAME_PHYSICSENGINE);i||(i=new pO(this),this._addComponent(i));try{if(t&&1!==t?.getPluginVersion()){if(2!==t?.getPluginVersion())throw new Error("Unsupported Physics plugin version.");this._physicsEngine=new BM(e,t)}else this._physicsEngine=new Hx(e,t);return this._physicsTimeAccumulator=0,!0}catch(e){return Z.V.Error(e.message),!1}},oi.Z.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},oi.Z.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},oi.Z.prototype.deleteCompoundImpostor=function(e){const t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},oi.Z.prototype._advancePhysicsEngineStep=function(e){if(this._physicsEngine){const t=this._physicsEngine.getSubTimeStep();if(t>0)for(this._physicsTimeAccumulator+=e;this._physicsTimeAccumulator>t;)this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(t/1e3),this.onAfterPhysicsObservable.notifyObservers(this),this._physicsTimeAccumulator-=t;else this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(e/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class pO{constructor(e){this.name=Ut.v.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new z.cP,this.scene.onAfterPhysicsObservable=new z.cP,this.scene.getDeterministicFrameTime=()=>this.scene._physicsEngine?1e3*this.scene._physicsEngine.getTimeStep():1e3/60}register(){}rebuild(){}dispose(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()}}Object.defineProperty(Pt.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(e){this._physicsBody!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add((()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)}))))},enumerable:!0,configurable:!0}),Pt.prototype.getPhysicsBody=function(){return this.physicsBody},Pt.prototype.applyImpulse=function(e,t){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(e,t),this},Pt.prototype.applyAngularImpulse=function(e){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyAngularImpulse(e),this};class _O{static GetContactPointToRef(e,t,i,r,s){const n=e.getScene().getPhysicsEngine(),o=n?.getPluginVersion();if(1===o){const s=new wi(t,i).intersectsMesh(e);if(s.hit&&s.pickedPoint)return r.copyFrom(s.pickedPoint),!0}else if(2===o)return e.physicsBody.getObjectCenterWorldToRef(r,s),!0;return!1}static HasAppliedForces(e,t){return 0===e.getMotionType(t)||0===(e.getMassProperties(t)?.mass??0)||0===e.transformNode?.getTotalVertices()}static IsInsideCylinder(e,t,i,r){const s=W.AA.Vector3[0];return e.subtractToRef(t,s),Math.abs(s.x)<=i&&Math.abs(s.z)<=i&&s.y>=0&&s.y<=r}}class mO{constructor(e){this._hitData={force:new W.Pq,contactPoint:new W.Pq,distanceFromOrigin:0},this._scene=e,this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine||Z.V.Warn("Physics engine not enabled. Please enable the physics before you can use the methods.")}applyRadialExplosionImpulse(e,t,i,r){if(!this._physicsEngine)return Z.V.Warn("Physics engine not enabled. Please enable the physics before you call this method."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;let s=!1;if("number"==typeof t){const e=t;(t=new SO).radius=e,t.strength=i??t.strength,t.falloff=r??t.falloff}else s=!(!t.affectedImpostorsCallback&&!t.affectedBodiesCallback);const n=new gO(this._scene,t),o=this._hitData;if(1===this._physicsEngine.getPluginVersion()){const t=Array();this._physicsEngine.getImpostors().forEach((i=>{n.getImpostorHitData(i,e,o)&&(i.applyImpulse(o.force,o.contactPoint),s&&t.push({impostor:i,hitData:this._copyPhysicsHitData(o)}))})),n.triggerAffectedImpostorsCallback(t)}else this._applicationForBodies(n,e,o,s,((e,t)=>{e.applyImpulse(t.force,t.contactPoint,t.instanceIndex)}));return n.dispose(!1),n}applyRadialExplosionForce(e,t,i,r){if(!this._physicsEngine)return Z.V.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;let s=!1;if("number"==typeof t){const e=t;(t=new SO).radius=e,t.strength=i??t.strength,t.falloff=r??t.falloff}else s=!(!t.affectedImpostorsCallback&&!t.affectedBodiesCallback);const n=new gO(this._scene,t),o=this._hitData;if(1===this._physicsEngine.getPluginVersion()){const t=Array();this._physicsEngine.getImpostors().forEach((i=>{n.getImpostorHitData(i,e,o)&&(i.applyForce(o.force,o.contactPoint),s&&t.push({impostor:i,hitData:this._copyPhysicsHitData(o)}))})),n.triggerAffectedImpostorsCallback(t)}else this._applicationForBodies(n,e,o,s,((e,t)=>{e.applyForce(t.force,t.contactPoint,t.instanceIndex)}));return n.dispose(!1),n}_applicationForBodies(e,t,i,r,s){const n=Array(),o=this._physicsEngine.getBodies();for(const a of o)a.iterateOverAllInstances(((o,a)=>{e.getBodyHitData(o,t,i,a)&&(s(o,i),r&&n.push({body:o,hitData:this._copyPhysicsHitData(i)}))}));e.triggerAffectedBodiesCallback(n)}gravitationalField(e,t,i,r){if(!this._physicsEngine)return Z.V.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new SO).radius=e,t.strength=i??t.strength,t.falloff=r??t.falloff}const s=new vO(this,this._scene,e,t);return s.dispose(!1),s}updraft(e,t,i,r,s){if(!this._physicsEngine)return Z.V.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new TO).radius=e,t.strength=i??t.strength,t.height=r??t.height,t.updraftMode=s??t.updraftMode}const n=new xO(this._scene,e,t);return n.dispose(!1),n}vortex(e,t,i,r){if(!this._physicsEngine)return Z.V.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new CO).radius=e,t.strength=i??t.strength,t.height=r??t.height}const s=new bO(this._scene,e,t);return s.dispose(!1),s}_copyPhysicsHitData(e){return{force:e.force.clone(),contactPoint:e.contactPoint.clone(),distanceFromOrigin:e.distanceFromOrigin,instanceIndex:e.instanceIndex}}}class gO{constructor(e,t){this._scene=e,this._options=t,this._dataFetched=!1,this._options={...new SO,...this._options}}getData(){return this._dataFetched=!0,{sphere:this._sphere}}_getHitData(e,t,i,r){const s=W.AA.Vector3[0];s.copyFrom(t).subtractInPlace(i);const n=W.AA.Vector3[1];if(!_O.GetContactPointToRef(e,i,s,n,r.instanceIndex))return!1;const o=W.Pq.Distance(i,n);if(o>this._options.radius)return!1;const a=0===this._options.falloff?this._options.strength:this._options.strength*(1-o/this._options.radius);return s.scaleInPlace(a),r.force.copyFrom(s),r.contactPoint.copyFrom(n),r.distanceFromOrigin=o,!0}getBodyHitData(e,t,i,r){if(_O.HasAppliedForces(e,r))return!1;const s=e.transformNode,n=e.getObjectCenterWorld(r);return i.instanceIndex=r,this._getHitData(s,n,t,i)}getImpostorHitData(e,t,i){if(0===e.mass)return!1;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;const r=e.object;if(!this._intersectsWithSphere(r,t,this._options.radius))return!1;const s=e.getObjectCenter();return this._getHitData(r,s,t,i),!0}triggerAffectedImpostorsCallback(e){this._options.affectedImpostorsCallback&&this._options.affectedImpostorsCallback(e)}triggerAffectedBodiesCallback(e){this._options.affectedBodiesCallback&&this._options.affectedBodiesCallback(e)}dispose(e=!0){this._sphere&&(e?this._sphere.dispose():setTimeout((()=>{this._dataFetched||this._sphere.dispose()}),0))}_prepareSphere(){this._sphere||(this._sphere=Qo("radialExplosionEventSphere",this._options.sphere,this._scene),this._sphere.isVisible=!1)}_intersectsWithSphere(e,t,i){return this._prepareSphere(),this._sphere.position=t,this._sphere.scaling.setAll(2*i),this._sphere._updateBoundingInfo(),this._sphere.computeWorldMatrix(!0),this._sphere.intersectsMesh(e,!0)}}class vO{constructor(e,t,i,r){this._physicsHelper=e,this._scene=t,this._origin=i,this._options=r,this._dataFetched=!1,this._options={...new SO,...this._options},this._tickCallback=()=>this._tick(),this._options.strength=-1*this._options.strength}getData(){return this._dataFetched=!0,{sphere:this._sphere}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._sphere&&(e?this._sphere.dispose():setTimeout((()=>{this._dataFetched||this._sphere.dispose()}),0))}_tick(){if(this._sphere)this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);else{const e=this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);e&&(this._sphere=e.getData().sphere?.clone("radialExplosionEventSphereClone"))}}}class xO{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=W.Pq.Zero(),this._originDirection=W.Pq.Zero(),this._cylinderPosition=W.Pq.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new TO,...this._options},this._origin.addToRef(new W.Pq(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new W.Pq(0,this._options.height,0),this._originTop),1===this._options.updraftMode&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?(this._cylinder.dispose(),this._cylinder=void 0):setTimeout((()=>{!this._dataFetched&&this._cylinder&&(this._cylinder.dispose(),this._cylinder=void 0)}),0))}_getHitData(e,t){let i;i=1===this._options.updraftMode?this._originDirection:e.subtract(this._originTop);const r=W.Pq.Distance(this._origin,e),s=-1*this._options.strength,n=i.multiplyByFloats(s,s,s);t.force.copyFrom(n),t.contactPoint.copyFrom(e),t.distanceFromOrigin=r}_getBodyHitData(e,t,i){if(_O.HasAppliedForces(e))return!1;const r=e.getObjectCenterWorld(i);return!!_O.IsInsideCylinder(r,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(r,t),!0)}_getImpostorHitData(e,t){if(0===e.mass)return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const r=e.getObjectCenter();return this._getHitData(r,t),!0}_tick(){const e=xO._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=No("updraftEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return!!this._cylinder&&(this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0))}}xO._HitData={force:new W.Pq,contactPoint:new W.Pq,distanceFromOrigin:0};class bO{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=W.Pq.Zero(),this._cylinderPosition=W.Pq.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new CO,...this._options},this._origin.addToRef(new W.Pq(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new W.Pq(0,this._options.height,0),this._originTop),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?this._cylinder.dispose():setTimeout((()=>{this._dataFetched||this._cylinder.dispose()}),0))}_getHitData(e,t,i){const r=bO._OriginOnPlane;r.set(this._origin.x,t.y,this._origin.z);const s=W.AA.Vector3[0];t.subtractToRef(r,s);const n=W.AA.Vector3[1];if(!_O.GetContactPointToRef(e,r,s,n,i.instanceIndex))return!1;const o=W.Pq.Distance(n,r)/this._options.radius,a=W.AA.Vector3[2];let l,h,c;if(n.normalizeToRef(a),o>this._options.centripetalForceThreshold&&a.negateInPlace(),o>this._options.centripetalForceThreshold)l=a.x*this._options.centripetalForceMultiplier,h=a.y*this._options.updraftForceMultiplier,c=a.z*this._options.centripetalForceMultiplier;else{const e=W.Pq.Cross(r,t).normalize();l=(e.x+a.x)*this._options.centrifugalForceMultiplier,h=this._originTop.y*this._options.updraftForceMultiplier,c=(e.z+a.z)*this._options.centrifugalForceMultiplier}const u=W.AA.Vector3[3];return u.set(l,h,c),u.scaleInPlace(this._options.strength),i.force.copyFrom(u),i.contactPoint.copyFrom(t),i.distanceFromOrigin=o,!0}_getBodyHitData(e,t,i){if(_O.HasAppliedForces(e,i))return!1;const r=e.transformNode,s=e.getObjectCenterWorld(i);return!!_O.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(r,s,t))}_getImpostorHitData(e,t){if(0===e.mass)return!1;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const r=e.getObjectCenter();return this._getHitData(i,r,t),!0}_tick(){const e=bO._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=No("vortexEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)}}bO._OriginOnPlane=W.Pq.Zero(),bO._HitData={force:new W.Pq,contactPoint:new W.Pq,distanceFromOrigin:0};class SO{constructor(){this.radius=5,this.strength=10,this.falloff=0,this.sphere={segments:32,diameter:1}}}class TO{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=0}}class CO{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}}!function(e){e[e.Constant=0]="Constant",e[e.Linear=1]="Linear"}(MM||(MM={})),function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"}(OM||(OM={}));class yO extends zx{constructor(){super(...arguments),this._hitDistance=0}get hitDistance(){return this._hitDistance}setHitDistance(e){this._hitDistance=e}reset(){super.reset(),this._hitDistance=0}}class EO extends zx{constructor(){super(...arguments),this._hitFraction=0}get hitFraction(){return this._hitFraction}setHitFraction(e){this._hitFraction=e}}class PO extends ms.w{get degree(){return this._effectWrapper.degree}set degree(e){this._effectWrapper.degree=e}getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i=null,r,s,n){const o={uniforms:l_.Uniforms,size:"number"==typeof t?t:void 0,camera:i,samplingMode:r,engine:s,reusable:n,...t};super(e,l_.FragmentUrl,{effectWrapper:"number"!=typeof t&&t.effectWrapper?void 0:new l_(e,s,o),...o})}static _Parse(e,t,i,r){return it.p.Parse((()=>new PO(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,r)}}(0,je.Cg)([(0,$e.lK)()],PO.prototype,"degree",null),(0,X.Y5)("BABYLON.BlackAndWhitePostProcess",PO);class AO{constructor(e,t,i,r){this._name=t,this._singleInstance=r||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(const e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){const t=this._postProcesses[e];for(let e=0;e{const t=r.attachPostProcess(e);this._indicesForCamera[s].push(t)})),this._cameras[s]||(this._cameras[s]=r)}}_detachCameras(e){const t=Ue.S0.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)})),this._cameras[r]&&(this._cameras[r]=null),delete this._indicesForCamera[r]}}_enable(e){const t=Ue.S0.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)}))}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}class RO extends ms.w{get threshold(){return this._effectWrapper.threshold}set threshold(e){this._effectWrapper.threshold=e}get _exposure(){return this._effectWrapper._exposure}set _exposure(e){this._effectWrapper._exposure=e}getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i=null,r,s,n,o=0,a=!1){const l={uniforms:__.Uniforms,size:"number"==typeof t?t:void 0,camera:i,samplingMode:r,engine:s,reusable:n,textureType:o,blockCompilation:a,...t};super(e,__.FragmentUrl,{effectWrapper:"number"!=typeof t&&t.effectWrapper?void 0:new __(e,s,l),...l}),this._inputPostProcess=null,this.onApplyObservable.add((e=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&e.setTextureFromPostProcess("textureSampler",this._inputPostProcess)}))}}(0,je.Cg)([(0,$e.lK)()],RO.prototype,"threshold",null),(0,X.Y5)("BABYLON.ExtractHighlightsPostProcess",RO);class IO extends ms.w{get weight(){return this._effectWrapper.weight}set weight(e){this._effectWrapper.weight=e}getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,r,s,n=null,o,a,l,h=0,c=!1){const u="number"==typeof s?c:!!s.blockCompilation,d={uniforms:d_.Uniforms,samplers:d_.Samplers,size:"number"==typeof s?s:void 0,camera:n,samplingMode:o,engine:a,reusable:l,textureType:h,...s,blockCompilation:!0};super(e,d_.FragmentUrl,{effectWrapper:"number"!=typeof s&&s.effectWrapper?void 0:new d_(e,a,d),...d}),this.weight=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("bloomBlur",i)})),u||this.updateEffect()}}(0,je.Cg)([(0,$e.lK)()],IO.prototype,"weight",null),(0,X.Y5)("BABYLON.BloomMergePostProcess",IO);class MO extends AO{get threshold(){return this._thinBloomEffect.threshold}set threshold(e){this._thinBloomEffect.threshold=e}get weight(){return this._thinBloomEffect.weight}set weight(e){this._thinBloomEffect.weight=e}get kernel(){return this._thinBloomEffect.kernel}set kernel(e){this._thinBloomEffect.kernel=e}get bloomScale(){return this._thinBloomEffect.scale}constructor(e,t,i,r,s=0,n=!1){const o=e._renderForCamera?e.getEngine():e;super(o,"bloom",(()=>this._effects),!0),this._effects=[],this._thinBloomEffect=new m_("bloom",o,t,n),this._downscale=new RO("highlights",{size:1,samplingMode:vi.g.BILINEAR_SAMPLINGMODE,engine:o,textureType:s,blockCompilation:n,effectWrapper:this._thinBloomEffect._downscale}),this._blurX=new _m("horizontal blur",this._thinBloomEffect._blurX.direction,this._thinBloomEffect._blurX.kernel,{size:t,samplingMode:vi.g.BILINEAR_SAMPLINGMODE,engine:o,textureType:s,blockCompilation:n,effectWrapper:this._thinBloomEffect._blurX}),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new _m("vertical blur",this._thinBloomEffect._blurY.direction,this._thinBloomEffect._blurY.kernel,{size:t,samplingMode:vi.g.BILINEAR_SAMPLINGMODE,engine:o,textureType:s,blockCompilation:n,effectWrapper:this._thinBloomEffect._blurY}),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=r,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new IO("bloomMerge",this._downscale,this._blurY,i,{size:t,samplingMode:vi.g.BILINEAR_SAMPLINGMODE,engine:o,textureType:s,blockCompilation:n,effectWrapper:this._thinBloomEffect._merge}),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t{e.setFloat("chromatic_aberration",this.aberrationAmount),e.setFloat("screen_width",t),e.setFloat("screen_height",i),e.setFloat("radialIntensity",this.radialIntensity),e.setFloat2("direction",this.direction.x,this.direction.y),e.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)}))}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,44134))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,76437))])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return it.p.Parse((()=>new OO(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,r)}}(0,je.Cg)([(0,$e.lK)()],OO.prototype,"aberrationAmount",void 0),(0,je.Cg)([(0,$e.lK)()],OO.prototype,"radialIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],OO.prototype,"direction",void 0),(0,je.Cg)([(0,$e.lK)()],OO.prototype,"centerPosition",void 0),(0,je.Cg)([(0,$e.lK)()],OO.prototype,"screenWidth",void 0),(0,je.Cg)([(0,$e.lK)()],OO.prototype,"screenHeight",void 0),(0,X.Y5)("BABYLON.ChromaticAberrationPostProcess",OO);class DO extends ms.w{get lensSize(){return this._effectWrapper.lensSize}set lensSize(e){this._effectWrapper.lensSize=e}get fStop(){return this._effectWrapper.fStop}set fStop(e){this._effectWrapper.fStop=e}get focusDistance(){return this._effectWrapper.focusDistance}set focusDistance(e){this._effectWrapper.focusDistance=e}get focalLength(){return this._effectWrapper.focalLength}set focalLength(e){this._effectWrapper.focalLength=e}getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,r,s,n,o,a=0,l=!1){const h={uniforms:T_.Uniforms,samplers:T_.Samplers,defines:"object"==typeof i&&i.depthNotNormalized?T_.DefinesDepthNotNormalized:void 0,size:"number"==typeof i?i:void 0,camera:r,samplingMode:s,engine:n,reusable:o,textureType:a,blockCompilation:l,...i};super(e,T_.FragmentUrl,{effectWrapper:"number"!=typeof i&&i.effectWrapper?void 0:new T_(e,n,h),...h}),this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add((e=>{this._depthTexture?(e.setTexture("depthSampler",this._depthTexture),this._effectWrapper.camera=this._depthTexture.activeCamera):Z.V.Warn("No depth texture set on CircleOfConfusionPostProcess")}))}set depthTexture(e){this._depthTexture=e}}(0,je.Cg)([(0,$e.lK)()],DO.prototype,"lensSize",null),(0,je.Cg)([(0,$e.lK)()],DO.prototype,"fStop",null),(0,je.Cg)([(0,$e.lK)()],DO.prototype,"focusDistance",null),(0,je.Cg)([(0,$e.lK)()],DO.prototype,"focalLength",null),(0,X.Y5)("BABYLON.CircleOfConfusionPostProcess",DO);class wO extends ms.w{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,r,s,n,o){super(e,"colorCorrection",null,["colorTable"],i,r,s,n,o);const a=r?.getScene()||null;this._colorTableTexture=new vi.g(t,a,!0,!1,vi.g.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=vi.g.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=vi.g.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=e=>{e.setTexture("colorTable",this._colorTableTexture)}}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,82308))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,42711))])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return it.p.Parse((()=>new wO(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,r)}}(0,je.Cg)([(0,$e.lK)()],wO.prototype,"colorTableUrl",void 0),(0,X.Y5)("BABYLON.ColorCorrectionPostProcess",wO);class NO extends ms.w{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,r,s,n,o,a=0){super(e,"convolution",["kernel","screenSize"],null,i,r,s,n,o,null,a),this.kernel=t,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setArray("kernel",this.kernel)}}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,79799))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,59188))])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return it.p.Parse((()=>new NO(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType)),e,i,r)}}NO.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],NO.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],NO.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],NO.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],NO.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],NO.GaussianKernel=[0,1,0,1,1,1,0,1,0],(0,je.Cg)([(0,$e.lK)()],NO.prototype,"kernel",void 0),(0,X.Y5)("BABYLON.ConvolutionPostProcess",NO);class FO extends _m{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,r,s,n,o,a=null,l=vi.g.BILINEAR_SAMPLINGMODE,h,c,u=0,d=!1,f=5){super(e,i,r,{camera:n,engine:h,reusable:c,textureType:u,defines:"#define DOF 1\n",blockCompilation:d,textureFormat:f,...s,samplingMode:2}),this.externalTextureSamplerBinding=!!a,this.onApplyObservable.add((e=>{null!=a&&e.setTextureFromPostProcess("textureSampler",a),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",o)}))}}(0,X.Y5)("BABYLON.DepthOfFieldBlurPostProcess",FO);class LO extends ms.w{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,r,s,n,o,a,l,h=0,c=!1){const u="number"==typeof s?c:!!s.blockCompilation,d={samplers:E_.Samplers,size:"number"==typeof s?s:void 0,camera:n,samplingMode:o,engine:a,reusable:l,textureType:h,...s,blockCompilation:!0};super(e,E_.FragmentUrl,{effectWrapper:"number"!=typeof s&&s.effectWrapper?void 0:new E_(e,a,d),...d}),this._blurSteps=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),r.forEach(((t,i)=>{e.setTextureFromPostProcessOutput("blurStep"+(r.length-i-1),t)}))})),u||this.updateEffect()}updateEffect(e=null,t=null,i=null,r,s,n){e||(e="",e+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),super.updateEffect(e,t,i,r,s,n)}}!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(DM||(DM={}));class BO extends AO{set focalLength(e){this._thinDepthOfFieldEffect.focalLength=e}get focalLength(){return this._thinDepthOfFieldEffect.focalLength}set fStop(e){this._thinDepthOfFieldEffect.fStop=e}get fStop(){return this._thinDepthOfFieldEffect.fStop}set focusDistance(e){this._thinDepthOfFieldEffect.focusDistance=e}get focusDistance(){return this._thinDepthOfFieldEffect.focusDistance}set lensSize(e){this._thinDepthOfFieldEffect.lensSize=e}get lensSize(){return this._thinDepthOfFieldEffect.lensSize}constructor(e,t,i=0,r=0,s=!1,n=!1){const o=e._renderForCamera?e.getEngine():e;super(o,"depth of field",(()=>this._effects),!0),this._effects=[],this._thinDepthOfFieldEffect=new I_("Depth of Field",o,i,!1,s);const a=o.isWebGPU||o.version>1?6:5;this._circleOfConfusion=new DO("circleOfConfusion",t,{size:1,samplingMode:vi.g.BILINEAR_SAMPLINGMODE,engine:o,textureType:r,blockCompilation:s,depthNotNormalized:n,effectWrapper:this._thinDepthOfFieldEffect._circleOfConfusion},null),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];const l=this._thinDepthOfFieldEffect._depthOfFieldBlurX.length;for(let e=0;enew VO(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,r)}}(0,X.Y5)("BABYLON.DisplayPassPostProcess",VO);class kO extends ms.w{getClassName(){return"FilterPostProcess"}constructor(e,t,i,r,s,n,o){super(e,"filter",["kernelMatrix"],null,i,r,s,n,o),this.kernelMatrix=t,this.onApply=e=>{e.setMatrix("kernelMatrix",this.kernelMatrix)}}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,26879))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,88770))])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return it.p.Parse((()=>new kO(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,r)}}(0,je.Cg)([(0,$e.GG)()],kO.prototype,"kernelMatrix",void 0),(0,X.Y5)("BABYLON.FilterPostProcess",kO);class UO extends ms.w{getClassName(){return"GrainPostProcess"}constructor(e,t,i,r,s,n,o=0,a=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,r,s,n,null,o,void 0,null,a),this.intensity=30,this.animated=!1,this.onApplyObservable.add((e=>{e.setFloat("intensity",this.intensity),e.setFloat("animatedSeed",this.animated?Math.random()+1:1)}))}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,35624))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,55099))])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return it.p.Parse((()=>new UO(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,r)}}(0,je.Cg)([(0,$e.lK)()],UO.prototype,"intensity",void 0),(0,je.Cg)([(0,$e.lK)()],UO.prototype,"animated",void 0),(0,X.Y5)("BABYLON.GrainPostProcess",UO);class GO extends ms.w{getClassName(){return"HighlightsPostProcess"}constructor(e,t,i,r,s,n,o=0){super(e,"highlights",null,null,t,i,r,s,n,null,o)}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,28162))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,13079))])),super._gatherImports(e,t)}}class zO extends ms.w{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 e=null;const t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){const i=t.scenes;e=i[i.length-1]}else e=he.q.LastCreatedScene;this._imageProcessingConfiguration=e?e.imageProcessingConfiguration:new gn.p}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateParameters()}))),t||this._updateParameters()}}get isSupported(){const e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,r,s,n,o=0,a){super(e,"imageProcessing",[],[],t,i,r,s,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},a?(a.applyByPostProcess=!0,this._attachImageProcessingConfiguration(a,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=e=>{this.imageProcessingConfiguration.bind(e,this.aspectRatio)}}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(i.bind(i,41123)))):t.push(Promise.resolve().then(i.bind(i,27220))),super._gatherImports(e,t)}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(const t in this._defines){const i=this._defines[t];switch(typeof i){case"number":case"string":e+=`#define ${t} ${i};\n`;break;default:i&&(e+=`#define ${t};\n`)}}const t=["textureSampler"],i=["scale"];gn.p&&(gn.p.PrepareSamplers(t,this._defines),gn.p.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)}}(0,je.Cg)([(0,$e.lK)()],zO.prototype,"_fromLinearSpace",void 0);var WO=i(2146),HO=i(24077);const XO=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureWidth"];(0,Ln.TV)(XO);class qO{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._enableDepth=!0,this._enableNormal=!0,this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._enableVelocityLinear=!1,this._enableScreenspaceDepth=!1,this._attachmentsFromPrePass=[]}_forceTextureType(e,t){e===qO.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===qO.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===qO.VELOCITY_LINEAR_TEXTURE_TYPE?(this._velocityLinearIndex=t,this._enableVelocityLinear=!0):e===qO.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===qO.DEPTH_TEXTURE_TYPE?(this._depthIndex=t,this._enableDepth=!0):e===qO.NORMAL_TEXTURE_TYPE?(this._normalIndex=t,this._enableNormal=!0):e===qO.SCREENSPACE_DEPTH_TEXTURE_TYPE&&(this._screenspaceDepthIndex=t,this._enableScreenspaceDepth=!0)}_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 qO.POSITION_TEXTURE_TYPE:return this._positionIndex;case qO.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case qO.VELOCITY_LINEAR_TEXTURE_TYPE:return this._velocityLinearIndex;case qO.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case qO.DEPTH_TEXTURE_TYPE:return this._depthIndex;case qO.NORMAL_TEXTURE_TYPE:return this._normalIndex;case qO.SCREENSPACE_DEPTH_TEXTURE_TYPE:return this._screenspaceDepthIndex;default:return-1}}get enableDepth(){return this._enableDepth}set enableDepth(e){this._enableDepth=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableNormal(){return this._enableNormal}set enableNormal(e){this._enableNormal=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}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 enableVelocityLinear(){return this._enableVelocityLinear}set enableVelocityLinear(e){this._enableVelocityLinear=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableScreenspaceDepth(){return this._enableScreenspaceDepth}set enableScreenspaceDepth(e){this._enableScreenspaceDepth=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return"object"==typeof this._ratioOrDimensions?1:this._ratioOrDimensions}get shaderLanguage(){return this._shaderLanguage}constructor(e,t=1,i=15,r){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._normalsAreUnsigned=!1,this._resizeObserver=null,this._enableDepth=!0,this._enableNormal=!0,this._enablePosition=!1,this._enableVelocity=!1,this._enableVelocityLinear=!1,this._enableReflectivity=!1,this._enableScreenspaceDepth=!1,this._clearColor=new H.ov(0,0,0,0),this._clearDepthColor=new H.ov(1e8,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._velocityLinearIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._screenspaceDepthIndex=-1,this._linkedWithPrePass=!1,this.useSpecificClearForDepthTexture=!1,this._shaderLanguage=0,this._shadersLoaded=!1,this._scene=e,this._ratioOrDimensions=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,this._textureTypesAndFormats=r||{},this._initShaderSourceAsync(),qO._SceneComponentInitialization(this._scene),this._createRenderTargets()}async _initShaderSourceAsync(){this._scene.getEngine().isWebGPU&&!qO.ForceGLSL?(this._shaderLanguage=1,await Promise.all([Promise.resolve().then(i.bind(i,20267)),Promise.resolve().then(i.bind(i,55745))])):await Promise.all([Promise.resolve().then(i.bind(i,24077)),Promise.resolve().then(i.bind(i,2146))]),this._shadersLoaded=!0}isReady(e,t){if(!this._shadersLoaded)return!1;const i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;const r=[],s=[st.R.PositionKind,st.R.NormalKind],n=e.getMesh();if(i){let e=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(r.push("#define ALPHATEST"),r.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),e=!0),(i.bumpTexture||i.normalTexture)&&Sn.BumpTextureEnabled){const t=i.bumpTexture||i.normalTexture;r.push("#define BUMP"),r.push(`#define BUMP_UV${t.coordinatesIndex+1}`),e=!0}if(this._enableReflectivity){let t=!1;"PBRMetallicRoughnessMaterial"===i.getClassName()?(i.metallicRoughnessTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!=i.metallic&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),t=!0),null!=i.roughness&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),t=!0),t&&(i.baseTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),e=!0),i.baseColor&&r.push("#define ALBEDOCOLOR"))):"PBRSpecularGlossinessMaterial"===i.getClassName()?(i.specularGlossinessTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),e=!0,i.specularGlossinessTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE")):i.specularColor&&r.push("#define REFLECTIVITYCOLOR"),null!=i.glossiness&&r.push("#define GLOSSINESS")):"PBRMaterial"===i.getClassName()?(i.metallicTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!=i.metallic&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),t=!0),null!=i.roughness&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),t=!0),t?(i.albedoTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),e=!0),i.albedoColor&&r.push("#define ALBEDOCOLOR")):(i.reflectivityTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0):i.reflectivityColor&&r.push("#define REFLECTIVITYCOLOR"),null!=i.microSurface&&r.push("#define GLOSSINESS"))):"StandardMaterial"===i.getClassName()&&(i.specularTexture&&(r.push("#define REFLECTIVITYTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0),i.specularColor&&r.push("#define REFLECTIVITYCOLOR"))}e&&(r.push("#define NEED_UV"),n.isVerticesDataPresent(st.R.UVKind)&&(s.push(st.R.UVKind),r.push("#define UV1")),n.isVerticesDataPresent(st.R.UV2Kind)&&(s.push(st.R.UV2Kind),r.push("#define UV2")))}this._enableDepth&&(r.push("#define DEPTH"),r.push("#define DEPTH_INDEX "+this._depthIndex)),this._enableNormal&&(r.push("#define NORMAL"),r.push("#define NORMAL_INDEX "+this._normalIndex)),this._enablePosition&&(r.push("#define POSITION"),r.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(r.push("#define VELOCITY"),r.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(n)&&r.push("#define BONES_VELOCITY_ENABLED")),this._enableVelocityLinear&&(r.push("#define VELOCITY_LINEAR"),r.push("#define VELOCITY_LINEAR_INDEX "+this._velocityLinearIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(n)&&r.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(r.push("#define REFLECTIVITY"),r.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this._enableScreenspaceDepth&&-1!==this._screenspaceDepthIndex&&(r.push("#define SCREENSPACE_DEPTH_INDEX "+this._screenspaceDepthIndex),r.push("#define SCREENSPACE_DEPTH")),this.generateNormalsInWorldSpace&&r.push("#define NORMAL_WORLDSPACE"),this._normalsAreUnsigned&&r.push("#define ENCODE_NORMAL"),n.useBones&&n.computeBonesUsingShaders&&n.skeleton?(s.push(st.R.MatricesIndicesKind),s.push(st.R.MatricesWeightsKind),n.numBoneInfluencers>4&&(s.push(st.R.MatricesIndicesExtraKind),s.push(st.R.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),r.push("#define BONETEXTURE "+n.skeleton.isUsingTextureForMatrices),r.push("#define BonesPerMesh "+(n.skeleton.bones.length+1))):(r.push("#define NUM_BONE_INFLUENCERS 0"),r.push("#define BONETEXTURE false"),r.push("#define BonesPerMesh 0"));const o=n.morphTargetManager;let a=0;o&&(a=o.numMaxInfluencers||o.numInfluencers,a>0&&(r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+a),o.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),(0,Bt.MF)(s,n,a))),t&&(r.push("#define INSTANCES"),(0,Bt.te)(s,this._enableVelocity||this._enableVelocityLinear),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES")),this._linkedWithPrePass?r.push("#define SCENE_MRT_COUNT "+this._attachmentsFromPrePass.length):r.push("#define SCENE_MRT_COUNT "+this._multiRenderTarget.textures.length),(0,Ln.tv)(i,this._scene,r);const l=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),c=h.defines,u=r.join("\n");return c!==u&&h.setEffect(l.createEffect("geometry",{attributes:s,uniformsNames:XO,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets","boneSampler"],defines:u,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:a},shaderLanguage:this.shaderLanguage},l),u),h.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=0;return this._enableDepth&&(this._depthIndex=i,i++,e.push("gBuffer_Depth"),t.push(this._textureTypesAndFormats[qO.DEPTH_TEXTURE_TYPE])),this._enableNormal&&(this._normalIndex=i,i++,e.push("gBuffer_Normal"),t.push(this._textureTypesAndFormats[qO.NORMAL_TEXTURE_TYPE])),this._enablePosition&&(this._positionIndex=i,i++,e.push("gBuffer_Position"),t.push(this._textureTypesAndFormats[qO.POSITION_TEXTURE_TYPE])),this._enableVelocity&&(this._velocityIndex=i,i++,e.push("gBuffer_Velocity"),t.push(this._textureTypesAndFormats[qO.VELOCITY_TEXTURE_TYPE])),this._enableVelocityLinear&&(this._velocityLinearIndex=i,i++,e.push("gBuffer_VelocityLinear"),t.push(this._textureTypesAndFormats[qO.VELOCITY_LINEAR_TEXTURE_TYPE])),this._enableReflectivity&&(this._reflectivityIndex=i,i++,e.push("gBuffer_Reflectivity"),t.push(this._textureTypesAndFormats[qO.REFLECTIVITY_TEXTURE_TYPE])),this._enableScreenspaceDepth&&(this._screenspaceDepthIndex=i,i++,e.push("gBuffer_ScreenspaceDepth"),t.push(this._textureTypesAndFormats[qO.SCREENSPACE_DEPTH_TEXTURE_TYPE])),[i,e,t]}_createRenderTargets(){const e=this._scene.getEngine(),[t,i,r]=this._assignRenderTargetIndices();let s=0;e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?s=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(s=2);const n=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions},o=[],a=[];for(const e of r)e?(o.push(e.textureType),a.push(e.textureFormat)):(o.push(s),a.push(5));if(this._normalsAreUnsigned=11===o[qO.NORMAL_TEXTURE_TYPE]||13===o[qO.NORMAL_TEXTURE_TYPE],this._multiRenderTarget=new Xb("gBuffer",n,t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,types:o,formats:a,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=vi.g.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=vi.g.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;const l=[!0],h=[!1],c=[!0];for(let e=1;e{e.bindAttachments(this.useSpecificClearForDepthTexture?d:u),e.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(e.bindAttachments(f),e.clear(this._clearDepthColor,!0,!0,!0)),e.bindAttachments(u)})),this._resizeObserver=e.onResizeObservable.add((()=>{if(this._multiRenderTarget){const t=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};this._multiRenderTarget.resize(t)}}));const p=e=>{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),r=this._scene,s=r.getEngine(),n=e.getMaterial();if(!n)return;if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,(this._enableVelocity||this._enableVelocityLinear)&&!this._previousTransformationMatrices[i.uniqueId]&&(this._previousTransformationMatrices[i.uniqueId]={world:W.uq.Identity(),viewProjection:r.getTransformMatrix()},t.skeleton)){const e=t.skeleton.getTransformMatrices(t);this._previousBonesTransformationMatrices[t.uniqueId]=this._copyBonesTransformationMatrices(e,new Float32Array(e.length))}const o=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;const a=s.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||t.hasThinInstances),l=i.getWorldMatrix();if(this.isReady(e,a)){const h=e._getDrawWrapper();if(!h)return;const c=h.effect;let u;s.enableEffect(h),a||t._bind(e,c,n.fillMode),this._useUbo?((0,Bt._8)(c,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(c.setMatrix("viewProjection",r.getTransformMatrix()),c.setMatrix("view",r.getViewMatrix()));const d=t._instanceDataStorage;if(d.isFrozen||!n.backFaceCulling&&null===n.sideOrientation)u=d.sideOrientation;else{const e=i._getWorldMatrixDeterminant();u=n._getEffectiveOrientation(t),e<0&&(u=u===Vt.ClockWiseSideOrientation?Vt.CounterClockWiseSideOrientation:Vt.ClockWiseSideOrientation)}if(n._preBind(h,u),n.needAlphaTesting()){const e=n.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if((n.bumpTexture||n.normalTexture)&&r.getEngine().getCaps().standardDerivatives&&Sn.BumpTextureEnabled){const e=n.bumpTexture||n.normalTexture;c.setFloat3("vBumpInfos",e.coordinatesIndex,1/e.level,n.parallaxScaleBias),c.setMatrix("bumpMatrix",e.getTextureMatrix()),c.setTexture("bumpSampler",e),c.setFloat2("vTangentSpaceParams",n.invertNormalMapX?-1:1,n.invertNormalMapY?-1:1)}if(this._enableReflectivity&&("PBRMetallicRoughnessMaterial"===n.getClassName()?(null!==n.metallicRoughnessTexture&&(c.setTexture("reflectivitySampler",n.metallicRoughnessTexture),c.setMatrix("reflectivityMatrix",n.metallicRoughnessTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.baseTexture&&(c.setTexture("albedoSampler",n.baseTexture),c.setMatrix("albedoMatrix",n.baseTexture.getTextureMatrix())),null!==n.baseColor&&c.setColor3("albedoColor",n.baseColor)):"PBRSpecularGlossinessMaterial"===n.getClassName()?(null!==n.specularGlossinessTexture?(c.setTexture("reflectivitySampler",n.specularGlossinessTexture),c.setMatrix("reflectivityMatrix",n.specularGlossinessTexture.getTextureMatrix())):null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor),null!==n.glossiness&&c.setFloat("glossiness",n.glossiness)):"PBRMaterial"===n.getClassName()?(null!==n.metallicTexture&&(c.setTexture("reflectivitySampler",n.metallicTexture),c.setMatrix("reflectivityMatrix",n.metallicTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.roughness||null!==n.metallic||null!==n.metallicTexture?(null!==n.albedoTexture&&(c.setTexture("albedoSampler",n.albedoTexture),c.setMatrix("albedoMatrix",n.albedoTexture.getTextureMatrix())),null!==n.albedoColor&&c.setColor3("albedoColor",n.albedoColor)):(null!==n.reflectivityTexture?(c.setTexture("reflectivitySampler",n.reflectivityTexture),c.setMatrix("reflectivityMatrix",n.reflectivityTexture.getTextureMatrix())):null!==n.reflectivityColor&&c.setColor3("reflectivityColor",n.reflectivityColor),null!==n.microSurface&&c.setFloat("glossiness",n.microSurface))):"StandardMaterial"===n.getClassName()&&(null!==n.specularTexture&&(c.setTexture("reflectivitySampler",n.specularTexture),c.setMatrix("reflectivityMatrix",n.specularTexture.getTextureMatrix())),null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor))),(0,Ln.gS)(c,n,this._scene),t.useBones&&t.computeBonesUsingShaders&&t.skeleton){const e=t.skeleton;if(e.isUsingTextureForMatrices&&c.getUniformIndex("boneTextureWidth")>-1){const i=e.getTransformMatrixTexture(t);c.setTexture("boneSampler",i),c.setFloat("boneTextureWidth",4*(e.bones.length+1))}else c.setMatrices("mBones",t.skeleton.getTransformMatrices(t));(this._enableVelocity||this._enableVelocityLinear)&&c.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[t.uniqueId])}(0,Bt.nR)(t,c),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(c),(this._enableVelocity||this._enableVelocityLinear)&&(c.setMatrix("previousWorld",this._previousTransformationMatrices[i.uniqueId].world),c.setMatrix("previousViewProjection",this._previousTransformationMatrices[i.uniqueId].viewProjection)),a&&t.hasThinInstances&&c.setMatrix("world",l),t._processRendering(i,e,c,n.fillMode,o,a,((e,t)=>{e||c.setMatrix("world",t)}))}(this._enableVelocity||this._enableVelocityLinear)&&(this._previousTransformationMatrices[i.uniqueId].world=l.clone(),this._previousTransformationMatrices[i.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),t.skeleton&&this._copyBonesTransformationMatrices(t.skeleton.getTransformMatrices(t),this._previousBonesTransformationMatrices[i.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(t,i,r)=>{if((r||0===i)&&t.subMeshes)for(let i=0;i{let n;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(s.length){for(e.setColorWrite(!1),n=0;n{throw(0,Je.n)("GeometryBufferRendererSceneComponent")};class YO{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(oi.Z.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(e){e&&e.isSupported&&(this._geometryBufferRenderer=e)},enumerable:!0,configurable:!0}),oi.Z.prototype.enableGeometryBufferRenderer=function(e=1,t=15,i){return this._geometryBufferRenderer||(this._geometryBufferRenderer=new qO(this,e,t,i),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null)),this._geometryBufferRenderer},oi.Z.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class KO{constructor(e){this.name=Ut.v.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(Ut.v.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}qO._SceneComponentInitialization=e=>{let t=e._getComponent(Ut.v.NAME_GEOMETRYBUFFERRENDERER);t||(t=new KO(e),e._addComponent(t))};class jO extends ms.w{get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this._motionBlurSamples=e,this._updateEffect()}get isObjectBased(){return this._isObjectBased}set isObjectBased(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"MotionBlurPostProcess"}constructor(e,t,i,r,s,n,o,a=0,l=!1,h=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,r,s,n,o,"#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED",a,void 0,null,l),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=h,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new YO)),this._applyMode()}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,95400))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,28377))])),super._gatherImports(e,t)}excludeSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}t.push(e)}}removeExcludedSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}const i=t.indexOf(e);-1!==i&&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 Z.V.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=W.uq.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 W.I9(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(qO.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.AA.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 W.I9(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(qO.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[t])}}_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("\n"))}}static _Parse(e,t,i,r){return it.p.Parse((()=>new jO(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,r)}}(0,je.Cg)([(0,$e.lK)()],jO.prototype,"motionStrength",void 0),(0,je.Cg)([(0,$e.lK)()],jO.prototype,"motionBlurSamples",null),(0,je.Cg)([(0,$e.lK)()],jO.prototype,"isObjectBased",null),(0,X.Y5)("BABYLON.MotionBlurPostProcess",jO);Cs.l.ShadersStore.refractionPixelShader="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);}";class $O extends ms.w{get refractionTexture(){return this._refTexture}set refractionTexture(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1}getClassName(){return"RefractionPostProcess"}constructor(e,t,i,r,s,n,o,a,l,h){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],n,o,a,l,h),this._ownRefractionTexture=!0,this.color=i,this.depth=r,this.colorLevel=s,this.refractionTextureUrl=t,this.onActivateObservable.add((e=>{this._refTexture=this._refTexture||new vi.g(t,e.getScene())})),this.onApplyObservable.add((e=>{e.setColor3("baseColor",this.color),e.setFloat("depth",this.depth),e.setFloat("colorLevel",this.colorLevel),e.setTexture("refractionSampler",this._refTexture)}))}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,r){return it.p.Parse((()=>new $O(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,r)}}(0,je.Cg)([(0,$e.lK)()],$O.prototype,"color",void 0),(0,je.Cg)([(0,$e.lK)()],$O.prototype,"depth",void 0),(0,je.Cg)([(0,$e.lK)()],$O.prototype,"colorLevel",void 0),(0,je.Cg)([(0,$e.lK)()],$O.prototype,"refractionTextureUrl",void 0),(0,X.Y5)("BABYLON.RefractionPostProcess",$O);var QO=i(3367);class ZO extends ms.w{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,r,s,n,o=0,a=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,r,s,n,null,o,void 0,null,a),this.colorAmount=1,this.edgeAmount=.3,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,68820))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,3367))])),super._gatherImports(e,t)}static _Parse(e,t,i,r){return it.p.Parse((()=>new ZO(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,r)}}(0,je.Cg)([(0,$e.lK)()],ZO.prototype,"colorAmount",void 0),(0,je.Cg)([(0,$e.lK)()],ZO.prototype,"edgeAmount",void 0),(0,X.Y5)("BABYLON.SharpenPostProcess",ZO);class JO{get name(){return this._name}get cameras(){return this._cameras}get engine(){return this._engine}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(Ue.S0.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(Ue.S0.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=Ue.S0.MakeArray(e||this._cameras);if(!i)return;const r=[];let s;for(s=0;s0){const i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}_adaptPostProcessesToViewPort(){const e=Object.keys(this._renderEffects);for(const t of e){const e=this._renderEffects[t].getPostProcesses();if(e)for(const t of e)t.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}}(0,je.Cg)([(0,$e.lK)()],JO.prototype,"_name",void 0);class eD{constructor(){this._renderPipelines={}}get supportedPipelines(){const e=[];for(const t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){const i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e}addPipeline(e){this._renderPipelines[e._name]=e}removePipeline(e){delete this._renderPipelines[e]}attachCamerasToRenderPipeline(e,t,i=!1){const r=this._renderPipelines[e];r&&r._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){const i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){const r=this._renderPipelines[e];r&&r._enableEffect(t,i)}disableEffectInPipeline(e,t,i){const r=this._renderPipelines[e];r&&r._disableEffect(t,i)}update(){for(const e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){const t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e]._rebuild()}dispose(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e].dispose()}}Object.defineProperty(oi.Z.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let e=this._getComponent(Ut.v.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new tD(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new eD}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class tD{constructor(e){this.name=Ut.v.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(Ut.v.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 iD extends JO{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 MO(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 BO(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 MO(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new OO("ChromaticAberration",o.getRenderWidth(),o.getRenderHeight(),1,null,vi.g.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new AO(o,this.ChromaticAberrationPostProcessId,(()=>this.chromaticAberration),!0),this.grain=new UO("Grain",1,null,vi.g.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new AO(o,this.GrainPostProcessId,(()=>this.grain),!0);let a=!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,a?Ue.S0.SetImmediate((()=>{this._buildPipeline()})):this._buildPipeline())})),this._buildPipeline(),a=!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(),null!==this._cameras&&(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 e of this._cameras)this._scene.enableDepthRenderer(e).useOnlyInActiveCamera=!0;this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add((e=>{this._cameras.indexOf(e.activeCamera)>-1&&(this.depthOfField.depthTexture=e.enableDepthRenderer(e.activeCamera).getDepthMap())}))}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);const e=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=e.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 zO("imageProcessing",1,null,vi.g.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new AO(e,this.ImageProcessingPostProcessId,(()=>this.imageProcessing),!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._cameras&&0!==this._cameras.length||(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 kR("fxaa",1,null,vi.g.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new AO(e,this.FxaaPostProcessId,(()=>this.fxaa),!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera))&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add((()=>{this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera)&&(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&&Z.V.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 iD(e._name,e._name._hdr,t)),e,t,i)}}(0,je.Cg)([(0,$e.lK)()],iD.prototype,"sharpenEnabled",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"bloomKernel",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"_bloomWeight",void 0),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"_bloomThreshold",void 0),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"_hdr",void 0),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"bloomWeight",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"bloomThreshold",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"bloomScale",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"bloomEnabled",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"depthOfFieldEnabled",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"depthOfFieldBlurLevel",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"fxaaEnabled",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"samples",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"imageProcessingEnabled",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"glowLayerEnabled",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"chromaticAberrationEnabled",null),(0,je.Cg)([(0,$e.lK)()],iD.prototype,"grainEnabled",null),(0,X.Y5)("BABYLON.DefaultRenderingPipeline",iD);var rD=i(76437);Cs.l.ShadersStore.lensHighlightsPixelShader="uniform sampler2D textureSampler; \nuniform 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; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;}\nfloat 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);\n#ifdef PENTAGON\nblurred+=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)));\n#else\nblurred+=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)));\n#endif\nblurred/=39.0;gl_FragColor=blurred;}";Cs.l.ShadersStore.depthOfFieldPixelShader="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; \nuniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV;\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \nvec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co)\n{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);}\nvec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; }\nvec2 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;}\nfloat 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;}\nfloat getBlurLevel(float size) {return min(3.0,ceil(size/1.0));}\nvec4 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);}\nif (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);}\ncol/=total_weight; \nif (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);}\nreturn col;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{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); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; }\nfloat 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;}\nfloat blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);}\nelse {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;}\nif (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;}}\nif (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;}}\n";class sD extends JO{constructor(e,t,i,r=1,s){super(i.getEngine(),e),this.LensChromaticAberrationEffect="LensChromaticAberrationEffect",this.HighlightsEnhancingEffect="HighlightsEnhancingEffect",this.LensDepthOfFieldEffect="LensDepthOfFieldEffect",this._pentagonBokehIsEnabled=!1,this._scene=i,this._depthTexture=i.enableDepthRenderer().getDepthMap(),t.grain_texture?this._grainTexture=t.grain_texture:this._createGrainTexture(),this._edgeBlur=t.edge_blur?t.edge_blur:0,this._grainAmount=t.grain_amount?t.grain_amount:0,this._chromaticAberration=t.chromatic_aberration?t.chromatic_aberration:0,this._distortion=t.distortion?t.distortion:0,this._highlightsGain=void 0!==t.dof_gain?t.dof_gain:-1,this._highlightsThreshold=t.dof_threshold?t.dof_threshold:1,this._dofDistance=void 0!==t.dof_focus_distance?t.dof_focus_distance:-1,this._dofAperture=t.dof_aperture?t.dof_aperture:1,this._dofDarken=t.dof_darken?t.dof_darken:0,this._dofPentagon=void 0===t.dof_pentagon||t.dof_pentagon,this._blurNoise=void 0===t.blur_noise||t.blur_noise,this._createChromaticAberrationPostProcess(r),this._createHighlightsPostProcess(r),this._createDepthOfFieldPostProcess(r/4),this.addEffect(new AO(i.getEngine(),this.LensChromaticAberrationEffect,(()=>this._chromaticAberrationPostProcess),!0)),this.addEffect(new AO(i.getEngine(),this.HighlightsEnhancingEffect,(()=>this._highlightsPostProcess),!0)),this.addEffect(new AO(i.getEngine(),this.LensDepthOfFieldEffect,(()=>this._depthOfFieldPostProcess),!0)),-1===this._highlightsGain&&this._disableEffect(this.HighlightsEnhancingEffect,null),i.postProcessRenderPipelineManager.addPipeline(this),s&&i.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}getClassName(){return"LensRenderingPipeline"}get scene(){return this._scene}get edgeBlur(){return this._edgeBlur}set edgeBlur(e){this.setEdgeBlur(e)}get grainAmount(){return this._grainAmount}set grainAmount(e){this.setGrainAmount(e)}get chromaticAberration(){return this._chromaticAberration}set chromaticAberration(e){this.setChromaticAberration(e)}get dofAperture(){return this._dofAperture}set dofAperture(e){this.setAperture(e)}get edgeDistortion(){return this._distortion}set edgeDistortion(e){this.setEdgeDistortion(e)}get dofDistortion(){return this._dofDistance}set dofDistortion(e){this.setFocusDistance(e)}get darkenOutOfFocus(){return this._dofDarken}set darkenOutOfFocus(e){this.setDarkenOutOfFocus(e)}get blurNoise(){return this._blurNoise}set blurNoise(e){this._blurNoise=e}get pentagonBokeh(){return this._pentagonBokehIsEnabled}set pentagonBokeh(e){e?this.enablePentagonBokeh():this.disablePentagonBokeh()}get highlightsGain(){return this._highlightsGain}set highlightsGain(e){this.setHighlightsGain(e)}get highlightsThreshold(){return this._highlightsThreshold}set highlightsThreshold(e){this.setHighlightsThreshold(e)}setEdgeBlur(e){this._edgeBlur=e}disableEdgeBlur(){this._edgeBlur=0}setGrainAmount(e){this._grainAmount=e}disableGrain(){this._grainAmount=0}setChromaticAberration(e){this._chromaticAberration=e}disableChromaticAberration(){this._chromaticAberration=0}setEdgeDistortion(e){this._distortion=e}disableEdgeDistortion(){this._distortion=0}setFocusDistance(e){this._dofDistance=e}disableDepthOfField(){this._dofDistance=-1}setAperture(e){this._dofAperture=e}setDarkenOutOfFocus(e){this._dofDarken=e}enablePentagonBokeh(){this._highlightsPostProcess.updateEffect("#define PENTAGON\n"),this._pentagonBokehIsEnabled=!0}disablePentagonBokeh(){this._pentagonBokehIsEnabled=!1,this._highlightsPostProcess.updateEffect()}enableNoiseBlur(){this._blurNoise=!0}disableNoiseBlur(){this._blurNoise=!1}setHighlightsGain(e){this._highlightsGain=e}setHighlightsThreshold(e){-1===this._highlightsGain&&(this._highlightsGain=1),this._highlightsThreshold=e}disableHighlights(){this._highlightsGain=-1}dispose(e=!1){this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),this._chromaticAberrationPostProcess=null,this._highlightsPostProcess=null,this._depthOfFieldPostProcess=null,this._grainTexture.dispose(),e&&this._scene.disableDepthRenderer()}_createChromaticAberrationPostProcess(e){this._chromaticAberrationPostProcess=new ms.w("LensChromaticAberration","chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],e,null,vi.g.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._chromaticAberrationPostProcess.onApply=e=>{e.setFloat("chromatic_aberration",this._chromaticAberration),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight()),e.setFloat("radialIntensity",1),e.setFloat2("direction",17,17),e.setFloat2("centerPosition",.5,.5)}}_createHighlightsPostProcess(e){this._highlightsPostProcess=new ms.w("LensHighlights","lensHighlights",["gain","threshold","screen_width","screen_height"],[],e,null,vi.g.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,this._dofPentagon?"#define PENTAGON\n":""),this._highlightsPostProcess.externalTextureSamplerBinding=!0,this._highlightsPostProcess.onApply=e=>{e.setFloat("gain",this._highlightsGain),e.setFloat("threshold",this._highlightsThreshold),e.setTextureFromPostProcess("textureSampler",this._chromaticAberrationPostProcess),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight())}}_createDepthOfFieldPostProcess(e){this._depthOfFieldPostProcess=new ms.w("LensDepthOfField","depthOfField",["grain_amount","blur_noise","screen_width","screen_height","distortion","dof_enabled","screen_distance","aperture","darken","edge_blur","highlights","near","far"],["depthSampler","grainSampler","highlightsSampler"],e,null,vi.g.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._depthOfFieldPostProcess.externalTextureSamplerBinding=!0,this._depthOfFieldPostProcess.onApply=e=>{e.setTexture("depthSampler",this._depthTexture),e.setTexture("grainSampler",this._grainTexture),e.setTextureFromPostProcess("textureSampler",this._highlightsPostProcess),e.setTextureFromPostProcess("highlightsSampler",this._depthOfFieldPostProcess),e.setFloat("grain_amount",this._grainAmount),e.setBool("blur_noise",this._blurNoise),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight()),e.setFloat("distortion",this._distortion),e.setBool("dof_enabled",-1!==this._dofDistance),e.setFloat("screen_distance",1/(.1-1/this._dofDistance)),e.setFloat("aperture",this._dofAperture),e.setFloat("darken",this._dofDarken),e.setFloat("edge_blur",this._edgeBlur),e.setBool("highlights",-1!==this._highlightsGain),this._scene.activeCamera&&(e.setFloat("near",this._scene.activeCamera.minZ),e.setFloat("far",this._scene.activeCamera.maxZ))}}_createGrainTexture(){const e=new Uint8Array(1048576);for(let t=0;tthis._originalColorPostProcess),!0)),this.addEffect(new AO(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new AO(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new AO(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new AO(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let e=0;e{e?t.push(Promise.resolve().then(i.bind(i,20661))):t.push(Promise.resolve().then(i.bind(i,33258)))}));return a.onApply=e=>{if(!this._scene.activeCamera)return;const t=o?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,i=o?this._originalColorPostProcess.width:this._originalColorPostProcess.height;e.setFloat("outSize",t>0?t:i),e.setInt("samples",this.bilateralSamples),e.setFloat("soften",this.bilateralSoften),e.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)])},a.samples=this.textureSamples,a.autoClear=!1,a}_radicalInverse_VdC(e){return this._bits[0]=e,this._bits[0]=(this._bits[0]<<16|this._bits[0]>>16)>>>0,this._bits[0]=(1431655765&this._bits[0])<<1|(2863311530&this._bits[0])>>>1>>>0,this._bits[0]=(858993459&this._bits[0])<<2|(3435973836&this._bits[0])>>>2>>>0,this._bits[0]=(252645135&this._bits[0])<<4|(4042322160&this._bits[0])>>>4>>>0,this._bits[0]=(16711935&this._bits[0])<<8|(4278255360&this._bits[0])>>>8>>>0,2.3283064365386963e-10*this._bits[0]}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){const i=2*t*Math.PI,r=1-.85*e,s=Math.sqrt(1-r*r);return new W.Pq(Math.cos(i)*s,Math.sin(i)*s,r)}_generateHemisphere(){const e=this.samples,t=[];let i,r=0;for(;r{e?t.push(Promise.resolve().then(i.bind(i,20661))):t.push(Promise.resolve().then(i.bind(i,33258)))})),this._ssaoPostProcess.autoClear=!1,this._ssaoPostProcess.onApply=e=>{if(this._scene.activeCamera){if(e.setArray3("sampleSphere",this._sampleSphere),e.setFloat("randTextureTiles",32),e.setFloat("samplesFactor",1/this.samples),e.setFloat("totalStrength",this.totalStrength),e.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),e.setFloat("radius",this.radius),e.setFloat("maxZ",this.maxZ),e.setFloat("minZAspect",this.minZAspect),e.setFloat("base",this.base),e.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===rt.PERSPECTIVE_CAMERA)e.setMatrix3x3("depthProjection",oD.PERSPECTIVE_DEPTH_PROJECTION),e.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),e.setFloat("yViewport",Math.tan(this._scene.activeCamera.fov/2));else{const t=this._scene.getEngine().getRenderWidth()/2,i=this._scene.getEngine().getRenderHeight()/2,r=this._scene.activeCamera.orthoLeft??-t,s=this._scene.activeCamera.orthoRight??t,n=this._scene.activeCamera.orthoBottom??-i,o=this._scene.activeCamera.orthoTop??i;e.setMatrix3x3("depthProjection",oD.ORTHO_DEPTH_PROJECTION),e.setFloat("xViewport",.5*(s-r)),e.setFloat("yViewport",.5*(o-n))}e.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),e.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),e.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),e.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new nD)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new ms.w("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t,void 0,void 0,void 0,void 0,this._scene.getEngine().isWebGPU?1:0,((e,t)=>{e?t.push(Promise.resolve().then(i.bind(i,93640))):t.push(Promise.resolve().then(i.bind(i,85387)))})),this._ssaoCombinePostProcess.onApply=e=>{const t=this._scene.activeCamera.viewport;e.setVector4("viewport",W.AA.Vector4[0].copyFromFloats(t.x,t.y,t.width,t.height)),e.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.autoClear=!1,this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){const e=new Uint8Array(65536),t=W.I9.Zero();for(let i=0;inew oD(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType)),e,t,i)}}oD.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1],oD.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1],(0,je.Cg)([(0,$e.lK)()],oD.prototype,"totalStrength",void 0),(0,je.Cg)([(0,$e.lK)()],oD.prototype,"maxZ",void 0),(0,je.Cg)([(0,$e.lK)()],oD.prototype,"minZAspect",void 0),(0,je.Cg)([(0,$e.lK)("epsilon")],oD.prototype,"_epsilon",void 0),(0,je.Cg)([(0,$e.lK)("samples")],oD.prototype,"_samples",void 0),(0,je.Cg)([(0,$e.lK)("textureSamples")],oD.prototype,"_textureSamples",void 0),(0,je.Cg)([(0,$e.lK)()],oD.prototype,"_forceGeometryBuffer",void 0),(0,je.Cg)([(0,$e.lK)()],oD.prototype,"_ratio",void 0),(0,je.Cg)([(0,$e.lK)()],oD.prototype,"_textureType",void 0),(0,je.Cg)([(0,$e.lK)()],oD.prototype,"radius",void 0),(0,je.Cg)([(0,$e.lK)()],oD.prototype,"base",void 0),(0,je.Cg)([(0,$e.lK)("bypassBlur")],oD.prototype,"_bypassBlur",void 0),(0,je.Cg)([(0,$e.lK)("expensiveBlur")],oD.prototype,"_expensiveBlur",void 0),(0,je.Cg)([(0,$e.lK)()],oD.prototype,"bilateralSamples",void 0),(0,je.Cg)([(0,$e.lK)()],oD.prototype,"bilateralSoften",void 0),(0,je.Cg)([(0,$e.lK)()],oD.prototype,"bilateralTolerance",void 0),(0,X.Y5)("BABYLON.SSAO2RenderingPipeline",oD);Cs.l.ShadersStore.ssaoPixelShader="uniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSAO\nuniform 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)\n{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);}\nvoid main()\n{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 AO(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new AO(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new AO(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new AO(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}_attachCameras(e,t){super._attachCameras(e,t);for(const e of this._cameras)this._scene.enableDepthRenderer(e).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let e=0;e{const e=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*e})),this._blurVPostProcess.onActivateObservable.add((()=>{const e=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*e}))}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){const t=[.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];this._ssaoPostProcess=new ms.w("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define SAMPLES 16\n#define SSAO"),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=e=>{this._firstUpdate&&(e.setArray3("sampleSphere",t),e.setFloat("samplesFactor",.0625),e.setFloat("randTextureTiles",4)),e.setFloat("totalStrength",this.totalStrength),e.setFloat("radius",this.radius),e.setFloat("area",this.area),e.setFloat("fallOff",this.fallOff),e.setFloat("base",this.base),e.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),e.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new ms.w("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,vi.g.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=e=>{e.setVector4("viewport",W.AA.Vector4[0].copyFromFloats(0,0,1,1)),e.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){const e=new Uint8Array(1048576);for(let t=0;t0.0)\nhitCoord-=dir;else\nhitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;}\nprojectedCoord=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;}\n/**\n* Tests the given world position (hitCoord) according to the given reflection vector (dir)\n* until it finds a collision (means that depth is enough close to say \"it's the pixel to sample!\").\n*/\nReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord)\n{ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i{const i=this._geometryBufferRenderer,r=this._prePassRenderer;if(!r&&!i)return;if(i){const t=i.getTextureIndex(qO.POSITION_TEXTURE_TYPE),r=i.getTextureIndex(qO.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("positionSampler",i.getGBuffer().textures[t]),e.setTexture("reflectivitySampler",i.getGBuffer().textures[r])}else if(r){const t=r.getIndex(1),i=r.getIndex(3),s=r.getIndex(6);e.setTexture("normalSampler",r.getRenderTarget().textures[s]),e.setTexture("positionSampler",r.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",r.getRenderTarget().textures[i])}const s=t.activeCamera;if(!s)return;const n=s.getViewMatrix(!0),o=s.getProjectionMatrix(!0);e.setMatrix("projection",o),e.setMatrix("view",n),e.setFloat("threshold",this.threshold),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.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 "+(0|this._reflectionSamples)),e.push("#define SMOOTH_STEPS "+(0|this._smoothSteps)),this.updateEffect(e.join("\n"))}static _Parse(e,t,i,r){return it.p.Parse((()=>new cD(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,r)}}(0,je.Cg)([(0,$e.lK)()],cD.prototype,"threshold",void 0),(0,je.Cg)([(0,$e.lK)()],cD.prototype,"strength",void 0),(0,je.Cg)([(0,$e.lK)()],cD.prototype,"reflectionSpecularFalloffExponent",void 0),(0,je.Cg)([(0,$e.lK)()],cD.prototype,"step",void 0),(0,je.Cg)([(0,$e.lK)()],cD.prototype,"roughnessFactor",void 0),(0,je.Cg)([(0,$e.lK)()],cD.prototype,"enableSmoothReflections",null),(0,je.Cg)([(0,$e.lK)()],cD.prototype,"reflectionSamples",null),(0,je.Cg)([(0,$e.lK)()],cD.prototype,"smoothSteps",null),(0,X.Y5)("BABYLON.ScreenSpaceReflectionPostProcess",cD);Cs.l.ShadersStore.standardPixelShader="uniform sampler2D textureSampler;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];void main(void)\n{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;}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void)\n{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)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;}\naccumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;void main(void)\n{gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];void main()\n{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++)\n{color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));}\naverage=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];uniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\n#include\n#endif\nvoid main()\n{vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++)\n{color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;uniform float averageLuminance;void main()\n{vec4 color=texture2D(textureAdderSampler,vUV);\n#ifndef AUTO_EXPOSURE\nvec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0;\n#endif\ngl_FragColor=color;}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p)\n{float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);}\nfloat noise(in vec2 p)\n{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)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);}\nfloat fbm(vec2 p)\n{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;}\nvec3 pattern(vec2 uv)\n{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);}\nfloat luminance(vec3 color)\n{return dot(color.rgb,vec3(0.2126,0.7152,0.0722));}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{return vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);}\nvoid main(void)\n{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)\nbreak;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);}\ngl_FragColor=result/float(nSamples);}\n#endif\n";class uD extends JO{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("\n"))}}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())return void Z.V.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");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\n#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\n#define MAX_MOTION_SAMPLES "+e.toFixed(1))),this._motionBlurSamples=e}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}constructor(e,t,i,r=null,s){super(t.getEngine(),e),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.blurHPostProcesses=[],this.blurVPostProcesses=[],this.textureAdderPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.luminancePostProcess=null,this.luminanceDownSamplePostProcesses=[],this.hdrPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlareFinalPostProcess=null,this.hdrFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.motionBlurPostProcess=null,this.depthOfFieldPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.brightThreshold=1,this.blurWidth=512,this.horizontalBlur=!1,this.lensTexture=null,this.volumetricLightCoefficient=.2,this.volumetricLightPower=4,this.volumetricLightBlurScale=64,this.sourceLight=null,this.hdrMinimumLuminance=1,this.hdrDecreaseRate=.5,this.hdrIncreaseRate=.5,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensFlareBlurWidth=512,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.depthOfFieldBlurWidth=64,this.animations=[],this._currentDepthOfFieldSource=null,this._fixedExposure=1,this._currentExposure=1,this._hdrAutoExposure=!1,this._hdrCurrentLuminance=1,this._motionStrength=1,this._isObjectBasedMotionBlur=!1,this._camerasToBeAttached=[],this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._vlsEnabled=!1,this._lensFlareEnabled=!1,this._hdrEnabled=!1,this._motionBlurEnabled=!1,this._fxaaEnabled=!1,this._screenSpaceReflectionsEnabled=!1,this._motionBlurSamples=64,this._volumetricLightStepsCount=50,this._samples=1,this._cameras=s||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=r,this._ratio=i,this._floatTextureType=t.getEngine().getCaps().textureFloatRender?1:2,t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline()}_buildPipeline(){const e=this._ratio,t=this._scene;this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new cD("HDRPass",t,e,null,vi.g.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add((()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess})),this.addEffect(new AO(t.getEngine(),"HDRScreenSpaceReflections",(()=>this.screenSpaceReflectionPostProcess),!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new ms.w("HDRPass","standard",[],[],e,null,vi.g.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 AO(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 ms.w("HDRDepthOfFieldSource","standard",[],[],e,null,vi.g.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new AO(t.getEngine(),"HDRBaseDepthOfFieldSource",(()=>this.textureAdderFinalPostProcess),!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new ms.w("HDRVLSFinal","standard",[],[],e,null,vi.g.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new AO(t.getEngine(),"HDRVLSFinal",(()=>this.volumetricLightFinalPostProcess),!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new ms.w("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,vi.g.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new AO(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",(()=>this.lensFlareFinalPostProcess),!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new ms.w("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,vi.g.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new AO(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 kR("fxaa",1,null,vi.g.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new AO(t.getEngine(),"HDRFxaa",(()=>this.fxaaPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&Z.V.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 ms.w("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=e=>{let t=0;const r=this.downSampleX4PostProcess.width,s=this.downSampleX4PostProcess.height;for(let e=-2;e<2;e++)for(let n=-2;n<2;n++)i[t]=(e+.5)*(1/r),i[t+1]=(n+.5)*(1/s),t+=2;e.setArray2("dsOffsets",i)},this.addEffect(new AO(e.getEngine(),"HDRDownSampleX4",(()=>this.downSampleX4PostProcess),!0))}_createBrightPassPostProcess(e,t){const i=new Array(8);this.brightPassPostProcess=new ms.w("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=e=>{const t=1/this.brightPassPostProcess.width,r=1/this.brightPassPostProcess.height;i[0]=-.5*t,i[1]=.5*r,i[2]=.5*t,i[3]=.5*r,i[4]=-.5*t,i[5]=-.5*r,i[6]=.5*t,i[7]=-.5*r,e.setArray2("dsOffsets",i),e.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new AO(e.getEngine(),"HDRBrightPass",(()=>this.brightPassPostProcess),!0))}_createBlurPostProcesses(e,t,i,r="blurWidth"){const s=e.getEngine(),n=new _m("HDRBlurH_"+i,new W.I9(1,0),this[r],t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),o=new _m("HDRBlurV_"+i,new W.I9(0,1),this[r],t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);n.onActivateObservable.add((()=>{const e=n.width/s.getRenderWidth();n.kernel=this[r]*e})),o.onActivateObservable.add((()=>{const e=o.height/s.getRenderHeight();o.kernel=this.horizontalBlur?64*e:this[r]*e})),this.addEffect(new AO(e.getEngine(),"HDRBlurH"+i,(()=>n),!0)),this.addEffect(new AO(e.getEngine(),"HDRBlurV"+i,(()=>o),!0)),this.blurHPostProcesses.push(n),this.blurVPostProcesses.push(o)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new ms.w("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._vlsEnabled?this._currentDepthOfFieldSource:this.originalPostProcess),e.setTexture("lensSampler",this.lensTexture),e.setFloat("exposure",this._currentExposure),this._currentDepthOfFieldSource=this.textureAdderFinalPostProcess},this.addEffect(new AO(e.getEngine(),"HDRTextureAdder",(()=>this.textureAdderPostProcess),!0))}_createVolumetricLightPostProcess(e,t){const i=e.enableGeometryBufferRenderer();i.enablePosition=!0;const r=i.getGBuffer();this.volumetricLightPostProcess=new ms.w("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));const s=W.I9.Zero();this.volumetricLightPostProcess.onApply=e=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){const t=this.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",r.textures[2]),e.setColor3("sunColor",this.sourceLight.diffuse),e.setVector3("sunDirection",this.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),e.setFloat("scatteringPower",this.volumetricLightPower),s.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),s.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),e.setVector2("depthValues",s)}},this.addEffect(new AO(e.getEngine(),"HDRVLS",(()=>this.volumetricLightPostProcess),!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new ms.w("HDRVLSMerge","standard",[],["originalSampler"],t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=e=>{e.setTextureFromPostProcess("originalSampler",this._bloomEnabled?this.textureAdderFinalPostProcess:this.originalPostProcess),this._currentDepthOfFieldSource=this.volumetricLightFinalPostProcess},this.addEffect(new AO(e.getEngine(),"HDRVLSMerge",(()=>this.volumetricLightMergePostProces),!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,uD.LuminanceSteps);this.luminancePostProcess=new ms.w("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);const r=[];this.luminancePostProcess.onApply=e=>{const t=1/this.luminancePostProcess.width,i=1/this.luminancePostProcess.height;r[0]=-.5*t,r[1]=.5*i,r[2]=.5*t,r[3]=.5*i,r[4]=-.5*t,r[5]=-.5*i,r[6]=.5*t,r[7]=-.5*i,e.setArray2("lumOffsets",r)},this.addEffect(new AO(e.getEngine(),"HDRLuminance",(()=>this.luminancePostProcess),!0));for(let r=uD.LuminanceSteps-1;r>=0;r--){i=Math.pow(3,r);let s="#define LUMINANCE_DOWN_SAMPLE\n";0===r&&(s+="#define FINAL_DOWN_SAMPLER");const n=new ms.w("HDRLuminanceDownSample"+r,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,t);this.luminanceDownSamplePostProcesses.push(n)}let s=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach(((t,i)=>{const r=new Array(18);t.onApply=e=>{if(!s)return;let n=0;for(let e=-1;e<2;e++)for(let t=-1;t<2;t++)r[n]=e/s.width,r[n+1]=t/s.height,n+=2;e.setArray2("dsOffsets",r),e.setFloat("halfDestPixelSize",.5/s.width),s=i===this.luminanceDownSamplePostProcesses.length-1?this.luminancePostProcess:t},i===this.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=()=>{const t=e.getEngine().readPixels(0,0,1,1),i=new W.IU(1/16581375,1/65025,1/255,1);t.then((e=>{const t=new Uint8Array(e.buffer);this._hdrCurrentLuminance=(t[0]*i.x+t[1]*i.y+t[2]*i.z+t[3]*i.w)/100}))}),this.addEffect(new AO(e.getEngine(),"HDRLuminanceDownSample"+i,(()=>t),!0))}))}_createHdrPostProcess(e,t){const i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new ms.w("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join("\n"),0);let r=1,s=0,n=0;this.hdrPostProcess.onApply=t=>{if(t.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),s+=e.getEngine().getDeltaTime(),r<0)r=this._hdrCurrentLuminance;else{const e=(n-s)/1e3;this._hdrCurrentLuminancer-this.hdrIncreaseRate*e?r-=this.hdrIncreaseRate*e:r=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/r:(r=(0,ar.Clamp)(r,this.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",r)),n=s,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new AO(e.getEngine(),"HDR",(()=>this.hdrPostProcess),!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new ms.w("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new AO(e.getEngine(),"HDRLensFlare",(()=>this.lensFlarePostProcess),!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new ms.w("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new AO(e.getEngine(),"HDRLensFlareCompose",(()=>this.lensFlareComposePostProcess),!0));const i=new W.I9(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=e=>{e.setTextureFromPostProcess("textureSampler",this._bloomEnabled?this.blurHPostProcesses[0]:this.originalPostProcess),e.setTexture("lensColorSampler",this.lensColorTexture),e.setFloat("strength",this.lensFlareStrength),e.setFloat("ghostDispersal",this.lensFlareGhostDispersal),e.setFloat("haloWidth",this.lensFlareHaloWidth),i.x=this.lensFlarePostProcess.width,i.y=this.lensFlarePostProcess.height,e.setVector2("resolution",i),e.setFloat("distortionStrength",this.lensFlareDistortionStrength)};const r=W.uq.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=W.uq.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=e=>{if(!this._scene.activeCamera)return;e.setTextureFromPostProcess("otherSampler",this.lensFlarePostProcess),e.setTexture("lensDirtSampler",this.lensFlareDirtTexture),e.setTexture("lensStarSampler",this.lensStarTexture);const t=this._scene.activeCamera.getViewMatrix().getRow(0),i=this._scene.activeCamera.getViewMatrix().getRow(2);let n=W.Pq.Dot(t.toVector3(),new W.Pq(1,0,0))+W.Pq.Dot(i.toVector3(),new W.Pq(0,0,1));n*=4;const o=W.uq.FromValues(.5*Math.cos(n),-Math.sin(n),0,0,Math.sin(n),.5*Math.cos(n),0,0,0,0,1,0,0,0,0,1),a=s.multiply(o).multiply(r);e.setMatrix("lensStarMatrix",a),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new ms.w("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",0),this.depthOfFieldPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._currentDepthOfFieldSource),e.setTexture("depthSampler",this._getDepthTexture()),e.setFloat("distance",this.depthOfFieldDistance)},this.addEffect(new AO(e.getEngine(),"HDRDepthOfField",(()=>this.depthOfFieldPostProcess),!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){const i=new jO("HDRMotionBlur",e,t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new ms.w("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,vi.g.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),0);let i=0,r=W.uq.Identity();const s=W.uq.Identity();let n=W.uq.Identity();const o=W.I9.Zero();this.motionBlurPostProcess.onApply=t=>{n=e.getProjectionMatrix().multiply(e.getViewMatrix()),n.invertToRef(s),t.setMatrix("inverseViewProjection",s),t.setMatrix("prevViewProjection",r),r=n,o.x=this.motionBlurPostProcess.width,o.y=this.motionBlurPostProcess.height,t.setVector2("screenSize",o),i=e.getEngine().getFps()/60,t.setFloat("motionScale",i),t.setFloat("motionStrength",this.motionStrength),t.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new AO(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 uD(e._name,t,e._ratio)),e,t,i);return e.sourceLightId&&(r.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&it.p.Parse((()=>r.screenSpaceReflectionPostProcess),e.screenSpaceReflectionPostProcess,t,i),r}}uD.LuminanceSteps=6,(0,je.Cg)([(0,$e.lK)()],uD.prototype,"brightThreshold",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"blurWidth",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"horizontalBlur",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"exposure",null),(0,je.Cg)([(0,$e.uM)("lensTexture")],uD.prototype,"lensTexture",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"volumetricLightCoefficient",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"volumetricLightPower",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"volumetricLightBlurScale",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"hdrMinimumLuminance",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"hdrDecreaseRate",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"hdrIncreaseRate",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"hdrAutoExposure",null),(0,je.Cg)([(0,$e.uM)("lensColorTexture")],uD.prototype,"lensColorTexture",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"lensFlareStrength",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"lensFlareGhostDispersal",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"lensFlareHaloWidth",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"lensFlareDistortionStrength",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"lensFlareBlurWidth",void 0),(0,je.Cg)([(0,$e.uM)("lensStarTexture")],uD.prototype,"lensStarTexture",void 0),(0,je.Cg)([(0,$e.uM)("lensFlareDirtTexture")],uD.prototype,"lensFlareDirtTexture",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"depthOfFieldDistance",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"depthOfFieldBlurWidth",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"motionStrength",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"objectBasedMotionBlur",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"_ratio",void 0),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"BloomEnabled",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"DepthOfFieldEnabled",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"LensFlareEnabled",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"HDREnabled",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"VLSEnabled",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"MotionBlurEnabled",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"fxaaEnabled",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"screenSpaceReflectionsEnabled",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"volumetricLightStepsCount",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"motionBlurSamples",null),(0,je.Cg)([(0,$e.lK)()],uD.prototype,"samples",null),(0,X.Y5)("BABYLON.StandardRenderingPipeline",uD);class dD{constructor(e=!1){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3],this.texturesRequired.push(e?10:5)}}const fD=W.uq.Compose(new W.Pq(.5,.5,.5),W.PT.Identity(),new W.Pq(.5,.5,.5)),pD=W.uq.Compose(new W.Pq(.5,.5,1),W.PT.Identity(),new W.Pq(.5,.5,0));class _D extends JO{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&&(0===e&&0!==this._reflectivityThreshold||0!==e&&0===this._reflectivityThreshold?(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=0===e&&0!==this._blurDispersionStrength||0!==e&&0===this._blurDispersionStrength;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():null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get inputTextureColorIsInGammaSpace(){return this._inputTextureColorIsInGammaSpace}set inputTextureColorIsInGammaSpace(e){this._inputTextureColorIsInGammaSpace!==e&&(this._inputTextureColorIsInGammaSpace=e,this._buildPipeline())}get generateOutputInGammaSpace(){return this._generateOutputInGammaSpace}set generateOutputInGammaSpace(e){this._generateOutputInGammaSpace!==e&&(this._generateOutputInGammaSpace=e,this._buildPipeline())}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._buildPipeline())}getScene(){return this._scene}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}get scene(){return this._scene}get isSupported(){const e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch}constructor(e,t,i,r=!1,s=0,n=!1){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._useScreenspaceDepth=!1,this._environmentTextureIsProbe=!1,this._attenuateScreenBorders=!0,this._attenuateIntersectionDistance=!0,this._attenuateIntersectionIterations=!0,this._attenuateFacingCamera=!1,this._attenuateBackfaceReflection=!1,this._clipToFrustum=!0,this._useFresnel=!1,this._enableAutomaticThicknessComputation=!1,this._backfaceDepthTextureDownsample=0,this._backfaceForceDepthWriteTransparentMeshes=!0,this._isEnabled=!0,this._inputTextureColorIsInGammaSpace=!0,this._generateOutputInGammaSpace=!0,this._debug=!1,this._forceGeometryBuffer=!1,this._isDirty=!1,this._camerasToBeAttached=[],this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=s,this._forceGeometryBuffer=r,this._useScreenspaceDepth=n,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){const e=t.enableGeometryBufferRenderer();e&&(e.enableReflectivity=!0,e.useSpecificClearForDepthTexture=!0,e.enableScreenspaceDepth=this._useScreenspaceDepth,e.enableDepth=!this._useScreenspaceDepth)}else{const e=t.enablePrePassRenderer();e&&(e.useSpecificClearForDepthTexture=!0,e.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(){const e=this._scene.getEngine(),t=this._prePassRenderer;let i={width:e.getRenderWidth(),height:e.getRenderHeight()};if(t&&this._scene.activeCamera?._getFirstPostProcess()===this._ssrPostProcess){const e=t.getRenderTarget();e&&e.textures&&(i=e.textures[t.getIndex(4)].getSize())}else this._ssrPostProcess?.inputTexture&&(i.width=this._ssrPostProcess.inputTexture.width,i.height=this._ssrPostProcess.inputTexture.height);return i}_updateEffectDefines(){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._useScreenspaceDepth&&e.push("#define SSRAYTRACE_SCREENSPACE_DEPTH"),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"),0===this._reflectivityThreshold&&e.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),(this._geometryBufferRenderer?.generateNormalsInWorldSpace??this._prePassRenderer?.generateNormalsInWorldSpace)&&e.push("#define SSR_NORMAL_IS_IN_WORLDSPACE"),this._geometryBufferRenderer?.normalsAreUnsigned&&e.push("#define SSR_DECODE_NORMAL");const t=this._cameras?.[0];t&&1===t.mode&&e.push("#define ORTHOGRAPHIC_CAMERA"),this._ssrPostProcess?.updateEffect(e.join("\n"))}_buildPipeline(){if(!this.isSupported)return;if(!this._isEnabled)return void(this._isDirty=!0);this._isDirty=!1;const e=this._scene.getEngine();if(this._disposeDepthRenderer(),this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._enableAutomaticThicknessComputation){const e=this._cameras?.[0];e&&(this._depthRendererCamera=e,this._depthRenderer=new px(this._scene,void 0,void 0,this._useScreenspaceDepth,1,!this._useScreenspaceDepth,"SSRBackDepth"),this._useScreenspaceDepth||(this._depthRenderer.clearColor.r=1e8),this._depthRenderer.reverseCulling=!0,this._depthRenderer.forceDepthWriteTransparentMeshes=this._backfaceForceDepthWriteTransparentMeshes,this._resizeDepthRenderer(),e.customRenderTargets.push(this._depthRenderer.getDepthMap()))}this._createSSRPostProcess(),this.addEffect(new AO(e,this.SSRRenderEffect,(()=>this._ssrPostProcess),!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new AO(e,this.SSRBlurRenderEffect,(()=>[this._blurPostProcessX,this._blurPostProcessY]),!0)),this.addEffect(new AO(e,this.SSRCombineRenderEffect,(()=>this._blurCombinerPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_resizeDepthRenderer(){if(!this._depthRenderer)return;const e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),r=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));t.width===i&&t.height===r||this._depthRenderer.getDepthMap().resize({width:i,height:r})}_disposeDepthRenderer(){if(this._depthRenderer){if(this._depthRendererCamera){const e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap())??-1;-1!==e&&this._depthRendererCamera.customRenderTargets.splice(e,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){for(let e=0;e{e?t.push(Promise.resolve().then(i.bind(i,98e3))):t.push(Promise.resolve().then(i.bind(i,87193)))})),this._updateEffectDefines(),this._ssrPostProcess.onApply=e=>{this._resizeDepthRenderer();const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){const i=t.getTextureIndex(qO.REFLECTIVITY_TEXTURE_TYPE),r=t.getTextureIndex(qO.NORMAL_TEXTURE_TYPE);if(e.setTexture("normalSampler",t.getGBuffer().textures[r]),e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),this._useScreenspaceDepth){const i=t.getTextureIndex(qO.SCREENSPACE_DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",t.getGBuffer().textures[i])}else{const i=t.getTextureIndex(qO.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",t.getGBuffer().textures[i])}}else if(i){const t=i.getIndex(this._useScreenspaceDepth?10:5),r=i.getIndex(3),s=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[s]),e.setTexture("depthSampler",i.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[r])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));const r=this._scene.activeCamera;if(!r)return;const s=r.getViewMatrix(),n=r.getProjectionMatrix();n.invertToRef(W.AA.Matrix[0]),s.invertToRef(W.AA.Matrix[1]),e.setMatrix("projection",n),e.setMatrix("view",s),e.setMatrix("invView",W.AA.Matrix[1]),e.setMatrix("invProjectionMatrix",W.AA.Matrix[0]),e.setFloat("thickness",this.thickness),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("maxSteps",this.maxSteps),e.setFloat("roughnessFactor",this.roughnessFactor),e.setFloat("nearPlaneZ",r.minZ),e.setFloat("farPlaneZ",r.maxZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);const o=this._getTextureSize();W.uq.ScalingToRef(o.width,o.height,1,W.AA.Matrix[2]),n.multiplyToRef(this._scene.getEngine().isWebGPU?pD:fD,W.AA.Matrix[3]),W.AA.Matrix[3].multiplyToRef(W.AA.Matrix[2],W.AA.Matrix[4]),e.setMatrix("projectionPixel",W.AA.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 dD(this._useScreenspaceDepth))}_createBlurAndCombinerPostProcesses(){const e=this._scene.getEngine();this._blurPostProcessX=new ms.w("SSRblurX","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._ssrDownsample+1):1,null,2,e,!1,"",this._textureType,void 0,void 0,void 0,void 0,this._scene.getEngine().isWebGPU?1:0,((e,t)=>{e?t.push(Promise.resolve().then(i.bind(i,86763))):t.push(Promise.resolve().then(i.bind(i,83514)))})),this._blurPostProcessX.autoClear=!1,this._blurPostProcessX.onApplyObservable.add((e=>{const t=this._blurPostProcessX?.inputTexture.width??this._scene.getEngine().getRenderWidth();e.setFloat2("texelOffsetScale",this._blurDispersionStrength/t,0)})),this._blurPostProcessY=new ms.w("SSRblurY","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._blurDownsample+1):1,null,2,e,!1,"",this._textureType,void 0,void 0,void 0,void 0,this._scene.getEngine().isWebGPU?1:0,((e,t)=>{e?t.push(Promise.resolve().then(i.bind(i,86763))):t.push(Promise.resolve().then(i.bind(i,83514)))})),this._blurPostProcessY.autoClear=!1,this._blurPostProcessY.onApplyObservable.add((e=>{const t=this._blurPostProcessY?.inputTexture.height??this._scene.getEngine().getRenderHeight();e.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/t)}));const t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],r=["textureSampler","mainSampler","reflectivitySampler"];let s="";this._debug&&(s+="#define SSRAYTRACE_DEBUG\n"),this._inputTextureColorIsInGammaSpace&&(s+="#define SSR_INPUT_IS_GAMMA_SPACE\n"),this._generateOutputInGammaSpace&&(s+="#define SSR_OUTPUT_IS_GAMMA_SPACE\n"),this.useFresnel&&(s+="#define SSR_BLEND_WITH_FRESNEL\n",t.push("projection","invProjectionMatrix","nearPlaneZ","farPlaneZ"),r.push("depthSampler","normalSampler")),this._useScreenspaceDepth&&(s+="#define SSRAYTRACE_SCREENSPACE_DEPTH"),0===this._reflectivityThreshold&&(s+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new ms.w("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,r,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,s,this._textureType,void 0,void 0,void 0,void 0,this._scene.getEngine().isWebGPU?1:0,((e,t)=>{e?t.push(Promise.resolve().then(i.bind(i,20136))):t.push(Promise.resolve().then(i.bind(i,36253)))})),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add((e=>{const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(i||t){if(i&&this._scene.activeCamera?._getFirstPostProcess()===this._ssrPostProcess){const t=i.getRenderTarget();t&&t.textures&&e.setTexture("mainSampler",t.textures[i.getIndex(4)])}else e.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(t){const i=t.getTextureIndex(qO.REFLECTIVITY_TEXTURE_TYPE);if(e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),this.useFresnel){const i=this._scene.activeCamera;if(i&&this._useScreenspaceDepth&&(e.setFloat("nearPlaneZ",i.minZ),e.setFloat("farPlaneZ",i.maxZ)),e.setTexture("normalSampler",t.getGBuffer().textures[1]),this._useScreenspaceDepth){const i=t.getTextureIndex(qO.SCREENSPACE_DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",t.getGBuffer().textures[i])}else e.setTexture("depthSampler",t.getGBuffer().textures[0])}}else if(i){const t=i.getIndex(3);if(e.setTexture("reflectivitySampler",i.getRenderTarget().textures[t]),this.useFresnel){const t=this._scene.activeCamera;t&&this._useScreenspaceDepth&&(e.setFloat("nearPlaneZ",t.minZ),e.setFloat("farPlaneZ",t.maxZ));const r=i.getIndex(this._useScreenspaceDepth?10:5),s=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[s]),e.setTexture("depthSampler",i.getRenderTarget().textures[r])}}if(e.setFloat("strength",this.strength),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){const t=this._scene.activeCamera;if(t){const i=t.getProjectionMatrix();i.invertToRef(W.AA.Matrix[0]),e.setMatrix("projection",i),e.setMatrix("invProjectionMatrix",W.AA.Matrix[0])}}}}))}serialize(){const e=it.p.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return it.p.Parse((()=>new _D(e._name,t,e._ratio)),e,t,i)}}(0,je.Cg)([(0,$e.lK)()],_D.prototype,"samples",null),(0,je.Cg)([(0,$e.lK)()],_D.prototype,"maxDistance",void 0),(0,je.Cg)([(0,$e.lK)()],_D.prototype,"step",void 0),(0,je.Cg)([(0,$e.lK)()],_D.prototype,"thickness",void 0),(0,je.Cg)([(0,$e.lK)()],_D.prototype,"strength",void 0),(0,je.Cg)([(0,$e.lK)()],_D.prototype,"reflectionSpecularFalloffExponent",void 0),(0,je.Cg)([(0,$e.lK)()],_D.prototype,"maxSteps",void 0),(0,je.Cg)([(0,$e.lK)()],_D.prototype,"roughnessFactor",void 0),(0,je.Cg)([(0,$e.lK)()],_D.prototype,"selfCollisionNumSkip",void 0),(0,je.Cg)([(0,$e.lK)()],_D.prototype,"_reflectivityThreshold",void 0),(0,je.Cg)([(0,$e.lK)("_ssrDownsample")],_D.prototype,"_ssrDownsample",void 0),(0,je.Cg)([(0,$e.lK)()],_D.prototype,"ssrDownsample",null),(0,je.Cg)([(0,$e.lK)("blurDispersionStrength")],_D.prototype,"_blurDispersionStrength",void 0),(0,je.Cg)([(0,$e.lK)("blurDownsample")],_D.prototype,"_blurDownsample",void 0),(0,je.Cg)([(0,$e.lK)("enableSmoothReflections")],_D.prototype,"_enableSmoothReflections",void 0),(0,je.Cg)([(0,$e.lK)("environmentTexture")],_D.prototype,"_environmentTexture",void 0),(0,je.Cg)([(0,$e.lK)("environmentTextureIsProbe")],_D.prototype,"_environmentTextureIsProbe",void 0),(0,je.Cg)([(0,$e.lK)("attenuateScreenBorders")],_D.prototype,"_attenuateScreenBorders",void 0),(0,je.Cg)([(0,$e.lK)("attenuateIntersectionDistance")],_D.prototype,"_attenuateIntersectionDistance",void 0),(0,je.Cg)([(0,$e.lK)("attenuateIntersectionIterations")],_D.prototype,"_attenuateIntersectionIterations",void 0),(0,je.Cg)([(0,$e.lK)("attenuateFacingCamera")],_D.prototype,"_attenuateFacingCamera",void 0),(0,je.Cg)([(0,$e.lK)("attenuateBackfaceReflection")],_D.prototype,"_attenuateBackfaceReflection",void 0),(0,je.Cg)([(0,$e.lK)("clipToFrustum")],_D.prototype,"_clipToFrustum",void 0),(0,je.Cg)([(0,$e.lK)("useFresnel")],_D.prototype,"_useFresnel",void 0),(0,je.Cg)([(0,$e.lK)("enableAutomaticThicknessComputation")],_D.prototype,"_enableAutomaticThicknessComputation",void 0),(0,je.Cg)([(0,$e.lK)("backfaceDepthTextureDownsample")],_D.prototype,"_backfaceDepthTextureDownsample",void 0),(0,je.Cg)([(0,$e.lK)("backfaceForceDepthWriteTransparentMeshes")],_D.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0),(0,je.Cg)([(0,$e.lK)("isEnabled")],_D.prototype,"_isEnabled",void 0),(0,je.Cg)([(0,$e.lK)("inputTextureColorIsInGammaSpace")],_D.prototype,"_inputTextureColorIsInGammaSpace",void 0),(0,je.Cg)([(0,$e.lK)("generateOutputInGammaSpace")],_D.prototype,"_generateOutputInGammaSpace",void 0),(0,je.Cg)([(0,$e.lK)("debug")],_D.prototype,"_debug",void 0),(0,X.Y5)("BABYLON.SSRRenderingPipeline",_D);class mD extends JO{set samples(e){this._taaThinPostProcess.samples=e}get samples(){return this._taaThinPostProcess.samples}set msaaSamples(e){this._msaaSamples!==e&&(this._msaaSamples=e,this._taaPostProcess&&(this._taaPostProcess.samples=e))}get msaaSamples(){return this._msaaSamples}get factor(){return this._taaThinPostProcess.factor}set factor(e){this._taaThinPostProcess.factor=e}get disableOnCameraMove(){return this._taaThinPostProcess.disableOnCameraMove}set disableOnCameraMove(e){this._taaThinPostProcess.disableOnCameraMove=e}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&(this._taaThinPostProcess._reset(),this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras))):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get scene(){return this._scene}get isSupported(){return this._scene.getEngine().getCaps().texelFetch}constructor(e,t,i,r=0){const s=t.getEngine();super(s,e),this.TAARenderEffect="TAARenderEffect",this.TAAPassEffect="TAAPassEffect",this._msaaSamples=1,this._isEnabled=!0,this._isDirty=!1,this._camerasToBeAttached=[],this._pingpong=0,this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=r,this._taaThinPostProcess=new W_("TAA",this._scene.getEngine()),this.isSupported&&(this._createPingPongTextures(s.getRenderWidth(),s.getRenderHeight()),t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline())}getClassName(){return"TAARenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(){this._disposePostProcesses(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._ping.dispose(),this._pong.dispose(),super.dispose()}_createPingPongTextures(e,t){const i=this._scene.getEngine();this._ping?.dispose(),this._pong?.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._taaThinPostProcess.textureWidth=e,this._taaThinPostProcess.textureHeight=t}_buildPipeline(){if(!this.isSupported)return;if(!this._isEnabled)return void(this._isDirty=!0);this._isDirty=!1;const e=this._scene.getEngine();this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._createTAAPostProcess(),this.addEffect(new AO(e,this.TAARenderEffect,(()=>this._taaPostProcess),!0)),this._createPassPostProcess(),this.addEffect(new AO(e,this.TAAPassEffect,(()=>this._passPostProcess),!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_disposePostProcesses(){for(let e=0;e{if(this._taaThinPostProcess.camera=this._scene.activeCamera,this._taaPostProcess?.width!==this._ping.width||this._taaPostProcess?.height!==this._ping.height){const e=this._scene.getEngine();this._createPingPongTextures(e.getRenderWidth(),e.getRenderHeight())}this._taaThinPostProcess.updateProjectionMatrix(),this._passPostProcess&&(this._passPostProcess.inputTexture=this._pingpong?this._ping:this._pong),this._pingpong=1^this._pingpong})),this._taaPostProcess.onApplyObservable.add((e=>{e._bindTexture("historySampler",this._pingpong?this._ping.texture:this._pong.texture)}))}_createPassPostProcess(){const e=this._scene.getEngine();this._passPostProcess=new _s.v("TAAPass",1,null,1,e),this._passPostProcess.inputTexture=this._ping,this._passPostProcess.autoClear=!1}serialize(){const e=it.p.Serialize(this);return e.customType="TAARenderingPipeline",e}static Parse(e,t,i){return it.p.Parse((()=>new mD(e._name,t,e._ratio)),e,t,i)}}(0,je.Cg)([(0,$e.lK)("samples")],mD.prototype,"samples",null),(0,je.Cg)([(0,$e.lK)("msaaSamples")],mD.prototype,"_msaaSamples",void 0),(0,je.Cg)([(0,$e.lK)()],mD.prototype,"factor",null),(0,je.Cg)([(0,$e.lK)()],mD.prototype,"disableOnCameraMove",null),(0,je.Cg)([(0,$e.lK)("isEnabled")],mD.prototype,"_isEnabled",void 0),(0,X.Y5)("BABYLON.TAARenderingPipeline",mD);var gD,vD=i(33258),xD=i(20661),bD=i(93640),SD=i(87193),TD=i(83514),CD=i(36253),yD=i(98e3),ED=i(86763),PD=i(20136);i(7672),i(88559),function(e){e[e.Hable=0]="Hable",e[e.Reinhard=1]="Reinhard",e[e.HejiDawson=2]="HejiDawson",e[e.Photographic=3]="Photographic"}(gD||(gD={}));class AD extends ms.w{getClassName(){return"TonemapPostProcess"}constructor(e,t,i,r,s=2,n,o=0,a){super(e,"tonemap",["_ExposureAdjustment"],null,1,r,s,n,a,null,o),this._operator=t,this.exposureAdjustment=i;let l="#define ";0===this._operator?l+="HABLE_TONEMAPPING":1===this._operator?l+="REINHARD_TONEMAPPING":2===this._operator?l+="OPTIMIZED_HEJIDAWSON_TONEMAPPING":3===this._operator&&(l+="PHOTOGRAPHIC_TONEMAPPING"),this.updateEffect(l),this.onApply=e=>{e.setFloat("_ExposureAdjustment",this.exposureAdjustment)}}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(i.bind(i,41739))]))):t.push(Promise.all([Promise.resolve().then(i.bind(i,47088))])),super._gatherImports(e,t)}}Cs.l.ShadersStore.volumetricLightScatteringPixelShader="uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec2 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{this.isSupported||this.dispose(e),this.onActivate=null},this.onApplyObservable.add((e=>{this._updateMeshScreenCoordinates(l),e.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),e.setFloat("exposure",this.exposure),e.setFloat("decay",this.decay),e.setFloat("weight",this.weight),e.setFloat("density",this.density),e.setVector2("meshPositionOnScreen",this._screenCoordinates)}))}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){const i=e.getMesh();if(i===this.mesh&&i.material)return i.material.isReady(i);const r=i._internalAbstractMeshDataInfo._materialForRenderPass?.[this._scene.getEngine().currentRenderPassId];if(r)return r.isReadyForSubMesh(i,e,t);const s=[],n=[st.R.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&s.push("#define ALPHATEST"),i.isVerticesDataPresent(st.R.UVKind)&&(n.push(st.R.UVKind),s.push("#define UV1")),i.isVerticesDataPresent(st.R.UV2Kind)&&(n.push(st.R.UV2Kind),s.push("#define UV2")));const a=new Tn;if(i.useBones&&i.computeBonesUsingShaders&&i.skeleton){n.push(st.R.MatricesIndicesKind),n.push(st.R.MatricesWeightsKind),i.numBoneInfluencers>4&&(n.push(st.R.MatricesIndicesExtraKind),n.push(st.R.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+i.numBoneInfluencers),i.numBoneInfluencers>0&&a.addCPUSkinningFallback(0,i);const e=i.skeleton;e.isUsingTextureForMatrices?s.push("#define BONETEXTURE"):s.push("#define BonesPerMesh "+(e.bones.length+1))}else s.push("#define NUM_BONE_INFLUENCERS 0");const l=i.morphTargetManager;let h=0;l&&(h=l.numMaxInfluencers||l.numInfluencers,h>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+h),l.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),(0,Bt.MF)(n,i,h))),t&&(s.push("#define INSTANCES"),(0,Bt.te)(n),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES"));const c=i.bakedVertexAnimationManager;c&&c.isEnabled&&(s.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&n.push("bakedVertexAnimationSettingsInstanced"));const u=e._getDrawWrapper(void 0,!0),d=u.defines,f=s.join("\n");if(d!==f){const e=["world","mBones","boneTextureWidth","viewProjection","diffuseMatrix","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],t=["diffuseSampler","morphTargets","boneSampler","bakedVertexAnimationTexture"];u.setEffect(i.getScene().getEngine().createEffect("volumetricLightScatteringPass",{attributes:n,uniformsNames:e,uniformBuffersNames:[],samplers:t,defines:f,fallbacks:a,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:h}},i.getScene().getEngine()),f)}return u.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){const t=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==t&&e.getScene().customRenderTargets.splice(t,1),this._volumetricLightScatteringRTT.dispose(),super.dispose(e)}getPass(){return this._volumetricLightScatteringRTT}_meshExcluded(e){return this.includedMeshes.length>0&&-1===this.includedMeshes.indexOf(e)||this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)}_createPass(e,t){const i=e.getEngine();this._volumetricLightScatteringRTT=new ln.$("volumetricLightScatteringMap",{width:i.getRenderWidth()*t,height:i.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=vi.g.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=vi.g.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;const r=this.getCamera();r?r.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);const s=e=>{const t=e.getRenderingMesh(),i=e.getEffectiveMesh();if(this._meshExcluded(t))return;i._internalAbstractMeshDataInfo._isActiveIntermediate=!1;const r=e.getMaterial();if(!r)return;const s=t.getScene(),n=s.getEngine();n.setState(r.backFaceCulling,void 0,void 0,void 0,r.cullBackFaces);const o=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;const a=n.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||t.hasThinInstances);if(this._isReady(e,a)){const l=i._internalAbstractMeshDataInfo._materialForRenderPass?.[n.currentRenderPassId];let h=e._getDrawWrapper();if(t!==this.mesh||h||(h=r._getDrawWrapper()),!h)return;const c=h.effect;if(n.enableEffect(h),a||t._bind(e,c,r.fillMode),t===this.mesh)r.bind(i.getWorldMatrix(),t);else if(l)l.bindForSubMesh(i.getWorldMatrix(),i,e);else{if(c.setMatrix("viewProjection",s.getTransformMatrix()),r.needAlphaTesting()){const e=r.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}(0,Bt.f$)(t,c),(0,Bt.nR)(t,c),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(c);const i=e.getMesh().bakedVertexAnimationManager;i&&i.isEnabled&&i.bind(c,a)}a&&t.hasThinInstances&&c.setMatrix("world",i.getWorldMatrix()),t._processRendering(i,e,c,Vt.TriangleFillMode,o,a,((e,t)=>{e||c.setMatrix("world",t)}))}};let n;const o=new H.ov(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((()=>{n=e.clearColor,e.clearColor=o})),this._volumetricLightScatteringRTT.onAfterRenderObservable.add((()=>{e.clearColor=n})),this._volumetricLightScatteringRTT.customIsReadyFunction=(e,t,r)=>{if((r||0===t)&&e.subMeshes)for(let t=0;t{const o=e.getEngine();let a;if(n.length){for(o.setColorWrite(!1),a=0;ae._alphaIndex>t._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0)),o.setAlphaMode(2),a=0;a{e.setFloat("curvature_ridge",.5/Math.max(this.ridge*this.ridge,1e-4)),e.setFloat("curvature_valley",.7/Math.max(this.valley*this.valley,1e-4));const t=this._geometryBufferRenderer.getGBuffer().textures[1];e.setTexture("normalSampler",t)}):Z.V.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){const e=he.q.LastCreatedEngine;return!!e&&e.getCaps().drawBuffersExtension}static _Parse(e,t,i,r){return it.p.Parse((()=>new ID(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,r)}}(0,je.Cg)([(0,$e.lK)()],ID.prototype,"ridge",void 0),(0,je.Cg)([(0,$e.lK)()],ID.prototype,"valley",void 0),(0,X.Y5)("BABYLON.ScreenSpaceCurvaturePostProcess",ID);var MD=i(18013),OD=i(45010),DD=i(45245),wD=i(95527),ND=i(56558),FD=i(42876),LD=i(30927),BD=i(88412),VD=i(418),kD=i(12253),UD=i(44341),GD=i(79132),zD=i(41123),WD=i(27220),HD=i(68820),XD=i(55099),qD=i(35624),YD=i(44134),KD=i(95610),jD=i(41289),$D=i(29743),QD=i(89328),ZD=i(94811),JD=i(63186),ew=i(83062),tw=i(9574),iw=i(75424),rw=i(84014),sw=i(54525),nw=i(32439),ow=i(27897),aw=i(31162),lw=i(20692),hw=i(2153),cw=i(59188),uw=i(79799),dw=i(42711),fw=i(82308),pw=i(28377),_w=i(95400),mw=i(88770),gw=i(26879),vw=i(13079),xw=i(28162),bw=i(17239),Sw=i(63788),Tw=i(47088),Cw=i(41739);Object.defineProperty(oi.Z.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(e){this._forceShowBoundingBoxes=e,e&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),oi.Z.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new yw(this)),this._boundingBoxRenderer},Object.defineProperty(Nt.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(e){this._showBoundingBox=e,e&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class yw{get shaderLanguage(){return this._shaderLanguage}constructor(e){this.name=Ut.v.NAME_BOUNDINGBOXRENDERER,this.frontColor=new H.v9(1,1,1),this.backColor=new H.v9(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new z.cP,this.onAfterBoxRenderingObservable=new z.cP,this.onResourcesReadyObservable=new z.cP,this.enabled=!0,this._shaderLanguage=0,this.renderList=new Qe.L(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,this.scene.getEngine().isWebGPU&&(this._shaderLanguage=1),e._addComponent(this),this._uniformBufferFront=new Rt.D(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!0),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new Rt.D(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!0),this._buildUniformLayout(this._uniformBufferBack)}_buildUniformLayout(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()}register(){this.scene._beforeEvaluateActiveMeshStage.registerStep(Ut.v.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(Ut.v.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(Ut.v.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(Ut.v.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){const i=t.getBoundingInfo();null!=i&&(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 xo("colorShader",this.scene,"boundingBoxRenderer",{attributes:[st.R.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,10737)),Promise.resolve().then(i.bind(i,83063))]):await Promise.all([Promise.resolve().then(i.bind(i,81473)),Promise.resolve().then(i.bind(i,16400))])}},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new xo("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[st.R.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,10737)),Promise.resolve().then(i.bind(i,83063))]):await Promise.all([Promise.resolve().then(i.bind(i,81473)),Promise.resolve().then(i.bind(i,16400))])}},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};const e=this.scene.getEngine(),t=qo({size:1});this._vertexBuffers[st.R.PositionKind]=new st.R(e,t.positions,st.R.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[st.R.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){if(0===this.renderList.length||!this.enabled)return;if(this._prepareResources(),!this._colorShader.isReady())return;const t=this.scene.getEngine();t.setDepthWrite(!1);const i=this.scene.getTransformMatrix();for(let r=0;r{let t=e._getComponent(Ut.v.NAME_DEPTHRENDERER);t||(t=new Ew(e),e._addComponent(t))};class Pw{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class Aw{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){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}get shaderLanguage(){return this._shaderLanguage}constructor(e,t=5){if(this._thinTextures=[],this._currentPingPongState=0,this._layoutCacheFormat=[[!0],[!0,!0],[!0,!0,!0]],this._layoutCache=[],this._candidateSubMeshes=new Qe.L(10),this._excludedSubMeshes=new Qe.L(10),this._excludedMeshes=[],this._colorCache=[new H.ov(Aw._DEPTH_CLEAR_VALUE,Aw._DEPTH_CLEAR_VALUE,0,0),new H.ov(-Aw._MIN_DEPTH,Aw._MAX_DEPTH,0,0),new H.ov(0,0,0,0)],this._shaderLanguage=0,this._scene=e,this._engine=e.getEngine(),this._passCount=t,e.enablePrePassRenderer()){for(let e=0;e{1===this._shaderLanguage?await Promise.resolve().then(i.bind(i,29551)):await Promise.resolve().then(i.bind(i,17738))}}),this._blendBackEffectWrapperPingPong=new Yp.$({fragmentShader:"oitBackBlend",useShaderStore:!0,engine:this._engine,samplerNames:["uBackColor"],uniformNames:[],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await Promise.resolve().then(i.bind(i,29551)):await Promise.resolve().then(i.bind(i,17738))}}),this._finalEffectWrapper=new Yp.$({fragmentShader:"oitFinal",useShaderStore:!0,engine:this._engine,samplerNames:["uFrontColor","uBackColor"],uniformNames:[],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await Promise.resolve().then(i.bind(i,21937)):await Promise.resolve().then(i.bind(i,4172))}}),this._effectRenderer=new Yp.J(this._engine)}setPrePassRenderer(e){e.addEffectConfiguration(this._prePassEffectConfiguration)}bind(e){e.setTexture("oitDepthSampler",this._thinTextures[3*this._currentPingPongState]),e.setTexture("oitFrontColorSampler",this._thinTextures[3*this._currentPingPongState+1])}_renderSubMeshes(e){let t;this._useRenderPasses&&(t={});for(let i=0;i{1===t?await Promise.all([Promise.resolve().then(i.bind(i,7217)),Promise.resolve().then(i.bind(i,27127))]):await Promise.all([Promise.resolve().then(i.bind(i,42644)),Promise.resolve().then(i.bind(i,85550))])}},!1);r.disableDepthWrite=!0,r.backFaceCulling=!1,r.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=r}return e._edgeRenderLineShader}get shaderLanguage(){return this._shaderLanguage}constructor(e,t=.95,i=!1,r=!0,s){this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new Qe.L(32),this._shaderLanguage=0,this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=s??null,this._epsilon=t;const n=this._source.getScene().getEngine();n.isWebGPU&&(this._drawWrapper=new gt.E(n),this._shaderLanguage=1),this._prepareRessources(),r&&(s?.useAlternateEdgeFinder??1?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=Mw._GetShader(this._source.getScene(),this._shaderLanguage))}_rebuild(){let e=this._buffers[st.R.PositionKind];e&&e._rebuild(),e=this._buffers[st.R.NormalKind],e&&e._rebuild();const t=this._source.getScene().getEngine();this._ib=t.createIndexBuffer(this._linesIndices)}dispose(){this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let e=this._buffers[st.R.PositionKind];e&&(e.dispose(),this._buffers[st.R.PositionKind]=null),e=this._buffers[st.R.NormalKind],e&&(e.dispose(),this._buffers[st.R.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),this._drawWrapper?.dispose()}_processEdgeForAdjacencies(e,t,i,r,s){return e===i&&t===r||e===r&&t===i?0:e===r&&t===s||e===s&&t===r?1:e===s&&t===i||e===i&&t===s?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,r,s){const n=1e-10;return e.equalsWithEpsilon(i,n)&&t.equalsWithEpsilon(r,n)||e.equalsWithEpsilon(r,n)&&t.equalsWithEpsilon(i,n)?0:e.equalsWithEpsilon(r,n)&&t.equalsWithEpsilon(s,n)||e.equalsWithEpsilon(s,n)&&t.equalsWithEpsilon(r,n)?1:e.equalsWithEpsilon(s,n)&&t.equalsWithEpsilon(i,n)||e.equalsWithEpsilon(i,n)&&t.equalsWithEpsilon(s,n)?2:-1}_checkEdge(e,t,i,r,s){let n;n=void 0===t||W.Pq.Dot(i[e],i[t]){i>=0&&t.push(i);for(let i=0;i=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 t=0;t<3;++t)t===n?e[t].sort(((e,t)=>e[1]t[1]?1:0)):e[t].sort(((e,t)=>e[1]>t[1]?-1:e[1]=n+1;--o)s(e[o%3],a,o!==n+2?r[i[t+(o+1)%3]]:-1);const h=a.length;i.push(r[i[t+n]],o[0],a[0]),i.push(r[i[t+(n+1)%3]],a[h-1],o[l-1]);const c=l<=h,u=c?l:h,d=c?h:l,f=c?l-1:h-1,p=c?0:1;let _=l+h-2,m=0,g=0;const v=c?o:a,x=c?a:o;let b=0;for(;_-- >0;){let e;p?i.push(v[m],x[g]):i.push(x[g],v[m]),b+=u,b>=d&&ml){const e=a;a=l,l=e}const c=a+"_"+l,u=o[c];u?u.done||(W.Pq.Dot(r,u.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)return void this._lineShader._setDrawWrapper(t);const i=this._source.hasInstances&&this.customInstances.length>0,r=i||this._source.hasThinInstances;let s=0;if(r)if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){const e=this._source._instanceDataStorage;if(s=this.customInstances.length,!e.instancesData)return void(this._source.getScene()._activeMeshesFrozen||this.customInstances.reset());if(!e.isFrozen){let t=0;for(let i=0;i{this._isVoxelGrid3D?e?t.push(Promise.resolve().then(i.bind(i,20008))):t.push(Promise.resolve().then(i.bind(i,95171))):e?t.push(Promise.resolve().then(i.bind(i,7426))):t.push(Promise.resolve().then(i.bind(i,68859)))}};this._voxelDebugPass=new ms.w(this.debugPassName,this._isVoxelGrid3D?"iblVoxelGrid3dDebug":"iblVoxelGrid2dArrayDebug",t),this._voxelDebugPass.onApplyObservable.add((e=>{0===this._voxelDebugAxis?e.setTexture("voxelTexture",this._voxelGridXaxis):1===this._voxelDebugAxis?e.setTexture("voxelTexture",this._voxelGridYaxis):2===this._voxelDebugAxis?e.setTexture("voxelTexture",this._voxelGridZaxis):e.setTexture("voxelTexture",this.getVoxelGrid()),e.setTexture("voxelSlabTexture",this._voxelSlabDebugRT),e.setVector4("sizeParams",this._debugSizeParams),e.setFloat("mipNumber",this._debugMipNumber)}))}}constructor(e,t,r=6,s=!0){this._voxelMrtsXaxis=[],this._voxelMrtsYaxis=[],this._voxelMrtsZaxis=[],this._isVoxelGrid3D=!0,this._renderTargets=[],this._triPlanarVoxelization=!0,this._voxelizationInProgress=!1,this._invWorldScaleMatrix=W.uq.Identity(),this._voxelResolution=64,this._voxelResolutionExp=6,this._mipArray=[],this._voxelDebugEnabled=!1,this._voxelDebugAxis=-1,this._debugSizeParams=new W.IU(0,0,0,0),this._includedMeshes=[],this._debugMipNumber=0,this._debugPassName="Voxelization Debug Pass",this._scene=e,this._engine=e.getEngine(),this._triPlanarVoxelization=s,this._engine.getCaps().drawBuffersExtension||Z.V.Error("Can't do voxel rendering without the draw buffers extension.");const n=this._engine.isWebGPU;this._maxDrawBuffers=this._engine.getCaps().maxDrawBuffers||0,this._copyMipEffectRenderer=new Yp.J(this._engine),this._copyMipEffectWrapper=new Yp.$({engine:this._engine,fragmentShader:"copyTexture3DLayerToTexture",useShaderStore:!0,uniformNames:["layerNum"],samplerNames:["textureSampler"],shaderLanguage:n?1:0,extraInitializationsAsync:async()=>{n?await Promise.resolve().then(i.bind(i,4357)):await Promise.resolve().then(i.bind(i,76978))}}),this.voxelResolutionExp=r}_generateMipMaps(){const e=Math.ceil(Math.log2(this._voxelResolution));for(let t=1;t{e?await Promise.resolve().then(i.bind(i,48016)):await Promise.resolve().then(i.bind(i,17897))}};this._triPlanarVoxelization?(this._voxelGridXaxis=new ln.$("voxelGridXaxis",t,this._scene,r),this._voxelGridYaxis=new ln.$("voxelGridYaxis",t,this._scene,r),this._voxelGridZaxis=new ln.$("voxelGridZaxis",t,this._scene,r),this._voxelMrtsXaxis=this._createVoxelMRTs("x_axis_",this._voxelGridXaxis,s),this._voxelMrtsYaxis=this._createVoxelMRTs("y_axis_",this._voxelGridYaxis,s),this._voxelMrtsZaxis=this._createVoxelMRTs("z_axis_",this._voxelGridZaxis,s),this._voxelGridRT=new cv("combinedVoxelGrid",t,"iblCombineVoxelGrids",this._scene,n,!1),this._scene.proceduralTextures.splice(this._scene.proceduralTextures.indexOf(this._voxelGridRT),1),this._voxelGridRT.setFloat("layer",0),this._voxelGridRT.setTexture("voxelXaxisSampler",this._voxelGridXaxis),this._voxelGridRT.setTexture("voxelYaxisSampler",this._voxelGridYaxis),this._voxelGridRT.setTexture("voxelZaxisSampler",this._voxelGridZaxis),this._voxelGridRT.autoClear=!1,this._voxelGridRT.wrapU=vi.g.CLAMP_ADDRESSMODE,this._voxelGridRT.wrapV=vi.g.CLAMP_ADDRESSMODE):(this._voxelGridZaxis=new ln.$("voxelGridZaxis",t,this._scene,n),this._voxelMrtsZaxis=this._createVoxelMRTs("z_axis_",this._voxelGridZaxis,s));const o={generateDepthBuffer:!1,generateMipMaps:!1,type:0,format:6,samplingMode:1,shaderLanguage:e?1:0,extraInitializationsAsync:async()=>{e?await Promise.resolve().then(i.bind(i,88789)):await Promise.resolve().then(i.bind(i,99638))}};this._mipArray=new Array(Math.ceil(Math.log2(this._voxelResolution)));for(let e=1;e<=this._mipArray.length;e++){const t=this._voxelResolution>>e,i={width:t,height:t,depth:t};this._mipArray[e-1]=new cv("voxelMip"+e,i,"iblGenerateVoxelMip",this._scene,o,!1),this._scene.proceduralTextures.splice(this._scene.proceduralTextures.indexOf(this._mipArray[e-1]),1);const r=this._mipArray[e-1];r.autoClear=!1,r.wrapU=vi.g.CLAMP_ADDRESSMODE,r.wrapV=vi.g.CLAMP_ADDRESSMODE,r.setTexture("srcMip",e>1?this._mipArray[e-2]:this.getVoxelGrid()),r.setInt("layerNum",0)}this._createVoxelMaterials()}_createVoxelMRTs(e,t,i){t.wrapU=vi.g.CLAMP_ADDRESSMODE,t.wrapV=vi.g.CLAMP_ADDRESSMODE,t.noPrePassRenderer=!0;const r=[],s=new Array(this._maxDrawBuffers).fill(this._isVoxelGrid3D?32879:35866);for(let n=0;nn*this._maxDrawBuffers+t));let o=new Array(this._maxDrawBuffers).fill("");o=o.map(((t,i)=>"voxel_grid_"+e+(n*this._maxDrawBuffers+i)));const a=new Xb("mrt_"+e+n,{width:this._voxelResolution,height:this._voxelResolution,depth:this._isVoxelGrid3D?this._voxelResolution:void 0},this._maxDrawBuffers,this._scene,{types:new Array(this._maxDrawBuffers).fill(0),samplingModes:new Array(this._maxDrawBuffers).fill(3),generateMipMaps:!1,targetTypes:s,formats:new Array(this._maxDrawBuffers).fill(6),faceIndex:new Array(this._maxDrawBuffers).fill(0),layerIndex:i,layerCounts:new Array(this._maxDrawBuffers).fill(this._voxelResolution),generateDepthBuffer:!1,generateStencilBuffer:!1},o);a.clearColor=new H.ov(0,0,0,1),a.noPrePassRenderer=!0;for(let e=0;e{e.dispose()})),this._voxelMaterial?.dispose(),this._voxelSlabDebugMaterial?.dispose(),this._mipArray=[],this._voxelMrtsXaxis=[],this._voxelMrtsYaxis=[],this._voxelMrtsZaxis=[]}_createVoxelMaterials(){const e=this._engine.isWebGPU;this._voxelMaterial=new xo("voxelization",this._scene,"iblVoxelGrid",{uniforms:["world","viewMatrix","invWorldScale","nearPlane","farPlane","stepSize"],defines:["MAX_DRAW_BUFFERS "+this._maxDrawBuffers],shaderLanguage:e?1:0,extraInitializationsAsync:async()=>{e?await Promise.all([Promise.resolve().then(i.bind(i,75904)),Promise.resolve().then(i.bind(i,79214))]):await Promise.all([Promise.resolve().then(i.bind(i,83145)),Promise.resolve().then(i.bind(i,19395))])}}),this._voxelMaterial.cullBackFaces=!1,this._voxelMaterial.backFaceCulling=!1,this._voxelMaterial.depthFunction=an.ALWAYS,this._voxelSlabDebugMaterial=new xo("voxelSlabDebug",this._scene,"iblVoxelSlabDebug",{uniforms:["world","viewMatrix","cameraViewMatrix","projection","invWorldScale","nearPlane","farPlane","stepSize"],defines:["MAX_DRAW_BUFFERS "+this._maxDrawBuffers],shaderLanguage:e?1:0,extraInitializationsAsync:async()=>{e?await Promise.all([Promise.resolve().then(i.bind(i,16615)),Promise.resolve().then(i.bind(i,94369))]):await Promise.all([Promise.resolve().then(i.bind(i,81284)),Promise.resolve().then(i.bind(i,71650))])}})}_setDebugBindings(){this._voxelSlabDebugMaterial.setMatrix("projection",this._scene.activeCamera.getProjectionMatrix()),this._voxelSlabDebugMaterial.setMatrix("cameraViewMatrix",this._scene.activeCamera.getViewMatrix())}isReady(){let e=this.getVoxelGrid().isReady();for(let t=0;tt===e[0]));if(t>=0)this._renderTargets.splice(t,e.length);else{const t=this._scene.customRenderTargets.findIndex((t=>t===e[0]));t>=0&&this._scene.customRenderTargets.splice(t,e.length)}}updateVoxelGrid(e){this._stopVoxelization(),this._includedMeshes=e,this._voxelizationInProgress=!0,this._triPlanarVoxelization?(this._addRTsForRender(this._voxelMrtsXaxis,e,0),this._addRTsForRender(this._voxelMrtsYaxis,e,1),this._addRTsForRender(this._voxelMrtsZaxis,e,2)):this._addRTsForRender(this._voxelMrtsZaxis,e,2),this._voxelDebugEnabled&&this._addRTsForRender([this._voxelSlabDebugRT],e,this._voxelDebugAxis,1,!0),this._renderVoxelGridBound=this._renderVoxelGrid.bind(this),this._scene.onAfterRenderObservable.add(this._renderVoxelGridBound)}_renderVoxelGrid(){if(this._voxelizationInProgress){let e=this.getVoxelGrid().isReady();for(let t=0;t{e.render()})),this._stopVoxelization(),this._triPlanarVoxelization&&this._voxelGridRT.render(),this._generateMipMaps(),this._copyMipMaps(),this._scene.onAfterRenderObservable.removeCallback(this._renderVoxelGridBound),this._voxelizationInProgress=!1)}}_addRTsForRender(e,t,i,r=0,s=!1){const n=1/this._computeNumberOfSlabs();let o;o=0===r?this._voxelMaterial:this._voxelSlabDebugMaterial,e.forEach(((e,r)=>{e.renderList=[];const s=r*n,a=(r+1)*n,l=n/this._maxDrawBuffers,h=new W.Pq(0,0,0);let c=new W.Pq(0,0,1);0===i?c=new W.Pq(1,0,0):1===i&&(c=new W.Pq(0,1,0));let u=new W.Pq(0,1,0);1===i&&(u=new W.Pq(1,0,0)),e.onBeforeRenderObservable.add((()=>{o.setMatrix("viewMatrix",W.uq.LookAtLH(h,c,u)),o.setMatrix("invWorldScale",this._invWorldScaleMatrix),o.setFloat("nearPlane",s),o.setFloat("farPlane",a),o.setFloat("stepSize",l)})),0!==t.length&&t.forEach((t=>{t&&(t.subMeshes&&t.subMeshes.length>0&&(e.renderList?.push(t),e.setMaterialForRendering(t,o)),t.getChildMeshes().forEach((t=>{t.subMeshes&&t.subMeshes.length>0&&(e.renderList?.push(t),e.setMaterialForRendering(t,o))})))}))})),s?e.forEach((e=>{-1===this._scene.customRenderTargets.indexOf(e)&&this._scene.customRenderTargets.push(e)})):this._renderTargets=this._renderTargets.concat(e)}resize(){this._voxelSlabDebugRT?.resize({width:this._scene.getEngine().getRenderWidth(),height:this._scene.getEngine().getRenderHeight()})}dispose(){this._disposeVoxelTextures(),this._voxelSlabDebugRT&&(this._removeVoxelRTs([this._voxelSlabDebugRT]),this._voxelSlabDebugRT.dispose()),this._voxelDebugPass&&this._voxelDebugPass.dispose()}}class ww{get voxelShadowOpacity(){return this._voxelShadowOpacity}set voxelShadowOpacity(e){this._voxelShadowOpacity=e}get ssShadowOpacity(){return this._ssShadowOpacity}set ssShadowOpacity(e){this._ssShadowOpacity=e}get sssSamples(){return this._sssSamples}set sssSamples(e){this._sssSamples=e}get sssStride(){return this._sssStride}set sssStride(e){this._sssStride=e}get sssMaxDist(){return this._sssMaxDist}set sssMaxDist(e){this._sssMaxDist=e}get sssThickness(){return this._sssThickness}set sssThickness(e){this._sssThickness=e}get voxelNormalBias(){return this._voxelNormalBias}set voxelNormalBias(e){this._voxelNormalBias=e}get voxelDirectionBias(){return this._voxelDirectionBias}set voxelDirectionBias(e){this._voxelDirectionBias=e}get sampleDirections(){return this._sampleDirections}set sampleDirections(e){this._sampleDirections=e}get envRotation(){return this._envRotation}set envRotation(e){this._envRotation=e}getOutputTexture(){return this._outputTexture}getDebugPassPP(){return this._debugPassPP||this._createDebugPass(),this._debugPassPP}get debugPassName(){return this._debugPassName}setWorldScaleMatrix(e){this._invWorldScaleMatrix=e}setDebugDisplayParams(e,t,i,r){this._debugSizeParams.set(e,t,i,r)}_createDebugPass(){const e=this._engine.isWebGPU;if(!this._debugPassPP){const t={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight(),uniforms:["sizeParams"],samplers:["debugSampler"],engine:this._engine,reusable:!1,shaderLanguage:e?1:0,extraInitializations:(e,t)=>{e?t.push(Promise.resolve().then(i.bind(i,65461))):t.push(Promise.resolve().then(i.bind(i,73588)))}};this._debugPassPP=new ms.w(this.debugPassName,"iblShadowDebug",t),this._debugPassPP.autoClear=!1,this._debugPassPP.onApplyObservable.add((e=>{e.setTexture("debugSampler",this._outputTexture),e.setVector4("sizeParams",this._debugSizeParams)}))}}constructor(e,t){this._voxelShadowOpacity=1,this._sssSamples=16,this._sssStride=8,this._sssMaxDist=.05,this._sssThickness=.5,this._ssShadowOpacity=1,this._cameraInvView=W.uq.Identity(),this._cameraInvProj=W.uq.Identity(),this._invWorldScaleMatrix=W.uq.Identity(),this._frameId=0,this._sampleDirections=4,this._shadowParameters=new W.IU(0,0,0,0),this._sssParameters=new W.IU(0,0,0,0),this._opacityParameters=new W.IU(0,0,0,0),this._voxelBiasParameters=new W.IU(0,0,0,0),this._voxelNormalBias=1.4,this._voxelDirectionBias=1.75,this.enabled=!0,this.debugEnabled=!1,this._debugPassName="Voxel Tracing Debug Pass",this._envRotation=0,this._debugVoxelMarchEnabled=!1,this._debugSizeParams=new W.IU(0,0,0,0),this._scene=e,this._engine=e.getEngine(),this._renderPipeline=t,this._createTextures()}_createTextures(){let e="";this._scene.useRightHandedSystem&&(e+="#define RIGHT_HANDED\n"),this._debugVoxelMarchEnabled&&(e+="#define VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION 1u\n");const t=this._engine.isWebGPU,r={type:0,format:5,samplingMode:1,generateDepthBuffer:!1,shaderLanguage:t?1:0,extraInitializationsAsync:async()=>{t?await Promise.all([Promise.resolve().then(i.bind(i,35680))]):await Promise.all([Promise.resolve().then(i.bind(i,74747))])}};this._outputTexture=new cv("voxelTracingPass",{width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},"iblShadowVoxelTracing",this._scene,r),this._outputTexture.refreshRate=-1,this._outputTexture.autoClear=!1,this._outputTexture.defines=e,this._setBindings(this._scene.activeCamera);let s=0;this._scene.onBeforeRenderObservable.add((()=>{s=0})),this._scene.onAfterRenderTargetsRenderObservable.add((()=>{2==++s&&this.enabled&&this._outputTexture.isReady()&&(this._setBindings(this._scene.activeCamera),this._outputTexture.render())}))}_setBindings(e){this._scene.useRightHandedSystem&&(this._outputTexture.defines="#define RIGHT_HANDED\n"),this._outputTexture.setMatrix("viewMtx",e.getViewMatrix()),this._outputTexture.setMatrix("projMtx",e.getProjectionMatrix()),e.getProjectionMatrix().invertToRef(this._cameraInvProj),e.getViewMatrix().invertToRef(this._cameraInvView),this._outputTexture.setMatrix("invProjMtx",this._cameraInvProj),this._outputTexture.setMatrix("invViewMtx",this._cameraInvView),this._outputTexture.setMatrix("wsNormalizationMtx",this._invWorldScaleMatrix),this._frameId++;let t=this._scene.useRightHandedSystem?-(this._envRotation+.5*Math.PI):this._envRotation-.5*Math.PI;t%=2*Math.PI,this._shadowParameters.set(this._sampleDirections,this._frameId,1,t),this._outputTexture.setVector4("shadowParameters",this._shadowParameters);const i=this._renderPipeline._getVoxelGridTexture(),r=Math.floor(Math.log2(i.getSize().width));this._voxelBiasParameters.set(this._voxelNormalBias,this._voxelDirectionBias,r,0),this._outputTexture.setVector4("voxelBiasParameters",this._voxelBiasParameters),this._sssParameters.set(this._sssSamples,this._sssStride,this._sssMaxDist,this._sssThickness),this._outputTexture.setVector4("sssParameters",this._sssParameters),this._opacityParameters.set(this._voxelShadowOpacity,this._ssShadowOpacity,0,0),this._outputTexture.setVector4("shadowOpacity",this._opacityParameters),this._outputTexture.setTexture("voxelGridSampler",i),this._outputTexture.setTexture("blueNoiseSampler",this._renderPipeline._getNoiseTexture()),this._outputTexture.setTexture("icdfySampler",this._renderPipeline._getIcdfyTexture()),this._outputTexture.setTexture("icdfxSampler",this._renderPipeline._getIcdfxTexture()),this._debugVoxelMarchEnabled&&(this._outputTexture.defines+="#define VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION 1u\n");const s=this._scene.geometryBufferRenderer;if(!s)return;const n=s.getTextureIndex(qO.SCREENSPACE_DEPTH_TEXTURE_TYPE);this._outputTexture.setTexture("depthSampler",s.getGBuffer().textures[n]);const o=s.getTextureIndex(qO.NORMAL_TEXTURE_TYPE);this._outputTexture.setTexture("worldNormalSampler",s.getGBuffer().textures[o])}resize(e=1){const t={width:Math.max(1,Math.floor(this._engine.getRenderWidth()*e)),height:Math.max(1,Math.floor(this._engine.getRenderHeight()*e))};this._outputTexture.resize(t,!1)}isReady(){return this._outputTexture.isReady()&&!(this._debugPassPP&&!this._debugPassPP.isReady())&&this._renderPipeline._getIcdfyTexture().isReady()&&this._renderPipeline._getIcdfxTexture().isReady()&&this._renderPipeline._getVoxelGridTexture().isReady()}dispose(){this._outputTexture.dispose(),this._debugPassPP&&this._debugPassPP.dispose()}}class Nw{get iblSource(){return this._iblSource}set iblSource(e){this._iblSource!==e&&(this._disposeTextures(),this._iblSource=e,e.isCube,e.isReadyOrNotBlocking()?this._recreateAssetsFromNewIbl(e):e.onLoadObservable.addOnce(this._recreateAssetsFromNewIbl.bind(this,e)))}_recreateAssetsFromNewIbl(e){this._debugPass&&this._debugPass.dispose(),this._createTextures(),this._debugPass&&this._createDebugPass(),this._icdfxPT.onGeneratedObservable.addOnce((()=>{this.onReadyObservable.notifyObservers()}))}getIcdfyTexture(){return this._icdfyPT}getIcdfxTexture(){return this._icdfxPT}setDebugDisplayParams(e,t,i,r){this._debugSizeParams.set(e,t,i,r)}get debugPassName(){return this._debugPassName}getDebugPassPP(){return this._debugPass||this._createDebugPass(),this._debugPass}constructor(e){this.debugEnabled=!1,this._debugSizeParams=new W.IU(0,0,0,0),this._debugPassName="Importance Sample Debug",this.onReadyObservable=new z.cP,this._scene=e,this._engine=e.getEngine()}_createTextures(){const e=this._iblSource?this._iblSource.getSize():{width:1,height:1};this._iblSource||(this._iblSource=xi.CreateRTexture(new Uint8Array([255]),1,1,this._scene,!1,!1,1,0),this._iblSource.name="Placeholder IBL Source"),this._iblSource.isCube&&(e.width*=4,e.height*=2);const t=this._engine.isWebGPU,r={generateDepthBuffer:!1,generateMipMaps:!1,format:6,type:1,samplingMode:1,shaderLanguage:t?1:0,extraInitializationsAsync:async()=>{t?await Promise.all([Promise.resolve().then(i.bind(i,43572)),Promise.resolve().then(i.bind(i,85917))]):await Promise.all([Promise.resolve().then(i.bind(i,47473)),Promise.resolve().then(i.bind(i,98824))])}},s={generateDepthBuffer:!1,generateMipMaps:!1,format:6,type:2,samplingMode:1,shaderLanguage:t?1:0,extraInitializationsAsync:async()=>{t?await Promise.all([Promise.resolve().then(i.bind(i,38957)),Promise.resolve().then(i.bind(i,27844))]):await Promise.all([Promise.resolve().then(i.bind(i,8970)),Promise.resolve().then(i.bind(i,7683))])}};this._cdfyPT=new cv("cdfyTexture",{width:e.width,height:e.height+1},"iblShadowsCdfy",this._scene,r,!1,!1),this._cdfyPT.autoClear=!1,this._cdfyPT.setTexture("iblSource",this._iblSource),this._cdfyPT.setInt("iblHeight",e.height),this._iblSource.isCube&&(this._cdfyPT.defines="#define IBL_USE_CUBE_MAP\n"),this._cdfyPT.refreshRate=0,this._icdfyPT=new cv("icdfyTexture",{width:e.width,height:e.height},"iblShadowsIcdfy",this._scene,s,!1,!1),this._icdfyPT.autoClear=!1,this._icdfyPT.setTexture("cdfy",this._cdfyPT),this._icdfyPT.refreshRate=0,this._cdfxPT=new cv("cdfxTexture",{width:e.width+1,height:1},"iblShadowsCdfx",this._scene,r,!1,!1),this._cdfxPT.autoClear=!1,this._cdfxPT.setTexture("cdfy",this._cdfyPT),this._cdfxPT.refreshRate=0,this._icdfxPT=new cv("icdfxTexture",{width:e.width,height:1},"iblShadowsIcdfx",this._scene,s,!1,!1),this._icdfxPT.autoClear=!1,this._icdfxPT.setTexture("cdfx",this._cdfxPT),this._icdfxPT.refreshRate=0}_disposeTextures(){this._cdfyPT?.dispose(),this._icdfyPT?.dispose(),this._cdfxPT?.dispose(),this._icdfxPT?.dispose()}_createDebugPass(){this._debugPass&&this._debugPass.dispose();const e=this._engine.isWebGPU,t={width:this._scene.getEngine().getRenderWidth(),height:this._scene.getEngine().getRenderHeight(),samplingMode:vi.g.BILINEAR_SAMPLINGMODE,engine:this._engine,textureType:0,uniforms:["sizeParams"],samplers:["cdfy","icdfy","cdfx","icdfx","iblSource"],defines:this._iblSource?.isCube?"#define IBL_USE_CUBE_MAP\n":"",shaderLanguage:e?1:0,extraInitializations:(e,t)=>{e?t.push(Promise.resolve().then(i.bind(i,78685))):t.push(Promise.resolve().then(i.bind(i,87382)))}};this._debugPass=new ms.w(this._debugPassName,"iblShadowsImportanceSamplingDebug",t);const r=this._debugPass.getEffect();r&&(r.defines=this._iblSource?.isCube?"#define IBL_USE_CUBE_MAP\n":""),this._iblSource?.isCube&&this._debugPass.updateEffect("#define IBL_USE_CUBE_MAP\n"),this._debugPass.onApplyObservable.add((e=>{e.setTexture("cdfy",this._cdfyPT),e.setTexture("icdfy",this._icdfyPT),e.setTexture("cdfx",this._cdfxPT),e.setTexture("icdfx",this._icdfxPT),e.setTexture("iblSource",this._iblSource),e.setFloat4("sizeParams",this._debugSizeParams.x,this._debugSizeParams.y,this._debugSizeParams.z,this._debugSizeParams.w)}))}isReady(){return this._iblSource&&"Placeholder IBL Source"!==this._iblSource.name&&this._iblSource.isReady()&&this._cdfyPT&&this._cdfyPT.isReady()&&this._icdfyPT&&this._icdfyPT.isReady()&&this._cdfxPT&&this._cdfxPT.isReady()&&this._icdfxPT&&this._icdfxPT.isReady()}dispose(){this._disposeTextures(),this._debugPass&&this._debugPass.dispose(),this.onReadyObservable.clear()}}class Fw{getOutputTexture(){return this._outputTexture}getDebugPassPP(){return this._debugPassPP||this._createDebugPass(),this._debugPassPP}get debugPassName(){return this._debugPassName}setWorldScale(e){this._worldScale=e}setDebugDisplayParams(e,t,i,r){this._debugSizeParams.set(e,t,i,r)}_createDebugPass(){if(!this._debugPassPP){const e=this._engine.isWebGPU,t={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight(),textureFormat:6,textureType:0,samplingMode:1,uniforms:["sizeParams"],samplers:["debugSampler"],engine:this._engine,reusable:!1,shaderLanguage:e?1:0,extraInitializations:(e,t)=>{e?t.push(Promise.resolve().then(i.bind(i,65461))):t.push(Promise.resolve().then(i.bind(i,73588)))}};this._debugPassPP=new ms.w(this.debugPassName,"iblShadowDebug",t),this._debugPassPP.autoClear=!1,this._debugPassPP.onApplyObservable.add((e=>{e.setTexture("debugSampler",this._outputTexture),e.setVector4("sizeParams",this._debugSizeParams)}))}}constructor(e,t){this._worldScale=1,this._blurParameters=new W.IU(0,0,0,0),this.enabled=!0,this._debugPassName="Spatial Blur Debug Pass",this.debugEnabled=!1,this._debugSizeParams=new W.IU(0,0,0,0),this._scene=e,this._engine=e.getEngine(),this._renderPipeline=t,this._createTextures()}_createTextures(){const e=this._engine.isWebGPU,t={type:0,format:5,samplingMode:1,generateDepthBuffer:!1,generateMipMaps:!1,shaderLanguage:e?1:0,extraInitializationsAsync:async()=>{e?await Promise.all([Promise.resolve().then(i.bind(i,45647))]):await Promise.all([Promise.resolve().then(i.bind(i,80018))])}};this._outputTexture=new cv("spatialBlurPass",{width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},"iblShadowSpatialBlur",this._scene,t,!1,!1,0),this._outputTexture.refreshRate=-1,this._outputTexture.autoClear=!1,this._setBindings();let r=0;this._scene.onBeforeRenderObservable.add((()=>{r=0})),this._scene.onAfterRenderTargetsRenderObservable.add((()=>{2==++r&&this.enabled&&this._outputTexture.isReady()&&(this._setBindings(),this._outputTexture.render())}))}_setBindings(){this._outputTexture.setTexture("voxelTracingSampler",this._renderPipeline._getVoxelTracingTexture()),this._blurParameters.set(1,this._worldScale,0,0),this._outputTexture.setVector4("blurParameters",this._blurParameters);const e=this._scene.geometryBufferRenderer;if(!e)return;const t=e.getTextureIndex(qO.SCREENSPACE_DEPTH_TEXTURE_TYPE);this._outputTexture.setTexture("depthSampler",e.getGBuffer().textures[t]);const i=e.getTextureIndex(qO.NORMAL_TEXTURE_TYPE);this._outputTexture.setTexture("worldNormalSampler",e.getGBuffer().textures[i])}resize(e=1){const t={width:Math.max(1,Math.floor(this._engine.getRenderWidth()*e)),height:Math.max(1,Math.floor(this._engine.getRenderHeight()*e))};this._outputTexture.resize(t,!1)}isReady(){return this._outputTexture.isReady()&&!(this._debugPassPP&&!this._debugPassPP.isReady())}dispose(){this._outputTexture.dispose(),this._debugPassPP&&this._debugPassPP.dispose()}}class Lw{getOutputTexture(){return this._outputTexture}getDebugPassPP(){return this._debugPassPP||this._createDebugPass(),this._debugPassPP}get debugPassName(){return this._debugPassName}get remanence(){return this._remanence}set remanence(e){this._remanence=e}get reset(){return this._reset}set reset(e){this._reset=e}set isMoving(e){this._isMoving=e}setDebugDisplayParams(e,t,i,r){this._debugSizeParams.set(e,t,i,r)}_createDebugPass(){if(!this._debugPassPP){const e=this._engine.isWebGPU,t={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight(),textureFormat:5,textureType:0,samplingMode:1,uniforms:["sizeParams"],samplers:["debugSampler"],engine:this._engine,reusable:!1,shaderLanguage:e?1:0,extraInitializations:(e,t)=>{e?t.push(Promise.resolve().then(i.bind(i,65461))):t.push(Promise.resolve().then(i.bind(i,73588)))}};this._debugPassPP=new ms.w(this.debugPassName,"iblShadowDebug",t),this._debugPassPP.autoClear=!1,this._debugPassPP.onApplyObservable.add((e=>{e.setTexture("debugSampler",this._outputTexture),e.setVector4("sizeParams",this._debugSizeParams)}))}}constructor(e,t){this._accumulationParams=new W.IU(0,0,0,0),this.debugEnabled=!1,this.enabled=!0,this.onReadyObservable=new z.cP,this._debugPassName="Shadow Accumulation Debug Pass",this._remanence=.9,this._reset=!0,this._isMoving=!1,this._debugSizeParams=new W.IU(0,0,0,0),this._scene=e,this._engine=e.getEngine(),this._renderPipeline=t,this._createTextures()}_createTextures(){const e=this._engine.isWebGPU,t={type:2,format:5,samplingMode:1,generateDepthBuffer:!1,generateMipMaps:!1,shaderLanguage:e?1:0,extraInitializationsAsync:async()=>{e?await Promise.all([Promise.resolve().then(i.bind(i,41115))]):await Promise.all([Promise.resolve().then(i.bind(i,17864))])}};this._outputTexture=new cv("shadowAccumulationPass",{width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},"iblShadowAccumulation",this._scene,t),this._outputTexture.refreshRate=-1,this._outputTexture.autoClear=!1,this._outputTexture.onGeneratedObservable.addOnce((()=>{this.onReadyObservable.notifyObservers()})),this._setOutputTextureBindings();let r=0;this._scene.onBeforeRenderObservable.add((()=>{r=0})),this._scene.onAfterRenderTargetsRenderObservable.add((()=>{2==++r&&this.enabled&&this._outputTexture.isReady()&&(this._setOutputTextureBindings(),this._outputTexture.render())}));const s={type:2,format:5,samplingMode:1,generateDepthBuffer:!1,generateMipMaps:!1,shaderLanguage:e?1:0,extraInitializationsAsync:async()=>{e?await Promise.all([Promise.resolve().then(i.bind(i,418))]):await Promise.all([Promise.resolve().then(i.bind(i,30927))])}};this._oldAccumulationCopy=new cv("oldAccumulationRT",{width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},"pass",this._scene,s,!1),this._oldAccumulationCopy.autoClear=!1,this._oldAccumulationCopy.refreshRate=1,this._oldAccumulationCopy.onBeforeGenerationObservable.add(this._setAccumulationCopyBindings.bind(this)),this._setAccumulationCopyBindings();const n={type:2,format:5,samplingMode:1,generateDepthBuffer:!1,generateMipMaps:!1,shaderLanguage:e?1:0,extraInitializationsAsync:async()=>{e?await Promise.all([Promise.resolve().then(i.bind(i,418))]):await Promise.all([Promise.resolve().then(i.bind(i,30927))])}};this._oldPositionCopy=new cv("oldLocalPositionRT",{width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},"pass",this._scene,n,!1),this._updatePositionCopy(),this._oldPositionCopy.autoClear=!1,this._oldPositionCopy.refreshRate=1,this._oldPositionCopy.onBeforeGenerationObservable.add(this._updatePositionCopy.bind(this))}_setOutputTextureBindings(){const e=this._isMoving?this.remanence:.99;this._accumulationParams.set(e,this.reset?1:0,this._renderPipeline.voxelGridSize,0),this._outputTexture.setTexture("spatialBlurSampler",this._renderPipeline._getSpatialBlurTexture()),this._outputTexture.setVector4("accumulationParameters",this._accumulationParams),this._outputTexture.setTexture("oldAccumulationSampler",this._oldAccumulationCopy?this._oldAccumulationCopy:this._renderPipeline._dummyTexture2d),this._outputTexture.setTexture("prevPositionSampler",this._oldPositionCopy?this._oldPositionCopy:this._renderPipeline._dummyTexture2d);const t=this._scene.geometryBufferRenderer;if(!t)return;const i=t.getTextureIndex(qO.VELOCITY_LINEAR_TEXTURE_TYPE);this._outputTexture.setTexture("motionSampler",t.getGBuffer().textures[i]);const r=t.getTextureIndex(qO.POSITION_TEXTURE_TYPE);this._outputTexture.setTexture("positionSampler",t.getGBuffer().textures[r]),this.reset=!1,this._isMoving=!1}_updatePositionCopy(){const e=this._scene.geometryBufferRenderer,t=e.getTextureIndex(qO.POSITION_TEXTURE_TYPE);this._oldPositionCopy.setTexture("textureSampler",e.getGBuffer().textures[t])}_setAccumulationCopyBindings(){this._oldAccumulationCopy.setTexture("textureSampler",this._outputTexture)}resize(e=1){const t={width:Math.max(1,Math.floor(this._engine.getRenderWidth()*e)),height:Math.max(1,Math.floor(this._engine.getRenderHeight()*e))};this._outputTexture.resize(t,!1),this._oldAccumulationCopy.resize(t,!1),this._oldPositionCopy.resize({width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},!1),this.reset=!0}_disposeTextures(){this._oldAccumulationCopy.dispose(),this._oldPositionCopy.dispose(),this._outputTexture.dispose()}isReady(){return this._oldAccumulationCopy&&this._oldAccumulationCopy.isReady()&&this._oldPositionCopy&&this._oldPositionCopy.isReady()&&this._outputTexture.isReady()&&!(this._debugPassPP&&!this._debugPassPP.isReady())}dispose(){this._disposeTextures(),this._debugPassPP&&this._debugPassPP.dispose(),this.onReadyObservable.clear()}}class Bw extends xn{constructor(){super(...arguments),this.RENDER_WITH_IBL_SHADOWS=!1}}class Vw extends Dn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e){super(e,Vw.Name,310,new Bw),this.shadowOpacity=1,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}prepareDefines(e){e.RENDER_WITH_IBL_SHADOWS=this._isEnabled}getClassName(){return"IBLShadowsPluginMaterial"}getUniforms(){return{ubo:[{name:"renderTargetSize",size:2,type:"vec2"},{name:"shadowOpacity",size:1,type:"float"}],fragment:"#ifdef RENDER_WITH_IBL_SHADOWS\n uniform vec2 renderTargetSize;\n uniform float shadowOpacity;\n #endif"}}getSamplers(e){e.push("iblShadowsTexture")}bindForSubMesh(e){this._isEnabled&&(e.bindTexture("iblShadowsTexture",this.iblShadowsTexture),e.updateFloat2("renderTargetSize",this._material.getScene().getEngine().getRenderWidth(),this._material.getScene().getEngine().getRenderHeight()),e.updateFloat("shadowOpacity",this.shadowOpacity))}getCustomCode(e,t){let i;return 1===t?(i={CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RENDER_WITH_IBL_SHADOWS\n var iblShadowsTextureSampler: sampler;\n var iblShadowsTexture: texture_2d;\n\n fn computeIndirectShadow() -> vec2f {\n var uv = fragmentInputs.position.xy / uniforms.renderTargetSize;\n var shadowValue: vec2f = textureSample(iblShadowsTexture, iblShadowsTextureSampler, uv).rg;\n return mix(shadowValue, vec2f(1.0), 1.0 - uniforms.shadowOpacity);\n }\n #endif\n "},this._material instanceof Gm?i.CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION="\n #ifdef RENDER_WITH_IBL_SHADOWS\n #ifdef REFLECTION\n var shadowValue: vec2f = computeIndirectShadow();\n finalIrradiance *= vec3f(shadowValue.x);\n finalRadianceScaled *= vec3f(mix(pow(shadowValue.y, 4.0), shadowValue.x, roughness));\n #endif\n #endif\n ":i.CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR="\n #ifdef RENDER_WITH_IBL_SHADOWS\n var shadowValue: vec2f = computeIndirectShadow();\n color *= toGammaSpace(vec4f(shadowValue.x, shadowValue.x, shadowValue.x, 1.0f));\n #endif\n "):(i={CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RENDER_WITH_IBL_SHADOWS\n uniform sampler2D iblShadowsTexture;\n\n vec2 computeIndirectShadow() {\n vec2 uv = gl_FragCoord.xy / renderTargetSize;\n vec2 shadowValue = texture2D(iblShadowsTexture, uv).rg;\n return mix(shadowValue.rg, vec2(1.0), 1.0 - shadowOpacity);\n }\n #endif\n "},this._material instanceof Gm?i.CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION="\n #ifdef RENDER_WITH_IBL_SHADOWS\n #ifdef REFLECTION\n vec2 shadowValue = computeIndirectShadow();\n finalIrradiance *= shadowValue.x;\n finalRadianceScaled *= mix(pow(shadowValue.y, 4.0), shadowValue.x, roughness);\n #endif\n #endif\n ":i.CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR="\n #ifdef RENDER_WITH_IBL_SHADOWS\n vec2 shadowValue = computeIndirectShadow();\n color.rgb *= toGammaSpace(shadowValue.x);\n #endif\n "),"vertex"===e?null:i}}Vw.Name="IBLShadowsPluginMaterial",(0,je.Cg)([(0,$e.lK)()],Vw.prototype,"iblShadowsTexture",void 0),(0,je.Cg)([(0,$e.lK)()],Vw.prototype,"shadowOpacity",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],Vw.prototype,"isEnabled",void 0),(0,X.Y5)("BABYLON.IBLShadowsPluginMaterial",Vw);class kw extends JO{resetAccumulation(){this._accumulationPass.reset=!0}get shadowOpacity(){return this._shadowOpacity}set shadowOpacity(e){this._shadowOpacity=e,this._setPluginParameters()}get shadowRenderSizeFactor(){return this._renderSizeFactor}set shadowRenderSizeFactor(e){this._renderSizeFactor=Math.max(Math.min(e,1),0),this._voxelTracingPass.resize(e),this._spatialBlurPass.resize(e),this._accumulationPass.resize(e),this._setPluginParameters()}get voxelShadowOpacity(){return this._voxelTracingPass?.voxelShadowOpacity}set voxelShadowOpacity(e){this._voxelTracingPass&&(this._voxelTracingPass.voxelShadowOpacity=e)}get ssShadowOpacity(){return this._voxelTracingPass?.ssShadowOpacity}set ssShadowOpacity(e){this._voxelTracingPass&&(this._voxelTracingPass.ssShadowOpacity=e)}get ssShadowSampleCount(){return this._voxelTracingPass?.sssSamples}set ssShadowSampleCount(e){this._voxelTracingPass&&(this._voxelTracingPass.sssSamples=e)}get ssShadowStride(){return this._voxelTracingPass?.sssStride}set ssShadowStride(e){this._voxelTracingPass&&(this._voxelTracingPass.sssStride=e)}get ssShadowDistanceScale(){return this._sssMaxDistScale}set ssShadowDistanceScale(e){this._sssMaxDistScale=e,this._updateSSShadowParams()}get ssShadowThicknessScale(){return this._sssThicknessScale}set ssShadowThicknessScale(e){this._sssThicknessScale=e,this._updateSSShadowParams()}setIblTexture(e){this._importanceSamplingRenderer&&(this._importanceSamplingRenderer.iblSource=e)}_getVoxelGridTexture(){const e=this._voxelRenderer?.getVoxelGrid();return e&&e.isReady()?e:this._dummyTexture3d}_getIcdfyTexture(){const e=this._importanceSamplingRenderer.getIcdfyTexture();return e&&e.isReady()?e:this._dummyTexture2d}_getIcdfxTexture(){const e=this._importanceSamplingRenderer.getIcdfxTexture();return e&&e.isReady()?e:this._dummyTexture2d}_getNoiseTexture(){const e=this._noiseTexture;return e&&e.isReady()?e:this._dummyTexture2d}_getVoxelTracingTexture(){const e=this._voxelTracingPass?.getOutputTexture();return e&&e.isReady()?e:this._dummyTexture2d}_getSpatialBlurTexture(){const e=this._spatialBlurPass.getOutputTexture();return e&&e.isReady()?e:this._dummyTexture2d}_getAccumulatedTexture(){const e=this._accumulationPass?.getOutputTexture();return e&&e.isReady()?e:this._dummyTexture2d}get gbufferDebugEnabled(){return this._gbufferDebugEnabled}set gbufferDebugEnabled(e){!e||this.allowDebugPasses?(this._gbufferDebugEnabled=e,e?this._enableEffect(this._getGBufferDebugPass().name,this.cameras):this._disableEffect(this._getGBufferDebugPass().name,this.cameras)):Z.V.Warn("Can't enable G-Buffer debug view without setting allowDebugPasses to true.")}get importanceSamplingDebugEnabled(){return this._importanceSamplingRenderer?.debugEnabled}set importanceSamplingDebugEnabled(e){this._importanceSamplingRenderer&&(!e||this.allowDebugPasses?e!==this._importanceSamplingRenderer.debugEnabled&&(this._importanceSamplingRenderer.debugEnabled=e,e?this._enableEffect(this._importanceSamplingRenderer.debugPassName,this.cameras):this._disableEffect(this._importanceSamplingRenderer.debugPassName,this.cameras)):Z.V.Warn("Can't enable importance sampling debug view without setting allowDebugPasses to true."))}get voxelDebugEnabled(){return this._voxelRenderer?.voxelDebugEnabled}set voxelDebugEnabled(e){this._voxelRenderer&&(!e||this.allowDebugPasses?(this._voxelRenderer.voxelDebugEnabled=e,e?this._enableEffect(this._voxelRenderer.debugPassName,this.cameras):this._disableEffect(this._voxelRenderer.debugPassName,this.cameras)):Z.V.Warn("Can't enable voxel debug view without setting allowDebugPasses to true."))}get voxelDebugAxis(){return this._voxelRenderer?.voxelDebugAxis}set voxelDebugAxis(e){this._voxelRenderer&&(this._voxelRenderer.voxelDebugAxis=e)}set voxelDebugDisplayMip(e){this._voxelRenderer&&this._voxelRenderer.setDebugMipNumber(e)}get voxelTracingDebugEnabled(){return this._voxelTracingPass?.debugEnabled}set voxelTracingDebugEnabled(e){this._voxelTracingPass&&(!e||this.allowDebugPasses?e!==this._voxelTracingPass.debugEnabled&&(this._voxelTracingPass.debugEnabled=e,e?this._enableEffect(this._voxelTracingPass.debugPassName,this.cameras):this._disableEffect(this._voxelTracingPass.debugPassName,this.cameras)):Z.V.Warn("Can't enable voxel tracing debug view without setting allowDebugPasses to true."))}get spatialBlurPassDebugEnabled(){return this._spatialBlurPass.debugEnabled}set spatialBlurPassDebugEnabled(e){this._spatialBlurPass&&(!e||this.allowDebugPasses?e!==this._spatialBlurPass.debugEnabled&&(this._spatialBlurPass.debugEnabled=e,e?this._enableEffect(this._spatialBlurPass.debugPassName,this.cameras):this._disableEffect(this._spatialBlurPass.debugPassName,this.cameras)):Z.V.Warn("Can't enable spatial blur debug view without setting allowDebugPasses to true."))}get accumulationPassDebugEnabled(){return this._accumulationPass?.debugEnabled}set accumulationPassDebugEnabled(e){this._accumulationPass&&(!e||this.allowDebugPasses?e!==this._accumulationPass.debugEnabled&&(this._accumulationPass.debugEnabled=e,e?this._enableEffect(this._accumulationPass.debugPassName,this.cameras):this._disableEffect(this._accumulationPass.debugPassName,this.cameras)):Z.V.Warn("Can't enable accumulation pass debug view without setting allowDebugPasses to true."))}addShadowCastingMesh(e){if(Array.isArray(e))for(const t of e)t&&-1===this._shadowCastingMeshes.indexOf(t)&&this._shadowCastingMeshes.push(t);else e&&-1===this._shadowCastingMeshes.indexOf(e)&&this._shadowCastingMeshes.push(e)}removeShadowCastingMesh(e){if(Array.isArray(e))for(const t of e){const e=this._shadowCastingMeshes.indexOf(t);-1!==e&&this._shadowCastingMeshes.splice(e,1)}else{const t=this._shadowCastingMeshes.indexOf(e);-1!==t&&this._shadowCastingMeshes.splice(t,1)}}get resolutionExp(){return this._voxelRenderer.voxelResolutionExp}set resolutionExp(e){e!==this._voxelRenderer.voxelResolutionExp&&(this._voxelRenderer.isVoxelizationInProgress()?Z.V.Warn("Can't change the resolution of the voxel grid while voxelization is in progress."):(this._voxelRenderer.voxelResolutionExp=Math.max(1,Math.min(e,8)),this._accumulationPass.reset=!0))}get sampleDirections(){return this._voxelTracingPass?.sampleDirections}set sampleDirections(e){this._voxelTracingPass&&(this._voxelTracingPass.sampleDirections=e)}get shadowRemanence(){return this._accumulationPass?.remanence}set shadowRemanence(e){this._accumulationPass&&(this._accumulationPass.remanence=e)}get envRotation(){return this._voxelTracingPass?.envRotation}set envRotation(e){this._voxelTracingPass&&(this._voxelTracingPass.envRotation=e,this._accumulationPass.reset=!0)}get allowDebugPasses(){return this._allowDebugPasses}set allowDebugPasses(e){this._allowDebugPasses!==e&&(this._allowDebugPasses=e,e?this._importanceSamplingRenderer.isReady()?this._createDebugPasses():this._importanceSamplingRenderer.onReadyObservable.addOnce((()=>{this._createDebugPasses()})):this._disposeDebugPasses())}static get IsSupported(){const e=he.q.LastCreatedEngine;return!!e&&e._features.supportIBLShadows}toggleShadow(e){this._enabled=e,this._voxelTracingPass.enabled=e,this._spatialBlurPass.enabled=e,this._accumulationPass.enabled=e,this._materialsWithRenderPlugin.forEach((t=>{t.pluginManager&&(t.pluginManager.getPlugin(Vw.Name).isEnabled=e)})),this._setPluginParameters()}updateVoxelization(){0!==this._shadowCastingMeshes.length?(this._voxelRenderer.updateVoxelGrid(this._shadowCastingMeshes),this._updateSSShadowParams()):Z.V.Warn("IBL Shadows: updateVoxelization called with no shadow-casting meshes to voxelize.")}updateSceneBounds(){const e={min:new W.Pq(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),max:new W.Pq(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE)};this._shadowCastingMeshes.forEach((t=>{const i=t.getHierarchyBoundingVectors(!0);e.min=W.Pq.Minimize(e.min,i.min),e.max=W.Pq.Maximize(e.max,i.max)}));const t=e.max.subtract(e.min);if(this.voxelGridSize=Math.max(t.x,t.y,t.z),0===this._shadowCastingMeshes.length||!isFinite(this.voxelGridSize)||0===this.voxelGridSize)return Z.V.Warn("IBL Shadows: Scene size is invalid. Can't update bounds."),void(this.voxelGridSize=1);const i=this.voxelGridSize/2,r=e.max.add(e.min).multiplyByFloats(-.5,-.5,-.5),s=W.uq.Compose(new W.Pq(1/i,1/i,1/i),new W.PT,new W.Pq(0,0,0));W.uq.Compose(new W.Pq(1,1,1),new W.PT,r).multiplyToRef(s,s),this._voxelTracingPass.setWorldScaleMatrix(s),this._voxelRenderer.setWorldScaleMatrix(s),this._spatialBlurPass.setWorldScale(2*i),this._updateSSShadowParams()}constructor(e,t,i={},r){super(t.getEngine(),e),this._allowDebugPasses=!1,this._debugPasses=[],this._shadowCastingMeshes=[],this._shadowOpacity=.8,this._enabled=!0,this._materialsWithRenderPlugin=[],this.onShadowTextureReadyObservable=new z.cP,this.onNewIblReadyObservable=new z.cP,this.voxelGridSize=1,this._renderSizeFactor=1,this._gbufferDebugEnabled=!1,this._gBufferDebugSizeParams=new W.IU(0,0,0,0),this.scene=t,this._cameras=r||[t.activeCamera];const s=new Uint8Array([0,0,0,255]);this._dummyTexture2d=new xi(s,1,1,an.TEXTUREFORMAT_RGBA,t,!1),this._dummyTexture3d=new Qb(s,1,1,1,an.TEXTUREFORMAT_RGBA,t,!1);const n={};n[qO.SCREENSPACE_DEPTH_TEXTURE_TYPE]={textureFormat:6,textureType:1},n[qO.VELOCITY_LINEAR_TEXTURE_TYPE]={textureFormat:7,textureType:2},n[qO.POSITION_TEXTURE_TYPE]={textureFormat:5,textureType:2},n[qO.NORMAL_TEXTURE_TYPE]={textureFormat:5,textureType:2};const o=t.enableGeometryBufferRenderer(void 0,14,n);o?(this._geometryBufferRenderer=o,this._geometryBufferRenderer.enableScreenspaceDepth=!0,this._geometryBufferRenderer.enableVelocityLinear=!0,this._geometryBufferRenderer.enablePosition=!0,this._geometryBufferRenderer.enableNormal=!0,this._geometryBufferRenderer.generateNormalsInWorldSpace=!0,this.shadowOpacity=i.shadowOpacity||.8,this._voxelRenderer=new Dw(this.scene,this,i?i.resolutionExp:6,void 0===i.triPlanarVoxelization||i.triPlanarVoxelization),this._importanceSamplingRenderer=new Nw(this.scene),this._voxelTracingPass=new ww(this.scene,this),this._spatialBlurPass=new Fw(this.scene,this),this._accumulationPass=new Lw(this.scene,this),this._accumulationPass.onReadyObservable.addOnce((()=>{this.onShadowTextureReadyObservable.notifyObservers()})),this.sampleDirections=i.sampleDirections||2,this.voxelShadowOpacity=i.voxelShadowOpacity??1,this.envRotation=i.envRotation??0,this.shadowRenderSizeFactor=i.shadowRenderSizeFactor||1,this.ssShadowOpacity=void 0===i.ssShadowsEnabled||i.ssShadowsEnabled?1:0,this.ssShadowDistanceScale=i.ssShadowDistanceScale||1.25,this.ssShadowSampleCount=i.ssShadowSampleCount||16,this.ssShadowStride=i.ssShadowStride||8,this.ssShadowThicknessScale=i.ssShadowThicknessScale||1,this.shadowRemanence=i.shadowRemanence??.75,this._noiseTexture=new vi.g("https://assets.babylonjs.com/textures/blue_noise/blue_noise_rgb.png",this.scene,!1,!0,1),this.scene.environmentTexture&&(this._importanceSamplingRenderer.iblSource=this.scene.environmentTexture),t.postProcessRenderPipelineManager.addPipeline(this),this.scene.onActiveCameraChanged.add(this._listenForCameraChanges.bind(this)),this.scene.onBeforeRenderObservable.add(this._updateBeforeRender.bind(this)),this._listenForCameraChanges(),this.scene.getEngine().onResizeObservable.add(this._handleResize.bind(this)),this._importanceSamplingRenderer.onReadyObservable.add((()=>{this._setPluginParameters(),this.onNewIblReadyObservable.notifyObservers()}))):Z.V.Error("Geometry buffer renderer is required for IBL shadows to work.")}_handleResize(){this._voxelRenderer.resize(),this._voxelTracingPass.resize(this.shadowRenderSizeFactor),this._spatialBlurPass.resize(this.shadowRenderSizeFactor),this._accumulationPass.resize(this.shadowRenderSizeFactor),this._setPluginParameters()}_getGBufferDebugPass(){if(this._gbufferDebugPass)return this._gbufferDebugPass;const e=this.engine.isWebGPU,t={width:this.scene.getEngine().getRenderWidth(),height:this.scene.getEngine().getRenderHeight(),samplingMode:1,engine:this.scene.getEngine(),textureType:0,textureFormat:5,uniforms:["sizeParams"],samplers:["depthSampler","normalSampler","positionSampler","velocitySampler"],reusable:!1,shaderLanguage:e?1:0,extraInitializations:(e,t)=>{e?t.push(Promise.resolve().then(i.bind(i,23008))):t.push(Promise.resolve().then(i.bind(i,64367)))}};return this._gbufferDebugPass=new ms.w("iblShadowGBufferDebug","iblShadowGBufferDebug",t),this._gbufferDebugPass.autoClear=!1,this._gbufferDebugPass.onApplyObservable.add((e=>{const t=this._geometryBufferRenderer.getTextureIndex(qO.SCREENSPACE_DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[t]);const i=this._geometryBufferRenderer.getTextureIndex(qO.NORMAL_TEXTURE_TYPE);e.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[i]);const r=this._geometryBufferRenderer.getTextureIndex(qO.POSITION_TEXTURE_TYPE);e.setTexture("positionSampler",this._geometryBufferRenderer.getGBuffer().textures[r]);const s=this._geometryBufferRenderer.getTextureIndex(qO.VELOCITY_LINEAR_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[s]),e.setVector4("sizeParams",this._gBufferDebugSizeParams),this.scene.activeCamera&&e.setFloat("maxDepth",this.scene.activeCamera.maxZ)})),this._gbufferDebugPass}_createDebugPasses(){this._debugPasses=[{pass:this._importanceSamplingRenderer.getDebugPassPP(),enabled:this.importanceSamplingDebugEnabled},{pass:this._voxelRenderer.getDebugPassPP(),enabled:this.voxelDebugEnabled},{pass:this._voxelTracingPass.getDebugPassPP(),enabled:this.voxelTracingDebugEnabled},{pass:this._spatialBlurPass.getDebugPassPP(),enabled:this.spatialBlurPassDebugEnabled},{pass:this._accumulationPass.getDebugPassPP(),enabled:this.accumulationPassDebugEnabled},{pass:this._getGBufferDebugPass(),enabled:this.gbufferDebugEnabled}];for(let e=0;ethis._debugPasses[e].pass),!0));const e=this.cameras.slice();this.scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this.name,this.cameras),this.scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this.name,e);for(let e=0;e{this._addShadowSupportToMaterial(e)})):this._addShadowSupportToMaterial(e):this.scene.materials.forEach((e=>{this._addShadowSupportToMaterial(e)}))}removeShadowReceivingMaterial(e){if(Array.isArray(e))e.forEach((e=>{const t=this._materialsWithRenderPlugin.indexOf(e);if(-1!==t){this._materialsWithRenderPlugin.splice(t,1);const i=e.pluginManager?.getPlugin(Vw.Name);i.isEnabled=!1}}));else{const t=this._materialsWithRenderPlugin.indexOf(e);-1!==t&&(this._materialsWithRenderPlugin.splice(t,1),e.pluginManager.getPlugin(Vw.Name).isEnabled=!1)}}_addShadowSupportToMaterial(e){if(!(e instanceof Gm||e instanceof Un))return;let t=e.pluginManager?.getPlugin(Vw.Name);t||(t=new Vw(e)),-1===this._materialsWithRenderPlugin.indexOf(e)&&(this._enabled&&(t.iblShadowsTexture=this._getAccumulatedTexture().getInternalTexture(),t.shadowOpacity=this.shadowOpacity),t.isEnabled=this._enabled,this._materialsWithRenderPlugin.push(e))}_setPluginParameters(){this._enabled&&this._materialsWithRenderPlugin.forEach((e=>{if(e.pluginManager){const t=e.pluginManager.getPlugin(Vw.Name);t.iblShadowsTexture=this._getAccumulatedTexture().getInternalTexture(),t.shadowOpacity=this.shadowOpacity}}))}_updateBeforeRender(){this._updateDebugPasses()}_listenForCameraChanges(){this.scene.activeCamera?.onViewMatrixChangedObservable.add((()=>{this._accumulationPass.isMoving=!0}))}isReady(){return this._noiseTexture.isReady()&&this._voxelRenderer.isReady()&&this._importanceSamplingRenderer.isReady()&&(!this._voxelTracingPass||this._voxelTracingPass.isReady())&&(!this._spatialBlurPass||this._spatialBlurPass.isReady())&&(!this._accumulationPass||this._accumulationPass.isReady())}getClassName(){return"IBLShadowsRenderPipeline"}dispose(){this._materialsWithRenderPlugin.splice(0).forEach((e=>{this.removeShadowReceivingMaterial(e)})),this._disposeEffectPasses(),this._noiseTexture.dispose(),this._voxelRenderer.dispose(),this._importanceSamplingRenderer.dispose(),this._voxelTracingPass.dispose(),this._spatialBlurPass.dispose(),this._accumulationPass.dispose(),this._dummyTexture2d.dispose(),this._dummyTexture3d.dispose(),this.onNewIblReadyObservable.clear(),this.onShadowTextureReadyObservable.clear(),super.dispose()}}class Uw extends Xb{constructor(e,t,i,r,s,n){super(e,i,r,s,n),this._beforeCompositionPostProcesses=[],this._internalTextureDirty=!1,this.enabled=!1,this.renderTargetTexture=null,this.renderTargetTexture=t}_createCompositionEffect(){this.imageProcessingPostProcess=new zO("prePassComposition",1,null,void 0,this._engine),this.imageProcessingPostProcess._updateParameters()}_checkSize(){const e=this._engine.getRenderWidth(!0),t=this._engine.getRenderHeight(!0),i=this.getRenderWidth(),r=this.getRenderHeight();i===e&&r===t||(this.resize({width:e,height:t}),this._internalTextureDirty=!0)}updateCount(e,t,i){super.updateCount(e,t,i),this._internalTextureDirty=!0}_resetPostProcessChain(){this._beforeCompositionPostProcesses.length=0}dispose(){const e=this._scene;if(super.dispose(),e&&e.prePassRenderer){const t=e.prePassRenderer.renderTargets.indexOf(this);-1!==t&&e.prePassRenderer.renderTargets.splice(t,1)}this.imageProcessingPostProcess&&this.imageProcessingPostProcess.dispose(),this.renderTargetTexture&&(this.renderTargetTexture._prePassRenderTarget=null),this._outputPostProcess&&(this._outputPostProcess.autoClear=!0,this._outputPostProcess.restoreDefaultInputTexture())}}class Gw{get generateNormalsInWorldSpace(){return this._generateNormalsInWorldSpace}set generateNormalsInWorldSpace(e){this._generateNormalsInWorldSpace!==e&&(this._generateNormalsInWorldSpace=e,this._markAllMaterialsAsPrePassDirty())}getIndex(e){return this._textureIndices[e]}get samples(){return this.defaultRT.samples}set samples(e){this.defaultRT.samples=e}get useSpecificClearForDepthTexture(){return this._useSpecificClearForDepthTexture}set useSpecificClearForDepthTexture(e){this._useSpecificClearForDepthTexture!==e&&(this._useSpecificClearForDepthTexture=e,this._isDirty=!0)}getRenderTarget(){return this._currentTarget}_setRenderTarget(e){e?this._currentTarget=e:(this._currentTarget=this.defaultRT,this._engine.currentRenderPassId=this._scene.activeCamera?.renderPassId??this._currentTarget.renderPassId)}get currentRTisSceneRT(){return this._currentTarget===this.defaultRT}_refreshGeometryBufferRendererLink(){if(this.doNotUseGeometryRendererFallback)this._geometryBuffer&&this._geometryBuffer._unlinkPrePassRenderer(),this._geometryBuffer=null,this._scene.disableGeometryBufferRenderer();else{if(this._geometryBuffer=this._scene.enableGeometryBufferRenderer(),!this._geometryBuffer)return void(this.doNotUseGeometryRendererFallback=!0);this._geometryBuffer._linkPrePassRenderer(this)}}get enabled(){return this._enabled}constructor(e){this.excludedSkinnedMesh=[],this.excludedMaterials=[],this.mrtCount=0,this._mrtTypes=[],this._mrtFormats=[],this._mrtLayout=[],this._mrtNames=[],this._textureIndices=[],this._generateNormalsInWorldSpace=!1,this._useSpecificClearForDepthTexture=!1,this._isDirty=!0,this._effectConfigurations=[],this.doNotUseGeometryRendererFallback=!0,this.renderTargets=[],this._clearColor=new H.ov(0,0,0,0),this._clearDepthColor=new H.ov(1e8,0,0,1),this._enabled=!1,this._needsCompositionForThisPass=!1,this.disableGammaTransform=!1,this._scene=e,this._engine=e.getEngine();let t=0;this._engine._caps.textureFloat&&this._engine._caps.textureFloatLinearFiltering?t=1:this._engine._caps.textureHalfFloat&&this._engine._caps.textureHalfFloatLinearFiltering&&(t=2);for(let e=0;e0&&(this._useSpecificClearForDepthTexture&&5===this._mrtLayout[s]?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),r.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(r)}_resetLayout(){for(let e=0;enull!=e)),this._scene.autoClear=!0;const r=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!r&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;const s=this._getFirstPostProcess(this._postProcessesSourceForThisPass),n=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0];let o=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||r,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),n?o=n:this._needsCompositionForThisPass?o=e.imageProcessingPostProcess:s&&(o=s),this._bindFrameBuffer(),this._linkInternalTexture(e,o)}_linkInternalTexture(e,t){t&&(t.autoClear=!1,t.inputTexture=e.renderTarget),e._outputPostProcess!==t&&(e._outputPostProcess&&this._unlinkInternalTexture(e),e._outputPostProcess=t),e._internalTextureDirty&&(this._updateGeometryBufferLayout(),e._internalTextureDirty=!1)}_unlinkInternalTexture(e){e._outputPostProcess&&(e._outputPostProcess.autoClear=!0,e._outputPostProcess.restoreDefaultInputTexture(),e._outputPostProcess=null)}_needsImageProcessing(){for(let e=0;enull!=e)),e)){for(let r=0;r=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw(0,Je.n)("PrePassRendererSceneComponent")},Gw.TextureFormats=[{purpose:0,type:2,format:5,name:"prePass_Irradiance"},{purpose:1,type:2,format:5,name:"prePass_Position"},{purpose:2,type:0,format:5,name:"prePass_Velocity"},{purpose:3,type:0,format:5,name:"prePass_Reflectivity"},{purpose:4,type:2,format:5,name:"prePass_Color"},{purpose:5,type:1,format:6,name:"prePass_Depth"},{purpose:6,type:2,format:5,name:"prePass_Normal"},{purpose:7,type:0,format:5,name:"prePass_Albedo"},{purpose:8,type:0,format:5,name:"prePass_WorldNormal"},{purpose:9,type:2,format:5,name:"prePass_LocalPosition"},{purpose:10,type:1,format:6,name:"prePass_ScreenDepth"},{purpose:11,type:2,format:5,name:"prePass_VelocityLinear"}],Object.defineProperty(oi.Z.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(e){e&&e.isSupported&&(this._prePassRenderer=e)},enumerable:!0,configurable:!0}),oi.Z.prototype.enablePrePassRenderer=function(){return this._prePassRenderer||(this._prePassRenderer=new Gw(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,Z.V.Error("PrePassRenderer needs WebGL 2 support.\nMaybe you tried to use the following features that need the PrePassRenderer :\n + Subsurface Scattering"))),this._prePassRenderer},oi.Z.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class zw{constructor(e){this.name=Ut.v.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(Ut.v.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(Ut.v.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(Ut.v.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(Ut.v.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(Ut.v.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(Ut.v.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(Ut.v.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(Ut.v.STEP_AFTERRENDERINGMESH_PREPASS,this,this._afterRenderingMeshStage)}_beforeRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._beforeDraw(void 0,t,i))}_afterRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&this.scene.prePassRenderer._afterDraw(t,i)}_beforeRenderTargetClearStage(e){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(e._prePassRenderTarget||(e._prePassRenderTarget=this.scene.prePassRenderer._createRenderTarget(e.name+"_prePassRTT",e)),this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._clear())}_beforeCameraDraw(e){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._beforeDraw(e))}_afterCameraDraw(){this.scene.prePassRenderer&&this.scene.prePassRenderer._afterDraw()}_beforeClearStage(){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._clear())}_beforeRenderingMeshStage(e,t,i,r){if(!r)return;const s=e.getScene();s.prePassRenderer&&s.prePassRenderer.bindAttachmentsForEffect(r,t)}_afterRenderingMeshStage(e){const t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){}dispose(){this.scene.disablePrePassRenderer()}}Gw._SceneComponentInitialization=e=>{let t=e._getComponent(Ut.v.NAME_PREPASSRENDERER);t||(t=new zw(e),e._addComponent(t))};Cs.l.IncludesShadersStore.fibonacci="#define rcp(x) 1./x\n#define GOLDEN_RATIO 1.618033988749895\n#define TWO_PI 6.2831855\nvec2 Golden2dSeq(int i,float n)\n{return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));}\nvec2 SampleDiskGolden(int i,int sampleCount)\n{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}",i(34001);Cs.l.IncludesShadersStore.diffusionProfile="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";Cs.l.ShadersStore.subSurfaceScatteringPixelShader="#include\n#include\n#include\n#include\nvarying 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;\n#define rcp(x) 1./x\n#define Sq(x) x*x\n#define SSS_BILATERAL_FILTER true\nvec3 EvalBurleyDiffusionProfile(float r,vec3 S)\n{vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); \nvec3 expSum=exp_13*(1.+exp_13*exp_13); \nreturn (S*rcp(8.*PI))*expSum; }\nvec2 SampleBurleyDiffusionProfile(float u,float rcpS)\n{u=1.-u; \nfloat g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); \nfloat p=(g*n)*n; \nfloat c=1.+p+n; \nfloat d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); \nfloat x=(3./LOG2_E)*log2(c)-d; \nfloat rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; \nreturn vec2(r,rcpPdf);}\nvec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf)\n{\n#ifndef SSS_BILATERAL_FILTER\nz=0.;\n#endif\nfloat r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf;\n#if SSS_CLAMP_ARTIFACT\nreturn clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0);\n#else\nreturn EvalBurleyDiffusionProfile(r,S)*area;\n#endif\n}\nvoid EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm,\nfloat phase,inout vec3 totalIrradiance,inout vec3 totalWeight)\n{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; \nfloat cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; \nvec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; \nfloat 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))\n{float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;}\nelse\n{}}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{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)\n{centerDepth=texture2D(depthSampler,vUV).r;}\nif (!passedStencilTest) { \ngl_FragColor=inputColor;return;}\nfloat 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; \nvec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; \nfloat 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)\n{\n#ifdef DEBUG_SSS_SAMPLES\nvec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return;\n#endif\ngl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;}\n#ifdef DEBUG_SSS_SAMPLES\nvec3 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;\n#endif\nfloat phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); \nvec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i{if(!t.prePassRenderer||!t.subSurfaceConfiguration)return void Z.V.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");const i=this.texelSize;e.setFloat("metersPerUnit",t.subSurfaceConfiguration.metersPerUnit),e.setFloat2("texelSize",i.x,i.y),e.setTexture("irradianceSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(0)]),e.setTexture("depthSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(5)]),e.setTexture("albedoSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(7)]),e.setFloat2("viewportSize",Math.tan(t.activeCamera.fov/2)*t.getEngine().getAspectRatio(t.activeCamera,!0),Math.tan(t.activeCamera.fov/2)),e.setArray3("diffusionS",t.subSurfaceConfiguration.ssDiffusionS),e.setArray("diffusionD",t.subSurfaceConfiguration.ssDiffusionD),e.setArray("filterRadii",t.subSurfaceConfiguration.ssFilterRadii)}))}}class Hw{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=Ut.v.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new H.v9(1,1,1)),this._scene=e,Hw._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return Z.V.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw(0,Je.n)("SubSurfaceSceneComponent")},ci(Ut.v.NAME_SUBSURFACE,((e,t)=>{if(void 0!==e.ssDiffusionProfileColors&&null!==e.ssDiffusionProfileColors&&(t.enableSubSurfaceForPrePass(),t.subSurfaceConfiguration))for(let i=0,r=e.ssDiffusionProfileColors.length;i{let t=e._getComponent(Ut.v.NAME_SUBSURFACE);t||(t=new Xw(e),e._addComponent(t))},oi.Z.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new qw(this)),this._outlineRenderer},Object.defineProperty(Yt.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(Yt.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});class qw{get shaderLanguage(){return this._shaderLanguage}constructor(e){this.name=Ut.v.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this._shaderLanguage=0,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let e=0;e<4;++e)this._passIdForDrawWrapper[e]=this._engine.createRenderPassId(`Outline Renderer (${e})`);this._engine.isWebGPU&&(this._shaderLanguage=1)}register(){this.scene._beforeRenderingMeshStage.registerStep(Ut.v.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(Ut.v.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e{f.setMatrix("world",t)})),n.setZOffset(0),n.setZOffsetUnits(0)}isReady(e,t,r){r=r??this._passIdForDrawWrapper[0];const s=[],n=[st.R.PositionKind,st.R.NormalKind],o=e.getMesh(),a=e.getMaterial();if(!a)return!1;const l=o.getScene();a.needAlphaTesting()&&(s.push("#define ALPHATEST"),o.isVerticesDataPresent(st.R.UVKind)&&(n.push(st.R.UVKind),s.push("#define UV1")),o.isVerticesDataPresent(st.R.UV2Kind)&&(n.push(st.R.UV2Kind),s.push("#define UV2"))),a.useLogarithmicDepth&&s.push("#define LOGARITHMICDEPTH"),(0,Ln.tv)(a,l,s);const h=new Tn;if(o.useBones&&o.computeBonesUsingShaders&&o.skeleton){n.push(st.R.MatricesIndicesKind),n.push(st.R.MatricesWeightsKind),o.numBoneInfluencers>4&&(n.push(st.R.MatricesIndicesExtraKind),n.push(st.R.MatricesWeightsExtraKind));const e=o.skeleton;s.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers),o.numBoneInfluencers>0&&h.addCPUSkinningFallback(0,o),e.isUsingTextureForMatrices?s.push("#define BONETEXTURE"):s.push("#define BonesPerMesh "+(e.bones.length+1))}else s.push("#define NUM_BONE_INFLUENCERS 0");const c=o.morphTargetManager;let u=0;c&&(u=c.numMaxInfluencers||c.numInfluencers,u>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+u),c.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),(0,Bt.MF)(n,o,u))),t&&(s.push("#define INSTANCES"),(0,Bt.te)(n),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES"));const d=o.bakedVertexAnimationManager;d&&d.isEnabled&&(s.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&n.push("bakedVertexAnimationSettingsInstanced"));const f=e._getDrawWrapper(r,!0),p=f.defines,_=s.join("\n");if(p!==_){const e=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","boneTextureWidth","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],t=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"];(0,Ln.TV)(e),f.setEffect(this.scene.getEngine().createEffect("outline",{attributes:n,uniformsNames:e,uniformBuffersNames:[],samplers:t,defines:_,fallbacks:h,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:u},shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,55515)),Promise.resolve().then(i.bind(i,18789))]):await Promise.all([Promise.resolve().then(i.bind(i,32192)),Promise.resolve().then(i.bind(i,65038))])}},this.scene.getEngine()),_)}return f.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){const r=t.getMaterial();r&&r.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(qw._StencilReference),this._engine.setStencilFunctionReference(qw._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),r&&r.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){const e=this._engine.getAlphaMode(),r=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(e),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))}}qw._StencilReference=4;var Yw,Kw=i(20005);class jw{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(){return!!this.vertexBuffers?.velocity}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}get shaderLanguage(){return this._shaderLanguage}constructor(e,t){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new z.cP,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._shaderLanguage=0,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null,this._shaderLanguage=t??(this._engine.isWebGPU?1:0)}_createEffects(){const e=["view","projection","particleRadius","size"],t=["position","offset"],r=[];this._effectsAreDirty=!1,this.useVelocity&&(t.push("velocity"),r.push("#define FLUIDRENDERING_VELOCITY")),this._scene.useRightHandedSystem&&r.push("#define FLUIDRENDERING_RHS"),this._depthEffectWrapper=new Yp.$({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:r,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,27014)),Promise.resolve().then(i.bind(i,40264))]):await Promise.all([Promise.resolve().then(i.bind(i,49377)),Promise.resolve().then(i.bind(i,21959))])}}),e.push("particleAlpha"),this._thicknessEffectWrapper=new Yp.$({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleThickness",fragmentShader:"fluidRenderingParticleThickness",attributeNames:["position","offset"],uniformNames:e,samplerNames:[],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await Promise.all([Promise.resolve().then(i.bind(i,64615)),Promise.resolve().then(i.bind(i,45261))]):await Promise.all([Promise.resolve().then(i.bind(i,3420)),Promise.resolve().then(i.bind(i,28566))])}})}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||0===e)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||0===e)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(){this._depthEffectWrapper?.dispose(!1),this._thicknessEffectWrapper?.dispose(!1),this.onParticleSizeChanged.clear()}}class $w extends jw{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,i){super(e,i),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 Qw{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,null!==this._blurPostProcesses)){const e=this._blurPostProcesses[0],t=this._blurPostProcesses[1];this._blurPostProcesses=[];for(let i=0;i<2*this._blurNumIterations;++i)this._blurPostProcesses[i]=1&i?t:e}}get renderTarget(){return this._rt}get renderTargetBlur(){return this._rtBlur}get texture(){return this._texture}get textureBlur(){return this._textureBlurred}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,r,s,n,o=1,a=6,l=1,h=6,c=!1,u=null,d=!0,f=1,p){this.enableBlur=!0,this.blurSizeDivisor=1,this.blurFilterSize=7,this._blurNumIterations=3,this.blurMaxFilterSize=100,this.blurDepthScale=10,this.particleSize=.02,this.onDisposeObservable=new z.cP,this._shaderLanguage=0,this._name=e,this._scene=t,this._camera=u,this._engine=t.getEngine(),this._width=i,this._height=r,this._blurTextureSizeX=s,this._blurTextureSizeY=n,this._textureType=o,this._textureFormat=a,this._blurTextureType=l,this._blurTextureFormat=h,this._useStandardBlur=c,this._generateDepthBuffer=d,this._samples=f,this._postProcessRunningIndex=0,this.enableBlur=0!==s&&0!==n,this._rt=null,this._texture=null,this._rtBlur=null,this._textureBlurred=null,this._blurPostProcesses=null,this._shaderLanguage=p??(this._engine.isWebGPU?1:0)}initialize(){if(this.dispose(),this._createRenderTarget(),this.enableBlur&&this._texture){const[e,t,i]=this._createBlurPostProcesses(this._texture,this._blurTextureType,this._blurTextureFormat,this.blurSizeDivisor,this._name,this._useStandardBlur);this._rtBlur=e,this._textureBlurred=t,this._blurPostProcesses=i}}applyBlurPostProcesses(){this.enableBlur&&this._blurPostProcesses&&(this._postProcessRunningIndex=0,this._scene.postProcessManager.directRender(this._blurPostProcesses,this._rtBlur,!0),this._engine.unBindFramebuffer(this._rtBlur))}_createRenderTarget(){this._rt=this._engine.createRenderTargetTexture({width:this._width,height:this._height},{generateMipMaps:!1,type:this._textureType,format:this._textureFormat,samplingMode:1,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTT-${this._name}`});const e=this._rt.texture;e.incrementReferences(),this._texture=new vi.g(null,this._scene),this._texture.name="rtt"+this._name,this._texture._texture=e,this._texture.wrapU=vi.g.CLAMP_ADDRESSMODE,this._texture.wrapV=vi.g.CLAMP_ADDRESSMODE,this._texture.anisotropicFilteringLevel=1}_createBlurPostProcesses(e,t,r,s,n,o=!1){const a=this._scene.getEngine(),l=new W.I9(Math.floor(this._blurTextureSizeX/s),Math.floor(this._blurTextureSizeY/s)),h=1===t&&a.getCaps().textureFloatLinearFiltering||2===t&&a.getCaps().textureHalfFloatLinearFiltering,c=this._engine.createRenderTargetTexture({width:l.x,height:l.y},{generateMipMaps:!1,type:t,format:r,samplingMode:h?2:1,generateDepthBuffer:!1,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTTBlur-${n}`}),u=c.texture;u.incrementReferences();const d=new vi.g(null,this._scene);if(d.name="rttBlurred"+n,d._texture=u,d.wrapU=vi.g.CLAMP_ADDRESSMODE,d.wrapV=vi.g.CLAMP_ADDRESSMODE,d.anisotropicFilteringLevel=1,o){const s=new ms.w("BilateralBlurX","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,a,!0,null,t,void 0,void 0,void 0,r,this._shaderLanguage,(async()=>{1===this.shaderLanguage?await Promise.resolve().then(i.bind(i,5769)):await Promise.resolve().then(i.bind(i,53360))}));s.samples=this._samples,s.externalTextureSamplerBinding=!0,s.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",s.inputTexture.texture),t.setInt("filterSize",this.blurFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++})),s.onSizeChangedObservable.add((()=>{s._textures.forEach((e=>{e.texture.wrapU=vi.g.CLAMP_ADDRESSMODE,e.texture.wrapV=vi.g.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(s);const n=new ms.w("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,a,!0,null,t,void 0,void 0,void 0,r,this._shaderLanguage,(async()=>{1===this.shaderLanguage?await Promise.resolve().then(i.bind(i,5769)):await Promise.resolve().then(i.bind(i,53360))}));n.samples=this._samples,n.onApplyObservable.add((e=>{e.setInt("filterSize",this.blurFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++})),n.onSizeChangedObservable.add((()=>{n._textures.forEach((e=>{e.texture.wrapU=vi.g.CLAMP_ADDRESSMODE,e.texture.wrapV=vi.g.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(n),s.autoClear=!1,n.autoClear=!1;const o=[];for(let e=0;e<2*this._blurNumIterations;++e)o[e]=1&e?n:s;return[c,d,o]}{const s=["maxFilterSize","blurDir","projectedParticleConstant","depthThreshold"],n=new ms.w("BilateralBlurX","fluidRenderingBilateralBlur",s,null,1,null,1,a,!0,null,t,void 0,void 0,void 0,r,this._shaderLanguage,(async()=>{1===this.shaderLanguage?await Promise.resolve().then(i.bind(i,92862)):await Promise.resolve().then(i.bind(i,93705))}));n.samples=this._samples,n.externalTextureSamplerBinding=!0,n.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",n.inputTexture.texture),t.setInt("maxFilterSize",this.blurMaxFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),t.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),t.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++})),n.onSizeChangedObservable.add((()=>{n._textures.forEach((e=>{e.texture.wrapU=vi.g.CLAMP_ADDRESSMODE,e.texture.wrapV=vi.g.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(n);const o=new ms.w("BilateralBlurY","fluidRenderingBilateralBlur",s,null,1,null,1,a,!0,null,t,void 0,void 0,void 0,r,this._shaderLanguage,(async()=>{1===this.shaderLanguage?await Promise.resolve().then(i.bind(i,92862)):await Promise.resolve().then(i.bind(i,93705))}));o.samples=this._samples,o.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++})),o.onSizeChangedObservable.add((()=>{o._textures.forEach((e=>{e.texture.wrapU=vi.g.CLAMP_ADDRESSMODE,e.texture.wrapV=vi.g.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(o),n.autoClear=!1,o.autoClear=!1;const l=[];for(let e=0;e<2*this._blurNumIterations;++e)l[e]=1&e?o:n;return[c,d,l]}}_fixReusablePostProcess(e){e.isReusable()&&(e.onActivateObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})),e.onApplyObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})))}_getProjectedParticleConstant(){return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan((this._camera?.fov??45*Math.PI/180)/2)}_getDepthThreshold(){return this.particleSize/2*this.blurDepthScale}dispose(){this.onDisposeObservable.hasObservers()&&this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._rt?.dispose(),this._rt=null,this._texture?.dispose(),this._texture=null,this._rtBlur?.dispose(),this._rtBlur=null,this._textureBlurred?.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}!function(e){e[e.DepthTexture=0]="DepthTexture",e[e.DepthBlurredTexture=1]="DepthBlurredTexture",e[e.ThicknessTexture=2]="ThicknessTexture",e[e.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",e[e.DiffuseTexture=4]="DiffuseTexture",e[e.Normals=5]="Normals",e[e.DiffuseRendering=6]="DiffuseRendering"}(Yw||(Yw={}));class Zw{get needInitialization(){return this._needInitialization}get generateDiffuseTexture(){return this._generateDiffuseTexture}set generateDiffuseTexture(e){this._generateDiffuseTexture!==e&&(this._generateDiffuseTexture=e,this._needInitialization=!0)}get debugFeature(){return this._debugFeature}set debugFeature(e){this._debugFeature!==e&&(this._needInitialization=!0,this._debugFeature=e)}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._needInitialization=!0)}get environmentMap(){return this._environmentMap}set environmentMap(e){this._environmentMap!==e&&(this._needInitialization=!0,this._environmentMap=e)}get enableBlurDepth(){return this._enableBlurDepth}set enableBlurDepth(e){this._enableBlurDepth!==e&&(this._enableBlurDepth=e,this._needInitialization=!0)}get blurDepthSizeDivisor(){return this._blurDepthSizeDivisor}set blurDepthSizeDivisor(e){this._blurDepthSizeDivisor!==e&&(this._blurDepthSizeDivisor=e,this._needInitialization=!0)}get blurDepthFilterSize(){return this._blurDepthFilterSize}set blurDepthFilterSize(e){this._blurDepthFilterSize!==e&&(this._blurDepthFilterSize=e,this._setBlurParameters())}get blurDepthNumIterations(){return this._blurDepthNumIterations}set blurDepthNumIterations(e){this._blurDepthNumIterations!==e&&(this._blurDepthNumIterations=e,this._setBlurParameters())}get blurDepthMaxFilterSize(){return this._blurDepthMaxFilterSize}set blurDepthMaxFilterSize(e){this._blurDepthMaxFilterSize!==e&&(this._blurDepthMaxFilterSize=e,this._setBlurParameters())}get blurDepthDepthScale(){return this._blurDepthDepthScale}set blurDepthDepthScale(e){this._blurDepthDepthScale!==e&&(this._blurDepthDepthScale=e,this._setBlurParameters())}get enableBlurThickness(){return this._enableBlurThickness}set enableBlurThickness(e){this._enableBlurThickness!==e&&(this._enableBlurThickness=e,this._needInitialization=!0)}get blurThicknessSizeDivisor(){return this._blurThicknessSizeDivisor}set blurThicknessSizeDivisor(e){this._blurThicknessSizeDivisor!==e&&(this._blurThicknessSizeDivisor=e,this._needInitialization=!0)}get blurThicknessFilterSize(){return this._blurThicknessFilterSize}set blurThicknessFilterSize(e){this._blurThicknessFilterSize!==e&&(this._blurThicknessFilterSize=e,this._setBlurParameters())}get blurThicknessNumIterations(){return this._blurThicknessNumIterations}set blurThicknessNumIterations(e){this._blurThicknessNumIterations!==e&&(this._blurThicknessNumIterations=e,this._setBlurParameters())}get useFixedThickness(){return this._useFixedThickness}set useFixedThickness(e){this._useFixedThickness!==e&&(this._useFixedThickness=e,this._needInitialization=!0)}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&(this._useVelocity=e,this._needInitialization=!0,this._onUseVelocityChanged.notifyObservers(this))}get depthMapSize(){return this._depthMapSize}set depthMapSize(e){this._depthMapSize!==e&&(this._depthMapSize=e,this._needInitialization=!0)}get thicknessMapSize(){return this._thicknessMapSize}set thicknessMapSize(e){this._thicknessMapSize!==e&&(this._thicknessMapSize=e,this._needInitialization=!0)}get diffuseMapSize(){return this._diffuseMapSize}set diffuseMapSize(e){this._diffuseMapSize!==e&&(this._diffuseMapSize=e,this._needInitialization=!0)}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._needInitialization=!0)}get compositeMode(){return this._compositeMode}set compositeMode(e){this._compositeMode!==e&&(this._compositeMode=e,this._needInitialization=!0)}get camera(){return this._camera}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i){this._generateDiffuseTexture=!1,this.fluidColor=new H.v9(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new W.Pq(-2,-1,1).normalize(),this._debugFeature=1,this._debug=!1,this._enableBlurDepth=!0,this._blurDepthSizeDivisor=1,this._blurDepthFilterSize=7,this._blurDepthNumIterations=3,this._blurDepthMaxFilterSize=100,this._blurDepthDepthScale=10,this._enableBlurThickness=!0,this._blurThicknessSizeDivisor=1,this._blurThicknessFilterSize=5,this._blurThicknessNumIterations=1,this._useFixedThickness=!1,this._onUseVelocityChanged=new z.cP,this._useVelocity=!1,this._depthMapSize=null,this._thicknessMapSize=null,this._diffuseMapSize=null,this._samples=1,this._compositeMode=!1,this._shaderLanguage=0,this._scene=e,this._engine=e.getEngine(),this._camera=t??e.activeCamera,this._needInitialization=!0,this._bgDepthTexture=null,this._invProjectionMatrix=new W.uq,this._depthClearColor=new H.ov(1e6,1e6,1e6,1),this._thicknessClearColor=new H.ov(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null,this._shaderLanguage=i??(this._engine.isWebGPU?1:0)}_initialize(){this.dispose(),this._needInitialization=!1;const e=this._depthMapSize??this._engine.getRenderWidth(),t=null!==this._depthMapSize?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new Qw("Depth",this._scene,e,t,e,t,1,7,1,7,!1,this._camera,!0,this._samples,this._shaderLanguage),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){const e=this._diffuseMapSize??this._engine.getRenderWidth(),t=null!==this._diffuseMapSize?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new Qw("Diffuse",this._scene,e,t,0,0,0,5,0,5,!0,this._camera,!0,this._samples,this._shaderLanguage),this._initializeRenderTarget(this._diffuseRenderTarget)}const i=this._thicknessMapSize??this._engine.getRenderWidth(),r=null!==this._thicknessMapSize?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new Qw("Thickness",this._scene,i,r,i,r,2,6,2,6,!0,this._camera,!1,this._samples,this._shaderLanguage),this._initializeRenderTarget(this._thicknessRenderTarget)),this._createLiquidRenderingPostProcess()}_setBlurParameters(e=null){null!==e&&e!==this._depthRenderTarget||this._setBlurDepthParameters(),null!==e&&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"],r=["depthSampler"],s=[];if(this.dispose(!0),!this._camera)return;const n=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,o=new W.I9(1/n.getSize().width,1/n.getSize().height);this._scene.useRightHandedSystem&&s.push("#define FLUIDRENDERING_RHS"),null!==this._environmentMap&&(this._environmentMap??this._scene.environmentTexture)&&(r.push("reflectionSampler"),s.push("#define FLUIDRENDERING_ENVIRONMENT")),this._diffuseRenderTarget?(r.push("diffuseSampler"),s.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):t.push("diffuseColor"),this._useVelocity&&(r.push("velocitySampler"),s.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(t.push("thickness"),r.push("bgDepthSampler"),s.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(t.push("minimumThickness"),r.push("thicknessSampler")),this._compositeMode&&s.push("#define FLUIDRENDERING_COMPOSITE_MODE"),this._debug&&(s.push("#define FLUIDRENDERING_DEBUG"),5===this._debugFeature?s.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):6===this._debugFeature?s.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(s.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),r.push("debugSampler"),0!==this._debugFeature&&1!==this._debugFeature||s.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new ms.w("FluidRendering","fluidRenderingRender",t,r,1,null,2,e,!1,null,0,void 0,void 0,!0,void 0,this._shaderLanguage,(async()=>{1===this._shaderLanguage?await Promise.resolve().then(i.bind(i,37009)):await Promise.resolve().then(i.bind(i,35116))})),this._renderPostProcess.updateEffect(s.join("\n")),this._renderPostProcess.samples=this._samples;const a=e,l=a.setTextureSampler;this._renderPostProcess.onApplyObservable.add((e=>{if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),l&&l.call(a,"textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(e.setTexture("depthSampler",this._depthRenderTarget.textureBlur),l&&l.call(a,"depthSamplerSampler",this._depthRenderTarget.textureBlur?.getInternalTexture()??null)):(e.setTexture("depthSampler",this._depthRenderTarget.texture),l&&l.call(a,"depthSamplerSampler",this._depthRenderTarget.texture?.getInternalTexture()??null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(e.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),l&&l.call(a,"diffuseSamplerSampler",this._diffuseRenderTarget.textureBlur?.getInternalTexture()??null)):(e.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),l&&l.call(a,"diffuseSamplerSampler",this._diffuseRenderTarget.texture?.getInternalTexture()??null)):e.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(e.setFloat("thickness",this.minimumThickness),e._bindTexture("bgDepthSampler",this._bgDepthTexture),l&&l.call(a,"bgDepthSamplerSampler",this._bgDepthTexture??null)):(this._thicknessRenderTarget.enableBlur?(e.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),l&&l.call(a,"thicknessSamplerSampler",this._thicknessRenderTarget.textureBlur?.getInternalTexture()??null)):(e.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),l&&l.call(a,"thicknessSamplerSampler",this._thicknessRenderTarget.texture?.getInternalTexture()??null)),e.setFloat("minimumThickness",this.minimumThickness)),null!==this._environmentMap){const t=this._environmentMap??this._scene.environmentTexture;t&&(e.setTexture("reflectionSampler",t),l&&l.call(a,"reflectionSamplerSampler",t?.getInternalTexture()??null))}if(e.setMatrix("viewMatrix",this._scene.getViewMatrix()),e.setMatrix("invProjectionMatrix",this._invProjectionMatrix),e.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),e.setVector2("texelSize",o),e.setFloat("density",this.density),e.setFloat("refractionStrength",this.refractionStrength),e.setFloat("fresnelClamp",this.fresnelClamp),e.setFloat("specularPower",this.specularPower),e.setVector3("dirLight",this.dirLight),e.setFloat("cameraFar",this._camera.maxZ),this._debug){let t=null;switch(this._debugFeature){case 0:t=this._depthRenderTarget.texture;break;case 1:t=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case 2:t=this._thicknessRenderTarget?.texture??null;break;case 3:t=this._thicknessRenderTarget?.enableBlur?this._thicknessRenderTarget?.textureBlur??null:this._thicknessRenderTarget?.texture??null;break;case 4:this._diffuseRenderTarget&&(t=this._diffuseRenderTarget.texture)}5!==this._debugFeature&&(e.setTexture("debugSampler",t),l&&l.call(a,"debugSamplerSampler",t?.getInternalTexture()??null))}}))}_clearTargets(){this._depthRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),this._engine.clear(this._depthClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),this._diffuseRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),this._thicknessRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!1,!1),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget))}_render(e){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),this._depthRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),this._diffuseRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),this._thicknessRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),this._depthRenderTarget?.applyBlurPostProcesses(),this._diffuseRenderTarget?.applyBlurPostProcesses(),this._thicknessRenderTarget?.applyBlurPostProcesses(),t&&this._engine.bindFramebuffer(t)}dispose(e=!1){e||(this._depthRenderTarget?.dispose(),this._depthRenderTarget=null,this._diffuseRenderTarget?.dispose(),this._diffuseRenderTarget=null,this._thicknessRenderTarget?.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),this._renderPostProcess?.dispose(),this._renderPostProcess=null,this._onUseVelocityChanged.clear(),this._needInitialization=!1}}class Jw extends jw{getClassName(){return"FluidRenderingObjectCustomParticles"}get vertexBuffers(){return this._vertexBuffers}constructor(e,t,i,r){super(e,r),this._numParticles=i,this._diffuseEffectWrapper=null,this._vertexBuffers={},this.addBuffers(t)}addBuffers(e){for(const t in e){let i,r=!0;switch(t){case"velocity":i=3;break;case"offset":r=!1}this._vertexBuffers[t]=new st.R(this._engine,e[t],t,!0,!1,i,r)}}_createEffects(){super._createEffects(),this._diffuseEffectWrapper=new Yp.$({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:["position","offset","color"],uniformNames:["view","projection","size"],samplerNames:[],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{1===this._shaderLanguage?await Promise.resolve().then(i.bind(i,89753)):await Promise.resolve().then(i.bind(i,76558))}})}isReady(){return this._vertexBuffers.offset||(this._vertexBuffers.offset=new st.R(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&(this._diffuseEffectWrapper?.effect.isReady()??!1)}get numParticles(){return this._numParticles}setNumParticles(e){this._numParticles=e}renderDiffuseTexture(){const e=this.numParticles;if(!this._diffuseEffectWrapper||0===e)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()),null!==this._particleSize&&i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}dispose(){super.dispose(),this._diffuseEffectWrapper?.dispose();for(const e in this._vertexBuffers)this._vertexBuffers[e].dispose();this._vertexBuffers={}}}class eN{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,r=1){this._engine=e,this._copyTextureToTexture=new Kp(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:r,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"}),this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil").label=`FluidDepthTextureCopy${t}x${i}x${r}`}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}}function tN(e){return!!e.particleSystem}function iN(e){return!!e.addBuffers}Object.defineProperty(oi.Z.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(e){this._fluidRenderer=e},enumerable:!0,configurable:!0}),oi.Z.prototype.enableFluidRenderer=function(){return this._fluidRenderer||(this._fluidRenderer=new sN(this)),this._fluidRenderer},oi.Z.prototype.disableFluidRenderer=function(){this._fluidRenderer?.dispose(),this._fluidRenderer=null};class rN{constructor(e){this.name=Ut.v.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(Ut.v.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(Ut.v.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)}_gatherActiveCameraRenderTargets(e){this.scene.fluidRenderer?._prepareRendering()}_afterCameraDraw(e){this.scene.fluidRenderer?._render(e)}rebuild(){const e=this.scene.fluidRenderer;if(!e)return;const t=new Set;for(let i=0;i{e._rebuild()}))}dispose(){this.scene.disableFluidRenderer()}}class sN{static _SceneComponentInitialization(e){let t=e._getComponent(Ut.v.NAME_FLUIDRENDERER);t||(t=new rN(e),e._addComponent(t))}get shaderLanguage(){return this._shaderLanguage}constructor(e){this._shaderLanguage=0,this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,sN._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add((()=>{this._initialize()})),this._engine.isWebGPU&&(this._shaderLanguage=1)}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){const t=this._getParticleSystemIndex(e);return-1!==t?this.renderObjects[t]:null}addParticleSystem(e,t,i,r){const s=new $w(this._scene,e,this._shaderLanguage);s.onParticleSizeChanged.add((()=>this._setParticleSizeForRenderTargets())),i||(i=new Zw(this._scene,r,this._shaderLanguage),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add((()=>this._setUseVelocityForRenderObject())),void 0!==t&&(i.generateDiffuseTexture=t);const n={object:s,targetRenderer:i};return this.renderObjects.push(n),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),n}addCustomParticles(e,t,i,r,s){const n=new Jw(this._scene,e,t,this._shaderLanguage);n.onParticleSizeChanged.add((()=>this._setParticleSizeForRenderTargets())),r||(r=new Zw(this._scene,s,this._shaderLanguage),this.targetRenderers.push(r)),r._onUseVelocityChanged.hasObservers()||r._onUseVelocityChanged.add((()=>this._setUseVelocityForRenderObject())),void 0!==i&&(r.generateDiffuseTexture=i);const o={object:n,targetRenderer:r};return this.renderObjects.push(o),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),o}removeRenderObject(e,t=!0){const i=this.renderObjects.indexOf(e);return-1!==i&&(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 t=0;t{s.inputTexture.depthStencilTexture||s.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,n[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${s.name}`);for(const e of n){const t=e._thicknessRenderTarget?.renderTarget,i=t?.texture;if(t&&i){const e=i.width+"_"+i.height;let r=o[e];r||(r=o[e]=new eN(this._engine,i.width,i.height)),r.depthRTWrapper.shareDepth(t)}}}))}t=this._cameras.keys();for(let i=t.next();!0!==i.done;i=t.next()){const t=i.value,r=this._cameras.get(t)[1],s=e.get(t);if(s)for(const e in r)s[1][e]||r[e].dispose();else for(const e in r)r[e].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){const e=new Map;for(let t=0;t{t._depthRenderTarget&&(t._depthRenderTarget.particleSize=e)}))}_setUseVelocityForRenderObject(){for(const e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(const e of this.targetRenderers)if(e.needInitialization)return void this._initialize()}_render(e){for(let t=0;t{const t=e[1];for(const e in t)t[e].dispose()})),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}var nN=i(49377),oN=i(21959),aN=i(3420),lN=i(28566);const hN="fluidRenderingParticleDiffuseVertexShader",cN="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;}\n";Cs.l.ShadersStore[hN]=cN;const uN={name:hN,shader:cN};var dN=i(76558),fN=i(93705),pN=i(53360),_N=i(35116),mN=i(27014),gN=i(40264),vN=i(64615),xN=i(45261);const bN="fluidRenderingParticleDiffuseVertexShader",SN="attribute position: vec3f;attribute offset: vec2f;attribute color: vec4f;uniform view: mat4x4f;uniform projection: mat4x4f;uniform size: vec2f;varying uv: vec2f;varying diffuseColor: vec3f;@vertex\nfn main(input: VertexInputs)->FragmentInputs {var cornerPos: vec3f=vec3f(\nvec2f(input.offset.x-0.5,input.offset.y-0.5)*uniforms.size,\n0.0\n);var viewPos: vec3f=(uniforms.view*vec4f(input.position,1.0)).xyz+cornerPos;vertexOutputs.position=uniforms.projection*vec4f(viewPos,1.0);vertexOutputs.uv=input.offset;vertexOutputs.diffuseColor=input.color.rgb;}\n";Cs.l.ShadersStoreWGSL[bN]=SN;const TN={name:bN,shader:SN};var CN=i(89753),yN=i(92862),EN=i(5769),PN=i(37009);class AN{get enable(){return this._enable}set enable(e){this._enable!==e&&(this._enable=e,this._customRenderTarget(e))}get positionWorldTexture(){return this._mrt.textures[0]}get normalWorldTexture(){return this._mrt.textures[1]}get fluxTexture(){return this._mrt.textures[2]}get renderList(){return this._mrt.renderList}get light(){return this._light}constructor(e,t,i={width:512,height:512}){this._lightTransformMatrix=W.uq.Identity(),this._enable=!1,this.forceUpdateLightParameters=!1,this._scene=e,this._light=t,this._textureDimensions=i,this._regularMatToMatWithPlugin=new Map,this._counters=[{name:"RSM Generation "+t.name,value:0}],this._createMultiRenderTarget(),this._recomputeLightTransformationMatrix(),this.enable=!0}setTextureDimensions(e){const t=this._mrt.renderList;this._textureDimensions=e,this._disposeMultiRenderTarget(),this._createMultiRenderTarget(),t?.forEach((e=>{this._addMeshToMRT(e)}))}addMesh(e){e?this._addMeshToMRT(e):this._scene.meshes.forEach((e=>{this._addMeshToMRT(e)})),this._recomputeLightTransformationMatrix()}updateLightParameters(){this._recomputeLightTransformationMatrix()}get lightTransformationMatrix(){return this.forceUpdateLightParameters&&this.updateLightParameters(),this._lightTransformMatrix}get countersGPU(){return this._counters}dispose(){this._disposeMultiRenderTarget()}_createMultiRenderTarget(){const e=this._light.name,t=this._scene.getEngine().getCaps(),i=t.rg11b10ufColorRenderable?13:2,r=t.rg11b10ufColorRenderable?4:5;let s,n;this._mrt=new Xb("RSMmrt_"+e,this._textureDimensions,3,this._scene,{types:[2,11,i],samplingModes:[2,2,2],generateMipMaps:!1,targetTypes:[3553,3553,3553],formats:[5,5,r]},["RSMPosition_"+e,"RSMNormal_"+e,"RSMFlux_"+e]),this._mrt.renderList=[],this._mrt.clearColor=new H.ov(0,0,0,1),this._mrt.noPrePassRenderer=!0;const o=this._scene.getEngine().supportsUniformBuffers;let a;o&&(s=this._scene.createSceneUniformBuffer(`Scene for RSM (light "${e}")`)),this._mrt.onBeforeBindObservable.add((()=>{n=this._scene.getSceneUniformBuffer(),a=this._light.shadowEnabled,this._light.shadowEnabled=!1})),this._mrt.onBeforeRenderObservable.add((e=>{s&&this._scene.setSceneUniformBuffer(s);const t=this._light.getViewMatrix(e),i=this._light.getProjectionMatrix(t||void 0,this._mrt.renderList||void 0);t&&i&&this._scene.setTransformMatrix(t,i),o&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._mrt.onAfterUnbindObservable.add((()=>{s&&this._scene.setSceneUniformBuffer(n),this._scene.updateTransformMatrix(),this._light.shadowEnabled=a,this._counters[0].value=this._mrt.renderTarget.gpuTimeInFrame?.counter.lastSecAverage??0})),this._customRenderTarget(!0)}_customRenderTarget(e){const t=this._scene.customRenderTargets.indexOf(this._mrt);e?-1===t&&this._scene.customRenderTargets.push(this._mrt):-1!==t&&this._scene.customRenderTargets.splice(t,1)}_recomputeLightTransformationMatrix(){const e=this._light.getViewMatrix(),t=this._light.getProjectionMatrix(e||void 0,this._mrt.renderList||void 0);e&&t&&e.multiplyToRef(t,this._lightTransformMatrix)}_addMeshToMRT(e){this._mrt.renderList?.push(e);const t=e.material;if(0===e.getTotalVertices()||!t)return;let i=this._regularMatToMatWithPlugin.get(t);if(!i&&(i=t.clone("RSMCreate_"+t.name)||void 0,i)){Object.defineProperty(i,"canRenderToMRT",{get:function(){return!1},enumerable:!0,configurable:!0}),i.disableLighting=!0;const e=new IN(i);e.isEnabled=!0,e.light=this._light,this._regularMatToMatWithPlugin.set(t,i)}this._mrt.setMaterialForRendering(e,i)}_disposeMultiRenderTarget(){this._customRenderTarget(!1),this._mrt.dispose()}}class RN extends xn{constructor(){super(...arguments),this.RSMCREATE=!1,this.RSMCREATE_PROJTEXTURE=!1,this.RSMCREATE_LIGHT_IS_SPOT=!1}}class IN extends Dn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e){super(e,IN.Name,300,new RN),this._lightColor=new H.v9,this._hasProjectionTexture=!1,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._varAlbedoName=e instanceof Gm?"surfaceAlbedo":"baseColor.rgb"}prepareDefines(e){e.RSMCREATE=this._isEnabled,this._hasProjectionTexture=!1;const t=this.light.getTypeID()===$t.LIGHTTYPEID_SPOTLIGHT;if(t){const e=this.light;this._hasProjectionTexture=!!e.projectionTexture&&e.projectionTexture.isReady()}e.RSMCREATE_PROJTEXTURE=this._hasProjectionTexture,e.RSMCREATE_LIGHT_IS_SPOT=t,e.SCENE_MRT_COUNT=3}getClassName(){return"RSMCreatePluginMaterial"}getUniforms(){return{ubo:[{name:"rsmTextureProjectionMatrix",size:16,type:"mat4"},{name:"rsmSpotInfo",size:4,type:"vec4"},{name:"rsmLightColor",size:3,type:"vec3"},{name:"rsmLightPosition",size:3,type:"vec3"}],fragment:"#ifdef RSMCREATE\n uniform mat4 rsmTextureProjectionMatrix;\n uniform vec4 rsmSpotInfo;\n uniform vec3 rsmLightColor;\n uniform vec3 rsmLightPosition;\n #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()===$t.LIGHTTYPEID_SPOTLIGHT)){const t=this.light;this._hasProjectionTexture&&(e.updateMatrix("rsmTextureProjectionMatrix",t.projectionTextureMatrix),e.setTexture("rsmTextureProjectionSampler",t.projectionTexture));const i=W.AA.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(.5*t.angle))}}getCustomCode(e,t){return"vertex"===e?null:1===t?{CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RSMCREATE\n #ifdef RSMCREATE_PROJTEXTURE\n var rsmTextureProjectionSamplerSampler: sampler;\n var rsmTextureProjectionSampler: texture_2d;\n #endif\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:`\n #ifdef RSMCREATE\n var rsmColor = ${this._varAlbedoName} * uniforms.rsmLightColor;\n #ifdef RSMCREATE_PROJTEXTURE\n {\n var strq = uniforms.rsmTextureProjectionMatrix * vec4f(fragmentInputs.vPositionW, 1.0);\n strq /= strq.w;\n rsmColor *= textureSample(rsmTextureProjectionSampler, rsmTextureProjectionSamplerSampler, strq.xy).rgb;\n }\n #endif\n #ifdef RSMCREATE_LIGHT_IS_SPOT\n {\n var cosAngle = max(0., dot(uniforms.rsmSpotInfo.xyz, normalize(fragmentInputs.vPositionW - uniforms.rsmLightPosition)));\n rsmColor = sign(cosAngle - uniforms.rsmSpotInfo.w) * rsmColor;\n }\n #endif\n\n #define MRT_AND_COLOR\n fragmentOutputs.fragData0 = vec4f(fragmentInputs.vPositionW, 1.);\n fragmentOutputs.fragData1 = vec4f(normalize(normalW) * 0.5 + 0.5, 1.);\n fragmentOutputs.fragData2 = vec4f(rsmColor, 1.);\n #endif\n `}:{CUSTOM_FRAGMENT_BEGIN:"\n #ifdef RSMCREATE\n #extension GL_EXT_draw_buffers : require\n #endif\n ",CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RSMCREATE\n #ifdef RSMCREATE_PROJTEXTURE\n uniform highp sampler2D rsmTextureProjectionSampler; \n #endif\n layout(location = 0) out highp vec4 glFragData[3];\n vec4 glFragColor;\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:`\n #ifdef RSMCREATE\n vec3 rsmColor = ${this._varAlbedoName} * rsmLightColor;\n #ifdef RSMCREATE_PROJTEXTURE\n {\n vec4 strq = rsmTextureProjectionMatrix * vec4(vPositionW, 1.0);\n strq /= strq.w;\n rsmColor *= texture2D(rsmTextureProjectionSampler, strq.xy).rgb;\n }\n #endif\n #ifdef RSMCREATE_LIGHT_IS_SPOT\n {\n float cosAngle = max(0., dot(rsmSpotInfo.xyz, normalize(vPositionW - rsmLightPosition)));\n rsmColor = sign(cosAngle - rsmSpotInfo.w) * rsmColor;\n }\n #endif\n glFragData[0] = vec4(vPositionW, 1.);\n glFragData[1] = vec4(normalize(normalW) * 0.5 + 0.5, 1.);\n glFragData[2] = vec4(rsmColor, 1.);\n #endif\n `}}}IN.Name="RSMCreate",(0,je.Cg)([(0,$e.lK)()],IN.prototype,"light",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],IN.prototype,"isEnabled",void 0),(0,X.Y5)("BABYLON.RSMCreatePluginMaterial",IN);class MN{constructor(e){this.numSamples=400,this.radius=.1,this.intensity=.1,this.edgeArtifactCorrection=.1,this.rotateSample=!0,this.noiseFactor=100,this.useFullTexture=!1,this.rsm=e}dispose(){this.rsm.dispose()}}class ON{get enable(){return this._enable}set enable(e){0===this._giRSM.length&&(e=!1),e!==this._enable&&(this._enable=e,this._debugLayer.isEnabled=this._showOnlyGI&&e,this._materialsWithRenderPlugin.forEach((t=>{t.pluginManager&&(t.pluginManager.getPlugin(wN.Name).isEnabled=e)})),this.recreateResources(!e))}get enableBlur(){return this._enableBlur}set enableBlur(e){e!==this._enableBlur&&(this._enableBlur=e,this.recreateResources())}get useQualityBlur(){return this._useQualityBlur}set useQualityBlur(e){e!==this._useQualityBlur&&(this._useQualityBlur=e,this.recreateResources())}get fullSizeBlur(){return this._forceFullSizeBlur}set fullSizeBlur(e){this._forceFullSizeBlur!==e&&(this._forceFullSizeBlur=e,this.recreateResources())}get useQualityUpsampling(){return this._useQualityUpsampling}set useQualityUpsampling(e){e!==this._useQualityUpsampling&&(this._useQualityUpsampling=e,this.recreateResources())}get showOnlyGI(){return this._showOnlyGI}set showOnlyGI(e){this._showOnlyGI!==e&&(this._showOnlyGI=e,this._debugLayer.isEnabled=e)}get use32BitsDepthBuffer(){return this._use32BitsDepthBuffer}set use32BitsDepthBuffer(e){this._use32BitsDepthBuffer!==e&&(this._use32BitsDepthBuffer=e,this.recreateResources())}setOutputDimensions(e){this._outputDimensions=e,this.recreateResources()}setGITextureDimensions(e){this._giTextureDimensions=e,this.recreateResources()}get giTextureType(){return this._giTextureType}set giTextureType(e){this._giTextureType!==e&&(this._giTextureType=e,this.recreateResources())}get shaderLanguage(){return this._shaderLanguage}get giRSM(){return this._giRSM}addGIRSM(e){Array.isArray(e)?this._giRSM.push(...e):this._giRSM.push(e),this.recreateResources()}removeGIRSM(e){if(Array.isArray(e))for(let t=0;t{e.getTotalVertices()>0&&e.isEnabled()&&e.material&&this._addGISupportToMaterial(e.material)}))}get countersGPU(){return this._counters}recreateResources(e=!1){this._shadersLoaded?(this._disposePostProcesses(e),this._createPostProcesses(),this._setPluginParameters()):this._onShaderLoadedObservable.addOnce((()=>{this.recreateResources(e)}))}generateSampleTexture(e){this._sampleTexture?.dispose(),this._maxSamples=e;const t=new Float32Array(4*this._maxSamples);for(let e=0;e{const e=this._engine._currentRenderTarget;let t=!1;if(this._enable){this.pause||(this._scene.postProcessManager.directRender(this._ppGlobalIllumination,this._ppGlobalIllumination[0].inputTexture),this._engine.unBindFramebuffer(this._ppGlobalIllumination[0].inputTexture,!0),this._engine.setAlphaMode(0),t=!0,this.enableBlur&&this._blurPostProcesses&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,this._blurRTT.renderTarget,!0),this._engine.unBindFramebuffer(this._blurRTT.renderTarget,!0)));for(let e=0;e{if(e.pluginManager){const t=e.pluginManager.getPlugin(wN.Name);t.textureGIContrib=this.enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture,t.outputTextureWidth=this._outputDimensions.width,t.outputTextureHeight=this._outputDimensions.height}}))}_createPostProcesses(){if(!this._enable)return;const e=13===this._giTextureType?4:5;this._firstActivation&&(this._firstActivation=!1,this._geomBufferEnabled=!!this._scene.geometryBufferRenderer,this._geomBufferEnablePosition=this._scene.geometryBufferRenderer?.enablePosition??!1),this._geomBufferEnabled||this._scene.disableGeometryBufferRenderer();const t=this._scene.enableGeometryBufferRenderer(this._enableBlur?this._outputDimensions:this._giTextureDimensions,this._use32BitsDepthBuffer?14:15,ON.GeometryBufferTextureTypesAndFormats);if(!t)throw new Error("Geometry buffer renderer is not supported but is required for GIRSMManager.");t.enablePosition=!0,this._geomBufferEnabled||(t.generateNormalsInWorldSpace=!0);const i=t.normalsAreUnsigned,r=t.generateNormalsInWorldSpace;this._counters.push({name:"Geometry buffer renderer",value:0}),this._countersRTW.push([this._scene.geometryBufferRenderer.getGBuffer().renderTarget]);let s="";i&&(s+="#define DECODE_NORMAL\n"),r||(s+="#define TRANSFORM_NORMAL\n");for(let i=0;i{e.setTexture("textureSampler",t.getGBuffer().textures[t.getTextureIndex(qO.POSITION_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(qO.NORMAL_TEXTURE_TYPE)]),e.setTexture("rsmPositionW",o.positionWorldTexture),e.setTexture("rsmNormalW",o.normalWorldTexture),e.setTexture("rsmFlux",o.fluxTexture),e.setMatrix("rsmLightMatrix",o.lightTransformationMatrix),n.useFullTexture?e.setFloat4("rsmInfo",o.fluxTexture.getInternalTexture().width,o.fluxTexture.getInternalTexture().height,n.intensity,n.edgeArtifactCorrection):(e.setTexture("rsmSamples",this._sampleTexture),e.setFloat4("rsmInfo",n.numSamples,n.radius,n.intensity,n.edgeArtifactCorrection),e.setFloat4("rsmInfo2",n.noiseFactor,n.rotateSample?1:0,o.fluxTexture.getInternalTexture().width,o.fluxTexture.getInternalTexture().height)),r||(this._tempMatrix.copyFrom(this._scene.activeCamera.getViewMatrix()),this._tempMatrix.invert(),e.setMatrix("invView",this._tempMatrix))}))}for(const e of this._ppGlobalIllumination)e.inputTexture||e.resize(this._giTextureDimensions.width,this._giTextureDimensions.height);if(this._counters.push({name:"GI generation",value:0}),this._countersRTW.push([this._ppGlobalIllumination[0].inputTexture]),this._enableBlur){const r=this._forceFullSizeBlur?this._outputDimensions:this._giTextureDimensions;this._blurRTT=new ln.$("GIRSMContribution",this._outputDimensions,this._scene,{type:this._giTextureType,format:e,generateDepthBuffer:!1}),this._blurRTT.wrapU=0,this._blurRTT.wrapV=0,this._blurRTT.updateSamplingMode(1),this._blurRTT.skipInitialClear=!0;const s=[];if(this._counters.push({name:"GI blur",value:0}),this._countersRTW.push(s),this._blurXPostprocess=new ms.w(this._useQualityBlur?"BilateralBlur":"BilateralBlurX",this._useQualityBlur?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:r,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e,shaderLanguage:this._shaderLanguage}),this._blurXPostprocess.onApplyObservable.add((e=>{e._bindTexture("textureSampler",this._ppGlobalIllumination[0].inputTexture.texture),e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(qO.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(qO.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.blurKernel),e.setFloat2("blurDir",1/this._giTextureDimensions.width,this._useQualityBlur?1/this._giTextureDimensions.height:0),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._blurXPostprocess.externalTextureSamplerBinding=!0,this._blurXPostprocess.autoClear=!1,this._useQualityBlur||(this._blurYPostprocess=new ms.w("BilateralBlurY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:r,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e,shaderLanguage:this._shaderLanguage}),this._blurYPostprocess.autoClear=!1,this._blurYPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(qO.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(qO.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.blurKernel),e.setFloat2("blurDir",0,1/this._giTextureDimensions.height),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._blurYPostprocess.resize(r.width,r.height),s.push(this._blurYPostprocess.inputTexture)),this._blurPostProcesses=[this._blurXPostprocess],this._blurYPostprocess&&this._blurPostProcesses.push(this._blurYPostprocess),this._giTextureDimensions.width>=this._outputDimensions.width&&this._giTextureDimensions.height>=this._outputDimensions.height||this._forceFullSizeBlur)s.push(this._blurRTT.renderTarget);else{const n=[];this._counters.push({name:"GI upsampling",value:0}),this._countersRTW.push(n),this._upsamplingXPostprocess=new ms.w(this._useQualityUpsampling?"BilateralUpsampling":"BilateralUpsamplingX",this._useQualityUpsampling?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:r,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e,shaderLanguage:this._shaderLanguage}),this._upsamplingXPostprocess.autoClear=!1,this._upsamplingXPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(qO.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(qO.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.upsamplerKernel),e.setFloat2("blurDir",1/this._outputDimensions.width,this._useQualityUpsampling?1/this._outputDimensions.height:0),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._upsamplingXPostprocess.resize(r.width,r.height),s.push(this._upsamplingXPostprocess.inputTexture),this.useQualityUpsampling||(this._upsamplingYPostprocess=new ms.w("BilateralUpsamplingY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:this._outputDimensions,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e,shaderLanguage:this._shaderLanguage}),this._upsamplingYPostprocess.autoClear=!1,this._upsamplingYPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(qO.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(qO.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.upsamplerKernel),e.setFloat2("blurDir",0,1/this._outputDimensions.height),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._upsamplingYPostprocess.resize(this._outputDimensions.width,this._outputDimensions.height),n.push(this._upsamplingYPostprocess.inputTexture)),n.push(this._blurRTT.renderTarget),this._blurPostProcesses.push(this._upsamplingXPostprocess),this._upsamplingYPostprocess&&this._blurPostProcesses.push(this._upsamplingYPostprocess)}}this._debugLayer.texture?.dispose(),this._debugLayer.texture=new js.t(this._scene,this._enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture)}_addGISupportToMaterial(e){if(e.pluginManager?.getPlugin(wN.Name))return;const t=new wN(e);this._enable&&this._ppGlobalIllumination.length>0&&(t.textureGIContrib=this._ppGlobalIllumination[0].inputTexture.texture,t.outputTextureWidth=this._outputDimensions.width,t.outputTextureHeight=this._outputDimensions.height),t.isEnabled=this._enable,this._materialsWithRenderPlugin.push(e)}}ON.GeometryBufferTextureTypesAndFormats={0:{textureType:2,textureFormat:6},1:{textureType:11,textureFormat:5},2:{textureType:2,textureFormat:5}};class DN extends xn{constructor(){super(...arguments),this.RENDER_WITH_GIRSM=!1,this.RSMCREATE_PROJTEXTURE=!1}}class wN extends Dn{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e){super(e,wN.Name,310,new DN),this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._isPBR=e instanceof Gm}prepareDefines(e){e.RENDER_WITH_GIRSM=this._isEnabled}getClassName(){return"GIRSMRenderPluginMaterial"}getUniforms(){return{ubo:[{name:"girsmTextureOutputSize",size:2,type:"vec2"}],fragment:"#ifdef RENDER_WITH_GIRSM\n uniform vec2 girsmTextureOutputSize;\n #endif"}}getSamplers(e){e.push("girsmTextureGIContrib")}bindForSubMesh(e){this._isEnabled&&(e.bindTexture("girsmTextureGIContrib",this.textureGIContrib),e.updateFloat2("girsmTextureOutputSize",this.outputTextureWidth,this.outputTextureHeight))}getCustomCode(e,t){let i;return 1===t?(i={CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RENDER_WITH_GIRSM\n var girsmTextureGIContribSampler: sampler;\n var girsmTextureGIContrib: texture_2d;\n\n fn computeIndirect() -> vec3f {\n var uv = fragmentInputs.position.xy / uniforms.girsmTextureOutputSize;\n return textureSample(girsmTextureGIContrib, girsmTextureGIContribSampler, uv).rgb;\n }\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:"\n #ifdef RENDER_WITH_GIRSM\n finalDiffuse += computeIndirect() * surfaceAlbedo.rgb;\n #endif\n "},this._isPBR||(i.CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR="\n #ifdef RENDER_WITH_GIRSM\n color = vec4f(color.rgb + computeIndirect() * baseColor.rgb, color.a);\n #endif\n ")):(i={CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RENDER_WITH_GIRSM\n uniform sampler2D girsmTextureGIContrib;\n\n vec3 computeIndirect() {\n vec2 uv = gl_FragCoord.xy / girsmTextureOutputSize;\n return texture2D(girsmTextureGIContrib, uv).rgb;\n }\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:"\n #ifdef RENDER_WITH_GIRSM\n finalDiffuse += computeIndirect() * surfaceAlbedo.rgb;\n #endif\n "},this._isPBR||(i.CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR="\n #ifdef RENDER_WITH_GIRSM\n color.rgb += computeIndirect() * baseColor.rgb;\n #endif\n ")),"vertex"===e?null:i}}wN.Name="GIRSMRender",(0,je.Cg)([(0,$e.lK)()],wN.prototype,"textureGIContrib",void 0),(0,je.Cg)([(0,$e.lK)()],wN.prototype,"outputTextureWidth",void 0),(0,je.Cg)([(0,$e.lK)()],wN.prototype,"outputTextureHeight",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],wN.prototype,"isEnabled",void 0),(0,X.Y5)("BABYLON.GIRSMRenderPluginMaterial",wN);var NN=i(41341),FN=i(47318),LN=i(58500),BN=i(69319),VN=i(84910),kN=i(46563),UN=i(31583),GN=i(91944),zN=i(66246),WN=i(61420),HN=i(55745),XN=i(20267),qN=i(16400),YN=i(81473),KN=i(83063),jN=i(10737),$N=i(85550),QN=i(42644),ZN=i(27127),JN=i(7217),eF=i(32192),tF=i(65038),iF=i(55515),rF=i(18789),sF=i(76978),nF=i(4357),oF=i(74747),aF=i(35680),lF=i(73588),hF=i(65461),cF=i(45647),uF=i(80018),dF=i(41115),fF=i(17864);const pF="iblShadowsCombinePixelShader",_F="precision highp float;varying vec2 vUV;uniform sampler2D shadowSampler;uniform sampler2D textureSampler;uniform float shadowOpacity;void main(void)\n{vec3 shadow=texture(shadowSampler,vUV).rgb;vec3 sceneColor=texture(textureSampler,vUV).rgb;float shadowValue=mix(1.0,shadow.x,shadowOpacity);gl_FragColor=vec4(sceneColor*shadowValue,1.0);}";Cs.l.ShadersStore[pF]=_F;const mF={name:pF,shader:_F},gF="iblShadowsCombinePixelShader",vF="varying vUV: vec2f;var shadowSamplerSampler : sampler;var shadowSampler : texture_2d;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform shadowOpacity: f32;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {var shadow\n: vec3f =\ntextureSample(shadowSampler,shadowSamplerSampler,input.vUV).rgb;var color\n: vec3f =\ntextureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var shadowValue: f32=mix(1.0,shadow.x,uniforms.shadowOpacity);fragmentOutputs.color=vec4f(color*shadowValue,1.0);}";Cs.l.ShadersStoreWGSL[gF]=vF;const xF={name:gF,shader:vF};var bF=i(48016),SF=i(17897),TF=i(99638),CF=i(88789),yF=i(64367),EF=i(23008),PF=i(43572),AF=i(47473),RF=i(85917),IF=i(98824),MF=i(38957),OF=i(8970),DF=i(27844),wF=i(7683),NF=i(78685),FF=i(87382),LF=i(68859),BF=i(7426),VF=i(83145),kF=i(19395),UF=i(75904),GF=i(79214),zF=i(95171),WF=i(20008),HF=i(71650),XF=i(81284),qF=i(94369),YF=i(16615),KF=i(17738),jF=i(4172),$F=i(29551),QF=i(21937);Cs.l.ShadersStore.spriteMapPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nprecision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;\n#include\n#include\nfloat mt;const float fdStep=1.0*0.25;const float aFrameSteps=MAX_ANIMATION_FRAMES==0.0 ? 0.0 : 1.0/MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID) {float fX=frameID/spriteCount;return mat4(\nTEXTUREFUNC(frameMap,vec2(fX,0.0),0.0),\nTEXTUREFUNC(frameMap,vec2(fX,fdStep*1.0),0.0),\nTEXTUREFUNC(frameMap,vec2(fX,fdStep*2.0),0.0),\nvec4(0.0)\n);}\nvoid main() {vec4 color=vec4(0.0);vec2 tileUV=fract(tUV);vec2 tileID=floor(tUV);vec2 sheetUnits=1.0/spriteMapSize;float spriteUnits=1.0/spriteCount;vec2 stageUnits=1.0/stageSize;for(int i=0; i0.0) {mt=mod(time*animationData.z,1.0);for(float f=0.0; fmt) {frameID=animationData.x;break;}\nanimationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.0);}}\nmat4 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;\n#ifdef FR_CW\nif (frameData[2].z==1.0) {tileUV.xy=tileUV.yx;} else {tileUV.xy=fract(tUV).xy;}\n#ifdef FLIPU\ntileUV.y=1.0-tileUV.y;\n#endif\n#else\nif (frameData[2].z==1.0) {\n#ifdef FLIPU\ntileUV.y=1.0-tileUV.y;\n#endif\ntileUV.xy=tileUV.yx;} else {tileUV.xy=fract(tUV).xy;\n#ifdef FLIPU\ntileUV.y=1.0-tileUV.y;\n#endif\n}\n#endif\nvec4 nc=TEXTUREFUNC(spriteSheet,tileUV*frameSize+offset,0.0);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);}}\ncolor.xyz*=colorMul;\n#include\n#include\ngl_FragColor=color;}";var ZF;Cs.l.ShadersStore.spriteMapVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform mat4 world;uniform mat4 view;uniform mat4 projection;uniform vec2 stageSize;uniform float stageScale;\n#include\n#include\nvoid main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; \nvec3 viewPos=(view*world*p).xyz; \ngl_Position=projection*vec4(viewPos,1.0); \n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n#include\n}",function(e){e[e.CCW=0]="CCW",e[e.CW=1]="CW"}(ZF||(ZF={}));class JF{get spriteCount(){return this.sprites.length}get position(){return this._output.position}set position(e){this._output.position=e}get rotation(){return this._output.rotation}set rotation(e){this._output.rotation=e}get animationMap(){return this._animationMap}set animationMap(e){const t=e._texture._bufferView,i=this._createTileAnimationBuffer(t);this._animationMap.dispose(),this._animationMap=i,this._material.setTexture("animationMap",this._animationMap)}get fogEnabled(){return this._material.fogEnabled}set fogEnabled(e){this._material.fogEnabled=e}get useLogarithmicDepth(){return this._material.useLogarithmicDepth}set useLogarithmicDepth(e){this._material.useLogarithmicDepth=e}constructor(e,t,i,r,s){this.name=e,this.sprites=[],this.atlasJSON=t,this.sprites=this.atlasJSON.frames,this.spriteSheet=i,this.options=r,r.stageSize=r.stageSize||new W.I9(1,1),r.outputSize=r.outputSize||r.stageSize,r.outputPosition=r.outputPosition||W.Pq.Zero(),r.outputRotation=r.outputRotation||W.Pq.Zero(),r.layerCount=r.layerCount||1,r.maxAnimationFrames=r.maxAnimationFrames||0,r.baseTile=r.baseTile||0,r.flipU=r.flipU||!1,r.colorMultiply=r.colorMultiply||new W.Pq(1,1,1),this._scene=s,this._frameMap=this._createFrameBuffer(),this._tileMaps=new Array;for(let e=0;e{this.spriteSheet&&this.spriteSheet.isReady()&&this.spriteSheet._texture?this._material.setVector2("spriteMapSize",new W.I9(this.spriteSheet._texture.baseWidth||1,this.spriteSheet._texture.baseHeight||1)):l<100&&setTimeout((()=>{l++,h()}),100)};h(),this._material.setVector3("colorMul",r.colorMultiply),this._material.setTexture("frameMap",this._frameMap),this._material.setTextureArray("tileMaps",this._tileMaps),this._material.setTexture("animationMap",this._animationMap),this._material.setFloat("time",this._time),this._output=Qi(e+":output",{size:1,updatable:!0},s),this._output.scaling.x=r.outputSize.x,this._output.scaling.y=r.outputSize.y,this.position=r.outputPosition,this.rotation=r.outputRotation,this._scene.onBeforeRenderObservable.add((()=>{this._time+=this._scene.getEngine().getDeltaTime(),this._material.setFloat("time",this._time)})),this._output.material=this._material}getTileIdxByName(e){return this.atlasJSON.frames.findIndex((t=>t.filename===e))}getTileID(){const e=this.getMousePosition();return e.multiplyInPlace(this.options.stageSize||W.I9.Zero()),e.x=Math.floor(e.x),e.y=Math.floor(e.y),e}getMousePosition(){const e=this._output,t=this._scene.pick(this._scene.pointerX,this._scene.pointerY,(t=>t===e));if(!t||!t.hit||!t.getTextureCoordinates)return new W.I9(-1,-1);return t.getTextureCoordinates()||new W.I9(-1,-1)}_createFrameBuffer(){const e=[];for(let t=0;t0&&(e+="\n\r"),e+=this._tileMaps[t]._texture._bufferView.toString();const t=document.createElement("a");t.href="data:octet/stream;charset=utf-8,"+encodeURI(e),t.target="_blank",t.download=this.name+".tilemaps",t.click(),t.remove()}loadTileMaps(e){const t=new XMLHttpRequest;t.open("GET",e);const i=this.options.layerCount||0;t.onload=()=>{const e=t.response.split("\n\r");for(let t=0;t{e.dispose()})),this._frameMap.dispose()}}class eL extends Jx{constructor(e,t,i,r,s=null,n=.01,o=vi.g.TRILINEAR_SAMPLINGMODE,a){super(e,t,i,64,r,n,o,!0,s,a),this.name=e}}var tL,iL,rL=i(3916),sL=i(3290),nL=i(25151),oL=i(56029),aL=i(94895),lL=i(69905);!function(e){e[e.ENTERING_XR=0]="ENTERING_XR",e[e.EXITING_XR=1]="EXITING_XR",e[e.IN_XR=2]="IN_XR",e[e.NOT_IN_XR=3]="NOT_IN_XR"}(tL||(tL={})),function(e){e[e.NOT_TRACKING=0]="NOT_TRACKING",e[e.TRACKING_LOST=1]="TRACKING_LOST",e[e.TRACKING=2]="TRACKING"}(iL||(iL={}));class hL extends Ig{constructor(e,t={}){super(e),this.options=t,this._direction=new W.Pq(0,0,-1),this._mat=new W.uq,this._onSelectEnabled=!1,this._origin=new W.Pq(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new z.cP,this._onHitTestResults=e=>{const t=e.map((e=>{const t=W.uq.FromArray(e.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||t.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&t.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),t),{xrHitResult:e,transformationMatrix:t}}));this.lastNativeXRHitResults=e,this.onHitTestResultObservable.notifyObservers(t)},this._onSelect=e=>{this._onSelectEnabled&&hL.XRHitTestWithSelectEvent(e,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",Ue.S0.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,r){return e.requestHitTest(t,i).then((e=>{const t=r||(e=>!!e.hitMatrix);return e.filter(t)}))}static XRHitTestWithSelectEvent(e,t){const i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);const r=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,r,t)}attach(){return!!super.attach()&&(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)}detach(){return!!super.detach()&&(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)}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;W.uq.FromArrayToRef(t.transform.matrix,0,this._mat),W.Pq.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),W.Pq.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});hL.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}hL.Name=hr.HIT_TEST,hL.Version=1,cr.AddWebXRFeature(hL.Name,((e,t)=>()=>new hL(e,t)),hL.Version,!1);let cL=0;class uL extends Ig{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 z.cP,this.onAnchorRemovedObservable=new z.cP,this.onAnchorUpdatedObservable=new z.cP,this._tmpVector=new W.Pq,this._tmpQuaternion=new W.PT,this.xrNativeFeatureName="anchors",this._options.clearAnchorsOnSessionInit&&this._xrSessionManager.onXRSessionInit.add((()=>{this._trackedAnchors.length=0,this._futureAnchors.length=0,this._lastFrameDetected.clear()}))}_populateTmpTransformation(e,t){return this._tmpVector.copyFrom(e),this._tmpQuaternion.copyFrom(t),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpVector.z*=-1,this._tmpQuaternion.z*=-1,this._tmpQuaternion.w*=-1),{position:this._tmpVector,rotationQuaternion:this._tmpQuaternion}}async addAnchorPointUsingHitTestResultAsync(e,t=new W.Pq,i=new W.PT){this._populateTmpTransformation(t,i);const r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w});if(!e.xrHitResult.createAnchor)throw this.detach(),new Error("Anchors not enabled in this environment/browser");try{const t=await e.xrHitResult.createAnchor(r);return new Promise(((e,i)=>{this._futureAnchors.push({nativeAnchor:t,resolved:!1,submitted:!0,xrTransformation:r,resolve:e,reject:i})}))}catch(e){throw new Error(e)}}async addAnchorAtPositionAndRotationAsync(e,t=new W.PT,i=!1){this._populateTmpTransformation(e,t);const r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),s=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(r,this._xrSessionManager.currentFrame):void 0;return new Promise(((e,t)=>{this._futureAnchors.push({nativeAnchor:s,resolved:!1,submitted:!1,xrTransformation:r,resolve:e,reject:t})}))}get anchors(){return this._trackedAnchors}detach(){if(!super.detach())return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){const e=this._trackedAnchors.pop();e&&this.onAnchorRemovedObservable.notifyObservers(e)}return!0}dispose(){this._futureAnchors.length=0,super.dispose(),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()}_onXRFrame(e){if(!this.attached||!e)return;const t=e.trackedAnchors;if(t){const i=this._trackedAnchors.filter((e=>!t.has(e.xrAnchor))).map((e=>this._trackedAnchors.indexOf(e)));let r=0;i.forEach((e=>{const t=this._trackedAnchors.splice(e-r,1)[0];this.onAnchorRemovedObservable.notifyObservers(t),r++})),t.forEach((t=>{if(this._lastFrameDetected.has(t)){const i=this._findIndexInAnchorArray(t),r=this._trackedAnchors[i];try{this._updateAnchorWithXRFrame(t,r,e),r.attachedNode&&(r.attachedNode.rotationQuaternion=r.attachedNode.rotationQuaternion||new W.PT,r.transformationMatrix.decompose(r.attachedNode.scaling,r.attachedNode.rotationQuaternion,r.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(r)}catch(e){Ue.S0.Warn("Anchor could not be updated")}}else{const i={id:cL++,xrAnchor:t,remove:()=>t.delete()},r=this._updateAnchorWithXRFrame(t,i,e);this._trackedAnchors.push(r),this.onAnchorAddedObservable.notifyObservers(r);const s=this._futureAnchors.filter((e=>e.nativeAnchor===t))[0];s&&(s.resolve(r),s.resolved=!0)}})),this._lastFrameDetected=t}this._futureAnchors.forEach((t=>{t.resolved||t.submitted||(this._createAnchorAtTransformation(t.xrTransformation,e).then((e=>{t.nativeAnchor=e}),(e=>{t.resolved=!0,t.reject(e)})),t.submitted=!0)}))}_findIndexInAnchorArray(e){for(let t=0;t()=>new uL(e,t)),uL.Version);let dL=0;class fL extends Ig{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new z.cP,this.onPlaneRemovedObservable=new z.cP,this.onPlaneUpdatedObservable=new z.cP,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"undefined"!=typeof XRPlane}async initiateRoomCapture(){return this._xrSessionManager.session.initiateRoomCapture?this._xrSessionManager.session.initiateRoomCapture():Promise.reject("initiateRoomCapture is not supported on this session")}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;const t=e.detectedPlanes||e.worldInformation?.detectedPlanes;if(t){for(let e=0;e{if(this._lastFrameDetected.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._findIndexInPlaneArray(t),r=this._detectedPlanes[i];this._updatePlaneWithXRPlane(t,r,e),this.onPlaneUpdatedObservable.notifyObservers(r)}}else{const i={id:dL++,xrPlane:t,polygonDefinition:[]},r=this._updatePlaneWithXRPlane(t,i,e);this._detectedPlanes.push(r),this.onPlaneAddedObservable.notifyObservers(r)}})),this._lastFrameDetected=t}}_init(){const e=()=>{this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes.length=0)};this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),this._xrSessionManager.session.updateWorldTrackingState?(this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),e()):e()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map((e=>{const t=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new W.Pq(e.x,e.y,e.z*t)}));const r=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(r){const e=t.transformationMatrix||new W.uq;W.uq.FromArrayToRef(r.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}_findIndexInPlaneArray(e){for(let t=0;t()=>new fL(e,t)),fL.Version);class pL extends Ig{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new z.cP}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((t=>t.setEnabled(e))),this.onBackgroundStateChangedObservable.notifyObservers(e)}}pL.Name=hr.BACKGROUND_REMOVER,pL.Version=1,cr.AddWebXRFeature(pL.Name,((e,t)=>()=>new pL(e,t)),pL.Version,!0);class _L{}class mL extends Ig{_createPhysicsImpostor(e){const t=this._options.physicsProperties.impostorType||sa.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,r=Qo("impostor-mesh-"+e.uniqueId,{diameterX:"number"==typeof i?i:i.width,diameterY:"number"==typeof i?i:i.height,diameterZ:"number"==typeof i?i:i.depth});r.isVisible=this._debugMode,r.isPickable=!1,r.rotationQuaternion=new W.PT;const s=e.grip||e.pointer;r.position.copyFrom(s.position),r.rotationQuaternion.copyFrom(s.rotationQuaternion);const n=new sa(r,t,{mass:0,...this._options.physicsProperties});this._controllers[e.uniqueId]={xrController:e,impostor:n,impostorMesh:r}}constructor(e,t){super(e),this._options=t,this._attachController=e=>{this._controllers[e.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||Z.V.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&e.inputSource.gamepad?e.onMotionControllerInitObservable.addOnce((t=>{t._doNotLoadControllerMesh?this._createPhysicsImpostor(e):t.onModelLoadedObservable.addOnce((()=>{const i=new sa(t.rootMesh,sa.MeshImpostor,{mass:0,...this._options.physicsProperties}),r=e.grip||e.pointer;this._controllers[e.uniqueId]={xrController:e,impostor:i,oldPos:r.position.clone(),oldRotation:r.rotationQuaternion.clone()}}))})):this._createPhysicsImpostor(e))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new W.PT,this._tmpVector=new W.Pq,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:sa.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=Qo("headset-mesh",{diameterX:"number"==typeof t?t:t.width,diameterY:"number"==typeof t?t:t.height,diameterZ:"number"==typeof t?t:t.depth}),this._headsetMesh.rotationQuaternion=new W.PT,this._headsetMesh.isVisible=!1,this._headsetImpostor=new sa(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)}getHeadsetImpostor(){return this._headsetImpostor}getImpostorForController(e){const t="string"==typeof e?e:e.uniqueId;return this._controllers[t]?this._controllers[t].impostor:null}setPhysicsProperties(e){this._options.physicsProperties={...this._options.physicsProperties,...e}}_onXRFrame(e){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),this._options.xrInput.xrCamera._lastXRViewerPose?.linearVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if(this._options.xrInput.xrCamera._lastXRViewerPose?.angularVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach((e=>{const t=this._controllers[e],i=t.xrController.grip||t.xrController.pointer,r=t.oldPos||t.impostorMesh.position;if(t.xrController._lastXRPose?.linearVelocity){const e=t.xrController._lastXRPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),t.impostor.setLinearVelocity(this._tmpVector)}else i.position.subtractToRef(r,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),t.impostor.setLinearVelocity(this._tmpVector);r.copyFrom(i.position),this._debugMode&&Z.V.Log([this._tmpVector,"linear"]);const s=t.oldRotation||t.impostorMesh.rotationQuaternion;if(t.xrController._lastXRPose?.angularVelocity){const e=t.xrController._lastXRPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),t.impostor.setAngularVelocity(this._tmpVector)}else if(!s.equalsWithEpsilon(i.rotationQuaternion)){s.conjugateInPlace().multiplyToRef(i.rotationQuaternion,this._tmpQuaternion);const e=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),e<.001)this._tmpVector.scaleInPlace(2);else{const t=2*Math.atan2(e,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(t/(e*(this._delta/1e3)))}t.impostor.setAngularVelocity(this._tmpVector)}s.copyFrom(i.rotationQuaternion),this._debugMode&&Z.V.Log([this._tmpVector,this._tmpQuaternion,"angular"])}))}_detachController(e){const t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}mL.Name=hr.PHYSICS_CONTROLLERS,mL.Version=1,cr.AddWebXRFeature(mL.Name,((e,t)=>()=>new mL(e,t)),mL.Version,!0);class gL extends Ig{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new W.uq,this._tmpPos=new W.Pq,this._tmpQuat=new W.PT,this._initHitTestSource=e=>{if(!e)return;const t=new XRRay(this.options.offsetRay||{}),i={space:this.options.useReferenceSpace?e:this._xrSessionManager.viewerReferenceSpace,offsetRay:t};this.options.entityTypes&&(i.entityTypes=this.options.entityTypes),i.space?this._xrSessionManager.session.requestHitTestSource(i).then((e=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=e})):Ue.S0.Warn("waiting for viewer reference space to initialize")},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new z.cP,this.paused=!1,this.xrNativeFeatureName="hit-test",Ue.S0.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach())return!1;if(!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((e=>{this._transientXrHitTestSource=e}))}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)}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((e=>{this._processWebXRHitTestResult(e.results,e.inputSource)}))}}_processWebXRHitTestResult(e,t){const i=[];e.forEach((e=>{const r=e.getPose(this._xrSessionManager.referenceSpace);if(!r)return;const s=r.transform.position,n=r.transform.orientation;this._tmpPos.set(s.x,s.y,s.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._tmpQuat.set(n.x,n.y,n.z,n.w),W.uq.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 o={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:e};i.push(o)})),this.onHitTestResultObservable.notifyObservers(i)}}gL.Name=hr.HIT_TEST,gL.Version=2,cr.AddWebXRFeature(gL.Name,((e,t)=>()=>new gL(e,t)),gL.Version,!1);class vL extends Ig{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new z.cP,this.onFeaturePointsUpdatedObservable=new z.cP,this.xrNativeFeatureName="bjsfeature-points",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){return!!super.detach()&&(this.featurePointCloud.length=0,!0)}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&&0!==t.length){if(t.length%5!=0)throw new Error("Received malformed feature point cloud of length: "+t.length);const e=t.length/5,i=[],r=[];for(let s=0;s0&&this.onFeaturePointsAddedObservable.notifyObservers(r),i.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(i)}}_init(){this._xrSessionManager.session.trySetFeaturePointCloudEnabled&&this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)&&(this._enabled=!0)}}vL.Name=hr.FEATURE_POINTS,vL.Version=1,cr.AddWebXRFeature(vL.Name,(e=>()=>new vL(e)),vL.Version);let xL=0;class bL extends Ig{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new z.cP,this.onMeshRemovedObservable=new z.cP,this.onMeshUpdatedObservable=new z.cP,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)}dispose(){super.dispose(),this.onMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onMeshUpdatedObservable.clear()}_onXRFrame(e){try{if(!this.attached||!e)return;const t=e.detectedMeshes||e.worldInformation?.detectedMeshes;if(t){const i=new Set;this._detectedMeshes.forEach(((e,r)=>{t.has(r)||i.add(r)})),i.forEach((e=>{const t=this._detectedMeshes.get(e);t&&(this.onMeshRemovedObservable.notifyObservers(t),this._detectedMeshes.delete(e))})),t.forEach((t=>{if(this._detectedMeshes.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._detectedMeshes.get(t);i&&(this._updateVertexDataWithXRMesh(t,i,e),this.onMeshUpdatedObservable.notifyObservers(i))}}else{const i={id:xL++,xrMesh:t},r=this._updateVertexDataWithXRMesh(t,i,e);this._detectedMeshes.set(t,r),this.onMeshAddedObservable.notifyObservers(r)}}))}}catch(e){Z.V.Log(e.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){t.xrMesh=e,t.worldParentNode=this._options.worldParentNode;const r=e.vertices||e.positions;if(this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=r,t.normals=e.normals;else{t.positions=new Float32Array(r.length);for(let e=0;e()=>new bL(e,t)),bL.Version,!1),function(e){e[e.NotReceived=0]="NotReceived",e[e.Waiting=1]="Waiting",e[e.Received=2]="Received"}(SL||(SL={}));class TL extends Ig{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new z.cP,this.onTrackableImageFoundObservable=new z.cP,this.onTrackedImageUpdatedObservable=new z.cP,this._trackableScoreStatus=SL.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((e=>"string"==typeof e.src?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(e.src):Promise.resolve(e.src)));try{const t=await Promise.all(e);return this._originalTrackingRequest=t.map(((e,t)=>({image:e,widthInMeters:this.options.images[t].estimatedRealWorldWidth}))),{trackedImages:this._originalTrackingRequest}}catch(e){return Ue.S0.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===SL.Waiting)return;if(this._trackableScoreStatus===SL.NotReceived)return void this._checkScoresAsync();const t=e.getImageTrackingResults();for(const i of t){let t=!1;const r=i.index,s=this._trackedImages[r];if(!s)continue;s.xrTrackingResult=i,s.realWorldWidth!==i.measuredWidthInMeters&&(s.realWorldWidth=i.measuredWidthInMeters,t=!0);const n=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(n){const e=s.transformationMatrix;W.uq.FromArrayToRef(n.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t=!0}const o="emulated"===i.trackingState;s.emulated!==o&&(s.emulated=o,t=!0),t&&this.onTrackedImageUpdatedObservable.notifyObservers(s)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==SL.NotReceived)return;this._trackableScoreStatus=SL.Waiting;const e=await this._xrSessionManager.session.getTrackedImageScores();if(e&&0!==e.length){for(let t=0;t0?SL.Received:SL.NotReceived}else this._trackableScoreStatus=SL.NotReceived}}TL.Name=hr.IMAGE_TRACKING,TL.Version=1,cr.AddWebXRFeature(TL.Name,((e,t)=>()=>new TL(e,t)),TL.Version,!1);class CL extends Ig{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",Ue.S0.Warn("dom-overlay is an experimental and unstable feature.")}attach(){return!(!super.attach()||!this._xrSessionManager.session.domOverlayState||null===this._xrSessionManager.session.domOverlayState.type||(this._domOverlayType=this._xrSessionManager.session.domOverlayState.type,null!==this._element&&!0===this.options.supressXRSelectEvents&&(this._beforeXRSelectListener=e=>{e.preventDefault()},this._element.addEventListener("beforexrselect",this._beforeXRSelectListener)),0))}get domOverlayType(){return this._domOverlayType}dispose(){super.dispose(),null!==this._element&&this._beforeXRSelectListener&&this._element.removeEventListener("beforexrselect",this._beforeXRSelectListener)}_onXRFrame(e){}async getXRSessionInitExtension(){if(void 0===this.options.element)return Ue.S0.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if("string"==typeof this.options.element){const e=document.querySelector(this.options.element);if(null===e)return Ue.S0.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}}}}CL.Name=hr.DOM_OVERLAY,CL.Version=1,cr.AddWebXRFeature(CL.Name,((e,t)=>()=>new CL(e,t)),CL.Version,!1);class yL extends Ig{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){super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new W.PT,this._tmpRotationMatrix=W.uq.Identity(),this._tmpTranslationDirection=new W.Pq,this._tmpMovementTranslation=new W.Pq,this._tempCacheQuaternion=new W.PT,this._attachController=e=>{if(this._controllers[e.uniqueId])return;this._controllers[e.uniqueId]={xrController:e,registeredComponents:[]};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController)for(const i of this._currentRegistrationConfigurations){let r=null;if(i.allowedComponentTypes)for(const t of i.allowedComponentTypes){const i=e.motionController.getComponentOfType(t);if(null!==i){r=i;break}}if(i.mainComponentOnly){const t=e.motionController.getMainComponent();if(null===t)continue;r=t}if("function"==typeof i.componentSelectionPredicate&&(r=i.componentSelectionPredicate(e)),r&&i.forceHandedness&&e.inputSource.handedness!==i.forceHandedness)continue;if(null===r)continue;const s={registrationConfiguration:i,component:r};t.registeredComponents.push(s),"axisChangedHandler"in i&&(s.onAxisChangedObserver=r.onAxisValueChangedObservable.add((e=>{i.axisChangedHandler(e,this._movementState,this._featureContext,this._xrInput)}))),"buttonChangedHandler"in i&&(s.onButtonChangedObserver=r.onButtonStateChangedObservable.add((e=>{e.changes.pressed&&i.buttonChangedHandler(e.changes.pressed,this._movementState,this._featureContext,this._xrInput)})))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}},t&&void 0!==t.xrInput?(Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=yL.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:t.movementOrientationFollowsViewerPose??!0,movementOrientationFollowsController:t.movementOrientationFollowsController??!1,orientationPreferredHandedness:t.orientationPreferredHandedness,movementSpeed:t.movementSpeed??1,movementThreshold:t.movementThreshold??.25,rotationEnabled:t.rotationEnabled??!0,rotationSpeed:t.rotationSpeed??1,rotationThreshold:t.rotationThreshold??.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput):Ue.S0.Error('WebXRControllerMovement feature requires "xrInput" option.')}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)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._controllers={},!0)}_onXRFrame(e){if(this.attached){if(0!==this._movementState.rotateX&&this._featureContext.rotationEnabled){const e=.001*this._xrSessionManager.scene.getEngine().getDeltaTime()*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);if(this._featureContext.movementOrientationFollowsViewerPose)this._xrInput.xrCamera.cameraRotation.y+=e,W.PT.RotationYawPitchRollToRef(e,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection);else if(this._featureContext.movementOrientationFollowsController){this._xrInput.xrCamera.cameraRotation.y+=e;const t=this._featureContext.orientationPreferredHandedness||"right",i=Object.keys(this._controllers).find((e=>this._controllers[e]?.xrController?.inputSource.handedness===t))||Object.keys(this._controllers)[0],r=this._controllers[i];W.PT.RotationYawPitchRollToRef(e,0,0,this._tempCacheQuaternion),(r?.xrController.pointer.rotationQuaternion||W.PT.Identity()).multiplyToRef(this._tempCacheQuaternion,this._movementDirection)}else W.PT.RotationYawPitchRollToRef(3*e,0,0,this._tempCacheQuaternion),this._movementDirection.multiplyInPlace(this._tempCacheQuaternion)}else if(this._featureContext.movementOrientationFollowsViewerPose)this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);else if(this._featureContext.movementOrientationFollowsController){const e=this._featureContext.orientationPreferredHandedness||"right",t=Object.keys(this._controllers).find((t=>this._controllers[t]?.xrController.inputSource.handedness===e))||Object.keys(this._controllers)[0],i=this._controllers[t];this._movementDirection.copyFrom(i?.xrController.pointer.rotationQuaternion||W.PT.Identity())}(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(W.uq.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),W.Pq.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 e of t.registeredComponents)e.onAxisChangedObserver&&e.component.onAxisValueChangedObservable.remove(e.onAxisChangedObserver),e.onButtonChangedObserver&&e.component.onButtonStateChangedObservable.remove(e.onButtonChangedObserver);delete this._controllers[e]}}}yL.Name=hr.MOVEMENT,yL.REGISTRATIONS={default:[{allowedComponentTypes:[Km.THUMBSTICK_TYPE,Km.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(e,t,i)=>{t.rotateX=Math.abs(e.x)>i.rotationThreshold?e.x:0,t.rotateY=Math.abs(e.y)>i.rotationThreshold?e.y:0}},{allowedComponentTypes:[Km.THUMBSTICK_TYPE,Km.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(e,t,i)=>{t.moveX=Math.abs(e.x)>i.movementThreshold?e.x:0,t.moveY=Math.abs(e.y)>i.movementThreshold?e.y:0}}]},yL.Version=1,cr.AddWebXRFeature(yL.Name,((e,t)=>()=>new yL(e,t)),yL.Version,!0);class EL extends Ig{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=W.Pq.Up().negateInPlace(),this._lightColor=H.v9.White(),this._intensity=1,this._sphericalHarmonics=new Ks.O,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new z.cP,this._updateReflectionCubeMap=()=>{if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){const e=Date.now();if(e-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 hm("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new W.Pq(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=jt.c.FALLOFF_GLTF),this._hdrFilter=new Bx(this._xrSessionManager.scene.getEngine()),Ue.S0.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 null===this._canvasContext&&(this._canvasContext=this._xrSessionManager.scene.getEngine()._gl),this._canvasContext}_getXRGLBinding(){if(null===this._xrWebGLBinding){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((e=>{this._xrLightProbe=e,this.options.disableCubeMapReflection||(this._reflectionCubeMap||(this._reflectionCubeMap=new js.t(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 null===this._xrLightProbe||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),null!==this._reflectionCubeMap&&(this._reflectionCubeMap._texture&&this._reflectionCubeMap._texture.dispose(),this._reflectionCubeMap.dispose(),this._reflectionCubeMap=null)}_onXRFrame(e){if(null!==this._xrLightProbe){if(this.options.lightEstimationPollInterval){const e=Date.now();if(e-this._lightEstimationPollTime()=>new EL(e,t)),EL.Version,!1);class PL extends Ig{constructor(e){super(e),this.onEyeTrackingStartedObservable=new z.cP,this.onEyeTrackingEndedObservable=new z.cP,this.onEyeTrackingFrameUpdateObservable=new z.cP,this._eyeTrackingStartListener=e=>{this._latestEyeSpace=e.gazeSpace,this._gazeRay=new wi(W.Pq.Zero(),W.Pq.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 e=t.transform.orientation;W.AA.Quaternion[0].set(e.x,e.y,e.z,e.w),this._xrSessionManager.scene.useRightHandedSystem?W.Pq.RightHandedForwardReadOnly.rotateByQuaternionToRef(W.AA.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,W.AA.Quaternion[0].z*=-1,W.AA.Quaternion[0].w*=-1,W.Pq.LeftHandedForwardReadOnly.rotateByQuaternionToRef(W.AA.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))}}PL.Name=hr.EYE_TRACKING,PL.Version=1,cr.AddWebXRFeature(PL.Name,(e=>()=>new PL(e)),PL.Version,!1);class AL{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 RL{constructor(){this._samples=new AL(20),this._entropy=0,this.onFirstStepDetected=new z.cP}update(e,t,i,r){this._samples.push(e,t);const s=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=W.I9.Distance(s,this._samples.at(1)),this._entropy>this._entropyThreshold)return;let n;for(n=this._samePointCheckStartIdx;no&&(a=t,o=e);if(on*this._squaredProjectionDistanceThreshold)return;const p=W.AA.Vector3[0];p.set(i,r,0);const _=W.AA.Vector3[1];_.set(h.x,h.y,0);const m=W.Pq.Cross(p,_).z>0,g=s.clone(),v=s.clone();l.subtractToRef(s,h),m?(h.scaleAndAddToRef(this._axisToApexShrinkFactor,g),h.scaleAndAddToRef(this._axisToApexExtendFactor,v)):(h.scaleAndAddToRef(this._axisToApexExtendFactor,g),h.scaleAndAddToRef(this._axisToApexShrinkFactor,v)),this.onFirstStepDetected.notifyObservers({leftApex:g,rightApex:v,currentPosition:s,currentStepDirection:m?"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 ML{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new RL,this._walker=null,this._movement=new W.I9,this._millisecondsSinceLastUpdate=ML._MillisecondsPerUpdate,this.movementThisFrame=W.Pq.Zero(),this._engine=e,this._detector.onFirstStepDetected.add((e=>{this._walker||(this._walker=new IL(e.leftApex,e.rightApex,e.currentPosition,e.currentStepDirection),this._walker.onFootfall.add((()=>{Z.V.Log("Footfall!")})),this._walker.onMovement.add((e=>{this._walker.forward.scaleAndAddToRef(.024*e.deltaT,this._movement)})))}))}update(e,t){t.y=0,t.normalize(),this._millisecondsSinceLastUpdate+=this._engine.getDeltaTime(),this._millisecondsSinceLastUpdate>=ML._MillisecondsPerUpdate&&(this._millisecondsSinceLastUpdate-=ML._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 OL extends Ig{static get Name(){return hr.WALKING_LOCOMOTION}static get Version(){return 1}get locomotionTarget(){return this._locomotionTarget}set locomotionTarget(e){this._locomotionTarget=e,this._isLocomotionTargetWebXRCamera="WebXRCamera"===this._locomotionTarget.getClassName()}constructor(e,t){super(e),this._up=new W.Pq,this._forward=new W.Pq,this._position=new W.Pq,this._movement=new W.Pq,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&Z.V.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 void 0===this._sessionManager.sessionMode||"immersive-vr"===this._sessionManager.sessionMode}attach(){return!(!this.isCompatible||!super.attach()||(this._walker=new ML(this._sessionManager.scene.getEngine()),0))}detach(){return!!super.detach()&&(this._walker=null,!0)}_onXRFrame(e){const t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;const i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,r=t.transform.matrix;this._up.copyFromFloats(r[4],r[5],i*r[6]),this._forward.copyFromFloats(r[8],r[9],i*r[10]),this._position.copyFromFloats(r[12],r[13],i*r[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||W.Pq.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}cr.AddWebXRFeature(OL.Name,((e,t)=>()=>new OL(e,t)),OL.Version,!1);class DL extends zn{constructor(e,t,i,r,s,n,o=null){super(e,t,i,r,n),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this.isMultiview=s,this.createRTTProvider=n,this._originalInternalTexture=o}}class wL extends Wn{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this.onRenderTargetTextureCreatedObservable=new z.cP,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t="none"){const i=this._lastSubImages.get(t),r="right"==t?1:0,s=e.colorTextureWidth??e.textureWidth,n=e.colorTextureHeight??e.textureHeight;if(!this._renderTargetTextures[r]||i?.textureWidth!==s||i?.textureHeight!==n){let i;const o=e.depthStencilTextureWidth??s,a=e.depthStencilTextureHeight??n;s!==o&&n!==a||(i=e.depthStencilTexture),this._renderTargetTextures[r]=this._createRenderTargetTexture(s,n,null,e.colorTexture,i,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:s,framebufferHeight:n},this.onRenderTargetTextureCreatedObservable.notifyObservers({texture:this._renderTargetTextures[r],eye:t})}return this._lastSubImages.set(t,e),this._renderTargetTextures[r]}_getSubImageForEye(e){const t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null}getRenderTargetTextureForEye(e){const t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e?.eye)}_setViewportForSubImage(e,t){const i=t.colorTextureWidth??t.textureWidth,r=t.colorTextureHeight??t.textureHeight,s=t.viewport;e.x=s.x/i,e.y=s.y/r,e.width=s.width/i,e.height=s.height/r}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return!!i&&(this._setViewportForSubImage(e,i),!0)}}class NL extends DL{constructor(e,t,i){super((()=>e.textureWidth),(()=>e.textureHeight),e,"XRProjectionLayer",t,(e=>new FL(e,i,this))),this.layer=e}}class FL extends wL{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)}}const LL={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1,clearOnAccess:!1},BL={};class VL extends Ig{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={...LL,...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)}createXRWebGLLayer(e=BL){const t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new Hn(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&&"texture-array"!==e.textureType)throw new Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'.");if(!t&&"texture-array"===e.textureType)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=LL,t=this._isMultiviewEnabled){this._extendXRLayerInit(e,t),this._validateLayerInit(e,t);const i=this._xrWebGLBinding.createProjectionLayer(e),r=new NL(i,t,this._xrWebGLBinding);return this.addXRSessionLayer(r),r}_createQuadLayer(e={params:{}},t){this._extendXRLayerInit(e.params,!1);const i=this._existingLayers[0].layer.textureWidth,r=this._existingLayers[0].layer.textureHeight,s={space:this._xrSessionManager.referenceSpace,viewPixelWidth:i,viewPixelHeight:r,clearOnAccess:!0,...e.params};this._validateLayerInit(s,!1);const n=this._xrWebGLBinding.createQuadLayer(s);n.width=this._isMultiviewEnabled?1:2,n.height=1;const o=new DL((()=>n.width),(()=>n.height),n,"XRQuadLayer",!1,(e=>new wL(e,this._xrWebGLBinding,o)));t&&this._compositionLayerTextureMapping.set(n,t);const a=o.createRenderTargetTextureProvider(this._xrSessionManager);return this._layerToRTTProviderMapping.set(n,a),this.addXRSessionLayer(o),o}addFullscreenAdvancedDynamicTexture(e,t={distanceFromHeadset:1.5}){const i=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}},e),r=i.layer,s={x:0,y:0,z:-Math.max(.1,t.distanceFromHeadset)};r.transform=new XRRigidTransform(s,{x:0,y:0,z:0,w:1});const n=this._layerToRTTProviderMapping.get(r);if(!n)throw new Error("Could not find the RTT provider for the layer");const o=this._xrSessionManager.scene.layers.find((t=>t.texture===e));if(!o)throw new Error("Could not find the babylon layer for the texture");return n.onRenderTargetTextureCreatedObservable.add((e=>{e.eye&&"right"===e.eye||(e.texture.clearColor=new H.ov(0,0,0,0),o.renderTargetTextures.push(e.texture),o.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.scene.onBeforeRenderObservable.add((()=>{e.texture.render()})),o.renderTargetTextures.push(e.texture),o.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.onXRSessionEnded.addOnce((()=>{o.renderTargetTextures.splice(o.renderTargetTextures.indexOf(e.texture),1),o.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;i.transform=new XRRigidTransform({x:0,y:0,z:-10},{x:0,y:0,z:0,w:1});const r=this._layerToRTTProviderMapping.get(i);if(!r)throw new Error("Could not find the RTT provider for the layer");return r.onRenderTargetTextureCreatedObservable.add((t=>{t.texture.clearColor=new H.ov(0,0,0,0),t.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((e=>e.layer)),this._xrSessionManager.updateRenderState(t),this._projectionLayerInitialized||this._xrSessionManager._setBaseLayerWrapper(e.length>0?e.at(0):null)}isCompatible(){return!this._xrSessionManager.isNative&&"undefined"!=typeof XRWebGLBinding&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){const t=this._existingLayers;for(let i=0;i()=>new VL(e,t)),VL.Version,!1);class kL extends Ig{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 Fs.h(e,0);return t.isCube=!1,t.invertY=!1,t._useSRGBBuffer=!1,t.format="ushort"===this.depthDataFormat?2:5,t.generateMipMaps=!1,t.type="ushort"===this.depthDataFormat?5:1,t.samplingMode=7,t.width=this.width??0,t.height=this.height??0,t._cachedWrapU=1,t._cachedWrapV=1,t._hardwareTexture=new Us.d(this._cachedWebGLTexture,e._gl),t}get latestDepthBuffer(){return this._cachedDepthBuffer?"ushort"===this.depthDataFormat?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 z.cP,this.xrNativeFeatureName="depth-sensing",Ue.S0.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){return!!super.attach(e)&&(null!=this._xrSessionManager.session.depthDataFormat&&null!=this._xrSessionManager.session.depthUsage&&(this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._xrSessionManager.scene.getEngine()._gl),!0))}dispose(){this._cachedDepthImageTexture?.dispose(),this.onGetDepthInMetersAvailable.clear()}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(null!=i)for(const t of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,t,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,t,this.depthDataFormat);break;default:Ue.S0.Error("Unknown depth usage"),this.detach()}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){const r=e.getDepthInformation(t);if(null===r)return;const{data:s,width:n,height:o,rawValueToMeters:a,getDepthInMeters:l}=r;switch(this._width=n,this._height=o,this._rawValueToMeters=a,this._cachedDepthBuffer=s,this.onGetDepthInMetersAvailable.notifyObservers(l.bind(r)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=xi.CreateRTexture(null,n,o,this._xrSessionManager.scene,!1,!0,vi.g.NEAREST_SAMPLINGMODE,1)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(s)).map((e=>e*a)));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(s).map((e=>e*a)))}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){const r=e.getDepthInformation(t);if(null===r)return;const{texture:s,width:n,height:o}=r;this._width=n,this._height=o,this._cachedWebGLTexture=s;const a=this._xrSessionManager.scene,l=a.getEngine().wrapWebGLTexture(s);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=xi.CreateRTexture(null,n,o,a,!1,!0,vi.g.NEAREST_SAMPLINGMODE,"ushort"===i?0:1)),this._cachedDepthImageTexture._texture=l}getXRSessionInitExtension(){const e=null!=this.options.usagePreference&&0!==this.options.usagePreference.length,t=null!=this.options.dataFormatPreference&&0!==this.options.dataFormatPreference.length;return new Promise((i=>{i(e&&t?{depthSensing:{usagePreference:this.options.usagePreference.map((e=>{switch(e){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}})),dataFormatPreference:this.options.dataFormatPreference.map((e=>{switch(e){case"ushort":return"luminance-alpha";case"float":return"float32"}}))}}:{})}))}}kL.Name=hr.DEPTH_SENSING,kL.Version=1,cr.AddWebXRFeature(kL.Name,((e,t)=>()=>new kL(e,t)),kL.Version,!1);Cs.l.ShadersStore.velocityPixelShader="precision highp float;\n#define CUSTOM_FRAGMENT_BEGIN\nvarying vec4 clipPos;varying vec4 previousClipPos;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nhighp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Cs.l.ShadersStore.velocityVertexShader="#define CUSTOM_VERTEX_BEGIN\n#define VELOCITY\nattribute vec3 position;\n#include\nuniform mat4 viewProjection;uniform mat4 previousViewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR;\n#endif\nvarying vec4 clipPos;varying vec4 previousClipPos;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;}\n#elif\nclipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";class UL extends ln.${constructor(e,t,i,r=512){super("spacewarp rtt",r,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[W.uq.Identity(),W.uq.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 xo("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add((e=>{this._previousWorldMatrices[e.uniqueId]=this._previousWorldMatrices[e.uniqueId]||e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[e.uniqueId]),this._previousWorldMatrices[e.uniqueId]=e.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((e=>{this._originalPairing.push([e,e.material]),e.material=this._velocityMaterial})),super.render(e,t),this._originalPairing.forEach((e=>{e[0].material=e[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 GL{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("XRProjectionLayer"!==t.layerType)throw new Error('For Space Warp, the base layer type should "XRProjectionLayer".');const i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,r,s){if(!this._engine)throw new Error("Engine is disposed");const n={width:e,height:t},o=new UL(r,s,this._scene,n),a=o.renderTarget;return i&&(a._framebuffer=i),a._colorTextureArray=r,a._depthStencilTextureArray=s,o.disableRescaling(),o.renderListPredicate=()=>!0,o}_getRenderTargetForSubImage(e,t){const i=this._lastSubImages.get(t);let r=this._renderTargetTextures.get(t.eye);const s=e.motionVectorTextureWidth,n=e.motionVectorTextureHeight;return r&&i?.textureWidth===s&&i?.textureHeight==n||(r=this._createRenderTargetTexture(s,n,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,r),this._framebufferDimensions={framebufferWidth:s,framebufferHeight:n}),this._lastSubImages.set(t,e),r}trySetViewportForView(e,t){const i=this._lastSubImages.get(t)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}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 zL extends Ig{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[hr.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 GL(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)}}zL.Name=hr.SPACE_WARP,zL.Version=1,cr.AddWebXRFeature(zL.Name,(e=>()=>new zL(e)),zL.Version,!1);class WL extends Ig{constructor(e,t={}){super(e),this.options=t,this._cachedInternalTextures=[],this.texturesData=[],this.viewIndex=[],this.cameraIntrinsics=[],this.onTexturesUpdatedObservable=new z.cP,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)}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)}dispose(){super.dispose(),this.onTexturesUpdatedObservable.clear()}_updateCameraIntrinsics(e,t){const i={width:e.camera.width,height:e.camera.height,x:0,y:0},r=e.projectionMatrix,s=(1-r[8])*i.width/2+i.x,n=(1-r[9])*i.height/2+i.y,o=i.width/2*r[0],a=i.height/2*r[5],l=i.width/2*r[4];this.cameraIntrinsics[t]={u0:s,v0:n,ax:o,ay:a,gamma:l,width:i.width,height:i.height,viewportX:i.x,viewportY:i.y}}_updateInternalTextures(e,t=0){if(!e.camera)return!1;this.viewIndex[t]=e.eye;const i=this._glBinding?.getCameraImage(e.camera);if(this._cachedInternalTextures[t])this._cachedInternalTextures[t]._hardwareTexture?.set(i);else{const r=new Fs.h(this._xrSessionManager.scene.getEngine(),0,!0);r.invertY=!1,r.format=5,r.generateMipMaps=!0,r.type=0,r.samplingMode=3,r.width=e.camera.width,r.height=e.camera.height,r._cachedWrapU=1,r._cachedWrapV=1,r._hardwareTexture=new Us.d(i,this._glContext),this._cachedInternalTextures[t]=r;const s=new js.t(this._xrSessionManager.scene);s.name=`WebXR Raw Camera Access (${t})`,s._texture=this._cachedInternalTextures[t],this.texturesData[t]=s,this._updateCameraIntrinsics(e,t)}return this._cachedInternalTextures[t].isReady=!0,!0}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(!i||!i.views)return;let r=!0;i.views.forEach(((e,t)=>{r=r&&this._updateInternalTextures(e,t)})),r&&this.onTexturesUpdatedObservable.notifyObservers(this.texturesData)}}WL.Name=hr.RAW_CAMERA_ACCESS,WL.Version=1,cr.AddWebXRFeature(WL.Name,((e,t)=>()=>new WL(e,t)),WL.Version,!1);class HL extends bg{constructor(e,t,i){super(e,XL[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(){}}Eg.RegisterController("generic-hand-select-grasp",((e,t)=>new HL(t,e.gamepad,e.handedness)));const XL={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 qL extends bg{constructor(e,t,i){super(e,YL["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="";return e="left"===this.handedness?qL.MODEL_LEFT_FILENAME:qL.MODEL_RIGHT_FILENAME,{filename:e,path:qL.MODEL_BASE_URL+"default/"}}_getModelLoadingConstraints(){const e=xg.IsPluginForExtensionAvailable(".glb");return e||Z.V.Warn("glTF / glb loaded was not registered, using generic controller instead"),e}_processLoadedModel(e){this.rootMesh&&(this.getComponentIds().forEach(((e,t)=>{if(!this.disableAnimation&&e&&this.rootMesh){const i=this._mapping.buttons[e],r=i.rootNodeName;if(!r)return void Z.V.Log("Skipping unknown button at index: "+t+" with mapped name: "+e);const s=this._getChildByName(this.rootMesh,r);if(!s)return void Z.V.Warn("Missing button mesh with name: "+r);if(i.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.valueNodeName),i.pressedMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.pressedNodeName),i.unpressedMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.unpressedNodeName),i.valueMesh&&i.pressedMesh&&i.unpressedMesh){const t=this.getComponent(e);t&&t.onButtonStateChangedObservable.add((e=>{this._lerpTransform(i,e.value)}),void 0,!0)}else Z.V.Warn("Missing button submesh under mesh with name: "+r)}})),this.getComponentIds().forEach((e=>{const t=this.getComponent(e);t.isAxes()&&["x-axis","y-axis"].forEach((i=>{if(!this.rootMesh)return;const r=this._mapping.axes[e][i],s=this._getChildByName(this.rootMesh,r.rootNodeName);s?(r.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.valueNodeName),r.minMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.minNodeName),r.maxMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.maxNodeName),r.valueMesh&&r.minMesh&&r.maxMesh?t&&t.onAxisValueChangedObservable.add((e=>{const t="x-axis"===i?e.x:e.y;this._lerpTransform(r,t,!0)}),void 0,!0):Z.V.Warn("Missing axis submesh under mesh with name: "+r.rootNodeName)):Z.V.Warn("Missing axis mesh with name: "+r.rootNodeName)}))})))}_setRootMesh(e){let t;this.rootMesh=new Yt(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;inew qL(t,e.gamepad,e.handedness)));const YL={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 KL extends bg{constructor(e,t,i,r=!1,s=!1){super(e,jL[i],t,i),this._forceLegacyControllers=s,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";return e="left"===this.handedness?KL.MODEL_LEFT_FILENAME:KL.MODEL_RIGHT_FILENAME,{filename:e,path:this._isQuest()?KL.QUEST_MODEL_BASE_URL:KL.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){const t=this._isQuest(),i="right"===this.handedness?-1:1;this.getComponentIds().forEach((e=>{const r=e&&this.getComponent(e);r&&r.onButtonStateChangedObservable.add((r=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(t||(this._modelRootNode.getChildren()[3].rotation.x=.2*-r.value,this._modelRootNode.getChildren()[3].position.y=.005*-r.value,this._modelRootNode.getChildren()[3].position.z=.005*-r.value));case"xr-standard-squeeze":return void(t||(this._modelRootNode.getChildren()[4].position.x=i*r.value*.0035));case"xr-standard-thumbstick":return;case"a-button":case"x-button":return void(t||(r.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0));case"b-button":case"y-button":return void(t||(r.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0))}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new Yt(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=W.PT.FromEulerAngles(0,Math.PI,0)),e.forEach((e=>{e.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}}KL.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",KL.MODEL_LEFT_FILENAME="left.babylon",KL.MODEL_RIGHT_FILENAME="right.babylon",KL.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",Eg.RegisterController("oculus-touch",((e,t)=>new KL(t,e.gamepad,e.handedness))),Eg.RegisterController("oculus-touch-legacy",((e,t)=>new KL(t,e.gamepad,e.handedness,!0)));const jL={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 $L extends bg{constructor(e,t,i){super(e,QL[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){return{filename:$L.MODEL_FILENAME,path:$L.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=e&&this.getComponent(e);t&&t.onButtonStateChangedObservable.add((t=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(this._modelRootNode.getChildren()[6].rotation.x=.15*-t.value);case"xr-standard-touchpad":case"xr-standard-squeeze":return}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new Yt(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1})),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=W.PT.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}$L.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",$L.MODEL_FILENAME="wand.babylon",Eg.RegisterController("htc-vive",((e,t)=>new $L(t,e.gamepad,e.handedness)));const QL={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 ZL{get session(){return this._nativeImpl.session}constructor(e){this._nativeImpl=e,this._xrTransform=new XRRigidTransform,this._xrPose={transform:this._xrTransform,emulatedPosition:!1},this._xrPoseVectorData=new Float32Array(8),this.fillPoses=this._nativeImpl.fillPoses.bind(this._nativeImpl),this.getViewerPose=this._nativeImpl.getViewerPose.bind(this._nativeImpl),this.getHitTestResults=this._nativeImpl.getHitTestResults.bind(this._nativeImpl),this.getHitTestResultsForTransientInput=()=>{throw new Error("XRFrame.getHitTestResultsForTransientInput not supported on native.")},this.createAnchor=this._nativeImpl.createAnchor.bind(this._nativeImpl),this.getJointPose=this._nativeImpl.getJointPose.bind(this._nativeImpl),this.fillJointRadii=this._nativeImpl.fillJointRadii.bind(this._nativeImpl),this.getLightEstimate=()=>{throw new Error("XRFrame.getLightEstimate not supported on native.")},this.getImageTrackingResults=()=>this._nativeImpl._imageTrackingResults??[]}getPose(e,t){if(!this._nativeImpl.getPoseData(e,t,this._xrPoseVectorData.buffer,this._xrTransform.matrix.buffer))return;const i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];const r=this._xrTransform.orientation;return r.x=this._xrPoseVectorData[4],r.y=this._xrPoseVectorData[5],r.z=this._xrPoseVectorData[6],r.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw new Error("This function is not available in Babylon Native")}}fh("NativeXRFrame",ZL);class JL{constructor(e,t=JL.UNITMODE_PIXEL,i=!0){this.negativeValueAllowed=i,this._value=1,this._unit=JL.UNITMODE_PIXEL,this.ignoreAdaptiveScaling=!1,this.onChangedObservable=new z.cP,this._value=e,this._unit=t,this._originalUnit=t}get isPercentage(){return this._unit===JL.UNITMODE_PERCENTAGE}get isPixel(){return this._unit===JL.UNITMODE_PIXEL}get internalValue(){return this._value}get value(){return this._value}set value(e){e!==this._value&&(this._value=e,this.onChangedObservable.notifyObservers())}get unit(){return this._unit}set unit(e){e!==this._unit&&(this._unit=e,this.onChangedObservable.notifyObservers())}getValueInPixel(e,t){return this.isPixel?this.getValue(e):this.getValue(e)*t}updateInPlace(e,t=JL.UNITMODE_PIXEL){return this.value===e&&this.unit===t||(this._value=e,this._unit=t,this.onChangedObservable.notifyObservers()),this}getValue(e){if(e&&!this.ignoreAdaptiveScaling&&this.unit!==JL.UNITMODE_PERCENTAGE){let t=0,i=0;if(e.idealWidth&&(t=Math.ceil(this._value*e.getSize().width/e.idealWidth)),e.idealHeight&&(i=Math.ceil(this._value*e.getSize().height/e.idealHeight)),e.useSmallestIdeal&&e.idealWidth&&e.idealHeight)return window.innerWidth{this._markAsDirty(),this._resetFontCache()}))),this._markAsDirty(),this._resetFontCache()}get _isFontSizeInPercentage(){return this._fontSize.isPercentage}get fontSizeInPixels(){const e=this._style?this._style._fontSize:this._fontSize;return e.isPixel?e.getValue(this._host):e.getValueInPixel(this._host,this._tempParentMeasure.height||this._cachedParentMeasure.height)}set fontSizeInPixels(e){isNaN(e)||(this.fontSize=e+"px")}get fontSize(){return this._fontSize.toString(this._host)}set fontSize(e){this._fontSize.toString(this._host)!==e&&this._fontSize.fromString(e)&&(this._markAsDirty(),this._resetFontCache())}get color(){return this._color}set color(e){this._color!==e&&(this._color=e,this._markAsDirty())}get gradient(){return this._gradient}set gradient(e){this._gradient!==e&&(this._gradient=e,this._markAsDirty())}get zIndex(){return this._zIndex}set zIndex(e){this.zIndex!==e&&(this._zIndex=e,this.parent&&this.parent._reOrderControl(this))}get notRenderable(){return this._doNotRender}set notRenderable(e){this._doNotRender!==e&&(this._doNotRender=e,this._markAsDirty())}get isVisible(){return this._isVisible}set isVisible(e){this._isVisible!==e&&(this._isVisible=e,this._markAsDirty(!0),this.onIsVisibleChangedObservable.notifyObservers(e))}get isDirty(){return this._isDirty}get linkedMesh(){return this._linkedMesh}get descendantsOnlyPadding(){return this._descendantsOnlyPadding}set descendantsOnlyPadding(e){this._descendantsOnlyPadding!==e&&(this._descendantsOnlyPadding=e,this._markAsDirty())}get paddingLeft(){return this._paddingLeft.toString(this._host)}set paddingLeft(e){this._paddingLeft.fromString(e)&&this._markAsDirty()}get paddingLeftInPixels(){return this._paddingLeft.getValueInPixel(this._host,this._cachedParentMeasure.width)}set paddingLeftInPixels(e){isNaN(e)||(this.paddingLeft=e+"px")}get _paddingLeftInPixels(){return this._descendantsOnlyPadding?0:this.paddingLeftInPixels}get paddingRight(){return this._paddingRight.toString(this._host)}set paddingRight(e){this._paddingRight.fromString(e)&&this._markAsDirty()}get paddingRightInPixels(){return this._paddingRight.getValueInPixel(this._host,this._cachedParentMeasure.width)}set paddingRightInPixels(e){isNaN(e)||(this.paddingRight=e+"px")}get _paddingRightInPixels(){return this._descendantsOnlyPadding?0:this.paddingRightInPixels}get paddingTop(){return this._paddingTop.toString(this._host)}set paddingTop(e){this._paddingTop.fromString(e)&&this._markAsDirty()}get paddingTopInPixels(){return this._paddingTop.getValueInPixel(this._host,this._cachedParentMeasure.height)}set paddingTopInPixels(e){isNaN(e)||(this.paddingTop=e+"px")}get _paddingTopInPixels(){return this._descendantsOnlyPadding?0:this.paddingTopInPixels}get paddingBottom(){return this._paddingBottom.toString(this._host)}set paddingBottom(e){this._paddingBottom.fromString(e)&&this._markAsDirty()}get paddingBottomInPixels(){return this._paddingBottom.getValueInPixel(this._host,this._cachedParentMeasure.height)}set paddingBottomInPixels(e){isNaN(e)||(this.paddingBottom=e+"px")}get _paddingBottomInPixels(){return this._descendantsOnlyPadding?0:this.paddingBottomInPixels}get left(){return this._left.toString(this._host)}set left(e){this._left.fromString(e)&&this._markAsDirty()}get leftInPixels(){return this._left.getValueInPixel(this._host,this._cachedParentMeasure.width)}set leftInPixels(e){isNaN(e)||(this.left=e+"px")}get top(){return this._top.toString(this._host)}set top(e){this._top.fromString(e)&&this._markAsDirty()}get topInPixels(){return this._top.getValueInPixel(this._host,this._cachedParentMeasure.height)}set topInPixels(e){isNaN(e)||(this.top=e+"px")}get linkOffsetX(){return this._linkOffsetX.toString(this._host)}set linkOffsetX(e){this._linkOffsetX.fromString(e)&&this._markAsDirty()}get linkOffsetXInPixels(){return this._linkOffsetX.getValueInPixel(this._host,this._cachedParentMeasure.width)}set linkOffsetXInPixels(e){isNaN(e)||(this.linkOffsetX=e+"px")}get linkOffsetY(){return this._linkOffsetY.toString(this._host)}set linkOffsetY(e){this._linkOffsetY.fromString(e)&&this._markAsDirty()}get linkOffsetYInPixels(){return this._linkOffsetY.getValueInPixel(this._host,this._cachedParentMeasure.height)}set linkOffsetYInPixels(e){isNaN(e)||(this.linkOffsetY=e+"px")}get centerX(){return this._currentMeasure.left+this._currentMeasure.width/2}get centerY(){return this._currentMeasure.top+this._currentMeasure.height/2}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled===e)return;this._isEnabled=e,this._markAsDirty();const t=e=>{if(e.host){for(const t in e.host._lastControlOver)e===this.host._lastControlOver[t]&&(e._onPointerOut(e,null,!0),delete e.host._lastControlOver[t]);void 0!==e.children&&e.children.forEach(t)}};t(this),this.onEnabledStateChangedObservable.notifyObservers(e)}get disabledColor(){return this._disabledColor}set disabledColor(e){this._disabledColor!==e&&(this._disabledColor=e,this._markAsDirty())}get disabledColorItem(){return this._disabledColorItem}set disabledColorItem(e){this._disabledColorItem!==e&&(this._disabledColorItem=e,this._markAsDirty())}get focusedColor(){return this._focusedColor}set focusedColor(e){this._focusedColor=e}onBlur(){this._isFocused&&(this._isFocused=!1,this.focusedColor&&null!=this._unfocusedColor&&(this.color=this._unfocusedColor),this.onBlurObservable.notifyObservers(this))}onFocus(){this._isFocused=!0,this.focusedColor&&(this._unfocusedColor=this.color,this.color=this.focusedColor),this.onFocusObservable.notifyObservers(this)}keepsFocusWith(){return null}focus(){this._host.moveFocusToControl(this)}blur(){this._host.focusedControl=null}processKeyboard(e){"Enter"===e.key&&this.onEnterPressedObservable.notifyObservers(this),this.onKeyboardEventProcessedObservable.notifyObservers(e,-1,this)}constructor(e){this.name=e,this._alpha=1,this._alphaSet=!1,this._zIndex=0,this._currentMeasure=sB.Empty(),this._tempPaddingMeasure=sB.Empty(),this._fontFamily="",this._fontStyle="",this._fontWeight="",this._fontSize=new JL(18,JL.UNITMODE_PIXEL,!1),this._width=new JL(1,JL.UNITMODE_PERCENTAGE,!1),this._height=new JL(1,JL.UNITMODE_PERCENTAGE,!1),this._color="",this._style=null,this._horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_CENTER,this._verticalAlignment=lB.VERTICAL_ALIGNMENT_CENTER,this._isDirty=!0,this._wasDirty=!1,this._tempParentMeasure=sB.Empty(),this._prevCurrentMeasureTransformedIntoGlobalSpace=sB.Empty(),this._cachedParentMeasure=sB.Empty(),this._descendantsOnlyPadding=!1,this._paddingLeft=new JL(0),this._paddingRight=new JL(0),this._paddingTop=new JL(0),this._paddingBottom=new JL(0),this._left=new JL(0),this._top=new JL(0),this._scaleX=1,this._scaleY=1,this._rotation=0,this._transformCenterX=.5,this._transformCenterY=.5,this._transformMatrix=oB.Identity(),this._invertTransformMatrix=oB.Identity(),this._transformedPosition=W.I9.Zero(),this._isMatrixDirty=!0,this._isVisible=!0,this._isHighlighted=!1,this._highlightColor="#4affff",this._highlightLineWidth=2,this._fontSet=!1,this._dummyVector2=W.I9.Zero(),this._downCount=0,this._enterCount=-1,this._doNotRender=!1,this._downPointerIds={},this._evaluatedMeasure=new sB(0,0,0,0),this._evaluatedParentMeasure=new sB(0,0,0,0),this._isEnabled=!0,this._disabledColor="#9a9a9a",this._disabledColorItem="#6a6a6a",this._isReadOnly=!1,this._gradient=null,this._rebuildLayout=!1,this.onEnabledStateChangedObservable=new z.cP,this._customData={},this._isClipped=!1,this._automaticSize=!1,this.metadata=null,this.isHitTestVisible=!0,this.isPointerBlocker=!1,this.isFocusInvisible=!1,this._clipChildren=!0,this._clipContent=!0,this.useBitmapCache=!1,this._shadowOffsetX=0,this._shadowOffsetY=0,this._shadowBlur=0,this._previousShadowBlur=0,this._shadowColor="black",this.hoverCursor="",this._linkOffsetX=new JL(0),this._linkOffsetY=new JL(0),this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new z.cP,this.onWheelObservable=new z.cP,this.onPointerMoveObservable=new z.cP,this.onPointerOutObservable=new z.cP,this.onPointerDownObservable=new z.cP,this.onPointerUpObservable=new z.cP,this.onPointerClickObservable=new z.cP,this.onEnterPressedObservable=new z.cP,this.onPointerEnterObservable=new z.cP,this.onDirtyObservable=new z.cP,this.onBeforeDrawObservable=new z.cP,this.onAfterDrawObservable=new z.cP,this.onDisposeObservable=new z.cP,this.onIsVisibleChangedObservable=new z.cP,this.isSerializable=!0,this._fixedRatio=0,this._fixedRatioMasterIsWidth=!0,this.animations=null,this._focusedColor=null,this.tabIndex=-1,this._isFocused=!1,this._unfocusedColor=null,this.onFocusObservable=new z.cP,this.onBlurObservable=new z.cP,this.onKeyboardEventProcessedObservable=new z.cP,this._tmpMeasureA=new sB(0,0,0,0)}_getTypeName(){return"Control"}getAscendantOfClass(e){return this.parent?this.parent.getClassName()===e?this.parent:this.parent.getAscendantOfClass(e):null}markAsDirty(e=!1){this._markAsDirty(e)}markAllAsDirty(){this._markAllAsDirty()}_resetFontCache(){this._fontSet=!0,this._markAsDirty()}isAscendant(e){return!!this.parent&&(this.parent===e||this.parent.isAscendant(e))}getLocalCoordinates(e){const t=W.I9.Zero();return this.getLocalCoordinatesToRef(e,t),t}getLocalCoordinatesToRef(e,t){return t.x=e.x-this._currentMeasure.left,t.y=e.y-this._currentMeasure.top,this}getParentLocalCoordinates(e){const t=W.I9.Zero();return t.x=e.x-this._cachedParentMeasure.left,t.y=e.y-this._cachedParentMeasure.top,t}moveToVector3(e,t){if(!this._host||this.parent!==this._host._rootContainer)return void Ue.S0.Error("Cannot move a control to a vector3 if the control is not at root level");this.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,this.verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP;const i=this._host._getGlobalViewport(),r=W.Pq.Project(e,W.uq.IdentityReadOnly,t.getTransformMatrix(),i);this._moveToProjectedPosition(r),r.z<0||r.z>1?this.notRenderable=!0:this.notRenderable=!1}getDescendantsToRef(e,t=!1,i){}getDescendants(e,t){const i=[];return this.getDescendantsToRef(i,e,t),i}linkWithMesh(e){if(!this._host||this.parent&&this.parent!==this._host._rootContainer)return void(e&&Ue.S0.Error("Cannot link a control to a mesh if the control is not at root level"));const t=this._host._linkedControls.indexOf(this);if(-1!==t)return this._linkedMesh=e,void(e||this._host._linkedControls.splice(t,1));e&&(this.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,this.verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP,this._linkedMesh=e,this._host._linkedControls.push(this))}setPadding(e,t,i,r){const s=e,n=t??s,o=i??s,a=r??n;this.paddingTop=s,this.paddingRight=n,this.paddingBottom=o,this.paddingLeft=a}setPaddingInPixels(e,t,i,r){const s=e,n=t??s,o=i??s,a=r??n;this.paddingTopInPixels=s,this.paddingRightInPixels=n,this.paddingBottomInPixels=o,this.paddingLeftInPixels=a}_moveToProjectedPosition(e){const t=this._left.getValue(this._host),i=this._top.getValue(this._host),r=this.parent?._currentMeasure;r&&this._processMeasures(r,this._host.getContext());let s=e.x+this._linkOffsetX.getValue(this._host)-this._currentMeasure.width/2,n=e.y+this._linkOffsetY.getValue(this._host)-this._currentMeasure.height/2;const o=this._left.ignoreAdaptiveScaling&&this._top.ignoreAdaptiveScaling;o&&(Math.abs(s-t)<.5&&(s=t),Math.abs(n-i)<.5&&(n=i)),(o||t!==s||i!==n)&&(this.left=s+"px",this.top=n+"px",this._left.ignoreAdaptiveScaling=!0,this._top.ignoreAdaptiveScaling=!0,this._markAsDirty())}_offsetLeft(e){this._isDirty=!0,this._currentMeasure.left+=e}_offsetTop(e){this._isDirty=!0,this._currentMeasure.top+=e}_markMatrixAsDirty(){this._isMatrixDirty=!0,this._flagDescendantsAsMatrixDirty()}_flagDescendantsAsMatrixDirty(){}_intersectsRect(e,t){return this._transform(t),!(this._evaluatedMeasure.left>=e.left+e.width||this._evaluatedMeasure.top>=e.top+e.height||this._evaluatedMeasure.left+this._evaluatedMeasure.width<=e.left||this._evaluatedMeasure.top+this._evaluatedMeasure.height<=e.top)}_computeAdditionalOffsetX(){return 0}_computeAdditionalOffsetY(){return 0}invalidateRect(){if(this._transform(),this.host&&this.host.useInvalidateRectOptimization){this._currentMeasure.transformToRef(this._transformMatrix,this._tmpMeasureA),sB.CombineToRef(this._tmpMeasureA,this._prevCurrentMeasureTransformedIntoGlobalSpace,this._tmpMeasureA);const e=this.shadowOffsetX,t=this.shadowOffsetY,i=Math.max(this._previousShadowBlur,this.shadowBlur),r=Math.min(Math.min(e,0)-2*i,0),s=Math.max(Math.max(e,0)+2*i,0),n=Math.min(Math.min(t,0)-2*i,0),o=Math.max(Math.max(t,0)+2*i,0),a=this._computeAdditionalOffsetX(),l=this._computeAdditionalOffsetY();this.host.invalidateRect(Math.floor(this._tmpMeasureA.left+r-a),Math.floor(this._tmpMeasureA.top+n-l),Math.ceil(this._tmpMeasureA.left+this._tmpMeasureA.width+s+a),Math.ceil(this._tmpMeasureA.top+this._tmpMeasureA.height+o+l))}}_markAsDirty(e=!1){(this._isVisible||e)&&(this._isDirty=!0,this._markMatrixAsDirty(),this._host&&this._host.markAsDirty())}_markAllAsDirty(){this._markAsDirty(),this._font&&this._prepareFont()}_link(e){this._host=e,this._host&&(this.uniqueId=this._host.getScene().getUniqueId())}_transform(e){if(!this._isMatrixDirty&&1===this._scaleX&&1===this._scaleY&&0===this._rotation)return;const t=this._currentMeasure.width*this._transformCenterX+this._currentMeasure.left,i=this._currentMeasure.height*this._transformCenterY+this._currentMeasure.top;e&&(e.translate(t,i),e.rotate(this._rotation),e.scale(this._scaleX,this._scaleY),e.translate(-t,-i)),(this._isMatrixDirty||this._cachedOffsetX!==t||this._cachedOffsetY!==i)&&(this._cachedOffsetX=t,this._cachedOffsetY=i,this._isMatrixDirty=!1,this._flagDescendantsAsMatrixDirty(),oB.ComposeToRef(-t,-i,this._rotation,this._scaleX,this._scaleY,this.parent?this.parent._transformMatrix:null,this._transformMatrix),this._transformMatrix.invertToRef(this._invertTransformMatrix),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure))}_renderHighlight(e){this.isHighlighted&&(e.save(),e.strokeStyle=this._highlightColor,e.lineWidth=this._highlightLineWidth,this._renderHighlightSpecific(e),e.restore())}_renderHighlightSpecific(e){e.strokeRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)}_getColor(e){return this.gradient?this.gradient.getCanvasGradient(e):this.color}_applyStates(e){this._isFontSizeInPercentage&&(this._fontSet=!0),this._host&&this._host.useSmallestIdeal&&!this._font&&(this._fontSet=!0),this._fontSet&&(this._prepareFont(),this._fontSet=!1),this._font&&(e.font=this._font),(this._color||this.gradient)&&(e.fillStyle=this._getColor(e)),lB.AllowAlphaInheritance?e.globalAlpha*=this._alpha:this._alphaSet&&(e.globalAlpha=this.parent&&!this.parent.renderToIntermediateTexture?this.parent.alpha*this._alpha:this._alpha)}_layout(e,t){if(!this.isDirty&&(!this.isVisible||this.notRenderable))return!1;if(this._isDirty||!this._cachedParentMeasure.isEqualsTo(e)){this.host._numLayoutCalls++,this._currentMeasure.addAndTransformToRef(this._transformMatrix,0|-this._paddingLeftInPixels,0|-this._paddingTopInPixels,0|this._paddingRightInPixels,0|this._paddingBottomInPixels,this._prevCurrentMeasureTransformedIntoGlobalSpace),t.save(),this._applyStates(t);let i=0;do{this._rebuildLayout=!1,this._processMeasures(e,t),i++}while(this._rebuildLayout&&i<3);i>=3&&Z.V.Error(`Layout cycle detected in GUI (Control name=${this.name}, uniqueId=${this.uniqueId})`),t.restore(),this.invalidateRect(),this._evaluateClippingState(e)}return this._wasDirty=this._isDirty,this._isDirty=!1,!0}_processMeasures(e,t){this._tempPaddingMeasure.copyFrom(e),this.parent&&this.parent.descendantsOnlyPadding&&(this._tempPaddingMeasure.left+=this.parent.paddingLeftInPixels,this._tempPaddingMeasure.top+=this.parent.paddingTopInPixels,this._tempPaddingMeasure.width-=this.parent.paddingLeftInPixels+this.parent.paddingRightInPixels,this._tempPaddingMeasure.height-=this.parent.paddingTopInPixels+this.parent.paddingBottomInPixels),this._currentMeasure.copyFrom(this._tempPaddingMeasure),this._preMeasure(this._tempPaddingMeasure,t),this._measure(),this._postMeasure(this._tempPaddingMeasure,t),this._computeAlignment(this._tempPaddingMeasure,t),this._currentMeasure.left=0|this._currentMeasure.left,this._currentMeasure.top=0|this._currentMeasure.top,this._currentMeasure.width=0|this._currentMeasure.width,this._currentMeasure.height=0|this._currentMeasure.height,this._additionalProcessing(this._tempPaddingMeasure,t),this._cachedParentMeasure.copyFrom(this._tempPaddingMeasure),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure),this.onDirtyObservable.hasObservers()&&this.onDirtyObservable.notifyObservers(this)}_evaluateClippingState(e){if(this._transform(),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure),this.parent&&this.parent.clipChildren){if(e.transformToRef(this.parent._transformMatrix,this._evaluatedParentMeasure),this._evaluatedMeasure.left>this._evaluatedParentMeasure.left+this._evaluatedParentMeasure.width)return void(this._isClipped=!0);if(this._evaluatedMeasure.left+this._evaluatedMeasure.widththis._evaluatedParentMeasure.top+this._evaluatedParentMeasure.height)return void(this._isClipped=!0);if(this._evaluatedMeasure.top+this._evaluatedMeasure.heightthis._currentMeasure.left+this._currentMeasure.width||tthis._currentMeasure.top+this._currentMeasure.height||(this.isPointerBlocker&&(this._host._shouldBlockPointer=!0),0))}_processPicking(e,t,i,r,s,n,o,a){return!(!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this._doNotRender||!this.contains(e,t)||(this._processObservables(r,e,t,i,s,n,o,a),0))}_onPointerMove(e,t,i,r){this.onPointerMoveObservable.notifyObservers(t,-1,e,this,r)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerMove(e,t,i,r)}_onPointerEnter(e,t){return!!this._isEnabled&&(!(this._enterCount>0)&&(-1===this._enterCount&&(this._enterCount=0),this._enterCount++,this.onPointerEnterObservable.notifyObservers(this,-1,e,this,t)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerEnter(e,t),!0))}_onPointerOut(e,t,i=!1){if(!i&&!this._isEnabled)return;this._enterCount=0;let r=!0;e.isAscendant(this)||(r=this.onPointerOutObservable.notifyObservers(this,-1,e,this,t)),r&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerOut(e,t,i)}_onPointerDown(e,t,i,r,s){return this._onPointerEnter(this,s),-1!==this.tabIndex&&(this.host.focusedControl=this),0===this._downCount&&(this._downCount++,this._downPointerIds[i]=!0,this.onPointerDownObservable.notifyObservers(new nB(t,r),-1,e,this,s)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerDown(e,t,i,r,s),s&&this.uniqueId!==this._host.rootContainer.uniqueId&&this._host._capturedPointerIds.add(s.event.pointerId),!0)}_onPointerUp(e,t,i,r,s,n){if(!this._isEnabled)return;this._downCount=0,delete this._downPointerIds[i];let o=s;s&&(this._enterCount>0||-1===this._enterCount)&&(this._host.usePointerTapForClickEvent||(o=this.onPointerClickObservable.notifyObservers(new nB(t,r),-1,e,this,n))),this.onPointerUpObservable.notifyObservers(new nB(t,r),-1,e,this,n)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerUp(e,t,i,r,o,n),n&&this.uniqueId!==this._host.rootContainer.uniqueId&&this._host._capturedPointerIds.delete(n.event.pointerId),this._host.usePointerTapForClickEvent&&this.isPointerBlocker&&(this._host._shouldBlockPointer=!1)}_onPointerPick(e,t,i,r,s,n){if(!this._host.usePointerTapForClickEvent)return!1;let o=s;return s&&(this._enterCount>0||-1===this._enterCount)&&(o=this.onPointerClickObservable.notifyObservers(new nB(t,r),-1,e,this,n)),this.onPointerUpObservable.notifyObservers(new nB(t,r),-1,e,this,n)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerPick(e,t,i,r,o,n),this._host.usePointerTapForClickEvent&&this.isPointerBlocker&&(this._host._shouldBlockPointer=!0),!0}_forcePointerUp(e=null){if(null!==e)this._onPointerUp(this,W.I9.Zero(),e,0,!0);else for(const e in this._downPointerIds)this._onPointerUp(this,W.I9.Zero(),+e,0,!0)}_onWheelScroll(e,t){this._isEnabled&&this.onWheelObservable.notifyObservers(new W.I9(e,t))&&null!=this.parent&&this.parent._onWheelScroll(e,t)}_onCanvasBlur(){}_processObservables(e,t,i,r,s,n,o,a){if(!this._isEnabled)return!1;if(this._dummyVector2.copyFromFloats(t,i),e===yi.Zp.POINTERMOVE){this._onPointerMove(this,this._dummyVector2,s,r);const e=this._host._lastControlOver[s];return e&&e!==this&&e._onPointerOut(this,r),e!==this&&this._onPointerEnter(this,r),this._host._lastControlOver[s]=this,!0}if(e===yi.Zp.POINTERDOWN)return this._onPointerDown(this,this._dummyVector2,s,n,r),this._host._registerLastControlDown(this,s),this._host._lastPickedControl=this,!0;if(e===yi.Zp.POINTERUP)return this._host._lastControlDown[s]&&this._host._lastControlDown[s]._onPointerUp(this,this._dummyVector2,s,n,!0,r),this._host.usePointerTapForClickEvent||delete this._host._lastControlDown[s],!0;if(e===yi.Zp.POINTERWHEEL){if(this._host._lastControlOver[s])return this._host._lastControlOver[s]._onWheelScroll(o,a),!0}else if(e===yi.Zp.POINTERTAP)return this._host._lastControlDown[s]&&this._host._lastControlDown[s]._onPointerPick(this,this._dummyVector2,s,n,!0,r),delete this._host._lastControlDown[s],!0;return!1}_getStyleProperty(e,t){const i=(this._style&&this._style[e])??this[e];return!i&&this.parent?this.parent._getStyleProperty(e,t):this.parent?i:t}_prepareFont(){(this._font||this._fontSet)&&(this._font=this._getStyleProperty("fontStyle","")+" "+this._getStyleProperty("fontWeight","")+" "+this.fontSizeInPixels+"px "+this._getStyleProperty("fontFamily","Arial"),this._fontOffset=lB._GetFontOffset(this._font,this._host?.getScene()?.getEngine()),this.getDescendants().forEach((e=>e._markAllAsDirty())))}isDimensionFullyDefined(e){return this.getDimension(e).isPixel}getDimension(e){return"width"===e?this._width:this._height}clone(e){const t={};this.serialize(t,!0);const i=new(Ue.S0.Instantiate("BABYLON.GUI."+t.className));return i.parse(t,e),i}parse(e,t,i){return this._urlRewriter=i,it.p.Parse((()=>this),e,null),this.name=e.name,this._parseFromContent(e,t??this._host),this}serialize(e,t=!1,i=!0){(this.isSerializable||t)&&(it.p.Serialize(this,e),e.name=this.name,e.className=this.getClassName(),i&&this._prepareFont(),this._fontFamily&&(e.fontFamily=this._fontFamily),this.fontSize&&(e.fontSize=this.fontSize),this.fontWeight&&(e.fontWeight=this.fontWeight),this.fontStyle&&(e.fontStyle=this.fontStyle),this._gradient&&(e.gradient={},this._gradient.serialize(e.gradient)),it.p.AppendSerializedAnimations(this,e))}_parseFromContent(e,t,i){if(e.fontFamily&&(this.fontFamily=e.fontFamily),e.fontSize&&(this.fontSize=e.fontSize),e.fontWeight&&(this.fontWeight=e.fontWeight),e.fontStyle&&(this.fontStyle=e.fontStyle),e.gradient){const t=Ue.S0.Instantiate("BABYLON.GUI."+e.gradient.className);this._gradient=new t,this._gradient?.parse(e.gradient)}if(e.animations){this.animations=[];for(let t=0;t-1&&this.linkWithMesh(null),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}static get HORIZONTAL_ALIGNMENT_LEFT(){return lB._HORIZONTAL_ALIGNMENT_LEFT}static get HORIZONTAL_ALIGNMENT_RIGHT(){return lB._HORIZONTAL_ALIGNMENT_RIGHT}static get HORIZONTAL_ALIGNMENT_CENTER(){return lB._HORIZONTAL_ALIGNMENT_CENTER}static get VERTICAL_ALIGNMENT_TOP(){return lB._VERTICAL_ALIGNMENT_TOP}static get VERTICAL_ALIGNMENT_BOTTOM(){return lB._VERTICAL_ALIGNMENT_BOTTOM}static get VERTICAL_ALIGNMENT_CENTER(){return lB._VERTICAL_ALIGNMENT_CENTER}static _GetFontOffset(e,t){if(lB._FontHeightSizes[e])return lB._FontHeightSizes[e];const i=t||he.q.LastCreatedEngine;if(!i)throw new Error("Invalid engine. Unable to create a canvas.");const r=i.getFontOffset(e);return lB._FontHeightSizes[e]=r,r}static Parse(e,t,i){const r=Ue.S0.Instantiate("BABYLON.GUI."+e.className),s=it.p.Parse((()=>{const e=new r;return e._urlRewriter=i,e}),e,null);return s.name=e.name,s._parseFromContent(e,t,i),s}static drawEllipse(e,t,i,r,s,n){n.translate(e,t),n.scale(i,r),n.beginPath(),n.arc(0,0,1,0,2*Math.PI*s,s<0),s>=1&&n.closePath(),n.scale(1/i,1/r),n.translate(-e,-t)}isReady(){return!0}}lB.AllowAlphaInheritance=!1,lB._ClipMeasure=new sB(0,0,0,0),lB._HORIZONTAL_ALIGNMENT_LEFT=0,lB._HORIZONTAL_ALIGNMENT_RIGHT=1,lB._HORIZONTAL_ALIGNMENT_CENTER=2,lB._VERTICAL_ALIGNMENT_TOP=0,lB._VERTICAL_ALIGNMENT_BOTTOM=1,lB._VERTICAL_ALIGNMENT_CENTER=2,lB._FontHeightSizes={},lB.AddHeader=()=>{},(0,je.Cg)([(0,$e.lK)()],lB.prototype,"metadata",void 0),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"isHitTestVisible",void 0),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"isPointerBlocker",void 0),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"isFocusInvisible",void 0),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"clipChildren",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"clipContent",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"useBitmapCache",void 0),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"shadowOffsetX",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"shadowOffsetY",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"shadowBlur",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"shadowColor",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"hoverCursor",void 0),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"fontOffset",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"alpha",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"isSerializable",void 0),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"scaleX",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"scaleY",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"rotation",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"transformCenterY",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"transformCenterX",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"horizontalAlignment",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"verticalAlignment",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"fixedRatio",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"fixedRatioMasterIsWidth",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"width",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"height",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"style",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"color",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"gradient",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"zIndex",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"notRenderable",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"isVisible",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"descendantsOnlyPadding",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"paddingLeft",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"paddingRight",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"paddingTop",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"paddingBottom",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"left",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"top",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"linkOffsetX",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"linkOffsetY",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"isEnabled",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"disabledColor",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"disabledColorItem",null),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"overlapGroup",void 0),(0,je.Cg)([(0,$e.lK)()],lB.prototype,"overlapDeltaMultiplier",void 0),(0,X.Y5)("BABYLON.GUI.Control",lB);class hB extends lB{get renderToIntermediateTexture(){return this._renderToIntermediateTexture}set renderToIntermediateTexture(e){this._renderToIntermediateTexture!==e&&(this._renderToIntermediateTexture=e,this._markAsDirty())}get adaptHeightToChildren(){return this._adaptHeightToChildren}set adaptHeightToChildren(e){this._adaptHeightToChildren!==e&&(this._adaptHeightToChildren=e,e&&(this.height="100%"),this._markAsDirty())}get adaptWidthToChildren(){return this._adaptWidthToChildren}set adaptWidthToChildren(e){this._adaptWidthToChildren!==e&&(this._adaptWidthToChildren=e,e&&(this.width="100%"),this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get backgroundGradient(){return this._backgroundGradient}set backgroundGradient(e){this._backgroundGradient!==e&&(this._backgroundGradient=e,this._markAsDirty())}get children(){return this._children}get isReadOnly(){return this._isReadOnly}set isReadOnly(e){this._isReadOnly=e;for(const t of this._children)t.isReadOnly=e}constructor(e){super(e),this.name=e,this._children=new Array,this._measureForChildren=sB.Empty(),this._background="",this._backgroundGradient=null,this._adaptWidthToChildren=!1,this._adaptHeightToChildren=!1,this._renderToIntermediateTexture=!1,this._intermediateTexture=null,this.delegatePickingToChildren=!1,this.logLayoutCycleErrors=!1,this.maxLayoutCycle=3,this.onControlAddedObservable=new z.cP,this.onControlRemovedObservable=new z.cP,this._inverseTransformMatrix=oB.Identity(),this._inverseMeasure=new sB(0,0,0,0)}_getTypeName(){return"Container"}_flagDescendantsAsMatrixDirty(){for(const e of this.children)e._isClipped=!1,e._markMatrixAsDirty()}getChildByName(e){for(const t of this.children)if(t.name===e)return t;return null}getChildByType(e,t){for(const e of this.children)if(e.typeName===t)return e;return null}containsControl(e){return-1!==this.children.indexOf(e)}addControl(e){return e?(-1!==this._children.indexOf(e)||(e._link(this._host),e._markAllAsDirty(),this._reOrderControl(e),this._markAsDirty(),this.onControlAddedObservable.notifyObservers(e)),this):this}clearControls(){const e=this.children.slice();for(const t of e)this.removeControl(t);return this}removeControl(e){const t=this._children.indexOf(e);return-1!==t&&(this._children.splice(t,1),e.parent=null),e.linkWithMesh(null),this._host&&this._host._cleanControlAfterRemoval(e),this._markAsDirty(),this.onControlRemovedObservable.notifyObservers(e),this}_reOrderControl(e){const t=e.linkedMesh;this.removeControl(e);let i=!1;for(let t=0;te.zIndex){this._children.splice(t,0,e),i=!0;break}i||this._children.push(e),e.parent=this,t&&e.linkWithMesh(t),this._markAsDirty()}_offsetLeft(e){super._offsetLeft(e);for(const t of this._children)t._offsetLeft(e)}_offsetTop(e){super._offsetTop(e);for(const t of this._children)t._offsetTop(e)}_markAllAsDirty(){super._markAllAsDirty();for(let e=0;e=0&&(r+=this.paddingLeftInPixels+this.paddingRightInPixels,this.width!==r+"px"&&(this.parent?._markAsDirty(),this.width=r+"px",this._width.ignoreAdaptiveScaling=!0,this._rebuildLayout=!0)),this.adaptHeightToChildren&&s>=0&&(s+=this.paddingTopInPixels+this.paddingBottomInPixels,this.height!==s+"px"&&(this.parent?._markAsDirty(),this.height=s+"px",this._height.ignoreAdaptiveScaling=!0,this._rebuildLayout=!0)),this._postMeasure()}i++}while(this._rebuildLayout&&i=3&&this.logLayoutCycleErrors&&Z.V.Error(`Layout cycle detected in GUI (Container name=${this.name}, uniqueId=${this.uniqueId})`),t.restore(),this._isDirty&&(this.invalidateRect(),this._isDirty=!1),!0}_postMeasure(){}_draw(e,t){const i=this._renderToIntermediateTexture&&this._intermediateTexture,r=i?this._intermediateTexture.getContext():e;i&&(r.save(),r.translate(-this._currentMeasure.left,-this._currentMeasure.top),t?(this._transformMatrix.invertToRef(this._inverseTransformMatrix),t.transformToRef(this._inverseTransformMatrix,this._inverseMeasure),r.clearRect(this._inverseMeasure.left,this._inverseMeasure.top,this._inverseMeasure.width,this._inverseMeasure.height)):r.clearRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),this._localDraw(r),e.save(),this.clipChildren&&this._clipForChildren(r);for(const e of this._children)t&&!e._intersectsRect(t)||e._render(r,t);i&&(r.restore(),e.save(),e.globalAlpha=this.alpha,e.drawImage(r.canvas,this._currentMeasure.left,this._currentMeasure.top),e.restore()),e.restore()}getDescendantsToRef(e,t=!1,i){if(this.children)for(let r=0;r=0;r--){const s=this._children[r];if(s.isEnabled&&s.isHitTestVisible&&s.isVisible&&!s.notRenderable&&s.contains(e,t)){i=!0;break}}if(!i)return!1}for(let l=this._children.length-1;l>=0;l--){const h=this._children[l];if(h._processPicking(e,t,i,r,s,n,o,a))return h.hoverCursor&&this._host._changeCursor(h.hoverCursor),!0}return!!l&&!!this.isHitTestVisible&&this._processObservables(r,e,t,i,s,n,o,a)}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.copyFrom(this._currentMeasure)}_getAdaptDimTo(e){return"width"===e?this.adaptWidthToChildren:this.adaptHeightToChildren}isDimensionFullyDefined(e){if(this._getAdaptDimTo(e)){for(const t of this.children)if(!t.isDimensionFullyDefined(e))return!1;return!0}return super.isDimensionFullyDefined(e)}serialize(e,t=!1,i=!0){if(super.serialize(e,t,i),(this.isSerializable||t)&&(this.backgroundGradient&&(e.backgroundGradient={},this.backgroundGradient.serialize(e.backgroundGradient)),this.children.length)){e.children=[];for(const r of this.children)if(r.isSerializable||t){const s={};r.serialize(s,t,i),e.children.push(s)}}}dispose(){super.dispose();for(let e=this.children.length-1;e>=0;e--)this.children[e].dispose();this._intermediateTexture?.dispose()}_parseFromContent(e,t,i){if(super._parseFromContent(e,t,i),this._link(t),e.backgroundGradient){const t=Ue.S0.Instantiate("BABYLON.GUI."+e.backgroundGradient.className);this._backgroundGradient=new t,this._backgroundGradient?.parse(e.backgroundGradient)}if(e.children)for(const r of e.children)this.addControl(lB.Parse(r,t,i))}isReady(){for(const e of this.children)if(!e.isReady())return!1;return!0}}(0,je.Cg)([(0,$e.lK)()],hB.prototype,"delegatePickingToChildren",void 0),(0,je.Cg)([(0,$e.lK)()],hB.prototype,"renderToIntermediateTexture",null),(0,je.Cg)([(0,$e.lK)()],hB.prototype,"maxLayoutCycle",void 0),(0,je.Cg)([(0,$e.lK)()],hB.prototype,"adaptHeightToChildren",null),(0,je.Cg)([(0,$e.lK)()],hB.prototype,"adaptWidthToChildren",null),(0,je.Cg)([(0,$e.lK)()],hB.prototype,"background",null),(0,je.Cg)([(0,$e.lK)()],hB.prototype,"backgroundGradient",null),(0,X.Y5)("BABYLON.GUI.Container",hB);class cB extends hB{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}get cornerRadius(){return this._cornerRadius[0]}set cornerRadius(e){e<0&&(e=0),this._cornerRadius[0]===e&&this._cornerRadius[1]===e&&this._cornerRadius[2]===e&&this._cornerRadius[3]===e||(this._cornerRadius[0]=this._cornerRadius[1]=this._cornerRadius[2]=this._cornerRadius[3]=e,this._markAsDirty())}get cornerRadiusX(){return this._cornerRadius[0]}set cornerRadiusX(e){this._cornerRadius[0]!==e&&(this._cornerRadius[0]=e)}get cornerRadiusY(){return this._cornerRadius[1]}set cornerRadiusY(e){this._cornerRadius[1]!==e&&(this._cornerRadius[1]=e)}get cornerRadiusZ(){return this._cornerRadius[2]}set cornerRadiusZ(e){this._cornerRadius[2]!==e&&(this._cornerRadius[2]=e)}get cornerRadiusW(){return this._cornerRadius[3]}set cornerRadiusW(e){this._cornerRadius[3]!==e&&(this._cornerRadius[3]=e)}constructor(e){super(e),this.name=e,this._thickness=1,this._cornerRadius=[0,0,0,0],this._cachedRadius=[0,0,0,0]}_getTypeName(){return"Rectangle"}_computeAdditionalOffsetX(){let e=0;return 0===this._cornerRadius[0]&&0===this._cornerRadius[1]&&0===this._cornerRadius[2]&&0===this._cornerRadius[3]||(e+=1),this.thickness&&(e+=this.thickness/2),e}_computeAdditionalOffsetY(){let e=0;return 0===this._cornerRadius[0]&&0===this._cornerRadius[1]&&0===this._cornerRadius[2]&&0===this._cornerRadius[3]||(e+=1),this.thickness&&(e+=this.thickness/2),e}_getRectangleFill(e){return this._getBackgroundColor(e)}_localDraw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),(this._background||this._backgroundGradient)&&(e.fillStyle=this._getRectangleFill(e),0!==this._cornerRadius[0]||0!==this._cornerRadius[1]||0!==this._cornerRadius[2]||0!==this._cornerRadius[3]?(this._drawRoundedRect(e,this._thickness/2),e.fill()):e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),this._thickness&&((this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),(this.color||this.gradient)&&(e.strokeStyle=this.gradient?this.gradient.getCanvasGradient(e):this.color),e.lineWidth=this._thickness,0!==this._cornerRadius[0]||0!==this._cornerRadius[1]||0!==this._cornerRadius[2]||0!==this._cornerRadius[3]?(this._drawRoundedRect(e,this._thickness/2),e.stroke()):e.strokeRect(this._currentMeasure.left+this._thickness/2,this._currentMeasure.top+this._thickness/2,this._currentMeasure.width-this._thickness,this._currentMeasure.height-this._thickness)),e.restore()}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.width-=2*this._thickness,this._measureForChildren.height-=2*this._thickness,this._measureForChildren.left+=this._thickness,this._measureForChildren.top+=this._thickness}_drawRoundedRect(e,t=0){const i=this._currentMeasure.left+t,r=this._currentMeasure.top+t,s=this._currentMeasure.width-2*t,n=this._currentMeasure.height-2*t;for(let e=0;ei&&(i=t.width)}if(this._resizeToFit){if(0===this._textWrapping||this._forceResizeWidth){const e=Math.ceil(this._paddingLeftInPixels)+Math.ceil(this._paddingRightInPixels)+Math.ceil(i);e!==this._width.getValueInPixel(this._host,this._tempParentMeasure.width)&&(this._width.updateInPlace(e,JL.UNITMODE_PIXEL),this._rebuildLayout=!0)}let e=this._paddingTopInPixels+this._paddingBottomInPixels+this._fontOffset.height*this._lines.length|0;if(this._lines.length>0&&0!==this._lineSpacing.internalValue){let t=0;t=this._lineSpacing.isPixel?this._lineSpacing.getValue(this._host):this._lineSpacing.getValue(this._host)*this._height.getValueInPixel(this._host,this._cachedParentMeasure.height),e+=(this._lines.length-1)*t}e!==this._height.internalValue&&(this._height.updateInPlace(e,JL.UNITMODE_PIXEL),this._rebuildLayout=!0)}}_drawText(e,t,i,r){const s=this._currentMeasure.width;let n=0;switch(this._textHorizontalAlignment){case lB.HORIZONTAL_ALIGNMENT_LEFT:n=0;break;case lB.HORIZONTAL_ALIGNMENT_RIGHT:n=s-t;break;case lB.HORIZONTAL_ALIGNMENT_CENTER:n=(s-t)/2}(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(r.shadowColor=this.shadowColor,r.shadowBlur=this.shadowBlur,r.shadowOffsetX=this.shadowOffsetX,r.shadowOffsetY=this.shadowOffsetY),this.outlineWidth&&r.strokeText(e,this._currentMeasure.left+n,i),r.fillText(e,this._currentMeasure.left+n,i),this._underline&&this._drawLine(this._currentMeasure.left+n,i+3,this._currentMeasure.left+n+t,i+3,r),this._lineThrough&&this._drawLine(this._currentMeasure.left+n,i-this.fontSizeInPixels/3,this._currentMeasure.left+n+t,i-this.fontSizeInPixels/3,r)}_drawLine(e,t,i,r,s){if(s.beginPath(),s.lineWidth=Math.round(.05*this.fontSizeInPixels),s.moveTo(e,t),s.lineTo(i,r),this.outlineWidth&&this.applyOutlineToUnderline)s.stroke(),s.fill();else{const e=s.strokeStyle;s.strokeStyle=s.fillStyle,s.stroke(),s.strokeStyle=e}s.closePath()}_draw(e){e.save(),this._applyStates(e),this._renderLines(e),e.restore()}_applyStates(e){super._applyStates(e),this.outlineWidth&&(e.lineWidth=this.outlineWidth,e.strokeStyle=this.outlineColor,e.lineJoin="miter",e.miterLimit=2)}_breakLines(e,t,i){this._linesTemp.length=0;const r=4===this._textWrapping?this._parseHTMLText(e,t,i):this.text.split("\n");switch(this._textWrapping){case 1:for(const t of r)this._linesTemp.push(...this._parseLineWordWrap(t,e,i));break;case 2:for(const t of r)this._linesTemp.push(this._parseLineEllipsis(t,e,i));break;case 3:for(const s of r)this._linesTemp.push(...this._parseLineWordWrapEllipsis(s,e,t,i));break;default:for(const e of r)this._linesTemp.push(this._parseLine(e,i))}return this._linesTemp}_parseHTMLText(e,t,i){const r=[];this._htmlElement||(this._htmlElement=document.createElement("div"),document.body.appendChild(this._htmlElement));const s=this._htmlElement;s.textContent=this.text,s.style.font=i.font,s.style.position="absolute",s.style.visibility="hidden",s.style.top="-1000px",s.style.left="-1000px",this.adjustWordWrappingHTMLElement?.(s),s.style.width=e+"px",s.style.height=t+"px";const n=s.textContent;if(!n)return r;const o=s.childNodes[0],a=document.createRange();let l=0;for(const e of n){a.setStart(o,0),a.setEnd(o,l+1);const t=a.getClientRects().length-1;r[t]=(r[t]||"")+e,l++}return this.reuseHTMLForWordWrapping||(s.remove(),this._htmlElement=null),r}_parseLine(e="",t){return{text:e,width:this._getTextMetricsWidth(t.measureText(e))}}_getCharsToRemove(e,t,i){const r=e>t?e-t:0,s=e/i;return Math.max(Math.floor(r/s),1)}_parseLineEllipsis(e="",t,i){let r=this._getTextMetricsWidth(i.measureText(e)),s=this._getCharsToRemove(r,t,e.length);const n=Array.from&&Array.from(e);if(n)for(;n.length&&r>t;)n.splice(n.length-s,s),e=`${n.join("")}…`,r=this._getTextMetricsWidth(i.measureText(e)),s=this._getCharsToRemove(r,t,e.length);else{for(;e.length>2&&r>t;)e=e.slice(0,-s),r=this._getTextMetricsWidth(i.measureText(e+"…")),s=this._getCharsToRemove(r,t,e.length);e+="…"}return{text:e,width:r}}_getTextMetricsWidth(e){return void 0!==e.actualBoundingBoxLeft?Math.abs(e.actualBoundingBoxLeft)+Math.abs(e.actualBoundingBoxRight):e.width}_parseLineWordWrap(e="",t,i){const r=[],s=this.wordSplittingFunction?this.wordSplittingFunction(e):e.split(this._wordDivider);let n=this._getTextMetricsWidth(i.measureText(e));for(let o=0;o0?e+this._wordDivider+s[o]:s[0],l=this._getTextMetricsWidth(i.measureText(a));l>t&&o>0?(r.push({text:e,width:n}),e=s[o],n=this._getTextMetricsWidth(i.measureText(e))):(n=l,e=a)}return r.push({text:e,width:n}),r}_parseLineWordWrapEllipsis(e="",t,i,r){const s=this._parseLineWordWrap(e,t,r);for(let e=1;e<=s.length;e++)if(this._computeHeightForLinesOf(e)>i&&e>1){const i=s[e-2],n=s[e-1];s[e-2]=this._parseLineEllipsis(i.text+this._wordDivider+n.text,t,r);const o=s.length-e+1;for(let e=0;e0&&0!==this._lineSpacing.internalValue){let i=0;i=this._lineSpacing.isPixel?this._lineSpacing.getValue(this._host):this._lineSpacing.getValue(this._host)*this._height.getValueInPixel(this._host,this._cachedParentMeasure.height),t+=(e-1)*i}return t}isDimensionFullyDefined(e){return!!this.resizeToFit||super.isDimensionFullyDefined(e)}computeExpectedHeight(){if(this.text&&this.widthInPixels){const e=he.q.LastCreatedEngine?.createCanvas(0,0).getContext("2d");if(e){this._applyStates(e),this._fontOffset||(this._fontOffset=lB._GetFontOffset(e.font,this._host.getScene()?.getEngine()));const t=this._lines?this._lines:this._breakLines(this.widthInPixels-this._paddingLeftInPixels-this._paddingRightInPixels,this.heightInPixels-this._paddingTopInPixels-this._paddingBottomInPixels,e);return this._computeHeightForLinesOf(t.length)}}return 0}dispose(){super.dispose(),this.onTextChangedObservable.clear(),this._htmlElement?.remove(),this._htmlElement=null}}(0,je.Cg)([(0,$e.lK)()],dB.prototype,"resizeToFit",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"textWrapping",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"text",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"textHorizontalAlignment",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"textVerticalAlignment",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"lineSpacing",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"outlineWidth",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"underline",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"lineThrough",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"applyOutlineToUnderline",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"outlineColor",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"wordDivider",null),(0,je.Cg)([(0,$e.lK)()],dB.prototype,"forceResizeWidth",null),(0,X.Y5)("BABYLON.GUI.TextBlock",dB);class fB extends lB{get isLoaded(){return this._loaded}isReady(){return this.isLoaded}get detectPointerOnOpaqueOnly(){return this._detectPointerOnOpaqueOnly}set detectPointerOnOpaqueOnly(e){this._detectPointerOnOpaqueOnly!==e&&(this._detectPointerOnOpaqueOnly=e)}get sliceLeft(){return this._sliceLeft}set sliceLeft(e){this._sliceLeft!==e&&(this._sliceLeft=e,this._markAsDirty())}get sliceRight(){return this._sliceRight}set sliceRight(e){this._sliceRight!==e&&(this._sliceRight=e,this._markAsDirty())}get sliceTop(){return this._sliceTop}set sliceTop(e){this._sliceTop!==e&&(this._sliceTop=e,this._markAsDirty())}get sliceBottom(){return this._sliceBottom}set sliceBottom(e){this._sliceBottom!==e&&(this._sliceBottom=e,this._markAsDirty())}get sourceLeft(){return this._sourceLeft}set sourceLeft(e){this._sourceLeft!==e&&(this._sourceLeft=e,this._markAsDirty())}get sourceTop(){return this._sourceTop}set sourceTop(e){this._sourceTop!==e&&(this._sourceTop=e,this._markAsDirty())}get sourceWidth(){return this._sourceWidth}set sourceWidth(e){this._sourceWidth!==e&&(this._sourceWidth=e,this._markAsDirty())}get sourceHeight(){return this._sourceHeight}set sourceHeight(e){this._sourceHeight!==e&&(this._sourceHeight=e,this._markAsDirty())}get imageWidth(){return this._imageWidth}get imageHeight(){return this._imageHeight}get populateNinePatchSlicesFromImage(){return this._populateNinePatchSlicesFromImage}set populateNinePatchSlicesFromImage(e){this._populateNinePatchSlicesFromImage!==e&&(this._populateNinePatchSlicesFromImage=e,this._populateNinePatchSlicesFromImage&&this._loaded&&this._extractNinePatchSliceDataFromImage())}get isSVG(){return this._isSVG}get svgAttributesComputationCompleted(){return this._svgAttributesComputationCompleted}get autoScale(){return this._autoScale}set autoScale(e){this._autoScale!==e&&(this._autoScale=e,e&&this._loaded&&this.synchronizeSizeWithContent())}get stretch(){return this._stretch}set stretch(e){this._stretch!==e&&(this._stretch=e,this._markAsDirty())}_rotate90(e,t=!1){const i=this._domImage.width,r=this._domImage.height,s=this._host?.getScene()?.getEngine()||he.q.LastCreatedEngine;if(!s)throw new Error("Invalid engine. Unable to create a canvas.");const n=s.createCanvas(r,i),o=n.getContext("2d");o.translate(n.width/2,n.height/2),o.rotate(e*Math.PI/2),o.drawImage(this._domImage,0,0,i,r,-i/2,-r/2,i,r);const a=n.toDataURL("image/jpg"),l=new fB(this.name+"rotated",a);return t&&(l._stretch=this._stretch,l._autoScale=this._autoScale,l._cellId=this._cellId,l._cellWidth=e%1?this._cellHeight:this._cellWidth,l._cellHeight=e%1?this._cellWidth:this._cellHeight),this._handleRotationForSVGImage(this,l,e),this._imageDataCache.data=null,l}_handleRotationForSVGImage(e,t,i){e._isSVG&&(e._svgAttributesComputationCompleted?(this._rotate90SourceProperties(e,t,i),this._markAsDirty()):e.onSVGAttributesComputedObservable.addOnce((()=>{this._rotate90SourceProperties(e,t,i),this._markAsDirty()})))}_rotate90SourceProperties(e,t,i){let r=e.sourceLeft,s=e.sourceTop,n=e.domImage.width,o=e.domImage.height,a=r,l=s,h=e.sourceWidth,c=e.sourceHeight;if(0!=i){const e=i<0?-1:1;i%=4;for(let t=0;t127&&-1===this._sliceLeft)this._sliceLeft=t;else if(e<127&&this._sliceLeft>-1){this._sliceRight=t;break}}this._sliceTop=-1,this._sliceBottom=-1;for(let i=0;i127&&-1===this._sliceTop)this._sliceTop=i;else if(t<127&&this._sliceTop>-1){this._sliceBottom=i;break}}}set domImage(e){this._domImage=e,this._loaded=!1,this._imageDataCache.data=null,this._domImage.width?this._onImageLoaded():this._domImage.onload=()=>{this._onImageLoaded()}}get domImage(){return this._domImage}_onImageLoaded(){this._imageDataCache.data=null,this._imageWidth=this._domImage.width,this._imageHeight=this._domImage.height,this._loaded=!0,this._populateNinePatchSlicesFromImage&&this._extractNinePatchSliceDataFromImage(),this._autoScale&&this.synchronizeSizeWithContent(),this.onImageLoadedObservable.notifyObservers(this),this._markAsDirty()}get source(){return this._source}static ResetImageCache(){fB.SourceImgCache.clear()}_removeCacheUsage(e){const t=e&&fB.SourceImgCache.get(e);if(t){t.timesUsed-=1;const i=t.img;i.parentNode&&i.parentNode.removeChild(i),0===t.timesUsed&&fB.SourceImgCache.delete(e)}}set source(e){if(this._urlRewriter&&e&&(e=this._urlRewriter(e)),this._source===e)return;this._removeCacheUsage(this._source),this._loaded=!1,this._source=e,this._imageDataCache.data=null,e&&(e=this._svgCheck(e));const t=this._host?.getScene()?.getEngine()||he.q.LastCreatedEngine;if(!t)throw new Error("Invalid engine. Unable to create a canvas.");if(e&&fB.SourceImgCache.has(e)){const t=fB.SourceImgCache.get(e);return this._domImage=t.img,t.timesUsed+=1,void(t.loaded?this._onImageLoaded():t.waitingForLoadCallback.push(this._onImageLoaded.bind(this)))}this._domImage=t.createCanvasImage();const i=this._domImage;let r=!1;i.style&&this._source?.endsWith(".svg")&&(i.style.visibility="hidden",i.style.position="absolute",i.style.top="0",t.getRenderingCanvas()?.parentNode?.appendChild(i),r=!0),e&&fB.SourceImgCache.set(e,{img:this._domImage,timesUsed:1,loaded:!1,waitingForLoadCallback:[this._onImageLoaded.bind(this)]}),this._domImage.onload=()=>{if(e){const t=fB.SourceImgCache.get(e);if(t){t.loaded=!0;for(const e of t.waitingForLoadCallback)e();return t.waitingForLoadCallback.length=0,void(r&&i.remove())}}this._onImageLoaded(),r&&i.remove()},e&&(Ue.S0.SetCorsBehavior(e,this._domImage),Ue.S0.SetReferrerPolicyBehavior(this.referrerPolicy,this._domImage),this._domImage.src=e)}_svgCheck(e){if(window.SVGSVGElement&&-1!==e.search(/(\.svg|\.svg?[?|#].*)$/gi)&&e.indexOf("#")===e.lastIndexOf("#")){this._isSVG=!0;const t=e.split("#")[0],i=e.split("#")[1],r=document.body.querySelector('object[data="'+t+'"]');if(r){const t=r.contentDocument;if(t&&t.documentElement){const s=t.documentElement.getAttribute("viewBox"),n=Number(t.documentElement.getAttribute("width")),o=Number(t.documentElement.getAttribute("height"));if(t.getElementById(i)&&s&&n&&o)return this._getSVGAttribs(r,i),e}r.addEventListener("load",(()=>{this._getSVGAttribs(r,i)}))}else{const e=document.createElement("object");e.data=t,e.type="image/svg+xml",e.width="0%",e.height="0%",document.body.appendChild(e),e.onload=()=>{const e=document.body.querySelector('object[data="'+t+'"]');e&&this._getSVGAttribs(e,i)}}return t}return e}_getSVGAttribs(e,t){const i=e.contentDocument;if(i&&i.documentElement){const e=i.documentElement.getAttribute("viewBox"),r=Number(i.documentElement.getAttribute("width")),s=Number(i.documentElement.getAttribute("height")),n=i.getElementById(t);if(e&&r&&s&&n){const t=Number(e.split(" ")[2]),i=Number(e.split(" ")[3]),o=n.getBBox();let a=1,l=1,h=0,c=0;const u=n.transform.baseVal.consolidate().matrix;n.transform&&n.transform.baseVal.consolidate()&&(a=u.a,l=u.d,h=u.e,c=u.f),this.sourceLeft=(a*o.x+h)*r/t,this.sourceTop=(l*o.y+c)*s/i,this.sourceWidth=o.width*a*(r/t),this.sourceHeight=o.height*l*(s/i),this._svgAttributesComputationCompleted=!0,this.onSVGAttributesComputedObservable.notifyObservers(this)}}}get cellWidth(){return this._cellWidth}set cellWidth(e){this._cellWidth!==e&&(this._cellWidth=e,this._markAsDirty())}get cellHeight(){return this._cellHeight}set cellHeight(e){this._cellHeight!==e&&(this._cellHeight=e,this._markAsDirty())}get cellId(){return this._cellId}set cellId(e){this._cellId!==e&&(this._cellId=e,this._markAsDirty())}constructor(e,t=null){super(e),this.name=e,this._workingCanvas=null,this._loaded=!1,this._stretch=fB.STRETCH_FILL,this._source=null,this._autoScale=!1,this._sourceLeft=0,this._sourceTop=0,this._sourceWidth=0,this._sourceHeight=0,this._svgAttributesComputationCompleted=!1,this._isSVG=!1,this._cellWidth=0,this._cellHeight=0,this._cellId=-1,this._populateNinePatchSlicesFromImage=!1,this._imageDataCache={data:null,key:""},this.onImageLoadedObservable=new z.cP,this.onSVGAttributesComputedObservable=new z.cP,this.source=t}contains(e,t){if(!super.contains(e,t))return!1;if(!this._detectPointerOnOpaqueOnly||!this._workingCanvas)return!0;const i=0|this._currentMeasure.width,r=0|this._currentMeasure.height,s=i+"_"+r;let n=this._imageDataCache.data;if(!n||this._imageDataCache.key!==s){const e=this._workingCanvas.getContext("2d");this._imageDataCache.data=n=e.getImageData(0,0,i,r).data,this._imageDataCache.key=s}return n[4*((e=e-this._currentMeasure.left|0)+(t=t-this._currentMeasure.top|0)*i)+3]>0}_getTypeName(){return"Image"}synchronizeSizeWithContent(){this._loaded&&(this.width=this._domImage.width+"px",this.height=this._domImage.height+"px")}_processMeasures(e,t){if(this._loaded)switch(this._stretch){case fB.STRETCH_NONE:case fB.STRETCH_FILL:case fB.STRETCH_UNIFORM:case fB.STRETCH_NINE_PATCH:break;case fB.STRETCH_EXTEND:this._autoScale&&this.synchronizeSizeWithContent(),this.parent&&this.parent.parent&&(this.parent.adaptWidthToChildren=!0,this.parent.adaptHeightToChildren=!0)}super._processMeasures(e,t)}_prepareWorkingCanvasForOpaqueDetection(){if(!this._detectPointerOnOpaqueOnly)return;const e=this._currentMeasure.width,t=this._currentMeasure.height;if(!this._workingCanvas){const i=this._host?.getScene()?.getEngine()||he.q.LastCreatedEngine;if(!i)throw new Error("Invalid engine. Unable to create a canvas.");this._workingCanvas=i.createCanvas(e,t)}this._workingCanvas.getContext("2d").clearRect(0,0,e,t)}_drawImage(e,t,i,r,s,n,o,a,l){if(e.drawImage(this._domImage,t,i,r,s,n,o,a,l),!this._detectPointerOnOpaqueOnly)return;const h=e.getTransform(),c=this._workingCanvas.getContext("2d");c.save();const u=n-this._currentMeasure.left,d=o-this._currentMeasure.top;c.setTransform(h.a,h.b,h.c,h.d,(u+a)/2,(d+l)/2),c.translate(-(u+a)/2,-(d+l)/2),c.drawImage(this._domImage,t,i,r,s,u,d,a,l),c.restore()}_draw(e){let t,i,r,s;if(e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),-1==this.cellId)t=this._sourceLeft,i=this._sourceTop,r=this._sourceWidth?this._sourceWidth:this._imageWidth,s=this._sourceHeight?this._sourceHeight:this._imageHeight;else{const e=this._domImage.naturalWidth/this.cellWidth,n=this.cellId/e|0,o=this.cellId%e;t=this.cellWidth*o,i=this.cellHeight*n,r=this.cellWidth,s=this.cellHeight}if(this._prepareWorkingCanvasForOpaqueDetection(),this._applyStates(e),this._loaded)switch(this._stretch){case fB.STRETCH_NONE:case fB.STRETCH_FILL:this._drawImage(e,t,i,r,s,this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height);break;case fB.STRETCH_UNIFORM:{const n=this._currentMeasure.width/r,o=this._currentMeasure.height/s,a=Math.min(n,o),l=(this._currentMeasure.width-r*a)/2,h=(this._currentMeasure.height-s*a)/2;this._drawImage(e,t,i,r,s,this._currentMeasure.left+l,this._currentMeasure.top+h,r*a,s*a);break}case fB.STRETCH_EXTEND:this._drawImage(e,t,i,r,s,this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height);break;case fB.STRETCH_NINE_PATCH:this._renderNinePatch(e,t,i,r,s)}e.restore()}_renderNinePatch(e,t,i,r,s){const n=this.host.idealWidth?this._width.getValue(this.host)/this.host.idealWidth:this.host.idealHeight?this._height.getValue(this.host)/this.host.idealHeight:1,o=this._sliceLeft,a=this._sliceTop,l=s-this._sliceBottom,h=r-this._sliceRight,c=this._sliceRight-this._sliceLeft,u=this._sliceBottom-this._sliceTop,d=Math.round(o*n),f=Math.round(a*n),p=Math.round(l*n),_=Math.round(h*n),m=Math.round(this._currentMeasure.width)-_-d+2,g=Math.round(this._currentMeasure.height)-p-f+2,v=Math.round(this._currentMeasure.left)+d-1,x=Math.round(this._currentMeasure.top)+f-1,b=Math.round(this._currentMeasure.left+this._currentMeasure.width)-_,S=Math.round(this._currentMeasure.top+this._currentMeasure.height)-p;this._drawImage(e,t,i,o,a,this._currentMeasure.left,this._currentMeasure.top,d,f),this._drawImage(e,t+this._sliceLeft,i,c,a,v+1,this._currentMeasure.top,m-2,f),this._drawImage(e,t+this._sliceRight,i,h,a,b,this._currentMeasure.top,_,f),this._drawImage(e,t,i+this._sliceTop,o,u,this._currentMeasure.left,x+1,d,g-2),this._drawImage(e,t+this._sliceLeft,i+this._sliceTop,c,u,v+1,x+1,m-2,g-2),this._drawImage(e,t+this._sliceRight,i+this._sliceTop,h,u,b,x+1,_,g-2),this._drawImage(e,t,i+this._sliceBottom,o,l,this._currentMeasure.left,S,d,p),this._drawImage(e,t+this.sliceLeft,i+this._sliceBottom,c,l,v+1,S,m-2,p),this._drawImage(e,t+this._sliceRight,i+this._sliceBottom,h,l,b,S,_,p)}dispose(){super.dispose(),this.onImageLoadedObservable.clear(),this.onSVGAttributesComputedObservable.clear(),this._removeCacheUsage(this._source)}}fB.SourceImgCache=new Map,fB.STRETCH_NONE=0,fB.STRETCH_FILL=1,fB.STRETCH_UNIFORM=2,fB.STRETCH_EXTEND=3,fB.STRETCH_NINE_PATCH=4,(0,je.Cg)([(0,$e.lK)()],fB.prototype,"detectPointerOnOpaqueOnly",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"sliceLeft",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"sliceRight",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"sliceTop",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"sliceBottom",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"sourceLeft",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"sourceTop",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"sourceWidth",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"sourceHeight",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"populateNinePatchSlicesFromImage",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"autoScale",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"stretch",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"source",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"cellWidth",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"cellHeight",null),(0,je.Cg)([(0,$e.lK)()],fB.prototype,"cellId",null),(0,X.Y5)("BABYLON.GUI.Image",fB);class pB extends cB{get image(){return this._image}get textBlock(){return this._textBlock}constructor(e){super(e),this.name=e,this.thickness=1,this.isPointerBlocker=!0;let t=null;this.pointerEnterAnimation=()=>{t=this.alpha,this.alpha-=.1},this.pointerOutAnimation=()=>{null!==t&&(this.alpha=t)},this.pointerDownAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05}}_getTypeName(){return"Button"}_processPicking(e,t,i,r,s,n,o,a){if(!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this.notRenderable)return!1;if(!super.contains(e,t))return!1;if(this.delegatePickingToChildren){let i=!1;for(let r=this._children.length-1;r>=0;r--){const s=this._children[r];if(s.isEnabled&&s.isHitTestVisible&&s.isVisible&&!s.notRenderable&&s.contains(e,t)){i=!0;break}}if(!i)return!1}return this._processObservables(r,e,t,i,s,n,o,a),!0}_onPointerEnter(e,t){return!!super._onPointerEnter(e,t)&&(!this.isReadOnly&&this.pointerEnterAnimation&&this.pointerEnterAnimation(),!0)}_onPointerOut(e,t,i=!1){!this.isReadOnly&&this.pointerOutAnimation&&this.pointerOutAnimation(),super._onPointerOut(e,t,i)}_onPointerDown(e,t,i,r,s){return!!super._onPointerDown(e,t,i,r,s)&&(!this.isReadOnly&&this.pointerDownAnimation&&this.pointerDownAnimation(),!0)}_getRectangleFill(e){return this.isEnabled?this._getBackgroundColor(e):this._disabledColor}_onPointerUp(e,t,i,r,s,n){!this.isReadOnly&&this.pointerUpAnimation&&this.pointerUpAnimation(),super._onPointerUp(e,t,i,r,s,n)}serialize(e,t){super.serialize(e,t),(this.isSerializable||t)&&(this._textBlock&&(e.textBlockName=this._textBlock.name),this._image&&(e.imageName=this._image.name))}_parseFromContent(e,t){super._parseFromContent(e,t),e.textBlockName&&(this._textBlock=this.getChildByName(e.textBlockName)),e.imageName&&(this._image=this.getChildByName(e.imageName))}static CreateImageButton(e,t,i){const r=new this(e),s=new dB(e+"_button",t);s.textWrapping=!0,s.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_CENTER,s.paddingLeft="20%",r.addControl(s);const n=new fB(e+"_icon",i);return n.width="20%",n.stretch=fB.STRETCH_UNIFORM,n.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,r.addControl(n),r._image=n,r._textBlock=s,r}static CreateImageOnlyButton(e,t){const i=new this(e),r=new fB(e+"_icon",t);return r.stretch=fB.STRETCH_FILL,r.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,i.addControl(r),i._image=r,i}static CreateSimpleButton(e,t){const i=new this(e),r=new dB(e+"_button",t);return r.textWrapping=!0,r.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_CENTER,i.addControl(r),i._textBlock=r,i}static CreateImageWithCenterTextButton(e,t,i){const r=new this(e),s=new fB(e+"_icon",i);s.stretch=fB.STRETCH_FILL,r.addControl(s);const n=new dB(e+"_button",t);return n.textWrapping=!0,n.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_CENTER,r.addControl(n),r._image=s,r._textBlock=n,r}}(0,X.Y5)("BABYLON.GUI.Button",pB);class _B extends hB{get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,this._markAsDirty())}get spacing(){return this._spacing}set spacing(e){this._spacing!==e&&(this._spacing=e,this._markAsDirty())}set width(e){this._doNotTrackManualChanges||(this._manualWidth=!0),this._width.toString(this._host)!==e&&this._width.fromString(e)&&this._markAsDirty()}get width(){return this._width.toString(this._host)}set height(e){this._doNotTrackManualChanges||(this._manualHeight=!0),this._height.toString(this._host)!==e&&this._height.fromString(e)&&this._markAsDirty()}get height(){return this._height.toString(this._host)}constructor(e){super(e),this.name=e,this._isVertical=!0,this._manualWidth=!1,this._manualHeight=!1,this._doNotTrackManualChanges=!1,this._spacing=0,this.ignoreLayoutWarnings=!1}_getTypeName(){return"StackPanel"}_preMeasure(e,t){for(const e of this._children)this._isVertical?e.verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP:e.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT;super._preMeasure(e,t)}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.copyFrom(e),this._measureForChildren.left=this._currentMeasure.left,this._measureForChildren.top=this._currentMeasure.top,this.isVertical&&!this._manualWidth||(this._measureForChildren.width=this._currentMeasure.width),(this.isVertical||this._manualHeight)&&(this._measureForChildren.height=this._currentMeasure.height)}_postMeasure(){let e=0,t=0;const i=this._children.length;for(let r=0;r=0?Math.min(e,this._characters.length):this._characters.length+Math.max(e,-this._characters.length),void 0===t?t=this._characters.length-e:(isNaN(t)||t<0)&&(t=0);const i=[];for(;--t>=0;)i[t]=this._characters[e+t];return i.join("")}return this._text.substring(e,t?t+e:void 0)}substring(e,t){if(this._characters){isNaN(e)?e=0:e>this._characters.length?e=this._characters.length:e<0&&(e=0),void 0===t?t=this._characters.length:isNaN(t)?t=0:t>this._characters.length?t=this._characters.length:t<0&&(t=0);const i=[];let r=0;for(;e{switch(e.type){case yu.COPY:this._onCopyText(e.event),this.onTextCopyObservable.notifyObservers(this);break;case yu.CUT:this._onCutText(e.event),this.onTextCutObservable.notifyObservers(this);break;case yu.PASTE:this._onPasteText(e.event),this.onTextPasteObservable.notifyObservers(this);break;default:return}}));const e=this._host.getScene();e&&(this._onPointerDblTapObserver=e.onPointerObservable.add((e=>{this._isFocused&&e.type===yi.Zp.POINTERDOUBLETAP&&this._processDblClick(e)}))),this._onFocusSelectAll&&this.selectAllText()}_getTypeName(){return"InputText"}keepsFocusWith(){return this._connectedVirtualKeyboard?[this._connectedVirtualKeyboard]:null}processKey(e,t,i){if(!this.isReadOnly&&(!i||!i.ctrlKey&&!i.metaKey||67!==e&&86!==e&&88!==e)){if(i&&(i.ctrlKey||i.metaKey)&&65===e)return this.selectAllText(),void i.preventDefault();switch(e){case 32:t=" ";break;case 191:i&&i.preventDefault();break;case 8:if(this._textWrapper.text&&this._textWrapper.length>0){if(this.isTextHighlightOn)return this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this._blinkIsEven=!1,void(i&&i.preventDefault());if(0===this._cursorOffset)this.text=this._textWrapper.substring(0,this._textWrapper.length-1);else{const e=this._textWrapper.length-this._cursorOffset;e>0&&(this._textWrapper.removePart(e-1,e),this._textHasChanged())}}return void(i&&i.preventDefault());case 46:if(this.isTextHighlightOn)return this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,void(i&&i.preventDefault());if(this._textWrapper.text&&this._textWrapper.length>0&&this._cursorOffset>0){const e=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(e,e+1),this._textHasChanged(),this._cursorOffset--}return void(i&&i.preventDefault());case 13:return this._host.focusedControl=null,void(this.isTextHighlightOn=!1);case 35:return this._cursorOffset=0,this._blinkIsEven=!1,this.isTextHighlightOn=!1,void this._markAsDirty();case 36:return this._cursorOffset=this._textWrapper.length,this._blinkIsEven=!1,this.isTextHighlightOn=!1,void this._markAsDirty();case 37:if(this._cursorOffset++,this._cursorOffset>this._textWrapper.length&&(this._cursorOffset=this._textWrapper.length),i&&i.shiftKey){if(this._blinkIsEven=!1,i.ctrlKey||i.metaKey){if(!this.isTextHighlightOn){if(this._textWrapper.length===this._cursorOffset)return;this._endHighlightIndex=this._textWrapper.length-this._cursorOffset+1}return this._startHighlightIndex=0,this._cursorIndex=this._textWrapper.length-this._endHighlightIndex,this._cursorOffset=this._textWrapper.length,this.isTextHighlightOn=!0,void this._markAsDirty()}return this.isTextHighlightOn?-1===this._cursorIndex&&(this._cursorIndex=this._textWrapper.length-this._endHighlightIndex,this._cursorOffset=0===this._startHighlightIndex?this._textWrapper.length:this._textWrapper.length-this._startHighlightIndex+1):(this.isTextHighlightOn=!0,this._cursorIndex=this._cursorOffset>=this._textWrapper.length?this._textWrapper.length:this._cursorOffset-1),this._cursorIndexthis._cursorOffset?(this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex):this.isTextHighlightOn=!1,void this._markAsDirty()}return this.isTextHighlightOn&&(this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this.isTextHighlightOn=!1),i&&(i.ctrlKey||i.metaKey)&&(this._cursorOffset=this._textWrapper.length,i.preventDefault()),this._blinkIsEven=!1,this.isTextHighlightOn=!1,this._cursorIndex=-1,void this._markAsDirty();case 39:if(this._cursorOffset--,this._cursorOffset<0&&(this._cursorOffset=0),i&&i.shiftKey){if(this._blinkIsEven=!1,i.ctrlKey||i.metaKey){if(!this.isTextHighlightOn){if(0===this._cursorOffset)return;this._startHighlightIndex=this._textWrapper.length-this._cursorOffset-1}return this._endHighlightIndex=this._textWrapper.length,this.isTextHighlightOn=!0,this._cursorIndex=this._textWrapper.length-this._startHighlightIndex,this._cursorOffset=0,void this._markAsDirty()}return this.isTextHighlightOn?-1===this._cursorIndex&&(this._cursorIndex=this._textWrapper.length-this._startHighlightIndex,this._cursorOffset=this._textWrapper.length===this._endHighlightIndex?0:this._textWrapper.length-this._endHighlightIndex-1):(this.isTextHighlightOn=!0,this._cursorIndex=this._cursorOffset<=0?0:this._cursorOffset+1),this._cursorIndexthis._cursorOffset?(this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex):this.isTextHighlightOn=!1,void this._markAsDirty()}return this.isTextHighlightOn&&(this._cursorOffset=this._textWrapper.length-this._endHighlightIndex,this.isTextHighlightOn=!1),i&&(i.ctrlKey||i.metaKey)&&(this._cursorOffset=0,i.preventDefault()),this._blinkIsEven=!1,this.isTextHighlightOn=!1,this._cursorIndex=-1,void this._markAsDirty()}if(32===e&&(t=i?.key??" "),this._deadKey="Dead"===t,t&&(-1===e||32===e||34===e||39===e||e>47&&e<64||e>64&&e<91||e>159&&e<193||e>218&&e<223||e>95&&e<112)&&(this._currentKey=t,this.onBeforeKeyAddObservable.notifyObservers(this),t=this._currentKey,this._addKey&&!this._deadKey))if(this.isTextHighlightOn)this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex,t),this._textHasChanged(),this._cursorOffset=this._textWrapper.length-(this._startHighlightIndex+1),this.isTextHighlightOn=!1,this._blinkIsEven=!1,this._markAsDirty();else if(0===this._cursorOffset)this.text+=this._deadKey&&i?.key?i.key:t;else{const e=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(e,e,t),this._textHasChanged()}}}_updateValueFromCursorIndex(e){if(this._blinkIsEven=!1,-1===this._cursorIndex)this._cursorIndex=e;else if(this._cursorIndexthis._cursorOffset))return this.isTextHighlightOn=!1,void this._markAsDirty();this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex}this.isTextHighlightOn=!0,this._markAsDirty()}_processDblClick(e){let t,i;this._startHighlightIndex=this._textWrapper.length-this._cursorOffset,this._endHighlightIndex=this._startHighlightIndex;do{i=this._endHighlightIndex0&&this._textWrapper.isWord(this._startHighlightIndex-1)?--this._startHighlightIndex:0}while(t||i);this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this.isTextHighlightOn=!0,this._clickedCoordinate=null,this._blinkIsEven=!0,this._cursorIndex=-1,this._markAsDirty()}selectAllText(){this._blinkIsEven=!0,this.isTextHighlightOn=!0,this._startHighlightIndex=0,this._endHighlightIndex=this._textWrapper.length,this._cursorOffset=this._textWrapper.length,this._cursorIndex=-1,this._markAsDirty()}processKeyboard(e){this.processKey(e.keyCode,e.key,e),super.processKeyboard(e)}_onCopyText(e){this.isTextHighlightOn=!1;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText}_onCutText(e){if(this._highlightedText){this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText,this._highlightedText=""}}_onPasteText(e){let t="";t=e.clipboardData&&-1!==e.clipboardData.types.indexOf("text/plain")?e.clipboardData.getData("text/plain"):this._host.clipboardData;const i=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(i,i,t),this._textHasChanged()}_draw(e){e.save(),this._applyStates(e),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._isFocused?this._focusedBackground&&(e.fillStyle=this._isEnabled?this._focusedBackground:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)):this._background&&(e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._fontOffset&&!this._wasDirty||(this._fontOffset=lB._GetFontOffset(e.font,this._host.getScene()?.getEngine()));const t=this._currentMeasure.left+this._margin.getValueInPixel(this._host,this._tempParentMeasure.width);this.color&&(e.fillStyle=this.color);let i=this._beforeRenderText(this._textWrapper);this._isFocused||this._textWrapper.text||!this._placeholderText||(i=new gB,i.text=this._placeholderText,this._placeholderColor&&(e.fillStyle=this._placeholderColor)),this._textWidth=e.measureText(i.text).width;const r=2*this._margin.getValueInPixel(this._host,this._tempParentMeasure.width);this._autoStretchWidth&&(this.width=Math.min(this._maxWidth.getValueInPixel(this._host,this._tempParentMeasure.width),this._textWidth+r)+"px",this._autoStretchWidth=!0);const s=this._fontOffset.ascent+(this._currentMeasure.height-this._fontOffset.height)/2,n=this._width.getValueInPixel(this._host,this._tempParentMeasure.width)-r;if(e.save(),e.beginPath(),e.rect(t,this._currentMeasure.top+(this._currentMeasure.height-this._fontOffset.height)/2,n+2,this._currentMeasure.height),e.clip(),this._isFocused&&this._textWidth>n){const e=t-this._textWidth+n;this._scrollLeft||(this._scrollLeft=e)}else this._scrollLeft=t;if(this.outlineWidth&&e.strokeText(i.text,this._scrollLeft,this._currentMeasure.top+s),e.fillText(i.text,this._scrollLeft,this._currentMeasure.top+s),this._isFocused){if(this._clickedCoordinate){const t=this._scrollLeft+this._textWidth-this._clickedCoordinate;let r=0;this._cursorOffset=0;let s=0;do{this._cursorOffset&&(s=Math.abs(t-r)),this._cursorOffset++,r=e.measureText(i.substr(i.length-this._cursorOffset,this._cursorOffset)).width}while(r=this._cursorOffset);Math.abs(t-r)>s&&this._cursorOffset--,this._blinkIsEven=!1,this._clickedCoordinate=null}if(!this._blinkIsEven){const r=i.substr(i.length-this._cursorOffset),s=e.measureText(r).width;let o=this._scrollLeft+this._textWidth-s;ot+n&&(this._scrollLeft+=t+n-o,o=t+n,this._markAsDirty()),this.isTextHighlightOn||e.fillRect(o,this._currentMeasure.top+(this._currentMeasure.height-this._fontOffset.height)/2,2,this._fontOffset.height)}if(clearTimeout(this._blinkTimeout),this._blinkTimeout=setTimeout((()=>{this._blinkIsEven=!this._blinkIsEven,this._markAsDirty()}),500),this.isTextHighlightOn){clearTimeout(this._blinkTimeout);const r=e.measureText(i.substring(this._startHighlightIndex)).width;let s=this._scrollLeft+this._textWidth-r;this._highlightedText=i.substring(this._startHighlightIndex,this._endHighlightIndex);let n=e.measureText(i.substring(this._startHighlightIndex,this._endHighlightIndex)).width;s=this._rowDefinitions.length?null:this._rowDefinitions[e]}getColumnDefinition(e){return e<0||e>=this._columnDefinitions.length?null:this._columnDefinitions[e]}addRowDefinition(e,t=!1){return this._rowDefinitions.push(new JL(e,t?JL.UNITMODE_PIXEL:JL.UNITMODE_PERCENTAGE)),this._rowDefinitionObservers.push(this._rowDefinitions[this.rowCount-1].onChangedObservable.add((()=>this._markAsDirty()))),this._markAsDirty(),this}addColumnDefinition(e,t=!1){return this._columnDefinitions.push(new JL(e,t?JL.UNITMODE_PIXEL:JL.UNITMODE_PERCENTAGE)),this._columnDefinitionObservers.push(this._columnDefinitions[this.columnCount-1].onChangedObservable.add((()=>this._markAsDirty()))),this._markAsDirty(),this}setRowDefinition(e,t,i=!1){if(e<0||e>=this._rowDefinitions.length)return this;const r=this._rowDefinitions[e];return r&&r.isPixel===i&&r.value===t||(this._rowDefinitions[e].onChangedObservable.remove(this._rowDefinitionObservers[e]),this._rowDefinitions[e]=new JL(t,i?JL.UNITMODE_PIXEL:JL.UNITMODE_PERCENTAGE),this._rowDefinitionObservers[e]=this._rowDefinitions[e].onChangedObservable.add((()=>this._markAsDirty())),this._markAsDirty()),this}setColumnDefinition(e,t,i=!1){if(e<0||e>=this._columnDefinitions.length)return this;const r=this._columnDefinitions[e];return r&&r.isPixel===i&&r.value===t||(this._columnDefinitions[e].onChangedObservable.remove(this._columnDefinitionObservers[e]),this._columnDefinitions[e]=new JL(t,i?JL.UNITMODE_PIXEL:JL.UNITMODE_PERCENTAGE),this._columnDefinitionObservers[e]=this._columnDefinitions[e].onChangedObservable.add((()=>this._markAsDirty())),this._markAsDirty()),this}getChildrenAt(e,t){const i=this._cells[`${e}:${t}`];return i?i.children:null}getChildCellInfo(e){return e._tag}_removeCell(e,t){if(e){super.removeControl(e);for(const t of e.children){const e=this._childControls.indexOf(t);-1!==e&&this._childControls.splice(e,1)}delete this._cells[t]}}_offsetCell(e,t){if(this._cells[t]){this._cells[e]=this._cells[t];for(const t of this._cells[e].children)t._tag=e;delete this._cells[t]}}removeColumnDefinition(e){if(e<0||e>=this._columnDefinitions.length)return this;for(let t=0;t=this._rowDefinitions.length)return this;for(let t=0;t{for(const s in this._cells){if(!Object.prototype.hasOwnProperty.call(this._cells,s))continue;const n=s.split(":"),o=parseInt(n[0]),a=parseInt(n[1]),l=this._cells[s];l.leftInPixels=e[a],l.topInPixels=t[o],l.widthInPixels=i[a],l.heightInPixels=r[o],l._left.ignoreAdaptiveScaling=!0,l._top.ignoreAdaptiveScaling=!0,l._width.ignoreAdaptiveScaling=!0,l._height.ignoreAdaptiveScaling=!0}})),super._additionalProcessing(e,t)}_flagDescendantsAsMatrixDirty(){for(const e in this._cells)Object.prototype.hasOwnProperty.call(this._cells,e)&&this._cells[e]._markMatrixAsDirty()}_renderHighlightSpecific(e){super._renderHighlightSpecific(e),this._getGridDefinitions(((t,i,r,s)=>{for(let i=0;i{e.tags.push(t._tag)}))}}_parseFromContent(e,t){super._parseFromContent(e,t);const i=[];this.children.forEach((e=>{i.push(e)})),this.removeRowDefinition(0),this.removeColumnDefinition(0);for(let t=0;t=1-bB._Epsilon&&(this._value.r=1),this._value.g>=1-bB._Epsilon&&(this._value.g=1),this._value.b>=1-bB._Epsilon&&(this._value.b=1),this.onValueChangedObservable.notifyObservers(this._value))}get width(){return this._width.toString(this._host)}set width(e){this._width.toString(this._host)!==e&&this._width.fromString(e)&&(0===this._width.getValue(this._host)&&(e="1px",this._width.fromString(e)),this._height.fromString(e),this._markAsDirty())}get height(){return this._height.toString(this._host)}set height(e){this._height.toString(this._host)!==e&&this._height.fromString(e)&&(0===this._height.getValue(this._host)&&(e="1px",this._height.fromString(e)),this._width.fromString(e),this._markAsDirty())}get size(){return this.width}set size(e){this.width=e}constructor(e){super(e),this.name=e,this._value=H.v9.Red(),this._tmpColor=new H.v9,this._pointerStartedOnSquare=!1,this._pointerStartedOnWheel=!1,this._squareLeft=0,this._squareTop=0,this._squareSize=0,this._h=360,this._s=1,this._v=1,this._lastPointerDownId=-1,this.onValueChangedObservable=new z.cP,this._pointerIsDown=!1,this.value=new H.v9(.88,.1,.1),this.size="200px",this.isPointerBlocker=!0}_getTypeName(){return"ColorPicker"}_preMeasure(e){e.widthl||rg?_:(_-p)*(e-m)/(g-m)+p,d=(s-h)/(e-h),o[u+3]=d1-f?255*(1-(d-(1-f))/f):255}return s.putImageData(n,0,0),r}_draw(e){e.save(),this._applyStates(e);const t=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),i=.2*t,r=this._currentMeasure.left,s=this._currentMeasure.top;this._colorWheelCanvas&&this._colorWheelCanvas.width==2*t||(this._colorWheelCanvas=this._createColorWheelCanvas(t,i)),this._updateSquareProps(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY,e.fillRect(this._squareLeft,this._squareTop,this._squareSize,this._squareSize)),e.drawImage(this._colorWheelCanvas,r,s),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._drawGradientSquare(this._h,this._squareLeft,this._squareTop,this._squareSize,this._squareSize,e);let n=this._squareLeft+this._squareSize*this._s,o=this._squareTop+this._squareSize*(1-this._v);this._drawCircle(n,o,.04*t,e);const a=t-.5*i;n=r+t+Math.cos((this._h-180)*Math.PI/180)*a,o=s+t+Math.sin((this._h-180)*Math.PI/180)*a,this._drawCircle(n,o,.35*i,e),e.restore()}_updateValueFromPointer(e,t){if(this._pointerStartedOnWheel){const i=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),r=i+this._currentMeasure.left,s=i+this._currentMeasure.top;this._h=180*Math.atan2(t-s,e-r)/Math.PI+180}else this._pointerStartedOnSquare&&(this._updateSquareProps(),this._s=(e-this._squareLeft)/this._squareSize,this._v=1-(t-this._squareTop)/this._squareSize,this._s=Math.min(this._s,1),this._s=Math.max(this._s,bB._Epsilon),this._v=Math.min(this._v,1),this._v=Math.max(this._v,bB._Epsilon));H.v9.HSVtoRGBToRef(this._h,this._s,this._v,this._tmpColor),this.value=this._tmpColor}_isPointOnSquare(e,t){this._updateSquareProps();const i=this._squareLeft,r=this._squareTop,s=this._squareSize;return e>=i&&e<=i+s&&t>=r&&t<=r+s}_isPointOnWheel(e,t){const i=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),r=i-.2*i,s=e-(i+this._currentMeasure.left),n=t-(i+this._currentMeasure.top),o=s*s+n*n;return o<=i*i&&o>=r*r}_onPointerDown(e,t,i,r,s){if(!super._onPointerDown(e,t,i,r,s))return!1;if(this.isReadOnly)return!0;this._pointerIsDown=!0,this._pointerStartedOnSquare=!1,this._pointerStartedOnWheel=!1,this._invertTransformMatrix.transformCoordinates(t.x,t.y,this._transformedPosition);const n=this._transformedPosition.x,o=this._transformedPosition.y;return this._isPointOnSquare(n,o)?this._pointerStartedOnSquare=!0:this._isPointOnWheel(n,o)&&(this._pointerStartedOnWheel=!0),this._updateValueFromPointer(n,o),this._host._capturingControl[i]=this,this._lastPointerDownId=i,!0}_onPointerMove(e,t,i,r){if(i==this._lastPointerDownId){if(!this.isReadOnly){this._invertTransformMatrix.transformCoordinates(t.x,t.y,this._transformedPosition);const e=this._transformedPosition.x,i=this._transformedPosition.y;this._pointerIsDown&&this._updateValueFromPointer(e,i)}super._onPointerMove(e,t,i,r)}}_onPointerUp(e,t,i,r,s,n){this._pointerIsDown=!1,delete this._host._capturingControl[i],super._onPointerUp(e,t,i,r,s,n)}_onCanvasBlur(){this._forcePointerUp(),super._onCanvasBlur()}static ShowPickerDialogAsync(e,t){return new Promise((i=>{t.pickerWidth=t.pickerWidth||"640px",t.pickerHeight=t.pickerHeight||"400px",t.headerHeight=t.headerHeight||"35px",t.lastColor=t.lastColor||"#000000",t.swatchLimit=t.swatchLimit||20,t.numSwatchesPerLine=t.numSwatchesPerLine||10;const r=t.swatchLimit/t.numSwatchesPerLine,s=parseFloat(t.pickerWidth)/t.numSwatchesPerLine,n=Math.floor(.25*s),o=n*(t.numSwatchesPerLine+1),a=Math.floor((parseFloat(t.pickerWidth)-o)/t.numSwatchesPerLine),l=a*r+n*(r+1),h=(parseInt(t.pickerHeight)+l+Math.floor(.25*a)).toString()+"px",c="#c0c0c0",u="#535353",d="#414141",f="515151",p="#555555",_="#454545",m=H.v9.FromHexString("#dddddd"),g=m.r+m.g+m.b,v="#aaaaaa",x="#ffffff";let b,S;const T=["R","G","B"],C="#454545",y="#f0f0f0";let E,P,A,R,I,M=!1;const O=new xB;if(O.name="Dialog Container",O.width=t.pickerWidth,t.savedColors){O.height=h;const e=parseInt(t.pickerHeight)/parseInt(h);O.addRowDefinition(e,!1),O.addRowDefinition(1-e,!1)}else O.height=t.pickerHeight,O.addRowDefinition(1,!1);if(e.addControl(O),t.savedColors){P=new xB,P.name="Swatch Drawer",P.verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP,P.background=u,P.width=t.pickerWidth;const e=t.savedColors.length/t.numSwatchesPerLine;let i;i=0==e?0:e+1,P.height=(a*e+i*n).toString()+"px",P.top=Math.floor(.25*a).toString()+"px";for(let e=0;e<2*Math.ceil(t.savedColors.length/t.numSwatchesPerLine)+1;e++)e%2!=0?P.addRowDefinition(a,!0):P.addRowDefinition(n,!0);for(let e=0;e<2*t.numSwatchesPerLine+1;e++)e%2!=0?P.addColumnDefinition(a,!0):P.addColumnDefinition(n,!0);O.addControl(P,1,0)}const D=new xB;D.name="Picker Panel",D.height=t.pickerHeight;const w=parseInt(t.headerHeight)/parseInt(t.pickerHeight),N=[w,1-w];D.addRowDefinition(N[0],!1),D.addRowDefinition(N[1],!1),O.addControl(D,0,0);const F=new cB;F.name="Dialogue Header Bar",F.background="#cccccc",F.thickness=0,D.addControl(F,0,0);const L=pB.CreateSimpleButton("closeButton","a");L.fontFamily="coreglyphs";const B=H.v9.FromHexString(F.background),V=new H.v9(1-B.r,1-B.g,1-B.b);L.color=V.toHexString(),L.fontSize=Math.floor(.6*parseInt(t.headerHeight)),L.textBlock.textVerticalAlignment=lB.VERTICAL_ALIGNMENT_CENTER,L.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_RIGHT,L.height=L.width=t.headerHeight,L.background=F.background,L.thickness=0,L.pointerDownAnimation=()=>{},L.pointerUpAnimation=()=>{L.background=F.background},L.pointerEnterAnimation=()=>{L.color=F.background,L.background="red"},L.pointerOutAnimation=()=>{L.color=V.toHexString(),L.background=F.background},L.onPointerClickObservable.add((()=>{De(ie.background)})),D.addControl(L,0,0);const k=new xB;k.name="Dialogue Body",k.background=u;const U=[.4375,.5625];k.addRowDefinition(1,!1),k.addColumnDefinition(U[0],!1),k.addColumnDefinition(U[1],!1),D.addControl(k,1,0);const G=new xB;G.name="Picker Grid",G.addRowDefinition(.85,!1),G.addRowDefinition(.15,!1),k.addControl(G,0,0);const z=new bB;z.name="GUI Color Picker",t.pickerHeight{I=z.name,R="",Re(!1)})),z.onValueChangedObservable.add((function(e){I==z.name&&ye(e,z.name)})),G.addControl(z,0,0);const W=new xB;W.name="Dialogue Right Half",W.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT;const X=[.514,.486];W.addRowDefinition(X[0],!1),W.addRowDefinition(X[1],!1),k.addControl(W,1,1);const q=new xB;q.name="Swatches and Buttons";const Y=[.417,.583];q.addRowDefinition(1,!1),q.addColumnDefinition(Y[0],!1),q.addColumnDefinition(Y[1],!1),W.addControl(q,0,0);const K=new xB;K.name="New and Current Swatches";const j=[.04,.16,.64,.16];K.addRowDefinition(j[0],!1),K.addRowDefinition(j[1],!1),K.addRowDefinition(j[2],!1),K.addRowDefinition(j[3],!1),q.addControl(K,0,0);const $=new xB;$.name="Active Swatches",$.width=.67,$.addRowDefinition(.5,!1),$.addRowDefinition(.5,!1),K.addControl($,2,0);const Q=Math.floor(parseInt(t.pickerWidth)*U[1]*Y[0]*.11),Z=Math.floor(parseInt(t.pickerHeight)*N[1]*X[0]*j[1]*.5);let J;J=t.pickerWidth>t.pickerHeight?Z:Q;const ee=new dB;ee.text="new",ee.name="New Color Label",ee.color=c,ee.fontSize=J,K.addControl(ee,1,0);const te=new cB;te.name="New Color Swatch",te.background=t.lastColor,te.thickness=0,$.addControl(te,0,0);const ie=pB.CreateSimpleButton("currentSwatch","");ie.background=t.lastColor,ie.thickness=0,ie.onPointerClickObservable.add((()=>{ye(H.v9.FromHexString(ie.background),ie.name),Re(!1)})),ie.pointerDownAnimation=()=>{},ie.pointerUpAnimation=()=>{},ie.pointerEnterAnimation=()=>{},ie.pointerOutAnimation=()=>{},$.addControl(ie,1,0);const re=new cB;re.name="Swatch Outline",re.width=.67,re.thickness=2,re.color="#404040",re.isHitTestVisible=!1,K.addControl(re,2,0);const se=new dB;se.name="Current Color Label",se.text="current",se.color=c,se.fontSize=J,K.addControl(se,3,0);const ne=new xB;ne.name="Button Grid",ne.height=.8;const oe=1/3;ne.addRowDefinition(oe,!1),ne.addRowDefinition(oe,!1),ne.addRowDefinition(oe,!1),q.addControl(ne,0,1);const ae=Math.floor(parseInt(t.pickerWidth)*U[1]*Y[1]*.67).toString()+"px",le=Math.floor(parseInt(t.pickerHeight)*N[1]*X[0]*(parseFloat(ne.height.toString())/100)*oe*.7).toString()+"px";b=parseFloat(ae)>parseFloat(le)?Math.floor(.45*parseFloat(le)):Math.floor(.11*parseFloat(ae));const he=pB.CreateSimpleButton("butOK","OK");he.width=ae,he.height=le,he.verticalAlignment=lB.VERTICAL_ALIGNMENT_CENTER,he.thickness=2,he.color=c,he.fontSize=b,he.background=u,he.onPointerEnterObservable.add((()=>{he.background=d})),he.onPointerOutObservable.add((()=>{he.background=u})),he.pointerDownAnimation=()=>{he.background=f},he.pointerUpAnimation=()=>{he.background=d},he.onPointerClickObservable.add((()=>{Re(!1),De(te.background)})),ne.addControl(he,0,0);const ce=pB.CreateSimpleButton("butCancel","Cancel");ce.width=ae,ce.height=le,ce.verticalAlignment=lB.VERTICAL_ALIGNMENT_CENTER,ce.thickness=2,ce.color=c,ce.fontSize=b,ce.background=u,ce.onPointerEnterObservable.add((()=>{ce.background=d})),ce.onPointerOutObservable.add((()=>{ce.background=u})),ce.pointerDownAnimation=()=>{ce.background=f},ce.pointerUpAnimation=()=>{ce.background=d},ce.onPointerClickObservable.add((()=>{Re(!1),De(ie.background)})),ne.addControl(ce,1,0),t.savedColors&&(A=pB.CreateSimpleButton("butSave","Save"),A.width=ae,A.height=le,A.verticalAlignment=lB.VERTICAL_ALIGNMENT_CENTER,A.thickness=2,A.fontSize=b,t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&(0==t.savedColors.length&&Me(!0),t.savedColors.length0&&Me(!0),ne.addControl(A,2,0));const ue=new xB;ue.name="Dialog Lower Right",ue.addRowDefinition(.02,!1),ue.addRowDefinition(.63,!1),ue.addRowDefinition(.21,!1),ue.addRowDefinition(.14,!1),W.addControl(ue,1,0);const de=H.v9.FromHexString(t.lastColor),fe=new xB;fe.name="RGB Values",fe.width=.82,fe.verticalAlignment=lB.VERTICAL_ALIGNMENT_CENTER,fe.addRowDefinition(1/3,!1),fe.addRowDefinition(1/3,!1),fe.addRowDefinition(1/3,!1),fe.addColumnDefinition(.1,!1),fe.addColumnDefinition(.2,!1),fe.addColumnDefinition(.7,!1),ue.addControl(fe,1,0);for(let e=0;e{I=pe.name,R=pe.text,Re(!1)})),pe.onBlurObservable.add((()=>{""==pe.text&&(pe.text="0"),Ee(pe,"r"),I==pe.name&&(I="")})),pe.onTextChangedObservable.add((()=>{I==pe.name&&Ee(pe,"r")})),fe.addControl(pe,0,1);const _e=new vB;_e.width=.83,_e.height=.72,_e.name="gIntField",_e.fontSize=b,_e.text=(255*de.g).toString(),_e.color=y,_e.background=C,_e.onFocusObservable.add((()=>{I=_e.name,R=_e.text,Re(!1)})),_e.onBlurObservable.add((()=>{""==_e.text&&(_e.text="0"),Ee(_e,"g"),I==_e.name&&(I="")})),_e.onTextChangedObservable.add((()=>{I==_e.name&&Ee(_e,"g")})),fe.addControl(_e,1,1);const me=new vB;me.width=.83,me.height=.72,me.name="bIntField",me.fontSize=b,me.text=(255*de.b).toString(),me.color=y,me.background=C,me.onFocusObservable.add((()=>{I=me.name,R=me.text,Re(!1)})),me.onBlurObservable.add((()=>{""==me.text&&(me.text="0"),Ee(me,"b"),I==me.name&&(I="")})),me.onTextChangedObservable.add((()=>{I==me.name&&Ee(me,"b")})),fe.addControl(me,2,1);const ge=new vB;ge.width=.95,ge.height=.72,ge.name="rDecField",ge.fontSize=b,ge.text=de.r.toString(),ge.color=y,ge.background=C,ge.onFocusObservable.add((()=>{I=ge.name,R=ge.text,Re(!1)})),ge.onBlurObservable.add((()=>{0!=parseFloat(ge.text)&&""!=ge.text||(ge.text="0",Pe(ge,"r")),I==ge.name&&(I="")})),ge.onTextChangedObservable.add((()=>{I==ge.name&&Pe(ge,"r")})),fe.addControl(ge,0,2);const ve=new vB;ve.width=.95,ve.height=.72,ve.name="gDecField",ve.fontSize=b,ve.text=de.g.toString(),ve.color=y,ve.background=C,ve.onFocusObservable.add((()=>{I=ve.name,R=ve.text,Re(!1)})),ve.onBlurObservable.add((()=>{0!=parseFloat(ve.text)&&""!=ve.text||(ve.text="0",Pe(ve,"g")),I==ve.name&&(I="")})),ve.onTextChangedObservable.add((()=>{I==ve.name&&Pe(ve,"g")})),fe.addControl(ve,1,2);const xe=new vB;xe.width=.95,xe.height=.72,xe.name="bDecField",xe.fontSize=b,xe.text=de.b.toString(),xe.color=y,xe.background=C,xe.onFocusObservable.add((()=>{I=xe.name,R=xe.text,Re(!1)})),xe.onBlurObservable.add((()=>{0!=parseFloat(xe.text)&&""!=xe.text||(xe.text="0",Pe(xe,"b")),I==xe.name&&(I="")})),xe.onTextChangedObservable.add((()=>{I==xe.name&&Pe(xe,"b")})),fe.addControl(xe,2,2);const be=new xB;be.name="Hex Value",be.width=.82,be.addRowDefinition(1,!1),be.addColumnDefinition(.1,!1),be.addColumnDefinition(.9,!1),ue.addControl(be,2,0);const Se=new dB;Se.text="#",Se.color=c,Se.fontSize=b,be.addControl(Se,0,0);const Te=new vB;Te.width=.96,Te.height=.72,Te.name="hexField",Te.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_CENTER,Te.fontSize=b;const Ce=t.lastColor.split("#");function ye(e,t){I=t;const i=e.toHexString();if(te.background=i,pe.name!=I&&(pe.text=Math.floor(255*e.r).toString()),_e.name!=I&&(_e.text=Math.floor(255*e.g).toString()),me.name!=I&&(me.text=Math.floor(255*e.b).toString()),ge.name!=I&&(ge.text=e.r.toString()),ve.name!=I&&(ve.text=e.g.toString()),xe.name!=I&&(xe.text=e.b.toString()),Te.name!=I){const e=i.split("#");Te.text=e[1]}z.name!=I&&(z.value=e)}function Ee(e,t){let i=e.text;if(/[^0-9]/g.test(i))e.text=R;else if(""!=i&&(Math.floor(parseInt(i))<0?i="0":Math.floor(parseInt(i))>255?i="255":isNaN(parseInt(i))&&(i="0")),I==e.name&&(R=i),""!=i){i=parseInt(i).toString(),e.text=i;const r=H.v9.FromHexString(te.background);I==e.name&&ye("r"==t?new H.v9(parseInt(i)/255,r.g,r.b):"g"==t?new H.v9(r.r,parseInt(i)/255,r.b):new H.v9(r.r,r.g,parseInt(i)/255),e.name)}}function Pe(e,t){let i=e.text;if(/[^0-9.]/g.test(i))return void(e.text=R);""!=i&&"."!=i&&0!=parseFloat(i)&&(parseFloat(i)<0?i="0.0":parseFloat(i)>1?i="1.0":isNaN(parseFloat(i))&&(i="0.0")),I==e.name&&(R=i),""!=i&&"."!=i&&0!=parseFloat(i)?(i=parseFloat(i).toString(),e.text=i):i="0.0";const r=H.v9.FromHexString(te.background);I==e.name&&ye("r"==t?new H.v9(parseFloat(i),r.g,r.b):"g"==t?new H.v9(r.r,parseFloat(i),r.b):new H.v9(r.r,r.g,parseFloat(i)),e.name)}function Ae(){if(t.savedColors&&t.savedColors[E]){let e;e=M?"b":"";const i=pB.CreateSimpleButton("Swatch_"+E,e);i.fontFamily="coreglyphs";const r=H.v9.FromHexString(t.savedColors[E]),s=r.r+r.g+r.b;i.color=s>g?v:x,i.fontSize=Math.floor(.7*a),i.textBlock.verticalAlignment=lB.VERTICAL_ALIGNMENT_CENTER,i.height=i.width=a.toString()+"px",i.background=t.savedColors[E],i.thickness=2;const n=E;return i.pointerDownAnimation=()=>{i.thickness=4},i.pointerUpAnimation=()=>{i.thickness=3},i.pointerEnterAnimation=()=>{i.thickness=3},i.pointerOutAnimation=()=>{i.thickness=2},i.onPointerClickObservable.add((()=>{M?(function(e){t.savedColors&&t.savedColors.splice(e,1),t.savedColors&&0==t.savedColors.length&&(Me(!1),M=!1)}(n),Ie("",A)):t.savedColors&&ye(H.v9.FromHexString(t.savedColors[n]),i.name)})),i}return null}function Re(e){let t;if(void 0!==e&&(M=e),M){for(let e=0;ei*t.numSwatchesPerLine?t.numSwatchesPerLine:t.savedColors.length-(i-1)*t.numSwatchesPerLine;const s=Math.min(Math.max(r,0),t.numSwatchesPerLine);for(let i=0,r=1;it.numSwatchesPerLine)continue;const s=Ae();null!=s&&(P.addControl(s,e,r),r+=2,E++)}}t.savedColors.length>=t.swatchLimit?Oe(i,!0):Oe(i,!1)}}function Me(e){e?(S=pB.CreateSimpleButton("butEdit","Edit"),S.width=ae,S.height=le,S.left=Math.floor(.1*parseInt(ae)).toString()+"px",S.top=(-1*parseFloat(S.left)).toString()+"px",S.verticalAlignment=lB.VERTICAL_ALIGNMENT_BOTTOM,S.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,S.thickness=2,S.color=c,S.fontSize=b,S.background=u,S.onPointerEnterObservable.add((()=>{S.background=d})),S.onPointerOutObservable.add((()=>{S.background=u})),S.pointerDownAnimation=()=>{S.background=f},S.pointerUpAnimation=()=>{S.background=d},S.onPointerClickObservable.add((()=>{M=!M,Re()})),G.addControl(S,1,0)):G.removeControl(S)}function Oe(e,t){t?(e.color=p,e.background=_):(e.color=c,e.background=u)}function De(r){t.savedColors&&t.savedColors.length>0?i({savedColors:t.savedColors,pickedColor:r}):i({pickedColor:r}),e.removeControl(O)}Te.text=Ce[1],Te.color=y,Te.background=C,Te.onFocusObservable.add((()=>{I=Te.name,R=Te.text,Re(!1)})),Te.onBlurObservable.add((()=>{if(3==Te.text.length){const e=Te.text.split("");Te.text=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]}""==Te.text&&(Te.text="000000",ye(H.v9.FromHexString(Te.text),"b")),I==Te.name&&(I="")})),Te.onTextChangedObservable.add((()=>{let e=Te.text;const t=/[^0-9A-F]/i.test(e);if((Te.text.length>6||t)&&I==Te.name)Te.text=R;else{if(Te.text.length<6){const t=6-Te.text.length;for(let i=0;i0&&Ie("",A)}))}}bB._Epsilon=1e-6,(0,je.Cg)([(0,$e.lK)()],bB.prototype,"value",null),(0,je.Cg)([(0,$e.lK)()],bB.prototype,"width",null),(0,je.Cg)([(0,$e.lK)()],bB.prototype,"height",null),(0,je.Cg)([(0,$e.lK)()],bB.prototype,"size",null),(0,X.Y5)("BABYLON.GUI.ColorPicker",bB);class SB extends hB{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}get arc(){return this._arc}set arc(e){this._arc!==e&&(this._arc=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thickness=1,this._arc=1}_getTypeName(){return"Ellipse"}_localDraw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),lB.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._thickness/2,this._currentMeasure.height/2-this._thickness/2,this._arc,e),(this._backgroundGradient||this._background)&&(e.fillStyle=this._getBackgroundColor(e),e.fill()),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._thickness&&(this.color&&(e.strokeStyle=this.color),e.lineWidth=this._thickness,e.stroke()),e.restore()}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.width-=2*this._thickness,this._measureForChildren.height-=2*this._thickness,this._measureForChildren.left+=this._thickness,this._measureForChildren.top+=this._thickness}_clipForChildren(e){lB.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2,this._currentMeasure.height/2,this._arc,e),e.clip()}_renderHighlightSpecific(e){lB.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._highlightLineWidth/2,this._currentMeasure.height/2-this._highlightLineWidth/2,this._arc,e),e.stroke()}}(0,je.Cg)([(0,$e.lK)()],SB.prototype,"thickness",null),(0,je.Cg)([(0,$e.lK)()],SB.prototype,"arc",null),(0,X.Y5)("BABYLON.GUI.Ellipse",SB);class TB extends pB{constructor(e){super(e),this.name=e,this._unfocusedColor=this.color}_onPointerDown(e,t,i,r,s){return this.isReadOnly||this.focus(),super._onPointerDown(e,t,i,r,s)}}(0,X.Y5)("BABYLON.GUI.FocusableButton",TB);class CB extends vB{get autoStretchHeight(){return this._autoStretchHeight}set autoStretchHeight(e){this._autoStretchHeight!==e&&(this._autoStretchHeight=e,this._markAsDirty())}set height(e){this.fixedRatioMasterIsWidth=!1,this._height.toString(this._host)!==e&&(this._height.fromString(e)&&this._markAsDirty(),this._autoStretchHeight=!1)}get maxHeight(){return this._maxHeight.toString(this._host)}get maxHeightInPixels(){return this._maxHeight.getValueInPixel(this._host,this._cachedParentMeasure.height)}set maxHeight(e){this._maxHeight.toString(this._host)!==e&&this._maxHeight.fromString(e)&&this._markAsDirty()}constructor(e,t=""){super(e),this.name=e,this._textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,this._textVerticalAlignment=lB.VERTICAL_ALIGNMENT_TOP,this._prevText=this.text,this._lineSpacing=new JL(0),this._maxHeight=new JL(1,JL.UNITMODE_PERCENTAGE,!1),this.onLinesReadyObservable=new z.cP,this.text=t,this.isPointerBlocker=!0,this.onLinesReadyObservable.add((()=>this._updateCursorPosition())),this._highlightCursorInfo={initialStartIndex:-1,initialRelativeStartIndex:-1,initialLineIndex:-1},this._cursorInfo={globalStartIndex:0,globalEndIndex:0,relativeEndIndex:0,relativeStartIndex:0,currentLineIndex:0}}_getTypeName(){return"InputTextArea"}processKeyboard(e){this.isReadOnly||(this.alternativeProcessKey(e.code,e.key,e),this.onKeyboardEventProcessedObservable.notifyObservers(e))}alternativeProcessKey(e,t,i){if(!i||!i.ctrlKey&&!i.metaKey||"c"!==t&&"v"!==t&&"x"!==t){switch(e){case"Period":i&&i.shiftKey&&i.preventDefault();break;case"Backspace":!this._isTextHighlightOn&&this._cursorInfo.globalStartIndex>0&&(this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex--),this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,i&&i.preventDefault(),this._blinkIsEven=!1,this._isTextHighlightOn=!1,this._textHasChanged();break;case"Delete":!this._isTextHighlightOn&&this._cursorInfo.globalEndIndexthis._highlightCursorInfo.initialStartIndex?this._cursorInfo.globalEndIndex--:this._cursorInfo.globalStartIndex--:(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex--,this._isTextHighlightOn=!0),this._blinkIsEven=!0,void i.preventDefault()):(this._isTextHighlightOn?this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex:i&&(i.ctrlKey||i.metaKey)?(this._cursorInfo.globalStartIndex-=this._cursorInfo.relativeStartIndex,i.preventDefault()):this._cursorInfo.globalStartIndex>0&&this._cursorInfo.globalStartIndex--,this._blinkIsEven=!1,void(this._isTextHighlightOn=!1));case"ArrowRight":if(this._markAsDirty(),i&&i.shiftKey){if(i.ctrlKey||i.metaKey){const e=this._lines[this._cursorInfo.currentLineIndex].text.length-this._cursorInfo.relativeEndIndex-1;this._cursorInfo.globalEndIndex+=e,this._cursorInfo.globalStartIndex=this._highlightCursorInfo.initialStartIndex}return this._isTextHighlightOn?this._cursorInfo.globalStartIndexa&&l>0&&i--,this._isTextHighlightOn?this._cursorInfo.currentLineIndex<=this._highlightCursorInfo.initialLineIndex?(this._cursorInfo.globalStartIndex=i,this._cursorInfo.globalEndIndex=this._highlightCursorInfo.initialStartIndex,this._cursorInfo.relativeEndIndex=this._highlightCursorInfo.initialRelativeStartIndex):this._cursorInfo.globalEndIndex=i:this._cursorInfo.globalStartIndex=i}return void this._markAsDirty();case"ArrowDown":if(this._blinkIsEven=!1,i&&(i.shiftKey?(this._isTextHighlightOn||(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex),this._isTextHighlightOn=!0,this._blinkIsEven=!0):this._isTextHighlightOn=!1,i.preventDefault()),this._cursorInfo.currentLineIndex===this._lines.length-1)this._cursorInfo.globalStartIndex=this.text.length;else{const e=this._lines[this._cursorInfo.currentLineIndex],t=this._lines[this._cursorInfo.currentLineIndex+1];let i=0,r=0;!this._isTextHighlightOn||this._cursorInfo.currentLineIndexa&&l>0&&i--,this._isTextHighlightOn?this._cursorInfo.currentLineIndexthis._cursorInfo.globalEndIndex&&(this._cursorInfo.globalEndIndex+=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex=this._cursorInfo.globalEndIndex-this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex-=this._cursorInfo.globalStartIndex)):(this._cursorInfo.globalEndIndex=i,this._cursorInfo.globalStartIndex=this._highlightCursorInfo.initialStartIndex):this._cursorInfo.globalStartIndex=i}return void this._markAsDirty()}if("a"===t&&i&&(i.ctrlKey||i.metaKey))return this.selectAllText(),void i.preventDefault();1===t?.length&&(i?.preventDefault(),this._currentKey=t,this.onBeforeKeyAddObservable.notifyObservers(this),t=this._currentKey,this._addKey&&(this._isTextHighlightOn=!1,this._blinkIsEven=!1,this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex,t),this._cursorInfo.globalStartIndex+=t.length,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._textHasChanged()))}}_parseLineWordWrap(e="",t,i){const r=[],s=e.split(" ");let n=0;for(let o=0;o0?e+" "+s[o]:s[0],l=i.measureText(a).width;if(l>t){o>0&&(n=i.measureText(e).width,r.push({text:e,width:n,lineEnding:" "})),e=s[o];let a="";e.split("").map((e=>{i.measureText(a+e).width>t&&(r.push({text:a,width:i.measureText(a).width,lineEnding:""}),a=""),a+=e})),e=a,n=i.measureText(e).width}else n=l,e=a}return r.push({text:e,width:n,lineEnding:" "}),r}_breakLines(e,t){const i=[],r=(this.text||this.placeholderText).split("\n");if(this.clipContent)for(const s of r)i.push(...this._parseLineWordWrap(s,e,t));else for(const e of r)i.push(this._parseLine(e,t));return i[i.length-1].lineEnding="\n",i}_parseLine(e="",t){return{text:e,width:t.measureText(e).width,lineEnding:" "}}_preMeasure(e,t){this._fontOffset&&!this._wasDirty||(this._fontOffset=lB._GetFontOffset(t.font,this._host.getScene()?.getEngine()));let i=this._beforeRenderText(this._textWrapper).text;!this.text&&this._placeholderText&&(i=this._placeholderText),this._textWidth=t.measureText(i).width;const r=2*this._margin.getValueInPixel(this._host,e.width);if(this._autoStretchWidth){const s=i.split("\n").reduce(((e,i)=>t.measureText(i).width>t.measureText(e).width?i:e),""),n=t.measureText(s).width;this.width=Math.min(this._maxWidth.getValueInPixel(this._host,e.width),n+r)+"px",this.autoStretchWidth=!0}if(this._availableWidth=this._width.getValueInPixel(this._host,e.width)-r,this._lines=this._breakLines(this._availableWidth,t),this._contextForBreakLines=t,this._autoStretchHeight){const t=this._lines.length*this._fontOffset.height+2*this._margin.getValueInPixel(this._host,e.height);this.height=Math.min(this._maxHeight.getValueInPixel(this._host,e.height),t)+"px",this._autoStretchHeight=!0}if(this._availableHeight=this._height.getValueInPixel(this._host,e.height)-r,this._isFocused){this._cursorInfo.currentLineIndex=0;let e=this._lines[this._cursorInfo.currentLineIndex].text.length+this._lines[this._cursorInfo.currentLineIndex].lineEnding.length,t=0;for(;t+e<=this._cursorInfo.globalStartIndex;)t+=e,this._cursorInfo.currentLineIndexthis._availableWidth){const e=this._clipTextLeft-this._lines[this._cursorInfo.currentLineIndex].width+this._availableWidth;this._scrollLeft||(this._scrollLeft=e)}else this._scrollLeft=this._clipTextLeft;if(this._isFocused){const e=(this._cursorInfo.currentLineIndex+1)*this._fontOffset.height,t=this._clipTextTop-e;this._scrollTop||(this._scrollTop=t)}else this._scrollTop=this._clipTextTop}_additionalProcessing(){this.highlightedText="",this.onLinesReadyObservable.notifyObservers(this)}_drawText(e,t,i,r){const s=this._currentMeasure.width;let n=this._scrollLeft;switch(this._textHorizontalAlignment){case lB.HORIZONTAL_ALIGNMENT_LEFT:n+=0;break;case lB.HORIZONTAL_ALIGNMENT_RIGHT:n+=s-t;break;case lB.HORIZONTAL_ALIGNMENT_CENTER:n+=(s-t)/2}(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(r.shadowColor=this.shadowColor,r.shadowBlur=this.shadowBlur,r.shadowOffsetX=this.shadowOffsetX,r.shadowOffsetY=this.shadowOffsetY),this.outlineWidth&&r.strokeText(e,this._currentMeasure.left+n,i),r.fillText(e,n,i)}_onCopyText(e){this._isTextHighlightOn=!1;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText}_onCutText(e){if(this._highlightedText){try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText,this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),this._textHasChanged()}}_onPasteText(e){let t="";t=e.clipboardData&&-1!==e.clipboardData.types.indexOf("text/plain")?e.clipboardData.getData("text/plain"):this._host.clipboardData,this._isTextHighlightOn=!1,this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex,t);const i=t.length-(this._cursorInfo.globalEndIndex-this._cursorInfo.globalStartIndex);this._cursorInfo.globalStartIndex+=i,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._clickedCoordinateX=null,this._clickedCoordinateY=null,super._textHasChanged()}_draw(e){this._computeScroll(),this._scrollLeft=this._scrollLeft??0,this._scrollTop=this._scrollTop??0,e.save(),this._applyStates(e),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._isFocused?this._focusedBackground&&(e.fillStyle=this._isEnabled?this._focusedBackground:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)):this._background&&(e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this.color&&(e.fillStyle=this.color);const t=this._currentMeasure.height,i=this._currentMeasure.width;let r=0;switch(this._textVerticalAlignment){case lB.VERTICAL_ALIGNMENT_TOP:r=this._fontOffset.ascent;break;case lB.VERTICAL_ALIGNMENT_BOTTOM:r=t-this._fontOffset.height*(this._lines.length-1)-this._fontOffset.descent;break;case lB.VERTICAL_ALIGNMENT_CENTER:r=this._fontOffset.ascent+(t-this._fontOffset.height*this._lines.length)/2}e.save(),e.beginPath(),e.fillStyle=this.fontStyle,!this._textWrapper.text&&this.placeholderText&&(e.fillStyle=this._placeholderColor),e.rect(this._clipTextLeft,this._clipTextTop,this._availableWidth+2,this._availableHeight+2),e.clip(),r+=this._scrollTop;for(let t=0;tthis._clipTextLeft+this._availableWidth&&(this._scrollLeft+=this._clipTextLeft+this._availableWidth-t,t=this._clipTextLeft+this._availableWidth,this._markAsDirty());let i=this._scrollTop+this._cursorInfo.currentLineIndex*this._fontOffset.height;ithis._clipTextTop+this._availableHeight&&this._availableHeight>this._fontOffset.height&&(this._scrollTop+=this._clipTextTop+this._availableHeight-i-this._fontOffset.height,i=this._clipTextTop+this._availableHeight-this._fontOffset.height,this._markAsDirty()),this._isTextHighlightOn||e.fillRect(t,i,2,this._fontOffset.height)}if(this._resetBlinking(),this._isTextHighlightOn){clearTimeout(this._blinkTimeout),this._highlightedText=this.text.substring(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),e.globalAlpha=this._highligherOpacity,e.fillStyle=this._textHighlightColor;const t=Math.min(this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialLineIndex),r=Math.max(this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialLineIndex);let s=this._scrollTop+t*this._fontOffset.height;for(let n=t;n<=r;n++){const o=this._lines[n];let a=this._scrollLeft;switch(this._textHorizontalAlignment){case lB.HORIZONTAL_ALIGNMENT_LEFT:a+=0;break;case lB.HORIZONTAL_ALIGNMENT_RIGHT:a+=i-o.width;break;case lB.HORIZONTAL_ALIGNMENT_CENTER:a+=(i-o.width)/2}const l=n===t?this._cursorInfo.relativeStartIndex:0,h=n===r?this._cursorInfo.relativeEndIndex:o.text.length,c=e.measureText(o.text.substring(0,l)).width,u=o.text.substring(l,h),d=e.measureText(u).width;e.fillRect(a+c,s,d,this._fontOffset.height),s+=this._fontOffset.height}this._cursorInfo.globalEndIndex===this._cursorInfo.globalStartIndex&&this._resetBlinking()}}e.restore(),this._thickness&&(this._isFocused?this.focusedColor&&(e.strokeStyle=this.focusedColor):this.color&&(e.strokeStyle=this.color),e.lineWidth=this._thickness,e.strokeRect(this._currentMeasure.left+this._thickness/2,this._currentMeasure.top+this._thickness/2,this._currentMeasure.width-this._thickness,this._currentMeasure.height-this._thickness))}_resetBlinking(){clearTimeout(this._blinkTimeout),this._blinkTimeout=setTimeout((()=>{this._blinkIsEven=!this._blinkIsEven,this._markAsDirty()}),500)}_onPointerDown(e,t,i,r,s){return!(!super._onPointerDown(e,t,i,r,s)||!this.isReadOnly&&(this._clickedCoordinateX=t.x,this._clickedCoordinateY=t.y,this._isTextHighlightOn=!1,this._highlightedText="",this._isPointerDown=!0,this._host._capturingControl[i]=this,this._host.focusedControl===this?(clearTimeout(this._blinkTimeout),this._markAsDirty(),0):!this._isEnabled||(this._host.focusedControl=this,0)))}_onPointerMove(e,t,i,r){0===r.event.movementX&&0===r.event.movementY||(this._host.focusedControl===this&&this._isPointerDown&&!this.isReadOnly&&(this._clickedCoordinateX=t.x,this._clickedCoordinateY=t.y,this._isTextHighlightOn||(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex,this._isTextHighlightOn=!0),this._markAsDirty()),super._onPointerMove(e,t,i,r))}_updateCursorPosition(){if(this._isFocused)if(!this._textWrapper.text&&this.placeholderText)this._cursorInfo.currentLineIndex=0,this._cursorInfo.globalStartIndex=0,this._cursorInfo.globalEndIndex=0,this._cursorInfo.relativeStartIndex=0,this._cursorInfo.relativeEndIndex=0;else if(this._clickedCoordinateX&&this._clickedCoordinateY){this._isTextHighlightOn||(this._cursorInfo={globalStartIndex:0,globalEndIndex:0,relativeStartIndex:0,relativeEndIndex:0,currentLineIndex:0});let e=0,t=0;const i=this._clickedCoordinateY-this._scrollTop,r=Math.floor(i/this._fontOffset.height);this._cursorInfo.currentLineIndex=Math.min(Math.max(r,0),this._lines.length-1);let s=0;const n=this._clickedCoordinateX-(this._scrollLeft??0);let o=0;for(let t=0;tt;)t++,o=Math.abs(n-s),s=this._contextForBreakLines.measureText(this._lines[this._cursorInfo.currentLineIndex].text.substring(0,t)).width;Math.abs(n-s)>o&&t>0&&t--,e+=t,this._isTextHighlightOn?e=this._highlightCursorInfo.initialStartIndex){for(;t+e<=this._cursorInfo.globalEndIndex;)t+=e,this._cursorInfo.currentLineIndex0&&this._textWrapper.isWord(this._cursorInfo.globalStartIndex-1)?--this._cursorInfo.globalStartIndex:0,i=this._cursorInfo.globalEndIndexthis._markAsDirty()))),this._connectedControl=e,this._markAsDirty())}get x1(){return this._x1.toString(this._host)}set x1(e){this._x1.toString(this._host)!==e&&this._x1.fromString(e)&&this._markAsDirty()}get y1(){return this._y1.toString(this._host)}set y1(e){this._y1.toString(this._host)!==e&&this._y1.fromString(e)&&this._markAsDirty()}get x2(){return this._x2.toString(this._host)}set x2(e){this._x2.toString(this._host)!==e&&this._x2.fromString(e)&&this._markAsDirty()}get y2(){return this._y2.toString(this._host)}set y2(e){this._y2.toString(this._host)!==e&&this._y2.fromString(e)&&this._markAsDirty()}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth!==e&&(this._lineWidth=e,this._markAsDirty())}set horizontalAlignment(e){}set verticalAlignment(e){}get _effectiveX2(){return(this._connectedControl?this._connectedControl.centerX:0)+this._x2.getValue(this._host)}get _effectiveY2(){return(this._connectedControl?this._connectedControl.centerY:0)+this._y2.getValue(this._host)}constructor(e){super(e),this.name=e,this._lineWidth=1,this._x1=new JL(0),this._y1=new JL(0),this._x2=new JL(0),this._y2=new JL(0),this._dash=new Array,this._automaticSize=!0,this.isHitTestVisible=!1,this._horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,this._verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP}_getTypeName(){return"Line"}_draw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._applyStates(e),e.strokeStyle=this._getColor(e),e.lineWidth=this._lineWidth,e.setLineDash(this._dash),e.beginPath(),e.moveTo(this._cachedParentMeasure.left+this._x1.getValue(this._host),this._cachedParentMeasure.top+this._y1.getValue(this._host)),e.lineTo(this._cachedParentMeasure.left+this._effectiveX2,this._cachedParentMeasure.top+this._effectiveY2),e.stroke(),e.restore()}_measure(){this._currentMeasure.width=Math.abs(this._x1.getValue(this._host)-this._effectiveX2)+this._lineWidth,this._currentMeasure.height=Math.abs(this._y1.getValue(this._host)-this._effectiveY2)+this._lineWidth}_computeAlignment(e){this._currentMeasure.left=e.left+Math.min(this._x1.getValue(this._host),this._effectiveX2)-this._lineWidth/2,this._currentMeasure.top=e.top+Math.min(this._y1.getValue(this._host),this._effectiveY2)-this._lineWidth/2}moveToVector3(e,t,i=!1){if(!this._host||this.parent!==this._host._rootContainer)return void Ue.S0.Error("Cannot move a control to a vector3 if the control is not at root level");const r=this._host._getGlobalViewport(),s=W.Pq.Project(e,W.uq.IdentityReadOnly,t.getTransformMatrix(),r);this._moveToProjectedPosition(s,i),s.z<0||s.z>1?this.notRenderable=!0:this.notRenderable=!1}_moveToProjectedPosition(e,t=!1){const i=e.x+this._linkOffsetX.getValue(this._host)+"px",r=e.y+this._linkOffsetY.getValue(this._host)+"px";t?(this.x2=i,this.y2=r,this._x2.ignoreAdaptiveScaling=!0,this._y2.ignoreAdaptiveScaling=!0):(this.x1=i,this.y1=r,this._x1.ignoreAdaptiveScaling=!0,this._y1.ignoreAdaptiveScaling=!0)}}(0,je.Cg)([(0,$e.lK)()],EB.prototype,"dash",null),(0,je.Cg)([(0,$e.lK)()],EB.prototype,"x1",null),(0,je.Cg)([(0,$e.lK)()],EB.prototype,"y1",null),(0,je.Cg)([(0,$e.lK)()],EB.prototype,"x2",null),(0,je.Cg)([(0,$e.lK)()],EB.prototype,"y2",null),(0,je.Cg)([(0,$e.lK)()],EB.prototype,"lineWidth",null),(0,X.Y5)("BABYLON.GUI.Line",EB);class PB{constructor(e){this._multiLine=e,this._x=new JL(0),this._y=new JL(0),this._point=new W.Pq(0,0,0)}get x(){return this._x.toString(this._multiLine._host)}set x(e){this._x.toString(this._multiLine._host)!==e&&this._x.fromString(e)&&this._multiLine._markAsDirty()}get y(){return this._y.toString(this._multiLine._host)}set y(e){this._y.toString(this._multiLine._host)!==e&&this._y.fromString(e)&&this._multiLine._markAsDirty()}get control(){return this._control}set control(e){this._control!==e&&(this._control&&this._controlObserver&&(this._control.onDirtyObservable.remove(this._controlObserver),this._controlObserver=null),this._control=e,this._control&&(this._controlObserver=this._control.onDirtyObservable.add(this._multiLine.onPointUpdate)),this._multiLine._markAsDirty())}get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh&&this._meshObserver&&this._mesh.getScene().onAfterCameraRenderObservable.remove(this._meshObserver),this._mesh=e,this._mesh&&(this._meshObserver=this._mesh.getScene().onAfterCameraRenderObservable.add(this._multiLine.onPointUpdate)),this._multiLine._markAsDirty())}resetLinks(){this.control=null,this.mesh=null}translate(){return this._point=this._translatePoint(),this._point}_translatePoint(){if(null!=this._mesh)return this._multiLine._host.getProjectedPositionWithZ(this._mesh.getBoundingInfo().boundingSphere.center,this._mesh.getWorldMatrix());if(null!=this._control)return new W.Pq(this._control.centerX,this._control.centerY,1-lt.bH);{const e=this._multiLine._host,t=this._x.getValueInPixel(e,Number(e._canvas.width)),i=this._y.getValueInPixel(e,Number(e._canvas.height));return new W.Pq(t,i,1-lt.bH)}}dispose(){this.resetLinks()}}class AB extends lB{constructor(e){super(e),this.name=e,this._lineWidth=1,this.onPointUpdate=()=>{this._markAsDirty()},this._automaticSize=!0,this.isHitTestVisible=!1,this._horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,this._verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP,this._dash=[],this._points=[]}get dash(){return this._dash}set dash(e){this._dash!==e&&(this._dash=e,this._markAsDirty())}getAt(e){return this._points[e]||(this._points[e]=new PB(this)),this._points[e]}add(...e){return e.map((e=>this.push(e)))}push(e){const t=this.getAt(this._points.length);return null==e||(e instanceof Nt?t.mesh=e:e instanceof lB?t.control=e:null!=e.x&&null!=e.y&&(t.x=e.x,t.y=e.y)),t}remove(e){let t;if(e instanceof PB){if(t=this._points.indexOf(e),-1===t)return}else t=e;const i=this._points[t];i&&(i.dispose(),this._points.splice(t,1))}reset(){for(;this._points.length>0;)this.remove(this._points.length-1)}resetLinks(){this._points.forEach((e=>{null!=e&&e.resetLinks()}))}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth!==e&&(this._lineWidth=e,this._markAsDirty())}set horizontalAlignment(e){}set verticalAlignment(e){}_getTypeName(){return"MultiLine"}_draw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._applyStates(e),e.strokeStyle=this.color,e.lineWidth=this._lineWidth,e.setLineDash(this._dash),e.beginPath();let t,i=!0;this._points.forEach((r=>{r&&(i?(e.moveTo(r._point.x,r._point.y),i=!1):r._point.z<1&&t.z<1?e.lineTo(r._point.x,r._point.y):e.moveTo(r._point.x,r._point.y),t=r._point)})),e.stroke(),e.restore()}_additionalProcessing(){this._minX=null,this._minY=null,this._maxX=null,this._maxY=null,this._points.forEach((e=>{e&&(e.translate(),(null==this._minX||e._point.xthis._maxX)&&(this._maxX=e._point.x),(null==this._maxY||e._point.y>this._maxY)&&(this._maxY=e._point.y))})),null==this._minX&&(this._minX=0),null==this._minY&&(this._minY=0),null==this._maxX&&(this._maxX=0),null==this._maxY&&(this._maxY=0)}_measure(){null!=this._minX&&null!=this._maxX&&null!=this._minY&&null!=this._maxY&&(this._currentMeasure.width=Math.abs(this._maxX-this._minX)+this._lineWidth,this._currentMeasure.height=Math.abs(this._maxY-this._minY)+this._lineWidth)}_computeAlignment(){null!=this._minX&&null!=this._minY&&(this._currentMeasure.left=this._minX-this._lineWidth/2,this._currentMeasure.top=this._minY-this._lineWidth/2)}dispose(){this.reset(),super.dispose()}}(0,je.Cg)([(0,$e.lK)()],AB.prototype,"dash",null),(0,X.Y5)("BABYLON.GUI.MultiLine",AB);class RB extends lB{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}get checkSizeRatio(){return this._checkSizeRatio}set checkSizeRatio(e){e=Math.max(Math.min(1,e),0),this._checkSizeRatio!==e&&(this._checkSizeRatio=e,this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get isChecked(){return this._isChecked}set isChecked(e){this._isChecked!==e&&(this._isChecked=e,this._markAsDirty(),this.onIsCheckedChangedObservable.notifyObservers(e),this._isChecked&&this._host&&this._host.executeOnAllControls((e=>{if(e===this)return;if(void 0===e.group)return;const t=e;t.group===this.group&&(t.isChecked=!1)})))}constructor(e){super(e),this.name=e,this._isChecked=!1,this._background="black",this._checkSizeRatio=.8,this._thickness=1,this.group="",this.onIsCheckedChangedObservable=new z.cP,this.isPointerBlocker=!0}_getTypeName(){return"RadioButton"}_draw(e){e.save(),this._applyStates(e);const t=this._currentMeasure.width-this._thickness,i=this._currentMeasure.height-this._thickness;if((this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),lB.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._thickness/2,this._currentMeasure.height/2-this._thickness/2,1,e),e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fill(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),e.strokeStyle=this.color,e.lineWidth=this._thickness,e.stroke(),this._isChecked){e.fillStyle=this._isEnabled?this.color:this._disabledColor;const r=t*this._checkSizeRatio,s=i*this._checkSizeRatio;lB.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,r/2-this._thickness/2,s/2-this._thickness/2,1,e),e.fill()}e.restore()}_onPointerDown(e,t,i,r,s){return!!super._onPointerDown(e,t,i,r,s)&&(this.isReadOnly||this.isChecked||(this.isChecked=!0),!0)}static AddRadioButtonWithHeader(e,t,i,r){const s=new _B;s.isVertical=!1,s.height="30px";const n=new RB;n.width="20px",n.height="20px",n.isChecked=i,n.color="green",n.group=t,n.onIsCheckedChangedObservable.add((e=>r(n,e))),s.addControl(n);const o=new dB;return o.text=e,o.width="180px",o.paddingLeft="5px",o.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,o.color="white",s.addControl(o),s}}(0,je.Cg)([(0,$e.lK)()],RB.prototype,"thickness",null),(0,je.Cg)([(0,$e.lK)()],RB.prototype,"group",void 0),(0,je.Cg)([(0,$e.lK)()],RB.prototype,"checkSizeRatio",null),(0,je.Cg)([(0,$e.lK)()],RB.prototype,"background",null),(0,je.Cg)([(0,$e.lK)()],RB.prototype,"isChecked",null),(0,X.Y5)("BABYLON.GUI.RadioButton",RB);class IB extends lB{get displayThumb(){return this._displayThumb}set displayThumb(e){this._displayThumb!==e&&(this._displayThumb=e,this._markAsDirty())}get step(){return this._step}set step(e){this._step!==e&&(this._step=e,this._markAsDirty())}get barOffset(){return this._barOffset.toString(this._host)}get barOffsetInPixels(){return this._barOffset.getValueInPixel(this._host,this._cachedParentMeasure.width)}set barOffset(e){this._barOffset.toString(this._host)!==e&&this._barOffset.fromString(e)&&this._markAsDirty()}get thumbWidth(){return this._thumbWidth.toString(this._host)}get thumbWidthInPixels(){return this._thumbWidth.getValueInPixel(this._host,this._cachedParentMeasure.width)}set thumbWidth(e){this._thumbWidth.toString(this._host)!==e&&this._thumbWidth.fromString(e)&&this._markAsDirty()}get minimum(){return this._minimum}set minimum(e){this._minimum!==e&&(this._minimum=e,this._markAsDirty(),this.value=Math.max(Math.min(this.value,this._maximum),this._minimum))}get maximum(){return this._maximum}set maximum(e){this._maximum!==e&&(this._maximum=e,this._markAsDirty(),this.value=Math.max(Math.min(this.value,this._maximum),this._minimum))}get value(){return this._value}set value(e){e=Math.max(Math.min(e,this._maximum),this._minimum),this._value!==e&&(this._value=e,this._markAsDirty(),this.onValueChangedObservable.notifyObservers(this._value))}get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,this._markAsDirty())}get isThumbClamped(){return this._isThumbClamped}set isThumbClamped(e){this._isThumbClamped!==e&&(this._isThumbClamped=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thumbWidth=new JL(20,JL.UNITMODE_PIXEL,!1),this._minimum=0,this._maximum=100,this._value=50,this._isVertical=!1,this._barOffset=new JL(5,JL.UNITMODE_PIXEL,!1),this._isThumbClamped=!1,this._displayThumb=!0,this._step=0,this._lastPointerDownId=-1,this._effectiveBarOffset=0,this.onValueChangedObservable=new z.cP,this._pointerIsDown=!1,this.isPointerBlocker=!0}_getTypeName(){return"BaseSlider"}_getThumbPosition(){return this.isVertical?(this.maximum-this.value)/(this.maximum-this.minimum)*this._backgroundBoxLength:(this.value-this.minimum)/(this.maximum-this.minimum)*this._backgroundBoxLength}_getThumbThickness(e){let t=0;switch(e){case"circle":t=this._thumbWidth.isPixel?Math.max(this._thumbWidth.getValue(this._host),this._backgroundBoxThickness):this._backgroundBoxThickness*this._thumbWidth.getValue(this._host);break;case"rectangle":t=this._thumbWidth.isPixel?Math.min(this._thumbWidth.getValue(this._host),this._backgroundBoxThickness):this._backgroundBoxThickness*this._thumbWidth.getValue(this._host)}return t}_prepareRenderingData(e){this._effectiveBarOffset=0,this._renderLeft=this._currentMeasure.left,this._renderTop=this._currentMeasure.top,this._renderWidth=this._currentMeasure.width,this._renderHeight=this._currentMeasure.height,this._backgroundBoxLength=Math.max(this._currentMeasure.width,this._currentMeasure.height),this._backgroundBoxThickness=Math.min(this._currentMeasure.width,this._currentMeasure.height),this._effectiveThumbThickness=this._getThumbThickness(e),this.displayThumb&&(this._backgroundBoxLength-=this._effectiveThumbThickness),this.isVertical&&this._currentMeasure.height=this._selectors.length))return this._selectors[e]}removeSelector(e){e<0||e>=this._selectors.length||(this._groupPanel.removeControl(this._selectors[e]),this._selectors.splice(e,1))}}class DB extends OB{addCheckbox(e,t=(e=>{}),i=!1){i=i||!1;const r=new mB;r.width="20px",r.height="20px",r.color="#364249",r.background="#CCCCCC",r.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,r.onIsCheckedChangedObservable.add((function(e){t(e)}));const s=lB.AddHeader(r,e,"200px",{isHorizontal:!0,controlFirst:!0});s.height="30px",s.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,s.left="4px",this.groupPanel.addControl(s),this.selectors.push(s),r.isChecked=i,this.groupPanel.parent&&this.groupPanel.parent.parent&&(r.color=this.groupPanel.parent.parent.buttonColor,r.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[1].text=t}_setSelectorLabelColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[0].background=t}}class wB extends OB{constructor(){super(...arguments),this._selectNb=0}addRadio(e,t=(e=>{}),i=!1){const r=this._selectNb++,s=new RB;s.name=e,s.width="20px",s.height="20px",s.color="#364249",s.background="#CCCCCC",s.group=this.name,s.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,s.onIsCheckedChangedObservable.add((function(e){e&&t(r)}));const n=lB.AddHeader(s,e,"200px",{isHorizontal:!0,controlFirst:!0});n.height="30px",n.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,n.left="4px",this.groupPanel.addControl(n),this.selectors.push(n),s.isChecked=i,this.groupPanel.parent&&this.groupPanel.parent.parent&&(s.color=this.groupPanel.parent.parent.buttonColor,s.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[1].text=t}_setSelectorLabelColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[0].background=t}}class NB extends OB{addSlider(e,t=(e=>{}),i="Units",r=0,s=0,n=0,o=(e=>0|e)){const a=new MB;a.name=i,a.value=n,a.minimum=r,a.maximum=s,a.width=.9,a.height="20px",a.color="#364249",a.background="#CCCCCC",a.borderColor="black",a.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,a.left="4px",a.paddingBottom="4px",a.onValueChangedObservable.add((function(e){a.parent.children[0].text=a.parent.children[0].name+": "+o(e)+" "+a.name,t(e)}));const l=lB.AddHeader(a,e+": "+o(n)+" "+i,"30px",{isHorizontal:!1,controlFirst:!1});l.height="60px",l.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,l.left="4px",l.children[0].name=e,this.groupPanel.addControl(l),this.selectors.push(l),this.groupPanel.parent&&this.groupPanel.parent.parent&&(a.color=this.groupPanel.parent.parent.buttonColor,a.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[0].name=t,this.selectors[e].children[0].text=t+": "+this.selectors[e].children[1].value+" "+this.selectors[e].children[1].name}_setSelectorLabelColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[1].background=t}}class FB extends cB{constructor(e,t=[]){if(super(e),this.name=e,this.groups=t,this._buttonColor="#364249",this._buttonBackground="#CCCCCC",this._headerColor="black",this._barColor="white",this._barHeight="2px",this._spacerHeight="20px",this._bars=new Array,this._groups=t,this.thickness=2,this._panel=new _B,this._panel.verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP,this._panel.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,this._panel.top=5,this._panel.left=5,this._panel.width=.95,t.length>0){for(let e=0;e0&&this._addSpacer(),this._panel.addControl(e.groupPanel),this._groups.push(e),e.groupPanel.children[0].color=this._headerColor;for(let t=0;t=this._groups.length)return;const t=this._groups[e];this._panel.removeControl(t.groupPanel),this._groups.splice(e,1),e=this._groups.length||(this._groups[t].groupPanel.children[0].text=e)}relabel(e,t,i){if(t<0||t>=this._groups.length)return;const r=this._groups[t];i<0||i>=r.selectors.length||r._setSelectorLabel(i,e)}removeFromGroupSelector(e,t){if(e<0||e>=this._groups.length)return;const i=this._groups[e];t<0||t>=i.selectors.length||i.removeSelector(t)}addToGroupCheckbox(e,t,i=(()=>{}),r=!1){e<0||e>=this._groups.length||this._groups[e].addCheckbox(t,i,r)}addToGroupRadio(e,t,i=(()=>{}),r=!1){e<0||e>=this._groups.length||this._groups[e].addRadio(t,i,r)}addToGroupSlider(e,t,i=(()=>{}),r="Units",s=0,n=0,o=0,a=(e=>0|e)){e<0||e>=this._groups.length||this._groups[e].addSlider(t,i,r,s,n,o,a)}}class LB extends hB{get freezeControls(){return this._freezeControls}set freezeControls(e){if(this._freezeControls===e)return;e||this._restoreMeasures(),this._freezeControls=!1;const t=this.host.getSize(),i=t.width,r=t.height,s=this.host.getContext(),n=new sB(0,0,i,r);this.host._numLayoutCalls=0,this.host._rootContainer._layout(n,s),e&&(this._updateMeasures(),this._useBuckets()&&this._makeBuckets()),this._freezeControls=e,this.host.markAsDirty()}get bucketWidth(){return this._bucketWidth}get bucketHeight(){return this._bucketHeight}setBucketSizes(e,t){this._bucketWidth=e,this._bucketHeight=t,this._useBuckets()?this._freezeControls&&this._makeBuckets():this._buckets={}}_useBuckets(){return this._bucketWidth>0&&this._bucketHeight>0}_makeBuckets(){this._buckets={},this._bucketLen=Math.ceil(this.widthInPixels/this._bucketWidth),this._dispatchInBuckets(this._children),this._oldLeft=null,this._oldTop=null}_dispatchInBuckets(e){for(let t=0;t0&&this._dispatchInBuckets(i._children)}}_updateMeasures(){const e=0|this.leftInPixels,t=0|this.topInPixels;this._measureForChildren.left-=e,this._measureForChildren.top-=t,this._currentMeasure.left-=e,this._currentMeasure.top-=t,this._customData.origLeftForChildren=this._measureForChildren.left,this._customData.origTopForChildren=this._measureForChildren.top,this._customData.origLeft=this._currentMeasure.left,this._customData.origTop=this._currentMeasure.top,this._updateChildrenMeasures(this._children,e,t)}_updateChildrenMeasures(e,t,i){for(let r=0;r0&&this._updateChildrenMeasures(s._children,t,i)}}_restoreMeasures(){const e=0|this.leftInPixels,t=0|this.topInPixels;this._measureForChildren.left=this._customData.origLeftForChildren+e,this._measureForChildren.top=this._customData.origTopForChildren+t,this._currentMeasure.left=this._customData.origLeft+e,this._currentMeasure.top=this._customData.origTop+t}constructor(e){super(e),this._freezeControls=!1,this._bucketWidth=0,this._bucketHeight=0,this._buckets={}}_getTypeName(){return"ScrollViewerWindow"}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._parentMeasure=e,this._measureForChildren.left=this._currentMeasure.left,this._measureForChildren.top=this._currentMeasure.top,this._measureForChildren.width=e.width,this._measureForChildren.height=e.height}_layout(e,t){return this._freezeControls?(this.invalidateRect(),!1):super._layout(e,t)}_scrollChildren(e,t,i){for(let r=0;r0&&this._scrollChildren(s._children,t,i)}}_scrollChildrenWithBuckets(e,t,i,r){const s=Math.max(0,Math.floor(-e/this._bucketWidth)),n=Math.floor((-e+this._parentMeasure.width-1)/this._bucketWidth),o=Math.floor((-t+this._parentMeasure.height-1)/this._bucketHeight);let a=Math.max(0,Math.floor(-t/this._bucketHeight));for(;a<=o;){for(let e=s;e<=n;++e){const t=a*this._bucketLen+e,s=this._buckets[t];if(s)for(let e=0;ethis._tempMeasure.left+this._tempMeasure.width||tthis._tempMeasure.top+this._tempMeasure.height)&&(this.isVertical?this.value=this.minimum+(1-(t-this._currentMeasure.top)/this._currentMeasure.height)*(this.maximum-this.minimum):this.value=this.minimum+(e-this._currentMeasure.left)/this._currentMeasure.width*(this.maximum-this.minimum)));let r=0;r=this.isVertical?-(t-this._originY)/(this._currentMeasure.height-this._effectiveThumbThickness):(e-this._originX)/(this._currentMeasure.width-this._effectiveThumbThickness),this.value+=i*r*(this.maximum-this.minimum),this._originX=e,this._originY=t}_onPointerDown(e,t,i,r,s){return this._first=!0,super._onPointerDown(e,t,i,r,s)}serialize(e){super.serialize(e),this.backgroundGradient&&(e.backgroundGradient={},this.backgroundGradient.serialize(e.backgroundGradient))}_parseFromContent(e,t){if(super._parseFromContent(e,t),e.backgroundGradient){const t=Ue.S0.Instantiate("BABYLON.GUI."+e.backgroundGradient.className);this.backgroundGradient=new t,this.backgroundGradient.parse(e.backgroundGradient)}}}(0,je.Cg)([(0,$e.lK)()],BB.prototype,"borderColor",null),(0,je.Cg)([(0,$e.lK)()],BB.prototype,"background",null),(0,je.Cg)([(0,$e.lK)()],BB.prototype,"invertScrollDirection",null),(0,X.Y5)("BABYLON.GUI.Scrollbar",BB);class VB extends IB{get invertScrollDirection(){return this._invertScrollDirection}set invertScrollDirection(e){this._invertScrollDirection=e}get backgroundImage(){return this._backgroundBaseImage}set backgroundImage(e){this._backgroundBaseImage!==e&&(this._backgroundBaseImage=e,this.isVertical&&0!==this.num90RotationInVerticalMode?e.isLoaded?(this._backgroundImage=e._rotate90(this.num90RotationInVerticalMode,!0),this._markAsDirty()):e.onImageLoadedObservable.addOnce((()=>{const t=e._rotate90(this.num90RotationInVerticalMode,!0);this._backgroundImage=t,t.isLoaded||t.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()})):(this._backgroundImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()))}get thumbImage(){return this._thumbBaseImage}set thumbImage(e){this._thumbBaseImage!==e&&(this._thumbBaseImage=e,this.isVertical&&0!==this.num90RotationInVerticalMode?e.isLoaded?(this._thumbImage=e._rotate90(-this.num90RotationInVerticalMode,!0),this._markAsDirty()):e.onImageLoadedObservable.addOnce((()=>{const t=e._rotate90(-this.num90RotationInVerticalMode,!0);this._thumbImage=t,t.isLoaded||t.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()})):(this._thumbImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()))}get thumbLength(){return this._thumbLength}set thumbLength(e){this._thumbLength!==e&&(this._thumbLength=e,this._markAsDirty())}get thumbHeight(){return this._thumbHeight}set thumbHeight(e){this._thumbLength!==e&&(this._thumbHeight=e,this._markAsDirty())}get barImageHeight(){return this._barImageHeight}set barImageHeight(e){this._barImageHeight!==e&&(this._barImageHeight=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thumbLength=.5,this._thumbHeight=1,this._barImageHeight=1,this._tempMeasure=new sB(0,0,0,0),this._invertScrollDirection=!1,this.num90RotationInVerticalMode=1}_getTypeName(){return"ImageScrollBar"}_getThumbThickness(){let e=0;return e=this._thumbWidth.isPixel?this._thumbWidth.getValue(this._host):this._backgroundBoxThickness*this._thumbWidth.getValue(this._host),e}_draw(e){e.save(),this._applyStates(e),this._prepareRenderingData("rectangle");const t=this._getThumbPosition(),i=this._renderLeft,r=this._renderTop,s=this._renderWidth,n=this._renderHeight;this._backgroundImage&&(this._tempMeasure.copyFromFloats(i,r,s,n),this.isVertical?(this._tempMeasure.copyFromFloats(i+s*(1-this._barImageHeight)*.5,this._currentMeasure.top,s*this._barImageHeight,n),this._tempMeasure.height+=this._effectiveThumbThickness,this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure)):(this._tempMeasure.copyFromFloats(this._currentMeasure.left,r+n*(1-this._barImageHeight)*.5,s,n*this._barImageHeight),this._tempMeasure.width+=this._effectiveThumbThickness,this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure)),this._backgroundImage._draw(e)),this.isVertical?this._tempMeasure.copyFromFloats(i-this._effectiveBarOffset+this._currentMeasure.width*(1-this._thumbHeight)*.5,this._currentMeasure.top+t,this._currentMeasure.width*this._thumbHeight,this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(this._currentMeasure.left+t,this._currentMeasure.top+this._currentMeasure.height*(1-this._thumbHeight)*.5,this._effectiveThumbThickness,this._currentMeasure.height*this._thumbHeight),this._thumbImage&&(this._thumbImage._currentMeasure.copyFrom(this._tempMeasure),this._thumbImage._draw(e)),e.restore()}_updateValueFromPointer(e,t){0!=this.rotation&&(this._invertTransformMatrix.transformCoordinates(e,t,this._transformedPosition),e=this._transformedPosition.x,t=this._transformedPosition.y);const i=this._invertScrollDirection?-1:1;this._first&&(this._first=!1,this._originX=e,this._originY=t,(ethis._tempMeasure.left+this._tempMeasure.width||tthis._tempMeasure.top+this._tempMeasure.height)&&(this.isVertical?this.value=this.minimum+(1-(t-this._currentMeasure.top)/this._currentMeasure.height)*(this.maximum-this.minimum):this.value=this.minimum+(e-this._currentMeasure.left)/this._currentMeasure.width*(this.maximum-this.minimum)));let r=0;r=this.isVertical?-(t-this._originY)/(this._currentMeasure.height-this._effectiveThumbThickness):(e-this._originX)/(this._currentMeasure.width-this._effectiveThumbThickness),this.value+=i*r*(this.maximum-this.minimum),this._originX=e,this._originY=t}_onPointerDown(e,t,i,r,s){return this._first=!0,super._onPointerDown(e,t,i,r,s)}}(0,je.Cg)([(0,$e.lK)()],VB.prototype,"num90RotationInVerticalMode",void 0),(0,je.Cg)([(0,$e.lK)()],VB.prototype,"invertScrollDirection",null);class kB extends cB{get horizontalBar(){return this._horizontalBar}get verticalBar(){return this._verticalBar}addControl(e){return e?(this._window.addControl(e),this):this}removeControl(e){return this._window.removeControl(e),this}get children(){return this._window.children}_flagDescendantsAsMatrixDirty(){for(const e of this._children)e._markMatrixAsDirty()}get freezeControls(){return this._window.freezeControls}set freezeControls(e){this._window.freezeControls=e}get bucketWidth(){return this._window.bucketWidth}get bucketHeight(){return this._window.bucketHeight}setBucketSizes(e,t){this._window.setBucketSizes(e,t)}get forceHorizontalBar(){return this._forceHorizontalBar}set forceHorizontalBar(e){this._grid.setRowDefinition(1,e?this._barSize:0,!0),this._horizontalBar.isVisible=e,this._forceHorizontalBar=e}get forceVerticalBar(){return this._forceVerticalBar}set forceVerticalBar(e){this._grid.setColumnDefinition(1,e?this._barSize:0,!0),this._verticalBar.isVisible=e,this._forceVerticalBar=e}constructor(e,t){super(e),this._barSize=20,this._pointerIsOver=!1,this._wheelPrecision=.05,this._thumbLength=.5,this._thumbHeight=1,this._barImageHeight=1,this._horizontalBarImageHeight=1,this._verticalBarImageHeight=1,this._oldWindowContentsWidth=0,this._oldWindowContentsHeight=0,this._forceHorizontalBar=!1,this._forceVerticalBar=!1,this._useImageBar=t||!1,this.onDirtyObservable.add((()=>{this._horizontalBarSpace.color=this.color,this._verticalBarSpace.color=this.color,this._dragSpace.color=this.color})),this.onPointerEnterObservable.add((()=>{this._pointerIsOver=!0})),this.onPointerOutObservable.add((()=>{this._pointerIsOver=!1})),this._grid=new xB,this._useImageBar?(this._horizontalBar=new VB,this._verticalBar=new VB):(this._horizontalBar=new BB,this._verticalBar=new BB),this._window=new LB("scrollViewer_window"),this._window.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,this._window.verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP,this._grid.addColumnDefinition(1),this._grid.addColumnDefinition(0,!0),this._grid.addRowDefinition(1),this._grid.addRowDefinition(0,!0),super.addControl(this._grid),this._grid.addControl(this._window,0,0),this._verticalBarSpace=new cB,this._verticalBarSpace.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,this._verticalBarSpace.verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP,this._verticalBarSpace.thickness=1,this._grid.addControl(this._verticalBarSpace,0,1),this._addBar(this._verticalBar,this._verticalBarSpace,!0,Math.PI),this._horizontalBarSpace=new cB,this._horizontalBarSpace.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,this._horizontalBarSpace.verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP,this._horizontalBarSpace.thickness=1,this._grid.addControl(this._horizontalBarSpace,1,0),this._addBar(this._horizontalBar,this._horizontalBarSpace,!1,0),this._dragSpace=new cB,this._dragSpace.thickness=1,this._grid.addControl(this._dragSpace,1,1),this._grid.clipChildren=!1,this._useImageBar||(this.barColor="grey",this.barBackground="transparent")}resetWindow(){this._window.width="100%",this._window.height="100%"}_getTypeName(){return"ScrollViewer"}_buildClientSizes(){const e=this.host.idealRatio;this._window.parentClientWidth=this._currentMeasure.width-(this._verticalBar.isVisible||this.forceVerticalBar?this._barSize*e:0)-2*this.thickness,this._window.parentClientHeight=this._currentMeasure.height-(this._horizontalBar.isVisible||this.forceHorizontalBar?this._barSize*e:0)-2*this.thickness,this._clientWidth=this._window.parentClientWidth,this._clientHeight=this._window.parentClientHeight}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._buildClientSizes()}_postMeasure(){super._postMeasure(),this._updateScroller(),this._setWindowPosition(!1)}get wheelPrecision(){return this._wheelPrecision}set wheelPrecision(e){this._wheelPrecision!==e&&(e<0&&(e=0),e>1&&(e=1),this._wheelPrecision=e)}get scrollBackground(){return this._horizontalBarSpace.background}set scrollBackground(e){this._horizontalBarSpace.background!==e&&(this._horizontalBarSpace.background=e,this._verticalBarSpace.background=e)}get barColor(){return this._barColor}set barColor(e){this._barColor!==e&&(this._barColor=e,this._horizontalBar.color=e,this._verticalBar.color=e)}get thumbImage(){return this._barImage}set thumbImage(e){if(this._barImage===e)return;this._barImage=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbImage=e,i.thumbImage=e}get horizontalThumbImage(){return this._horizontalBarImage}set horizontalThumbImage(e){this._horizontalBarImage!==e&&(this._horizontalBarImage=e,this._horizontalBar.thumbImage=e)}get verticalThumbImage(){return this._verticalBarImage}set verticalThumbImage(e){this._verticalBarImage!==e&&(this._verticalBarImage=e,this._verticalBar.thumbImage=e)}get barSize(){return this._barSize}set barSize(e){this._barSize!==e&&(this._barSize=e,this._markAsDirty(),this._horizontalBar.isVisible&&this._grid.setRowDefinition(1,this._barSize,!0),this._verticalBar.isVisible&&this._grid.setColumnDefinition(1,this._barSize,!0))}get thumbLength(){return this._thumbLength}set thumbLength(e){if(this._thumbLength===e)return;e<=0&&(e=.1),e>1&&(e=1),this._thumbLength=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbLength=e,i.thumbLength=e,this._markAsDirty()}get thumbHeight(){return this._thumbHeight}set thumbHeight(e){if(this._thumbHeight===e)return;e<=0&&(e=.1),e>1&&(e=1),this._thumbHeight=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbHeight=e,i.thumbHeight=e,this._markAsDirty()}get barImageHeight(){return this._barImageHeight}set barImageHeight(e){if(this._barImageHeight===e)return;e<=0&&(e=.1),e>1&&(e=1),this._barImageHeight=e;const t=this._horizontalBar,i=this._verticalBar;t.barImageHeight=e,i.barImageHeight=e,this._markAsDirty()}get horizontalBarImageHeight(){return this._horizontalBarImageHeight}set horizontalBarImageHeight(e){this._horizontalBarImageHeight!==e&&(e<=0&&(e=.1),e>1&&(e=1),this._horizontalBarImageHeight=e,this._horizontalBar.barImageHeight=e,this._markAsDirty())}get verticalBarImageHeight(){return this._verticalBarImageHeight}set verticalBarImageHeight(e){this._verticalBarImageHeight!==e&&(e<=0&&(e=.1),e>1&&(e=1),this._verticalBarImageHeight=e,this._verticalBar.barImageHeight=e,this._markAsDirty())}get barBackground(){return this._barBackground}set barBackground(e){if(this._barBackground===e)return;this._barBackground=e;const t=this._horizontalBar,i=this._verticalBar;t.background=e,i.background=e,this._dragSpace.background=e}get barImage(){return this._barBackgroundImage}set barImage(e){this._barBackgroundImage=e;const t=this._horizontalBar,i=this._verticalBar;t.backgroundImage=e,i.backgroundImage=e}get horizontalBarImage(){return this._horizontalBarBackgroundImage}set horizontalBarImage(e){this._horizontalBarBackgroundImage=e,this._horizontalBar.backgroundImage=e}get verticalBarImage(){return this._verticalBarBackgroundImage}set verticalBarImage(e){this._verticalBarBackgroundImage=e,this._verticalBar.backgroundImage=e}_setWindowPosition(e=!0){const t=this.host.idealRatio,i=this._window._currentMeasure.width,r=this._window._currentMeasure.height;if(!e&&this._oldWindowContentsWidth===i&&this._oldWindowContentsHeight===r)return;this._oldWindowContentsWidth=i,this._oldWindowContentsHeight=r;const s=this._clientWidth-i,n=this._clientHeight-r,o=this._horizontalBar.value/t*s+"px",a=this._verticalBar.value/t*n+"px";o!==this._window.left&&(this._window.left=o,this.freezeControls||(this._rebuildLayout=!0)),a!==this._window.top&&(this._window.top=a,this.freezeControls||(this._rebuildLayout=!0))}_updateScroller(){const e=this._window._currentMeasure.width,t=this._window._currentMeasure.height;this._horizontalBar.isVisible&&e<=this._clientWidth&&!this.forceHorizontalBar?(this._grid.setRowDefinition(1,0,!0),this._horizontalBar.isVisible=!1,this._horizontalBar.value=0,this._rebuildLayout=!0):!this._horizontalBar.isVisible&&(e>this._clientWidth||this.forceHorizontalBar)&&(this._grid.setRowDefinition(1,this._barSize,!0),this._horizontalBar.isVisible=!0,this._rebuildLayout=!0),this._verticalBar.isVisible&&t<=this._clientHeight&&!this.forceVerticalBar?(this._grid.setColumnDefinition(1,0,!0),this._verticalBar.isVisible=!1,this._verticalBar.value=0,this._rebuildLayout=!0):!this._verticalBar.isVisible&&(t>this._clientHeight||this.forceVerticalBar)&&(this._grid.setColumnDefinition(1,this._barSize,!0),this._verticalBar.isVisible=!0,this._rebuildLayout=!0),this._buildClientSizes();const i=this.host.idealRatio;this._horizontalBar.thumbWidth=.9*this._thumbLength*(this._clientWidth/i)+"px",this._verticalBar.thumbWidth=.9*this._thumbLength*(this._clientHeight/i)+"px"}_link(e){super._link(e),this._attachWheel()}_addBar(e,t,i,r){e.paddingLeft=0,e.width="100%",e.height="100%",e.barOffset=0,e.value=0,e.maximum=1,e.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_CENTER,e.verticalAlignment=lB.VERTICAL_ALIGNMENT_CENTER,e.isVertical=i,e.rotation=r,e.isVisible=!1,t.addControl(e),e.onValueChangedObservable.add((()=>{this._setWindowPosition()}))}_attachWheel(){this._host&&!this._onWheelObserver&&(this._onWheelObserver=this.onWheelObservable.add((e=>{this._pointerIsOver&&!this.isReadOnly&&(1==this._verticalBar.isVisible&&(e.y<0&&this._verticalBar.value>0?this._verticalBar.value-=this._wheelPrecision:e.y>0&&this._verticalBar.value0&&this._horizontalBar.value>0&&(this._horizontalBar.value-=this._wheelPrecision)))})))}_renderHighlightSpecific(e){this.isHighlighted&&(super._renderHighlightSpecific(e),this._grid._renderHighlightSpecific(e),e.restore())}dispose(){this.onWheelObservable.remove(this._onWheelObserver),this._onWheelObserver=null,super.dispose()}}(0,je.Cg)([(0,$e.lK)()],kB.prototype,"wheelPrecision",null),(0,je.Cg)([(0,$e.lK)()],kB.prototype,"scrollBackground",null),(0,je.Cg)([(0,$e.lK)()],kB.prototype,"barColor",null),(0,je.Cg)([(0,$e.lK)()],kB.prototype,"barSize",null),(0,je.Cg)([(0,$e.lK)()],kB.prototype,"barBackground",null),(0,X.Y5)("BABYLON.GUI.ScrollViewer",kB);class UB extends cB{get group(){return this._group}set group(e){this._group!==e&&(this._group=e)}get isActive(){return this._isActive}set isActive(e){this._isActive!==e&&(this._isActive=e,this._isActive?this.toActiveAnimation?.():this.toInactiveAnimation?.(),this._markAsDirty(),this.onIsActiveChangedObservable.notifyObservers(e),this._isActive&&this._host&&this._group&&this._host.executeOnAllControls((e=>{if("ToggleButton"===e.typeName){if(e===this)return;const t=e;t.group===this.group&&(t.isActive=!1)}})))}constructor(e,t){super(e),this.name=e,this.onIsActiveChangedObservable=new z.cP,this.delegatePickingToChildren=!1,this._isActive=!1,this.group=t??"",this.thickness=0,this.isPointerBlocker=!0;let i=null;this.toActiveAnimation=()=>{this.thickness=1},this.toInactiveAnimation=()=>{this.thickness=0},this.pointerEnterActiveAnimation=()=>{i=this.alpha,this.alpha-=.1},this.pointerOutActiveAnimation=()=>{null!==i&&(this.alpha=i)},this.pointerDownActiveAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpActiveAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05},this.pointerEnterInactiveAnimation=()=>{i=this.alpha,this.alpha-=.1},this.pointerOutInactiveAnimation=()=>{null!==i&&(this.alpha=i)},this.pointerDownInactiveAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpInactiveAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05}}_getTypeName(){return"ToggleButton"}_processPicking(e,t,i,r,s,n,o,a){if(!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this.notRenderable)return!1;if(!super.contains(e,t))return!1;if(this.delegatePickingToChildren){let i=!1;for(let r=this._children.length-1;r>=0;r--){const s=this._children[r];if(s.isEnabled&&s.isHitTestVisible&&s.isVisible&&!s.notRenderable&&s.contains(e,t)){i=!0;break}}if(!i)return!1}return this._processObservables(r,e,t,i,s,n,o,a),!0}_onPointerEnter(e,t){return!!super._onPointerEnter(e,t)&&(this.isReadOnly||(this._isActive?this.pointerEnterActiveAnimation&&this.pointerEnterActiveAnimation():this.pointerEnterInactiveAnimation&&this.pointerEnterInactiveAnimation()),!0)}_onPointerOut(e,t,i=!1){this.isReadOnly||(this._isActive?this.pointerOutActiveAnimation&&this.pointerOutActiveAnimation():this.pointerOutInactiveAnimation&&this.pointerOutInactiveAnimation()),super._onPointerOut(e,t,i)}_onPointerDown(e,t,i,r,s){return!!super._onPointerDown(e,t,i,r,s)&&(this.isReadOnly||(this._isActive?this.pointerDownActiveAnimation&&this.pointerDownActiveAnimation():this.pointerDownInactiveAnimation&&this.pointerDownInactiveAnimation()),!0)}_onPointerUp(e,t,i,r,s,n){this.isReadOnly||(this._isActive?this.pointerUpActiveAnimation&&this.pointerUpActiveAnimation():this.pointerUpInactiveAnimation&&this.pointerUpInactiveAnimation()),super._onPointerUp(e,t,i,r,s,n)}}(0,X.Y5)("BABYLON.GUI.ToggleButton",UB);class GB{}class zB extends _B{constructor(){super(...arguments),this.onKeyPressObservable=new z.cP,this.defaultButtonWidth="40px",this.defaultButtonHeight="40px",this.defaultButtonPaddingLeft="2px",this.defaultButtonPaddingRight="2px",this.defaultButtonPaddingTop="2px",this.defaultButtonPaddingBottom="2px",this.defaultButtonColor="#DDD",this.defaultButtonBackground="#070707",this.shiftButtonColor="#7799FF",this.selectedShiftThickness=1,this.shiftState=0,this._currentlyConnectedInputText=null,this._connectedInputTexts=[],this._onKeyPressObserver=null}_getTypeName(){return"VirtualKeyboard"}_createKey(e,t){const i=pB.CreateSimpleButton(e,e);return i.width=t&&t.width?t.width:this.defaultButtonWidth,i.height=t&&t.height?t.height:this.defaultButtonHeight,i.color=t&&t.color?t.color:this.defaultButtonColor,i.background=t&&t.background?t.background:this.defaultButtonBackground,i.paddingLeft=t&&t.paddingLeft?t.paddingLeft:this.defaultButtonPaddingLeft,i.paddingRight=t&&t.paddingRight?t.paddingRight:this.defaultButtonPaddingRight,i.paddingTop=t&&t.paddingTop?t.paddingTop:this.defaultButtonPaddingTop,i.paddingBottom=t&&t.paddingBottom?t.paddingBottom:this.defaultButtonPaddingBottom,i.thickness=0,i.isFocusInvisible=!0,i.shadowColor=this.shadowColor,i.shadowBlur=this.shadowBlur,i.shadowOffsetX=this.shadowOffsetX,i.shadowOffsetY=this.shadowOffsetY,i.onPointerUpObservable.add((()=>{this.onKeyPressObservable.notifyObservers(e)})),i}addKeysRow(e,t){const i=new _B;i.isVertical=!1,i.isFocusInvisible=!0;let r=null;for(let s=0;sr.heightInPixels)&&(r=o),i.addControl(o)}i.height=r?r.height:this.defaultButtonHeight,this.addControl(i)}applyShiftState(e){if(this.children)for(let t=0;t1?this.selectedShiftThickness:0),s.text=e>0?s.text.toUpperCase():s.text.toLowerCase()}}}get connectedInputText(){return this._currentlyConnectedInputText}connect(e){if(this._connectedInputTexts.some((t=>t.input===e)))return;null===this._onKeyPressObserver&&(this._onKeyPressObserver=this.onKeyPressObservable.add((e=>{if(this._currentlyConnectedInputText){switch(this._currentlyConnectedInputText._host.focusedControl=this._currentlyConnectedInputText,e){case"⇧":return this.shiftState++,this.shiftState>2&&(this.shiftState=0),void this.applyShiftState(this.shiftState);case"←":return void(this._currentlyConnectedInputText instanceof CB?this._currentlyConnectedInputText.alternativeProcessKey("Backspace"):this._currentlyConnectedInputText.processKey(8));case"↵":return void(this._currentlyConnectedInputText instanceof CB?this._currentlyConnectedInputText.alternativeProcessKey("Enter"):this._currentlyConnectedInputText.processKey(13))}this._currentlyConnectedInputText instanceof CB?this._currentlyConnectedInputText.alternativeProcessKey("",this.shiftState?e.toUpperCase():e):this._currentlyConnectedInputText.processKey(-1,this.shiftState?e.toUpperCase():e),1===this.shiftState&&(this.shiftState=0,this.applyShiftState(this.shiftState))}}))),this.isVisible=!1,this._currentlyConnectedInputText=e,e._connectedVirtualKeyboard=this;const t=e.onFocusObservable.add((()=>{this._currentlyConnectedInputText=e,e._connectedVirtualKeyboard=this,this.isVisible=!0})),i=e.onBlurObservable.add((()=>{e._connectedVirtualKeyboard=null,this._currentlyConnectedInputText=null,this.isVisible=!1}));this._connectedInputTexts.push({input:e,onBlurObserver:i,onFocusObserver:t})}disconnect(e){if(e){const t=this._connectedInputTexts.filter((t=>t.input===e));1===t.length&&(this._removeConnectedInputObservables(t[0]),this._connectedInputTexts=this._connectedInputTexts.filter((t=>t.input!==e)),this._currentlyConnectedInputText===e&&(this._currentlyConnectedInputText=null))}else this._connectedInputTexts.forEach((e=>{this._removeConnectedInputObservables(e)})),this._connectedInputTexts.length=0;0===this._connectedInputTexts.length&&(this._currentlyConnectedInputText=null,this.onKeyPressObservable.remove(this._onKeyPressObserver),this._onKeyPressObserver=null)}_removeConnectedInputObservables(e){e.input._connectedVirtualKeyboard=null,e.input.onFocusObservable.remove(e.onFocusObserver),e.input.onBlurObservable.remove(e.onBlurObserver)}dispose(){super.dispose(),this.disconnect()}static CreateDefaultLayout(e){const t=new zB(e);return t.addKeysRow(["1","2","3","4","5","6","7","8","9","0","←"]),t.addKeysRow(["q","w","e","r","t","y","u","i","o","p"]),t.addKeysRow(["a","s","d","f","g","h","j","k","l",";","'","↵"]),t.addKeysRow(["⇧","z","x","c","v","b","n","m",",",".","/"]),t.addKeysRow([" "],[{width:"200px"}]),t}_parseFromContent(e,t){super._parseFromContent(e,t);for(const e of this.children)if("StackPanel"===e.getClassName()){const t=e;for(const e of t.children)"Button"===e.getClassName()&&e.name&&e.onPointerUpObservable.add((()=>{this.onKeyPressObservable.notifyObservers(e.name)}))}}}(0,X.Y5)("BABYLON.GUI.VirtualKeyboard",zB);class WB extends lB{get displayMinorLines(){return this._displayMinorLines}set displayMinorLines(e){this._displayMinorLines!==e&&(this._displayMinorLines=e,this._markAsDirty())}get displayMajorLines(){return this._displayMajorLines}set displayMajorLines(e){this._displayMajorLines!==e&&(this._displayMajorLines=e,this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get cellWidth(){return this._cellWidth}set cellWidth(e){this._cellWidth=e,this._markAsDirty()}get cellHeight(){return this._cellHeight}set cellHeight(e){this._cellHeight=e,this._markAsDirty()}get minorLineTickness(){return this._minorLineTickness}set minorLineTickness(e){this._minorLineTickness=e,this._markAsDirty()}get minorLineColor(){return this._minorLineColor}set minorLineColor(e){this._minorLineColor=e,this._markAsDirty()}get majorLineTickness(){return this._majorLineTickness}set majorLineTickness(e){this._majorLineTickness=e,this._markAsDirty()}get majorLineColor(){return this._majorLineColor}set majorLineColor(e){this._majorLineColor=e,this._markAsDirty()}get majorLineFrequency(){return this._majorLineFrequency}set majorLineFrequency(e){this._majorLineFrequency=e,this._markAsDirty()}constructor(e){super(e),this.name=e,this._cellWidth=20,this._cellHeight=20,this._minorLineTickness=1,this._minorLineColor="DarkGray",this._majorLineTickness=2,this._majorLineColor="White",this._majorLineFrequency=5,this._background="Black",this._displayMajorLines=!0,this._displayMinorLines=!0}_draw(e){if(e.save(),this._applyStates(e),this._isEnabled){this._background&&(e.fillStyle=this._background,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height));const t=this._currentMeasure.width/this._cellWidth,i=this._currentMeasure.height/this._cellHeight,r=this._currentMeasure.left+this._currentMeasure.width/2,s=this._currentMeasure.top+this._currentMeasure.height/2;if(this._displayMinorLines){e.strokeStyle=this._minorLineColor,e.lineWidth=this._minorLineTickness;for(let i=-t/2+1;ithis._markAsDirty())),this._markAsDirty())}get valueBarImage(){return this._valueBarImage}set valueBarImage(e){this._valueBarImage!==e&&(this._valueBarImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>this._markAsDirty())),this._markAsDirty())}get thumbImage(){return this._thumbImage}set thumbImage(e){this._thumbImage!==e&&(this._thumbImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>this._markAsDirty())),this._markAsDirty())}constructor(e){super(e),this.name=e,this._tempMeasure=new sB(0,0,0,0)}_getTypeName(){return"ImageBasedSlider"}_draw(e){e.save(),this._applyStates(e),this._prepareRenderingData("rectangle");const t=this._getThumbPosition(),i=this._renderLeft,r=this._renderTop,s=this._renderWidth,n=this._renderHeight;this._backgroundImage&&(this._tempMeasure.copyFromFloats(i,r,s,n),this.isThumbClamped&&this.displayThumb&&(this.isVertical?this._tempMeasure.height+=this._effectiveThumbThickness:this._tempMeasure.width+=this._effectiveThumbThickness),this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure),this._backgroundImage._draw(e)),this._valueBarImage&&(this.isVertical?this.isThumbClamped&&this.displayThumb?this._tempMeasure.copyFromFloats(i,r+t,s,n-t+this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(i,r+t,s,n-t):this.isThumbClamped&&this.displayThumb?this._tempMeasure.copyFromFloats(i,r,t+this._effectiveThumbThickness/2,n):this._tempMeasure.copyFromFloats(i,r,t,n),this._valueBarImage._currentMeasure.copyFrom(this._tempMeasure),this._valueBarImage._draw(e)),this.displayThumb&&(this.isVertical?this._tempMeasure.copyFromFloats(i-this._effectiveBarOffset,this._currentMeasure.top+t,this._currentMeasure.width,this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(this._currentMeasure.left+t,this._currentMeasure.top,this._effectiveThumbThickness,this._currentMeasure.height),this._thumbImage._currentMeasure.copyFrom(this._tempMeasure),this._thumbImage._draw(e)),e.restore()}serialize(e){super.serialize(e);const t={},i={},r={};this.backgroundImage.serialize(t),this.thumbImage.serialize(i),this.valueBarImage.serialize(r),e.backgroundImage=t,e.thumbImage=i,e.valueBarImage=r}_parseFromContent(e,t){super._parseFromContent(e,t),this.backgroundImage=fB.Parse(e.backgroundImage,t),this.thumbImage=fB.Parse(e.thumbImage,t),this.valueBarImage=fB.Parse(e.valueBarImage,t)}}(0,je.Cg)([(0,$e.lK)()],HB.prototype,"displayThumb",null),(0,X.Y5)("BABYLON.GUI.ImageBasedSlider",HB);const XB="Statics";lB.AddHeader=function(e,t,i,r){const s=new _B("panel"),n=!r||r.isHorizontal,o=!r||r.controlFirst;s.isVertical=!n;const a=new dB("header");return a.text=t,a.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,n?a.width=i:a.height=i,o?(s.addControl(e),s.addControl(a),a.paddingLeft="5px"):(s.addControl(a),s.addControl(e),a.paddingRight="5px"),a.shadowBlur=e.shadowBlur,a.shadowColor=e.shadowColor,a.shadowOffsetX=e.shadowOffsetX,a.shadowOffsetY=e.shadowOffsetY,s};class qB{constructor(){this._colorStops=[],this._gradientDirty=!0}_addColorStopsToCanvasGradient(){for(const e of this._colorStops)this._canvasGradient.addColorStop(e.offset,e.color)}getCanvasGradient(e){return(this._gradientDirty||this._context!==e)&&(this._context=e,this._canvasGradient=this._createCanvasGradient(e),this._addColorStopsToCanvasGradient(),this._gradientDirty=!1),this._canvasGradient}addColorStop(e,t){this._colorStops.push({offset:e,color:t}),this._gradientDirty=!0}removeColorStop(e){this._colorStops=this._colorStops.filter((t=>t.offset!==e)),this._gradientDirty=!0}clearColorStops(){this._colorStops=[],this._gradientDirty=!0}get colorStops(){return this._colorStops}getClassName(){return"BaseGradient"}serialize(e){e.colorStops=this._colorStops,e.className=this.getClassName()}parse(e){this._colorStops=e.colorStops}}class YB extends qB{constructor(e,t,i,r){super(),this._x0=e??0,this._y0=t??0,this._x1=i??0,this._y1=r??0}_createCanvasGradient(e){return e.createLinearGradient(this._x0,this._y0,this._x1,this._y1)}get x0(){return this._x0}get x1(){return this._x1}get y0(){return this._y0}get y1(){return this._y1}getClassName(){return"LinearGradient"}serialize(e){super.serialize(e),e.x0=this._x0,e.y0=this._y0,e.x1=this._x1,e.y1=this._y1}parse(e){super.parse(e),this._x0=e.x0,this._y0=e.y0,this._x1=e.x1,this._y1=e.y1}}(0,X.Y5)("BABYLON.GUI.LinearGradient",YB);class KB extends qB{constructor(e,t,i,r,s,n){super(),this._x0=e??0,this._y0=t??0,this._r0=i??0,this._x1=r??0,this._y1=s??0,this._r1=n??0}_createCanvasGradient(e){return e.createRadialGradient(this._x0,this._y0,this._r0,this._x1,this._y1,this._r1)}get x0(){return this._x0}get x1(){return this._x1}get y0(){return this._y0}get y1(){return this._y1}get r0(){return this._r0}get r1(){return this._r1}getClassName(){return"RadialGradient"}serialize(e){super.serialize(e),e.x0=this._x0,e.y0=this._y0,e.r0=this._r0,e.x1=this._x1,e.y1=this._y1,e.r1=this._r1}parse(e){super.parse(e),this._x0=e.x0,this._y0=e.y0,this._r0=e.r0,this._x1=e.x1,this._y1=e.y1,this._r1=e.r1}}(0,X.Y5)("BABYLON.GUI.RadialGradient",KB);class jB{constructor(e){this._fontFamily="Arial",this._fontStyle="",this._fontWeight="",this._fontSize=new JL(18,JL.UNITMODE_PIXEL,!1),this.onChangedObservable=new z.cP,this._host=e}get fontSize(){return this._fontSize.toString(this._host)}set fontSize(e){this._fontSize.toString(this._host)!==e&&this._fontSize.fromString(e)&&this.onChangedObservable.notifyObservers(this)}get fontFamily(){return this._fontFamily}set fontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.onChangedObservable.notifyObservers(this))}get fontStyle(){return this._fontStyle}set fontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.onChangedObservable.notifyObservers(this))}get fontWeight(){return this._fontWeight}set fontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.onChangedObservable.notifyObservers(this))}dispose(){this.onChangedObservable.clear()}}class $B extends Gn{get numLayoutCalls(){return this._numLayoutCalls}get numRenderCalls(){return this._numRenderCalls}get renderScale(){return this._renderScale}set renderScale(e){e!==this._renderScale&&(this._renderScale=e,this._onResize())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this.markAsDirty())}get idealWidth(){return this._idealWidth}set idealWidth(e){this._idealWidth!==e&&(this._idealWidth=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get idealHeight(){return this._idealHeight}set idealHeight(e){this._idealHeight!==e&&(this._idealHeight=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get useSmallestIdeal(){return this._useSmallestIdeal}set useSmallestIdeal(e){this._useSmallestIdeal!==e&&(this._useSmallestIdeal=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get renderAtIdealSize(){return this._renderAtIdealSize}set renderAtIdealSize(e){this._renderAtIdealSize!==e&&(this._renderAtIdealSize=e,this._onResize())}get idealRatio(){let e=0,t=0;return this._idealWidth&&(e=this.getSize().width/this._idealWidth),this._idealHeight&&(t=this.getSize().height/this._idealHeight),this._useSmallestIdeal&&this._idealWidth&&this._idealHeight?window.innerWidtht.typeName===e))}getControlByName(e){return this._getControlByKey("name",e)}_getControlByKey(e,t){return this._rootContainer.getDescendants().find((i=>i[e]===t))||null}get focusedControl(){return this._focusedControl}set focusedControl(e){this._focusedControl!=e&&(this._focusedControl&&this._focusedControl.onBlur(),e&&e.onFocus(),this._focusedControl=e)}get isForeground(){return!this.layer||!this.layer.isBackground}set isForeground(e){this.layer&&this.layer.isBackground!==!e&&(this.layer.isBackground=!e)}get clipboardData(){return this._clipboardData}set clipboardData(e){this._clipboardData=e}constructor(e,t,i=0,r,s=!1,n=vi.g.NEAREST_SAMPLINGMODE,o=!0){const a="object"==typeof(t=t??0)&&void 0!==t?t.width??0:t??0,l="object"==typeof t&&void 0!==t?t.height??0:i;if(super(e,{width:a,height:l},"object"==typeof t&&void 0!==t?t:r,s,n,Il.TEXTUREFORMAT_RGBA,o),this.useStandalone=!1,this.onGuiReadyObservable=new z.cP,this._isDirty=!1,this._rootContainer=new hB("root"),this._lastControlOver={},this._lastControlDown={},this._capturingControl={},this._linkedControls=new Array,this._isFullscreen=!1,this._fullscreenViewport=new et.L(0,0,1,1),this._idealWidth=0,this._idealHeight=0,this._useSmallestIdeal=!1,this._renderAtIdealSize=!1,this._blockNextFocusCheck=!1,this._renderScale=1,this._cursorChanged=!1,this._defaultMousePointerId=0,this._rootChildrenHaveChanged=!1,this._capturedPointerIds=new Set,this._numLayoutCalls=0,this._numRenderCalls=0,this._clipboardData="",this.onClipboardObservable=new z.cP,this.onControlPickedObservable=new z.cP,this.onBeginLayoutObservable=new z.cP,this.onEndLayoutObservable=new z.cP,this.onBeginRenderObservable=new z.cP,this.onEndRenderObservable=new z.cP,this.premulAlpha=!1,this.applyYInversionOnUpdate=!0,this.disableTabNavigation=!1,this.disablePicking=!1,this.usePointerTapForClickEvent=!1,this.skipBlockEvents=0,this.checkPointerEveryFrame=!1,this._useInvalidateRectOptimization=!0,this._invalidatedRectangle=null,this._clearMeasure=new sB(0,0,0,0),this._focusProperties={index:0,total:-1},this._onClipboardCopy=e=>{const t=e,i=new Eu(yu.COPY,t);this.onClipboardObservable.notifyObservers(i),t.preventDefault()},this._onClipboardCut=e=>{const t=e,i=new Eu(yu.CUT,t);this.onClipboardObservable.notifyObservers(i),t.preventDefault()},this._onClipboardPaste=e=>{const t=e,i=new Eu(yu.PASTE,t);this.onClipboardObservable.notifyObservers(i),t.preventDefault()},this.parseContent=this.parseSerializedObject,!(r=this.getScene())||!this._texture)return;this.applyYInversionOnUpdate=o,this._rootElement=r.getEngine().getInputElement();const h=t;this.useStandalone=!!h?.useStandalone,this.useStandalone||(this._renderObserver=r.onBeforeCameraRenderObservable.add((e=>this._checkUpdate(e)))),this._controlAddedObserver=this._rootContainer.onControlAddedObservable.add((e=>{e&&(this._rootChildrenHaveChanged=!0)})),this._controlRemovedObserver=this._rootContainer.onControlRemovedObservable.add((e=>{e&&(this._rootChildrenHaveChanged=!0)})),this._preKeyboardObserver=r.onPreKeyboardObservable.add((e=>{if(!this.disableTabNavigation&&e.type===Ar.TB.KEYDOWN&&"Tab"===e.event.code){const t=!e.event.shiftKey;return t&&this._focusProperties.index===this._focusProperties.total-1||!t&&0===this._focusProperties.index&&this._focusProperties.total>0?(this.focusedControl=null,this._focusProperties.index=0,void(this._focusProperties.total=-1)):(this._focusNextElement(t),void e.event.preventDefault())}this._focusedControl&&(e.type===Ar.TB.KEYDOWN&&this._focusedControl.processKeyboard(e.event),e.skipOnPointerObservable=!0)})),this._rootContainer._link(this),this.hasAlpha=!0,a&&l||(this._resizeObserver=r.getEngine().onResizeObservable.add((()=>this._onResize())),this._onResize()),this._texture.isReady=!0}getClassName(){return"AdvancedDynamicTexture"}executeOnAllControls(e,t){t||(t=this._rootContainer),e(t);for(const i of t.children)i.children?this.executeOnAllControls(e,i):e(i)}get useInvalidateRectOptimization(){return this._useInvalidateRectOptimization}set useInvalidateRectOptimization(e){this._useInvalidateRectOptimization=e}invalidateRect(e,t,i,r){if(this._useInvalidateRectOptimization)if(this._invalidatedRectangle){const s=Math.ceil(Math.max(this._invalidatedRectangle.left+this._invalidatedRectangle.width-1,i)),n=Math.ceil(Math.max(this._invalidatedRectangle.top+this._invalidatedRectangle.height-1,r));this._invalidatedRectangle.left=Math.floor(Math.min(this._invalidatedRectangle.left,e)),this._invalidatedRectangle.top=Math.floor(Math.min(this._invalidatedRectangle.top,t)),this._invalidatedRectangle.width=s-this._invalidatedRectangle.left+1,this._invalidatedRectangle.height=n-this._invalidatedRectangle.top+1}else this._invalidatedRectangle=new sB(e,t,i-e+1,r-t+1)}markAsDirty(){this._isDirty=!0}createStyle(){return new jB(this)}addControl(e){return this._rootContainer.addControl(e),this}removeControl(e){return this._rootContainer.removeControl(e),this}moveToNonOverlappedPosition(e,t=1,i=1){let r;if(Array.isArray(e))r=e;else{const t=this.getDescendants(!0);r=void 0===e?t.filter((e=>void 0!==e.overlapGroup)):t.filter((t=>t.overlapGroup===e))}r.forEach((e=>{let s=W.I9.Zero();const n=new W.I9(e.centerX,e.centerY);r.forEach((t=>{if(e!==t&&$B._Overlaps(e,t)){const e=n.subtract(new W.I9(t.centerX,t.centerY)),r=e.length();r>0&&(s=s.add(e.normalize().scale(i/r)))}})),s.length()>0&&(s=s.normalize().scale(t*(e.overlapDeltaMultiplier??1)),e.linkOffsetXInPixels+=s.x,e.linkOffsetYInPixels+=s.y)}))}dispose(){const e=this.getScene();e&&(this._rootElement=null,e.onBeforeCameraRenderObservable.remove(this._renderObserver),this._resizeObserver&&e.getEngine().onResizeObservable.remove(this._resizeObserver),this._prePointerObserver&&e.onPrePointerObservable.remove(this._prePointerObserver),this._sceneRenderObserver&&e.onBeforeRenderObservable.remove(this._sceneRenderObserver),this._pointerObserver&&e.onPointerObservable.remove(this._pointerObserver),this._preKeyboardObserver&&e.onPreKeyboardObservable.remove(this._preKeyboardObserver),this._canvasPointerOutObserver&&e.getEngine().onCanvasPointerOutObservable.remove(this._canvasPointerOutObserver),this._canvasBlurObserver&&e.getEngine().onCanvasBlurObservable.remove(this._canvasBlurObserver),this._controlAddedObserver&&this._rootContainer.onControlAddedObservable.remove(this._controlAddedObserver),this._controlRemovedObserver&&this._rootContainer.onControlRemovedObservable.remove(this._controlRemovedObserver),this._layerToDispose&&(this._layerToDispose.texture=null,this._layerToDispose.dispose(),this._layerToDispose=null),this._rootContainer.dispose(),this.onClipboardObservable.clear(),this.onControlPickedObservable.clear(),this.onBeginRenderObservable.clear(),this.onEndRenderObservable.clear(),this.onBeginLayoutObservable.clear(),this.onEndLayoutObservable.clear(),this.onGuiReadyObservable.clear(),super.dispose())}_onResize(){const e=this.getScene();if(!e)return;const t=e.getEngine(),i=this.getSize();let r=t.getRenderWidth()*this._renderScale,s=t.getRenderHeight()*this._renderScale;this._renderAtIdealSize&&(this._idealWidth?(s=s*this._idealWidth/r,r=this._idealWidth):this._idealHeight&&(r=r*this._idealHeight/s,s=this._idealHeight)),i.width===r&&i.height===s||(this.scaleTo(r,s),this.markAsDirty(),(this._idealWidth||this._idealHeight)&&this._rootContainer._markAllAsDirty()),this.invalidateRect(0,0,i.width-1,i.height-1)}_getGlobalViewport(){const e=this.getSize(),t=this._fullscreenViewport.toGlobal(e.width,e.height),i=Math.round(t.width*(1/this.rootContainer.scaleX)),r=Math.round(t.height*(1/this.rootContainer.scaleY));return t.x+=(t.width-i)/2,t.y+=(t.height-r)/2,t.width=i,t.height=r,t}getProjectedPosition(e,t){const i=this.getProjectedPositionWithZ(e,t);return new W.I9(i.x,i.y)}getProjectedPositionWithZ(e,t){const i=this.getScene();if(!i)return W.Pq.Zero();const r=this._getGlobalViewport(),s=W.Pq.Project(e,t,i.getTransformMatrix(),r);return new W.Pq(s.x,s.y,s.z)}_checkUpdate(e,t){if(!this._layerToDispose||!e||e.layerMask&this._layerToDispose.layerMask){if(this._isFullscreen&&this._linkedControls.length){const e=this.getScene();if(!e)return;const t=this._getGlobalViewport();for(const i of this._linkedControls){if(!i.isVisible)continue;const r=i._linkedMesh;if(!r||r.isDisposed()){Ue.S0.SetImmediate((()=>{i.linkWithMesh(null)}));continue}const s=r.getBoundingInfo?r.getBoundingInfo().boundingSphere.center:W.Pq.ZeroReadOnly,n=W.Pq.Project(s,r.getWorldMatrix(),e.getTransformMatrix(),t);n.z<0||n.z>1?i.notRenderable=!0:(i.notRenderable=!1,this.useInvalidateRectOptimization&&i.invalidateRect(),i._moveToProjectedPosition(n))}}(this._isDirty||this._rootContainer.isDirty)&&(this._isDirty=!1,this._render(t),t||this.update(this.applyYInversionOnUpdate,this.premulAlpha,$B.AllowGPUOptimizations))}}_render(e){const t=this.getSize(),i=t.width,r=t.height,s=this.getContext();if(s.font="18px Arial",s.strokeStyle="white",this.onGuiReadyObservable.hasObservers()&&this._checkGuiIsReady(),this._rootChildrenHaveChanged){const e=this.getScene()?.activeCamera;e&&(this._rootChildrenHaveChanged=!1,this._checkUpdate(e,!0))}this.onBeginLayoutObservable.notifyObservers(this);const n=new sB(0,0,i,r);this._numLayoutCalls=0,this._rootContainer._layout(n,s),this.onEndLayoutObservable.notifyObservers(this),this._isDirty=!1,e||(this._invalidatedRectangle?this._clearMeasure.copyFrom(this._invalidatedRectangle):this._clearMeasure.copyFromFloats(0,0,i,r),s.clearRect(this._clearMeasure.left,this._clearMeasure.top,this._clearMeasure.width,this._clearMeasure.height),this._background&&(s.save(),s.fillStyle=this._background,s.fillRect(this._clearMeasure.left,this._clearMeasure.top,this._clearMeasure.width,this._clearMeasure.height),s.restore()),this.onBeginRenderObservable.notifyObservers(this),this._numRenderCalls=0,this._rootContainer._render(s,this._invalidatedRectangle),this.onEndRenderObservable.notifyObservers(this),this._invalidatedRectangle=null)}_changeCursor(e){this._rootElement&&(this._rootElement.style.cursor=e,this._cursorChanged=!0)}_registerLastControlDown(e,t){this._lastControlDown[t]=e,this.onControlPickedObservable.notifyObservers(e)}_doPicking(e,t,i,r,s,n,o,a){const l=this.getScene();if(!l||this.disablePicking)return;const h=l.getEngine(),c=this.getSize();if(this._isFullscreen){const i=l.cameraToUseForPointers||l.activeCamera;if(!i)return;const r=i.viewport;e*=c.width/(h.getRenderWidth()*r.width),t*=c.height/(h.getRenderHeight()*r.height)}if(this._capturingControl[s])return this._capturingControl[s].isPointerBlocker&&(this._shouldBlockPointer=!0),void this._capturingControl[s]._processObservables(r,e,t,i,s,n);this._cursorChanged=!1,this._rootContainer._processPicking(e,t,i,r,s,n,o,a)||(l.doNotHandleCursors||this._changeCursor(""),r===yi.Zp.POINTERMOVE&&this._lastControlOver[s]&&(this._lastControlOver[s]._onPointerOut(this._lastControlOver[s],i),delete this._lastControlOver[s])),this._cursorChanged||l.doNotHandleCursors||this._changeCursor(""),this._manageFocus()}_cleanControlAfterRemovalFromList(e,t){for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&e[i]===t&&delete e[i]}_cleanControlAfterRemoval(e){this._cleanControlAfterRemovalFromList(this._lastControlDown,e),this._cleanControlAfterRemovalFromList(this._lastControlOver,e)}pick(e,t,i=null){this._isFullscreen&&this._scene&&this._translateToPicking(this._scene,new et.L(0,0,0,0),i,e,t)}_translateToPicking(e,t,i,r=e.pointerX,s=e.pointerY){const n=e.cameraToUseForPointers||e.activeCamera,o=e.getEngine(),a=e.cameraToUseForPointers;if(n)if(n.rigCameras.length){const i=new et.L(0,0,1,1);n.rigCameras.forEach((n=>{n.viewport.toGlobalToRef(o.getRenderWidth(),o.getRenderHeight(),i);const a=r/o.getHardwareScalingLevel()-i.x,l=s/o.getHardwareScalingLevel()-(o.getRenderHeight()-i.y-i.height);a<0||l<0||r>i.width||s>i.height||(e.cameraToUseForPointers=n,t.x=i.x,t.y=i.y,t.width=i.width,t.height=i.height)}))}else n.viewport.toGlobalToRef(o.getRenderWidth(),o.getRenderHeight(),t);else t.x=0,t.y=0,t.width=o.getRenderWidth(),t.height=o.getRenderHeight();const l=r/o.getHardwareScalingLevel()-t.x,h=s/o.getHardwareScalingLevel()-(o.getRenderHeight()-t.y-t.height);if(this._shouldBlockPointer=!1,i){const e=i.event.pointerId||this._defaultMousePointerId;this._doPicking(l,h,i,i.type,e,i.event.button,i.event.deltaX,i.event.deltaY),(this._shouldBlockPointer&&!(i.type&this.skipBlockEvents)||this._capturingControl[e])&&(i.skipOnPointerObservable=!0)}else this._doPicking(l,h,null,yi.Zp.POINTERMOVE,this._defaultMousePointerId,0);e.cameraToUseForPointers=a}attach(){const e=this.getScene();if(!e)return;const t=new et.L(0,0,0,0);this._prePointerObserver=e.onPrePointerObservable.add((i=>{if((!e.isPointerCaptured(i.event.pointerId)||i.type!==yi.Zp.POINTERUP||this._capturedPointerIds.has(i.event.pointerId))&&(i.type===yi.Zp.POINTERMOVE||i.type===yi.Zp.POINTERUP||i.type===yi.Zp.POINTERDOWN||i.type===yi.Zp.POINTERWHEEL||i.type===yi.Zp.POINTERTAP)){if(i.type===yi.Zp.POINTERMOVE){if(e.isPointerCaptured(i.event.pointerId))return;i.event.pointerId&&(this._defaultMousePointerId=i.event.pointerId)}this._translateToPicking(e,t,i)}})),this._attachPickingToSceneRender(e,(()=>this._translateToPicking(e,t,null)),!1),this._attachToOnPointerOut(e),this._attachToOnBlur(e)}_focusNextElement(e=!0){const t=[];if(this.executeOnAllControls((e=>{e.isFocusInvisible||!e.isVisible||e.tabIndex<0||t.push(e)})),0===t.length)return;t.sort(((e,t)=>0===e.tabIndex?1:0===t.tabIndex?-1:e.tabIndex-t.tabIndex)),this._focusProperties.total=t.length;let i=-1;this._focusedControl?(i=t.indexOf(this._focusedControl)+(e?1:-1),i<0?i=t.length-1:i>=t.length&&(i=0)):i=e?0:t.length-1,t[i].focus(),this._focusProperties.index=i}registerClipboardEvents(){self.addEventListener("copy",this._onClipboardCopy,!1),self.addEventListener("cut",this._onClipboardCut,!1),self.addEventListener("paste",this._onClipboardPaste,!1)}unRegisterClipboardEvents(){self.removeEventListener("copy",this._onClipboardCopy),self.removeEventListener("cut",this._onClipboardCut),self.removeEventListener("paste",this._onClipboardPaste)}_transformUvs(e){const t=this.getTextureMatrix();let i;if(t.isIdentityAs3x2())i=e;else{const r=W.AA.Matrix[0];t.getRowToRef(0,W.AA.Vector4[0]),t.getRowToRef(1,W.AA.Vector4[1]),t.getRowToRef(2,W.AA.Vector4[2]);const s=W.AA.Vector4[0],n=W.AA.Vector4[1],o=W.AA.Vector4[2];r.setRowFromFloats(0,s.x,s.y,0,0),r.setRowFromFloats(1,n.x,n.y,0,0),r.setRowFromFloats(2,0,0,1,0),r.setRowFromFloats(3,o.x,o.y,0,1),i=W.AA.Vector2[0],W.I9.TransformToRef(e,r,i)}if((this.wrapU===vi.g.WRAP_ADDRESSMODE||this.wrapU===vi.g.MIRROR_ADDRESSMODE)&&i.x>1){let e=i.x-Math.trunc(i.x);this.wrapU===vi.g.MIRROR_ADDRESSMODE&&Math.trunc(i.x)%2==1&&(e=1-e),i.x=e}if((this.wrapV===vi.g.WRAP_ADDRESSMODE||this.wrapV===vi.g.MIRROR_ADDRESSMODE)&&i.y>1){let e=i.y-Math.trunc(i.y);this.wrapV===vi.g.MIRROR_ADDRESSMODE&&Math.trunc(i.x)%2==1&&(e=1-e),i.y=e}return i}attachToMesh(e,t=!0){const i=this.getScene();i&&(this._pointerObserver&&i.onPointerObservable.remove(this._pointerObserver),this._pointerObserver=i.onPointerObservable.add((t=>{if(t.type!==yi.Zp.POINTERMOVE&&t.type!==yi.Zp.POINTERUP&&t.type!==yi.Zp.POINTERDOWN&&t.type!==yi.Zp.POINTERWHEEL)return;t.type===yi.Zp.POINTERMOVE&&t.event.pointerId&&(this._defaultMousePointerId=t.event.pointerId);const i=t.event.pointerId||this._defaultMousePointerId;if(t.pickInfo&&t.pickInfo.hit&&t.pickInfo.pickedMesh===e){let e=t.pickInfo.getTextureCoordinates();if(e){e=this._transformUvs(e);const r=this.getSize();this._doPicking(e.x*r.width,(this.applyYInversionOnUpdate?1-e.y:e.y)*r.height,t,t.type,i,t.event.button,t.event.deltaX,t.event.deltaY)}}else if(t.type===yi.Zp.POINTERUP){if(this._lastControlDown[i]&&this._lastControlDown[i]._forcePointerUp(i),delete this._lastControlDown[i],this.focusedControl){const e=this.focusedControl.keepsFocusWith();let t=!0;if(e)for(const r of e){if(this===r._host)continue;const e=r._host;if(e._lastControlOver[i]&&e._lastControlOver[i].isAscendant(r)){t=!1;break}}t&&(this.focusedControl=null)}}else t.type===yi.Zp.POINTERMOVE&&(this._lastControlOver[i]&&this._lastControlOver[i]._onPointerOut(this._lastControlOver[i],t,!0),delete this._lastControlOver[i])})),e.enablePointerMoveEvents=t,this._attachPickingToSceneRender(i,(()=>{const t=this._defaultMousePointerId,r=i?.pick(i.pointerX,i.pointerY);if(r&&r.hit&&r.pickedMesh===e){let e=r.getTextureCoordinates();if(e){e=this._transformUvs(e);const i=this.getSize();this._doPicking(e.x*i.width,(this.applyYInversionOnUpdate?1-e.y:e.y)*i.height,null,yi.Zp.POINTERMOVE,t,0)}}else this._lastControlOver[t]&&this._lastControlOver[t]._onPointerOut(this._lastControlOver[t],null,!0),delete this._lastControlOver[t]}),!0),this._attachToOnPointerOut(i),this._attachToOnBlur(i))}moveFocusToControl(e){this.focusedControl=e,this._lastPickedControl=e,this._blockNextFocusCheck=!0}_manageFocus(){if(this._blockNextFocusCheck)return this._blockNextFocusCheck=!1,void(this._lastPickedControl=this._focusedControl);if(this._focusedControl&&this._focusedControl!==this._lastPickedControl){if(this._lastPickedControl.isFocusInvisible)return;this.focusedControl=null}}_attachPickingToSceneRender(e,t,i){this._sceneRenderObserver=e.onBeforeRenderObservable.add((()=>{this.checkPointerEveryFrame&&(this._linkedControls.length>0||i)&&t()}))}_attachToOnPointerOut(e){this._canvasPointerOutObserver=e.getEngine().onCanvasPointerOutObservable.add((e=>{this._lastControlOver[e.pointerId]&&this._lastControlOver[e.pointerId]._onPointerOut(this._lastControlOver[e.pointerId],null),delete this._lastControlOver[e.pointerId],this._lastControlDown[e.pointerId]&&this._lastControlDown[e.pointerId]!==this._capturingControl[e.pointerId]&&(this._lastControlDown[e.pointerId]._forcePointerUp(e.pointerId),delete this._lastControlDown[e.pointerId])}))}_attachToOnBlur(e){this._canvasBlurObserver=e.getEngine().onCanvasBlurObservable.add((()=>{Object.entries(this._lastControlDown).forEach((([,e])=>{e._onCanvasBlur()})),this.focusedControl=null,this._lastControlDown={}}))}serializeContent(){const e=this.getSize(),t={root:{},width:e.width,height:e.height};return this._rootContainer.serialize(t.root),t}parseSerializedObject(e,t,i){if(this._rootContainer=lB.Parse(e.root,this,i),t){const t=e.width,i=e.height;"number"==typeof t&&"number"==typeof i&&t>=0&&i>=0?this.scaleTo(t,i):this.scaleTo(1920,1080)}}clone(e,t){const i=this.getScene();if(!i)return this;const r=this.getSize(),s=this.serializeContent();let n;return n=this._isFullscreen?$B.CreateFullscreenUI(e??"Clone of "+this.name):t?$B.CreateForMesh(t,r.width,r.height):new $B(e??"Clone of "+this.name,r.width,r.height,i,!this.noMipmap,this.samplingMode),n.parseSerializedObject(s),n}static async ParseFromSnippetAsync(e,t,i,r){const s=i??$B.CreateFullscreenUI("ADT from snippet");if("_BLANK"===e)return s;const n=await $B._LoadURLContentAsync($B.SnippetUrl+"/"+e.replace(/#/g,"/"),!0);return s.parseSerializedObject(n,t,r),s}parseFromSnippetAsync(e,t,i){return $B.ParseFromSnippetAsync(e,t,this,i)}static async ParseFromFileAsync(e,t,i,r){const s=i??$B.CreateFullscreenUI("ADT from URL"),n=await $B._LoadURLContentAsync(e);return s.parseSerializedObject(n,t,r),s}parseFromURLAsync(e,t,i){return $B.ParseFromFileAsync(e,t,this,i)}static _LoadURLContentAsync(e,t=!1){return""===e?Promise.reject("No URL provided"):new Promise(((i,r)=>{const s=new go.u;s.addEventListener("readystatechange",(()=>{if(4==s.readyState)if(200==s.status){let e;if(t){const t=JSON.parse(JSON.parse(s.responseText).jsonPayload);e=t.encodedGui?new TextDecoder("utf-8").decode((0,bi.yS)(t.encodedGui)):t.gui}else e=s.responseText;const r=JSON.parse(e);i(r)}else r("Unable to load")})),s.open("GET",e),s.send()}))}static _Overlaps(e,t){return!(e.centerX>t.centerX+t.widthInPixels||e.centerX+e.widthInPixelst.centerY+t.heightInPixels)}static CreateForMesh(e,t=1024,i=1024,r=!0,s=!1,n,o=this._CreateMaterial,a=vi.g.TRILINEAR_SAMPLINGMODE){const l=(0,Au.z)(),h=new $B(`AdvancedDynamicTexture for ${e.name} [${l}]`,t,i,e.getScene(),!0,a,n);return o(e,l,h,s),h.attachToMesh(e,r),h}static _CreateMaterial(e,t,i,r){const s=(0,X.n9)("BABYLON.StandardMaterial");if(!s)throw"StandardMaterial needs to be imported before as it contains a side-effect required by your code.";const n=new s(`AdvancedDynamicTextureMaterial for ${e.name} [${t}]`,e.getScene());n.backFaceCulling=!1,n.diffuseColor=H.v9.Black(),n.specularColor=H.v9.Black(),r?(n.diffuseTexture=i,n.emissiveTexture=i,i.hasAlpha=!0):(n.emissiveTexture=i,n.opacityTexture=i),e.material=n}static CreateForMeshTexture(e,t=1024,i=1024,r=!0,s,n=vi.g.TRILINEAR_SAMPLINGMODE){const o=new $B(e.name+" AdvancedDynamicTexture",t,i,e.getScene(),!0,n,s);return o.attachToMesh(e,r),o}static CreateFullscreenUI(e,t=!0,i=null,r=vi.g.BILINEAR_SAMPLINGMODE,s=!1){const n=!i||i._isScene?new $B(e,0,0,i,!1,r):new $B(e,i),o=n.getScene(),a=new zv(e+"_layer",null,o,!t);if(a.texture=n,n._layerToDispose=a,n._isFullscreen=!0,n.useStandalone&&(a.layerMask=0),s&&o){const e=1/o.getEngine().getHardwareScalingLevel();n._rootContainer.scaleX=e,n._rootContainer.scaleY=e}return n.attach(),n}scale(e){super.scale(e),this.markAsDirty()}scaleTo(e,t){super.scaleTo(e,t),this.markAsDirty()}_checkGuiIsReady(){this.guiIsReady()&&(this.onGuiReadyObservable.notifyObservers(this),this.onGuiReadyObservable.clear())}guiIsReady(){return this._rootContainer.isReady()}}$B.SnippetUrl=Il.SnippetUrl,$B.AllowGPUOptimizations=!0;class QB{get renderTimeCounter(){return this._renderTime}get layoutTimeCounter(){return this._layoutTime}get captureRenderTime(){return this._captureRenderTime}set captureRenderTime(e){e!==this._captureRenderTime&&(this._captureRenderTime=e,e?(this._onBeginRenderObserver=this.texture.onBeginRenderObservable.add((()=>{this._renderTime.beginMonitoring()})),this._onEndRenderObserver=this.texture.onEndRenderObservable.add((()=>{this._renderTime.endMonitoring(!0)}))):(this.texture.onBeginRenderObservable.remove(this._onBeginRenderObserver),this._onBeginRenderObserver=null,this.texture.onEndRenderObservable.remove(this._onEndRenderObserver),this._onEndRenderObserver=null))}get captureLayoutTime(){return this._captureLayoutTime}set captureLayoutTime(e){e!==this._captureLayoutTime&&(this._captureLayoutTime=e,e?(this._onBeginLayoutObserver=this.texture.onBeginLayoutObservable.add((()=>{this._layoutTime.beginMonitoring()})),this._onEndLayoutObserver=this.texture.onEndLayoutObservable.add((()=>{this._layoutTime.endMonitoring(!0)}))):(this.texture.onBeginLayoutObservable.remove(this._onBeginLayoutObserver),this._onBeginLayoutObserver=null,this.texture.onEndLayoutObservable.remove(this._onEndLayoutObserver),this._onEndLayoutObserver=null))}constructor(e){this.texture=e,this._captureRenderTime=!1,this._renderTime=new on.A,this._captureLayoutTime=!1,this._layoutTime=new on.A,this._onBeginRenderObserver=null,this._onEndRenderObserver=null,this._onBeginLayoutObserver=null,this._onEndLayoutObserver=null}dispose(){this.texture.onBeginRenderObservable.remove(this._onBeginRenderObserver),this._onBeginRenderObserver=null,this.texture.onEndRenderObservable.remove(this._onEndRenderObserver),this._onEndRenderObserver=null,this.texture.onBeginLayoutObservable.remove(this._onBeginLayoutObserver),this._onBeginLayoutObserver=null,this.texture.onEndLayoutObservable.remove(this._onEndLayoutObserver),this._onEndLayoutObserver=null,this.texture=null}}class ZB extends kp{get disabled(){return this._disabled}set disabled(e){this._disabled=e,this._adt.disablePicking=e}get gui(){return this._adt}constructor(e,t,i){if(super(e,t),i){if(!i.useStandalone)throw new Error(`AdvancedDynamicTexture "${e}": the texture must have been created with the useStandalone property set to true`)}else i=$B.CreateFullscreenUI(e,void 0,{useStandalone:!0});this._adt=i,this.outputTexture=this._frameGraph.createDanglingHandle()}isReady(){return this._adt.guiIsReady()&&this._adt._layerToDispose.isReady()}record(){if(void 0===this.destinationTexture)throw new Error("FrameGraphGUITask: destinationTexture is required");this._frameGraph.resolveDanglingHandle(this.outputTexture,this.destinationTexture);const e=this._frameGraph.addRenderPass(this.name);e.setRenderTarget(this.outputTexture),e.setExecuteFunc((e=>{this._adt._checkUpdate(null),e.render(this._adt._layerToDispose)}));const t=this._frameGraph.addRenderPass(this.name+"_disabled",!0);t.setRenderTarget(this.outputTexture),t.setExecuteFunc((e=>{}))}dispose(){this._adt.dispose(),super.dispose()}}class JB extends wp{get task(){return this._frameGraphTask}get gui(){return this._frameGraphTask.gui}constructor(e,t,i){super(e,t,i),this.registerInput("destination",Rp.Texture),this.registerOutput("output",Rp.BasedOnInput),this.destination.addAcceptedConnectionPointTypes(Rp.TextureAll),this.output._typeConnectionSource=this.destination,this._gui=$B.CreateFullscreenUI(this.name,void 0,{useStandalone:!0}),this._frameGraphTask=new ZB(this.name,t,this._gui)}getClassName(){return"GUI.NodeRenderGraphGUIBlock"}get destination(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this._frameGraphTask.name=this.name,this.output.value=this._frameGraphTask.outputTexture;const t=this.destination.connectedPoint;t&&(this._frameGraphTask.destinationTexture=t.value)}}(0,X.Y5)("BABYLON.GUI.NodeRenderGraphGUIBlock",JB);const eV="XmlLoader Exception : XML file is malformed or corrupted.";class tV{constructor(e=null){this._nodes={},this._nodeTypes={element:1,attribute:2,text:3},this._isLoaded=!1,this._objectAttributes={textHorizontalAlignment:1,textVerticalAlignment:2,horizontalAlignment:3,verticalAlignment:4,stretch:5},e&&(this._parentClass=e)}_getChainElement(e){let t=window;this._parentClass&&(t=this._parentClass);let i=e;i=i.split(".");for(let e=0;e0&&u>d)throw"XmlLoader Exception : In the Grid element, the number of columns is defined in the first row, do not add more columns in the subsequent rows.";if(0==c){if(!n[e].attributes.getNamedItem("width"))throw"XmlLoader Exception : Width must be defined for all the grid columns in the first row";r=Number(n[e].attributes.getNamedItem("width").nodeValue),h=!!n[e].attributes.getNamedItem("isPixel")&&JSON.parse(n[e].attributes.getNamedItem("isPixel").nodeValue),t.addColumnDefinition(r,h)}a=n[e].children;for(let e=0;e{if(4===s.readyState&&200===s.status){if(!s.responseXML){if(r)return void r(eV);throw eV}const e=s.responseXML.documentElement;this._parseXml(e.firstChild,t),this._isLoaded=!0,i&&i()}},s.onerror=function(){r&&r("an error occurred during loading the layout")},s.open("GET",e,!0),s.send()}async loadLayoutAsync(e,t){return new Promise(((i,r)=>{this.loadLayout(e,t,i,r)}))}}class iV extends W.Pq{constructor(e,t=0){super(e.x,e.y,e.z),this.buttonIndex=t}}class rV{get position(){return this._node?this._node.position:(this._position=this._position||W.Pq.Zero(),this._position)}set position(e){this._position=e,this._node&&(this._node.position=this._position)}get scaling(){return this._node?this._node.scaling:(this._scaling=this.scaling||new W.Pq(1,1,1),this._scaling)}set scaling(e){this._scaling=e,this._node&&(this._isScaledByManager=!1,this._node.scaling=this._scaling)}get behaviors(){return this._behaviors}addBehavior(e){if(-1!==this._behaviors.indexOf(e))return this;e.init();const t=this._host.scene;return t.isLoading?t.onDataLoadedObservable.addOnce((()=>{e.attach(this)})):e.attach(this),this._behaviors.push(e),this}removeBehavior(e){const t=this._behaviors.indexOf(e);return-1===t||(this._behaviors[t].detach(),this._behaviors.splice(t,1)),this}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}get isVisible(){return this._isVisible}set isVisible(e){if(this._isVisible===e)return;this._isVisible=e;const t=this.mesh;t&&t.setEnabled(e)}constructor(e){this.name=e,this._downCount=0,this._enterCount=-1,this._downPointerIds={},this._isVisible=!0,this._isScaledByManager=!1,this.onPointerMoveObservable=new z.cP,this.onPointerOutObservable=new z.cP,this.onPointerDownObservable=new z.cP,this.onPointerUpObservable=new z.cP,this.onPointerClickObservable=new z.cP,this.onPointerEnterObservable=new z.cP,this._behaviors=new Array}get typeName(){return this._getTypeName()}getClassName(){return this._getTypeName()}_getTypeName(){return"Control3D"}get node(){return this._node}get mesh(){return this._node instanceof Nt?this._node:null}linkToTransformNode(e){return this._node&&(this._node.parent=e),this}_prepareNode(e){if(!this._node){if(this._node=this._createNode(e),!this.node)return;this._position&&(this.node.position=this._position),this._scaling&&(this.node.scaling=this._scaling),this._injectGUI3DReservedDataStore(this.node).control=this;const t=this.mesh;t&&(t.isPickable=!0,this._affectMaterial(t))}}_injectGUI3DReservedDataStore(e){return e.reservedDataStore=e.reservedDataStore??{},e.reservedDataStore.GUI3D=e.reservedDataStore.GUI3D??{},e.reservedDataStore.GUI3D}_createNode(e){return null}_affectMaterial(e){e.material=null}_isTouchButton3D(e){return void 0!==e._generatePointerEventType}_onPointerMove(e,t){this.onPointerMoveObservable.notifyObservers(t,-1,e,this)}_onPointerEnter(e){return-1===this._enterCount&&(this._enterCount=0),this._enterCount++,!(this._enterCount>1||(this.onPointerEnterObservable.notifyObservers(this,-1,e,this),this.pointerEnterAnimation&&this.pointerEnterAnimation(),0))}_onPointerOut(e){this._enterCount--,this._enterCount>0||(this._enterCount=0,this.onPointerOutObservable.notifyObservers(this,-1,e,this),this.pointerOutAnimation&&this.pointerOutAnimation())}_onPointerDown(e,t,i,r){return this._downCount++,this._downPointerIds[i]=this._downPointerIds[i]+1||1,1===this._downCount&&(this.onPointerDownObservable.notifyObservers(new iV(t,r),-1,e,this),this.pointerDownAnimation&&this.pointerDownAnimation(),!0)}_onPointerUp(e,t,i,r,s){this._downCount--,this._downPointerIds[i]--,this._downPointerIds[i]<=0&&delete this._downPointerIds[i],this._downCount<0?this._downCount=0:0==this._downCount&&(s&&(this._enterCount>0||-1===this._enterCount)&&this.onPointerClickObservable.notifyObservers(new iV(t,r),-1,e,this),this.onPointerUpObservable.notifyObservers(new iV(t,r),-1,e,this),this.pointerUpAnimation&&this.pointerUpAnimation())}forcePointerUp(e=null){if(null!==e)this._onPointerUp(this,W.Pq.Zero(),e,0,!0);else{for(const e in this._downPointerIds)this._onPointerUp(this,W.Pq.Zero(),+e,0,!0);this._downCount>0&&(this._downCount=1,this._onPointerUp(this,W.Pq.Zero(),0,0,!0))}}_processObservables(e,t,i,r,s){if(this._isTouchButton3D(this)&&i&&(e=this._generatePointerEventType(e,i,this._downCount)),e===yi.Zp.POINTERMOVE){this._onPointerMove(this,t);const e=this._host._lastControlOver[r];return e&&e!==this&&e._onPointerOut(this),e!==this&&this._onPointerEnter(this),this._host._lastControlOver[r]=this,!0}return e===yi.Zp.POINTERDOWN?(this._onPointerDown(this,t,r,s),this._host._lastControlDown[r]=this,this._host._lastPickedControl=this,!0):(e===yi.Zp.POINTERUP||e===yi.Zp.POINTERDOUBLETAP)&&(this._host._lastControlDown[r]&&this._host._lastControlDown[r]._onPointerUp(this,t,r,s,!0),delete this._host._lastControlDown[r],!0)}_disposeNode(){this._node&&(this._node.dispose(),this._node=null)}dispose(){this.onPointerDownObservable.clear(),this.onPointerEnterObservable.clear(),this.onPointerMoveObservable.clear(),this.onPointerOutObservable.clear(),this.onPointerUpObservable.clear(),this.onPointerClickObservable.clear(),this._disposeNode();for(const e of this._behaviors)e.detach()}}class sV extends rV{constructor(){super(...arguments),this._contentResolution=512,this._contentScaleRatio=2}get content(){return this._content}set content(e){if(this._content=e,e&&this._host&&this._host.utilityLayer){if(this._facadeTexture)this._facadeTexture.rootContainer.clearControls();else{const e="number"==typeof this._contentResolution?this._contentResolution:this._contentResolution.width,t="number"==typeof this._contentResolution?this._contentResolution:this._contentResolution.height;this._facadeTexture=new $B("Facade",e,t,this._host.utilityLayer.utilityLayerScene,!0,vi.g.TRILINEAR_SAMPLINGMODE),this._setFacadeTextureScaling(),this._facadeTexture.premulAlpha=!0}this._facadeTexture.addControl(e),this._applyFacade(this._facadeTexture)}}_setFacadeTextureScaling(){this._facadeTexture&&("number"!=typeof this._contentResolution&&(this._contentScaleRatioY=this._contentResolution.height/this._contentResolution.width*this._contentScaleRatio),this._facadeTexture.rootContainer.scaleX=this._contentScaleRatio,this._facadeTexture.rootContainer.scaleY=this._contentScaleRatioY??this._contentScaleRatio)}get contentResolution(){return this._contentResolution}set contentResolution(e){const t="number"==typeof e?e:e.width,i="number"==typeof e?e:e.height,r="number"==typeof this._contentResolution?this._contentResolution:this._contentResolution.width,s="number"==typeof this._contentResolution?this._contentResolution:this._contentResolution.height;t===r&&i===s||(this._contentResolution=e,this._resetContent())}_disposeFacadeTexture(){this._facadeTexture&&(this._facadeTexture.dispose(),this._facadeTexture=null)}_resetContent(){this._disposeFacadeTexture(),this.content=this._content}_applyFacade(e){}}class nV extends sV{constructor(e){super(e)}_getTypeName(){return"AbstractButton3D"}_createNode(e){return new Pt("button"+this.name,e)}}class oV extends nV{constructor(e,t){super(e),this._options={width:1,height:1,depth:.08,...t},this.pointerEnterAnimation=()=>{this.mesh&&(this._currentMaterial.emissiveColor=H.v9.Red())},this.pointerOutAnimation=()=>{this._currentMaterial.emissiveColor=H.v9.Black()},this.pointerDownAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/.95)}}_applyFacade(e){this._currentMaterial.emissiveTexture=e}_getTypeName(){return"Button3D"}_createNode(e){const t=new Array(6);for(let e=0;e<6;e++)t[e]=new W.IU(0,0,0,0);e.useRightHandedSystem?t[0].copyFromFloats(1,0,0,1):t[1].copyFromFloats(0,0,1,1);const i=Ko(this.name+"_rootMesh",{width:this._options.width,height:this._options.height,depth:this._options.depth,faceUV:t,wrap:!0},e);return this._contentScaleRatioY=this._contentScaleRatio*this._options.width/this._options.height,this._setFacadeTextureScaling(),i}_affectMaterial(e){const t=new Un(this.name+"Material",e.getScene());t.specularColor=H.v9.Black(),e.material=t,this._currentMaterial=t,this._resetContent()}dispose(){super.dispose(),this._disposeFacadeTexture(),this._currentMaterial&&this._currentMaterial.dispose()}}class aV extends rV{get children(){return this._children}get blockLayout(){return this._blockLayout}set blockLayout(e){this._blockLayout!==e&&(this._blockLayout=e,this._blockLayout||this._arrangeChildren())}constructor(e){super(e),this._blockLayout=!1,this._children=new Array}updateLayout(){return this._arrangeChildren(),this}containsControl(e){return-1!==this._children.indexOf(e)}addControl(e){return-1!==this._children.indexOf(e)||(e.parent=this,e._host=this._host,this._children.push(e),this._host.utilityLayer&&(e._prepareNode(this._host.utilityLayer.utilityLayerScene),e.node&&(e.node.parent=this.node),this.blockLayout||this._arrangeChildren())),this}_arrangeChildren(){}_createNode(e){return new Pt("ContainerNode",e)}removeControl(e){const t=this._children.indexOf(e);return-1!==t&&(this._children.splice(t,1),e.parent=null,e._disposeNode()),this}_getTypeName(){return"Container3D"}dispose(){for(const e of this._children)e.dispose();this._children.length=0,super.dispose()}}aV.UNSET_ORIENTATION=0,aV.FACEORIGIN_ORIENTATION=1,aV.FACEORIGINREVERSED_ORIENTATION=2,aV.FACEFORWARD_ORIENTATION=3,aV.FACEFORWARDREVERSED_ORIENTATION=4;class lV extends aV{get orientation(){return this._orientation}set orientation(e){this._orientation!==e&&(this._orientation=e,Ue.S0.SetImmediate((()=>{this._arrangeChildren()})))}get columns(){return this._columns}set columns(e){this._columns!==e&&(this._columns=e,this._rowThenColum=!0,Ue.S0.SetImmediate((()=>{this._arrangeChildren()})))}get rows(){return this._rows}set rows(e){this._rows!==e&&(this._rows=e,this._rowThenColum=!1,Ue.S0.SetImmediate((()=>{this._arrangeChildren()})))}constructor(e){super(e),this._columns=10,this._rows=0,this._rowThenColum=!0,this._orientation=aV.FACEORIGIN_ORIENTATION,this.margin=0}_arrangeChildren(){this._cellWidth=0,this._cellHeight=0;let e=0,t=0,i=0;for(const e of this._children){if(!e.mesh)continue;i++,e.mesh.computeWorldMatrix(!0);const t=e.mesh.getBoundingInfo().boundingBox.extendSize,r=e.mesh.getDescendants(!1);for(const e of r){e.computeWorldMatrix(!0);const i=e;if("function"==typeof i.getBoundingInfo){const e=i.getBoundingInfo().boundingBox.extendSize;t.x=Math.max(t.x,e.x),t.y=Math.max(t.y,e.y),t.z=Math.max(t.z,e.z)}}this._cellWidth=Math.max(this._cellWidth,2*t.x),this._cellHeight=Math.max(this._cellHeight,2*t.y)}this._cellWidth+=2*this.margin,this._cellHeight+=2*this.margin,this._rowThenColum?(t=this._columns,e=Math.ceil(i/this._columns)):(e=this._rows,t=Math.ceil(i/this._rows));const r=.5*t*this._cellWidth,s=.5*e*this._cellHeight,n=[];let o=0;if(this._rowThenColum)for(let a=0;ai));e++);else for(let a=0;ai));t++);o=0;for(const e of this._children)e.mesh&&(this._mapGridNode(e,n[o]),o++);this._finalProcessing()}_finalProcessing(){}}class hV extends lV{constructor(){super(...arguments),this._radius=5}get radius(){return this._radius}set radius(e){this._radius!==e&&(this._radius=e,Ue.S0.SetImmediate((()=>{this._arrangeChildren()})))}_mapGridNode(e,t){const i=e.mesh;if(!i)return;const r=this._cylindricalMapping(t);switch(e.position=r,this.orientation){case aV.FACEORIGIN_ORIENTATION:i.lookAt(new W.Pq(2*r.x,r.y,2*r.z));break;case aV.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new W.Pq(-r.x,r.y,-r.z));break;case aV.FACEFORWARD_ORIENTATION:break;case aV.FACEFORWARDREVERSED_ORIENTATION:i.rotate(Mt._0.Y,Math.PI,0)}}_cylindricalMapping(e){const t=new W.Pq(0,e.y,this._radius),i=e.x/this._radius;return W.uq.RotationYawPitchRollToRef(i,0,0,W.AA.Matrix[0]),W.Pq.TransformNormal(t,W.AA.Matrix[0])}}Cs.l.ShadersStore.fluentVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 world;uniform mat4 viewProjection;varying vec2 vUV;\n#ifdef BORDER\nvarying vec2 scaleInfo;uniform float borderWidth;uniform vec3 scaleFactor;\n#endif\n#ifdef HOVERLIGHT\nvarying vec3 worldPosition;\n#endif\nvoid main(void) {vUV=uv;\n#ifdef BORDER\nvec3 scale=scaleFactor;float minScale=min(min(scale.x,scale.y),scale.z);float maxScale=max(max(scale.x,scale.y),scale.z);float minOverMiddleScale=minScale/(scale.x+scale.y+scale.z-minScale-maxScale);float areaYZ=scale.y*scale.z;float areaXZ=scale.x*scale.z;float areaXY=scale.x*scale.y;float scaledBorderWidth=borderWidth; \nif (abs(normal.x)==1.0) \n{scale.x=scale.y;scale.y=scale.z;if (areaYZ>areaXZ && areaYZ>areaXY)\n{scaledBorderWidth*=minOverMiddleScale;}}\nelse if (abs(normal.y)==1.0) \n{scale.x=scale.z;if (areaXZ>areaXY && areaXZ>areaYZ)\n{scaledBorderWidth*=minOverMiddleScale;}}\nelse \n{if (areaXY>areaYZ && areaXY>areaXZ)\n{scaledBorderWidth*=minOverMiddleScale;}}\nfloat scaleRatio=min(scale.x,scale.y)/max(scale.x,scale.y);if (scale.x>scale.y)\n{scaleInfo.x=1.0-(scaledBorderWidth*scaleRatio);scaleInfo.y=1.0-scaledBorderWidth;}\nelse\n{scaleInfo.x=1.0-scaledBorderWidth;scaleInfo.y=1.0-(scaledBorderWidth*scaleRatio);} \n#endif \nvec4 worldPos=world*vec4(position,1.0);\n#ifdef HOVERLIGHT\nworldPosition=worldPos.xyz;\n#endif\ngl_Position=viewProjection*worldPos;}\n";Cs.l.ShadersStore.fluentPixelShader="precision highp float;varying vec2 vUV;uniform vec4 albedoColor;\n#ifdef INNERGLOW\nuniform vec4 innerGlowColor;\n#endif\n#ifdef BORDER\nvarying vec2 scaleInfo;uniform float edgeSmoothingValue;uniform float borderMinValue;\n#endif\n#ifdef HOVERLIGHT\nvarying vec3 worldPosition;uniform vec3 hoverPosition;uniform vec4 hoverColor;uniform float hoverRadius;\n#endif\n#ifdef TEXTURE\nuniform sampler2D albedoSampler;uniform mat4 textureMatrix;vec2 finalUV;\n#endif\nvoid main(void) {vec3 albedo=albedoColor.rgb;float alpha=albedoColor.a;\n#ifdef TEXTURE\nfinalUV=vec2(textureMatrix*vec4(vUV,1.0,0.0));albedo=texture2D(albedoSampler,finalUV).rgb;\n#endif\n#ifdef HOVERLIGHT\nfloat pointToHover=(1.0-clamp(length(hoverPosition-worldPosition)/hoverRadius,0.,1.))*hoverColor.a;albedo=clamp(albedo+hoverColor.rgb*pointToHover,0.,1.);\n#else\nfloat pointToHover=1.0;\n#endif\n#ifdef BORDER \nfloat borderPower=10.0;float inverseBorderPower=1.0/borderPower;vec3 borderColor=albedo*borderPower;vec2 distanceToEdge;distanceToEdge.x=abs(vUV.x-0.5)*2.0;distanceToEdge.y=abs(vUV.y-0.5)*2.0;float borderValue=max(smoothstep(scaleInfo.x-edgeSmoothingValue,scaleInfo.x+edgeSmoothingValue,distanceToEdge.x),\nsmoothstep(scaleInfo.y-edgeSmoothingValue,scaleInfo.y+edgeSmoothingValue,distanceToEdge.y));borderColor=borderColor*borderValue*max(borderMinValue*inverseBorderPower,pointToHover); \nalbedo+=borderColor;alpha=max(alpha,borderValue);\n#endif\n#ifdef INNERGLOW\nvec2 uvGlow=(vUV-vec2(0.5,0.5))*(innerGlowColor.a*2.0);uvGlow=uvGlow*uvGlow;uvGlow=uvGlow*uvGlow;albedo+=mix(vec3(0.0,0.0,0.0),innerGlowColor.rgb,uvGlow.x+uvGlow.y); \n#endif\ngl_FragColor=vec4(albedo,alpha);}";class cV extends xn{constructor(){super(),this.INNERGLOW=!1,this.BORDER=!1,this.HOVERLIGHT=!1,this.TEXTURE=!1,this.rebuild()}}class uV extends bn{constructor(e,t){super(e,t),this.innerGlowColorIntensity=.5,this.innerGlowColor=new H.v9(1,1,1),this.albedoColor=new H.v9(.3,.35,.4),this.renderBorders=!1,this.borderWidth=.5,this.edgeSmoothingValue=.02,this.borderMinValue=.1,this.renderHoverLight=!1,this.hoverRadius=.01,this.hoverColor=new H.ov(.3,.3,.3,1),this.hoverPosition=W.Pq.Zero()}needAlphaBlending(){return 1!==this.alpha}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new cV);const r=this.getScene(),s=t.materialDefines;if(!this.checkReadyOnEveryCall&&t.effect&&s._renderId===r.getRenderId())return!0;if(s._areTexturesDirty)if(s.INNERGLOW=this.innerGlowColorIntensity>0,s.BORDER=this.renderBorders,s.HOVERLIGHT=this.renderHoverLight,this._albedoTexture){if(!this._albedoTexture.isReadyOrNotBlocking())return!1;s.TEXTURE=!0}else s.TEXTURE=!1;const n=r.getEngine();if(s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=[st.R.PositionKind];e.push(st.R.NormalKind),e.push(st.R.UVKind);const i="fluent",o=["world","viewProjection","innerGlowColor","albedoColor","borderWidth","edgeSmoothingValue","scaleFactor","borderMinValue","hoverColor","hoverPosition","hoverRadius","textureMatrix"],a=["albedoSampler"],l=[];(0,Bt.Bb)({uniformsNames:o,uniformBuffersNames:l,samplers:a,defines:s,maxSimultaneousLights:4});const h=s.toString();t.setEffect(r.getEngine().createEffect(i,{attributes:e,uniformsNames:o,uniformBuffersNames:l,samplers:a,defines:h,fallbacks:null,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;if(n){if(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),this._mustRebind(r,n,i)&&(this._activeEffect.setColor4("albedoColor",this.albedoColor,this.alpha),s.INNERGLOW&&this._activeEffect.setColor4("innerGlowColor",this.innerGlowColor,this.innerGlowColorIntensity),s.BORDER&&(this._activeEffect.setFloat("borderWidth",this.borderWidth),this._activeEffect.setFloat("edgeSmoothingValue",this.edgeSmoothingValue),this._activeEffect.setFloat("borderMinValue",this.borderMinValue),t.getBoundingInfo().boundingBox.extendSize.multiplyToRef(t.scaling,W.AA.Vector3[0]),this._activeEffect.setVector3("scaleFactor",W.AA.Vector3[0])),s.HOVERLIGHT&&(this._activeEffect.setDirectColor4("hoverColor",this.hoverColor),this._activeEffect.setFloat("hoverRadius",this.hoverRadius),this._activeEffect.setVector3("hoverPosition",this.hoverPosition)),s.TEXTURE&&this._albedoTexture)){this._activeEffect.setTexture("albedoSampler",this._albedoTexture);const e=this._albedoTexture.getTextureMatrix();this._activeEffect.setMatrix("textureMatrix",e)}this._afterBind(t,this._activeEffect,i)}}getActiveTextures(){return super.getActiveTextures()}hasTexture(e){return!!super.hasTexture(e)}dispose(e){super.dispose(e)}clone(e){return it.p.Clone((()=>new uV(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GUI.FluentMaterial",e}getClassName(){return"FluentMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new uV(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],uV.prototype,"innerGlowColorIntensity",void 0),(0,je.Cg)([(0,$e.jT)()],uV.prototype,"innerGlowColor",void 0),(0,je.Cg)([(0,$e.jT)()],uV.prototype,"albedoColor",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],uV.prototype,"renderBorders",void 0),(0,je.Cg)([(0,$e.lK)()],uV.prototype,"borderWidth",void 0),(0,je.Cg)([(0,$e.lK)()],uV.prototype,"edgeSmoothingValue",void 0),(0,je.Cg)([(0,$e.lK)()],uV.prototype,"borderMinValue",void 0),(0,je.Cg)([(0,$e.lK)(),(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],uV.prototype,"renderHoverLight",void 0),(0,je.Cg)([(0,$e.lK)()],uV.prototype,"hoverRadius",void 0),(0,je.Cg)([(0,$e.qK)()],uV.prototype,"hoverColor",void 0),(0,je.Cg)([(0,$e.P_)()],uV.prototype,"hoverPosition",void 0),(0,je.Cg)([(0,$e.uM)("albedoTexture")],uV.prototype,"_albedoTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesAndMiscDirty")],uV.prototype,"albedoTexture",void 0),(0,X.Y5)("BABYLON.GUI.FluentMaterial",uV);class dV extends lV{get backPlateMargin(){return this._backPlateMargin}set backPlateMargin(e){this._backPlateMargin=e,this._children.length>=1&&(this.children.forEach((e=>{this._updateCurrentMinMax(e.position)})),this._updateMargins())}_createNode(e){const t=new Yt(`menu_${this.name}`,e);return this._backPlate=Ko("backPlate"+this.name,{size:1},e),this._backPlate.parent=t,t}_affectMaterial(e){this._backPlateMaterial=new uV(this.name+"backPlateMaterial",e.getScene()),this._backPlateMaterial.albedoColor=new H.v9(.08,.15,.55),this._backPlateMaterial.renderBorders=!0,this._backPlateMaterial.renderHoverLight=!0,this._pickedPointObserver=this._host.onPickedPointChangedObservable.add((e=>{e?(this._backPlateMaterial.hoverPosition=e,this._backPlateMaterial.hoverColor.a=1):this._backPlateMaterial.hoverColor.a=0})),this._backPlate.material=this._backPlateMaterial}_mapGridNode(e,t){e.mesh&&(e.position=t.clone(),this._updateCurrentMinMax(t))}_finalProcessing(){this._updateMargins()}_updateCurrentMinMax(e){this._currentMin||(this._currentMin=e.clone(),this._currentMax=e.clone()),this._currentMin.minimizeInPlace(e),this._currentMax.maximizeInPlace(e)}_updateMargins(){if(this._children.length>0){this._currentMin.addInPlaceFromFloats(-this._cellWidth/2,-this._cellHeight/2,0),this._currentMax.addInPlaceFromFloats(this._cellWidth/2,this._cellHeight/2,0);const e=this._currentMax.subtract(this._currentMin);this._backPlate.scaling.x=e.x+this._cellWidth*this.backPlateMargin,this._backPlate.scaling.y=e.y+this._cellHeight*this.backPlateMargin,this._backPlate.scaling.z=.001;for(let t=0;t0.0 ? g : 1.0;Gradient2=Position_Object.z>0.0 ? 1.0 : g;} else {Gradient1=g+(1.0-g)*(Radial_Gradient);Gradient2=1.0;}}\nvoid Pick_Radius_B144(\nfloat Radius,\nfloat Radius_Top_Left,\nfloat Radius_Top_Right,\nfloat Radius_Bottom_Left,\nfloat Radius_Bottom_Right,\nvec3 Position,\nout float Result)\n{bool whichY=Position.y>0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid main()\n{vec3 Nrm_World_Q128;Nrm_World_Q128=normalize((world*vec4(normal,0.0)).xyz);vec3 Tangent_World_Q131;vec3 Tangent_World_N_Q131;float Tangent_Length_Q131;Tangent_World_Q131=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q131=length(Tangent_World_Q131);Tangent_World_N_Q131=Tangent_World_Q131/Tangent_Length_Q131;vec3 Binormal_World_Q132;vec3 Binormal_World_N_Q132;float Binormal_Length_Q132;Object_To_World_Dir_B132(vec3(0,1,0),Binormal_World_Q132,Binormal_World_N_Q132,Binormal_Length_Q132);float Anisotropy_Q133=Tangent_Length_Q131/Binormal_Length_Q132;vec3 Result_Q177;Result_Q177=mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(_Use_Global_Left_Index_));vec3 Result_Q178;Result_Q178=mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(_Use_Global_Right_Index_));float Result_Q144;Pick_Radius_B144(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q144);vec3 Dir_Q140;PickDir_B140(_Angle_,Tangent_World_N_Q131,Binormal_World_N_Q132,Dir_Q140);float Radius_Q147;float Line_Width_Q147;RelativeOrAbsoluteDetail_B147(Result_Q144,_Line_Width_,_Absolute_Sizes_,Binormal_Length_Q132,Radius_Q147,Line_Width_Q147);vec4 Out_Color_Q145=vec4(Radius_Q147,Line_Width_Q147,0,1);vec3 New_P_Q129;vec2 New_UV_Q129;float Radial_Gradient_Q129;vec3 Radial_Dir_Q129;Move_Verts_B129(Anisotropy_Q133,position,Radius_Q147,New_P_Q129,New_UV_Q129,Radial_Gradient_Q129,Radial_Dir_Q129);vec3 Pos_World_Q115;Object_To_World_Pos_B115(New_P_Q129,Pos_World_Q115);vec4 Blob_Info_Q180;\n#if BLOB_ENABLE\nBlob_Vertex_B180(Pos_World_Q115,Nrm_World_Q128,Tangent_World_N_Q131,Binormal_World_N_Q132,Result_Q177,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q180);\n#else\nBlob_Info_Q180=vec4(0,0,0,0);\n#endif\nvec4 Blob_Info_Q181;\n#if BLOB_ENABLE_2\nBlob_Vertex_B180(Pos_World_Q115,Nrm_World_Q128,Tangent_World_N_Q131,Binormal_World_N_Q132,Result_Q178,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q181);\n#else\nBlob_Info_Q181=vec4(0,0,0,0);\n#endif\nfloat Gradient1_Q130;float Gradient2_Q130;\n#if SMOOTH_EDGES\nEdge_AA_Vertex_B130(Pos_World_Q115,position,normal,cameraPosition,Radial_Gradient_Q129,Radial_Dir_Q129,tangent,Gradient1_Q130,Gradient2_Q130);\n#else\nGradient1_Q130=1.0;Gradient2_Q130=1.0;\n#endif\nvec2 Rect_UV_Q139;vec4 Rect_Parms_Q139;vec2 Scale_XY_Q139;vec2 Line_UV_Q139;Round_Rect_Vertex_B139(New_UV_Q129,Radius_Q147,0.0,Anisotropy_Q133,Gradient1_Q130,Gradient2_Q130,Rect_UV_Q139,Rect_Parms_Q139,Scale_XY_Q139,Line_UV_Q139);vec3 Line_Vertex_Q135;Line_Vertex_B135(Scale_XY_Q139,Line_UV_Q139,0.0,_Rate_,_Highlight_Transform_,Line_Vertex_Q135);vec3 Position=Pos_World_Q115;vec3 Normal=Dir_Q140;vec2 UV=Rect_UV_Q139;vec3 Tangent=Line_Vertex_Q135;vec3 Binormal=Nrm_World_Q128;vec4 Color=Out_Color_Q145;vec4 Extra1=Rect_Parms_Q139;vec4 Extra2=Blob_Info_Q180;vec4 Extra3=Blob_Info_Q181;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class pV extends xn{constructor(){super(),this.BLOB_ENABLE=!0,this.BLOB_ENABLE_2=!0,this.SMOOTH_EDGES=!0,this.IRIDESCENT_MAP_ENABLE=!0,this._needNormals=!0,this.rebuild()}}class _V extends bn{constructor(e,t){super(e,t),this.radius=.03,this.lineWidth=.01,this.absoluteSizes=!1,this._filterWidth=1,this.baseColor=new H.ov(.0392157,.0666667,.207843,1),this.lineColor=new H.ov(.14902,.133333,.384314,1),this.blobIntensity=.98,this.blobFarSize=.04,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.08,this.blobNearSize=.22,this.blobPulse=0,this.blobFade=0,this.blobNearSize2=.22,this.blobPulse2=0,this.blobFade2=0,this._rate=.135,this.highlightColor=new H.ov(.98,.98,.98,1),this.highlightWidth=.25,this._highlightTransform=new W.IU(1,1,0,0),this._highlight=1,this.iridescenceIntensity=0,this.iridescenceEdgeIntensity=1,this._angle=-45,this.fadeOut=1,this._reflected=!0,this._frequency=1,this._verticalOffset=0,this.globalLeftIndexTipPosition=W.Pq.Zero(),this._globalLeftIndexTipPosition4=W.IU.Zero(),this.globalRightIndexTipPosition=W.Pq.Zero(),this._globalRightIndexTipPosition4=W.IU.Zero(),this.alphaMode=Il.ALPHA_DISABLE,this.backFaceCulling=!1,this._blobTexture=new vi.g(_V.BLOB_TEXTURE_URL,this.getScene(),!0,!1,vi.g.NEAREST_SAMPLINGMODE),this._iridescentMap=new vi.g(_V.IM_TEXTURE_URL,this.getScene(),!0,!1,vi.g.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new pV);const r=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if((0,Bt.qB)(e,r,!1,!1),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=new Tn;r.FOG&&e.addFallback(1,"FOG"),(0,Bt.c4)(r,e),r.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const i=[st.R.PositionKind];r.NORMAL&&i.push(st.R.NormalKind),r.UV1&&i.push(st.R.UVKind),r.UV2&&i.push(st.R.UV2Kind),r.VERTEXCOLOR&&i.push(st.R.ColorKind),r.TANGENT&&i.push(st.R.TangentKind),(0,Bt.ER)(i,r);const o="fluentBackplate",a=r.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Absolute_Sizes_","_Filter_Width_","_Base_Color_","_Line_Color_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Rate_","_Highlight_Color_","_Highlight_Width_","_Highlight_Transform_","_Highlight_","_Iridescence_Intensity_","_Iridescence_Edge_Intensity_","_Angle_","_Fade_Out_","_Reflected_","_Frequency_","_Vertical_Offset_","_Iridescent_Map_","_Use_Global_Left_Index_","_Use_Global_Right_Index_","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position"],h=["_Blob_Texture_","_Iridescent_Map_"],c=[];(0,Bt.Bb)({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:r,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera?.position??W.Pq.ZeroReadOnly),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Base_Color_",this.baseColor),this._activeEffect.setDirectColor4("_Line_Color_",this.lineColor),this._activeEffect.setFloat("_Radius_Top_Left_",1),this._activeEffect.setFloat("_Radius_Top_Right_",1),this._activeEffect.setFloat("_Radius_Bottom_Left_",1),this._activeEffect.setFloat("_Radius_Bottom_Right_",1),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setFloat("_Rate_",this._rate),this._activeEffect.setDirectColor4("_Highlight_Color_",this.highlightColor),this._activeEffect.setFloat("_Highlight_Width_",this.highlightWidth),this._activeEffect.setVector4("_Highlight_Transform_",this._highlightTransform),this._activeEffect.setFloat("_Highlight_",this._highlight),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setFloat("_Iridescence_Edge_Intensity_",this.iridescenceEdgeIntensity),this._activeEffect.setFloat("_Angle_",this._angle),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._activeEffect.setFloat("_Reflected_",this._reflected?1:0),this._activeEffect.setFloat("_Frequency_",this._frequency),this._activeEffect.setFloat("_Vertical_Offset_",this._verticalOffset),this._activeEffect.setTexture("_Iridescent_Map_",this._iridescentMap),this._activeEffect.setFloat("_Use_Global_Left_Index_",1),this._activeEffect.setFloat("_Use_Global_Right_Index_",1),this._globalLeftIndexTipPosition4.set(this.globalLeftIndexTipPosition.x,this.globalLeftIndexTipPosition.y,this.globalLeftIndexTipPosition.z,1),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this._globalLeftIndexTipPosition4),this._globalRightIndexTipPosition4.set(this.globalRightIndexTipPosition.x,this.globalRightIndexTipPosition.y,this.globalRightIndexTipPosition.z,1),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this._globalRightIndexTipPosition4),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._blobTexture.dispose(),this._iridescentMap.dispose()}clone(e){return it.p.Clone((()=>new _V(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FluentBackplateMaterial",e}getClassName(){return"FluentBackplateMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new _V(e.name,t)),e,t,i)}}_V.BLOB_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-backplate-blob.png",_V.IM_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-backplate-iridescence.png",(0,je.Cg)([(0,$e.lK)()],_V.prototype,"radius",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"lineWidth",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"absoluteSizes",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"baseColor",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"lineColor",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobFarSize",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobNearDistance",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobFarDistance",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobFadeLength",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobNearSize",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobPulse",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobFade",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobNearSize2",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobPulse2",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"blobFade2",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"highlightColor",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"highlightWidth",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"iridescenceIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"iridescenceEdgeIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],_V.prototype,"fadeOut",void 0),(0,je.Cg)([(0,$e.P_)()],_V.prototype,"globalLeftIndexTipPosition",void 0),(0,je.Cg)([(0,$e.P_)()],_V.prototype,"globalRightIndexTipPosition",void 0),(0,X.Y5)("BABYLON.GUI.FluentBackplateMaterial",_V);class mV extends rV{set renderingGroupId(e){this._model.renderingGroupId=e}get renderingGroupId(){return this._model.renderingGroupId}get material(){return this._material}get shareMaterials(){return this._shareMaterials}constructor(e,t=!0){super(e),this._shareMaterials=t}_getTypeName(){return"HolographicBackplate"}_createNode(e){const t=Ko((this.name??"HolographicBackplate")+"_CollisionMesh",{width:1,height:1,depth:1},e);return t.isPickable=!0,t.visibility=0,xg.ImportMeshAsync(void 0,mV.MODEL_BASE_URL,mV.MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.name=`${this.name}_frontPlate`,i.isPickable=!1,i.parent=t,this._material&&(i.material=this._material),this._model=i})),t}_createMaterial(e){this._material=new _V(this.name+" Material",e.getScene())}_affectMaterial(e){this._shareMaterials?this._host._touchSharedMaterials.fluentBackplateMaterial?this._material=this._host._touchSharedMaterials.fluentBackplateMaterial:(this._createMaterial(e),this._host._touchSharedMaterials.fluentBackplateMaterial=this._material):this._createMaterial(e)}dispose(){super.dispose(),this.shareMaterials||this._material.dispose(),this._model.dispose()}}mV.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",mV.MODEL_FILENAME="mrtk-fluent-backplate.glb";class gV extends oV{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}set tooltipText(e){if(e){if(!this._tooltipFade){const e=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=Qi("",{size:1},this._backPlate._scene);const t=Qi("",{size:1,sideOrientation:Yt.DOUBLESIDE},this._backPlate._scene),i=new Un("",this._backPlate._scene);i.diffuseColor=H.v9.FromHexString("#212121"),t.material=i,t.isPickable=!1,this._tooltipMesh.addChild(t),t.position=W.Pq.Forward(e).scale(.05),this._tooltipMesh.scaling.y=1/3,this._tooltipMesh.position=W.Pq.Up().scale(.7).add(W.Pq.Forward(e).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._backPlate,this._tooltipTexture=$B.CreateForMesh(this._tooltipMesh),this._tooltipTextBlock=new dB,this._tooltipTextBlock.scaleY=3,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=130,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new Mi,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)})),this._tooltipOutObserver=this.onPointerOutObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)}))}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}else this._disposeTooltip()}get tooltipText(){return this._tooltipTextBlock?this._tooltipTextBlock.text:null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}constructor(e,t=!0){super(e),this._shareMaterials=!0,this._shareMaterials=t,this.pointerEnterAnimation=()=>{this.mesh&&this._frontPlate.setEnabled(!0)},this.pointerOutAnimation=()=>{this.mesh&&this._frontPlate.setEnabled(!1)}}_getTypeName(){return"HolographicButton"}_rebuildContent(){this._disposeFacadeTexture();const e=new _B;if(e.isVertical=!0,(0,ii.Nf)()&&document.createElement&&this._imageUrl){const t=new fB;t.source=this._imageUrl,t.paddingTop="40px",t.height="180px",t.width="100px",t.paddingBottom="40px",e.addControl(t)}if(this._text){const t=new dB;t.text=this._text,t.color="white",t.height="30px",t.fontSize=24,e.addControl(t)}this._frontPlate&&(this.content=e)}_createNode(e){return this._backPlate=Ko(this.name+"BackMesh",{width:1,height:1,depth:.08},e),this._frontPlate=Ko(this.name+"FrontMesh",{width:1,height:1,depth:.08},e),this._frontPlate.parent=this._backPlate,this._frontPlate.position=W.Pq.Forward(e.useRightHandedSystem).scale(-.08),this._frontPlate.isPickable=!1,this._frontPlate.setEnabled(!1),this._textPlate=super._createNode(e),this._textPlate.parent=this._backPlate,this._textPlate.position=W.Pq.Forward(e.useRightHandedSystem).scale(-.08),this._textPlate.isPickable=!1,this._backPlate}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e}_createBackMaterial(e){this._backMaterial=new uV(this.name+"Back Material",e.getScene()),this._backMaterial.renderHoverLight=!0,this._pickedPointObserver=this._host.onPickedPointChangedObservable.add((e=>{e?(this._backMaterial.hoverPosition=e,this._backMaterial.hoverColor.a=1):this._backMaterial.hoverColor.a=0}))}_createFrontMaterial(e){this._frontMaterial=new uV(this.name+"Front Material",e.getScene()),this._frontMaterial.innerGlowColorIntensity=0,this._frontMaterial.alpha=.5,this._frontMaterial.renderBorders=!0}_createPlateMaterial(e){this._plateMaterial=new Un(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=H.v9.Black()}_affectMaterial(e){this._shareMaterials?(this._host._sharedMaterials.backFluentMaterial?this._backMaterial=this._host._sharedMaterials.backFluentMaterial:(this._createBackMaterial(e),this._host._sharedMaterials.backFluentMaterial=this._backMaterial),this._host._sharedMaterials.frontFluentMaterial?this._frontMaterial=this._host._sharedMaterials.frontFluentMaterial:(this._createFrontMaterial(e),this._host._sharedMaterials.frontFluentMaterial=this._frontMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._frontPlate.material=this._frontMaterial,this._textPlate.material=this._plateMaterial,this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}Cs.l.ShadersStore.fluentButtonPixelShader="uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;uniform float _Edge_Width_;uniform vec4 _Edge_Color_;uniform bool _Relative_Width_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Active_Face_Dir_;uniform vec3 _Active_Face_Up_;uniform bool Enable_Fade;uniform float _Fade_Width_;uniform bool _Smooth_Active_Face_;uniform bool _Show_Frame_;uniform bool _Use_Blob_Texture_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;void Holo_Edge_Fragment_B35(\nvec4 Edges,\nfloat Edge_Width,\nout float NotEdge)\n{vec2 c=vec2(min(Edges.r,Edges.g),min(Edges.b,Edges.a));vec2 df=fwidth(c)*Edge_Width;vec2 g=clamp(c/df,0.0,1.0);NotEdge=g.x*g.y;}\nvoid Blob_Fragment_B39(\nvec2 UV,\nvec3 Blob_Info,\nsampler2D Blob_Texture,\nout vec4 Blob_Color)\n{float k=dot(UV,UV);Blob_Color=Blob_Info.y*texture(Blob_Texture,vec2(vec2(sqrt(k),Blob_Info.x).x,1.0-vec2(sqrt(k),Blob_Info.x).y))*(1.0-clamp(k,0.0,1.0));}\nvec2 FilterStep(vec2 Edge,vec2 X)\n{vec2 dX=max(fwidth(X),vec2(0.00001,0.00001));return clamp( (X+dX-max(Edge,X-dX))/(dX*2.0),0.0,1.0);}\nvoid Wireframe_Fragment_B59(\nvec3 Widths,\nvec2 UV,\nfloat Proximity,\nvec4 Edge_Color,\nout vec4 Wireframe)\n{vec2 c=min(UV,vec2(1.0,1.0)-UV);vec2 g=FilterStep(Widths.xy*0.5,c); \nWireframe=(1.0-min(g.x,g.y))*Proximity*Edge_Color;}\nvoid Proximity_B53(\nvec3 Proximity_Center,\nvec3 Proximity_Center_2,\nfloat Proximity_Max_Intensity,\nfloat Proximity_Near_Radius,\nvec3 Position,\nvec3 Show_Selection,\nvec4 Extra1,\nfloat Dist_To_Face,\nfloat Intensity,\nout float Proximity)\n{vec2 delta1=Extra1.xy;vec2 delta2=Extra1.zw;float d2=sqrt(min(dot(delta1,delta1),dot(delta2,delta2))+Dist_To_Face*Dist_To_Face);Proximity=Intensity*Proximity_Max_Intensity*(1.0-clamp(d2/Proximity_Near_Radius,0.0,1.0))*(1.0-Show_Selection.x)+Show_Selection.x;}\nvoid To_XYZ_B46(\nvec3 Vec3,\nout float X,\nout float Y,\nout float Z)\n{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;}\nvoid main()\n{float NotEdge_Q35;\n#if ENABLE_FADE\nHolo_Edge_Fragment_B35(vColor,_Fade_Width_,NotEdge_Q35);\n#else\nNotEdge_Q35=1.0;\n#endif\nvec4 Blob_Color_Q39;float k=dot(vUV,vUV);vec2 blobTextureCoord=vec2(vec2(sqrt(k),vTangent.x).x,1.0-vec2(sqrt(k),vTangent.x).y);vec4 blobColor=mix(vec4(1.0,1.0,1.0,1.0)*step(1.0-vTangent.x,clamp(sqrt(k)+0.1,0.0,1.0)),texture(_Blob_Texture_,blobTextureCoord),float(_Use_Blob_Texture_));Blob_Color_Q39=vTangent.y*blobColor*(1.0-clamp(k,0.0,1.0));float Is_Quad_Q24;Is_Quad_Q24=vNormal.z;vec3 Blob_Position_Q41= mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(Use_Global_Left_Index));vec3 Blob_Position_Q42= mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(Use_Global_Right_Index));float X_Q46;float Y_Q46;float Z_Q46;To_XYZ_B46(vBinormal,X_Q46,Y_Q46,Z_Q46);float Proximity_Q53;Proximity_B53(Blob_Position_Q41,Blob_Position_Q42,_Proximity_Max_Intensity_,_Proximity_Near_Radius_,vPosition,vBinormal,vExtra1,Y_Q46,Z_Q46,Proximity_Q53);vec4 Wireframe_Q59;Wireframe_Fragment_B59(vNormal,vUV,Proximity_Q53,_Edge_Color_,Wireframe_Q59);vec4 Wire_Or_Blob_Q23=mix(Wireframe_Q59,Blob_Color_Q39,Is_Quad_Q24);vec4 Result_Q22;Result_Q22=mix(Wire_Or_Blob_Q23,vec4(0.3,0.3,0.3,0.3),float(_Show_Frame_));vec4 Final_Color_Q37=NotEdge_Q35*Result_Q22;vec4 Out_Color=Final_Color_Q37;float Clip_Threshold=0.0;bool To_sRGB=false;gl_FragColor=Out_Color;}";Cs.l.ShadersStore.fluentButtonVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform float _Edge_Width_;uniform vec4 _Edge_Color_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Active_Face_Dir_;uniform vec3 _Active_Face_Up_;uniform bool _Enable_Fade_;uniform float _Fade_Width_;uniform bool _Smooth_Active_Face_;uniform bool _Show_Frame_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;void Blob_Vertex_B47(\nvec3 Position,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nvec3 Blob_Position,\nfloat Intensity,\nfloat Blob_Near_Size,\nfloat Blob_Far_Size,\nfloat Blob_Near_Distance,\nfloat Blob_Far_Distance,\nvec4 Vx_Color,\nvec2 UV,\nvec3 Face_Center,\nvec2 Face_Size,\nvec2 In_UV,\nfloat Blob_Fade_Length,\nfloat Selection_Fade,\nfloat Selection_Fade_Size,\nfloat Inner_Fade,\nvec3 Active_Face_Center,\nfloat Blob_Pulse,\nfloat Blob_Fade,\nfloat Blob_Enabled,\nout vec3 Out_Position,\nout vec2 Out_UV,\nout vec3 Blob_Info)\n{float blobSize,fadeIn;vec3 Hit_Position;Blob_Info=vec3(0.0,0.0,0.0);float Hit_Distance=dot(Blob_Position-Face_Center,Normal);Hit_Position=Blob_Position-Hit_Distance*Normal;float absD=abs(Hit_Distance);float lerpVal=clamp((absD-Blob_Near_Distance)/(Blob_Far_Distance-Blob_Near_Distance),0.0,1.0);fadeIn=1.0-clamp((absD-Blob_Far_Distance)/Blob_Fade_Length,0.0,1.0);float innerFade=1.0-clamp(-Hit_Distance/Inner_Fade,0.0,1.0);float farClip=clamp(1.0-step(Blob_Far_Distance+Blob_Fade_Length,absD),0.0,1.0);float size=mix(Blob_Near_Size,Blob_Far_Size,lerpVal)*farClip;blobSize=mix(size,Selection_Fade_Size,Selection_Fade)*innerFade*Blob_Enabled;Blob_Info.x=lerpVal*0.5+0.5;Blob_Info.y=fadeIn*Intensity*(1.0-Selection_Fade)*Blob_Fade;Blob_Info.x*=(1.0-Blob_Pulse);vec3 delta=Hit_Position-Face_Center;vec2 blobCenterXY=vec2(dot(delta,Tangent),dot(delta,Bitangent));vec2 quadUVin=2.0*UV-1.0; \nvec2 blobXY=blobCenterXY+quadUVin*blobSize;vec2 blobClipped=clamp(blobXY,-Face_Size*0.5,Face_Size*0.5);vec2 blobUV=(blobClipped-blobCenterXY)/max(blobSize,0.0001)*2.0;vec3 blobCorner=Face_Center+blobClipped.x*Tangent+blobClipped.y*Bitangent;Out_Position=mix(Position,blobCorner,Vx_Color.rrr);Out_UV=mix(In_UV,blobUV,Vx_Color.rr);}\nvec2 ProjectProximity(\nvec3 blobPosition,\nvec3 position,\nvec3 center,\nvec3 dir,\nvec3 xdir,\nvec3 ydir,\nout float vdistance\n)\n{vec3 delta=blobPosition-position;vec2 xy=vec2(dot(delta,xdir),dot(delta,ydir));vdistance=abs(dot(delta,dir));return xy;}\nvoid Proximity_Vertex_B66(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Active_Face_Center,\nvec3 Active_Face_Dir,\nvec3 Position,\nfloat Proximity_Far_Distance,\nfloat Relative_Scale,\nfloat Proximity_Anisotropy,\nvec3 Up,\nout vec4 Extra1,\nout float Distance_To_Face,\nout float Intensity)\n{vec3 Active_Face_Dir_X=normalize(cross(Active_Face_Dir,Up));vec3 Active_Face_Dir_Y=cross(Active_Face_Dir,Active_Face_Dir_X);float distz1,distz2;Extra1.xy=ProjectProximity(Blob_Position,Position,Active_Face_Center,Active_Face_Dir,Active_Face_Dir_X*Proximity_Anisotropy,Active_Face_Dir_Y,distz1)/Relative_Scale;Extra1.zw=ProjectProximity(Blob_Position_2,Position,Active_Face_Center,Active_Face_Dir,Active_Face_Dir_X*Proximity_Anisotropy,Active_Face_Dir_Y,distz2)/Relative_Scale;Distance_To_Face=dot(Active_Face_Dir,Position-Active_Face_Center);Intensity=1.0-clamp(min(distz1,distz2)/Proximity_Far_Distance,0.0,1.0);}\nvoid Holo_Edge_Vertex_B44(\nvec3 Incident,\nvec3 Normal,\nvec2 UV,\nvec3 Tangent,\nvec3 Bitangent,\nbool Smooth_Active_Face,\nfloat Active,\nout vec4 Holo_Edges)\n{float NdotI=dot(Incident,Normal);vec2 flip=(UV-vec2(0.5,0.5));float udot=dot(Incident,Tangent)*flip.x*NdotI;float uval=1.0-float(udot>0.0);float vdot=-dot(Incident,Bitangent)*flip.y*NdotI;float vval=1.0-float(vdot>0.0);float Smooth_And_Active=step(1.0,float(Smooth_Active_Face && Active>0.0));uval=mix(uval,max(1.0,uval),Smooth_And_Active); \nvval=mix(vval,max(1.0,vval),Smooth_And_Active);Holo_Edges=vec4(1.0,1.0,1.0,1.0)-vec4(uval*UV.x,uval*(1.0-UV.x),vval*UV.y,vval*(1.0-UV.y));}\nvoid Object_To_World_Pos_B13(\nvec3 Pos_Object,\nout vec3 Pos_World)\n{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;}\nvoid Choose_Blob_B38(\nvec4 Vx_Color,\nvec3 Position1,\nvec3 Position2,\nbool Blob_Enable_1,\nbool Blob_Enable_2,\nfloat Near_Size_1,\nfloat Near_Size_2,\nfloat Blob_Inner_Fade_1,\nfloat Blob_Inner_Fade_2,\nfloat Blob_Pulse_1,\nfloat Blob_Pulse_2,\nfloat Blob_Fade_1,\nfloat Blob_Fade_2,\nout vec3 Position,\nout float Near_Size,\nout float Inner_Fade,\nout float Blob_Enable,\nout float Fade,\nout float Pulse)\n{Position=Position1*(1.0-Vx_Color.g)+Vx_Color.g*Position2;float b1=float(Blob_Enable_1);float b2=float(Blob_Enable_2);Blob_Enable=b1+(b2-b1)*Vx_Color.g;Pulse=Blob_Pulse_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Pulse_2;Fade=Blob_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Fade_2;Near_Size=Near_Size_1*(1.0-Vx_Color.g)+Vx_Color.g*Near_Size_2;Inner_Fade=Blob_Inner_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Inner_Fade_2;}\nvoid Wireframe_Vertex_B51(\nvec3 Position,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nfloat Edge_Width,\nvec2 Face_Size,\nout vec3 Wire_Vx_Pos,\nout vec2 UV,\nout vec2 Widths)\n{Widths.xy=Edge_Width/Face_Size;float x=dot(Position,Tangent);float y=dot(Position,Bitangent);float dx=0.5-abs(x);float newx=(0.5-dx*Widths.x*2.0)*sign(x);float dy=0.5-abs(y);float newy=(0.5-dy*Widths.y*2.0)*sign(y);Wire_Vx_Pos=Normal*0.5+newx*Tangent+newy*Bitangent;UV.x=dot(Wire_Vx_Pos,Tangent)+0.5;UV.y=dot(Wire_Vx_Pos,Bitangent)+0.5;}\nvec2 ramp2(vec2 start,vec2 end,vec2 x)\n{return clamp((x-start)/(end-start),vec2(0.0,0.0),vec2(1.0,1.0));}\nfloat computeSelection(\nvec3 blobPosition,\nvec3 normal,\nvec3 tangent,\nvec3 bitangent,\nvec3 faceCenter,\nvec2 faceSize,\nfloat selectionFuzz,\nfloat farDistance,\nfloat fadeLength\n)\n{vec3 delta=blobPosition-faceCenter;float absD=abs(dot(delta,normal));float fadeIn=1.0-clamp((absD-farDistance)/fadeLength,0.0,1.0);vec2 blobCenterXY=vec2(dot(delta,tangent),dot(delta,bitangent));vec2 innerFace=faceSize*(1.0-selectionFuzz)*0.5;vec2 selectPulse=ramp2(-faceSize*0.5,-innerFace,blobCenterXY)-ramp2(innerFace,faceSize*0.5,blobCenterXY);return selectPulse.x*selectPulse.y*fadeIn;}\nvoid Selection_Vertex_B48(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Face_Center,\nvec2 Face_Size,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nfloat Selection_Fuzz,\nfloat Selected,\nfloat Far_Distance,\nfloat Fade_Length,\nvec3 Active_Face_Dir,\nout float Show_Selection)\n{float select1=computeSelection(Blob_Position,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float select2=computeSelection(Blob_Position_2,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float Active=max(0.0,dot(Active_Face_Dir,Normal));Show_Selection=mix(max(select1,select2),1.0,Selected)*Active;}\nvoid Proximity_Visibility_B54(\nfloat Selection,\nvec3 Proximity_Center,\nvec3 Proximity_Center_2,\nfloat Input_Width,\nfloat Proximity_Far_Distance,\nfloat Proximity_Radius,\nvec3 Active_Face_Center,\nvec3 Active_Face_Dir,\nout float Width)\n{vec3 boxEdges=(world*vec4(vec3(0.5,0.5,0.5),0.0)).xyz;float boxMaxSize=length(boxEdges);float d1=dot(Proximity_Center-Active_Face_Center,Active_Face_Dir);vec3 blob1=Proximity_Center-d1*Active_Face_Dir;float d2=dot(Proximity_Center_2-Active_Face_Center,Active_Face_Dir);vec3 blob2=Proximity_Center_2-d2*Active_Face_Dir;vec3 delta1=blob1-Active_Face_Center;vec3 delta2=blob2-Active_Face_Center;float dist1=dot(delta1,delta1);float dist2=dot(delta2,delta2);float nearestProxDist=sqrt(min(dist1,dist2));Width=Input_Width*(1.0-step(boxMaxSize+Proximity_Radius,nearestProxDist))*(1.0-step(Proximity_Far_Distance,min(d1,d2))*(1.0-step(0.0001,Selection)));}\nvoid Object_To_World_Dir_B67(\nvec3 Dir_Object,\nout vec3 Dir_World)\n{Dir_World=(world*vec4(Dir_Object,0.0)).xyz;}\nvoid main()\n{vec3 Active_Face_Center_Q49;Active_Face_Center_Q49=(world*vec4(_Active_Face_Dir_*0.5,1.0)).xyz;vec3 Blob_Position_Q41= mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(Use_Global_Left_Index));vec3 Blob_Position_Q42= mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(Use_Global_Right_Index));vec3 Active_Face_Dir_Q64=normalize((world*vec4(_Active_Face_Dir_,0.0)).xyz);float Relative_Scale_Q57;\n#if RELATIVE_WIDTH\nRelative_Scale_Q57=length((world*vec4(vec3(0,1,0),0.0)).xyz);\n#else\nRelative_Scale_Q57=1.0;\n#endif\nvec3 Tangent_World_Q30;Tangent_World_Q30=(world*vec4(tangent,0.0)).xyz;vec3 Binormal_World_Q31;Binormal_World_Q31=(world*vec4((cross(normal,tangent)),0.0)).xyz;vec3 Normal_World_Q60;Normal_World_Q60=(world*vec4(normal,0.0)).xyz;vec3 Result_Q18=0.5*normal;vec3 Dir_World_Q67;Object_To_World_Dir_B67(_Active_Face_Up_,Dir_World_Q67);float Product_Q56=_Edge_Width_*Relative_Scale_Q57;vec3 Normal_World_N_Q29=normalize(Normal_World_Q60);vec3 Tangent_World_N_Q28=normalize(Tangent_World_Q30);vec3 Binormal_World_N_Q32=normalize(Binormal_World_Q31);vec3 Position_Q38;float Near_Size_Q38;float Inner_Fade_Q38;float Blob_Enable_Q38;float Fade_Q38;float Pulse_Q38;Choose_Blob_B38(color,Blob_Position_Q41,Blob_Position_Q42,_Blob_Enable_,_Blob_Enable_2_,_Blob_Near_Size_,_Blob_Near_Size_2_,_Blob_Inner_Fade_,_Blob_Inner_Fade_2_,_Blob_Pulse_,_Blob_Pulse_2_,_Blob_Fade_,_Blob_Fade_2_,Position_Q38,Near_Size_Q38,Inner_Fade_Q38,Blob_Enable_Q38,Fade_Q38,Pulse_Q38);vec3 Face_Center_Q33;Face_Center_Q33=(world*vec4(Result_Q18,1.0)).xyz;vec2 Face_Size_Q50=vec2(length(Tangent_World_Q30),length(Binormal_World_Q31));float Show_Selection_Q48;Selection_Vertex_B48(Blob_Position_Q41,Blob_Position_Q42,Face_Center_Q33,Face_Size_Q50,Normal_World_N_Q29,Tangent_World_N_Q28,Binormal_World_N_Q32,_Selection_Fuzz_,_Selected_,_Selected_Distance_,_Selected_Fade_Length_,Active_Face_Dir_Q64,Show_Selection_Q48);vec3 Normalized_Q72=normalize(Dir_World_Q67);float Active_Q34=max(0.0,dot(Active_Face_Dir_Q64,Normal_World_N_Q29));float Width_Q54;Proximity_Visibility_B54(Show_Selection_Q48,Blob_Position_Q41,Blob_Position_Q42,Product_Q56,_Proximity_Far_Distance_,_Proximity_Near_Radius_,Active_Face_Center_Q49,Active_Face_Dir_Q64,Width_Q54);vec3 Wire_Vx_Pos_Q51;vec2 UV_Q51;vec2 Widths_Q51;Wireframe_Vertex_B51(position,normal,tangent,(cross(normal,tangent)),Width_Q54,Face_Size_Q50,Wire_Vx_Pos_Q51,UV_Q51,Widths_Q51);vec3 Vec3_Q27=vec3(Widths_Q51.x,Widths_Q51.y,color.r);vec3 Pos_World_Q13;Object_To_World_Pos_B13(Wire_Vx_Pos_Q51,Pos_World_Q13);vec3 Incident_Q36=normalize(Pos_World_Q13-cameraPosition);vec3 Out_Position_Q47;vec2 Out_UV_Q47;vec3 Blob_Info_Q47;Blob_Vertex_B47(Pos_World_Q13,Normal_World_N_Q29,Tangent_World_N_Q28,Binormal_World_N_Q32,Position_Q38,_Blob_Intensity_,Near_Size_Q38,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,color,uv,Face_Center_Q33,Face_Size_Q50,UV_Q51,_Blob_Fade_Length_,_Selection_Fade_,_Selection_Fade_Size_,Inner_Fade_Q38,Active_Face_Center_Q49,Pulse_Q38,Fade_Q38,Blob_Enable_Q38,Out_Position_Q47,Out_UV_Q47,Blob_Info_Q47);vec4 Extra1_Q66;float Distance_To_Face_Q66;float Intensity_Q66;Proximity_Vertex_B66(Blob_Position_Q41,Blob_Position_Q42,Active_Face_Center_Q49,Active_Face_Dir_Q64,Pos_World_Q13,_Proximity_Far_Distance_,Relative_Scale_Q57,_Proximity_Anisotropy_,Normalized_Q72,Extra1_Q66,Distance_To_Face_Q66,Intensity_Q66);vec4 Holo_Edges_Q44;Holo_Edge_Vertex_B44(Incident_Q36,Normal_World_N_Q29,uv,Tangent_World_Q30,Binormal_World_Q31,_Smooth_Active_Face_,Active_Q34,Holo_Edges_Q44);vec3 Vec3_Q19=vec3(Show_Selection_Q48,Distance_To_Face_Q66,Intensity_Q66);vec3 Position=Out_Position_Q47;vec2 UV=Out_UV_Q47;vec3 Tangent=Blob_Info_Q47;vec3 Binormal=Vec3_Q19;vec3 Normal=Vec3_Q27;vec4 Extra1=Extra1_Q66;vec4 Color=Holo_Edges_Q44;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;}";class vV extends xn{constructor(){super(),this.RELATIVE_WIDTH=!0,this.ENABLE_FADE=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class xV extends bn{constructor(e,t){super(e,t),this.edgeWidth=.04,this.edgeColor=new H.ov(.592157,.592157,.592157,1),this.proximityMaxIntensity=.45,this.proximityFarDistance=.16,this.proximityNearRadius=1.5,this.proximityAnisotropy=1,this.selectionFuzz=.5,this.selected=0,this.selectionFade=0,this.selectionFadeSize=.3,this.selectedDistance=.08,this.selectedFadeLength=.08,this.blobIntensity=.5,this.blobFarSize=.05,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.08,this.leftBlobEnable=!0,this.leftBlobNearSize=.025,this.leftBlobPulse=0,this.leftBlobFade=1,this.leftBlobInnerFade=.01,this.rightBlobEnable=!0,this.rightBlobNearSize=.025,this.rightBlobPulse=0,this.rightBlobFade=1,this.rightBlobInnerFade=.01,this.activeFaceDir=new W.Pq(0,0,-1),this.activeFaceUp=new W.Pq(0,1,0),this.enableFade=!0,this.fadeWidth=1.5,this.smoothActiveFace=!0,this.showFrame=!1,this.useBlobTexture=!0,this.globalLeftIndexTipPosition=W.Pq.Zero(),this.globalRightIndexTipPosition=W.Pq.Zero(),this.alphaMode=Il.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1,this._blobTexture=new vi.g(xV.BLOB_TEXTURE_URL,this.getScene(),!0,!1,vi.g.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!0}needAlphaTesting(){return!0}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new vV);const r=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if((0,Bt.qB)(e,r,!0,!1),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=new Tn;r.FOG&&e.addFallback(1,"FOG"),(0,Bt.c4)(r,e),r.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const i=[st.R.PositionKind];r.NORMAL&&i.push(st.R.NormalKind),r.UV1&&i.push(st.R.UVKind),r.UV2&&i.push(st.R.UV2Kind),r.VERTEXCOLOR&&i.push(st.R.ColorKind),r.TANGENT&&i.push(st.R.TangentKind),(0,Bt.ER)(i,r);const o="fluentButton",a=r.toString(),l=["world","viewProjection","cameraPosition","_Edge_Width_","_Edge_Color_","_Relative_Width_","_Proximity_Max_Intensity_","_Proximity_Far_Distance_","_Proximity_Near_Radius_","_Proximity_Anisotropy_","_Selection_Fuzz_","_Selected_","_Selection_Fade_","_Selection_Fade_Size_","_Selected_Distance_","_Selected_Fade_Length_","_Blob_Enable_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Inner_Fade_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Enable_2_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Inner_Fade_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Active_Face_Dir_","_Active_Face_Up_","_Enable_Fade_","_Fade_Width_","_Smooth_Active_Face_","_Show_Frame_","_Use_Blob_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],h=["_Blob_Texture_"],c=[];(0,Bt.Bb)({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:r,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const r=this.getScene();if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",r.activeCamera.position),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Edge_Width_",this.edgeWidth),this._activeEffect.setColor4("_Edge_Color_",new H.v9(this.edgeColor.r,this.edgeColor.g,this.edgeColor.b),this.edgeColor.a),this._activeEffect.setFloat("_Proximity_Max_Intensity_",this.proximityMaxIntensity),this._activeEffect.setFloat("_Proximity_Far_Distance_",this.proximityFarDistance),this._activeEffect.setFloat("_Proximity_Near_Radius_",this.proximityNearRadius),this._activeEffect.setFloat("_Proximity_Anisotropy_",this.proximityAnisotropy),this._activeEffect.setFloat("_Selection_Fuzz_",this.selectionFuzz),this._activeEffect.setFloat("_Selected_",this.selected),this._activeEffect.setFloat("_Selection_Fade_",this.selectionFade),this._activeEffect.setFloat("_Selection_Fade_Size_",this.selectionFadeSize),this._activeEffect.setFloat("_Selected_Distance_",this.selectedDistance),this._activeEffect.setFloat("_Selected_Fade_Length_",this.selectedFadeLength),this._activeEffect.setFloat("_Blob_Enable_",this.leftBlobEnable?1:0),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.leftBlobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Inner_Fade_",this.leftBlobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_",this.leftBlobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.leftBlobFade),this._activeEffect.setFloat("_Blob_Enable_2_",this.rightBlobEnable?1:0),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.rightBlobNearSize),this._activeEffect.setFloat("_Blob_Inner_Fade_2_",this.rightBlobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_2_",this.rightBlobPulse),this._activeEffect.setFloat("_Blob_Fade_2_",this.rightBlobFade),this._activeEffect.setVector3("_Active_Face_Dir_",this.activeFaceDir),this._activeEffect.setVector3("_Active_Face_Up_",this.activeFaceUp),this._activeEffect.setFloat("_Fade_Width_",this.fadeWidth),this._activeEffect.setFloat("_Smooth_Active_Face_",this.smoothActiveFace?1:0),this._activeEffect.setFloat("_Show_Frame_",this.showFrame?1:0),this._activeEffect.setFloat("_Use_Blob_Texture_",this.useBlobTexture?1:0),this._activeEffect.setFloat("Use_Global_Left_Index",1),this._activeEffect.setFloat("Use_Global_Right_Index",1),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",new W.IU(this.globalLeftIndexTipPosition.x,this.globalLeftIndexTipPosition.y,this.globalLeftIndexTipPosition.z,1)),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",new W.IU(this.globalRightIndexTipPosition.x,this.globalRightIndexTipPosition.y,this.globalRightIndexTipPosition.z,1)),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return it.p.Clone((()=>new xV(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FluentButtonMaterial",e}getClassName(){return"FluentButtonMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new xV(e.name,t)),e,t,i)}}xV.BLOB_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-button-blob.png",(0,je.Cg)([(0,$e.lK)()],xV.prototype,"edgeWidth",void 0),(0,je.Cg)([(0,$e.qK)()],xV.prototype,"edgeColor",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"proximityMaxIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"proximityFarDistance",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"proximityNearRadius",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"proximityAnisotropy",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"selectionFuzz",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"selected",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"selectionFade",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"selectionFadeSize",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"selectedDistance",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"selectedFadeLength",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"blobIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"blobFarSize",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"blobNearDistance",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"blobFarDistance",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"blobFadeLength",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"leftBlobEnable",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"leftBlobNearSize",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"leftBlobPulse",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"leftBlobFade",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"leftBlobInnerFade",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"rightBlobEnable",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"rightBlobNearSize",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"rightBlobPulse",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"rightBlobFade",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"rightBlobInnerFade",void 0),(0,je.Cg)([(0,$e.P_)()],xV.prototype,"activeFaceDir",void 0),(0,je.Cg)([(0,$e.P_)()],xV.prototype,"activeFaceUp",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"enableFade",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"fadeWidth",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"smoothActiveFace",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"showFrame",void 0),(0,je.Cg)([(0,$e.lK)()],xV.prototype,"useBlobTexture",void 0),(0,je.Cg)([(0,$e.P_)()],xV.prototype,"globalLeftIndexTipPosition",void 0),(0,je.Cg)([(0,$e.P_)()],xV.prototype,"globalRightIndexTipPosition",void 0),(0,X.Y5)("BABYLON.GUI.FluentButtonMaterial",xV);class bV extends oV{constructor(e,t){super(e),this._isNearPressed=!1,this._interactionSurfaceHeight=0,this._isToggleButton=!1,this._toggleState=!1,this._toggleButtonCallback=()=>{this._onToggle(!this._toggleState)},this.onToggleObservable=new z.cP,this.collidableFrontDirection=W.Pq.Zero(),t&&(this.collisionMesh=t)}get isActiveNearInteraction(){return this._isNearPressed}set collidableFrontDirection(e){if(this._collidableFrontDirection=e.normalize(),this._collisionMesh){const e=W.AA.Matrix[0];e.copyFrom(this._collisionMesh.getWorldMatrix()),e.invert(),W.Pq.TransformNormalToRef(this._collidableFrontDirection,e,this._collidableFrontDirection),this._collidableFrontDirection.normalize()}}get collidableFrontDirection(){if(this._collisionMesh){const e=W.AA.Vector3[0];return W.Pq.TransformNormalToRef(this._collidableFrontDirection,this._collisionMesh.getWorldMatrix(),e),e.normalize()}return this._collidableFrontDirection}set collisionMesh(e){this._collisionMesh&&(this._collisionMesh.isNearPickable=!1,this._collisionMesh.reservedDataStore?.GUI3D&&(this._collisionMesh.reservedDataStore.GUI3D={}),this._collisionMesh.getChildMeshes().forEach((e=>{e.isNearPickable=!1,e.reservedDataStore?.GUI3D&&(e.reservedDataStore.GUI3D={})}))),this._collisionMesh=e,this._injectGUI3DReservedDataStore(this._collisionMesh).control=this,this._collisionMesh.isNearPickable=!0,this._collisionMesh.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this,e.isNearPickable=!0})),this.collidableFrontDirection=e.forward}set isToggleButton(e){e!==this._isToggleButton&&(this._isToggleButton=e,e?this.onPointerUpObservable.add(this._toggleButtonCallback):(this.onPointerUpObservable.removeCallback(this._toggleButtonCallback),this._toggleState&&this._onToggle(!1)))}get isToggleButton(){return this._isToggleButton}set isToggled(e){this._isToggleButton&&this._toggleState!==e&&this._onToggle(e)}get isToggled(){return this._toggleState}_onToggle(e){this._toggleState=e,this.onToggleObservable.notifyObservers(e)}_isInteractionInFrontOfButton(e){return this._getInteractionHeight(e,this._collisionMesh.getAbsolutePosition())>0}getPressDepth(e){if(!this._isNearPressed)return 0;const t=this._getInteractionHeight(e,this._collisionMesh.getAbsolutePosition());return this._interactionSurfaceHeight-t}_getInteractionHeight(e,t){const i=this.collidableFrontDirection;if(0===i.length())return W.Pq.Distance(e,t);const r=W.Pq.Dot(t,i);return W.Pq.Dot(e,i)-r}_generatePointerEventType(e,t,i){if(e===yi.Zp.POINTERDOWN||e===yi.Zp.POINTERMOVE){if(!this._isInteractionInFrontOfButton(t))return yi.Zp.POINTERMOVE;this._isNearPressed=!0,this._interactionSurfaceHeight=this._getInteractionHeight(t,this._collisionMesh.getAbsolutePosition())}if(e===yi.Zp.POINTERUP){if(0==i)return yi.Zp.POINTERMOVE;this._isNearPressed=!1}return e}_getTypeName(){return"TouchButton3D"}_createNode(e){return super._createNode(e)}dispose(){super.dispose(),this.onPointerUpObservable.removeCallback(this._toggleButtonCallback),this.onToggleObservable.clear(),this._collisionMesh&&this._collisionMesh.dispose()}}class SV extends bV{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}get mesh(){return this._backPlate}set tooltipText(e){if(e){if(!this._tooltipFade){const e=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=Qi("",{size:1},this._backPlate._scene);const t=Qi("",{size:1,sideOrientation:Yt.DOUBLESIDE},this._backPlate._scene),i=new Un("",this._backPlate._scene);i.diffuseColor=H.v9.FromHexString("#212121"),t.material=i,t.isPickable=!1,this._tooltipMesh.addChild(t),t.position=W.Pq.Forward(e).scale(.05),this._tooltipMesh.scaling.y=1/3,this._tooltipMesh.position=W.Pq.Up().scale(.7).add(W.Pq.Forward(e).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._backPlate,this._tooltipTexture=$B.CreateForMesh(this._tooltipMesh),this._tooltipTextBlock=new dB,this._tooltipTextBlock.scaleY=3,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=130,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new Mi,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)})),this._tooltipOutObserver=this.onPointerOutObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)}))}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}else this._disposeTooltip()}get tooltipText(){return this._tooltipTextBlock?this._tooltipTextBlock.text:null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}set isBackplateVisible(e){this.mesh&&this._backMaterial&&(e&&!this._isBackplateVisible?this._backPlate.visibility=1:!e&&this._isBackplateVisible&&(this._backPlate.visibility=0)),this._isBackplateVisible=e}constructor(e,t=!0){super(e),this._shareMaterials=!0,this._isBackplateVisible=!0,this._frontPlateDepth=.5,this._backPlateDepth=.04,this._backplateColor=new H.v9(.08,.15,.55),this._backplateToggledColor=new H.v9(.25,.4,.95),this._shareMaterials=t,this.pointerEnterAnimation=()=>{this._frontMaterial.leftBlobEnable=!0,this._frontMaterial.rightBlobEnable=!0},this.pointerOutAnimation=()=>{this._frontMaterial.leftBlobEnable=!1,this._frontMaterial.rightBlobEnable=!1},this.pointerDownAnimation=()=>{this._frontPlate&&!this.isActiveNearInteraction&&(this._frontPlate.scaling.z=.2*this._frontPlateDepth,this._frontPlate.position=W.Pq.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-.2*this._frontPlateDepth)/2),this._textPlate.position=W.Pq.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+.2*this._frontPlateDepth)/2))},this.pointerUpAnimation=()=>{this._frontPlate&&(this._frontPlate.scaling.z=this._frontPlateDepth,this._frontPlate.position=W.Pq.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-this._frontPlateDepth)/2),this._textPlate.position=W.Pq.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+this._frontPlateDepth)/2))},this.onPointerMoveObservable.add((e=>{if(this._frontPlate&&this.isActiveNearInteraction){const t=W.Pq.Zero();if(this._backPlate.getWorldMatrix().decompose(t,void 0,void 0)){let i=this._getInteractionHeight(e,this._backPlate.getAbsolutePosition())/t.z;i=Gy.Clamp(i-this._backPlateDepth/2,.2*this._frontPlateDepth,this._frontPlateDepth),this._frontPlate.scaling.z=i,this._frontPlate.position=W.Pq.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-i)/2),this._textPlate.position=W.Pq.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+i)/2)}}})),this._pointerHoverObserver=this.onPointerMoveObservable.add((e=>{this._frontMaterial.globalLeftIndexTipPosition=e}))}_getTypeName(){return"TouchHolographicButton"}_rebuildContent(){this._disposeFacadeTexture();const e=new _B;if(e.isVertical=!0,(0,ii.Nf)()&&document.createElement&&this._imageUrl){const t=new fB;t.source=this._imageUrl,t.paddingTop="40px",t.height="180px",t.width="100px",t.paddingBottom="40px",e.addControl(t)}if(this._text){const t=new dB;t.text=this._text,t.color="white",t.height="30px",t.fontSize=24,e.addControl(t)}this.content=e}_createNode(e){this.name=this.name??"TouchHolographicButton";const t=Ko(`${this.name}_collisionMesh`,{width:1,height:1,depth:this._frontPlateDepth},e);t.isPickable=!0,t.isNearPickable=!0,t.visibility=0,t.position=W.Pq.Forward(e.useRightHandedSystem).scale(-this._frontPlateDepth/2),xg.ImportMeshAsync(void 0,SV.MODEL_BASE_URL,SV.MODEL_FILENAME,e).then((i=>{const r=Ko("${this.name}_alphaMesh",{width:1,height:1,depth:1},e);r.isPickable=!1,r.material=new Un("${this.name}_alphaMesh_material",e),r.material.alpha=.15;const s=i.meshes[1];s.name=`${this.name}_frontPlate`,s.isPickable=!1,s.scaling.z=this._frontPlateDepth,r.parent=s,s.parent=t,this._frontMaterial&&(s.material=this._frontMaterial),this._frontPlate=s})),this._backPlate=Ko(`${this.name}_backPlate`,{width:1,height:1,depth:this._backPlateDepth},e),this._backPlate.position=W.Pq.Forward(e.useRightHandedSystem).scale(this._backPlateDepth/2),this._backPlate.isPickable=!1,this._textPlate=super._createNode(e),this._textPlate.name=`${this.name}_textPlate`,this._textPlate.isPickable=!1,this._textPlate.position=W.Pq.Forward(e.useRightHandedSystem).scale(-this._frontPlateDepth/2),this._backPlate.addChild(t),this._backPlate.addChild(this._textPlate);const i=new Pt("{this.name}_root",e);return this._backPlate.setParent(i),this.collisionMesh=t,this.collidableFrontDirection=this._backPlate.forward.negate(),i}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e,this._plateMaterial.diffuseColor=new H.v9(.4,.4,.4)}_createBackMaterial(e){this._backMaterial=new uV(this.name+"backPlateMaterial",e.getScene()),this._backMaterial.albedoColor=this._backplateColor,this._backMaterial.renderBorders=!0,this._backMaterial.renderHoverLight=!1}_createFrontMaterial(e){this._frontMaterial=new xV(this.name+"Front Material",e.getScene())}_createPlateMaterial(e){this._plateMaterial=new Un(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=H.v9.Black()}_onToggle(e){this._backMaterial&&(this._backMaterial.albedoColor=e?this._backplateToggledColor:this._backplateColor),super._onToggle(e)}_affectMaterial(e){this._shareMaterials?(this._host._touchSharedMaterials.backFluentMaterial?this._backMaterial=this._host._touchSharedMaterials.backFluentMaterial:(this._createBackMaterial(e),this._host._touchSharedMaterials.backFluentMaterial=this._backMaterial),this._host._touchSharedMaterials.frontFluentMaterial?this._frontMaterial=this._host._touchSharedMaterials.frontFluentMaterial:(this._createFrontMaterial(e),this._host._touchSharedMaterials.frontFluentMaterial=this._frontMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._textPlate.material=this._plateMaterial,this._isBackplateVisible||(this._backPlate.visibility=0),this._frontPlate&&(this._frontPlate.material=this._frontMaterial),this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.onPointerMoveObservable.remove(this._pointerHoverObserver),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}SV.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",SV.MODEL_FILENAME="mrtk-fluent-button.glb";class TV{constructor(){this.followBehaviorEnabled=!1,this.sixDofDragBehaviorEnabled=!0,this.surfaceMagnetismBehaviorEnabled=!0,this._followBehavior=new lr,this._sixDofDragBehavior=new ir,this._surfaceMagnetismBehavior=new rr}get name(){return"Default"}get followBehavior(){return this._followBehavior}get sixDofDragBehavior(){return this._sixDofDragBehavior}get surfaceMagnetismBehavior(){return this._surfaceMagnetismBehavior}init(){}attach(e,t,i){this._scene=e.getScene(),this.attachedNode=e,this._addObservables(),this._followBehavior.attach(e),this._sixDofDragBehavior.attach(e),this._sixDofDragBehavior.draggableMeshes=t||null,this._sixDofDragBehavior.faceCameraOnDragStart=!0,this._surfaceMagnetismBehavior.attach(e,this._scene),i&&(this._surfaceMagnetismBehavior.meshes=i),this._surfaceMagnetismBehavior.enabled=!1}detach(){this.attachedNode=null,this._removeObservables(),this._followBehavior.detach(),this._sixDofDragBehavior.detach(),this._surfaceMagnetismBehavior.detach()}_addObservables(){this._onBeforeRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{this._followBehavior._enabled=!this._sixDofDragBehavior.isMoving&&this.followBehaviorEnabled})),this._onDragObserver=this._sixDofDragBehavior.onDragObservable.add((e=>{this._sixDofDragBehavior.disableMovement=this._surfaceMagnetismBehavior.findAndUpdateTarget(e.pickInfo)}))}_removeObservables(){this._scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._sixDofDragBehavior.onDragObservable.remove(this._onDragObserver)}}Cs.l.ShadersStore.handleVertexShader="precision highp float;attribute vec3 position;uniform vec3 positionOffset;uniform mat4 worldViewProjection;uniform float scale;void main(void) {vec4 vPos=vec4((vec3(position)+positionOffset)*scale,1.0);gl_Position=worldViewProjection*vPos;}";Cs.l.ShadersStore.handlePixelShader="uniform vec3 color;void main(void) {gl_FragColor=vec4(color,1.0);}";class CV extends xo{get hover(){return this._hover}set hover(e){this._hover=e,this._updateInterpolationTarget()}get drag(){return this._drag}set drag(e){this._drag=e,this._updateInterpolationTarget()}constructor(e,t){super(e,t,"handle",{attributes:["position"],uniforms:["worldViewProjection","color","scale","positionOffset"],needAlphaBlending:!1,needAlphaTesting:!1}),this._hover=!1,this._drag=!1,this._color=new H.v9,this._scale=1,this._lastTick=-1,this.animationLength=100,this.hoverColor=new H.v9(0,.467,.84),this.baseColor=new H.v9(1,1,1),this.hoverScale=.75,this.baseScale=.35,this.dragScale=.55,this._positionOffset=W.Pq.Zero(),this._updateInterpolationTarget(),this._lastTick=Date.now(),this._onBeforeRender=this.getScene().onBeforeRenderObservable.add((()=>{const e=Date.now(),t=e-this._lastTick,i=this._targetScale-this._scale,r=H.IG.Color3[0].copyFrom(this._targetColor).subtractToRef(this._color,H.IG.Color3[0]);this._scale=this._scale+i*t/this.animationLength,r.scaleToRef(t/this.animationLength,r),this._color.addToRef(r,this._color),this.setColor3("color",this._color),this.setFloat("scale",this._scale),this.setVector3("positionOffset",this._positionOffset),this._lastTick=e}))}_updateInterpolationTarget(){this.drag?(this._targetColor=this.hoverColor,this._targetScale=this.dragScale):this.hover?(this._targetColor=this.hoverColor,this._targetScale=this.hoverScale):(this._targetColor=this.baseColor,this._targetScale=this.baseScale)}dispose(){super.dispose(),this.getScene().onBeforeRenderObservable.remove(this._onBeforeRender)}}var yV;!function(e){e[e.IDLE=0]="IDLE",e[e.HOVER=1]="HOVER",e[e.DRAG=2]="DRAG"}(yV||(yV={}));class EV{get state(){return this._state}get gizmo(){return this._gizmo}set hover(e){e?this._state|=1:this._state&=-2,this._updateMaterial()}set drag(e){e?this._state|=2:this._state&=-3,this._updateMaterial()}constructor(e,t){this._state=0,this._materials=[],this._scene=t,this._gizmo=e,this.node=this.createNode(),this.node.reservedDataStore={handle:this}}_createMaterial(e){const t=new CV("handle",this._scene);return e&&(t._positionOffset=e),t}_updateMaterial(){const e=this._state;for(const e of this._materials)e.hover=!1,e.drag=!1;if(2&e)for(const e of this._materials)e.drag=!0;else if(1&e)for(const e of this._materials)e.hover=!0}setDragBehavior(e,t,i){const r=new tr;this._dragBehavior=r,this._dragStartObserver=r.onDragStartObservable.add(e),this._draggingObserver=r.onDragObservable.add(t),this._dragEndObserver=r.onDragEndObservable.add(i),this._dragBehavior.attach(this.node)}dispose(){this._dragBehavior.onDragStartObservable.remove(this._dragStartObserver),this._dragBehavior.onDragObservable.remove(this._draggingObserver),this._dragBehavior.onDragEndObservable.remove(this._dragEndObserver),this._dragBehavior.detach();for(const e of this._materials)e.dispose();this.node.dispose()}}class PV extends EV{createNode(){const e=Ko("sideVert",{width:1,height:10,depth:.1},this._scene),t=new Pt("side",this._scene);e.parent=t;const i=this._createMaterial();return e.material=i,e.isNearGrabbable=!0,this._materials.push(i),t}}class AV extends EV{createNode(){const e=Ko("angleHor",{width:3,height:1,depth:.1},this._scene),t=Ko("angleVert",{width:1,height:3,depth:.1},this._scene),i=new Pt("angle",this._scene);return e.parent=i,t.parent=i,e.material=this._createMaterial(new W.Pq(1,0,0)),t.material=this._createMaterial(new W.Pq(0,1,0)),t.isNearGrabbable=!0,e.isNearGrabbable=!0,this._materials.push(e.material),this._materials.push(t.material),i}}class RV extends Go{set attachedSlate(e){e?(this.attachedMesh=e.mesh,this.updateBoundingBox(),this._pickedPointObserver=e._host.onPickingObservable.add((e=>{if(!this._handleHovered||e&&e.parent===this._handleHovered.node||(this._handleHovered.hover=!1,this._handleHovered=null),e&&e.parent&&e.parent.reservedDataStore&&e.parent.reservedDataStore.handle){const t=e.parent.reservedDataStore.handle;t.gizmo===this&&(this._handleHovered=t,this._handleHovered.hover=!0)}}))):this._attachedSlate&&this._attachedSlate._host.onPickingObservable.remove(this._pickedPointObserver),this._attachedSlate=e}get attachedSlate(){return this._attachedSlate}constructor(e){super(e),this._boundingDimensions=new W.Pq(0,0,0),this._renderObserver=null,this._tmpQuaternion=new W.PT,this._tmpVector=new W.Pq(0,0,0),this._corners=[],this._sides=[],this._boundingBoxGizmo={min:new W.Pq,max:new W.Pq},this._margin=.35,this._handleSize=.075,this._attachedSlate=null,this._existingSlateScale=new W.Pq,this.fixedScreenSize=!1,this.fixedScreenSizeDistanceFactor=10,this._createNode(),this.updateScale=!1,this._renderObserver=this.gizmoLayer.originalScene.onBeforeRenderObservable.add((()=>{this.attachedMesh&&!this._existingSlateScale.equals(this.attachedMesh.scaling)&&this.updateBoundingBox()}))}_createNode(){this._handlesParent=new Pt("handlesParent",this.gizmoLayer.utilityLayerScene),this._handlesParent.rotationQuaternion=W.PT.Identity();const e=[{dimensions:new W.Pq(-1,-1,0),origin:new W.Pq(1,0,0)},{dimensions:new W.Pq(1,-1,0),origin:new W.Pq(0,0,0)},{dimensions:new W.Pq(1,1,0),origin:new W.Pq(0,1,0)},{dimensions:new W.Pq(-1,1,0),origin:new W.Pq(1,1,0)}];for(let t=0;t<4;t++){const i=new AV(this,this.gizmoLayer.utilityLayerScene);this._corners.push(i),i.node.rotation.z=Math.PI/2*t,i.node.parent=this._handlesParent,this._assignDragBehaviorCorners(i,((e,t,i,r)=>this._moveHandle(e,t,i,r,!0)),e[t])}for(let e=0;e<4;e++){const t=new PV(this,this.gizmoLayer.utilityLayerScene);this._sides.push(t),t.node.rotation.z=Math.PI/2*e,t.node.parent=this._handlesParent,this._assignDragBehaviorSides(t,e%2==0?new W.Pq(0,1,0):new W.Pq(1,0,0))}this._handlesParent.parent=this._rootMesh}_keepAspectRatio(e,t,i=!1){const r=W.AA.Vector3[0];r.copyFromFloats(t,1,0).normalize(),i&&(r.y*=-1);const s=W.Pq.Dot(e,r);e.copyFrom(r).scaleInPlace(s)}_clampDimensions(e,t,i,r=!1){const s=W.AA.Vector3[0];s.copyFrom(e).multiplyInPlace(i);const n=W.AA.Vector3[1];if(n.copyFromFloats(Math.max(this._attachedSlate.minDimensions.x,s.x+t.x),Math.max(this._attachedSlate.minDimensions.y,s.y+t.y),0),r){const e=t.x/t.y;n.x=Math.max(n.x,n.y*e),n.y=Math.max(n.y,n.x/e)}s.copyFrom(n).subtractInPlace(t),e.x=Math.sign(e.x)*Math.abs(s.x),e.y=Math.sign(e.y)*Math.abs(s.y)}_moveHandle(e,t,i,r,s){if(!this._attachedSlate)return;if(s){const e=t.x/t.y;this._keepAspectRatio(i,e,r.dimensions.x*r.dimensions.y<0)}this._clampDimensions(i,t,r.dimensions,s);const n=W.AA.Vector3[0],o=W.AA.Vector3[1];n.copyFrom(i).multiplyInPlace(r.origin),o.copyFrom(i).multiplyInPlace(r.dimensions),this._attachedSlate.origin.copyFrom(e).addInPlace(n),this._attachedSlate.dimensions.set(t.x+o.x,t.y+o.y)}_assignDragBehaviorCorners(e,t,i){const r=new W.Pq,s=new W.Pq,n=new W.Pq,o=new W.uq,a=new W.Pq;e.setDragBehavior((e=>{this.attachedSlate&&this.attachedMesh&&(r.set(this.attachedSlate.dimensions.x,this.attachedSlate.dimensions.y,lt.bH),s.copyFrom(this.attachedSlate.origin),n.copyFrom(e.position),o.copyFrom(this.attachedMesh.computeWorldMatrix(!0)),o.invert(),this.attachedSlate._followButton.isToggled=!1,W.Pq.TransformNormalToRef(W.Pq.Forward(),this.attachedMesh.getWorldMatrix(),a),a.normalize(),this._handleHovered&&(this._handleDragged=this._handleHovered,this._handleDragged.drag=!0))}),(e=>{this.attachedSlate&&this.attachedMesh&&(((e,t,i,r)=>{e.subtractToRef(i,W.AA.Vector3[0]);const s=W.Pq.Dot(W.AA.Vector3[0],t);W.AA.Vector3[1].copyFrom(t).scaleInPlace(s),W.AA.Vector3[0].subtractInPlace(W.AA.Vector3[1]),W.AA.Vector3[0].addToRef(i,r)})(e.position,a,n,this._tmpVector),this._tmpVector.subtractInPlace(n),W.Pq.TransformNormalToRef(this._tmpVector,o,this._tmpVector),t(s,r,this._tmpVector,i),this.attachedSlate._positionElements(),this.updateBoundingBox())}),(()=>{this.attachedSlate&&this.attachedNode&&(this.attachedSlate._updatePivot(),this._handleDragged&&(this._handleDragged.drag=!1,this._handleDragged=null))}))}_assignDragBehaviorSides(e,t){const i=new W.PT,r=new W.Pq,s=new W.Pq,n=new W.Pq,o=new W.Pq;e.setDragBehavior((e=>{this.attachedSlate&&this.attachedMesh&&(i.copyFrom(this.attachedMesh.rotationQuaternion),r.copyFrom(e.position),n.copyFrom(this.attachedMesh.getAbsolutePivotPoint()),s.copyFrom(r).subtractInPlace(n).normalize(),this.attachedSlate._followButton.isToggled=!1,W.Pq.TransformNormalToRef(t,this.attachedMesh.getWorldMatrix(),o),o.normalize(),this._handleHovered&&(this._handleDragged=this._handleHovered,this._handleDragged.drag=!0))}),(e=>{if(this.attachedSlate&&this.attachedMesh){this._tmpVector.copyFrom(e.position),this._tmpVector.subtractInPlace(n),this._tmpVector.normalize();const r=-W.Pq.GetAngleBetweenVectorsOnPlane(this._tmpVector,s,o);W.PT.RotationAxisToRef(t,r,this._tmpQuaternion),i.multiplyToRef(this._tmpQuaternion,this.attachedMesh.rotationQuaternion)}}),(()=>{this.attachedSlate&&this.attachedNode&&(this.attachedSlate._updatePivot(),this._handleDragged&&(this._handleDragged.drag=!1,this._handleDragged=null))}))}_attachedNodeChanged(e){e&&this.updateBoundingBox()}updateBoundingBox(){if(this.attachedMesh){ji._RemoveAndStorePivotPoint(this.attachedMesh);const e=this.attachedMesh.parent;this.attachedMesh.setParent(null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=W.PT.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);const t=this.attachedMesh.getHierarchyBoundingVectors();t.max.subtractToRef(t.min,this._boundingDimensions),this._boundingBoxGizmo.min=t.min,this._boundingBoxGizmo.max=t.max,this._updateHandlesPosition(),this._updateHandlesScaling(),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),ji._RestorePivotPoint(this.attachedMesh),this.attachedMesh.setParent(e),this.attachedMesh.computeWorldMatrix(!0),this._existingSlateScale.copyFrom(this.attachedMesh.scaling)}}_updateHandlesPosition(){const e=this._boundingBoxGizmo.min.clone(),t=this._boundingBoxGizmo.max.clone(),i=this._corners[0].node.scaling.length();e.x-=this._margin*i,e.y-=this._margin*i,t.x+=this._margin*i,t.y+=this._margin*i;const r=e.add(t).scaleInPlace(.5);this._corners[0].node.position.copyFromFloats(e.x,e.y,0),this._corners[1].node.position.copyFromFloats(t.x,e.y,0),this._corners[2].node.position.copyFromFloats(t.x,t.y,0),this._corners[3].node.position.copyFromFloats(e.x,t.y,0),this._sides[0].node.position.copyFromFloats(e.x,r.y,0),this._sides[1].node.position.copyFromFloats(r.x,e.y,0),this._sides[2].node.position.copyFromFloats(t.x,r.y,0),this._sides[3].node.position.copyFromFloats(r.x,t.y,0)}_updateHandlesScaling(){if(this._attachedSlate&&this._attachedSlate.mesh){const e=this._attachedSlate.mesh.scaling.x*this._attachedSlate.dimensions.x,t=this._attachedSlate.mesh.scaling.y*this._attachedSlate.dimensions.y,i=Math.min(e,t)*this._handleSize;for(let e=0;ei?this.minDimensions.x/e.x:this.minDimensions.y/e.y}this._dimensions.copyFrom(e).scaleInPlace(t),this._updatePivot(),this._positionElements()}get titleBarHeight(){return this._titleBarHeight}set titleBarHeight(e){this._titleBarHeight=e}set renderingGroupId(e){this._titleBar.renderingGroupId=e,this._titleBarTitle.renderingGroupId=e,this._contentPlate.renderingGroupId=e,this._backPlate.renderingGroupId=e}get renderingGroupId(){return this._titleBar.renderingGroupId}set title(e){this._titleText=e,this._titleTextComponent&&(this._titleTextComponent.text=e)}get title(){return this._titleText}constructor(e){super(e),this.titleBarMargin=.005,this.origin=new W.Pq(0,0,0),this._dimensions=new W.I9(21.875,12.5),this._titleBarHeight=.625,this._titleText="",this.fitContentToDimensions=!1,this._contentScaleRatio=1,this.minDimensions=new W.I9(15.625,6.25),this.defaultDimensions=this._dimensions.clone(),this._followButton=new SV("followButton"+this.name),this._followButton.isToggleButton=!0,this._closeButton=new SV("closeButton"+this.name),this._contentViewport=new et.L(0,0,1,1),this._contentDragBehavior=new Ji({dragPlaneNormal:new W.Pq(0,0,-1)})}_applyFacade(e){this._contentMaterial.albedoTexture=e,this._resetContentPositionAndZoom(),this._applyContentViewport(),e.attachToMesh(this._contentPlate,!0)}_addControl(e){e._host=this._host,this._host.utilityLayer&&e._prepareNode(this._host.utilityLayer.utilityLayerScene)}_getTypeName(){return"HolographicSlate"}_positionElements(){const e=this._followButton,t=this._closeButton,i=this._titleBar,r=this._titleBarTitle,s=this._contentPlate,n=this._backPlate;if(e&&t&&i){t.scaling.setAll(this.titleBarHeight),e.scaling.setAll(this.titleBarHeight),t.position.copyFromFloats(this.dimensions.x-this.titleBarHeight/2,-this.titleBarHeight/2,0).addInPlace(this.origin),e.position.copyFromFloats(this.dimensions.x-3*this.titleBarHeight/2,-this.titleBarHeight/2,0).addInPlace(this.origin);const o=this.dimensions.y-this.titleBarHeight-this.titleBarMargin,a=s.getScene().useRightHandedSystem;i.scaling.set(this.dimensions.x,this.titleBarHeight,lt.bH),r.scaling.set(this.dimensions.x-2*this.titleBarHeight,this.titleBarHeight,lt.bH),s.scaling.copyFromFloats(this.dimensions.x,o,lt.bH),n.scaling.copyFromFloats(this.dimensions.x,o,lt.bH),i.position.copyFromFloats(this.dimensions.x/2,-this.titleBarHeight/2,0).addInPlace(this.origin),r.position.copyFromFloats(this.dimensions.x/2-this.titleBarHeight,-this.titleBarHeight/2,a?lt.bH:-lt.bH).addInPlace(this.origin),s.position.copyFromFloats(this.dimensions.x/2,-(this.titleBarHeight+this.titleBarMargin+o/2),0).addInPlace(this.origin),n.position.copyFromFloats(this.dimensions.x/2,-(this.titleBarHeight+this.titleBarMargin+o/2),a?-lt.bH:lt.bH).addInPlace(this.origin),this._titleTextComponent.host.scaleTo(IV._DEFAULT_TEXT_RESOLUTION_Y*r.scaling.x/r.scaling.y,IV._DEFAULT_TEXT_RESOLUTION_Y);const l=this.dimensions.x/o;this._contentViewport.width=this._contentScaleRatio,this._contentViewport.height=this._contentScaleRatio/l,this._applyContentViewport(),this._gizmo&&this._gizmo.updateBoundingBox()}}_applyContentViewport(){if(this._contentPlate?.material&&this._contentPlate.material.albedoTexture){const e=this._contentPlate.material.albedoTexture;e.uScale=this._contentScaleRatio,e.vScale=this.fitContentToDimensions?this._contentScaleRatio:this._contentScaleRatio/this._contentViewport.width*this._contentViewport.height,e.uOffset=this._contentViewport.x,e.vOffset=this._contentViewport.y}}_resetContentPositionAndZoom(){this._contentViewport.x=0,this._contentViewport.y=0,this._contentScaleRatio=1}_updatePivot(){if(!this.mesh)return;const e=new W.Pq(.5*this.dimensions.x,.5*-this.dimensions.y,lt.bH);e.addInPlace(this.origin),e.z=0;const t=new W.Pq(0,0,0);W.Pq.TransformCoordinatesToRef(t,this.mesh.computeWorldMatrix(!0),t),this.mesh.setPivotPoint(e);const i=new W.Pq(0,0,0);W.Pq.TransformCoordinatesToRef(i,this.mesh.computeWorldMatrix(!0),i),this.mesh.position.addInPlace(t).subtractInPlace(i)}_createNode(e){const t=new Yt("slate_"+this.name,e);this._titleBar=Ko("titleBar_"+this.name,{size:1},e),this._titleBarTitle=Qi("titleText_"+this.name,{size:1},e),this._titleBarTitle.parent=t,this._titleBarTitle.isPickable=!1;const i=$B.CreateForMesh(this._titleBarTitle);if(this._titleTextComponent=new dB("titleText_"+this.name,this._titleText),this._titleTextComponent.textWrapping=2,this._titleTextComponent.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,this._titleTextComponent.color="white",this._titleTextComponent.fontSize=IV._DEFAULT_TEXT_RESOLUTION_Y/2,this._titleTextComponent.paddingLeft=IV._DEFAULT_TEXT_RESOLUTION_Y/4,i.addControl(this._titleTextComponent),e.useRightHandedSystem){const t=new hc.IU(0,0,1,1);this._contentPlate=Qi("contentPlate_"+this.name,{size:1,sideOrientation:bt.BACKSIDE,frontUVs:t},e),this._backPlate=Qi("backPlate_"+this.name,{size:1,sideOrientation:bt.FRONTSIDE},e)}else{const t=new hc.IU(0,0,1,1);this._contentPlate=Qi("contentPlate_"+this.name,{size:1,sideOrientation:bt.FRONTSIDE,frontUVs:t},e),this._backPlate=Qi("backPlate_"+this.name,{size:1,sideOrientation:bt.BACKSIDE},e)}this._titleBar.parent=t,this._titleBar.isNearGrabbable=!0,this._contentPlate.parent=t,this._backPlate.parent=t,this._attachContentPlateBehavior(),this._addControl(this._followButton),this._addControl(this._closeButton);const r=this._followButton,s=this._closeButton;return r.node.parent=t,s.node.parent=t,this._positionElements(),this._followButton.imageUrl=IV.ASSETS_BASE_URL+IV.FOLLOW_ICON_FILENAME,this._closeButton.imageUrl=IV.ASSETS_BASE_URL+IV.CLOSE_ICON_FILENAME,this._followButton.isBackplateVisible=!1,this._closeButton.isBackplateVisible=!1,this._followButton.onToggleObservable.add((e=>{this._defaultBehavior.followBehaviorEnabled=e,this._defaultBehavior.followBehaviorEnabled&&this._defaultBehavior.followBehavior.recenter()})),this._closeButton.onPointerClickObservable.add((()=>{this.dispose()})),t.rotationQuaternion=W.PT.Identity(),t.isVisible=!1,t}_attachContentPlateBehavior(){this._contentDragBehavior.attach(this._contentPlate),this._contentDragBehavior.moveAttached=!1,this._contentDragBehavior.useObjectOrientationForDragging=!0,this._contentDragBehavior.updateDragPlane=!1;const e=new W.Pq,t=new W.Pq,i=new W.Pq,r=new W.Pq,s=new W.I9;let n,o;this._contentDragBehavior.onDragStartObservable.add((s=>{this.node&&(n=this._contentViewport.clone(),o=this.node.computeWorldMatrix(!0),e.copyFrom(s.dragPlanePoint),t.set(this.dimensions.x,this.dimensions.y,lt.bH),t.y-=this.titleBarHeight+this.titleBarMargin,W.Pq.TransformNormalToRef(t,o,t),i.copyFromFloats(0,1,0),W.Pq.TransformNormalToRef(i,o,i),r.copyFromFloats(1,0,0),W.Pq.TransformNormalToRef(r,o,r),i.normalize(),i.scaleInPlace(1/W.Pq.Dot(i,t)),r.normalize(),r.scaleInPlace(1/W.Pq.Dot(r,t)))}));const a=new W.Pq;this._contentDragBehavior.onDragObservable.add((t=>{this.fitContentToDimensions||(a.copyFrom(t.dragPlanePoint),a.subtractInPlace(e),s.copyFromFloats(W.Pq.Dot(a,r),W.Pq.Dot(a,i)),this._contentViewport.x=Gy.Clamp(n.x-a.x,0,1-this._contentViewport.width*this._contentScaleRatio),this._contentViewport.y=Gy.Clamp(n.y-a.y,0,1-this._contentViewport.height*this._contentScaleRatio),this._applyContentViewport())}))}_affectMaterial(e){this._titleBarMaterial=new _V(`${this.name} plateMaterial`,e.getScene()),this._contentMaterial=new uV(`${this.name} contentMaterial`,e.getScene()),this._contentMaterial.renderBorders=!0,this._backMaterial=new _V(`${this.name} backPlate`,e.getScene()),this._backMaterial.lineWidth=lt.bH,this._backMaterial.radius=.005,this._backMaterial.backFaceCulling=!0,this._titleBar.material=this._titleBarMaterial,this._contentPlate.material=this._contentMaterial,this._backPlate.material=this._backMaterial,this._resetContent(),this._applyContentViewport()}_prepareNode(e){super._prepareNode(e),this._gizmo=new RV(this._host.utilityLayer),this._gizmo.attachedSlate=this,this._defaultBehavior=new TV,this._defaultBehavior.attach(this.node,[this._titleBar]),this._defaultBehavior.sixDofDragBehavior.onDragStartObservable.add((()=>{this._followButton.isToggled=!1})),this._positionChangedObserver=this._defaultBehavior.sixDofDragBehavior.onPositionChangedObservable.add((()=>{this._gizmo.updateBoundingBox()})),this._updatePivot(),this.resetDefaultAspectAndPose(!1)}resetDefaultAspectAndPose(e=!0){if(!this._host||!this._host.utilityLayer||!this.node)return;const t=this._host.utilityLayer.utilityLayerScene,i=t.activeCamera;if(i){const r=i.getWorldMatrix(),s=W.Pq.TransformNormal(W.Pq.Backward(t.useRightHandedSystem),r);this.origin.setAll(0),this._gizmo.updateBoundingBox();const n=this.node.getAbsolutePivotPoint();this.node.position.equalsToFloats(0,0,0)&&this.node.position.copyFrom(i.position).subtractInPlace(s).subtractInPlace(n),this.node.rotationQuaternion=W.PT.FromLookDirectionLH(s,new W.Pq(0,1,0)),e&&(this.dimensions=this.defaultDimensions)}}dispose(){super.dispose(),this._titleBarMaterial.dispose(),this._contentMaterial.dispose(),this._titleBar.dispose(),this._titleBarTitle.dispose(),this._contentPlate.dispose(),this._backPlate.dispose(),this._followButton.dispose(),this._closeButton.dispose(),this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._defaultBehavior.sixDofDragBehavior.onPositionChangedObservable.remove(this._positionChangedObserver),this._defaultBehavior.detach(),this._gizmo.dispose(),this._contentDragBehavior.detach()}}IV.ASSETS_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",IV.CLOSE_ICON_FILENAME="IconClose.png",IV.FOLLOW_ICON_FILENAME="IconFollowMe.png",IV._DEFAULT_TEXT_RESOLUTION_Y=102.4;class MV extends oV{constructor(e,t){super(t),this._currentMesh=e,this.pointerEnterAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1.1)},this.pointerOutAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/1.1)},this.pointerDownAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/.95)}}_getTypeName(){return"MeshButton3D"}_createNode(e){return this._currentMesh.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this})),this._currentMesh}_affectMaterial(e){}}class OV extends dV{get defaultBehavior(){return this._defaultBehavior}get isPinned(){return this._isPinned}set isPinned(e){this._pinButton.isToggled===e?(this._isPinned=e,this._defaultBehavior.followBehaviorEnabled=!e):this._pinButton.isToggled=e}_createPinButton(e){const t=new SV("pin"+this.name,!1);return t.imageUrl=OV._ASSETS_BASE_URL+OV._PIN_ICON_FILENAME,t.parent=this,t._host=this._host,t.isToggleButton=!0,t.onToggleObservable.add((e=>{this.isPinned=e})),this._host.utilityLayer&&(t._prepareNode(this._host.utilityLayer.utilityLayerScene),t.scaling.scaleInPlace(dV.MENU_BUTTON_SCALE),t.node&&(t.node.parent=e)),t}_createNode(e){const t=super._createNode(e);return this._pinButton=this._createPinButton(t),this.isPinned=!1,this._defaultBehavior.attach(t,[this._backPlate]),this._defaultBehavior.followBehavior.ignoreCameraPitchAndRoll=!0,this._defaultBehavior.followBehavior.pitchOffset=-15,this._defaultBehavior.followBehavior.minimumDistance=.3,this._defaultBehavior.followBehavior.defaultDistance=.4,this._defaultBehavior.followBehavior.maximumDistance=.6,this._backPlate.isNearGrabbable=!0,t.isVisible=!1,t}_finalProcessing(){super._finalProcessing(),this._pinButton.position.copyFromFloats((this._backPlate.scaling.x+dV.MENU_BUTTON_SCALE)/2,this._backPlate.scaling.y/2,0)}constructor(e){super(e),this._isPinned=!1,this._defaultBehavior=new TV,this._dragObserver=this._defaultBehavior.sixDofDragBehavior.onDragObservable.add((()=>{this.isPinned=!0})),this.backPlateMargin=1}dispose(){super.dispose(),this._defaultBehavior.sixDofDragBehavior.onDragObservable.remove(this._dragObserver),this._defaultBehavior.detach()}}OV._ASSETS_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",OV._PIN_ICON_FILENAME="IconPin.png";class DV extends lV{_mapGridNode(e,t){const i=e.mesh;if(!i)return;e.position=t.clone();const r=W.AA.Vector3[0];switch(r.copyFrom(t),this.orientation){case aV.FACEORIGIN_ORIENTATION:case aV.FACEFORWARD_ORIENTATION:r.addInPlace(new W.Pq(0,0,1)),i.lookAt(r);break;case aV.FACEFORWARDREVERSED_ORIENTATION:case aV.FACEORIGINREVERSED_ORIENTATION:r.addInPlace(new W.Pq(0,0,-1)),i.lookAt(r)}}}class wV extends lV{constructor(){super(...arguments),this._iteration=100}get iteration(){return this._iteration}set iteration(e){this._iteration!==e&&(this._iteration=e,Ue.S0.SetImmediate((()=>{this._arrangeChildren()})))}_mapGridNode(e,t){const i=e.mesh,r=this._scatterMapping(t);if(i){switch(this.orientation){case aV.FACEORIGIN_ORIENTATION:case aV.FACEFORWARD_ORIENTATION:i.lookAt(new W.Pq(0,0,1));break;case aV.FACEFORWARDREVERSED_ORIENTATION:case aV.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new W.Pq(0,0,-1))}e.position=r}}_scatterMapping(e){return e.x=(1-2*Math.random())*this._cellWidth,e.y=(1-2*Math.random())*this._cellHeight,e}_finalProcessing(){const e=[];for(const t of this._children)t.mesh&&e.push(t.mesh);for(let t=0;t{const i=e.position.lengthSquared(),r=t.position.lengthSquared();return ir?-1:0}));const t=Math.pow(this.margin,2),i=Math.max(this._cellWidth,this._cellHeight),r=W.AA.Vector2[0],s=W.AA.Vector3[0];for(let n=0;n0.0) {C=mix(H,S,k);} else {C=mix(H,G,k); }\nreturn C;}\nvoid Sky_Environment_B50(\nvec3 Normal,\nvec3 Reflected,\nvec4 Sky_Color,\nvec4 Horizon_Color,\nvec4 Ground_Color,\nfloat Horizon_Power,\nout vec4 Reflected_Color,\nout vec4 Indirect_Color)\n{Reflected_Color=SampleEnv_Bid50(Reflected,Sky_Color,Horizon_Color,Ground_Color,Horizon_Power);Indirect_Color=mix(Ground_Color,Sky_Color,Normal.y*0.5+0.5);}\nvoid Min_Segment_Distance_B65(\nvec3 P0,\nvec3 P1,\nvec3 Q0,\nvec3 Q1,\nout vec3 NearP,\nout vec3 NearQ,\nout float Distance)\n{vec3 u=P1-P0;vec3 v=Q1-Q0;vec3 w=P0-Q0;float a=dot(u,u);float b=dot(u,v);float c=dot(v,v);float d=dot(u,w);float e=dot(v,w);float D=a*c-b*b;float sD=D;float tD=D;float sc,sN,tc,tN;if (D<0.00001) {sN=0.0;sD=1.0;tN=e;tD=c;} else {sN=(b*e-c*d);tN=(a*e-b*d);if (sN<0.0) {sN=0.0;tN=e;tD=c;} else if (sN>sD) {sN=sD;tN=e+b;tD=c;}}\nif (tN<0.0) {tN=0.0;if (-d<0.0) {sN=0.0;} else if (-d>a) {sN=sD;} else {sN=-d;sD=a;}} else if (tN>tD) {tN=tD;if ((-d+b)<0.0) {sN=0.0;} else if ((-d+b)>a) {sN=sD;} else {sN=(-d+b);sD=a;}}\nsc=abs(sN)<0.000001 ? 0.0 : sN/sD;tc=abs(tN)<0.000001 ? 0.0 : tN/tD;NearP=P0+sc*u;NearQ=Q0+tc*v;Distance=distance(NearP,NearQ);}\nvoid To_XYZ_B74(\nvec3 Vec3,\nout float X,\nout float Y,\nout float Z)\n{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;}\nvoid Finger_Positions_B64(\nvec3 Left_Index_Pos,\nvec3 Right_Index_Pos,\nvec3 Left_Index_Middle_Pos,\nvec3 Right_Index_Middle_Pos,\nout vec3 Left_Index,\nout vec3 Right_Index,\nout vec3 Left_Index_Middle,\nout vec3 Right_Index_Middle)\n{Left_Index= (Use_Global_Left_Index ? Global_Left_Index_Tip_Position.xyz : Left_Index_Pos);Right_Index= (Use_Global_Right_Index ? Global_Right_Index_Tip_Position.xyz : Right_Index_Pos);Left_Index_Middle= (Use_Global_Left_Index ? Global_Left_Index_Middle_Position.xyz : Left_Index_Middle_Pos);Right_Index_Middle= (Use_Global_Right_Index ? Global_Right_Index_Middle_Position.xyz : Right_Index_Middle_Pos);}\nvoid VaryHSV_B108(\nvec3 HSV_In,\nfloat Hue_Shift,\nfloat Saturation_Shift,\nfloat Value_Shift,\nout vec3 HSV_Out)\n{HSV_Out=vec3(fract(HSV_In.x+Hue_Shift),clamp(HSV_In.y+Saturation_Shift,0.0,1.0),clamp(HSV_In.z+Value_Shift,0.0,1.0));}\nvoid Remap_Range_B114(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid To_HSV_B75(\nvec4 Color,\nout float Hue,\nout float Saturation,\nout float Value,\nout float Alpha,\nout vec3 HSV)\n{vec4 K=vec4(0.0,-1.0/3.0,2.0/3.0,-1.0);vec4 p=Color.g0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid Conditional_Float_B36(\nbool Which,\nfloat If_True,\nfloat If_False,\nout float Result)\n{Result=Which ? If_True : If_False;}\nvoid Greater_Than_B37(\nfloat Left,\nfloat Right,\nout bool Not_Greater_Than,\nout bool Greater_Than)\n{Greater_Than=Left>Right;Not_Greater_Than=!Greater_Than;}\nvoid Remap_Range_B105(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid main()\n{vec2 XY_Q85;XY_Q85=(uv-vec2(0.5,0.5))*_Decal_Scale_XY_+vec2(0.5,0.5);vec3 Tangent_World_Q27;vec3 Tangent_World_N_Q27;float Tangent_Length_Q27;Tangent_World_Q27=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q27=length(Tangent_World_Q27);Tangent_World_N_Q27=Tangent_World_Q27/Tangent_Length_Q27;vec3 Normal_World_Q60;vec3 Normal_World_N_Q60;float Normal_Length_Q60;Object_To_World_Dir_B60(vec3(0,0,1),Normal_World_Q60,Normal_World_N_Q60,Normal_Length_Q60);float X_Q78;float Y_Q78;float Z_Q78;To_XYZ_B78(position,X_Q78,Y_Q78,Z_Q78);vec3 Nrm_World_Q26;Nrm_World_Q26=normalize((world*vec4(normal,0.0)).xyz);vec3 Binormal_World_Q28;vec3 Binormal_World_N_Q28;float Binormal_Length_Q28;Object_To_World_Dir_B28(vec3(0,1,0),Binormal_World_Q28,Binormal_World_N_Q28,Binormal_Length_Q28);float Anisotropy_Q29=Tangent_Length_Q27/Binormal_Length_Q28;float Result_Q69;Pick_Radius_B69(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q69);float Anisotropy_Q53=Binormal_Length_Q28/Normal_Length_Q60;bool Not_Greater_Than_Q37;bool Greater_Than_Q37;Greater_Than_B37(Z_Q78,0.0,Not_Greater_Than_Q37,Greater_Than_Q37);vec4 Linear_Q101;Linear_Q101.rgb=clamp(_Left_Color_.rgb*_Left_Color_.rgb,0.0,1.0);Linear_Q101.a=_Left_Color_.a;vec4 Linear_Q102;Linear_Q102.rgb=clamp(_Right_Color_.rgb*_Right_Color_.rgb,0.0,1.0);Linear_Q102.a=_Right_Color_.a;vec3 Difference_Q61=vec3(0,0,0)-Normal_World_N_Q60;vec4 Out_Color_Q34=vec4(X_Q78,Y_Q78,Z_Q78,1);float Result_Q36;Conditional_Float_B36(Greater_Than_Q37,_Bevel_Back_,_Bevel_Front_,Result_Q36);float Result_Q94;Conditional_Float_B36(Greater_Than_Q37,_Bevel_Back_Stretch_,_Bevel_Front_Stretch_,Result_Q94);vec3 New_P_Q130;vec2 New_UV_Q130;float Radial_Gradient_Q130;vec3 Radial_Dir_Q130;vec3 New_Normal_Q130;Move_Verts_B130(Anisotropy_Q29,position,Result_Q69,Result_Q36,normal,Anisotropy_Q53,Result_Q94,New_P_Q130,New_UV_Q130,Radial_Gradient_Q130,Radial_Dir_Q130,New_Normal_Q130);float X_Q98;float Y_Q98;X_Q98=New_UV_Q130.x;Y_Q98=New_UV_Q130.y;vec3 Pos_World_Q12;Object_To_World_Pos_B12(New_P_Q130,Pos_World_Q12);vec3 Nrm_World_Q32;Object_To_World_Normal_B32(New_Normal_Q130,Nrm_World_Q32);vec4 Blob_Info_Q23;\n#if BLOB_ENABLE\nBlob_Vertex_B23(Pos_World_Q12,Nrm_World_Q26,Tangent_World_N_Q27,Binormal_World_N_Q28,_Blob_Position_,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q23);\n#else\nBlob_Info_Q23=vec4(0,0,0,0);\n#endif\nvec4 Blob_Info_Q24;\n#if BLOB_ENABLE_2\nBlob_Vertex_B24(Pos_World_Q12,Nrm_World_Q26,Tangent_World_N_Q27,Binormal_World_N_Q28,_Blob_Position_2_,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q24);\n#else\nBlob_Info_Q24=vec4(0,0,0,0);\n#endif\nfloat Out_Q105;Remap_Range_B105(0.0,1.0,0.0,1.0,X_Q98,Out_Q105);float X_Q86;float Y_Q86;float Z_Q86;To_XYZ_B78(Nrm_World_Q32,X_Q86,Y_Q86,Z_Q86);vec4 Color_At_T_Q97=mix(Linear_Q101,Linear_Q102,Out_Q105);float Minus_F_Q87=-Z_Q86;float R_Q99;float G_Q99;float B_Q99;float A_Q99;R_Q99=Color_At_T_Q97.r; G_Q99=Color_At_T_Q97.g; B_Q99=Color_At_T_Q97.b; A_Q99=Color_At_T_Q97.a;float ClampF_Q88=clamp(0.0,Minus_F_Q87,1.0);float Result_Q93;Conditional_Float_B93(_Decal_Front_Only_,ClampF_Q88,1.0,Result_Q93);vec4 Vec4_Q89=vec4(Result_Q93,Radial_Gradient_Q130,G_Q99,B_Q99);vec3 Position=Pos_World_Q12;vec3 Normal=Nrm_World_Q32;vec2 UV=XY_Q85;vec3 Tangent=Tangent_World_N_Q27;vec3 Binormal=Difference_Q61;vec4 Color=Out_Color_Q34;vec4 Extra1=Vec4_Q89;vec4 Extra2=Blob_Info_Q23;vec4 Extra3=Blob_Info_Q24;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class NV extends xn{constructor(){super(),this.SKY_ENABLED=!0,this.BLOB_ENABLE_2=!0,this.IRIDESCENCE_ENABLED=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class FV extends bn{constructor(e,t){super(e,t),this.radius=.6,this.bevelFront=.6,this.bevelFrontStretch=.077,this.bevelBack=0,this.bevelBackStretch=0,this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this.bulgeEnabled=!1,this.bulgeHeight=-.323,this.bulgeRadius=.73,this.sunIntensity=1.102,this.sunTheta=.76,this.sunPhi=.526,this.indirectDiffuse=.658,this.albedo=new H.ov(.0117647,.505882,.996078,1),this.specular=0,this.shininess=10,this.sharpness=0,this.subsurface=0,this.leftGradientColor=new H.ov(.0117647,.505882,.996078,1),this.rightGradientColor=new H.ov(.0117647,.505882,.996078,1),this.reflection=.749,this.frontReflect=0,this.edgeReflect=.09,this.power=8.13,this.skyColor=new H.ov(.0117647,.964706,.996078,1),this.horizonColor=new H.ov(.0117647,.333333,.996078,1),this.groundColor=new H.ov(0,.254902,.996078,1),this.horizonPower=1,this.width=.02,this.fuzz=.5,this.minFuzz=.001,this.clipFade=.01,this.hueShift=0,this.saturationShift=0,this.valueShift=0,this.blobPosition=new W.Pq(0,0,.1),this.blobIntensity=.5,this.blobNearSize=.01,this.blobFarSize=.03,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.576,this.blobPulse=0,this.blobFade=1,this.blobPosition2=new W.Pq(.2,0,.1),this.blobNearSize2=.01,this.blobPulse2=0,this.blobFade2=1,this.blobTexture=new vi.g("",this.getScene()),this.leftIndexPosition=new W.Pq(0,0,1),this.rightIndexPosition=new W.Pq(-1,-1,-1),this.leftIndexMiddlePosition=new W.Pq(0,0,0),this.rightIndexMiddlePosition=new W.Pq(0,0,0),this.decalScaleXY=new W.I9(1.5,1.5),this.decalFrontOnly=!0,this.rimIntensity=.287,this.rimHueShift=0,this.rimSaturationShift=0,this.rimValueShift=-1,this.iridescenceIntensity=0,this.useGlobalLeftIndex=1,this.useGlobalRightIndex=1,this.globalLeftIndexTipProximity=0,this.globalRightIndexTipProximity=0,this.globalLeftIndexTipPosition=new W.IU(.5,0,-.55,1),this.globaRightIndexTipPosition=new W.IU(0,0,0,1),this.globalLeftThumbTipPosition=new W.IU(.5,0,-.55,1),this.globalRightThumbTipPosition=new W.IU(0,0,0,1),this.globalLeftIndexMiddlePosition=new W.IU(.5,0,-.55,1),this.globalRightIndexMiddlePosition=new W.IU(0,0,0,1),this.alphaMode=Il.ALPHA_DISABLE,this.backFaceCulling=!1,this._blueGradientTexture=new vi.g(FV.BLUE_GRADIENT_TEXTURE_URL,this.getScene(),!0,!1,vi.g.NEAREST_SAMPLINGMODE),this._decalTexture=new vi.g("",this.getScene()),this._reflectionMapTexture=new vi.g("",this.getScene()),this._indirectEnvTexture=new vi.g("",this.getScene())}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new NV);const r=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if((0,Bt.qB)(e,r,!1,!1),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=new Tn;r.FOG&&e.addFallback(1,"FOG"),(0,Bt.c4)(r,e),r.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const i=[st.R.PositionKind];r.NORMAL&&i.push(st.R.NormalKind),r.UV1&&i.push(st.R.UVKind),r.UV2&&i.push(st.R.UV2Kind),r.VERTEXCOLOR&&i.push(st.R.ColorKind),r.TANGENT&&i.push(st.R.TangentKind),(0,Bt.ER)(i,r);const o="mrdlSliderBar",a=r.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Bevel_Front_","_Bevel_Front_Stretch_","_Bevel_Back_","_Bevel_Back_Stretch_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Bulge_Enabled_","_Bulge_Height_","_Bulge_Radius_","_Sun_Intensity_","_Sun_Theta_","_Sun_Phi_","_Indirect_Diffuse_","_Albedo_","_Specular_","_Shininess_","_Sharpness_","_Subsurface_","_Left_Color_","_Right_Color_","_Reflection_","_Front_Reflect_","_Edge_Reflect_","_Power_","_Sky_Color_","_Horizon_Color_","_Ground_Color_","_Horizon_Power_","_Reflection_Map_","_Indirect_Environment_","_Width_","_Fuzz_","_Min_Fuzz_","_Clip_Fade_","_Hue_Shift_","_Saturation_Shift_","_Value_Shift_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Left_Index_Pos_","_Right_Index_Pos_","_Left_Index_Middle_Pos_","_Right_Index_Middle_Pos_","_Decal_","_Decal_Scale_XY_","_Decal_Front_Only_","_Rim_Intensity_","_Rim_Texture_","_Rim_Hue_Shift_","_Rim_Saturation_Shift_","_Rim_Value_Shift_","_Iridescence_Intensity_","_Iridescence_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Middle_Position;","Global_Right_Index_Middle_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],h=["_Rim_Texture_","_Iridescence_Texture_"],c=[];(0,Bt.Bb)({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:r,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Bevel_Front_",this.bevelFront),this._activeEffect.setFloat("_Bevel_Front_Stretch_",this.bevelFrontStretch),this._activeEffect.setFloat("_Bevel_Back_",this.bevelBack),this._activeEffect.setFloat("_Bevel_Back_Stretch_",this.bevelBackStretch),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Bulge_Enabled_",this.bulgeEnabled?1:0),this._activeEffect.setFloat("_Bulge_Height_",this.bulgeHeight),this._activeEffect.setFloat("_Bulge_Radius_",this.bulgeRadius),this._activeEffect.setFloat("_Sun_Intensity_",this.sunIntensity),this._activeEffect.setFloat("_Sun_Theta_",this.sunTheta),this._activeEffect.setFloat("_Sun_Phi_",this.sunPhi),this._activeEffect.setFloat("_Indirect_Diffuse_",this.indirectDiffuse),this._activeEffect.setDirectColor4("_Albedo_",this.albedo),this._activeEffect.setFloat("_Specular_",this.specular),this._activeEffect.setFloat("_Shininess_",this.shininess),this._activeEffect.setFloat("_Sharpness_",this.sharpness),this._activeEffect.setFloat("_Subsurface_",this.subsurface),this._activeEffect.setDirectColor4("_Left_Color_",this.leftGradientColor),this._activeEffect.setDirectColor4("_Right_Color_",this.rightGradientColor),this._activeEffect.setFloat("_Reflection_",this.reflection),this._activeEffect.setFloat("_Front_Reflect_",this.frontReflect),this._activeEffect.setFloat("_Edge_Reflect_",this.edgeReflect),this._activeEffect.setFloat("_Power_",this.power),this._activeEffect.setDirectColor4("_Sky_Color_",this.skyColor),this._activeEffect.setDirectColor4("_Horizon_Color_",this.horizonColor),this._activeEffect.setDirectColor4("_Ground_Color_",this.groundColor),this._activeEffect.setFloat("_Horizon_Power_",this.horizonPower),this._activeEffect.setTexture("_Reflection_Map_",this._reflectionMapTexture),this._activeEffect.setTexture("_Indirect_Environment_",this._indirectEnvTexture),this._activeEffect.setFloat("_Width_",this.width),this._activeEffect.setFloat("_Fuzz_",this.fuzz),this._activeEffect.setFloat("_Min_Fuzz_",this.minFuzz),this._activeEffect.setFloat("_Clip_Fade_",this.clipFade),this._activeEffect.setFloat("_Hue_Shift_",this.hueShift),this._activeEffect.setFloat("_Saturation_Shift_",this.saturationShift),this._activeEffect.setFloat("_Value_Shift_",this.valueShift),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this.blobTexture),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setVector3("_Left_Index_Pos_",this.leftIndexPosition),this._activeEffect.setVector3("_Right_Index_Pos_",this.rightIndexPosition),this._activeEffect.setVector3("_Left_Index_Middle_Pos_",this.leftIndexMiddlePosition),this._activeEffect.setVector3("_Right_Index_Middle_Pos_",this.rightIndexMiddlePosition),this._activeEffect.setTexture("_Decal_",this._decalTexture),this._activeEffect.setVector2("_Decal_Scale_XY_",this.decalScaleXY),this._activeEffect.setFloat("_Decal_Front_Only_",this.decalFrontOnly?1:0),this._activeEffect.setFloat("_Rim_Intensity_",this.rimIntensity),this._activeEffect.setTexture("_Rim_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("_Rim_Hue_Shift_",this.rimHueShift),this._activeEffect.setFloat("_Rim_Saturation_Shift_",this.rimSaturationShift),this._activeEffect.setFloat("_Rim_Value_Shift_",this.rimValueShift),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setTexture("_Iridescence_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("Use_Global_Left_Index",this.useGlobalLeftIndex),this._activeEffect.setFloat("Use_Global_Right_Index",this.useGlobalRightIndex),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this.globalLeftIndexTipPosition),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this.globaRightIndexTipPosition),this._activeEffect.setVector4("Global_Left_Thumb_Tip_Position",this.globalLeftThumbTipPosition),this._activeEffect.setVector4("Global_Right_Thumb_Tip_Position",this.globalRightThumbTipPosition),this._activeEffect.setVector4("Global_Left_Index_Middle_Position",this.globalLeftIndexMiddlePosition),this._activeEffect.setVector4("Global_Right_Index_Middle_Position",this.globalRightIndexMiddlePosition),this._activeEffect.setFloat("Global_Left_Index_Tip_Proximity",this.globalLeftIndexTipProximity),this._activeEffect.setFloat("Global_Right_Index_Tip_Proximity",this.globalRightIndexTipProximity),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._reflectionMapTexture.dispose(),this._indirectEnvTexture.dispose(),this._blueGradientTexture.dispose(),this._decalTexture.dispose()}clone(e){return it.p.Clone((()=>new FV(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLSliderBarMaterial",e}getClassName(){return"MRDLSliderBarMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new FV(e.name,t)),e,t,i)}}FV.BLUE_GRADIENT_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-blue-gradient.png",(0,je.Cg)([(0,$e.lK)()],FV.prototype,"radius",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"bevelFront",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"bevelFrontStretch",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"bevelBack",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"bevelBackStretch",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"radiusTopLeft",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"radiusTopRight",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"radiusBottomLeft",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"radiusBottomRight",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"bulgeEnabled",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"bulgeHeight",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"bulgeRadius",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"sunIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"sunTheta",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"sunPhi",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"indirectDiffuse",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"albedo",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"specular",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"shininess",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"sharpness",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"subsurface",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"leftGradientColor",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"rightGradientColor",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"reflection",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"frontReflect",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"edgeReflect",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"power",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"skyColor",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"horizonColor",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"groundColor",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"horizonPower",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"width",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"fuzz",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"minFuzz",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"clipFade",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"hueShift",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"saturationShift",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"valueShift",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobPosition",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobNearSize",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobFarSize",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobNearDistance",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobFarDistance",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobFadeLength",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobPulse",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobFade",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobPosition2",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobNearSize2",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobPulse2",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobFade2",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"blobTexture",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"leftIndexPosition",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"rightIndexPosition",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"leftIndexMiddlePosition",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"rightIndexMiddlePosition",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"decalScaleXY",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"decalFrontOnly",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"rimIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"rimHueShift",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"rimSaturationShift",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"rimValueShift",void 0),(0,je.Cg)([(0,$e.lK)()],FV.prototype,"iridescenceIntensity",void 0),(0,X.Y5)("BABYLON.GUI.MRDLSliderBarMaterial",FV);Cs.l.ShadersStore.mrdlSliderThumbPixelShader="uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;uniform float _Radius_;uniform float _Bevel_Front_;uniform float _Bevel_Front_Stretch_;uniform float _Bevel_Back_;uniform float _Bevel_Back_Stretch_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform bool _Bulge_Enabled_;uniform float _Bulge_Height_;uniform float _Bulge_Radius_;uniform float _Sun_Intensity_;uniform float _Sun_Theta_;uniform float _Sun_Phi_;uniform float _Indirect_Diffuse_;uniform vec4 _Albedo_;uniform float _Specular_;uniform float _Shininess_;uniform float _Sharpness_;uniform float _Subsurface_;uniform vec4 _Left_Color_;uniform vec4 _Right_Color_;uniform float _Reflection_;uniform float _Front_Reflect_;uniform float _Edge_Reflect_;uniform float _Power_;uniform vec4 _Sky_Color_;uniform vec4 _Horizon_Color_;uniform vec4 _Ground_Color_;uniform float _Horizon_Power_;uniform sampler2D _Reflection_Map_;uniform sampler2D _Indirect_Environment_;uniform float _Width_;uniform float _Fuzz_;uniform float _Min_Fuzz_;uniform float _Clip_Fade_;uniform float _Hue_Shift_;uniform float _Saturation_Shift_;uniform float _Value_Shift_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Left_Index_Pos_;uniform vec3 _Right_Index_Pos_;uniform vec3 _Left_Index_Middle_Pos_;uniform vec3 _Right_Index_Middle_Pos_;uniform sampler2D _Decal_;uniform vec2 _Decal_Scale_XY_;uniform bool _Decal_Front_Only_;uniform float _Rim_Intensity_;uniform sampler2D _Rim_Texture_;uniform float _Rim_Hue_Shift_;uniform float _Rim_Saturation_Shift_;uniform float _Rim_Value_Shift_;uniform float _Iridescence_Intensity_;uniform sampler2D _Iridescence_Texture_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform vec4 Global_Left_Index_Middle_Position;uniform vec4 Global_Right_Index_Middle_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;void Blob_Fragment_B180(\nsampler2D Blob_Texture,\nvec4 Blob_Info1,\nvec4 Blob_Info2,\nout vec4 Blob_Color)\n{float k1=dot(Blob_Info1.xy,Blob_Info1.xy);float k2=dot(Blob_Info2.xy,Blob_Info2.xy);vec3 closer=k10.0) {C=mix(H,S,k);} else {C=mix(H,G,k); }\nreturn C;}\nvoid Sky_Environment_B200(\nvec3 Normal,\nvec3 Reflected,\nvec4 Sky_Color,\nvec4 Horizon_Color,\nvec4 Ground_Color,\nfloat Horizon_Power,\nout vec4 Reflected_Color,\nout vec4 Indirect_Color)\n{Reflected_Color=SampleEnv_Bid200(Reflected,Sky_Color,Horizon_Color,Ground_Color,Horizon_Power);Indirect_Color=mix(Ground_Color,Sky_Color,Normal.y*0.5+0.5);}\nvoid Min_Segment_Distance_B215(\nvec3 P0,\nvec3 P1,\nvec3 Q0,\nvec3 Q1,\nout vec3 NearP,\nout vec3 NearQ,\nout float Distance)\n{vec3 u=P1-P0;vec3 v=Q1-Q0;vec3 w=P0-Q0;float a=dot(u,u);float b=dot(u,v);float c=dot(v,v);float d=dot(u,w);float e=dot(v,w);float D=a*c-b*b;float sD=D;float tD=D;float sc,sN,tc,tN;if (D<0.00001) {sN=0.0;sD=1.0;tN=e;tD=c;} else {sN=(b*e-c*d);tN=(a*e-b*d);if (sN<0.0) {sN=0.0;tN=e;tD=c;} else if (sN>sD) {sN=sD;tN=e+b;tD=c;}}\nif (tN<0.0) {tN=0.0;if (-d<0.0) {sN=0.0;} else if (-d>a) {sN=sD;} else {sN=-d;sD=a;}} else if (tN>tD) {tN=tD;if ((-d+b)<0.0) {sN=0.0;} else if ((-d+b)>a) {sN=sD;} else {sN=(-d+b);sD=a;}}\nsc=abs(sN)<0.000001 ? 0.0 : sN/sD;tc=abs(tN)<0.000001 ? 0.0 : tN/tD;NearP=P0+sc*u;NearQ=Q0+tc*v;Distance=distance(NearP,NearQ);}\nvoid To_XYZ_B224(\nvec3 Vec3,\nout float X,\nout float Y,\nout float Z)\n{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;}\nvoid Finger_Positions_B214(\nvec3 Left_Index_Pos,\nvec3 Right_Index_Pos,\nvec3 Left_Index_Middle_Pos,\nvec3 Right_Index_Middle_Pos,\nout vec3 Left_Index,\nout vec3 Right_Index,\nout vec3 Left_Index_Middle,\nout vec3 Right_Index_Middle)\n{Left_Index= (Use_Global_Left_Index ? Global_Left_Index_Tip_Position.xyz : Left_Index_Pos);Right_Index= (Use_Global_Right_Index ? Global_Right_Index_Tip_Position.xyz : Right_Index_Pos);Left_Index_Middle= (Use_Global_Left_Index ? Global_Left_Index_Middle_Position.xyz : Left_Index_Middle_Pos);Right_Index_Middle= (Use_Global_Right_Index ? Global_Right_Index_Middle_Position.xyz : Right_Index_Middle_Pos);}\nvoid VaryHSV_B258(\nvec3 HSV_In,\nfloat Hue_Shift,\nfloat Saturation_Shift,\nfloat Value_Shift,\nout vec3 HSV_Out)\n{HSV_Out=vec3(fract(HSV_In.x+Hue_Shift),clamp(HSV_In.y+Saturation_Shift,0.0,1.0),clamp(HSV_In.z+Value_Shift,0.0,1.0));}\nvoid Remap_Range_B264(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid To_HSV_B225(\nvec4 Color,\nout float Hue,\nout float Saturation,\nout float Value,\nout float Alpha,\nout vec3 HSV)\n{vec4 K=vec4(0.0,-1.0/3.0,2.0/3.0,-1.0);vec4 p=Color.g0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid Conditional_Float_B186(\nbool Which,\nfloat If_True,\nfloat If_False,\nout float Result)\n{Result=Which ? If_True : If_False;}\nvoid Greater_Than_B187(\nfloat Left,\nfloat Right,\nout bool Not_Greater_Than,\nout bool Greater_Than)\n{Greater_Than=Left>Right;Not_Greater_Than=!Greater_Than;}\nvoid Remap_Range_B255(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid main()\n{vec2 XY_Q235;XY_Q235=(uv-vec2(0.5,0.5))*_Decal_Scale_XY_+vec2(0.5,0.5);vec3 Tangent_World_Q177;vec3 Tangent_World_N_Q177;float Tangent_Length_Q177;Tangent_World_Q177=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q177=length(Tangent_World_Q177);Tangent_World_N_Q177=Tangent_World_Q177/Tangent_Length_Q177;vec3 Normal_World_Q210;vec3 Normal_World_N_Q210;float Normal_Length_Q210;Object_To_World_Dir_B210(vec3(0,0,1),Normal_World_Q210,Normal_World_N_Q210,Normal_Length_Q210);float X_Q228;float Y_Q228;float Z_Q228;To_XYZ_B228(position,X_Q228,Y_Q228,Z_Q228);vec3 Nrm_World_Q176;Nrm_World_Q176=normalize((world*vec4(normal,0.0)).xyz);vec3 Binormal_World_Q178;vec3 Binormal_World_N_Q178;float Binormal_Length_Q178;Object_To_World_Dir_B178(vec3(0,1,0),Binormal_World_Q178,Binormal_World_N_Q178,Binormal_Length_Q178);float Anisotropy_Q179=Tangent_Length_Q177/Binormal_Length_Q178;float Result_Q219;Pick_Radius_B219(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q219);float Anisotropy_Q203=Binormal_Length_Q178/Normal_Length_Q210;bool Not_Greater_Than_Q187;bool Greater_Than_Q187;Greater_Than_B187(Z_Q228,0.0,Not_Greater_Than_Q187,Greater_Than_Q187);vec4 Linear_Q251;Linear_Q251.rgb=clamp(_Left_Color_.rgb*_Left_Color_.rgb,0.0,1.0);Linear_Q251.a=_Left_Color_.a;vec4 Linear_Q252;Linear_Q252.rgb=clamp(_Right_Color_.rgb*_Right_Color_.rgb,0.0,1.0);Linear_Q252.a=_Right_Color_.a;vec3 Difference_Q211=vec3(0,0,0)-Normal_World_N_Q210;vec4 Out_Color_Q184=vec4(X_Q228,Y_Q228,Z_Q228,1);float Result_Q186;Conditional_Float_B186(Greater_Than_Q187,_Bevel_Back_,_Bevel_Front_,Result_Q186);float Result_Q244;Conditional_Float_B186(Greater_Than_Q187,_Bevel_Back_Stretch_,_Bevel_Front_Stretch_,Result_Q244);vec3 New_P_Q280;vec2 New_UV_Q280;float Radial_Gradient_Q280;vec3 Radial_Dir_Q280;vec3 New_Normal_Q280;Move_Verts_B280(Anisotropy_Q179,position,Result_Q219,Result_Q186,normal,Anisotropy_Q203,Result_Q244,New_P_Q280,New_UV_Q280,Radial_Gradient_Q280,Radial_Dir_Q280,New_Normal_Q280);float X_Q248;float Y_Q248;X_Q248=New_UV_Q280.x;Y_Q248=New_UV_Q280.y;vec3 Pos_World_Q162;Object_To_World_Pos_B162(New_P_Q280,Pos_World_Q162);vec3 Nrm_World_Q182;Object_To_World_Normal_B182(New_Normal_Q280,Nrm_World_Q182);vec4 Blob_Info_Q173;\n#if BLOB_ENABLE\nBlob_Vertex_B173(Pos_World_Q162,Nrm_World_Q176,Tangent_World_N_Q177,Binormal_World_N_Q178,_Blob_Position_,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q173);\n#else\nBlob_Info_Q173=vec4(0,0,0,0);\n#endif\nvec4 Blob_Info_Q174;\n#if BLOB_ENABLE_2\nBlob_Vertex_B174(Pos_World_Q162,Nrm_World_Q176,Tangent_World_N_Q177,Binormal_World_N_Q178,_Blob_Position_2_,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q174);\n#else\nBlob_Info_Q174=vec4(0,0,0,0);\n#endif\nfloat Out_Q255;Remap_Range_B255(0.0,1.0,0.0,1.0,X_Q248,Out_Q255);float X_Q236;float Y_Q236;float Z_Q236;To_XYZ_B228(Nrm_World_Q182,X_Q236,Y_Q236,Z_Q236);vec4 Color_At_T_Q247=mix(Linear_Q251,Linear_Q252,Out_Q255);float Minus_F_Q237=-Z_Q236;float R_Q249;float G_Q249;float B_Q249;float A_Q249;R_Q249=Color_At_T_Q247.r; G_Q249=Color_At_T_Q247.g; B_Q249=Color_At_T_Q247.b; A_Q249=Color_At_T_Q247.a;float ClampF_Q238=clamp(0.0,Minus_F_Q237,1.0);float Result_Q243;Conditional_Float_B243(_Decal_Front_Only_,ClampF_Q238,1.0,Result_Q243);vec4 Vec4_Q239=vec4(Result_Q243,Radial_Gradient_Q280,G_Q249,B_Q249);vec3 Position=Pos_World_Q162;vec3 Normal=Nrm_World_Q182;vec2 UV=XY_Q235;vec3 Tangent=Tangent_World_N_Q177;vec3 Binormal=Difference_Q211;vec4 Color=Out_Color_Q184;vec4 Extra1=Vec4_Q239;vec4 Extra2=Blob_Info_Q173;vec4 Extra3=Blob_Info_Q174;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class LV extends xn{constructor(){super(),this.SKY_ENABLED=!0,this.BLOB_ENABLE_2=!0,this.IRIDESCENCE_ENABLED=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class BV extends bn{constructor(e,t){super(e,t),this.radius=.157,this.bevelFront=.065,this.bevelFrontStretch=.077,this.bevelBack=.031,this.bevelBackStretch=0,this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this.bulgeEnabled=!1,this.bulgeHeight=-.323,this.bulgeRadius=.73,this.sunIntensity=2,this.sunTheta=.937,this.sunPhi=.555,this.indirectDiffuse=1,this.albedo=new H.ov(.0117647,.505882,.996078,1),this.specular=0,this.shininess=10,this.sharpness=0,this.subsurface=.31,this.leftGradientColor=new H.ov(.0117647,.505882,.996078,1),this.rightGradientColor=new H.ov(.0117647,.505882,.996078,1),this.reflection=.749,this.frontReflect=0,this.edgeReflect=.09,this.power=8.1,this.skyColor=new H.ov(.0117647,.960784,.996078,1),this.horizonColor=new H.ov(.0117647,.333333,.996078,1),this.groundColor=new H.ov(0,.254902,.996078,1),this.horizonPower=1,this.width=.02,this.fuzz=.5,this.minFuzz=.001,this.clipFade=.01,this.hueShift=0,this.saturationShift=0,this.valueShift=0,this.blobPosition=new W.Pq(0,0,.1),this.blobIntensity=.5,this.blobNearSize=.01,this.blobFarSize=.03,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.576,this.blobPulse=0,this.blobFade=1,this.blobPosition2=new W.Pq(.2,0,.1),this.blobNearSize2=.01,this.blobPulse2=0,this.blobFade2=1,this.blobTexture=new vi.g("",this.getScene()),this.leftIndexPosition=new W.Pq(0,0,1),this.rightIndexPosition=new W.Pq(-1,-1,-1),this.leftIndexMiddlePosition=new W.Pq(0,0,0),this.rightIndexMiddlePosition=new W.Pq(0,0,0),this.decalScaleXY=new W.I9(1.5,1.5),this.decalFrontOnly=!0,this.rimIntensity=.287,this.rimHueShift=0,this.rimSaturationShift=0,this.rimValueShift=-1,this.iridescenceIntensity=0,this.useGlobalLeftIndex=1,this.useGlobalRightIndex=1,this.globalLeftIndexTipProximity=0,this.globalRightIndexTipProximity=0,this.globalLeftIndexTipPosition=new W.IU(.5,0,-.55,1),this.globaRightIndexTipPosition=new W.IU(0,0,0,1),this.globalLeftThumbTipPosition=new W.IU(.5,0,-.55,1),this.globalRightThumbTipPosition=new W.IU(0,0,0,1),this.globalLeftIndexMiddlePosition=new W.IU(.5,0,-.55,1),this.globalRightIndexMiddlePosition=new W.IU(0,0,0,1),this.alphaMode=Il.ALPHA_DISABLE,this.backFaceCulling=!1,this._blueGradientTexture=new vi.g(BV.BLUE_GRADIENT_TEXTURE_URL,t,!0,!1,vi.g.NEAREST_SAMPLINGMODE),this._decalTexture=new vi.g("",this.getScene()),this._reflectionMapTexture=new vi.g("",this.getScene()),this._indirectEnvTexture=new vi.g("",this.getScene())}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new LV);const r=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if((0,Bt.qB)(e,r,!1,!1),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=new Tn;r.FOG&&e.addFallback(1,"FOG"),(0,Bt.c4)(r,e),r.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const i=[st.R.PositionKind];r.NORMAL&&i.push(st.R.NormalKind),r.UV1&&i.push(st.R.UVKind),r.UV2&&i.push(st.R.UV2Kind),r.VERTEXCOLOR&&i.push(st.R.ColorKind),r.TANGENT&&i.push(st.R.TangentKind),(0,Bt.ER)(i,r);const o="mrdlSliderThumb",a=r.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Bevel_Front_","_Bevel_Front_Stretch_","_Bevel_Back_","_Bevel_Back_Stretch_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Bulge_Enabled_","_Bulge_Height_","_Bulge_Radius_","_Sun_Intensity_","_Sun_Theta_","_Sun_Phi_","_Indirect_Diffuse_","_Albedo_","_Specular_","_Shininess_","_Sharpness_","_Subsurface_","_Left_Color_","_Right_Color_","_Reflection_","_Front_Reflect_","_Edge_Reflect_","_Power_","_Sky_Color_","_Horizon_Color_","_Ground_Color_","_Horizon_Power_","_Reflection_Map_","_Indirect_Environment_","_Width_","_Fuzz_","_Min_Fuzz_","_Clip_Fade_","_Hue_Shift_","_Saturation_Shift_","_Value_Shift_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Left_Index_Pos_","_Right_Index_Pos_","_Left_Index_Middle_Pos_","_Right_Index_Middle_Pos_","_Decal_","_Decal_Scale_XY_","_Decal_Front_Only_","_Rim_Intensity_","_Rim_Texture_","_Rim_Hue_Shift_","_Rim_Saturation_Shift_","_Rim_Value_Shift_","_Iridescence_Intensity_","_Iridescence_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Middle_Position;","Global_Right_Index_Middle_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],h=["_Rim_Texture_","_Iridescence_Texture_"],c=[];(0,Bt.Bb)({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:r,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),r)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Bevel_Front_",this.bevelFront),this._activeEffect.setFloat("_Bevel_Front_Stretch_",this.bevelFrontStretch),this._activeEffect.setFloat("_Bevel_Back_",this.bevelBack),this._activeEffect.setFloat("_Bevel_Back_Stretch_",this.bevelBackStretch),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Bulge_Enabled_",this.bulgeEnabled?1:0),this._activeEffect.setFloat("_Bulge_Height_",this.bulgeHeight),this._activeEffect.setFloat("_Bulge_Radius_",this.bulgeRadius),this._activeEffect.setFloat("_Sun_Intensity_",this.sunIntensity),this._activeEffect.setFloat("_Sun_Theta_",this.sunTheta),this._activeEffect.setFloat("_Sun_Phi_",this.sunPhi),this._activeEffect.setFloat("_Indirect_Diffuse_",this.indirectDiffuse),this._activeEffect.setDirectColor4("_Albedo_",this.albedo),this._activeEffect.setFloat("_Specular_",this.specular),this._activeEffect.setFloat("_Shininess_",this.shininess),this._activeEffect.setFloat("_Sharpness_",this.sharpness),this._activeEffect.setFloat("_Subsurface_",this.subsurface),this._activeEffect.setDirectColor4("_Left_Color_",this.leftGradientColor),this._activeEffect.setDirectColor4("_Right_Color_",this.rightGradientColor),this._activeEffect.setFloat("_Reflection_",this.reflection),this._activeEffect.setFloat("_Front_Reflect_",this.frontReflect),this._activeEffect.setFloat("_Edge_Reflect_",this.edgeReflect),this._activeEffect.setFloat("_Power_",this.power),this._activeEffect.setDirectColor4("_Sky_Color_",this.skyColor),this._activeEffect.setDirectColor4("_Horizon_Color_",this.horizonColor),this._activeEffect.setDirectColor4("_Ground_Color_",this.groundColor),this._activeEffect.setFloat("_Horizon_Power_",this.horizonPower),this._activeEffect.setTexture("_Reflection_Map_",this._reflectionMapTexture),this._activeEffect.setTexture("_Indirect_Environment_",this._indirectEnvTexture),this._activeEffect.setFloat("_Width_",this.width),this._activeEffect.setFloat("_Fuzz_",this.fuzz),this._activeEffect.setFloat("_Min_Fuzz_",this.minFuzz),this._activeEffect.setFloat("_Clip_Fade_",this.clipFade),this._activeEffect.setFloat("_Hue_Shift_",this.hueShift),this._activeEffect.setFloat("_Saturation_Shift_",this.saturationShift),this._activeEffect.setFloat("_Value_Shift_",this.valueShift),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this.blobTexture),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setVector3("_Left_Index_Pos_",this.leftIndexPosition),this._activeEffect.setVector3("_Right_Index_Pos_",this.rightIndexPosition),this._activeEffect.setVector3("_Left_Index_Middle_Pos_",this.leftIndexMiddlePosition),this._activeEffect.setVector3("_Right_Index_Middle_Pos_",this.rightIndexMiddlePosition),this._activeEffect.setTexture("_Decal_",this._decalTexture),this._activeEffect.setVector2("_Decal_Scale_XY_",this.decalScaleXY),this._activeEffect.setFloat("_Decal_Front_Only_",this.decalFrontOnly?1:0),this._activeEffect.setFloat("_Rim_Intensity_",this.rimIntensity),this._activeEffect.setTexture("_Rim_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("_Rim_Hue_Shift_",this.rimHueShift),this._activeEffect.setFloat("_Rim_Saturation_Shift_",this.rimSaturationShift),this._activeEffect.setFloat("_Rim_Value_Shift_",this.rimValueShift),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setTexture("_Iridescence_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("Use_Global_Left_Index",this.useGlobalLeftIndex),this._activeEffect.setFloat("Use_Global_Right_Index",this.useGlobalRightIndex),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this.globalLeftIndexTipPosition),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this.globaRightIndexTipPosition),this._activeEffect.setVector4("Global_Left_Thumb_Tip_Position",this.globalLeftThumbTipPosition),this._activeEffect.setVector4("Global_Right_Thumb_Tip_Position",this.globalRightThumbTipPosition),this._activeEffect.setVector4("Global_Left_Index_Middle_Position",this.globalLeftIndexMiddlePosition),this._activeEffect.setVector4("Global_Right_Index_Middle_Position",this.globalRightIndexMiddlePosition),this._activeEffect.setFloat("Global_Left_Index_Tip_Proximity",this.globalLeftIndexTipProximity),this._activeEffect.setFloat("Global_Right_Index_Tip_Proximity",this.globalRightIndexTipProximity),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._reflectionMapTexture.dispose(),this._indirectEnvTexture.dispose(),this._blueGradientTexture.dispose(),this._decalTexture.dispose()}clone(e){return it.p.Clone((()=>new BV(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLSliderThumbMaterial",e}getClassName(){return"MRDLSliderThumbMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new BV(e.name,t)),e,t,i)}}BV.BLUE_GRADIENT_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-blue-gradient.png",(0,je.Cg)([(0,$e.lK)()],BV.prototype,"radius",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"bevelFront",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"bevelFrontStretch",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"bevelBack",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"bevelBackStretch",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"radiusTopLeft",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"radiusTopRight",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"radiusBottomLeft",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"radiusBottomRight",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"bulgeEnabled",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"bulgeHeight",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"bulgeRadius",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"sunIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"sunTheta",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"sunPhi",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"indirectDiffuse",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"albedo",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"specular",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"shininess",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"sharpness",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"subsurface",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"leftGradientColor",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"rightGradientColor",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"reflection",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"frontReflect",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"edgeReflect",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"power",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"skyColor",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"horizonColor",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"groundColor",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"horizonPower",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"width",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"fuzz",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"minFuzz",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"clipFade",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"hueShift",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"saturationShift",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"valueShift",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobPosition",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobNearSize",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobFarSize",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobNearDistance",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobFarDistance",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobFadeLength",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobPulse",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobFade",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobPosition2",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobNearSize2",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobPulse2",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobFade2",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"blobTexture",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"leftIndexPosition",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"rightIndexPosition",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"leftIndexMiddlePosition",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"rightIndexMiddlePosition",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"decalScaleXY",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"decalFrontOnly",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"rimIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"rimHueShift",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"rimSaturationShift",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"rimValueShift",void 0),(0,je.Cg)([(0,$e.lK)()],BV.prototype,"iridescenceIntensity",void 0),(0,X.Y5)("BABYLON.GUI.MRDLSliderThumbMaterial",BV);Cs.l.ShadersStore.mrdlBackplatePixelShader="uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vExtra1;varying vec4 vExtra2;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Filter_Width_;uniform vec4 _Base_Color_;uniform vec4 _Line_Color_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform float _Rate_;uniform vec4 _Highlight_Color_;uniform float _Highlight_Width_;uniform vec4 _Highlight_Transform_;uniform float _Highlight_;uniform float _Iridescence_Intensity_;uniform float _Iridescence_Edge_Intensity_;uniform vec4 _Iridescence_Tint_;uniform sampler2D _Iridescent_Map_;uniform float _Angle_;uniform bool _Reflected_;uniform float _Frequency_;uniform float _Vertical_Offset_;uniform vec4 _Gradient_Color_;uniform vec4 _Top_Left_;uniform vec4 _Top_Right_;uniform vec4 _Bottom_Left_;uniform vec4 _Bottom_Right_;uniform float _Edge_Width_;uniform float _Edge_Power_;uniform float _Line_Gradient_Blend_;uniform float _Fade_Out_;void FastLinearTosRGB_B353(\nvec4 Linear,\nout vec4 sRGB)\n{sRGB.rgb=sqrt(clamp(Linear.rgb,0.0,1.0));sRGB.a=Linear.a;}\nvoid Round_Rect_Fragment_B332(\nfloat Radius,\nfloat Line_Width,\nvec4 Line_Color,\nfloat Filter_Width,\nvec2 UV,\nfloat Line_Visibility,\nvec4 Rect_Parms,\nvec4 Fill_Color,\nout vec4 Color)\n{float d=length(max(abs(UV)-Rect_Parms.xy,0.0));float dx=max(fwidth(d)*Filter_Width,0.00001);float g=min(Rect_Parms.z,Rect_Parms.w);float dgrad=max(fwidth(g)*Filter_Width,0.00001);float Inside_Rect=clamp(g/dgrad,0.0,1.0);float inner=clamp((d+dx*0.5-max(Radius-Line_Width,d-dx*0.5))/dx,0.0,1.0);Color=clamp(mix(Fill_Color,Line_Color,inner),0.0,1.0)*Inside_Rect;}\nvoid Iridescence_B343(\nvec3 Position,\nvec3 Normal,\nvec2 UV,\nvec3 Axis,\nvec3 Eye,\nvec4 Tint,\nsampler2D Texture,\nbool Reflected,\nfloat Frequency,\nfloat Vertical_Offset,\nout vec4 Color)\n{vec3 i=normalize(Position-Eye);vec3 r=reflect(i,Normal);float idota=dot(i,Axis);float idotr=dot(i,r);float x=Reflected ? idotr : idota;vec2 xy;xy.x=fract((x*Frequency+1.0)*0.5+UV.y*Vertical_Offset);xy.y=0.5;Color=texture(Texture,xy);Color.rgb*=Tint.rgb;}\nvoid Scale_RGB_B346(\nvec4 Color,\nfloat Scalar,\nout vec4 Result)\n{Result=vec4(Scalar,Scalar,Scalar,1)*Color;}\nvoid Scale_RGB_B344(\nfloat Scalar,\nvec4 Color,\nout vec4 Result)\n{Result=vec4(Scalar,Scalar,Scalar,1)*Color;}\nvoid Line_Fragment_B362(\nvec4 Base_Color,\nvec4 Highlight_Color,\nfloat Highlight_Width,\nvec3 Line_Vertex,\nfloat Highlight,\nout vec4 Line_Color)\n{float k2=1.0-clamp(abs(Line_Vertex.y/Highlight_Width),0.0,1.0);Line_Color=mix(Base_Color,Highlight_Color,Highlight*k2);}\nvoid Edge_B356(\nvec4 RectParms,\nfloat Radius,\nfloat Line_Width,\nvec2 UV,\nfloat Edge_Width,\nfloat Edge_Power,\nout float Result)\n{float d=length(max(abs(UV)-RectParms.xy,0.0));float edge=1.0-clamp((1.0-d/(Radius-Line_Width))/Edge_Width,0.0,1.0);Result=pow(edge,Edge_Power);}\nvoid Gradient_B355(\nvec4 Gradient_Color,\nvec4 Top_Left,\nvec4 Top_Right,\nvec4 Bottom_Left,\nvec4 Bottom_Right,\nvec2 UV,\nout vec4 Result)\n{vec3 top=Top_Left.rgb+(Top_Right.rgb-Top_Left.rgb)*UV.x;vec3 bottom=Bottom_Left.rgb+(Bottom_Right.rgb-Bottom_Left.rgb)*UV.x;Result.rgb=Gradient_Color.rgb*(bottom+(top-bottom)*UV.y);Result.a=1.0;}\nvoid main()\n{float X_Q338;float Y_Q338;float Z_Q338;float W_Q338;X_Q338=vExtra2.x;Y_Q338=vExtra2.y;Z_Q338=vExtra2.z;W_Q338=vExtra2.w;vec4 Color_Q343;\n#if IRIDESCENCE_ENABLE\nIridescence_B343(vPosition,vNormal,vUV,vBinormal,cameraPosition,_Iridescence_Tint_,_Iridescent_Map_,_Reflected_,_Frequency_,_Vertical_Offset_,Color_Q343);\n#else\nColor_Q343=vec4(0,0,0,0);\n#endif\nvec4 Result_Q344;Scale_RGB_B344(_Iridescence_Intensity_,Color_Q343,Result_Q344);vec4 Line_Color_Q362;Line_Fragment_B362(_Line_Color_,_Highlight_Color_,_Highlight_Width_,vTangent,_Highlight_,Line_Color_Q362);float Result_Q356;\n#if EDGE_ONLY\nEdge_B356(vExtra1,Z_Q338,W_Q338,vUV,_Edge_Width_,_Edge_Power_,Result_Q356);\n#else\nResult_Q356=1.0;\n#endif\nvec2 Vec2_Q339=vec2(X_Q338,Y_Q338);vec4 Result_Q355;Gradient_B355(_Gradient_Color_,_Top_Left_,_Top_Right_,_Bottom_Left_,_Bottom_Right_,Vec2_Q339,Result_Q355);vec4 Linear_Q348;Linear_Q348.rgb=clamp(Result_Q355.rgb*Result_Q355.rgb,0.0,1.0);Linear_Q348.a=Result_Q355.a;vec4 Result_Q346;Scale_RGB_B346(Linear_Q348,Result_Q356,Result_Q346);vec4 Sum_Q345=Result_Q346+Result_Q344;vec4 Color_At_T_Q347=mix(Line_Color_Q362,Result_Q346,_Line_Gradient_Blend_);vec4 Base_And_Iridescent_Q350;Base_And_Iridescent_Q350=_Base_Color_+vec4(Sum_Q345.rgb,0.0);vec4 Sum_Q349=Color_At_T_Q347+_Iridescence_Edge_Intensity_*Color_Q343;vec4 Result_Q351=Sum_Q349; Result_Q351.a=1.0;vec4 Color_Q332;Round_Rect_Fragment_B332(Z_Q338,W_Q338,Result_Q351,_Filter_Width_,vUV,1.0,vExtra1,Base_And_Iridescent_Q350,Color_Q332);vec4 Result_Q354=_Fade_Out_*Color_Q332;vec4 sRGB_Q353;FastLinearTosRGB_B353(Result_Q354,sRGB_Q353);vec4 Out_Color=sRGB_Q353;float Clip_Threshold=0.001;bool To_sRGB=false;gl_FragColor=Out_Color;}";Cs.l.ShadersStore.mrdlBackplateVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec3 tangent;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Filter_Width_;uniform vec4 _Base_Color_;uniform vec4 _Line_Color_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform float _Rate_;uniform vec4 _Highlight_Color_;uniform float _Highlight_Width_;uniform vec4 _Highlight_Transform_;uniform float _Highlight_;uniform float _Iridescence_Intensity_;uniform float _Iridescence_Edge_Intensity_;uniform vec4 _Iridescence_Tint_;uniform sampler2D _Iridescent_Map_;uniform float _Angle_;uniform bool _Reflected_;uniform float _Frequency_;uniform float _Vertical_Offset_;uniform vec4 _Gradient_Color_;uniform vec4 _Top_Left_;uniform vec4 _Top_Right_;uniform vec4 _Bottom_Left_;uniform vec4 _Bottom_Right_;uniform float _Edge_Width_;uniform float _Edge_Power_;uniform float _Line_Gradient_Blend_;uniform float _Fade_Out_;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vExtra1;varying vec4 vExtra2;void Object_To_World_Pos_B314(\nvec3 Pos_Object,\nout vec3 Pos_World)\n{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;}\nvoid Round_Rect_Vertex_B357(\nvec2 UV,\nfloat Radius,\nfloat Margin,\nfloat Anisotropy,\nfloat Gradient1,\nfloat Gradient2,\nvec3 Normal,\nvec4 Color_Scale_Translate,\nout vec2 Rect_UV,\nout vec4 Rect_Parms,\nout vec2 Scale_XY,\nout vec2 Line_UV,\nout vec2 Color_UV_Info)\n{Scale_XY=vec2(Anisotropy,1.0);Line_UV=(UV-vec2(0.5,0.5));Rect_UV=Line_UV*Scale_XY;Rect_Parms.xy=Scale_XY*0.5-vec2(Radius,Radius)-vec2(Margin,Margin);Rect_Parms.z=Gradient1; \nRect_Parms.w=Gradient2;Color_UV_Info=(Line_UV+vec2(0.5,0.5))*Color_Scale_Translate.xy+Color_Scale_Translate.zw;}\nvoid Line_Vertex_B333(\nvec2 Scale_XY,\nvec2 UV,\nfloat Time,\nfloat Rate,\nvec4 Highlight_Transform,\nout vec3 Line_Vertex)\n{float angle2=(Rate*Time)*2.0*3.1416;float sinAngle2=sin(angle2);float cosAngle2=cos(angle2);vec2 xformUV=UV*Highlight_Transform.xy+Highlight_Transform.zw;Line_Vertex.x=0.0;Line_Vertex.y=cosAngle2*xformUV.x-sinAngle2*xformUV.y;Line_Vertex.z=0.0; }\nvoid PickDir_B334(\nfloat Degrees,\nvec3 DirX,\nvec3 DirY,\nout vec3 Dir)\n{float a=Degrees*3.14159/180.0;Dir=cos(a)*DirX+sin(a)*DirY;}\nvoid Move_Verts_B327(\nfloat Anisotropy,\nvec3 P,\nfloat Radius,\nout vec3 New_P,\nout vec2 New_UV,\nout float Radial_Gradient,\nout vec3 Radial_Dir)\n{vec2 UV=P.xy*2.0+0.5;vec2 center=clamp(UV,0.0,1.0);vec2 delta=UV-center;vec2 r2=2.0*vec2(Radius/Anisotropy,Radius);New_UV=center+r2*(UV-2.0*center+0.5);New_P=vec3(New_UV-0.5,P.z);Radial_Gradient=1.0-length(delta)*2.0;Radial_Dir=vec3(delta*r2,0.0);}\nvoid Pick_Radius_B336(\nfloat Radius,\nfloat Radius_Top_Left,\nfloat Radius_Top_Right,\nfloat Radius_Bottom_Left,\nfloat Radius_Bottom_Right,\nvec3 Position,\nout float Result)\n{bool whichY=Position.y>0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid Edge_AA_Vertex_B328(\nvec3 Position_World,\nvec3 Position_Object,\nvec3 Normal_Object,\nvec3 Eye,\nfloat Radial_Gradient,\nvec3 Radial_Dir,\nvec3 Tangent,\nout float Gradient1,\nout float Gradient2)\n{vec3 I=(Eye-Position_World);vec3 T=(vec4(Tangent,0.0)).xyz;float g=(dot(T,I)<0.0) ? 0.0 : 1.0;if (Normal_Object.z==0.0) { \nGradient1=Position_Object.z>0.0 ? g : 1.0;Gradient2=Position_Object.z>0.0 ? 1.0 : g;} else {Gradient1=g+(1.0-g)*(Radial_Gradient);Gradient2=1.0;}}\nvoid Object_To_World_Dir_B330(\nvec3 Dir_Object,\nout vec3 Binormal_World,\nout vec3 Binormal_World_N,\nout float Binormal_Length)\n{Binormal_World=(world*vec4(Dir_Object,0.0)).xyz;Binormal_Length=length(Binormal_World);Binormal_World_N=Binormal_World/Binormal_Length;}\nvoid RelativeOrAbsoluteDetail_B341(\nfloat Nominal_Radius,\nfloat Nominal_LineWidth,\nbool Absolute_Measurements,\nfloat Height,\nout float Radius,\nout float Line_Width)\n{float scale=Absolute_Measurements ? 1.0/Height : 1.0;Radius=Nominal_Radius*scale;Line_Width=Nominal_LineWidth*scale;}\nvoid main()\n{vec3 Nrm_World_Q326;Nrm_World_Q326=normalize((world*vec4(normal,0.0)).xyz);vec3 Tangent_World_Q329;vec3 Tangent_World_N_Q329;float Tangent_Length_Q329;Tangent_World_Q329=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q329=length(Tangent_World_Q329);Tangent_World_N_Q329=Tangent_World_Q329/Tangent_Length_Q329;vec3 Binormal_World_Q330;vec3 Binormal_World_N_Q330;float Binormal_Length_Q330;Object_To_World_Dir_B330(vec3(0,1,0),Binormal_World_Q330,Binormal_World_N_Q330,Binormal_Length_Q330);float Radius_Q341;float Line_Width_Q341;RelativeOrAbsoluteDetail_B341(_Radius_,_Line_Width_,_Absolute_Sizes_,Binormal_Length_Q330,Radius_Q341,Line_Width_Q341);vec3 Dir_Q334;PickDir_B334(_Angle_,Tangent_World_N_Q329,Binormal_World_N_Q330,Dir_Q334);float Result_Q336;Pick_Radius_B336(Radius_Q341,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q336);float Anisotropy_Q331=Tangent_Length_Q329/Binormal_Length_Q330;vec4 Out_Color_Q337=vec4(Result_Q336,Line_Width_Q341,0,1);vec3 New_P_Q327;vec2 New_UV_Q327;float Radial_Gradient_Q327;vec3 Radial_Dir_Q327;Move_Verts_B327(Anisotropy_Q331,position,Result_Q336,New_P_Q327,New_UV_Q327,Radial_Gradient_Q327,Radial_Dir_Q327);vec3 Pos_World_Q314;Object_To_World_Pos_B314(New_P_Q327,Pos_World_Q314);float Gradient1_Q328;float Gradient2_Q328;\n#if SMOOTH_EDGES\nEdge_AA_Vertex_B328(Pos_World_Q314,position,normal,cameraPosition,Radial_Gradient_Q327,Radial_Dir_Q327,tangent,Gradient1_Q328,Gradient2_Q328);\n#else\nGradient1_Q328=1.0;Gradient2_Q328=1.0;\n#endif\nvec2 Rect_UV_Q357;vec4 Rect_Parms_Q357;vec2 Scale_XY_Q357;vec2 Line_UV_Q357;vec2 Color_UV_Info_Q357;Round_Rect_Vertex_B357(New_UV_Q327,Result_Q336,0.0,Anisotropy_Q331,Gradient1_Q328,Gradient2_Q328,normal,vec4(1,1,0,0),Rect_UV_Q357,Rect_Parms_Q357,Scale_XY_Q357,Line_UV_Q357,Color_UV_Info_Q357);vec3 Line_Vertex_Q333;Line_Vertex_B333(Scale_XY_Q357,Line_UV_Q357,(20.0),_Rate_,_Highlight_Transform_,Line_Vertex_Q333);float X_Q359;float Y_Q359;X_Q359=Color_UV_Info_Q357.x;Y_Q359=Color_UV_Info_Q357.y;vec4 Vec4_Q358=vec4(X_Q359,Y_Q359,Result_Q336,Line_Width_Q341);vec3 Position=Pos_World_Q314;vec3 Normal=Nrm_World_Q326;vec2 UV=Rect_UV_Q357;vec3 Tangent=Line_Vertex_Q333;vec3 Binormal=Dir_Q334;vec4 Color=Out_Color_Q337;vec4 Extra1=Rect_Parms_Q357;vec4 Extra2=Vec4_Q358;vec4 Extra3=vec4(0,0,0,0);gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vExtra1=Extra1;vExtra2=Extra2;}";class VV extends xn{constructor(){super(),this.IRIDESCENCE_ENABLE=!0,this.SMOOTH_EDGES=!0,this._needNormals=!0,this.rebuild()}}class kV extends bn{constructor(e,t){super(e,t),this.radius=.3,this.lineWidth=.003,this.absoluteSizes=!1,this._filterWidth=1,this.baseColor=new H.ov(0,0,0,1),this.lineColor=new H.ov(.2,.262745,.4,1),this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this._rate=0,this.highlightColor=new H.ov(.239216,.435294,.827451,1),this.highlightWidth=0,this._highlightTransform=new W.IU(1,1,0,0),this._highlight=1,this.iridescenceIntensity=.45,this.iridescenceEdgeIntensity=1,this.iridescenceTint=new H.ov(1,1,1,1),this._angle=-45,this.fadeOut=1,this._reflected=!0,this._frequency=1,this._verticalOffset=0,this.gradientColor=new H.ov(.74902,.74902,.74902,1),this.topLeftGradientColor=new H.ov(.00784314,.294118,.580392,1),this.topRightGradientColor=new H.ov(.305882,0,1,1),this.bottomLeftGradientColor=new H.ov(.133333,.258824,.992157,1),this.bottomRightGradientColor=new H.ov(.176471,.176471,.619608,1),this.edgeWidth=.5,this.edgePower=1,this.edgeLineGradientBlend=.5,this.alphaMode=Il.ALPHA_DISABLE,this.backFaceCulling=!1,this._iridescentMapTexture=new vi.g(kV.IRIDESCENT_MAP_TEXTURE_URL,this.getScene(),!0,!1,vi.g.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new VV);const r=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if((0,Bt.qB)(e,r,!1,!1),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=new Tn;r.FOG&&e.addFallback(1,"FOG"),(0,Bt.c4)(r,e),r.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const i=[st.R.PositionKind];r.NORMAL&&i.push(st.R.NormalKind),r.UV1&&i.push(st.R.UVKind),r.UV2&&i.push(st.R.UV2Kind),r.VERTEXCOLOR&&i.push(st.R.ColorKind),r.TANGENT&&i.push(st.R.TangentKind),(0,Bt.ER)(i,r);const o="mrdlBackplate",a=r.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Absolute_Sizes_","_Filter_Width_","_Base_Color_","_Line_Color_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Rate_","_Highlight_Color_","_Highlight_Width_","_Highlight_Transform_","_Highlight_","_Iridescence_Intensity_","_Iridescence_Edge_Intensity_","_Iridescence_Tint_","_Iridescent_Map_","_Angle_","_Reflected_","_Frequency_","_Vertical_Offset_","_Gradient_Color_","_Top_Left_","_Top_Right_","_Bottom_Left_","_Bottom_Right_","_Edge_Width_","_Edge_Power_","_Line_Gradient_Blend_","_Fade_Out_"],h=["_Iridescent_Map_"],c=[];(0,Bt.Bb)({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:r,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),r)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Base_Color_",this.baseColor),this._activeEffect.setDirectColor4("_Line_Color_",this.lineColor),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Rate_",this._rate),this._activeEffect.setDirectColor4("_Highlight_Color_",this.highlightColor),this._activeEffect.setFloat("_Highlight_Width_",this.highlightWidth),this._activeEffect.setVector4("_Highlight_Transform_",this._highlightTransform),this._activeEffect.setFloat("_Highlight_",this._highlight),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setFloat("_Iridescence_Edge_Intensity_",this.iridescenceEdgeIntensity),this._activeEffect.setDirectColor4("_Iridescence_Tint_",this.iridescenceTint),this._activeEffect.setTexture("_Iridescent_Map_",this._iridescentMapTexture),this._activeEffect.setFloat("_Angle_",this._angle),this._activeEffect.setFloat("_Reflected_",this._reflected?1:0),this._activeEffect.setFloat("_Frequency_",this._frequency),this._activeEffect.setFloat("_Vertical_Offset_",this._verticalOffset),this._activeEffect.setDirectColor4("_Gradient_Color_",this.gradientColor),this._activeEffect.setDirectColor4("_Top_Left_",this.topLeftGradientColor),this._activeEffect.setDirectColor4("_Top_Right_",this.topRightGradientColor),this._activeEffect.setDirectColor4("_Bottom_Left_",this.bottomLeftGradientColor),this._activeEffect.setDirectColor4("_Bottom_Right_",this.bottomRightGradientColor),this._activeEffect.setFloat("_Edge_Width_",this.edgeWidth),this._activeEffect.setFloat("_Edge_Power_",this.edgePower),this._activeEffect.setFloat("_Line_Gradient_Blend_",this.edgeLineGradientBlend),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return it.p.Clone((()=>new kV(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLBackplateMaterial",e}getClassName(){return"MRDLBackplateMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new kV(e.name,t)),e,t,i)}}kV.IRIDESCENT_MAP_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-backplate-iridescence.png",(0,je.Cg)([(0,$e.lK)()],kV.prototype,"radius",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"lineWidth",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"absoluteSizes",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"baseColor",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"lineColor",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"radiusTopLeft",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"radiusTopRight",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"radiusBottomLeft",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"radiusBottomRight",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"highlightColor",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"highlightWidth",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"iridescenceIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"iridescenceEdgeIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"iridescenceTint",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"fadeOut",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"gradientColor",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"topLeftGradientColor",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"topRightGradientColor",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"bottomLeftGradientColor",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"bottomRightGradientColor",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"edgeWidth",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"edgePower",void 0),(0,je.Cg)([(0,$e.lK)()],kV.prototype,"edgeLineGradientBlend",void 0),(0,X.Y5)("BABYLON.GUI.MRDLBackplateMaterial",kV);class UV extends rV{constructor(e,t){super(e),this.onValueChangedObservable=new z.cP,this._sliderBackplateVisible=t||!1,this._minimum=0,this._maximum=100,this._step=0,this._value=50}get mesh(){return this.node?this._sliderThumb:null}get minimum(){return this._minimum}set minimum(e){this._minimum!==e&&(this._minimum=Math.max(e,0),this._value=Math.max(Math.min(this._value,this._maximum),this._minimum))}get maximum(){return this._maximum}set maximum(e){this._maximum!==e&&(this._maximum=Math.max(e,this._minimum),this._value=Math.max(Math.min(this._value,this._maximum),this._minimum))}get step(){return this._step}set step(e){this._step!==e&&(this._step=Math.max(Math.min(e,this._maximum-this._minimum),0))}get value(){return this._value}set value(e){this._value!==e&&(this._value=Math.max(Math.min(e,this._maximum),this._minimum),this._sliderThumb&&(this._sliderThumb.position.x=this._convertToPosition(this.value)),this.onValueChangedObservable.notifyObservers(this._value))}get start(){return this.node?this._sliderBar.position.x-this._sliderBar.scaling.x/2:-.5}get end(){return this.node?this._sliderBar.position.x+this._sliderBar.scaling.x/2:.5}get sliderBarMaterial(){return this._sliderBarMaterial}get sliderThumbMaterial(){return this._sliderThumbMaterial}get sliderBackplateMaterial(){return this._sliderBackplateMaterial}get sliderBar(){return this._sliderBar}get sliderThumb(){return this._sliderThumb}get sliderBackplate(){return this._sliderBackplate}set isVisible(e){this._isVisible!==e&&(this._isVisible=e,this.node?.setEnabled(e))}_createNode(e){const t=Ko(`${this.name}_sliderbackplate`,{width:1,height:1,depth:1},e);return t.isPickable=!1,t.visibility=0,t.scaling=new W.Pq(1,.5,.8),xg.ImportMeshAsync(void 0,UV.MODEL_BASE_URL,UV.MODEL_FILENAME,e).then((e=>{e.meshes.forEach((e=>{e.isPickable=!1}));const i=e.meshes[1],r=e.meshes[1].clone(`${this.name}_sliderbar`,t),s=e.meshes[1].clone(`${this.name}_sliderthumb`,t);i.visibility=0,this._sliderBackplateVisible&&(i.visibility=1,i.name=`${this.name}_sliderbackplate`,i.scaling.x=1,i.scaling.z=.2,i.parent=t,this._sliderBackplateMaterial&&(i.material=this._sliderBackplateMaterial),this._sliderBackplate=i),r&&(r.parent=t,r.position.z=-.1,r.scaling=new W.Pq(.8,.04,.3),this._sliderBarMaterial&&(r.material=this._sliderBarMaterial),this._sliderBar=r),s&&(s.parent=t,s.isPickable=!0,s.position.z=-.115,s.scaling=new W.Pq(.025,.3,.6),s.position.x=this._convertToPosition(this.value),s.addBehavior(this._createBehavior()),this._sliderThumbMaterial&&(s.material=this._sliderThumbMaterial),this._sliderThumb=s),this._injectGUI3DReservedDataStore(t).control=this,t.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this}))})),this._affectMaterial(t),t}_affectMaterial(e){this._sliderBackplateMaterial=this._sliderBackplateMaterial??new kV(`${this.name}_sliderbackplate_material`,e.getScene()),this._sliderBarMaterial=this._sliderBarMaterial??new FV(`${this.name}_sliderbar_material`,e.getScene()),this._sliderThumbMaterial=this._sliderThumbMaterial??new BV(`${this.name}_sliderthumb_material`,e.getScene())}_createBehavior(){const e=new Ji({dragAxis:W.Pq.Right()});return e.moveAttached=!1,e.onDragStartObservable.add((()=>{this._draggedPosition=this._sliderThumb.position.x})),e.onDragObservable.add((e=>{this._draggedPosition+=e.dragDistance/this.scaling.x,this.value=this._convertToValue(this._draggedPosition)})),e}_convertToPosition(e){const t=(e-this.minimum)/(this.maximum-this.minimum)*(this.end-this.start)+this.start;return Math.min(Math.max(t,this.start),this.end)}_convertToValue(e){let t=(e-this.start)/(this.end-this.start)*(this.maximum-this.minimum);return t=this.step?Math.round(t/this.step)*this.step:t,Math.max(Math.min(this.minimum+t,this._maximum),this._minimum)}dispose(){super.dispose(),this._sliderBar?.dispose(),this._sliderThumb?.dispose(),this._sliderBarMaterial?.dispose(),this._sliderThumbMaterial?.dispose(),this._sliderBackplate?.dispose(),this._sliderBackplateMaterial?.dispose()}}UV.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",UV.MODEL_FILENAME="mrtk-fluent-backplate.glb";class GV extends lV{constructor(){super(...arguments),this._radius=5}get radius(){return this._radius}set radius(e){this._radius!==e&&(this._radius=e,Ue.S0.SetImmediate((()=>{this._arrangeChildren()})))}_mapGridNode(e,t){const i=e.mesh;if(!i)return;const r=this._sphericalMapping(t);switch(e.position=r,this.orientation){case aV.FACEORIGIN_ORIENTATION:i.lookAt(new W.Pq(2*r.x,2*r.y,2*r.z));break;case aV.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new W.Pq(-r.x,-r.y,-r.z));break;case aV.FACEFORWARD_ORIENTATION:break;case aV.FACEFORWARDREVERSED_ORIENTATION:i.rotate(Mt._0.Y,Math.PI,0)}}_sphericalMapping(e){const t=new W.Pq(0,0,this._radius),i=e.y/this._radius,r=-e.x/this._radius;return W.uq.RotationYawPitchRollToRef(r,i,0,W.AA.Matrix[0]),W.Pq.TransformNormal(t,W.AA.Matrix[0])}}class zV extends aV{get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,Ue.S0.SetImmediate((()=>{this._arrangeChildren()})))}constructor(e=!1){super(),this._isVertical=!1,this.margin=.1,this._isVertical=e}_arrangeChildren(){let e=0,t=0,i=0;const r=[],s=W.uq.Invert(this.node.computeWorldMatrix(!0));for(const n of this._children){if(!n.mesh)continue;i++,n.mesh.computeWorldMatrix(!0),n.mesh.getWorldMatrix().multiplyToRef(s,W.AA.Matrix[0]);const o=n.mesh.getBoundingInfo().boundingBox,a=W.Pq.TransformNormal(o.extendSize,W.AA.Matrix[0]);r.push(a),this._isVertical?t+=a.y:e+=a.x}let n;this._isVertical?t+=(i-1)*this.margin/2:e+=(i-1)*this.margin/2,n=this._isVertical?-t:-e;let o=0;for(const e of this._children){if(!e.mesh)continue;i--;const t=r[o++];this._isVertical?(e.position.y=n+t.y,e.position.x=0,n+=2*t.y):(e.position.x=n+t.x,e.position.y=0,n+=2*t.x),n+=i>0?this.margin:0}}}class WV extends bV{constructor(e,t){super(t,e),this._currentMesh=e,this.pointerEnterAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1.1)},this.pointerOutAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/1.1)},this.pointerDownAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/.95)}}_getTypeName(){return"TouchMeshButton3D"}_createNode(){return this._currentMesh.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this})),this._currentMesh}_affectMaterial(e){}}Cs.l.ShadersStore.mrdlBackglowPixelShader="uniform vec3 cameraPosition;varying vec3 vNormal;varying vec2 vUV;uniform float _Bevel_Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Tuning_Motion_;uniform float _Motion_;uniform float _Max_Intensity_;uniform float _Intensity_Fade_In_Exponent_;uniform float _Outer_Fuzz_Start_;uniform float _Outer_Fuzz_End_;uniform vec4 _Color_;uniform vec4 _Inner_Color_;uniform float _Blend_Exponent_;uniform float _Falloff_;uniform float _Bias_;float BiasFunc(float b,float v) {return pow(v,log(clamp(b,0.001,0.999))/log(0.5));}\nvoid Fuzzy_Round_Rect_B33(\nfloat Size_X,\nfloat Size_Y,\nfloat Radius_X,\nfloat Radius_Y,\nfloat Line_Width,\nvec2 UV,\nfloat Outer_Fuzz,\nfloat Max_Outer_Fuzz,\nout float Rect_Distance,\nout float Inner_Distance)\n{vec2 halfSize=vec2(Size_X,Size_Y)*0.5;vec2 r=max(min(vec2(Radius_X,Radius_Y),halfSize),vec2(0.001,0.001));float radius=min(r.x,r.y)-Max_Outer_Fuzz;vec2 v=abs(UV);vec2 nearestp=min(v,halfSize-r);float d=distance(nearestp,v);Inner_Distance=clamp(1.0-(radius-d)/Line_Width,0.0,1.0);Rect_Distance=clamp(1.0-(d-radius)/Outer_Fuzz,0.0,1.0)*Inner_Distance;}\nvoid main()\n{float X_Q42;float Y_Q42;X_Q42=vNormal.x;Y_Q42=vNormal.y;float MaxAB_Q24=max(_Tuning_Motion_,_Motion_);float Sqrt_F_Q27=sqrt(MaxAB_Q24);float Power_Q43=pow(MaxAB_Q24,_Intensity_Fade_In_Exponent_);float Value_At_T_Q26=mix(_Outer_Fuzz_Start_,_Outer_Fuzz_End_,Sqrt_F_Q27);float Product_Q23=_Max_Intensity_*Power_Q43;float Rect_Distance_Q33;float Inner_Distance_Q33;Fuzzy_Round_Rect_B33(X_Q42,Y_Q42,_Bevel_Radius_,_Bevel_Radius_,_Line_Width_,vUV,Value_At_T_Q26,_Outer_Fuzz_Start_,Rect_Distance_Q33,Inner_Distance_Q33);float Power_Q44=pow(Inner_Distance_Q33,_Blend_Exponent_);float Result_Q45=pow(BiasFunc(_Bias_,Rect_Distance_Q33),_Falloff_);vec4 Color_At_T_Q25=mix(_Inner_Color_,_Color_,Power_Q44);float Product_Q22=Result_Q45*Product_Q23;vec4 Result_Q28=Product_Q22*Color_At_T_Q25;vec4 Out_Color=Result_Q28;float Clip_Threshold=0.0;gl_FragColor=Out_Color;}";Cs.l.ShadersStore.mrdlBackglowVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;uniform float _Bevel_Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Tuning_Motion_;uniform float _Motion_;uniform float _Max_Intensity_;uniform float _Intensity_Fade_In_Exponent_;uniform float _Outer_Fuzz_Start_;uniform float _Outer_Fuzz_End_;uniform vec4 _Color_;uniform vec4 _Inner_Color_;uniform float _Blend_Exponent_;uniform float _Falloff_;uniform float _Bias_;varying vec3 vNormal;varying vec2 vUV;void main()\n{vec3 Dir_World_Q41=(world*vec4(tangent,0.0)).xyz;vec3 Dir_World_Q40=(world*vec4((cross(normal,tangent)),0.0)).xyz;float MaxAB_Q24=max(_Tuning_Motion_,_Motion_);float Length_Q16=length(Dir_World_Q41);float Length_Q17=length(Dir_World_Q40);bool Greater_Than_Q37=MaxAB_Q24>0.0;vec3 Sizes_Q35;vec2 XY_Q35;Sizes_Q35=(_Absolute_Sizes_ ? vec3(Length_Q16,Length_Q17,0) : vec3(Length_Q16/Length_Q17,1,0));XY_Q35=(uv-vec2(0.5,0.5))*Sizes_Q35.xy;vec3 Result_Q38=Greater_Than_Q37 ? position : vec3(0,0,0);vec3 Pos_World_Q39=(world*vec4(Result_Q38,1.0)).xyz;vec3 Position=Pos_World_Q39;vec3 Normal=Sizes_Q35;vec2 UV=XY_Q35;vec3 Tangent=vec3(0,0,0);vec3 Binormal=vec3(0,0,0);vec4 Color=vec4(1,1,1,1);gl_Position=viewProjection*vec4(Position,1);vNormal=Normal;vUV=UV;}";class HV extends xn{constructor(){super(),this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class XV extends bn{constructor(e,t){super(e,t),this.bevelRadius=.16,this.lineWidth=.16,this.absoluteSizes=!1,this.tuningMotion=0,this.motion=1,this.maxIntensity=.7,this.intensityFadeInExponent=2,this.outerFuzzStart=.04,this.outerFuzzEnd=.04,this.color=new H.ov(.682353,.698039,1,1),this.innerColor=new H.ov(.356863,.392157,.796078,1),this.blendExponent=1.5,this.falloff=2,this.bias=.5,this.alphaMode=Il.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new HV);const r=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if((0,Bt.qB)(e,r,!1,!1),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=new Tn;r.FOG&&e.addFallback(1,"FOG"),(0,Bt.c4)(r,e),r.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const i=[st.R.PositionKind];r.NORMAL&&i.push(st.R.NormalKind),r.UV1&&i.push(st.R.UVKind),r.UV2&&i.push(st.R.UV2Kind),r.VERTEXCOLOR&&i.push(st.R.ColorKind),r.TANGENT&&i.push(st.R.TangentKind),(0,Bt.ER)(i,r);const o="mrdlBackglow",a=r.toString(),l=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Bevel_Radius_","_Line_Width_","_Absolute_Sizes_","_Tuning_Motion_","_Motion_","_Max_Intensity_","_Intensity_Fade_In_Exponent_","_Outer_Fuzz_Start_","_Outer_Fuzz_End_","_Color_","_Inner_Color_","_Blend_Exponent_","_Falloff_","_Bias_"],h=[],c=[];(0,Bt.Bb)({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:r,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),r)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const r=this.getScene();if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",r.activeCamera.position),this._activeEffect.setFloat("_Bevel_Radius_",this.bevelRadius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Tuning_Motion_",this.tuningMotion),this._activeEffect.setFloat("_Motion_",this.motion),this._activeEffect.setFloat("_Max_Intensity_",this.maxIntensity),this._activeEffect.setFloat("_Intensity_Fade_In_Exponent_",this.intensityFadeInExponent),this._activeEffect.setFloat("_Outer_Fuzz_Start_",this.outerFuzzStart),this._activeEffect.setFloat("_Outer_Fuzz_End_",this.outerFuzzEnd),this._activeEffect.setDirectColor4("_Color_",this.color),this._activeEffect.setDirectColor4("_Inner_Color_",this.innerColor),this._activeEffect.setFloat("_Blend_Exponent_",this.blendExponent),this._activeEffect.setFloat("_Falloff_",this.falloff),this._activeEffect.setFloat("_Bias_",this.bias),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return it.p.Clone((()=>new XV(e,this.getScene())),this)}serialize(){const e=it.p.Serialize(this);return e.customType="BABYLON.MRDLBackglowMaterial",e}getClassName(){return"MRDLBackglowMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new XV(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.lK)()],XV.prototype,"bevelRadius",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"lineWidth",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"absoluteSizes",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"tuningMotion",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"motion",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"maxIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"intensityFadeInExponent",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"outerFuzzStart",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"outerFuzzEnd",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"color",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"innerColor",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"blendExponent",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"falloff",void 0),(0,je.Cg)([(0,$e.lK)()],XV.prototype,"bias",void 0),(0,X.Y5)("BABYLON.GUI.MRDLBackglowMaterial",XV);Cs.l.ShadersStore.mrdlFrontplatePixelShader="uniform vec3 cameraPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Relative_To_Height_;uniform float _Filter_Width_;uniform vec4 _Edge_Color_;uniform float _Fade_Out_;uniform bool _Smooth_Edges_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform float _Blob_Pulse_Max_Size_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform float _Gaze_Intensity_;uniform float _Gaze_Focus_;uniform sampler2D _Blob_Texture_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform bool _Use_Global_Left_Index_;uniform bool _Use_Global_Right_Index_;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;void Scale_Color_B54(\nvec4 Color,\nfloat Scalar,\nout vec4 Result)\n{Result=Scalar*Color;}\nvoid Scale_RGB_B50(\nvec4 Color,\nfloat Scalar,\nout vec4 Result)\n{Result=vec4(Scalar,Scalar,Scalar,1)*Color;}\nvoid Proximity_Fragment_B51(\nfloat Proximity_Max_Intensity,\nfloat Proximity_Near_Radius,\nvec4 Deltas,\nfloat Show_Selection,\nfloat Distance_Fade1,\nfloat Distance_Fade2,\nfloat Strength,\nout float Proximity)\n{float proximity1=(1.0-clamp(length(Deltas.xy)/Proximity_Near_Radius,0.0,1.0))*Distance_Fade1;float proximity2=(1.0-clamp(length(Deltas.zw)/Proximity_Near_Radius,0.0,1.0))*Distance_Fade2;Proximity=Strength*(Proximity_Max_Intensity*max(proximity1,proximity2) *(1.0-Show_Selection)+Show_Selection);}\nvoid Blob_Fragment_B56(\nvec2 UV,\nvec3 Blob_Info,\nsampler2D Blob_Texture,\nout vec4 Blob_Color)\n{float k=dot(UV,UV);Blob_Color=Blob_Info.y*texture(Blob_Texture,vec2(vec2(sqrt(k),Blob_Info.x).x,1.0-vec2(sqrt(k),Blob_Info.x).y))*(1.0-clamp(k,0.0,1.0));}\nvoid Round_Rect_Fragment_B61(\nfloat Radius,\nvec4 Line_Color,\nfloat Filter_Width,\nfloat Line_Visibility,\nvec4 Fill_Color,\nbool Smooth_Edges,\nvec4 Rect_Parms,\nout float Inside_Rect)\n{float d=length(max(abs(Rect_Parms.zw)-Rect_Parms.xy,0.0));float dx=max(fwidth(d)*Filter_Width,0.00001);Inside_Rect=Smooth_Edges ? clamp((Radius-d)/dx,0.0,1.0) : 1.0-step(Radius,d);}\nvoid main()\n{float Is_Quad_Q53;Is_Quad_Q53=vNormal.z;vec4 Blob_Color_Q56;Blob_Fragment_B56(vUV,vTangent,_Blob_Texture_,Blob_Color_Q56);float X_Q52;float Y_Q52;float Z_Q52;float W_Q52;X_Q52=vExtra3.x;Y_Q52=vExtra3.y;Z_Q52=vExtra3.z;W_Q52=vExtra3.w;float Proximity_Q51;Proximity_Fragment_B51(_Proximity_Max_Intensity_,_Proximity_Near_Radius_,vExtra2,X_Q52,Y_Q52,Z_Q52,1.0,Proximity_Q51);float Inside_Rect_Q61;Round_Rect_Fragment_B61(W_Q52,vec4(1,1,1,1),_Filter_Width_,1.0,vec4(0,0,0,0),_Smooth_Edges_,vExtra1,Inside_Rect_Q61);vec4 Result_Q50;Scale_RGB_B50(_Edge_Color_,Proximity_Q51,Result_Q50);vec4 Result_Q47=Inside_Rect_Q61*Blob_Color_Q56;vec4 Color_At_T_Q48=mix(Result_Q50,Result_Q47,Is_Quad_Q53);vec4 Result_Q54;Scale_Color_B54(Color_At_T_Q48,_Fade_Out_,Result_Q54);vec4 Out_Color=Result_Q54;float Clip_Threshold=0.001;bool To_sRGB=false;gl_FragColor=Out_Color;}";Cs.l.ShadersStore.mrdlFrontplateVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Relative_To_Height_;uniform float _Filter_Width_;uniform vec4 _Edge_Color_;uniform float _Fade_Out_;uniform bool _Smooth_Edges_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform float _Blob_Pulse_Max_Size_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform float _Gaze_Intensity_;uniform float _Gaze_Focus_;uniform sampler2D _Blob_Texture_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform bool _Use_Global_Left_Index_;uniform bool _Use_Global_Right_Index_;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;void Blob_Vertex_B40(\nvec3 Position,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nvec3 Blob_Position,\nfloat Intensity,\nfloat Blob_Near_Size,\nfloat Blob_Far_Size,\nfloat Blob_Near_Distance,\nfloat Blob_Far_Distance,\nvec4 Vx_Color,\nvec2 UV,\nvec3 Face_Center,\nvec2 Face_Size,\nvec2 In_UV,\nfloat Blob_Fade_Length,\nfloat Selection_Fade,\nfloat Selection_Fade_Size,\nfloat Inner_Fade,\nfloat Blob_Pulse,\nfloat Blob_Fade,\nfloat Blob_Enabled,\nfloat DistanceOffset,\nout vec3 Out_Position,\nout vec2 Out_UV,\nout vec3 Blob_Info,\nout vec2 Blob_Relative_UV)\n{float blobSize,fadeIn;vec3 Hit_Position;Blob_Info=vec3(0.0,0.0,0.0);float Hit_Distance=dot(Blob_Position-Face_Center,Normal)+DistanceOffset*Blob_Far_Distance;Hit_Position=Blob_Position-Hit_Distance*Normal;float absD=abs(Hit_Distance);float lerpVal=clamp((absD-Blob_Near_Distance)/(Blob_Far_Distance-Blob_Near_Distance),0.0,1.0);fadeIn=1.0-clamp((absD-Blob_Far_Distance)/Blob_Fade_Length,0.0,1.0);float innerFade=1.0-clamp(-Hit_Distance/Inner_Fade,0.0,1.0);float farClip=clamp(1.0-step(Blob_Far_Distance+Blob_Fade_Length,absD),0.0,1.0);float size=mix(Blob_Near_Size,Blob_Far_Size,lerpVal)*farClip;blobSize=mix(size,Selection_Fade_Size,Selection_Fade)*innerFade*Blob_Enabled;Blob_Info.x=lerpVal*0.5+0.5;Blob_Info.y=fadeIn*Intensity*(1.0-Selection_Fade)*Blob_Fade;Blob_Info.x*=(1.0-Blob_Pulse);vec3 delta=Hit_Position-Face_Center;vec2 blobCenterXY=vec2(dot(delta,Tangent),dot(delta,Bitangent));vec2 quadUVin=2.0*UV-1.0; \nvec2 blobXY=blobCenterXY+quadUVin*blobSize;vec2 blobClipped=clamp(blobXY,-Face_Size*0.5,Face_Size*0.5);vec2 blobUV=(blobClipped-blobCenterXY)/max(blobSize,0.0001)*2.0;vec3 blobCorner=Face_Center+blobClipped.x*Tangent+blobClipped.y*Bitangent;Out_Position=mix(Position,blobCorner,Vx_Color.rrr);Out_UV=mix(In_UV,blobUV,Vx_Color.rr);Blob_Relative_UV=blobClipped/Face_Size.y;}\nvoid Round_Rect_Vertex_B36(\nvec2 UV,\nvec3 Tangent,\nvec3 Binormal,\nfloat Radius,\nfloat Anisotropy,\nvec2 Blob_Center_UV,\nout vec2 Rect_UV,\nout vec2 Scale_XY,\nout vec4 Rect_Parms)\n{Scale_XY=vec2(Anisotropy,1.0);Rect_UV=(UV-vec2(0.5,0.5))*Scale_XY;Rect_Parms.xy=Scale_XY*0.5-vec2(Radius,Radius);Rect_Parms.zw=Blob_Center_UV;}\nvec2 ProjectProximity(\nvec3 blobPosition,\nvec3 position,\nvec3 center,\nvec3 dir,\nvec3 xdir,\nvec3 ydir,\nout float vdistance\n)\n{vec3 delta=blobPosition-position;vec2 xy=vec2(dot(delta,xdir),dot(delta,ydir));vdistance=abs(dot(delta,dir));return xy;}\nvoid Proximity_Vertex_B33(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Face_Center,\nvec3 Position,\nfloat Proximity_Far_Distance,\nfloat Relative_Scale,\nfloat Proximity_Anisotropy,\nvec3 Normal,\nvec3 Tangent,\nvec3 Binormal,\nout vec4 Extra,\nout float Distance_To_Face,\nout float Distance_Fade1,\nout float Distance_Fade2)\n{float distz1,distz2;Extra.xy=ProjectProximity(Blob_Position,Position,Face_Center,Normal,Tangent*Proximity_Anisotropy,Binormal,distz1)/Relative_Scale;Extra.zw=ProjectProximity(Blob_Position_2,Position,Face_Center,Normal,Tangent*Proximity_Anisotropy,Binormal,distz2)/Relative_Scale;Distance_To_Face=dot(Normal,Position-Face_Center);Distance_Fade1=1.0-clamp(distz1/Proximity_Far_Distance,0.0,1.0);Distance_Fade2=1.0-clamp(distz2/Proximity_Far_Distance,0.0,1.0);}\nvoid Object_To_World_Pos_B12(\nvec3 Pos_Object,\nout vec3 Pos_World)\n{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;}\nvoid Choose_Blob_B27(\nvec4 Vx_Color,\nvec3 Position1,\nvec3 Position2,\nbool Blob_Enable_1,\nbool Blob_Enable_2,\nfloat Near_Size_1,\nfloat Near_Size_2,\nfloat Blob_Inner_Fade_1,\nfloat Blob_Inner_Fade_2,\nfloat Blob_Pulse_1,\nfloat Blob_Pulse_2,\nfloat Blob_Fade_1,\nfloat Blob_Fade_2,\nout vec3 Position,\nout float Near_Size,\nout float Inner_Fade,\nout float Blob_Enable,\nout float Fade,\nout float Pulse)\n{Position=Position1*(1.0-Vx_Color.g)+Vx_Color.g*Position2;float b1=Blob_Enable_1 ? 1.0 : 0.0;float b2=Blob_Enable_2 ? 1.0 : 0.0;Blob_Enable=b1+(b2-b1)*Vx_Color.g;Pulse=Blob_Pulse_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Pulse_2;Fade=Blob_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Fade_2;Near_Size=Near_Size_1*(1.0-Vx_Color.g)+Vx_Color.g*Near_Size_2;Inner_Fade=Blob_Inner_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Inner_Fade_2;}\nvoid Move_Verts_B32(\nvec2 UV,\nfloat Radius,\nfloat Anisotropy,\nfloat Line_Width,\nfloat Visible,\nout vec3 New_P,\nout vec2 New_UV)\n{vec2 xy=2.0*UV-vec2(0.5,0.5);vec2 center=clamp(xy,0.0,1.0);vec2 delta=2.0*(xy-center);float deltaLength=length(delta);vec2 aniso=vec2(1.0/Anisotropy,1.0);center=(center-vec2(0.5,0.5))*(1.0-2.0*Radius*aniso);New_UV=vec2((2.0-2.0*deltaLength)*Visible,0.0);float deltaRadius= (Radius-Line_Width*New_UV.x);New_P.xy=(center+deltaRadius/deltaLength *aniso*delta);New_P.z=0.0;}\nvoid Object_To_World_Dir_B14(\nvec3 Dir_Object,\nout vec3 Binormal_World)\n{Binormal_World=(world*vec4(Dir_Object,0.0)).xyz;}\nvoid Proximity_Visibility_B55(\nfloat Selection,\nvec3 Proximity_Center,\nvec3 Proximity_Center_2,\nfloat Proximity_Far_Distance,\nfloat Proximity_Radius,\nvec3 Face_Center,\nvec3 Normal,\nvec2 Face_Size,\nfloat Gaze,\nout float Width)\n{float boxMaxSize=length(Face_Size)*0.5;float d1=dot(Proximity_Center-Face_Center,Normal);vec3 blob1=Proximity_Center-d1*Normal;float d2=dot(Proximity_Center_2-Face_Center,Normal);vec3 blob2=Proximity_Center_2-d2*Normal;vec3 delta1=blob1-Face_Center;vec3 delta2=blob2-Face_Center;float dist1=dot(delta1,delta1);float dist2=dot(delta2,delta2);float nearestProxDist=sqrt(min(dist1,dist2));Width=(1.0-step(boxMaxSize+Proximity_Radius,nearestProxDist))*(1.0-step(Proximity_Far_Distance,min(d1,d2))*(1.0-step(0.0001,Selection)));Width=max(Gaze,Width);}\nvec2 ramp2(vec2 start,vec2 end,vec2 x)\n{return clamp((x-start)/(end-start),vec2(0.0,0.0),vec2(1.0,1.0));}\nfloat computeSelection(\nvec3 blobPosition,\nvec3 normal,\nvec3 tangent,\nvec3 bitangent,\nvec3 faceCenter,\nvec2 faceSize,\nfloat selectionFuzz,\nfloat farDistance,\nfloat fadeLength\n)\n{vec3 delta=blobPosition-faceCenter;float absD=abs(dot(delta,normal));float fadeIn=1.0-clamp((absD-farDistance)/fadeLength,0.0,1.0);vec2 blobCenterXY=vec2(dot(delta,tangent),dot(delta,bitangent));vec2 innerFace=faceSize*(1.0-selectionFuzz)*0.5;vec2 selectPulse=ramp2(-faceSize*0.5,-innerFace,blobCenterXY)-ramp2(innerFace,faceSize*0.5,blobCenterXY);return selectPulse.x*selectPulse.y*fadeIn;}\nvoid Selection_Vertex_B31(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Face_Center,\nvec2 Face_Size,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nfloat Selection_Fuzz,\nfloat Selected,\nfloat Far_Distance,\nfloat Fade_Length,\nvec3 Active_Face_Dir,\nout float Show_Selection)\n{float select1=computeSelection(Blob_Position,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float select2=computeSelection(Blob_Position_2,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);Show_Selection=mix(max(select1,select2),1.0,Selected);}\nvoid main()\n{vec3 Vec3_Q29=vec3(vec2(0,0).x,vec2(0,0).y,color.r);vec3 Nrm_World_Q24;Nrm_World_Q24=normalize((world*vec4(normal,0.0)).xyz);vec3 Face_Center_Q30;Face_Center_Q30=(world*vec4(vec3(0,0,0),1.0)).xyz;vec3 Tangent_World_Q13;Tangent_World_Q13=(world*vec4(tangent,0.0)).xyz;vec3 Result_Q42;Result_Q42=_Use_Global_Left_Index_ ? Global_Left_Index_Tip_Position.xyz : _Blob_Position_;vec3 Result_Q43;Result_Q43=_Use_Global_Right_Index_ ? Global_Right_Index_Tip_Position.xyz : _Blob_Position_2_;float Value_At_T_Q58=mix(_Blob_Near_Size_,_Blob_Pulse_Max_Size_,_Blob_Pulse_);float Value_At_T_Q59=mix(_Blob_Near_Size_2_,_Blob_Pulse_Max_Size_,_Blob_Pulse_2_);vec3 Cross_Q70=cross(normal,tangent);float Product_Q45=_Gaze_Intensity_*_Gaze_Focus_;float Step_Q46=step(0.0001,Product_Q45);vec3 Tangent_World_N_Q15=normalize(Tangent_World_Q13);vec3 Position_Q27;float Near_Size_Q27;float Inner_Fade_Q27;float Blob_Enable_Q27;float Fade_Q27;float Pulse_Q27;Choose_Blob_B27(color,Result_Q42,Result_Q43,_Blob_Enable_,_Blob_Enable_2_,Value_At_T_Q58,Value_At_T_Q59,_Blob_Inner_Fade_,_Blob_Inner_Fade_2_,_Blob_Pulse_,_Blob_Pulse_2_,_Blob_Fade_,_Blob_Fade_2_,Position_Q27,Near_Size_Q27,Inner_Fade_Q27,Blob_Enable_Q27,Fade_Q27,Pulse_Q27);vec3 Binormal_World_Q14;Object_To_World_Dir_B14(Cross_Q70,Binormal_World_Q14);float Anisotropy_Q21=length(Tangent_World_Q13)/length(Binormal_World_Q14);vec3 Binormal_World_N_Q16=normalize(Binormal_World_Q14);vec2 Face_Size_Q35;float ScaleY_Q35;Face_Size_Q35=vec2(length(Tangent_World_Q13),length(Binormal_World_Q14));ScaleY_Q35=Face_Size_Q35.y;float Out_Radius_Q38;float Out_Line_Width_Q38;Out_Radius_Q38=_Relative_To_Height_ ? _Radius_ : _Radius_/ScaleY_Q35;Out_Line_Width_Q38=_Relative_To_Height_ ? _Line_Width_ : _Line_Width_/ScaleY_Q35;float Show_Selection_Q31;Selection_Vertex_B31(Result_Q42,Result_Q43,Face_Center_Q30,Face_Size_Q35,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,_Selection_Fuzz_,_Selected_,_Selected_Distance_,_Selected_Fade_Length_,vec3(0,0,-1),Show_Selection_Q31);float MaxAB_Q41=max(Show_Selection_Q31,Product_Q45);float Width_Q55;Proximity_Visibility_B55(Show_Selection_Q31,Result_Q42,Result_Q43,_Proximity_Far_Distance_,_Proximity_Near_Radius_,Face_Center_Q30,Nrm_World_Q24,Face_Size_Q35,Step_Q46,Width_Q55);vec3 New_P_Q32;vec2 New_UV_Q32;Move_Verts_B32(uv,Out_Radius_Q38,Anisotropy_Q21,Out_Line_Width_Q38,Width_Q55,New_P_Q32,New_UV_Q32);vec3 Pos_World_Q12;Object_To_World_Pos_B12(New_P_Q32,Pos_World_Q12);vec3 Out_Position_Q40;vec2 Out_UV_Q40;vec3 Blob_Info_Q40;vec2 Blob_Relative_UV_Q40;Blob_Vertex_B40(Pos_World_Q12,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,Position_Q27,_Blob_Intensity_,Near_Size_Q27,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,color,uv,Face_Center_Q30,Face_Size_Q35,New_UV_Q32,_Blob_Fade_Length_,_Selection_Fade_,_Selection_Fade_Size_,Inner_Fade_Q27,Pulse_Q27,Fade_Q27,Blob_Enable_Q27,0.0,Out_Position_Q40,Out_UV_Q40,Blob_Info_Q40,Blob_Relative_UV_Q40);vec2 Rect_UV_Q36;vec2 Scale_XY_Q36;vec4 Rect_Parms_Q36;Round_Rect_Vertex_B36(New_UV_Q32,Tangent_World_Q13,Binormal_World_Q14,Out_Radius_Q38,Anisotropy_Q21,Blob_Relative_UV_Q40,Rect_UV_Q36,Scale_XY_Q36,Rect_Parms_Q36);vec4 Extra_Q33;float Distance_To_Face_Q33;float Distance_Fade1_Q33;float Distance_Fade2_Q33;Proximity_Vertex_B33(Result_Q42,Result_Q43,Face_Center_Q30,Pos_World_Q12,_Proximity_Far_Distance_,1.0,_Proximity_Anisotropy_,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,Extra_Q33,Distance_To_Face_Q33,Distance_Fade1_Q33,Distance_Fade2_Q33);vec4 Vec4_Q37=vec4(MaxAB_Q41,Distance_Fade1_Q33,Distance_Fade2_Q33,Out_Radius_Q38);vec3 Position=Out_Position_Q40;vec3 Normal=Vec3_Q29;vec2 UV=Out_UV_Q40;vec3 Tangent=Blob_Info_Q40;vec3 Binormal=vec3(0,0,0);vec4 Color=vec4(1,1,1,1);vec4 Extra1=Rect_Parms_Q36;vec4 Extra2=Extra_Q33;vec4 Extra3=Vec4_Q37;gl_Position=viewProjection*vec4(Position,1);vNormal=Normal;vUV=UV;vTangent=Tangent;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class qV extends xn{constructor(){super(),this.SMOOTH_EDGES=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class YV extends bn{constructor(e,t){super(e,t),this.radius=.12,this.lineWidth=.01,this.relativeToHeight=!1,this._filterWidth=1,this.edgeColor=new H.ov(.53,.53,.53,1),this.blobEnable=!0,this.blobPosition=new W.Pq(100,100,100),this.blobIntensity=.5,this.blobNearSize=.032,this.blobFarSize=.048,this.blobNearDistance=.008,this.blobFarDistance=.064,this.blobFadeLength=.04,this.blobInnerFade=.01,this.blobPulse=0,this.blobFade=1,this.blobPulseMaxSize=.05,this.blobEnable2=!0,this.blobPosition2=new W.Pq(10,10.1,-.6),this.blobNearSize2=.008,this.blobInnerFade2=.1,this.blobPulse2=0,this.blobFade2=1,this.gazeIntensity=.8,this.gazeFocus=0,this.selectionFuzz=.5,this.selected=1,this.selectionFade=.2,this.selectionFadeSize=0,this.selectedDistance=.08,this.selectedFadeLength=.08,this.proximityMaxIntensity=.45,this.proximityFarDistance=.16,this.proximityNearRadius=.016,this.proximityAnisotropy=1,this.useGlobalLeftIndex=!0,this.useGlobalRightIndex=!0,this.fadeOut=1,this.alphaMode=Il.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1,this._blobTexture=new vi.g(YV.BLOB_TEXTURE_URL,t,!0,!1,vi.g.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new qV);const r=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if((0,Bt.qB)(e,r,!1,!1),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=new Tn;r.FOG&&e.addFallback(1,"FOG"),(0,Bt.c4)(r,e),r.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const i=[st.R.PositionKind];r.NORMAL&&i.push(st.R.NormalKind),r.UV1&&i.push(st.R.UVKind),r.UV2&&i.push(st.R.UV2Kind),r.VERTEXCOLOR&&i.push(st.R.ColorKind),r.TANGENT&&i.push(st.R.TangentKind),(0,Bt.ER)(i,r);const o="mrdlFrontplate",a=r.toString(),l=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Relative_To_Height_","_Filter_Width_","_Edge_Color_","_Fade_Out_","_Smooth_Edges_","_Blob_Enable_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Inner_Fade_","_Blob_Pulse_","_Blob_Fade_","_Blob_Pulse_Max_Size_","_Blob_Enable_2_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Inner_Fade_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Gaze_Intensity_","_Gaze_Focus_","_Blob_Texture_","_Selection_Fuzz_","_Selected_","_Selection_Fade_","_Selection_Fade_Size_","_Selected_Distance_","_Selected_Fade_Length_","_Proximity_Max_Intensity_","_Proximity_Far_Distance_","_Proximity_Near_Radius_","_Proximity_Anisotropy_","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","_Use_Global_Left_Index_","_Use_Global_Right_Index_"],h=[],c=[];(0,Bt.Bb)({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:r,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),r)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const r=this.getScene();if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",r.activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Relative_To_Height_",this.relativeToHeight?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Edge_Color_",this.edgeColor),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._activeEffect.setFloat("_Blob_Enable_",this.blobEnable?1:0),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Inner_Fade_",this.blobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setFloat("_Blob_Pulse_Max_Size_",this.blobPulseMaxSize),this._activeEffect.setFloat("_Blob_Enable_2_",this.blobEnable2?1:0),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Inner_Fade_2_",this.blobInnerFade2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setFloat("_Gaze_Intensity_",this.gazeIntensity),this._activeEffect.setFloat("_Gaze_Focus_",this.gazeFocus),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Selection_Fuzz_",this.selectionFuzz),this._activeEffect.setFloat("_Selected_",this.selected),this._activeEffect.setFloat("_Selection_Fade_",this.selectionFade),this._activeEffect.setFloat("_Selection_Fade_Size_",this.selectionFadeSize),this._activeEffect.setFloat("_Selected_Distance_",this.selectedDistance),this._activeEffect.setFloat("_Selected_Fade_Length_",this.selectedFadeLength),this._activeEffect.setFloat("_Proximity_Max_Intensity_",this.proximityMaxIntensity),this._activeEffect.setFloat("_Proximity_Far_Distance_",this.proximityFarDistance),this._activeEffect.setFloat("_Proximity_Near_Radius_",this.proximityNearRadius),this._activeEffect.setFloat("_Proximity_Anisotropy_",this.proximityAnisotropy),this._activeEffect.setFloat("_Use_Global_Left_Index_",this.useGlobalLeftIndex?1:0),this._activeEffect.setFloat("_Use_Global_Right_Index_",this.useGlobalRightIndex?1:0),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return it.p.Clone((()=>new YV(e,this.getScene())),this)}serialize(){const e=it.p.Serialize(this);return e.customType="BABYLON.MRDLFrontplateMaterial",e}getClassName(){return"MRDLFrontplateMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new YV(e.name,t)),e,t,i)}}YV.BLOB_TEXTURE_URL="",(0,je.Cg)([(0,$e.lK)()],YV.prototype,"radius",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"lineWidth",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"relativeToHeight",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"edgeColor",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobEnable",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobPosition",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobNearSize",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobFarSize",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobNearDistance",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobFarDistance",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobFadeLength",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobInnerFade",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobPulse",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobFade",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobPulseMaxSize",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobEnable2",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobPosition2",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobNearSize2",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobInnerFade2",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobPulse2",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"blobFade2",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"gazeIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"gazeFocus",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"selectionFuzz",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"selected",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"selectionFade",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"selectionFadeSize",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"selectedDistance",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"selectedFadeLength",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"proximityMaxIntensity",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"proximityFarDistance",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"proximityNearRadius",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"proximityAnisotropy",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"useGlobalLeftIndex",void 0),(0,je.Cg)([(0,$e.lK)()],YV.prototype,"useGlobalRightIndex",void 0),(0,X.Y5)("BABYLON.GUI.MRDLFrontplateMaterial",YV);Cs.l.ShadersStore.mrdlInnerquadPixelShader="uniform vec3 cameraPosition;varying vec2 vUV;varying vec3 vTangent;uniform vec4 _Color_;uniform float _Radius_;uniform bool _Fixed_Radius_;uniform float _Filter_Width_;uniform float _Glow_Fraction_;uniform float _Glow_Max_;uniform float _Glow_Falloff_;float FilterStep_Bid194(float edge,float x,float filterWidth)\n{float dx=max(1.0E-5,fwidth(x)*filterWidth);return max((x+dx*0.5-max(edge,x-dx*0.5))/dx,0.0);}\nvoid Round_Rect_B194(\nfloat Size_X,\nfloat Size_Y,\nfloat Radius,\nvec4 Rect_Color,\nfloat Filter_Width,\nvec2 UV,\nfloat Glow_Fraction,\nfloat Glow_Max,\nfloat Glow_Falloff,\nout vec4 Color)\n{vec2 halfSize=vec2(Size_X,Size_Y)*0.5;vec2 r=max(min(vec2(Radius,Radius),halfSize),vec2(0.01,0.01));vec2 v=abs(UV);vec2 nearestp=min(v,halfSize-r);vec2 delta=(v-nearestp)/max(vec2(0.01,0.01),r);float Distance=length(delta);float insideRect=1.0-FilterStep_Bid194(1.0-Glow_Fraction,Distance,Filter_Width);float glow=clamp((1.0-Distance)/Glow_Fraction,0.0,1.0);glow=pow(glow,Glow_Falloff);Color=Rect_Color*max(insideRect,glow*Glow_Max);}\nvoid main()\n{float X_Q192;float Y_Q192;float Z_Q192;X_Q192=vTangent.x;Y_Q192=vTangent.y;Z_Q192=vTangent.z;vec4 Color_Q194;Round_Rect_B194(X_Q192,1.0,Y_Q192,_Color_,_Filter_Width_,vUV,_Glow_Fraction_,_Glow_Max_,_Glow_Falloff_,Color_Q194);vec4 Out_Color=Color_Q194;float Clip_Threshold=0.0;gl_FragColor=Out_Color;}\n";Cs.l.ShadersStore.mrdlInnerquadVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform vec4 _Color_;uniform float _Radius_;uniform bool _Fixed_Radius_;uniform float _Filter_Width_;uniform float _Glow_Fraction_;uniform float _Glow_Max_;uniform float _Glow_Falloff_;varying vec2 vUV;varying vec3 vTangent;void main()\n{vec3 Pos_World_Q189;Pos_World_Q189=(world*vec4(position,1.0)).xyz;vec3 Dir_World_Q190;Dir_World_Q190=(world*vec4(tangent,0.0)).xyz;vec3 Dir_World_Q191;Dir_World_Q191=(world*vec4((cross(normal,tangent)),0.0)).xyz;float Length_Q180=length(Dir_World_Q190);float Length_Q181=length(Dir_World_Q191);float Quotient_Q184=Length_Q180/Length_Q181;float Quotient_Q195=_Radius_/Length_Q181;vec2 Result_Q193;Result_Q193=vec2((uv.x-0.5)*Length_Q180/Length_Q181,(uv.y-0.5));float Result_Q198=_Fixed_Radius_ ? Quotient_Q195 : _Radius_;vec3 Vec3_Q183=vec3(Quotient_Q184,Result_Q198,0);vec3 Position=Pos_World_Q189;vec3 Normal=vec3(0,0,0);vec2 UV=Result_Q193;vec3 Tangent=Vec3_Q183;vec3 Binormal=vec3(0,0,0);vec4 Color=color;gl_Position=viewProjection*vec4(Position,1);vUV=UV;vTangent=Tangent;}\n";class KV extends xn{constructor(){super(),this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class jV extends bn{constructor(e,t){super(e,t),this.color=new H.ov(1,1,1,.05),this.radius=.12,this.fixedRadius=!0,this._filterWidth=1,this.glowFraction=0,this.glowMax=.5,this.glowFalloff=2,this.alphaMode=Il.ALPHA_COMBINE,this.backFaceCulling=!1}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new KV);const r=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=s.getEngine();if((0,Bt.qB)(e,r,!0,!1),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=new Tn;r.FOG&&e.addFallback(1,"FOG"),(0,Bt.c4)(r,e),r.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess;const i=[st.R.PositionKind];r.NORMAL&&i.push(st.R.NormalKind),r.UV1&&i.push(st.R.UVKind),r.UV2&&i.push(st.R.UV2Kind),r.VERTEXCOLOR&&i.push(st.R.ColorKind),r.TANGENT&&i.push(st.R.TangentKind),(0,Bt.ER)(i,r);const o="mrdlInnerquad",a=r.toString(),l=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Color_","_Radius_","_Fixed_Radius_","_Filter_Width_","_Glow_Fraction_","_Glow_Max_","_Glow_Falloff_"],h=[],c=[];(0,Bt.Bb)({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:r,maxSimultaneousLights:4}),t.setEffect(s.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),r)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const r=this.getScene();if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",r.activeCamera.position),this._activeEffect.setDirectColor4("_Color_",this.color),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Fixed_Radius_",this.fixedRadius?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setFloat("_Glow_Fraction_",this.glowFraction),this._activeEffect.setFloat("_Glow_Max_",this.glowMax),this._activeEffect.setFloat("_Glow_Falloff_",this.glowFalloff),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return it.p.Clone((()=>new jV(e,this.getScene())),this)}serialize(){const e=it.p.Serialize(this);return e.customType="BABYLON.MRDLInnerquadMaterial",e}getClassName(){return"MRDLInnerquadMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new jV(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.lK)()],jV.prototype,"color",void 0),(0,je.Cg)([(0,$e.lK)()],jV.prototype,"radius",void 0),(0,je.Cg)([(0,$e.lK)()],jV.prototype,"fixedRadius",void 0),(0,je.Cg)([(0,$e.lK)()],jV.prototype,"glowFraction",void 0),(0,je.Cg)([(0,$e.lK)()],jV.prototype,"glowMax",void 0),(0,je.Cg)([(0,$e.lK)()],jV.prototype,"glowFalloff",void 0),(0,X.Y5)("BABYLON.GUI.MRDLInnerquadMaterial",jV);class $V extends bV{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._backGlow.renderingGroupId=e,this._innerQuad.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}get mesh(){return this._backPlate}set tooltipText(e){if(e){if(!this._tooltipFade){const e=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=Qi("",{size:1},this._backPlate._scene),this._tooltipMesh.position=W.Pq.Down().scale(.7).add(W.Pq.Forward(e).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._frontPlateCollisionMesh,this._tooltipTexture=$B.CreateForMesh(this._tooltipMesh);const t=new cB;t.height=.25,t.width=.8,t.cornerRadius=25,t.color="#ffffff",t.thickness=20,t.background="#060668",this._tooltipTexture.addControl(t),this._tooltipTextBlock=new dB,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=100,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new Mi,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)})),this._tooltipOutObserver=this.onPointerOutObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)}))}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}else this._disposeTooltip()}get tooltipText(){return this._tooltipTextBlock?.text||null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get subtext(){return this._subtext}set subtext(e){this._subtext!==e&&(this._subtext=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get backGlowMaterial(){return this._backGlowMaterial}get innerQuadMaterial(){return this._innerQuadMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}set isBackplateVisible(e){this.mesh&&this._backMaterial&&(e&&!this._isBackplateVisible?this._backPlate.visibility=1:!e&&this._isBackplateVisible&&(this._backPlate.visibility=0)),this._isBackplateVisible=e}constructor(e,t=!0){super(e),this.width=1,this.height=1,this.radius=.14,this.textSizeInPixels=18,this.imageSizeInPixels=40,this.plateMaterialColor=new H.v9(.4,.4,.4),this.frontPlateDepth=.2,this.backPlateDepth=.04,this.backGlowOffset=.1,this.flatPlaneDepth=.001,this.innerQuadRadius=this.radius-.04,this.innerQuadColor=new H.ov(0,0,0,0),this.innerQuadToggledColor=new H.ov(.5197843,.6485234,.9607843,.6),this.innerQuadHoverColor=new H.ov(1,1,1,.05),this.innerQuadToggledHoverColor=new H.ov(.5197843,.6485234,.9607843,1),this._isBackplateVisible=!0,this._shareMaterials=!0,this._shareMaterials=t,this.pointerEnterAnimation=()=>{this._frontPlate&&this._textPlate&&!this.isToggleButton&&this._performEnterExitAnimation(1),this.isToggleButton&&this._innerQuadMaterial&&(this.isToggled?this._innerQuadMaterial.color=this.innerQuadToggledHoverColor:this._innerQuadMaterial.color=this.innerQuadHoverColor)},this.pointerOutAnimation=()=>{this._frontPlate&&this._textPlate&&!this.isToggleButton&&this._performEnterExitAnimation(-.8),this.isToggleButton&&this._innerQuadMaterial&&this._onToggle(this.isToggled)},this.pointerDownAnimation=()=>{},this.pointerUpAnimation=()=>{},this._pointerClickObserver=this.onPointerClickObservable.add((()=>{this._frontPlate&&this._backGlow&&!this.isActiveNearInteraction&&this._performClickAnimation(),this.isToggleButton&&this._innerQuadMaterial&&this._onToggle(this.isToggled)})),this._pointerEnterObserver=this.onPointerEnterObservable.add((()=>{this.pointerEnterAnimation()})),this._pointerOutObserver=this.onPointerOutObservable.add((()=>{this.pointerOutAnimation()})),this._toggleObserver=this.onToggleObservable.add((e=>{this._innerQuadMaterial.color=e?this.innerQuadToggledColor:this.innerQuadColor}))}_getTypeName(){return"TouchHolographicButton"}_rebuildContent(){let e;e=this._getAspectRatio()<=1?this._alignContentVertically():this._alignContentHorizontally(),this.content=e}_getAspectRatio(){return this.width/this.height}_alignContentVertically(){const e=new _B;if(e.isVertical=!0,(0,ii.Nf)()&&document.createElement&&this._imageUrl){const t=new fB;t.source=this._imageUrl,t.heightInPixels=180,t.widthInPixels=100,t.paddingTopInPixels=40,t.paddingBottomInPixels=40,e.addControl(t)}if(this._text){const t=new dB;t.text=this._text,t.color="white",t.heightInPixels=30,t.fontSize=24,e.addControl(t)}return e}_alignContentHorizontally(){let e=240;const t=15,i=new cB;i.widthInPixels=e,i.heightInPixels=e,i.color="transparent",i.setPaddingInPixels(t,t,t,t),e-=30;const r=new _B;if(r.isVertical=!1,r.scaleY=this._getAspectRatio(),(0,ii.Nf)()&&document.createElement&&this._imageUrl){const t=new cB(`${this.name}_image`);t.widthInPixels=this.imageSizeInPixels,t.heightInPixels=this.imageSizeInPixels,t.color="transparent",e-=this.imageSizeInPixels;const i=new fB;i.source=this._imageUrl,t.addControl(i),r.addControl(t)}if(this._text){const i=new dB(`${this.name}_text`);if(i.text=this._text,i.color="white",i.fontSize=this.textSizeInPixels,i.widthInPixels=e,this._imageUrl&&(i.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,i.paddingLeftInPixels=t),this._subtext){const s=new xB;s.addColumnDefinition(1),s.addRowDefinition(.5),s.addRowDefinition(.5),s.widthInPixels=e,s.heightInPixels=45;const n=new dB(`${this.name}_subtext`);n.text=this._subtext,n.color="#EEEEEEAB",n.fontSize=.75*this.textSizeInPixels,n.fontWeight="600",this._imageUrl&&(n.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT,n.paddingLeftInPixels=t),s.addControl(i,0),s.addControl(n,1),r.addControl(s)}else r.addControl(i)}return i.addControl(r),i}_createNode(e){this.name=this.name??"TouchHolographicButton";const t=this._createBackPlate(e),i=this._createFrontPlate(e),r=this._createInnerQuad(e),s=this._createBackGlow(e);this._frontPlateCollisionMesh=i,this._textPlate=super._createNode(e),this._textPlate.name=`${this.name}_textPlate`,this._textPlate.isPickable=!1,this._textPlate.scaling.x=this.width,this._textPlate.parent=i,this._backPlate=t,this._backPlate.position=W.Pq.Forward(e.useRightHandedSystem).scale(this.backPlateDepth/2),this._backPlate.isPickable=!1,this._backPlate.addChild(i),this._backPlate.addChild(r),s&&this._backPlate.addChild(s);const n=new Pt(`${this.name}_root`,e);return this._backPlate.setParent(n),this.collisionMesh=i,this.collidableFrontDirection=this._backPlate.forward.negate(),n}_createBackPlate(e){const t=Ko(`${this.name}_backPlate`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=.2,xg.ImportMeshAsync(void 0,$V.MRTK_ASSET_BASE_URL,$V.BACKPLATE_MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.visibility=0,this._isBackplateVisible&&(i.visibility=1,i.name=`${this.name}_backPlate`,i.isPickable=!1,i.scaling.x=this.width,i.scaling.y=this.height,i.parent=t),this._backMaterial&&(i.material=this._backMaterial),this._backPlate=i})),t}_createFrontPlate(e){const t=Ko(`${this.name}_frontPlate`,{width:this.width,height:this.height,depth:this.frontPlateDepth},e);return t.isPickable=!0,t.isNearPickable=!0,t.visibility=0,t.position=W.Pq.Forward(e.useRightHandedSystem).scale((this.backPlateDepth-this.frontPlateDepth)/2),xg.ImportMeshAsync(void 0,$V.MRTK_ASSET_BASE_URL,$V.FRONTPLATE_MODEL_FILENAME,e).then((i=>{const r=Ko(`${this.name}_collisionPlate`,{width:this.width,height:this.height},e);r.isPickable=!1,r.scaling.z=this.frontPlateDepth,r.visibility=0,r.parent=t,this._collisionPlate=r;const s=i.meshes[1];s.name=`${this.name}_frontPlate`,s.isPickable=!1,s.scaling.x=this.width-this.backGlowOffset,s.scaling.y=this.height-this.backGlowOffset,s.position=W.Pq.Forward(e.useRightHandedSystem).scale(-.5),s.parent=r,this.isToggleButton&&(s.visibility=0),this._frontMaterial&&(s.material=this._frontMaterial),this._textPlate.scaling.x=1,this._textPlate.parent=s,this._frontPlate=s})),t}_createInnerQuad(e){const t=Ko(`${this.name}_innerQuad`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=this.flatPlaneDepth,t.position.z+=this.backPlateDepth/2-this.flatPlaneDepth,xg.ImportMeshAsync(void 0,$V.MRTK_ASSET_BASE_URL,$V.INNERQUAD_MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.name=`${this.name}_innerQuad`,i.isPickable=!1,i.scaling.x=this.width-this.backGlowOffset,i.scaling.y=this.height-this.backGlowOffset,i.parent=t,this._innerQuadMaterial&&(i.material=this._innerQuadMaterial),this._innerQuad=i})),t}_createBackGlow(e){if(this.isToggleButton)return;const t=Ko(`${this.name}_backGlow`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=this.flatPlaneDepth,t.position.z+=this.backPlateDepth/2-2*this.flatPlaneDepth,xg.ImportMeshAsync(void 0,$V.MRTK_ASSET_BASE_URL,$V.BACKGLOW_MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.name=`${this.name}_backGlow`,i.isPickable=!1,i.scaling.x=this.width-this.backGlowOffset,i.scaling.y=this.height-this.backGlowOffset,i.parent=t,this._backGlowMaterial&&(i.material=this._backGlowMaterial),this._backGlow=i})),t}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e,this._plateMaterial.diffuseColor=this.plateMaterialColor}_performClickAnimation(){const e=new Fe.AnimationGroup("Click Animation Group"),t=[{name:"backGlowMotion",mesh:this._backGlow,property:"material.motion",keys:[{frame:0,values:[0,0,0]},{frame:20,values:[1,.0144,.0144]},{frame:40,values:[.0027713229489760476,0,0]},{frame:45,values:[.0027713229489760476]}]},{name:"_collisionPlateZSlide",mesh:this._collisionPlate,property:"position.z",keys:[{frame:0,values:[0,0,0]},{frame:20,values:[W.Pq.Forward(this._collisionPlate._scene.useRightHandedSystem).scale(this.frontPlateDepth/2).z,0,0]},{frame:40,values:[0,.005403332496794331]},{frame:45,values:[0]}]},{name:"_collisionPlateZScale",mesh:this._collisionPlate,property:"scaling.z",keys:[{frame:0,values:[this.frontPlateDepth,0,0]},{frame:20,values:[this.backPlateDepth,0,0]},{frame:40,values:[this.frontPlateDepth,.0054]},{frame:45,values:[this.frontPlateDepth]}]}];for(const i of t){const t=new pe.X5(i.name,i.property,60,pe.X5.ANIMATIONTYPE_FLOAT,pe.X5.ANIMATIONLOOPMODE_CYCLE),r=[];for(const e of i.keys)r.push({frame:e.frame,value:e.values[0],inTangent:e.values[1],outTangent:e.values[2],interpolation:e.values[3]});t.setKeys(r),i.mesh&&e.addTargetedAnimation(t,i.mesh)}e.normalize(0,45),e.speedRatio=1,e.play()}_performEnterExitAnimation(e){const t=new Fe.AnimationGroup("Enter Exit Animation Group"),i=[{name:"frontPlateFadeOut",mesh:this._frontPlate,property:"material.fadeOut",keys:[{frame:0,values:[0,0,.025045314830017686,0]},{frame:40,values:[1.00205599570012,.025045314830017686,0,0]}]},{name:"textPlateZSlide",mesh:this._textPlate,property:"position.z",keys:[{frame:0,values:[0,0,0]},{frame:40,values:[W.Pq.Forward(this._textPlate._scene.useRightHandedSystem).scale(-.15).z,0,0]}]}];for(const e of i){const i=new pe.X5(e.name,e.property,60,pe.X5.ANIMATIONTYPE_FLOAT,pe.X5.ANIMATIONLOOPMODE_CYCLE),r=[];for(const t of e.keys)r.push({frame:t.frame,value:t.values[0],inTangent:t.values[1],outTangent:t.values[2],interpolation:t.values[3]});i.setKeys(r),e.mesh&&t.addTargetedAnimation(i,e.mesh)}t.normalize(0,45),t.speedRatio=e,t.play()}_createBackMaterial(e){this._backMaterial=this._backMaterial??new kV(this.name+"backPlateMaterial",e.getScene()),this._backMaterial.absoluteSizes=!0,this._backMaterial.radius=this.radius,this._backMaterial.lineWidth=.02}_createFrontMaterial(e){this._frontMaterial=this._frontMaterial??new YV(this.name+"Front Material",e.getScene()),this.frontMaterial.radius=this.innerQuadRadius,this.frontMaterial.fadeOut=0}_createBackGlowMaterial(e){const t=this.radius+.04;this._backGlowMaterial=this._backGlowMaterial??new XV(this.name+"Back Glow Material",e.getScene()),this._backGlowMaterial.bevelRadius=t,this._backGlowMaterial.lineWidth=t,this._backGlowMaterial.motion=0}_createInnerQuadMaterial(e){this._innerQuadMaterial=this._innerQuadMaterial??new jV("inner_quad",e.getScene()),this._innerQuadMaterial.radius=this.innerQuadRadius,this.isToggleButton&&(this._innerQuadMaterial.color=this.innerQuadColor)}_createPlateMaterial(e){this._plateMaterial=this._plateMaterial??new Un(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=H.v9.Black()}_onToggle(e){super._onToggle(e)}_affectMaterial(e){this._shareMaterials?(this._host._touchSharedMaterials.mrdlBackplateMaterial?this._backMaterial=this._host._touchSharedMaterials.mrdlBackplateMaterial:(this._createBackMaterial(e),this._host._touchSharedMaterials.mrdlBackplateMaterial=this._backMaterial),this._host._touchSharedMaterials.mrdlFrontplateMaterial?this._frontMaterial=this._host._touchSharedMaterials.mrdlFrontplateMaterial:(this._createFrontMaterial(e),this._host._touchSharedMaterials.mrdlFrontplateMaterial=this._frontMaterial),this._host._touchSharedMaterials.mrdlBackglowMaterial?this._backGlowMaterial=this._host._touchSharedMaterials.mrdlBackglowMaterial:(this._createBackGlowMaterial(e),this._host._touchSharedMaterials.mrdlBackglowMaterial=this._backGlowMaterial),this._host._touchSharedMaterials.mrdlInnerQuadMaterial?this._innerQuadMaterial=this._host._touchSharedMaterials.mrdlInnerQuadMaterial:(this._createInnerQuadMaterial(e),this._host._touchSharedMaterials.mrdlInnerQuadMaterial=this._innerQuadMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e),this._createBackGlowMaterial(e),this._createInnerQuadMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._textPlate.material=this._plateMaterial,this._isBackplateVisible||(this._backPlate.visibility=0),this._frontPlate&&(this._frontPlate.material=this._frontMaterial),this._backGlow&&(this._backGlow.material=this._backGlowMaterial),this._innerQuad&&(this._innerQuad.material=this._innerQuadMaterial),this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.onPointerClickObservable.remove(this._pointerClickObserver),this.onPointerEnterObservable.remove(this._pointerEnterObserver),this.onPointerOutObservable.remove(this._pointerOutObserver),this.onToggleObservable.remove(this._toggleObserver),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._backGlowMaterial.dispose(),this._innerQuadMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}$V.MRTK_ASSET_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",$V.FRONTPLATE_MODEL_FILENAME="mrtk-fluent-frontplate.glb",$V.BACKPLATE_MODEL_FILENAME="mrtk-fluent-backplate.glb",$V.BACKGLOW_MODEL_FILENAME="mrtk-fluent-button.glb",$V.INNERQUAD_MODEL_FILENAME="SlateProximity.glb";class QV{get scene(){return this._scene}get utilityLayer(){return this._utilityLayer}get controlScaling(){return this._customControlScaling}set controlScaling(e){if(this._customControlScaling!==e&&e>0){const t=e/this._customControlScaling;this._customControlScaling=e,this._rootContainer.children.forEach((i=>{i.scaling.scaleInPlace(t),1!==e&&(i._isScaledByManager=!0)}))}}get useRealisticScaling(){return this.controlScaling===QV.MRTK_REALISTIC_SCALING}set useRealisticScaling(e){this.controlScaling=e?QV.MRTK_REALISTIC_SCALING:1}constructor(e){this._customControlScaling=1,this._lastControlOver={},this._lastControlDown={},this.onPickedPointChangedObservable=new z.cP,this.onPickingObservable=new z.cP,this._sharedMaterials={},this._touchSharedMaterials={},this._scene=e||he.q.LastCreatedScene,this._sceneDisposeObserver=this._scene.onDisposeObservable.add((()=>{this._sceneDisposeObserver=null,this._utilityLayer=null,this.dispose()})),this._utilityLayer=Bo._CreateDefaultUtilityLayerFromScene(this._scene),this._utilityLayer.onlyCheckPointerDownEvents=!1,this._utilityLayer.pickUtilitySceneFirst=!1,this._utilityLayer.mainSceneTrackerPredicate=e=>e&&e.reservedDataStore?.GUI3D?.control?._node,this._rootContainer=new aV("RootContainer"),this._rootContainer._host=this;const t=this._utilityLayer.utilityLayerScene;this._pointerOutObserver=this._utilityLayer.onPointerOutObservable.add((e=>{this._handlePointerOut(e,!0)})),this._pointerObserver=t.onPointerObservable.add((e=>{this._doPicking(e)})),this._utilityLayer.utilityLayerScene.autoClear=!1,this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,new Lo("hemi",W.Pq.Up(),this._utilityLayer.utilityLayerScene)}_handlePointerOut(e,t){const i=this._lastControlOver[e];i&&(i._onPointerOut(i),delete this._lastControlOver[e]),t&&this._lastControlDown[e]&&(this._lastControlDown[e].forcePointerUp(),delete this._lastControlDown[e]),this.onPickedPointChangedObservable.notifyObservers(null)}_doPicking(e){if(!this._utilityLayer||!this._utilityLayer.shouldRender||!this._utilityLayer.utilityLayerScene.activeCamera)return!1;const t=e.event,i=t.pointerId||0,r=t.button,s=e.pickInfo;if(s&&this.onPickingObservable.notifyObservers(s.pickedMesh),!s||!s.hit)return this._handlePointerOut(i,e.type===yi.Zp.POINTERUP),!1;s.pickedPoint&&this.onPickedPointChangedObservable.notifyObservers(s.pickedPoint);const n=s.pickedMesh.reservedDataStore?.GUI3D?.control;return n&&!n._processObservables(e.type,s.pickedPoint,s.originMesh?.position||null,i,r)&&e.type===yi.Zp.POINTERMOVE&&(this._lastControlOver[i]&&this._lastControlOver[i]._onPointerOut(this._lastControlOver[i]),delete this._lastControlOver[i]),e.type===yi.Zp.POINTERUP&&(this._lastControlDown[t.pointerId]&&(this._lastControlDown[t.pointerId].forcePointerUp(),delete this._lastControlDown[t.pointerId]),("touch"===t.pointerType||"xr"===t.pointerType&&this._scene.getEngine().hostInformation.isMobile)&&this._handlePointerOut(i,!1)),!0}get rootContainer(){return this._rootContainer}containsControl(e){return this._rootContainer.containsControl(e)}addControl(e){return this._rootContainer.addControl(e),1!==this._customControlScaling&&(e.scaling.scaleInPlace(this._customControlScaling),e._isScaledByManager=!0),this}removeControl(e){return this._rootContainer.removeControl(e),e._isScaledByManager&&(e.scaling.scaleInPlace(1/this._customControlScaling),e._isScaledByManager=!1),this}dispose(){this._rootContainer.dispose();for(const e in this._sharedMaterials)Object.prototype.hasOwnProperty.call(this._sharedMaterials,e)&&this._sharedMaterials[e].dispose();this._sharedMaterials={};for(const e in this._touchSharedMaterials)Object.prototype.hasOwnProperty.call(this._touchSharedMaterials,e)&&this._touchSharedMaterials[e].dispose();this._touchSharedMaterials={},this._pointerOutObserver&&this._utilityLayer&&(this._utilityLayer.onPointerOutObservable.remove(this._pointerOutObserver),this._pointerOutObserver=null),this.onPickedPointChangedObservable.clear(),this.onPickingObservable.clear();const e=this._utilityLayer?this._utilityLayer.utilityLayerScene:null;e&&this._pointerObserver&&(e.onPointerObservable.remove(this._pointerObserver),this._pointerObserver=null),this._scene&&this._sceneDisposeObserver&&(this._scene.onDisposeObservable.remove(this._sceneDisposeObserver),this._sceneDisposeObserver=null),this._utilityLayer&&this._utilityLayer.dispose()}}function ZV(e,t,i,r){const s={externalResourceFunction:r};return i&&(s.uri="file:"===t?i:t+i),ArrayBuffer.isView(e)?GLTFValidator.validateBytes(e,s):GLTFValidator.validateString(e,s)}function JV(){const e=[];onmessage=t=>{const i=t.data;switch(i.id){case"init":importScripts(i.url);break;case"validate":ZV(i.data,i.rootUrl,i.fileName,(t=>new Promise(((i,r)=>{const s=e.length;e.push({resolve:i,reject:r}),postMessage({id:"getExternalResource",index:s,uri:t})})))).then((e=>{postMessage({id:"validate.resolve",value:e})}),(e=>{postMessage({id:"validate.reject",reason:e})}));break;case"getExternalResource.resolve":e[i.index].resolve(i.value);break;case"getExternalResource.reject":e[i.index].reject(i.reason)}}}QV.MRTK_REALISTIC_SCALING=.032;class ek{static ValidateAsync(e,t,i,r){return"function"==typeof Worker?new Promise(((s,n)=>{const o=`${ZV}(${JV})()`,a=URL.createObjectURL(new Blob([o],{type:"application/javascript"})),l=new Worker(a),h=e=>{l.removeEventListener("error",h),l.removeEventListener("message",c),n(e)},c=e=>{const t=e.data;switch(t.id){case"getExternalResource":r(t.uri).then((e=>{l.postMessage({id:"getExternalResource.resolve",index:t.index,value:e},[e.buffer])}),(e=>{l.postMessage({id:"getExternalResource.reject",index:t.index,reason:e})}));break;case"validate.resolve":l.removeEventListener("error",h),l.removeEventListener("message",c),s(t.value),l.terminate();break;case"validate.reject":l.removeEventListener("error",h),l.removeEventListener("message",c),n(t.reason),l.terminate()}};if(l.addEventListener("error",h),l.addEventListener("message",c),l.postMessage({id:"init",url:Ue.S0.GetBabylonScriptURL(this.Configuration.url)}),ArrayBuffer.isView(e)){const r=e.slice();l.postMessage({id:"validate",data:r,rootUrl:t,fileName:i},[r.buffer])}else l.postMessage({id:"validate",data:e,rootUrl:t,fileName:i})})):(this._LoadScriptPromise||(this._LoadScriptPromise=Ue.S0.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then((()=>ZV(e,t,i,r))))}}ek.Configuration={url:`${Ue.S0._DefaultCdnUrl}/gltf_validator.js`};const tk="Z2xURg",ik="gltf",rk={".gltf":{isBinary:!1,mimeType:"model/gltf+json"},".glb":{isBinary:!0,mimeType:"model/gltf-binary"}},sk=e=>-1!==e.indexOf("asset")&&-1!==e.indexOf("version")||e.startsWith("data:base64,"+tk)||e.startsWith("data:;base64,"+tk)||e.startsWith("data:application/octet-stream;base64,"+tk)||e.startsWith("data:model/gltf-binary;base64,"+tk);function nk(e,t,i){try{return Promise.resolve(new Uint8Array(e,t,i))}catch(e){return Promise.reject(e)}}var ok,ak,lk,hk,ck,uk,dk,fk,pk,_k,mk,gk;!function(e){e[e.AUTO=0]="AUTO",e[e.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"}(ok||(ok={})),function(e){e[e.NONE=0]="NONE",e[e.FIRST=1]="FIRST",e[e.ALL=2]="ALL"}(ak||(ak={})),function(e){e[e.LOADING=0]="LOADING",e[e.READY=1]="READY",e[e.COMPLETE=2]="COMPLETE"}(lk||(lk={}));class vk{constructor(){this.coordinateSystemMode=ok.AUTO,this.animationStartMode=ak.FIRST,this.loadNodeAnimations=!0,this.loadSkins=!0,this.loadMorphTargets=!0,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.useGltfTextureNames=!1,this.preprocessUrlAsync=e=>Promise.resolve(e),this.extensionOptions={}}copyFrom(e){e&&(this.onParsed=e.onParsed,this.coordinateSystemMode=e.coordinateSystemMode??this.coordinateSystemMode,this.animationStartMode=e.animationStartMode??this.animationStartMode,this.loadNodeAnimations=e.loadNodeAnimations??this.loadNodeAnimations,this.loadSkins=e.loadSkins??this.loadSkins,this.loadMorphTargets=e.loadMorphTargets??this.loadMorphTargets,this.compileMaterials=e.compileMaterials??this.compileMaterials,this.useClipPlane=e.useClipPlane??this.useClipPlane,this.compileShadowGenerators=e.compileShadowGenerators??this.compileShadowGenerators,this.transparencyAsCoverage=e.transparencyAsCoverage??this.transparencyAsCoverage,this.useRangeRequests=e.useRangeRequests??this.useRangeRequests,this.createInstances=e.createInstances??this.createInstances,this.alwaysComputeBoundingBox=e.alwaysComputeBoundingBox??this.alwaysComputeBoundingBox,this.loadAllMaterials=e.loadAllMaterials??this.loadAllMaterials,this.loadOnlyMaterials=e.loadOnlyMaterials??this.loadOnlyMaterials,this.skipMaterials=e.skipMaterials??this.skipMaterials,this.useSRGBBuffers=e.useSRGBBuffers??this.useSRGBBuffers,this.targetFps=e.targetFps??this.targetFps,this.alwaysComputeSkeletonRootNode=e.alwaysComputeSkeletonRootNode??this.alwaysComputeSkeletonRootNode,this.useGltfTextureNames=e.useGltfTextureNames??this.useGltfTextureNames,this.preprocessUrlAsync=e.preprocessUrlAsync??this.preprocessUrlAsync,this.customRootNode=e.customRootNode,this.onMeshLoaded=e.onMeshLoaded,this.onSkinLoaded=e.onSkinLoaded,this.onTextureLoaded=e.onTextureLoaded,this.onMaterialLoaded=e.onMaterialLoaded,this.onCameraLoaded=e.onCameraLoaded,this.extensionOptions=e.extensionOptions??this.extensionOptions)}}class xk extends vk{constructor(e){super(),this.onParsedObservable=new z.cP,this.onMeshLoadedObservable=new z.cP,this.onSkinLoadedObservable=new z.cP,this.onTextureLoadedObservable=new z.cP,this.onMaterialLoadedObservable=new z.cP,this.onCameraLoadedObservable=new z.cP,this.onCompleteObservable=new z.cP,this.onErrorObservable=new z.cP,this.onDisposeObservable=new z.cP,this.onExtensionLoadedObservable=new z.cP,this.validate=!1,this.onValidatedObservable=new z.cP,this._loader=null,this._state=null,this._requests=new Array,this.name=ik,this.extensions=rk,this.onLoaderStateChangedObservable=new z.cP,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled,this.copyFrom(e)}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),e&&(this._onParsedObserver=this.onParsedObservable.add(e))}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),e&&(this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e))}set onSkinLoaded(e){this._onSkinLoadedObserver&&this.onSkinLoadedObservable.remove(this._onSkinLoadedObserver),e&&(this._onSkinLoadedObserver=this.onSkinLoadedObservable.add((t=>e(t.node,t.skinnedNode))))}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),e&&(this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e))}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),e&&(this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e))}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),e&&(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,r,s,n,o,a){if(ArrayBuffer.isView(t))return this._loadBinary(e,t,i,r,o,a),null;this._progressCallback=s;const l=t.name||Ue.S0.GetFilename(t);if(n){if(this.useRangeRequests){this.validate&&Z.V.Warn("glTF validation is not supported when range requests are enabled");const i={abort:()=>{},onCompleteObservable:new z.cP},s={readAsync:(i,r)=>new Promise(((s,n)=>{this._loadFile(e,t,(e=>{s(new Uint8Array(e))}),!0,(e=>{n(e)}),(e=>{e.setRequestHeader("Range",`bytes=${i}-${i+r-1}`)}))})),byteLength:0};return this._unpackBinaryAsync(new tI(s)).then((e=>{i.onCompleteObservable.notifyObservers(i),r(e)}),o?e=>o(void 0,e):void 0),i}return this._loadFile(e,t,(t=>{this._validate(e,new Uint8Array(t,0,t.byteLength),i,l),this._unpackBinaryAsync(new tI({readAsync:(e,i)=>nk(t,e,i),byteLength:t.byteLength})).then((e=>{r(e)}),o?e=>o(void 0,e):void 0)}),!0,o)}return this._loadFile(e,t,(t=>{try{this._validate(e,t,i,l),r({json:this._parseJson(t)})}catch{o&&o()}}),!1,o)}_loadBinary(e,t,i,r,s,n){this._validate(e,new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i,n),this._unpackBinaryAsync(new tI({readAsync:(e,i)=>function(e,t,i){try{if(t<0||t>=e.byteLength)throw new RangeError("Offset is out of range.");if(t+i>e.byteLength)throw new RangeError("Length is out of range.");return Promise.resolve(new Uint8Array(e.buffer,e.byteOffset+t,i))}catch(e){return Promise.reject(e)}}(t,e,i),byteLength:t.byteLength})).then((e=>{r(e)}),s?e=>s(void 0,e):void 0)}importMeshAsync(e,t,i,r,s,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,r,s,n))))}loadAsync(e,t,i,r,s){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,i,r,s))))}loadAssetContainerAsync(e,t,i,r,s){return Promise.resolve().then((()=>{this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t);const n=new ei(e),o=[];this.onMaterialLoadedObservable.add((e=>{o.push(e)}));const a=[];this.onTextureLoadedObservable.add((e=>{a.push(e)}));const l=[];this.onCameraLoadedObservable.add((e=>{l.push(e)}));const h=[];return this.onMeshLoadedObservable.add((e=>{e.morphTargetManager&&h.push(e.morphTargetManager)})),this._loader.importMeshAsync(null,e,n,t,i,r,s).then((e=>(Array.prototype.push.apply(n.geometries,e.geometries),Array.prototype.push.apply(n.meshes,e.meshes),Array.prototype.push.apply(n.particleSystems,e.particleSystems),Array.prototype.push.apply(n.skeletons,e.skeletons),Array.prototype.push.apply(n.animationGroups,e.animationGroups),Array.prototype.push.apply(n.materials,o),Array.prototype.push.apply(n.textures,a),Array.prototype.push.apply(n.lights,e.lights),Array.prototype.push.apply(n.transformNodes,e.transformNodes),Array.prototype.push.apply(n.cameras,l),Array.prototype.push.apply(n.morphTargetManagers,h),n)))}))}canDirectLoad(e){return sk(e)}directLoad(e,t){if(t.startsWith("base64,"+tk)||t.startsWith(";base64,"+tk)||t.startsWith("application/octet-stream;base64,"+tk)||t.startsWith("model/gltf-binary;base64,"+tk)){const i=(0,$m.rz)(t);return this._validate(e,new Uint8Array(i,0,i.byteLength)),this._unpackBinaryAsync(new tI({readAsync:(e,t)=>nk(i,e,t),byteLength:i.byteLength}))}return this._validate(e,t),Promise.resolve({json:this._parseJson(t)})}createPlugin(e){return new xk(e[ik])}get loaderState(){return this._state}whenCompleteAsync(){return new Promise(((e,t)=>{this.onCompleteObservable.addOnce((()=>{e()})),this.onErrorObservable.addOnce((e=>{t(e)}))}))}_setState(e){this._state!==e&&(this._state=e,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(lk[this._state]))}_loadFile(e,t,i,r,s,n){const o=e._loadFile(t,i,(e=>{this._onProgress(e,o)}),!0,r,s,n);return o.onCompleteObservable.add((()=>{o._lengthComputable=!0,o._total=o._loaded})),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,r=0,s=0;for(const e of this._requests){if(void 0===e._lengthComputable||void 0===e._loaded||void 0===e._total)return;i=i&&e._lengthComputable,r+=e._loaded,s+=e._total}this._progressCallback({lengthComputable:i,loaded:r,total:i?s:0})}_validate(e,t,i="",r=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),ek.ValidateAsync(t,i,r,(t=>this.preprocessUrlAsync(i+t).then((t=>e._loadFileAsync(t,void 0,!0,!0).then((e=>new Uint8Array(e,0,e.byteLength))))))).then((e=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(e),this.onValidatedObservable.clear()}),(e=>{this._endPerformanceCounter("Validate JSON"),Ue.S0.Warn(`Failed to validate: ${e.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=xk._parseVersion(t.version);if(!i)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=xk._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(xk._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const r={1:xk._CreateGLTF1Loader,2:xk._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=e.readUint32();if(1179937895!==t)throw new nt.bu("Unexpected magic: "+t,nt.tG.GLTFLoaderUnexpectedMagicError);const i=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${i}`);const r=e.readUint32();let s;switch(this.useRangeRequests||r===e.buffer.byteLength||Z.V.Warn(`Length in header does not match actual data length: ${r} != ${e.buffer.byteLength}`),i){case 1:s=this._unpackBinaryV1Async(e,r);break;case 2:s=this._unpackBinaryV2Async(e,r);break;default:throw new Error("Unsupported version: "+i)}return this._endPerformanceCounter("Unpack Binary"),s}))}_unpackBinaryV1Async(e,t){const i=e.readUint32(),r=e.readUint32();if(0!==r)throw new Error(`Unexpected content format: ${r}`);const s=t-e.byteOffset,n={json:this._parseJson(e.readString(i)),bin:null};if(0!==s){const t=e.byteOffset;n.bin={readAsync:(i,r)=>e.buffer.readAsync(t+i,r),byteLength:s}}return Promise.resolve(n)}_unpackBinaryV2Async(e,t){const i=1313821514,r=e.readUint32();if(e.readUint32()!==i)throw new Error("First chunk format is not JSON");return e.byteOffset+r===t?e.loadAsync(r).then((()=>({json:this._parseJson(e.readString(r)),bin:null}))):e.loadAsync(r+8).then((()=>{const s={json:this._parseJson(e.readString(r)),bin:null},n=()=>{const r=e.readUint32();switch(e.readUint32()){case i:throw new Error("Unexpected JSON chunk");case 5130562:{const t=e.byteOffset;s.bin={readAsync:(i,r)=>e.buffer.readAsync(t+i,r),byteLength:r},e.skipBytes(r);break}default:e.skipBytes(r)}return e.byteOffset!==t?e.loadAsync(8).then(n):Promise.resolve(s)};return n()}))}static _parseVersion(e){if("1.0"===e||"1.0.1"===e)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,s){case hk.BYTE:return new Int8Array(o,i,r);case hk.UNSIGNED_BYTE:return new Uint8Array(o,i,r);case hk.SHORT:return new Int16Array(o,i,r);case hk.UNSIGNED_SHORT:return new Uint16Array(o,i,r);default:return new Float32Array(o,i,r)}}static GetBufferFromAccessor(e,t){const i=e.bufferViews[t.bufferView],r=t.count*bk.GetByteStrideFromType(t);return bk.GetBufferFromBufferView(e,i,t.byteOffset,r,t.componentType)}static DecodeBufferToText(e){let t="";const i=e.byteLength;for(let r=0;r=this._maxPos}}const Tk=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],Ck=["world","view","projection","worldView","worldViewProjection","mBones"],yk=["translation","rotation","scale"],Ek=["position","rotationQuaternion","scaling"],Pk=(e,t,i)=>{for(const r in e){const s=e[r];i[t][r]=s}},Ak=e=>{if(e)for(let t=0;t{if("NORMAL"===e.semantic)return"normal";if("POSITION"===e.semantic)return"position";if("JOINT"===e.semantic)return"matricesIndices";if("WEIGHT"===e.semantic)return"matricesWeights";if("COLOR"===e.semantic)return"color";if(e.semantic&&-1!==e.semantic.indexOf("TEXCOORD_")){const t=Number(e.semantic.split("_")[1]);return"uv"+(0===t?"":t+1)}return null},Ik=e=>{let t=null;if(e.translation||e.rotation||e.scale){const i=W.Pq.FromArray(e.scale||[1,1,1]),r=W.PT.FromArray(e.rotation||[0,0,0,1]),s=W.Pq.FromArray(e.translation||[0,0,0]);t=W.uq.Compose(i,r,s)}else t=W.uq.FromArray(e.matrix);return t},Mk=(e,t,i,r)=>{for(let e=0;e{for(let i=0;i{const i=e.nodes;let r=i[t];if(r)return{node:r,id:t};for(const e in i)if(r=i[e],r.jointName===t)return{node:r,id:e};return null},wk=(e,t)=>{for(let i=0;i{if(s||(e.scene._blockEntityCollection=!!e.assetContainer,(s=new Yt(t.name||"",e.scene))._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,s.id=r),!t.babylonNode)return s;const n=[];let o=null;const a=[],l=[],h=[],c=[];for(let t=0;t1?(u=new kt("multimat"+r,e.scene),u.subMaterials=n):u=new Un("multimat"+r,e.scene),1===n.length&&(u=n[0]),u._parentContainer=e.assetContainer,s.material||(s.material=u),new yt(r,e.scene,o,!1,s),s.computeWorldMatrix(!0),e.scene._blockEntityCollection=!1,s.subMeshes=[];let d=0;for(let t=0;t{e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=i),e.scaling&&(e.scaling=r)},Lk=(e,t,i)=>{let r=null;if(e.importOnlyMeshes&&(t.skin||t.meshes)&&e.importMeshesNames&&e.importMeshesNames.length>0&&-1===e.importMeshesNames.indexOf(t.name||""))return null;if(t.skin){if(t.meshes){const s=e.skins[t.skin],n=Nk(e,t,t.meshes,i,t.babylonNode);n.skeleton=e.scene.getLastSkeletonById(t.skin),null===n.skeleton&&(n.skeleton=((e,t,i,r)=>{if(r||(r=new Ti(t.name||"","",e.scene)),!t.babylonSkeleton)return r;const s=[],n=[];((e,t,i,r)=>{for(const s in e.nodes){const n=e.nodes[s],o=s;if(!n.jointName||wk(i,n.jointName))continue;const a=Ik(n),l=new Si.$(n.name||"",t,null,a);l.id=o,r.push({bone:l,node:n,id:o})}for(let e=0;e0&&(u=Ok(s,l),u&&-1===n.indexOf(u)&&n.push(u)),new Si.$(a.jointName||"",r,u,d).id=l}const o=r.bones;r.bones=[];for(let i=0;i{if(t.matrix){const i=new W.Pq(0,0,0),r=new W.PT,s=new W.Pq(0,0,0);W.uq.FromArray(t.matrix).decompose(s,r,i),Fk(e,i,r,s)}else t.translation&&t.rotation&&t.scale&&Fk(e,W.Pq.FromArray(t.translation),W.PT.FromArray(t.rotation),W.Pq.FromArray(t.scale));e.computeWorldMatrix(!0)})(r,t);else{const e=t.translation||[0,0,0],i=t.rotation||[0,0,0,1],s=t.scale||[1,1,1];Fk(r,W.Pq.FromArray(e),W.PT.FromArray(i),W.Pq.FromArray(s))}r.updateCache(!0),t.babylonNode=r}return r},Bk=(e,t,i,r=!1)=>{const s=e.nodes[t];let n=null;if(r=!(e.importOnlyMeshes&&!r&&e.importMeshesNames)||-1!==e.importMeshesNames.indexOf(s.name||"")||0===e.importMeshesNames.length,!s.jointName&&r&&(n=Lk(e,s,t),null!==n&&(n.id=t,n.parent=i)),s.children)for(let t=0;t{let t=e.currentScene;if(t)for(let i=0;i{for(const t in e.animations){const i=e.animations[t];if(!i.channels||!i.samplers)continue;let r=null;for(let s=0;s{for(const r in t.uniforms){const s=t.uniforms[r],n=t.parameters[s];if(e.currentIdentifier===r&&n.semantic&&!n.source&&!n.node){const e=Tk.indexOf(n.semantic);if(-1!==e)return delete i[r],Ck[e]}}return e.currentIdentifier},Uk=e=>{for(const t in e.materials)Wk.LoadMaterialAsync(e,t,(()=>{}),(()=>{}))};class Gk{static CreateRuntime(e,t,i){const r={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&&Pk(e.extensions,"extensions",r),e.extensionsUsed&&Pk(e.extensionsUsed,"extensionsUsed",r),e.buffers&&((e,t)=>{for(const i in e){const r=e[i];t.buffers[i]=r,t.buffersCount++}})(e.buffers,r),e.bufferViews&&Pk(e.bufferViews,"bufferViews",r),e.accessors&&Pk(e.accessors,"accessors",r),e.meshes&&Pk(e.meshes,"meshes",r),e.lights&&Pk(e.lights,"lights",r),e.cameras&&Pk(e.cameras,"cameras",r),e.nodes&&Pk(e.nodes,"nodes",r),e.images&&Pk(e.images,"images",r),e.textures&&Pk(e.textures,"textures",r),e.shaders&&((e,t)=>{for(const i in e){const r=e[i];t.shaders[i]=r,t.shaderscount++}})(e.shaders,r),e.programs&&Pk(e.programs,"programs",r),e.samplers&&Pk(e.samplers,"samplers",r),e.techniques&&Pk(e.techniques,"techniques",r),e.materials&&Pk(e.materials,"materials",r),e.animations&&Pk(e.animations,"animations",r),e.skins&&Pk(e.skins,"skins",r),e.scenes&&(r.scenes=e.scenes),e.scene&&e.scenes&&(r.currentScene=e.scenes[e.scene]),r}static LoadBufferAsync(e,t,i,r,s){const n=e.buffers[t];Ue.S0.IsBase64(n.uri)?setTimeout((()=>i(new Uint8Array(Ue.S0.DecodeBase64(n.uri))))):Ue.S0.LoadFile(e.rootUrl+n.uri,(e=>i(new Uint8Array(e))),s,void 0,!0,(e=>{e&&r(e.status+" "+e.statusText)}))}static LoadTextureBufferAsync(e,t,i,r){const s=e.textures[t];if(!s||!s.source)return void r("");if(s.babylonTexture)return void i(null);const n=e.images[s.source];Ue.S0.IsBase64(n.uri)?setTimeout((()=>i(new Uint8Array(Ue.S0.DecodeBase64(n.uri))))):Ue.S0.LoadFile(e.rootUrl+n.uri,(e=>i(new Uint8Array(e))),void 0,void 0,!0,(e=>{e&&r(e.status+" "+e.statusText)}))}static CreateTextureAsync(e,t,i,r){const s=e.textures[t];if(s.babylonTexture)return void r(s.babylonTexture);const n=e.samplers[s.sampler],o=n.minFilter===fk.NEAREST_MIPMAP_NEAREST||n.minFilter===fk.NEAREST_MIPMAP_LINEAR||n.minFilter===fk.LINEAR_MIPMAP_NEAREST||n.minFilter===fk.LINEAR_MIPMAP_LINEAR,a=vi.g.BILINEAR_SAMPLINGMODE,l=null==i?new Blob:new Blob([i]),h=URL.createObjectURL(l),c=()=>URL.revokeObjectURL(h),u=new vi.g(h,e.scene,!o,!0,a,c,c);void 0!==n.wrapS&&(u.wrapU=bk.GetWrapMode(n.wrapS)),void 0!==n.wrapT&&(u.wrapV=bk.GetWrapMode(n.wrapT)),u.name=t,s.babylonTexture=u,r(u)}static LoadShaderStringAsync(e,t,i,r){const s=e.shaders[t];if(Ue.S0.IsBase64(s.uri)){const e=atob(s.uri.split(",")[1]);i&&i(e)}else Ue.S0.LoadFile(e.rootUrl+s.uri,i,void 0,void 0,!1,(e=>{e&&r&&r(e.status+" "+e.statusText)}))}static LoadMaterialAsync(e,t,i,r){const s=e.materials[t];if(!s.technique)return void(r&&r("No technique found."));const n=e.techniques[s.technique];if(!n){e.scene._blockEntityCollection=!!e.assetContainer;const r=new Un(t,e.scene);return r._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,r.diffuseColor=new H.v9(.5,.5,.5),r.sideOrientation=Vt.CounterClockWiseSideOrientation,void i(r)}const o=e.programs[n.program],a=n.states,l=Cl.M.ShadersStore[o.vertexShader+"VertexShader"],h=Cl.M.ShadersStore[o.fragmentShader+"PixelShader"];let c="",u="";const d=new Sk(l),f=new Sk(h),p={},_=[],m=[],g=[];for(const e in n.uniforms){const t=n.uniforms[e],i=n.parameters[t];if(p[e]=i,!i.semantic||i.node||i.source)i.type===uk.SAMPLER_2D?g.push(e):_.push(e);else{const t=Tk.indexOf(i.semantic);-1!==t?(_.push(Ck[t]),delete p[e]):_.push(e)}}for(const e in n.attributes){const t=n.attributes[e],i=n.parameters[t];if(i.semantic){const e=Rk(i);e&&m.push(e)}}for(;!d.isEnd()&&d.getNextToken();){if(d.currentToken!==gk.IDENTIFIER){c+=d.currentString;continue}let e=!1;for(const t in n.attributes){const i=n.attributes[t],r=n.parameters[i];if(d.currentIdentifier===t&&r.semantic){c+=Rk(r),e=!0;break}}e||(c+=kk(d,n,p))}for(;!f.isEnd()&&f.getNextToken();)f.currentToken===gk.IDENTIFIER?u+=kk(f,n,p):u+=f.currentString;const v={vertex:o.vertexShader+t,fragment:o.fragmentShader+t},x={attributes:m,uniforms:_,samplers:g,needAlphaBlending:a&&a.enable&&-1!==a.enable.indexOf(3042)};Cl.M.ShadersStore[o.vertexShader+t+"VertexShader"]=c,Cl.M.ShadersStore[o.fragmentShader+t+"PixelShader"]=u;const b=new xo(t,e.scene,v,x);if(b.onError=((e,t,i)=>(r,s)=>{t.dispose(!0),i("Cannot compile program named "+e.name+". Error: "+s+". Default material will be applied")})(o,b,r),b.onCompiled=((e,t,i,r,s,n)=>o=>{((e,t,i,r,s)=>{const n=r.values||i.parameters,o=i.uniforms;for(const i in s){const a=s[i],l=a.type;let h=n[o[i]];if(void 0===h&&(h=a.value),!h)continue;const c=e=>i=>{a.value&&e&&(t.setTexture(e,i),delete s[e])};l===uk.SAMPLER_2D?Wk.LoadTextureAsync(e,r.values?h:a.value,c(i),(()=>c(null))):a.value&&bk.SetUniform(t,i,r.values?h:a.value,l)&&delete s[i]}})(e,t,i,r,s),t.onBind=o=>{((e,t,i,r,s,n,o)=>{const a=n.values||s.parameters;for(const o in i){const l=i[o],h=l.type;if(h===uk.FLOAT_MAT2||h===uk.FLOAT_MAT3||h===uk.FLOAT_MAT4)if(!l.semantic||l.source||l.node){if(l.semantic&&(l.source||l.node)){let e=t.scene.getNodeByName(l.source||l.node||"");if(null===e&&(e=t.scene.getNodeById(l.source||l.node||"")),null===e)continue;bk.SetMatrix(t.scene,e,l,o,r.getEffect())}}else bk.SetMatrix(t.scene,e,l,o,r.getEffect());else{const e=a[s.uniforms[o]];if(!e)continue;if(h===uk.SAMPLER_2D){const i=t.textures[n.values?e:l.value].babylonTexture;if(null==i)continue;r.getEffect().setTexture(o,i)}else bk.SetUniform(r.getEffect(),o,e,h)}}o(r)})(o,e,s,t,i,r,n)}})(e,b,n,s,p,i),b.sideOrientation=Vt.CounterClockWiseSideOrientation,a&&a.functions){const e=a.functions;e.cullFace&&e.cullFace[0]!==_k.BACK&&(b.backFaceCulling=!1);const t=e.blendFuncSeparate;t&&(t[0]===mk.SRC_ALPHA&&t[1]===mk.ONE_MINUS_SRC_ALPHA&&t[2]===mk.ONE&&t[3]===mk.ONE?b.alphaMode=Il.ALPHA_COMBINE:t[0]===mk.ONE&&t[1]===mk.ONE&&t[2]===mk.ZERO&&t[3]===mk.ONE?b.alphaMode=Il.ALPHA_ONEONE:t[0]===mk.SRC_ALPHA&&t[1]===mk.ONE&&t[2]===mk.ZERO&&t[3]===mk.ONE?b.alphaMode=Il.ALPHA_ADD:t[0]===mk.ZERO&&t[1]===mk.ONE_MINUS_SRC_COLOR&&t[2]===mk.ONE&&t[3]===mk.ONE?b.alphaMode=Il.ALPHA_SUBTRACT:t[0]===mk.DST_COLOR&&t[1]===mk.ZERO&&t[2]===mk.ONE&&t[3]===mk.ONE?b.alphaMode=Il.ALPHA_MULTIPLY:t[0]===mk.SRC_ALPHA&&t[1]===mk.ONE_MINUS_SRC_COLOR&&t[2]===mk.ONE&&t[3]===mk.ONE&&(b.alphaMode=Il.ALPHA_MAXIMIZED))}}}class zk{static RegisterExtension(e){zk.Extensions[e.name]?Ue.S0.Error('Tool with the same name "'+e.name+'" already exists'):zk.Extensions[e.name]=e}dispose(){}_importMeshAsync(e,t,i,r,s,n,o,a){return t.useRightHandedSystem=!0,Wk.LoadRuntimeAsync(t,i,r,(t=>{t.assetContainer=s,t.importOnlyMeshes=!0,""===e?t.importMeshesNames=[]:"string"==typeof e?t.importMeshesNames=[e]:!e||e instanceof Array?(t.importMeshesNames=[],Ue.S0.Warn("Argument meshesNames must be of type string or string[]")):t.importMeshesNames=[e],this._createNodes(t);const i=[],r=[];for(const e in t.nodes){const r=t.nodes[e];r.babylonNode instanceof Nt&&i.push(r.babylonNode)}for(const e in t.skins){const i=t.skins[e];i.babylonSkeleton instanceof Ti&&r.push(i.babylonSkeleton)}this._loadBuffersAsync(t,(()=>{this._loadShadersAsync(t,(()=>{Uk(t),Vk(t),!xk.IncrementalLoading&&n&&n(i,r)}))})),xk.IncrementalLoading&&n&&n(i,r)}),a),!0}importMeshAsync(e,t,i,r,s,n){return new Promise(((o,a)=>{this._importMeshAsync(e,t,r,s,i,((e,t)=>{o({meshes:e,particleSystems:[],skeletons:t,animationGroups:[],lights:[],transformNodes:[],geometries:[],spriteManagers:[]})}),n,(e=>{a(new Error(e))}))}))}_loadAsync(e,t,i,r,s,n){e.useRightHandedSystem=!0,Wk.LoadRuntimeAsync(e,t,i,(e=>{Wk.LoadRuntimeExtensionsAsync(e,(()=>{this._createNodes(e),this._loadBuffersAsync(e,(()=>{this._loadShadersAsync(e,(()=>{Uk(e),Vk(e),xk.IncrementalLoading||r()}))})),xk.IncrementalLoading&&r()}),n)}),n)}loadAsync(e,t,i,r){return new Promise(((s,n)=>{this._loadAsync(e,t,i,(()=>{s()}),r,(e=>{n(new Error(e))}))}))}_loadShadersAsync(e,t){let i=!1;const r=(i,r)=>{Wk.LoadShaderStringAsync(e,i,(s=>{s instanceof ArrayBuffer||(e.loadedShaderCount++,s&&(Cl.M.ShadersStore[i+(r.type===ck.VERTEX?"VertexShader":"PixelShader")]=s),e.loadedShaderCount===e.shaderscount&&t())}),(()=>{Ue.S0.Error("Error when loading shader program named "+i+" located at "+r.uri)}))};for(const t in e.shaders){i=!0;const s=e.shaders[t];s?r.bind(this,t,s)():Ue.S0.Error("No shader named: "+t)}i||t()}_loadBuffersAsync(e,t){let i=!1;const r=(i,r)=>{Wk.LoadBufferAsync(e,i,(s=>{e.loadedBufferCount++,s&&(s.byteLength!=e.buffers[i].byteLength&&Ue.S0.Error("Buffer named "+i+" is length "+s.byteLength+". Expected: "+r.byteLength),e.loadedBufferViews[i]=s),e.loadedBufferCount===e.buffersCount&&t()}),(()=>{Ue.S0.Error("Error when loading buffer named "+i+" located at "+r.uri)}))};for(const t in e.buffers){i=!0;const s=e.buffers[t];s?r.bind(this,t,s)():Ue.S0.Error("No buffer named: "+t)}i||t()}_createNodes(e){let t=e.currentScene;if(t)for(let i=0;in.loadRuntimeAsync(e,t,i,r,s)),(()=>{setTimeout((()=>{r&&r(Gk.CreateRuntime(t.json,e,i))}))}))}static LoadRuntimeExtensionsAsync(e,t,i){Wk._ApplyExtensions((r=>r.loadRuntimeExtensionsAsync(e,t,i)),(()=>{setTimeout((()=>{t()}))}))}static LoadBufferAsync(e,t,i,r,s){Wk._ApplyExtensions((n=>n.loadBufferAsync(e,t,i,r,s)),(()=>{Gk.LoadBufferAsync(e,t,i,r,s)}))}static LoadTextureAsync(e,t,i,r){Wk._LoadTextureBufferAsync(e,t,(s=>{s&&Wk._CreateTextureAsync(e,t,s,i,r)}),r)}static LoadShaderStringAsync(e,t,i,r){Wk._ApplyExtensions((s=>s.loadShaderStringAsync(e,t,i,r)),(()=>{Gk.LoadShaderStringAsync(e,t,i,r)}))}static LoadMaterialAsync(e,t,i,r){Wk._ApplyExtensions((s=>s.loadMaterialAsync(e,t,i,r)),(()=>{Gk.LoadMaterialAsync(e,t,i,r)}))}static _LoadTextureBufferAsync(e,t,i,r){Wk._ApplyExtensions((s=>s.loadTextureBufferAsync(e,t,i,r)),(()=>{Gk.LoadTextureBufferAsync(e,t,i,r)}))}static _CreateTextureAsync(e,t,i,r,s){Wk._ApplyExtensions((n=>n.createTextureAsync(e,t,i,r,s)),(()=>{Gk.CreateTextureAsync(e,t,i,r)}))}static _ApplyExtensions(e,t){for(const t in zk.Extensions)if(e(zk.Extensions[t]))return;t()}}function Hk(e,t,i,r){return W.Pq.FromArray(t,i).scaleInPlace(r)}xk._CreateGLTF1Loader=()=>new zk,zk.RegisterExtension(new class extends Wk{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,i,r){const s=t.json.extensionsUsed;return!(!s||-1===s.indexOf(this.name)||!t.bin||(this._bin=t.bin,r(Gk.CreateRuntime(t.json,e,i)),0))}loadBufferAsync(e,t,i,r){return-1!==e.extensionsUsed.indexOf(this.name)&&"binary_glTF"===t&&(this._bin.readAsync(0,this._bin.byteLength).then(i,(e=>r(e.message))),!0)}loadTextureBufferAsync(e,t,i){const r=e.textures[t],s=e.images[r.source];if(!s.extensions||!(this.name in s.extensions))return!1;const n=s.extensions[this.name],o=e.bufferViews[n.bufferView];return i(bk.GetBufferFromBufferView(e,o,0,o.byteLength,hk.UNSIGNED_BYTE)),!0}loadShaderStringAsync(e,t,i){const r=e.shaders[t];if(!r.extensions||!(this.name in r.extensions))return!1;const s=r.extensions[this.name],n=e.bufferViews[s.bufferView],o=bk.GetBufferFromBufferView(e,n,0,n.byteLength,hk.UNSIGNED_BYTE);return setTimeout((()=>{const e=bk.DecodeBufferToText(o);i(e)})),!0}}),zk.RegisterExtension(new class extends Wk{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 t in i){const r=i[t];switch(r.type){case"ambient":{const t=new Lo(r.name,new W.Pq(0,1,0),e.scene),i=r.ambient;i&&(t.diffuse=H.v9.FromArray(i.color||[1,1,1]));break}case"point":{const t=new wx(r.name,new W.Pq(10,10,10),e.scene),i=r.point;i&&(t.diffuse=H.v9.FromArray(i.color||[1,1,1]));break}case"directional":{const t=new hm(r.name,new W.Pq(0,-1,0),e.scene),i=r.directional;i&&(t.diffuse=H.v9.FromArray(i.color||[1,1,1]));break}case"spot":{const t=r.spot;t&&(new dm(r.name,new W.Pq(0,10,0),new W.Pq(0,-1,0),t.fallOffAngle||Math.PI,t.fallOffExponent||0,e.scene).diffuse=H.v9.FromArray(t.color||[1,1,1]));break}default:Ue.S0.Warn('GLTF Material Common extension: light type "'+r.type+"” not supported")}}return!1}loadMaterialAsync(e,t,i,r){const s=e.materials[t];if(!s||!s.extensions)return!1;const n=s.extensions[this.name];if(!n)return!1;const o=new Un(t,e.scene);return o.sideOrientation=Vt.CounterClockWiseSideOrientation,"CONSTANT"===n.technique&&(o.disableLighting=!0),o.backFaceCulling=void 0!==n.doubleSided&&!n.doubleSided,o.alpha=void 0===n.values.transparency?1:n.values.transparency,o.specularPower=void 0===n.values.shininess?0:n.values.shininess,"string"==typeof n.values.ambient?this._loadTexture(e,n.values.ambient,o,"ambientTexture",r):o.ambientColor=H.v9.FromArray(n.values.ambient||[0,0,0]),"string"==typeof n.values.diffuse?this._loadTexture(e,n.values.diffuse,o,"diffuseTexture",r):o.diffuseColor=H.v9.FromArray(n.values.diffuse||[0,0,0]),"string"==typeof n.values.emission?this._loadTexture(e,n.values.emission,o,"emissiveTexture",r):o.emissiveColor=H.v9.FromArray(n.values.emission||[0,0,0]),"string"==typeof n.values.specular?this._loadTexture(e,n.values.specular,o,"specularTexture",r):o.specularColor=H.v9.FromArray(n.values.specular||[0,0,0]),!0}_loadTexture(e,t,i,r,s){Gk.LoadTextureBufferAsync(e,t,(s=>{Gk.CreateTextureAsync(e,t,s,(e=>i[r]=e))}),s)}});class Xk{constructor(e,t,i,r){this.type=e,this.name=t,this.getValue=i,this.getStride=r}_buildAnimation(e,t,i){const r=new pe.X5(e,this.name,t,this.type);return r.setKeys(i),r}}class qk extends Xk{buildAnimations(e,t,i,r,s){s(e._babylonTransformNode,this._buildAnimation(t,i,r))}}const Yk={translation:[new qk(pe.X5.ANIMATIONTYPE_VECTOR3,"position",Hk,(()=>3))],rotation:[new qk(pe.X5.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",(function(e,t,i,r){return W.PT.FromArray(t,i).scaleInPlace(r)}),(()=>4))],scale:[new qk(pe.X5.ANIMATIONTYPE_VECTOR3,"scaling",Hk,(()=>3))],weights:[new class extends Xk{buildAnimations(e,t,i,r,s){if(e._numMorphTargets)for(let n=0;n({frame:e.frame,inTangent:e.inTangent?e.inTangent[n]:void 0,value:e.value[n],outTangent:e.outTangent?e.outTangent[n]:void 0,interpolation:e.interpolation})))),e._primitiveBabylonMeshes)for(const t of e._primitiveBabylonMeshes)if(t.morphTargetManager){const e=t.morphTargetManager.getTarget(n),i=o.clone();e.animations.push(i),s(e,i)}}}}(pe.X5.ANIMATIONTYPE_FLOAT,"influence",(function(e,t,i,r){const s=new Array(e._numMorphTargets);for(let e=0;ee._numMorphTargets))]},Kk=new Map,jk=Kk;function $k(e,t,i){Qk(e)&&Z.V.Warn(`Extension with the name '${e}' already exists`),Kk.set(e,{isGLTFExtension:t,factory:i})}function Qk(e){return Kk.delete(e)}function Zk(...e){const t=e=>e&&"object"==typeof e;return e.reduce(((e,i)=>(Object.keys(i).forEach((r=>{const s=e[r],n=i[r];Array.isArray(s)&&Array.isArray(n)?e[r]=s.concat(...n):t(s)&&t(n)?e[r]=Zk(s,n):e[r]=n})),e)),{})}class Jk{static Get(e,t,i){if(!t||null==i||!t[i])throw new Error(`${e}: Failed to find index (${i})`);return t[i]}static TryGet(e,t){return e&&null!=t&&e[t]?e[t]:null}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,r,s,n,o=""){return Promise.resolve().then((()=>{this._babylonScene=t,this._assetContainer=i,this._loadData(r);let n=null;if(e){const t={};if(this._gltf.nodes)for(const e of this._gltf.nodes)e.name&&(t[e.name]=e.index);n=(e instanceof Array?e:[e]).map((e=>{const i=t[e];if(void 0===i)throw new Error(`Failed to find node '${e}'`);return i}))}return this._loadAsync(s,o,n,(()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]})))}))}loadAsync(e,t,i,r,s=""){return Promise.resolve().then((()=>(this._babylonScene=e,this._loadData(t),this._loadAsync(i,s,null,(()=>{})))))}_loadAsync(e,t,i,r){return Promise.resolve().then((async()=>{this._rootUrl=e,this._uniqueRootUrl=!e.startsWith("file:")&&t?e:`${e}${Date.now()}/`,this._fileName=t,this._allMaterialsDirtyRequired=!1,await this._loadExtensionsAsync();const s=`${lk[lk.LOADING]} => ${lk[lk.READY]}`,n=`${lk[lk.LOADING]} => ${lk[lk.COMPLETE]}`;this._parent._startPerformanceCounter(s),this._parent._startPerformanceCounter(n),this._parent._setState(lk.LOADING),this._extensionsOnLoading();const o=new Array,a=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials)if(i)o.push(this.loadSceneAsync("/nodes",{nodes:i,index:-1}));else if(null!=this._gltf.scene||this._gltf.scenes&&this._gltf.scenes[0]){const e=Jk.Get("/scene",this._gltf.scenes,this._gltf.scene||0);o.push(this.loadSceneAsync(`/scenes/${e.index}`,e))}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let e=0;e{})))}return this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=a:this._babylonScene._forceBlockMaterialDirtyMechanism(a),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(lk.READY),this._startAnimations(),r()))).then((e=>(this._parent._endPerformanceCounter(s),Ue.S0.SetImmediate((()=>{this._disposed||Promise.all(this._completePromises).then((()=>{this._parent._endPerformanceCounter(n),this._parent._setState(lk.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()}),(e=>{this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()}))})),e)))})).catch((e=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()),e}))}_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)&&Z.V.Warn(`Binary buffer length (${i.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else Z.V.Warn("Unexpected BIN chunk")}}_setupData(){if(Jk.Assign(this._gltf.accessors),Jk.Assign(this._gltf.animations),Jk.Assign(this._gltf.buffers),Jk.Assign(this._gltf.bufferViews),Jk.Assign(this._gltf.cameras),Jk.Assign(this._gltf.images),Jk.Assign(this._gltf.materials),Jk.Assign(this._gltf.meshes),Jk.Assign(this._gltf.nodes),Jk.Assign(this._gltf.samplers),Jk.Assign(this._gltf.scenes),Jk.Assign(this._gltf.skins),Jk.Assign(this._gltf.textures),this._gltf.nodes){const e={};for(const t of this._gltf.nodes)if(t.children)for(const i of t.children)e[i]=t.index;const t=this._createRootNode();for(const i of this._gltf.nodes){const r=e[i.index];i.parent=void 0===r?t:this._gltf.nodes[r]}}}async _loadExtensionsAsync(){const e=[];if(jk.forEach(((t,i)=>{!1===this.parent.extensionOptions[i]?.enabled?t.isGLTFExtension&&this.isExtensionUsed(i)&&Z.V.Warn(`Extension ${i} is used but has been explicitly disabled.`):t.isGLTFExtension&&!this.isExtensionUsed(i)||e.push((async()=>{const e=await t.factory(this);return e.name!==i&&Z.V.Warn(`The name of the glTF loader extension instance does not match the registered name: ${e.name} !== ${i}`),this._parent.onExtensionLoadedObservable.notifyObservers(e),e})())})),this._extensions.push(...await Promise.all(e)),this._extensions.sort(((e,t)=>(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE))),this._parent.onExtensionLoadedObservable.clear(),this._gltf.extensionsRequired)for(const e of this._gltf.extensionsRequired)if(!this._extensions.some((t=>t.name===e&&t.enabled))){if(!1===this.parent.extensionOptions[e]?.enabled)throw new Error(`Required extension ${e} is disabled`);throw new Error(`Required extension ${e} is not available`)}}_createRootNode(){if(void 0!==this._parent.customRootNode)return this._rootBabylonMesh=this._parent.customRootNode,{_babylonTransformNode:null===this._rootBabylonMesh?void 0:this._rootBabylonMesh,index:-1};this._babylonScene._blockEntityCollection=!!this._assetContainer;const e=new Yt("__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 ok.AUTO:this._babylonScene.useRightHandedSystem||(t.rotation=[0,1,0,0],t.scale=[1,1,-1],eU._LoadTransform(t,this._rootBabylonMesh));break;case ok.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 r=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const i of t.nodes){const t=Jk.Get(`${e}/nodes/${i}`,this._gltf.nodes,i);r.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=this._rootBabylonMesh})))}for(const e of this._postSceneLoadActions)e();return r.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(r).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,(t=>{const i=t.geometry;i&&-1===e.indexOf(i)&&e.push(i)}));return e}_getMeshes(){const e=[];this._rootBabylonMesh instanceof Nt&&e.push(this._rootBabylonMesh);const t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,(t=>{e.push(t)}));return e}_getTransformNodes(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)i._babylonTransformNode&&"TransformNode"===i._babylonTransformNode.getClassName()&&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 ak.NONE:break;case ak.FIRST:{const e=this._getAnimationGroups();0!==e.length&&e[0].start(!0);break}case ak.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:return void Z.V.Error(`Invalid animation start mode (${this._parent.animationStartMode})`)}}loadNodeAsync(e,t,i=(()=>{})){const r=this._extensionsLoadNodeAsync(e,t,i);if(r)return r;if(t._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const s=new Array;this.logOpen(`${e} ${t.name||""}`);const n=r=>{if(eU.AddPointerMetadata(r,e),eU._LoadTransform(t,r),null!=t.camera){const i=Jk.Get(`${e}/camera`,this._gltf.cameras,t.camera);s.push(this.loadCameraAsync(`/cameras/${i.index}`,i,(e=>{e.parent=r})))}if(t.children)for(const i of t.children){const t=Jk.Get(`${e}/children/${i}`,this._gltf.nodes,i);s.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=r})))}i(r)},o=null!=t.mesh,a=this._parent.loadSkins&&null!=t.skin;if(!o||a){const e=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new Pt(e,this._babylonScene);i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,null==t.mesh?t._babylonTransformNode=i:t._babylonTransformNodeForSkin=i,n(i)}if(o)if(a){const i=Jk.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);s.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,(i=>{const r=t._babylonTransformNodeForSkin;i.metadata=Zk(r.metadata,i.metadata||{});const n=Jk.Get(`${e}/skin`,this._gltf.skins,t.skin);s.push(this._loadSkinAsync(`/skins/${n.index}`,t,n,(e=>{this._forEachPrimitive(t,(t=>{t.skeleton=e})),this._postSceneLoadActions.push((()=>{if(null!=n.skeleton){const e=Jk.Get(`/skins/${n.index}/skeleton`,this._gltf.nodes,n.skeleton).parent;t.index===e.index?i.parent=r.parent:i.parent=e._babylonTransformNode}else i.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:r,skinnedNode:i})}))})))})))}else{const i=Jk.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);s.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,n))}return this.logClose(),Promise.all(s).then((()=>(this._forEachPrimitive(t,(e=>{e.geometry&&e.geometry.useBoundingInfoFromGeometry?e._updateBoundingInfo():e.refreshBoundingInfo(!0,!0)})),t._babylonTransformNode)))}_loadMeshAsync(e,t,i,r){const s=i.primitives;if(!s||!s.length)throw new Error(`${e}: Primitives are missing`);null==s[0].index&&Jk.Assign(s);const n=new Array;this.logOpen(`${e} ${i.name||""}`);const o=t.name||`node${t.index}`;if(1===s.length){const r=i.primitives[0];n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${r.index}`,o,t,i,r,(e=>{t._babylonTransformNode=e,t._primitiveBabylonMeshes=[e]})))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new Pt(o,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(const r of s)n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${r.index}`,`${o}_primitive${r.index}`,t,i,r,(e=>{e.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(e)})))}return r(t._babylonTransformNode),this.logClose(),Promise.all(n).then((()=>t._babylonTransformNode))}_loadMeshPrimitiveAsync(e,t,i,r,s,n){const o=this._extensionsLoadMeshPrimitiveAsync(e,t,i,r,s,n);if(o)return o;this.logOpen(`${e}`);const a=0===this._disableInstancedMesh&&this._parent.createInstances&&null==i.skin&&!r.primitives[0].targets;let l,h;if(a&&s._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,l=s._instanceData.babylonSourceMesh.createInstance(t),l._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,h=s._instanceData.promise;else{const n=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new Yt(t,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,o.sideOrientation=this._babylonScene.useRightHandedSystem?Vt.CounterClockWiseSideOrientation:Vt.ClockWiseSideOrientation,this._createMorphTargets(e,i,r,s,o),n.push(this._loadVertexDataAsync(e,s,o).then((t=>this._loadMorphTargetsAsync(e,s,o,t).then((()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,t.applyToMesh(o),t._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})))));const c=eU._GetDrawMode(e,s.mode);if(null==s.material){let e=this._defaultBabylonMaterialData[c];e||(e=this._createDefaultMaterial("__GLTFLoader._default",c),this._parent.onMaterialLoadedObservable.notifyObservers(e),this._defaultBabylonMaterialData[c]=e),o.material=e}else if(!this.parent.skipMaterials){const t=Jk.Get(`${e}/material`,this._gltf.materials,s.material);n.push(this._loadMaterialAsync(`/materials/${t.index}`,t,o,c,(e=>{o.material=e})))}h=Promise.all(n),a&&(s._instanceData={babylonSourceMesh:o,promise:h}),l=o}return eU.AddPointerMetadata(l,e),this._parent.onMeshLoadedObservable.notifyObservers(l),n(l),this.logClose(),h.then((()=>l))}_loadVertexDataAsync(e,t,i){const r=this._extensionsLoadVertexDataAsync(e,t,i);if(r)return r;const s=t.attributes;if(!s)throw new Error(`${e}: Attributes are missing`);const n=new Array,o=new yt(i.name,this._babylonScene);if(null==t.indices)i.isUnIndexed=!0;else{const i=Jk.Get(`${e}/indices`,this._gltf.accessors,t.indices);n.push(this._loadIndicesAccessorAsync(`/accessors/${i.index}`,i).then((e=>{o.setIndices(e)})))}const a=(t,r,a)=>{if(null==s[t])return;i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(r)&&i._delayInfo.push(r);const l=Jk.Get(`${e}/attributes/${t}`,this._gltf.accessors,s[t]);n.push(this._loadVertexAccessorAsync(`/accessors/${l.index}`,l,r).then((e=>{if(e.getKind()===st.R.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!i.skeleton&&l.min&&l.max){const e=W.AA.Vector3[0].copyFromFloats(...l.min),t=W.AA.Vector3[1].copyFromFloats(...l.max);if(l.normalized&&5126!==l.componentType){let i=1;switch(l.componentType){case 5120:i=127;break;case 5121:i=255;break;case 5122:i=32767;break;case 5123:i=65535}const r=1/i;e.scaleInPlace(r),t.scaleInPlace(r)}o._boundingInfo=new _t(e,t),o.useBoundingInfoFromGeometry=!0}o.setVerticesBuffer(e,l.count)}))),r==st.R.MatricesIndicesExtraKind&&(i.numBoneInfluencers=8),a&&a(l)};return a("POSITION",st.R.PositionKind),a("NORMAL",st.R.NormalKind),a("TANGENT",st.R.TangentKind),a("TEXCOORD_0",st.R.UVKind),a("TEXCOORD_1",st.R.UV2Kind),a("TEXCOORD_2",st.R.UV3Kind),a("TEXCOORD_3",st.R.UV4Kind),a("TEXCOORD_4",st.R.UV5Kind),a("TEXCOORD_5",st.R.UV6Kind),a("JOINTS_0",st.R.MatricesIndicesKind),a("WEIGHTS_0",st.R.MatricesWeightsKind),a("JOINTS_1",st.R.MatricesIndicesExtraKind),a("WEIGHTS_1",st.R.MatricesWeightsExtraKind),a("COLOR_0",st.R.ColorKind,(e=>{"VEC4"===e.type&&(i.hasVertexAlpha=!0)})),Promise.all(n).then((()=>o))}_createMorphTargets(e,t,i,r,s){if(!r.targets||!this._parent.loadMorphTargets)return;if(null==t._numMorphTargets)t._numMorphTargets=r.targets.length;else if(r.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,s.morphTargetManager=new Gx(this._babylonScene),s.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,s.morphTargetManager.areUpdatesFrozen=!0;for(let e=0;e{n.areUpdatesFrozen=!1}))}_loadMorphTargetVertexDataAsync(e,t,i,r){const s=new Array,n=(r,n,o)=>{if(null==i[r])return;const a=t.getVertexBuffer(n);if(!a)return;const l=Jk.Get(`${e}/${r}`,this._gltf.accessors,i[r]);s.push(this._loadFloatAccessorAsync(`/accessors/${l.index}`,l).then((e=>{o(a,e)})))};return n("POSITION",st.R.PositionKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(t.length,((e,r)=>{i[r]=t[r]+e})),r.setPositions(i)})),n("NORMAL",st.R.NormalKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(i.length,((e,r)=>{i[r]=t[r]+e})),r.setNormals(i)})),n("TANGENT",st.R.TangentKind,((e,t)=>{const i=new Float32Array(t.length/3*4);let s=0;e.forEach(t.length/3*4,((e,r)=>{(r+1)%4!=0&&(i[s]=t[s]+e,s++)})),r.setTangents(i)})),Promise.all(s).then((()=>{}))}static _LoadTransform(e,t){if(null!=e.skin)return;let i=W.Pq.Zero(),r=W.PT.Identity(),s=W.Pq.One();e.matrix?W.uq.FromArray(e.matrix).decompose(s,r,i):(e.translation&&(i=W.Pq.FromArray(e.translation)),e.rotation&&(r=W.PT.FromArray(e.rotation)),e.scale&&(s=W.Pq.FromArray(e.scale))),t.position=i,t.rotationQuaternion=r,t.scaling=s}_loadSkinAsync(e,t,i,r){if(!this._parent.loadSkins)return Promise.resolve();const s=this._extensionsLoadSkinAsync(e,t,i);if(s)return s;if(i._data)return r(i._data.babylonSkeleton),i._data.promise;const n=`skeleton${i.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new Ti(i.name||n,n,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,i,o);const a=this._loadSkinInverseBindMatricesDataAsync(e,i).then((e=>{this._updateBoneMatrices(o,e)}));return i._data={babylonSkeleton:o,promise:a},r(o),a}_loadBones(e,t,i){if(null==t.skeleton||this._parent.alwaysComputeSkeletonRootNode){const i=this._findSkeletonRootNode(`${e}/joints`,t.joints);if(i)if(void 0===t.skeleton)t.skeleton=i.index;else{const r=(e,t)=>{for(;t.parent;t=t.parent)if(t.parent===e)return!0;return!1},s=Jk.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);s===i||r(s,i)||(Z.V.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=i.index)}else Z.V.Warn(`${e}: Failed to find common root`)}const r={};for(const s of t.joints){const n=Jk.Get(`${e}/joints/${s}`,this._gltf.nodes,s);this._loadBone(n,t,i,r)}}_findSkeletonRootNode(e,t){if(0===t.length)return null;const i={};for(const r of t){const t=[];let s=Jk.Get(`${e}/${r}`,this._gltf.nodes,r);for(;-1!==s.index;)t.unshift(s),s=s.parent;i[r]=t}let r=null;for(let e=0;;++e){let s=i[t[0]];if(e>=s.length)return r;const n=s[e];for(let o=1;o=s.length||n!==s[e])return r;r=n}}_loadBone(e,t,i,r){e._isJoint=!0;let s=r[e.index];if(s)return s;let n=null;e.index!==t.skeleton&&(e.parent&&-1!==e.parent.index?n=this._loadBone(e.parent,t,i,r):void 0!==t.skeleton&&Z.V.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));const o=t.joints.indexOf(e.index);return s=new Si.$(e.name||`joint${e.index}`,i,n,this._getNodeMatrix(e),null,null,o),r[e.index]=s,this._postSceneLoadActions.push((()=>{s.linkTransformNode(e._babylonTransformNode)})),s}_loadSkinInverseBindMatricesDataAsync(e,t){if(null==t.inverseBindMatrices)return Promise.resolve(null);const i=Jk.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 e=W.uq.Identity(),r=i._index;t&&-1!==r&&(W.uq.FromArrayToRef(t,16*r,e),e.invertToRef(e));const s=i.getParent();s&&e.multiplyToRef(s.getAbsoluteInverseBindMatrix(),e),i.updateMatrix(e,!1,!1),i._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?W.uq.FromArray(e.matrix):W.uq.Compose(e.scale?W.Pq.FromArray(e.scale):W.Pq.One(),e.rotation?W.PT.FromArray(e.rotation):W.PT.Identity(),e.translation?W.Pq.FromArray(e.translation):W.Pq.Zero())}loadCameraAsync(e,t,i=(()=>{})){const r=this._extensionsLoadCameraAsync(e,t,i);if(r)return r;const s=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const n=new es(t.name||`camera${t.index}`,W.Pq.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 i=t.perspective;if(!i)throw new Error(`${e}: Camera perspective properties are missing`);n.fov=i.yfov,n.minZ=i.znear,n.maxZ=i.zfar||0;break}case"orthographic":if(!t.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);n.mode=rt.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 eU.AddPointerMetadata(n,e),this._parent.onCameraLoadedObservable.notifyObservers(n),i(n),this.logClose(),Promise.all(s).then((()=>n))}_loadAnimationsAsync(){const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let i=0;i{0===e.targetedAnimations.length&&e.dispose()})))}return Promise.all(t).then((()=>{}))}loadAnimationAsync(e,t){return this._extensionsLoadAnimationAsync(e,t)||Promise.resolve().then(i.bind(i,7042)).then((({AnimationGroup:i})=>{this._babylonScene._blockEntityCollection=!!this._assetContainer;const r=new i(t.name||`animation${t.index}`,this._babylonScene);r._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=r;const s=new Array;Jk.Assign(t.channels),Jk.Assign(t.samplers);for(const i of t.channels)s.push(this._loadAnimationChannelAsync(`${e}/channels/${i.index}`,e,t,i,((e,t)=>{e.animations=e.animations||[],e.animations.push(t),r.addTargetedAnimation(t,e)})));return Promise.all(s).then((()=>(r.normalize(0),r)))}))}_loadAnimationChannelAsync(e,t,i,r,s){const n=this._extensionsLoadAnimationChannelAsync(e,t,i,r,s);if(n)return n;if(null==r.target.node)return Promise.resolve();const o=Jk.Get(`${e}/target/node`,this._gltf.nodes,r.target.node),a=r.target.path,l="weights"===a;if(l&&!o._numMorphTargets||!l&&!o._babylonTransformNode)return Promise.resolve();if(!this._parent.loadNodeAnimations&&!l&&!o._isJoint)return Promise.resolve();let h;switch(a){case"translation":h=Yk.translation;break;case"rotation":h=Yk.rotation;break;case"scale":h=Yk.scale;break;case"weights":h=Yk.weights;break;default:throw new Error(`${e}/target/path: Invalid value (${r.target.path})`)}const c={object:o,info:h};return this._loadAnimationChannelFromTargetInfoAsync(e,t,i,r,c,s)}_loadAnimationChannelFromTargetInfoAsync(e,t,i,r,s,n){const o=this.parent.targetFps,a=1/o,l=Jk.Get(`${e}/sampler`,i.samplers,r.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${r.sampler}`,l).then((e=>{let t=0;const l=s.object,h=s.info;for(const s of h){const h=s.getStride(l),c=e.input,u=e.output,d=new Array(c.length);let f=0;switch(e.interpolation){case"STEP":for(let e=0;e0){const e=`${i.name||`animation${i.index}`}_channel${r.index}_${t}`;s.buildAnimations(l,e,o,d,((e,i)=>{++t,n(e,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 r=Jk.Get(`${e}/input`,this._gltf.accessors,t.input),s=Jk.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${r.index}`,r),this._loadFloatAccessorAsync(`/accessors/${s.index}`,s)]).then((([e,t])=>({input:e,interpolation:i,output:t}))),t._data}loadBufferAsync(e,t,i,r){const s=this._extensionsLoadBufferAsync(e,t,i,r);if(s)return s;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((t=>{try{return new Uint8Array(t.buffer,t.byteOffset+i,r)}catch(t){throw new Error(`${e}: ${t.message}`)}}))}loadBufferViewAsync(e,t){const i=this._extensionsLoadBufferViewAsync(e,t);if(i)return i;if(t._data)return t._data;const r=Jk.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${r.index}`,r,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,t,i){if(t._data)return t._data;const r=eU._GetNumComponents(e,t.type),s=r*st.R.GetTypeByteLength(t.componentType),n=r*t.count;if(null==t.bufferView)t._data=Promise.resolve(new i(n));else{const o=Jk.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${o.index}`,o).then((a=>{if(5126!==t.componentType||t.normalized||o.byteStride&&o.byteStride!==s){const e=new i(n);return st.R.ForEach(a,t.byteOffset||0,o.byteStride||s,r,t.componentType,e.length,t.normalized||!1,((t,i)=>{e[i]=t})),e}return eU._GetTypedArray(e,t.componentType,a,t.byteOffset,n)}))}if(t.sparse){const n=t.sparse;t._data=t._data.then((o=>{const a=o,l=Jk.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,n.indices.bufferView),h=Jk.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,n.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${l.index}`,l),this.loadBufferViewAsync(`/bufferViews/${h.index}`,h)]).then((([o,l])=>{const h=eU._GetTypedArray(`${e}/sparse/indices`,n.indices.componentType,o,n.indices.byteOffset,n.count),c=r*n.count;let u;if(5126!==t.componentType||t.normalized){const o=eU._GetTypedArray(`${e}/sparse/values`,t.componentType,l,n.values.byteOffset,c);u=new i(c),st.R.ForEach(o,0,s,r,t.componentType,u.length,t.normalized||!1,((e,t)=>{u[t]=e}))}else u=eU._GetTypedArray(`${e}/sparse/values`,t.componentType,l,n.values.byteOffset,c);let d=0;for(let e=0;eeU._GetTypedArray(e,t.componentType,i,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((e=>new st.h(t,e,!1))),e._babylonBuffer}_loadVertexAccessorAsync(e,t,i){if(t._babylonVertexBuffer?.[i])return t._babylonVertexBuffer[i];t._babylonVertexBuffer||(t._babylonVertexBuffer={});const r=this._babylonScene.getEngine();if(t.sparse||null==t.bufferView)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then((e=>new st.R(r,e,i,!1)));else{const s=Jk.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[i]=this._loadVertexBufferViewAsync(s).then((n=>{const o=eU._GetNumComponents(e,t.type);return new st.R(r,n,i,!1,void 0,s.byteStride,void 0,t.byteOffset,o,t.componentType,t.normalized,!0,void 0,!0)}))}return t._babylonVertexBuffer[i]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const r=new Array;return t&&(t.baseColorFactor?(i.albedoColor=H.v9.FromArray(t.baseColorFactor),i.alpha=t.baseColorFactor[3]):i.albedoColor=H.v9.White(),i.metallic=null==t.metallicFactor?1:t.metallicFactor,i.roughness=null==t.roughnessFactor?1:t.roughnessFactor,t.baseColorTexture&&r.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,t.baseColorTexture,(e=>{e.name=`${i.name} (Base Color)`,i.albedoTexture=e}))),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,t.metallicRoughnessTexture,(e=>{e.name=`${i.name} (Metallic Roughness)`,i.metallicTexture=e}))),i.useMetallnessFromMetallicTextureBlue=!0,i.useRoughnessFromMetallicTextureGreen=!0,i.useRoughnessFromMetallicTextureAlpha=!1)),Promise.all(r).then((()=>{}))}_loadMaterialAsync(e,t,i,r,s=(()=>{})){const n=this._extensionsLoadMaterialAsync(e,t,i,r,s);if(n)return n;t._data=t._data||{};let o=t._data[r];if(!o){this.logOpen(`${e} ${t.name||""}`);const i=this.createMaterial(e,t,r);o={babylonMaterial:i,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,i)},t._data[r]=o,eU.AddPointerMetadata(i,e),this._parent.onMaterialLoadedObservable.notifyObservers(i),this.logClose()}return i&&(o.babylonMeshes.push(i),i.onDisposeObservable.addOnce((()=>{const e=o.babylonMeshes.indexOf(i);-1!==e&&o.babylonMeshes.splice(e,1)}))),s(o.babylonMaterial),o.promise.then((()=>o.babylonMaterial))}_createDefaultMaterial(e,t){this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new zm(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=zm.PBRMATERIAL_OPAQUE,i.metallic=1,i.roughness=1,i}createMaterial(e,t,i){const r=this._extensionsCreateMaterial(e,t,i);if(r)return r;const s=t.name||`material${t.index}`;return this._createDefaultMaterial(s,i)}loadMaterialPropertiesAsync(e,t,i){const r=this._extensionsLoadMaterialPropertiesAsync(e,t,i);if(r)return r;const s=new Array;return s.push(this.loadMaterialBasePropertiesAsync(e,t,i)),t.pbrMetallicRoughness&&s.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,i)),this.loadMaterialAlphaProperties(e,t,i),Promise.all(s).then((()=>{}))}loadMaterialBasePropertiesAsync(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const r=new Array;return i.emissiveColor=t.emissiveFactor?H.v9.FromArray(t.emissiveFactor):new H.v9(0,0,0),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),t.normalTexture&&(t.normalTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/normalTexture`,t.normalTexture,(e=>{e.name=`${i.name} (Normal)`,i.bumpTexture=e}))),i.invertNormalMapX=!this._babylonScene.useRightHandedSystem,i.invertNormalMapY=this._babylonScene.useRightHandedSystem,null!=t.normalTexture.scale&&i.bumpTexture&&(i.bumpTexture.level=t.normalTexture.scale),i.forceIrradianceInFragment=!0),t.occlusionTexture&&(t.occlusionTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,t.occlusionTexture,(e=>{e.name=`${i.name} (Occlusion)`,i.ambientTexture=e}))),i.useAmbientInGrayScale=!0,null!=t.occlusionTexture.strength&&(i.ambientTextureStrength=t.occlusionTexture.strength)),t.emissiveTexture&&r.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,t.emissiveTexture,(e=>{e.name=`${i.name} (Emissive)`,i.emissiveTexture=e}))),Promise.all(r).then((()=>{}))}loadMaterialAlphaProperties(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);switch(t.alphaMode||"OPAQUE"){case"OPAQUE":i.transparencyMode=zm.PBRMATERIAL_OPAQUE,i.alpha=1;break;case"MASK":i.transparencyMode=zm.PBRMATERIAL_ALPHATEST,i.alphaCutOff=null==t.alphaCutoff?.5:t.alphaCutoff,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0);break;case"BLEND":i.transparencyMode=zm.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 r=this._extensionsLoadTextureInfoAsync(e,t,i);if(r)return r;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const s=Jk.Get(`${e}/index`,this._gltf.textures,t.index);s._textureInfo=t;const n=this._loadTextureAsync(`/textures/${t.index}`,s,(r=>{r.coordinatesIndex=t.texCoord||0,eU.AddPointerMetadata(r,e),this._parent.onTextureLoadedObservable.notifyObservers(r),i(r)}));return this.logClose(),n}_loadTextureAsync(e,t,i=(()=>{})){const r=this._extensionsLoadTextureAsync(e,t,i);if(r)return r;this.logOpen(`${e} ${t.name||""}`);const s=null==t.sampler?eU.DefaultSampler:Jk.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),n=Jk.Get(`${e}/source`,this._gltf.images,t.source),o=this._createTextureAsync(e,s,n,i,void 0,!t._textureInfo.nonColorData);return this.logClose(),o}_createTextureAsync(e,t,i,r=(()=>{}),s,n){const o=this._loadSampler(`/samplers/${t.index}`,t),a=new Array,l=new uR;this._babylonScene._blockEntityCollection=!!this._assetContainer;const h={noMipmap:o.noMipMaps,invertY:!1,samplingMode:o.samplingMode,onLoad:()=>{this._disposed||l.resolve()},onError:(t,i)=>{this._disposed||l.reject(new Error(`${e}: ${i&&i.message?i.message:t||"Failed to load texture"}`))},mimeType:i.mimeType,loaderOptions:s,useSRGBBuffer:!!n&&this._parent.useSRGBBuffers},c=new vi.g(null,this._babylonScene,h);return c._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,a.push(l.promise),a.push(this.loadImageAsync(`/images/${i.index}`,i).then((e=>{const t=i.uri||`${this._fileName}#image${i.index}`,r=`data:${this._uniqueRootUrl}${t}`;c.updateURL(r,e);const s=c.getInternalTexture();s&&(s.label=i.name)}))),c.wrapU=o.wrapU,c.wrapV=o.wrapV,r(c),this._parent.useGltfTextureNames&&(c.name=i.name||i.uri||`image${i.index}`),Promise.all(a).then((()=>c))}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:eU._GetTextureSamplingMode(e,t),wrapU:eU._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:eU._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=Jk.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 r=this._extensionsLoadUriAsync(e,t,i);if(r)return r;if(!eU._ValidateUri(i))throw new Error(`${e}: '${i}' is invalid`);if((0,$m.f2)(i)){const t=new Uint8Array((0,$m.rz)(i));return this.log(`${e}: Decoded ${i.substring(0,64)}... (${t.length} bytes)`),Promise.resolve(t)}return this.log(`${e}: Loading ${i}`),this._parent.preprocessUrlAsync(this._rootUrl+i).then((t=>new Promise(((r,s)=>{this._parent._loadFile(this._babylonScene,t,(t=>{this._disposed||(this.log(`${e}: Loaded ${i} (${t.byteLength} bytes)`),r(new Uint8Array(t)))}),!0,(t=>{s(new $m.hX(`${e}: Failed to load '${i}'${t?": "+t.status+" "+t.statusText:""}`,t))}))}))))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};const i=e._internalMetadata=e._internalMetadata||{},r=i.gltf=i.gltf||{};(r.pointers=r.pointers||[]).push(t)}static _GetTextureWrapMode(e,t){switch(t=null==t?10497:t){case 33071:return vi.g.CLAMP_ADDRESSMODE;case 33648:return vi.g.MIRROR_ADDRESSMODE;case 10497:return vi.g.WRAP_ADDRESSMODE;default:return Z.V.Warn(`${e}: Invalid value (${t})`),vi.g.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,t){const i=null==t.magFilter?9729:t.magFilter,r=null==t.minFilter?9987:t.minFilter;if(9729===i)switch(r){case 9728:return vi.g.LINEAR_NEAREST;case 9729:return vi.g.LINEAR_LINEAR;case 9984:return vi.g.LINEAR_NEAREST_MIPNEAREST;case 9985:return vi.g.LINEAR_LINEAR_MIPNEAREST;case 9986:return vi.g.LINEAR_NEAREST_MIPLINEAR;case 9987:return vi.g.LINEAR_LINEAR_MIPLINEAR;default:return Z.V.Warn(`${e}/minFilter: Invalid value (${r})`),vi.g.LINEAR_LINEAR_MIPLINEAR}else switch(9728!==i&&Z.V.Warn(`${e}/magFilter: Invalid value (${i})`),r){case 9728:return vi.g.NEAREST_NEAREST;case 9729:return vi.g.NEAREST_LINEAR;case 9984:return vi.g.NEAREST_NEAREST_MIPNEAREST;case 9985:return vi.g.NEAREST_LINEAR_MIPNEAREST;case 9986:return vi.g.NEAREST_NEAREST_MIPLINEAR;case 9987:return vi.g.NEAREST_LINEAR_MIPLINEAR;default:return Z.V.Warn(`${e}/minFilter: Invalid value (${r})`),vi.g.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,r,s){const n=i.buffer;r=i.byteOffset+(r||0);const o=eU._GetTypedArrayConstructor(`${e}/componentType`,t),a=st.R.GetTypeByteLength(t);return r%a!=0?(Z.V.Warn(`${e}: Copying buffer as byte offset (${r}) is not a multiple of component type byte length (${a})`),new o(n.slice(r,r+s*a),0)):new o(n,r,s)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return Ue.S0.IsBase64(e)||-1===e.indexOf("..")}static _GetDrawMode(e,t){switch(null==t&&(t=4),t){case 0:return Vt.PointListDrawMode;case 1:return Vt.LineListDrawMode;case 2:return Vt.LineLoopDrawMode;case 3:return Vt.LineStripDrawMode;case 4:return Vt.TriangleFillMode;case 5:return Vt.TriangleStripDrawMode;case 6:return Vt.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 r=t._data[i];for(const t of r.babylonMeshes){t.computeWorldMatrix(!0);const i=r.babylonMaterial;e.push(i.forceCompilationAsync(t)),e.push(i.forceCompilationAsync(t,{useInstances:!0})),this._parent.useClipPlane&&(e.push(i.forceCompilationAsync(t,{clipPlane:!0})),e.push(i.forceCompilationAsync(t,{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 t=i.getShadowGenerator();t&&e.push(t.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 r of this._extensions)if(r.enabled){const s=`${r.name}.${t}`,n=e;n._activeLoaderExtensionFunctions=n._activeLoaderExtensionFunctions||{};const o=n._activeLoaderExtensionFunctions;if(!o[s]){o[s]=!0;try{const e=i(r);if(e)return e}finally{delete o[s]}}}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",(r=>r.loadNodeAsync&&r.loadNodeAsync(e,t,i)))}_extensionsLoadCameraAsync(e,t,i){return this._applyExtensions(t,"loadCamera",(r=>r.loadCameraAsync&&r.loadCameraAsync(e,t,i)))}_extensionsLoadVertexDataAsync(e,t,i){return this._applyExtensions(t,"loadVertexData",(r=>r._loadVertexDataAsync&&r._loadVertexDataAsync(e,t,i)))}_extensionsLoadMeshPrimitiveAsync(e,t,i,r,s,n){return this._applyExtensions(s,"loadMeshPrimitive",(o=>o._loadMeshPrimitiveAsync&&o._loadMeshPrimitiveAsync(e,t,i,r,s,n)))}_extensionsLoadMaterialAsync(e,t,i,r,s){return this._applyExtensions(t,"loadMaterial",(n=>n._loadMaterialAsync&&n._loadMaterialAsync(e,t,i,r,s)))}_extensionsCreateMaterial(e,t,i){return this._applyExtensions(t,"createMaterial",(r=>r.createMaterial&&r.createMaterial(e,t,i)))}_extensionsLoadMaterialPropertiesAsync(e,t,i){return this._applyExtensions(t,"loadMaterialProperties",(r=>r.loadMaterialPropertiesAsync&&r.loadMaterialPropertiesAsync(e,t,i)))}_extensionsLoadTextureInfoAsync(e,t,i){return this._applyExtensions(t,"loadTextureInfo",(r=>r.loadTextureInfoAsync&&r.loadTextureInfoAsync(e,t,i)))}_extensionsLoadTextureAsync(e,t,i){return this._applyExtensions(t,"loadTexture",(r=>r._loadTextureAsync&&r._loadTextureAsync(e,t,i)))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",(i=>i.loadAnimationAsync&&i.loadAnimationAsync(e,t)))}_extensionsLoadAnimationChannelAsync(e,t,i,r,s){return this._applyExtensions(i,"loadAnimationChannel",(n=>n._loadAnimationChannelAsync&&n._loadAnimationChannelAsync(e,t,i,r,s)))}_extensionsLoadSkinAsync(e,t,i){return this._applyExtensions(i,"loadSkin",(r=>r._loadSkinAsync&&r._loadSkinAsync(e,t,i)))}_extensionsLoadUriAsync(e,t,i){return this._applyExtensions(t,"loadUri",(r=>r._loadUriAsync&&r._loadUriAsync(e,t,i)))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",(i=>i.loadBufferViewAsync&&i.loadBufferViewAsync(e,t)))}_extensionsLoadBufferAsync(e,t,i,r){return this._applyExtensions(t,"loadBuffer",(s=>s.loadBufferAsync&&s.loadBufferAsync(e,t,i,r)))}static LoadExtensionAsync(e,t,i,r){if(!t.extensions)return null;const s=t.extensions[i];return s?r(`${e}/extensions/${i}`,s):null}static LoadExtraAsync(e,t,i,r){if(!t.extras)return null;const s=t.extras[i];return s?r(`${e}/extras/${i}`,s):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&-1!==this._gltf.extensionsUsed.indexOf(e)}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)}}eU.DefaultSampler={index:-1},xk._CreateGLTF2Loader=e=>new eU(e);const tU="EXT_lights_image_based";class iU{constructor(e){this.name=tU,this._loader=e,this.enabled=this._loader.isExtensionUsed(tU)}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 eU.LoadExtensionAsync(e,t,this.name,((i,r)=>{this._loader._allMaterialsDirtyRequired=!0;const s=new Array;s.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${i}`);const n=Jk.Get(`${i}/light`,this._lights,r.light);return s.push(this._loadLightAsync(`/extensions/${this.name}/lights/${r.light}`,n).then((e=>{this._loader.babylonScene.environmentTexture=e}))),this._loader.logClose(),Promise.all(s).then((()=>{}))}))}_loadLightAsync(e,t){if(!t._loaded){const i=new Array;this._loader.logOpen(`${e}`);const r=new Array(t.specularImages.length);for(let s=0;s{r[s][t]=e}))),this._loader.logClose()}}this._loader.logClose(),t._loaded=Promise.all(i).then((()=>{const i=new $b(this._loader.babylonScene,null,t.specularImageSize);if(i.name=t.name||"environment",t._babylonTexture=i,null!=t.intensity&&(i.level=t.intensity),t.rotation){let e=W.PT.FromArray(t.rotation);this._loader.babylonScene.useRightHandedSystem||(e=W.PT.Inverse(e)),W.uq.FromQuaternionToRef(e,i.getReflectionTextureMatrix())}if(!t.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const s=Ks.O.FromArray(t.irradianceCoefficients);s.scaleInPlace(t.intensity),s.convertIrradianceToLambertianRadiance();const n=Ks.Q.FromHarmonics(s),o=(r.length-1)/Math.log2(t.specularImageSize);return i.updateRGBDAsync(r,n,o)}))}return t._loaded.then((()=>t._babylonTexture))}}Qk(tU),$k(tU,!0,(e=>new iU(e)));const rU="EXT_mesh_gpu_instancing";class sU{constructor(e){this.name=rU,this._loader=e,this.enabled=this._loader.isExtensionUsed(rU)}dispose(){this._loader=null}loadNodeAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((e,r)=>{this._loader._disableInstancedMesh++;const s=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,i);if(this._loader._disableInstancedMesh--,!t._primitiveBabylonMeshes)return s;const n=new Array;let o=0;const a=t=>{if(null==r.attributes[t])return void n.push(Promise.resolve(null));const i=Jk.Get(`${e}/attributes/${t}`,this._loader.gltf.accessors,r.attributes[t]);if(n.push(this._loader._loadFloatAccessorAsync(`/accessors/${i.bufferView}`,i)),0===o)o=i.count;else if(o!==i.count)throw new Error(`${e}/attributes: Instance buffer accessors do not have the same count.`)};return a("TRANSLATION"),a("ROTATION"),a("SCALE"),s.then((e=>Promise.all(n).then((([i,r,s])=>{const n=new Float32Array(16*o);W.AA.Vector3[0].copyFromFloats(0,0,0),W.AA.Quaternion[0].copyFromFloats(0,0,0,1),W.AA.Vector3[1].copyFromFloats(1,1,1);for(let e=0;enew sU(e)));const nU="EXT_meshopt_compression";class oU{constructor(e){this.name=nU,this.enabled=e.isExtensionUsed(nU),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,t){return eU.LoadExtensionAsync(e,t,this.name,((i,r)=>{const s=t;if(s._meshOptData)return s._meshOptData;const n=Jk.Get(`${e}/buffer`,this._loader.gltf.buffers,r.buffer);return s._meshOptData=this._loader.loadBufferAsync(`/buffers/${n.index}`,n,r.byteOffset||0,r.byteLength).then((e=>Jy.Default.decodeGltfBufferAsync(e,r.count,r.byteStride,r.mode,r.filter))),s._meshOptData}))}}Qk(nU),$k(nU,!0,(e=>new oU(e)));const aU="EXT_texture_webp";class lU{constructor(e){this.name=aU,this._loader=e,this.enabled=e.isExtensionUsed(aU)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=null==t.sampler?eU.DefaultSampler:Jk.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=Jk.Get(`${r}/source`,this._loader.gltf.images,s.source);return this._loader._createTextureAsync(e,n,o,(e=>{i(e)}),void 0,!t._textureInfo.nonColorData)}))}}Qk(aU),$k(aU,!0,(e=>new lU(e)));const hU="EXT_texture_avif";class cU{constructor(e){this.name=hU,this._loader=e,this.enabled=e.isExtensionUsed(hU)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=null==t.sampler?eU.DefaultSampler:Jk.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=Jk.Get(`${r}/source`,this._loader.gltf.images,s.source);return this._loader._createTextureAsync(e,n,o,(e=>{i(e)}),void 0,!t._textureInfo.nonColorData)}))}}Qk(hU),$k(hU,!0,(e=>new cU(e)));const uU="KHR_draco_mesh_compression";class dU{constructor(e){this.name=uU,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=Zy.DecoderAvailable&&this._loader.isExtensionUsed(uU)}dispose(){delete this.dracoCompression,this._loader=null}_loadVertexDataAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{if(null!=t.mode&&4!==t.mode&&5!==t.mode)throw new Error(`${e}: Unsupported mode ${t.mode}`);const n={},o={},a=(e,r)=>{const a=s.attributes[e];if(null!=a&&(i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(r)&&i._delayInfo.push(r),n[r]=a,this.useNormalizedFlagFromAccessor)){const i=Jk.TryGet(this._loader.gltf.accessors,t.attributes[e]);i&&(o[r]=i.normalized||!1)}};a("POSITION",st.R.PositionKind),a("NORMAL",st.R.NormalKind),a("TANGENT",st.R.TangentKind),a("TEXCOORD_0",st.R.UVKind),a("TEXCOORD_1",st.R.UV2Kind),a("TEXCOORD_2",st.R.UV3Kind),a("TEXCOORD_3",st.R.UV4Kind),a("TEXCOORD_4",st.R.UV5Kind),a("TEXCOORD_5",st.R.UV6Kind),a("JOINTS_0",st.R.MatricesIndicesKind),a("WEIGHTS_0",st.R.MatricesWeightsKind),a("COLOR_0",st.R.ColorKind);const l=Jk.Get(r,this._loader.gltf.bufferViews,s.bufferView);return l._dracoBabylonGeometry||(l._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${l.index}`,l).then((t=>(this.dracoCompression||Zy.Default)._decodeMeshToGeometryForGltfAsync(i.name,this._loader.babylonScene,t,n,o).catch((t=>{throw new Error(`${e}: ${t.message}`)}))))),l._dracoBabylonGeometry}))}}Qk(uU),$k(uU,!0,(e=>new dU(e)));const fU="KHR_lights_punctual";class pU{constructor(e){this.name=fU,this._loader=e,this.enabled=this._loader.isExtensionUsed(fU)}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,Jk.Assign(this._lights)}}loadNodeAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>(this._loader._allMaterialsDirtyRequired=!0,this._loader.loadNodeAsync(e,t,(e=>{let t;const n=Jk.Get(r,this._lights,s.light),o=n.name||e.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,n.type){case"directional":{const e=new hm(o,W.Pq.Backward(),this._loader.babylonScene);e.position.setAll(0),t=e;break}case"point":t=new wx(o,W.Pq.Zero(),this._loader.babylonScene);break;case"spot":{const e=new dm(o,W.Pq.Zero(),W.Pq.Backward(),0,1,this._loader.babylonScene);e.angle=2*(n.spot&&n.spot.outerConeAngle||Math.PI/4),e.innerAngle=2*(n.spot&&n.spot.innerConeAngle||0),t=e;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${r}: Invalid light type (${n.type})`)}t._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,n._babylonLight=t,t.falloffType=$t.FALLOFF_GLTF,t.diffuse=n.color?H.v9.FromArray(n.color):H.v9.White(),t.intensity=null==n.intensity?1:n.intensity,t.range=null==n.range?Number.MAX_VALUE:n.range,t.parent=e,this._loader._babylonLights.push(t),eU.AddPointerMetadata(t,r),i(e)})))))}}Qk(fU),$k(fU,!0,(e=>new pU(e)));const _U="KHR_materials_pbrSpecularGlossiness";class mU{constructor(e){this.name=_U,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(_U)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loadSpecularGlossinessPropertiesAsync(r,s,i)),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(n).then((()=>{}))}))}_loadSpecularGlossinessPropertiesAsync(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const r=new Array;return i.metallic=null,i.roughness=null,t.diffuseFactor?(i.albedoColor=H.v9.FromArray(t.diffuseFactor),i.alpha=t.diffuseFactor[3]):i.albedoColor=H.v9.White(),i.reflectivityColor=t.specularFactor?H.v9.FromArray(t.specularFactor):H.v9.White(),i.microSurface=null==t.glossinessFactor?1:t.glossinessFactor,t.diffuseTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,t.diffuseTexture,(e=>{e.name=`${i.name} (Diffuse)`,i.albedoTexture=e}))),t.specularGlossinessTexture&&(r.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,t.specularGlossinessTexture,(e=>{e.name=`${i.name} (Specular Glossiness)`,i.reflectivityTexture=e,i.reflectivityTexture.hasAlpha=!0}))),i.useMicroSurfaceFromReflectivityMapAlpha=!0),Promise.all(r).then((()=>{}))}}Qk(_U),$k(_U,!0,(e=>new mU(e)));const gU="KHR_materials_unlit";class vU{constructor(e){this.name=gU,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(gU)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,(()=>this._loadUnlitPropertiesAsync(e,t,i)))}_loadUnlitPropertiesAsync(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const r=new Array;i.unlit=!0;const s=t.pbrMetallicRoughness;return s&&(s.baseColorFactor?(i.albedoColor=H.v9.FromArray(s.baseColorFactor),i.alpha=s.baseColorFactor[3]):i.albedoColor=H.v9.White(),s.baseColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,s.baseColorTexture,(e=>{e.name=`${i.name} (Base Color)`,i.albedoTexture=e})))),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(r).then((()=>{}))}}Qk(gU),$k(gU,!0,(e=>new vU(e)));const xU="KHR_materials_clearcoat";class bU{constructor(e){this.name=xU,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(xU)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadClearCoatPropertiesAsync(r,s,i)),Promise.all(n).then((()=>{}))}))}_loadClearCoatPropertiesAsync(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const r=new Array;return i.clearCoat.isEnabled=!0,i.clearCoat.useRoughnessFromMainTexture=!1,i.clearCoat.remapF0OnInterfaceChange=!1,null!=t.clearcoatFactor?i.clearCoat.intensity=t.clearcoatFactor:i.clearCoat.intensity=0,t.clearcoatTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,(e=>{e.name=`${i.name} (ClearCoat)`,i.clearCoat.texture=e}))),null!=t.clearcoatRoughnessFactor?i.clearCoat.roughness=t.clearcoatRoughnessFactor:i.clearCoat.roughness=0,t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatRoughnessTexture`,t.clearcoatRoughnessTexture,(e=>{e.name=`${i.name} (ClearCoat Roughness)`,i.clearCoat.textureRoughness=e})))),t.clearcoatNormalTexture&&(t.clearcoatNormalTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatNormalTexture`,t.clearcoatNormalTexture,(e=>{e.name=`${i.name} (ClearCoat Normal)`,i.clearCoat.bumpTexture=e}))),i.invertNormalMapX=!i.getScene().useRightHandedSystem,i.invertNormalMapY=i.getScene().useRightHandedSystem,null!=t.clearcoatNormalTexture.scale&&(i.clearCoat.bumpTexture.level=t.clearcoatNormalTexture.scale)),Promise.all(r).then((()=>{}))}}Qk(xU),$k(xU,!0,(e=>new bU(e)));const SU="KHR_materials_iridescence";class TU{constructor(e){this.name=SU,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(SU)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIridescencePropertiesAsync(r,s,i)),Promise.all(n).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const r=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&&r.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,(e=>{e.name=`${i.name} (Iridescence)`,i.iridescence.texture=e}))),t.iridescenceThicknessTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,(e=>{e.name=`${i.name} (Iridescence Thickness)`,i.iridescence.thicknessTexture=e}))),Promise.all(r).then((()=>{}))}}Qk(SU),$k(SU,!0,(e=>new TU(e)));const CU="KHR_materials_anisotropy";class yU{constructor(e){this.name=CU,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(CU)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIridescencePropertiesAsync(r,s,i)),Promise.all(n).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const r=new Array;return i.anisotropy.isEnabled=!0,i.anisotropy.intensity=t.anisotropyStrength??0,i.anisotropy.angle=t.anisotropyRotation??0,t.anisotropyTexture&&(t.anisotropyTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,(e=>{e.name=`${i.name} (Anisotropy Intensity)`,i.anisotropy.texture=e})))),Promise.all(r).then((()=>{}))}}Qk(CU),$k(CU,!0,(e=>new yU(e)));const EU="KHR_materials_emissive_strength";class PU{constructor(e){this.name=EU,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(EU)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>this._loader.loadMaterialPropertiesAsync(e,t,i).then((()=>{this._loadEmissiveProperties(r,s,i)}))))}_loadEmissiveProperties(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);void 0!==t.emissiveStrength&&(i.emissiveIntensity=t.emissiveStrength)}}Qk(EU),$k(EU,!0,(e=>new PU(e)));const AU="KHR_materials_sheen";class RU{constructor(e){this.name=AU,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(AU)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadSheenPropertiesAsync(r,s,i)),Promise.all(n).then((()=>{}))}))}_loadSheenPropertiesAsync(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const r=new Array;return i.sheen.isEnabled=!0,i.sheen.intensity=1,null!=t.sheenColorFactor?i.sheen.color=H.v9.FromArray(t.sheenColorFactor):i.sheen.color=H.v9.Black(),t.sheenColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/sheenColorTexture`,t.sheenColorTexture,(e=>{e.name=`${i.name} (Sheen Color)`,i.sheen.texture=e}))),void 0!==t.sheenRoughnessFactor?i.sheen.roughness=t.sheenRoughnessFactor:i.sheen.roughness=0,t.sheenRoughnessTexture&&(t.sheenRoughnessTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/sheenRoughnessTexture`,t.sheenRoughnessTexture,(e=>{e.name=`${i.name} (Sheen Roughness)`,i.sheen.textureRoughness=e})))),i.sheen.albedoScaling=!0,i.sheen.useRoughnessFromMainTexture=!1,Promise.all(r).then((()=>{}))}}Qk(AU),$k(AU,!0,(e=>new RU(e)));const IU="KHR_materials_specular";class MU{constructor(e){this.name=IU,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(IU)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadSpecularPropertiesAsync(r,s,i)),Promise.all(n).then((()=>{}))}))}_loadSpecularPropertiesAsync(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const r=new Array;return void 0!==t.specularFactor&&(i.metallicF0Factor=t.specularFactor),void 0!==t.specularColorFactor&&(i.metallicReflectanceColor=H.v9.FromArray(t.specularColorFactor)),t.specularTexture&&(t.specularTexture.nonColorData=!0,r.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,t.specularTexture,(e=>{e.name=`${i.name} (Specular)`,i.metallicReflectanceTexture=e,i.useOnlyMetallicFromMetallicReflectanceTexture=!0})))),t.specularColorTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,t.specularColorTexture,(e=>{e.name=`${i.name} (Specular Color)`,i.reflectanceTexture=e}))),Promise.all(r).then((()=>{}))}}Qk(IU),$k(IU,!0,(e=>new MU(e)));const OU="KHR_materials_ior";class DU{constructor(e){this.name=OU,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(OU)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIorPropertiesAsync(r,s,i)),Promise.all(n).then((()=>{}))}))}_loadIorPropertiesAsync(e,t,i){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);return void 0!==t.ior?i.indexOfRefraction=t.ior:i.indexOfRefraction=DU._DEFAULT_IOR,Promise.resolve()}}DU._DEFAULT_IOR=1.5,Qk(OU),$k(OU,!0,(e=>new DU(e)));const wU="KHR_materials_variants";class NU{constructor(e){this.name=wU,this._loader=e,this.enabled=this._loader.isExtensionUsed(wU)}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return NU.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 ${wU} extension`);const r=e=>{const t=i.variants[e];if(t)for(const e of t)e.mesh.material=e.material};if(t instanceof Array)for(const e of t)r(e);else r(t);i.lastSelected=t}selectVariant(e,t){NU.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 ${wU} extension`);for(const e of t.original)e.mesh.material=e.material;t.lastSelected=null}reset(e){NU.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 ${wU} extension`);return t.lastSelected}getLastSelectedVariant(e){return NU.GetLastSelectedVariant(e)}static _GetExtensionMetadata(e){return e?._internalMetadata?.gltf?.[wU]||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,r,s,n){return eU.LoadExtensionAsync(e,s,this.name,((o,a)=>{const l=new Array;return l.push(this._loader._loadMeshPrimitiveAsync(e,t,i,r,s,(t=>{if(n(t),t instanceof Yt){const i=eU._GetDrawMode(e,s.mode),r=this._loader.rootBabylonMesh,n=r?r._internalMetadata=r._internalMetadata||{}:{},h=n.gltf=n.gltf||{},c=h[wU]=h[wU]||{lastSelected:null,original:[],variants:{}};c.original.push({mesh:t,material:t.material});for(let e=0;e{for(let i=0;i{const i=e;let s=null,n=i;do{if(n=n.parent,!n)return;s=NU._GetExtensionMetadata(n)}while(null===s);if(r&&s===NU._GetExtensionMetadata(r)){n._internalMetadata={};for(const e in r._internalMetadata)n._internalMetadata[e]=r._internalMetadata[e];n._internalMetadata.gltf=[];for(const e in r._internalMetadata.gltf)n._internalMetadata.gltf[e]=r._internalMetadata.gltf[e];n._internalMetadata.gltf[wU]={lastSelected:null,original:[],variants:{}};for(const e of s.original)n._internalMetadata.gltf[wU].original.push({mesh:e.mesh,material:e.material});for(const e in s.variants)if(Object.prototype.hasOwnProperty.call(s.variants,e)){n._internalMetadata.gltf[wU].variants[e]=[];for(const t of s.variants[e])n._internalMetadata.gltf[wU].variants[e].push({mesh:t.mesh,material:t.material})}s=n._internalMetadata.gltf[wU]}for(const e of s.original)e.mesh===t&&(e.mesh=i);for(const e of s.variants[o.name])e.mesh===t&&(e.mesh=i)}))}})))}}}))),Promise.all(l).then((([e])=>e))}))}}Qk(wU),$k(wU,!0,(e=>new NU(e)));class FU{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:Il.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,t){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._options={...FU._GetDefaultOptions(),...e},this._scene=t,this._scene._transmissionHelper=this,this.onErrorObservable=new z.cP,this._scene.onDisposeObservable.addOnce((()=>{this.dispose()})),this._parseScene(),this._setupRenderTargets()}updateOptions(e){if(!Object.keys(e).filter((t=>this._options[t]!==e[t])).length)return;const t={...this._options,...e},i=this._options;this._options=t,t.renderSize===i.renderSize&&t.renderTargetTextureType===i.renderTargetTextureType&&t.generateMipmaps===i.generateMipmaps&&this._opaqueRenderTarget?(this._opaqueRenderTarget.samples=t.samples,this._opaqueRenderTarget.lodGenerationScale=t.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=t.lodGenerationOffset):this._setupRenderTargets()}getOpaqueTarget(){return this._opaqueRenderTarget}_shouldRenderAsTransmission(e){return!!e&&!!(e instanceof zm&&e.subSurface.isRefractionEnabled)}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),Ue.S0.SetImmediate((()=>{this._shouldRenderAsTransmission(e.material)?(e.material.refractionTexture=this._opaqueRenderTarget,-1===this._transparentMeshesCache.indexOf(e)&&this._transparentMeshesCache.push(e)):-1===this._opaqueMeshesCache.indexOf(e)&&this._opaqueMeshesCache.push(e)}))}_removeMesh(e){e.onMaterialChangedObservable.remove(this._materialObservers[e.uniqueId]),delete this._materialObservers[e.uniqueId];let t=this._transparentMeshesCache.indexOf(e);-1!==t&&this._transparentMeshesCache.splice(t,1),t=this._opaqueMeshesCache.indexOf(e),-1!==t&&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 zm&&(e.material.subSurface.refractionTexture=this._opaqueRenderTarget),-1!==i?(this._opaqueMeshesCache.splice(i,1),this._transparentMeshesCache.push(e)):-1===t&&this._transparentMeshesCache.push(e)):-1!==t?(this._transparentMeshesCache.splice(t,1),this._opaqueMeshesCache.push(e)):-1===i&&this._opaqueMeshesCache.push(e)}_isRenderTargetValid(){return null!==this._opaqueRenderTarget?.getInternalTexture()}_setupRenderTargets(){let e,t;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new ln.$("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=this._options.clearColor?.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,this._opaqueRenderTarget.onBeforeBindObservable.add((i=>{t=this._scene.environmentIntensity,this._scene.environmentIntensity=1,e=this._scene.imageProcessingConfiguration.applyByPostProcess,this._options.clearColor?i.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(i.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((e=>{this._shouldRenderAsTransmission(e.material)&&(e.material.refractionTexture=this._opaqueRenderTarget)}))}dispose(){this._scene._transmissionHelper=void 0,this._opaqueRenderTarget&&(this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=null),this._transparentMeshesCache=[],this._opaqueMeshesCache=[]}}const LU="KHR_materials_transmission";class BU{constructor(e){this.name=LU,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(LU),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadTransparentPropertiesAsync(r,t,i,s)),Promise.all(n).then((()=>{}))}))}_loadTransparentPropertiesAsync(e,t,i,r){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const s=i;if(s.subSurface.isRefractionEnabled=!0,s.subSurface.volumeIndexOfRefraction=1,s.subSurface.useAlbedoToTintRefraction=!0,void 0===r.transmissionFactor)return s.subSurface.refractionIntensity=0,s.subSurface.isRefractionEnabled=!1,Promise.resolve();{s.subSurface.refractionIntensity=r.transmissionFactor;const e=s.getScene();s.subSurface.refractionIntensity&&!e._transmissionHelper?new FU({},s.getScene()):s.subSurface.refractionIntensity&&!e._transmissionHelper?._isRenderTargetValid()&&e._transmissionHelper?._setupRenderTargets()}return s.subSurface.minimumThickness=0,s.subSurface.maximumThickness=0,r.transmissionTexture?(r.transmissionTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,r.transmissionTexture,void 0).then((e=>{e.name=`${i.name} (Transmission)`,s.subSurface.refractionIntensityTexture=e,s.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}Qk(LU),$k(LU,!0,(e=>new BU(e)));const VU="KHR_materials_diffuse_transmission";class kU{constructor(e){this.name=VU,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(VU),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadTranslucentPropertiesAsync(r,t,i,s)),Promise.all(n).then((()=>{}))}))}_loadTranslucentPropertiesAsync(e,t,i,r){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);const s=i;if(s.subSurface.isTranslucencyEnabled=!0,s.subSurface.volumeIndexOfRefraction=1,s.subSurface.minimumThickness=0,s.subSurface.maximumThickness=0,s.subSurface.useAlbedoToTintTranslucency=!1,void 0===r.diffuseTransmissionFactor)return s.subSurface.translucencyIntensity=0,s.subSurface.isTranslucencyEnabled=!1,Promise.resolve();s.subSurface.translucencyIntensity=r.diffuseTransmissionFactor;const n=new Array;return s.subSurface.useGltfStyleTextures=!0,r.diffuseTransmissionTexture&&(r.diffuseTransmissionTexture.nonColorData=!0,n.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionTexture`,r.diffuseTransmissionTexture).then((e=>{e.name=`${i.name} (Diffuse Transmission)`,s.subSurface.translucencyIntensityTexture=e})))),void 0!==r.diffuseTransmissionColorFactor?s.subSurface.translucencyColor=H.v9.FromArray(r.diffuseTransmissionColorFactor):s.subSurface.translucencyColor=H.v9.White(),r.diffuseTransmissionColorTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionColorTexture`,r.diffuseTransmissionColorTexture).then((e=>{e.name=`${i.name} (Diffuse Transmission Color)`,s.subSurface.translucencyColorTexture=e}))),Promise.all(n).then((()=>{}))}}Qk(VU),$k(VU,!0,(e=>new kU(e)));const UU="KHR_materials_volume";class GU{constructor(e){this.name=UU,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(UU),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadVolumePropertiesAsync(r,t,i,s)),Promise.all(n).then((()=>{}))}))}_loadVolumePropertiesAsync(e,t,i,r){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);if(!i.subSurface.isRefractionEnabled&&!i.subSurface.isTranslucencyEnabled||!r.thicknessFactor)return Promise.resolve();i.subSurface.volumeIndexOfRefraction=i.indexOfRefraction;const s=void 0!==r.attenuationDistance?r.attenuationDistance:Number.MAX_VALUE;return i.subSurface.tintColorAtDistance=s,void 0!==r.attenuationColor&&3==r.attenuationColor.length&&i.subSurface.tintColor.copyFromFloats(r.attenuationColor[0],r.attenuationColor[1],r.attenuationColor[2]),i.subSurface.minimumThickness=0,i.subSurface.maximumThickness=r.thicknessFactor,i.subSurface.useThicknessAsDepth=!0,r.thicknessTexture?(r.thicknessTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,r.thicknessTexture).then((e=>{e.name=`${i.name} (Thickness)`,i.subSurface.thicknessTexture=e,i.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}Qk(UU),$k(UU,!0,(e=>new GU(e)));const zU="KHR_materials_dispersion";class WU{constructor(e){this.name=zU,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(zU)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadDispersionPropertiesAsync(r,t,i,s)),Promise.all(n).then((()=>{}))}))}_loadDispersionPropertiesAsync(e,t,i,r){if(!(i instanceof zm))throw new Error(`${e}: Material type not supported`);return i.subSurface.isRefractionEnabled&&r.dispersion?(i.subSurface.isDispersionEnabled=!0,i.subSurface.dispersion=r.dispersion,Promise.resolve()):Promise.resolve()}}Qk(zU),$k(zU,!0,(e=>new WU(e)));const HU="KHR_mesh_quantization";class XU{constructor(e){this.name=HU,this.enabled=e.isExtensionUsed(HU)}dispose(){}}Qk(HU),$k(HU,!0,(e=>new XU(e)));const qU="KHR_texture_basisu";class YU{constructor(e){this.name=qU,this._loader=e,this.enabled=e.isExtensionUsed(qU)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>{const n=null==t.sampler?eU.DefaultSampler:Jk.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=Jk.Get(`${r}/source`,this._loader.gltf.images,s.source);return this._loader._createTextureAsync(e,n,o,(e=>{i(e)}),t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)}))}}Qk(qU),$k(qU,!0,(e=>new YU(e)));const KU="KHR_texture_transform";class jU{constructor(e){this.name=KU,this._loader=e,this.enabled=this._loader.isExtensionUsed(KU)}dispose(){this._loader=null}loadTextureInfoAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((r,s)=>this._loader.loadTextureInfoAsync(e,t,(e=>{if(!(e instanceof vi.g))throw new Error(`${r}: Texture type not supported`);s.offset&&(e.uOffset=s.offset[0],e.vOffset=s.offset[1]),e.uRotationCenter=0,e.vRotationCenter=0,s.rotation&&(e.wAng=-s.rotation),s.scale&&(e.uScale=s.scale[0],e.vScale=s.scale[1]),null!=s.texCoord&&(e.coordinatesIndex=s.texCoord),i(e)}))))}}Qk(KU),$k(KU,!0,(e=>new jU(e)));const $U="KHR_xmp_json_ld";class QU{constructor(e){this.name=$U,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed($U)}dispose(){this._loader=null}onLoading(){if(null===this._loader.rootBabylonMesh)return;const e=this._loader.gltf.extensions?.KHR_xmp_json_ld,t=this._loader.gltf.asset?.extensions?.KHR_xmp_json_ld;if(e&&t){const i=+t.packet;e.packets&&i2)),new nG(pe.X5.ANIMATIONTYPE_FLOAT,`${e}.vScale`,tG,(()=>2))],offset:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,JU,(()=>2)),new nG(pe.X5.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,tG,(()=>2))],rotation:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,`${e}.wAng`,eG,(()=>1))]}}Qk($U),$k($U,!0,(e=>new QU(e)));class sG extends Xk{buildAnimations(e,t,i,r,s){s(e._babylonCamera,this._buildAnimation(t,i,r))}}class nG extends Xk{buildAnimations(e,t,i,r,s){for(const n in e._data)s(e._data[n].babylonMaterial,this._buildAnimation(t,i,r))}}class oG extends Xk{buildAnimations(e,t,i,r,s){s(e._babylonLight,this._buildAnimation(t,i,r))}}const aG={__array__:{__target__:!0,...Yk}},lG={__array__:{__target__:!0,orthographic:{xmag:[new sG(pe.X5.ANIMATIONTYPE_FLOAT,"orthoLeft",eG,(()=>1)),new sG(pe.X5.ANIMATIONTYPE_FLOAT,"orthoRight",tG,(()=>1))],ymag:[new sG(pe.X5.ANIMATIONTYPE_FLOAT,"orthoBottom",eG,(()=>1)),new sG(pe.X5.ANIMATIONTYPE_FLOAT,"orthoTop",tG,(()=>1))],zfar:[new sG(pe.X5.ANIMATIONTYPE_FLOAT,"maxZ",JU,(()=>1))],znear:[new sG(pe.X5.ANIMATIONTYPE_FLOAT,"minZ",JU,(()=>1))]},perspective:{yfov:[new sG(pe.X5.ANIMATIONTYPE_FLOAT,"fov",JU,(()=>1))],zfar:[new sG(pe.X5.ANIMATIONTYPE_FLOAT,"maxZ",JU,(()=>1))],znear:[new sG(pe.X5.ANIMATIONTYPE_FLOAT,"minZ",JU,(()=>1))]}}},hG={nodes:aG,materials:{__array__:{__target__:!0,pbrMetallicRoughness:{baseColorFactor:[new nG(pe.X5.ANIMATIONTYPE_COLOR3,"albedoColor",ZU,(()=>4)),new nG(pe.X5.ANIMATIONTYPE_FLOAT,"alpha",(function(e,t,i,r){return t[i+3]*r}),(()=>4))],metallicFactor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"metallic",JU,(()=>1))],roughnessFactor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"roughness",JU,(()=>1))],baseColorTexture:{extensions:{KHR_texture_transform:rG("albedoTexture")}},metallicRoughnessTexture:{extensions:{KHR_texture_transform:rG("metallicTexture")}}},emissiveFactor:[new nG(pe.X5.ANIMATIONTYPE_COLOR3,"emissiveColor",ZU,(()=>3))],normalTexture:{scale:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"bumpTexture.level",JU,(()=>1))],extensions:{KHR_texture_transform:rG("bumpTexture")}},occlusionTexture:{strength:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",JU,(()=>1))],extensions:{KHR_texture_transform:rG("ambientTexture")}},emissiveTexture:{extensions:{KHR_texture_transform:rG("emissiveTexture")}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",JU,(()=>1))],anisotropyRotation:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"anisotropy.angle",JU,(()=>1))],anisotropyTexture:{extensions:{KHR_texture_transform:rG("anisotropy.texture")}}},KHR_materials_clearcoat:{clearcoatFactor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",JU,(()=>1))],clearcoatRoughnessFactor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",JU,(()=>1))],clearcoatTexture:{extensions:{KHR_texture_transform:rG("clearCoat.texture")}},clearcoatNormalTexture:{scale:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",JU,(()=>1))],extensions:{KHR_texture_transform:rG("clearCoat.bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:rG("clearCoat.textureRoughness")}}},KHR_materials_dispersion:{dispersion:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",JU,(()=>1))]},KHR_materials_emissive_strength:{emissiveStrength:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"emissiveIntensity",JU,(()=>1))]},KHR_materials_ior:{ior:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"indexOfRefraction",JU,(()=>1))]},KHR_materials_iridescence:{iridescenceFactor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"iridescence.intensity",JU,(()=>1))],iridescenceIor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",JU,(()=>1))],iridescenceThicknessMinimum:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",JU,(()=>1))],iridescenceThicknessMaximum:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",JU,(()=>1))],iridescenceTexture:{extensions:{KHR_texture_transform:rG("iridescence.texture")}},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:rG("iridescence.thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:[new nG(pe.X5.ANIMATIONTYPE_COLOR3,"sheen.color",ZU,(()=>3))],sheenRoughnessFactor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"sheen.roughness",JU,(()=>1))],sheenColorTexture:{extensions:{KHR_texture_transform:rG("sheen.texture")}},sheenRoughnessTexture:{extensions:{KHR_texture_transform:rG("sheen.textureRoughness")}}},KHR_materials_specular:{specularFactor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"metallicF0Factor",JU,(()=>1))],specularColorFactor:[new nG(pe.X5.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",ZU,(()=>3))],specularTexture:{extensions:{KHR_texture_transform:rG("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:rG("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",JU,(()=>1))],transmissionTexture:{extensions:{KHR_texture_transform:rG("subSurface.refractionIntensityTexture")}}},KHR_materials_volume:{attenuationColor:[new nG(pe.X5.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",ZU,(()=>3))],attenuationDistance:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",JU,(()=>1))],thicknessFactor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",JU,(()=>1))],thicknessTexture:{extensions:{KHR_texture_transform:rG("subSurface.thicknessTexture")}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:[new nG(pe.X5.ANIMATIONTYPE_FLOAT,"subSurface.translucencyIntensity",JU,(()=>1))],diffuseTransmissionTexture:{extensions:{KHR_texture_transform:rG("subSurface.translucencyIntensityTexture")}},diffuseTransmissionColorFactor:[new nG(pe.X5.ANIMATIONTYPE_COLOR3,"subSurface.translucencyColor",ZU,(()=>3))],diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:rG("subSurface.translucencyColorTexture")}}}}}},cameras:lG,extensions:{KHR_lights_punctual:{lights:{__array__:{__target__:!0,color:[new oG(pe.X5.ANIMATIONTYPE_COLOR3,"diffuse",ZU,(()=>3))],intensity:[new oG(pe.X5.ANIMATIONTYPE_FLOAT,"intensity",JU,(()=>1))],range:[new oG(pe.X5.ANIMATIONTYPE_FLOAT,"range",JU,(()=>1))],spot:{innerConeAngle:[new oG(pe.X5.ANIMATIONTYPE_FLOAT,"innerAngle",iG,(()=>1))],outerConeAngle:[new oG(pe.X5.ANIMATIONTYPE_FLOAT,"angle",iG,(()=>1))]}}}}}};class cG{constructor(e,t){this._gltf=e,this._infoTree=t}convert(e){let t,i=this._gltf,r=this._infoTree;if(!e.startsWith("/"))throw new Error("Path must start with a /");const s=e.split("/");s.shift();for(const n of s){if(r.__array__)r=r.__array__;else if(r=r[n],!r)throw new Error(`Path ${e} is invalid`);if(void 0===i)throw new Error(`Path ${e} is invalid`);i=i[n],r.__target__&&(t=i)}return{object:t,info:r}}}const uG="KHR_animation_pointer";class dG extends cG{constructor(e){super(e,hG)}}class fG{constructor(e){this.name=uG,this._loader=e,this._pathToObjectConverter=new dG(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(uG)}dispose(){this._loader=null,delete this._pathToObjectConverter}_loadAnimationChannelAsync(e,t,i,r,s){const n=r.target.extensions?.KHR_animation_pointer;if(!n||!this._pathToObjectConverter)return null;"pointer"!==r.target.path&&Z.V.Warn(`${e}/target/path: Value (${r.target.path}) must be (pointer) when using the ${this.name} extension`),null!=r.target.node&&Z.V.Warn(`${e}/target/node: Value (${r.target.node}) must not be present when using the ${this.name} extension`);const o=`${e}/extensions/${this.name}`,a=n.pointer;if(!a)throw new Error(`${o}: Pointer is missing`);try{const n=this._pathToObjectConverter.convert(a);return this._loader._loadAnimationChannelFromTargetInfoAsync(e,t,i,r,n,s)}catch(e){return Z.V.Warn(`${o}/pointer: Invalid pointer (${a}) skipped`),null}}}Qk(uG),$k(uG,!0,(e=>new fG(e)));const pG="MSFT_audio_emitter";class _G{constructor(e){this.name=pG,this._loader=e,this.enabled=this._loader.isExtensionUsed(pG)}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,Jk.Assign(this._clips),Jk.Assign(this._emitters)}}loadSceneAsync(e,t){return eU.LoadExtensionAsync(e,t,this.name,((i,r)=>{const s=new Array;s.push(this._loader.loadSceneAsync(e,t));for(const e of r.emitters){const t=Jk.Get(`${i}/emitters`,this._emitters,e);if(null!=t.refDistance||null!=t.maxDistance||null!=t.rolloffFactor||null!=t.distanceModel||null!=t.innerAngle||null!=t.outerAngle)throw new Error(`${i}: Direction or Distance properties are not allowed on emitters attached to a scene`);s.push(this._loadEmitterAsync(`${i}/emitters/${t.index}`,t))}return Promise.all(s).then((()=>{}))}))}loadNodeAsync(e,t,i){return eU.LoadExtensionAsync(e,t,this.name,((e,r)=>{const s=new Array;return this._loader.loadNodeAsync(e,t,(t=>{for(const i of r.emitters){const r=Jk.Get(`${e}/emitters`,this._emitters,i);s.push(this._loadEmitterAsync(`${e}/emitters/${r.index}`,r).then((()=>{for(const e of r._babylonSounds)e.attachToMesh(t),null==r.innerAngle&&null==r.outerAngle||(e.setLocalDirectionToMesh(W.Pq.Forward()),e.setDirectionalCone(2*Ue.S0.ToDegrees(null==r.innerAngle?Math.PI:r.innerAngle),2*Ue.S0.ToDegrees(null==r.outerAngle?Math.PI:r.outerAngle),0))})))}i(t)})).then((e=>Promise.all(s).then((()=>e))))}))}loadAnimationAsync(e,t){return eU.LoadExtensionAsync(e,t,this.name,((i,r)=>this._loader.loadAnimationAsync(e,t).then((s=>{const n=new Array;Jk.Assign(r.events);for(const o of r.events)n.push(this._loadAnimationEventAsync(`${i}/events/${o.index}`,e,t,o,s));return Promise.all(n).then((()=>s))}))))}_loadClipAsync(e,t){if(t._objectURL)return t._objectURL;let i;if(t.uri)i=this._loader.loadUriAsync(e,t,t.uri);else{const r=Jk.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,t.bufferView);i=this._loader.loadBufferViewAsync(`/bufferViews/${r.index}`,r)}return t._objectURL=i.then((e=>URL.createObjectURL(new Blob([e],{type:t.mimeType})))),t._objectURL}_loadEmitterAsync(e,t){if(t._babylonSounds=t._babylonSounds||[],!t._babylonData){const e=new Array,i=t.name||`emitter${t.index}`,r={loop:!1,autoplay:!1,volume:null==t.volume?1:t.volume};for(let s=0;s{const n=t._babylonSounds[s]=new si(i,e,this._loader.babylonScene,null,r);n.refDistance=t.refDistance||1,n.maxDistance=t.maxDistance||256,n.rolloffFactor=t.rolloffFactor||1,n.distanceModel=t.distanceModel||"exponential"})))}const s=Promise.all(e).then((()=>{const e=t.clips.map((e=>e.weight||1)),i=new mi(t.loop||!1,t._babylonSounds,e);t.innerAngle&&(i.directionalConeInnerAngle=2*Ue.S0.ToDegrees(t.innerAngle)),t.outerAngle&&(i.directionalConeOuterAngle=2*Ue.S0.ToDegrees(t.outerAngle)),t.volume&&(i.volume=t.volume),t._babylonData.sound=i}));t._babylonData={loaded:s}}return t._babylonData.loaded}_getEventAction(e,t,i,r,s){switch(i){case"play":return e=>{const i=(s||0)+(e-r);t.play(i)};case"stop":return()=>{t.stop()};case"pause":return()=>{t.pause()};default:throw new Error(`${e}: Unsupported action ${i}`)}}_loadAnimationEventAsync(e,t,i,r,s){if(0==s.targetedAnimations.length)return Promise.resolve();const n=s.targetedAnimations[0],o=r.emitter,a=Jk.Get(`/extensions/${this.name}/emitters`,this._emitters,o);return this._loadEmitterAsync(e,a).then((()=>{const t=a._babylonData.sound;if(t){const i=new we(r.time,this._getEventAction(e,t,r.action,r.time,r.startOffset));n.animation.addEvent(i),s.onAnimationGroupEndObservable.add((()=>{t.stop()})),s.onAnimationGroupPauseObservable.add((()=>{t.pause()}))}}))}}Qk(pG),$k(pG,!0,(e=>new _G(e)));const mG="MSFT_lod";class gG{constructor(e){this.name=mG,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new z.cP,this.onMaterialLODsLoadedObservable=new z.cP,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.maxLODsToLoad=this._loader.parent.extensionOptions[mG]?.maxLODsToLoad??this.maxLODsToLoad,this.enabled=this._loader.isExtensionUsed(mG)}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{0!==e&&(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{0!==e&&(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 eU.LoadExtensionAsync(e,t,this.name,((e,r)=>{let s;const n=this._getLODs(e,t,this._loader.gltf.nodes,r.ids);this._loader.logOpen(`${e}`);for(let e=0;e{i(e),e.setEnabled(!1)},o=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,r).then((t=>{if(0!==e){const t=n[e-1];t._babylonTransformNode&&(this._disposeTransformNode(t._babylonTransformNode),delete t._babylonTransformNode)}return t.setEnabled(!0),t}));this._nodePromiseLODs[e]=this._nodePromiseLODs[e]||[],0===e?s=o:(this._nodeIndexLOD=null,this._nodePromiseLODs[e].push(o))}return this._loader.logClose(),s}))}_loadMaterialAsync(e,t,i,r,s){return this._nodeIndexLOD?null:eU.LoadExtensionAsync(e,t,this.name,((e,n)=>{let o;const a=this._getLODs(e,t,this._loader.gltf.materials,n.ids);this._loader.logOpen(`${e}`);for(let e=0;e{0===e&&s(t)})).then((t=>{if(0!==e){s(t);const i=a[e-1]._data;i[r]&&(this._disposeMaterials([i[r].babylonMaterial]),delete i[r])}return t}));this._materialPromiseLODs[e]=this._materialPromiseLODs[e]||[],0===e?o=n:(this._materialIndexLOD=null,this._materialPromiseLODs[e].push(n))}return this._loader.logClose(),o}))}_loadUriAsync(e,t,i){if(null!==this._nodeIndexLOD){this._loader.log("deferred");const r=this._nodeIndexLOD-1;return this._nodeSignalLODs[r]=this._nodeSignalLODs[r]||new uR,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then((()=>this._loader.loadUriAsync(e,t,i)))}if(null!==this._materialIndexLOD){this._loader.log("deferred");const r=this._materialIndexLOD-1;return this._materialSignalLODs[r]=this._materialSignalLODs[r]||new uR,this._materialSignalLODs[r].promise.then((()=>this._loader.loadUriAsync(e,t,i)))}return null}loadBufferAsync(e,t,i,r){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 t=(e,t)=>{const s=i,n=s+r-1;let o=e[t];return o?(o.start=Math.min(o.start,s),o.end=Math.max(o.end,n)):(o={start:s,end:n,loaded:new uR},e[t]=o),o.loaded.promise.then((e=>new Uint8Array(e.buffer,e.byteOffset+i-o.start,r)))};return this._loader.log("deferred"),null!==this._nodeIndexLOD?t(this._nodeBufferLODs,this._nodeIndexLOD):null!==this._materialIndexLOD?t(this._materialBufferLODs,this._materialIndexLOD):t(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((e=>{i.loaded.resolve(e)}),(e=>{i.loaded.reject(e)})))}_getLODs(e,t,i,r){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const s=[];for(let t=r.length-1;t>=0;t--)if(s.push(Jk.Get(`${e}/ids/${r[t]}`,i,r[t])),s.length===this.maxLODsToLoad)return s;return s.push(t),s}_disposeTransformNode(e){const t=[],i=e.material;i&&t.push(i);for(const i of e.getChildMeshes())i.material&&t.push(i.material);e.dispose();const r=t.filter((e=>this._loader.babylonScene.meshes.every((t=>t.material!=e))));this._disposeMaterials(r)}_disposeMaterials(e){const t={};for(const i of e){for(const e of i.getActiveTextures())t[e.uniqueId]=e;i.dispose()}for(const e in t)for(const i of this._loader.babylonScene.materials)i.hasTexture(t[e])&&delete t[e];for(const e in t)t[e].dispose()}}Qk(mG),$k(mG,!0,(e=>new gG(e)));const vG="MSFT_minecraftMesh";class xG{constructor(e){this.name=vG,this._loader=e,this.enabled=this._loader.isExtensionUsed(vG)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtraAsync(e,t,this.name,((r,s)=>{if(s){if(!(i instanceof zm))throw new Error(`${r}: Material type not supported`);const s=this._loader.loadMaterialPropertiesAsync(e,t,i);return i.needAlphaBlending()&&(i.forceDepthWrite=!0,i.separateCullingPass=!0),i.backFaceCulling=i.forceDepthWrite,i.twoSidedLighting=!0,s}return null}))}}Qk(vG),$k(vG,!0,(e=>new xG(e)));const bG="MSFT_sRGBFactors";class SG{constructor(e){this.name=bG,this._loader=e,this.enabled=this._loader.isExtensionUsed(bG)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return eU.LoadExtraAsync(e,t,this.name,((r,s)=>{if(s){if(!(i instanceof zm))throw new Error(`${r}: Material type not supported`);const s=this._loader.loadMaterialPropertiesAsync(e,t,i),n=i.getScene().getEngine().useExactSrgbConversions;return i.albedoTexture||i.albedoColor.toLinearSpaceToRef(i.albedoColor,n),i.reflectivityTexture||i.reflectivityColor.toLinearSpaceToRef(i.reflectivityColor,n),s}return null}))}}Qk(bG),$k(bG,!0,(e=>new SG(e)));const TG={"lifecycle/onStart":Ep.ClassName,"lifecycle/onTick":Ap.ClassName,log:ld.ClassName,"flow/delay":Sd.ClassName,"customEvent/send":fd.ClassName,"customEvent/receive":Pp.ClassName,"flow/sequence":Id.ClassName,"world/get":Bd.ClassName,"world/set":dd.ClassName,"flow/doN":_d.ClassName,"variable/get":Nd.ClassName,"variable/set":hd.ClassName,"flow/whileLoop":Pd.ClassName,"math/random":af.ClassName,"math/e":hf.ClassName,"math/pi":cf.ClassName,"math/inf":uf.ClassName,"math/nan":df.ClassName,"math/abs":pf.ClassName,"math/sign":_f.ClassName,"math/trunc":mf.ClassName,"math/floor":gf.ClassName,"math/ceil":vf.ClassName,"math/fract":xf.ClassName,"math/neg":bf.ClassName,"math/add":rf.ClassName,"math/sub":sf.ClassName,"math/mul":nf.ClassName,"math/div":of.ClassName,"math/rem":Tf.ClassName,"math/min":Cf.ClassName,"math/max":yf.ClassName,"math/clamp":Af.ClassName,"math/saturate":If.ClassName,"math/mix":Mf.ClassName,"math/eq":Of.ClassName,"math/lt":wf.ClassName,"math/le":Nf.ClassName,"math/gt":Ff.ClassName,"math/ge":Lf.ClassName,"math/isnan":Bf.ClassName,"math/isinf":Vf.ClassName,"math/rad":kf.ClassName,"math/deg":Uf.ClassName,"math/sin":Gf.ClassName,"math/cos":zf.ClassName,"math/tan":Wf.ClassName,"math/asin":Hf.ClassName,"math/acos":Xf.ClassName,"math/atan":qf.ClassName,"math/atan2":Yf.ClassName,"math/sinh":Kf.ClassName,"math/cosh":jf.ClassName,"math/tanh":$f.ClassName,"math/asinh":Qf.ClassName,"math/acosh":Zf.ClassName,"math/atanh":Jf.ClassName,"math/exp":ep.ClassName,"math/log":tp.ClassName,"math/log2":ip.ClassName,"math/log10":rp.ClassName,"math/sqrt":sp.ClassName,"math/cbrt":np.ClassName,"math/pow":op.ClassName,"math/length":ap.ClassName,"math/normalize":lp.ClassName,"math/dot":lf.ClassName,"math/cross":hp.ClassName,"math/rotate2d":cp.ClassName,"math/rotate3d":up.ClassName,"math/transpose":dp.ClassName,"math/determinant":fp.ClassName,"math/inverse":pp.ClassName,"math/matmul":_p.ClassName,"math/not":mp.ClassName,"math/and":gp.ClassName,"math/or":vp.ClassName,"math/xor":xp.ClassName,"math/asr":Sp.ClassName,"math/lsl":bp.ClassName,"math/clz":Tp.ClassName,"math/ctz":Cp.ClassName,"math/popcnt":yp.ClassName},CG={float2:"Vector2",float3:"Vector3",float4:"Vector4",float4x4:"Matrix",int:"FlowGraphInteger"};function yG(e,t,i){if(void 0!==e.type){const r=t.types&&t.types[e.type];if(!r)throw new Error(`${i}: Unknown type: ${e.type}`);const s=r.signature;if(!s)throw new Error(`${i}: Type ${e.type} has no signature`);const n=CG[s];return{value:e.value,className:n}}return e.value}function EG(e,t,i){const r=TG[t.type];if(!r)throw new Error(`/extensions/KHR_interactivity/nodes/${e}: Unknown block type: ${t.type}`);const s=e.toString(),n=function(e,t,i){const r={},s=e.configuration??[];for(const e of s)if("customEvent"===e.id){const s=t.customEvents&&t.customEvents[e.value];if(!s)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Unknown custom event: ${e.value}`);r.eventId=s.id,r.eventData=s.values.map((e=>e.id))}else if("variable"===e.id){const s=t.variables&&t.variables[e.value];if(!s)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Unknown variable: ${e.value}`);r.variableName=s.id}else if("path"===e.id){const t=e.value;r.path=t}else r[e.id]=yG(e,t,`/extensions/KHR_interactivity/nodes/${i}`);return r}(t,i,s);return{className:r,config:n,uniqueId:s,metadata:t.metadata,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[]}}class PG extends cG{constructor(e){super(e,AG)}}const AG={nodes:{__array__:{__target__:!0,translation:{type:"Vector3",get:e=>e._babylonTransformNode.position,set:(e,t)=>{t._babylonTransformNode.position=e},getObject:e=>e._babylonTransformNode}}}},RG="KHR_interactivity";class IG{constructor(e){this._loader=e,this.name=RG,this.enabled=this._loader.isExtensionUsed(RG),this._pathConverter=new PG(this._loader.gltf)}dispose(){this._loader=null,delete this._pathConverter}onReady(){if(!this._loader.babylonScene||!this._pathConverter)return;const e=this._loader.babylonScene,t=this._loader.gltf.extensions?.KHR_interactivity,i=function(e){const t={uniqueId:(0,Au.z)(),_userVariables:{},_connectionValues:{}},i=[t],r=[];for(let t=0;te.name===a));h||(h={uniqueId:(0,Au.z)(),name:a,_connectionType:0,connectedPointIds:[]},l.signalInputs.push(h)),h.connectedPointIds.push(s.uniqueId),s.connectedPointIds.push(h.uniqueId)}const a=s.values??[];for(const s of a){const o=s.id,a={uniqueId:(0,Au.z)(),name:o,_connectionType:0,connectedPointIds:[]};if(n.dataInputs.push(a),void 0!==s.value){const r=yG(s,e,`/extensions/KHR_interactivity/nodes/${i}`);t._connectionValues[a.uniqueId]=r}else{if(void 0===s.node||void 0===s.socket)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Invalid socket ${o} in node ${i}`);{const e=s.node,t=s.socket,n=r[e];if(!n)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Could not find node with id ${e} that connects its output with node${i}'s input ${o}`);let l=n.dataOutputs.find((e=>e.name===t));l||(l={uniqueId:(0,Au.z)(),name:t,_connectionType:1,connectedPointIds:[]},n.dataOutputs.push(l)),a.connectedPointIds.push(l.uniqueId),l.connectedPointIds.push(a.uniqueId)}}}}const s=e.variables??[];for(let i=0;inew IG(e)));const MG="KHR_node_visibility";class OG{constructor(e){this.name=MG,this._loader=e,this.enabled=e.isExtensionUsed(MG)}async onReady(){this._loader.gltf.nodes?.forEach((e=>{e._primitiveBabylonMeshes?.forEach((e=>{e.inheritVisibility=!0})),e.extensions?.KHR_node_visibility&&!1===e.extensions?.KHR_node_visibility.visible&&(e._babylonTransformNode&&(e._babylonTransformNode.isVisible=!1),e._primitiveBabylonMeshes?.forEach((e=>{e.isVisible=!1})))}))}dispose(){this._loader=null}}Qk(MG),$k(MG,!0,(e=>new OG(e)));const DG="ExtrasAsMetadata";class wG{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){const i=e.metadata=e.metadata||{};(i.gltf=i.gltf||{}).extras=t.extras}}constructor(e){this.name=DG,this.enabled=!0,this._loader=e}dispose(){this._loader=null}loadNodeAsync(e,t,i){return this._loader.loadNodeAsync(e,t,(e=>{this._assignExtras(e,t),i(e)}))}loadCameraAsync(e,t,i){return this._loader.loadCameraAsync(e,t,(e=>{this._assignExtras(e,t),i(e)}))}createMaterial(e,t,i){const r=this._loader.createMaterial(e,t,i);return this._assignExtras(r,t),r}}Qk(DG),$k(DG,!1,(e=>new wG(e)));class NG{constructor(){this.materials=[]}parseMTL(e,t,i,r){if(t instanceof ArrayBuffer)return;const s=t.split("\n"),n=/\s+/;let o,a=null;for(let t=0;t=0?l.substring(0,h):l;c=c.toLowerCase();const u=h>=0?l.substring(h+1).trim():"";if("newmtl"===c)a&&this.materials.push(a),e._blockEntityCollection=!!r,a=new Un(u,e),a._parentContainer=r,e._blockEntityCollection=!1;else if("kd"===c&&a)o=u.split(n,3).map(parseFloat),a.diffuseColor=H.v9.FromArray(o);else if("ka"===c&&a)o=u.split(n,3).map(parseFloat),a.ambientColor=H.v9.FromArray(o);else if("ks"===c&&a)o=u.split(n,3).map(parseFloat),a.specularColor=H.v9.FromArray(o);else if("ke"===c&&a)o=u.split(n,3).map(parseFloat),a.emissiveColor=H.v9.FromArray(o);else if("ns"===c&&a)a.specularPower=parseFloat(u);else if("d"===c&&a)a.alpha=parseFloat(u);else if("map_ka"===c&&a)a.ambientTexture=NG._GetTexture(i,u,e);else if("map_kd"===c&&a)a.diffuseTexture=NG._GetTexture(i,u,e);else if("map_ks"===c&&a)a.specularTexture=NG._GetTexture(i,u,e);else if("map_ns"===c);else if("map_bump"===c&&a){const t=u.split(n),r=t.indexOf("-bm");let s=null;r>=0&&(s=t[r+1],t.splice(r,2)),a.bumpTexture=NG._GetTexture(i,t.join(" "),e),a.bumpTexture&&null!==s&&(a.bumpTexture.level=parseFloat(s))}else"map_d"===c&&a&&(a.opacityTexture=NG._GetTexture(i,u,e))}a&&this.materials.push(a)}static _GetTexture(e,t,i){if(!t)return null;let r=e;if("file:"===e){let e=t.lastIndexOf("\\");-1===e&&(e=t.lastIndexOf("/")),r+=e>-1?t.substring(e+1):t}else r+=t;return new vi.g(r,i,!1,NG.INVERT_TEXTURE_Y)}}NG.INVERT_TEXTURE_Y=!0;class FG{constructor(e,t,i){this._positions=[],this._normals=[],this._uvs=[],this._colors=[],this._extColors=[],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 H.ov(.5,.5,.5,1),this._hasLineData=!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-1===i?-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 1!=i&&t[2]===e[t[0]].uv[i]?e[t[0]].idx[i]:-1}_setData(e,t,i,r,s,n,o){let a;a=this._loadingOptions.optimizeWithUV?this._isInArrayUV(this._tuplePosNorm,[e,i,t]):this._isInArray(this._tuplePosNorm,[e,i]),-1===a?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(r),s=s??new W.I9(0,0),this._wrappedUvsForBabylon.push(s),this._wrappedNormalsForBabylon.push(n),void 0!==o&&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(a)}_unwrapData(){try{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._handledMesh.hasLines=this._hasLineData,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,this._hasLineData=!1)}_optimizeNormals(e){const t=e.getVerticesData(st.R.PositionKind),i=e.getVerticesData(st.R.NormalKind),r={};if(!t||!i)return;for(let e=0;ethis._triangles.push(e[0],e[t],e[t+1]),this._handednessSign=1):i.useRightHandedSystem?(this._pushTriangle=(e,t)=>this._triangles.push(e[0],e[t+1],e[t]),this._handednessSign=1):(this._pushTriangle=(e,t)=>this._triangles.push(e[0],e[t],e[t+1]),this._handednessSign=-1);const n=t.split("\n"),o=[];let a=[];o.push(a);for(let e=0;e=7){const e=parseFloat(i[4]),t=parseFloat(i[5]),r=parseFloat(i[6]);this._colors.push(new H.ov(e>1?e/255:e,t>1?t/255:t,r>1?r/255:r,7===i.length||void 0===i[7]?1:parseFloat(i[7])))}else this._colors.push(this._grayColor)}else if(null!==(i=FG.NormalPattern.exec(t)))this._normals.push(new W.Pq(parseFloat(i[1]),parseFloat(i[2]),parseFloat(i[3])));else if(null!==(i=FG.UVPattern.exec(t)))this._uvs.push(new W.I9(parseFloat(i[1])*this._loadingOptions.UVScaling.x,parseFloat(i[2])*this._loadingOptions.UVScaling.y));else if(null!==(i=FG.FacePattern3.exec(t)))this._setDataForCurrentFaceWithPattern3(i[1].trim().split(" "),1);else if(null!==(i=FG.FacePattern4.exec(t)))this._setDataForCurrentFaceWithPattern4(i[1].trim().split(" "),1);else if(null!==(i=FG.FacePattern5.exec(t)))this._setDataForCurrentFaceWithPattern5(i[1].trim().split(" "),1);else if(null!==(i=FG.FacePattern2.exec(t)))this._setDataForCurrentFaceWithPattern2(i[1].trim().split(" "),1);else if(null!==(i=FG.FacePattern1.exec(t)))this._setDataForCurrentFaceWithPattern1(i[1].trim().split(" "),1);else if(null!==(i=FG.LinePattern1.exec(t)))this._setDataForCurrentFaceWithPattern1(i[1].trim().split(" "),0),this._hasLineData=!0;else if(null!==(i=FG.LinePattern2.exec(t)))this._setDataForCurrentFaceWithPattern2(i[1].trim().split(" "),0),this._hasLineData=!0;else if(i=FG._GetZbrushMRGB(t,!this._loadingOptions.importVertexColors))i.forEach((e=>{this._extColors.push(e)}));else if(null!==(i=FG.LinePattern3.exec(t)))this._setDataForCurrentFaceWithPattern3(i[1].trim().split(" "),0),this._hasLineData=!0;else if(FG.GroupDescriptor.test(t)||FG.ObjectDescriptor.test(t)){const e={name:t.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:FG.ObjectDescriptor.test(t)};this._addPreviousObjMesh(),this._meshesFromObj.push(e),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(FG.UseMtlDescriptor.test(t)){if(this._materialNameFromObj=t.substring(7).trim(),!this._isFirstMaterial||!this._hasMeshes){this._addPreviousObjMesh();const e={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(e),this._hasMeshes=!0}this._hasMeshes&&this._isFirstMaterial&&(this._meshesFromObj[this._meshesFromObj.length-1].materialName=this._materialNameFromObj,this._isFirstMaterial=!1)}else FG.MtlLibGroupDescriptor.test(t)?s(t.substring(7).trim()):FG.SmoothDescriptor.test(t)||Z.V.Log("Unhandled expression at line : "+t)}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._handledMesh.hasLines=this._hasLineData,this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon)),!this._hasMeshes){let e=null;if(this._indicesForBabylon.length)this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData();else{for(const e of this._positions)this._unwrappedPositionsForBabylon.push(e.x,e.y,e.z);if(this._normals.length)for(const e of this._normals)this._unwrappedNormalsForBabylon.push(e.x,e.y,e.z);if(this._uvs.length)for(const e of this._uvs)this._unwrappedUVForBabylon.push(e.x,e.y);if(this._extColors.length)for(const e of this._extColors)this._unwrappedColorsForBabylon.push(e.r,e.g,e.b,e.a);else if(this._colors.length)for(const e of this._colors)this._unwrappedColorsForBabylon.push(e.r,e.g,e.b,e.a);this._materialNameFromObj||(e=new Un(yt.RandomId(),i),e.pointsCloud=!0,this._materialNameFromObj=e.name,this._normals.length||(e.disableLighting=!0,e.emissiveColor=H.v9.White()))}this._meshesFromObj.push({name:yt.RandomId(),indices:this._indicesForBabylon,positions:this._unwrappedPositionsForBabylon,colors:this._unwrappedColorsForBabylon,normals:this._unwrappedNormalsForBabylon,uvs:this._unwrappedUVForBabylon,materialName:this._materialNameFromObj,directMaterial:e,isObject:!0,hasLines:this._hasLineData})}for(let t=0;t=0;--e)if(this._meshesFromObj[e].isObject&&this._meshesFromObj[e]._babylonMesh){s.parent=this._meshesFromObj[e]._babylonMesh;break}if(this._materialToUse.push(this._meshesFromObj[t].materialName),this._handledMesh.hasLines&&(s._internalMetadata??(s._internalMetadata={}),s._internalMetadata._isLine=!0),0===this._handledMesh.positions?.length){this._babylonMeshesArray.push(s);continue}const n=new bt;if(n.uvs=this._handledMesh.uvs,n.indices=this._handledMesh.indices,n.positions=this._handledMesh.positions,this._loadingOptions.computeNormals){const e=new Array;bt.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,e),n.normals=e}else n.normals=this._handledMesh.normals;this._loadingOptions.importVertexColors&&(n.colors=this._handledMesh.colors),n.applyToMesh(s),this._loadingOptions.invertY&&(s.scaling.y*=-1),this._loadingOptions.optimizeNormals&&this._optimizeNormals(s),this._babylonMeshesArray.push(s),this._handledMesh.directMaterial&&(s.material=this._handledMesh.directMaterial)}}}FG.ObjectDescriptor=/^o/,FG.GroupDescriptor=/^g/,FG.MtlLibGroupDescriptor=/^mtllib /,FG.UseMtlDescriptor=/^usemtl /,FG.SmoothDescriptor=/^s /,FG.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/,FG.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,FG.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,FG.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/,FG.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,FG.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,FG.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,FG.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/,FG.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/,FG.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/,FG.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;class LG{static get INVERT_TEXTURE_Y(){return NG.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){NG.INVERT_TEXTURE_Y=e}constructor(e){this.name="obj",this.extensions=".obj",this._assetContainer=null,this._loadingOptions=e||LG._DefaultLoadingOptions}static get _DefaultLoadingOptions(){return{computeNormals:LG.COMPUTE_NORMALS,optimizeNormals:LG.OPTIMIZE_NORMALS,importVertexColors:LG.IMPORT_VERTEX_COLORS,invertY:LG.INVERT_Y,invertTextureY:LG.INVERT_TEXTURE_Y,UVScaling:LG.UV_SCALING,materialLoadingFailsSilently:LG.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:LG.OPTIMIZE_WITH_UV,skipMaterials:LG.SKIP_MATERIALS,useLegacyBehavior:LG.USE_LEGACY_BEHAVIOR}}_loadMTL(e,t,i,r){const s=t+e;Ue.S0.LoadFile(s,i,void 0,void 0,!1,((e,t)=>{r(s,t)}))}createPlugin(){return new LG(LG._DefaultLoadingOptions)}canDirectLoad(){return!1}importMeshAsync(e,t,i,r){return this._parseSolid(e,t,i,r).then((e=>({meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]})))}loadAsync(e,t,i){return this.importMeshAsync(null,e,t,i).then((()=>{}))}loadAssetContainerAsync(e,t,i){const r=new ei(e);return this._assetContainer=r,this.importMeshAsync(null,e,t,i).then((e=>(e.meshes.forEach((e=>r.meshes.push(e))),e.meshes.forEach((e=>{const t=e.material;t&&-1==r.materials.indexOf(t)&&(r.materials.push(t),t.getActiveTextures().forEach((e=>{-1==r.textures.indexOf(e)&&r.textures.push(e)})))})),this._assetContainer=null,r))).catch((e=>{throw this._assetContainer=null,e}))}_parseSolid(e,t,i,r){let s="";const n=new NG,o=[],a=[];i=i.replace(/#.*$/gm,"").trim(),new FG(o,a,this._loadingOptions).parse(e,i,t,this._assetContainer,(e=>{s=e}));const l=[];return""===s||this._loadingOptions.skipMaterials||l.push(new Promise(((e,i)=>{this._loadMTL(s,r,(l=>{try{n.parseMTL(t,l,r,this._assetContainer);for(let e=0;e-1;)i.push(r),t=r+1;if(-1===r&&0===i.length)n.materials[e].dispose();else for(let t=0;t{Ue.S0.Warn(`Error downloading MTL file: '${s}'`),this._loadingOptions.materialLoadingFailsSilently?e():i(r)}))}))),Promise.all(l).then((()=>{const e=e=>Boolean(e._internalMetadata?._isLine??!1);return a.forEach((i=>{if(e(i)){let r=i.material??new Un(i.name+"_line",t);r.getBindedMeshes().filter((t=>!e(t))).length>0&&(r=r.clone(r.name+"_line")??r),r.wireframe=!0,i.material=r,i._internalMetadata&&(i._internalMetadata._isLine=void 0)}})),a}))}}LG.OPTIMIZE_WITH_UV=!0,LG.INVERT_Y=!1,LG.IMPORT_VERTEX_COLORS=!1,LG.COMPUTE_NORMALS=!1,LG.OPTIMIZE_NORMALS=!1,LG.UV_SCALING=new W.I9(1,1),LG.SKIP_MATERIALS=!1,LG.MATERIAL_LOADING_FAILS_SILENTLY=!0,LG.USE_LEGACY_BEHAVIOR=!1,ng(new LG);const BG={".stl":{isBinary:!0}};class VG{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=BG}importMesh(e,t,i,r,s){let n;if("string"!=typeof i){if(this._isBinary(i)){const e=new Yt("stlmesh",t);return this._parseBinary(e,i),s&&s.push(e),!0}i=(new TextDecoder).decode(new Uint8Array(i))}for(;n=this.solidPattern.exec(i);){let i=n[1];const r=n[3];if(r&&i!=r)return Ue.S0.Error("Error in STL, solid name != endsolid name"),!1;if(e&&i)if(e instanceof Array){if(!e.indexOf(i))continue}else if(i!==e)continue;i=i||"stlmesh";const o=new Yt(i,t);this._parseASCII(o,n[2]),s&&s.push(o)}return!0}load(e,t,i){return this.importMesh(null,e,t,i,null)}loadAssetContainer(e,t,i){const r=new ei(e);return e._blockEntityCollection=!0,this.importMesh(null,e,t,i,r.meshes),e._blockEntityCollection=!1,r}_isBinary(e){const t=new DataView(e);if(t.byteLength<=80)return!1;if(84+50*t.getUint32(80,!0)===t.byteLength)return!0;const i=[115,111,108,105,100];for(let e=0;e<5;e++)if(t.getUint8(e)!==i[e])return!0;return!1}_parseBinary(e,t){const i=new DataView(t),r=i.getUint32(80,!0);let s=0;const n=new Float32Array(3*r*3),o=new Float32Array(3*r*3),a=new Uint32Array(3*r);let l=0;for(let e=0;e({meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]})))}static _BuildPointCloud(e,t){if(!t.byteLength)return!1;const i=new Uint8Array(t),r=new Float32Array(t),s=i.length/32;return e.addPoints(s,(function(e,t){const s=r[8*t+0],n=r[8*t+1],o=r[8*t+2];e.position=new W.Pq(s,n,o);const a=i[32*t+24+0]/255,l=i[32*t+24+1]/255,h=i[32*t+24+2]/255;e.color=new H.ov(a,l,h,1)})),!0}static _BuildMesh(e,t){const i=new Yt("PLYMesh",e),r=new Uint8Array(t.data),s=new Float32Array(t.data),n=r.length/32,o=[],a=new bt;for(let e=0;e{const i=[];switch(e.mode){case 0:{const r=new wA("GaussianSplatting",null,t,this._loadingOptions.keepInRam);r._parentContainer=this._assetContainer,i.push(r),await r.updateDataAsync(e.data)}break;case 1:{const r=new xM("PointCloud",1,t);if(zG._BuildPointCloud(r,e.data))return Promise.all([r.buildMeshAsync()]).then((e=>(i.push(e[0]),i)));r.dispose()}break;case 2:if(!e.faces)throw new Error("PLY mesh doesn't contain face informations.");i.push(zG._BuildMesh(t,e));break;default:throw new Error("Unsupported Splat mode")}return new Promise((e=>{e(i)}))}))}loadAssetContainerAsync(e,t,i){const r=new ei(e);return this._assetContainer=r,this.importMeshAsync(null,e,t,i).then((e=>(e.meshes.forEach((e=>r.meshes.push(e))),this._assetContainer=null,r))).catch((e=>{throw this._assetContainer=null,e}))}loadAsync(e,t,i){return this.importMeshAsync(null,e,t,i).then((()=>{}))}static _ConvertPLYToSplat(e){const t=new Uint8Array(e),i=(new TextDecoder).decode(t.slice(0,10240)),r=i.indexOf("end_header\n");if(r<0||!i)return new Promise((t=>{t({mode:0,data:e})}));const s=parseInt(/element vertex (\d+)\n/.exec(i)[1]),n=/element face (\d+)\n/.exec(i);let o=0;n&&(o=parseInt(n[1]));const a=/element chunk (\d+)\n/.exec(i);let l=0;a&&(l=parseInt(a[1]));let h=0,c=0;const u={double:8,int:4,uint:4,float:4,short:2,ushort:2,uchar:1,list:0};let d;!function(e){e[e.Vertex=0]="Vertex",e[e.Chunk=1]="Chunk"}(d||(d={}));let f=1;const p=[],_=[],m=i.slice(0,r).split("\n");for(const e of m)if(e.startsWith("property ")){const[,t,i]=e.split(" ");1==f?(_.push({name:i,type:t,offset:c}),c+=u[t]):0==f&&(p.push({name:i,type:t,offset:h}),h+=u[t]),u[t]||Z.V.Warn(`Unsupported property type: ${t}.`)}else if(e.startsWith("element ")){const[,t]=e.split(" ");"chunk"==t?f=1:"vertex"==t&&(f=0)}const g=h,v=c;return wA.ConvertPLYToSplatAsync(e).then((t=>{const i=new DataView(e,r+11);let n=v*l+g*s;const a=[];if(o)for(let e=0;e{e({mode:0,data:t,faces:a,hasVertexColors:!1})}));let h=0,c=0;const u=["x","y","z","scale_0","scale_1","scale_2","opacity","rot_0","rot_1","rot_2","rot_3"],d=["red","green","blue","f_dc_0","f_dc_1","f_dc_2"];for(let e=0;e{e({mode:_,data:t,faces:a,hasVertexColors:!!c})}))}))}}zG._DefaultLoadingOptions={keepInRam:!1},ng(new zG);var WG=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class HG{constructor(e){this.occWorkerManager=e}saveShapeSTEP(e){return WG(this,void 0,void 0,(function*(){this.saveSTEP(e)}))}saveShapeSTEPAndReturn(e){return WG(this,void 0,void 0,(function*(){return this.saveSTEP(e)}))}saveShapeStl(e){return WG(this,void 0,void 0,(function*(){this.saveStl(e)}))}saveShapeStlAndReturn(e){return WG(this,void 0,void 0,(function*(){return this.saveStl(e)}))}saveSTEP(e){return this.occWorkerManager.genericCallToWorkerPromise("io.saveShapeSTEP",e).then((t=>{if(e.tryDownload&&document){const i=new Blob([t],{type:"text/plain"}),r=URL.createObjectURL(i),s=e.fileName?e.fileName:"bitbybit-dev.step",n=document.createElement("a");n.href=r,n.target="_self",n.download=s,n.click(),n.remove()}return t}))}saveStl(e){return this.occWorkerManager.genericCallToWorkerPromise("io.saveShapeStl",e).then((t=>{if(e.tryDownload&&document){const i=new Blob([t],{type:"application/stl"}),r=URL.createObjectURL(i),s=e.fileName?e.fileName:"bitbybit-dev.stl",n=document.createElement("a");n.href=r,n.target="_self",n.download=s,n.click(),n.remove()}return t}))}}class XG{constructor(e){this.occWorkerManager=e}makeCompound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.compound.makeCompound",e)}}class qG{constructor(e){this.occWorkerManager=e}line(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.line",e)}arcThroughThreePoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcThroughThreePoints",e)}arcThroughTwoPointsAndTangent(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcThroughTwoPointsAndTangent",e)}arcFromCircleAndTwoPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcFromCircleAndTwoPoints",e)}arcFromCircleAndTwoAngles(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcFromCircleAndTwoAngles",e)}arcFromCirclePointAndAngle(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcFromCirclePointAndAngle",e)}createCircleEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.createCircleEdge",e)}createEllipseEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.createEllipseEdge",e)}removeInternalEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.removeInternalEdges",e)}makeEdgeFromGeom2dCurveAndSurface(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.makeEdgeFromGeom2dCurveAndSurface",e)}getEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdge",e)}getEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdges",e)}getEdgesAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgesAlongWire",e)}getCircularEdgesAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgesAlongWire",e)}getLinearEdgesAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getLinearEdgesAlongWire",e)}getCornerPointsOfEdgesForShape(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCornerPointsOfEdgesForShape",e)}getEdgeLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgeLength",e)}getEdgesLengths(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgesLengths",e)}getEdgeCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgeCenterOfMass",e)}getEdgesCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgesCentersOfMass",e)}getCircularEdgeCenterPoint(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgeCenterPoint",e)}getCircularEdgeRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgeRadius",e)}getCircularEdgePlaneDirection(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgePlaneDirection",e)}pointOnEdgeAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.pointOnEdgeAtParam",e)}edgesToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.edgesToPoints",e)}reversedEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.reversedEdge",e)}tangentOnEdgeAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.tangentOnEdgeAtParam",e)}pointOnEdgeAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.pointOnEdgeAtLength",e)}tangentOnEdgeAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.tangentOnEdgeAtLength",e)}startPointOnEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.startPointOnEdge",e)}endPointOnEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.endPointOnEdge",e)}divideEdgeByParamsToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.divideEdgeByParamsToPoints",e)}divideEdgeByEqualDistanceToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.divideEdgeByEqualDistanceToPoints",e)}constraintTanLinesFromTwoPtsToCircle(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanLinesFromTwoPtsToCircle",e)}constraintTanLinesFromPtToCircle(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanLinesFromPtToCircle",e)}constraintTanLinesOnTwoCircles(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanLinesOnTwoCircles",e)}constraintTanCirclesOnTwoCircles(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanCirclesOnTwoCircles",e)}constraintTanCirclesOnCircleAndPnt(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanCirclesOnCircleAndPnt",e)}}class YG{constructor(e){this.occWorkerManager=e}createFacesFromWiresOnFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFacesFromWiresOnFace",e)}createFaceFromWireOnFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromWireOnFace",e)}createFaceFromWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromWire",e)}createFaceFromWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromWires",e)}createFaceFromWiresOnFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromWiresOnFace",e)}createFacesFromWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFacesFromWires",e)}createFaceFromMultipleCircleTanWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromMultipleCircleTanWires",e)}createFaceFromMultipleCircleTanWireCollections(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromMultipleCircleTanWireCollections",e)}faceFromSurface(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.faceFromSurface",e)}faceFromSurfaceAndWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.faceFromSurfaceAndWire",e)}createPolygonFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createPolygonFace",e)}createCircleFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createCircleFace",e)}createEllipseFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createEllipseFace",e)}createSquareFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createSquareFace",e)}createRectangleFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createRectangleFace",e)}getFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFace",e)}getFaces(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFaces",e)}reversedFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.reversedFace",e)}subdivideToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToPoints",e)}subdivideToWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToWires",e)}subdivideToRectangleWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToRectangleWires",e)}subdivideToRectangleHoles(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToRectangleHoles",e)}subdivideToPointsControlled(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToPointsControlled",e)}subdivideToNormals(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToNormals",e)}subdivideToUV(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToUV",e)}pointOnUV(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.pointOnUV",e)}normalOnUV(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.normalOnUV",e)}pointsOnUVs(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.pointsOnUVs",e)}normalsOnUVs(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.normalsOnUVs",e)}subdivideToPointsOnParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToPointsOnParam",e)}wireAlongParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.wireAlongParam",e)}wiresAlongParams(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.wiresAlongParams",e)}getUMinBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getUMinBound",e)}getUMaxBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getUMaxBound",e)}getVMinBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getVMinBound",e)}getVMaxBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getVMaxBound",e)}getFaceArea(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFaceArea",e)}getFacesAreas(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFacesAreas",e)}getFaceCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFaceCenterOfMass",e)}getFacesCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFacesCentersOfMass",e)}filterFacePoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.filterFacePoints",e)}}class KG{constructor(e){this.occWorkerManager=e}fromClosedShell(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.fromClosedShell",e)}createBox(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createBox",e)}createCube(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCube",e)}createBoxFromCorner(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createBoxFromCorner",e)}createCylinder(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCylinder",e)}createCylindersOnLines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCylindersOnLines",e)}createSphere(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createSphere",e)}createCone(e){return e.angle=e.angle*(Math.PI/180),this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCone",e)}getSolidSurfaceArea(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidSurfaceArea",e)}getSolidVolume(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidVolume",e)}getSolidsVolumes(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidsVolumes",e)}getSolidCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidCenterOfMass",e)}getSolidsCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidsCentersOfMass",e)}getSolids(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolids",e)}filterSolidPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.filterSolidPoints",e)}}class jG{constructor(e){this.occWorkerManager=e}createPolygonWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolygonWire",e)}createPolygons(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolygons",e)}createLineWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createLineWire",e)}createLines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createLines",e)}splitOnPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.splitOnPoints",e)}wiresToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.wiresToPoints",e)}createPolylineWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolylineWire",e)}createZigZagBetweenTwoWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createZigZagBetweenTwoWires",e)}createWireFromTwoCirclesTan(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createWireFromTwoCirclesTan",e)}createPolylines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolylines",e)}createBezier(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBezier",e)}createBezierWeights(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBezierWeights",e)}createBezierWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBezierWires",e)}interpolatePoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.interpolatePoints",e)}interpolateWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.interpolateWires",e)}createBSpline(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBSpline",e)}createBSplines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBSplines",e)}combineEdgesAndWiresIntoAWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.combineEdgesAndWiresIntoAWire",e)}createWireFromEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createWireFromEdge",e)}addEdgesAndWiresToWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.addEdgesAndWiresToWire",e)}divideWireByParamsToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWireByParamsToPoints",e)}divideWiresByParamsToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWiresByParamsToPoints",e)}divideWireByEqualDistanceToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWireByEqualDistanceToPoints",e)}divideWiresByEqualDistanceToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWiresByEqualDistanceToPoints",e)}pointOnWireAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.pointOnWireAtParam",e)}pointOnWireAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.pointOnWireAtLength",e)}pointsOnWireAtLengths(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.pointsOnWireAtLengths",e)}pointsOnWireAtEqualLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.pointsOnWireAtEqualLength",e)}pointsOnWireAtPatternOfLengths(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.pointsOnWireAtPatternOfLengths",e)}tangentOnWireAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.tangentOnWireAtParam",e)}tangentOnWireAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.tangentOnWireAtLength",e)}derivativesOnWireAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.derivativesOnWireAtLength",e)}derivativesOnWireAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.derivativesOnWireAtParam",e)}startPointOnWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.startPointOnWire",e)}endPointOnWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.endPointOnWire",e)}createCircleWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createCircleWire",e)}createSquareWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createSquareWire",e)}createStarWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createStarWire",e)}createChristmasTreeWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createChristmasTreeWire",e)}createNGonWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createNGonWire",e)}createParallelogramWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createParallelogramWire",e)}createHeartWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createHeartWire",e)}createRectangleWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createRectangleWire",e)}createLPolygonWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createLPolygonWire",e)}createEllipseWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createEllipseWire",e)}getWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWire",e)}getWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWires",e)}getWireCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWireCenterOfMass",e)}getWiresCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWiresCentersOfMass",e)}reversedWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.reversedWire",e)}reversedWireFromReversedEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.reversedWireFromReversedEdges",e)}getWireLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWireLength",e)}getWiresLengths(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWiresLengths",e)}placeWireOnFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.placeWireOnFace",e)}placeWiresOnFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.placeWiresOnFace",e)}closeOpenWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.closeOpenWire",e)}project(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.project",e)}projectWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.projectWires",e)}}class $G{constructor(e){this.occWorkerManager=e}sewFaces(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shell.sewFaces",e)}getShellSurfaceArea(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shell.getShellSurfaceArea",e)}}class QG{constructor(e){this.occWorkerManager=e}purgeInternalEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.purgeInternalEdges",e)}unifySameDomain(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.unifySameDomain",e)}isClosed(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isClosed",e)}isConvex(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isConvex",e)}isChecked(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isChecked",e)}isFree(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isFree",e)}isInfinite(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isInfinite",e)}isModified(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isModified",e)}isLocked(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isLocked",e)}isNull(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isNull",e)}isEqual(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isEqual",e)}isNotEqual(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isNotEqual",e)}isPartner(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isPartner",e)}isSame(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isSame",e)}getOrientation(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.getOrientation",e)}getShapeType(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.getShapeType",e)}}class ZG{constructor(e){this.occWorkerManager=e}vertexFromXYZ(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.vertexFromXYZ",e)}vertexFromPoint(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.vertexFromPoint",e)}verticesFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.verticesFromPoints",e)}verticesCompoundFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.verticesCompoundFromPoints",e)}getVertices(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.getVertices",e)}getVerticesAsPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.getVerticesAsPoints",e)}verticesToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.verticesToPoints",e)}vertexToPoint(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.vertexToPoint",e)}projectPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.projectPoints",e)}}class JG{constructor(e){this.vertex=new ZG(e),this.edge=new qG(e),this.wire=new jG(e),this.face=new YG(e),this.shell=new $G(e),this.solid=new KG(e),this.compound=new XG(e),this.shape=new QG(e)}}class ez{constructor(e){this.occWorkerManager=e}transform(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.transform",e)}rotate(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotate",e)}rotateAroundCenter(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotateAroundCenter",e)}align(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.align",e)}alignAndTranslate(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.alignAndTranslate",e)}translate(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.translate",e)}scale(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scale",e)}scale3d(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scale3d",e)}mirror(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirror",e)}mirrorAlongNormal(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirrorAlongNormal",e)}transformShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.transformShapes",e)}rotateShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotateShapes",e)}rotateAroundCenterShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotateAroundCenterShapes",e)}alignShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.alignShapes",e)}alignAndTranslateShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.alignAndTranslateShapes",e)}translateShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.translateShapes",e)}scaleShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scaleShapes",e)}scale3dShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scale3dShapes",e)}mirrorShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirrorShapes",e)}mirrorAlongNormalShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirrorAlongNormalShapes",e)}}class tz{constructor(e){this.occWorkerManager=e}loft(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.loft",e)}loftAdvanced(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.loftAdvanced",e)}closestPointsBetweenTwoShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.closestPointsBetweenTwoShapes",e)}closestPointsOnShapeFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.closestPointsOnShapeFromPoints",e)}closestPointsOnShapesFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.closestPointsOnShapesFromPoints",e)}distancesToShapeFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.distancesToShapeFromPoints",e)}extrude(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.extrude",e)}extrudeShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.extrudeShapes",e)}splitShapeWithShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.splitShapeWithShapes",e)}revolve(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.revolve",e)}rotatedExtrude(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.rotatedExtrude",e)}pipe(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipe",e)}pipePolylineWireNGon(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipePolylineWireNGon",e)}pipeWiresCylindrical(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipeWiresCylindrical",e)}pipeWireCylindrical(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipeWireCylindrical",e)}offset(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.offset",e)}offsetAdv(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.offsetAdv",e)}makeThickSolidSimple(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.makeThickSolidSimple",e)}makeThickSolidByJoin(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.makeThickSolidByJoin",e)}slice(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.slice",e)}sliceInStepPattern(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.sliceInStepPattern",e)}offset3DWire(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.offset3DWire",e)}}class iz{constructor(e){this.occWorkerManager=e}union(e){return this.occWorkerManager.genericCallToWorkerPromise("booleans.union",e)}difference(e){return this.occWorkerManager.genericCallToWorkerPromise("booleans.difference",e)}intersection(e){return this.occWorkerManager.genericCallToWorkerPromise("booleans.intersection",e)}}class rz{constructor(e){this.occWorkerManager=e}geom2dEllipse(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geom2dEllipse",e)}geom2dTrimmedCurve(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geom2dTrimmedCurve",e)}geom2dSegment(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geom2dSegment",e)}get2dPointFrom2dCurveOnParam(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.get2dPointFrom2dCurveOnParam",e)}geomCircleCurve(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geomCircleCurve",e)}geomEllipseCurve(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geomEllipseCurve",e)}}class sz{constructor(e){this.occWorkerManager=e}cylindricalSurface(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.surfaces.cylindricalSurface",e)}surfaceFromFace(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.surfaces.surfaceFromFace",e)}}class nz{constructor(e){this.curves=new rz(e),this.surfaces=new sz(e)}}class oz{constructor(e){this.occWorkerManager=e}filletEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdges",e)}filletEdgesList(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesList",e)}filletEdgesListOneRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesListOneRadius",e)}filletEdgeVariableRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgeVariableRadius",e)}filletEdgesSameVariableRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesSameVariableRadius",e)}filletEdgesVariableRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesVariableRadius",e)}fillet3DWire(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.fillet3DWire",e)}chamferEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdges",e)}chamferEdgesList(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesList",e)}chamferEdgeTwoDistances(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgeTwoDistances",e)}chamferEdgesTwoDistances(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesTwoDistances",e)}chamferEdgesTwoDistancesLists(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesTwoDistancesLists",e)}chamferEdgeDistAngle(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgeDistAngle",e)}chamferEdgesDistAngle(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesDistAngle",e)}chamferEdgesDistsAngles(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesDistsAngles",e)}fillet2d(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.fillet2d",e)}filletTwoEdgesInPlaneIntoAWire(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletTwoEdgesInPlaneIntoAWire",e)}}class az{constructor(e){this.occWorkerManager=e}basicShapeRepair(e){return this.occWorkerManager.genericCallToWorkerPromise("shapeFix.basicShapeRepair",e)}fixSmallEdgeOnWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapeFix.fixSmallEdgeOnWire",e)}fixEdgeOrientationsAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapeFix.fixEdgeOrientationsAlongWire",e)}}var lz=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class hz{constructor(e){this.occWorkerManager=e,this.shapes=new JG(e),this.geom=new nz(e),this.transforms=new ez(e),this.operations=new tz(e),this.booleans=new iz(e),this.fillets=new oz(e),this.shapeFix=new az(e),this.io=new HG(e)}shapeToMesh(e){return lz(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("shapeToMesh",e)}))}shapesToMeshes(e){return lz(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("shapesToMeshes",e)}))}deleteShape(e){return lz(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("deleteShape",e)}))}deleteShapes(e){return lz(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("deleteShapes",e)}))}cleanAllCache(){return lz(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("cleanAllCache",{})}))}}var cz=function(e,t){return cz=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},cz(e,t)};function uz(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}cz(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}function dz(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],r=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function fz(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var r,s,n=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(e){s={error:e}}finally{try{r&&!r.done&&(i=n.return)&&i.call(n)}finally{if(s)throw s.error}}return o}function pz(e,t,i){if(i||2===arguments.length)for(var r,s=0,n=t.length;s0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,i=this,r=i.hasError,s=i.isStopped,n=i.observers;return r||s?bz:(this.currentObservers=null,n.push(e),new xz((function(){t.currentObservers=null,vz(n,e)})))},t.prototype._checkFinalizedStatuses=function(e){var t=this,i=t.hasError,r=t.thrownError,s=t.isStopped;i?e.error(r):s&&e.complete()},t.prototype.asObservable=function(){var e=new Hz;return e.source=this,e},t.create=function(e,t){return new Qz(e,t)},t}(Hz),Qz=function(e){function t(t,i){var r=e.call(this)||this;return r.destination=t,r.source=i,r}return uz(t,e),t.prototype.next=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===i||i.call(t,e)},t.prototype.error=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===i||i.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,i;return null!==(i=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==i?i:bz},t}($z);!function(e){e.loading="loading",e.loaded="loaded",e.initialised="initialised",e.computing="computing"}(qz||(qz={}));class Zz{constructor(){this.occWorkerState$=new $z,this.promisesMade=[]}occWorkerAlreadyInitialised(){return!!this.occWorker}setOccWorker(e){this.occWorker=e,this.occWorker.onmessage=({data:e})=>{if("occ-initialised"===e)this.occWorkerState$.next({state:qz.initialised});else if("busy"===e)this.occWorkerState$.next({state:qz.computing});else{const t=this.promisesMade.find((t=>t.uid===e.uid));t&&void 0!==e.result&&!e.error?t.resolve(e.result):e.error&&(this.errorCallback&&this.errorCallback(e.error),t.reject(e.error)),this.promisesMade=this.promisesMade.filter((t=>t.uid!==e.uid)),0===this.promisesMade.length?this.occWorkerState$.next({state:qz.loaded}):this.occWorkerState$.next({state:qz.computing})}}}cleanPromisesMade(){this.promisesMade=[]}genericCallToWorkerPromise(e,t){const i=`call${Math.random()}${Date.now()}`,r={uid:i},s=new Promise(((e,t)=>{r.resolve=e,r.reject=t}));return r.promise=s,this.promisesMade.push(r),this.occWorker.postMessage({action:{functionName:e,inputs:t},uid:i}),s}startedTheRun(){return this.genericCallToWorkerPromise("startedTheRun",{})}cleanAllCache(){return this.genericCallToWorkerPromise("cleanAllCache",{})}}!function(e){let t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m,g;!function(e){e.arc="arc",e.intersection="intersection",e.tangent="tangent"}(t=e.joinTypeEnum||(e.joinTypeEnum={})),function(e){e.skin="skin",e.pipe="pipe",e.rectoVerso="rectoVerso"}(i=e.bRepOffsetModeEnum||(e.bRepOffsetModeEnum={})),function(e){e.approxChordLength="approxChordLength",e.approxCentripetal="approxCentripetal",e.approxIsoParametric="approxIsoParametric"}(r=e.approxParametrizationTypeEnum||(e.approxParametrizationTypeEnum={})),function(e){e.outside="outside",e.inside="inside",e.middle="middle"}(s=e.directionEnum||(e.directionEnum={})),function(e){e.iges="iges",e.step="step"}(n=e.fileTypeEnum||(e.fileTypeEnum={})),function(e){e.forward="forward",e.reversed="reversed",e.internal="internal",e.external="external"}(o=e.topAbsOrientationEnum||(e.topAbsOrientationEnum={})),function(e){e.in="in",e.out="out",e.on="on",e.unknown="unknown"}(a=e.topAbsStateEnum||(e.topAbsStateEnum={})),function(e){e.unknown="unknown",e.vertex="vertex",e.edge="edge",e.wire="wire",e.face="face",e.shell="shell",e.solid="solid",e.compSolid="compSolid",e.compound="compound",e.shape="shape"}(l=e.shapeTypeEnum||(e.shapeTypeEnum={})),function(e){e.unqualified="unqualified",e.enclosing="enclosing",e.enclosed="enclosed",e.outside="outside",e.noqualifier="noqualifier"}(h=e.gccEntPositionEnum||(e.gccEntPositionEnum={})),function(e){e.keepSide1="keepSide1",e.keepSide2="keepSide2",e.all="all"}(c=e.positionResultEnum||(e.positionResultEnum={})),function(e){e.none="none",e.keepSide1="keepSide1",e.keepSide2="keepSide2"}(u=e.circleInclusionEnum||(e.circleInclusionEnum={})),function(e){e.none="none",e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(d=e.twoCircleInclusionEnum||(e.twoCircleInclusionEnum={})),function(e){e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(f=e.fourSidesStrictEnum||(e.fourSidesStrictEnum={})),function(e){e.outside="outside",e.inside="inside"}(p=e.twoSidesStrictEnum||(e.twoSidesStrictEnum={})),function(e){e.allWithAll="allWithAll",e.inOrder="inOrder",e.inOrderClosed="inOrderClosed"}(_=e.combinationCirclesForFaceEnum||(e.combinationCirclesForFaceEnum={})),function(e){e[e.curve=0]="curve",e[e.edge=1]="edge",e[e.wire=2]="wire",e[e.face=3]="face"}(m=e.typeSpecificityEnum||(e.typeSpecificityEnum={})),function(e){e.all="all",e.closest="closest",e.furthest="furthest",e.closestAndFurthest="closestAndFurthest"}(g=e.pointProjectionTypeEnum||(e.pointProjectionTypeEnum={})),e.DecomposedMeshDto=class{constructor(e,t){void 0!==e&&(this.faceList=e),void 0!==t&&(this.edgeList=t)}},e.DecomposedFaceDto=class{},e.DecomposedEdgeDto=class{},e.ShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.PointDto=class{constructor(e){this.point=[0,0,0],void 0!==e&&(this.point=e)}},e.XYZDto=class{constructor(e,t,i){void 0!==e&&(this.x=e),void 0!==t&&(this.y=t),void 0!==i&&(this.z=i)}},e.PointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.ConstraintTanLinesFromPtToCircleDto=class{constructor(e,t,i,r,s){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==i&&(this.tolerance=i),void 0!==r&&(this.positionResult=r),void 0!==s&&(this.circleRemainder=s)}},e.ConstraintTanLinesFromTwoPtsToCircleDto=class{constructor(e,t,i,r,s,n){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point1=t),void 0!==i&&(this.point1=i),void 0!==r&&(this.tolerance=r),void 0!==s&&(this.positionResult=s),void 0!==n&&(this.circleRemainder=n)}},e.ConstraintTanLinesOnTwoCirclesDto=class{constructor(e,t,i,r,s){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainders=d.none,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.tolerance=i),void 0!==r&&(this.positionResult=r),void 0!==s&&(this.circleRemainders=s)}},e.ConstraintTanCirclesOnTwoCirclesDto=class{constructor(e,t,i,r){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.tolerance=i),void 0!==r&&(this.radius=r)}},e.ConstraintTanCirclesOnCircleAndPntDto=class{constructor(e,t,i,r){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==i&&(this.tolerance=i),void 0!==r&&(this.radius=r)}},e.CurveAndSurfaceDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.surface=t)}},e.FilletTwoEdgesInPlaneDto=class{constructor(e,t,i,r,s,n){this.planeOrigin=[0,0,0],this.planeDirection=[0,1,0],this.radius=.3,this.solution=-1,void 0!==e&&(this.edge1=e),void 0!==t&&(this.edge2=t),void 0!==i&&(this.planeOrigin=i),void 0!==r&&(this.planeDirection=r),void 0!==s&&(this.radius=s),void 0!==n&&(this.solution=n)}},e.ClosestPointsOnShapeFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.SplitWireOnPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.ClosestPointsOnShapesFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shapes=e),void 0!==t&&(this.points=t)}},e.ClosestPointsBetweenTwoShapesDto=class{constructor(e,t){void 0!==e&&(this.shape1=e),void 0!==t&&(this.shape2=t)}},e.FaceFromSurfaceAndWireDto=class{constructor(e,t,i){this.inside=!0,void 0!==e&&(this.surface=e),void 0!==t&&(this.wire=t),void 0!==i&&(this.inside=i)}},e.WireOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wire=e),void 0!==t&&(this.face=t)}},e.DrawShapeDto=class{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m,g,v){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shape=e),void 0!==t&&(this.faceOpacity=t),void 0!==i&&(this.edgeOpacity=i),void 0!==r&&(this.edgeColour=r),void 0!==s&&(this.faceMaterial=s),void 0!==n&&(this.faceColour=n),void 0!==c&&(this.vertexColour=c),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==l&&(this.drawFaces=l),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==f&&(this.drawEdgeIndexes=f),void 0!==p&&(this.edgeIndexHeight=p),void 0!==_&&(this.edgeIndexColour=_),void 0!==m&&(this.drawFaceIndexes=m),void 0!==g&&(this.faceIndexHeight=g),void 0!==v&&(this.faceIndexColour=v)}},e.DrawShapesDto=class{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m,g,v){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shapes=e),void 0!==t&&(this.faceOpacity=t),void 0!==i&&(this.edgeOpacity=i),void 0!==r&&(this.edgeColour=r),void 0!==s&&(this.faceMaterial=s),void 0!==n&&(this.faceColour=n),void 0!==c&&(this.vertexColour=c),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==l&&(this.drawFaces=l),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==f&&(this.drawEdgeIndexes=f),void 0!==p&&(this.edgeIndexHeight=p),void 0!==_&&(this.edgeIndexColour=_),void 0!==m&&(this.drawFaceIndexes=m),void 0!==g&&(this.faceIndexHeight=g),void 0!==v&&(this.faceIndexColour=v)}},e.FaceSubdivisionDto=class{constructor(e,t,i,r,s,n,o,a,l){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepU=!1,this.removeStartEdgeU=!1,this.removeEndEdgeU=!1,this.shiftHalfStepV=!1,this.removeStartEdgeV=!1,this.removeEndEdgeV=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==i&&(this.nrDivisionsV=i),void 0!==r&&(this.shiftHalfStepU=r),void 0!==s&&(this.removeStartEdgeU=s),void 0!==n&&(this.removeEndEdgeU=n),void 0!==o&&(this.shiftHalfStepV=o),void 0!==a&&(this.removeStartEdgeV=a),void 0!==l&&(this.removeEndEdgeV=l)}},e.FaceSubdivisionToWiresDto=class{constructor(e,t,i,r,s,n){this.nrDivisions=10,this.isU=!0,this.shiftHalfStep=!1,this.removeStart=!1,this.removeEnd=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisions=t),void 0!==i&&(this.isU=i),void 0!==r&&(this.shiftHalfStep=r),void 0!==s&&(this.removeStart=s),void 0!==n&&(this.removeEnd=n)}},e.FaceSubdivideToRectangleWiresDto=class{constructor(e,t,i,r,s,n,o,a,l){this.nrRectanglesU=10,this.nrRectanglesV=10,this.offsetFromBorderU=0,this.offsetFromBorderV=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrRectanglesU=t),void 0!==i&&(this.nrRectanglesU=i),void 0!==r&&(this.scalePatternU=r),void 0!==s&&(this.scalePatternV=s),void 0!==n&&(this.filletPattern=n),void 0!==o&&(this.inclusionPattern=o),void 0!==a&&(this.offsetFromBorderU=a),void 0!==l&&(this.offsetFromBorderV=l)}},e.FaceSubdivideToRectangleHolesDto=class{constructor(e,t,i,r,s,n,o,a,l,h){this.nrRectanglesU=10,this.nrRectanglesV=10,this.holesToFaces=!1,this.offsetFromBorderU=0,this.offsetFromBorderV=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrRectanglesU=t),void 0!==i&&(this.nrRectanglesU=i),void 0!==r&&(this.scalePatternU=r),void 0!==s&&(this.scalePatternV=s),void 0!==n&&(this.filletPattern=n),void 0!==o&&(this.inclusionPattern=o),void 0!==a&&(this.holesToFaces=a),void 0!==l&&(this.offsetFromBorderU=l),void 0!==h&&(this.offsetFromBorderV=h)}},e.FaceSubdivisionControlledDto=class{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepNthU=0,this.shiftHalfStepUOffsetN=0,this.removeStartEdgeNthU=0,this.removeStartEdgeUOffsetN=0,this.removeEndEdgeNthU=0,this.removeEndEdgeUOffsetN=0,this.shiftHalfStepNthV=0,this.shiftHalfStepVOffsetN=0,this.removeStartEdgeNthV=0,this.removeStartEdgeVOffsetN=0,this.removeEndEdgeNthV=0,this.removeEndEdgeVOffsetN=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==i&&(this.nrDivisionsV=i),void 0!==r&&(this.shiftHalfStepNthU=r),void 0!==s&&(this.shiftHalfStepUOffsetN=s),void 0!==n&&(this.removeStartEdgeNthU=n),void 0!==o&&(this.removeStartEdgeUOffsetN=o),void 0!==a&&(this.removeEndEdgeNthU=a),void 0!==l&&(this.removeEndEdgeUOffsetN=l),void 0!==h&&(this.shiftHalfStepNthV=h),void 0!==c&&(this.shiftHalfStepVOffsetN=c),void 0!==u&&(this.removeStartEdgeNthV=u),void 0!==d&&(this.removeStartEdgeVOffsetN=d),void 0!==f&&(this.removeEndEdgeNthV=f),void 0!==p&&(this.removeEndEdgeVOffsetN=p)}},e.FaceLinearSubdivisionDto=class{constructor(e,t,i,r,s,n,o){this.isU=!0,this.param=.5,this.nrPoints=10,this.shiftHalfStep=!1,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.isU=t),void 0!==i&&(this.param=i),void 0!==r&&(this.nrPoints=r),void 0!==s&&(this.shiftHalfStep=s),void 0!==n&&(this.removeStartPoint=n),void 0!==o&&(this.removeEndPoint=o)}},e.WireAlongParamDto=class{constructor(e,t,i){this.isU=!0,this.param=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.isU=t),void 0!==i&&(this.param=i)}},e.WiresAlongParamsDto=class{constructor(e,t,i){this.isU=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.isU=t),void 0!==i&&(this.params=i)}},e.DataOnUVDto=class{constructor(e,t,i){this.paramU=.5,this.paramV=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.paramU=t),void 0!==i&&(this.paramV=i)}},e.DataOnUVsDto=class{constructor(e,t){this.paramsUV=[[.5,.5]],void 0!==e&&(this.shape=e),void 0!==t&&(this.paramsUV=t)}},e.PolygonDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolygonsDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polygons=e),void 0!==t&&(this.returnCompound=t)}},e.PolylineDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolylinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polylines=e),void 0!==t&&(this.returnCompound=t)}},e.SquareDto=class{constructor(e,t,i){this.size=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.RectangleDto=class{constructor(e,t,i,r){this.width=1,this.length=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.center=i),void 0!==r&&(this.direction=r)}},e.LPolygonDto=class{constructor(e,t,i,r,n,o,a,l){this.widthFirst=1,this.lengthFirst=2,this.widthSecond=.5,this.lengthSecond=2,this.align=s.outside,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.widthFirst=e),void 0!==t&&(this.lengthFirst=t),void 0!==i&&(this.widthSecond=i),void 0!==r&&(this.lengthSecond=r),void 0!==n&&(this.align=n),void 0!==o&&(this.rotation=o),void 0!==a&&(this.center=a),void 0!==l&&(this.direction=l)}},e.BoxDto=class{constructor(e,t,i,r){this.width=1,this.length=2,this.height=3,this.center=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.height=i),void 0!==r&&(this.center=r)}},e.CubeDto=class{constructor(e,t){this.size=1,this.center=[0,0,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t)}},e.BoxFromCornerDto=class{constructor(e,t,i,r){this.width=1,this.length=2,this.height=3,this.corner=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.height=i),void 0!==r&&(this.corner=r)}},e.SphereDto=class{constructor(e,t){this.radius=1,this.center=[0,0,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t)}},e.ConeDto=class{constructor(e,t,i,r,s,n){this.radius1=2,this.radius2=1,this.height=2,this.angle=360,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius1=e),void 0!==t&&(this.radius2=t),void 0!==i&&(this.height=i),void 0!==r&&(this.angle=r),void 0!==s&&(this.center=s),void 0!==n&&(this.direction=n)}},e.LineDto=class{constructor(e,t){this.start=[0,0,0],this.end=[0,1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.LinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.lines=e),void 0!==t&&(this.returnCompound=t)}},e.ArcEdgeTwoPointsTangentDto=class{constructor(e,t,i){this.start=[0,0,0],this.tangentVec=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.tangentVec=t),void 0!==i&&(this.end=i)}},e.ArcEdgeCircleTwoPointsDto=class{constructor(e,t,i,r){this.start=[0,0,0],this.end=[0,0,1],this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.start=t),void 0!==i&&(this.end=i),void 0!==r&&(this.sense=r)}},e.ArcEdgeCircleTwoAnglesDto=class{constructor(e,t,i,r){this.alphaAngle1=0,this.alphaAngle2=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle1=t),void 0!==i&&(this.alphaAngle2=i),void 0!==r&&(this.sense=r)}},e.ArcEdgeCirclePointAngleDto=class{constructor(e,t,i,r){this.alphaAngle=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle=t),void 0!==r&&(this.sense=r)}},e.ArcEdgeThreePointsDto=class{constructor(e,t,i){this.start=[0,0,0],this.middle=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.middle=t),void 0!==i&&(this.end=i)}},e.CylinderDto=class{constructor(e,t,i,r){this.radius=1,this.height=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.height=t),void 0!==i&&(this.center=i),void 0!==r&&(this.direction=r)}},e.CylindersOnLinesDto=class{constructor(e,t){void 0!==e&&(this.radius=e),void 0!==t&&(this.lines=t)}},e.FilletDto=class{constructor(e,t,i,r){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.radiusList=i),void 0!==r&&(this.indexes=r)}},e.FilletEdgesListDto=class{constructor(e,t,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusList=i)}},e.FilletEdgesListOneRadiusDto=class{constructor(e,t,i){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radius=i)}},e.FilletEdgeVariableRadiusDto=class{constructor(e,t,i,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.radiusList=i),void 0!==r&&(this.paramsU=r)}},e.FilletEdgesVariableRadiusDto=class{constructor(e,t,i,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusLists=i),void 0!==r&&(this.paramsULists=r)}},e.FilletEdgesSameVariableRadiusDto=class{constructor(e,t,i,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusList=i),void 0!==r&&(this.paramsU=r)}},e.Fillet3DWireDto=class{constructor(e,t,i,r,s){this.radius=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.direction=i),void 0!==r&&(this.radiusList=r),void 0!==s&&(this.indexes=s)}},e.ChamferDto=class{constructor(e,t,i,r){this.distance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.distance=t),void 0!==i&&(this.distanceList=i),void 0!==r&&(this.indexes=r)}},e.ChamferEdgesListDto=class{constructor(e,t,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.distanceList=i)}},e.ChamferEdgeDistAngleDto=class{constructor(e,t,i,r,s){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.face=i),void 0!==r&&(this.distance=r),void 0!==s&&(this.angle=s)}},e.ChamferEdgeTwoDistancesDto=class{constructor(e,t,i,r,s){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.face=i),void 0!==r&&(this.distance1=r),void 0!==s&&(this.distance2=s)}},e.ChamferEdgesTwoDistancesListsDto=class{constructor(e,t,i,r,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==r&&(this.distances1=r),void 0!==s&&(this.distances2=s)}},e.ChamferEdgesTwoDistancesDto=class{constructor(e,t,i,r,s){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==r&&(this.distance1=r),void 0!==s&&(this.distance2=s)}},e.ChamferEdgesDistsAnglesDto=class{constructor(e,t,i,r,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==r&&(this.distances=r),void 0!==s&&(this.angles=s)}},e.ChamferEdgesDistAngleDto=class{constructor(e,t,i,r,s){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==r&&(this.distance=r),void 0!==s&&(this.angle=s)}},e.BSplineDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BSplinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bSplines=e),void 0!==t&&(this.returnCompound=t)}},e.WireFromTwoCirclesTanDto=class{constructor(e,t,i,r,s){this.keepLines=p.outside,this.circleRemainders=f.outside,this.tolerance=1e-7,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.keepLines=i),void 0!==r&&(this.circleRemainders=r),void 0!==s&&(this.tolerance=s)}},e.FaceFromMultipleCircleTanWiresDto=class{constructor(e,t,i,r){this.combination=_.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.circles=e),void 0!==t&&(this.combination=t),void 0!==i&&(this.unify=i),void 0!==r&&(this.tolerance=r)}},e.FaceFromMultipleCircleTanWireCollectionsDto=class{constructor(e,t,i,r){this.combination=_.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.listsOfCircles=e),void 0!==t&&(this.combination=t),void 0!==i&&(this.unify=i),void 0!==r&&(this.tolerance=r)}},e.ZigZagBetweenTwoWiresDto=class{constructor(e,t,i,r,s,n){this.nrZigZags=20,this.divideByEqualDistance=!1,this.zigZagsPerEdge=!0,void 0!==e&&(this.wire1=e),void 0!==t&&(this.wire2=t),void 0!==i&&(this.nrZigZags=i),void 0!==r&&(this.inverse=r),void 0!==s&&(this.divideByEqualDistance=s),void 0!==n&&(this.zigZagsPerEdge=n)}},e.InterpolationDto=class{constructor(e,t,i){this.periodic=!1,this.tolerance=1e-7,void 0!==e&&(this.points=e),void 0!==t&&(this.periodic=t),void 0!==i&&(this.tolerance=i)}},e.InterpolateWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.interpolations=e),void 0!==t&&(this.returnCompound=t)}},e.BezierDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BezierWeightsDto=class{constructor(e,t,i){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.weights=t),void 0!==i&&(this.closed=i)}},e.BezierWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bezierWires=e),void 0!==t&&(this.returnCompound=t)}},e.DivideDto=class{constructor(e,t,i,r){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.removeStartPoint=i),void 0!==r&&(this.removeEndPoint=r)}},e.ProjectWireDto=class{constructor(e,t,i){this.direction=[0,1,0],void 0!==e&&(this.wire=e),void 0!==t&&(this.shape=t),void 0!==i&&(this.direction=i)}},e.ProjectPointsOnShapeDto=class{constructor(e,t,i,r){this.direction=[0,10,0],void 0!==e&&(this.points=e),void 0!==t&&(this.shape=t),void 0!==i&&(this.direction=i),void 0!==r&&(this.projectionType=r)}},e.WiresToPointsDto=class{constructor(e,t,i,r,s,n){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==i&&(this.curvatureDeflection=i),void 0!==r&&(this.minimumOfPoints=r),void 0!==s&&(this.uTolerance=s),void 0!==n&&(this.minimumLength=n)}},e.EdgesToPointsDto=class{constructor(e,t,i,r,s,n){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==i&&(this.curvatureDeflection=i),void 0!==r&&(this.minimumOfPoints=r),void 0!==s&&(this.uTolerance=s),void 0!==n&&(this.minimumLength=n)}},e.ProjectWiresDto=class{constructor(e,t,i){this.direction=[0,1,0],void 0!==e&&(this.wires=e),void 0!==t&&(this.shape=t),void 0!==i&&(this.direction=i)}},e.DivideShapesDto=class{constructor(e,t,i,r){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.removeStartPoint=i),void 0!==r&&(this.removeEndPoint=r)}},e.DataOnGeometryAtParamDto=class{constructor(e,t){this.param=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t)}},e.PointInFaceDto=class{constructor(e,t,i,r){this.tEdgeParam=.5,this.distance2DParam=.5,void 0!==e&&(this.face=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.tEdgeParam=i),void 0!==r&&(this.distance2DParam=r)}},e.PointsOnWireAtEqualLengthDto=class{constructor(e,t,i,r,s){this.length=.5,this.tryNext=!1,this.includeFirst=!1,this.includeLast=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.length=t),void 0!==i&&(this.tryNext=i),void 0!==r&&(this.includeFirst=r),void 0!==s&&(this.includeLast=s)}},e.PointsOnWireAtPatternOfLengthsDto=class{constructor(e,t,i,r,s){this.tryNext=!1,this.includeFirst=!1,this.includeLast=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.lengths=t),void 0!==i&&(this.tryNext=i),void 0!==r&&(this.includeLast=r),void 0!==s&&(this.includeLast=s)}},e.DataOnGeometryAtLengthDto=class{constructor(e,t){this.length=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.length=t)}},e.DataOnGeometryAtLengthsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.lengths=t)}},e.CircleDto=class{constructor(e,t,i){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.LoftDto=class{constructor(e,t){this.makeSolid=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t)}},e.LoftAdvancedDto=class{constructor(e,t,i,s,n,o,a,l,h,c,u,d){this.makeSolid=!1,this.closed=!1,this.periodic=!1,this.straight=!1,this.nrPeriodicSections=10,this.useSmoothing=!1,this.maxUDegree=3,this.tolerance=1e-7,this.parType=r.approxCentripetal,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t),void 0!==i&&(this.closed=i),void 0!==s&&(this.periodic=s),void 0!==n&&(this.straight=n),void 0!==o&&(this.nrPeriodicSections=o),void 0!==a&&(this.useSmoothing=a),void 0!==l&&(this.maxUDegree=l),void 0!==h&&(this.tolerance=h),void 0!==c&&(this.parType=c),void 0!==u&&(this.startVertex=u),void 0!==d&&(this.endVertex=d)}},e.OffsetDto=class{constructor(e,t,i,r){this.distance=.2,this.tolerance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.face=t),void 0!==i&&(this.distance=i),void 0!==r&&(this.tolerance=r)}},e.OffsetAdvancedDto=class{constructor(e,i,r,s,n,o){this.distance=.2,this.tolerance=.1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==i&&(this.face=i),void 0!==r&&(this.distance=r),void 0!==s&&(this.tolerance=s),void 0!==n&&(this.joinType=n),void 0!==o&&(this.removeIntEdges=o)}},e.RevolveDto=class{constructor(e,t,i,r){this.angle=360,this.direction=[0,1,0],this.copy=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.direction=i),void 0!==r&&(this.copy=r)}},e.ShapeShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.WiresOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wires=e),void 0!==t&&(this.face=t)}},e.PipeWiresCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.radius=t)}},e.PipeWireCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t)}},e.PipePolygonWireNGonDto=class{constructor(e,t,i){this.radius=.1,this.nrCorners=6,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.nrCorners=i)}},e.ExtrudeDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t)}},e.ExtrudeShapesDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.direction=t)}},e.SplitDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.UnionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.DifferenceDto=class{constructor(e,t,i){this.keepEdges=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t),void 0!==i&&(this.keepEdges=i)}},e.IntersectionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.ShapeDto=class{constructor(e){void 0!==e&&(this.shape=e)}},e.CompareShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.otherShape=t)}},e.FixSmallEdgesInWireDto=class{constructor(e,t,i){this.lockvtx=!1,this.precsmall=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.lockvtx=t),void 0!==i&&(this.precsmall=i)}},e.BasicShapeRepairDto=class{constructor(e,t,i,r){this.precision=.001,this.maxTolerance=.01,this.minTolerance=1e-4,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.maxTolerance=i),void 0!==r&&(this.minTolerance=r)}},e.FixClosedDto=class{constructor(e,t){this.precision=-.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t)}},e.ShapesWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.ShapeWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.tolerance=t)}},e.ShapeIndexDto=class{constructor(e,t){this.index=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.EdgeIndexDto=class{constructor(e,t){this.index=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.RotationExtrudeDto=class{constructor(e,t,i){this.height=1,this.angle=360,void 0!==e&&(this.shape=e),void 0!==t&&(this.height=t),void 0!==i&&(this.angle=i)}},e.ThickSolidByJoinDto=class{constructor(e,i,r,s,n,o,a,l){this.offset=1,this.tolerance=.001,this.intersection=!1,this.selfIntersection=!1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==i&&(this.shapes=i),void 0!==r&&(this.offset=r),void 0!==s&&(this.tolerance=s),void 0!==n&&(this.intersection=n),void 0!==o&&(this.selfIntersection=o),void 0!==a&&(this.joinType=a),void 0!==l&&(this.removeIntEdges=l)}},e.TransformDto=class{constructor(e,t,i,r,s){this.translation=[0,0,0],this.rotationAxis=[0,1,0],this.rotationAngle=0,this.scaleFactor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t),void 0!==i&&(this.rotationAxis=i),void 0!==r&&(this.rotationAngle=r),void 0!==s&&(this.scaleFactor=s)}},e.TransformShapesDto=class{constructor(e,t,i,r,s){this.translations=[[0,0,0]],this.rotationAxes=[[0,1,0]],this.rotationAngles=[0],this.scaleFactors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t),void 0!==i&&(this.rotationAxes=i),void 0!==r&&(this.rotationAngles=r),void 0!==s&&(this.scaleFactors=s)}},e.TranslateDto=class{constructor(e,t){this.translation=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t)}},e.TranslateShapesDto=class{constructor(e,t){this.translations=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t)}},e.AlignDto=class{constructor(e,t,i,r,s){this.fromOrigin=[0,0,0],this.fromDirection=[0,0,1],this.toOrigin=[0,1,0],this.toDirection=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.fromOrigin=t),void 0!==i&&(this.fromDirection=i),void 0!==r&&(this.toOrigin=r),void 0!==s&&(this.toDirection=s)}},e.AlignShapesDto=class{constructor(e,t,i,r,s){this.fromOrigins=[[0,0,0]],this.fromDirections=[[0,0,1]],this.toOrigins=[[0,1,0]],this.toDirections=[[0,1,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.fromOrigins=t),void 0!==i&&(this.fromDirections=i),void 0!==r&&(this.toOrigins=r),void 0!==s&&(this.toDirections=s)}},e.MirrorDto=class{constructor(e,t,i){this.origin=[0,0,0],this.direction=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.direction=i)}},e.MirrorShapesDto=class{constructor(e,t,i){this.origins=[[0,0,0]],this.directions=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==i&&(this.directions=i)}},e.MirrorAlongNormalDto=class{constructor(e,t,i){this.origin=[0,0,0],this.normal=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.normal=i)}},e.MirrorAlongNormalShapesDto=class{constructor(e,t,i){this.origins=[[0,0,0]],this.normals=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==i&&(this.normals=i)}},e.AlignAndTranslateDto=class{constructor(e,t,i){this.direction=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.center=i)}},e.UnifySameDomainDto=class{constructor(e,t,i,r){this.unifyEdges=!0,this.unifyFaces=!0,this.concatBSplines=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.unifyEdges=t),void 0!==i&&(this.unifyFaces=i),void 0!==r&&(this.concatBSplines=r)}},e.FilterFacePointsDto=class{constructor(e,t,i,r,s,n,o,a,l){this.tolerance=1e-4,this.useBndBox=!1,this.gapTolerance=.1,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==i&&(this.tolerance=i),void 0!==r&&(this.useBndBox=r),void 0!==s&&(this.gapTolerance=s),void 0!==n&&(this.keepIn=n),void 0!==o&&(this.keepOn=o),void 0!==a&&(this.keepOut=a),void 0!==l&&(this.keepUnknown=l)}},e.FilterSolidPointsDto=class{constructor(e,t,i,r,s,n,o){this.tolerance=1e-4,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==i&&(this.tolerance=i),void 0!==r&&(this.keepIn=r),void 0!==s&&(this.keepOn=s),void 0!==n&&(this.keepOut=n),void 0!==o&&(this.keepUnknown=o)}},e.AlignAndTranslateShapesDto=class{constructor(e,t,i){this.directions=[[0,1,0]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.directions=t),void 0!==i&&(this.centers=i)}},e.RotateDto=class{constructor(e,t,i){this.axis=[0,0,1],this.angle=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.angle=i)}},e.RotateAroundCenterDto=class{constructor(e,t,i,r){this.angle=0,this.center=[0,0,0],this.axis=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.center=i),void 0!==r&&(this.axis=r)}},e.RotateShapesDto=class{constructor(e,t,i){this.angles=[0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.axes=t),void 0!==i&&(this.angles=i)}},e.RotateAroundCenterShapesDto=class{constructor(e,t,i,r){this.angles=[0],this.centers=[[0,0,0]],this.axes=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.angles=t),void 0!==i&&(this.centers=i),void 0!==r&&(this.axes=r)}},e.ScaleDto=class{constructor(e,t){this.factor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.factor=t)}},e.ScaleShapesDto=class{constructor(e,t){this.factors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.factors=t)}},e.Scale3DDto=class{constructor(e,t,i){this.scale=[1,1,1],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.scale=t),void 0!==i&&(this.center=i)}},e.Scale3DShapesDto=class{constructor(e,t,i){this.scales=[[1,1,1]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.scales=t),void 0!==i&&(this.centers=i)}},e.ShapeToMeshDto=class{constructor(e,t,i){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.adjustYtoZ=i)}},e.ShapesToMeshesDto=class{constructor(e,t,i){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.adjustYtoZ=i)}},e.SaveStepDto=class{constructor(e,t,i,r){this.fileName="shape.step",this.adjustYtoZ=!1,this.tryDownload=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.adjustYtoZ=i),void 0!==r&&(this.tryDownload=r)}},e.SaveStlDto=class{constructor(e,t,i,r,s,n){this.fileName="shape.stl",this.precision=.01,this.adjustYtoZ=!1,this.tryDownload=!0,this.binary=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.precision=i),void 0!==r&&(this.adjustYtoZ=r),void 0!==s&&(this.tryDownload=s),void 0!==n&&(this.binary=n)}},e.ImportStepIgesFromTextDto=class{constructor(e,t,i){this.fileType=n.step,this.adjustZtoY=!0,void 0!==e&&(this.text=e),void 0!==t&&(this.fileType=t),void 0!==i&&(this.adjustZtoY=i)}},e.ImportStepIgesDto=class{constructor(e,t){this.adjustZtoY=!0,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.adjustZtoY=t)}},e.LoadStepOrIgesDto=class{constructor(e,t,i){this.fileName="shape.igs",this.adjustZtoY=!0,void 0!==e&&(this.filetext=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.adjustZtoY=i)}},e.CompoundShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.ThisckSolidSimpleDto=class{constructor(e,t){this.offset=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t)}},e.Offset3DWireDto=class{constructor(e,t,i){this.offset=1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t),void 0!==i&&(this.direction=i)}},e.FaceFromWireDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.planar=t)}},e.FaceFromWireOnFaceDto=class{constructor(e,t,i){this.inside=!0,void 0!==e&&(this.wire=e),void 0!==t&&(this.face=t),void 0!==i&&(this.inside=i)}},e.FacesFromWiresOnFaceDto=class{constructor(e,t,i){this.inside=!0,void 0!==e&&(this.wires=e),void 0!==t&&(this.face=t),void 0!==i&&(this.inside=i)}},e.FaceFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.FacesFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.FaceFromWiresOnFaceDto=class{constructor(e,t,i){this.inside=!0,void 0!==e&&(this.wires=e),void 0!==t&&(this.face=t),void 0!==i&&(this.inside=i)}},e.SewDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.FaceIsoCurveAtParamDto=class{constructor(e,t,i){this.dir="u",void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t),void 0!==i&&(this.dir=i)}},e.DivideFaceToUVPointsDto=class{constructor(e,t,i,r){this.nrOfPointsU=10,this.nrOfPointsV=10,this.flat=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfPointsU=t),void 0!==i&&(this.nrOfPointsV=i),void 0!==r&&(this.flat=r)}},e.Geom2dEllipseDto=class{constructor(e,t,i,r,s){this.center=[0,0],this.direction=[1,0],this.radiusMinor=1,this.radiusMajor=2,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radiusMinor=i),void 0!==r&&(this.radiusMajor=r),void 0!==s&&(this.sense=s)}},e.Geom2dCircleDto=class{constructor(e,t,i,r){this.center=[0,0],this.direction=[1,0],this.radius=1,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radius=i),void 0!==r&&(this.sense=r)}},e.ChristmasTreeDto=class{constructor(e,t,i,r,s,n,o,a,l,h){this.height=6,this.innerDist=1.5,this.outerDist=3,this.nrSkirts=5,this.trunkHeight=1,this.trunkWidth=1,this.half=!1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.innerDist=t),void 0!==i&&(this.outerDist=i),void 0!==r&&(this.nrSkirts=r),void 0!==s&&(this.trunkHeight=s),void 0!==n&&(this.trunkWidth=n),void 0!==o&&(this.half=o),void 0!==a&&(this.rotation=a),void 0!==l&&(this.origin=l),void 0!==h&&(this.direction=h)}},e.StarDto=class{constructor(e,t,i,r,s,n,o){this.center=[0,0,0],this.direction=[0,1,0],this.numRays=7,this.half=!1,void 0!==e&&(this.outerRadius=e),void 0!==t&&(this.innerRadius=t),void 0!==i&&(this.numRays=i),void 0!==r&&(this.center=r),void 0!==s&&(this.direction=s),void 0!==n&&(this.offsetOuterEdges=n),void 0!==o&&(this.half=o)}},e.ParallelogramDto=class{constructor(e,t,i,r,s,n){this.center=[0,0,0],this.direction=[0,1,0],this.aroundCenter=!0,this.width=2,this.height=1,this.angle=15,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.aroundCenter=i),void 0!==r&&(this.width=r),void 0!==s&&(this.height=s),void 0!==n&&(this.angle=n)}},e.Heart2DDto=class{constructor(e,t,i,r){this.center=[0,0,0],this.direction=[0,1,0],this.rotation=0,this.sizeApprox=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.rotation=i),void 0!==r&&(this.sizeApprox=r)}},e.NGonWireDto=class{constructor(e,t,i,r){this.center=[0,0,0],this.direction=[0,1,0],this.nrCorners=6,this.radius=1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.nrCorners=i),void 0!==r&&(this.radius=r)}},e.EllipseDto=class{constructor(e,t,i,r){this.center=[0,0,0],this.direction=[0,1,0],this.radiusMinor=1,this.radiusMajor=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radiusMinor=i),void 0!==r&&(this.radiusMajor=r)}},e.GeomCylindricalSurfaceDto=class{constructor(e,t,i){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.Geom2dTrimmedCurveDto=class{constructor(e,t,i,r,s){this.u1=0,this.u2=1,this.sense=!0,this.adjustPeriodic=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.u1=t),void 0!==i&&(this.u2=i),void 0!==r&&(this.sense=r),void 0!==s&&(this.adjustPeriodic=s)}},e.Geom2dSegmentDto=class{constructor(e,t){this.start=[0,0],this.end=[1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.SliceDto=class{constructor(e,t,i){this.step=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.step=t),void 0!==i&&(this.direction=i)}},e.SliceInStepPatternDto=class{constructor(e,t,i){this.steps=[.1,.2],this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.steps=t),void 0!==i&&(this.direction=i)}}}(Yz||(Yz={})),function(e){let t;!function(e){e.default="default",e.clearSky="clearSky",e.city="city",e.greyGradient="greyGradient"}(t=e.skyboxEnum||(e.skyboxEnum={}))}(Kz||(Kz={})),"undefined"!=typeof document&&document.currentScript&&document.currentScript.src;class Jz{constructor(e){this.context=e}create(e){const t=new hc.Pq(e.target[0],e.target[1],e.target[2]),i=new is(`arcRotateCamera${Math.random()}`,this.getRadians(e.alpha),this.getRadians(e.beta),e.radius,t,this.context.scene);void 0!==e.angularSensibilityX&&(i.angularSensibilityX=e.angularSensibilityX),void 0!==e.angularSensibilityY&&(i.angularSensibilityY=e.angularSensibilityY),void 0!==e.lowerRadiusLimit&&(i.lowerRadiusLimit=e.lowerRadiusLimit),void 0!==e.upperRadiusLimit&&(i.upperRadiusLimit=e.upperRadiusLimit),void 0!==e.lowerAlphaLimit&&(i.lowerAlphaLimit=this.getRadians(e.lowerAlphaLimit)),void 0!==e.upperAlphaLimit&&(i.upperAlphaLimit=this.getRadians(e.upperAlphaLimit)),void 0!==e.lowerBetaLimit&&(i.lowerBetaLimit=this.getRadians(e.lowerBetaLimit)),void 0!==e.upperBetaLimit&&(i.upperBetaLimit=this.getRadians(e.upperBetaLimit)),void 0!==e.panningSensibility&&(i.panningSensibility=e.panningSensibility),void 0!==e.wheelPrecision&&(i.wheelPrecision=e.wheelPrecision),void 0!==e.maxZ&&(i.maxZ=e.maxZ),i.minZ=0;const r=document.getElementById("renderCanvas");return i.attachControl(r,!0),i}getRadians(e){let t=hc.uM.FromDegrees(e).radians();return e<0&&(t=-t),t}}class eW{constructor(e){this.context=e}create(e){const t=new hc.Pq(e.position[0],e.position[1],e.position[2]),i=new es(`freeCamera${Math.random()}`,t,this.context.scene),r=new hc.Pq(e.target[0],e.target[1],e.target[2]);i.setTarget(r);const s=document.getElementById("renderCanvas");return i.attachControl(s,!0),i.minZ=0,i.maxZ=1e3,i}}class tW{constructor(e){this.context=e}create(e){const t=new hc.Pq(e.position[0],e.position[1],e.position[2]),i=new Jr(`freeCamera${Math.random()}`,t,this.context.scene),r=new hc.Pq(e.target[0],e.target[1],e.target[2]);i.setTarget(r);const s=document.getElementById("renderCanvas");return i.attachControl(s,!0),i.minZ=0,i.maxZ=1e3,i}}class iW{constructor(e){this.context=e,this.free=new eW(this.context),this.arcRotate=new Jz(this.context),this.target=new tW(this.context)}freezeProjectionMatrix(e){e.camera.freezeProjectionMatrix()}unfreezeProjectionMatrix(e){e.camera.unfreezeProjectionMatrix()}setPosition(e){const t=new hc.Pq(e.position[0],e.position[1],e.position[2]);e.camera.position=t}getPosition(e){return[e.camera.position.x,e.camera.position.y,e.camera.position.z]}setTarget(e){const t=new hc.Pq(e.target[0],e.target[1],e.target[2]);e.camera.setTarget(t)}getTarget(e){return[e.camera.target.x,e.camera.target.y,e.camera.target.z]}setSpeed(e){e.camera.speed=e.speed}getSpeed(e){return[e.camera.target.x,e.camera.target.y,e.camera.target.z]}setMinZ(e){e.camera.minZ=e.minZ}setMaxZ(e){e.camera.maxZ=e.maxZ}makeCameraOrthographic(e){e.camera.mode=rt.ORTHOGRAPHIC_CAMERA,e.camera.orthoBottom=e.orthoBottom||-1,e.camera.orthoTop=e.orthoTop||1,e.camera.orthoLeft=e.orthoLeft||-1,e.camera.orthoRight=e.orthoRight||1}makeCameraPerspective(e){e.camera.mode=rt.PERSPECTIVE_CAMERA}}class rW{constructor(e,t){this.context=e,this.color=t}create(e){const t=new Cb(e.name,this.context.scene);return t.baseColor=hc.v9.FromHexString(e.baseColor),t.metallic=e.metallic,t.roughness=e.roughness,t.alpha=e.alpha,t.backFaceCulling=e.backFaceCulling,t.zOffset=e.zOffset,t.alphaMode=1,e.emissiveColor&&(t.emissiveColor=hc.v9.FromHexString(e.emissiveColor)),t}setBaseColor(e){e.material.baseColor=hc.v9.FromHexString(e.baseColor)}setMetallic(e){e.material.metallic=e.metallic}setRoughness(e){e.material.roughness=e.roughness}setAlpha(e){e.material.alpha=e.alpha}setBackFaceCulling(e){e.material.backFaceCulling=e.backFaceCulling}setBaseTexture(e){e.material.baseTexture=e.baseTexture}getBaseColor(e){const t=e.material,i=this.context.remap(t.baseColor.r,0,1,0,255),r=this.context.remap(t.baseColor.g,0,1,0,255),s=this.context.remap(t.baseColor.b,0,1,0,255);return this.color.rgbToHex({r:i,g:r,b:s,min:0,max:255})}getMetallic(e){return e.material.metallic}getRoughness(e){return e.material.roughness}getAlpha(e){return e.material.alpha}getBackFaceCulling(e){return e.material.backFaceCulling}getBaseTexture(e){return e.material.baseTexture}}i(51314),i(65343);Cs.l.ShadersStore.cellPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nvec3 computeCustomDiffuseLighting(lightingInfo info,vec3 diffuseBase,float shadow)\n{diffuseBase=info.diffuse*shadow;\n#ifdef CELLBASIC\nfloat level=1.0;if (info.ndl<0.5)\nlevel=0.5;diffuseBase.rgb*vec3(level,level,level);\n#else\nfloat ToonThresholds[4];ToonThresholds[0]=0.95;ToonThresholds[1]=0.5;ToonThresholds[2]=0.2;ToonThresholds[3]=0.03;float ToonBrightnessLevels[5];ToonBrightnessLevels[0]=1.0;ToonBrightnessLevels[1]=0.8;ToonBrightnessLevels[2]=0.6;ToonBrightnessLevels[3]=0.35;ToonBrightnessLevels[4]=0.2;if (info.ndl>ToonThresholds[0])\n{diffuseBase.rgb*=ToonBrightnessLevels[0];}\nelse if (info.ndl>ToonThresholds[1])\n{diffuseBase.rgb*=ToonBrightnessLevels[1];}\nelse if (info.ndl>ToonThresholds[2])\n{diffuseBase.rgb*=ToonBrightnessLevels[2];}\nelse if (info.ndl>ToonThresholds[3])\n{diffuseBase.rgb*=ToonBrightnessLevels[3];}\nelse\n{diffuseBase.rgb*=ToonBrightnessLevels[4];}\n#endif\nreturn max(diffuseBase,vec3(0.2));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nlightingInfo info;vec3 diffuseBase=vec3(0.,0.,0.);float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}",i(61374);Cs.l.ShadersStore.cellVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class sW extends xn{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.NDOTL=!0,this.CUSTOMUSERLIGHTING=!0,this.CELLBASIC=!0,this.DEPTHPREPASS=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class nW extends bn{constructor(e,t){super(e,t),this.diffuseColor=new H.v9(1,1,1),this._computeHighLevel=!1,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r.effect&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new sW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(s._areTexturesDirty&&(s._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&Sn.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;s._needUVs=!0,s.DIFFUSE=!0}if(s.CELLBASIC=!this.computeHighLevel,(0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=(0,Bt.az)(n,e,s,!1,this._maxSimultaneousLights,this._disableLighting),(0,Bt.OR)(n,o,this,s,!!i),(0,Bt.qB)(e,s,!0,!0),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial();const i=new Tn;s.FOG&&i.addFallback(1,"FOG"),(0,Bt.c4)(s,i,this.maxSimultaneousLights),s.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),s.UV1&&r.push(st.R.UVKind),s.UV2&&r.push(st.R.UV2Kind),s.VERTEXCOLOR&&r.push(st.R.ColorKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="cell",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant"],c=["diffuseSampler"],u=[];(0,Ln.TV)(h),(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights-1}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._mustRebind(r,n,i)&&(this._diffuseTexture&&Sn.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),(0,Ln.gS)(this._activeEffect,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s,this._maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),super.dispose(e)}getClassName(){return"CellMaterial"}clone(e){return it.p.Clone((()=>new nW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.CellMaterial",e}static Parse(e,t,i){return it.p.Parse((()=>new nW(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.uM)("diffuseTexture")],nW.prototype,"_diffuseTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],nW.prototype,"diffuseTexture",void 0),(0,je.Cg)([(0,$e.jT)("diffuse")],nW.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.lK)("computeHighLevel")],nW.prototype,"_computeHighLevel",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],nW.prototype,"computeHighLevel",void 0),(0,je.Cg)([(0,$e.lK)("disableLighting")],nW.prototype,"_disableLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],nW.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.lK)("maxSimultaneousLights")],nW.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],nW.prototype,"maxSimultaneousLights",void 0),(0,X.Y5)("BABYLON.CellMaterial",nW);class oW{constructor(){}}class aW extends Un{AttachAfterBind(e,t){if(this._newUniformInstances)for(const e in this._newUniformInstances){const i=e.toString().split("-");"vec2"==i[0]?t.setVector2(i[1],this._newUniformInstances[e]):"vec3"==i[0]?this._newUniformInstances[e]instanceof H.v9?t.setColor3(i[1],this._newUniformInstances[e]):t.setVector3(i[1],this._newUniformInstances[e]):"vec4"==i[0]?(this._newUniformInstances[e]instanceof H.ov?t.setDirectColor4(i[1],this._newUniformInstances[e]):t.setVector4(i[1],this._newUniformInstances[e]),t.setVector4(i[1],this._newUniformInstances[e])):"mat4"==i[0]?t.setMatrix(i[1],this._newUniformInstances[e]):"float"==i[0]&&t.setFloat(i[1],this._newUniformInstances[e])}if(this._newSamplerInstances)for(const e in this._newSamplerInstances){const i=e.toString().split("-");"sampler2D"==i[0]&&this._newSamplerInstances[e].isReady&&this._newSamplerInstances[e].isReady()&&t.setTexture(i[1],this._newSamplerInstances[e])}}ReviewUniform(e,t){if("uniform"==e&&this._newUniforms)for(let e=0;e0&&n.push(...this._customAttributes),this.ReviewUniform("uniform",t),this.ReviewUniform("sampler",r);const o=this._createdShaderName;return Cl.M.ShadersStore[o+"VertexShader"]&&Cl.M.ShadersStore[o+"PixelShader"]||(Cl.M.ShadersStore[o+"VertexShader"]=this._injectCustomCode(this.VertexShader,"vertex"),Cl.M.ShadersStore[o+"PixelShader"]=this._injectCustomCode(this.FragmentShader,"fragment")),o}_injectCustomCode(e,t){const i=this._getCustomCode(t);for(const t in i){const r=i[t];if(r&&r.length>0){const i="#define "+t;e=e.replace(i,"\n"+r+"\n"+i)}}return e}_getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_BEGIN:this.CustomParts.Vertex_Begin,CUSTOM_VERTEX_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Vertex_Definitions||""),CUSTOM_VERTEX_MAIN_BEGIN:this.CustomParts.Vertex_MainBegin,CUSTOM_VERTEX_UPDATE_POSITION:this.CustomParts.Vertex_Before_PositionUpdated,CUSTOM_VERTEX_UPDATE_NORMAL:this.CustomParts.Vertex_Before_NormalUpdated,CUSTOM_VERTEX_MAIN_END:this.CustomParts.Vertex_MainEnd,CUSTOM_VERTEX_UPDATE_WORLDPOS:this.CustomParts.Vertex_After_WorldPosComputed}:{CUSTOM_FRAGMENT_BEGIN:this.CustomParts.Fragment_Begin,CUSTOM_FRAGMENT_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Fragment_Definitions||""),CUSTOM_FRAGMENT_MAIN_BEGIN:this.CustomParts.Fragment_MainBegin,CUSTOM_FRAGMENT_UPDATE_DIFFUSE:this.CustomParts.Fragment_Custom_Diffuse,CUSTOM_FRAGMENT_UPDATE_ALPHA:this.CustomParts.Fragment_Custom_Alpha,CUSTOM_FRAGMENT_BEFORE_LIGHTS:this.CustomParts.Fragment_Before_Lights,CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:this.CustomParts.Fragment_Before_FragColor,CUSTOM_FRAGMENT_MAIN_END:this.CustomParts.Fragment_MainEnd,CUSTOM_FRAGMENT_BEFORE_FOG:this.CustomParts.Fragment_Before_Fog}}constructor(e,t){super(e,t,!0),this.CustomParts=new oW,this.customShaderNameResolve=this.Builder,this.FragmentShader=Cl.M.ShadersStore.defaultPixelShader,this.VertexShader=Cl.M.ShadersStore.defaultVertexShader,aW.ShaderIndexer++,this._createdShaderName="custom_"+aW.ShaderIndexer}_afterBind(e,t=null,i){if(t){this.AttachAfterBind(e,t);try{super._afterBind(e,t,i)}catch(e){}}}AddUniform(e,t,i){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances={},this._newUniformInstances={}),i&&(-1!=t.indexOf("sampler")?this._newSamplerInstances[t+"-"+e]=i:this._newUniformInstances[t+"-"+e]=i),this._customUniform.push("uniform "+t+" "+e+";"),this._newUniforms.push(e),this}AddAttribute(e){return this._customAttributes||(this._customAttributes=[]),this._customAttributes.push(e),this}Fragment_Begin(e){return this.CustomParts.Fragment_Begin=e,this}Fragment_Definitions(e){return this.CustomParts.Fragment_Definitions=e,this}Fragment_MainBegin(e){return this.CustomParts.Fragment_MainBegin=e,this}Fragment_MainEnd(e){return this.CustomParts.Fragment_MainEnd=e,this}Fragment_Custom_Diffuse(e){return this.CustomParts.Fragment_Custom_Diffuse=e.replace("result","diffuseColor"),this}Fragment_Custom_Alpha(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this}Fragment_Before_Lights(e){return this.CustomParts.Fragment_Before_Lights=e,this}Fragment_Before_Fog(e){return this.CustomParts.Fragment_Before_Fog=e,this}Fragment_Before_FragColor(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this}Vertex_Begin(e){return this.CustomParts.Vertex_Begin=e,this}Vertex_Definitions(e){return this.CustomParts.Vertex_Definitions=e,this}Vertex_MainBegin(e){return this.CustomParts.Vertex_MainBegin=e,this}Vertex_Before_PositionUpdated(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this}Vertex_Before_NormalUpdated(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this}Vertex_After_WorldPosComputed(e){return this.CustomParts.Vertex_After_WorldPosComputed=e,this}Vertex_MainEnd(e){return this.CustomParts.Vertex_MainEnd=e,this}}aW.ShaderIndexer=1,(0,X.Y5)("BABYLON.CustomMaterial",aW);class lW{constructor(){}}class hW extends zm{AttachAfterBind(e,t){if(this._newUniformInstances)for(const e in this._newUniformInstances){const i=e.toString().split("-");"vec2"==i[0]?t.setVector2(i[1],this._newUniformInstances[e]):"vec3"==i[0]?this._newUniformInstances[e]instanceof H.v9?t.setColor3(i[1],this._newUniformInstances[e]):t.setVector3(i[1],this._newUniformInstances[e]):"vec4"==i[0]?(this._newUniformInstances[e]instanceof H.ov?t.setDirectColor4(i[1],this._newUniformInstances[e]):t.setVector4(i[1],this._newUniformInstances[e]),t.setVector4(i[1],this._newUniformInstances[e])):"mat4"==i[0]?t.setMatrix(i[1],this._newUniformInstances[e]):"float"==i[0]&&t.setFloat(i[1],this._newUniformInstances[e])}if(this._newSamplerInstances)for(const e in this._newSamplerInstances){const i=e.toString().split("-");"sampler2D"==i[0]&&this._newSamplerInstances[e].isReady&&this._newSamplerInstances[e].isReady()&&t.setTexture(i[1],this._newSamplerInstances[e])}}ReviewUniform(e,t){if("uniform"==e&&this._newUniforms)for(let e=0;e{if("vertex"===t)return e?e(t,i):i;const r=new $l(i);return r.inlineToken="#define pbr_inline",r.processCode(),e?e(t,r.code):r.code}}n&&this._customAttributes&&this._customAttributes.length>0&&n.push(...this._customAttributes),this.ReviewUniform("uniform",t),this.ReviewUniform("sampler",r);const a=this._createdShaderName;return Cl.M.ShadersStore[a+"VertexShader"]&&Cl.M.ShadersStore[a+"PixelShader"]||(Cl.M.ShadersStore[a+"VertexShader"]=this._injectCustomCode(this.VertexShader,"vertex"),Cl.M.ShadersStore[a+"PixelShader"]=this._injectCustomCode(this.FragmentShader,"fragment")),a}_injectCustomCode(e,t){const i=this._getCustomCode(t);for(const t in i){const r=i[t];if(r&&r.length>0){const i="#define "+t;e=e.replace(i,"\n"+r+"\n"+i)}}return e}_getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_BEGIN:this.CustomParts.Vertex_Begin,CUSTOM_VERTEX_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Vertex_Definitions||""),CUSTOM_VERTEX_MAIN_BEGIN:this.CustomParts.Vertex_MainBegin,CUSTOM_VERTEX_UPDATE_POSITION:this.CustomParts.Vertex_Before_PositionUpdated,CUSTOM_VERTEX_UPDATE_NORMAL:this.CustomParts.Vertex_Before_NormalUpdated,CUSTOM_VERTEX_MAIN_END:this.CustomParts.Vertex_MainEnd,CUSTOM_VERTEX_UPDATE_WORLDPOS:this.CustomParts.Vertex_After_WorldPosComputed}:{CUSTOM_FRAGMENT_BEGIN:this.CustomParts.Fragment_Begin,CUSTOM_FRAGMENT_MAIN_BEGIN:this.CustomParts.Fragment_MainBegin,CUSTOM_FRAGMENT_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Fragment_Definitions||""),CUSTOM_FRAGMENT_UPDATE_ALBEDO:this.CustomParts.Fragment_Custom_Albedo,CUSTOM_FRAGMENT_UPDATE_ALPHA:this.CustomParts.Fragment_Custom_Alpha,CUSTOM_FRAGMENT_BEFORE_LIGHTS:this.CustomParts.Fragment_Before_Lights,CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS:this.CustomParts.Fragment_Custom_MetallicRoughness,CUSTOM_FRAGMENT_UPDATE_MICROSURFACE:this.CustomParts.Fragment_Custom_MicroSurface,CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:this.CustomParts.Fragment_Before_FinalColorComposition,CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:this.CustomParts.Fragment_Before_FragColor,CUSTOM_FRAGMENT_MAIN_END:this.CustomParts.Fragment_MainEnd,CUSTOM_FRAGMENT_BEFORE_FOG:this.CustomParts.Fragment_Before_Fog}}constructor(e,t){super(e,t,!0),this.CustomParts=new lW,this.customShaderNameResolve=this.Builder,this.FragmentShader=Cl.M.ShadersStore.pbrPixelShader,this.VertexShader=Cl.M.ShadersStore.pbrVertexShader,this.FragmentShader=this.FragmentShader.replace(/#include/g,Cl.M.IncludesShadersStore.pbrBlockAlbedoOpacity),this.FragmentShader=this.FragmentShader.replace(/#include/g,Cl.M.IncludesShadersStore.pbrBlockReflectivity),this.FragmentShader=this.FragmentShader.replace(/#include/g,Cl.M.IncludesShadersStore.pbrBlockFinalColorComposition),hW.ShaderIndexer++,this._createdShaderName="custompbr_"+hW.ShaderIndexer}_afterBind(e,t=null,i){if(t){this.AttachAfterBind(e,t);try{super._afterBind(e,t,i)}catch(e){}}}AddUniform(e,t,i){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances={},this._newUniformInstances={}),i&&(-1!=t.indexOf("sampler")?this._newSamplerInstances[t+"-"+e]=i:this._newUniformInstances[t+"-"+e]=i),this._customUniform.push("uniform "+t+" "+e+";"),this._newUniforms.push(e),this}AddAttribute(e){return this._customAttributes||(this._customAttributes=[]),this._customAttributes.push(e),this}Fragment_Begin(e){return this.CustomParts.Fragment_Begin=e,this}Fragment_Definitions(e){return this.CustomParts.Fragment_Definitions=e,this}Fragment_MainBegin(e){return this.CustomParts.Fragment_MainBegin=e,this}Fragment_Custom_Albedo(e){return this.CustomParts.Fragment_Custom_Albedo=e.replace("result","surfaceAlbedo"),this}Fragment_Custom_Alpha(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this}Fragment_Before_Lights(e){return this.CustomParts.Fragment_Before_Lights=e,this}Fragment_Custom_MetallicRoughness(e){return this.CustomParts.Fragment_Custom_MetallicRoughness=e,this}Fragment_Custom_MicroSurface(e){return this.CustomParts.Fragment_Custom_MicroSurface=e,this}Fragment_Before_Fog(e){return this.CustomParts.Fragment_Before_Fog=e,this}Fragment_Before_FinalColorComposition(e){return this.CustomParts.Fragment_Before_FinalColorComposition=e,this}Fragment_Before_FragColor(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this}Fragment_MainEnd(e){return this.CustomParts.Fragment_MainEnd=e,this}Vertex_Begin(e){return this.CustomParts.Vertex_Begin=e,this}Vertex_Definitions(e){return this.CustomParts.Vertex_Definitions=e,this}Vertex_MainBegin(e){return this.CustomParts.Vertex_MainBegin=e,this}Vertex_Before_PositionUpdated(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this}Vertex_Before_NormalUpdated(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this}Vertex_After_WorldPosComputed(e){return this.CustomParts.Vertex_After_WorldPosComputed=e,this}Vertex_MainEnd(e){return this.CustomParts.Vertex_MainEnd=e,this}}hW.ShaderIndexer=1,(0,X.Y5)("BABYLON.PBRCustomMaterial",hW);Cs.l.ShadersStore.firePixelShader="precision highp float;uniform vec4 vEyePosition;varying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\nuniform sampler2D distortionSampler;uniform sampler2D opacitySampler;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;varying vec2 vDistortionCoords2;varying vec2 vDistortionCoords3;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nvec4 bx2(vec4 x)\n{return vec4(2.0)*x-vec4(1.0);}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);float alpha=1.0;\n#ifdef DIFFUSE\nconst float distortionAmount0 =0.092;const float distortionAmount1 =0.092;const float distortionAmount2 =0.092;vec2 heightAttenuation=vec2(0.3,0.39);vec4 noise0=texture2D(distortionSampler,vDistortionCoords1);vec4 noise1=texture2D(distortionSampler,vDistortionCoords2);vec4 noise2=texture2D(distortionSampler,vDistortionCoords3);vec4 noiseSum=bx2(noise0)*distortionAmount0+bx2(noise1)*distortionAmount1+bx2(noise2)*distortionAmount2;vec4 perturbedBaseCoords=vec4(vDiffuseUV,0.0,1.0)+noiseSum*(vDiffuseUV.y*heightAttenuation.x+heightAttenuation.y);vec4 opacityColor=texture2D(opacitySampler,perturbedBaseCoords.xy);\n#ifdef ALPHATEST\nif (opacityColor.r<0.1)\ndiscard;\n#endif\n#include\nbaseColor=texture2D(diffuseSampler,perturbedBaseCoords.xy)*2.0;baseColor*=opacityColor;baseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(1.0,1.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec4 color=vec4(baseColor.rgb,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Cs.l.ShadersStore.fireVertexShader="precision highp float;attribute vec3 position;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\nuniform float time;uniform float speed;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;varying vec2 vDistortionCoords2;varying vec2 vDistortionCoords3;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef DIFFUSE\nvDiffuseUV=uv;vDiffuseUV.y-=0.2;\n#endif\n#include\n#include\n#include\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#ifdef DIFFUSE\nvec3 layerSpeed=vec3(-0.2,-0.52,-0.1)*speed;vDistortionCoords1.x=uv.x;vDistortionCoords1.y=uv.y+layerSpeed.x*time/1000.0;vDistortionCoords2.x=uv.x;vDistortionCoords2.y=uv.y+layerSpeed.y*time/1000.0;vDistortionCoords3.x=uv.x;vDistortionCoords3.y=uv.y+layerSpeed.z*time/1000.0;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class cW extends xn{constructor(){super(),this.DIFFUSE=!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.POINTSIZE=!1,this.FOG=!1,this.UV1=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.BonesPerMesh=0,this.NUM_BONE_INFLUENCERS=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class uW extends bn{constructor(e,t){super(e,t),this.diffuseColor=new H.v9(1,1,1),this.speed=1,this._scaledDiffuse=new H.v9,this._lastTime=0}needAlphaBlending(){return!1}needAlphaTesting(){return!0}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new cW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(s._areTexturesDirty&&(s._needUVs=!1,this._diffuseTexture&&Sn.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;s._needUVs=!0,s.DIFFUSE=!0}if(s.ALPHATEST=!!this._opacityTexture,s._areMiscDirty&&(s.POINTSIZE=this.pointsCloud||n.forcePointsCloud,s.FOG=n.fogEnabled&&e.applyFog&&n.fogMode!==oi.Z.FOGMODE_NONE&&this.fogEnabled,s.LOGARITHMICDEPTH=this._useLogarithmicDepth),(0,Bt.OR)(n,o,this,s,!!i),(0,Bt.qB)(e,s,!1,!0),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial();const i=new Tn;s.FOG&&i.addFallback(1,"FOG"),s.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.UV1&&r.push(st.R.UVKind),s.VERTEXCOLOR&&r.push(st.R.ColorKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="fire",l=["world","view","viewProjection","vEyePosition","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant","time","speed"];(0,Ln.TV)(l);const h=s.toString();t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:l,uniformBuffersNames:[],samplers:["diffuseSampler","distortionSampler","opacitySampler"],defines:h,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:null,maxSimultaneousLights:4,transformFeedbackVaryings:null},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._mustRebind(r,n,i)&&(this._diffuseTexture&&Sn.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix()),this._activeEffect.setTexture("distortionSampler",this._distortionTexture),this._activeEffect.setTexture("opacitySampler",this._opacityTexture)),(0,Ln.gS)(this._activeEffect,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._lastTime+=r.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime),this._activeEffect.setFloat("speed",this.speed),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._distortionTexture&&this._distortionTexture.animations&&this._distortionTexture.animations.length>0&&e.push(this._distortionTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._distortionTexture&&e.push(this._distortionTexture),this._opacityTexture&&e.push(this._opacityTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e||this._distortionTexture===e||this._opacityTexture===e}getClassName(){return"FireMaterial"}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),this._distortionTexture&&this._distortionTexture.dispose(),super.dispose(e)}clone(e){return it.p.Clone((()=>new uW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FireMaterial",e.diffuseColor=this.diffuseColor.asArray(),e.speed=this.speed,this._diffuseTexture&&(e._diffuseTexture=this._diffuseTexture.serialize()),this._distortionTexture&&(e._distortionTexture=this._distortionTexture.serialize()),this._opacityTexture&&(e._opacityTexture=this._opacityTexture.serialize()),e}static Parse(e,t,i){const r=new uW(e.name,t);return r.diffuseColor=H.v9.FromArray(e.diffuseColor),r.speed=e.speed,r.alpha=e.alpha,r.id=e.id,Ge.Y.AddTagsTo(r,e.tags),r.backFaceCulling=e.backFaceCulling,r.wireframe=e.wireframe,e._diffuseTexture&&(r._diffuseTexture=vi.g.Parse(e._diffuseTexture,t,i)),e._distortionTexture&&(r._distortionTexture=vi.g.Parse(e._distortionTexture,t,i)),e._opacityTexture&&(r._opacityTexture=vi.g.Parse(e._opacityTexture,t,i)),r}}(0,je.Cg)([(0,$e.uM)("diffuseTexture")],uW.prototype,"_diffuseTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],uW.prototype,"diffuseTexture",void 0),(0,je.Cg)([(0,$e.uM)("distortionTexture")],uW.prototype,"_distortionTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],uW.prototype,"distortionTexture",void 0),(0,je.Cg)([(0,$e.uM)("opacityTexture")],uW.prototype,"_opacityTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],uW.prototype,"opacityTexture",void 0),(0,je.Cg)([(0,$e.jT)("diffuse")],uW.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.lK)()],uW.prototype,"speed",void 0),(0,X.Y5)("BABYLON.FireMaterial",uW);Cs.l.ShadersStore.furPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;uniform vec4 furColor;uniform float furLength;varying vec3 vPositionW;varying float vfur_length;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef HIGHLEVEL\nuniform float furOffset;uniform float furOcclusion;uniform sampler2D furTexture;varying vec2 vFurUV;\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#include\n#include\nfloat Rand(vec3 rv) {float x=dot(rv,vec3(12.9898,78.233,24.65487));return fract(sin(x)*43758.5453);}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=furColor;vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor*=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef HIGHLEVEL\nvec4 furTextureColor=texture2D(furTexture,vec2(vFurUV.x,vFurUV.y));if (furTextureColor.a<=0.0 || furTextureColor.g[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase.rgb*baseColor.rgb,0.0,1.0);\n#ifdef HIGHLEVEL\nvec4 color=vec4(finalDiffuse,alpha);\n#else\nfloat r=vfur_length/furLength*0.5;vec4 color=vec4(finalDiffuse*(0.5+r),alpha);\n#endif\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Cs.l.ShadersStore.furVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\nuniform float furLength;uniform float furAngle;\n#ifdef HIGHLEVEL\nuniform float furOffset;uniform vec3 furGravity;uniform float furTime;uniform float furSpacing;uniform float furDensity;\n#endif\n#ifdef HEIGHTMAP\nuniform sampler2D heightTexture;\n#endif\n#ifdef HIGHLEVEL\nvarying vec2 vFurUV;\n#endif\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\nvarying float vfur_length;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nfloat Rand(vec3 rv) {float x=dot(rv,vec3(12.9898,78.233,24.65487));return fract(sin(x)*43758.5453);}\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nfloat r=Rand(position);\n#ifdef HEIGHTMAP\n#if __VERSION__>100\nvfur_length=furLength*texture(heightTexture,uv).x;\n#else\nvfur_length=furLength*texture2D(heightTexture,uv).r;\n#endif\n#else \nvfur_length=(furLength*r);\n#endif\nvec3 tangent1=vec3(normal.y,-normal.x,0);vec3 tangent2=vec3(-normal.z,0,normal.x);r=Rand(tangent1*r);float J=(2.0+4.0*r);r=Rand(tangent2*r);float K=(2.0+2.0*r);tangent1=tangent1*J+tangent2*K;tangent1=normalize(tangent1);vec3 newPosition=position+normal*vfur_length*cos(furAngle)+tangent1*vfur_length*sin(furAngle);\n#ifdef HIGHLEVEL\nvec3 forceDirection=vec3(0.0,0.0,0.0);forceDirection.x=sin(furTime+position.x*0.05)*0.2;forceDirection.y=cos(furTime*0.7+position.y*0.04)*0.2;forceDirection.z=sin(furTime*0.7+position.z*0.04)*0.2;vec3 displacement=vec3(0.0,0.0,0.0);displacement=furGravity+forceDirection;float displacementFactor=pow(furOffset,3.0);vec3 aNormal=normal;aNormal.xyz+=displacement*displacementFactor;newPosition=vec3(newPosition.x,newPosition.y,newPosition.z)+(normalize(aNormal)*furOffset*furSpacing);\n#endif\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\ngl_Position=viewProjection*finalWorld*vec4(newPosition,1.0);vec4 worldPos=finalWorld*vec4(newPosition,1.0);vPositionW=vec3(worldPos);\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#ifdef HIGHLEVEL\nvFurUV=vDiffuseUV*furDensity;\n#endif\n#else\n#ifdef HIGHLEVEL\nvFurUV=uv*furDensity;\n#endif\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class dW extends xn{constructor(){super(),this.DIFFUSE=!1,this.HEIGHTMAP=!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.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.HIGHLEVEL=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class fW extends bn{constructor(e,t){super(e,t),this.diffuseColor=new H.v9(1,1,1),this.furLength=1,this.furAngle=0,this.furColor=new H.v9(.44,.21,.02),this.furOffset=0,this.furSpacing=12,this.furGravity=new W.Pq(0,0,0),this.furSpeed=100,this.furDensity=20,this.furOcclusion=0,this._disableLighting=!1,this._maxSimultaneousLights=4,this.highLevelFur=!0,this._furTime=0}get furTime(){return this._furTime}set furTime(e){this._furTime=e}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}updateFur(){for(let e=1;e0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),s.UV1&&r.push(st.R.UVKind),s.UV2&&r.push(st.R.UV2Kind),s.VERTEXCOLOR&&r.push(st.R.ColorKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="fur",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant","furLength","furAngle","furColor","furOffset","furGravity","furTime","furSpacing","furDensity","furOcclusion"];(0,Ln.TV)(h);const c=["diffuseSampler","heightTexture","furTexture"],u=[];(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._mustRebind(r,n,i)&&(this._diffuseTexture&&Sn.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),this._heightTexture&&this._activeEffect.setTexture("heightTexture",this._heightTexture),(0,Ln.gS)(this._activeEffect,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._activeEffect.setFloat("furLength",this.furLength),this._activeEffect.setFloat("furAngle",this.furAngle),this._activeEffect.setColor4("furColor",this.furColor,1),this.highLevelFur&&(this._activeEffect.setVector3("furGravity",this.furGravity),this._activeEffect.setFloat("furOffset",this.furOffset),this._activeEffect.setFloat("furSpacing",this.furSpacing),this._activeEffect.setFloat("furDensity",this.furDensity),this._activeEffect.setFloat("furOcclusion",this.furOcclusion),this._furTime+=this.getScene().getEngine().getDeltaTime()/this.furSpeed,this._activeEffect.setFloat("furTime",this._furTime),this._activeEffect.setTexture("furTexture",this.furTexture)),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.heightTexture&&this.heightTexture.animations&&this.heightTexture.animations.length>0&&e.push(this.heightTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._heightTexture&&e.push(this._heightTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e||this._heightTexture===e}dispose(e){if(this.diffuseTexture&&this.diffuseTexture.dispose(),this._meshes)for(let t=1;tnew fW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FurMaterial",this._meshes&&(e.sourceMeshName=this._meshes[0].name,e.quality=this._meshes.length),e}getClassName(){return"FurMaterial"}static Parse(e,t,i){const r=it.p.Parse((()=>new fW(e.name,t)),e,t,i);return e.sourceMeshName&&r.highLevelFur&&t.executeWhenReady((()=>{const i=t.getMeshByName(e.sourceMeshName);if(i){const s=fW.GenerateTexture("Fur Texture",t);r.furTexture=s,fW.FurifyMesh(i,e.quality)}})),r}static GenerateTexture(e,t){const i=new Gn("FurTexture "+e,256,t,!0),r=i.getContext();for(let e=0;e<2e4;++e)r.fillStyle="rgba(255, "+Math.floor(255*Math.random())+", "+Math.floor(255*Math.random())+", 1)",r.fillRect(Math.random()*i.getSize().width,Math.random()*i.getSize().height,2,2);return i.update(!1),i.wrapU=vi.g.WRAP_ADDRESSMODE,i.wrapV=vi.g.WRAP_ADDRESSMODE,i}static FurifyMesh(e,t){const i=[e],r=e.material;let s;if(!(r instanceof fW))throw"The material of the source mesh must be a Fur Material";for(s=1;s0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),s.UV1&&r.push(st.R.UVKind),s.UV2&&r.push(st.R.UV2Kind),s.VERTEXCOLOR&&r.push(st.R.ColorKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="gradient",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","logarithmicDepthConstant","topColor","bottomColor","offset","smoothness","scale"];(0,Ln.TV)(h);const c=[],u=[];(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:4}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,n),this._mustRebind(r,n,i)&&((0,Ln.gS)(n,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),r.lightsEnabled&&!this.disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._activeEffect.setColor4("topColor",this.topColor,this.topColorAlpha),this._activeEffect.setColor4("bottomColor",this.bottomColor,this.bottomColorAlpha),this._activeEffect.setFloat("offset",this.offset),this._activeEffect.setFloat("scale",this.scale),this._activeEffect.setFloat("smoothness",this.smoothness),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return it.p.Clone((()=>new _W(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GradientMaterial",e}getClassName(){return"GradientMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new _W(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.lK)("maxSimultaneousLights")],_W.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],_W.prototype,"maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.jT)()],_W.prototype,"topColor",void 0),(0,je.Cg)([(0,$e.lK)()],_W.prototype,"topColorAlpha",void 0),(0,je.Cg)([(0,$e.jT)()],_W.prototype,"bottomColor",void 0),(0,je.Cg)([(0,$e.lK)()],_W.prototype,"bottomColorAlpha",void 0),(0,je.Cg)([(0,$e.lK)()],_W.prototype,"offset",void 0),(0,je.Cg)([(0,$e.lK)()],_W.prototype,"scale",void 0),(0,je.Cg)([(0,$e.lK)()],_W.prototype,"smoothness",void 0),(0,je.Cg)([(0,$e.lK)("disableLighting")],_W.prototype,"_disableLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],_W.prototype,"disableLighting",void 0),(0,X.Y5)("BABYLON.GradientMaterial",_W);Cs.l.ShadersStore.gridPixelShader="#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;uniform float visibility;uniform vec3 mainColor;uniform vec3 lineColor;uniform vec4 gridControl;uniform vec3 gridOffset;varying vec3 vPosition;varying vec3 vNormal;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#ifdef OPACITY\nvarying vec2 vOpacityUV;uniform sampler2D opacitySampler;uniform vec2 vOpacityInfos;\n#endif\nfloat getDynamicVisibility(float position) {float majorGridFrequency=gridControl.y;if (floor(position+0.5)==floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{return 1.0;}\nreturn gridControl.z;}\nfloat getAnisotropicAttenuation(float differentialLength) {const float maxNumberOfLines=10.0;return clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);}\nfloat isPointOnLine(float position,float differentialLength) {float fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \n#ifdef ANTIALIAS\nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);float result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result;\n#else\nreturn abs(fractionPartOfPosition)\nfloat gridRatio=gridControl.x;vec3 gridPos=(vPosition+gridOffset.xyz)/gridRatio;float x=contributionOnAxis(gridPos.x);float y=contributionOnAxis(gridPos.y);float z=contributionOnAxis(gridPos.z);vec3 normal=normalize(vNormal);x*=normalImpactOnAxis(normal.x);y*=normalImpactOnAxis(normal.y);z*=normalImpactOnAxis(normal.z);\n#ifdef MAX_LINE\nfloat grid=clamp(max(max(x,y),z),0.,1.);\n#else\nfloat grid=clamp(x+y+z,0.,1.);\n#endif\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include\n#endif\nfloat opacity=1.0;\n#ifdef TRANSPARENT\nopacity=clamp(grid,0.08,gridControl.w*grid);\n#endif\n#ifdef OPACITY\nopacity*=texture2D(opacitySampler,vOpacityUV).a;\n#endif\ngl_FragColor=vec4(color.rgb,opacity*visibility);\n#ifdef TRANSPARENT\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Cs.l.ShadersStore.gridVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#include\nuniform mat4 projection;uniform mat4 view;varying vec3 vPosition;varying vec3 vNormal;\n#include\n#include\n#ifdef OPACITY\nvarying vec2 vOpacityUV;uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#include\nvec4 cameraSpacePosition=view*worldPos;gl_Position=projection*cameraSpacePosition;\n#ifdef OPACITY\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\nif (vOpacityInfos.x==0.)\n{vOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));}\nelse\n{vOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));}\n#endif \n#include\n#include\nvPosition=position;vNormal=normal;\n#define CUSTOM_VERTEX_MAIN_END\n}";class mW extends xn{constructor(){super(),this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.OPACITY=!1,this.ANTIALIAS=!1,this.TRANSPARENT=!1,this.FOG=!1,this.PREMULTIPLYALPHA=!1,this.MAX_LINE=!1,this.UV1=!1,this.UV2=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class gW extends bn{constructor(e,t){super(e,t),this.mainColor=H.v9.Black(),this.lineColor=H.v9.Teal(),this.gridRatio=1,this.gridOffset=W.Pq.Zero(),this.majorUnitFrequency=10,this.minorUnitVisibility=.33,this.opacity=1,this.antialias=!0,this.preMultiplyAlpha=!1,this.useMaxLine=!1,this._gridControl=new W.IU(this.gridRatio,this.majorUnitFrequency,this.minorUnitVisibility,this.opacity)}needAlphaBlending(){return this.opacity<1||this._opacityTexture&&this._opacityTexture.isReady()}needAlphaBlendingForMesh(e){return e.visibility<1||this.needAlphaBlending()}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r.effect&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new mW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;if(s.TRANSPARENT!==this.opacity<1&&(s.TRANSPARENT=!s.TRANSPARENT,s.markAsUnprocessed()),s.PREMULTIPLYALPHA!=this.preMultiplyAlpha&&(s.PREMULTIPLYALPHA=!s.PREMULTIPLYALPHA,s.markAsUnprocessed()),s.MAX_LINE!==this.useMaxLine&&(s.MAX_LINE=!s.MAX_LINE,s.markAsUnprocessed()),s.ANTIALIAS!==this.antialias&&(s.ANTIALIAS=!s.ANTIALIAS,s.markAsUnprocessed()),s._areTexturesDirty&&(s._needUVs=!1,n.texturesEnabled&&this._opacityTexture&&Sn.OpacityTextureEnabled)){if(!this._opacityTexture.isReady())return!1;s._needUVs=!0,s.OPACITY=!0}if((0,Bt.fm)(e,n,this._useLogarithmicDepth,!1,this.fogEnabled,!1,s),(0,Bt.OR)(n,n.getEngine(),this,s,!!i),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial(),(0,Bt.qB)(e,s,!1,!1);const i=[st.R.PositionKind,st.R.NormalKind];s.UV1&&i.push(st.R.UVKind),s.UV2&&i.push(st.R.UV2Kind),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess,(0,Bt.ER)(i,s);const r=["projection","mainColor","lineColor","gridControl","gridOffset","vFogInfos","vFogColor","world","view","opacityMatrix","vOpacityInfos","visibility","logarithmicDepthConstant"],o=s.toString();(0,Ln.TV)(r),t.setEffect(n.getEngine().createEffect("grid",i,r,["opacitySampler"],o,void 0,this.onCompiled,this.onError),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,this._activeEffect.setFloat("visibility",t.visibility),s.INSTANCES&&!s.THIN_INSTANCE||this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("view",r.getViewMatrix()),this._activeEffect.setMatrix("projection",r.getProjectionMatrix()),this._mustRebind(r,n,i)&&(this._activeEffect.setColor3("mainColor",this.mainColor),this._activeEffect.setColor3("lineColor",this.lineColor),this._activeEffect.setVector3("gridOffset",this.gridOffset),this._gridControl.x=this.gridRatio,this._gridControl.y=Math.round(this.majorUnitFrequency),this._gridControl.z=this.minorUnitVisibility,this._gridControl.w=this.opacity,this._activeEffect.setVector4("gridControl",this._gridControl),this._opacityTexture&&Sn.OpacityTextureEnabled&&(this._activeEffect.setTexture("opacitySampler",this._opacityTexture),this._activeEffect.setFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),this._activeEffect.setMatrix("opacityMatrix",this._opacityTexture.getTextureMatrix())),(0,Ln.gS)(n,this,r),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r)),(0,Bt.Yy)(r,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}dispose(e){super.dispose(e)}clone(e){return it.p.Clone((()=>new gW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GridMaterial",e}getClassName(){return"GridMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new gW(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.jT)()],gW.prototype,"mainColor",void 0),(0,je.Cg)([(0,$e.jT)()],gW.prototype,"lineColor",void 0),(0,je.Cg)([(0,$e.lK)()],gW.prototype,"gridRatio",void 0),(0,je.Cg)([(0,$e.P_)()],gW.prototype,"gridOffset",void 0),(0,je.Cg)([(0,$e.lK)()],gW.prototype,"majorUnitFrequency",void 0),(0,je.Cg)([(0,$e.lK)()],gW.prototype,"minorUnitVisibility",void 0),(0,je.Cg)([(0,$e.lK)()],gW.prototype,"opacity",void 0),(0,je.Cg)([(0,$e.lK)()],gW.prototype,"antialias",void 0),(0,je.Cg)([(0,$e.lK)()],gW.prototype,"preMultiplyAlpha",void 0),(0,je.Cg)([(0,$e.lK)()],gW.prototype,"useMaxLine",void 0),(0,je.Cg)([(0,$e.uM)("opacityTexture")],gW.prototype,"_opacityTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],gW.prototype,"opacityTexture",void 0),(0,X.Y5)("BABYLON.GridMaterial",gW);Cs.l.ShadersStore.lavaPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;uniform float time;uniform float speed;uniform float movingSpeed;uniform vec3 fogColor;uniform sampler2D noiseTexture;uniform float fogDensity;varying float noise;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include\n#include\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nfloat random( vec3 scale,float seed ){return fract( sin( dot( gl_FragCoord.xyz+seed,scale ) )*43758.5453+seed ) ;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nvec4 noiseTex=texture2D( noiseTexture,vDiffuseUV );vec2 T1=vDiffuseUV+vec2( 1.5,-1.5 )*time *0.02;vec2 T2=vDiffuseUV+vec2( -0.5,2.0 )*time*0.01*speed;T1.x+=noiseTex.x*2.0;T1.y+=noiseTex.y*2.0;T2.x-=noiseTex.y*0.2+time*0.001*movingSpeed;T2.y+=noiseTex.z*0.2+time*0.002*movingSpeed;float p=texture2D( noiseTexture,T1*3.0 ).a;vec4 lavaColor=texture2D( diffuseSampler,T2*4.0);vec4 temp=lavaColor*( vec4( p,p,p,p )*2. )+( lavaColor*lavaColor-0.1 );baseColor=temp;float depth=gl_FragCoord.z*4.0;const float LOG2=1.442695;float fogFactor=exp2(-fogDensity*fogDensity*depth*depth*LOG2 );fogFactor=1.0-clamp( fogFactor,0.0,1.0 );baseColor=mix( baseColor,vec4( fogColor,baseColor.w ),fogFactor );diffuseColor=baseColor.rgb;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#include[0]\n#include[1]\n#include[2]\n#include[3]\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Cs.l.ShadersStore.lavaVertexShader="precision highp float;uniform float time;uniform float lowFrequencySpeed;varying float noise;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n/* NOISE FUNCTIONS */\nvec3 mod289(vec3 x)\n{return x-floor(x*(1.0/289.0))*289.0;}\nvec4 mod289(vec4 x)\n{return x-floor(x*(1.0/289.0))*289.0;}\nvec4 permute(vec4 x)\n{return mod289(((x*34.0)+1.0)*x);}\nvec4 taylorInvSqrt(vec4 r)\n{return 1.79284291400159-0.85373472095314*r;}\nvec3 fade(vec3 t) {return t*t*t*(t*(t*6.0-15.0)+10.0);}\nfloat pnoise(vec3 P,vec3 rep)\n{vec3 Pi0=mod(floor(P),rep); \nvec3 Pi1=mod(Pi0+vec3(1.0),rep); \nPi0=mod289(Pi0);Pi1=mod289(Pi1);vec3 Pf0=fract(P); \nvec3 Pf1=Pf0-vec3(1.0); \nvec4 ix=vec4(Pi0.x,Pi1.x,Pi0.x,Pi1.x);vec4 iy=vec4(Pi0.yy,Pi1.yy);vec4 iz0=Pi0.zzzz;vec4 iz1=Pi1.zzzz;vec4 ixy=permute(permute(ix)+iy);vec4 ixy0=permute(ixy+iz0);vec4 ixy1=permute(ixy+iz1);vec4 gx0=ixy0*(1.0/7.0);vec4 gy0=fract(floor(gx0)*(1.0/7.0))-0.5;gx0=fract(gx0);vec4 gz0=vec4(0.5)-abs(gx0)-abs(gy0);vec4 sz0=step(gz0,vec4(0.0));gx0-=sz0*(step(0.0,gx0)-0.5);gy0-=sz0*(step(0.0,gy0)-0.5);vec4 gx1=ixy1*(1.0/7.0);vec4 gy1=fract(floor(gx1)*(1.0/7.0))-0.5;gx1=fract(gx1);vec4 gz1=vec4(0.5)-abs(gx1)-abs(gy1);vec4 sz1=step(gz1,vec4(0.0));gx1-=sz1*(step(0.0,gx1)-0.5);gy1-=sz1*(step(0.0,gy1)-0.5);vec3 g000=vec3(gx0.x,gy0.x,gz0.x);vec3 g100=vec3(gx0.y,gy0.y,gz0.y);vec3 g010=vec3(gx0.z,gy0.z,gz0.z);vec3 g110=vec3(gx0.w,gy0.w,gz0.w);vec3 g001=vec3(gx1.x,gy1.x,gz1.x);vec3 g101=vec3(gx1.y,gy1.y,gz1.y);vec3 g011=vec3(gx1.z,gy1.z,gz1.z);vec3 g111=vec3(gx1.w,gy1.w,gz1.w);vec4 norm0=taylorInvSqrt(vec4(dot(g000,g000),dot(g010,g010),dot(g100,g100),dot(g110,g110)));g000*=norm0.x;g010*=norm0.y;g100*=norm0.z;g110*=norm0.w;vec4 norm1=taylorInvSqrt(vec4(dot(g001,g001),dot(g011,g011),dot(g101,g101),dot(g111,g111)));g001*=norm1.x;g011*=norm1.y;g101*=norm1.z;g111*=norm1.w;float n000=dot(g000,Pf0);float n100=dot(g100,vec3(Pf1.x,Pf0.yz));float n010=dot(g010,vec3(Pf0.x,Pf1.y,Pf0.z));float n110=dot(g110,vec3(Pf1.xy,Pf0.z));float n001=dot(g001,vec3(Pf0.xy,Pf1.z));float n101=dot(g101,vec3(Pf1.x,Pf0.y,Pf1.z));float n011=dot(g011,vec3(Pf0.x,Pf1.yz));float n111=dot(g111,Pf1);vec3 fade_xyz=fade(Pf0);vec4 n_z=mix(vec4(n000,n100,n010,n110),vec4(n001,n101,n011,n111),fade_xyz.z);vec2 n_yz=mix(n_z.xy,n_z.zw,fade_xyz.y);float n_xyz=mix(n_yz.x,n_yz.y,fade_xyz.x);return 2.2*n_xyz;}\n/* END FUNCTION */\nfloat turbulence( vec3 p ) {float w=100.0;float t=-.5;for (float f=1.0 ; f<=10.0 ; f++ ){float power=pow( 2.0,f );t+=abs( pnoise( vec3( power*p ),vec3( 10.0,10.0,10.0 ) )/power );}\nreturn t;}\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\n#ifdef NORMAL\nnoise=10.0* -.10*turbulence( .5*normal+time*1.15 );float b=lowFrequencySpeed*5.0*pnoise( 0.05*position +vec3(time*1.025),vec3( 100.0 ) );float displacement=- 1.5*noise+b;vec3 newPosition=position+normal*displacement;gl_Position=viewProjection*finalWorld*vec4( newPosition,1.0 );vec4 worldPos=finalWorld*vec4(newPosition,1.0);vPositionW=vec3(worldPos);vNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";class vW extends xn{constructor(){super(),this.DIFFUSE=!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.POINTSIZE=!1,this.FOG=!1,this.LIGHT0=!1,this.LIGHT1=!1,this.LIGHT2=!1,this.LIGHT3=!1,this.SPOTLIGHT0=!1,this.SPOTLIGHT1=!1,this.SPOTLIGHT2=!1,this.SPOTLIGHT3=!1,this.HEMILIGHT0=!1,this.HEMILIGHT1=!1,this.HEMILIGHT2=!1,this.HEMILIGHT3=!1,this.DIRLIGHT0=!1,this.DIRLIGHT1=!1,this.DIRLIGHT2=!1,this.DIRLIGHT3=!1,this.POINTLIGHT0=!1,this.POINTLIGHT1=!1,this.POINTLIGHT2=!1,this.POINTLIGHT3=!1,this.SHADOW0=!1,this.SHADOW1=!1,this.SHADOW2=!1,this.SHADOW3=!1,this.SHADOWS=!1,this.SHADOWESM0=!1,this.SHADOWESM1=!1,this.SHADOWESM2=!1,this.SHADOWESM3=!1,this.SHADOWPOISSON0=!1,this.SHADOWPOISSON1=!1,this.SHADOWPOISSON2=!1,this.SHADOWPOISSON3=!1,this.SHADOWPCF0=!1,this.SHADOWPCF1=!1,this.SHADOWPCF2=!1,this.SHADOWPCF3=!1,this.SHADOWPCSS0=!1,this.SHADOWPCSS1=!1,this.SHADOWPCSS2=!1,this.SHADOWPCSS3=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.UNLIT=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class xW extends bn{constructor(e,t){super(e,t),this.speed=1,this.movingSpeed=1,this.lowFrequencySpeed=1,this.fogDensity=.15,this._lastTime=0,this.diffuseColor=new H.v9(1,1,1),this._disableLighting=!1,this._unlit=!1,this._maxSimultaneousLights=4,this._scaledDiffuse=new H.v9}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r.effect&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new vW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(s._areTexturesDirty&&(s._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&Sn.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;s._needUVs=!0,s.DIFFUSE=!0}if((0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=!0,(0,Bt.az)(n,e,s,!1,this._maxSimultaneousLights,this._disableLighting),(0,Bt.OR)(n,o,this,s,!!i),(0,Bt.qB)(e,s,!0,!0),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial();const i=new Tn;s.FOG&&i.addFallback(1,"FOG"),(0,Bt.c4)(s,i),s.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),s.UV1&&r.push(st.R.UVKind),s.UV2&&r.push(st.R.UV2Kind),s.VERTEXCOLOR&&r.push(st.R.ColorKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="lava",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant","time","speed","movingSpeed","fogColor","fogDensity","lowFrequencySpeed"];(0,Ln.TV)(h);const c=["diffuseSampler","noiseTexture"],u=[];(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,s.UNLIT=this._unlit,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._mustRebind(r,n,i)&&(this.diffuseTexture&&Sn.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),this.noiseTexture&&this._activeEffect.setTexture("noiseTexture",this.noiseTexture),(0,Ln.gS)(n,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._lastTime+=r.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime*this.speed/1e3),this.fogColor||(this.fogColor=H.v9.Black()),this._activeEffect.setColor3("fogColor",this.fogColor),this._activeEffect.setFloat("fogDensity",this.fogDensity),this._activeEffect.setFloat("lowFrequencySpeed",this.lowFrequencySpeed),this._activeEffect.setFloat("movingSpeed",this.movingSpeed),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.noiseTexture&&this.noiseTexture.animations&&this.noiseTexture.animations.length>0&&e.push(this.noiseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this.diffuseTexture&&this.diffuseTexture.dispose(),this.noiseTexture&&this.noiseTexture.dispose(),super.dispose(e)}clone(e){return it.p.Clone((()=>new xW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.LavaMaterial",e}getClassName(){return"LavaMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new xW(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.uM)("diffuseTexture")],xW.prototype,"_diffuseTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],xW.prototype,"diffuseTexture",void 0),(0,je.Cg)([(0,$e.uM)()],xW.prototype,"noiseTexture",void 0),(0,je.Cg)([(0,$e.jT)()],xW.prototype,"fogColor",void 0),(0,je.Cg)([(0,$e.lK)()],xW.prototype,"speed",void 0),(0,je.Cg)([(0,$e.lK)()],xW.prototype,"movingSpeed",void 0),(0,je.Cg)([(0,$e.lK)()],xW.prototype,"lowFrequencySpeed",void 0),(0,je.Cg)([(0,$e.lK)()],xW.prototype,"fogDensity",void 0),(0,je.Cg)([(0,$e.jT)()],xW.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.lK)("disableLighting")],xW.prototype,"_disableLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],xW.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.lK)("unlit")],xW.prototype,"_unlit",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],xW.prototype,"unlit",void 0),(0,je.Cg)([(0,$e.lK)("maxSimultaneousLights")],xW.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],xW.prototype,"maxSimultaneousLights",void 0),(0,X.Y5)("BABYLON.LavaMaterial",xW);Cs.l.ShadersStore.mixPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform sampler2D mixMap1Sampler;uniform vec2 vTextureInfos;\n#ifdef MIXMAP2\nuniform sampler2D mixMap2Sampler;\n#endif\nuniform sampler2D diffuse1Sampler;uniform sampler2D diffuse2Sampler;uniform sampler2D diffuse3Sampler;uniform sampler2D diffuse4Sampler;uniform vec2 diffuse1Infos;uniform vec2 diffuse2Infos;uniform vec2 diffuse3Infos;uniform vec2 diffuse4Infos;\n#ifdef MIXMAP2\nuniform sampler2D diffuse5Sampler;uniform sampler2D diffuse6Sampler;uniform sampler2D diffuse7Sampler;uniform sampler2D diffuse8Sampler;uniform vec2 diffuse5Infos;uniform vec2 diffuse6Infos;uniform vec2 diffuse7Infos;uniform vec2 diffuse8Infos;\n#endif\n#endif\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 finalMixColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef MIXMAP2\nvec4 mixColor2=vec4(1.,1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\nfloat alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec4 mixColor=texture2D(mixMap1Sampler,vTextureUV);\n#include\nmixColor.rgb*=vTextureInfos.y;vec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);vec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);vec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);vec4 diffuse4Color=texture2D(diffuse4Sampler,vTextureUV*diffuse4Infos);diffuse1Color.rgb*=mixColor.r;diffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,mixColor.g);diffuse3Color.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,mixColor.b);finalMixColor.rgb=mix(diffuse3Color.rgb,diffuse4Color.rgb,1.0-mixColor.a);\n#ifdef MIXMAP2\nmixColor=texture2D(mixMap2Sampler,vTextureUV);mixColor.rgb*=vTextureInfos.y;vec4 diffuse5Color=texture2D(diffuse5Sampler,vTextureUV*diffuse5Infos);vec4 diffuse6Color=texture2D(diffuse6Sampler,vTextureUV*diffuse6Infos);vec4 diffuse7Color=texture2D(diffuse7Sampler,vTextureUV*diffuse7Infos);vec4 diffuse8Color=texture2D(diffuse8Sampler,vTextureUV*diffuse8Infos);diffuse5Color.rgb=mix(finalMixColor.rgb,diffuse5Color.rgb,mixColor.r);diffuse6Color.rgb=mix(diffuse5Color.rgb,diffuse6Color.rgb,mixColor.g);diffuse7Color.rgb=mix(diffuse6Color.rgb,diffuse7Color.rgb,mixColor.b);finalMixColor.rgb=mix(diffuse7Color.rgb,diffuse8Color.rgb,1.0-mixColor.a);\n#endif\n#endif\n#ifdef VERTEXCOLOR\nfinalMixColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor*finalMixColor.rgb,0.0,1.0);vec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Cs.l.ShadersStore.mixVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform mat4 textureMatrix;uniform vec2 vTextureInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vTextureInfos.x==0.)\n{vTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));}\nelse\n{vTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class bW extends xn{constructor(){super(),this.DIFFUSE=!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.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.MIXMAP2=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class SW extends bn{constructor(e,t){super(e,t),this.diffuseColor=new H.v9(1,1,1),this.specularColor=new H.v9(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r.effect&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new bW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(n.texturesEnabled){if(!this._mixTexture1||!this._mixTexture1.isReady())return!1;if(s._needUVs=!0,Sn.DiffuseTextureEnabled){if(!this._diffuseTexture1||!this._diffuseTexture1.isReady())return!1;if(s.DIFFUSE=!0,!this._diffuseTexture2||!this._diffuseTexture2.isReady())return!1;if(!this._diffuseTexture3||!this._diffuseTexture3.isReady())return!1;if(!this._diffuseTexture4||!this._diffuseTexture4.isReady())return!1;if(this._mixTexture2){if(!this._mixTexture2.isReady())return!1;if(s.MIXMAP2=!0,!this._diffuseTexture5||!this._diffuseTexture5.isReady())return!1;if(!this._diffuseTexture6||!this._diffuseTexture6.isReady())return!1;if(!this._diffuseTexture7||!this._diffuseTexture7.isReady())return!1;if(!this._diffuseTexture8||!this._diffuseTexture8.isReady())return!1}}}if((0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=(0,Bt.az)(n,e,s,!1,this._maxSimultaneousLights,this._disableLighting),(0,Bt.OR)(n,o,this,s,!!i),(0,Bt.qB)(e,s,!0,!0),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial();const i=new Tn;s.FOG&&i.addFallback(1,"FOG"),(0,Bt.c4)(s,i,this.maxSimultaneousLights),s.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),s.UV1&&r.push(st.R.UVKind),s.UV2&&r.push(st.R.UV2Kind),s.VERTEXCOLOR&&r.push(st.R.ColorKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="mix",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","textureMatrix","logarithmicDepthConstant","diffuse1Infos","diffuse2Infos","diffuse3Infos","diffuse4Infos","diffuse5Infos","diffuse6Infos","diffuse7Infos","diffuse8Infos"],c=["mixMap1Sampler","mixMap2Sampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","diffuse4Sampler","diffuse5Sampler","diffuse6Sampler","diffuse7Sampler","diffuse8Sampler"],u=[];(0,Ln.TV)(h),(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._mustRebind(r,n,i)&&(this._mixTexture1&&(this._activeEffect.setTexture("mixMap1Sampler",this._mixTexture1),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture1.coordinatesIndex,this._mixTexture1.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture1.getTextureMatrix()),Sn.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale)),this._diffuseTexture4&&(this._activeEffect.setTexture("diffuse4Sampler",this._diffuseTexture4),this._activeEffect.setFloat2("diffuse4Infos",this._diffuseTexture4.uScale,this._diffuseTexture4.vScale)))),this._mixTexture2&&(this._activeEffect.setTexture("mixMap2Sampler",this._mixTexture2),Sn.DiffuseTextureEnabled&&(this._diffuseTexture5&&(this._activeEffect.setTexture("diffuse5Sampler",this._diffuseTexture5),this._activeEffect.setFloat2("diffuse5Infos",this._diffuseTexture5.uScale,this._diffuseTexture5.vScale)),this._diffuseTexture6&&(this._activeEffect.setTexture("diffuse6Sampler",this._diffuseTexture6),this._activeEffect.setFloat2("diffuse6Infos",this._diffuseTexture6.uScale,this._diffuseTexture6.vScale)),this._diffuseTexture7&&(this._activeEffect.setTexture("diffuse7Sampler",this._diffuseTexture7),this._activeEffect.setFloat2("diffuse7Infos",this._diffuseTexture7.uScale,this._diffuseTexture7.vScale)),this._diffuseTexture8&&(this._activeEffect.setTexture("diffuse8Sampler",this._diffuseTexture8),this._activeEffect.setFloat2("diffuse8Infos",this._diffuseTexture8.uScale,this._diffuseTexture8.vScale)))),(0,Ln.gS)(n,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),r.lightsEnabled&&!this.disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._mixTexture1&&this._mixTexture1.animations&&this._mixTexture1.animations.length>0&&e.push(this._mixTexture1),this._mixTexture2&&this._mixTexture2.animations&&this._mixTexture2.animations.length>0&&e.push(this._mixTexture2),e}getActiveTextures(){const e=super.getActiveTextures();return this._mixTexture1&&e.push(this._mixTexture1),this._diffuseTexture1&&e.push(this._diffuseTexture1),this._diffuseTexture2&&e.push(this._diffuseTexture2),this._diffuseTexture3&&e.push(this._diffuseTexture3),this._diffuseTexture4&&e.push(this._diffuseTexture4),this._mixTexture2&&e.push(this._mixTexture2),this._diffuseTexture5&&e.push(this._diffuseTexture5),this._diffuseTexture6&&e.push(this._diffuseTexture6),this._diffuseTexture7&&e.push(this._diffuseTexture7),this._diffuseTexture8&&e.push(this._diffuseTexture8),e}hasTexture(e){return!!super.hasTexture(e)||this._mixTexture1===e||this._diffuseTexture1===e||this._diffuseTexture2===e||this._diffuseTexture3===e||this._diffuseTexture4===e||this._mixTexture2===e||this._diffuseTexture5===e||this._diffuseTexture6===e||this._diffuseTexture7===e||this._diffuseTexture8===e}dispose(e){this._mixTexture1&&this._mixTexture1.dispose(),super.dispose(e)}clone(e){return it.p.Clone((()=>new SW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MixMaterial",e}getClassName(){return"MixMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new SW(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.uM)("mixTexture1")],SW.prototype,"_mixTexture1",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],SW.prototype,"mixTexture1",void 0),(0,je.Cg)([(0,$e.uM)("mixTexture2")],SW.prototype,"_mixTexture2",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],SW.prototype,"mixTexture2",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture1")],SW.prototype,"_diffuseTexture1",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],SW.prototype,"diffuseTexture1",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture2")],SW.prototype,"_diffuseTexture2",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],SW.prototype,"diffuseTexture2",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture3")],SW.prototype,"_diffuseTexture3",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],SW.prototype,"diffuseTexture3",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture4")],SW.prototype,"_diffuseTexture4",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],SW.prototype,"diffuseTexture4",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture1")],SW.prototype,"_diffuseTexture5",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],SW.prototype,"diffuseTexture5",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture2")],SW.prototype,"_diffuseTexture6",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],SW.prototype,"diffuseTexture6",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture3")],SW.prototype,"_diffuseTexture7",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],SW.prototype,"diffuseTexture7",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture4")],SW.prototype,"_diffuseTexture8",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],SW.prototype,"diffuseTexture8",void 0),(0,je.Cg)([(0,$e.jT)()],SW.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.jT)()],SW.prototype,"specularColor",void 0),(0,je.Cg)([(0,$e.lK)()],SW.prototype,"specularPower",void 0),(0,je.Cg)([(0,$e.lK)("disableLighting")],SW.prototype,"_disableLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],SW.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.lK)("maxSimultaneousLights")],SW.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],SW.prototype,"maxSimultaneousLights",void 0),(0,X.Y5)("BABYLON.MixMaterial",SW);Cs.l.ShadersStore.normalPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef LIGHTING\n#include\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef NORMAL\nbaseColor=mix(baseColor,vec4(vNormalW,1.0),0.5);\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef LIGHTING\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#include[0]\n#include[1]\n#include[2]\n#include[3]\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse= baseColor.rgb;\n#endif\nvec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Cs.l.ShadersStore.normalVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class TW extends xn{constructor(){super(),this.DIFFUSE=!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.POINTSIZE=!1,this.FOG=!1,this.LIGHT0=!1,this.LIGHT1=!1,this.LIGHT2=!1,this.LIGHT3=!1,this.SPOTLIGHT0=!1,this.SPOTLIGHT1=!1,this.SPOTLIGHT2=!1,this.SPOTLIGHT3=!1,this.HEMILIGHT0=!1,this.HEMILIGHT1=!1,this.HEMILIGHT2=!1,this.HEMILIGHT3=!1,this.DIRLIGHT0=!1,this.DIRLIGHT1=!1,this.DIRLIGHT2=!1,this.DIRLIGHT3=!1,this.POINTLIGHT0=!1,this.POINTLIGHT1=!1,this.POINTLIGHT2=!1,this.POINTLIGHT3=!1,this.SHADOW0=!1,this.SHADOW1=!1,this.SHADOW2=!1,this.SHADOW3=!1,this.SHADOWS=!1,this.SHADOWESM0=!1,this.SHADOWESM1=!1,this.SHADOWESM2=!1,this.SHADOWESM3=!1,this.SHADOWPOISSON0=!1,this.SHADOWPOISSON1=!1,this.SHADOWPOISSON2=!1,this.SHADOWPOISSON3=!1,this.SHADOWPCF0=!1,this.SHADOWPCF1=!1,this.SHADOWPCF2=!1,this.SHADOWPCF3=!1,this.SHADOWPCSS0=!1,this.SHADOWPCSS1=!1,this.SHADOWPCSS2=!1,this.SHADOWPCSS3=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.LIGHTING=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class CW extends bn{constructor(e,t){super(e,t),this.diffuseColor=new H.v9(1,1,1),this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaBlendingForMesh(e){return this.needAlphaBlending()||e.visibility<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r.effect&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new TW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(s._areTexturesDirty&&(s._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&Sn.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;s._needUVs=!0,s.DIFFUSE=!0}if((0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=!0,(0,Bt.az)(n,e,s,!1,this._maxSimultaneousLights,this._disableLighting),(0,Bt.OR)(n,o,this,s,!!i),s.LIGHTING=!this._disableLighting,(0,Bt.qB)(e,s,!0,!0),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial();const i=new Tn;s.FOG&&i.addFallback(1,"FOG"),(0,Bt.c4)(s,i),s.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),s.UV1&&r.push(st.R.UVKind),s.UV2&&r.push(st.R.UV2Kind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="normal",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant"],c=["diffuseSampler"],u=[];(0,Ln.TV)(h),(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:4}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._mustRebind(r,n,i)&&(this.diffuseTexture&&Sn.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),(0,Ln.gS)(n,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this.diffuseTexture&&this.diffuseTexture.dispose(),super.dispose(e)}clone(e){return it.p.Clone((()=>new CW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.NormalMaterial",e}getClassName(){return"NormalMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new CW(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.uM)("diffuseTexture")],CW.prototype,"_diffuseTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],CW.prototype,"diffuseTexture",void 0),(0,je.Cg)([(0,$e.jT)()],CW.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.lK)("disableLighting")],CW.prototype,"_disableLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],CW.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.lK)("maxSimultaneousLights")],CW.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],CW.prototype,"maxSimultaneousLights",void 0),(0,X.Y5)("BABYLON.NormalMaterial",CW);Cs.l.ShadersStore.shadowOnlyPixelShader="precision highp float;uniform vec4 vEyePosition;uniform float alpha;uniform vec3 shadowColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#include[0..1]\nvec4 color=vec4(shadowColor,(1.0-clamp(shadow,0.,1.))*alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Cs.l.ShadersStore.shadowOnlyVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class yW extends xn{constructor(){super(),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.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class EW extends bn{constructor(e,t){super(e,t),this._needAlphaBlending=!0,this.shadowColor=H.v9.Black()}needAlphaBlending(){return this._needAlphaBlending}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}get activeLight(){return this._activeLight}set activeLight(e){this._activeLight=e}_getFirstShadowLightForMesh(e){for(const t of e.lightSources)if(t.shadowEnabled)return t;return null}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r.effect&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new yW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(this._activeLight)for(const t of e.lightSources)if(t.shadowEnabled){if(this._activeLight===t)break;const i=e.lightSources.indexOf(this._activeLight);-1!==i&&(e.lightSources.splice(i,1),e.lightSources.splice(0,0,this._activeLight));break}(0,Bt.OR)(n,o,this,s,!!i),(0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=(0,Bt.az)(n,e,s,!1,1);const a=this._getFirstShadowLightForMesh(e)?.getShadowGenerator();if(this._needAlphaBlending=!0,a&&a.getClassName&&"CascadedShadowGenerator"===a.getClassName()){const e=a;this._needAlphaBlending=!e.autoCalcDepthBounds}if((0,Bt.qB)(e,s,!1,!0),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial();const i=new Tn;s.FOG&&i.addFallback(1,"FOG"),(0,Bt.c4)(s,i,1),s.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="shadowOnly",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","alpha","shadowColor","mBones","logarithmicDepthConstant"],c=[],u=[];(0,Ln.TV)(h),(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:1}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:1}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;if(n){if(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._mustRebind(r,n,i)&&((0,Ln.gS)(n,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setFloat("alpha",this.alpha),this._activeEffect.setColor3("shadowColor",this.shadowColor),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),r.lightsEnabled){(0,Bt.RL)(r,t,this._activeEffect,s,1);const e=this._getFirstShadowLightForMesh(t);e&&(e._renderId=-1)}(r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE||s.SHADOWCSM0)&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._afterBind(t,this._activeEffect,i)}}clone(e){return it.p.Clone((()=>new EW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.ShadowOnlyMaterial",e}getClassName(){return"ShadowOnlyMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new EW(e.name,t)),e,t,i)}}(0,X.Y5)("BABYLON.ShadowOnlyMaterial",EW);Cs.l.ShadersStore.simplePixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Cs.l.ShadersStore.simpleVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class PW extends xn{constructor(){super(),this.DIFFUSE=!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.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class AW extends bn{constructor(e,t){super(e,t),this.diffuseColor=new H.v9(1,1,1),this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r.effect&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new PW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(s._areTexturesDirty&&(s._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&Sn.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;s._needUVs=!0,s.DIFFUSE=!0}if((0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=(0,Bt.az)(n,e,s,!1,this._maxSimultaneousLights,this._disableLighting),(0,Bt.OR)(n,o,this,s,!!i),(0,Bt.qB)(e,s,!0,!0),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial();const i=new Tn;s.FOG&&i.addFallback(1,"FOG"),(0,Bt.c4)(s,i,this.maxSimultaneousLights),s.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),s.UV1&&r.push(st.R.UVKind),s.UV2&&r.push(st.R.UV2Kind),s.VERTEXCOLOR&&r.push(st.R.ColorKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="simple",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant"],c=["diffuseSampler"],u=[];(0,Ln.TV)(h),(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights-1}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._mustRebind(r,n,i)&&(this._diffuseTexture&&Sn.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),(0,Ln.gS)(n,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),super.dispose(e)}clone(e){return it.p.Clone((()=>new AW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.SimpleMaterial",e}getClassName(){return"SimpleMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new AW(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.uM)("diffuseTexture")],AW.prototype,"_diffuseTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],AW.prototype,"diffuseTexture",void 0),(0,je.Cg)([(0,$e.jT)("diffuse")],AW.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.lK)("disableLighting")],AW.prototype,"_disableLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],AW.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.lK)("maxSimultaneousLights")],AW.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],AW.prototype,"maxSimultaneousLights",void 0),(0,X.Y5)("BABYLON.SimpleMaterial",AW);Cs.l.ShadersStore.skyPixelShader="precision highp float;varying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\nuniform vec3 cameraPosition;uniform vec3 cameraOffset;uniform vec3 up;uniform float luminance;uniform float turbidity;uniform float rayleigh;uniform float mieCoefficient;uniform float mieDirectionalG;uniform vec3 sunPosition;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nconst float e=2.71828182845904523536028747135266249775724709369995957;const float pi=3.141592653589793238462643383279502884197169;const float n=1.0003;const float N=2.545E25;const float pn=0.035;const vec3 lambda=vec3(680E-9,550E-9,450E-9);const vec3 K=vec3(0.686,0.678,0.666);const float v=4.0;const float rayleighZenithLength=8.4E3;const float mieZenithLength=1.25E3;const float EE=1000.0;const float sunAngularDiameterCos=0.999956676946448443553574619906976478926848692873900859324;const float cutoffAngle=pi/1.95;const float steepness=1.5;vec3 totalRayleigh(vec3 lambda)\n{return (8.0*pow(pi,3.0)*pow(pow(n,2.0)-1.0,2.0)*(6.0+3.0*pn))/(3.0*N*pow(lambda,vec3(4.0))*(6.0-7.0*pn));}\nvec3 simplifiedRayleigh()\n{return 0.0005/vec3(94,40,18);}\nfloat rayleighPhase(float cosTheta)\n{ \nreturn (3.0/(16.0*pi))*(1.0+pow(cosTheta,2.0));}\nvec3 totalMie(vec3 lambda,vec3 K,float T)\n{float c=(0.2*T )*10E-18;return 0.434*c*pi*pow((2.0*pi)/lambda,vec3(v-2.0))*K;}\nfloat hgPhase(float cosTheta,float g)\n{return (1.0/(4.0*pi))*((1.0-pow(g,2.0))/pow(1.0-2.0*g*cosTheta+pow(g,2.0),1.5));}\nfloat sunIntensity(float zenithAngleCos)\n{return EE*max(0.0,1.0-exp((-(cutoffAngle-acos(zenithAngleCos))/steepness)));}\nfloat A=0.15;float B=0.50;float C=0.10;float D=0.20;float EEE=0.02;float F=0.30;float W=1000.0;vec3 Uncharted2Tonemap(vec3 x)\n{return ((x*(A*x+C*B)+D*EEE)/(x*(A*x+B)+D*F))-EEE/F;}\n#if DITHER\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n/**\n*--------------------------------------------------------------------------------------------------\n* Sky Color\n*--------------------------------------------------------------------------------------------------\n*/\nfloat sunfade=1.0-clamp(1.0-exp((sunPosition.y/450000.0)),0.0,1.0);float rayleighCoefficient=rayleigh-(1.0*(1.0-sunfade));vec3 sunDirection=normalize(sunPosition);float sunE=sunIntensity(dot(sunDirection,up));vec3 betaR=simplifiedRayleigh()*rayleighCoefficient;vec3 betaM=totalMie(lambda,K,turbidity)*mieCoefficient;float zenithAngle=acos(max(0.0,dot(up,normalize(vPositionW-cameraPosition+cameraOffset))));float sR=rayleighZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));float sM=mieZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));vec3 Fex=exp(-(betaR*sR+betaM*sM));float cosTheta=dot(normalize(vPositionW-cameraPosition),sunDirection);float rPhase=rayleighPhase(cosTheta*0.5+0.5);vec3 betaRTheta=betaR*rPhase;float mPhase=hgPhase(cosTheta,mieDirectionalG);vec3 betaMTheta=betaM*mPhase;vec3 Lin=pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*(1.0-Fex),vec3(1.5));Lin*=mix(vec3(1.0),pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*Fex,vec3(1.0/2.0)),clamp(pow(1.0-dot(up,sunDirection),5.0),0.0,1.0));vec3 direction=normalize(vPositionW-cameraPosition);float theta=acos(direction.y);float phi=atan(direction.z,direction.x);vec2 uv=vec2(phi,theta)/vec2(2.0*pi,pi)+vec2(0.5,0.0);vec3 L0=vec3(0.1)*Fex;float sundisk=smoothstep(sunAngularDiameterCos,sunAngularDiameterCos+0.00002,cosTheta);L0+=(sunE*19000.0*Fex)*sundisk;vec3 whiteScale=1.0/Uncharted2Tonemap(vec3(W));vec3 texColor=(Lin+L0);texColor*=0.04 ;texColor+=vec3(0.0,0.001,0.0025)*0.3;float g_fMaxLuminance=1.0;float fLumScaled=0.1/luminance; \nfloat fLumCompressed=(fLumScaled*(1.0+(fLumScaled/(g_fMaxLuminance*g_fMaxLuminance))))/(1.0+fLumScaled); \nfloat ExposureBias=fLumCompressed;vec3 curr=Uncharted2Tonemap((log2(2.0/pow(luminance,4.0)))*texColor);vec3 retColor=curr*whiteScale;/**\n*--------------------------------------------------------------------------------------------------\n* Sky Color\n*--------------------------------------------------------------------------------------------------\n*/\nfloat alpha=1.0;\n#ifdef VERTEXCOLOR\nretColor.rgb*=vColor.rgb;\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#if DITHER\nretColor.rgb+=dither(gl_FragCoord.xy,0.5);\n#endif\nvec4 color=clamp(vec4(retColor.rgb,alpha),0.0,1.0);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Cs.l.ShadersStore.skyVertexShader="precision highp float;attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\nuniform mat4 world;uniform mat4 view;uniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\ngl_Position=viewProjection*world*vec4(position,1.0);vec4 worldPos=world*vec4(position,1.0);vPositionW=vec3(worldPos);\n#include\n#include\n#include\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class RW extends xn{constructor(){super(),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.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.DITHER=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class IW extends bn{constructor(e,t){super(e,t),this.luminance=1,this.turbidity=10,this.rayleigh=2,this.mieCoefficient=.005,this.mieDirectionalG=.8,this.distance=500,this.inclination=.49,this.azimuth=.25,this.sunPosition=new W.Pq(0,100,0),this.useSunPosition=!1,this.cameraOffset=W.Pq.Zero(),this.up=W.Pq.Up(),this.dithering=!1,this._cameraPosition=W.Pq.Zero(),this._skyOrientation=new W.PT}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new RW);const r=t.materialDefines,s=this.getScene();if(this._isReadyForSubMesh(t))return!0;if((0,Bt.fm)(e,s,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,!1,r),(0,Bt.qB)(e,r,!0,!1),r.IMAGEPROCESSINGPOSTPROCESS!==s.imageProcessingConfiguration.applyByPostProcess&&r.markAsMiscDirty(),r.DITHER!==this.dithering&&r.markAsMiscDirty(),r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=new Tn;r.FOG&&e.addFallback(1,"FOG"),r.IMAGEPROCESSINGPOSTPROCESS=s.imageProcessingConfiguration.applyByPostProcess,r.DITHER=this.dithering;const i=[st.R.PositionKind];r.VERTEXCOLOR&&i.push(st.R.ColorKind);const n="sky",o=["world","viewProjection","view","vFogInfos","vFogColor","logarithmicDepthConstant","pointSize","luminance","turbidity","rayleigh","mieCoefficient","mieDirectionalG","sunPosition","cameraPosition","cameraOffset","up"];(0,Ln.TV)(o);const a=r.toString();t.setEffect(s.getEngine().createEffect(n,i,o,[],a,e,this.onCompiled,this.onError),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),this._mustRebind(r,n,i)&&((0,Ln.gS)(n,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r)),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect);const o=r.activeCamera;if(o){const e=o.getWorldMatrix();this._cameraPosition.x=e.m[12],this._cameraPosition.y=e.m[13],this._cameraPosition.z=e.m[14],this._activeEffect.setVector3("cameraPosition",this._cameraPosition)}if(this._activeEffect.setVector3("cameraOffset",this.cameraOffset),this._activeEffect.setVector3("up",this.up),this.luminance>0&&this._activeEffect.setFloat("luminance",this.luminance),this._activeEffect.setFloat("turbidity",this.turbidity),this._activeEffect.setFloat("rayleigh",this.rayleigh),this._activeEffect.setFloat("mieCoefficient",this.mieCoefficient),this._activeEffect.setFloat("mieDirectionalG",this.mieDirectionalG),!this.useSunPosition){const e=Math.PI*(this.inclination-.5),t=2*Math.PI*(this.azimuth-.5);this.sunPosition.x=this.distance*Math.cos(t)*Math.cos(e),this.sunPosition.y=this.distance*Math.sin(-e),this.sunPosition.z=this.distance*Math.sin(t)*Math.cos(e),W.PT.FromUnitVectorsToRef(W.Pq.UpReadOnly,this.up,this._skyOrientation),this.sunPosition.rotateByQuaternionToRef(this._skyOrientation,this.sunPosition)}this._activeEffect.setVector3("sunPosition",this.sunPosition),this._afterBind(t,this._activeEffect,i)}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return it.p.Clone((()=>new IW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.SkyMaterial",e}getClassName(){return"SkyMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new IW(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.lK)()],IW.prototype,"luminance",void 0),(0,je.Cg)([(0,$e.lK)()],IW.prototype,"turbidity",void 0),(0,je.Cg)([(0,$e.lK)()],IW.prototype,"rayleigh",void 0),(0,je.Cg)([(0,$e.lK)()],IW.prototype,"mieCoefficient",void 0),(0,je.Cg)([(0,$e.lK)()],IW.prototype,"mieDirectionalG",void 0),(0,je.Cg)([(0,$e.lK)()],IW.prototype,"distance",void 0),(0,je.Cg)([(0,$e.lK)()],IW.prototype,"inclination",void 0),(0,je.Cg)([(0,$e.lK)()],IW.prototype,"azimuth",void 0),(0,je.Cg)([(0,$e.P_)()],IW.prototype,"sunPosition",void 0),(0,je.Cg)([(0,$e.lK)()],IW.prototype,"useSunPosition",void 0),(0,je.Cg)([(0,$e.P_)()],IW.prototype,"cameraOffset",void 0),(0,je.Cg)([(0,$e.P_)()],IW.prototype,"up",void 0),(0,je.Cg)([(0,$e.lK)()],IW.prototype,"dithering",void 0),(0,X.Y5)("BABYLON.SkyMaterial",IW);Cs.l.ShadersStore.terrainPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform sampler2D textureSampler;uniform vec2 vTextureInfos;uniform sampler2D diffuse1Sampler;uniform sampler2D diffuse2Sampler;uniform sampler2D diffuse3Sampler;uniform vec2 diffuse1Infos;uniform vec2 diffuse2Infos;uniform vec2 diffuse3Infos;\n#endif\n#ifdef BUMP\nuniform sampler2D bump1Sampler;uniform sampler2D bump2Sampler;uniform sampler2D bump3Sampler;\n#endif\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;float invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));return mat3(tangent*invmax,binormal*invmax,normal);}\nvec3 perturbNormal(vec3 viewDir,vec3 mixColor)\n{vec3 bump1Color=texture2D(bump1Sampler,vTextureUV*diffuse1Infos).xyz;vec3 bump2Color=texture2D(bump2Sampler,vTextureUV*diffuse2Infos).xyz;vec3 bump3Color=texture2D(bump3Sampler,vTextureUV*diffuse3Infos).xyz;bump1Color.rgb*=mixColor.r;bump2Color.rgb=mix(bump1Color.rgb,bump2Color.rgb,mixColor.g);vec3 map=mix(bump2Color.rgb,bump3Color.rgb,mixColor.b);map=map*255./127.-128./127.;mat3 TBN=cotangent_frame(vNormalW*vTextureInfos.y,-viewDir,vTextureUV);return normalize(TBN*map);}\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\nfloat alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(textureSampler,vTextureUV);\n#if defined(BUMP) && defined(DIFFUSE)\nnormalW=perturbNormal(viewDirectionW,baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vTextureInfos.y;vec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);vec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);vec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);diffuse1Color.rgb*=baseColor.r;diffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,baseColor.g);baseColor.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,baseColor.b);\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor*baseColor.rgb,0.0,1.0);vec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Cs.l.ShadersStore.terrainVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform mat4 textureMatrix;uniform vec2 vTextureInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vTextureInfos.x==0.)\n{vTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));}\nelse\n{vTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class MW extends xn{constructor(){super(),this.DIFFUSE=!1,this.BUMP=!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.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class OW extends bn{constructor(e,t){super(e,t),this.diffuseColor=new H.v9(1,1,1),this.specularColor=new H.v9(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r.effect&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new MW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(n.texturesEnabled){if(!this.mixTexture||!this.mixTexture.isReady())return!1;if(s._needUVs=!0,Sn.DiffuseTextureEnabled){if(!this.diffuseTexture1||!this.diffuseTexture1.isReady())return!1;if(!this.diffuseTexture2||!this.diffuseTexture2.isReady())return!1;if(!this.diffuseTexture3||!this.diffuseTexture3.isReady())return!1;s.DIFFUSE=!0}if(this.bumpTexture1&&this.bumpTexture2&&this.bumpTexture3&&Sn.BumpTextureEnabled){if(!this.bumpTexture1.isReady())return!1;if(!this.bumpTexture2.isReady())return!1;if(!this.bumpTexture3.isReady())return!1;s._needNormals=!0,s.BUMP=!0}}if((0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._needNormals=(0,Bt.az)(n,e,s,!1,this._maxSimultaneousLights,this._disableLighting),(0,Bt.OR)(n,o,this,s,!!i),(0,Bt.qB)(e,s,!0,!0),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial();const i=new Tn;s.FOG&&i.addFallback(1,"FOG"),(0,Bt.c4)(s,i,this.maxSimultaneousLights),s.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),s.UV1&&r.push(st.R.UVKind),s.UV2&&r.push(st.R.UV2Kind),s.VERTEXCOLOR&&r.push(st.R.ColorKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="terrain",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","textureMatrix","diffuse1Infos","diffuse2Infos","diffuse3Infos"],c=["textureSampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","bump1Sampler","bump2Sampler","bump3Sampler","logarithmicDepthConstant"],u=[];(0,Ln.TV)(h),(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("view",r.getViewMatrix()),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._mustRebind(r,n,i)&&(this.mixTexture&&(this._activeEffect.setTexture("textureSampler",this._mixTexture),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture.coordinatesIndex,this._mixTexture.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture.getTextureMatrix()),Sn.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale))),Sn.BumpTextureEnabled&&r.getEngine().getCaps().standardDerivatives&&(this._bumpTexture1&&this._activeEffect.setTexture("bump1Sampler",this._bumpTexture1),this._bumpTexture2&&this._activeEffect.setTexture("bump2Sampler",this._bumpTexture2),this._bumpTexture3&&this._activeEffect.setTexture("bump3Sampler",this._bumpTexture3))),(0,Ln.gS)(n,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),r.lightsEnabled&&!this.disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._mixTexture&&e.push(this._mixTexture),this._diffuseTexture1&&e.push(this._diffuseTexture1),this._diffuseTexture2&&e.push(this._diffuseTexture2),this._diffuseTexture3&&e.push(this._diffuseTexture3),this._bumpTexture1&&e.push(this._bumpTexture1),this._bumpTexture2&&e.push(this._bumpTexture2),this._bumpTexture3&&e.push(this._bumpTexture3),e}hasTexture(e){return!!super.hasTexture(e)||this._mixTexture===e||this._diffuseTexture1===e||this._diffuseTexture2===e||this._diffuseTexture3===e||this._bumpTexture1===e||this._bumpTexture2===e||this._bumpTexture3===e}dispose(e){this.mixTexture&&this.mixTexture.dispose(),super.dispose(e)}clone(e){return it.p.Clone((()=>new OW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.TerrainMaterial",e}getClassName(){return"TerrainMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new OW(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.uM)("mixTexture")],OW.prototype,"_mixTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],OW.prototype,"mixTexture",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture1")],OW.prototype,"_diffuseTexture1",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],OW.prototype,"diffuseTexture1",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture2")],OW.prototype,"_diffuseTexture2",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],OW.prototype,"diffuseTexture2",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexture3")],OW.prototype,"_diffuseTexture3",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],OW.prototype,"diffuseTexture3",void 0),(0,je.Cg)([(0,$e.uM)("bumpTexture1")],OW.prototype,"_bumpTexture1",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],OW.prototype,"bumpTexture1",void 0),(0,je.Cg)([(0,$e.uM)("bumpTexture2")],OW.prototype,"_bumpTexture2",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],OW.prototype,"bumpTexture2",void 0),(0,je.Cg)([(0,$e.uM)("bumpTexture3")],OW.prototype,"_bumpTexture3",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],OW.prototype,"bumpTexture3",void 0),(0,je.Cg)([(0,$e.jT)()],OW.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.jT)()],OW.prototype,"specularColor",void 0),(0,je.Cg)([(0,$e.lK)()],OW.prototype,"specularPower",void 0),(0,je.Cg)([(0,$e.lK)("disableLighting")],OW.prototype,"_disableLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],OW.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.lK)("maxSimultaneousLights")],OW.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],OW.prototype,"maxSimultaneousLights",void 0),(0,X.Y5)("BABYLON.TerrainMaterial",OW);Cs.l.ShadersStore.triplanarPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;uniform sampler2D diffuseSamplerX;\n#ifdef BUMPX\nuniform sampler2D normalSamplerX;\n#endif\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;uniform sampler2D diffuseSamplerY;\n#ifdef BUMPY\nuniform sampler2D normalSamplerY;\n#endif\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;uniform sampler2D diffuseSamplerZ;\n#ifdef BUMPZ\nuniform sampler2D normalSamplerZ;\n#endif\n#endif\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(0.,0.,0.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=tangentSpace[2];\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec4 baseNormal=vec4(0.0,0.0,0.0,1.0);normalW*=normalW;\n#ifdef DIFFUSEX\nbaseColor+=texture2D(diffuseSamplerX,vTextureUVX)*normalW.x;\n#ifdef BUMPX\nbaseNormal+=texture2D(normalSamplerX,vTextureUVX)*normalW.x;\n#endif\n#endif\n#ifdef DIFFUSEY\nbaseColor+=texture2D(diffuseSamplerY,vTextureUVY)*normalW.y;\n#ifdef BUMPY\nbaseNormal+=texture2D(normalSamplerY,vTextureUVY)*normalW.y;\n#endif\n#endif\n#ifdef DIFFUSEZ\nbaseColor+=texture2D(diffuseSamplerZ,vTextureUVZ)*normalW.z;\n#ifdef BUMPZ\nbaseNormal+=texture2D(normalSamplerZ,vTextureUVZ)*normalW.z;\n#endif\n#endif\n#ifdef NORMAL\nnormalW=normalize((2.0*baseNormal.xyz-1.0)*tangentSpace);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Cs.l.ShadersStore.triplanarVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;\n#endif\nuniform float tileSize;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef DIFFUSEX\nvTextureUVX=worldPos.zy/tileSize;\n#endif\n#ifdef DIFFUSEY\nvTextureUVY=worldPos.xz/tileSize;\n#endif\n#ifdef DIFFUSEZ\nvTextureUVZ=worldPos.xy/tileSize;\n#endif\n#ifdef NORMAL\nvec3 xtan=vec3(0,0,1);vec3 xbin=vec3(0,1,0);vec3 ytan=vec3(1,0,0);vec3 ybin=vec3(0,0,1);vec3 ztan=vec3(1,0,0);vec3 zbin=vec3(0,1,0);vec3 normalizedNormal=normalize(normal);normalizedNormal*=normalizedNormal;vec3 worldBinormal=normalize(xbin*normalizedNormal.x+ybin*normalizedNormal.y+zbin*normalizedNormal.z);vec3 worldTangent=normalize(xtan*normalizedNormal.x+ytan*normalizedNormal.y+ztan*normalizedNormal.z);mat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nworldTangent=normalize((normalWorld*worldTangent).xyz);worldBinormal=normalize((normalWorld*worldBinormal).xyz);vec3 worldNormal=normalize((normalWorld*normalize(normal)).xyz);tangentSpace[0]=worldTangent;tangentSpace[1]=worldBinormal;tangentSpace[2]=worldNormal;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class DW extends xn{constructor(){super(),this.DIFFUSEX=!1,this.DIFFUSEY=!1,this.DIFFUSEZ=!1,this.BUMPX=!1,this.BUMPY=!1,this.BUMPZ=!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.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.NONUNIFORMSCALING=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class wW extends bn{constructor(e,t){super(e,t),this.tileSize=1,this.diffuseColor=new H.v9(1,1,1),this.specularColor=new H.v9(.2,.2,.2),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r.effect&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new DW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(s._areTexturesDirty&&n.texturesEnabled){if(Sn.DiffuseTextureEnabled){const e=[this.diffuseTextureX,this.diffuseTextureY,this.diffuseTextureZ],t=["DIFFUSEX","DIFFUSEY","DIFFUSEZ"];for(let i=0;i0&&i.addCPUSkinningFallback(0,e),s.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),s.VERTEXCOLOR&&r.push(st.R.ColorKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="triplanar",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","mBones","tileSize"],c=["diffuseSamplerX","diffuseSamplerY","diffuseSamplerZ","normalSamplerX","normalSamplerY","normalSamplerZ","logarithmicDepthConstant"],u=[];(0,Ln.TV)(h),(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._activeEffect.setFloat("tileSize",this.tileSize),this._mustRebind(r,n,i)&&(this.diffuseTextureX&&this._activeEffect.setTexture("diffuseSamplerX",this.diffuseTextureX),this.diffuseTextureY&&this._activeEffect.setTexture("diffuseSamplerY",this.diffuseTextureY),this.diffuseTextureZ&&this._activeEffect.setTexture("diffuseSamplerZ",this.diffuseTextureZ),this.normalTextureX&&this._activeEffect.setTexture("normalSamplerX",this.normalTextureX),this.normalTextureY&&this._activeEffect.setTexture("normalSamplerY",this.normalTextureY),this.normalTextureZ&&this._activeEffect.setTexture("normalSamplerZ",this.normalTextureZ),(0,Ln.gS)(n,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),r.lightsEnabled&&!this.disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTextureX&&e.push(this._diffuseTextureX),this._diffuseTextureY&&e.push(this._diffuseTextureY),this._diffuseTextureZ&&e.push(this._diffuseTextureZ),this._normalTextureX&&e.push(this._normalTextureX),this._normalTextureY&&e.push(this._normalTextureY),this._normalTextureZ&&e.push(this._normalTextureZ),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTextureX===e||this._diffuseTextureY===e||this._diffuseTextureZ===e||this._normalTextureX===e||this._normalTextureY===e||this._normalTextureZ===e}dispose(e){this.mixTexture&&this.mixTexture.dispose(),super.dispose(e)}clone(e){return it.p.Clone((()=>new wW(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.TriPlanarMaterial",e}getClassName(){return"TriPlanarMaterial"}static Parse(e,t,i){return it.p.Parse((()=>new wW(e.name,t)),e,t,i)}}(0,je.Cg)([(0,$e.uM)()],wW.prototype,"mixTexture",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTextureX")],wW.prototype,"_diffuseTextureX",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],wW.prototype,"diffuseTextureX",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTexturY")],wW.prototype,"_diffuseTextureY",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],wW.prototype,"diffuseTextureY",void 0),(0,je.Cg)([(0,$e.uM)("diffuseTextureZ")],wW.prototype,"_diffuseTextureZ",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],wW.prototype,"diffuseTextureZ",void 0),(0,je.Cg)([(0,$e.uM)("normalTextureX")],wW.prototype,"_normalTextureX",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],wW.prototype,"normalTextureX",void 0),(0,je.Cg)([(0,$e.uM)("normalTextureY")],wW.prototype,"_normalTextureY",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],wW.prototype,"normalTextureY",void 0),(0,je.Cg)([(0,$e.uM)("normalTextureZ")],wW.prototype,"_normalTextureZ",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],wW.prototype,"normalTextureZ",void 0),(0,je.Cg)([(0,$e.lK)()],wW.prototype,"tileSize",void 0),(0,je.Cg)([(0,$e.jT)()],wW.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.jT)()],wW.prototype,"specularColor",void 0),(0,je.Cg)([(0,$e.lK)()],wW.prototype,"specularPower",void 0),(0,je.Cg)([(0,$e.lK)("disableLighting")],wW.prototype,"_disableLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],wW.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.lK)("maxSimultaneousLights")],wW.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],wW.prototype,"maxSimultaneousLights",void 0),(0,X.Y5)("BABYLON.TriPlanarMaterial",wW);Cs.l.ShadersStore.waterPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#ifdef BUMP\nvarying vec2 vNormalUV;\n#ifdef BUMPSUPERIMPOSE\nvarying vec2 vNormalUV2;\n#endif\nuniform sampler2D normalSampler;uniform vec2 vNormalInfos;\n#endif\nuniform sampler2D refractionSampler;uniform sampler2D reflectionSampler;const float LOG2=1.442695;uniform vec3 cameraPosition;uniform vec4 waterColor;uniform float colorBlendFactor;uniform vec4 waterColor2;uniform float colorBlendFactor2;uniform float bumpHeight;uniform float time;varying vec3 vRefractionMapTexCoord;varying vec3 vReflectionMapTexCoord;\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef BUMP\n#ifdef BUMPSUPERIMPOSE\nbaseColor=0.6*texture2D(normalSampler,vNormalUV)+0.4*texture2D(normalSampler,vec2(vNormalUV2.x,vNormalUV2.y));\n#else\nbaseColor=texture2D(normalSampler,vNormalUV);\n#endif\nvec3 bumpColor=baseColor.rgb;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vNormalInfos.y;\n#else\nvec3 bumpColor=vec3(1.0);\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec2 perturbation=bumpHeight*(baseColor.rg-0.5);\n#ifdef BUMPAFFECTSREFLECTION\nvec3 normalW=normalize(vNormalW+vec3(perturbation.x*8.0,0.0,perturbation.y*8.0));if (normalW.y<0.0) {normalW.y=-normalW.y;}\n#else\nvec3 normalW=normalize(vNormalW);\n#endif\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);vec2 perturbation=bumpHeight*(vec2(1.0,1.0)-0.5);\n#endif\n#ifdef FRESNELSEPARATE\n#ifdef REFLECTION\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation*0.5,0.0,1.0);vec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\n#ifdef IS_REFRACTION_LINEAR\nrefractiveColor.rgb=toGammaSpace(refractiveColor.rgb);\n#endif\nvec2 projectedReflectionTexCoords=clamp(vec2(\nvReflectionMapTexCoord.x/vReflectionMapTexCoord.z+perturbation.x*0.3,\nvReflectionMapTexCoord.y/vReflectionMapTexCoord.z+perturbation.y\n),0.0,1.0);vec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\n#ifdef IS_REFLECTION_LINEAR\nreflectiveColor.rgb=toGammaSpace(reflectiveColor.rgb);\n#endif\nvec3 upVector=vec3(0.0,1.0,0.0);float fresnelTerm=clamp(abs(pow(dot(viewDirectionW,upVector),3.0)),0.05,0.65);float IfresnelTerm=1.0-fresnelTerm;refractiveColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*refractiveColor;reflectiveColor=IfresnelTerm*colorBlendFactor2*waterColor+(1.0-colorBlendFactor2*IfresnelTerm)*reflectiveColor;vec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*IfresnelTerm;baseColor=combinedColor;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#else \n#ifdef REFLECTION\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation,0.0,1.0);vec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\n#ifdef IS_REFRACTION_LINEAR\nrefractiveColor.rgb=toGammaSpace(refractiveColor.rgb);\n#endif\nvec2 projectedReflectionTexCoords=clamp(vReflectionMapTexCoord.xy/vReflectionMapTexCoord.z+perturbation,0.0,1.0);vec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\n#ifdef IS_REFLECTION_LINEAR\nreflectiveColor.rgb=toGammaSpace(reflectiveColor.rgb);\n#endif\nvec3 upVector=vec3(0.0,1.0,0.0);float fresnelTerm=max(dot(viewDirectionW,upVector),0.0);vec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*(1.0-fresnelTerm);baseColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*combinedColor;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#endif\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#elif defined(IMAGEPROCESSING)\ncolor.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color);\n#endif\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Cs.l.ShadersStore.waterVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef BUMP\nvarying vec2 vNormalUV;\n#ifdef BUMPSUPERIMPOSE\nvarying vec2 vNormalUV2;\n#endif\nuniform mat4 normalMatrix;uniform vec2 vNormalInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\nuniform mat4 reflectionViewProjection;uniform vec2 windDirection;uniform float waveLength;uniform float time;uniform float windForce;uniform float waveHeight;uniform float waveSpeed;uniform float waveCount;varying vec3 vRefractionMapTexCoord;varying vec3 vReflectionMapTexCoord;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef BUMP\nif (vNormalInfos.x==0.)\n{vNormalUV=vec2(normalMatrix*vec4((uv*1.0)/waveLength+time*windForce*windDirection,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv*0.721)/waveLength+time*1.2*windForce*windDirection,1.0,0.0));\n#endif\n}\nelse\n{vNormalUV=vec2(normalMatrix*vec4((uv2*1.0)/waveLength+time*windForce*windDirection ,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv2*0.721)/waveLength+time*1.2*windForce*windDirection ,1.0,0.0));\n#endif\n}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\nfloat finalWaveCount=1.0/(waveCount*0.5);\n#ifdef USE_WORLD_COORDINATES\nvec3 p=worldPos.xyz;\n#else\nvec3 p=position;\n#endif\nfloat newY=(sin(((p.x/finalWaveCount)+time*waveSpeed))*waveHeight*windDirection.x*5.0)\n+ (cos(((p.z/finalWaveCount)+ time*waveSpeed))*waveHeight*windDirection.y*5.0);p.y+=abs(newY);\n#ifdef USE_WORLD_COORDINATES\ngl_Position=viewProjection*vec4(p,1.0);\n#else\ngl_Position=viewProjection*finalWorld*vec4(p,1.0);\n#endif\n#ifdef REFLECTION\nvRefractionMapTexCoord.x=0.5*(gl_Position.w+gl_Position.x);vRefractionMapTexCoord.y=0.5*(gl_Position.w+gl_Position.y);vRefractionMapTexCoord.z=gl_Position.w;worldPos=reflectionViewProjection*finalWorld*vec4(position,1.0);vReflectionMapTexCoord.x=0.5*(worldPos.w+worldPos.x);vReflectionMapTexCoord.y=0.5*(worldPos.w+worldPos.y);vReflectionMapTexCoord.z=worldPos.w;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class NW extends xn{constructor(){super(),this.BUMP=!1,this.REFLECTION=!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.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.SPECULARTERM=!1,this.LOGARITHMICDEPTH=!1,this.USE_REVERSE_DEPTHBUFFER=!1,this.FRESNELSEPARATE=!1,this.BUMPSUPERIMPOSE=!1,this.BUMPAFFECTSREFLECTION=!1,this.USE_WORLD_COORDINATES=!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.rebuild()}}class FW extends bn{get hasRenderTargetTextures(){return!0}constructor(e,t,i=new W.I9(512,512)){super(e,t),this.renderTargetSize=i,this.diffuseColor=new H.v9(1,1,1),this.specularColor=new H.v9(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4,this.windForce=6,this.windDirection=new W.I9(0,1),this.waveHeight=.4,this.bumpHeight=.4,this._bumpSuperimpose=!1,this._fresnelSeparate=!1,this._bumpAffectsReflection=!1,this.waterColor=new H.v9(.1,.1,.6),this.colorBlendFactor=.2,this.waterColor2=new H.v9(.1,.1,.6),this.colorBlendFactor2=.2,this.waveLength=.1,this.waveSpeed=1,this.waveCount=20,this.disableClipPlane=!1,this._useWorldCoordinatesForWaveDeformation=!1,this._renderTargets=new Qe.L(16),this._mesh=null,this._reflectionTransform=W.uq.Zero(),this._lastTime=0,this._lastDeltaTime=0,this._createRenderTargets(this.getScene(),i),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._renderTargets.push(this._reflectionRTT),this._renderTargets.push(this._refractionRTT),this._renderTargets),this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}get refractionTexture(){return this._refractionRTT}get reflectionTexture(){return this._reflectionRTT}addToRenderList(e){this._refractionRTT&&this._refractionRTT.renderList&&this._refractionRTT.renderList.push(e),this._reflectionRTT&&this._reflectionRTT.renderList&&this._reflectionRTT.renderList.push(e)}removeFromRenderList(e){if(this._refractionRTT&&this._refractionRTT.renderList){const t=this._refractionRTT.renderList.indexOf(e);-1!==t&&this._refractionRTT.renderList.splice(t,1)}if(this._reflectionRTT&&this._reflectionRTT.renderList){const t=this._reflectionRTT.renderList.indexOf(e);-1!==t&&this._reflectionRTT.renderList.splice(t,1)}}enableRenderTargets(e){const t=e?1:0;this._refractionRTT&&(this._refractionRTT.refreshRate=t),this._reflectionRTT&&(this._reflectionRTT.refreshRate=t)}getRenderList(){return this._refractionRTT?this._refractionRTT.renderList:[]}get renderTargetsEnabled(){return!(this._refractionRTT&&0===this._refractionRTT.refreshRate)}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const r=t._drawWrapper;if(this.isFrozen&&r.effect&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new NW);const s=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(s._areTexturesDirty&&(s._needUVs=!1,n.texturesEnabled)){if(this.bumpTexture&&Sn.BumpTextureEnabled){if(!this.bumpTexture.isReady())return!1;s._needUVs=!0,s.BUMP=!0}Sn.ReflectionTextureEnabled&&(s.REFLECTION=!0)}if((0,Bt.OR)(n,o,this,s,!!i),(0,Bt.fm)(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s._areMiscDirty&&(s.FRESNELSEPARATE=this._fresnelSeparate,s.BUMPSUPERIMPOSE=this._bumpSuperimpose,s.BUMPAFFECTSREFLECTION=this._bumpAffectsReflection,s.USE_WORLD_COORDINATES=this._useWorldCoordinatesForWaveDeformation),s._needNormals=(0,Bt.az)(n,e,s,!0,this._maxSimultaneousLights,this._disableLighting),s._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s),s.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,s.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}if((0,Bt.qB)(e,s,!0,!0),this._mesh=e,this._waitingRenderList){for(let e=0;e0&&i.addCPUSkinningFallback(0,e);const r=[st.R.PositionKind];s.NORMAL&&r.push(st.R.NormalKind),s.UV1&&r.push(st.R.UVKind),s.UV2&&r.push(st.R.UV2Kind),s.VERTEXCOLOR&&r.push(st.R.ColorKind),(0,Bt.ni)(r,e,s,i),(0,Bt.ER)(r,s);const a="water",l=s.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vNormalInfos","mBones","normalMatrix","logarithmicDepthConstant","reflectionViewProjection","windDirection","waveLength","time","windForce","cameraPosition","bumpHeight","waveHeight","waterColor","waterColor2","colorBlendFactor","colorBlendFactor2","waveSpeed","waveCount"],c=["normalSampler","refractionSampler","reflectionSampler"],u=[];gn.p&&(gn.p.PrepareUniforms(h,s),gn.p.PrepareSamplers(c,s)),(0,Ln.TV)(h),(0,Bt.Bb)({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:s,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:r,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},o),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const r=this.getScene(),s=i.materialDefines;if(!s)return;const n=i.effect;if(!n||!this._mesh)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),(0,Bt.f$)(t,this._activeEffect),this._mustRebind(r,n,i)&&(this.bumpTexture&&Sn.BumpTextureEnabled&&(this._activeEffect.setTexture("normalSampler",this.bumpTexture),this._activeEffect.setFloat2("vNormalInfos",this.bumpTexture.coordinatesIndex,this.bumpTexture.level),this._activeEffect.setMatrix("normalMatrix",this.bumpTexture.getTextureMatrix())),(0,Ln.gS)(n,this,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&(0,Bt.DL)(s,n,r),r.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),r.lightsEnabled&&!this.disableLighting&&(0,Bt.RL)(r,t,this._activeEffect,s,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==oi.Z.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),(0,Bt.Yy)(r,t,this._activeEffect),(0,Bt.DL)(s,this._activeEffect,r),Sn.ReflectionTextureEnabled&&(this._activeEffect.setTexture("refractionSampler",this._refractionRTT),this._activeEffect.setTexture("reflectionSampler",this._reflectionRTT));const o=this._reflectionTransform.multiply(r.getProjectionMatrix()),a=r.getEngine().getDeltaTime();a!==this._lastDeltaTime&&(this._lastDeltaTime=a,this._lastTime+=this._lastDeltaTime),this._activeEffect.setMatrix("reflectionViewProjection",o),this._activeEffect.setVector2("windDirection",this.windDirection),this._activeEffect.setFloat("waveLength",this.waveLength),this._activeEffect.setFloat("time",this._lastTime/1e5),this._activeEffect.setFloat("windForce",this.windForce),this._activeEffect.setFloat("waveHeight",this.waveHeight),this._activeEffect.setFloat("bumpHeight",this.bumpHeight),this._activeEffect.setColor4("waterColor",this.waterColor,1),this._activeEffect.setFloat("colorBlendFactor",this.colorBlendFactor),this._activeEffect.setColor4("waterColor2",this.waterColor2,1),this._activeEffect.setFloat("colorBlendFactor2",this.colorBlendFactor2),this._activeEffect.setFloat("waveSpeed",this.waveSpeed),this._activeEffect.setFloat("waveCount",this.waveCount),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect),this._afterBind(t,this._activeEffect,i)}_createRenderTargets(e,t){this._refractionRTT=new ln.$(name+"_refraction",{width:t.x,height:t.y},e,!1,!0),this._refractionRTT.wrapU=Il.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.wrapV=Il.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.ignoreCameraViewport=!0;let i,r=!1;this._refractionRTT.onBeforeRenderObservable.add((()=>{r=e.getBoundingBoxRenderer().enabled,e.getBoundingBoxRenderer().enabled=!1})),this._refractionRTT.onAfterRenderObservable.add((()=>{e.getBoundingBoxRenderer().enabled=r})),this._reflectionRTT=new ln.$(name+"_reflection",{width:t.x,height:t.y},e,!1,!0),this._reflectionRTT.wrapU=Il.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.wrapV=Il.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.ignoreCameraViewport=!0;let s,n=null;const o=W.uq.Zero();this._refractionRTT.onBeforeRender=()=>{if(this._mesh&&(i=this._mesh.isVisible,this._mesh.isVisible=!1),!this.disableClipPlane){n=e.clipPlane;const t=this._mesh?this._mesh.absolutePosition.y:0;e.clipPlane=Ft.Z.FromPositionAndNormal(new W.Pq(0,t+.05,0),new W.Pq(0,1,0))}},this._refractionRTT.onAfterRender=()=>{this._mesh&&(this._mesh.isVisible=i),this.disableClipPlane||(e.clipPlane=n)},this._reflectionRTT.onBeforeRender=()=>{if(this._mesh&&(i=this._mesh.isVisible,this._mesh.isVisible=!1),!this.disableClipPlane){n=e.clipPlane;const t=this._mesh?this._mesh.absolutePosition.y:0;e.clipPlane=Ft.Z.FromPositionAndNormal(new W.Pq(0,t-.05,0),new W.Pq(0,-1,0)),W.uq.ReflectionToRef(e.clipPlane,o)}s=e.getViewMatrix(),o.multiplyToRef(s,this._reflectionTransform),e.setTransformMatrix(this._reflectionTransform,e.getProjectionMatrix()),e._mirroredCameraPosition=W.Pq.TransformCoordinates(e.activeCamera.position,o)},this._reflectionRTT.onAfterRender=()=>{this._mesh&&(this._mesh.isVisible=i),e.clipPlane=n,e.setTransformMatrix(s,e.getProjectionMatrix()),e._mirroredCameraPosition=null}}getAnimatables(){const e=[];return this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0&&e.push(this.bumpTexture),this._reflectionRTT&&this._reflectionRTT.animations&&this._reflectionRTT.animations.length>0&&e.push(this._reflectionRTT),this._refractionRTT&&this._refractionRTT.animations&&this._refractionRTT.animations.length>0&&e.push(this._refractionRTT),e}getActiveTextures(){const e=super.getActiveTextures();return this._bumpTexture&&e.push(this._bumpTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._bumpTexture===e}dispose(e){this.bumpTexture&&this.bumpTexture.dispose();let t=this.getScene().customRenderTargets.indexOf(this._refractionRTT);-1!=t&&this.getScene().customRenderTargets.splice(t,1),t=-1,t=this.getScene().customRenderTargets.indexOf(this._reflectionRTT),-1!=t&&this.getScene().customRenderTargets.splice(t,1),this._reflectionRTT&&this._reflectionRTT.dispose(),this._refractionRTT&&this._refractionRTT.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return it.p.Clone((()=>new FW(e,this.getScene())),this)}serialize(){const e=super.serialize();if(e.customType="BABYLON.WaterMaterial",e.renderList=[],this._refractionRTT&&this._refractionRTT.renderList)for(let t=0;tnew FW(e.name,t)),e,t,i);return r._waitingRenderList=e.renderList,r}static CreateDefaultMesh(e,t){return io(e,{width:512,height:512,subdivisions:32,updatable:!1},t)}}(0,je.Cg)([(0,$e.uM)("bumpTexture")],FW.prototype,"_bumpTexture",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsTexturesDirty")],FW.prototype,"bumpTexture",void 0),(0,je.Cg)([(0,$e.jT)()],FW.prototype,"diffuseColor",void 0),(0,je.Cg)([(0,$e.jT)()],FW.prototype,"specularColor",void 0),(0,je.Cg)([(0,$e.lK)()],FW.prototype,"specularPower",void 0),(0,je.Cg)([(0,$e.lK)("disableLighting")],FW.prototype,"_disableLighting",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],FW.prototype,"disableLighting",void 0),(0,je.Cg)([(0,$e.lK)("maxSimultaneousLights")],FW.prototype,"_maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsLightsDirty")],FW.prototype,"maxSimultaneousLights",void 0),(0,je.Cg)([(0,$e.lK)()],FW.prototype,"windForce",void 0),(0,je.Cg)([(0,$e.WM)()],FW.prototype,"windDirection",void 0),(0,je.Cg)([(0,$e.lK)()],FW.prototype,"waveHeight",void 0),(0,je.Cg)([(0,$e.lK)()],FW.prototype,"bumpHeight",void 0),(0,je.Cg)([(0,$e.lK)("bumpSuperimpose")],FW.prototype,"_bumpSuperimpose",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],FW.prototype,"bumpSuperimpose",void 0),(0,je.Cg)([(0,$e.lK)("fresnelSeparate")],FW.prototype,"_fresnelSeparate",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],FW.prototype,"fresnelSeparate",void 0),(0,je.Cg)([(0,$e.lK)("bumpAffectsReflection")],FW.prototype,"_bumpAffectsReflection",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],FW.prototype,"bumpAffectsReflection",void 0),(0,je.Cg)([(0,$e.jT)()],FW.prototype,"waterColor",void 0),(0,je.Cg)([(0,$e.lK)()],FW.prototype,"colorBlendFactor",void 0),(0,je.Cg)([(0,$e.jT)()],FW.prototype,"waterColor2",void 0),(0,je.Cg)([(0,$e.lK)()],FW.prototype,"colorBlendFactor2",void 0),(0,je.Cg)([(0,$e.lK)()],FW.prototype,"waveLength",void 0),(0,je.Cg)([(0,$e.lK)()],FW.prototype,"waveSpeed",void 0),(0,je.Cg)([(0,$e.lK)()],FW.prototype,"waveCount",void 0),(0,je.Cg)([(0,$e.lK)()],FW.prototype,"disableClipPlane",void 0),(0,je.Cg)([(0,$e.lK)("useWorldCoordinatesForWaveDeformation")],FW.prototype,"_useWorldCoordinatesForWaveDeformation",void 0),(0,je.Cg)([(0,$e.$z)("_markAllSubMeshesAsMiscDirty")],FW.prototype,"useWorldCoordinatesForWaveDeformation",void 0),(0,X.Y5)("BABYLON.WaterMaterial",FW);class LW{constructor(e){this.context=e}create(e){const t=new IW("bitbybit-skyMaterial",this.context.scene);return void 0!==e.luminance&&(t.luminance=e.luminance),void 0!==e.turbidity&&(t.turbidity=e.turbidity),void 0!==e.rayleigh&&(t.rayleigh=e.rayleigh),void 0!==e.mieCoefficient&&(t.mieCoefficient=e.mieCoefficient),void 0!==e.mieDirectionalG&&(t.mieDirectionalG=e.mieDirectionalG),void 0!==e.distance&&(t.distance=e.distance),void 0!==e.inclination&&(t.inclination=e.inclination),void 0!==e.azimuth&&(t.azimuth=e.azimuth),void 0!==e.sunPosition&&(t.sunPosition=new hc.Pq(e.sunPosition[0],e.sunPosition[1],e.sunPosition[2])),void 0!==e.useSunPosition&&(t.useSunPosition=e.useSunPosition),void 0!==e.cameraOffset&&(t.cameraOffset=new hc.Pq(e.cameraOffset[0],e.cameraOffset[1],e.cameraOffset[2])),void 0!==e.up&&(t.up=new hc.Pq(e.up[0],e.up[1],e.up[2])),void 0!==e.dithering&&(t.dithering=e.dithering),t}setLuminance(e){e.material.luminance=e.luminance}setTurbidity(e){e.material.turbidity=e.turbidity}setRayleigh(e){e.material.rayleigh=e.rayleigh}setMieCoefficient(e){e.material.mieCoefficient=e.mieCoefficient}setMieDirectionalG(e){e.material.mieDirectionalG=e.mieDirectionalG}setDistance(e){e.material.distance=e.distance}setInclination(e){e.material.inclination=e.inclination}setAzimuth(e){e.material.azimuth=e.azimuth}setSunPosition(e){e.material.sunPosition=new hc.Pq(e.sunPosition[0],e.sunPosition[1],e.sunPosition[2])}setUseSunPosition(e){e.material.useSunPosition=e.useSunPosition}setCameraOffset(e){e.material.cameraOffset=new hc.Pq(e.cameraOffset[0],e.cameraOffset[1],e.cameraOffset[2])}setUp(e){e.material.up=new hc.Pq(e.up[0],e.up[1],e.up[2])}setDithering(e){e.material.dithering=e.dithering}getLuminance(e){return e.skyMaterial.luminance}getTurbidity(e){return e.skyMaterial.turbidity}getRayleigh(e){return e.skyMaterial.rayleigh}getMieCoefficient(e){return e.skyMaterial.mieCoefficient}getMieDirectionalG(e){return e.skyMaterial.mieDirectionalG}getDistance(e){return e.skyMaterial.distance}getInclination(e){return e.skyMaterial.inclination}getAzimuth(e){return e.skyMaterial.azimuth}getSunPosition(e){return e.skyMaterial.sunPosition.asArray()}getUseSunPosition(e){return e.skyMaterial.useSunPosition}getCameraOffset(e){return e.skyMaterial.cameraOffset.asArray()}getUp(e){return e.skyMaterial.up.asArray()}getDithering(e){return e.skyMaterial.dithering}}class BW{constructor(e,t){this.context=e,this.color=t,this.pbrMetallicRoughness=new rW(e,t),this.skyMaterial=new LW(e)}}var VW=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class kW{constructor(e){this.context=e}createImmersiveARExperience(){return VW(this,void 0,void 0,(function*(){if(yield Qn.IsSessionSupportedAsync("immersive-ar"))return yield this.context.scene.createDefaultXRExperienceAsync({uiOptions:{sessionMode:"immersive-ar",referenceSpaceType:"local-floor"},outputCanvasOptions:{canvasOptions:{framebufferScaleFactor:2,antialias:!0}},optionalFeatures:!0});throw new Error("AR is not supported on this device.")}))}createDefaultXRExperienceWithTeleportation(e){return VW(this,void 0,void 0,(function*(){this.createDefaultXRExperienceWithTeleportationReturn(e)}))}createDefaultXRExperienceWithTeleportationReturn(e){return VW(this,void 0,void 0,(function*(){const t=yield this.context.scene.createDefaultXRExperienceAsync();this.context.scene.metadata?this.context.scene.metadata.xr=t:this.context.scene.metadata={xr:t};const i=[];e.groundMeshes.forEach((e=>{e.getChildMeshes&&(null==e||e.getChildMeshes().forEach((e=>{e.isPickable=!0,i.push(e)}))),i.push(e),e.isPickable=!0}));const r=t.baseExperience.featuresManager,s=new Cb("teleportation");s.baseColor=new hc.v9(0,0,1),s.metallic=0,s.roughness=1,r.enableFeature(hr.TELEPORTATION,"stable",{xrInput:t.input,floorMeshes:i,defaultTargetMeshOptions:{torusArrowMaterial:s,disableLighting:!1}});const n=new QV(this.context.scene);this.context.scene.metadata.guiManager=n,n.useRealisticScaling=!0;const o=new OV("near");n.addControl(o);const a=new SV("button1"),l=new dB;return l.text="Exit VR",l.color="white",l.fontSize="48px",a.onPointerClickObservable.add((()=>VW(this,void 0,void 0,(function*(){yield t.baseExperience.exitXRAsync()})))),o.addButton(a),a.content=l,{xr:t,torusMat:s,manager:n,near:o,button:a,text:l,dispose:()=>{t.dispose(),s.dispose(),n.dispose(),o.dispose(),a.dispose(),l.dispose()}}}))}}class UW{constructor(e){this.context=e,this.simple=new kW(e)}}class GW{constructor(e){this.context=e}getEngine(){return this.context.engine}getRenderingCanvas(){return this.context.engine.getRenderingCanvas()}}var zW;class WW{constructor(e){this.context=e}create(e){return t=this,i=void 0,s=function*(){if(void 0!==e.url)return xg.ImportMeshAsync(null,e.url,void 0,this.context.scene,void 0,".ply").then((e=>{const t=e.meshes[0];return t.name=`gaussian-splatting-${Math.random()}`,t}))},new((r=void 0)||(r=Promise))((function(e,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r((function(e){e(i)}))).then(o,a)}l((s=s.apply(t,i||[])).next())}));var t,i,r,s}clone(e){return e.babylonMesh.clone(`gaussian-splatting-${Math.random()}`)}getSplatPositions(e){const t=e.babylonMesh._splatPositions,i=[];for(let e=0;es[e]&&(s[e]=t),++n}}return{min:r,max:s}}static _NormalizeTangentFromRef(e){const t=Math.sqrt(e.x*e.x+e.y*e.y+e.z*e.z);t>0&&(e.x/=t,e.y/=t,e.z/=t)}static _GetDataAccessorElementCount(e){switch(e){case"MAT2":case"VEC4":return 4;case"MAT3":return 9;case"MAT4":return 16;case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3}}}!function(e){e[e.INTANGENT=0]="INTANGENT",e[e.OUTTANGENT=1]="OUTTANGENT"}(zW||(zW={}));class XW{static _IsTransformable(e){return e&&(e instanceof Pt||e instanceof rt||e instanceof $t)}static _CreateNodeAnimation(e,t,i,r,s){if(this._IsTransformable(e)){const n=[],o=[],a=t.getKeys(),l=XW._CalculateMinMaxKeyFrames(a),h=XW._DeduceInterpolation(a,i,r),c=h.interpolationType,u=h.shouldBakeAnimation;if(u?XW._CreateBakedAnimation(e,t,i,l.min,l.max,t.framePerSecond,s,n,o,l,r):"LINEAR"===c||"STEP"===c?XW._CreateLinearOrStepAnimation(e,t,i,n,o,r):"CUBICSPLINE"===c?XW._CreateCubicSplineAnimation(e,t,i,n,o,r):XW._CreateBakedAnimation(e,t,i,l.min,l.max,t.framePerSecond,s,n,o,l,r),n.length&&o.length)return{inputs:n,outputs:o,samplerInterpolation:c,inputsMin:u?l.min:Ue.S0.FloatRound(l.min/t.framePerSecond),inputsMax:u?l.max:Ue.S0.FloatRound(l.max/t.framePerSecond)}}return null}static _DeduceAnimationInfo(e){let t=null,i="VEC3",r=!1;const s=e.targetProperty.split(".");switch(s[0]){case"scaling":t="scale";break;case"position":t="translation";break;case"rotation":i="VEC4",t="rotation";break;case"rotationQuaternion":i="VEC4",r=!0,t="rotation";break;case"influence":i="SCALAR",t="weights";break;default:Ue.S0.Error(`Unsupported animatable property ${s[0]}`)}return t?{animationChannelTargetPath:t,dataAccessorType:i,useQuaternion:r}:(Ue.S0.Error("animation channel target path and data accessor type could be deduced"),null)}static _CreateNodeAnimationFromNodeAnimations(e,t,i,r,s,n,o,a,l,h){let c;if(XW._IsTransformable(e)&&e.animations)for(const s of e.animations){if(h&&!h(s))continue;const u=XW._DeduceAnimationInfo(s);u&&(c={name:s.name,samplers:[],channels:[]},XW._AddAnimation(`${s.name}`,s.hasRunningRuntimeAnimations?t:c,e,s,u.dataAccessorType,u.animationChannelTargetPath,r,n,o,a,u.useQuaternion,l),c.samplers.length&&c.channels.length&&i.push(c))}}static _CreateMorphTargetAnimationFromMorphTargetAnimations(e,t,i,r,s,n,o,a,l,h){let c;if(e instanceof Yt){const s=e.morphTargetManager;if(s)for(let u=0;u{for(let i=0;ie.morphTargetManager===i));r&&(h.has(r)||h.set(r,new Map),h.get(r)?.set(t,_),d.add(r),u.set(r,_))}}}}d.forEach((e=>{const t=e.morphTargetManager;let a=null;const d=[],p=u.get(e).getKeys(),_=p.length;for(let i=0;i<_;++i)for(let r=0;r0;)t=f.inputs.shift(),e%d==0&&i.push(t),e++;f.inputs=i}const r=o[i.uniqueId];let c=4*f.inputs.length;p=HW._CreateBufferView(0,a.getByteOffset(),c,void 0,`${e} keyframe data view`),l.push(p),f.inputs.forEach((function(e){a.setFloat32(e)})),_=HW._CreateAccessor(l.length-1,`${e} keyframes`,"SCALAR",5126,f.inputs.length,null,[f.inputsMin],[f.inputsMax]),h.push(_),m=h.length-1,v=f.outputs.length,c=4*HW._GetDataAccessorElementCount(s)*f.outputs.length,p=HW._CreateBufferView(0,a.getByteOffset(),c,void 0,`${e} data view`),l.push(p),f.outputs.forEach((function(e){e.forEach((function(e){a.setFloat32(e)}))})),_=HW._CreateAccessor(l.length-1,`${e} data`,s,5126,v,null,null,null),h.push(_),g=h.length-1,x={interpolation:f.samplerInterpolation,input:m,output:g},t.samplers.push(x),b={sampler:t.samplers.length-1,target:{node:r,path:n}},t.channels.push(b)}}static _CreateBakedAnimation(e,t,i,r,s,n,o,a,l,h,c){let u;const d=W.PT.Identity();let f,p=null,_=null,m=null,g=null,v=null,x=null;h.min=Ue.S0.FloatRound(r/n);const b=t.getKeys();for(let r=0,h=b.length;r{"StandardMaterial"===e.getClassName()?r.push(this._convertStandardMaterialAsync(e,t,i)):-1!==e.getClassName().indexOf("PBR")?r.push(this._convertPBRMaterialAsync(e,t,i)):Ue.S0.Warn(`Unsupported material type: ${e.name}`)})),Promise.all(r).then((()=>{}))}_stripTexturesFromMaterial(e){const t={};if(e){t.name=e.name,t.doubleSided=e.doubleSided,t.alphaMode=e.alphaMode,t.alphaCutoff=e.alphaCutoff,t.emissiveFactor=e.emissiveFactor;const i=e.pbrMetallicRoughness;i&&(t.pbrMetallicRoughness={},t.pbrMetallicRoughness.baseColorFactor=i.baseColorFactor,t.pbrMetallicRoughness.metallicFactor=i.metallicFactor,t.pbrMetallicRoughness.roughnessFactor=i.roughnessFactor)}return t}_hasTexturesPresent(e){if(e.emissiveTexture||e.normalTexture||e.occlusionTexture)return!0;const t=e.pbrMetallicRoughness;if(t&&(t.baseColorTexture||t.metallicRoughnessTexture))return!0;if(e.extensions)for(const t in e.extensions){const i=e.extensions[t];if(i)return i.hasTextures?.()}return!1}_getTextureInfo(e){if(e){const t=e.uid;if(t in this._textureMap)return this._textureMap[t]}return null}_convertToGLTFPBRMetallicRoughness(e){const t=new W.I9(0,1),i=new W.I9(0,.1),r=new W.I9(0,.1),s=new W.I9(1300,.1),n=e.diffuseColor.toLinearSpace(e.getScene().getEngine().useExactSrgbConversions).scale(.5),o=e.alpha,a=(l=Gy.Clamp(e.specularPower,0,YW._MaxSpecularPower),h=Math.pow(l/s.x,.333333),c=t.y,u=i.y,d=r.y,f=s.y,(1-h)*(1-h)*(1-h)*c+3*(1-h)*(1-h)*h*u+3*(1-h)*h*h*d+h*h*h*f);var l,h,c,u,d,f;return{baseColorFactor:[n.r,n.g,n.b,o],metallicFactor:0,roughnessFactor:a}}static _SolveMetallic(e,t,i){if(t{e&&(o.baseColorTexture=e)})));const i=e.bumpTexture;i&&n.push(this._exportTextureAsync(i,t).then((e=>{e&&(a.normalTexture=e,1!==i.level&&(a.normalTexture.scale=i.level))}))),e.emissiveTexture&&(a.emissiveFactor=[1,1,1],n.push(this._exportTextureAsync(e.emissiveTexture,t).then((e=>{e&&(a.emissiveTexture=e)})))),e.ambientTexture&&n.push(this._exportTextureAsync(e.ambientTexture,t).then((e=>{if(e){const t={index:e.index};a.occlusionTexture=t}})))}return(e.alpha<1||e.opacityTexture)&&(e.alphaMode===Il.ALPHA_COMBINE?a.alphaMode="BLEND":Ue.S0.Warn(e.name+": glTF 2.0 does not support alpha mode: "+e.alphaMode.toString())),e.emissiveColor&&!YW._FuzzyEquals(e.emissiveColor,H.v9.Black(),YW._Epsilon)&&(a.emissiveFactor=e.emissiveColor.asArray()),a.pbrMetallicRoughness=o,YW._SetAlphaMode(a,e),s.push(a),r[e.uniqueId]=s.length-1,this._finishMaterial(n,a,e,t)}_finishMaterial(e,t,i,r){return Promise.all(e).then((()=>{const e=this._exporter._extensionsPostExportMaterialAdditionalTextures("exportMaterial",t,i);let s=null;for(const t of e)s||(s=[]),s.push(this._exportTextureAsync(t,r));return s||(s=[Promise.resolve(null)]),Promise.all(s).then((()=>{const e=this._exporter._extensionsPostExportMaterialAsync("exportMaterial",t,i);return e?e.then((()=>t)):t}))}))}async _getImageDataAsync(e,t,i,r){const s=Il.TEXTURETYPE_UNSIGNED_INT,n=this._exporter._babylonScene,o=n.getEngine(),a=o.createRawTexture(e,t,i,Il.TEXTUREFORMAT_RGBA,!1,!0,vi.g.NEAREST_SAMPLINGMODE,null,s);await Ac.LO.ApplyPostProcess("pass",a,n,s,Il.TEXTURE_NEAREST_SAMPLINGMODE,Il.TEXTUREFORMAT_RGBA);const l=await o._readTexturePixels(a,t,i);return await UR.DumpTools.DumpDataAsync(t,i,l,r,void 0,!0,!0)}_createWhiteTexture(e,t,i){const r=new Uint8Array(e*t*4);for(let e=0;es.width?(o=t&&t instanceof vi.g?Ac.LO.CreateResizedCopy(t,r.width,r.height,!0):this._createWhiteTexture(r.width,r.height,i),n=e):(n=e,o=t),{texture1:n,texture2:o}}_convertPixelArrayToFloat32(e){if(e instanceof Uint8Array){const t=e.length,i=new Float32Array(e.length);for(let r=0;rYW._Epsilon?S.baseColor.r:1,m[i+1]/=S.baseColor.g>YW._Epsilon?S.baseColor.g:1,m[i+2]/=S.baseColor.b>YW._Epsilon?S.baseColor.b:1;const r=H.v9.FromInts(m[i],m[i+1],m[i+2]).toGammaSpace(n.getEngine().useExactSrgbConversions);m[i]=255*r.r,m[i+1]=255*r.g,m[i+2]=255*r.b,YW._FuzzyEquals(r,H.v9.White(),YW._Epsilon)||(C=!0),_[i+1]/=S.roughness>YW._Epsilon?S.roughness:1,_[i+2]/=S.metallic>YW._Epsilon?S.metallic:1;const s=H.v9.FromInts(255,_[i+1],_[i+2]);YW._FuzzyEquals(s,H.v9.White(),YW._Epsilon)||(T=!0)}return T&&s.push(this._getImageDataAsync(_,c,u,r).then((e=>{S.metallicRoughnessTextureData=e}))),C&&s.push(this._getImageDataAsync(m,c,u,r).then((e=>{S.baseColorTextureData=e}))),Promise.all(s).then((()=>S))}return Promise.reject("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!")}_convertSpecularGlossinessToMetallicRoughness(e){const t=this._getPerceivedBrightness(e.diffuseColor),i=this._getPerceivedBrightness(e.specularColor),r=1-this._getMaxComponent(e.specularColor),s=YW._SolveMetallic(t,i,r),n=e.diffuseColor.scale(r/(1-YW._DielectricSpecular.r)/Math.max(1-s,YW._Epsilon)),o=e.specularColor.subtract(YW._DielectricSpecular.scale(1-s)).scale(1/Math.max(s,YW._Epsilon));let a=H.v9.Lerp(n,o,s*s);return a=a.clampToRef(0,1,a),{baseColor:a,metallic:s,roughness:1-e.glossiness}}_getPerceivedBrightness(e){return e?Math.sqrt(.299*e.r*e.r+.587*e.g*e.g+.114*e.b*e.b):0}_getMaxComponent(e){return e?Math.max(e.r,Math.max(e.g,e.b)):0}_convertMetalRoughFactorsToMetallicRoughnessAsync(e,t,i,r){const s=[],n={baseColor:e._albedoColor,metallic:e._metallic,roughness:e._roughness};if(r){e._albedoTexture&&s.push(this._exportTextureAsync(e._albedoTexture,t).then((e=>{e&&(i.baseColorTexture=e)})));const r=e._metallicTexture;r&&s.push(this._exportTextureAsync(r,t).then((e=>{e&&(i.metallicRoughnessTexture=e)})))}return Promise.all(s).then((()=>n))}_getTextureSampler(e){const t={};if(!(e&&e instanceof vi.g))return t;const i=this._getGLTFTextureWrapMode(e.wrapU);10497!==i&&(t.wrapS=i);const r=this._getGLTFTextureWrapMode(e.wrapV);switch(10497!==r&&(t.wrapT=r),e.samplingMode){case vi.g.LINEAR_LINEAR:t.magFilter=9729,t.minFilter=9729;break;case vi.g.LINEAR_NEAREST:t.magFilter=9729,t.minFilter=9728;break;case vi.g.NEAREST_LINEAR:t.magFilter=9728,t.minFilter=9729;break;case vi.g.NEAREST_LINEAR_MIPLINEAR:t.magFilter=9728,t.minFilter=9987;break;case vi.g.NEAREST_NEAREST:t.magFilter=9728,t.minFilter=9728;break;case vi.g.NEAREST_LINEAR_MIPNEAREST:t.magFilter=9728,t.minFilter=9985;break;case vi.g.LINEAR_NEAREST_MIPNEAREST:t.magFilter=9729,t.minFilter=9984;break;case vi.g.LINEAR_NEAREST_MIPLINEAR:t.magFilter=9729,t.minFilter=9986;break;case vi.g.NEAREST_NEAREST_MIPLINEAR:t.magFilter=9728,t.minFilter=9986;break;case vi.g.LINEAR_LINEAR_MIPLINEAR:t.magFilter=9729,t.minFilter=9987;break;case vi.g.LINEAR_LINEAR_MIPNEAREST:t.magFilter=9729,t.minFilter=9985;break;case vi.g.NEAREST_NEAREST_MIPNEAREST:t.magFilter=9728,t.minFilter=9984}return t}_getGLTFTextureWrapMode(e){switch(e){case vi.g.WRAP_ADDRESSMODE:return 10497;case vi.g.CLAMP_ADDRESSMODE:return 33071;case vi.g.MIRROR_ADDRESSMODE:return 33648;default:return Ue.S0.Error(`Unsupported Texture Wrap Mode ${e}!`),10497}}_convertSpecGlossFactorsToMetallicRoughnessAsync(e,t,i,r){return Promise.resolve().then((()=>{const s={diffuseColor:e._albedoColor,specularColor:e._reflectivityColor,glossiness:e._microSurface},n=e._albedoTexture,o=e._reflectivityTexture,a=e._useMicroSurfaceFromReflectivityMapAlpha;if(o&&!a)return Promise.reject("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture are currently not supported");if((n||o)&&r){const e=this._exportTextureSampler(n||o);return this._convertSpecularGlossinessTexturesToMetallicRoughnessAsync(n,o,s,t).then((r=>{const s=this._exporter._textures;if(r.baseColorTextureData){const o=this._exportImage(`baseColor${s.length}`,t,r.baseColorTextureData);i.baseColorTexture=this._exportTextureInfo(o,e,n?.coordinatesIndex)}if(r.metallicRoughnessTextureData){const n=this._exportImage(`metallicRoughness${s.length}`,t,r.metallicRoughnessTextureData);i.metallicRoughnessTexture=this._exportTextureInfo(n,e,o?.coordinatesIndex)}return r}))}return this._convertSpecularGlossinessToMetallicRoughness(s)}))}_convertPBRMaterialAsync(e,t,i){const r={},s={name:e.name};if(e.isMetallicWorkflow()){const n=e._albedoColor,o=e.alpha;return n&&(r.baseColorFactor=[n.r,n.g,n.b,o]),this._convertMetalRoughFactorsToMetallicRoughnessAsync(e,t,r,i).then((n=>this._setMetallicRoughnessPbrMaterial(n,e,s,r,t,i)))}return this._convertSpecGlossFactorsToMetallicRoughnessAsync(e,t,r,i).then((n=>this._setMetallicRoughnessPbrMaterial(n,e,s,r,t,i)))}_setMetallicRoughnessPbrMaterial(e,t,i,r,s,n){const o=this._exporter._materialMap,a=this._exporter._materials,l=[];if(e){if(YW._SetAlphaMode(i,t),YW._FuzzyEquals(e.baseColor,H.v9.White(),YW._Epsilon)&&t.alpha>=YW._Epsilon||(r.baseColorFactor=[e.baseColor.r,e.baseColor.g,e.baseColor.b,t.alpha]),null!=e.metallic&&1!==e.metallic&&(r.metallicFactor=e.metallic),null!=e.roughness&&1!==e.roughness&&(r.roughnessFactor=e.roughness),null==t.backFaceCulling||t.backFaceCulling||(t._twoSidedLighting||Ue.S0.Warn(t.name+": Back-face culling disabled and two-sided lighting disabled is not supported in glTF."),i.doubleSided=!0),n){const e=t._bumpTexture;if(e){const t=this._exportTextureAsync(e,s).then((t=>{t&&(i.normalTexture=t,1!==e.level&&(i.normalTexture.scale=e.level))}));l.push(t)}const r=t._ambientTexture;if(r){const e=this._exportTextureAsync(r,s).then((e=>{if(e){const r={index:e.index,texCoord:e.texCoord,extensions:e.extensions};i.occlusionTexture=r;const s=t._ambientTextureStrength;s&&(r.strength=s)}}));l.push(e)}const n=t._emissiveTexture;if(n){const e=this._exportTextureAsync(n,s).then((e=>{e&&(i.emissiveTexture=e)}));l.push(e)}}const h=t._emissiveColor;YW._FuzzyEquals(h,H.v9.Black(),YW._Epsilon)||(i.emissiveFactor=h.asArray()),i.pbrMetallicRoughness=r,a.push(i),o[t.uniqueId]=a.length-1}return this._finishMaterial(l,i,t,s)}_getPixelsFromTexture(e){return e.textureType,Il.TEXTURETYPE_UNSIGNED_INT,e.readPixels()}_exportTextureAsync(e,t){const i=this._exporter._extensionsPreExportTextureAsync("exporter",e,t);return i?i.then((i=>i?this._exportTextureInfoAsync(i,t):this._exportTextureInfoAsync(e,t))):this._exportTextureInfoAsync(e,t)}async _exportTextureInfoAsync(e,t){const i=e.uid;if(!(i in this._textureMap)){const r=await this._getPixelsFromTexture(e);if(!r)return null;const s=this._exportTextureSampler(e),n=e.mimeType;if(n)switch(n){case"image/jpeg":case"image/png":case"image/webp":t=n;break;default:Ue.S0.Warn(`Unsupported media type: ${n}`)}const o=this._internalTextureToImage,a=e.getInternalTexture().uniqueId;o[a]||(o[a]={});let l=o[a][t];if(void 0===l){const i=e.getSize();l=(async()=>{const s=await this._getImageDataAsync(r,i.width,i.height,t);return this._exportImage(e.name,t,s)})(),o[a][t]=l}const h=this._exportTextureInfo(await l,s,e.coordinatesIndex);this._textureMap[i]=h,this._exporter._extensionsPostExportTextures("exporter",this._textureMap[i],e)}return this._textureMap[i]}_exportImage(e,t,i){const r=this._exporter._imageData,s=e.replace(/\.\/|\/|\.\\|\\/g,"_"),n=function(e){switch(e){case"image/jpeg":return".jpg";case"image/png":return".png";case"image/webp":return".webp";case"image/avif":return".avif"}}(t);let o=s+n;o in r&&(o=`${s}_${Ue.S0.RandomId()}${n}`),r[o]={data:i,mimeType:t};const a=this._exporter._images;return a.push({name:e,uri:o}),a.length-1}_exportTextureInfo(e,t,i){const r=this._exporter._textures;let s=r.findIndex((i=>i.sampler==t&&i.source===e));-1===s&&(s=r.length,r.push({source:e,sampler:t}));const n={index:s};return i&&(n.texCoord=i),n}_exportTextureSampler(e){const t=this._getTextureSampler(e),i=this._exporter._samplers,r=i.findIndex((e=>e.minFilter===t.minFilter&&e.magFilter===t.magFilter&&e.wrapS===t.wrapS&&e.wrapT===t.wrapT));return-1!==r?r:(i.push(t),i.length-1)}}YW._DielectricSpecular=new H.v9(.04,.04,.04),YW._MaxSpecularPower=1024,YW._Epsilon=1e-6;const KW=W.uq.Compose(new W.Pq(-1,1,1),W.PT.Identity(),W.Pq.Zero()),jW=new W.PT(0,1,0,0);function $W(e,t){if(!(e instanceof Pt))return!1;if(t){if(!e.getWorldMatrix().isIdentity())return!1}else if(!e.getWorldMatrix().multiplyToRef(KW,W.AA.Matrix[0]).isIdentity())return!1;return!(e instanceof Yt&&e.geometry||e instanceof Kt&&e.sourceMesh.geometry)}function QW(e){const t=W.Pq.FromArrayToRef(e.translation||[0,0,0],0,W.AA.Vector3[0]),i=W.PT.FromArrayToRef(e.rotation||[0,0,0,1],0,W.AA.Quaternion[0]),r=W.Pq.FromArrayToRef(e.scale||[1,1,1],0,W.AA.Vector3[1]);W.uq.ComposeToRef(r,i,t,W.AA.Matrix[0]).multiplyToRef(KW,W.AA.Matrix[0]).decompose(r,i,t),t.equalsToFloats(0,0,0)?delete e.translation:e.translation=t.asArray(),W.PT.IsIdentity(i)?delete e.rotation:e.rotation=i.asArray(),r.equalsToFloats(1,1,1)?delete e.scale:e.scale=r.asArray()}function ZW(e,t){switch(t){case 5121:return e.setUInt8.bind(e);case 5123:return e.setUInt16.bind(e);case 5125:return e.setUInt32.bind(e);case 5126:return e.setFloat32.bind(e);default:return Ue.S0.Warn("Unsupported Attribute Component kind: "+t),null}}class JW{_applyExtension(e,t,i,r){if(i>=t.length)return Promise.resolve(e);const s=r(t[i],e);return s?s.then((e=>this._applyExtension(e,t,i+1,r))):this._applyExtension(e,t,i+1,r)}_applyExtensions(e,t){const i=[];for(const e of JW._ExtensionNames)i.push(this._extensions[e]);return this._applyExtension(e,i,0,t)}_extensionsPreExportTextureAsync(e,t,i){return this._applyExtensions(t,((t,r)=>t.preExportTextureAsync&&t.preExportTextureAsync(e,r,i)))}_extensionsPostExportMeshPrimitiveAsync(e,t,i,r){return this._applyExtensions(t,((t,s)=>t.postExportMeshPrimitiveAsync&&t.postExportMeshPrimitiveAsync(e,s,i,r)))}_extensionsPostExportNodeAsync(e,t,i,r,s){return this._applyExtensions(t,((t,n)=>t.postExportNodeAsync&&t.postExportNodeAsync(e,n,i,r,s)))}_extensionsPostExportMaterialAsync(e,t,i){return this._applyExtensions(t,((t,r)=>t.postExportMaterialAsync&&t.postExportMaterialAsync(e,r,i)))}_extensionsPostExportMaterialAdditionalTextures(e,t,i){const r=[];for(const s of JW._ExtensionNames){const n=this._extensions[s];n.postExportMaterialAdditionalTextures&&r.push(...n.postExportMaterialAdditionalTextures(e,t,i))}return r}_extensionsPostExportTextures(e,t,i){for(const r of JW._ExtensionNames){const s=this._extensions[r];s.postExportTexture&&s.postExportTexture(e,t,i)}}_forEachExtensions(e){for(const t of JW._ExtensionNames){const i=this._extensions[t];i.enabled&&e(i)}}_extensionsOnExporting(){this._forEachExtensions((e=>{e.wasUsed&&(null==this._glTF.extensionsUsed&&(this._glTF.extensionsUsed=[]),-1===this._glTF.extensionsUsed.indexOf(e.name)&&this._glTF.extensionsUsed.push(e.name),e.required&&(null==this._glTF.extensionsRequired&&(this._glTF.extensionsRequired=[]),-1===this._glTF.extensionsRequired.indexOf(e.name)&&this._glTF.extensionsRequired.push(e.name)),null==this._glTF.extensions&&(this._glTF.extensions={}),e.onExporting&&e.onExporting())}))}_loadExtensions(){for(const e of JW._ExtensionNames){const t=JW._ExtensionFactories[e](this);this._extensions[e]=t}}constructor(e,t){this._extensions={},this._glTF={asset:{generator:`Babylon.js v${an.Version}`,version:"2.0"}},(e=e||he.q.LastCreatedScene)&&(this._babylonScene=e,this._bufferViews=[],this._accessors=[],this._meshes=[],this._scenes=[],this._cameras=[],this._nodes=[],this._images=[],this._materials=[],this._materialMap=[],this._textures=[],this._samplers=[],this._skins=[],this._animations=[],this._imageData={},this._orderedImageData=[],this._options=t||{},this._animationSampleRate=this._options.animationSampleRate||1/60,this._glTFMaterialExporter=new YW(this),this._loadExtensions())}dispose(){for(const e in this._extensions)this._extensions[e].dispose()}get options(){return this._options}static RegisterExtension(e,t){JW.UnregisterExtension(e)&&Ue.S0.Warn(`Extension with the name ${e} already exists`),JW._ExtensionFactories[e]=t,JW._ExtensionNames.push(e)}static UnregisterExtension(e){if(!JW._ExtensionFactories[e])return!1;delete JW._ExtensionFactories[e];const t=JW._ExtensionNames.indexOf(e);return-1!==t&&JW._ExtensionNames.splice(t,1),!0}_reorderIndicesBasedOnPrimitiveMode(e,t,i,r,s){switch(t){case Vt.TriangleFillMode:r||(r=0);for(let t=e.indexStart,i=e.indexStart+e.indexCount;t=n;--t)s.setUInt32(i[t],r),r+=4;break;case Vt.TriangleStripDrawMode:e.indexCount>=3&&(s.setUInt32(i[e.indexStart+2],r+4),s.setUInt32(i[e.indexStart+1],r+8))}}_reorderVertexAttributeDataBasedOnPrimitiveMode(e,t,i,r,s,n){switch(t){case Vt.TriangleFillMode:this._reorderTriangleFillMode(e,i,r,s,n);break;case Vt.TriangleStripDrawMode:this._reorderTriangleStripDrawMode(e,i,r,s,n);break;case Vt.TriangleFanDrawMode:this._reorderTriangleFanMode(e,i,r,s,n)}}_reorderTriangleFillMode(e,t,i,r,s){const n=this._getVertexBufferFromMesh(t,e.getMesh());if(n){const o=n.byteStride/st.R.GetTypeByteLength(n.type);if(e.verticesCount%3!=0)Ue.S0.Error("The submesh vertices for the triangle fill mode is not divisible by 3!");else{const a=[];let l=0;switch(t){case st.R.PositionKind:case st.R.NormalKind:for(let t=e.verticesStart;t=e.verticesStart;--t)l=t*o,a.push(W.IU.FromArray(i,l));break;case st.R.ColorKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,4===n.getSize()?a.push(W.IU.FromArray(i,l)):a.push(W.Pq.FromArray(i,l));break;case st.R.UVKind:case st.R.UV2Kind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(W.I9.FromArray(i,l));break;default:Ue.S0.Error(`Unsupported Vertex Buffer type: ${t}`)}this._writeVertexAttributeData(a,r+12,t,s)}else Ue.S0.Warn(`reorderTriangleStripDrawMode: Vertex buffer kind ${t} not present!`)}_reorderTriangleFanMode(e,t,i,r,s){const n=this._getVertexBufferFromMesh(t,e.getMesh());if(n){const o=n.byteStride/st.R.GetTypeByteLength(n.type),a=[];let l=0;switch(t){case st.R.PositionKind:case st.R.NormalKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(W.Pq.FromArray(i,l));break;case st.R.TangentKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(W.IU.FromArray(i,l));break;case st.R.ColorKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(W.IU.FromArray(i,l)),4===n.getSize()?a.push(W.IU.FromArray(i,l)):a.push(W.Pq.FromArray(i,l));break;case st.R.UVKind:case st.R.UV2Kind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(W.I9.FromArray(i,l));break;default:Ue.S0.Error(`Unsupported Vertex Buffer type: ${t}`)}this._writeVertexAttributeData(a,r,t,s)}else Ue.S0.Warn(`reorderTriangleFanMode: Vertex buffer kind ${t} not present!`)}_writeVertexAttributeData(e,t,i,r){for(const s of e){i===st.R.NormalKind?s.normalize():i===st.R.TangentKind&&s instanceof W.IU&&HW._NormalizeTangentFromRef(s);for(const e of s.asArray())r.setFloat32(e,t),t+=4}}_writeAttributeData(e,t,i,r,s,n){let o,a=[];switch(e){case st.R.PositionKind:for(let e=0,t=i.length/r;e{e.uri&&(n=this._imageData[e.uri],this._orderedImageData.push(n),s=e.uri.split(".")[0]+" image",o=HW._CreateBufferView(0,a,n.data.byteLength,void 0,s),a+=n.data.byteLength,this._bufferViews.push(o),e.bufferView=this._bufferViews.length-1,e.name=s,e.mimeType=n.mimeType,e.uri=void 0,this._glTF.images||(this._glTF.images=[]),this._glTF.images.push(e))})),r.byteLength=a):this._glTF.images=this._images),e||(r.uri=t+".bin"),i?JSON.stringify(this._glTF,null,2):JSON.stringify(this._glTF)}_generateGLTFAsync(e,t=!0){return this._generateBinaryAsync().then((i=>{this._extensionsOnExporting();const r=this._generateJSON(!1,e,!0),s=new Blob([i],{type:"application/octet-stream"}),n=e+".gltf",o=e+".bin",a=new qW;if(a.glTFFiles[n]=r,a.glTFFiles[o]=s,this._imageData)for(const e in this._imageData)a.glTFFiles[e]=new Blob([this._imageData[e].data],{type:this._imageData[e].mimeType});return t&&this.dispose(),a}))}_generateBinaryAsync(){const e=new eH(4);return this._createSceneAsync(e).then((()=>(this._localEngine&&this._localEngine.dispose(),e.getArrayBuffer())))}_getPadding(e){const t=e%4;return 0===t?t:4-t}_generateGLBAsync(e,t=!0){return this._generateBinaryAsync().then((i=>{this._extensionsOnExporting();const r=this._generateJSON(!0),s=e+".glb";let n,o=r.length,a=0;"undefined"!=typeof TextEncoder&&(n=(new TextEncoder).encode(r),o=n.length);for(let e=0;e0){if(d._getEffectiveOrientation(o)===(this._babylonScene.useRightHandedSystem?Vt.ClockWiseSideOrientation:Vt.CounterClockWiseSideOrientation)){let e=null!=l?this._bufferViews[l].byteOffset:null;null==e&&(e=0);let t=null;if(null!=l&&(t=o.getIndices()),t)this._reorderIndicesBasedOnPrimitiveMode(s,h,t,e,i);else for(const e of a){const t=o.getVerticesData(e.kind,void 0,void 0,!0);if(t){const r=this._bufferViews[c[e.kind]].byteOffset||0;this._reorderVertexAttributeDataBasedOnPrimitiveMode(s,h,e.kind,t,r,i)}}}null!=f&&(_.material=f)}if(u){e.extras||(e.extras={}),e.extras.targetNames=[];for(let t=0;t{}))}_createSceneAsync(e){const t={nodes:[]};let i,r,s;const n=[...this._babylonScene.transformNodes,...this._babylonScene.meshes,...this._babylonScene.lights,...this._babylonScene.cameras],o=new Set;if(this._babylonScene.metadata&&(this._options.metadataSelector?t.extras=this._options.metadataSelector(this._babylonScene.metadata):this._babylonScene.metadata.gltf&&(t.extras=this._babylonScene.metadata.gltf.extras)),(this._options.removeNoopRootNodes??1)&&!this._options.includeCoordinateSystemConversionNodes)for(const e of this._babylonScene.rootNodes)$W(e,this._babylonScene.useRightHandedSystem)&&(o.add(e),n.splice(n.indexOf(e),1));const a=new Map;this._babylonScene.cameras.forEach((e=>{if(this._options.shouldExportNode&&!this._options.shouldExportNode(e))return;const t={type:e.mode===rt.PERSPECTIVE_CAMERA?"perspective":"orthographic"};if(e.name&&(t.name=e.name),"perspective"===t.type)t.perspective={aspectRatio:e.getEngine().getAspectRatio(e),yfov:e.fovMode===rt.FOVMODE_VERTICAL_FIXED?e.fov:e.fov*e.getEngine().getAspectRatio(e),znear:e.minZ,zfar:e.maxZ};else if("orthographic"===t.type){const i=e.orthoLeft&&e.orthoRight?.5*(e.orthoRight-e.orthoLeft):.5*e.getEngine().getRenderWidth(),r=e.orthoBottom&&e.orthoTop?.5*(e.orthoTop-e.orthoBottom):.5*e.getEngine().getRenderHeight();t.orthographic={xmag:i,ymag:r,znear:e.minZ,zfar:e.maxZ}}a.set(e,this._cameras.length),this._cameras.push(t)}));const[l,h]=this._getExportNodes(n);return this._glTFMaterialExporter._convertMaterialsToGLTFAsync(h,"image/png",!0).then((()=>this._createNodeMapAndAnimationsAsync(l,e).then((l=>this._createSkinsAsync(l,e).then((h=>{if(this._nodeMap=l,this._totalByteLength=e.getByteOffset(),null==this._totalByteLength)throw new Error("undefined byte length!");for(const e of n)if(i=this._nodeMap[e.uniqueId],void 0!==i&&(r=this._nodes[i],e.metadata&&(this._options.metadataSelector?r.extras=this._options.metadataSelector(e.metadata):e.metadata.gltf&&(r.extras=e.metadata.gltf.extras)),e instanceof rt&&(r.camera=a.get(e)),this._options.shouldExportNode&&!this._options.shouldExportNode(e)?Ue.S0.Log("Omitting "+e.name+" from scene."):(e.parent||this._babylonScene.useRightHandedSystem||QW(r),e.parent&&!o.has(e.parent)||t.nodes.push(i)),e instanceof Yt&&e.skeleton&&(r.skin=h[e.skeleton.uniqueId]),s=e.getDescendants(!0),!r.children&&s&&s.length)){const e=[];for(const t of s)null!=this._nodeMap[t.uniqueId]&&e.push(this._nodeMap[t.uniqueId]);e.length&&(r.children=e)}t.nodes.length&&this._scenes.push(t)}))))))}_getExportNodes(e){const t=[],i=new Set;for(const r of e)if(!this._options.shouldExportNode||this._options.shouldExportNode(r)){t.push(r);const e=r;if(e.subMeshes&&e.subMeshes.length>0){const t=e.material||e.getScene().defaultMaterial;if(t instanceof kt)for(const e of t.subMaterials)e&&i.add(e);else i.add(t)}}else r.name;return[t,i]}_createNodeMapAndAnimationsAsync(e,t){let i=Promise.resolve();const r={};let s;const n={name:"runtime animations",channels:[],samplers:[]},o=[];for(const a of e)i=i.then((()=>this._createNodeAsync(a,t).then((e=>{const i=this._extensionsPostExportNodeAsync("createNodeAsync",e,a,r,t);return null==i?(Ue.S0.Warn(`Not exporting node ${a.name}`),Promise.resolve()):i.then((e=>{e&&(this._nodes.push(e),s=this._nodes.length-1,r[a.uniqueId]=s,this._babylonScene.animationGroups.length||(XW._CreateMorphTargetAnimationFromMorphTargetAnimations(a,n,o,r,this._nodes,t,this._bufferViews,this._accessors,this._animationSampleRate,this._options.shouldExportAnimation),a.animations.length&&XW._CreateNodeAnimationFromNodeAnimations(a,n,o,r,this._nodes,t,this._bufferViews,this._accessors,this._animationSampleRate,this._options.shouldExportAnimation)))}))}))));return i.then((()=>(n.channels.length&&n.samplers.length&&this._animations.push(n),o.forEach((e=>{e.channels.length&&e.samplers.length&&this._animations.push(e)})),this._babylonScene.animationGroups.length&&XW._CreateNodeAndMorphAnimationFromAnimationGroups(this._babylonScene,this._animations,r,t,this._bufferViews,this._accessors,this._animationSampleRate,this._options.shouldExportAnimation),r)))}_createNodeAsync(e,t){return Promise.resolve().then((()=>{const i={},r={primitives:[]};if(e.name&&(i.name=e.name),e instanceof Pt){if(this._setNodeTransformation(i,e),e instanceof Yt){const t=e.morphTargetManager;if(t&&t.numTargets>0){r.weights=[];for(let e=0;e(r.primitives.length&&(this._meshes.push(r),i.mesh=this._meshes.length-1),i)))}return e instanceof rt?(this._setCameraTransformation(i,e),i):i}))}_createSkinsAsync(e,t){const i=Promise.resolve(),r={};for(const i of this._babylonScene.skeletons){if(i.bones.length<=0)continue;const s={joints:[]},n=[],o={};let a=-1;for(let e=0;ea&&(a=r))}for(let t=0;t<=a;++t){const i=o[t];n.push(i.getInvertedAbsoluteTransform());const r=i.getTransformNode();r&&null!==e[r.uniqueId]&&void 0!==e[r.uniqueId]?s.joints.push(e[r.uniqueId]):Ue.S0.Warn("Exporting a bone without a linked transform node is currently unsupported")}if(s.joints.length>0){const e=64,o=n.length*e,a=t.getByteOffset(),l=HW._CreateBufferView(0,a,o,void 0,"InverseBindMatrices - "+i.name);this._bufferViews.push(l);const h=this._bufferViews.length-1,c=HW._CreateAccessor(h,"InverseBindMatrices - "+i.name,"MAT4",5126,n.length,null,null,null),u=this._accessors.push(c)-1;s.inverseBindMatrices=u,this._skins.push(s),r[i.uniqueId]=this._skins.length-1,n.forEach((e=>{e.m.forEach((e=>{t.setFloat32(e)}))}))}}return i.then((()=>r))}}JW._ExtensionNames=new Array,JW._ExtensionFactories={};class eH{constructor(e){this._arrayBuffer=new ArrayBuffer(e),this._dataView=new DataView(this._arrayBuffer),this._byteOffset=0}_resizeBuffer(e){const t=new ArrayBuffer(e),i=Math.min(this._arrayBuffer.byteLength,e),r=new Uint8Array(this._arrayBuffer,0,i);return new Uint8Array(t).set(r,0),this._arrayBuffer=t,this._dataView=new DataView(this._arrayBuffer),t}getArrayBuffer(){return this._resizeBuffer(this.getByteOffset())}getByteOffset(){if(null==this._byteOffset)throw new Error("Byte offset is undefined!");return this._byteOffset}setUInt8(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setUint8(this._byteOffset,e),this._byteOffset+=1)}setUInt16(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setUint16(this._byteOffset,e,!0),this._byteOffset+=2)}getUInt32(e){if(ethis._byteOffset?Ue.S0.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(e.x=this._dataView.getFloat32(t,!0),e.y=this._dataView.getFloat32(t+4,!0),e.z=this._dataView.getFloat32(t+8,!0))}setVector3Float32FromRef(e,t){t+8>this._byteOffset?Ue.S0.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(this._dataView.setFloat32(t,e.x,!0),this._dataView.setFloat32(t+4,e.y,!0),this._dataView.setFloat32(t+8,e.z,!0))}getVector4Float32FromRef(e,t){t+12>this._byteOffset?Ue.S0.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(e.x=this._dataView.getFloat32(t,!0),e.y=this._dataView.getFloat32(t+4,!0),e.z=this._dataView.getFloat32(t+8,!0),e.w=this._dataView.getFloat32(t+12,!0))}setVector4Float32FromRef(e,t){t+12>this._byteOffset?Ue.S0.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(this._dataView.setFloat32(t,e.x,!0),this._dataView.setFloat32(t+4,e.y,!0),this._dataView.setFloat32(t+8,e.z,!0),this._dataView.setFloat32(t+12,e.w,!0))}setFloat32(e,t){isNaN(e)&&Ue.S0.Error("Invalid data being written!"),null!=t&&(tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setFloat32(this._byteOffset,e,!0),this._byteOffset+=4}setUInt32(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setUint32(this._byteOffset,e,!0),this._byteOffset+=4)}setInt16(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setInt16(this._byteOffset,e,!0),this._byteOffset+=2)}setByte(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setInt8(this._byteOffset,e),this._byteOffset++)}}class tH{static GLTFAsync(e,t,i){return e.whenReadyAsync().then((()=>{const r=t.replace(/\.[^/.]+$/,"");return new JW(e,i)._generateGLTFAsync(r)}))}static _PreExportAsync(e,t){return Promise.resolve().then((()=>t&&t.exportWithoutWaitingForScene?Promise.resolve():e.whenReadyAsync()))}static _PostExportAsync(e,t,i){return Promise.resolve().then((()=>(i&&i.exportWithoutWaitingForScene,t)))}static GLBAsync(e,t,i){return this._PreExportAsync(e,i).then((()=>{const r=t.replace(/\.[^/.]+$/,"");return new JW(e,i)._generateGLBAsync(r).then((t=>this._PostExportAsync(e,t,i)))}))}}const iH="KHR_texture_transform";class rH{constructor(){this.name=iH,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}postExportTexture(e,t,i){if(i&&(0===i.uAng&&0===i.wAng&&0===i.vAng||0===i.uRotationCenter&&0===i.vRotationCenter)){const e={};let r=!1;if(0===i.uOffset&&0===i.vOffset||(e.offset=[i.uOffset,i.vOffset],r=!0),1===i.uScale&&1===i.vScale||(e.scale=[i.uScale,i.vScale],r=!0),0!==i.wAng&&(e.rotation=-i.wAng,r=!0),0!==i.coordinatesIndex&&(e.texCoord=i.coordinatesIndex,r=!0),!r)return;this._wasUsed=!0,t.extensions||(t.extensions={}),t.extensions[iH]=e}}preExportTextureAsync(e,t){return new Promise(((i,r)=>{t.getScene()?0!==t.uAng||0!==t.vAng?(Ue.S0.Warn(`${e}: Texture ${t.name} with rotation in the u or v axis is not supported in glTF.`),i(null)):0===t.wAng||0===t.uRotationCenter&&0===t.vRotationCenter?i(t):(Ue.S0.Warn(`${e}: Texture ${t.name} with rotation not centered at the origin cannot be exported with ${iH}`),i(null)):r(`${e}: "scene" is not defined for Babylon texture ${t.name}!`)}))}}JW.RegisterExtension(iH,(()=>new rH));const sH="KHR_lights_punctual";class nH{constructor(e){this.name=sH,this.enabled=!0,this.required=!1,this._exporter=e}dispose(){this._lights=null}get wasUsed(){return!!this._lights}onExporting(){this._exporter._glTF.extensions[sH]=this._lights}postExportNodeAsync(e,t,i,r){return new Promise((s=>{if(t&&i instanceof lm){let n;const o=i.getTypeID()==$t.LIGHTTYPEID_POINTLIGHT?"point":i.getTypeID()==$t.LIGHTTYPEID_DIRECTIONALLIGHT?"directional":i.getTypeID()==$t.LIGHTTYPEID_SPOTLIGHT?"spot":null;if(null==o)Z.V.Warn(`${e}: Light ${i.name} is not supported in ${sH}`);else{if(i.position.equalsToFloats(0,0,0)||(t.translation=i.position.asArray()),"point"!==o){const e=i.direction,r=-Math.atan2(e.z,e.x)+Math.PI/2,s=Math.sqrt(e.x*e.x+e.z*e.z),n=-Math.atan2(e.y,s),o=W.PT.RotationYawPitchRoll(r+Math.PI,n,0);W.PT.IsIdentity(o)||(t.rotation=o.asArray())}if(i.falloffType!==$t.FALLOFF_GLTF&&Z.V.Warn(`${e}: Light falloff for ${i.name} does not match the ${sH} specification!`),n={type:o},i.diffuse.equals(H.v9.White())||(n.color=i.diffuse.asArray()),1!==i.intensity&&(n.intensity=i.intensity),i.range!==Number.MAX_VALUE&&(n.range=i.range),"spot"===o){const e=i;e.angle!==Math.PI/2&&(null==n.spot&&(n.spot={}),n.spot.outerConeAngle=e.angle/2),0!==e.innerAngle&&(null==n.spot&&(n.spot={}),n.spot.innerConeAngle=e.innerAngle/2)}this._lights||(this._lights={lights:[]}),this._lights.lights.push(n);const a={light:this._lights.lights.length-1},l=i.parent;if(l&&1==l.getChildren().length){const e=this._exporter._nodes[r[l.uniqueId]];if(e){const i=W.Pq.FromArrayToRef(e.translation||[0,0,0],0,W.AA.Vector3[0]),r=W.PT.FromArrayToRef(e.rotation||[0,0,0,1],0,W.AA.Quaternion[0]),n=W.Pq.FromArrayToRef(e.scale||[1,1,1],0,W.AA.Vector3[1]),o=W.uq.ComposeToRef(n,r,i,W.AA.Matrix[0]),l=W.Pq.FromArrayToRef(t.translation||[0,0,0],0,W.AA.Vector3[2]),h=W.PT.FromArrayToRef(t.rotation||[0,0,0,1],0,W.AA.Quaternion[1]),c=W.uq.ComposeToRef(W.Pq.OneReadOnly,h,l,W.AA.Matrix[1]);return o.multiplyToRef(c,c),c.decompose(n,r,i),i.equalsToFloats(0,0,0)?delete e.translation:e.translation=i.asArray(),W.PT.IsIdentity(r)?delete e.rotation:e.rotation=r.asArray(),n.equalsToFloats(1,1,1)?delete e.scale:e.scale=n.asArray(),e.extensions||(e.extensions={}),e.extensions[sH]=a,void s(null)}}t.extensions||(t.extensions={}),t.extensions[sH]=a}}s(t)}))}}JW.RegisterExtension(sH,(e=>new nH(e)));const oH="KHR_materials_clearcoat";class aH{constructor(e){this.name=oH,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const r=[];return i instanceof Gm&&i.clearCoat.isEnabled?(i.clearCoat.texture&&r.push(i.clearCoat.texture),!i.clearCoat.useRoughnessFromMainTexture&&i.clearCoat.textureRoughness&&r.push(i.clearCoat.textureRoughness),i.clearCoat.bumpTexture&&r.push(i.clearCoat.bumpTexture),r):[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Gm){if(!i.clearCoat.isEnabled)return void e(t);this._wasUsed=!0,t.extensions=t.extensions||{};const r=this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.texture);let s;s=i.clearCoat.useRoughnessFromMainTexture?this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.texture):this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.textureRoughness),i.clearCoat.isTintEnabled&&Ue.S0.Warn(`Clear Color tint is not supported for glTF export. Ignoring for: ${i.name}`),i.clearCoat.remapF0OnInterfaceChange&&Ue.S0.Warn(`Clear Color F0 remapping is not supported for glTF export. Ignoring for: ${i.name}`);const n=this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.bumpTexture),o={clearcoatFactor:i.clearCoat.intensity,clearcoatTexture:r??void 0,clearcoatRoughnessFactor:i.clearCoat.roughness,clearcoatRoughnessTexture:s??void 0,clearcoatNormalTexture:n??void 0,hasTextures:()=>null!==o.clearcoatTexture||null!==o.clearcoatRoughnessTexture||null!==o.clearcoatRoughnessTexture};t.extensions[oH]=o}e(t)}))}}JW.RegisterExtension(oH,(e=>new aH(e)));const lH="KHR_materials_iridescence";class hH{constructor(e){this.name=lH,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const r=[];return i instanceof Gm&&i.iridescence.isEnabled?(i.iridescence.texture&&r.push(i.iridescence.texture),i.iridescence.thicknessTexture&&i.iridescence.thicknessTexture!==i.iridescence.texture&&r.push(i.iridescence.thicknessTexture),r):[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Gm){if(!i.iridescence.isEnabled)return void e(t);this._wasUsed=!0,t.extensions=t.extensions||{};const r=this._exporter._glTFMaterialExporter._getTextureInfo(i.iridescence.texture),s=this._exporter._glTFMaterialExporter._getTextureInfo(i.iridescence.thicknessTexture),n={iridescenceFactor:i.iridescence.intensity,iridescenceIor:i.iridescence.indexOfRefraction,iridescenceThicknessMinimum:i.iridescence.minimumThickness,iridescenceThicknessMaximum:i.iridescence.maximumThickness,iridescenceTexture:r??void 0,iridescenceThicknessTexture:s??void 0,hasTextures:()=>null!==n.iridescenceTexture||null!==n.iridescenceThicknessTexture};t.extensions[lH]=n}e(t)}))}}JW.RegisterExtension(lH,(e=>new hH(e)));const cH="KHR_materials_anisotropy";class uH{constructor(e){this.name=cH,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const r=[];return i instanceof Gm&&i.anisotropy.isEnabled&&!i.anisotropy.legacy?(i.anisotropy.texture&&r.push(i.anisotropy.texture),r):[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Gm){if(!i.anisotropy.isEnabled||i.anisotropy.legacy)return void e(t);this._wasUsed=!0,t.extensions=t.extensions||{};const r=this._exporter._glTFMaterialExporter._getTextureInfo(i.anisotropy.texture),s={anisotropyStrength:i.anisotropy.intensity,anisotropyRotation:i.anisotropy.angle,anisotropyTexture:r??void 0,hasTextures:()=>null!==s.anisotropyTexture};t.extensions[cH]=s}e(t)}))}}JW.RegisterExtension(cH,(e=>new uH(e)));const dH="KHR_materials_sheen";class fH{constructor(e){this.name=dH,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){return i instanceof zm&&i.sheen.isEnabled&&i.sheen.texture?[i.sheen.texture]:[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zm){if(!i.sheen.isEnabled)return void e(t);this._wasUsed=!0,null==t.extensions&&(t.extensions={});const r={sheenColorFactor:i.sheen.color.asArray(),sheenRoughnessFactor:i.sheen.roughness??0,hasTextures:()=>null!==r.sheenColorTexture||null!==r.sheenRoughnessTexture};i.sheen.texture&&(r.sheenColorTexture=this._exporter._glTFMaterialExporter._getTextureInfo(i.sheen.texture)??void 0),i.sheen.textureRoughness&&!i.sheen.useRoughnessFromMainTexture?r.sheenRoughnessTexture=this._exporter._glTFMaterialExporter._getTextureInfo(i.sheen.textureRoughness)??void 0:i.sheen.texture&&i.sheen.useRoughnessFromMainTexture&&(r.sheenRoughnessTexture=this._exporter._glTFMaterialExporter._getTextureInfo(i.sheen.texture)??void 0),t.extensions[dH]=r}e(t)}))}}JW.RegisterExtension(dH,(e=>new fH(e)));const pH="KHR_materials_unlit";class _H{constructor(){this.name=pH,this.enabled=!0,this.required=!1,this._wasUsed=!1}get wasUsed(){return this._wasUsed}dispose(){}postExportMaterialAsync(e,t,i){return new Promise((e=>{let r=!1;i instanceof zm?r=i.unlit:i instanceof Un&&(r=i.disableLighting),r&&(this._wasUsed=!0,null==t.extensions&&(t.extensions={}),t.extensions[pH]={}),e(t)}))}}JW.RegisterExtension(pH,(()=>new _H));const mH="KHR_materials_ior";class gH{constructor(){this.name=mH,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}_isExtensionEnabled(e){return!e.unlit&&null!=e.indexOfRefraction&&1.5!=e.indexOfRefraction}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zm&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e={ior:i.indexOfRefraction};t.extensions=t.extensions||{},t.extensions[mH]=e}e(t)}))}}JW.RegisterExtension(mH,(e=>new gH));const vH="KHR_materials_specular";class xH{constructor(e){this.name=vH,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const r=[];return i instanceof zm&&this._isExtensionEnabled(i)?(i.metallicReflectanceTexture&&r.push(i.metallicReflectanceTexture),i.reflectanceTexture&&r.push(i.reflectanceTexture),r):r}_isExtensionEnabled(e){return!e.unlit&&(null!=e.metallicF0Factor&&1!=e.metallicF0Factor||null!=e.metallicReflectanceColor&&!e.metallicReflectanceColor.equalsFloats(1,1,1)||this._hasTexturesExtension(e))}_hasTexturesExtension(e){return null!=e.metallicReflectanceTexture||null!=e.reflectanceTexture}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zm&&this._isExtensionEnabled(i)){this._wasUsed=!0,t.extensions=t.extensions||{};const e=this._exporter._glTFMaterialExporter._getTextureInfo(i.metallicReflectanceTexture)??void 0,r=this._exporter._glTFMaterialExporter._getTextureInfo(i.reflectanceTexture)??void 0,s={specularFactor:1==i.metallicF0Factor?void 0:i.metallicF0Factor,specularTexture:e,specularColorFactor:i.metallicReflectanceColor.equalsFloats(1,1,1)?void 0:i.metallicReflectanceColor.asArray(),specularColorTexture:r,hasTextures:()=>this._hasTexturesExtension(i)};t.extensions[vH]=s}e(t)}))}}JW.RegisterExtension(vH,(e=>new xH(e)));const bH="KHR_materials_volume";class SH{constructor(e){this.name=bH,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const r=[];return i instanceof zm&&this._isExtensionEnabled(i)?(i.subSurface.thicknessTexture&&r.push(i.subSurface.thicknessTexture),r):r}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return!(!t.isRefractionEnabled&&!t.isTranslucencyEnabled)&&(null!=t.maximumThickness&&0!=t.maximumThickness||null!=t.tintColorAtDistance&&t.tintColorAtDistance!=Number.POSITIVE_INFINITY||null!=t.tintColor&&t.tintColor!=H.v9.White()||this._hasTexturesExtension(e))}_hasTexturesExtension(e){return null!=e.subSurface.thicknessTexture}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zm&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e=i.subSurface,r={thicknessFactor:0==e.maximumThickness?void 0:e.maximumThickness,thicknessTexture:this._exporter._glTFMaterialExporter._getTextureInfo(e.thicknessTexture)??void 0,attenuationDistance:e.tintColorAtDistance==Number.POSITIVE_INFINITY?void 0:e.tintColorAtDistance,attenuationColor:e.tintColor.equalsFloats(1,1,1)?void 0:e.tintColor.asArray(),hasTextures:()=>this._hasTexturesExtension(i)};t.extensions=t.extensions||{},t.extensions[bH]=r}e(t)}))}}JW.RegisterExtension(bH,(e=>new SH(e)));const TH="KHR_materials_dispersion";class CH{constructor(){this.name=TH,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return!(!t.isRefractionEnabled&&!t.isDispersionEnabled)}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zm&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e={dispersion:i.subSurface.dispersion};t.extensions=t.extensions||{},t.extensions[TH]=e}e(t)}))}}JW.RegisterExtension(TH,(()=>new CH));const yH="KHR_materials_transmission";class EH{constructor(e){this.name=yH,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const r=[];return i instanceof zm&&this._isExtensionEnabled(i)?(i.subSurface.thicknessTexture&&r.push(i.subSurface.thicknessTexture),r):r}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return t.isRefractionEnabled&&null!=t.refractionIntensity&&0!=t.refractionIntensity||this._hasTexturesExtension(e)}_hasTexturesExtension(e){return null!=e.subSurface.refractionIntensityTexture}async postExportMaterialAsync(e,t,i){if(i instanceof zm&&this._isExtensionEnabled(i)){this._wasUsed=!0;const r=i.subSurface,s={transmissionFactor:0===r.refractionIntensity?void 0:r.refractionIntensity,hasTextures:()=>this._hasTexturesExtension(i)};if(r.refractionIntensityTexture)if(r.useGltfStyleTextures){const e=await this._exporter._glTFMaterialExporter._exportTextureInfoAsync(r.refractionIntensityTexture,"image/png");e&&(s.transmissionTexture=e)}else Z.V.Warn(`${e}: Exporting a subsurface refraction intensity texture without \`useGltfStyleTextures\` is not supported`);t.extensions||(t.extensions={}),t.extensions[yH]=s}return t}}JW.RegisterExtension(yH,(e=>new EH(e)));const PH="EXT_mesh_gpu_instancing";class AH{constructor(e){this.name=PH,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportNodeAsync(e,t,i,r,s){return new Promise((e=>{if(t&&i instanceof Yt&&i.hasThinInstances&&s){this._wasUsed=!0;const e=W.Pq.Zero(),r=W.PT.Identity(),n=W.Pq.One(),o=i.thinInstanceGetWorldMatrices(),a=W.AA.Vector3[2],l=W.AA.Quaternion[1],h=W.AA.Vector3[3];let c=!1,u=!1,d=!1;const f=new Float32Array(3*i.thinInstanceCount),p=new Float32Array(4*i.thinInstanceCount),_=new Float32Array(3*i.thinInstanceCount);let m=0;for(const t of o)t.decompose(h,l,a),f.set(a.asArray(),3*m),p.set(l.normalize().asArray(),4*m),_.set(h.asArray(),3*m),c=c||!a.equalsWithEpsilon(e),u=u||!l.equalsWithEpsilon(r),d=d||!h.equalsWithEpsilon(n),m++;const g={attributes:{}};if(c&&(g.attributes.TRANSLATION=this._buildAccessor(f,"VEC3",i.thinInstanceCount,s,5126)),u){const e=5126;g.attributes.ROTATION=this._buildAccessor(p,"VEC4",i.thinInstanceCount,s,e)}d&&(g.attributes.SCALE=this._buildAccessor(_,"VEC3",i.thinInstanceCount,s,5126)),t.extensions=t.extensions||{},t.extensions[PH]=g}e(t)}))}_buildAccessor(e,t,i,r,s){const n=r.getByteOffset();switch(s){case 5126:for(let t=0;t!=e.length;t++)r.setFloat32(e[t]);break;case 5120:for(let t=0;t!=e.length;t++)r.setByte(127*e[t]);break;case 5122:for(let t=0;t!=e.length;t++)r.setInt16(32767*e[t])}const o={buffer:0,byteOffset:n,byteLength:e.length*st.R.GetTypeByteLength(s)},a=this._exporter._bufferViews.length;this._exporter._bufferViews.push(o);const l=this._exporter._accessors.length,h={bufferView:a,componentType:s,count:i,type:t,normalized:5120==s||5122==s};return this._exporter._accessors.push(h),l}}JW.RegisterExtension(PH,(e=>new AH(e)));const RH="KHR_materials_emissive_strength";class IH{constructor(){this.name=RH,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(!(i instanceof zm))return e(t);const r=i.emissiveColor.asArray(),s=Math.max(...r);if(s>1){this._wasUsed=!0,t.extensions||(t.extensions={});const e={emissiveStrength:s},r=i.emissiveColor.scale(1/e.emissiveStrength);t.emissiveFactor=r.asArray(),t.extensions[RH]=e}return e(t)}))}}JW.RegisterExtension(RH,(e=>new IH));const MH="KHR_materials_diffuse_transmission";class OH{constructor(e){this.name=MH,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const r=[];return i instanceof zm&&this._isExtensionEnabled(i)?(i.subSurface.thicknessTexture&&r.push(i.subSurface.thicknessTexture),r):r}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return!!t.isTranslucencyEnabled&&!e.unlit&&!t.useAlbedoToTintTranslucency&&t.useGltfStyleTextures&&1===t.volumeIndexOfRefraction&&0===t.minimumThickness&&0===t.maximumThickness}_hasTexturesExtension(e){return null!=e.subSurface.translucencyIntensityTexture||null!=e.subSurface.translucencyColorTexture}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zm&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e=i.subSurface,r={diffuseTransmissionFactor:1==e.translucencyIntensity?void 0:e.translucencyIntensity,diffuseTransmissionTexture:this._exporter._glTFMaterialExporter._getTextureInfo(e.translucencyIntensityTexture)??void 0,diffuseTransmissionColorFactor:!e.translucencyColor||e.translucencyColor.equalsFloats(1,1,1)?void 0:e.translucencyColor.asArray(),diffuseTransmissionColorTexture:this._exporter._glTFMaterialExporter._getTextureInfo(e.translucencyColorTexture)??void 0,hasTextures:()=>this._hasTexturesExtension(i)};t.extensions=t.extensions||{},t.extensions[MH]=r}e(t)}))}}JW.RegisterExtension(MH,(e=>new OH(e)));class DH{static CreateSTL(e,t=!0,i="stlmesh",r=!1,s=!0,n=!1,o=!1,a=!1){const l=function(e,t,i){const r=[3*e[i],3*e[i+1],3*e[i+2]],s=[new W.Pq(t[r[0]],t[r[0]+2],t[r[0]+1]),new W.Pq(t[r[1]],t[r[1]+2],t[r[1]+1]),new W.Pq(t[r[2]],t[r[2]+2],t[r[2]+1])],n=s[0].subtract(s[1]),o=s[2].subtract(s[1]);return{v:s,n:W.Pq.Cross(o,n).normalize()}},h=function(e,t,i,r){return t=c(e,t,i.x,r),t=c(e,t,i.y,r),c(e,t,i.z,r)},c=function(e,t,i,r){return e.setFloat32(t,i,r),t+4},u=function(e){if(o){let t=e;e instanceof Kt&&(t=e.sourceMesh);const i=t.getVerticesData(st.R.PositionKind,!0,!0);if(!i)return[];const r=W.Pq.Zero();let s;for(s=0;s"bitbybit-hdrSkyBox"!==e.name&&!e.name.includes("bitbybit-ground")}),tH.GLBAsync(this.context.scene,e.fileName,t).then((e=>{e.downloadFiles()}))}exportMeshToStl(e){return aX(this,void 0,void 0,(function*(){const t=e.mesh.getChildMeshes();let i=[];t&&t.length>0&&(i=t.filter((e=>!(e instanceof Ca||e instanceof AE))));let r=[e.mesh,...i];return r=r.filter((e=>e.isVisible)),DH.CreateSTL(r,!0,e.fileName,!0,!0,!0),Promise.resolve({})}))}exportMeshesToStl(e){return aX(this,void 0,void 0,(function*(){let t;return e.meshes.forEach((e=>{const i=e.getChildMeshes();let r=[];i&&i.length>0&&(r=i.filter((e=>!(e instanceof Ca||e instanceof AE)))),t.push(e),r.length>0&&t.push(...r)})),DH.CreateSTL(t,!0,e.fileName,!0,!0,!0),Promise.resolve({})}))}loadAsset(e,t,i,r){return aX(this,void 0,void 0,(function*(){const e=yield xg.ImportMeshAsync("",t,i,this.context.scene),s=this.context.scene.metadata.shadowGenerators,n=new Yt("ImportedMeshContainer"+Math.random(),this.context.scene);return s.length>0&&e.meshes.forEach((e=>{if(e.isPickable=!1,r&&(e.isVisible=!1),e.getChildMeshes().forEach((e=>{e.isPickable=!1,r&&(e.isVisible=!1)})),this.context.scene.metadata.shadowGenerators.length>0){try{e.receiveShadows=!0}catch(e){}s.forEach((t=>{t.addShadowCaster(e)})),e.getChildMeshes().forEach((e=>{try{e.receiveShadows=!0}catch(e){}s.forEach((t=>{t.addShadowCaster(e)}))}))}})),e.meshes.forEach((e=>{e.parent=n})),n}))}}class hX{constructor(e){this.context=e}setDirectionToTarget(e){e.shadowLight.setDirectionToTarget(new hc.Pq(e.target[0],e.target[1],e.target[2]))}setPosition(e){e.shadowLight.position=new hc.Pq(e.position[0],e.position[1],e.position[2])}}class cX{constructor(e){this.context=e,this.shadowLight=new hX(e)}}class uX{constructor(e){this.context=e}createFullScreenUI(e){const t=vi.g.BILINEAR_SAMPLINGMODE;return $B.CreateFullscreenUI(e.name,e.foreground,this.context.scene,t,e.adaptiveScaling)}createForMesh(e){const t=this.context.getSamplingMode(e.sampling);return $B.CreateForMesh(e.mesh,e.width,e.height,e.supportPointerMove,e.onlyAlphaTesting,e.invertY,void 0,t)}}class dX{constructor(e){this.context=e}createStackPanel(e){const t=new _B(e.name);return t.isVertical=e.isVertical,t.spacing=e.spacing,t.onDisposeObservable.add((e=>{e.clearControls()})),void 0!==e.width?t.width=e.width:t.width=1,void 0!==e.height&&(t.height=e.height),void 0!==e.color&&(t.color=e.color),void 0!==e.background&&(t.background=e.background),t}setIsVertical(e){return e.stackPanel.isVertical=e.isVertical,e.stackPanel}setSpacing(e){return e.stackPanel.spacing=e.spacing,e.stackPanel}setWidth(e){return e.stackPanel.width=e.width,e.stackPanel}setHeight(e){return e.stackPanel.height=e.height,e.stackPanel}getIsVertical(e){return e.stackPanel.isVertical}getSpacing(e){return e.stackPanel.spacing}getWidth(e){return e.stackPanel.width}getHeight(e){return e.stackPanel.height}}class fX{constructor(e){this.context=e}addControls(e){return e.clearControlsFirst&&e.container.clearControls&&e.container.clearControls(),e.controls.forEach((t=>e.container.addControl(t))),e.container}setBackground(e){return e.container.background=e.background,e.container}setIsReadonly(e){return e.container.isReadOnly=e.isReadOnly,e.container}getBackground(e){return e.container.background}getIsReadonly(e){return e.container.isReadOnly}}class pX{constructor(e){this.context=e}createSimpleButton(e){const t=pB.CreateSimpleButton(e.name,e.label);return e.width?t.width=e.width:t.width=1,e.height?t.height=e.height:t.height="42px",t.color=e.color,t.fontSize=e.fontSize,t.background=e.background,t}setButtonText(e){return e.button.textBlock.text=e.text,e.button}getButtonText(e){return e.button.textBlock.text}}class _X{constructor(e){this.context=e}changeControlPadding(e){return void 0!==e.paddingLeft&&(e.control.paddingLeft=e.paddingLeft),void 0!==e.paddingRight&&(e.control.paddingRight=e.paddingRight),void 0!==e.paddingTop&&(e.control.paddingTop=e.paddingTop),void 0!==e.paddingBottom&&(e.control.paddingBottom=e.paddingBottom),e.control}changeControlAlignment(e){switch(e.horizontalAlignment){case"left":e.control.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT;break;case"right":e.control.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_RIGHT;break;case"center":e.control.horizontalAlignment=lB.HORIZONTAL_ALIGNMENT_CENTER}switch(e.verticalAlignment){case"top":e.control.verticalAlignment=lB.VERTICAL_ALIGNMENT_TOP;break;case"bottom":e.control.verticalAlignment=lB.VERTICAL_ALIGNMENT_BOTTOM;break;case"center":e.control.verticalAlignment=lB.VERTICAL_ALIGNMENT_CENTER}return e.control}cloneControl(e){const t=e.control.clone(e.host);return e.container&&e.container.addControl(t),e.name&&(t.name=e.name),t}createControlObservableSelector(e){return e.selector}getControlByName(e){return e.container.children.find((t=>t.name===e.name))}setIsVisible(e){return e.control.isVisible=e.isVisible,e.control}setIsReadonly(e){return e.control.isReadOnly=e.isReadOnly,e.control}setIsEnabled(e){return e.control.isEnabled=e.isEnabled,e.control}setHeight(e){return e.control.height=e.height,e.control}setWidth(e){return e.control.width=e.width,e.control}setColor(e){return e.control.color=e.color,e.control}setFontSize(e){return e.control.fontSize=e.fontSize,e.control}getHeight(e){return e.control.height}getWidth(e){return e.control.width}getColor(e){return e.control.color}getFontSize(e){return e.control.fontSize}getIsVisible(e){return e.control.isVisible}getIsReadonly(e){return e.control.isReadOnly}getIsEnabled(e){return e.control.isEnabled}}class mX{constructor(e){this.context=e}createSlider(e){const t=new MB(e.name);return t.minimum=e.minimum,t.maximum=e.maximum,t.value=e.value,t.step=e.step,t.isVertical=e.isVertical,t.displayThumb=e.displayThumb,t.thumbColor="white",e.isVertical?(e.height?t.height=e.height:t.height=1,e.width?t.width=e.width:t.width="42px"):(e.width?t.width=e.width:t.width=1,e.height?t.height=e.height:t.height="42px"),t.color=e.color,t.background=e.background,t}changeSliderThumb(e){return e.slider.thumbColor=e.thumbColor,e.slider.isThumbCircle=e.isThumbCircle,e.slider.isThumbClamped=e.isThumbClamped,e.slider.displayThumb=e.displayThumb,e.thumbWidth&&(e.slider.thumbWidth=e.thumbWidth),e.slider}setBorderColor(e){return e.slider.borderColor=e.borderColor,e.slider}setBackgroundColor(e){return e.slider.background=e.backgroundColor,e.slider}setMaximum(e){return e.slider.maximum=e.value,e.slider}setMinimum(e){return e.slider.minimum=e.value,e.slider}setStep(e){return e.slider.step=e.value,e.slider}setValue(e){return e.slider.value=e.value,e.slider}createSliderObservableSelector(e){return e.selector}getBorderColor(e){return e.slider.borderColor}getBackgroundColor(e){return e.slider.background}getMaximum(e){return e.slider.maximum}getMinimum(e){return e.slider.minimum}getStep(e){return e.slider.step}getValue(e){return e.slider.value}getThumbColor(e){return e.slider.thumbColor}getThumbWidth(e){return e.slider.thumbWidth}getIsVertical(e){return e.slider.isVertical}getDisplayThumb(e){return e.slider.displayThumb}getIsThumbCircle(e){return e.slider.isThumbCircle}getIsThumbClamped(e){return e.slider.isThumbClamped}}!function(e){e.ArcRotateCameraDto=class{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f){this.radius=20,this.target=[0,0,0],this.alpha=45,this.beta=70,this.lowerBetaLimit=1,this.upperBetaLimit=179,this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.panningSensibility=1e3,this.wheelPrecision=3,this.maxZ=1e3,void 0!==e&&(this.radius=e),void 0!==t&&(this.alpha=t),void 0!==i&&(this.beta=i),void 0!==r&&(this.lowerRadiusLimit=r),void 0!==s&&(this.upperRadiusLimit=s),void 0!==n&&(this.lowerAlphaLimit=n),void 0!==o&&(this.upperAlphaLimit=o),void 0!==a&&(this.lowerBetaLimit=a),void 0!==l&&(this.upperBetaLimit=l),void 0!==h&&(this.angularSensibilityX=h),void 0!==c&&(this.angularSensibilityY=c),void 0!==u&&(this.panningSensibility=u),void 0!==d&&(this.wheelPrecision=d),void 0!==f&&(this.maxZ=f)}},e.FreeCameraDto=class{constructor(e,t){this.position=[20,20,20],this.target=[0,0,0],void 0!==e&&(this.position=e),void 0!==t&&(this.target=t)}},e.TargetCameraDto=class{constructor(e,t){this.position=[20,20,20],this.target=[0,0,0],void 0!==e&&(this.position=e),void 0!==t&&(this.target=t)}},e.PositionDto=class{constructor(e,t){this.position=[20,20,20],void 0!==e&&(this.camera=e),void 0!==t&&(this.position=t)}},e.SpeedDto=class{constructor(e,t){this.speed=1,void 0!==e&&(this.camera=e),void 0!==t&&(this.speed=t)}},e.TargetDto=class{constructor(e,t){this.target=[0,0,0],void 0!==e&&(this.camera=e),void 0!==t&&(this.target=t)}},e.MinZDto=class{constructor(e,t){this.minZ=0,void 0!==e&&(this.camera=e),void 0!==t&&(this.minZ=t)}},e.MaxZDto=class{constructor(e,t){this.maxZ=1e3,void 0!==e&&(this.camera=e),void 0!==t&&(this.maxZ=t)}},e.OrthographicDto=class{constructor(e,t,i,r,s){this.orthoLeft=-1,this.orthoRight=1,this.orthoBottom=-1,this.orthoTop=1,void 0!==e&&(this.camera=e),void 0!==t&&(this.orthoLeft=t),void 0!==i&&(this.orthoRight=i),void 0!==r&&(this.orthoTop=r),void 0!==s&&(this.orthoBottom=s)}},e.CameraDto=class{constructor(e){void 0!==e&&(this.camera=e)}}}(wH||(wH={})),function(e){e.ExportSceneGlbDto=class{constructor(e,t){this.fileName="bitbybit-scene",this.discardSkyboxAndGrid=!1,void 0!==e&&(this.fileName=e),void 0!==t&&(this.discardSkyboxAndGrid=t)}},e.ExportSceneDto=class{constructor(e){this.fileName="bitbybit-scene",void 0!==e&&(this.fileName=e)}},e.ExportMeshToStlDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.fileName=t)}},e.ExportMeshesToStlDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.fileName=t)}}}(NH||(NH={})),function(e){e.PBRMetallicRoughnessDto=class{constructor(e,t,i,r,s,n,o,a){this.name="Custom Material",this.baseColor="#0000ff",this.emissiveColor="#000000",this.metallic=.6,this.roughness=.5,this.alpha=1,this.backFaceCulling=!1,this.zOffset=0,void 0!==e&&(this.name=e),void 0!==t&&(this.baseColor=t),void 0!==i&&(this.emissiveColor=i),void 0!==r&&(this.metallic=r),void 0!==s&&(this.roughness=s),void 0!==n&&(this.alpha=n),void 0!==o&&(this.backFaceCulling=o),void 0!==a&&(this.zOffset=a)}},e.BaseColorDto=class{constructor(e,t){this.baseColor="#0000ff",void 0!==e&&(this.material=e),void 0!==t&&(this.baseColor=t)}},e.MaterialPropDto=class{constructor(e){void 0!==e&&(this.material=e)}},e.SkyMaterialPropDto=class{constructor(e){void 0!==e&&(this.skyMaterial=e)}},e.MetallicDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.metallic=t)}},e.RoughnessDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.roughness=t)}},e.AlphaDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.alpha=t)}},e.BackFaceCullingDto=class{constructor(e,t){this.backFaceCulling=!0,void 0!==e&&(this.material=e),void 0!==t&&(this.backFaceCulling=t)}},e.BaseTextureDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.baseTexture=t)}},e.SkyMaterialDto=class{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d){this.luminance=1,this.turbidity=10,this.rayleigh=2,this.mieCoefficient=.005,this.mieDirectionalG=.8,this.distance=500,this.inclination=.49,this.azimuth=.25,this.useSunPosition=!1,this.up=[0,1,0],this.dithering=!1,void 0!==e&&(this.luminance=e),void 0!==t&&(this.turbidity=t),void 0!==i&&(this.rayleigh=i),void 0!==r&&(this.mieCoefficient=r),void 0!==s&&(this.mieDirectionalG=s),void 0!==n&&(this.distance=n),void 0!==o&&(this.inclination=o),void 0!==a&&(this.azimuth=a),void 0!==l&&(this.sunPosition=l),void 0!==h&&(this.useSunPosition=h),void 0!==c&&(this.cameraOffset=c),void 0!==u&&(this.up=u),void 0!==d&&(this.dithering=d)}},e.LuminanceDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.luminance=t)}},e.TurbidityDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.turbidity=t)}},e.RayleighDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.rayleigh=t)}},e.MieCoefficientDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.mieCoefficient=t)}},e.MieDirectionalGDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.mieDirectionalG=t)}},e.DistanceDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.distance=t)}},e.InclinationDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.inclination=t)}},e.AzimuthDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.azimuth=t)}},e.SunPositionDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.sunPosition=t)}},e.UseSunPositionDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.useSunPosition=t)}},e.CameraOffsetDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.cameraOffset=t)}},e.UpDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.up=t)}},e.DitheringDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.dithering=t)}}}(FH||(FH={})),function(e){e.ShadowLightDirectionToTargetDto=class{constructor(e,t){void 0!==e&&(this.shadowLight=e),void 0!==t&&(this.target=t)}},e.ShadowLightPositionDto=class{constructor(e,t){void 0!==e&&(this.shadowLight=e),void 0!==t&&(this.position=t)}}}(LH||(LH={})),function(e){let t;!function(e){e.nearest="nearest",e.bilinear="bilinear",e.trilinear="trilinear"}(t=e.samplingModeEnum||(e.samplingModeEnum={})),e.TextureSimpleDto=class{constructor(t,i,r,s,n,o,a,l,h,c){this.name="Custom Texture",this.invertY=!1,this.invertZ=!1,this.wAng=0,this.uScale=1,this.vScale=1,this.uOffset=0,this.vOffset=0,this.samplingMode=e.samplingModeEnum.nearest,void 0!==t&&(this.name=t),void 0!==i&&(this.url=i),void 0!==r&&(this.invertY=r),void 0!==s&&(this.invertZ=s),void 0!==n&&(this.wAng=n),void 0!==o&&(this.uScale=o),void 0!==a&&(this.vScale=a),void 0!==l&&(this.uOffset=l),void 0!==h&&(this.vOffset=h),void 0!==c&&(this.samplingMode=c)}}}(BH||(BH={})),function(e){let t,i,r,s,n,o,a,l,h;!function(e){e.left="left",e.center="center",e.right="right"}(t=e.horizontalAlignmentEnum||(e.horizontalAlignmentEnum={})),function(e){e.top="top",e.center="center",e.bottom="bottom"}(i=e.verticalAlignmentEnum||(e.verticalAlignmentEnum={})),function(e){e.onTextChangedObservable="onTextChangedObservable",e.onBeforeKeyAddObservable="onBeforeKeyAddObservable",e.onTextHighlightObservable="onTextHighlightObservable",e.onTextCopyObservable="onTextCopyObservable",e.onTextCutObservable="onTextCutObservable",e.onTextPasteObservable="onTextPasteObservable"}(r=e.inputTextObservableSelectorEnum||(e.inputTextObservableSelectorEnum={})),function(e){e.onValueChangedObservable="onValueChangedObservable"}(s=e.sliderObservableSelectorEnum||(e.sliderObservableSelectorEnum={})),function(e){e.onValueChangedObservable="onValueChangedObservable"}(n=e.colorPickerObservableSelectorEnum||(e.colorPickerObservableSelectorEnum={})),function(e){e.onTextChangedObservable="onTextChangedObservable"}(o=e.textBlockObservableSelectorEnum||(e.textBlockObservableSelectorEnum={})),function(e){e.onIsCheckedChangedObservable="onIsCheckedChangedObservable"}(a=e.checkboxObservableSelectorEnum||(e.checkboxObservableSelectorEnum={})),function(e){e.onIsCheckedChangedObservable="onIsCheckedChangedObservable"}(l=e.radioButtonObservableSelectorEnum||(e.radioButtonObservableSelectorEnum={})),function(e){e.onFocusObservable="onFocusObservable",e.onBlurObservable="onBlurObservable",e.onAccessibilityTagChangedObservable="onAccessibilityTagChangedObservable",e.onWheelObservable="onWheelObservable",e.onPointerMoveObservable="onPointerMoveObservable",e.onPointerOutObservable="onPointerOutObservable",e.onPointerDownObservable="onPointerDownObservable",e.onPointerUpObservable="onPointerUpObservable",e.onPointerClickObservable="onPointerClickObservable",e.onEnterPressedObservable="onEnterPressedObservable",e.onPointerEnterObservable="onPointerEnterObservable",e.onDirtyObservable="onDirtyObservable",e.onBeforeDrawObservable="onBeforeDrawObservable",e.onAfterDrawObservable="onAfterDrawObservable",e.onDisposeObservable="onDisposeObservable",e.onIsVisibleChangedObservable="onIsVisibleChangedObservable"}(h=e.controlObservableSelectorEnum||(e.controlObservableSelectorEnum={})),e.CreateFullScreenUIDto=class{constructor(e,t,i){this.name="fullscreen",void 0!==e&&(this.name=e),void 0!==t&&(this.foreground=t),void 0!==i&&(this.adaptiveScaling=i)}},e.CreateForMeshDto=class{constructor(e,t,i,r,s,n,o){this.supportPointerMove=!0,this.onlyAlphaTesting=!1,this.invertY=!0,this.sampling=BH.samplingModeEnum.trilinear,void 0!==e&&(this.mesh=e),void 0!==t&&(this.width=t),void 0!==i&&(this.height=i),void 0!==r&&(this.supportPointerMove=r),void 0!==s&&(this.onlyAlphaTesting=s),void 0!==n&&(this.invertY=n),void 0!==o&&(this.sampling=o)}},e.CreateStackPanelDto=class{constructor(e,t,i,r,s,n,o){this.name="stackPanel",this.isVertical=!0,this.spacing=0,this.color="#00000000",this.background="#00000055",void 0!==e&&(this.name=e),void 0!==t&&(this.isVertical=t),void 0!==i&&(this.spacing=i),void 0!==r&&(this.width=r),void 0!==s&&(this.height=s),void 0!==n&&(this.color=n),void 0!==o&&(this.background=o)}},e.SetStackPanelIsVerticalDto=class{constructor(e,t){this.isVertical=!0,void 0!==e&&(this.stackPanel=e),void 0!==t&&(this.isVertical=t)}},e.SetStackPanelSpacingDto=class{constructor(e,t){this.spacing=0,void 0!==e&&(this.stackPanel=e),void 0!==t&&(this.spacing=t)}},e.SetStackPanelWidthDto=class{constructor(e,t){void 0!==e&&(this.stackPanel=e),void 0!==t&&(this.width=t)}},e.SetStackPanelHeightDto=class{constructor(e,t){void 0!==e&&(this.stackPanel=e),void 0!==t&&(this.height=t)}},e.StackPanelDto=class{constructor(e){void 0!==e&&(this.stackPanel=e)}},e.SliderObservableSelectorDto=class{constructor(e){this.selector=e}},e.ColorPickerObservableSelectorDto=class{constructor(e){this.selector=e}},e.InputTextObservableSelectorDto=class{constructor(e){this.selector=e}},e.RadioButtonObservableSelectorDto=class{constructor(e){this.selector=e}},e.CheckboxObservableSelectorDto=class{constructor(e){this.selector=e}},e.ControlObservableSelectorDto=class{constructor(e){this.selector=e}},e.TextBlockObservableSelectorDto=class{constructor(e){this.selector=e}},e.ContainerDto=class{constructor(e){void 0!==e&&(this.container=e)}},e.AddControlsToContainerDto=class{constructor(e,t,i){this.clearControlsFirst=!0,void 0!==e&&(this.container=e),void 0!==t&&(this.controls=t),void 0!==i&&(this.clearControlsFirst=i)}},e.GetControlByNameDto=class{constructor(e,t){this.name="controlName",void 0!==e&&(this.container=e),void 0!==t&&(this.name=t)}},e.SetControlIsVisibleDto=class{constructor(e,t){this.isVisible=!0,void 0!==e&&(this.control=e),void 0!==t&&(this.isVisible=t)}},e.SetControlIsReadonlyDto=class{constructor(e,t){this.isReadOnly=!1,void 0!==e&&(this.control=e),void 0!==t&&(this.isReadOnly=t)}},e.SetControlIsEnabledDto=class{constructor(e,t){this.isEnabled=!0,void 0!==e&&(this.control=e),void 0!==t&&(this.isEnabled=t)}},e.CreateImageDto=class{constructor(e,t,i,r,s){this.name="imageName",this.color="black",void 0!==e&&(this.name=e),void 0!==t&&(this.url=t),void 0!==i&&(this.color=i),void 0!==r&&(this.width=r),void 0!==s&&(this.height=s)}},e.SetImageUrlDto=class{constructor(e,t){void 0!==e&&(this.image=e),void 0!==t&&(this.url=t)}},e.ImageDto=class{constructor(e){void 0!==e&&(this.image=e)}},e.CreateButtonDto=class{constructor(e,t,i,r,s,n,o){this.name="buttonName",this.label="Click me!",this.color="black",this.background="#f0cebb",this.fontSize=24,void 0!==e&&(this.name=e),void 0!==t&&(this.label=t),void 0!==i&&(this.color=i),void 0!==r&&(this.background=r),void 0!==s&&(this.width=s),void 0!==n&&(this.height=n),void 0!==o&&(this.fontSize=o)}},e.SetButtonTextDto=class{constructor(e,t){this.text="Click me!",void 0!==e&&(this.button=e),void 0!==t&&(this.text=t)}},e.ButtonDto=class{constructor(e){void 0!==e&&(this.button=e)}},e.CreateColorPickerDto=class{constructor(e,t,i,r,s,n){this.name="colorPickerName",this.defaultColor="#f0cebb",this.color="#f0cebb",void 0!==e&&(this.name=e),void 0!==this.defaultColor&&(this.defaultColor=t),void 0!==i&&(this.color=i),void 0!==r&&(this.width=r),void 0!==s&&(this.height=s),void 0!==n&&(this.size=n)}},e.SetColorPickerValueDto=class{constructor(e,t){void 0!==e&&(this.colorPicker=e),void 0!==t&&(this.color=t)}},e.SetColorPickerSizeDto=class{constructor(e,t){void 0!==e&&(this.colorPicker=e),void 0!==t&&(this.size=t)}},e.ColorPickerDto=class{constructor(e){void 0!==e&&(this.colorPicker=e)}},e.CreateCheckboxDto=class{constructor(e,t,i,r,s,n,o){this.name="checkboxName",this.isChecked=!1,this.checkSizeRatio=.8,this.color="#f0cebb",this.background="black",void 0!==e&&(this.name=e),void 0!==t&&(this.isChecked=t),void 0!==i&&(this.checkSizeRatio=i),void 0!==r&&(this.color=r),void 0!==s&&(this.background=s),void 0!==n&&(this.width=n),void 0!==o&&(this.height=o)}},e.SetControlFontSizeDto=class{constructor(e,t){this.fontSize=24,void 0!==e&&(this.control=e),void 0!==t&&(this.fontSize=t)}},e.SetControlHeightDto=class{constructor(e,t){void 0!==e&&(this.control=e),void 0!==t&&(this.height=t)}},e.SetControlWidthDto=class{constructor(e,t){void 0!==e&&(this.control=e),void 0!==t&&(this.width=t)}},e.SetControlColorDto=class{constructor(e,t){this.color="#f0cebb",void 0!==e&&(this.control=e),void 0!==t&&(this.color=t)}},e.SetContainerBackgroundDto=class{constructor(e,t){this.background="black",void 0!==e&&(this.container=e),void 0!==t&&(this.background=t)}},e.SetContainerIsReadonlyDto=class{constructor(e,t){this.isReadOnly=!1,void 0!==e&&(this.container=e),void 0!==t&&(this.isReadOnly=t)}},e.SetCheckboxBackgroundDto=class{constructor(e,t){this.background="black",void 0!==e&&(this.checkbox=e),void 0!==t&&(this.background=t)}},e.SetCheckboxCheckSizeRatioDto=class{constructor(e,t){this.checkSizeRatio=.8,void 0!==e&&(this.checkbox=e),void 0!==t&&(this.checkSizeRatio=t)}},e.CheckboxDto=class{constructor(e){void 0!==e&&(this.checkbox=e)}},e.ControlDto=class{constructor(e){void 0!==e&&(this.control=e)}},e.SetCheckboxIsCheckedDto=class{constructor(e,t){this.isChecked=!1,void 0!==e&&(this.checkbox=e),void 0!==t&&(this.isChecked=t)}},e.CreateInputTextDto=class{constructor(e,t,i,r,s){this.name="inputName",this.color="#f0cebb",this.background="black",void 0!==e&&(this.name=e),void 0!==t&&(this.color=t),void 0!==i&&(this.background=i),void 0!==r&&(this.width=r),void 0!==s&&(this.height=s)}},e.SetInputTextBackgroundDto=class{constructor(e,t){this.background="black",void 0!==e&&(this.inputText=e),void 0!==t&&(this.background=t)}},e.SetInputTextTextDto=class{constructor(e,t){void 0!==e&&(this.inputText=e),void 0!==t&&(this.text=t)}},e.SetInputTextPlaceholderDto=class{constructor(e,t){void 0!==e&&(this.inputText=e),void 0!==t&&(this.placeholder=t)}},e.InputTextDto=class{constructor(e){void 0!==e&&(this.inputText=e)}},e.CreateRadioButtonDto=class{constructor(e,t,i,r,s,n,o,a){this.name="radioBtnName",this.isChecked=!1,this.checkSizeRatio=.8,this.color="#f0cebb",this.background="black",void 0!==e&&(this.name=e),void 0!==t&&(this.group=t),void 0!==i&&(this.isChecked=i),void 0!==r&&(this.checkSizeRatio=r),void 0!==s&&(this.color=s),void 0!==n&&(this.background=n),void 0!==o&&(this.width=o),void 0!==a&&(this.height=a)}},e.SetRadioButtonCheckSizeRatioDto=class{constructor(e,t){this.checkSizeRatio=.8,void 0!==e&&(this.radioButton=e),void 0!==t&&(this.checkSizeRatio=t)}},e.SetRadioButtonGroupDto=class{constructor(e,t){void 0!==e&&(this.radioButton=e),void 0!==t&&(this.group=t)}},e.SetRadioButtonBackgroundDto=class{constructor(e,t){this.background="black",void 0!==e&&(this.radioButton=e),void 0!==t&&(this.background=t)}},e.RadioButtonDto=class{constructor(e){void 0!==e&&(this.radioButton=e)}},e.CreateSliderDto=class{constructor(e,t,i,r,s,n,o,a,l,h,c){this.name="sliderName",this.minimum=0,this.maximum=10,this.value=5,this.step=.01,this.isVertical=!1,this.color="#f0cebb",this.background="black",this.displayThumb=!0,void 0!==e&&(this.name=e),void 0!==t&&(this.minimum=t),void 0!==i&&(this.maximum=i),void 0!==r&&(this.value=r),void 0!==s&&(this.step=s),void 0!==n&&(this.isVertical=n),void 0!==o&&(this.color=o),void 0!==a&&(this.background=a),void 0!==l&&(this.width=l),void 0!==h&&(this.height=h),void 0!==c&&(this.displayThumb=c)}},e.CreateTextBlockDto=class{constructor(e,t,i,r,s){this.name="textBlockName",this.text="Hello World!",this.color="#f0cebb",this.fontSize=24,void 0!==e&&(this.name=e),void 0!==t&&(this.text=t),void 0!==i&&(this.color=i),void 0!==r&&(this.width=r),void 0!==s&&(this.height=s)}},e.SetTextBlockTextDto=class{constructor(e,t){void 0!==e&&(this.textBlock=e),void 0!==t&&(this.text=t)}},e.SetTextBlockResizeToFitDto=class{constructor(e,t){this.resizeToFit=!1,void 0!==e&&(this.textBlock=e),void 0!==t&&(this.resizeToFit=t)}},e.SetTextBlockTextWrappingDto=class{constructor(e,t){void 0!==e&&(this.textBlock=e),void 0!==t&&(this.textWrapping=t)}},e.SetTextBlockLineSpacingDto=class{constructor(e,t){void 0!==e&&(this.textBlock=e),void 0!==t&&(this.lineSpacing=t)}},e.TextBlockDto=class{constructor(e){void 0!==e&&(this.textBlock=e)}},e.SliderThumbDto=class{constructor(e,t,i,r,s,n){this.isThumbCircle=!1,this.thumbColor="white",this.isThumbClamped=!1,this.displayThumb=!0,void 0!==e&&(this.slider=e),void 0!==t&&(this.isThumbCircle=t),void 0!==i&&(this.thumbColor=i),void 0!==r&&(this.thumbWidth=r),void 0!==s&&(this.isThumbClamped=s),void 0!==n&&(this.displayThumb=n)}},e.SliderDto=class{constructor(e){void 0!==e&&(this.slider=e)}},e.SliderBorderColorDto=class{constructor(e,t){this.borderColor="white",void 0!==e&&(this.slider=e),void 0!==t&&(this.borderColor=t)}},e.SliderBackgroundColorDto=class{constructor(e,t){this.backgroundColor="black",void 0!==e&&(this.slider=e),void 0!==t&&(this.backgroundColor=t)}},e.SetSliderValueDto=class{constructor(e,t){void 0!==e&&(this.slider=e),void 0!==t&&(this.value=t)}},e.PaddingLeftRightTopBottomDto=class{constructor(e,t,i,r,s){void 0!==e&&(this.control=e),void 0!==t&&(this.paddingLeft=t),void 0!==i&&(this.paddingRight=i),void 0!==r&&(this.paddingTop=r),void 0!==s&&(this.paddingBottom=s)}},e.CloneControlDto=class{constructor(e,t,i,r){this.name="clonedControl",void 0!==e&&(this.control=e),void 0!==t&&(this.container=t),void 0!==i&&(this.name=i),void 0!==r&&(this.host=r)}},e.AlignmentDto=class{constructor(e,t,i){void 0!==e&&(this.control=e),void 0!==t&&(this.horizontalAlignment=t),void 0!==i&&(this.verticalAlignment=i)}},e.SetTextBlockTextOutlineDto=class{constructor(e,t,i){void 0!==e&&(this.textBlock=e),void 0!==t&&(this.outlineWidth=t),void 0!==i&&(this.outlineColor=i)}}}(VH||(VH={})),function(e){e.CreateGaussianSplattingMeshDto=class{constructor(e){void 0!==e&&(this.url=e)}},e.GaussianSplattingMeshDto=class{constructor(e){void 0!==e&&(this.babylonMesh=e)}}}(kH||(kH={})),function(e){let t;!function(e){e.frontside="frontside",e.backside="backside",e.doubleside="doubleside"}(t=e.sideOrientationEnum||(e.sideOrientationEnum={})),e.UpdateDrawnBabylonMesh=class{constructor(e,t,i,r,s){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.position=t),void 0!==i&&(this.rotation=i),void 0!==r&&(this.scaling=r),void 0!==s&&(this.colours=s)}},e.SetParentDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.parentMesh=t)}},e.UpdateDrawnBabylonMeshPositionDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.position=t)}},e.UpdateDrawnBabylonMeshRotationDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.rotation=t)}},e.UpdateDrawnBabylonMeshScaleDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.scale=t)}},e.IntersectsMeshDto=class{constructor(e,t,i,r){this.precise=!1,this.includeDescendants=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.babylonMesh2=t),void 0!==i&&(this.precise=i),void 0!==r&&(this.includeDescendants=r)}},e.IntersectsPointDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.point=t)}},e.BabylonMeshDto=class{constructor(e){void 0!==e&&(this.babylonMesh=e)}},e.CloneToPositionsDto=class{constructor(e,t){this.positions=[],void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.positions=t)}},e.MergeMeshesDto=class{constructor(e,t,i,r,s,n){this.disposeSource=!0,this.allow32BitsIndices=!1,this.subdivideWithSubMeshes=!1,this.multiMultiMaterials=!1,void 0!==e&&(this.arrayOfMeshes=e),void 0!==t&&(this.disposeSource=t),void 0!==i&&(this.allow32BitsIndices=i),void 0!==r&&(this.meshSubclass=r),void 0!==s&&(this.subdivideWithSubMeshes=s),void 0!==n&&(this.multiMultiMaterials=n)}},e.BabylonMeshWithChildrenDto=class{constructor(e){this.includeChildren=!0,void 0!==e&&(this.babylonMesh=e)}},e.ShowHideMeshDto=class{constructor(e,t){this.includeChildren=!0,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.includeChildren=t)}},e.CloneBabylonMeshDto=class{constructor(e){void 0!==e&&(this.babylonMesh=e)}},e.ChildMeshesBabylonMeshDto=class{constructor(e,t){this.directDescendantsOnly=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.directDescendantsOnly=t)}},e.TranslateBabylonMeshDto=class{constructor(e,t){this.distance=0,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.distance=t)}},e.NameBabylonMeshDto=class{constructor(e,t,i){this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.name=t),void 0!==i&&(this.includeChildren=i)}},e.ByNameBabylonMeshDto=class{constructor(e){void 0!==e&&(this.name=e)}},e.MaterialBabylonMeshDto=class{constructor(e,t,i){this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.material=t),void 0!==i&&(this.includeChildren=i)}},e.IdBabylonMeshDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.id=t)}},e.ByIdBabylonMeshDto=class{constructor(e){void 0!==e&&(this.id=e)}},e.UniqueIdBabylonMeshDto=class{constructor(e){void 0!==e&&(this.uniqueId=e)}},e.PickableBabylonMeshDto=class{constructor(e,t,i){this.pickable=!1,this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.pickable=t),void 0!==i&&(this.includeChildren=i)}},e.CheckCollisionsBabylonMeshDto=class{constructor(e,t,i){this.checkCollisions=!1,this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.checkCollisions=t),void 0!==i&&(this.includeChildren=i)}},e.RotateBabylonMeshDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.rotate=t)}},e.SetMeshVisibilityDto=class{constructor(e,t,i){this.visibility=0,this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.visibility=t),void 0!==i&&(this.includeChildren=i)}},e.MeshInstanceAndTransformDto=class{constructor(e,t,i,r){void 0!==e&&(this.mesh=e),void 0!==t&&(this.position=t),void 0!==i&&(this.rotation=i),void 0!==r&&(this.scaling=r)}},e.MeshInstanceDto=class{constructor(e){void 0!==e&&(this.mesh=e)}},e.RotateAroundAxisNodeDto=class{constructor(e,t,i,r){this.position=[0,0,0],this.axis=[0,1,0],this.angle=0,void 0!==e&&(this.mesh=e),void 0!==t&&(this.position=t),void 0!==i&&(this.axis=i),void 0!==r&&(this.angle=r)}}}(UH||(UH={})),function(e){e.RotationCenterAxisDto=class{constructor(e,t,i){this.angle=90,this.axis=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.angle=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.center=i)}},e.TransformBabylonMeshDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.transformation=t)}},e.RotationCenterDto=class{constructor(e,t){this.angle=90,this.center=[0,0,0],void 0!==e&&(this.angle=e),void 0!==t&&(this.center=t)}},e.RotationCenterYawPitchRollDto=class{constructor(e,t,i,r){this.yaw=0,this.pitch=0,this.roll=0,this.center=[0,0,0],void 0!==e&&(this.yaw=e),void 0!==t&&(this.pitch=t),void 0!==i&&(this.roll=i),void 0!==r&&(this.center=r)}},e.ScaleXYZDto=class{constructor(e){this.scaleXyz=[1,1,1],void 0!==e&&(this.scaleXyz=e)}},e.ScaleCenterXYZDto=class{constructor(e,t){this.center=[0,0,0],this.scaleXyz=[1,1,1],void 0!==e&&(this.center=e),void 0!==t&&(this.scaleXyz=t)}},e.UniformScaleDto=class{constructor(e){this.scale=1,void 0!==e&&(this.scale=e)}},e.UniformScaleFromCenterDto=class{constructor(e,t){this.scale=1,this.center=[0,0,0],void 0!==e&&(this.scale=e),void 0!==t&&(this.center=t)}},e.TranslationXYZDto=class{constructor(e){this.translation=[0,0,0],void 0!==e&&(this.translation=e)}},e.TranslationsXYZDto=class{constructor(e){void 0!==e&&(this.translations=e)}}}(GH||(GH={})),function(e){e.RayDto=class{constructor(e){void 0!==e&&(this.ray=e)}},e.PickInfo=class{constructor(e){void 0!==e&&(this.pickInfo=e)}}}(zH||(zH={})),function(e){e.BaseRayDto=class{constructor(e,t,i){void 0!==e&&(this.origin=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.length=i)}},e.RayDto=class{constructor(e){void 0!==e&&(this.ray=e)}},e.FromToDto=class{constructor(e,t){void 0!==e&&(this.from=e),void 0!==t&&(this.to=t)}}}(WH||(WH={})),function(e){e.ScreenshotDto=class{constructor(e,t,i,r,s){this.width=1920,this.height=1080,this.quality=1,void 0!==e&&(this.camera=e),void 0!==r&&(this.mimeType=r),void 0!==s&&(this.quality=s),void 0!==t&&(this.width=t),void 0!==i&&(this.height=i)}}}(HH||(HH={})),function(e){e.CreateBoxDto=class{constructor(e,t,i,r,s){this.width=1,this.depth=1,this.height=1,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.width=e),void 0!==t&&(this.depth=t),void 0!==i&&(this.height=i),void 0!==r&&(this.sideOrientation=r),void 0!==s&&(this.enableShadows=s)}},e.CreateCubeDto=class{constructor(e,t,i){this.size=1,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.size=e),void 0!==t&&(this.sideOrientation=t),void 0!==i&&(this.enableShadows=i)}},e.CreateSquarePlaneDto=class{constructor(e,t,i){this.size=1,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.size=e),void 0!==t&&(this.sideOrientation=t),void 0!==i&&(this.enableShadows=i)}},e.CreateSphereDto=class{constructor(e,t,i,r){this.diameter=1,this.segments=32,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.diameter=e),void 0!==t&&(this.segments=t),void 0!==i&&(this.sideOrientation=i),void 0!==r&&(this.enableShadows=r)}},e.CreateIcoSphereDto=class{constructor(e,t,i,r,s,n,o,a){this.radius=1,this.radiusX=0,this.radiusY=0,this.radiusZ=0,this.flat=!1,this.subdivisions=4,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.radius=e),void 0!==t&&(this.radiusX=t),void 0!==i&&(this.radiusY=i),void 0!==r&&(this.radiusZ=r),void 0!==s&&(this.flat=s),void 0!==n&&(this.subdivisions=n),void 0!==o&&(this.sideOrientation=o),void 0!==a&&(this.enableShadows=a)}},e.CreateDiscDto=class{constructor(e,t,i,r){this.radius=1,this.tessellation=32,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.radius=e),void 0!==t&&(this.tessellation=t),void 0!==i&&(this.sideOrientation=i),void 0!==r&&(this.enableShadows=r)}},e.CreateRibbonDto=class{constructor(e,t,i,r,s,n,o){this.closeArray=!1,this.closePath=!1,this.offset=0,this.updatable=!1,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.pathArray=e),void 0!==t&&(this.closeArray=t),void 0!==i&&(this.closePath=i),void 0!==r&&(this.offset=r),void 0!==s&&(this.updatable=s),void 0!==n&&(this.sideOrientation=n),void 0!==o&&(this.enableShadows=o)}},e.CreateTorusDto=class{constructor(e,t,i,r,s){this.diameter=1,this.thickness=.5,this.tessellation=32,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.diameter=e),void 0!==t&&(this.thickness=t),void 0!==i&&(this.tessellation=i),void 0!==r&&(this.sideOrientation=r),void 0!==s&&(this.enableShadows=s)}},e.CreateTorusKnotDto=class{constructor(e,t,i,r,s,n,o,a){this.radius=2,this.tube=.5,this.radialSegments=128,this.tubularSegments=32,this.p=2,this.q=3,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.radius=e),void 0!==t&&(this.tube=t),void 0!==i&&(this.radialSegments=i),void 0!==r&&(this.tubularSegments=r),void 0!==s&&(this.p=s),void 0!==n&&(this.q=n),void 0!==o&&(this.sideOrientation=o),void 0!==a&&(this.enableShadows=a)}},e.CreatePolygonDto=class{constructor(e,t,i,r,s,n,o){this.depth=0,this.smoothingThreshold=.01,this.sideOrientation=UH.sideOrientationEnum.frontside,this.wrap=!1,this.enableShadows=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.holes=t),void 0!==i&&(this.depth=i),void 0!==r&&(this.smoothingThreshold=r),void 0!==s&&(this.sideOrientation=s),void 0!==n&&(this.wrap=n),void 0!==o&&(this.enableShadows=o)}},e.ExtrudePolygonDto=class{constructor(e,t,i,r,s,n){this.depth=1,this.sideOrientation=UH.sideOrientationEnum.frontside,this.wrap=!1,this.enableShadows=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.holes=t),void 0!==i&&(this.depth=i),void 0!==r&&(this.sideOrientation=r),void 0!==s&&(this.wrap=s),void 0!==n&&(this.enableShadows=n)}},e.CreatePolyhedronDto=class{constructor(e,t,i,r,s,n,o,a,l){this.size=1,this.type=0,this.sizeX=0,this.sizeY=0,this.sizeZ=0,this.flat=!1,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.size=e),void 0!==t&&(this.type=t),void 0!==i&&(this.sizeX=i),void 0!==r&&(this.sizeY=r),void 0!==s&&(this.sizeZ=s),void 0!==n&&(this.custom=n),void 0!==o&&(this.flat=o),void 0!==a&&(this.sideOrientation=a),void 0!==l&&(this.enableShadows=l)}},e.CreateGeodesicDto=class{constructor(e,t,i,r,s,n,o,a,l,h){this.m=4,this.n=4,this.size=1,this.sizeX=0,this.sizeY=0,this.sizeZ=0,this.flat=!1,this.subdivisions=4,this.sideOrientation=UH.sideOrientationEnum.frontside,this.enableShadows=!0,void 0!==e&&(this.m=e),void 0!==t&&(this.n=t),void 0!==i&&(this.size=i),void 0!==r&&(this.sizeX=r),void 0!==s&&(this.sizeY=s),void 0!==n&&(this.sizeZ=n),void 0!==o&&(this.flat=o),void 0!==a&&(this.subdivisions=a),void 0!==l&&(this.sideOrientation=l),void 0!==h&&(this.enableShadows=h)}},e.CreateCapsuleDto=class{constructor(e,t,i,r,s,n,o,a,l,h,c,u){this.subdivisions=2,this.tessellation=16,this.height=2,this.radius=1,this.capSubdivisions=6,this.radiusTop=.5,this.radiusBottom=.5,this.topCapSubdivisions=6,this.bottomCapSubdivisions=6,this.sideOrientation=UH.sideOrientationEnum.doubleside,this.enableShadows=!0,void 0!==e&&(this.orientation=e),void 0!==t&&(this.subdivisions=t),void 0!==i&&(this.tessellation=i),void 0!==r&&(this.height=r),void 0!==s&&(this.radius=s),void 0!==n&&(this.capSubdivisions=n),void 0!==o&&(this.radiusTop=o),void 0!==a&&(this.radiusBottom=a),void 0!==l&&(this.topCapSubdivisions=l),void 0!==h&&(this.bottomCapSubdivisions=h),void 0!==c&&(this.sideOrientation=c),void 0!==u&&(this.enableShadows=u)}},e.CreateGoldbergDto=class{constructor(e,t,i,r,s,n,o,a){this.m=4,this.n=4,this.size=1,this.sizeX=0,this.sizeY=0,this.sizeZ=0,this.sideOrientation=UH.sideOrientationEnum.doubleside,this.enableShadows=!0,void 0!==e&&(this.m=e),void 0!==t&&(this.n=t),void 0!==i&&(this.size=i),void 0!==r&&(this.sizeX=r),void 0!==s&&(this.sizeY=s),void 0!==n&&(this.sizeZ=n),void 0!==o&&(this.sideOrientation=o),void 0!==a&&(this.enableShadows=a)}},e.CreateTubeDto=class{constructor(e,t,i,r,s,n,o){this.radius=1,this.tessellation=32,this.cap=0,this.arc=1,this.sideOrientation=UH.sideOrientationEnum.doubleside,this.enableShadows=!0,void 0!==e&&(this.path=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.tessellation=i),void 0!==r&&(this.cap=r),void 0!==s&&(this.arc=s),void 0!==n&&(this.sideOrientation=n),void 0!==o&&(this.enableShadows=o)}},e.CreateExtrudedShapeDto=class{constructor(e,t,i,r,s,n,o){this.scale=1,this.rotation=0,this.closeShape=!1,this.closePath=!1,this.cap=0,this.sideOrientation=UH.sideOrientationEnum.doubleside,this.enableShadows=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.path=t),void 0!==i&&(this.scale=i),void 0!==r&&(this.rotation=r),void 0!==s&&(this.cap=s),void 0!==n&&(this.sideOrientation=n),void 0!==o&&(this.enableShadows=o)}},e.CreateCylinderDto=class{constructor(e,t,i,r,s,n,o){this.height=1,this.diameterTop=1,this.diameterBottom=1,this.tessellation=64,this.subdivisions=1,this.sideOrientation=UH.sideOrientationEnum.doubleside,this.enableShadows=!0,void 0!==e&&(this.height=e),void 0!==t&&(this.diameterTop=t),void 0!==i&&(this.diameterBottom=i),void 0!==r&&(this.tessellation=r),void 0!==s&&(this.subdivisions=s),void 0!==n&&(this.sideOrientation=n),void 0!==o&&(this.enableShadows=o)}},e.CreateLatheDto=class{constructor(e,t,i,r,s,n,o){this.radius=1,this.tessellation=64,this.arc=1,this.closed=!0,this.sideOrientation=UH.sideOrientationEnum.doubleside,this.enableShadows=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.tessellation=i),void 0!==r&&(this.arc=r),void 0!==s&&(this.closed=s),void 0!==n&&(this.sideOrientation=n),void 0!==o&&(this.enableShadows=o)}},e.CreateGroundDto=class{constructor(e,t,i,r,s,n){this.width=10,this.height=10,this.subdivisionsX=1,this.subdivisionsY=1,this.sideOrientation=UH.sideOrientationEnum.doubleside,this.enableShadows=!0,void 0!==e&&(this.width=e),void 0!==t&&(this.height=t),void 0!==i&&(this.subdivisionsX=i),void 0!==r&&(this.subdivisionsY=r),void 0!==s&&(this.sideOrientation=s),void 0!==n&&(this.enableShadows=n)}},e.CreateRectanglePlaneDto=class{constructor(e,t,i,r){this.width=1,this.height=1,this.sideOrientation=UH.sideOrientationEnum.doubleside,this.enableShadows=!0,void 0!==e&&(this.width=e),void 0!==t&&(this.height=t),void 0!==i&&(this.sideOrientation=i),void 0!==r&&(this.enableShadows=r)}}}(XH||(XH={})),function(e){let t,i,r,s;!function(e){e.onDragStartObservable="onDragStartObservable",e.onDragObservable="onDragObservable",e.onDragEndObservable="onDragEndObservable"}(t=e.positionGizmoObservableSelectorEnum||(e.positionGizmoObservableSelectorEnum={})),function(e){e.onDragStartObservable="onDragStartObservable",e.onDragObservable="onDragObservable",e.onDragEndObservable="onDragEndObservable"}(i=e.rotationGizmoObservableSelectorEnum||(e.rotationGizmoObservableSelectorEnum={})),function(e){e.onDragStartObservable="onDragStartObservable",e.onDragObservable="onDragObservable",e.onDragEndObservable="onDragEndObservable"}(r=e.scaleGizmoObservableSelectorEnum||(e.scaleGizmoObservableSelectorEnum={})),function(e){e.onDragStartObservable="onDragStartObservable",e.onScaleBoxDragObservable="onScaleBoxDragObservable",e.onScaleBoxDragEndObservable="onScaleBoxDragEndObservable",e.onRotationSphereDragObservable="onRotationSphereDragObservable",e.onRotationSphereDragEndObservable="onRotationSphereDragEndObservable"}(s=e.boundingBoxGizmoObservableSelectorEnum||(e.boundingBoxGizmoObservableSelectorEnum={})),e.CreateGizmoDto=class{constructor(e,t,i,r,s,n,o,a){this.usePointerToAttachGizmos=!0,this.clearGizmoOnEmptyPointerEvent=!1,this.scaleRatio=1,void 0!==e&&(this.positionGizmoEnabled=e),void 0!==t&&(this.rotationGizmoEnabled=t),void 0!==i&&(this.scaleGizmoEnabled=i),void 0!==r&&(this.boundingBoxGizmoEnabled=r),void 0!==n&&(this.clearGizmoOnEmptyPointerEvent=n),void 0!==o&&(this.scaleRatio=o),void 0!==a&&(this.usePointerToAttachGizmos=a),void 0!==s&&(this.attachableMeshes=s)}},e.GizmoDto=class{constructor(e){void 0!==e&&(this.gizmo=e)}},e.SetGizmoScaleRatioDto=class{constructor(e,t){this.scaleRatio=1,void 0!==e&&(this.gizmo=e),void 0!==t&&(this.scaleRatio=t)}},e.GizmoManagerDto=class{constructor(e){void 0!==e&&(this.gizmoManager=e)}},e.PositionGizmoDto=class{constructor(e){void 0!==e&&(this.positionGizmo=e)}},e.SetPlanarGizmoEnabled=class{constructor(e,t){this.planarGizmoEnabled=!0,void 0!==e&&(this.positionGizmo=e),void 0!==t&&(this.planarGizmoEnabled=t)}},e.SetScaleGizmoSnapDistanceDto=class{constructor(e,t){this.snapDistance=0,void 0!==e&&(this.scaleGizmo=e),void 0!==t&&(this.snapDistance=t)}},e.SetScaleGizmoIncrementalSnapDto=class{constructor(e,t){this.incrementalSnap=!1,void 0!==e&&(this.scaleGizmo=e),void 0!==t&&(this.incrementalSnap=t)}},e.SetScaleGizmoSensitivityDto=class{constructor(e,t){this.sensitivity=1,void 0!==e&&(this.scaleGizmo=e),void 0!==t&&(this.sensitivity=t)}},e.ScaleGizmoDto=class{constructor(e){void 0!==e&&(this.scaleGizmo=e)}},e.BoundingBoxGizmoDto=class{constructor(e){void 0!==e&&(this.boundingBoxGizmo=e)}},e.SetBoundingBoxGizmoRotationSphereSizeDto=class{constructor(e,t){this.rotationSphereSize=.1,void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.rotationSphereSize=t)}},e.SetBoundingBoxGizmoFixedDragMeshScreenSizeDto=class{constructor(e,t){this.fixedDragMeshScreenSize=!1,void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.fixedDragMeshScreenSize=t)}},e.SetBoundingBoxGizmoFixedDragMeshBoundsSizeDto=class{constructor(e,t){this.fixedDragMeshBoundsSize=!1,void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.fixedDragMeshBoundsSize=t)}},e.SetBoundingBoxGizmoFixedDragMeshScreenSizeDistanceFactorDto=class{constructor(e,t){this.fixedDragMeshScreenSizeDistanceFactor=10,void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.fixedDragMeshScreenSizeDistanceFactor=t)}},e.SetBoundingBoxGizmoScalingSnapDistanceDto=class{constructor(e,t){this.scalingSnapDistance=0,void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.scalingSnapDistance=t)}},e.SetBoundingBoxGizmoRotationSnapDistanceDto=class{constructor(e,t){this.rotationSnapDistance=0,void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.rotationSnapDistance=t)}},e.SetBoundingBoxGizmoScaleBoxSizeDto=class{constructor(e,t){this.scaleBoxSize=.1,void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.scaleBoxSize=t)}},e.SetBoundingBoxGizmoIncrementalSnapDto=class{constructor(e,t){this.incrementalSnap=!1,void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.incrementalSnap=t)}},e.SetBoundingBoxGizmoScalePivotDto=class{constructor(e,t){void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.scalePivot=t)}},e.SetBoundingBoxGizmoAxisFactorDto=class{constructor(e,t){void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.axisFactor=t)}},e.SetBoundingBoxGizmoScaleDragSpeedDto=class{constructor(e,t){this.scaleDragSpeed=1,void 0!==e&&(this.boundingBoxGizmo=e),void 0!==t&&(this.scaleDragSpeed=t)}},e.SetPositionGizmoSnapDistanceDto=class{constructor(e,t){this.snapDistance=0,void 0!==e&&(this.positionGizmo=e),void 0!==t&&(this.snapDistance=t)}},e.SetRotationGizmoSnapDistanceDto=class{constructor(e,t){this.snapDistance=0,void 0!==e&&(this.rotationGizmo=e),void 0!==t&&(this.snapDistance=t)}},e.SetRotationGizmoSensitivityDto=class{constructor(e,t){this.sensitivity=1,void 0!==e&&(this.rotationGizmo=e),void 0!==t&&(this.sensitivity=t)}},e.RotationGizmoDto=class{constructor(e){void 0!==e&&(this.rotationGizmo=e)}},e.AxisScaleGizmoDto=class{constructor(e){void 0!==e&&(this.axisScaleGizmo=e)}},e.SetIsEnabledAxisScaleGizmoDto=class{constructor(e,t){this.isEnabled=!0,void 0!==e&&(this.axisScaleGizmo=e),void 0!==t&&(this.isEnabled=t)}},e.AxisDragGizmoDto=class{constructor(e){void 0!==e&&(this.axisDragGizmo=e)}},e.SetIsEnabledAxisDragGizmoDto=class{constructor(e,t){this.isEnabled=!0,void 0!==e&&(this.axisDragGizmo=e),void 0!==t&&(this.isEnabled=t)}},e.SetIsEnabledPlaneRotationGizmoDto=class{constructor(e,t){this.isEnabled=!0,void 0!==e&&(this.planeRotationGizmo=e),void 0!==t&&(this.isEnabled=t)}},e.SetIsEnabledPlaneDragGizmoDto=class{constructor(e,t){this.isEnabled=!0,void 0!==e&&(this.planeDragGizmo=e),void 0!==t&&(this.isEnabled=t)}},e.PlaneDragGizmoDto=class{constructor(e){void 0!==e&&(this.planeDragGizmo=e)}},e.PlaneRotationGizmoDto=class{constructor(e){void 0!==e&&(this.planeRotationGizmo=e)}},e.AttachToMeshDto=class{constructor(e,t){this.mesh=e,this.gizmoManager=t}},e.PositionGizmoObservableSelectorDto=class{constructor(e){this.selector=e}},e.BoundingBoxGizmoObservableSelectorDto=class{constructor(e){this.selector=e}},e.RotationGizmoObservableSelectorDto=class{constructor(e){this.selector=e}},e.ScaleGizmoObservableSelectorDto=class{constructor(e){this.selector=e}}}(qH||(qH={})),function(e){e.WebXRDefaultExperienceOptions=class{constructor(e){void 0!==e&&(this.disableDefaultUI=e)}},e.DefaultWebXRWithTeleportationDto=class{constructor(e){void 0!==e&&(this.groundMeshes=e)}},e.WebXRDefaultExperienceDto=class{constructor(e){void 0!==e&&(this.webXRDefaultExperience=e)}},e.WebXRExperienceHelperDto=class{constructor(e){void 0!==e&&(this.baseExperience=e)}}}(YH||(YH={})),function(e){let t,i;!function(e){e.default="default",e.clearSky="clearSky",e.city="city",e.greyGradient="greyGradient"}(t=e.skyboxEnum||(e.skyboxEnum={})),function(e){e.none="none",e.exponential="exponential",e.exponentialSquared="exponentialSquared",e.linear="linear"}(i=e.fogModeEnum||(e.fogModeEnum={}))}(KH||(KH={})),function(e){e.SceneBackgroundColourDto=class{constructor(e){this.colour="#ffffff",void 0!==e&&(this.colour=e)}},e.SceneDto=class{constructor(e){void 0!==e&&(this.scene=e)}},e.EnablePhysicsDto=class{constructor(e){this.vector=[0,-9.81,0],void 0!==e&&(this.vector=e)}},e.PointLightDto=class{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f){this.position=[0,0,0],this.intensity=2e3,this.diffuse="#ffffff",this.specular="#ffffff",this.radius=.1,this.shadowGeneratorMapSize=1024,this.enableShadows=!0,this.shadowDarkness=0,this.shadowUsePercentageCloserFiltering=!0,this.shadowContactHardeningLightSizeUVRatio=.2,this.shadowBias=1e-4,this.shadowNormalBias=.002,this.shadowMaxZ=1e3,this.shadowMinZ=0,void 0!==e&&(this.position=e),void 0!==t&&(this.intensity=t),void 0!==i&&(this.diffuse=i),void 0!==r&&(this.specular=r),void 0!==s&&(this.radius=s),void 0!==n&&(this.shadowGeneratorMapSize=n),void 0!==o&&(this.enableShadows=o),void 0!==a&&(this.shadowDarkness=a),void 0!==l&&(this.shadowUsePercentageCloserFiltering=l),void 0!==h&&(this.shadowContactHardeningLightSizeUVRatio=h),void 0!==c&&(this.shadowBias=c),void 0!==u&&(this.shadowNormalBias=u),void 0!==d&&(this.shadowMaxZ=d),void 0!==f&&(this.shadowMinZ=f)}},e.ActiveCameraDto=class{constructor(e){void 0!==e&&(this.camera=e)}},e.UseRightHandedSystemDto=class{constructor(e){this.use=!0,void 0!==e&&(this.use=e)}},e.DirectionalLightDto=class{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d){this.direction=[-100,-100,-100],this.intensity=.5,this.diffuse="#ffffff",this.specular="#ffffff",this.shadowGeneratorMapSize=1024,this.enableShadows=!0,this.shadowDarkness=0,this.shadowUsePercentageCloserFiltering=!0,this.shadowContactHardeningLightSizeUVRatio=.2,this.shadowBias=1e-4,this.shadowNormalBias=.002,this.shadowMaxZ=1e3,this.shadowMinZ=0,void 0!==e&&(this.direction=e),void 0!==t&&(this.intensity=t),void 0!==i&&(this.diffuse=i),void 0!==r&&(this.specular=r),void 0!==s&&(this.shadowGeneratorMapSize=s),void 0!==n&&(this.enableShadows=n),void 0!==o&&(this.shadowDarkness=o),void 0!==a&&(this.shadowUsePercentageCloserFiltering=a),void 0!==l&&(this.shadowContactHardeningLightSizeUVRatio=l),void 0!==h&&(this.shadowBias=h),void 0!==c&&(this.shadowNormalBias=c),void 0!==u&&(this.shadowMaxZ=u),void 0!==d&&(this.shadowMinZ=d)}},e.CameraConfigurationDto=class{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d){this.position=[10,10,10],this.lookAt=[0,0,0],this.lowerBetaLimit=1,this.upperBetaLimit=179,this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.maxZ=1e3,this.panningSensibility=1e3,this.wheelPrecision=3,void 0!==e&&(this.position=e),void 0!==t&&(this.lookAt=t),void 0!==i&&(this.lowerRadiusLimit=i),void 0!==r&&(this.upperRadiusLimit=r),void 0!==s&&(this.lowerAlphaLimit=s),void 0!==n&&(this.upperAlphaLimit=n),void 0!==o&&(this.lowerBetaLimit=o),void 0!==a&&(this.upperBetaLimit=a),void 0!==l&&(this.angularSensibilityX=l),void 0!==h&&(this.angularSensibilityY=h),void 0!==c&&(this.maxZ=c),void 0!==u&&(this.panningSensibility=u),void 0!==d&&(this.wheelPrecision=d)}},e.SkyboxDto=class{constructor(e,t,i,r){this.skybox=KH.skyboxEnum.clearSky,this.size=1e3,this.blur=.1,this.environmentIntensity=.7,void 0!==e&&(this.skybox=e),void 0!==t&&(this.size=t),void 0!==i&&(this.blur=i),void 0!==r&&(this.environmentIntensity=r)}},e.PointerDto=class{},e.FogDto=class{constructor(e,t,i,r,s){this.color="#ffffff",this.density=.1,void 0!==e&&(this.mode=e),void 0!==t&&(this.color=t),void 0!==i&&(this.density=i),void 0!==r&&(this.start=r),void 0!==s&&(this.end=s)}}}(jH||(jH={})),function(e){e.NodeDto=class{constructor(e){void 0!==e&&(this.node=e)}},e.NodeTranslationDto=class{constructor(e,t,i){void 0!==e&&(this.node=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.distance=i)}},e.NodeParentDto=class{constructor(e,t){void 0!==e&&(this.node=e),void 0!==t&&(this.parentNode=t)}},e.NodeDirectionDto=class{constructor(e,t){void 0!==e&&(this.node=e),void 0!==t&&(this.direction=t)}},e.NodePositionDto=class{constructor(e,t){void 0!==e&&(this.node=e),void 0!==t&&(this.position=t)}},e.RotateNodeDto=class{constructor(e,t,i){this.axis=[0,1,0],this.angle=0,void 0!==e&&(this.node=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.angle=i)}},e.RotateAroundAxisNodeDto=class{constructor(e,t,i,r){this.position=[0,0,0],this.axis=[0,1,0],this.angle=0,void 0!==e&&(this.node=e),void 0!==t&&(this.position=t),void 0!==i&&(this.axis=i),void 0!==r&&(this.angle=r)}},e.CreateNodeFromRotationDto=class{constructor(e,t,i){this.origin=[0,0,0],this.rotation=[0,0,0],void 0!==e&&(this.parent=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.rotation=i)}},e.DrawNodeDto=class{constructor(e,t,i,r,s){this.colorX="#ff0000",this.colorY="#00ff00",this.colorZ="#0000ff",this.size=2,void 0!==e&&(this.node=e),void 0!==t&&(this.colorX=t),void 0!==i&&(this.colorY=i),void 0!==r&&(this.colorZ=r),void 0!==s&&(this.size=s)}},e.DrawNodesDto=class{constructor(e,t,i,r,s){this.colorX="#ff0000",this.colorY="#00ff00",this.colorZ="#0000ff",this.size=2,void 0!==e&&(this.nodes=e),void 0!==t&&(this.colorX=t),void 0!==i&&(this.colorY=i),void 0!==r&&(this.colorZ=r),void 0!==s&&(this.size=s)}}}($H||($H={})),function(e){let t;e.DrawAny=class{constructor(e,t,i){void 0!==e&&(this.entity=e),void 0!==t&&(this.options=t),void 0!==i&&(this.babylonMesh=i)}},e.SceneDrawGridMeshDto=class{constructor(e,t,i,r,s,n,o,a,l,h){this.width=400,this.height=400,this.subdivisions=10,this.majorUnitFrequency=10,this.minorUnitVisibility=.45,this.gridRatio=.5,this.opacity=.5,this.backFaceCulling=!1,this.mainColor="#ffffff",this.secondaryColor="#ffffff",void 0!==e&&(this.width=e),void 0!==t&&(this.height=t),void 0!==i&&(this.subdivisions=i),void 0!==r&&(this.majorUnitFrequency=r),void 0!==s&&(this.minorUnitVisibility=s),void 0!==n&&(this.gridRatio=n),void 0!==o&&(this.opacity=o),void 0!==a&&(this.backFaceCulling=a),void 0!==l&&(this.mainColor=l),void 0!==h&&(this.secondaryColor=h)}},e.DrawBasicGeometryOptions=class{constructor(e,t,i,r,s){this.colours="#ff0000",this.size=.1,this.opacity=1,this.updatable=!1,this.hidden=!1,void 0!==e&&(this.colours=e),void 0!==t&&(this.size=t),void 0!==i&&(this.opacity=i),void 0!==r&&(this.updatable=r),void 0!==s&&(this.hidden=s)}},e.DrawNodeOptions=class{constructor(e,t,i,r){this.colorX="#0000ff",this.colorY="#00ff00",this.colorZ="#ff0000",this.size=2,void 0!==e&&(this.colorX=e),void 0!==t&&(this.colorY=t),void 0!==i&&(this.colorZ=i),void 0!==r&&(this.size=r)}},e.DrawManifoldOrCrossSectionOptions=class{constructor(e,t,i,r,s,n,o){this.faceOpacity=1,this.faceColour="#ff0000",this.crossSectionColour="#ff00ff",this.crossSectionWidth=2,this.computeNormals=!1,void 0!==e&&(this.faceOpacity=e),void 0!==t&&(this.faceMaterial=t),void 0!==i&&(this.faceColour=i),void 0!==r&&(this.crossSectionColour=r),void 0!==s&&(this.crossSectionWidth=s),void 0!==n&&(this.crossSectionOpacity=n),void 0!==o&&(this.computeNormals=o)}},e.DrawOcctShapeOptions=class{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m,g){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.vertexColour="#ffaaff",this.edgeWidth=2,this.vertexSize=.03,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.faceOpacity=e),void 0!==t&&(this.edgeOpacity=t),void 0!==i&&(this.edgeColour=i),void 0!==r&&(this.faceMaterial=r),void 0!==s&&(this.faceColour=s),void 0!==h&&(this.vertexColour=h),void 0!==c&&(this.vertexSize=c),void 0!==n&&(this.edgeWidth=n),void 0!==o&&(this.drawEdges=o),void 0!==a&&(this.drawFaces=a),void 0!==l&&(this.drawVertices=l),void 0!==u&&(this.precision=u),void 0!==d&&(this.drawEdgeIndexes=d),void 0!==f&&(this.edgeIndexHeight=f),void 0!==p&&(this.edgeIndexColour=p),void 0!==_&&(this.drawFaceIndexes=_),void 0!==m&&(this.faceIndexHeight=m),void 0!==g&&(this.faceIndexColour=g)}},e.DrawOcctShapeSimpleOptions=class{constructor(e,t,i,r,s,n){this.precision=.01,this.drawFaces=!0,this.faceColour="#ff0000",this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=2,void 0!==e&&(this.precision=e),void 0!==t&&(this.drawFaces=t),void 0!==i&&(this.faceColour=i),void 0!==r&&(this.drawEdges=r),void 0!==s&&(this.edgeColour=s),void 0!==n&&(this.edgeWidth=n)}},e.DrawOcctShapeMaterialOptions=class{constructor(e,t,i,r,s){this.precision=.01,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=2,void 0!==e&&(this.precision=e),void 0!==t&&(this.faceMaterial=t),void 0!==i&&(this.drawEdges=i),void 0!==r&&(this.edgeColour=r),void 0!==s&&(this.edgeWidth=s)}},function(e){e[e.point=0]="point",e[e.points=1]="points",e[e.line=2]="line",e[e.lines=3]="lines",e[e.node=4]="node",e[e.nodes=5]="nodes",e[e.polyline=6]="polyline",e[e.polylines=7]="polylines",e[e.verbCurve=8]="verbCurve",e[e.verbCurves=9]="verbCurves",e[e.verbSurface=10]="verbSurface",e[e.verbSurfaces=11]="verbSurfaces",e[e.jscadMesh=12]="jscadMesh",e[e.jscadMeshes=13]="jscadMeshes",e[e.occt=14]="occt",e[e.manifold=15]="manifold",e[e.tag=16]="tag",e[e.tags=17]="tags"}(t=e.drawingTypes||(e.drawingTypes={}))}(QH||(QH={})),function(e){e.GetAssetDto=class{constructor(e){void 0!==e&&(this.fileName=e)}},e.FetchDto=class{constructor(e){void 0!==e&&(this.url=e)}},e.FileDto=class{constructor(e){void 0!==e&&(this.file=e)}},e.FilesDto=class{constructor(e){void 0!==e&&(this.files=e)}},e.AssetFileDto=class{constructor(e,t){this.hidden=!1,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.hidden=t)}},e.AssetFileByUrlDto=class{constructor(e,t,i){this.hidden=!1,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.rootUrl=t),void 0!==i&&(this.hidden=i)}}}(ZH||(ZH={})),function(e){e.StringifyDto=class{constructor(e){void 0!==e&&(this.json=e)}},e.ParseDto=class{constructor(e){this.text="[0, 0, 0]",void 0!==e&&(this.text=e)}},e.QueryDto=class{constructor(e,t){void 0!==e&&(this.json=e),void 0!==t&&(this.query=t)}},e.SetValueOnPropDto=class{constructor(e,t,i){this.property="propName",void 0!==e&&(this.json=e),void 0!==t&&(this.value=t),void 0!==i&&(this.property=i)}},e.GetJsonFromArrayByFirstPropMatchDto=class{constructor(e,t,i){this.property="propName",void 0!==e&&(this.jsonArray=e),void 0!==t&&(this.property=t),void 0!==i&&(this.match=i)}},e.GetValueOnPropDto=class{constructor(e,t){this.property="propName",void 0!==e&&(this.json=e),void 0!==t&&(this.property=t)}},e.SetValueDto=class{constructor(e,t,i,r){this.path="$.pathToParent",this.prop="propertyName",void 0!==e&&(this.json=e),void 0!==t&&(this.value=t),void 0!==i&&(this.path=i),void 0!==r&&(this.prop=r)}},e.SetValuesOnPathsDto=class{constructor(e,t,i,r){void 0!==e&&(this.json=e),void 0!==t&&(this.values=t),void 0!==i&&(this.paths=i),void 0!==r&&(this.props=r)}},e.PathsDto=class{constructor(e,t){void 0!==e&&(this.json=e),void 0!==t&&(this.query=t)}},e.JsonDto=class{constructor(e){void 0!==e&&(this.json=e)}}}(JH||(JH={})),function(e){e.LinePointsDto=class{constructor(e,t){void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.LineStartEndPointsDto=class{constructor(e,t){void 0!==e&&(this.startPoints=e),void 0!==t&&(this.endPoints=t)}},e.DrawLineDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.line=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==r&&(this.size=r),void 0!==s&&(this.updatable=s),void 0!==n&&(this.lineMesh=n)}},e.DrawLinesDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.lines=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==r&&(this.size=r),void 0!==s&&(this.updatable=s),void 0!==n&&(this.linesMesh=n)}},e.PointsLinesDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.LineDto=class{constructor(e){void 0!==e&&(this.line=e)}},e.LinesDto=class{constructor(e){void 0!==e&&(this.lines=e)}},e.PointOnLineDto=class{constructor(e,t){void 0!==e&&(this.line=e),void 0!==t&&(this.param=t)}},e.TransformLineDto=class{constructor(e,t){void 0!==e&&(this.line=e),void 0!==t&&(this.transformation=t)}},e.TransformsLinesDto=class{constructor(e,t){void 0!==e&&(this.lines=e),void 0!==t&&(this.transformation=t)}},e.TransformLinesDto=class{constructor(e,t){void 0!==e&&(this.lines=e),void 0!==t&&(this.transformation=t)}}}(eX||(eX={})),function(e){e.PolylinePropertiesDto=class{constructor(e,t){this.isClosed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.isClosed=t)}},e.PolylineDto=class{constructor(e){void 0!==e&&(this.polyline=e)}},e.PolylinesDto=class{constructor(e){void 0!==e&&(this.polylines=e)}},e.TransformPolylineDto=class{constructor(e,t){void 0!==e&&(this.polyline=e),void 0!==t&&(this.transformation=t)}},e.DrawPolylineDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.polyline=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==r&&(this.size=r),void 0!==s&&(this.updatable=s),void 0!==n&&(this.polylineMesh=n)}},e.DrawPolylinesDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.polylines=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==r&&(this.size=r),void 0!==s&&(this.updatable=s),void 0!==n&&(this.polylinesMesh=n)}}}(tX||(tX={})),function(e){e.DrawTagDto=class{constructor(e,t,i){this.updatable=!1,void 0!==e&&(this.tag=e),void 0!==t&&(this.updatable=t),void 0!==i&&(this.tagVariable=i)}},e.DrawTagsDto=class{constructor(e,t,i){this.updatable=!1,void 0!==e&&(this.tags=e),void 0!==t&&(this.updatable=t),void 0!==i&&(this.tagsVariable=i)}},e.TagDto=class{constructor(e,t,i,r,s,n,o){this.position=[0,0,0],this.colour="#444444",this.size=12,this.adaptDepth=!1,void 0!==e&&(this.text=e),void 0!==t&&(this.position=t),void 0!==i&&(this.colour=i),void 0!==r&&(this.size=r),void 0!==s&&(this.adaptDepth=s),void 0!==n&&(this.needsUpdate=n),void 0!==o&&(this.id=o)}}}(iX||(iX={})),function(e){e.PostFromIframe=class{constructor(e,t){void 0!==e&&(this.data=e),void 0!==t&&(this.targetOrigin=t)}}}(rX||(rX={})),function(e){e.CurveDto=class{constructor(e){void 0!==e&&(this.curve=e)}},e.CurvesDto=class{constructor(e){void 0!==e&&(this.curves=e)}},e.ClosestPointDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.point=t)}},e.ClosestPointsDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.points=t)}},e.BezierCurveDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.weights=t)}},e.DrawCurveDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.curve=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==r&&(this.size=r),void 0!==s&&(this.updatable=s),void 0!==n&&(this.curveMesh=n)}},e.CurveParameterDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.parameter=t)}},e.CurvesParameterDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.parameter=t)}},e.CurveTransformDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.transformation=t)}},e.CurvesTransformDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.transformation=t)}},e.CurveToleranceDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.tolerance=t)}},e.CurveLengthToleranceDto=class{constructor(e,t,i){void 0!==e&&(this.curve=e),void 0!==t&&(this.length=t),void 0!==i&&(this.tolerance=i)}},e.CurveDerivativesDto=class{constructor(e,t,i){void 0!==e&&(this.curve=e),void 0!==t&&(this.parameter=t),void 0!==i&&(this.numDerivatives=i)}},e.CurveSubdivisionsDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.subdivision=t)}},e.CurvesSubdivisionsDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.subdivision=t)}},e.CurvesDivideLengthDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.length=t)}},e.CurveDivideLengthDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.length=t)}},e.DrawCurvesDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.curves=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==r&&(this.size=r),void 0!==s&&(this.updatable=s),void 0!==n&&(this.curvesMesh=n)}},e.CurveNurbsDataDto=class{constructor(e,t,i,r){void 0!==e&&(this.degree=e),void 0!==t&&(this.weights=t),void 0!==i&&(this.knots=i),void 0!==r&&(this.points=r)}},e.CurvePathDataDto=class{constructor(e,t){void 0!==e&&(this.degree=e),void 0!==t&&(this.points=t)}},e.EllipseDto=class{constructor(e){void 0!==e&&(this.ellipse=e)}},e.CircleDto=class{constructor(e){void 0!==e&&(this.circle=e)}},e.ArcDto=class{constructor(e){void 0!==e&&(this.arc=e)}},e.EllipseParametersDto=class{constructor(e,t,i){void 0!==e&&(this.xAxis=e),void 0!==t&&(this.yAxis=t),void 0!==i&&(this.center=i)}},e.CircleParametersDto=class{constructor(e,t,i,r){void 0!==e&&(this.xAxis=e),void 0!==t&&(this.yAxis=t),void 0!==i&&(this.radius=i),void 0!==r&&(this.center=r)}},e.ArcParametersDto=class{constructor(e,t,i,r,s,n){void 0!==e&&(this.minAngle=e),void 0!==t&&(this.maxAngle=t),void 0!==i&&(this.xAxis=i),void 0!==r&&(this.yAxis=r),void 0!==s&&(this.radius=s),void 0!==n&&(this.center=n)}},e.EllipseArcParametersDto=class{constructor(e,t,i,r,s){void 0!==e&&(this.minAngle=e),void 0!==t&&(this.maxAngle=t),void 0!==i&&(this.xAxis=i),void 0!==r&&(this.yAxis=r),void 0!==s&&(this.center=s)}},e.SurfaceDto=class{constructor(e){void 0!==e&&(this.surface=e)}},e.SurfaceTransformDto=class{constructor(e,t){void 0!==e&&(this.surface=e),void 0!==t&&(this.transformation=t)}},e.SurfaceParameterDto=class{constructor(e,t,i){void 0!==e&&(this.surface=e),void 0!==t&&(this.parameter=t),void 0!==i&&(this.useV=i)}},e.IsocurvesParametersDto=class{constructor(e,t,i){void 0!==e&&(this.surface=e),void 0!==t&&(this.parameters=t),void 0!==i&&(this.useV=i)}},e.IsocurveSubdivisionDto=class{constructor(e,t,i,r,s){this.useV=!1,this.includeLast=!0,this.includeFirst=!0,void 0!==e&&(this.surface=e),void 0!==t&&(this.useV=t),void 0!==i&&(this.includeLast=i),void 0!==r&&(this.includeFirst=r),void 0!==s&&(this.isocurveSegments=s)}},e.DerivativesDto=class{constructor(e,t,i,r){void 0!==e&&(this.surface=e),void 0!==t&&(this.u=t),void 0!==i&&(this.v=i),void 0!==r&&(this.numDerivatives=r)}},e.SurfaceLocationDto=class{constructor(e,t,i){void 0!==e&&(this.surface=e),void 0!==t&&(this.u=t),void 0!==i&&(this.v=i)}},e.CornersDto=class{constructor(e,t,i,r){void 0!==e&&(this.point1=e),void 0!==t&&(this.point2=t),void 0!==i&&(this.point3=i),void 0!==r&&(this.point4=r)}},e.SurfaceParamDto=class{constructor(e,t){void 0!==e&&(this.surface=e),void 0!==t&&(this.point=t)}},e.KnotsControlPointsWeightsDto=class{constructor(e,t,i,r,s,n){void 0!==e&&(this.degreeU=e),void 0!==t&&(this.degreeV=t),void 0!==i&&(this.knotsU=i),void 0!==r&&(this.knotsV=r),void 0!==s&&(this.points=s),void 0!==n&&(this.weights=n)}},e.LoftCurvesDto=class{constructor(e,t){void 0!==e&&(this.degreeV=e),void 0!==t&&(this.curves=t)}},e.DrawSurfaceDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.surface=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==r&&(this.updatable=r),void 0!==s&&(this.hidden=s),void 0!==n&&(this.surfaceMesh=n)}},e.DrawSurfacesDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.surfaces=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==r&&(this.updatable=r),void 0!==s&&(this.hidden=s),void 0!==n&&(this.surfacesMesh=n)}},e.DrawSurfacesColoursDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.updatable=!1,this.hidden=!1,void 0!==e&&(this.surfaces=e),void 0!==t&&(this.colours=t),void 0!==i&&(this.opacity=i),void 0!==r&&(this.updatable=r),void 0!==s&&(this.hidden=s),void 0!==n&&(this.surfacesMesh=n)}},e.ConeAndCylinderParametersDto=class{constructor(e,t,i,r,s){this.axis=[0,1,0],this.xAxis=[1,0,0],this.base=[0,0,0],this.height=2,this.radius=1,void 0!==e&&(this.axis=e),void 0!==t&&(this.xAxis=t),void 0!==i&&(this.base=i),void 0!==r&&(this.height=r),void 0!==s&&(this.radius=s)}},e.ConeDto=class{constructor(e){void 0!==e&&(this.cone=e)}},e.CylinderDto=class{constructor(e){void 0!==e&&(this.cylinder=e)}},e.ExtrusionParametersDto=class{constructor(e,t){void 0!==e&&(this.profile=e),void 0!==t&&(this.direction=t)}},e.ExtrusionDto=class{constructor(e){void 0!==e&&(this.extrusion=e)}},e.SphericalParametersDto=class{constructor(e,t){void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t)}},e.SphereDto=class{constructor(e){void 0!==e&&(this.sphere=e)}},e.RevolutionParametersDto=class{constructor(e,t,i,r){void 0!==e&&(this.profile=e),void 0!==t&&(this.center=t),void 0!==i&&(this.axis=i),void 0!==r&&(this.angle=r)}},e.RevolutionDto=class{constructor(e){void 0!==e&&(this.revolution=e)}},e.SweepParametersDto=class{constructor(e,t){void 0!==e&&(this.profile=e),void 0!==t&&(this.rail=t)}},e.SweepDto=class{constructor(e){void 0!==e&&(this.sweep=e)}},e.CurveCurveDto=class{constructor(e,t,i){void 0!==e&&(this.firstCurve=e),void 0!==t&&(this.secondCurve=t),void 0!==i&&(this.tolerance=i)}},e.CurveSurfaceDto=class{constructor(e,t,i){void 0!==e&&(this.curve=e),void 0!==t&&(this.surface=t),void 0!==i&&(this.tolerance=i)}},e.SurfaceSurfaceDto=class{constructor(e,t,i){void 0!==e&&(this.firstSurface=e),void 0!==t&&(this.secondSurface=t),void 0!==i&&(this.tolerance=i)}},e.CurveCurveIntersectionsDto=class{constructor(e){void 0!==e&&(this.intersections=e)}},e.CurveSurfaceIntersectionsDto=class{constructor(e){void 0!==e&&(this.intersections=e)}}}(sX||(sX={})),function(e){let t,i;e.PolylinePropertiesDto=class{constructor(e,t){this.isClosed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.isClosed=t)}},function(e){e.edge="edge",e.round="round",e.chamfer="chamfer"}(t=e.solidCornerTypeEnum||(e.solidCornerTypeEnum={})),function(e){e.left="left",e.center="center",e.right="right"}(i=e.jscadTextAlignEnum||(e.jscadTextAlignEnum={})),e.DrawSolidMeshDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.mesh=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==r&&(this.updatable=r),void 0!==s&&(this.hidden=s),void 0!==n&&(this.jscadMesh=n)}},e.DrawSolidMeshesDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.meshes=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==r&&(this.updatable=r),void 0!==s&&(this.hidden=s),void 0!==n&&(this.jscadMesh=n)}},e.DrawPathDto=class{constructor(e,t,i,r,s,n){this.colour="#444444",this.opacity=1,this.width=10,this.updatable=!1,void 0!==e&&(this.path=e),void 0!==t&&(this.colour=t),void 0!==i&&(this.opacity=i),void 0!==r&&(this.width=r),void 0!==s&&(this.updatable=s),void 0!==n&&(this.pathMesh=n)}},e.TransformSolidsDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.transformation=t)}},e.TransformSolidDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.transformation=t)}},e.DownloadSolidDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.fileName=t)}},e.DownloadGeometryDto=class{constructor(e,t,i){this.fileName="jscad-geometry",void 0!==e&&(this.geometry=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.options=i)}},e.DownloadSolidsDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.fileName=t)}},e.ColorizeDto=class{constructor(e,t){this.color="#0000ff",void 0!==e&&(this.geometry=e),void 0!==t&&(this.color=t)}},e.BooleanObjectsDto=class{constructor(e){void 0!==e&&(this.meshes=e)}},e.BooleanTwoObjectsDto=class{constructor(e,t){void 0!==e&&(this.first=e),void 0!==t&&(this.second=t)}},e.BooleanObjectsFromDto=class{constructor(e,t){void 0!==e&&(this.from=e),void 0!==t&&(this.meshes=t)}},e.ExpansionDto=class{constructor(e,i,r,s){this.delta=.1,this.corners=t.edge,this.segments=24,void 0!==e&&(this.geometry=e),void 0!==i&&(this.delta=i),void 0!==r&&(this.corners=r),void 0!==s&&(this.segments=s)}},e.OffsetDto=class{constructor(e,i,r,s){this.delta=.1,this.corners=t.edge,this.segments=24,void 0!==e&&(this.geometry=e),void 0!==i&&(this.delta=i),void 0!==r&&(this.corners=r),void 0!==s&&(this.segments=s)}},e.ExtrudeLinearDto=class{constructor(e,t,i,r){this.height=1,this.twistAngle=90,this.twistSteps=15,void 0!==e&&(this.geometry=e),void 0!==t&&(this.height=t),void 0!==i&&(this.twistAngle=i),void 0!==r&&(this.twistSteps=r)}},e.HullDto=class{constructor(e){void 0!==e&&(this.meshes=e)}},e.ExtrudeRectangularDto=class{constructor(e,t,i){this.height=1,this.size=1,void 0!==e&&(this.geometry=e),void 0!==t&&(this.height=t),void 0!==i&&(this.size=i)}},e.ExtrudeRectangularPointsDto=class{constructor(e,t,i){this.height=1,this.size=1,void 0!==e&&(this.points=e),void 0!==t&&(this.height=t),void 0!==i&&(this.size=i)}},e.ExtrudeRotateDto=class{constructor(e,t,i,r){this.angle=90,this.startAngle=0,this.segments=24,void 0!==e&&(this.polygon=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.startAngle=i),void 0!==r&&(this.segments=r)}},e.PolylineDto=class{constructor(e){void 0!==e&&(this.polyline=e)}},e.CurveDto=class{constructor(e){void 0!==e&&(this.curve=e)}},e.PointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PathDto=class{constructor(e){void 0!==e&&(this.path=e)}},e.PathFromPointsDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.PathsFromPointsDto=class{constructor(e){void 0!==e&&(this.pointsLists=e)}},e.PathFromPolylineDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.polyline=e),void 0!==t&&(this.closed=t)}},e.PathAppendCurveDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.path=t)}},e.PathAppendPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.path=t)}},e.PathAppendPolylineDto=class{constructor(e,t){void 0!==e&&(this.polyline=e),void 0!==t&&(this.path=t)}},e.PathAppendArcDto=class{constructor(e,t,i,r,s,n,o,a){this.endPoint=[1,1],this.xAxisRotation=90,this.clockwise=!0,this.large=!1,this.segments=24,this.radiusX=1,this.radiusY=1,void 0!==e&&(this.path=e),void 0!==t&&(this.endPoint=t),void 0!==i&&(this.xAxisRotation=i),void 0!==r&&(this.clockwise=r),void 0!==s&&(this.large=s),void 0!==n&&(this.segments=n),void 0!==o&&(this.radiusX=o),void 0!==a&&(this.radiusY=a)}},e.CircleDto=class{constructor(e,t,i){this.center=[0,0],this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.EllipseDto=class{constructor(e,t,i){this.center=[0,0],this.radius=[1,2],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.SquareDto=class{constructor(e,t){this.center=[0,0],this.size=1,void 0!==e&&(this.center=e),void 0!==t&&(this.size=t)}},e.RectangleDto=class{constructor(e,t,i){this.center=[0,0],this.width=1,this.length=1,void 0!==e&&(this.center=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i)}},e.RoundedRectangleDto=class{constructor(e,t,i,r,s){this.center=[0,0],this.roundRadius=.2,this.segments=24,this.width=1,this.length=1,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.segments=i),void 0!==r&&(this.width=r),void 0!==s&&(this.length=s)}},e.StarDto=class{constructor(e,t,i,r,s,n){this.center=[0,0],this.vertices=10,this.density=1,this.outerRadius=2,this.innerRadius=1,this.startAngle=0,void 0!==e&&(this.center=e),void 0!==t&&(this.vertices=t),void 0!==i&&(this.density=i),void 0!==r&&(this.outerRadius=r),void 0!==s&&(this.innerRadius=s),void 0!==n&&(this.startAngle=n)}},e.CubeDto=class{constructor(e,t){this.center=[0,0,0],this.size=1,void 0!==e&&(this.center=e),void 0!==t&&(this.size=t)}},e.CubeCentersDto=class{constructor(e,t){this.size=1,void 0!==e&&(this.centers=e),void 0!==t&&(this.size=t)}},e.CuboidDto=class{constructor(e,t,i,r){this.center=[0,0,0],this.width=1,this.length=1,this.height=1,void 0!==e&&(this.center=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==r&&(this.height=r)}},e.CuboidCentersDto=class{constructor(e,t,i,r){this.width=1,this.length=1,this.height=1,void 0!==e&&(this.centers=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==r&&(this.height=r)}},e.RoundedCuboidDto=class{constructor(e,t,i,r,s,n){this.center=[0,0,0],this.roundRadius=1,this.width=1,this.length=1,this.height=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.width=i),void 0!==r&&(this.length=r),void 0!==s&&(this.height=s),void 0!==n&&(this.segments=n)}},e.RoundedCuboidCentersDto=class{constructor(e,t,i,r,s,n){this.roundRadius=.1,this.width=1,this.length=1,this.height=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.width=i),void 0!==r&&(this.length=r),void 0!==s&&(this.height=s),void 0!==n&&(this.segments=n)}},e.CylidnerEllipticDto=class{constructor(e,t,i,r,s){this.center=[0,0,0],this.height=1,this.startRadius=[1,2],this.endRadius=[2,3],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.height=t),void 0!==i&&(this.startRadius=i),void 0!==r&&(this.endRadius=r),void 0!==s&&(this.segments=s)}},e.CylidnerCentersEllipticDto=class{constructor(e,t,i,r,s){this.height=1,this.startRadius=[1,2],this.endRadius=[2,3],this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.height=t),void 0!==i&&(this.startRadius=i),void 0!==r&&(this.endRadius=r),void 0!==s&&(this.segments=s)}},e.CylidnerDto=class{constructor(e,t,i,r){this.center=[0,0,0],this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.height=t),void 0!==i&&(this.radius=i),void 0!==r&&(this.segments=r)}},e.RoundedCylidnerDto=class{constructor(e,t,i,r,s){this.center=[0,0,0],this.roundRadius=.1,this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.height=i),void 0!==r&&(this.radius=r),void 0!==s&&(this.segments=s)}},e.EllipsoidDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=[1,2,3],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.EllipsoidCentersDto=class{constructor(e,t,i){this.radius=[1,2,3],this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.GeodesicSphereDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=1,this.frequency=12,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.frequency=i)}},e.GeodesicSphereCentersDto=class{constructor(e,t,i){this.radius=1,this.frequency=12,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.frequency=i)}},e.CylidnerCentersDto=class{constructor(e,t,i,r){this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.height=t),void 0!==i&&(this.radius=i),void 0!==r&&(this.segments=r)}},e.RoundedCylidnerCentersDto=class{constructor(e,t,i,r,s){this.roundRadius=.1,this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.height=i),void 0!==r&&(this.radius=r),void 0!==s&&(this.segments=s)}},e.SphereDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.SphereCentersDto=class{constructor(e,t,i){this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.TorusDto=class{constructor(e,t,i,r,s,n,o,a){this.center=[0,0,0],this.innerRadius=1,this.outerRadius=2,this.innerSegments=24,this.outerSegments=24,this.innerRotation=0,this.outerRotation=360,this.startAngle=0,void 0!==e&&(this.center=e),void 0!==t&&(this.innerRadius=t),void 0!==i&&(this.outerRadius=i),void 0!==r&&(this.innerSegments=r),void 0!==s&&(this.outerSegments=s),void 0!==n&&(this.innerRotation=n),void 0!==o&&(this.outerRotation=o),void 0!==a&&(this.startAngle=a)}},e.TextDto=class{constructor(e,t,r,s,n,o,a,l,h){this.text="Hello World",this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.segments=t),void 0!==r&&(this.xOffset=r),void 0!==s&&(this.yOffset=s),void 0!==n&&(this.height=n),void 0!==o&&(this.lineSpacing=o),void 0!==a&&(this.letterSpacing=a),void 0!==l&&(this.align=l),void 0!==h&&(this.extrudeOffset=h)}},e.CylinderTextDto=class{constructor(e,t,r,s,n,o,a,l,h,c,u){this.text="Hello World",this.extrusionHeight=.5,this.extrusionSize=.1,this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.extrusionHeight=t),void 0!==r&&(this.extrusionSize=r),void 0!==s&&(this.segments=s),void 0!==n&&(this.xOffset=n),void 0!==o&&(this.yOffset=o),void 0!==a&&(this.height=a),void 0!==l&&(this.lineSpacing=l),void 0!==h&&(this.letterSpacing=h),void 0!==c&&(this.align=c),void 0!==u&&(this.extrudeOffset=u)}},e.SphereTextDto=class{constructor(e,t,r,s,n,o,a,l,h,c){this.text="Hello World",this.radius=.1,this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.radius=t),void 0!==r&&(this.segments=r),void 0!==s&&(this.xOffset=s),void 0!==n&&(this.yOffset=n),void 0!==o&&(this.height=o),void 0!==a&&(this.lineSpacing=a),void 0!==l&&(this.letterSpacing=l),void 0!==h&&(this.align=h),void 0!==c&&(this.extrudeOffset=c)}},e.FromPolygonPoints=class{constructor(e){void 0!==e&&(this.polygonPoints=e)}}}(nX||(nX={})),function(e){let t,i;!function(e){e.evenOdd="EvenOdd",e.nonZero="NonZero",e.positive="Positive",e.negative="Negative"}(t=e.fillRuleEnum||(e.fillRuleEnum={})),function(e){e.square="Square",e.round="Round",e.miter="Miter"}(i=e.manifoldJoinTypeEnum||(e.manifoldJoinTypeEnum={})),e.DecomposedManifoldMeshDto=class{},e.DrawManifoldOrCrossSectionDto=class{constructor(e,t,i,r,s,n,o,a){this.faceOpacity=1,this.faceColour="#ff0000",this.crossSectionColour="#ff00ff",this.crossSectionWidth=2,this.crossSectionOpacity=1,this.computeNormals=!1,void 0!==e&&(this.manifoldOrCrossSection=e),void 0!==t&&(this.faceOpacity=t),void 0!==i&&(this.faceMaterial=i),void 0!==r&&(this.faceColour=r),void 0!==s&&(this.crossSectionColour=s),void 0!==n&&(this.crossSectionWidth=n),void 0!==o&&(this.crossSectionOpacity=o),void 0!==a&&(this.computeNormals=a)}},e.DrawManifoldsOrCrossSectionsDto=class{constructor(e,t,i,r,s,n,o,a){this.faceColour="#ff0000",this.faceOpacity=1,this.crossSectionColour="#ff00ff",this.crossSectionWidth=2,this.crossSectionOpacity=1,this.computeNormals=!1,void 0!==e&&(this.manifoldsOrCrossSections=e),void 0!==t&&(this.faceOpacity=t),void 0!==i&&(this.faceMaterial=i),void 0!==r&&(this.faceColour=r),void 0!==s&&(this.crossSectionColour=s),void 0!==n&&(this.crossSectionWidth=n),void 0!==o&&(this.crossSectionOpacity=o),void 0!==a&&(this.computeNormals=a)}},e.CreateFromMeshDto=class{constructor(e){void 0!==e&&(this.mesh=e)}},e.CubeDto=class{constructor(e,t){this.center=!0,this.size=1,void 0!==e&&(this.center=e),void 0!==t&&(this.size=t)}},e.CreateContourSectionDto=class{constructor(e,i){this.fillRule=t.evenOdd,void 0!==e&&(this.polygons=e),void 0!==i&&(this.fillRule=i)}},e.SquareDto=class{constructor(e,t){this.center=!1,this.size=1,void 0!==e&&(this.center=e),void 0!==t&&(this.size=t)}},e.SphereDto=class{constructor(e,t){this.radius=1,void 0!==e&&(this.radius=e),void 0!==t&&(this.circularSegments=t)}},e.CylinderDto=class{constructor(e,t,i,r,s){this.height=1,this.radiusLow=1,this.radiusHigh=1,this.circularSegments=32,this.center=!0,void 0!==e&&(this.height=e),void 0!==t&&(this.radiusLow=t),void 0!==i&&(this.radiusHigh=i),void 0!==r&&(this.circularSegments=r),void 0!==s&&(this.center=s)}},e.CircleDto=class{constructor(e,t){this.radius=1,this.circularSegments=32,void 0!==e&&(this.radius=e),void 0!==t&&(this.circularSegments=t)}},e.RectangleDto=class{constructor(e,t,i){this.length=1,this.height=1,this.center=!1,void 0!==e&&(this.length=e),void 0!==t&&(this.height=t),void 0!==i&&(this.center=i)}},e.ManifoldDto=class{constructor(e){void 0!==e&&(this.manifold=e)}},e.CalculateNormalsDto=class{constructor(e,t,i){this.normalIdx=0,this.minSharpAngle=0,void 0!==e&&(this.manifold=e),void 0!==t&&(this.normalIdx=t),void 0!==i&&(this.minSharpAngle=i)}},e.CalculateCurvatureDto=class{constructor(e){void 0!==e&&(this.manifold=e)}},e.CountDto=class{constructor(e){void 0!==e&&(this.count=e)}},e.ManifoldsMinGapDto=class{constructor(e,t,i){this.searchLength=100,void 0!==e&&(this.manifold1=e),void 0!==t&&(this.manifold2=t),void 0!==i&&(this.searchLength=i)}},e.ManifoldRefineToleranceDto=class{constructor(e,t){this.tolerance=1e-6,void 0!==e&&(this.manifold=e),void 0!==t&&(this.tolerance=t)}},e.ManifoldRefineLengthDto=class{constructor(e,t){this.length=.1,void 0!==e&&(this.manifold=e),void 0!==t&&(this.length=t)}},e.ManifoldRefineDto=class{constructor(e,t){this.number=1,void 0!==e&&(this.manifold=e),void 0!==t&&(this.number=t)}},e.ManifoldSmoothByNormalsDto=class{constructor(e,t){this.normalIdx=0,void 0!==e&&(this.manifold=e),void 0!==t&&(this.normalIdx=t)}},e.ManifoldSmoothOutDto=class{constructor(e,t,i){this.minSharpAngle=60,this.minSmoothness=0,void 0!==e&&(this.manifold=e),void 0!==t&&(this.minSharpAngle=t),void 0!==i&&(this.minSmoothness=i)}},e.HullPointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.SliceDto=class{constructor(e){this.height=.5,void 0!==e&&(this.manifold=e)}},e.MeshDto=class{constructor(e){void 0!==e&&(this.mesh=e)}},e.MeshVertexIndexDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.vertexIndex=t)}},e.MeshTriangleRunIndexDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.triangleRunIndex=t)}},e.MeshHalfEdgeIndexDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.halfEdgeIndex=t)}},e.MeshTriangleIndexDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.triangleIndex=t)}},e.CrossSectionDto=class{constructor(e){void 0!==e&&(this.crossSection=e)}},e.CrossSectionsDto=class{constructor(e){void 0!==e&&(this.crossSections=e)}},e.ExtrudeDto=class{constructor(e){this.height=1,this.nDivisions=1,this.twistDegrees=0,this.scaleTopX=1,this.scaleTopY=1,this.center=!0,void 0!==e&&(this.crossSection=e)}},e.RevolveDto=class{constructor(e,t,i,r){this.matchProfile=!0,this.circularSegments=32,void 0!==e&&(this.crossSection=e),void 0!==t&&(this.revolveDegrees=t),void 0!==i&&(this.matchProfile=i),void 0!==r&&(this.circularSegments=r)}},e.OffsetDto=class{constructor(e,t,r,s,n){this.joinType=i.round,this.miterLimit=2,this.circularSegments=32,void 0!==e&&(this.crossSection=e),void 0!==t&&(this.delta=t),void 0!==r&&(this.joinType=r),void 0!==s&&(this.miterLimit=s),void 0!==n&&(this.circularSegments=n)}},e.SimplifyDto=class{constructor(e,t){this.epsilon=1e-6,void 0!==e&&(this.crossSection=e),void 0!==t&&(this.epsilon=t)}},e.ComposeDto=class{constructor(e){void 0!==e&&(this.polygons=e)}},e.MirrorCrossSectionDto=class{constructor(e,t){this.normal=[1,0],void 0!==e&&(this.crossSection=e),void 0!==t&&(this.normal=t)}},e.Scale2DCrossSectionDto=class{constructor(e,t){this.vector=[2,2],void 0!==e&&(this.crossSection=e),void 0!==t&&(this.vector=t)}},e.TranslateCrossSectionDto=class{constructor(e,t){void 0!==e&&(this.crossSection=e),void 0!==t&&(this.vector=t)}},e.RotateCrossSectionDto=class{constructor(e,t){void 0!==e&&(this.crossSection=e),void 0!==t&&(this.degrees=t)}},e.ScaleCrossSectionDto=class{constructor(e,t){this.factor=2,void 0!==e&&(this.crossSection=e),void 0!==t&&(this.factor=t)}},e.TranslateXYCrossSectionDto=class{constructor(e,t,i){this.x=0,this.y=0,void 0!==e&&(this.crossSection=e),void 0!==t&&(this.x=t),void 0!==i&&(this.y=i)}},e.TransformCrossSectionDto=class{constructor(e,t){void 0!==e&&(this.crossSection=e),void 0!==t&&(this.transform=t)}},e.MirrorDto=class{constructor(e,t){this.normal=[1,0,0],void 0!==e&&(this.manifold=e),void 0!==t&&(this.normal=t)}},e.Scale3DDto=class{constructor(e,t){this.vector=[2,2,2],void 0!==e&&(this.manifold=e),void 0!==t&&(this.vector=t)}},e.TranslateDto=class{constructor(e,t){void 0!==e&&(this.manifold=e),void 0!==t&&(this.vector=t)}},e.TranslateByVectorsDto=class{constructor(e,t){void 0!==e&&(this.manifold=e),void 0!==t&&(this.vectors=t)}},e.RotateDto=class{constructor(e,t){void 0!==e&&(this.manifold=e),void 0!==t&&(this.vector=t)}},e.RotateXYZDto=class{constructor(e,t,i,r){this.x=0,this.y=0,this.z=0,void 0!==e&&(this.manifold=e),void 0!==t&&(this.x=t),void 0!==i&&(this.y=i),void 0!==r&&(this.z=r)}},e.ScaleDto=class{constructor(e,t){this.factor=2,void 0!==e&&(this.manifold=e),void 0!==t&&(this.factor=t)}},e.TranslateXYZDto=class{constructor(e,t,i,r){this.x=0,this.y=0,this.z=0,void 0!==e&&(this.manifold=e),void 0!==t&&(this.x=t),void 0!==i&&(this.y=i),void 0!==r&&(this.z=r)}},e.TransformDto=class{constructor(e,t){void 0!==e&&(this.manifold=e),void 0!==t&&(this.transform=t)}},e.TransformsDto=class{constructor(e,t){void 0!==e&&(this.manifold=e),void 0!==t&&(this.transforms=t)}},e.TwoCrossSectionsDto=class{constructor(e,t){void 0!==e&&(this.crossSection1=e),void 0!==t&&(this.crossSection2=t)}},e.TwoManifoldsDto=class{constructor(e,t){void 0!==e&&(this.manifold1=e),void 0!==t&&(this.manifold2=t)}},e.SplitManifoldsDto=class{constructor(e,t){void 0!==e&&(this.manifoldToSplit=e),void 0!==t&&(this.manifoldCutter=t)}},e.TrimByPlaneDto=class{constructor(e,t,i){this.normal=[1,0,0],this.originOffset=0,void 0!==e&&(this.manifold=e),void 0!==t&&(this.normal=t),void 0!==i&&(this.originOffset=i)}},e.SplitByPlaneDto=class{constructor(e,t,i){this.normal=[1,0,0],this.originOffset=0,void 0!==e&&(this.manifold=e),void 0!==t&&(this.normal=t),void 0!==i&&(this.originOffset=i)}},e.ManifoldsDto=class{constructor(e){void 0!==e&&(this.manifolds=e)}},e.ManifoldToMeshDto=class{constructor(e,t){void 0!==e&&(this.manifold=e),void 0!==t&&(this.normalIdx=t)}},e.ManifoldsToMeshesDto=class{constructor(e,t){void 0!==e&&(this.manifolds=e),void 0!==t&&(this.normalIdx=t)}},e.DecomposeManifoldOrCrossSectionDto=class{constructor(e,t){void 0!==e&&(this.manifoldOrCrossSection=e),void 0!==t&&(this.normalIdx=t)}},e.ManifoldOrCrossSectionDto=class{constructor(e){void 0!==e&&(this.manifoldOrCrossSection=e)}},e.ManifoldsOrCrossSectionsDto=class{constructor(e){void 0!==e&&(this.manifoldsOrCrossSections=e)}},e.DecomposeManifoldsOrCrossSectionsDto=class{constructor(e,t){void 0!==e&&(this.manifoldsOrCrossSections=e),void 0!==t&&(this.normalIdx=t)}}}(oX||(oX={}));class gX{constructor(e){this.context=e}createTextBlock(e){const t=new dB(e.name,e.text);return e.height?t.height=e.height:t.height=1,e.width?t.width=e.width:t.width="42px",e.width?t.width=e.width:t.width=1,e.height?t.height=e.height:t.height="42px",t.fontSize=e.fontSize,t.color=e.color,t}alignText(e){switch(e.horizontalAlignment){case VH.horizontalAlignmentEnum.left:e.control.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_LEFT;break;case VH.horizontalAlignmentEnum.right:e.control.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_RIGHT;break;case VH.horizontalAlignmentEnum.center:e.control.textHorizontalAlignment=lB.HORIZONTAL_ALIGNMENT_CENTER}switch(e.verticalAlignment){case VH.verticalAlignmentEnum.top:e.control.textVerticalAlignment=lB.VERTICAL_ALIGNMENT_TOP;break;case VH.verticalAlignmentEnum.bottom:e.control.textVerticalAlignment=lB.VERTICAL_ALIGNMENT_BOTTOM;break;case VH.verticalAlignmentEnum.center:e.control.textVerticalAlignment=lB.VERTICAL_ALIGNMENT_CENTER}return e.control}setTextOutline(e){return e.textBlock.outlineWidth=e.outlineWidth,e.textBlock.outlineColor=e.outlineColor,e.textBlock}setText(e){return e.textBlock.text=e.text,e.textBlock}setRsizeToFit(e){return e.textBlock.resizeToFit=e.resizeToFit,e.textBlock}setTextWrapping(e){return e.textBlock.textWrapping=e.textWrapping,e.textBlock}setLineSpacing(e){return e.textBlock.lineSpacing=e.lineSpacing,e.textBlock}getText(e){return e.textBlock.text}getTextWrapping(e){return e.textBlock.textWrapping}getLineSpacing(e){return e.textBlock.lineSpacing}getOutlineWidth(e){return e.textBlock.outlineWidth}getResizeToFit(e){return e.textBlock.resizeToFit}getTextHorizontalAlignment(e){return e.textBlock.textHorizontalAlignment}getTextVerticalAlignment(e){return e.textBlock.textVerticalAlignment}createTextBlockObservableSelector(e){return e.selector}}class vX{constructor(e){this.context=e}createRadioButton(e){const t=new RB(e.name);return e.height?t.height=e.height:t.height="32px",e.width?t.width=e.width:t.width="32px",t.checkSizeRatio=e.checkSizeRatio,t.group=e.group,t.color=e.color,t.isChecked=e.isChecked,t.background=e.background,t}setCheckSizeRatio(e){return e.radioButton.checkSizeRatio=e.checkSizeRatio,e.radioButton}setGroup(e){return e.radioButton.group=e.group,e.radioButton}setBackground(e){return e.radioButton.background=e.background,e.radioButton}getCheckSizeRatio(e){return e.radioButton.checkSizeRatio}getGroup(e){return e.radioButton.group}getBackground(e){return e.radioButton.background}createRadioButtonObservableSelector(e){return e.selector}}class xX{constructor(e){this.context=e}createCheckbox(e){const t=new mB(e.name);return e.height?t.height=e.height:t.height="32px",e.width?t.width=e.width:t.width="32px",t.checkSizeRatio=e.checkSizeRatio,t.color=e.color,t.isChecked=e.isChecked,t.background=e.background,t}setBackground(e){return e.checkbox.background=e.background,e.checkbox}setCheckSizeRatio(e){return e.checkbox.checkSizeRatio=e.checkSizeRatio,e.checkbox}setIsChecked(e){return e.checkbox.isChecked=e.isChecked,e.checkbox}getCheckSizeRatio(e){return e.checkbox.checkSizeRatio}getIsChecked(e){return e.checkbox.isChecked}getBackground(e){return e.checkbox.background}createCheckboxObservableSelector(e){return e.selector}}class bX{constructor(e){this.context=e}createInputText(e){const t=new vB(e.name);return e.height?t.height=e.height:t.height="56px",e.width?t.width=e.width:t.width=1,t.text=e.text,t.placeholderText=e.placeholder,t.color=e.color,t.background=e.background,t}setBackground(e){return e.inputText.background=e.background,e.inputText}setText(e){return e.inputText.text=e.text,e.inputText}setPlaceholder(e){return e.inputText.placeholderText=e.placeholder,e.inputText}getBackground(e){return e.inputText.background}getText(e){return e.inputText.text}getPlaceholder(e){return e.inputText.placeholderText}createInputTextObservableSelector(e){return e.selector}}class SX{constructor(e){this.context=e}createColorPicker(e){const t=new bB(e.name);return e.height?t.height=e.height:t.height="300px",e.width?t.width=e.width:t.width="300px",e.size&&(t.size=e.size),e.defaultColor&&(t.value=hc.v9.FromHexString(e.defaultColor)),t.color=e.color,t}setColorPickerValue(e){return e.colorPicker.value=hc.v9.FromHexString(e.color),e.colorPicker}setColorPickerSize(e){return e.colorPicker.size=e.size,e.colorPicker}getColorPickerValue(e){return e.colorPicker.value.toHexString()}getColorPickerSize(e){return e.colorPicker.size}createColorPickerObservableSelector(e){return e.selector}}class TX{constructor(e){this.context=e}createImage(e){const t=new fB(e.name,e.url);return e.width?t.width=e.width:t.width="200px",e.height?t.height=e.height:t.height="200px",t.color=e.color,t}setSourceUrl(e){return e.image.source=e.url,e.image}getSourceUrl(e){return e.image.source}}class CX{constructor(e){this.context=e,this.advancedDynamicTexture=new uX(e),this.control=new _X(e),this.container=new fX(e),this.stackPanel=new dX(e),this.button=new pX(e),this.slider=new mX(e),this.textBlock=new gX(e),this.radioButton=new vX(e),this.checkbox=new xX(e),this.inputText=new bX(e),this.colorPicker=new SX(e),this.image=new TX(e)}}class yX{constructor(e){this.context=e}dispose(e){e.babylonMesh&&(e.babylonMesh.getScene().removeMesh(e.babylonMesh,!0),e.babylonMesh.dispose())}updateDrawn(e){const t=e.babylonMesh.metadata.type;e.babylonMesh.position=new hc.Pq(e.position[0],e.position[1],e.position[2]),e.babylonMesh.rotation=new hc.Pq(e.rotation[0],e.rotation[1],e.rotation[2]),e.babylonMesh.scaling=new hc.Pq(e.scaling[0],e.scaling[1],e.scaling[2]);const i=Array.isArray(e.colours);let r;if(e.babylonMesh.getChildMeshes&&(r=e.babylonMesh.getChildMeshes()),r&&r.length>0)i&&e.colours.length===r.length?r.forEach(((t,i)=>{const r=hc.v9.FromHexString(e.colours[i]);this.assignColorToMesh(t,r)})):i?r.forEach((t=>{const i=hc.v9.FromHexString(e.colours[0]);this.assignColorToMesh(t,i)})):r.forEach((t=>{const i=hc.v9.FromHexString(e.colours);this.assignColorToMesh(t,i)}));else{const t=i?hc.v9.FromHexString(e.colours[0]):hc.v9.FromHexString(e.colours);this.assignColorToMesh(e.babylonMesh,t)}if(null!==e.babylonMesh.edgesRenderer){const t=i?hc.v9.FromHexString(e.colours[0]):hc.v9.FromHexString(e.colours);e.babylonMesh.edgesColor=hc.ov.FromColor3(t)}if([QH.drawingTypes.point,QH.drawingTypes.points,QH.drawingTypes.line,QH.drawingTypes.lines,QH.drawingTypes.polyline,QH.drawingTypes.polylines].includes(t)){const t=e.babylonMesh.getVerticesData(st.R.ColorKind).length/4,r=[];if(i&&t===e.colours.length)for(let i=0;i{t.visibility=e.visibility}))}hide(e){e.babylonMesh.isVisible=!1,e.includeChildren&&e.babylonMesh.getChildMeshes&&e.babylonMesh.getChildMeshes().forEach((e=>{e.isVisible=!1}))}show(e){e.babylonMesh.isVisible=!0,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((e=>{e.isVisible=!0}))}setParent(e){e.babylonMesh.parent=e.parentMesh}getParent(e){return e.babylonMesh.parent}setCheckCollisions(e){e.babylonMesh.checkCollisions=e.checkCollisions,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((t=>{t.checkCollisions=e.checkCollisions}))}getCheckCollisions(e){return e.babylonMesh.checkCollisions}setPickable(e){e.babylonMesh.isPickable=e.pickable,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((t=>{t.isPickable=e.pickable}))}enablePointerMoveEvents(e){e.babylonMesh.enablePointerMoveEvents=!0,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((e=>{e.enablePointerMoveEvents=!1}))}disablePointerMoveEvents(e){e.babylonMesh.enablePointerMoveEvents=!1,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((e=>{e.enablePointerMoveEvents=!1}))}getPickable(e){return e.babylonMesh.isPickable}getMeshesWhereNameContains(e){return this.context.scene.meshes.filter((t=>t.name.includes(e.name)))}getChildMeshes(e){return e.babylonMesh.getChildMeshes(e.directDescendantsOnly)}getMeshesOfId(e){return this.context.scene.getMeshesById(e.id)}getMeshOfId(e){return this.context.scene.getMeshById(e.id)}getMeshOfUniqueId(e){return this.context.scene.getMeshByUniqueId(e.uniqueId)}mergeMeshes(e){return Yt.MergeMeshes(e.arrayOfMeshes,e.disposeSource,e.allow32BitsIndices,e.meshSubclass,e.subdivideWithSubMeshes,e.multiMultiMaterials)}convertToFlatShadedMesh(e){return e.babylonMesh.convertToFlatShadedMesh()}clone(e){var t,i;const r=e.babylonMesh.clone();if(!e.babylonMesh.metadata||e.babylonMesh.metadata&&!1!==e.babylonMesh.metadata.shadows){const e=null===(i=null===(t=this.context.scene)||void 0===t?void 0:t.metadata)||void 0===i?void 0:i.shadowGenerators;e.length>0&&(r.getChildMeshes().forEach((t=>{t.receiveShadows=!0,e.forEach((e=>e.addShadowCaster(t)))})),r.receiveShadows=!0,e.forEach((e=>e.addShadowCaster(r))))}return r.metadata=Object.assign({},e.babylonMesh.metadata),r}cloneToPositions(e){const t=[];return e.positions.forEach((i=>{const r=e.babylonMesh.clone();r.position=new hc.Pq(i[0],i[1],i[2]),t.push(r)})),t}setId(e){e.babylonMesh.id=e.id}getId(e){return e.babylonMesh.id}getUniqueId(e){return e.babylonMesh.uniqueId}setName(e){e.babylonMesh.name=e.name,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((t=>{t.name=e.name}))}getVerticesAsPolygonPoints(e){const t=e.babylonMesh.getVerticesData(st.R.PositionKind),i=e.babylonMesh.getIndices(),r=[];for(let e=0;e{t.material=e.material}))}getMaterial(e){return e.babylonMesh.material}getPosition(e){const t=e.babylonMesh;return[t.position.x,t.position.y,t.position.z]}getAbsolutePosition(e){const t=e.babylonMesh;return[t.absolutePosition.x,t.absolutePosition.y,t.absolutePosition.z]}getRotation(e){const t=e.babylonMesh;return[t.rotation.x,t.rotation.y,t.rotation.z]}getScale(e){const t=e.babylonMesh;return[t.scaling.x,t.scaling.y,t.scaling.z]}moveForward(e){const t=e.babylonMesh;t.translate(t.forward,e.distance,hc.$x.WORLD)}moveBackward(e){const t=e.babylonMesh;t.translate(t.forward.negate(),e.distance,hc.$x.WORLD)}moveUp(e){const t=e.babylonMesh;t.translate(t.up,e.distance,hc.$x.WORLD)}moveDown(e){const t=e.babylonMesh;t.translate(t.up.negate(),e.distance,hc.$x.WORLD)}moveRight(e){const t=e.babylonMesh;t.translate(t.right,e.distance,hc.$x.WORLD)}moveLeft(e){const t=e.babylonMesh;t.translate(t.right.negate(),e.distance,hc.$x.WORLD)}yaw(e){const t=e.babylonMesh,i=hc.uM.FromDegrees(e.rotate).radians();t.rotate(hc._0.Y,i,hc.$x.LOCAL)}pitch(e){const t=e.babylonMesh,i=hc.uM.FromDegrees(e.rotate).radians();t.rotate(hc._0.X,i,hc.$x.LOCAL)}roll(e){const t=e.babylonMesh,i=hc.uM.FromDegrees(e.rotate).radians();t.rotate(hc._0.Z,i,hc.$x.LOCAL)}rotateAroundAxisWithPosition(e){e.mesh.rotateAround(new hc.Pq(e.position[0],e.position[1],e.position[2]),new hc.Pq(e.axis[0],e.axis[1],e.axis[2]),hc.uM.FromDegrees(e.angle).radians())}setPosition(e){e.babylonMesh.position=new hc.Pq(e.position[0],e.position[1],e.position[2])}setRotation(e){const t=hc.uM.FromDegrees(e.rotation[0]).radians(),i=hc.uM.FromDegrees(e.rotation[1]).radians(),r=hc.uM.FromDegrees(e.rotation[2]).radians();e.babylonMesh.rotation=new hc.Pq(t,i,r)}setScale(e){e.babylonMesh.scaling=new hc.Pq(e.scale[0],e.scale[1],e.scale[2])}intersectsMesh(e){return e.babylonMesh.intersectsMesh(e.babylonMesh2,e.precise,e.includeDescendants)}intersectsPoint(e){const t=new hc.Pq(e.point[0],e.point[1],e.point[2]);return e.babylonMesh.intersectsPoint(t)}createMeshInstanceAndTransformNoReturn(e){this.createMeshInstanceAndTransform(e)}createMeshInstanceAndTransform(e){var t,i;const r=new Yt("instanceContainer"+Math.random(),this.context.scene),s=null===(i=null===(t=this.context.scene)||void 0===t?void 0:t.metadata)||void 0===i?void 0:i.shadowGenerators;if(e.mesh&&e.mesh.getChildMeshes&&e.mesh.getChildMeshes().length>0)e.mesh.getChildMeshes(!1).forEach((t=>{const i=t.getTotalVertices();if(t.createInstance&&i>0){t.disableEdgesRendering();const i=t.createInstance(`InstanceMesh${Math.random()}`);i.position=new hc.Pq(e.position[0],e.position[1],e.position[2]),i.rotation=new hc.Pq(e.rotation[0],e.rotation[1],e.rotation[2]),i.scaling=new hc.Pq(e.scaling[0],e.scaling[1],e.scaling[2]),(!e.mesh.metadata||e.mesh.metadata&&!1!==e.mesh.metadata.shadows)&&s.length>0&&(s.forEach((e=>{e.addShadowCaster(i)})),i.receiveShadows=!0),r.metadata=e.mesh.metadata,i.parent=r}})),e.mesh.isVisible=!1;else if(e.mesh){e.mesh.isVisible=!1;const t=e.mesh.createInstance(`InstanceMesh${Math.random()}`);t.position=new hc.Pq(e.position[0],e.position[1],e.position[2]),t.rotation=new hc.Pq(hc.uM.FromDegrees(e.rotation[0]).radians(),hc.uM.FromDegrees(e.rotation[1]).radians(),hc.uM.FromDegrees(e.rotation[2]).radians()),t.scaling=new hc.Pq(e.scaling[0],e.scaling[1],e.scaling[2]),t.parent=r,(!e.mesh.metadata||e.mesh.metadata&&!1!==e.mesh.metadata.shadows)&&(s.length>0&&s.forEach((e=>{e.addShadowCaster(t)})),t.receiveShadows=!0),t.metadata=e.mesh.metadata}return r}createMeshInstance(e){let t;if(e.mesh&&e.mesh.getChildMeshes&&e.mesh.getChildMeshes().length>0){e.mesh.setParent(null);const i=new Yt("meshCloneContainer"+Math.random());e.mesh.getChildMeshes(!1).forEach((e=>{e.createInstance&&e.getTotalVertices()>0&&e.getTotalIndices()>0&&(e.createInstance(`InstanceMesh${Math.random()}`).parent=i)})),t=i;const r=this.context.scene.metadata.shadowGenerators;(!e.mesh.metadata||e.mesh.metadata&&!1!==e.mesh.metadata.shadows)&&r.length>0&&(t.getChildMeshes().forEach((e=>{r.forEach((t=>t.addShadowCaster(e))),e.receiveShadows=!0})),r.forEach((e=>e.addShadowCaster(t))),t.receiveShadows=!0)}else if(e.mesh&&(e.mesh.setParent(null),e.mesh.getTotalVertices()>0)){const i=new Yt("meshCloneContainer"+Math.random());e.mesh.createInstance(`InstanceMesh${Math.random()}`).parent=i,t=i}return t}getSideOrientation(e){switch(e){case UH.sideOrientationEnum.frontside:return Yt.FRONTSIDE;case UH.sideOrientationEnum.backside:return Yt.BACKSIDE;case UH.sideOrientationEnum.doubleside:return Yt.DOUBLESIDE;default:return Yt.FRONTSIDE}}assignColorToMesh(e,t){const i=e.material;i instanceof Cb?i.baseColor=t:i instanceof Un&&(i.diffuseColor=t)}}var EX=i(66570);class PX{constructor(e,t){this.context=e,this.mesh=t}createBox(e){const t=bl.CreateBox("BabylonMesh"+Math.random(),{width:e.width,height:e.height,depth:e.depth,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createCube(e){const t=bl.CreateBox("BabylonMesh"+Math.random(),{size:e.size,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createSquarePlane(e){const t=bl.CreatePlane("BabylonMesh"+Math.random(),{size:e.size,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createSphere(e){const t=bl.CreateSphere("BabylonMesh"+Math.random(),{diameter:e.diameter,segments:e.segments,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createIcoSphere(e){const t=bl.CreateIcoSphere("BabylonMesh"+Math.random(),{radius:e.radius,radiusX:e.radiusX,radiusY:e.radiusY,radiusZ:e.radiusZ,flat:e.flat,subdivisions:e.subdivisions,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createDisc(e){const t=bl.CreateDisc("BabylonMesh"+Math.random(),{radius:e.radius,tessellation:e.tessellation,arc:e.arc,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createTorus(e){const t=bl.CreateTorus("BabylonMesh"+Math.random(),{diameter:e.diameter,thickness:e.thickness,tessellation:e.tessellation,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createTorusKnot(e){const t=bl.CreateTorusKnot("BabylonMesh"+Math.random(),{radius:e.radius,tube:e.tube,radialSegments:e.radialSegments,tubularSegments:e.tubularSegments,p:e.p,q:e.q,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createPolygon(e){var t;const i=bl.CreatePolygon("BabylonMesh"+Math.random(),{shape:e.shape.map((e=>new hc.Pq(e[0],e[1],e[2]))),holes:null===(t=e.holes)||void 0===t?void 0:t.map((e=>e.map((e=>new hc.Pq(e[0],e[1],e[2]))))),depth:e.depth,smoothingThreshold:e.smoothingThreshold,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation),wrap:e.wrap},this.context.scene,EX);return e.enableShadows?this.enableShadows(i):i.metadata={shadows:!1},i}extrudePolygon(e){var t;console.log(EX);const i=bl.ExtrudePolygon("BabylonMesh"+Math.random(),{shape:e.shape.map((e=>new hc.Pq(e[0],e[1],e[2]))),holes:null===(t=e.holes)||void 0===t?void 0:t.map((e=>e.map((e=>new hc.Pq(e[0],e[1],e[2]))))),depth:e.depth,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation),wrap:e.wrap},this.context.scene,EX);return e.enableShadows?this.enableShadows(i):i.metadata={shadows:!1},i}createTube(e){const t=e.path.map((e=>new hc.Pq(e[0],e[1],e[2]))),i=bl.CreateTube("BabylonMesh"+Math.random(),{path:t,radius:e.radius,tessellation:e.tessellation,cap:e.cap,arc:e.arc,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(i):i.metadata={shadows:!1},i}createPolyhedron(e){const t=bl.CreatePolyhedron("BabylonMesh"+Math.random(),{type:e.type,size:e.size,sizeX:e.sizeX,sizeY:e.sizeY,sizeZ:e.sizeZ,custom:e.custom,flat:e.flat,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createGeodesic(e){const t=bl.CreateGeodesic("BabylonMesh"+Math.random(),{m:e.m,n:e.n,size:e.size,sizeX:e.sizeX,sizeY:e.sizeY,sizeZ:e.sizeZ,flat:e.flat,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createGoldberg(e){const t=bl.CreateGoldberg("BabylonMesh"+Math.random(),{n:e.n,m:e.m,size:e.size,sizeX:e.sizeX,sizeY:e.sizeY,sizeZ:e.sizeZ,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createCapsule(e){const t=bl.CreateCapsule("BabylonMesh"+Math.random(),{orientation:new hc.Pq(...e.orientation),subdivisions:e.subdivisions,tessellation:e.tessellation,height:e.height,radius:e.radius,capSubdivisions:e.capSubdivisions,radiusTop:e.radiusTop,radiusBottom:e.radiusBottom,topCapSubdivisions:e.topCapSubdivisions,bottomCapSubdivisions:e.bottomCapSubdivisions},this.context.scene);return t.sideOrientation=this.mesh.getSideOrientation(e.sideOrientation),e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createCylinder(e){const t=bl.CreateCylinder("BabylonMesh"+Math.random(),{height:e.height,diameterTop:e.diameterTop,diameterBottom:e.diameterBottom,tessellation:e.tessellation,subdivisions:e.subdivisions,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createExtrudedSahpe(e){const t=e.shape.map((e=>new hc.Pq(e[0],e[1],e[2]))),i=e.path.map((e=>new hc.Pq(e[0],e[1],e[2]))),r=bl.ExtrudeShape("BabylonMesh"+Math.random(),{shape:t,path:i,scale:e.scale,rotation:e.rotation,closeShape:e.closeShape,closePath:e.closePath,cap:e.cap,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(r):r.metadata={shadows:!1},r}createRibbon(e){const t=e.pathArray.map((e=>e.map((e=>new hc.Pq(e[0],e[1],e[2]))))),i=bl.CreateRibbon("BabylonMesh"+Math.random(),{pathArray:t,closeArray:e.closeArray,closePath:e.closePath,offset:e.offset,updatable:e.updatable,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(i):i.metadata={shadows:!1},i}createLathe(e){const t=e.shape.map((e=>new hc.Pq(e[0],e[1],e[2]))),i=bl.CreateLathe("BabylonMesh"+Math.random(),{shape:t,radius:e.radius,tessellation:e.tessellation,arc:e.arc,closed:e.closed,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(i):i.metadata={shadows:!1},i}createGround(e){const t=bl.CreateGround("BabylonMesh"+Math.random(),{width:e.width,height:e.height,subdivisionsX:e.subdivisionsX,subdivisionsY:e.subdivisionsY},this.context.scene);return t.sideOrientation=this.mesh.getSideOrientation(e.sideOrientation),e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}createRectanglePlane(e){const t=bl.CreatePlane("BabylonMesh"+Math.random(),{width:e.width,height:e.height,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return e.enableShadows?this.enableShadows(t):t.metadata={shadows:!1},t}enableShadows(e){this.context.scene.metadata.shadowGenerators&&(e.receiveShadows=!0,this.context.scene.metadata.shadowGenerators.forEach((t=>{t.addShadowCaster(e)})))}}class AX{constructor(e,t){this.context=e,this.drawHelper=t}drawNode(e){this.drawHelper.localAxes(e.size,this.context.scene,e.colorX,e.colorY,e.colorZ).parent=e.node}drawNodes(e){e.nodes.forEach((t=>{this.drawHelper.localAxes(e.size,this.context.scene,e.colorX,e.colorY,e.colorZ).parent=t}))}createNodeFromRotation(e){const t=new Pt(`node${Math.random()}`,this.context.scene);return e.parent&&(t.parent=e.parent),t.position=new hc.Pq(e.origin[0],e.origin[1],e.origin[2]),t.rotation=new hc.Pq(hc.uM.FromDegrees(e.rotation[0]).radians(),hc.uM.FromDegrees(e.rotation[1]).radians(),hc.uM.FromDegrees(e.rotation[2]).radians()),t}createWorldNode(){const e=new Pt(`root${Math.random()}`,this.context.scene);return e.parent=this.context.scene.getTransformNodeByID("root"),e}getAbsoluteForwardVector(e){const t=e.node.forward;return[t.x,t.y,t.z]}getAbsoluteRightVector(e){const t=e.node.right;return[t.x,t.y,t.z]}getAbsoluteUpVector(e){const t=e.node.up;return[t.x,t.y,t.z]}getAbsolutePosition(e){const t=e.node.getAbsolutePosition();return[t.x,t.y,t.z]}getAbsoluteRotationTransformation(e){const t=new hc.uq;return e.node.absoluteRotationQuaternion.toRotationMatrix(t),[...t.toArray()]}getRotationTransformation(e){const t=new hc.uq;return e.node.rotationQuaternion.toRotationMatrix(t),[...t.toArray()]}getChildren(e){return e.node.getChildren()}getParent(e){return e.node.parent}getPositionExpressedInLocalSpace(e){const t=e.node.getPositionExpressedInLocalSpace();return[t.x,t.y,t.z]}getRootNode(){return this.context.scene.getTransformNodeByID("root")}getRotation(e){const t=e.node.rotation;return[hc.uM.FromRadians(t.x).degrees(),hc.uM.FromRadians(t.y).degrees(),hc.uM.FromRadians(t.z).degrees()]}rotateAroundAxisWithPosition(e){e.node.rotateAround(new hc.Pq(e.position[0],e.position[1],e.position[2]),new hc.Pq(e.axis[0],e.axis[1],e.axis[2]),hc.uM.FromDegrees(e.angle).radians())}rotate(e){e.node.rotate(new hc.Pq(e.axis[0],e.axis[1],e.axis[2]),hc.uM.FromDegrees(e.angle).radians())}setAbsolutePosition(e){e.node.setAbsolutePosition(new hc.Pq(e.position[0],e.position[1],e.position[2]))}setDirection(e){e.node.setDirection(new hc.Pq(e.direction[0],e.direction[1],e.direction[2]))}setParent(e){e.node.setParent(e.parentNode)}translate(e){e.node.translate(new hc.Pq(e.direction[0],e.direction[1],e.direction[2]),e.distance)}}class RX{constructor(e){this.context=e}pickWithRay(e){return this.context.scene.pickWithRay(e.ray)}pickWithPickingRay(){const e=this.context.scene,t=e.createPickingRay(e.pointerX,e.pointerY,hc.uq.Identity(),this.context.scene.activeCamera,!1);return e.pickWithRay(t)}getDistance(e){return e.pickInfo.distance}getPickedMesh(e){return e.pickInfo.pickedMesh}getPickedPoint(e){const t=e.pickInfo.pickedPoint;return[t.x,t.y,t.z]}hit(e){return e.pickInfo.hit}getSubMeshId(e){return e.pickInfo.subMeshId}getSubMeshFaceId(e){return e.pickInfo.subMeshFaceId}getBU(e){return e.pickInfo.bu}getBV(e){return e.pickInfo.bv}getPickedSprite(e){return e.pickInfo.pickedSprite}}class IX{constructor(e){this.context=e}createPickingRay(){const e=this.context.scene;return e.createPickingRay(e.pointerX,e.pointerY,hc.uq.Identity(),this.context.scene.activeCamera,!1)}createRay(e){const t=new hc.Pq(e.origin[0],e.origin[1],e.origin[2]),i=new hc.Pq(e.direction[0],e.direction[1],e.direction[2]);let r;return 0!==e.length&&(r=e.length),new wi(t,i,r)}createRayFromTo(e){const t=new hc.Pq(e.from[0],e.from[1],e.from[2]),i=new hc.Pq(e.to[0],e.to[1],e.to[2]);return wi.CreateNewFromTo(t,i)}getOrigin(e){const t=e.ray.origin;return[t.x,t.y,t.z]}getDirection(e){const t=e.ray.direction;return[t.x,t.y,t.z]}getLength(e){return e.ray.length}}class MX{constructor(e){this.context=e}getScene(){return this.context.scene}setAndAttachScene(e){return e.scene.metadata={shadowGenerators:[]},new Pt("root",this.context.scene),this.context.scene=e.scene}backgroundColour(e){this.context.scene.clearColor=hc.ov.FromColor3(hc.v9.FromHexString(e.colour))}activateCamera(e){this.context.scene.activeCamera.detachControl(),this.context.scene.activeCamera=e.camera}useRightHandedSystem(e){this.context.scene.useRightHandedSystem=e.use,this.context.scene.activeCamera.getViewMatrix(!0),this.context.scene.activeCamera.getProjectionMatrix(!0)}drawPointLightNoReturn(e){this.drawPointLight(e)}getShadowGenerators(){return this.context.scene.metadata&&this.context.scene.metadata.shadowGenerators?this.context.scene.metadata.shadowGenerators:[]}drawPointLight(e){const t=new hc.Pq(e.position[0],e.position[1],e.position[2]),i=new wx(`pointLight${Math.random()}`,t,this.context.scene);if(e.enableShadows){i.shadowEnabled=!0;const t=new ux(e.shadowGeneratorMapSize,i);t.darkness=e.shadowDarkness,t.usePercentageCloserFiltering=e.shadowUsePercentageCloserFiltering,t.contactHardeningLightSizeUVRatio=e.shadowContactHardeningLightSizeUVRatio,t.bias=e.shadowBias,t.normalBias=e.shadowNormalBias,i.shadowMaxZ=e.shadowMaxZ,i.shadowMinZ=e.shadowMinZ,this.context.scene.metadata.shadowGenerators.push(t),this.context.scene.meshes.forEach((e=>{"bitbybit-hdrSkyBox"===e.name||e.name.includes("bitbybit-ground")||e.metadata&&(!e.metadata||!1===e.metadata.shadows)||(t.addShadowCaster(e,!0),e.receiveShadows=!0)}))}if(i.diffuse=hc.v9.FromHexString(e.diffuse),i.specular=hc.v9.FromHexString(e.specular),i.intensityMode=$t.INTENSITYMODE_LUMINOUSPOWER,i.intensity=e.intensity,e.radius>0){const t=bl.CreateSphere(`PointLightSphere${Math.random()}`,{diameter:2*e.radius},this.context.scene),r=new Un(`LightMaterial${Math.random()}`,this.context.scene);r.diffuseColor=i.diffuse,r.specularColor=i.diffuse,r.emissiveColor=i.diffuse,t.material=r,t.parent=i}return i}drawDirectionalLightNoReturn(e){this.drawDirectionalLight(e)}drawDirectionalLight(e){const t=new hc.Pq(e.direction[0],e.direction[1],e.direction[2]),i=new hm(`directionalLight${Math.random()}`,t,this.context.scene);if(e.enableShadows){i.shadowEnabled=!0;const t=new ux(e.shadowGeneratorMapSize,i);t.darkness=e.shadowDarkness,t.usePercentageCloserFiltering=e.shadowUsePercentageCloserFiltering,t.contactHardeningLightSizeUVRatio=e.shadowContactHardeningLightSizeUVRatio,t.bias=e.shadowBias,t.normalBias=e.shadowNormalBias,i.shadowMaxZ=e.shadowMaxZ,i.shadowMinZ=e.shadowMinZ,this.context.scene.metadata.shadowGenerators.push(t),this.context.scene.meshes.forEach((e=>{"bitbybit-hdrSkyBox"===e.name||e.name.includes("bitbybit-ground")||e.metadata&&(!e.metadata||!1===e.metadata.shadows)||(t.addShadowCaster(e,!0),e.receiveShadows=!0)}))}return i.diffuse=hc.v9.FromHexString(e.diffuse),i.specular=hc.v9.FromHexString(e.specular),i.intensity=e.intensity,i.shadowMaxZ=e.shadowMaxZ,i}getActiveCamera(){return this.context.scene.activeCamera}adjustActiveArcRotateCamera(e){const t=this.context.scene.getCameraByName("Camera");t.position=new hc.Pq(e.position[0],e.position[1],e.position[2]),t.target=new hc.Pq(e.lookAt[0],e.lookAt[1],e.lookAt[2]);const i=hc.Pq.Distance(t.position,t.target);t.radius=i,void 0!==e.lowerRadiusLimit&&(t.lowerRadiusLimit=e.lowerRadiusLimit),void 0!==e.upperRadiusLimit&&(t.upperRadiusLimit=e.upperRadiusLimit),void 0!==e.lowerAlphaLimit&&(t.lowerAlphaLimit=this.getRadians(e.lowerAlphaLimit)),void 0!==e.upperAlphaLimit&&(t.upperAlphaLimit=this.getRadians(e.upperAlphaLimit)),void 0!==e.lowerBetaLimit&&(t.lowerBetaLimit=this.getRadians(e.lowerBetaLimit)),void 0!==e.upperBetaLimit&&(t.upperBetaLimit=this.getRadians(e.upperBetaLimit)),void 0!==e.angularSensibilityX&&(t.angularSensibilityX=e.angularSensibilityX),void 0!==e.angularSensibilityY&&(t.angularSensibilityY=e.angularSensibilityY),void 0!==e.panningSensibility&&(t.panningSensibility=e.panningSensibility),void 0!==e.wheelPrecision&&(t.wheelPrecision=e.wheelPrecision),void 0!==e.maxZ&&(t.maxZ=e.maxZ)}clearAllDrawn(){const e=this.context.scene;if(e&&(e.environmentTexture&&e.environmentTexture.dispose(),e.environmentTexture=null,e.fogMode=oi.Z.FOGMODE_NONE,e.meshes.forEach((e=>e.dispose())),e.meshes=[],e.materials.forEach((e=>e.dispose())),e.textures.forEach((e=>e.dispose())),e.materials=[],e.textures=[],e.useRightHandedSystem=!1,e.geometries.forEach((e=>{e.meshes&&e.meshes.forEach((e=>e.dispose())),e.dispose&&e.dispose()})),e.geometries=[],e.lights.forEach((e=>{"HemiLight"!==e.name&&e.dispose()})),e.lights=e.lights.filter((e=>"HemiLight"===e.name)),e.transformNodes&&e.transformNodes.forEach((e=>{e&&"root"!==e.name&&e.dispose()})),e.metadata&&(e.metadata.shadowGenerators.length>0&&(e.metadata.shadowGenerators.forEach((e=>e.dispose())),e.metadata.shadowGenerators=[]),e.metadata.xr&&e.metadata.xr.dispose(),e.metadata.guiManager&&e.metadata.guiManager.dispose()),e.transformNodes=[e.getTransformNodeByName("root")],e.activeCamera&&"Camera"!==e.activeCamera.name)){e.cameras.forEach((e=>e.dispose()));const t=new is("Camera",0,10,10,new hc.Pq(0,0,0),e);t.lowerRadiusLimit=0,e.setActiveCameraByName(t.name),t.setPosition(new hc.Pq(0,10,20));const i=document.getElementById("renderCanvas");t.attachControl(i,!0),t.minZ=0}}enableSkybox(e){let t;e.skybox===Kz.skyboxEnum.default?t=new gm("https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.19.0-alpha.0/textures/skybox/default_skybox/skybox",this.context.scene):e.skybox===Kz.skyboxEnum.greyGradient?t=new gm("https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.19.0-alpha.0/textures/skybox/grey_gradient/skybox",this.context.scene):e.skybox===Kz.skyboxEnum.clearSky?t=gm.CreateFromPrefilteredData("https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.19.0-alpha.0/textures/skybox/clear_sky/environment.env",this.context.scene,!1,!1):e.skybox===Kz.skyboxEnum.city&&(t=gm.CreateFromPrefilteredData("https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.19.0-alpha.0/textures/skybox/city/environmentSpecular.env",this.context.scene,!1,!1)),this.context.scene.createDefaultSkybox(t,!0,e.size,e.blur,!0).name="bitbybit-hdrSkyBox",this.context.scene.environmentIntensity=e.environmentIntensity}onPointerDown(e){this.context.scene.onPointerDown=e.statement_update}onPointerUp(e){this.context.scene.onPointerUp=e.statement_update}onPointerMove(e){this.context.scene.onPointerMove=e.statement_update}fog(e){switch(e.mode){case KH.fogModeEnum.none:this.context.scene.fogMode=0;break;case KH.fogModeEnum.exponential:this.context.scene.fogMode=1;break;case KH.fogModeEnum.exponentialSquared:this.context.scene.fogMode=2;break;case KH.fogModeEnum.linear:this.context.scene.fogMode=3}this.context.scene.fogDensity=e.density,this.context.scene.fogStart=e.start,this.context.scene.fogEnd=e.end,this.context.scene.fogColor=hc.v9.FromHexString(e.color)}enablePhysics(e){this.context.scene.enablePhysics(new hc.Pq(e.vector[0],e.vector[1],e.vector[2]),this.context.havokPlugin)}getRadians(e){let t=hc.uM.FromDegrees(e).radians();return e<0&&(t=-t),t}}class OX{constructor(e){this.context=e}createSimple(e){const t=new vi.g(e.url,this.context.scene,void 0,e.invertY,this.context.getSamplingMode(e.samplingMode));return t.uScale=e.uScale,t.vScale=e.vScale,t.wAng=e.wAng,t.invertZ=e.invertZ,t.uOffset=e.uOffset,t.vOffset=e.vOffset,t}}var DX=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class wX{constructor(e){this.context=e}createScreenshot(e){return DX(this,void 0,void 0,(function*(){const t=e.camera?e.camera:this.context.scene.activeCamera;return Ue.S0.CreateScreenshotAsync(this.context.engine,t,{width:e.width,height:e.height},e.mimeType,e.quality)}))}createScreenshotAndDownload(e){return DX(this,void 0,void 0,(function*(){return new Promise(((t,i)=>{const r=e.camera?e.camera:this.context.scene.activeCamera;return Ue.S0.CreateScreenshot(this.context.engine,r,{width:e.width,height:e.height},(()=>{t("done")}),e.mimeType,!0,e.quality)}))}))}}class NX{rotationCenterAxis(e){return[[...hc.uq.Translation(-e.center[0],-e.center[1],-e.center[2]).asArray()],[...hc.uq.RotationAxis(new hc.Pq(e.axis[0],e.axis[1],e.axis[2]),hc.uM.FromDegrees(e.angle).radians()).asArray()],[...hc.uq.Translation(e.center[0],e.center[1],e.center[2]).asArray()]]}rotationCenterX(e){return[[...hc.uq.Translation(-e.center[0],-e.center[1],-e.center[2]).asArray()],[...hc.uq.RotationX(hc.uM.FromDegrees(e.angle).radians()).asArray()],[...hc.uq.Translation(e.center[0],e.center[1],e.center[2]).asArray()]]}rotationCenterY(e){return[[...hc.uq.Translation(-e.center[0],-e.center[1],-e.center[2]).asArray()],[...hc.uq.RotationY(hc.uM.FromDegrees(e.angle).radians()).asArray()],[...hc.uq.Translation(e.center[0],e.center[1],e.center[2]).asArray()]]}rotationCenterZ(e){return[[...hc.uq.Translation(-e.center[0],-e.center[1],-e.center[2]).asArray()],[...hc.uq.RotationZ(hc.uM.FromDegrees(e.angle).radians()).asArray()],[...hc.uq.Translation(e.center[0],e.center[1],e.center[2]).asArray()]]}rotationCenterYawPitchRoll(e){return[[...hc.uq.Translation(-e.center[0],-e.center[1],-e.center[2]).asArray()],[...hc.uq.RotationYawPitchRoll(hc.uM.FromDegrees(e.yaw).radians(),hc.uM.FromDegrees(e.pitch).radians(),hc.uM.FromDegrees(e.roll).radians()).asArray()],[...hc.uq.Translation(e.center[0],e.center[1],e.center[2]).asArray()]]}scaleCenterXYZ(e){return[[...hc.uq.Translation(-e.center[0],-e.center[1],-e.center[2]).asArray()],[...hc.uq.Scaling(e.scaleXyz[0],e.scaleXyz[1],e.scaleXyz[2]).asArray()],[...hc.uq.Translation(e.center[0],e.center[1],e.center[2]).asArray()]]}scaleXYZ(e){return[[...hc.uq.Scaling(e.scaleXyz[0],e.scaleXyz[1],e.scaleXyz[2]).asArray()]]}uniformScale(e){return[[...hc.uq.Scaling(e.scale,e.scale,e.scale).asArray()]]}uniformScaleFromCenter(e){return[[...hc.uq.Translation(-e.center[0],-e.center[1],-e.center[2]).asArray()],[...hc.uq.Scaling(e.scale,e.scale,e.scale).asArray()],[...hc.uq.Translation(e.center[0],e.center[1],e.center[2]).asArray()]]}translationXYZ(e){return[[...hc.uq.Translation(e.translation[0],e.translation[1],e.translation[2]).asArray()]]}translationsXYZ(e){return e.translations.map((e=>[[...hc.uq.Translation(e[0],e[1],e[2]).asArray()]]))}}class FX{constructor(e){this.context=e}createGizmoManager(e){const t=new am(this.context.scene);return t.positionGizmoEnabled=e.positionGizmoEnabled,t.rotationGizmoEnabled=e.rotationGizmoEnabled,t.scaleGizmoEnabled=e.scaleGizmoEnabled,t.boundingBoxGizmoEnabled=e.boundingBoxGizmoEnabled,e.attachableMeshes&&e.attachableMeshes.length>0&&(t.attachableMeshes=e.attachableMeshes),t.clearGizmoOnEmptyPointerEvent=e.clearGizmoOnEmptyPointerEvent,t.scaleRatio=e.scaleRatio,t.usePointerToAttachGizmos=e.usePointerToAttachGizmos,t}getPositionGizmo(e){return e.gizmoManager.gizmos.positionGizmo}getRotationGizmo(e){return e.gizmoManager.gizmos.rotationGizmo}getScaleGizmo(e){return e.gizmoManager.gizmos.scaleGizmo}getBoundingBoxGizmo(e){return e.gizmoManager.gizmos.boundingBoxGizmo}attachToMesh(e){return e.gizmoManager.attachToMesh(e.mesh),e.gizmoManager}detachMesh(e){return e.gizmoManager.attachToMesh(null),e.gizmoManager}}class LX{constructor(e){this.context=e}planarGizmoEnabled(e){return e.positionGizmo.planarGizmoEnabled=e.planarGizmoEnabled,e.positionGizmo}snapDistance(e){return e.positionGizmo.snapDistance=e.snapDistance,e.positionGizmo}getAttachedMesh(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.attachedMesh}getAttachedNode(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.attachedNode}getXGizmo(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.xGizmo}getYGizmo(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.yGizmo}getZGizmo(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.zGizmo}getXPlaneGizmo(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.xPlaneGizmo}getYPlaneGizmo(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.yPlaneGizmo}getZPlaneGizmo(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.zPlaneGizmo}getPlanarGizmoEnabled(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.planarGizmoEnabled}getSnapDistance(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.snapDistance}getIsDragging(e){var t;return null===(t=e.positionGizmo)||void 0===t?void 0:t.isDragging}createPositionGizmoObservableSelector(e){return e.selector}}class BX{constructor(e){this.context=e}setIsEnabled(e){return e.axisDragGizmo.isEnabled=e.isEnabled,e.axisDragGizmo}getIsEnabled(e){return e.axisDragGizmo.isEnabled}}class VX{constructor(e){this.context=e}setIsEnabled(e){return e.planeDragGizmo.isEnabled=e.isEnabled,e.planeDragGizmo}getIsEnabled(e){return e.planeDragGizmo.isEnabled}}class kX{constructor(e){this.context=e}snapDistance(e){return e.rotationGizmo.snapDistance=e.snapDistance,e.rotationGizmo}sensitivity(e){return e.rotationGizmo.sensitivity=e.sensitivity,e.rotationGizmo}getAttachedMesh(e){var t;return null===(t=e.rotationGizmo)||void 0===t?void 0:t.attachedMesh}getAttachedNode(e){var t;return null===(t=e.rotationGizmo)||void 0===t?void 0:t.attachedNode}getXGizmo(e){var t;return null===(t=e.rotationGizmo)||void 0===t?void 0:t.xGizmo}getYGizmo(e){var t;return null===(t=e.rotationGizmo)||void 0===t?void 0:t.yGizmo}getZGizmo(e){var t;return null===(t=e.rotationGizmo)||void 0===t?void 0:t.zGizmo}getSnapDistance(e){var t;return null===(t=e.rotationGizmo)||void 0===t?void 0:t.snapDistance}getSensitivity(e){var t;return null===(t=e.rotationGizmo)||void 0===t?void 0:t.sensitivity}createRotationGizmoObservableSelector(e){return e.selector}}class UX{constructor(e){this.context=e}getXGizmo(e){var t;return null===(t=e.scaleGizmo)||void 0===t?void 0:t.xGizmo}getYGizmo(e){var t;return null===(t=e.scaleGizmo)||void 0===t?void 0:t.yGizmo}getZGizmo(e){var t;return null===(t=e.scaleGizmo)||void 0===t?void 0:t.zGizmo}snapDistance(e){return e.scaleGizmo.snapDistance=e.snapDistance,e.scaleGizmo}setIncrementalSnap(e){return e.scaleGizmo.incrementalSnap=e.incrementalSnap,e.scaleGizmo}sensitivity(e){return e.scaleGizmo.sensitivity=e.sensitivity,e.scaleGizmo}getIncrementalSnap(e){return e.scaleGizmo.incrementalSnap}getSnapDistance(e){return e.scaleGizmo.snapDistance}getSensitivity(e){return e.scaleGizmo.sensitivity}createScaleGizmoObservableSelector(e){return e.selector}}class GX{constructor(e){this.context=e}setIsEnabled(e){return e.axisScaleGizmo.isEnabled=e.isEnabled,e.axisScaleGizmo}getIsEnabled(e){return e.axisScaleGizmo.isEnabled}}class zX{constructor(e){this.context=e}setRotationSphereSize(e){return e.boundingBoxGizmo.rotationSphereSize=e.rotationSphereSize,e.boundingBoxGizmo}setFixedDragMeshScreenSize(e){return e.boundingBoxGizmo.fixedDragMeshScreenSize=e.fixedDragMeshScreenSize,e.boundingBoxGizmo}setFixedDragMeshBoundsSize(e){return e.boundingBoxGizmo.fixedDragMeshBoundsSize=e.fixedDragMeshBoundsSize,e.boundingBoxGizmo}setFixedDragMeshScreenSizeDistanceFactor(e){return e.boundingBoxGizmo.fixedDragMeshScreenSizeDistanceFactor=e.fixedDragMeshScreenSizeDistanceFactor,e.boundingBoxGizmo}setScalingSnapDistance(e){return e.boundingBoxGizmo.scalingSnapDistance=e.scalingSnapDistance,e.boundingBoxGizmo}setRotationSnapDistance(e){return e.boundingBoxGizmo.rotationSnapDistance=e.rotationSnapDistance,e.boundingBoxGizmo}setScaleBoxSize(e){return e.boundingBoxGizmo.scaleBoxSize=e.scaleBoxSize,e.boundingBoxGizmo}setIncrementalSnap(e){return e.boundingBoxGizmo.incrementalSnap=e.incrementalSnap,e.boundingBoxGizmo}setScalePivot(e){return e.boundingBoxGizmo.scalePivot=new hc.Pq(...e.scalePivot),e.boundingBoxGizmo}setAxisFactor(e){return e.boundingBoxGizmo.axisFactor=new hc.Pq(...e.axisFactor),e.boundingBoxGizmo}setScaleDragSpeed(e){return e.boundingBoxGizmo.scaleDragSpeed=e.scaleDragSpeed,e.boundingBoxGizmo}getRotationSphereSize(e){var t;return null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.rotationSphereSize}getScaleBoxSize(e){var t;return null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.scaleBoxSize}getFixedDragMeshScreenSize(e){var t;return null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.fixedDragMeshScreenSize}getFixedDragMeshBoundsSize(e){var t;return null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.fixedDragMeshBoundsSize}getFixedDragMeshScreenSizeDistanceFactor(e){var t;return null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.fixedDragMeshScreenSizeDistanceFactor}getScalingSnapDistance(e){var t;return null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.scalingSnapDistance}getRotationSnapDistance(e){var t;return null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.rotationSnapDistance}getIncrementalSnap(e){var t;return null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.incrementalSnap}getScalePivot(e){var t,i;return null===(i=null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.scalePivot)||void 0===i?void 0:i.asArray()}getAxisFactor(e){var t,i;return null===(i=null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.axisFactor)||void 0===i?void 0:i.asArray()}getScaleDragSpeed(e){var t;return null===(t=e.boundingBoxGizmo)||void 0===t?void 0:t.scaleDragSpeed}createBoundingBoxGizmoObservableSelector(e){return e.selector}}class WX{constructor(e){this.context=e}setIsEnabled(e){return e.planeRotationGizmo.isEnabled=e.isEnabled,e.planeRotationGizmo}getIsEnabled(e){return e.planeRotationGizmo.isEnabled}}class HX{constructor(e){this.context=e}scaleRatio(e){return e.gizmo.scaleRatio=e.scaleRatio,e.gizmo}getScaleRatio(e){var t;return null===(t=e.gizmo)||void 0===t?void 0:t.scaleRatio}}class XX{constructor(e){this.context=e,this.manager=new FX(e),this.base=new HX(e),this.positionGizmo=new LX(e),this.rotationGizmo=new kX(e),this.scaleGizmo=new UX(e),this.boundingBoxGizmo=new zX(e),this.axisDragGizmo=new BX(e),this.axisScaleGizmo=new GX(e),this.planeDragGizmo=new VX(e),this.planeRotationGizmo=new WX(e)}}class qX{constructor(e,t,i){this.mesh=new yX(e),this.camera=new iW(e),this.gaussianSplatting=new WW(e),this.node=new AX(e,t),this.scene=new MX(e),this.webXr=new UW(e),this.gui=new CX(e),this.transforms=new NX,this.io=new lX(e),this.ray=new IX(e),this.pick=new RX(e),this.material=new BW(e,i),this.lights=new cX(e),this.texture=new OX(e),this.meshBuilder=new PX(e,this.mesh),this.tools=new wX(e),this.engine=new GW(e),this.gizmo=new XX(e)}}class YX extends HG{constructor(e,t){super(e),this.occWorkerManager=e,this.context=t}loadSTEPorIGES(e){return this.context.getFile(e.assetFile).then((t=>this.occWorkerManager.genericCallToWorkerPromise("io.loadSTEPorIGES",new Yz.LoadStepOrIgesDto(t,e.assetFile.name,e.adjustZtoY))))}loadSTEPorIGESFromText(e){return this.occWorkerManager.genericCallToWorkerPromise("io.loadSTEPorIGES",new Yz.LoadStepOrIgesDto(e.text,`fake.${e.fileType}`,e.adjustZtoY))}}class KX extends hz{constructor(e,t){super(t),this.context=e,this.occWorkerManager=t,this.io=new YX(t,e)}}class jX{constructor(e,t){this.context=e,this.math=t}createCircle(e){return new this.context.verb.geom.Circle(e.center,e.xAxis,e.yAxis,e.radius)}createArc(e){return new this.context.verb.geom.Arc(e.center,e.xAxis,e.yAxis,e.radius,this.math.degToRad({number:e.minAngle}),this.math.degToRad({number:e.maxAngle}))}center(e){return e.circle.center()}radius(e){return e.circle.radius()}maxAngle(e){return this.math.radToDeg({number:e.circle.maxAngle()})}minAngle(e){return this.math.radToDeg({number:e.circle.minAngle()})}xAxis(e){return e.circle.xaxis()}yAxis(e){return e.circle.yaxis()}}class $X{constructor(e,t){this.context=e,this.math=t}createEllipse(e){return new this.context.verb.geom.Ellipse(e.center,e.xAxis,e.yAxis)}createArc(e){return new this.context.verb.geom.EllipseArc(e.center,e.xAxis,e.yAxis,this.math.degToRad({number:e.minAngle}),this.math.degToRad({number:e.maxAngle}))}center(e){return e.ellipse.center()}maxAngle(e){return this.math.radToDeg({number:e.ellipse.maxAngle()})}minAngle(e){return this.math.radToDeg({number:e.ellipse.minAngle()})}xAxis(e){return e.ellipse.xaxis()}yAxis(e){return e.ellipse.yaxis()}}class QX{constructor(e,t,i){this.context=e,this.geometryHelper=t,this.math=i,this.circle=new jX(e,this.math),this.ellipse=new $X(e,this.math)}createCurveByKnotsControlPointsWeights(e){return this.context.verb.geom.NurbsCurve.byKnotsControlPointsWeights(e.degree,e.knots,e.points,e.weights)}createCurveByPoints(e){return this.context.verb.geom.NurbsCurve.byPoints(e.points,e.degree)}createBezierCurve(e){return new this.context.verb.geom.BezierCurve(e.points,e.weights)}clone(e){return e.curve.clone()}closestParam(e){return e.curve.closestParam(e.point)}closestParams(e){return e.points.map((t=>e.curve.closestParam(t)))}closestPoint(e){return e.curve.closestPoint(e.point)}closestPoints(e){return e.points.map((t=>e.curve.closestPoint(t)))}controlPoints(e){return e.curve.controlPoints()}degree(e){return e.curve.degree()}derivatives(e){return e.curve.derivatives(e.parameter,e.numDerivatives)}divideByEqualArcLengthToParams(e){return e.curve.divideByEqualArcLength(e.subdivision).map((e=>e.u))}divideByEqualArcLengthToPoints(e){return e.curve.divideByEqualArcLength(e.subdivision).map((t=>e.curve.point(t.u)))}divideByArcLengthToParams(e){return e.curve.divideByArcLength(e.length).map((e=>e.u))}divideByArcLengthToPoints(e){return e.curve.divideByArcLength(e.length).map((t=>e.curve.point(t.u)))}divideCurvesByEqualArcLengthToPoints(e){return e.curves.map((t=>this.divideByEqualArcLengthToPoints({curve:t,subdivision:e.subdivision})))}divideCurvesByArcLengthToPoints(e){return e.curves.map((t=>this.divideByArcLengthToPoints({curve:t,length:e.length})))}domain(e){return e.curve.domain()}startPoint(e){return e.curve.point(e.curve.domain().min)}endPoint(e){return e.curve.point(e.curve.domain().max)}startPoints(e){return e.curves.map((e=>this.startPoint({curve:e})))}endPoints(e){return e.curves.map((e=>this.endPoint({curve:e})))}knots(e){return e.curve.knots()}lengthAtParam(e){return e.curve.lengthAtParam(e.parameter)}length(e){return e.curve.length()}paramAtLength(e){return e.curve.paramAtLength(e.length,e.tolerance)}pointAtParam(e){return e.curve.point(e.parameter)}pointsAtParam(e){return e.curves.map((t=>this.pointAtParam({curve:t,parameter:e.parameter})))}reverse(e){return e.curve.reverse()}split(e){return e.curve.split(e.parameter)}tangent(e){return e.curve.tangent(e.parameter)}tessellate(e){return e.curve.tessellate(e.tolerance)}transform(e){const t=e.curve.controlPoints(),i=this.geometryHelper.transformControlPoints(e.transformation,t);return this.context.verb.geom.NurbsCurve.byKnotsControlPointsWeights(e.curve.degree(),e.curve.knots(),i,e.curve.weights())}transformCurves(e){return e.curves.map((t=>this.transform({curve:t,transformation:e.transformation})))}weights(e){return e.curve.weights()}}class ZX{constructor(e,t){this.context=e,this.geometryHelper=t}curves(e){return this.context.verb.geom.Intersect.curves(e.firstCurve,e.secondCurve,e.tolerance)}curveAndSurface(e){return this.context.verb.geom.Intersect.curveAndSurface(e.curve,e.surface,e.tolerance)}surfaces(e){return this.context.verb.geom.Intersect.surfaces(e.firstSurface,e.secondSurface)}curveCurveFirstParams(e){return e.intersections.filter((e=>e.u0>=0&&e.u0<=1)).map((e=>e.u0))}curveCurveSecondParams(e){return e.intersections.filter((e=>e.u1>=0&&e.u1<=1)).map((e=>e.u1))}curveCurveFirstPoints(e){return e.intersections.filter((e=>e.u0>=0&&e.u0<=1)).map((e=>e.point0))}curveCurveSecondPoints(e){return e.intersections.filter((e=>e.u1>=0&&e.u1<=1)).map((e=>e.point1))}curveSurfaceCurveParams(e){return e.intersections.filter((e=>e.u>=0&&e.u<=1)).map((e=>e.u))}curveSurfaceSurfaceParams(e){return e.intersections.map((e=>e.uv))}curveSurfaceCurvePoints(e){return e.intersections.filter((e=>e.u>=0&&e.u<=1)).map((e=>e.curvePoint))}curveSurfaceSurfacePoints(e){return e.intersections.map((e=>e.surfacePoint))}}class JX{constructor(e){this.context=e}create(e){return new this.context.verb.geom.ConicalSurface(e.axis,e.xAxis,e.base,e.height,e.radius)}axis(e){return e.cone.axis()}base(e){return e.cone.base()}height(e){return e.cone.height()}radius(e){return e.cone.radius()}xAxis(e){return e.cone.xaxis()}}class eq{constructor(e){this.context=e}create(e){return new this.context.verb.geom.CylindricalSurface(e.axis,e.xAxis,e.base,e.height,e.radius)}axis(e){return e.cylinder.axis()}base(e){return e.cylinder.base()}height(e){return e.cylinder.height()}radius(e){return e.cylinder.radius()}xAxis(e){return e.cylinder.xaxis()}}class tq{constructor(e){this.context=e}create(e){return new this.context.verb.geom.ExtrudedSurface(e.profile,e.direction)}direction(e){return e.extrusion.direction()}profile(e){return e.extrusion.profile()}}class iq{constructor(e,t){this.context=e,this.math=t}create(e){return new this.context.verb.geom.RevolvedSurface(e.profile,e.center,e.axis,this.math.degToRad({number:e.angle}))}profile(e){return e.revolution.profile()}center(e){return e.revolution.center()}axis(e){return e.revolution.axis()}angle(e){return this.math.radToDeg({number:e.revolution.angle()})}}class rq{constructor(e){this.context=e}create(e){return new this.context.verb.geom.SphericalSurface(e.center,e.radius)}radius(e){return e.sphere.radius()}center(e){return e.sphere.center()}}class sq{constructor(e){this.context=e}create(e){return new this.context.verb.geom.SweptSurface(e.profile,e.rail)}profile(e){return e.sweep.profile()}rail(e){return e.sweep.rail()}}class nq{constructor(e,t,i){this.context=e,this.geometryHelper=t,this.math=i,this.cone=new JX(e),this.cylinder=new eq(e),this.extrusion=new tq(e),this.sphere=new rq(e),this.revolved=new iq(e,i),this.sweep=new sq(e)}boundaries(e){return e.surface.boundaries()}createSurfaceByCorners(e){return this.context.verb.geom.NurbsSurface.byCorners(e.point1,e.point2,e.point3,e.point4)}createSurfaceByKnotsControlPointsWeights(e){return this.context.verb.geom.NurbsSurface.byKnotsControlPointsWeights(e.degreeU,e.degreeV,e.knotsU,e.knotsV,e.points,e.weights)}createSurfaceByLoftingCurves(e){return this.context.verb.geom.NurbsSurface.byLoftingCurves(e.curves,e.degreeV)}clone(e){return e.surface.clone()}closestParam(e){return e.surface.closestParam(e.point)}closestPoint(e){return e.surface.closestPoint(e.point)}controlPoints(e){return e.surface.controlPoints()}degreeU(e){return e.surface.degreeU()}degreeV(e){return e.surface.degreeV()}derivatives(e){return e.surface.derivatives(e.u,e.v,e.numDerivatives)}domainU(e){return e.surface.domainU()}domainV(e){return e.surface.domainV()}isocurve(e){return e.surface.isocurve(e.parameter,e.useV)}isocurvesSubdivision(e){const t=.999999/e.isocurveSegments,i=this.context.verb.core.Vec.span(1e-7,.9999999,t);return e.includeLast||i.pop(),e.includeFirst||i.shift(),i.map((t=>e.surface.isocurve(t,e.useV)))}isocurvesAtParams(e){return e.parameters.map((t=>e.surface.isocurve(t,e.useV)))}knotsU(e){return e.surface.knotsU()}knotsV(e){return e.surface.knotsV()}normal(e){return e.surface.normal(e.u,e.v)}point(e){return e.surface.point(e.u,e.v)}reverse(e){return e.surface.reverse()}split(e){return e.surface.split(e.parameter,e.useV)}transformSurface(e){const t=e.surface.controlPoints(),i=e.transformation,r=[];return t.forEach((e=>{let t=e;t=this.geometryHelper.transformControlPoints(i,t),r.push(t)})),this.context.verb.geom.NurbsSurface.byKnotsControlPointsWeights(e.surface.degreeU(),e.surface.degreeV(),e.surface.knotsU(),e.surface.knotsV(),r,e.surface.weights())}weights(e){return e.surface.weights()}}class oq{constructor(e,t,i){this.math=i,this.curve=new QX(e,t,this.math),this.surface=new nq(e,t,this.math),this.intersect=new ZX(e,t)}}class aq{}var lq,hq=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class cq{constructor(){this.assetManager=new aq}getFile(e){return this.assetManager.getAsset(e.fileName)}getLocalFile(e){return this.assetManager.getLocalAsset(e.fileName)}fetchBlob(e){return hq(this,void 0,void 0,(function*(){return(yield fetch(e.url)).blob()}))}fetchFile(e){return hq(this,void 0,void 0,(function*(){const t=yield fetch(e.url),i=yield t.blob();return new File([i],e.url.split("/").pop().split("?")[0])}))}fetchJSON(e){return hq(this,void 0,void 0,(function*(){return(yield fetch(e.url)).json()}))}fetchText(e){return hq(this,void 0,void 0,(function*(){return(yield fetch(e.url)).text()}))}createObjectURL(e){return URL.createObjectURL(e.file)}createObjectURLs(e){return e.files.map((e=>URL.createObjectURL(e)))}}!function(e){e.IntervalDto=class{constructor(){this.min=0,this.max=1}},e.UVDto=class{constructor(){this.u=0,this.v=0}},e.CurveCurveIntersection=class{},e.CurveSurfaceIntersection=class{},e.SurfaceSurfaceIntersectionPoint=class{}}(lq||(lq={}));class uq{constructor(e){this.context=e}stringify(e){return JSON.stringify(e.json)}parse(e){return JSON.parse(e.text)}query(e){return this.context.jsonpath({path:e.query,json:e.json})}setValueOnProp(e){const t=Object.assign({},structuredClone(e.json));return t[e.property]=e.value,t}getJsonFromArrayByFirstPropMatch(e){return e.jsonArray.find((t=>t[e.property]===e.match))}getValueOnProp(e){try{return Object.assign({},structuredClone(e.json))[e.property]}catch(t){return e.json[e.property]}}setValue(e){if(e.json instanceof Object){const t=Object.assign({},structuredClone(e.json)),i=t=>(t[e.prop]=e.value,t);return this.context.jsonpath({path:e.path,json:t,callback:i}),t}throw new Error("Json must be an object")}setValuesOnPaths(e){let t=Object.assign({},structuredClone(e.json));return e.paths.forEach(((i,r)=>{t=this.setValue({json:t,path:i,value:e.values[r],prop:e.props[r]})})),t}paths(e){return this.context.jsonpath({json:e.json,path:e.query,resultType:"path"})}createEmpty(){return{}}previewAndSaveJson(e){e.json&&this.context.promptPrintSave({text:e.json,isJson:!0,hidden:!1})}previewJson(e){e.json&&this.context.promptPrint({text:e.json,isJson:!0,hidden:!1})}}class dq{constructor(e,t){this.context=e,this.geometryHelper=t}convertToNurbsCurve(e){return new this.context.verb.geom.Line(e.line.start,e.line.end)}convertLinesToNurbsCurves(e){return e.lines.map((e=>new this.context.verb.geom.Line(e.start,e.end)))}getStartPoint(e){return e.line.start}getEndPoint(e){return e.line.end}length(e){return this.context.verb.core.Vec.dist(e.line.start,e.line.end)}reverse(e){return{start:e.line.end,end:e.line.start}}transformLine(e){const t=e.transformation;let i=[e.line.start,e.line.end];return i=this.geometryHelper.transformControlPoints(t,i),{start:i[0],end:i[1]}}transformsForLines(e){return e.lines.map(((t,i)=>{const r=e.transformation[i];let s=[t.start,t.end];return s=this.geometryHelper.transformControlPoints(r,s),{start:s[0],end:s[1]}}))}create(e){return{start:e.start,end:e.end}}createAsync(e){return Promise.resolve({start:e.start,end:e.end})}getPointOnLine(e){const t=e.line.start,i=e.line.end,r=e.param,s=[i[0]-t[0],i[1]-t[1],i[2]-t[2]];return[t[0]+r*s[0],t[1]+r*s[1],t[2]+r*s[2]]}linesBetweenPoints(e){const t=[];for(let i=1;i({start:t,end:e.endPoints[i]}))).filter((e=>0!==this.context.verb.core.Vec.dist(e.start,e.end)))}linesBetweenStartAndEndPointsAsync(e){return Promise.resolve(this.linesBetweenStartAndEndPoints(e))}}class fq{constructor(e,t){this.context=e,this.geometryHelper=t}convertToNurbsCurve(e){return this.context.verb.geom.NurbsCurve.byPoints(e.polyline.points,1)}length(e){let t=0;for(let i=1;it.id===e.tagVariable.id));Object.keys(e.tag).forEach((i=>{t[i]=e.tag[i]})),t.needsUpdate=!0}else{const t=document.createElement("span"),i="_tag"+(new Date).getTime()+this.context.tagBag.length;e.tag.id=i,t.id=i,t.textContent=e.tag.text,document.querySelector("."+this.context.canvasZoneClass).appendChild(t),e.tag.needsUpdate=!0,this.context.tagBag.push(e.tag)}return e.tag}drawTags(e){if(e.tagsVariable&&e.updatable){if(e.tagsVariable.length{const r=this.context.tagBag.find((e=>e.id===t.id)),s=e.tags[i];if(s)Object.keys(s).forEach((e=>{r[e]=s[e]})),r.needsUpdate=!0;else{this.context.tagBag=this.context.tagBag.filter((e=>e.id!==r.id));const e=document.getElementById(r.id);e.parentNode.removeChild(e)}}))}else{const t=[];e.tags.forEach(((i,r)=>{const s=document.createElement("span"),n="_tag"+(new Date).getTime()+this.context.tagBag.length;i.id=n,s.id=n,s.textContent=i.text,document.querySelector("."+this.context.canvasZoneClass).appendChild(s),i.needsUpdate=!0,this.context.tagBag.push(i),t.push(i),e.tagsVariable=t}))}return e.tagsVariable}}class _q{constructor(e){this.context=e}registerRenderFunction(e){this.context.renderLoopBag.push((t=>{e(t)}))}}class mq{constructor(){this.canvasZoneClass="canvasZone",this.tolerance=1e-5,this.snapTolerance=1e-5,this.tagBag=[],this.timeoutBag=[],this.intervalBag=[],this.renderLoopBag=[],this.keyDownBag=[],this.keyUpBag=[],this.keyPressBag=[],this.currentlyPressedKeys=[]}getFile(e){return new Promise(((t,i)=>{if(e){const r=new FileReader;r.readAsText(e,"UTF-8"),r.onload=e=>{const i=e.target.result;t(i)},r.onerror=e=>{i()}}else i()}))}remap(e,t,i,r,s){return(e-t)/(i-t)*(s-r)+r}}class gq{detectPoint(e){return Array.isArray(e)&&3===e.length&&this.checkIfElementsInArrayAreNumbers(e)}detectPoints(e){return Array.isArray(e)&&this.checkIfElementsInArrayAreArrays(e)&&this.arraysInChildrenArraysContainNumbers(e)&&this.arraysInChildrenArraysAreOfLength3(e)}detectLine(e){return e.start&&e.end&&Array.isArray(e.start)&&Array.isArray(e.end)}detectLines(e){return Array.isArray(e)&&!e.some((e=>!this.detectLine(e)))}detectPolyline(e){return e.points&&Array.isArray(e.points)}detectPolylines(e){return Array.isArray(e)&&!e.some((e=>!this.detectPolyline(e)))}detectNode(e){return!Array.isArray(e)&&e.id&&e.id.includes("node")}detectNodes(e){return Array.isArray(e)&&!e.some((e=>!this.detectNode(e)))}detectVerbCurve(e){return!Array.isArray(e)&&e._data&&e._data.controlPoints&&e._data.knots&&e._data.degree}detectVerbSurface(e){return!Array.isArray(e)&&e._data&&e._data.controlPoints&&e._data.degreeU&&e._data.degreeV&&e._data.knotsU&&e._data.knotsV}detectVerbCurves(e){return Array.isArray(e)&&!e.some((e=>!this.detectVerbCurve(e)))}detectVerbSurfaces(e){return Array.isArray(e)&&!e.some((e=>!this.detectVerbSurface(e)))}detectJscadMesh(e){return!Array.isArray(e)&&(e.sides||e.polygons)}detectJscadMeshes(e){return Array.isArray(e)&&!e.some((e=>!this.detectJscadMesh(e)))}detectOcctShape(e){return"occ-shape"===(null==e?void 0:e.type)}detectOcctShapes(e){return Array.isArray(e)&&!e.some((e=>!this.detectOcctShape(e)))}detectManifoldShape(e){return"manifold-shape"===(null==e?void 0:e.type)}detectManifoldShapes(e){return Array.isArray(e)&&!e.some((e=>!this.detectManifoldShape(e)))}detectTag(e){return!Array.isArray(e)&&e.text}detectTags(e){return Array.isArray(e)&&!e.some((e=>!this.detectTag(e)))}checkIfElementsInArrayAreNumbers(e){return!e.some((e=>isNaN(e)))}checkIfElementsInArrayAreArrays(e){return!e.some((e=>!Array.isArray(e)))}arraysInChildrenArraysContainNumbers(e){return!e.some((e=>!this.checkIfElementsInArrayAreNumbers(e)))}arraysInChildrenArraysAreOfLength3(e){return!e.some((e=>3!==e.length))}}class vq{constructor(e){this.vector=e}computeEdgeMiddlePos(e){let t;if(2===e.vertex_coord.length){const i=e.vertex_coord[0],r=e.vertex_coord[1];t=this.vector.lerp({first:i,second:r,fraction:.5})}else if(3===e.vertex_coord.length)t=e.vertex_coord[1];else{const i=e.vertex_coord[Math.floor(e.vertex_coord.length/2)],r=e.vertex_coord[Math.floor(e.vertex_coord.length/2+1)];t=this.vector.lerp({first:i,second:r,fraction:.5})}return t}computeFaceMiddlePos(e){let t=0,i=0,r=0,s=0;return e.forEach((e=>{t+=e[0],i+=e[1],r+=e[2],s++})),[t/s,i/s,r/s]}}var xq,bq,Sq,Tq,Cq,yq,Eq,Pq,Aq=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class Rq extends gq{constructor(e,t,i,r){super(),this.drawHelper=e,this.node=t,this.tag=i,this.context=r,this.defaultBasicOptions=new QH.DrawBasicGeometryOptions,this.defaultPolylineOptions=Object.assign(Object.assign({},new QH.DrawBasicGeometryOptions),{size:2,colours:"#ff00ff"}),this.defaultNodeOptions={colorX:"#ff0000",colorY:"#00ff00",colorZ:"#0000ff",size:2}}drawAnyAsyncNoReturn(e){return Aq(this,void 0,void 0,(function*(){this.drawAnyAsync(e)}))}drawAnyAsync(e){return Aq(this,void 0,void 0,(function*(){const t=e.entity;return void 0===t||Array.isArray(t)&&0===t.length?Promise.resolve(void 0):this.detectJscadMesh(t)?this.handleJscadMesh(e):this.detectOcctShape(t)?this.handleOcctShape(e):this.detectOcctShapes(t)?this.handleOcctShapes(e):this.detectJscadMeshes(t)?this.handleJscadMeshes(e):this.detectManifoldShape(t)?this.handleManifoldShape(e):this.detectManifoldShapes(t)?this.handleManifoldShapes(e):Promise.resolve(this.drawAny(e))}))}updateAny(e){let t;if(e.babylonMesh&&e.babylonMesh.metadata)switch(e.babylonMesh.metadata.type){case QH.drawingTypes.point:t=this.handlePoint(e);break;case QH.drawingTypes.points:t=this.handlePoints(e);break;case QH.drawingTypes.line:t=this.handleLine(e);break;case QH.drawingTypes.lines:t=this.handleLines(e);break;case QH.drawingTypes.polyline:t=this.handlePolyline(e);break;case QH.drawingTypes.polylines:t=this.handlePolylines(e);break;case QH.drawingTypes.verbCurve:t=this.handleVerbCurve(e);break;case QH.drawingTypes.verbCurves:t=this.handleVerbCurves(e);break;case QH.drawingTypes.verbSurface:t=this.handleVerbSurface(e);break;case QH.drawingTypes.verbSurfaces:t=this.handleVerbSurfaces(e);break;case QH.drawingTypes.tag:t=this.handleTag(e);break;case QH.drawingTypes.tags:t=this.handleTags(e);break;case QH.drawingTypes.node:t=this.handleNode(e);break;case QH.drawingTypes.nodes:t=this.handleNodes(e)}return t}drawAnyNoReturn(e){this.drawAny(e)}drawAny(e){let t;const i=e.entity;return e.babylonMesh?t=this.updateAny(e):this.detectLine(i)?t=this.handleLine(e):this.detectPoint(i)?t=this.handlePoint(e):this.detectPolyline(i)?t=this.handlePolyline(e):this.detectNode(i)?t=this.handleNode(e):this.detectVerbCurve(i)?t=this.handleVerbCurve(e):this.detectVerbSurface(i)?t=this.handleVerbSurface(e):this.detectPolylines(i)?t=this.handlePolylines(e):this.detectLines(i)?t=this.handleLines(e):this.detectPoints(i)?t=this.handlePoints(e):this.detectNodes(i)?t=this.handleNodes(e):this.detectVerbCurves(i)?t=this.handleVerbCurves(e):this.detectVerbSurfaces(i)?t=this.handleVerbSurfaces(e):this.detectTag(i)?t=this.handleTag(e):this.detectTags(i)&&(t=this.handleTags(e)),t}drawGridMeshNoReturn(e){this.drawGridMesh(e)}drawGridMesh(e){try{const t=new gW(`groundMaterial${Math.random()}`,this.context.scene);t.majorUnitFrequency=e.majorUnitFrequency,t.minorUnitVisibility=e.minorUnitVisibility,t.gridRatio=e.gridRatio,t.backFaceCulling=e.backFaceCulling,t.mainColor=hc.v9.FromHexString(e.mainColor),t.lineColor=hc.v9.FromHexString(e.secondaryColor),t.opacity=e.opacity;const i=bl.CreateGround(`bitbybit-ground${Math.random()}`,{width:e.width,height:e.height,subdivisions:e.subdivisions,updatable:!1},this.context.scene);return i.material=t,i}catch(e){return console.log("Error happened: ",e),new Yt("error-ground",this.context.scene)}}optionsSimple(e){return e}optionsOcctShape(e){return e}optionsOcctShapeSimple(e){return e}optionsOcctShapeMaterial(e){return e}optionsManifoldShapeMaterial(e){return e}optionsBabylonNode(e){return e}handleTags(e){const t=e.options?e.options:{updatable:!1},i=this.tag.drawTags(Object.assign({tagsVariable:e.babylonMesh,tags:e.entity},t));return i.metadata={type:QH.drawingTypes.tags,options:t},i}handleTag(e){let t=e.options?e.options:{updatable:!1};!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.tag.drawTag(Object.assign({tagVariable:e.babylonMesh,tag:e.entity},t));return i.metadata={type:QH.drawingTypes.tag,options:t},i}handleVerbSurfaces(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.drawHelper.drawSurfacesMultiColour(Object.assign({surfacesMesh:e.babylonMesh,surfaces:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.verbSurfaces,t,i),i}handleVerbCurves(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.drawHelper.drawCurves(Object.assign({curvesMesh:e.babylonMesh,curves:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.verbCurves,t,i),i}handleNodes(e){let t=e.options?e.options:this.defaultNodeOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=e.entity;return this.node.drawNodes(Object.assign({nodes:e.entity},t)),this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.nodes,t,i),i}handlePoints(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.drawHelper.drawPoints(Object.assign({pointsMesh:e.babylonMesh,points:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.points,t,i),i}handleLines(e){let t=e.options?e.options:this.defaultPolylineOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=e.entity,r=this.drawHelper.drawPolylinesWithColours(Object.assign({polylinesMesh:e.babylonMesh,polylines:i.map((e=>({points:[e.start,e.end]})))},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.lines,t,r),r}handlePolylines(e){let t=e.options?e.options:this.defaultPolylineOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.drawHelper.drawPolylinesWithColours(Object.assign({polylinesMesh:e.babylonMesh,polylines:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.polylines,t,i),i}handleVerbSurface(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.drawHelper.drawSurface(Object.assign({surfaceMesh:e.babylonMesh,surface:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.verbSurface,t,i),i}handleVerbCurve(e){let t=e.options?e.options:this.defaultPolylineOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.drawHelper.drawCurve(Object.assign({curveMesh:e.babylonMesh,curve:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.verbCurve,t,i),i}handleNode(e){let t=e.options?e.options:this.defaultNodeOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=e.entity;return this.node.drawNode(Object.assign({node:e.entity},t)),this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.node,t,i),i}handlePolyline(e){let t=e.options?e.options:this.defaultPolylineOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.drawHelper.drawPolylineClose(Object.assign({polylineMesh:e.babylonMesh,polyline:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.polyline,t,i),i}handlePoint(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.drawHelper.drawPoint(Object.assign({pointMesh:e.babylonMesh,point:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.point,t,i),i}handleLine(e){let t=e.options?e.options:this.defaultPolylineOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=e.entity,r=this.drawHelper.drawPolylinesWithColours(Object.assign({polylinesMesh:e.babylonMesh,polylines:[{points:[i.start,i.end]}]},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.line,t,r),r}handleJscadMeshes(e){let t=e.options?e.options:this.defaultPolylineOptions;return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.drawHelper.drawSolidOrPolygonMeshes(Object.assign({jscadMesh:e.babylonMesh,meshes:e.entity},t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.jscadMeshes,t,e),e)))}handleManifoldShape(e){let t=e.options?e.options:new oX.DrawManifoldOrCrossSectionDto(e.entity);return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.drawHelper.drawManifoldOrCrossSection(Object.assign(Object.assign({manifoldOrCrossSection:e.entity},new QH.DrawManifoldOrCrossSectionOptions),t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.manifold,t,e),e)))}handleManifoldShapes(e){let t=e.options?e.options:new oX.DrawManifoldOrCrossSectionDto(e.entity);return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.drawHelper.drawManifoldsOrCrossSections(Object.assign(Object.assign({manifoldsOrCrossSections:e.entity},new oX.DrawManifoldOrCrossSectionDto),t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.manifold,t,e),e)))}handleOcctShape(e){let t=e.options?e.options:new Yz.DrawShapeDto(e.entity);return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.drawHelper.drawShape(Object.assign(Object.assign({shape:e.entity},new QH.DrawOcctShapeOptions),t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.occt,t,e),e)))}handleOcctShapes(e){let t=e.options?e.options:new Yz.DrawShapeDto(e.entity);return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.drawHelper.drawShapes(Object.assign(Object.assign({shapes:e.entity},new QH.DrawOcctShapeOptions),t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.occt,t,e),e)))}handleJscadMesh(e){let t=e.options?e.options:this.defaultBasicOptions;return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.drawHelper.drawSolidOrPolygonMesh(Object.assign({jscadMesh:e.babylonMesh,mesh:e.entity},t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(QH.drawingTypes.jscadMesh,t,e),e)))}applyGlobalSettingsAndMetadataAndShadowCasting(e,t,i){const r={type:e,options:t},s=this.context.scene.metadata.shadowGenerators;i.isPickable=!1,i.getChildMeshes().forEach((e=>{e.isPickable=!1}));let n=!0;i.metadata&&!1===i.metadata.shadows&&(n=!1),n&&s.length>0&&(i.receiveShadows=!0,s.forEach((e=>e.addShadowCaster(i))),i.getChildMeshes().forEach((e=>{e.receiveShadows=!0,s.forEach((t=>t.addShadowCaster(e)))}))),i.metadata=i.metadata?Object.assign(Object.assign({},i.metadata),r):r}}class Iq extends mq{getSamplingMode(e){switch(e){case BH.samplingModeEnum.nearest:return vi.g.NEAREST_SAMPLINGMODE;case BH.samplingModeEnum.bilinear:return vi.g.BILINEAR_SAMPLINGMODE;case BH.samplingModeEnum.trilinear:return vi.g.TRILINEAR_SAMPLINGMODE;default:return vi.g.NEAREST_SAMPLINGMODE}}}!function(e){e.HexDto=class{constructor(e){this.color="#0000ff",void 0!==e&&(this.color=e)}},e.InvertHexDto=class{constructor(e){this.color="#0000ff",this.blackAndWhite=!1,void 0!==e&&(this.color=e)}},e.HexDtoMapped=class{constructor(e,t,i){this.color="#0000ff",this.from=0,this.to=255,void 0!==e&&(this.color=e),void 0!==t&&(this.from=t),void 0!==i&&(this.to=i)}},e.RGBObjectMaxDto=class{constructor(e,t){this.min=0,this.max=255,void 0!==e&&(this.rgb=e),void 0!==t&&(this.max=t)}},e.RGBMinMaxDto=class{constructor(e,t,i,r,s){this.r=255,this.g=255,this.b=255,this.min=0,this.max=255,void 0!==e&&(this.r=e),void 0!==t&&(this.g=t),void 0!==i&&(this.b=i),void 0!==r&&(this.min=r),void 0!==s&&(this.max=s)}},e.RGBObjectDto=class{constructor(e){void 0!==e&&(this.rgb=e)}}}(xq||(xq={})),function(e){let t;!function(e){e.first="first",e.last="last"}(t=e.firstLastEnum||(e.firstLastEnum={})),e.ListItemDto=class{constructor(e,t,i){this.index=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.index=t),void 0!==i&&(this.clone=i)}},e.SubListDto=class{constructor(e,t,i,r){this.indexStart=0,this.indexEnd=1,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.indexStart=t),void 0!==i&&(this.indexEnd=i),void 0!==r&&(this.clone=r)}},e.ListCloneDto=class{constructor(e,t){this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.clone=t)}},e.RepeatInPatternDto=class{constructor(e){this.clone=!0,this.lengthLimit=100,void 0!==e&&(this.list=e)}},e.SortDto=class{constructor(e,t,i){this.clone=!0,this.orderAsc=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.clone=t),void 0!==i&&(this.orderAsc=i)}},e.SortJsonDto=class{constructor(e,t,i){this.clone=!0,this.orderAsc=!0,this.property="propName",void 0!==e&&(this.list=e),void 0!==t&&(this.clone=t),void 0!==i&&(this.orderAsc=i)}},e.ListDto=class{constructor(e){void 0!==e&&(this.list=e)}},e.GroupListDto=class{constructor(e,t,i){this.nrElements=2,this.keepRemainder=!1,void 0!==e&&(this.list=e),void 0!==t&&(this.nrElements=t),void 0!==i&&(this.keepRemainder=i)}},e.MultiplyItemDto=class{constructor(e,t){void 0!==e&&(this.item=e),void 0!==t&&(this.times=t)}},e.AddItemAtIndexDto=class{constructor(e,t,i,r){this.index=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.item=t),void 0!==i&&(this.index=i),void 0!==r&&(this.clone=r)}},e.AddItemAtIndexesDto=class{constructor(e,t,i,r){this.indexes=[0],this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.item=t),void 0!==i&&(this.indexes=i),void 0!==r&&(this.clone=r)}},e.AddItemsAtIndexesDto=class{constructor(e,t,i,r){this.indexes=[0],this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.items=t),void 0!==i&&(this.indexes=i),void 0!==r&&(this.clone=r)}},e.RemoveItemAtIndexDto=class{constructor(e,t,i){this.index=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.index=t),void 0!==i&&(this.clone=i)}},e.RemoveItemsAtIndexesDto=class{constructor(e,t,i){this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.indexes=t),void 0!==i&&(this.clone=i)}},e.RemoveNthItemDto=class{constructor(e,t,i,r){this.nth=2,this.offset=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.nth=t),void 0!==i&&(this.offset=i),void 0!==r&&(this.clone=r)}},e.RandomThresholdDto=class{constructor(e,t,i){this.threshold=1,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.threshold=t),void 0!==i&&(this.clone=i)}},e.RemoveDuplicatesDto=class{constructor(e,t){this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.clone=t)}},e.RemoveDuplicatesToleranceDto=class{constructor(e,t,i){this.tolerance=1e-7,this.clone=!0,void 0!==e&&(this.list=e),void 0!==i&&(this.tolerance=i),void 0!==t&&(this.clone=t)}},e.GetByPatternDto=class{constructor(e,t){this.pattern=[!0,!0,!1],void 0!==e&&(this.list=e),void 0!==t&&(this.pattern=t)}},e.GetNthItemDto=class{constructor(e,t,i,r){this.nth=2,this.offset=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.nth=t),void 0!==i&&(this.offset=i),void 0!==r&&(this.clone=r)}},e.GetLongestListLength=class{constructor(e){void 0!==e&&(this.lists=e)}},e.MergeElementsOfLists=class{constructor(e,t){this.level=0,void 0!==e&&(this.lists=e),void 0!==t&&(this.level=t)}},e.AddItemDto=class{constructor(e,t,i){this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.item=t),void 0!==i&&(this.clone=i)}},e.AddItemFirstLastDto=class{constructor(e,i,r,s){this.position=t.last,this.clone=!0,void 0!==e&&(this.list=e),void 0!==i&&(this.item=i),void 0!==r&&(this.position=r),void 0!==s&&(this.clone=s)}}}(bq||(bq={})),function(e){let t;!function(e){e.less="<",e.lessOrEqual="<=",e.greater=">",e.greaterOrEqual=">=",e.tripleEqual="===",e.tripleNotEqual="!==",e.equal="==",e.notEqual="!="}(t=e.BooleanOperatorsEnum||(e.BooleanOperatorsEnum={})),e.ComparisonDto=class{constructor(e,t,i){void 0!==e&&(this.first=e),void 0!==t&&(this.second=t),void 0!==i&&(this.operator=i)}},e.BooleanDto=class{constructor(e){this.boolean=!1,void 0!==e&&(this.boolean=e)}},e.BooleanListDto=class{constructor(e){void 0!==e&&(this.booleans=e)}},e.ValueGateDto=class{constructor(e,t){this.boolean=!1,void 0!==e&&(this.value=e),void 0!==t&&(this.boolean=t)}},e.TwoValueGateDto=class{constructor(e,t){void 0!==e&&(this.value1=e),void 0!==t&&(this.value2=t)}},e.RandomBooleansDto=class{constructor(e){this.length=10,this.trueThreshold=.5,void 0!==e&&(this.length=e)}},e.TwoThresholdRandomGradientDto=class{},e.ThresholdBooleanListDto=class{},e.ThresholdGapsBooleanListDto=class{}}(Sq||(Sq={})),function(e){let t,i,r;!function(e){e.add="add",e.subtract="subtract",e.multiply="multiply",e.divide="divide",e.power="power",e.modulus="modulus"}(t=e.mathTwoNrOperatorEnum||(e.mathTwoNrOperatorEnum={})),function(e){e.absolute="absolute",e.negate="negate",e.ln="ln",e.log10="log10",e.tenPow="tenPow",e.round="round",e.floor="floor",e.ceil="ceil",e.sqrt="sqrt",e.sin="sin",e.cos="cos",e.tan="tan",e.asin="asin",e.acos="acos",e.atan="atan",e.log="log",e.exp="exp",e.radToDeg="radToDeg",e.degToRad="degToRad"}(i=e.mathOneNrOperatorEnum||(e.mathOneNrOperatorEnum={})),function(e){e.easeInSine="easeInSine",e.easeOutSine="easeOutSine",e.easeInOutSine="easeInOutSine",e.easeInQuad="easeInQuad",e.easeOutQuad="easeOutQuad",e.easeInOutQuad="easeInOutQuad",e.easeInCubic="easeInCubic",e.easeOutCubic="easeOutCubic",e.easeInOutCubic="easeInOutCubic",e.easeInQuart="easeInQuart",e.easeOutQuart="easeOutQuart",e.easeInOutQuart="easeInOutQuart",e.easeInQuint="easeInQuint",e.easeOutQuint="easeOutQuint",e.easeInOutQuint="easeInOutQuint",e.easeInExpo="easeInExpo",e.easeOutExpo="easeOutExpo",e.easeInOutExpo="easeInOutExpo",e.easeInCirc="easeInCirc",e.easeOutCirc="easeOutCirc",e.easeInOutCirc="easeInOutCirc",e.easeInElastic="easeInElastic",e.easeOutElastic="easeOutElastic",e.easeInOutElastic="easeInOutElastic",e.easeInBack="easeInBack",e.easeOutBack="easeOutBack",e.easeInOutBack="easeInOutBack",e.easeInBounce="easeInBounce",e.easeOutBounce="easeOutBounce",e.easeInOutBounce="easeInOutBounce"}(r=e.easeEnum||(e.easeEnum={})),e.ModulusDto=class{constructor(e,t){this.number=1,this.modulus=2,void 0!==e&&(this.number=e),void 0!==t&&(this.modulus=t)}},e.NumberDto=class{constructor(e){this.number=1,void 0!==e&&(this.number=e)}},e.EaseDto=class{constructor(e){this.x=.5,this.min=0,this.max=1,void 0!==e&&(this.x=e)}},e.RoundToDecimalsDto=class{constructor(e,t){this.number=1.123456,this.decimalPlaces=2,void 0!==e&&(this.number=e),void 0!==t&&(this.decimalPlaces=t)}},e.ActionOnTwoNumbersDto=class{constructor(e,t,i){this.first=1,this.second=1,void 0!==e&&(this.first=e),void 0!==t&&(this.second=t),void 0!==i&&(this.operation=i)}},e.TwoNumbersDto=class{constructor(e,t){this.first=1,this.second=2,void 0!==e&&(this.first=e),void 0!==t&&(this.second=t)}},e.ActionOnOneNumberDto=class{constructor(e,t){this.number=1,void 0!==e&&(this.number=e),void 0!==t&&(this.operation=t)}},e.RemapNumberDto=class{constructor(e,t,i,r,s){this.number=.5,this.fromLow=0,this.fromHigh=1,this.toLow=1,this.toHigh=2,void 0!==e&&(this.number=e),void 0!==t&&(this.fromLow=t),void 0!==i&&(this.fromHigh=i),void 0!==r&&(this.toLow=r),void 0!==s&&(this.toHigh=s)}},e.RandomNumberDto=class{constructor(e,t){this.low=0,this.high=1,void 0!==e&&(this.low=e),void 0!==t&&(this.high=t)}},e.RandomNumbersDto=class{constructor(e,t,i){this.low=0,this.high=1,this.count=10,void 0!==e&&(this.low=e),void 0!==t&&(this.high=t),void 0!==i&&(this.count=i)}},e.ToFixedDto=class{constructor(e,t){this.decimalPlaces=2,void 0!==e&&(this.number=e),void 0!==t&&(this.decimalPlaces=t)}}}(Tq||(Tq={})),function(e){e.PointDto=class{constructor(e){void 0!==e&&(this.point=e)}},e.PointXYZDto=class{constructor(e,t,i){this.x=0,this.y=0,this.z=0,void 0!==e&&(this.x=e),void 0!==t&&(this.y=t),void 0!==i&&(this.z=i)}},e.PointXYDto=class{constructor(e,t){this.x=0,this.y=0,void 0!==e&&(this.x=e),void 0!==t&&(this.y=t)}},e.PointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.TwoPointsDto=class{constructor(e,t){void 0!==e&&(this.point1=e),void 0!==t&&(this.point2=t)}},e.DrawPointDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.size=3,this.colours="#444444",this.updatable=!1,void 0!==e&&(this.point=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.size=i),void 0!==r&&(this.colours=r),void 0!==s&&(this.updatable=s),void 0!==n&&(this.pointMesh=n)}},e.DrawPointsDto=class{constructor(e,t,i,r,s,n){this.opacity=1,this.size=.1,this.colours="#444444",this.updatable=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.size=i),void 0!==r&&(this.colours=r),void 0!==s&&(this.updatable=s),void 0!==n&&(this.pointsMesh=n)}},e.TransformPointDto=class{constructor(e,t){void 0!==e&&(this.point=e),void 0!==t&&(this.transformation=t)}},e.TransformPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.transformation=t)}},e.TranslatePointsWithVectorsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.translations=t)}},e.TranslatePointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.translation=t)}},e.TranslateXYZPointsDto=class{constructor(e,t,i,r){this.x=0,this.y=1,this.z=0,void 0!==e&&(this.points=e),void 0!==t&&(this.x=t),void 0!==i&&(this.y=i),void 0!==r&&(this.z=r)}},e.ScalePointsCenterXYZDto=class{constructor(e,t,i){this.center=[0,0,0],this.scaleXyz=[1,1,1],void 0!==e&&(this.points=e),void 0!==t&&(this.center=t),void 0!==i&&(this.scaleXyz=i)}},e.RotatePointsCenterAxisDto=class{constructor(e,t,i,r){this.angle=90,this.axis=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.points=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.axis=i),void 0!==r&&(this.center=r)}},e.TransformsForPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.transformation=t)}},e.RemoveConsecutiveDuplicatesDto=class{constructor(e,t,i){this.tolerance=1e-7,this.checkFirstAndLast=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.tolerance=t),void 0!==i&&(this.checkFirstAndLast=i)}},e.ClosestPointFromPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.point=t)}},e.StartEndPointsDto=class{constructor(e,t){void 0!==e&&(this.startPoint=e),void 0!==t&&(this.endPoint=t)}},e.StartEndPointsListDto=class{constructor(e,t){void 0!==e&&(this.startPoint=e),void 0!==t&&(this.endPoints=t)}},e.MultiplyPointDto=class{constructor(e,t){void 0!==e&&(this.point=e),void 0!==t&&(this.amountOfPoints=t)}},e.SpiralDto=class{constructor(e,t,i,r,s){this.phi=.9,this.numberPoints=200,this.widening=3,this.radius=6,this.factor=1,void 0!==e&&(this.radius=e),void 0!==t&&(this.numberPoints=t),void 0!==i&&(this.widening=i),void 0!==r&&(this.factor=r),void 0!==s&&(this.phi=s)}},e.HexGridCentersDto=class{constructor(e,t,i,r,s){this.nrHexagonsY=21,this.nrHexagonsX=21,this.orientOnCenter=!1,this.pointsOnGround=!1,void 0!==e&&(this.nrHexagonsX=e),void 0!==t&&(this.nrHexagonsY=t),void 0!==i&&(this.radiusHexagon=i),void 0!==r&&(this.orientOnCenter=r),void 0!==s&&(this.pointsOnGround=s)}}}(Cq||(Cq={})),function(e){e.TextDto=class{constructor(e){this.text="Hello World",void 0!==e&&(this.text=e)}},e.TextSplitDto=class{constructor(e,t){this.text="a,b,c",this.separator=",",void 0!==e&&(this.text=e),void 0!==t&&(this.separator=t)}},e.TextReplaceDto=class{constructor(e,t,i){this.text="a-c",this.search="-",this.replaceWith="b",void 0!==e&&(this.text=e),void 0!==t&&(this.search=t),void 0!==i&&(this.replaceWith=i)}},e.TextJoinDto=class{constructor(e,t){this.separator=",",void 0!==e&&(this.list=e),void 0!==t&&(this.separator=t)}},e.ToStringDto=class{constructor(e){void 0!==e&&(this.item=e)}},e.ToStringEachDto=class{constructor(e){void 0!==e&&(this.list=e)}},e.TextFormatDto=class{constructor(e,t){this.text="Hello {0}",this.values=["World"],void 0!==e&&(this.text=e),void 0!==t&&(this.values=t)}}}(yq||(yq={})),function(e){e.RotationCenterAxisDto=class{constructor(e,t,i){this.angle=90,this.axis=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.angle=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.center=i)}},e.RotationCenterDto=class{constructor(e,t){this.angle=90,this.center=[0,0,0],void 0!==e&&(this.angle=e),void 0!==t&&(this.center=t)}},e.RotationCenterYawPitchRollDto=class{constructor(e,t,i,r){this.yaw=0,this.pitch=0,this.roll=0,this.center=[0,0,0],void 0!==e&&(this.yaw=e),void 0!==t&&(this.pitch=t),void 0!==i&&(this.roll=i),void 0!==r&&(this.center=r)}},e.ScaleXYZDto=class{constructor(e){this.scaleXyz=[1,1,1],void 0!==e&&(this.scaleXyz=e)}},e.ScaleCenterXYZDto=class{constructor(e,t){this.center=[0,0,0],this.scaleXyz=[1,1,1],void 0!==e&&(this.center=e),void 0!==t&&(this.scaleXyz=t)}},e.UniformScaleDto=class{constructor(e){this.scale=1,void 0!==e&&(this.scale=e)}},e.UniformScaleFromCenterDto=class{constructor(e,t){this.scale=1,this.center=[0,0,0],void 0!==e&&(this.scale=e),void 0!==t&&(this.center=t)}},e.TranslationXYZDto=class{constructor(e){this.translation=[0,0,0],void 0!==e&&(this.translation=e)}},e.TranslationsXYZDto=class{constructor(e){void 0!==e&&(this.translations=e)}}}(Eq||(Eq={})),function(e){e.TwoVectorsDto=class{constructor(e,t){void 0!==e&&(this.first=e),void 0!==t&&(this.second=t)}},e.VectorBoolDto=class{constructor(e){void 0!==e&&(this.vector=e)}},e.RemoveAllDuplicateVectorsDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.vectors=e),void 0!==t&&(this.tolerance=t)}},e.RemoveConsecutiveDuplicateVectorsDto=class{constructor(e,t,i){this.checkFirstAndLast=!1,this.tolerance=1e-7,void 0!==e&&(this.vectors=e),void 0!==t&&(this.checkFirstAndLast=t),void 0!==i&&(this.tolerance=i)}},e.VectorDto=class{constructor(e){void 0!==e&&(this.vector=e)}},e.RangeMaxDto=class{constructor(e){void 0!==e&&(this.max=e)}},e.VectorXYZDto=class{constructor(e,t,i){void 0!==e&&(this.x=e),void 0!==t&&(this.y=t),void 0!==i&&(this.z=i)}},e.VectorXYDto=class{constructor(e,t){void 0!==e&&(this.x=e),void 0!==t&&(this.y=t)}},e.SpanDto=class{constructor(e,t,i){this.step=.1,this.min=0,this.max=1,void 0!==e&&(this.step=e),void 0!==t&&(this.min=t),void 0!==i&&(this.max=i)}},e.SpanEaseItemsDto=class{constructor(e,t,i,r){this.nrItems=100,this.min=0,this.max=1,this.ease=Tq.easeEnum.easeInSine,this.intervals=!1,void 0!==e&&(this.nrItems=e),void 0!==t&&(this.min=t),void 0!==i&&(this.max=i),void 0!==r&&(this.ease=r)}},e.SpanLinearItemsDto=class{constructor(e,t,i){this.nrItems=100,this.min=0,this.max=1,void 0!==e&&(this.nrItems=e),void 0!==t&&(this.min=t),void 0!==i&&(this.max=i)}},e.RayPointDto=class{constructor(e,t,i){void 0!==e&&(this.point=e),void 0!==t&&(this.distance=t),void 0!==i&&(this.vector=i)}},e.VectorsDto=class{constructor(e){void 0!==e&&(this.vectors=e)}},e.FractionTwoVectorsDto=class{constructor(e,t,i){this.fraction=.5,void 0!==e&&(this.fraction=e),void 0!==t&&(this.first=t),void 0!==i&&(this.second=i)}},e.VectorScalarDto=class{constructor(e,t){void 0!==e&&(this.scalar=e),void 0!==t&&(this.vector=t)}},e.TwoVectorsReferenceDto=class{constructor(e,t,i){void 0!==e&&(this.reference=e),void 0!==t&&(this.first=t),void 0!==i&&(this.second=i)}}}(Pq||(Pq={}));var Mq=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class Oq extends vq{constructor(e,t,i,r,s,n){super(i),this.context=e,this.solidText=t,this.vector=i,this.jscadWorkerManager=r,this.manifoldWorkerManager=s,this.occWorkerManager=n,this.usedMaterials=[]}createOrUpdateSurfacesMesh(e,t,i,r,s,n){const o=()=>{const r=e.pop(),s=new bt;s.positions=r.positions,s.indices=r.indices,s.normals=r.normals,s.uvs=r.uvs;const n=[];e.forEach((e=>{const t=new bt;t.positions=e.positions,t.indices=e.indices,t.normals=e.normals,e.uvs&&(t.uvs=e.uvs),n.push(t)})),s.merge(n),s.applyToMesh(t,i)};if(t&&i)t.dispose(),o(),t.flipFaces(!1);else{let e=null;s&&(e=this.context.scene),t=new Yt(`surface${Math.random()}`,e),o(),t.flipFaces(!1),r&&(t.material=r)}return r&&(t.material=r),n&&(t.isVisible=!1),t.isPickable=!1,t}edgesRendering(e,t,i,r){e.enableEdgesRendering(),e.edgesWidth=t;const s=Array.isArray(r)?hc.v9.FromHexString(r[0]):hc.v9.FromHexString(r);e.color=s,e.edgesColor=new hc.ov(s.r,s.g,s.b,i)}drawLines(e){const t=[],i=[];return e.lines.forEach(((r,s)=>{let n;t.push([new hc.Pq(r.start[0],r.start[1],r.start[2]),new hc.Pq(r.end[0],r.end[1],r.end[2])]),n=Array.isArray(e.colours)&&e.colours.length===e.lines.length?hc.v9.FromHexString(e.colours[s]):Array.isArray(e.colours)?hc.v9.FromHexString(e.colours[0]):hc.v9.FromHexString(e.colours),i.push([new hc.ov(n.r,n.g,n.b,e.opacity),new hc.ov(n.r,n.g,n.b,e.opacity)])})),e.linesMesh&&e.updatable?e.linesMesh.getTotalVertices()/2===t.length?e.linesMesh=bl.CreateLineSystem(null,{lines:t,instance:e.linesMesh,colors:i,useVertexAlpha:!0,updatable:e.updatable},null):(e.linesMesh.dispose(),e.linesMesh=this.createLineSystemMesh(e.updatable,t,i)):e.linesMesh=this.createLineSystemMesh(e.updatable,t,i),this.edgesRendering(e.linesMesh,e.size,e.opacity,e.colours),e.linesMesh}drawPolylineClose(e){const t=e.polyline.points;return e.polyline.isClosed&&t.push(t[0]),this.drawPolyline(e.polylineMesh,t,e.updatable,e.size,e.opacity,e.colours)}drawCurve(e){const t=e.curve.tessellate();return this.drawPolyline(e.curveMesh,t,e.updatable,e.size,e.opacity,e.colours)}drawSurface(e){const t=e.surface.tessellate(),i={positions:[],indices:[],normals:[]};let r=0;t.faces.forEach((e=>{r=this.parseFaces(e,t,i,r)}));const s=new Cb("pbr"+Math.random(),this.context.scene);return s.baseColor=hc.v9.FromHexString(Array.isArray(e.colours)?e.colours[0]:e.colours),s.metallic=1,s.roughness=.6,s.alpha=e.opacity,s.alphaMode=1,s.backFaceCulling=!1,s.doubleSided=!0,this.createOrUpdateSurfacesMesh([i],e.surfaceMesh,e.updatable,s,!0,e.hidden)}drawSurfaces(e){const t=[];e.surfaces.forEach((e=>{t.push(e.tessellate())}));const i={positions:[],indices:[],normals:[]};let r=0;t.forEach((e=>{e.faces.forEach((t=>{r=this.parseFaces(t,e,i,r)}))}));const s=new Cb("pbr"+Math.random(),this.context.scene);return s.baseColor=hc.v9.FromHexString(Array.isArray(e.colours)?e.colours[0]:e.colours),s.metallic=1,s.roughness=.6,s.alpha=e.opacity,s.alphaMode=1,s.backFaceCulling=!0,s.doubleSided=!1,this.createOrUpdateSurfacesMesh([i],e.surfacesMesh,e.updatable,s,!0,e.hidden)}drawSurfacesMultiColour(e){return e.surfacesMesh&&e.updatable&&e.surfacesMesh.getChildren().forEach((e=>e.dispose())),e.surfacesMesh=new Yt(`ColouredSurfaces${Math.random()}`,this.context.scene),Array.isArray(e.colours)?e.surfaces.forEach(((t,i)=>{const r=this.drawSurface({surface:t,colours:e.colours[i]?e.colours[i]:e.colours[0],updatable:e.updatable,opacity:e.opacity,hidden:e.hidden});e.surfacesMesh.addChild(r)})):e.surfaces.forEach(((t,i)=>{const r=this.drawSurface({surface:t,colours:e.colours,updatable:e.updatable,opacity:e.opacity,hidden:e.hidden});e.surfacesMesh.addChild(r)})),e.surfacesMesh}drawCurves(e){const t=e.curves.map((e=>e.tessellate()));return this.drawPolylines(e.curvesMesh,t,e.updatable,e.size,e.opacity,e.colours)}drawPolyline(e,t,i,r,s,n){return this.drawPolylines(e,[t],i,r,s,n)}drawPolylinesWithColours(e){let t=e.colours;const i=e.polylines.map(((e,i)=>{const r=e.points;return e.isClosed&&r.push(r[0]),e.color&&(Array.isArray(t)||(t=[]),Array.isArray(e.color)?t[i]=hc.v9.FromArray(e.color).toHexString():t[i]=e.color),r}));return this.drawPolylines(e.polylinesMesh,i,e.updatable,e.size,e.opacity,t)}drawPolylines(e,t,i,r,s,n){var o;const a=[];if(t&&t.length>0){t.forEach((e=>{const t=e.map((e=>2===e.length?[e[0],e[1],0]:e));a.push(t.flat())}));const l=r/100,h=Array.isArray(n)?hc.v9.FromHexString(n[0]):hc.v9.FromHexString(n);if(e&&i){if(!(null===(o=null==e?void 0:e.metadata)||void 0===o?void 0:o.linesForRenderLengths.some(((e,t)=>e!==a[t].length))))return e.setPoints(a),e;e.dispose(),(e=this.createGreasedPolylines(i,a,l,h,s)).metadata={linesForRenderLengths:a.map((e=>e.length))}}else(e=this.createGreasedPolylines(i,a,l,h,s)).metadata={linesForRenderLengths:a.map((e=>e.length))};return e}}createGreasedPolylines(e,t,i,r,s){const n=ME(`lineSystem${Math.random()}`,{points:t,updatable:e},{width:i,color:r},this.context.scene);return n.material.alpha=s,n}localAxes(e,t,i,r,s){const n=bl.CreateLines("pilot_local_axisX"+Math.random(),{points:[hc.Pq.Zero(),new hc.Pq(e,0,0),new hc.Pq(.95*e,.05*e,0),new hc.Pq(e,0,0),new hc.Pq(.95*e,-.05*e,0)]},t),o=hc.v9.FromHexString(i);n.color=o;const a=bl.CreateLines("pilot_local_axisY"+Math.random(),{points:[hc.Pq.Zero(),new hc.Pq(0,e,0),new hc.Pq(-.05*e,.95*e,0),new hc.Pq(0,e,0),new hc.Pq(.05*e,.95*e,0)]},t),l=hc.v9.FromHexString(r);a.color=l;const h=bl.CreateLines("pilot_local_axisZ"+Math.random(),{points:[hc.Pq.Zero(),new hc.Pq(0,0,e),new hc.Pq(0,-.05*e,.95*e),new hc.Pq(0,0,e),new hc.Pq(0,.05*e,.95*e)]},t),c=hc.v9.FromHexString(s);h.color=c;const u=new Yt("local_origin"+Math.random(),t);return u.isVisible=!1,n.parent=u,a.parent=u,h.parent=u,u}drawPoint(e){const t=[e.point];let i=[];return i=Array.isArray(e.colours)?e.colours:[e.colours],e.pointMesh&&e.updatable?this.updatePointsInstances(e.pointMesh,t):e.pointMesh=this.createPointSpheresMesh(`poinsMesh${Math.random()}`,t,i,e.opacity,e.size,e.updatable),e.pointMesh}drawPoints(e){const t=e.points;let i=[];return Array.isArray(e.colours)?(i=e.colours,1===i.length&&(i=e.points.map((()=>i[0])))):i=e.points.map((()=>e.colours)),e.pointsMesh&&e.updatable?e.pointsMesh.getChildMeshes().length===t.length?this.updatePointsInstances(e.pointsMesh,t):(e.pointsMesh.dispose(),e.pointsMesh=this.createPointSpheresMesh(`pointsMesh${Math.random()}`,t,i,e.opacity,e.size,e.updatable)):e.pointsMesh=this.createPointSpheresMesh(`pointsMesh${Math.random()}`,t,i,e.opacity,e.size,e.updatable),e.pointsMesh}updatePointsInstances(e,t){const i=e.getChildMeshes(),r={};t.forEach(((e,t)=>{r[t]=new hc.Pq(e[0],e[1],e[2])})),i.forEach((e=>{e.position=r[e.metadata.index]}))}createPointSpheresMesh(e,t,i,r,s,n){const o=t.map(((e,t)=>({position:e,color:i[t],index:t}))),a=Array.from(new Set(i)),l=a.map(((e,t)=>{const i=new Un(`mat${Math.random()}`,this.context.scene);i.disableLighting=!0,i.emissiveColor=hc.v9.FromHexString(e),i.alpha=r;const s=o.filter((t=>t.color===e));return{hex:a,material:i,positions:s}})),h=new Yt(e,this.context.scene);return l.forEach((e=>{const t=e.positions.length>1e3?1:6;let i;i=e.positions.length<1e4?bl.CreateSphere(`point${Math.random()}`,{diameter:s,segments:t,updatable:n},this.context.scene):bl.CreateBox(`point${Math.random()}`,{size:s,updatable:n},this.context.scene),i.material=e.material,i.isVisible=!1,e.positions.forEach(((e,t)=>{const r=i.createInstance(`point-${t}-${Math.random()}`);r.position=new hc.Pq(e.position[0],e.position[1],e.position[2]),r.metadata={index:e.index},r.parent=h,r.isVisible=!0}))})),h}drawSolidOrPolygonMesh(e){return Mq(this,void 0,void 0,(function*(){const t=yield this.jscadWorkerManager.genericCallToWorkerPromise("shapeToMesh",e);let i,r;i=e.jscadMesh&&e.updatable?e.jscadMesh:new Yt(`jscadMesh${Math.random()}`,this.context.scene),r=e.mesh.color&&e.mesh.color.length>0?hc.v9.FromArray(e.mesh.color).toHexString():Array.isArray(e.colours)?e.colours[0]:e.colours;const s=this.makeMesh(Object.assign(Object.assign({},e),{colour:r}),i,t);return e.jscadMesh=s,s}))}makeMesh(e,t,i){this.createMesh(i.positions,i.indices,i.normals,t,i.transforms,e.updatable),t.material=new Cb(`jscadMaterial${Math.random()}`,this.context.scene),t.flipFaces(!1);const r=t.material;return r.baseColor=hc.v9.FromHexString(e.colour),r.metallic=1,r.roughness=.6,r.alpha=e.opacity,r.alphaMode=1,r.backFaceCulling=!0,r.zOffset=0,t.isPickable=!1,e.hidden&&(t.isVisible=!1),t}drawSolidOrPolygonMeshes(e){return Mq(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapesToMeshes",e).then((t=>{let i;e.jscadMesh&&e.updatable?(i=e.jscadMesh,i.getChildMeshes().forEach((e=>{e.dispose(),i.removeChild(e)}))):i=new Yt("local_origin"+Math.random(),this.context.scene),i.isVisible=!1;const r=Array.isArray(e.colours)&&e.colours.length===t.length,s=Array.isArray(e.colours);return t.map(((t,n)=>{const o=new Yt(`jscadMesh${Math.random()}`,this.context.scene);let a;a=t.color?hc.v9.FromArray(t.color).toHexString():r?e.colours[n]:s?e.colours[0]:e.colours,this.makeMesh(Object.assign(Object.assign({},e),{colour:a}),o,t).parent=i})),e.jscadMesh=i,i}))}))}drawPath(e){return Mq(this,void 0,void 0,(function*(){return new Promise((t=>{if(e.path.points&&e.path.isClosed){const t=e.path.points[0];e.path.points.push([t[0],0,t[1]])}let i=e.colour;e.path.color&&(i=hc.v9.FromArray(e.path.color).toHexString()),t(this.drawPolyline(e.pathMesh,e.path.points,e.updatable,e.width,e.opacity,i))}))}))}drawManifoldsOrCrossSections(e){return Mq(this,void 0,void 0,(function*(){const t=(yield this.manifoldWorkerManager.genericCallToWorkerPromise("decomposeManifoldsOrCrossSections",e)).map((t=>this.handleDecomposedManifold(e,t))),i=new Yt("manifoldMeshContainer"+Math.random(),this.context.scene);return t.forEach((e=>{e.parent=i})),i}))}drawManifoldOrCrossSection(e){return Mq(this,void 0,void 0,(function*(){const t=yield this.manifoldWorkerManager.genericCallToWorkerPromise("decomposeManifoldOrCrossSection",e);return this.handleDecomposedManifold(e,t)}))}drawShape(e){return Mq(this,void 0,void 0,(function*(){const t=Object.assign({},e);e.faceMaterial&&delete e.faceMaterial;const i=yield this.occWorkerManager.genericCallToWorkerPromise("shapeToMesh",e);return this.handleDecomposedMesh(e,i,t)}))}drawShapes(e){return Mq(this,void 0,void 0,(function*(){const t=Object.assign({},e);e.faceMaterial&&delete e.faceMaterial;const i=yield this.occWorkerManager.genericCallToWorkerPromise("shapesToMeshes",e),r=yield Promise.all(i.map((i=>Mq(this,void 0,void 0,(function*(){return this.handleDecomposedMesh(e,i,t)}))))),s=new Yt("shapesMeshContainer"+Math.random(),this.context.scene);return r.forEach((e=>{e.parent=s})),s}))}handleDecomposedMesh(e,t,i){return Mq(this,void 0,void 0,(function*(){const r=new Yt("brepMesh"+Math.random(),this.context.scene);let s;if(r.isVisible=!1,e.drawFaces&&t&&t.faceList&&t.faceList.length){let n;if(i.faceMaterial)n=i.faceMaterial;else{const t=Array.isArray(e.faceColour)?e.faceColour[0]:e.faceColour,i=e.faceOpacity,r=e.drawEdges?2:0,s=this.usedMaterials.find((e=>e.sceneId===this.context.scene.uid&&e.hex===t&&e.alpha===i&&e.zOffset===r));if(this.usedMaterials=this.usedMaterials.filter((e=>e.sceneId===this.context.scene.uid)),s)n=s.material;else{const e=new Cb("pbr"+Math.random(),this.context.scene);e.baseColor=hc.v9.FromHexString(t),e.metallic=1,e.roughness=.6,e.alpha=i,e.alphaMode=1,e.backFaceCulling=!0,e.doubleSided=!1,e.zOffset=r,this.usedMaterials.push({sceneId:this.context.scene.uid,hex:t,alpha:i,zOffset:r,material:e}),n=e}}const o=t.faceList.map((e=>({positions:e.vertex_coord,normals:e.normal_coord,indices:e.tri_indexes,uvs:e.uvs})));this.createOrUpdateSurfacesMesh(o,s,!1,n,!0,!1).parent=r}if(e.drawEdges&&t&&t.edgeList&&t.edgeList.length){const i=[];t.edgeList.forEach((e=>{const t=e.vertex_coord.filter((e=>void 0!==e));i.push(t)})),this.drawPolylines(s,i,!1,e.edgeWidth,e.edgeOpacity,e.edgeColour).parent=r}if(e.drawVertices&&t&&t.pointsList&&t.pointsList.length&&(this.drawPoints({pointsMesh:s,points:t.pointsList,opacity:1,size:e.vertexSize,colours:e.vertexColour,updatable:!1}).parent=r),e.drawEdgeIndexes){const i=t.edgeList.map((t=>Mq(this,void 0,void 0,(function*(){let i=t.middle_point;void 0===i&&(i=this.computeEdgeMiddlePos(t));const r=new nX.TextDto;return r.text=`${t.edge_index+1}`,r.height=e.edgeIndexHeight,r.lineSpacing=1.5,(yield this.solidText.createVectorText(r)).map((e=>e.map((e=>[e[0],e[1]+.05,0])).map((e=>this.vector.add({first:e,second:i})))))})))),s=yield Promise.all(i),n=this.drawPolylines(null,s.flat(),!1,.2,1,e.edgeIndexColour);n.parent=r,n.material.zOffset=-2}if(e.drawFaceIndexes){const i=t.faceList.map((t=>Mq(this,void 0,void 0,(function*(){let i=t.center_point;void 0===i&&(i=this.computeFaceMiddlePos(t.vertex_coord_vec));const r=new nX.TextDto;return r.text=`${t.face_index}`,r.height=e.faceIndexHeight,r.lineSpacing=1.5,(yield this.solidText.createVectorText(r)).map((e=>e.map((e=>[e[0],e[1]+.05,0])).map((e=>this.vector.add({first:e,second:i})))))})))),s=yield Promise.all(i),n=this.drawPolylines(null,s.flat(),!1,.2,1,e.faceIndexColour);n.parent=r,e.drawEdges&&(n.material.zOffset=-2)}return r}))}handleDecomposedManifold(e,t){if(t.vertProperties){const i=t,r=new Yt(`manifoldMesh-${Math.random()}`,this.context.scene),s=new bt;s.indices=i.triVerts.length>65535?new Uint32Array(i.triVerts):new Uint16Array(i.triVerts);for(let e=0;e({points:e.map((e=>[e[0],e[1],0])),isClosed:!0})));return this.drawPolylinesWithColours({polylinesMesh:void 0,polylines:r,updatable:!1,size:e.crossSectionWidth,opacity:e.crossSectionOpacity,colours:e.crossSectionColour}).parent=i,i}}createLineSystemMesh(e,t,i){return bl.CreateLineSystem(`lines${Math.random()}`,{lines:t,colors:i,useVertexAlpha:!0,updatable:e},this.context.scene)}createMesh(e,t,i,r,s,n){const o=new bt;o.positions=e,o.indices=t,bt.ComputeNormals(e,t,i,{useRightHandedSystem:!0}),o.normals=i,o.applyToMesh(r,n),r.setPreTransformMatrix(hc.uq.FromArray(s))}parseFaces(e,t,i,r){return e.reverse().forEach((e=>{const s=t.normals[e];i.normals.push(s[0],s[1],s[2]);const n=t.points[e];i.positions.push(n[0],n[1],n[2]),i.indices.push(r),r++})),r}}class Dq{static get version(){return"1.3.9"}static toString(){return"JavaScript Expression Parser (JSEP) v"+Dq.version}static addUnaryOp(e){return Dq.max_unop_len=Math.max(e.length,Dq.max_unop_len),Dq.unary_ops[e]=1,Dq}static addBinaryOp(e,t,i){return Dq.max_binop_len=Math.max(e.length,Dq.max_binop_len),Dq.binary_ops[e]=t,i?Dq.right_associative.add(e):Dq.right_associative.delete(e),Dq}static addIdentifierChar(e){return Dq.additional_identifier_chars.add(e),Dq}static addLiteral(e,t){return Dq.literals[e]=t,Dq}static removeUnaryOp(e){return delete Dq.unary_ops[e],e.length===Dq.max_unop_len&&(Dq.max_unop_len=Dq.getMaxKeyLen(Dq.unary_ops)),Dq}static removeAllUnaryOps(){return Dq.unary_ops={},Dq.max_unop_len=0,Dq}static removeIdentifierChar(e){return Dq.additional_identifier_chars.delete(e),Dq}static removeBinaryOp(e){return delete Dq.binary_ops[e],e.length===Dq.max_binop_len&&(Dq.max_binop_len=Dq.getMaxKeyLen(Dq.binary_ops)),Dq.right_associative.delete(e),Dq}static removeAllBinaryOps(){return Dq.binary_ops={},Dq.max_binop_len=0,Dq}static removeLiteral(e){return delete Dq.literals[e],Dq}static removeAllLiterals(){return Dq.literals={},Dq}get char(){return this.expr.charAt(this.index)}get code(){return this.expr.charCodeAt(this.index)}constructor(e){this.expr=e,this.index=0}static parse(e){return new Dq(e).parse()}static getMaxKeyLen(e){return Math.max(0,...Object.keys(e).map((e=>e.length)))}static isDecimalDigit(e){return e>=48&&e<=57}static binaryPrecedence(e){return Dq.binary_ops[e]||0}static isIdentifierStart(e){return e>=65&&e<=90||e>=97&&e<=122||e>=128&&!Dq.binary_ops[String.fromCharCode(e)]||Dq.additional_identifier_chars.has(String.fromCharCode(e))}static isIdentifierPart(e){return Dq.isIdentifierStart(e)||Dq.isDecimalDigit(e)}throwError(e){const t=new Error(e+" at character "+this.index);throw t.index=this.index,t.description=e,t}runHook(e,t){if(Dq.hooks[e]){const i={context:this,node:t};return Dq.hooks.run(e,i),i.node}return t}searchHook(e){if(Dq.hooks[e]){const t={context:this};return Dq.hooks[e].find((function(e){return e.call(t.context,t),t.node})),t.node}}gobbleSpaces(){let e=this.code;for(;e===Dq.SPACE_CODE||e===Dq.TAB_CODE||e===Dq.LF_CODE||e===Dq.CR_CODE;)e=this.expr.charCodeAt(++this.index);this.runHook("gobble-spaces")}parse(){this.runHook("before-all");const e=this.gobbleExpressions(),t=1===e.length?e[0]:{type:Dq.COMPOUND,body:e};return this.runHook("after-all",t)}gobbleExpressions(e){let t,i,r=[];for(;this.index0;){if(Dq.binary_ops.hasOwnProperty(e)&&(!Dq.isIdentifierStart(this.code)||this.index+e.lengths.right_a&&e.right_a?i>e.prec:i<=e.prec;for(;r.length>2&&a(r[r.length-2]);)o=r.pop(),t=r.pop().value,n=r.pop(),e={type:Dq.BINARY_EXP,operator:t,left:n,right:o},r.push(e);e=this.gobbleToken(),e||this.throwError("Expected expression after "+l),r.push(s,e)}for(a=r.length-1,e=r[a];a>1;)e={type:Dq.BINARY_EXP,operator:r[a-1].value,left:r[a-2],right:e},a-=2;return e}gobbleToken(){let e,t,i,r;if(this.gobbleSpaces(),r=this.searchHook("gobble-token"),r)return this.runHook("after-token",r);if(e=this.code,Dq.isDecimalDigit(e)||e===Dq.PERIOD_CODE)return this.gobbleNumericLiteral();if(e===Dq.SQUOTE_CODE||e===Dq.DQUOTE_CODE)r=this.gobbleStringLiteral();else if(e===Dq.OBRACK_CODE)r=this.gobbleArray();else{for(t=this.expr.substr(this.index,Dq.max_unop_len),i=t.length;i>0;){if(Dq.unary_ops.hasOwnProperty(t)&&(!Dq.isIdentifierStart(this.code)||this.index+t.length=t.length&&this.throwError("Unexpected token "+String.fromCharCode(e));break}if(s===Dq.COMMA_CODE){if(this.index++,r++,r!==t.length)if(e===Dq.CPAREN_CODE)this.throwError("Unexpected token ,");else if(e===Dq.CBRACK_CODE)for(let e=t.length;e{if("object"!=typeof e||!e.name||!e.init)throw new Error("Invalid JSEP plugin format");this.registered[e.name]||(e.init(this.jsep),this.registered[e.name]=e)}))}}(Dq),COMPOUND:"Compound",SEQUENCE_EXP:"SequenceExpression",IDENTIFIER:"Identifier",MEMBER_EXP:"MemberExpression",LITERAL:"Literal",THIS_EXP:"ThisExpression",CALL_EXP:"CallExpression",UNARY_EXP:"UnaryExpression",BINARY_EXP:"BinaryExpression",ARRAY_EXP:"ArrayExpression",TAB_CODE:9,LF_CODE:10,CR_CODE:13,SPACE_CODE:32,PERIOD_CODE:46,COMMA_CODE:44,SQUOTE_CODE:39,DQUOTE_CODE:34,OPAREN_CODE:40,CPAREN_CODE:41,OBRACK_CODE:91,CBRACK_CODE:93,QUMARK_CODE:63,SEMCOL_CODE:59,COLON_CODE:58,unary_ops:{"-":1,"!":1,"~":1,"+":1},binary_ops:{"||":1,"&&":2,"|":3,"^":4,"&":5,"==":6,"!=":6,"===":6,"!==":6,"<":7,">":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":10,"/":10,"%":10},right_associative:new Set,additional_identifier_chars:new Set(["$","_"]),literals:{true:!0,false:!1,null:null},this_str:"this"}),Dq.max_unop_len=Dq.getMaxKeyLen(Dq.unary_ops),Dq.max_binop_len=Dq.getMaxKeyLen(Dq.binary_ops);const Nq=e=>new Dq(e).parse(),Fq=Object.getOwnPropertyNames(class{});Object.getOwnPropertyNames(Dq).filter((e=>!Fq.includes(e)&&void 0===Nq[e])).forEach((e=>{Nq[e]=Dq[e]})),Nq.Jsep=Dq;var Lq={name:"ternary",init(e){e.hooks.add("after-expression",(function(t){if(t.node&&this.code===e.QUMARK_CODE){this.index++;const i=t.node,r=this.gobbleExpression();if(r||this.throwError("Expected expression"),this.gobbleSpaces(),this.code===e.COLON_CODE){this.index++;const s=this.gobbleExpression();if(s||this.throwError("Expected expression"),t.node={type:"ConditionalExpression",test:i,consequent:r,alternate:s},i.operator&&e.binary_ops[i.operator]<=.9){let r=i;for(;r.right.operator&&e.binary_ops[r.right.operator]<=.9;)r=r.right;t.node.test=r.right,r.right=t.node,t.node=i}}else this.throwError("Expected :")}}))}};Nq.plugins.register(Lq);var Bq={name:"regex",init(e){e.hooks.add("gobble-token",(function(t){if(47===this.code){const i=++this.index;let r=!1;for(;this.index=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57))break;n+=this.char}try{s=new RegExp(r,n)}catch(e){this.throwError(e.message)}return t.node={type:e.LITERAL,value:s,raw:this.expr.slice(i-1,this.index)},t.node=this.gobbleTokenProperty(t.node),t.node}this.code===e.OBRACK_CODE?r=!0:r&&this.code===e.CBRACK_CODE&&(r=!1),this.index+=92===this.code?2:1}this.throwError("Unclosed Regex")}}))}};const Vq={name:"assignment",assignmentOperators:new Set(["=","*=","**=","/=","%=","+=","-=","<<=",">>=",">>>=","&=","^=","|="]),updateOperators:[43,45],assignmentPrecedence:.9,init(e){const t=[e.IDENTIFIER,e.MEMBER_EXP];function i(e){Vq.assignmentOperators.has(e.operator)?(e.type="AssignmentExpression",i(e.left),i(e.right)):e.operator||Object.values(e).forEach((e=>{e&&"object"==typeof e&&i(e)}))}Vq.assignmentOperators.forEach((t=>e.addBinaryOp(t,Vq.assignmentPrecedence,!0))),e.hooks.add("gobble-token",(function(e){const i=this.code;Vq.updateOperators.some((e=>e===i&&e===this.expr.charCodeAt(this.index+1)))&&(this.index+=2,e.node={type:"UpdateExpression",operator:43===i?"++":"--",argument:this.gobbleTokenProperty(this.gobbleIdentifier()),prefix:!0},e.node.argument&&t.includes(e.node.argument.type)||this.throwError(`Unexpected ${e.node.operator}`))})),e.hooks.add("after-token",(function(e){if(e.node){const i=this.code;Vq.updateOperators.some((e=>e===i&&e===this.expr.charCodeAt(this.index+1)))&&(t.includes(e.node.type)||this.throwError(`Unexpected ${e.node.operator}`),this.index+=2,e.node={type:"UpdateExpression",operator:43===i?"++":"--",argument:e.node,prefix:!1})}})),e.hooks.add("after-expression",(function(e){e.node&&i(e.node)}))}};Nq.plugins.register(Bq,Vq),Nq.addUnaryOp("typeof"),Nq.addLiteral("null",null),Nq.addLiteral("undefined",void 0);const kq={evalAst(e,t){switch(e.type){case"BinaryExpression":case"LogicalExpression":return kq.evalBinaryExpression(e,t);case"Compound":return kq.evalCompound(e,t);case"ConditionalExpression":return kq.evalConditionalExpression(e,t);case"Identifier":return kq.evalIdentifier(e,t);case"Literal":return kq.evalLiteral(e,t);case"MemberExpression":return kq.evalMemberExpression(e,t);case"UnaryExpression":return kq.evalUnaryExpression(e,t);case"ArrayExpression":return kq.evalArrayExpression(e,t);case"CallExpression":return kq.evalCallExpression(e,t);case"AssignmentExpression":return kq.evalAssignmentExpression(e,t);default:throw SyntaxError("Unexpected expression",e)}},evalBinaryExpression:(e,t)=>({"||":(e,t)=>e||t(),"&&":(e,t)=>e&&t(),"|":(e,t)=>e|t(),"^":(e,t)=>e^t(),"&":(e,t)=>e&t(),"==":(e,t)=>e==t(),"!=":(e,t)=>e!=t(),"===":(e,t)=>e===t(),"!==":(e,t)=>e!==t(),"<":(e,t)=>e":(e,t)=>e>t(),"<=":(e,t)=>e<=t(),">=":(e,t)=>e>=t(),"<<":(e,t)=>e<>":(e,t)=>e>>t(),">>>":(e,t)=>e>>>t(),"+":(e,t)=>e+t(),"-":(e,t)=>e-t(),"*":(e,t)=>e*t(),"/":(e,t)=>e/t(),"%":(e,t)=>e%t()}[e.operator](kq.evalAst(e.left,t),(()=>kq.evalAst(e.right,t)))),evalCompound(e,t){let i;for(let r=0;rkq.evalAst(e.test,t)?kq.evalAst(e.consequent,t):kq.evalAst(e.alternate,t),evalIdentifier(e,t){if(e.name in t)return t[e.name];throw ReferenceError(`${e.name} is not defined`)},evalLiteral:e=>e.value,evalMemberExpression(e,t){if("Identifier"===e.property.type&&"constructor"===e.property.name||"Identifier"===e.object.type&&"constructor"===e.object.name)throw new Error("'constructor' property is disabled");const i=e.computed?kq.evalAst(e.property):e.property.name,r=kq.evalAst(e.object,t),s=r[i];if("function"==typeof s){if(r===Function&&"bind"===i)throw new Error("Function.prototype.bind is disabled");if(r===Function&&("call"===i||"apply"===i))throw new Error("Function.prototype.call and Function.prototype.apply are disabled");return s===Function?s:s.bind(r)}return s},evalUnaryExpression:(e,t)=>({"-":e=>-kq.evalAst(e,t),"!":e=>!kq.evalAst(e,t),"~":e=>~kq.evalAst(e,t),"+":e=>+kq.evalAst(e,t),typeof:e=>typeof kq.evalAst(e,t)}[e.operator](e.argument)),evalArrayExpression:(e,t)=>e.elements.map((e=>kq.evalAst(e,t))),evalCallExpression(e,t){const i=e.arguments.map((e=>kq.evalAst(e,t))),r=kq.evalAst(e.callee,t);if(r===Function)throw new Error("Function constructor is disabled");return r(...i)},evalAssignmentExpression(e,t){if("Identifier"!==e.left.type)throw SyntaxError("Invalid left-hand side in assignment");const i=e.left.name;if("__proto__"===i)throw new Error("Assignment to __proto__ is disabled");const r=kq.evalAst(e.right,t);return t[i]=r,t[i]}};function Uq(e,t){return(e=e.slice()).push(t),e}function Gq(e,t){return(t=t.slice()).unshift(e),t}class zq extends Error{constructor(e){super('JSONPath should not be called with "new" (it prevents return of (unwrapped) scalar values)'),this.avoidNew=!0,this.value=e,this.name="NewError"}}function Wq(e,t,i,r,s){if(!(this instanceof Wq))try{return new Wq(e,t,i,r,s)}catch(e){if(!e.avoidNew)throw e;return e.value}"string"==typeof e&&(s=r,r=i,i=t,t=e,e=null);const n=e&&"object"==typeof e;if(e=e||{},this.json=e.json||i,this.path=e.path||t,this.resultType=e.resultType||"value",this.flatten=e.flatten||!1,this.wrap=!Object.hasOwn(e,"wrap")||e.wrap,this.sandbox=e.sandbox||{},this.eval=void 0===e.eval?"safe":e.eval,this.ignoreEvalErrors=void 0!==e.ignoreEvalErrors&&e.ignoreEvalErrors,this.parent=e.parent||null,this.parentProperty=e.parentProperty||null,this.callback=e.callback||r||null,this.otherTypeCallback=e.otherTypeCallback||s||function(){throw new TypeError("You must supply an otherTypeCallback callback option with the @other() operator.")},!1!==e.autostart){const r={path:n?e.path:t};n?"json"in e&&(r.json=e.json):r.json=i;const s=this.evaluate(r);if(!s||"object"!=typeof s)throw new zq(s);return s}}Wq.prototype.evaluate=function(e,t,i,r){let s=this.parent,n=this.parentProperty,{flatten:o,wrap:a}=this;if(this.currResultType=this.resultType,this.currEval=this.eval,this.currSandbox=this.sandbox,i=i||this.callback,this.currOtherTypeCallback=r||this.otherTypeCallback,t=t||this.json,(e=e||this.path)&&"object"==typeof e&&!Array.isArray(e)){if(!e.path&&""!==e.path)throw new TypeError('You must supply a "path" property when providing an object argument to JSONPath.evaluate().');if(!Object.hasOwn(e,"json"))throw new TypeError('You must supply a "json" property when providing an object argument to JSONPath.evaluate().');({json:t}=e),o=Object.hasOwn(e,"flatten")?e.flatten:o,this.currResultType=Object.hasOwn(e,"resultType")?e.resultType:this.currResultType,this.currSandbox=Object.hasOwn(e,"sandbox")?e.sandbox:this.currSandbox,a=Object.hasOwn(e,"wrap")?e.wrap:a,this.currEval=Object.hasOwn(e,"eval")?e.eval:this.currEval,i=Object.hasOwn(e,"callback")?e.callback:i,this.currOtherTypeCallback=Object.hasOwn(e,"otherTypeCallback")?e.otherTypeCallback:this.currOtherTypeCallback,s=Object.hasOwn(e,"parent")?e.parent:s,n=Object.hasOwn(e,"parentProperty")?e.parentProperty:n,e=e.path}if(s=s||null,n=n||null,Array.isArray(e)&&(e=Wq.toPathString(e)),!e&&""!==e||!t)return;const l=Wq.toPathArray(e);"$"===l[0]&&l.length>1&&l.shift(),this._hasParentSelector=null;const h=this._trace(l,t,["$"],s,n,i).filter((function(e){return e&&!e.isParentSelector}));return h.length?a||1!==h.length||h[0].hasArrExpr?h.reduce(((e,t)=>{const i=this._getPreferredOutput(t);return o&&Array.isArray(i)?e=e.concat(i):e.push(i),e}),[]):this._getPreferredOutput(h[0]):a?[]:void 0},Wq.prototype._getPreferredOutput=function(e){const t=this.currResultType;switch(t){case"all":{const t=Array.isArray(e.path)?e.path:Wq.toPathArray(e.path);return e.pointer=Wq.toPointer(t),e.path="string"==typeof e.path?e.path:Wq.toPathString(e.path),e}case"value":case"parent":case"parentProperty":return e[t];case"path":return Wq.toPathString(e[t]);case"pointer":return Wq.toPointer(e.path);default:throw new TypeError("Unknown result type")}},Wq.prototype._handleCallback=function(e,t,i){if(t){const r=this._getPreferredOutput(e);e.path="string"==typeof e.path?e.path:Wq.toPathString(e.path),t(r,i,e)}},Wq.prototype._trace=function(e,t,i,r,s,n,o,a){let l;if(!e.length)return l={path:i,value:t,parent:r,parentProperty:s,hasArrExpr:o},this._handleCallback(l,n,"value"),l;const h=e[0],c=e.slice(1),u=[];function d(e){Array.isArray(e)?e.forEach((e=>{u.push(e)})):u.push(e)}if(("string"!=typeof h||a)&&t&&Object.hasOwn(t,h))d(this._trace(c,t[h],Uq(i,h),t,h,n,o));else if("*"===h)this._walk(t,(e=>{d(this._trace(c,t[e],Uq(i,e),t,e,n,!0,!0))}));else if(".."===h)d(this._trace(c,t,i,r,s,n,o)),this._walk(t,(r=>{"object"==typeof t[r]&&d(this._trace(e.slice(),t[r],Uq(i,r),t,r,n,!0))}));else{if("^"===h)return this._hasParentSelector=!0,{path:i.slice(0,-1),expr:c,isParentSelector:!0};if("~"===h)return l={path:Uq(i,h),value:s,parent:r,parentProperty:null},this._handleCallback(l,n,"property"),l;if("$"===h)d(this._trace(c,t,i,null,null,n,o));else if(/^(-?\d*):(-?\d*):?(\d*)$/u.test(h))d(this._slice(h,c,t,i,r,s,n));else if(0===h.indexOf("?(")){if(!1===this.currEval)throw new Error("Eval [?(expr)] prevented in JSONPath expression.");const e=h.replace(/^\?\((.*?)\)$/u,"$1"),o=/@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(e);o?this._walk(t,(e=>{const a=[o[2]],l=o[1]?t[e][o[1]]:t[e];this._trace(a,l,i,r,s,n,!0).length>0&&d(this._trace(c,t[e],Uq(i,e),t,e,n,!0))})):this._walk(t,(o=>{this._eval(e,t[o],o,i,r,s)&&d(this._trace(c,t[o],Uq(i,o),t,o,n,!0))}))}else if("("===h[0]){if(!1===this.currEval)throw new Error("Eval [(expr)] prevented in JSONPath expression.");d(this._trace(Gq(this._eval(h,t,i.at(-1),i.slice(0,-1),r,s),c),t,i,r,s,n,o))}else if("@"===h[0]){let e=!1;const o=h.slice(1,-2);switch(o){case"scalar":t&&["object","function"].includes(typeof t)||(e=!0);break;case"boolean":case"string":case"undefined":case"function":typeof t===o&&(e=!0);break;case"integer":!Number.isFinite(t)||t%1||(e=!0);break;case"number":Number.isFinite(t)&&(e=!0);break;case"nonFinite":"number"!=typeof t||Number.isFinite(t)||(e=!0);break;case"object":t&&typeof t===o&&(e=!0);break;case"array":Array.isArray(t)&&(e=!0);break;case"other":e=this.currOtherTypeCallback(t,i,r,s);break;case"null":null===t&&(e=!0);break;default:throw new TypeError("Unknown value type "+o)}if(e)return l={path:i,value:t,parent:r,parentProperty:s},this._handleCallback(l,n,"value"),l}else if("`"===h[0]&&t&&Object.hasOwn(t,h.slice(1))){const e=h.slice(1);d(this._trace(c,t[e],Uq(i,e),t,e,n,o,!0))}else if(h.includes(",")){const e=h.split(",");for(const o of e)d(this._trace(Gq(o,c),t,i,r,s,n,!0))}else!a&&t&&Object.hasOwn(t,h)&&d(this._trace(c,t[h],Uq(i,h),t,h,n,o,!0))}if(this._hasParentSelector)for(let e=0;e{t(e)}))},Wq.prototype._slice=function(e,t,i,r,s,n,o){if(!Array.isArray(i))return;const a=i.length,l=e.split(":"),h=l[2]&&Number.parseInt(l[2])||1;let c=l[0]&&Number.parseInt(l[0])||0,u=l[1]&&Number.parseInt(l[1])||a;c=c<0?Math.max(0,c+a):Math.min(a,c),u=u<0?Math.max(0,u+a):Math.min(a,u);const d=[];for(let e=c;e{d.push(e)}));return d},Wq.prototype._eval=function(e,t,i,r,s,n){this.currSandbox._$_parentProperty=n,this.currSandbox._$_parent=s,this.currSandbox._$_property=i,this.currSandbox._$_root=this.json,this.currSandbox._$_v=t;const o=e.includes("@path");o&&(this.currSandbox._$_path=Wq.toPathString(r.concat([i])));const a=this.currEval+"Script:"+e;if(!Wq.cache[a]){let t=e.replaceAll("@parentProperty","_$_parentProperty").replaceAll("@parent","_$_parent").replaceAll("@property","_$_property").replaceAll("@root","_$_root").replaceAll(/@([.\s)[])/gu,"_$_v$1");if(o&&(t=t.replaceAll("@path","_$_path")),"safe"===this.currEval||!0===this.currEval||void 0===this.currEval)Wq.cache[a]=new this.safeVm.Script(t);else if("native"===this.currEval)Wq.cache[a]=new this.vm.Script(t);else if("function"==typeof this.currEval&&this.currEval.prototype&&Object.hasOwn(this.currEval.prototype,"runInNewContext")){const e=this.currEval;Wq.cache[a]=new e(t)}else{if("function"!=typeof this.currEval)throw new TypeError(`Unknown "eval" property "${this.currEval}"`);Wq.cache[a]={runInNewContext:e=>this.currEval(t,e)}}}try{return Wq.cache[a].runInNewContext(this.currSandbox)}catch(t){if(this.ignoreEvalErrors)return!1;throw new Error("jsonPath: "+t.message+": "+e)}},Wq.cache={},Wq.toPathString=function(e){const t=e,i=t.length;let r="$";for(let e=1;ee[t]));t=r.reduce(((t,i)=>{let r=e[i].toString();return/function/u.test(r)||(r="function "+r),"var "+i+"="+r+";"+t}),"")+t,/(['"])use strict\1/u.test(t)||i.includes("arguments")||(t="var arguments = undefined;"+t),t=t.replace(/;\s*$/u,"");const n=t.lastIndexOf(";"),o=n>-1?t.slice(0,n+1)+" return "+t.slice(n+1):" return "+t;return new Function(...i,o)(...s)}}};class Hq{constructor(e){this.math=e}hexColor(e){return e.color}hexToRgb(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e.color);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:void 0}rgbToHex(e){let t=e.r,i=e.g,r=e.b;return 255!==e.max&&(t=Math.round(this.math.remap({number:t,fromLow:e.min,fromHigh:e.max,toLow:0,toHigh:255})),i=Math.round(this.math.remap({number:i,fromLow:e.min,fromHigh:e.max,toLow:0,toHigh:255})),r=Math.round(this.math.remap({number:r,fromLow:e.min,fromHigh:e.max,toLow:0,toHigh:255}))),`#${Number(16777216+65536*t+256*i+r).toString(16).substring(1,7)}`}rgbObjToHex(e){return this.rgbToHex({r:e.rgb.r,g:e.rgb.g,b:e.rgb.b,min:e.min,max:e.max})}hexToRgbMapped(e){const t=this.hexToRgb(e);return{r:this.math.remap({number:t.r,fromLow:0,fromHigh:255,toLow:e.from,toHigh:e.to}),g:this.math.remap({number:t.g,fromLow:0,fromHigh:255,toLow:e.from,toHigh:e.to}),b:this.math.remap({number:t.b,fromLow:0,fromHigh:255,toLow:e.from,toHigh:e.to})}}getRedParam(e){return this.hexToRgbMapped(e).r}getGreenParam(e){return this.hexToRgbMapped(e).g}getBlueParam(e){return this.hexToRgbMapped(e).b}rgbToRed(e){return e.rgb.r}rgbToGreen(e){return e.rgb.g}rgbToBlue(e){return e.rgb.b}invert(e){const{r:t,g:i,b:r}=this.hexToRgbMapped({color:e.color,from:0,to:255});if(e.blackAndWhite)return.299*t+.587*i+.114*r>186?"#000000":"#ffffff";const s=255-t,n=255-i,o=255-r;return this.rgbToHex({r:s,g:n,b:o,min:0,max:255})}}class Xq{getItem(e){if(e.index<0||e.index>=e.list.length)throw new Error("Index out of bounds");let t;return t=e.clone?structuredClone(e.list[e.index]):e.list[e.index],t}randomGetThreshold(e){let t=e.list;e.clone&&(t=structuredClone(e.list));const i=[];for(let r=0;r=s)t.forEach(((e,t)=>{!0===i[t]&&n.push(e)}));else{const e=[],o=Math.ceil(s/r);for(let t=0;t{!0===e[i]&&n.push(t)}))}return n}mergeElementsOfLists(e){const t=e.lists,i=e.level,r=[],s=[];t.forEach((e=>{const t=e.flat(i);r.push(t)}));const n=this.getLongestListLength({lists:r});for(let e=0;e0&&s.push(t)}let o=[];if(i>0)for(let e=0;e{e.length>t&&(t=e.length)})),t):void 0}reverse(e){let t=e.list;return e.clone&&(t=structuredClone(e.list)),t.reverse()}flipLists(e){if(e.list.length>0){const t=e.list[0].length;let i=!0;if(e.list.forEach((e=>{e.length!==t&&(i=!1)})),i){const i=[];for(let r=0;r{t.push(e[r])})),i.push(t)}return i}throw new Error("Lists are not of the same length")}throw new Error("List is empty")}groupNth(e){return(e=>{const{nrElements:t,list:i,keepRemainder:r}=e,s=t,n=[];let o=[];return i.forEach(((e,t)=>{o.push(e),(t+1)%s==0&&(n.push(o),o=[]),r&&t===i.length-1&&n.push(o)})),n})(e)}getListDepth(e){let t=0,i=!0,r=e.list;for(;i;){let e=!1;for(let t=0;t=0&&e.index<=t.length&&t.splice(e.index,0,e.item),t}addItemAtIndexes(e){let t=e.list;e.clone&&(t=structuredClone(e.list));let i=[...e.indexes];return i=i.filter((e=>e>=0&&e<=t.length)),i.sort(((e,t)=>e-t)),i.forEach(((i,r)=>{i>=0&&i+r<=t.length&&t.splice(i+r,0,e.item)})),t}addItemsAtIndexes(e){if(e.items.length!==e.indexes.length)throw new Error("Items and indexes must have the same length");for(let t=0;t0&&e.indexes[t-1]>e.indexes[t])throw new Error("Indexes must be in ascending order");let t=e.list;return e.clone&&(t=structuredClone(e.list)),[...e.indexes].forEach(((i,r)=>{i>=0&&i+r<=t.length&&t.splice(i+r,0,e.items[r])})),t}removeItemAtIndex(e){let t=e.list;return e.clone&&(t=structuredClone(e.list)),e.index>=0&&e.index<=t.length&&t.splice(e.index,1),t}removeItemsAtIndexes(e){let t=e.list;e.clone&&(t=structuredClone(e.list));const i=[...e.indexes];return i.sort(((e,t)=>t-e)),i.forEach((e=>{e>=0&&ee.threshold&&i.push(t[r]);return i}removeDuplicateNumbers(e){let t=e.list;return e.clone&&(t=structuredClone(e.list)),t.filter(((e,t,i)=>i.indexOf(e)===t))}removeDuplicateNumbersTolerance(e){let t=e.list;return e.clone&&(t=structuredClone(e.list)),t.filter(((t,i,r)=>r.findIndex((i=>Math.abs(i-t)e-t)):t.sort(((e,t)=>t-e))}sortTexts(e){let t=e.list;return e.clone&&(t=structuredClone(e.list)),e.orderAsc?t.sort():t.sort().reverse()}sortByPropValue(e){let t=e.list;return e.clone&&(t=structuredClone(e.list)),e.orderAsc?t.sort(((t,i)=>t[e.property]-i[e.property])):t.sort(((t,i)=>i[e.property]-t[e.property]))}}class qq{boolean(e){return e.boolean}randomBooleans(e){const t=[];for(let i=0;i{if(ie.thresholdTotalFalse)t.push(!1);else{const r=i-e.thresholdTotalTrue,s=(e.thresholdTotalFalse-e.thresholdTotalTrue)/e.nrLevels,n=Math.ceil(r/s)/e.nrLevels;Math.random()>n?t.push(!0):t.push(!1)}})),t}thresholdBooleanList(e){const t=[];return e.numbers.forEach((i=>{i!e)):t}thresholdGapsBooleanList(e){const t=[];return e.numbers.forEach((i=>{let r=!1;e.gapThresholds.forEach((e=>{const s=e[0],n=e[1];i>=s&&i<=n&&(t.push(!0),r=!0)})),r||t.push(!1)})),e.inverse?t.map((e=>!e)):t}not(e){return!e.boolean}notList(e){return e.booleans.map((e=>!e))}compare(e){switch(e.operator){case"==":return e.first==e.second;case"!=":return e.first!=e.second;case"===":return e.first===e.second;case"!==":return e.first!==e.second;case"<":return e.first":return e.first>e.second;case">=":return e.first>=e.second;default:return!1}}valueGate(e){return e.boolean?e.value:void 0}firstDefinedValueGate(e){let t;return t=void 0!==e.value1?e.value1:void 0!==e.value2?e.value2:void 0,t}}class Yq{number(e){return e.number}twoNrOperation(e){let t;switch(e.operation){case Tq.mathTwoNrOperatorEnum.add:t=e.first+e.second;break;case Tq.mathTwoNrOperatorEnum.subtract:t=e.first-e.second;break;case Tq.mathTwoNrOperatorEnum.multiply:t=e.first*e.second;break;case Tq.mathTwoNrOperatorEnum.divide:t=e.first/e.second;break;case Tq.mathTwoNrOperatorEnum.power:t=Math.pow(e.first,e.second);break;case Tq.mathTwoNrOperatorEnum.modulus:t=e.first%e.second}return t}modulus(e){return this.twoNrOperation({first:e.number,second:e.modulus,operation:Tq.mathTwoNrOperatorEnum.modulus})}roundToDecimals(e){return Math.round(e.number*Math.pow(10,e.decimalPlaces))/Math.pow(10,e.decimalPlaces)}oneNrOperation(e){let t;switch(e.operation){case Tq.mathOneNrOperatorEnum.absolute:t=Math.abs(e.number);break;case Tq.mathOneNrOperatorEnum.negate:t=-e.number;break;case Tq.mathOneNrOperatorEnum.ln:t=Math.log(e.number);break;case Tq.mathOneNrOperatorEnum.log10:t=Math.log10(e.number);break;case Tq.mathOneNrOperatorEnum.tenPow:t=Math.pow(10,e.number);break;case Tq.mathOneNrOperatorEnum.round:t=Math.round(e.number);break;case Tq.mathOneNrOperatorEnum.floor:t=Math.floor(e.number);break;case Tq.mathOneNrOperatorEnum.ceil:t=Math.ceil(e.number);break;case Tq.mathOneNrOperatorEnum.sqrt:t=Math.sqrt(e.number);break;case Tq.mathOneNrOperatorEnum.sin:t=Math.sin(e.number);break;case Tq.mathOneNrOperatorEnum.cos:t=Math.cos(e.number);break;case Tq.mathOneNrOperatorEnum.tan:t=Math.tan(e.number);break;case Tq.mathOneNrOperatorEnum.asin:t=Math.asin(e.number);break;case Tq.mathOneNrOperatorEnum.acos:t=Math.acos(e.number);break;case Tq.mathOneNrOperatorEnum.atan:t=Math.atan(e.number);break;case Tq.mathOneNrOperatorEnum.log:t=Math.log(e.number);break;case Tq.mathOneNrOperatorEnum.exp:t=Math.exp(e.number);break;case Tq.mathOneNrOperatorEnum.degToRad:t=e.number*Math.PI/180;break;case Tq.mathOneNrOperatorEnum.radToDeg:t=180*e.number/Math.PI}return t}remap(e){return(e.number-e.fromLow)*(e.toHigh-e.toLow)/(e.fromHigh-e.fromLow)+e.toLow}random(){return Math.random()}randomNumber(e){return Math.random()*(e.high-e.low)+e.low}randomNumbers(e){const t=[];for(let i=0;ithis.geometryHelper.transformControlPoints(e.transformation[i],[t])[0]))}translatePoints(e){const t=this.transforms.translationXYZ({translation:e.translation});return this.geometryHelper.transformControlPoints(t,e.points)}translatePointsWithVectors(e){if(e.points.length!==e.translations.length)throw new Error("You must provide equal nr of points and translations");const t=this.transforms.translationsXYZ({translations:e.translations});return e.points.map(((e,i)=>this.geometryHelper.transformControlPoints(t[i],[e])[0]))}translateXYZPoints(e){const t=this.transforms.translationXYZ({translation:[e.x,e.y,e.z]});return this.geometryHelper.transformControlPoints(t,e.points)}scalePointsCenterXYZ(e){const t=this.transforms.scaleCenterXYZ({center:e.center,scaleXyz:e.scaleXyz});return this.geometryHelper.transformControlPoints(t,e.points)}rotatePointsCenterAxis(e){const t=this.transforms.rotationCenterAxis({center:e.center,axis:e.axis,angle:e.angle});return this.geometryHelper.transformControlPoints(t,e.points)}closestPointFromPointsDistance(e){return this.closestPointFromPointData(e).distance}closestPointFromPointsIndex(e){return this.closestPointFromPointData(e).index}closestPointFromPoints(e){return this.closestPointFromPointData(e).point}distance(e){const t=e.endPoint[0]-e.startPoint[0],i=e.endPoint[1]-e.startPoint[1],r=e.endPoint[2]-e.startPoint[2];return Math.sqrt(t*t+i*i+r*r)}distancesToPoints(e){return e.endPoints.map((t=>this.distance({startPoint:e.startPoint,endPoint:t})))}multiplyPoint(e){const t=[];for(let i=0;i{t.push(e[0]),i.push(e[1]),r.push(e[2])})),[t.reduce(((e,t)=>e+t),0)/e.points.length,i.reduce(((e,t)=>e+t),0)/e.points.length,r.reduce(((e,t)=>e+t),0)/e.points.length]}pointXYZ(e){return[e.x,e.y,e.z]}pointXY(e){return[e.x,e.y]}spiral(e){const t=e.phi,i=Math.log(t)/(Math.PI/e.widening),r=[],s=e.radius/e.numberPoints;for(let t=0;t{i[s]=[r[0]-e,r[1]-t,0]}))}return e.pointsOnGround&&i.forEach(((e,t)=>{i[t]=[e[0],0,e[1]]})),i}removeConsecutiveDuplicates(e){return this.geometryHelper.removeConsecutivePointDuplicates(e.points,e.checkFirstAndLast,e.tolerance)}closestPointFromPointData(e){let t,i,r=Number.MAX_SAFE_INTEGER;for(let s=0;se.toString()))}format(e){return e.text.replace(/{(\d+)}/g,((t,i)=>void 0!==e.values[i]?e.values[i]:t))}}class $q{constructor(e,t){this.math=e,this.geometryHelper=t}removeAllDuplicateVectors(e){return this.geometryHelper.removeAllDuplicateVectors(e.vectors,e.tolerance)}removeConsecutiveDuplicateVectors(e){return this.geometryHelper.removeConsecutiveVectorDuplicates(e.vectors,e.checkFirstAndLast,e.tolerance)}angleBetween(e){return this.math.radToDeg({number:Math.acos(this.dot({first:e.first,second:e.second})/(this.norm({vector:e.first})*this.norm({vector:e.second})))})}angleBetweenNormalized2d(e){const t=e.first[0]*e.second[1]-e.first[1]*e.second[0];return this.math.radToDeg({number:Math.atan2(t,this.dot({first:e.first,second:e.second}))})}positiveAngleBetween(e){const t=this.signedAngleBetween(e);return t<0?360+t:t}addAll(e){const t=[];for(let i=0;ie))}cross(e){const t=[];return t.push(e.first[1]*e.second[2]-e.first[2]*e.second[1]),t.push(e.first[2]*e.second[0]-e.first[0]*e.second[2]),t.push(e.first[0]*e.second[1]-e.first[1]*e.second[0]),t}distSquared(e){let t=0;for(let i=0;iisFinite(e)))}isZero(e){return 0===this.norm({vector:e.vector})}lerp(e){return this.add({first:this.mul({vector:e.first,scalar:e.fraction}),second:this.mul({vector:e.second,scalar:1-e.fraction})})}max(e){return Math.max(...e.vector)}min(e){return Math.min(...e.vector)}mul(e){const t=[];for(let i=0;i0?o:2*Math.PI-o;return this.math.radToDeg({number:a})}span(e){const t=[];for(let i=e.min;i<=e.max;i+=e.step)t.push(i);return t}spanEaseItems(e){const t=[];for(let i=0;i0===t?e:e-i[t-1])):t}spanLinearItems(e){const t=[],i=e.max-e.min;for(let r=0;re+t),0)}}class Qq{constructor(e,t){this.vector=e,this.math=t}rotationCenterAxis(e){return[this.translation(-e.center[0],-e.center[1],-e.center[2]),this.rotationAxis(e.axis,this.math.degToRad({number:e.angle})),this.translation(e.center[0],e.center[1],e.center[2])]}rotationCenterX(e){return[this.translation(-e.center[0],-e.center[1],-e.center[2]),this.rotationX(this.math.degToRad({number:e.angle})),this.translation(e.center[0],e.center[1],e.center[2])]}rotationCenterY(e){return[this.translation(-e.center[0],-e.center[1],-e.center[2]),this.rotationY(this.math.degToRad({number:e.angle})),this.translation(e.center[0],e.center[1],e.center[2])]}rotationCenterZ(e){return[this.translation(-e.center[0],-e.center[1],-e.center[2]),this.rotationZ(this.math.degToRad({number:e.angle})),this.translation(e.center[0],e.center[1],e.center[2])]}rotationCenterYawPitchRoll(e){return[this.translation(-e.center[0],-e.center[1],-e.center[2]),this.rotationYawPitchRoll(this.math.degToRad({number:e.yaw}),this.math.degToRad({number:e.pitch}),this.math.degToRad({number:e.roll})),this.translation(e.center[0],e.center[1],e.center[2])]}scaleCenterXYZ(e){return[this.translation(-e.center[0],-e.center[1],-e.center[2]),this.scaling(e.scaleXyz[0],e.scaleXyz[1],e.scaleXyz[2]),this.translation(e.center[0],e.center[1],e.center[2])]}scaleXYZ(e){return[this.scaling(e.scaleXyz[0],e.scaleXyz[1],e.scaleXyz[2])]}uniformScale(e){return[this.scaling(e.scale,e.scale,e.scale)]}uniformScaleFromCenter(e){return[this.translation(-e.center[0],-e.center[1],-e.center[2]),this.scaling(e.scale,e.scale,e.scale),this.translation(e.center[0],e.center[1],e.center[2])]}translationXYZ(e){return[this.translation(e.translation[0],e.translation[1],e.translation[2])]}translationsXYZ(e){return e.translations.map((e=>[this.translation(e[0],e[1],e[2])]))}translation(e,t,i){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1]}scaling(e,t,i){return[e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1]}identity(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}rotationAxis(e,t){const i=Math.sin(-t),r=Math.cos(-t),s=1-r,n=this.vector.normalized({vector:e}),o=n[0],a=n[1],l=n[2],h=this.identity();return h[0]=o*o*s+r,h[1]=o*a*s-l*i,h[2]=o*l*s+a*i,h[3]=0,h[4]=a*o*s+l*i,h[5]=a*a*s+r,h[6]=a*l*s-o*i,h[7]=0,h[8]=l*o*s-a*i,h[9]=l*a*s+o*i,h[10]=l*l*s+r,h[11]=0,h[12]=0,h[13]=0,h[14]=0,h[15]=1,h}rotationX(e){const t=Math.sin(e),i=Math.cos(e);return[1,0,0,0,0,i,t,0,0,-t,i,0,0,0,0,1]}rotationY(e){const t=Math.sin(e),i=Math.cos(e);return[i,0,-t,0,0,1,0,0,t,0,i,0,0,0,0,1]}rotationZ(e){const t=Math.sin(e),i=Math.cos(e);return[i,t,0,0,-t,i,0,0,0,0,1,0,0,0,0,1]}rotationYawPitchRoll(e,t,i){const r=.5*i,s=.5*t,n=.5*e,o=Math.sin(r),a=Math.cos(r),l=Math.sin(s),h=Math.cos(s),c=Math.sin(n),u=Math.cos(n),d=u*l*a+c*h*o,f=c*h*a-u*l*o,p=u*h*o-c*l*a,_=u*h*a+c*l*o;return this.rotationMatrixFromQuat(d,f,p,_)}rotationMatrixFromQuat(e,t,i,r){const s=e*e,n=t*t,o=i*i,a=e*t,l=i*r,h=i*e,c=t*r,u=t*i,d=e*r,f=this.identity();return f[0]=1-2*(n+o),f[1]=2*(a+l),f[2]=2*(h-c),f[3]=0,f[4]=2*(a-l),f[5]=1-2*(o+s),f[6]=2*(u+d),f[7]=0,f[8]=2*(h+c),f[9]=2*(u-d),f[10]=1-2*(n+s),f[11]=0,f[12]=0,f[13]=0,f[14]=0,f[15]=1,f}}class Zq{constructor(){this.getArrayDepth=e=>Array.isArray(e)?1+Math.max(...e.map(this.getArrayDepth)):0}transformControlPoints(e,t){return this.getFlatTransformations(e).forEach((e=>{t=this.transformPointsByMatrixArray(t,e)})),t}getFlatTransformations(e){let t=[];return 3===this.getArrayDepth(e)?e.forEach((e=>{t.push(...e)})):t=e,t}transformPointsByMatrixArray(e,t){return this.transformPointsCoordinates(e,t)}transformPointsCoordinates(e,t){const i=[];for(const r of e){const e=this.transformCoordinates(r[0],r[1],r[2],t);i.push(e)}return i}removeAllDuplicateVectors(e,t=1e-7){const i=[];return e.forEach((e=>{i.some((i=>this.vectorsTheSame(e,i,t)))||i.push(e)})),i}removeConsecutiveVectorDuplicates(e,t=!0,i=1e-7){const r=[];if(e.length>1){for(let t=1;t1){for(let t=1;t0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,i=this,r=i.hasError,s=i.isStopped,n=i.observers;return r||s?CY:(this.currentObservers=null,n.push(e),new TY((function(){t.currentObservers=null,SY(n,e)})))},t.prototype._checkFinalizedStatuses=function(e){var t=this,i=t.hasError,r=t.thrownError,s=t.isStopped;i?e.error(r):s&&e.complete()},t.prototype.asObservable=function(){var e=new YY;return e.source=this,e},t.create=function(e,t){return new ZY(e,t)},t}(YY),ZY=function(e){function t(t,i){var r=e.call(this)||this;return r.destination=t,r.source=i,r}return uz(t,e),t.prototype.next=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===i||i.call(t,e)},t.prototype.error=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===i||i.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,i;return null!==(i=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==i?i:CY},t}(QY);!function(e){e[e.loading=0]="loading",e[e.loaded=1]="loaded",e[e.initialised=2]="initialised",e[e.computing=3]="computing"}(jY||(jY={}));class JY{constructor(){this.jscadWorkerState$=new QY,this.promisesMade=[]}jscadWorkerAlreadyInitialised(){return!!this.jscadWorker}setJscadWorker(e){this.jscadWorker=e,this.jscadWorker.onmessage=({data:e})=>{if("jscad-initialised"===e)this.jscadWorkerState$.next({state:jY.initialised});else if("busy"===e)this.jscadWorkerState$.next({state:jY.computing});else{const t=this.promisesMade.find((t=>t.uid===e.uid));t&&e.result&&!e.error?t.resolve(e.result):e.error&&(this.errorCallback&&this.errorCallback(e.error),t.reject(e.error)),this.promisesMade=this.promisesMade.filter((t=>t.uid!==e.uid)),0===this.promisesMade.length?this.jscadWorkerState$.next({state:jY.loaded}):this.jscadWorkerState$.next({state:jY.computing})}}}cleanPromisesMade(){this.promisesMade=[]}genericCallToWorkerPromise(e,t){const i=`call${Math.random()}${Date.now()}`,r={uid:i},s=new Promise(((e,t)=>{r.resolve=e,r.reject=t}));return r.promise=s,this.promisesMade.push(r),this.jscadWorker.postMessage({action:{functionName:e,inputs:t},uid:i}),s}startedTheRun(){return this.genericCallToWorkerPromise("startedTheRun",{})}cleanAllCache(){return this.genericCallToWorkerPromise("cleanAllCache",{})}}var eK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class tK{constructor(e){this.manifoldWorkerManager=e}manifoldFromMesh(e){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.shapes.manifoldFromMesh",e)}cube(e){return eK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.shapes.cube",e)}))}sphere(e){return eK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.shapes.sphere",e)}))}tetrahedron(){return eK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.shapes.tetrahedron",{})}))}cylinder(e){return eK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.shapes.cylinder",e)}))}}var iK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class rK{constructor(e){this.manifoldWorkerManager=e}subtract(e){return iK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.subtract",e)}))}add(e){return iK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.add",e)}))}intersect(e){return iK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.intersect",e)}))}differenceTwo(e){return iK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.differenceTwo",e)}))}unionTwo(e){return iK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.unionTwo",e)}))}intersectionTwo(e){return iK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.intersectionTwo",e)}))}difference(e){return iK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.difference",e)}))}union(e){return iK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.union",e)}))}intersection(e){return iK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.intersection",e)}))}split(e){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.split",e)}splitByPlane(e){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.splitByPlane",e)}trimByPlane(e){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.booleans.trimByPlane",e)}}var sK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class nK{constructor(e){this.manifoldWorkerManager=e}hull(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.hull",e)}))}hullPoints(e){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.hullPoints",e)}slice(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.slice",e)}))}project(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.project",e)}))}setTolerance(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.setTolerance",e)}))}reserveIds(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.reserveIds",e)}))}asOriginal(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.asOriginal",e)}))}compose(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.compose",e)}))}decompose(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.decompose",e)}))}calculateNormals(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.calculateNormals",e)}))}calculateCurvature(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.calculateCurvature",e)}))}refineToTolerance(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.refineToTolerance",e)}))}refineToLength(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.refineToLength",e)}))}refine(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.refine",e)}))}smoothOut(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.smoothOut",e)}))}smoothByNormals(e){return sK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.operations.smoothByNormals",e)}))}}var oK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class aK{constructor(e){this.manifoldWorkerManager=e}scale3D(e){return oK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.transforms.scale3D",e)}))}scale(e){return oK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.transforms.scale",e)}))}mirror(e){return oK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.transforms.mirror",e)}))}translate(e){return oK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.transforms.translate",e)}))}translateByVectors(e){return oK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.transforms.translateByVectors",e)}))}translateXYZ(e){return oK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.transforms.translateXYZ",e)}))}rotate(e){return oK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.transforms.rotate",e)}))}rotateXYZ(e){return oK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.transforms.rotateXYZ",e)}))}transform(e){return oK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.transforms.transform",e)}))}transforms(e){return oK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.transforms.transforms",e)}))}}var lK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class hK{constructor(e){this.manifoldWorkerManager=e}surfaceArea(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.surfaceArea",e)}))}volume(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.volume",e)}))}isEmpty(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.isEmpty",e)}))}numVert(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.numVert",e)}))}numTri(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.numTri",e)}))}numEdge(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.numEdge",e)}))}numProp(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.numProp",e)}))}numPropVert(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.numPropVert",e)}))}boundingBox(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.boundingBox",e)}))}tolerance(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.tolerance",e)}))}genus(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.genus",e)}))}minGap(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.minGap",e)}))}originalID(e){return lK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.evaluate.originalID",e)}))}}var cK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class uK{constructor(e){this.manifoldWorkerManager=e,this.shapes=new tK(e),this.booleans=new rK(e),this.operations=new nK(e),this.transforms=new aK(e),this.evaluate=new hK(e)}manifoldToMesh(e){return cK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.manifoldToMesh",e)}))}manifoldsToMeshes(e){return cK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifold.manifoldsToMeshes",e)}))}}var dK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class fK{constructor(e){this.manifoldWorkerManager=e}hull(e){return dK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.operations.hull",e)}))}extrude(e){return dK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.operations.extrude",e)}))}revolve(e){return dK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.operations.revolve",e)}))}offset(e){return dK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.operations.offset",e)}))}simplify(e){return dK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.operations.simplify",e)}))}compose(e){return dK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.operations.compose",e)}))}decompose(e){return dK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.operations.decompose",e)}))}}var pK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class _K{constructor(e){this.manifoldWorkerManager=e}create(e){return pK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.shapes.create",e)}))}square(e){return pK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.shapes.square",e)}))}circle(e){return pK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.shapes.circle",e)}))}rectangle(e){return pK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.shapes.rectangle",e)}))}}var mK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class gK{constructor(e){this.manifoldWorkerManager=e}scale2D(e){return mK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.transforms.scale2D",e)}))}scale(e){return mK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.transforms.scale",e)}))}mirror(e){return mK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.transforms.mirror",e)}))}translate(e){return mK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.transforms.translate",e)}))}translateXY(e){return mK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.transforms.translateXY",e)}))}rotate(e){return mK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.transforms.rotate",e)}))}transform(e){return mK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.transforms.transform",e)}))}}var vK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class xK{constructor(e){this.manifoldWorkerManager=e}subtract(e){return vK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.booleans.subtract",e)}))}add(e){return vK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.booleans.add",e)}))}intersect(e){return vK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.booleans.intersect",e)}))}differenceTwo(e){return vK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.booleans.differenceTwo",e)}))}unionTwo(e){return vK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.booleans.unionTwo",e)}))}intersectionTwo(e){return vK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.booleans.intersectionTwo",e)}))}difference(e){return vK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.booleans.difference",e)}))}union(e){return vK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.booleans.union",e)}))}intersection(e){return vK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.booleans.intersection",e)}))}}var bK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class SK{constructor(e){this.manifoldWorkerManager=e}area(e){return bK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.evaluate.area",e)}))}isEmpty(e){return bK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.evaluate.isEmpty",e)}))}numVert(e){return bK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.evaluate.numVert",e)}))}numContour(e){return bK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.evaluate.numContour",e)}))}bounds(e){return bK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.evaluate.bounds",e)}))}}var TK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class CK{constructor(e){this.manifoldWorkerManager=e,this.shapes=new _K(e),this.operations=new fK(e),this.booleans=new xK(e),this.transforms=new gK(e),this.evaluate=new SK(e)}crossSectionToPolygons(e){return TK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.crossSectionToPolygons",e)}))}crossSectionsToPolygons(e){return TK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("crossSection.crossSectionsToPolygons",e)}))}}class yK{constructor(e){this.manifoldWorkerManager=e}merge(e){return t=this,i=void 0,s=function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("mesh.operations.merge",e)},new((r=void 0)||(r=Promise))((function(e,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r((function(e){e(i)}))).then(o,a)}l((s=s.apply(t,i||[])).next())}));var t,i,r,s}}var EK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class PK{constructor(e){this.manifoldWorkerManager=e}position(e){return EK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("mesh.evaluate.position",e)}))}verts(e){return EK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("mesh.evaluate.verts",e)}))}tangent(e){return EK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("mesh.evaluate.tangent",e)}))}extras(e){return EK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("mesh.evaluate.extras",e)}))}transform(e){return EK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("mesh.evaluate.transform",e)}))}numProp(e){return EK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("mesh.evaluate.numProp",e)}))}numVert(e){return EK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("mesh.evaluate.numVert",e)}))}numTri(e){return EK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("mesh.evaluate.numTri",e)}))}numRun(e){return EK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("mesh.evaluate.numRun",e)}))}}class AK{constructor(e){this.manifoldWorkerManager=e,this.operations=new yK(e),this.evaluate=new PK(e)}}var RK,IK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class MK{constructor(e){this.manifoldWorkerManager=e,this.manifold=new uK(e),this.crossSection=new CK(e),this.mesh=new AK(e)}manifoldToMeshPointer(e){return IK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("manifoldToMeshPointer",e)}))}decomposeManifoldOrCrossSection(e){return IK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("decomposeManifoldOrCrossSection",e)}))}decomposeManifoldsOrCrossSections(e){return IK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("decomposeManifoldsOrCrossSections",e)}))}deleteManifoldOrCrossSection(e){return IK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("deleteManifoldOrCrossSection",e)}))}deleteManifoldsOrCrossSections(e){return IK(this,void 0,void 0,(function*(){return this.manifoldWorkerManager.genericCallToWorkerPromise("deleteManifoldsOrCrossSections",e)}))}}!function(e){e[e.loading=0]="loading",e[e.loaded=1]="loaded",e[e.initialised=2]="initialised",e[e.computing=3]="computing"}(RK||(RK={}));class OK{constructor(){this.manifoldWorkerState$=new QY,this.promisesMade=[]}manifoldWorkerAlreadyInitialised(){return!!this.manifoldWorker}setManifoldWorker(e){this.manifoldWorker=e,this.manifoldWorker.onmessage=({data:e})=>{if("manifold-initialised"===e)this.manifoldWorkerState$.next({state:RK.initialised});else if("busy"===e)this.manifoldWorkerState$.next({state:RK.computing});else{const t=this.promisesMade.find((t=>t.uid===e.uid));t&&void 0!==e.result&&!e.error?t.resolve(e.result):e.error&&(this.errorCallback&&this.errorCallback(e.error),t.reject(e.error)),this.promisesMade=this.promisesMade.filter((t=>t.uid!==e.uid)),0===this.promisesMade.length?this.manifoldWorkerState$.next({state:RK.loaded}):this.manifoldWorkerState$.next({state:RK.computing})}}}cleanPromisesMade(){this.promisesMade=[]}genericCallToWorkerPromise(e,t){const i=`call${Math.random()}${Date.now()}`,r={uid:i},s=new Promise(((e,t)=>{r.resolve=e,r.reject=t}));return r.promise=s,this.promisesMade.push(r),this.manifoldWorker.postMessage({action:{functionName:e,inputs:t},uid:i}),s}startedTheRun(){return this.genericCallToWorkerPromise("startedTheRun",{})}cleanAllCache(){return this.genericCallToWorkerPromise("cleanAllCache",{})}}var DK=i(34258);class wK{constructor(){this.context=new Iq,this.jscadWorkerManager=new JY,this.manifoldWorkerManager=new OK,this.occtWorkerManager=new Zz,this.jscad=new gY(this.jscadWorkerManager),this.manifold=new MK(this.manifoldWorkerManager);const e=new Zq;this.math=new Yq,this.vector=new $q(this.math,e);const t=new Oq(this.context,this.jscad.text,this.vector,this.jscadWorkerManager,this.manifoldWorkerManager,this.occtWorkerManager);this.babylon=new qX(this.context,t,this.color),this.tag=new pq(this.context),this.draw=new Rq(t,this.babylon.node,this.tag,this.context),this.color=new Hq(this.math),this.line=new dq(this.context,e),this.transforms=new Qq(this.vector,this.math),this.point=new Kq(e,this.transforms),this.polyline=new fq(this.context,e),this.verb=new oq(this.context,e,this.math),this.time=new _q(this.context),this.occt=new KX(this.context,this.occtWorkerManager),this.asset=new cq,this.logic=new qq,this.json=new uq(this.context),this.text=new jq,this.lists=new Xq}init(e,t,i,r,s){this.context.scene=e,s&&(this.context.havokPlugin=s);const n={geom:DK.geom,core:DK.core};this.context.verb=n,this.context.jsonpath=Wq,t&&this.occtWorkerManager.setOccWorker(t),i&&this.jscadWorkerManager.setJscadWorker(i),r&&this.manifoldWorkerManager.setManifoldWorker(r)}}const NK="assets/textures";class FK{constructor(e){this.name="",this.scene=void 0,this.wAng=0,this.uScale=1,this.vScale=1,this.color=void 0,this.albedoTextureUrl=void 0,this.microSurfaceTextureUrl=void 0,this.bumpTextureUrl=void 0,this.metallic=.1,this.roughness=.9,this.zOffset=2,Object.keys(this).forEach((t=>this[t]=e[t]))}}class LK{static simpleBlackMaterial(e){const t=new zm("blackMaterial"+Math.random(),e);return t.albedoColor=new hc.v9(0,0,0),t.metallic=0,t.roughness=.7,t.zOffset=2,t}static rock1Material(e,t,i){const r=new FK({name:"wood1",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:LK.textures.rock1.default.albedo,bumpTextureUrl:LK.textures.rock1.microSurfaceTexture,microSurfaceTextureUrl:LK.textures.rock1.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return LK.createMaterial(r)}static wood1Material(e,t,i){const r=new FK({name:"wood1",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:LK.textures.wood1.light.albedo,bumpTextureUrl:LK.textures.wood1.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return LK.createMaterial(r)}static wood2Material(e,t,i){const r=new FK({name:"wood2",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:LK.textures.wood2.light.albedo,microSurfaceTextureUrl:LK.textures.wood2.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return LK.createMaterial(r)}static wood3Material(e,t,i){const r=new FK({name:"wood3",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:LK.textures.wood1.dark.albedo,microSurfaceTextureUrl:LK.textures.wood1.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return LK.createMaterial(r)}static brownPlanks(e,t,i){const r=new FK({name:"brownPlanks",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:LK.textures.brownPlanks.light.albedo,microSurfaceTextureUrl:LK.textures.brownPlanks.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return LK.createMaterial(r)}static woodenPlanks(e,t,i){const r=new FK({name:"woodenPlanks",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:LK.textures.woodenPlanks.light.albedo,microSurfaceTextureUrl:LK.textures.woodenPlanks.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return LK.createMaterial(r)}static glass(e,t){const i=new zm("faceGlassMaterial"+Math.random(),e);return i.albedoColor=hc.v9.FromHexString(t),i.ambientColor=hc.v9.FromHexString("#ffffff"),i.metallic=.8,i.roughness=.1,i.zOffset=1,i.alpha=.5,i}static brushedConcrete(e,t,i){const r=new FK({name:"brushedConcrete",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:LK.textures.brushedConcrete.grey.albedo,microSurfaceTextureUrl:LK.textures.brushedConcrete.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return LK.createMaterial(r)}static metal1(e,t,i){const r=new FK({name:"metal1",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:LK.textures.metal1.light.albedo,microSurfaceTextureUrl:LK.textures.metal1.microSurfaceTexture,bumpTextureUrl:LK.textures.metal1.light.roughness,metallic:.3,roughness:.6,zOffset:2});return LK.createMaterial(r)}static roughPlastic(e,t){const i=new FK({name:"roughPlastic-"+t,color:t,scene:e,metallic:.1,roughness:.9,zOffset:2});return LK.createMaterial(i)}static createMaterial(e){const t=new zm(e.name,e.scene);return e.color&&(t.albedoColor=hc.v9.FromHexString(e.color)),e.albedoTextureUrl&&(t.albedoTexture=LK.createTexture(e.albedoTextureUrl,e)),e.microSurfaceTextureUrl&&(t.microSurfaceTexture=LK.createTexture(e.microSurfaceTextureUrl,e)),e.bumpTextureUrl&&(t.bumpTexture=LK.createTexture(e.bumpTextureUrl,e)),t.metallic=e.metallic,t.roughness=e.roughness,t.zOffset=e.zOffset,t}static createTexture(e,t){const i=new vi.g(e,t.scene);return i.uScale=t.uScale,i.vScale=t.vScale,i.wAng=t.wAng,i}}LK.textures={wood1:{microSurfaceTexture:`${NK}/Wood048_1K/Wood048_1K_NormalGL.jpg`,light:{albedo:`${NK}/Wood048_1K/Wood048_1K_Light.jpg`},dark:{albedo:`${NK}/Wood048_1K/Wood048_1K_Color_Dark.jpg`}},wood2:{microSurfaceTexture:`${NK}/Wood084_1K/Wood084A_1K_NormalGL.jpg`,light:{albedo:`${NK}/Wood084_1K/Wood084A_1K_Color.jpg`}},metal1:{microSurfaceTexture:`${NK}/metal_1/Metal029_1K_Displacement.jpg`,light:{albedo:`${NK}/metal_1/Metal029_1K_Color.jpg`,normalGL:`${NK}/metal_1/Metal029_1K_NormalGL.jpg`,roughness:`${NK}/metal_1/Metal029_1K_Roughness.jpg`,metalness:`${NK}/metal_1/Metal029_1K_Metalness.jpg`}},brownPlanks:{microSurfaceTexture:`${NK}/brown_planks/brown_planks_05_nor_gl_1k.jpg`,light:{albedo:`${NK}/brown_planks/brown_planks_05_diff_1k.jpg`}},woodenPlanks:{microSurfaceTexture:`${NK}/wooden_planks/wooden_planks_nor_gl_1k.jpg`,light:{albedo:`${NK}/wooden_planks/wooden_planks_diff_1k.jpg`}},brushedConcrete:{microSurfaceTexture:`${NK}/brushed_concrete/brushed_concrete_03_nor_gl_1k.jpg`,sand:{albedo:`${NK}/brushed_concrete/brushed_concrete_03_diff_1k.jpg`},grey:{albedo:`${NK}/brushed_concrete/brushed_concrete_03_diff_grey_1k.jpg`}},rock1:{microSurfaceTexture:`${NK}/Rock044_1K/Rock044_1K_NormalGL.jpg`,default:{albedo:`${NK}/Rock044_1K/Rock044_1K_Color.jpg`,roughness:`${NK}/Rock044_1K/Rock044_1K_Roughness.jpg`}}};var BK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class VK{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return BK(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.wingtipVilla",e);if(t){const e=t.shapes.find((e=>e.id===t.data.roof.compound)),i=t.shapes.find((e=>e.id===t.data.walls.compound));return{type:t.data.type,name:t.data.name,compound:t.compound,roof:{compound:e.shape,shapes:t.shapes.filter((e=>t.data.roof.shapes.includes(e.id))).map((e=>e.shape))},walls:{compound:i.shape,shapes:t.shapes.filter((e=>t.data.walls.shapes.includes(e.id))).map((e=>e.shape))},stick:{shape:t.shapes.find((e=>e.id===t.data.stick.shape)).shape},floor:{shape:t.shapes.find((e=>e.id===t.data.floor.shape)).shape},chimney:{shape:t.shapes.find((e=>e.id===t.data.chimney.shape)).shape},basicPoints:t.data.basicPoints}}}))}drawModel(e){return BK(this,void 0,void 0,(function*(){const t=new Yt("brepMesh"+Math.random(),this.context.scene),i=new QH.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#ffffff";const r=yield this.draw.drawAnyAsync({entity:e.roof.compound,options:i}),s=r.getChildMeshes(),n=s[0],o=s[1],a=yield this.draw.drawAnyAsync({entity:e.walls.compound,options:i}),l=a.getChildMeshes(),h=l[0],c=l[1],u=yield this.draw.drawAnyAsync({entity:e.floor.shape,options:i}),d=u.getChildMeshes(),f=d[0],p=d[1],_=yield this.draw.drawAnyAsync({entity:e.stick.shape,options:i}),m=_.getChildMeshes(),g=m[0],v=m[1],x=yield this.draw.drawAnyAsync({entity:e.chimney.shape,options:i}),b=x.getChildMeshes(),S=b[0],T=b[1],C=new vi.g("assets/textures/Wood048_1K/Wood048_1K_Red.jpg",this.context.scene),y=new vi.g("assets/textures/Wood048_1K/Wood048_1K_Color_Dark.jpg",this.context.scene),E=new vi.g("assets/textures/Wood048_1K/Wood048_1K_NormalGL.jpg",this.context.scene);C.uScale=.3,C.vScale=.3,C.wAng=Math.PI/2,y.uScale=.3,y.vScale=.3,y.wAng=Math.PI/2,E.uScale=.3,E.vScale=.3,E.wAng=Math.PI/2;const P=new zm("wood-red",this.context.scene);P.albedoTexture=C,P.microSurfaceTexture=E,P.metallic=0,P.roughness=1,P.zOffset=2;const A=new zm("wood-dark",this.context.scene);return A.albedoTexture=y,A.microSurfaceTexture=E,A.metallic=0,A.roughness=1,A.zOffset=2,n.material=P,h.material=LK.wood1Material(this.context.scene,Math.PI/2,.3),f.material=P,g.material=P,S.material=A,n.parent=t,h.parent=t,f.parent=t,g.parent=t,S.parent=t,o.parent=t,c.parent=t,p.parent=t,v.parent=t,T.parent=t,r.dispose(),u.dispose(),a.dispose(),_.dispose(),x.dispose(),t}))}dispose(e){return BK(this,void 0,void 0,(function*(){const t=[e.compound,e.chimney.shape,e.floor.shape,...e.roof.shapes,...e.walls.shapes,e.stick.shape];yield this.occt.deleteShapes({shapes:t})}))}}var kK=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class UK{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}dispose(e){return kK(this,void 0,void 0,(function*(){const t=[e.compound,e.floor.shape,...e.roof.shapes,...e.walls.shapes,e.stick.shape];yield this.occt.deleteShapes({shapes:t})}))}create(e){return kK(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.chirpyChalet",e);if(t){const e=t.shapes.find((e=>e.id===t.data.roof.compound)),i=t.shapes.find((e=>e.id===t.data.walls.compound));return{type:t.data.type,name:t.data.name,compound:t.compound,roof:{compound:e.shape,shapes:t.shapes.filter((e=>t.data.roof.shapes.includes(e.id))).map((e=>e.shape))},walls:{compound:i.shape,shapes:t.shapes.filter((e=>t.data.walls.shapes.includes(e.id))).map((e=>e.shape))},stick:{shape:t.shapes.find((e=>e.id===t.data.stick.shape)).shape},floor:{shape:t.shapes.find((e=>e.id===t.data.floor.shape)).shape},basicPoints:t.data.basicPoints}}}))}drawModel(e){return kK(this,void 0,void 0,(function*(){const t=new Yt("brepMesh"+Math.random(),this.context.scene),i=new QH.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#ffffff";const r=yield this.draw.drawAnyAsync({entity:e.roof.compound,options:i}),s=r.getChildMeshes()[0],n=yield this.draw.drawAnyAsync({entity:e.walls.compound,options:i}),o=n.getChildMeshes()[0],a=yield this.draw.drawAnyAsync({entity:e.floor.shape,options:i}),l=a.getChildMeshes()[0],h=yield this.draw.drawAnyAsync({entity:e.stick.shape,options:i}),c=h.getChildMeshes()[0],u=new vi.g("assets/textures/Wood048_1K/Wood048_1K_Color.jpg",this.context.scene),d=new vi.g("assets/textures/Wood048_1K/Wood048_1K_Light.jpg",this.context.scene),f=new vi.g("assets/textures/Wood048_1K/Wood048_1K_NormalGL.jpg",this.context.scene);d.uScale=.3,d.vScale=.3,d.wAng=Math.PI/2,u.uScale=.3,u.vScale=.3,u.wAng=Math.PI/2,f.uScale=.3,f.vScale=.3,f.wAng=Math.PI/2;const p=new zm("roof",this.context.scene);p.albedoTexture=u,p.microSurfaceTexture=f,p.metallic=0,p.roughness=1,p.zOffset=2;const _=new zm("walls",this.context.scene);return _.albedoTexture=d,_.microSurfaceTexture=f,_.metallic=0,_.roughness=1,_.zOffset=2,s.material=p,o.material=_,l.material=p,c.material=p,r.setParent(t),a.setParent(t),n.setParent(t),h.setParent(t),t}))}}class GK{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.wingtipVilla=new VK(this.occWorkerManager,this.context,this.draw,this.occt),this.chirpyChalet=new UK(this.occWorkerManager,this.context,this.draw,this.occt)}}class zK{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.birdhouses=new GK(this.occWorkerManager,this.context,this.draw,this.occt)}}var WK,XK,qK,YK,KK,jK,$K=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class QK{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return $K(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.serenitySwirl",e);return t?{type:t.data.type,name:t.data.name,compound:t.compound}:void 0}))}drawModel(e,t=.003){return $K(this,void 0,void 0,(function*(){const i=new Yt("brepMesh"+Math.random(),this.context.scene),r=new QH.DrawOcctShapeOptions;r.faceOpacity=0,r.edgeColour="#bc7e5b",r.edgeWidth=.6,r.precision=t;const s=yield this.draw.drawAnyAsync({entity:e.compound,options:r}),n=new zm("brepMaterial"+Math.random(),this.context.scene);return n.albedoColor=new hc.v9(1,1,1),n.ambientColor=hc.v9.FromHexString("#ffffff"),n.metallic=0,n.roughness=.7,n.zOffset=1,s.getChildMeshes()[0].material=n,s.material=n,s.parent=i,i}))}dispose(e){return $K(this,void 0,void 0,(function*(){const t=[e.compound];yield this.occt.deleteShapes({shapes:t})}))}}!function(e){e.low="low",e.middle="middle",e.high="high"}(WK||(WK={}));class ZK{constructor(){this.lod=WK.low}}class JK{}class ej{constructor(e,t,i,r,s,n,o,a,l){this.swirl=.6,this.nrOfDivisions=10,this.addRadiusNarrow=.4,this.addRadiusWide=.2,this.addMiddleHeight=1.6,this.addTopHeight=1.5,this.thickness=1,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.swirl=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.addRadiusNarrow=i),void 0!==r&&(this.addRadiusWide=r),void 0!==s&&(this.addMiddleHeight=s),void 0!==n&&(this.addTopHeight=n),void 0!==o&&(this.thickness=o),void 0!==a&&(this.rotation=a),void 0!==l&&(this.origin=l)}}class tj{constructor(){this.type="parametric-model",this.name="serenitySwirl"}}class ij{}class rj{constructor(e,t,i,r,s,n,o,a,l,h,c,u){this.profilePoints=[[2,0,0],[4,5,0],[1.5,10,0],[3,14,0]],this.nrOfSides=6,this.nrOfVerticalArches=4,this.archCenterThickness=.8,this.edgesThickness=.2,this.thickness=1,this.baseHeight=.4,this.patchHoles=!0,this.lod=WK.high,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],this.scale=[1,1,1],void 0!==e&&(this.nrOfSides=e),void 0!==t&&(this.nrOfVerticalArches=t),void 0!==i&&(this.archCenterThickness=i),void 0!==r&&(this.edgesThickness=r),void 0!==s&&(this.thickness=s),void 0!==n&&(this.baseHeight=n),void 0!==o&&(this.patchHoles=o),void 0!==a&&(this.lod=a),void 0!==l&&(this.rotation=l),void 0!==h&&(this.origin=h),void 0!==c&&(this.direction=c),void 0!==u&&(this.scale=u)}}class sj{constructor(){this.type="parametric-model",this.name="arabicArchway"}}class nj{}class oj{}class aj{}class lj{constructor(e,t,i,r,s,n,o,a){this.textHeading="LOVE YOU",this.textName="NORA",this.fullModel=!0,this.thickness=6,this.decorationThickness=1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.textHeading=e),void 0!==t&&(this.textName=t),void 0!==i&&(this.fullModel=i),void 0!==r&&(this.thickness=r),void 0!==s&&(this.decorationThickness=s),void 0!==n&&(this.rotation=n),void 0!==o&&(this.origin=o),void 0!==a&&(this.direction=a)}}class hj{constructor(){this.type="parametric-model",this.name="eternalLove"}}class cj{}class uj{constructor(e,t,i,r,s,n,o,a,l,h,c,u){this.height=6,this.radiusBottom=4,this.radiusTopOffset=2,this.thickness=.6,this.fillet=.2,this.nrOfHandles=1,this.handleDist=2,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.radiusBottom=t),void 0!==i&&(this.radiusTopOffset=i),void 0!==r&&(this.thickness=r),void 0!==s&&(this.fillet=s),void 0!==n&&(this.nrOfHandles=n),void 0!==o&&(this.handleDist=o),void 0!==a&&(this.precision=a),void 0!==l&&(this.rotation=l),void 0!==h&&(this.scale=h),void 0!==c&&(this.origin=c),void 0!==u&&(this.direction=u)}}class dj{constructor(){this.type="parametric-model",this.name="calmCup"}}class fj{}class pj{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m,g,v,x,b){this.height=8,this.radiusBottom=4,this.radiusTopOffset=2,this.radiusMidOffset=2,this.rotationTopAngle=20,this.rotationMidAngle=20,this.nrSkinCellsVertical=5,this.nrSkinCellsHorizontal=10,this.nrSkinCellDivisionsTop=1,this.nrSkinCellDivisionsBottom=3,this.skinCellOuterHeight=.4,this.skinCellInnerHeight=.3,this.skinCellBottomHeight=.4,this.skinCellTopHeight=.4,this.thickness=.6,this.bottomThickness=1,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.radiusBottom=t),void 0!==i&&(this.radiusTopOffset=i),void 0!==r&&(this.radiusMidOffset=r),void 0!==s&&(this.rotationTopAngle=s),void 0!==n&&(this.rotationMidAngle=n),void 0!==o&&(this.nrSkinCellsVertical=o),void 0!==a&&(this.nrSkinCellsHorizontal=a),void 0!==l&&(this.nrSkinCellDivisionsTop=l),void 0!==h&&(this.nrSkinCellDivisionsBottom=h),void 0!==c&&(this.skinCellOuterHeight=c),void 0!==u&&(this.skinCellInnerHeight=u),void 0!==d&&(this.skinCellBottomHeight=d),void 0!==f&&(this.skinCellTopHeight=f),void 0!==p&&(this.thickness=p),void 0!==_&&(this.bottomThickness=_),void 0!==m&&(this.precision=m),void 0!==g&&(this.rotation=g),void 0!==v&&(this.scale=v),void 0!==x&&(this.origin=x),void 0!==b&&(this.direction=b)}}class _j{constructor(){this.type="parametric-model",this.name="dragonCup"}}class mj{}class gj{}class vj{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m,g){this.heightBottom=5,this.heightTop=16,this.widthBack=25,this.widthFront=10,this.length=16,this.backOffset=6,this.thickness=.4,this.applyOrnaments=!1,this.filletRadius=2,this.phoneHeight=16.8,this.phoneWidth=7.8,this.phoneThickness=.7,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.heightBottom=e),void 0!==t&&(this.heightTop=t),void 0!==i&&(this.widthBack=i),void 0!==r&&(this.widthFront=r),void 0!==s&&(this.length=s),void 0!==n&&(this.backOffset=n),void 0!==o&&(this.thickness=o),void 0!==a&&(this.applyOrnaments=a),void 0!==l&&(this.filletRadius=l),void 0!==h&&(this.phoneHeight=h),void 0!==c&&(this.phoneWidth=c),void 0!==u&&(this.phoneThickness=u),void 0!==d&&(this.precision=d),void 0!==f&&(this.drawEdges=f),void 0!==p&&(this.rotation=p),void 0!==_&&(this.scale=_),void 0!==m&&(this.origin=m),void 0!==g&&(this.direction=g)}}class xj{constructor(){this.type="parametric-model",this.name="phoneNest"}}class bj extends JK{}class Sj{}class Tj extends JK{}class Cj{}class yj{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class Ej{}class Pj{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m,g,v){this.textTop="Pepper",this.textFront="For Your Spicy Needs",this.nrSides=4,this.nrOffsets=1,this.height=6,this.radiusBase=4,this.radiusOffset=2,this.coverHeight=1,this.baseHeight=1,this.thickness=.6,this.ornamentalThickness=.1,this.nrOrnamnetsPerSide=10,this.invertOrnaments=!1,this.fillet=.2,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.textTop=e),void 0!==t&&(this.textFront=t),void 0!==i&&(this.nrSides=i),void 0!==r&&(this.nrOffsets=r),void 0!==s&&(this.height=s),void 0!==n&&(this.coverHeight=n),void 0!==o&&(this.baseHeight=o),void 0!==a&&(this.radiusBase=a),void 0!==l&&(this.radiusOffset=l),void 0!==h&&(this.thickness=h),void 0!==c&&(this.ornamentalThickness=c),void 0!==u&&(this.nrOrnamnetsPerSide=u),void 0!==d&&(this.invertOrnaments=d),void 0!==f&&(this.fillet=f),void 0!==p&&(this.precision=p),void 0!==_&&(this.rotation=_),void 0!==m&&(this.scale=m),void 0!==g&&(this.origin=g),void 0!==v&&(this.direction=v)}}class Aj{constructor(){this.type="parametric-model",this.name="spicyBox"}}class Rj{}class Ij{}class Mj{constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m,g,v,x,b,S,T,C,y,E,P,A,R,I){this.widthFirstWing=4,this.lengthFirstWing=10,this.terraceWidth=3,this.widthSecondWing=5,this.lengthSecondWing=10,this.heightWalls=3,this.roofAngleFirstWing=15,this.roofAngleSecondWing=25,this.roofOffset=.5,this.roofInsideOverhang=.5,this.roofMaxDistAttachmentBeams=.8,this.roofAttachmentBeamWidth=.2,this.roofAttachmentBeamHeight=.05,this.roofOutsideOverhang=.5,this.columnSize=.3,this.ceilingBeamHeight=.25,this.ceilingBeamWidth=.1,this.nrCeilingBeamsBetweenColumns=3,this.distBetweenColumns=2,this.floorHeight=.1,this.groundLevel=.6,this.facadePanelThickness=.05,this.windowWidthOffset=.1,this.windowHeightOffset=.2,this.windowFrameThickness=.1,this.windowGlassFrameThickness=.05,this.lod=WK.high,this.skinOpacity=1,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.widthFirstWing=e),void 0!==t&&(this.lengthFirstWing=t),void 0!==i&&(this.terraceWidth=i),void 0!==r&&(this.widthSecondWing=r),void 0!==s&&(this.lengthSecondWing=s),void 0!==n&&(this.heightWalls=n),void 0!==o&&(this.roofAngleFirstWing=o),void 0!==a&&(this.roofAngleSecondWing=a),void 0!==l&&(this.roofOffset=l),void 0!==h&&(this.roofInsideOverhang=h),void 0!==c&&(this.roofMaxDistAttachmentBeams=c),void 0!==u&&(this.roofAttachmentBeamWidth=u),void 0!==d&&(this.roofAttachmentBeamHeight=d),void 0!==f&&(this.roofOutsideOverhang=f),void 0!==p&&(this.columnSize=p),void 0!==_&&(this.ceilingBeamHeight=_),void 0!==m&&(this.ceilingBeamWidth=m),void 0!==g&&(this.nrCeilingBeamsBetweenColumns=g),void 0!==v&&(this.distBetweenColumns=v),void 0!==x&&(this.floorHeight=x),void 0!==b&&(this.groundLevel=b),void 0!==S&&(this.facadePanelThickness=S),void 0!==T&&(this.windowWidthOffset=T),void 0!==C&&(this.windowHeightOffset=C),void 0!==y&&(this.windowFrameThickness=y),void 0!==E&&(this.windowGlassFrameThickness=E),void 0!==P&&(this.lod=P),void 0!==A&&(this.skinOpacity=A),void 0!==R&&(this.rotation=R),void 0!==I&&(this.origin=I)}}class Oj{constructor(){this.type="parametric-model",this.name="zenHideout"}}class Dj{}class wj{}class Nj{constructor(){this.wallThickness=.4,this.facadePanelThickness=.05,this.glassFrameThickness=.02,this.glassThickness=.005,this.frameThckness=.05,this.height=3,this.lengthFirst=1,this.lengthSecond=2,this.rotation=0}}class Fj{constructor(){this.thickness=.3,this.glassFrameThickness=.02,this.glassThickness=.005,this.frameThickness=.05,this.height=3,this.width=1,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0]}}class Lj extends Fj{}class Bj extends Nj{}class Vj{constructor(){this.name="sandwitch-panel",this.createWindow=!0,this.createInnerPanel=!0,this.createExteriorPanel=!0,this.wallWidth=.3,this.exteriorPanelWidth=.4,this.exteriorPanelHeight=3,this.exteriorPanelThickness=.05,this.exteriorPanelBottomOffset=0,this.interiorPanelWidth=.4,this.interiorPanelHeight=3,this.interiorPanelThickness=.05,this.interiorPanelBottomOffset=0,this.windowWidthOffset=0,this.windowHeightOffset=0,this.windowFrameThickness=.1,this.windowGlassFrameThickness=.05}}class kj{constructor(){this.name="sandwitch-panel-flex",this.createInteriorPanel=!0,this.createExteriorPanel=!0,this.wallWidth=.3,this.exteriorPanelThickness=.05,this.interiorPanelThickness=.05,this.interiorPanelPolygonPoints=[],this.exteriorPanelPolygonPoints=[]}}class Uj extends Vj{}class Gj extends kj{}class zj{}class Wj{}class Hj{}class Xj{}class qj{}class Yj{}class Kj{constructor(){this.invert=!1,this.widthFirstLanding=1,this.widthSecondLanding=1,this.lengthFirstWing=2,this.lengthSecondWing=1,this.maxWishedStepHeight=.25,this.stepHeightWidthProportion=1.35,this.totalHeight=1,this.rotation=0,this.origin=[0,0,0]}}class jj extends Kj{}class $j{}class Qj{constructor(){this.name="roof-cover",this.roofAngle=15,this.roofLength=3,this.roofWidth=3,this.roofOutsideOverhang=.5,this.roofInsideOverhang=1,this.roofOverhangFacade=.1,this.roofThickness=.05,this.roofCoverHeight=.3,this.rotation=0,this.lod=WK.high,this.center=[0,0,0],this.direction=[0,1,0]}}class Zj extends Qj{}class Jj{}class e${}class t${constructor(){this.widthFirstWing=1,this.widthSecondWing=2,this.lengthStairFirstWing=2,this.lengthStairSecondWing=1,this.lengthWallFirstWing=2,this.lengthWallSecondWing=1,this.facadePanelThickness=.05,this.wallThickness=3,this.wallHeightExterior=3,this.wallHeightInterior=3,this.windowFrameOffsetTop=.3,this.windowFrameThickness=.1,this.glassFrameThickness=.05,this.doorWidth=1,this.windowWidthOffset=.3,this.stairTotalHeight=1,this.createStair=!1,this.flipDirection=!1,this.rotation=0,this.origin=[0,0,0]}}class i${constructor(e,t,i,r,s,n,o,a,l,h,c,u,d){this.interiorWidth=3,this.interiorLength=3,this.interiorHeight=5,this.thickness=.5,this.holeDiameter=1.5,this.holeDistToBottom=2.5,this.stickLength=1.2,this.stickDiameter=.5,this.baseAttachmentHeight=2,this.roofOverhang=1,this.rotation=0,this.chimneyHeight=1,this.origin=[0,0,0],void 0!==e&&(this.interiorWidth=e),void 0!==t&&(this.interiorLength=t),void 0!==i&&(this.interiorHeight=i),void 0!==r&&(this.thickness=r),void 0!==s&&(this.holeDiameter=s),void 0!==n&&(this.holeDistToBottom=n),void 0!==o&&(this.stickLength=o),void 0!==a&&(this.stickDiameter=a),void 0!==l&&(this.baseAttachmentHeight=l),void 0!==h&&(this.roofOverhang=h),void 0!==c&&(this.rotation=c),void 0!==u&&(this.chimneyHeight=u),void 0!==d&&(this.origin=d)}}class r${constructor(){this.type="parametric-model",this.name="wingtipVilla"}}class s${constructor(e,t,i,r,s,n,o,a,l,h,c,u,d){this.interiorWidth=3,this.interiorLength=3,this.interiorHeight=5,this.thickness=.3,this.holeDiameter=1.2,this.holeDistToBottom=2.5,this.stickLength=.9,this.stickDiameter=.3,this.baseAttachmentHeight=2,this.roofOverhang=.5,this.roofAngle=20,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.interiorWidth=e),void 0!==t&&(this.interiorLength=t),void 0!==i&&(this.interiorHeight=i),void 0!==r&&(this.thickness=r),void 0!==s&&(this.holeDiameter=s),void 0!==n&&(this.holeDistToBottom=n),void 0!==o&&(this.stickLength=o),void 0!==a&&(this.stickDiameter=a),void 0!==l&&(this.baseAttachmentHeight=l),void 0!==h&&(this.roofOverhang=h),void 0!==c&&(this.roofAngle=c),void 0!==u&&(this.rotation=u),void 0!==d&&(this.origin=d)}}class n${constructor(){this.type="parametric-model",this.name="chirpyChalet"}}class o${}class a${constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p){this.sittingHeight=.45,this.backRestOffset=.1,this.backRestHeight=.7,this.width=.45,this.length=.45,this.thickness=.05,this.nrOrnamentPlanks=7,this.ornamentDepth=.01,this.filletRadius=.05,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.sittingHeight=e),void 0!==t&&(this.backRestOffset=t),void 0!==i&&(this.backRestHeight=i),void 0!==r&&(this.width=r),void 0!==s&&(this.length=s),void 0!==n&&(this.thickness=n),void 0!==o&&(this.nrOrnamentPlanks=o),void 0!==a&&(this.ornamentDepth=a),void 0!==l&&(this.filletRadius=l),void 0!==h&&(this.precision=h),void 0!==c&&(this.drawEdges=c),void 0!==u&&(this.rotation=u),void 0!==d&&(this.scale=d),void 0!==f&&(this.origin=f),void 0!==p&&(this.direction=p)}}class l${constructor(){this.type="parametric-model",this.name="snakeChair"}}class h$ extends JK{}class c${}class u$ extends JK{}class d${}class f${constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class p${}class _${constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_){this.height=.74,this.width=1,this.length=2,this.topThickness=.02,this.topOffset=.03,this.bottomThickness=.05,this.minFillet=.2,this.radiusLegTop=.03,this.radiusLegBottom=.01,this.nrLegPairs=2,this.precision=.001,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==r&&(this.topThickness=r),void 0!==s&&(this.topOffset=s),void 0!==n&&(this.bottomThickness=n),void 0!==o&&(this.minFillet=o),void 0!==a&&(this.radiusLegTop=a),void 0!==l&&(this.radiusLegBottom=l),void 0!==h&&(this.nrLegPairs=h),void 0!==c&&(this.precision=c),void 0!==u&&(this.drawEdges=u),void 0!==d&&(this.rotation=d),void 0!==f&&(this.scale=f),void 0!==p&&(this.origin=p),void 0!==_&&(this.direction=_)}}class m${constructor(){this.type="parametric-model",this.name="elegantTable"}}class g$ extends JK{}class v${}class x$ extends JK{}class b$ extends JK{}class S${constructor(){this.index=0}}class T${}class C${constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class y${}class E${constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m,g){this.height=.4,this.width=1,this.length=1.2,this.chamfer=.01,this.topThickness=.05,this.topGlassOffset=.2,this.glassThickness=.005,this.glassHolderLength=.02,this.shelfTopOffset=.15,this.shelfThickness=.03,this.legWidth=.1,this.legDepth=.05,this.precision=.001,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==r&&(this.chamfer=r),void 0!==s&&(this.topThickness=s),void 0!==n&&(this.topGlassOffset=n),void 0!==o&&(this.glassThickness=o),void 0!==a&&(this.glassHolderLength=a),void 0!==l&&(this.shelfTopOffset=l),void 0!==h&&(this.shelfThickness=h),void 0!==c&&(this.legWidth=c),void 0!==u&&(this.legDepth=u),void 0!==d&&(this.precision=d),void 0!==f&&(this.drawEdges=f),void 0!==p&&(this.rotation=p),void 0!==_&&(this.scale=_),void 0!==m&&(this.origin=m),void 0!==g&&(this.direction=g)}}class P${constructor(){this.type="parametric-model",this.name="goodCoffeeTable"}}class A$ extends JK{}class R${}class I$ extends JK{}class M$ extends JK{}class O$ extends JK{}class D${constructor(){this.index=0}}class w${}class N${constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class F${}class L${constructor(e,t,i,r,s,n,o,a,l,h,c,u,d,f,p,_,m){this.height=.74,this.width=1,this.length=2,this.supportLength=.5,this.shelfHeight=.2,this.thickness=.05,this.glassThickness=.005,this.glassOffset=0,this.nrOrnamentPlanks=7,this.ornamentDepth=.01,this.filletRadius=.05,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==r&&(this.supportLength=r),void 0!==s&&(this.shelfHeight=s),void 0!==n&&(this.thickness=n),void 0!==o&&(this.glassThickness=o),void 0!==a&&(this.glassOffset=a),void 0!==l&&(this.nrOrnamentPlanks=l),void 0!==h&&(this.ornamentDepth=h),void 0!==c&&(this.filletRadius=c),void 0!==u&&(this.precision=u),void 0!==d&&(this.drawEdges=d),void 0!==f&&(this.rotation=f),void 0!==p&&(this.scale=p),void 0!==_&&(this.origin=_),void 0!==m&&(this.direction=m)}}class B${constructor(){this.type="parametric-model",this.name="snakeTable"}}class V$ extends JK{}class k${}class U$ extends JK{}class G${}class z${constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}!function(e){e.Aboreto="Aboreto",e.Bungee="Bungee",e.IndieFlower="IndieFlower",e.Lugrasimo="Lugrasimo",e.Orbitron="Orbitron",e.Roboto="Roboto",e.RobotoSlab="RobotoSlab",e.Silkscreen="Silkscreen",e.Tektur="Tektur",e.Workbench="Workbench"}(XK||(XK={})),function(e){e.Regular="Regular",e.Black="Black",e.Bold="Bold",e.ExtraBold="ExtraBold",e.Medium="Medium",e.SemiBold="SemiBold",e.BlackItalic="BlackItalic",e.BoldItalic="BoldItalic",e.Italic="Italic",e.Light="Light",e.LightItalic="LightItalic",e.MediumItalic="MediumItalic",e.Thin="Thin",e.ThinItalic="ThinItalic",e.ExtraLight="ExtraLight"}(qK||(qK={})),function(e){e.separatedExtrusion="separatedExtrusion",e.integratedExtrusion="integratedExtrusion",e.cutout="cutout"}(YK||(YK={})),function(e){e.compound="compound",e.cutout="originalCutout",e.cutoutInsideCharacter="cutoutInsideCharacter"}(KK||(KK={})),function(e){e.leftTop="leftTop",e.leftMiddle="leftMiddle",e.leftBottom="leftBottom",e.centerTop="centerTop",e.centerMiddle="centerMiddle",e.centerBottom="centerBottom",e.rightTop="rightTop",e.rightMiddle="rightMiddle",e.rightBottom="rightBottom"}(jK||(jK={}));const W$=[{key:"Aboreto",variants:["Regular"]},{key:"Bungee",variants:["Regular"]},{key:"IndieFlower",variants:["Regular"]},{key:"Lugrasimo",variants:["Regular"]},{key:"Orbitron",variants:["Black","Bold","ExtraBold","Medium","Regular","SemiBold"]},{key:"Roboto",variants:["Black","BlackItalic","Bold","BoldItalic","Italic","Light","LightItalic","Medium","MediumItalic","Regular","Thin","ThinItalic"]},{key:"RobotoSlab",variants:["Black","Bold","ExtraBold","ExtraLight","Light","Medium","Regular","SemiBold","Thin"]},{key:"Silkscreen",variants:["Bold","Regular"]},{key:"Tektur",variants:["Black","Bold","ExtraBold","Medium","Regular","SemiBold"]},{key:"Workbench",variants:["Regular"]}];class H${constructor(e,t,i,r,s,n,o,a,l){this.text="bitbybit.dev",this.fontType=XK.Roboto,this.fontVariant=qK.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.origin=[0,0,0],this.direction=[0,1,0],this.originAlignment=jK.centerMiddle,void 0!==e&&(this.text=e),void 0!==t&&(this.fontType=t),void 0!==i&&(this.fontVariant=i),void 0!==r&&(this.fontSize=r),void 0!==s&&(this.height=s),void 0!==n&&(this.rotation=n),void 0!==o&&(this.origin=o),void 0!==a&&(this.direction=a),void 0!==l&&(this.originAlignment=l)}}class X${constructor(e,t,i,r,s,n,o,a,l,h,c,u){this.facePlanar=!1,this.faceTextVar=YK.separatedExtrusion,this.text="bitbybit.dev",this.fontType=XK.Roboto,this.fontVariant=qK.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.originParamU=.5,this.originParamV=.5,this.originAlignment=jK.centerMiddle,void 0!==e&&(this.face=e),void 0!==t&&(this.facePlanar=t),void 0!==i&&(this.faceTextVar=i),void 0!==r&&(this.text=r),void 0!==s&&(this.fontType=s),void 0!==n&&(this.fontVariant=n),void 0!==o&&(this.fontSize=o),void 0!==a&&(this.height=a),void 0!==l&&(this.rotation=l),void 0!==h&&(this.originParamU=h),void 0!==c&&(this.originParamV=c),void 0!==u&&(this.originAlignment=u)}}class q${constructor(){this.type="parametric-model",this.name="text3d"}}class Y${constructor(){this.index=0}}class K${}class j${}class $${constructor(e,t,i,r,s,n,o,a,l,h){this.faceTextVar=YK.separatedExtrusion,this.text="bitbybit.dev",this.fontType=XK.Roboto,this.fontVariant=qK.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.originParamU=.5,this.originParamV=.5,this.originAlignment=jK.centerMiddle,void 0!==e&&(this.faceTextVar=e),void 0!==t&&(this.text=t),void 0!==i&&(this.fontType=i),void 0!==r&&(this.fontVariant=r),void 0!==s&&(this.fontSize=s),void 0!==n&&(this.height=n),void 0!==o&&(this.rotation=o),void 0!==a&&(this.originParamU=a),void 0!==l&&(this.originParamV=l),void 0!==h&&(this.originAlignment=h)}}class Q${constructor(e,t,i){this.facePlanar=!1,void 0!==e&&(this.face=e),void 0!==t&&(this.facePlanar=t),void 0!==i&&(this.definitions=i)}}class Z${constructor(e,t,i,r){this.uNumber=10,this.vNumber=10,this.height=.2,this.precision=.01,void 0!==e&&(this.faces=e),void 0!==r&&(this.height=r)}}class J${constructor(e,t,i,r,s,n,o){this.uNumber=10,this.vNumber=5,this.defaultHeight=.2,this.affectMinHeight=0,this.affectMaxHeight=1,this.precision=.01,void 0!==e&&(this.faces=e),void 0!==t&&(this.affectorPoints=t),void 0!==i&&(this.uNumber=i),void 0!==r&&(this.vNumber=r),void 0!==s&&(this.affectMinHeight=s),void 0!==n&&(this.affectMaxHeight=n),void 0!==o&&(this.precision=o)}}class eQ{constructor(){this.type="parametric-model",this.name="patternsFacePatternPyramidSimple"}}class tQ{constructor(){this.index=0}}class iQ{}class rQ{}class sQ{}class nQ{}class oQ{constructor(){this.faceIndex=0}}class aQ{constructor(){this.faceIndex=0,this.uIndex=0,this.vIndex=0}}class lQ{constructor(){this.faceIndex=0,this.uIndex=0}}class hQ{constructor(){this.faceIndex=0,this.vIndex=0}}class cQ{}class uQ{}var dQ;!function(e){e.wire="wire",e.face="face",e.solid="solid"}(dQ||(dQ={}));class fQ{static parse(e,t){var i;const r=[e],s=new Set;for(;r.length>0;){const e=r.pop();if("object"==typeof e&&null!==e&&!s.has(e))if(s.add(e),Array.isArray(e))for(let t=0;tt.id===e.shapes[s])))||void 0===i?void 0:i.shape)}for(const t in e)r.push(e[t])}}return e}}var pQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class _Q{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return pQ(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.arabicArchway",e);if(t){const e=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},e),{type:t.data.type,name:t.data.name,compound:t.compound,shapes:t.shapes,originalInputs:t.data.originalInputs})}}))}drawModel(e,t=.003){return pQ(this,void 0,void 0,(function*(){const i=new Yt("brepMesh"+Math.random(),this.context.scene),r=new QH.DrawOcctShapeOptions;this.materials||(this.materials=this.createMaterials(e.originalInputs.lod)),r.faceOpacity=0,r.edgeColour="#bc7e5b",r.edgeWidth=.6,r.precision=t;const s={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?e.originalInputs.lod===WK.high&&"compound"===t?i(void 0):this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:r}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,t)=>{const r=o[t];if(r){if(r.parent=i,void 0!==this.materials[e]){const t=r.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}r.name=e,r.getChildMeshes().forEach((e=>e.isVisible=!0)),s[e]=r}})),i}))}dispose(e){return pQ(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}disposeMaterials(){this.materials&&Object.keys(this.materials).forEach((e=>{const t=this.materials[e];t&&t.dispose()}))}createMaterials(e){const t=new oj;return e===WK.high?t.compound=this.createBaseMaterial():t.compound=this.createOpaqueMaterial(),t.vasePartsCompound=this.createBaseMaterial(),t.glassPartsCompound=this.createGlassMaterial(),t.vaseBaseCompound=this.createBaseMaterial(),t}createOpaqueMaterial(){const e=new zm("opaqueMat"+Math.random(),this.context.scene);return e.albedoColor=new hc.v9(1,1,1),e.ambientColor=hc.v9.FromHexString("#ffffff"),e.metallic=0,e.roughness=.7,e.zOffset=1,e.backFaceCulling=!1,e.alpha=.3,e}createBaseMaterial(){const e=new zm("faceMaterial"+Math.random(),this.context.scene);return e.albedoColor=new hc.v9(1,1,1),e.ambientColor=hc.v9.FromHexString("#ffffff"),e.metallic=0,e.roughness=.7,e.zOffset=1,e}createGlassMaterial(){const e=new zm("faceGlassMaterial"+Math.random(),this.context.scene);return e.albedoColor=new hc.v9(0,0,.05),e.ambientColor=hc.v9.FromHexString("#ffffff"),e.metallic=.8,e.roughness=.1,e.zOffset=1,e.alpha=.5,e}}class mQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.serenitySwirl=new QK(this.occWorkerManager,this.context,this.draw,this.occt),this.arabicArchway=new _Q(this.occWorkerManager,this.context,this.draw,this.occt)}}var gQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class vQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return gQ(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.eternalLove",e);return t?{type:t.data.type,originalInputs:t.data.originalInputs,name:t.data.name,compound:t.compound}:void 0}))}drawModel(e,t=.003){return gQ(this,void 0,void 0,(function*(){const i=new Yt("brepMesh"+Math.random(),this.context.scene),r=new QH.DrawOcctShapeOptions;r.faceOpacity=0,r.edgeColour="#bc7e5b",r.edgeWidth=.6,r.precision=t;const s=yield this.draw.drawAnyAsync({entity:e.compound,options:r}),n=new zm("brepMaterial"+Math.random(),this.context.scene);return n.albedoColor=new hc.v9(1,.9,1),n.ambientColor=hc.v9.FromHexString("#ff00ff"),n.metallic=.8,n.roughness=.7,n.zOffset=1,s.getChildMeshes()[0].material=n,s.material=n,s.parent=i,i}))}dispose(e){return gQ(this,void 0,void 0,(function*(){const t=[e.compound];yield this.occt.deleteShapes({shapes:t})}))}}class xQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.eternalLove=new vQ(this.occWorkerManager,this.context,this.draw,this.occt)}}var bQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class SQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return bQ(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.calmCup",e);return t?{type:t.data.type,originalInputs:t.data.originalInputs,name:t.data.name,compound:t.compound}:void 0}))}drawModel(e){return bQ(this,void 0,void 0,(function*(){const t=new Yt("brepMesh"+Math.random(),this.context.scene),i=new QH.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#bc7e5b",i.edgeWidth=.6*e.originalInputs.scale,i.precision=e.originalInputs.precision*e.originalInputs.scale;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:i}),s=new zm("brepMaterial"+Math.random(),this.context.scene);return s.albedoColor=new hc.v9(1,1,1),s.ambientColor=hc.v9.FromHexString("#ffffff"),s.metallic=.8,s.roughness=.7,s.zOffset=2,r.getChildMeshes()[0].material=s,r.material=s,r.parent=t,t}))}dispose(e){return bQ(this,void 0,void 0,(function*(){const t=[e.compound];yield this.occt.deleteShapes({shapes:t})}))}}var TQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class CQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return TQ(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.dragonCup",e);return t?{type:t.data.type,originalInputs:t.data.originalInputs,name:t.data.name,compound:t.compound}:void 0}))}getCompoundShape(e){return e.model.compound}drawModel(e){return TQ(this,void 0,void 0,(function*(){const t=new Yt("brepMesh"+Math.random(),this.context.scene),i=new QH.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#617bff",i.edgeWidth=.6*e.originalInputs.scale,i.precision=e.originalInputs.precision*e.originalInputs.scale;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:i}),s=new zm("brepMaterial"+Math.random(),this.context.scene);return s.albedoColor=hc.v9.FromHexString("#2b00ff"),s.ambientColor=hc.v9.FromHexString("#ffffff"),s.metallic=.9,s.roughness=.3,s.zOffset=2,r.getChildMeshes()[0].material=s,r.material=s,r.parent=t,t}))}}class yQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.calmCup=new SQ(this.occWorkerManager,this.context,this.draw,this.occt),this.dragonCup=new CQ(this.occWorkerManager,this.context,this.draw,this.occt)}}var EQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class PQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return EQ(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.main.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.phoneNest",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}drawOptions(e){return e}drawModel(e,t){return EQ(this,void 0,void 0,(function*(){const i=new Yt("brepMesh"+Math.random(),this.context.scene),r=new QH.DrawOcctShapeOptions;t?(r.drawEdges=t.drawEdges,r.drawFaces=t.drawFaces,r.edgeColour=t.edgeColour,r.edgeWidth=t.edgeWidth,r.precision=t.precision):(r.faceOpacity=0,r.drawEdges=e.originalInputs.drawEdges,r.edgeColour="#ffffff",r.edgeWidth=.06*e.originalInputs.scale,r.precision=e.originalInputs.precision*e.originalInputs.scale);const s={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?("phone"===t&&(r.edgeColour="#000000"),this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:r}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)}))):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,r)=>{const n=o[r];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),s[e]=n}})),i}))}dispose(e){return EQ(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="phone-nest-",t=new Sj,i=LK.wood3Material(this.context.scene,Math.PI/2,1);i.name=e+i.name,t.main=i;const r=LK.glass(this.context.scene,"#000000");return r.name=e+r.name,t.phone=r,t}}class AQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.phoneNest=new PQ(this.occWorkerManager,this.context,this.draw,this.occt)}}class RQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.vases=new mQ(this.occWorkerManager,this.context,this.draw,this.occt),this.cups=new yQ(this.occWorkerManager,this.context,this.draw,this.occt),this.medals=new xQ(this.occWorkerManager,this.context,this.draw,this.occt),this.desktop=new AQ(this.occWorkerManager,this.context,this.draw,this.occt)}}var IQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class MQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return IQ(this,void 0,void 0,(function*(){void 0===this.materials&&(this.materials=this.createMaterials()),void 0===this.skin&&(this.skin=this.createSkin());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.zenHideout",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}drawModel(e,t=.003){return IQ(this,void 0,void 0,(function*(){const i=new Yt("brepMesh"+Math.random(),this.context.scene),r=new QH.DrawOcctShapeOptions;if(r.faceOpacity=0,r.edgeColour="#bc7e5b",r.edgeWidth=.06,r.precision=t,e.originalInputs.lod===WK.high&&e.drawingPart){const t={},s=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:r}).then((r=>{r.isVisible=!1,r.getChildMeshes().forEach((e=>e.isVisible=!1)),!0===this.skin[t]&&(r.visibility=e.originalInputs.skinOpacity,r.getChildMeshes().forEach((t=>t.visibility=e.originalInputs.skinOpacity))),i(r)}),(()=>{i(void 0)})):i(void 0)})))),n=yield Promise.all(s);Object.keys(e.drawingPart.shapes).forEach(((e,r)=>{const s=n[r];if(s){if(s.parent=i,void 0!==this.materials[e]){const t=s.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}s.name=e,s.isVisible=!0,s.getChildMeshes().forEach((e=>e.isVisible=!0)),t[e]=s}}))}else if(e.originalInputs.lod===WK.middle){const t=new zm("brepMaterial"+Math.random(),this.context.scene);t.albedoColor=new hc.v9(0,0,0),t.metallic=0,t.roughness=.7,t.zOffset=2;const s=yield this.draw.drawAnyAsync({entity:e.compound,options:r});s.getChildMeshes()[0].material=t,s.material=t,s.parent=i}else e.originalInputs.lod===WK.low&&(r.edgeColour="#e89668",r.edgeWidth=10,(yield this.draw.drawAnyAsync({entity:e.compound,options:r})).parent=i);return i}))}dispose(e){return IQ(this,void 0,void 0,(function*(){const t=e.shapes.map((e=>e.shape));yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="zen-hideout-",t=new wj,i=new Cb(e+"windowGlassCompound",this.context.scene);i.alpha=.2,i.metallic=.9,i.roughness=.1,i.baseColor=new hc.v9(.9,.9,1),i.zOffset=2,t.windowGlassCompound=i;const r=new Cb(e+"windowGlassCompound",this.context.scene);r.metallic=.1,r.roughness=.8,r.baseColor=new hc.v9(.05,.05,.05),r.zOffset=2,t.windowFrameCompound=r;const s=new Cb(e+"glassFramesCompound",this.context.scene);s.metallic=.1,s.roughness=.8,s.baseColor=new hc.v9(0,0,0),s.zOffset=2,t.glassFramesCompound=s;const n=LK.metal1(this.context.scene,0,.3);t.roofCoverFirstCompound=n,t.roofCoverSecondCompound=n;const o=LK.wood1Material(this.context.scene,0,1);t.beamsCompound=o,t.columnsCompound=o;const a=LK.woodenPlanks(this.context.scene,0,1);t.firstFloorExteriorPanelsCompound=a;const l=new Cb(e+"firstFloorInteriorPanelsCompound",this.context.scene);l.metallic=.1,l.roughness=.8,l.baseColor=new hc.v9(.1,.1,.1),l.zOffset=2,t.firstFloorInteriorPanelsCompound=l;const h=LK.wood3Material(this.context.scene,Math.PI/2,1);t.roofExteriorPanelsCompound=h;const c=new Cb(e+"roofInteriorPanelsCompound",this.context.scene);c.metallic=.1,c.roughness=.8,c.baseColor=new hc.v9(.3,.3,.3),c.zOffset=2,t.roofInteriorPanelsCompound=c;const u=LK.wood2Material(this.context.scene,0,.5);t.floorCompound=u;const d=new Cb(e+"ceilingCompound",this.context.scene);d.metallic=.3,d.roughness=.7,d.baseColor=new hc.v9(1,1,1),d.zOffset=2,t.ceilingCompound=d;const f=LK.brushedConcrete(this.context.scene,0,1);return t.stairsCompound=f,t}createSkin(){return{windowGlassCompound:!0,glassFramesCompound:!1,windowFrameCompound:!1,beamsCompound:!1,columnsCompound:!1,firstFloorExteriorPanelsCompound:!0,firstFloorInteriorPanelsCompound:!0,roofExteriorPanelsCompound:!0,roofInteriorPanelsCompound:!0,roofCoverFirstCompound:!0,roofCoverSecondCompound:!0,floorCompound:!0,ceilingCompound:!0,stairsCompound:!1}}}class OQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.zenHideout=new MQ(this.occWorkerManager,this.context,this.draw,this.occt)}}class DQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.houses=new OQ(this.occWorkerManager,this.context,this.draw,this.occt)}}class wQ{lodEnum(e){return e.lod}}var NQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class FQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return NQ(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.top.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.elegantTable",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getLegShapes(e){return e.model.legParts.map((e=>e.shapes.leg))}getLegShapeByIndex(e){return e.index>=0&&e.indexe.bottomCenter))}getLegTopPoints(e){return e.model.legParts.map((e=>e.topCenter))}drawOptions(e){return e}drawModel(e,t){return NQ(this,void 0,void 0,(function*(){const i=new Yt("brepMesh"+Math.random(),this.context.scene),r=new QH.DrawOcctShapeOptions;t?(r.drawEdges=t.drawEdges,r.drawFaces=t.drawFaces,r.edgeColour=t.edgeColour,r.edgeWidth=t.edgeWidth,r.precision=t.precision):(r.faceOpacity=0,r.drawEdges=e.originalInputs.drawEdges,r.edgeColour="#bc7e5b",r.edgeWidth=.06*e.originalInputs.scale,r.precision=e.originalInputs.precision*e.originalInputs.scale);const s={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:r}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,r)=>{const n=o[r];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),s[e]=n}})),i}))}dispose(e){return NQ(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="elegant-table-",t=new v$,i=LK.wood3Material(this.context.scene,Math.PI/2,2);i.name=e+i.name,t.top=i;const r=LK.wood1Material(this.context.scene,Math.PI/2,2);r.name=e+i.name,t.topBase=r;const s=LK.wood1Material(this.context.scene,0,1);return s.name=e+i.name,t.legs=s,t}}var LQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class BQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return LQ(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.top.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.goodCoffeeTable",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getLegShapes(e){return e.model.legParts.map((e=>e.shapes.leg))}getLegShapeByIndex(e){return e.index>=0&&e.indexe.bottomCenter))}getLegTopPoints(e){return e.model.legParts.map((e=>e.topCenter))}drawOptions(e){return e}drawModel(e,t){return LQ(this,void 0,void 0,(function*(){const i=new Yt("brepMesh"+Math.random(),this.context.scene),r=new QH.DrawOcctShapeOptions;t?(r.drawEdges=t.drawEdges,r.drawFaces=t.drawFaces,r.edgeColour=t.edgeColour,r.edgeWidth=t.edgeWidth,r.precision=t.precision):(r.faceOpacity=0,r.drawEdges=e.originalInputs.drawEdges,r.edgeColour="#bc7e5b",r.edgeWidth=.06*e.originalInputs.scale,r.precision=e.originalInputs.precision*e.originalInputs.scale);const s={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:r}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,r)=>{const n=o[r];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),s[e]=n}})),i}))}dispose(e){return LQ(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="good-coffee-table-",t=new R$,i=LK.wood3Material(this.context.scene,Math.PI/2,2);i.name=e+i.name,t.top=i,t.legs=i,t.shelf=i;const r=LK.glass(this.context.scene,"#000000");return r.name=e+i.name,t.topGlass=r,t}}var VQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class kQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return VQ(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.main.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.snakeTable",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getGlassShape(e){return e.model.mainPart.shapes.glass}getMainShape(e){return e.model.mainPart.shapes.main}getTopCenterPoint(e){return e.model.mainPart.topCenter}drawOptions(e){return e}drawModel(e,t){return VQ(this,void 0,void 0,(function*(){const i=new Yt("brepMesh"+Math.random(),this.context.scene),r=new QH.DrawOcctShapeOptions;t?(r.drawEdges=t.drawEdges,r.drawFaces=t.drawFaces,r.edgeColour=t.edgeColour,r.edgeWidth=t.edgeWidth,r.precision=t.precision):(r.faceOpacity=0,r.drawEdges=e.originalInputs.drawEdges,r.edgeColour="#000000",r.edgeWidth=.06*e.originalInputs.scale,r.precision=e.originalInputs.precision*e.originalInputs.scale);const s={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:r}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,r)=>{const n=o[r];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),s[e]=n}})),i}))}dispose(e){return VQ(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="snake-table-",t=new k$,i=LK.roughPlastic(this.context.scene,"#ffffff");i.name=e+i.name,t.main=i;const r=LK.glass(this.context.scene,"#000000");return r.name=e+r.name,t.glass=r,t}}class UQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.elegantTable=new FQ(this.occWorkerManager,this.context,this.draw,this.occt),this.goodCoffeeTable=new BQ(this.occWorkerManager,this.context,this.draw,this.occt),this.snakeTable=new kQ(this.occWorkerManager,this.context,this.draw,this.occt)}}var GQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class zQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return GQ(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.main.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.snakeChair",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getSittingWireShape(e){return e.model.mainPart.shapes.sittingWire}getSittingAreaCenterPoint(e){return e.model.mainPart.sittingCenter}drawOptions(e){return e}drawModel(e,t){return GQ(this,void 0,void 0,(function*(){const i=new Yt("brepMesh"+Math.random(),this.context.scene),r=new QH.DrawOcctShapeOptions;t?(r.drawEdges=t.drawEdges,r.drawFaces=t.drawFaces,r.edgeColour=t.edgeColour,r.edgeWidth=t.edgeWidth,r.precision=t.precision):(r.faceOpacity=0,r.drawEdges=e.originalInputs.drawEdges,r.edgeColour="#000000",r.edgeWidth=.06*e.originalInputs.scale,r.precision=e.originalInputs.precision*e.originalInputs.scale);const s={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:r}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,r)=>{const n=o[r];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),s[e]=n}})),i}))}dispose(e){return GQ(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e=new c$,t=LK.roughPlastic(this.context.scene,"#ffffff");return t.name="snake-chair-"+t.name,e.main=t,e}}class WQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.snakeChair=new zQ(this.occWorkerManager,this.context,this.draw,this.occt)}}class HQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.chairs=new WQ(this.occWorkerManager,this.context,this.draw,this.occt),this.tables=new UQ(this.occWorkerManager,this.context,this.draw,this.occt)}}class XQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r,this.kidsCorner=new zK(this.occWorkerManager,this.context,this.draw,this.occt),this.threeDPrinting=new RQ(this.occWorkerManager,this.context,this.draw,this.occt),this.architecture=new DQ(this.occWorkerManager,this.context,this.draw,this.occt),this.furniture=new HQ(this.occWorkerManager,this.context,this.draw,this.occt),this.enums=new wQ}}var qQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class YQ{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}create(e){return qQ(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.text3d",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}createTextOnFace(e){return qQ(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.text3dFace",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}createTextsOnFace(e){return qQ(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.texts3dFace",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}definition3dTextOnFace(e){return e}drawModel(e,t=.003){return qQ(this,void 0,void 0,(function*(){const i=new Yt("brepMesh"+Math.random(),this.context.scene),r=new QH.DrawOcctShapeOptions;r.faceOpacity=0,r.edgeColour="#bc7e5b",r.edgeWidth=.6,r.precision=t;const s=yield this.draw.drawAnyAsync({entity:e.compound,options:r}),n=new zm("brepMaterial"+Math.random(),this.context.scene);return n.albedoColor=new hc.v9(1,1,1),n.ambientColor=hc.v9.FromHexString("#ffffff"),n.metallic=0,n.roughness=.7,n.zOffset=1,s.getChildMeshes()[0].material=n,s.material=n,s.parent=i,i}))}getCompoundShape(e){return e.model.compound}getCharacterShape(e){if(e.index<0||e.index>=e.model.characterParts.length)throw new Error("Index is out of bounds.");return e.model.characterParts[e.index].shapes.compound}getCharacterShapes(e){return e.model.characterParts.map((e=>e.shapes.compound))}getCharacterCenterCoordinates(e){return e.model.characterCenterCoordinates}getFaceCutout(e){if(e.model.faceParts){const t=e.model.faceParts.filter((e=>e.type===KK.cutout)).map((e=>e.shapes.face));if(t.length>0)return t[0];throw new Error("No cutout was found.")}throw new Error("It seems this text was not created on the face, so there is no face cutout.")}getAllFacesOfCutout(e){if(e.model.faceParts)return e.model.faceParts.filter((e=>e.type===KK.cutout||e.type===KK.cutoutInsideCharacter)).map((e=>e.shapes.face));throw new Error("It seems this text was not created on the face, so there is no face cutout.")}getCutoutsInsideCharacters(e){if(e.model.faceParts)return e.model.faceParts.filter((e=>e.type===KK.cutoutInsideCharacter)).map((e=>e.shapes.face));throw new Error("It seems this text was not created on the face, so there is no face cutout.")}getAdvanceWidth(e){return e.model.advanceWidth}}var KQ,jQ=function(e,t,i,r){return new(i||(i=Promise))((function(s,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((r=r.apply(e,t||[])).next())}))};class $Q{constructor(e,t,i,r){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=r}createPyramidSimple(e){return jQ(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.pyramidSimple",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}createPyramidSimpleAffectors(e){return jQ(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.pyramidSimpleAffectors",e),i=fQ.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}drawModel(e){return jQ(this,void 0,void 0,(function*(){const t=new Yt("brepMesh"+Math.random(),this.context.scene),i=new QH.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#bc7e5b",i.edgeWidth=1,i.precision=e.originalInputs.precision;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:i}),s=new zm("brepMaterial"+Math.random(),this.context.scene);return s.albedoColor=new hc.v9(1,1,1),s.ambientColor=hc.v9.FromHexString("#ffffff"),s.metallic=.3,s.roughness=.6,s.zOffset=2,r.getChildMeshes()[0].material=s,r.material=s,r.parent=t,t}))}getCompoundShape(e){return e.model.compound}getCompoundShapeOnFace(e){if(e.model.faceParts&&e.faceIndext.uIndex===e.uIndex&&t.vIndex===e.vIndex));if(t)return t.shapes.compound;throw new Error("Cell does not exist on the face")}throw new Error("Cell u or v index is out of range")}throw new Error("Face index is out of range")}getAllPyramidCells(e){return e.model.faceParts.map((e=>e.cells)).flat()}getAllPyramidCellsOnFace(e){if(e.model.faceParts&&e.faceIndext.uIndex===e.uIndex));throw new Error("Face index is out of range")}getAllPyramidUCellsOnFaceAtV(e){if(e.model.faceParts&&e.faceIndext.vIndex===e.vIndex));throw new Error("Face index is out of range")}getCellOnIndex(e){if(e.model.faceParts&&e.faceIndext.uIndex===e.uIndex&&t.vIndex===e.vIndex));if(t)return t;throw new Error("Cell does not exist on the face")}throw new Error("Cell u or v index is out of range")}throw new Error("Face index is out of range")}getTopPointsOfCells(e){return e.cells.map((e=>e.topPoint))}getCenterPointsOfCells(e){return e.cells.map((e=>e.centerPoint))}getCornerPointsOfCells(e){return e.cells.map((e=>[e.cornerPoint1,e.cornerPoint2,e.cornerPoint3,e.cornerPoint4].filter((e=>void 0!==e))))}getCornerPointOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.cornerPoint1:1===e.index?t.cornerPoint2:2===e.index?t.cornerPoint3:3===e.index?t.cornerPoint4:void 0));throw new Error("Corner index is out of range")}getCornerNormalOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.cornerNormal1:1===e.index?t.cornerNormal2:2===e.index?t.cornerNormal3:3===e.index?t.cornerNormal4:void 0));throw new Error("Corner index is out of range")}getCornerNormalsOfCells(e){return e.cells.map((e=>[e.cornerNormal1,e.cornerNormal2,e.cornerNormal3,e.cornerNormal4].filter((e=>void 0!==e))))}getCompoundShapesOfCells(e){return e.cells.map((e=>e.shapes.compound))}getFaceShapesOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.shapes.face1:1===e.index?t.shapes.face2:2===e.index?t.shapes.face3:3===e.index?t.shapes.face4:void 0));throw new Error("Face index is out of range")}getWireShapesOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.shapes.wire1:1===e.index?t.shapes.wire2:2===e.index?t.shapes.wire3:3===e.index?t.shapes.wire4:void 0));throw new Error("Wire index is out of range")}getStartPolylineWireU(e){if(e.faceIndex>=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]0&&"string"!=typeof t[e])for(var i=function(i){var r=t[e][i];"object"==typeof r&&null!==r&&r.then&&(r.then((function(r){return t[e][i]=r,r})),n.push(t[e][i]))},r=0;r0&&e.startedAsyncTask(i,r,"#eeeeff"),n.length>0?[2,Promise.all(n).then((function(t){return e.finishedAsyncTask(i,r),t}))]:[2,null]}))}))},e.finishedAsyncTask=function(e,t){},e.startedAsyncTask=function(e,t,i){},e.runtimeValidation=function(e,t){},e.validate=function(e,t,i){},e.handleBlockException=function(e,t){},e.errorHappened=function(e,t,i){},e.updateListInputs=function(e){Object.keys(e).forEach((function(t){if(Array.isArray(e[t])){var i=[];e[t].forEach((function(e){if(e&&e.result){var t=e.result;e.transformers&&e.transformers.length&&e.transformers.forEach((function(e){e.type===iZ.flat&&(t=t.flat())})),t instanceof Array?i.push.apply(i,t):i.push(t)}})),e[t]=i}}))},e.executeBasedOnTypeAsync=function(e,t,i){return sZ(this,void 0,void 0,(function(){var r,s,n,o,a,l,h,c,u;return nZ(this,(function(d){switch(d.label){case 0:if(t)return[3,5];l=this.performActionOnAllVariationsSimplified(e,i),d.label=1;case 1:return d.trys.push([1,3,,4]),[4,Promise.all(l)];case 2:return r=d.sent(),[3,4];case 3:throw s=d.sent(),new Error(s);case 4:return[3,9];case 5:if(!t)return[3,9];for(n=Object.keys(e),o=n.map((function(t){return e[t]})),a=this.normalizeListsToEqualLength(o),l=[],h=function(e){var t={};n.forEach((function(i,r){t[i]=o[r][e]})),l.push(i(t,e))},c=0;ct&&(t=e.length)})),t},e.drawNodeMeshes=function(e,t){return sZ(this,void 0,void 0,(function(){var i,r=this;return nZ(this,(function(s){switch(s.label){case 0:return i=e.map((function(e){return sZ(r,void 0,void 0,(function(){var i,r,s;return nZ(this,(function(n){switch(n.label){case 0:return i=e.result,r=[],i instanceof Array&&i.length>0&&i[0]&&i[0].hash?i.forEach((function(e){var i=t.draw.drawAnyAsync({entity:e,options:void 0});r.push(i)})):(s=t.draw.drawAnyAsync({entity:i,options:void 0}),r.push(s)),[4,Promise.all(r)];case 1:return[2,n.sent()]}}))}))})),[4,Promise.all(i)];case 1:return s.sent(),[2]}}))}))},e}(),hZ=function(){function e(e){this.context=e}return e.prototype.handleTags=function(e,t,i,r){var s=this;!t&&this.context.tagBag.length>0&&this.context.tagBag.find((function(e){return e.needsUpdate}))&&(t=!0),t&&this.context.tagBag.length>0&&this.context.tagBag.forEach((function(t){var n=document.querySelector("#"+t.id),o=new hc.Pq(t.position[0],t.position[1],t.position[2]);n.textContent=t.text;var a=i.getRenderWidth()/2,l=i.getRenderHeight()/2,h=hc.Pq.Project(o,hc.uq.IdentityReadOnly,r.getTransformMatrix(),e.viewport.toGlobal(a,l)),c=hc.Pq.Distance(e.position,o),u=t.adaptDepth?Math.ceil(s.context.remap(c,0,100,t.size,3)):t.size;h.x>0&&h.x0&&h.y0&&h.z<1&&u>3?n.style="".concat("position: absolute; transform: translate(-50%, -50%); font-weight: 400;"," font-size: ").concat(u,"px; color: ").concat(t.colour,"; left: ").concat(h.x,"px; top: ").concat(h.y,"px; display: inline;"):n.style="display: none;"}))},e.prototype.removeTagsIfNeeded=function(){this.tagsExist()&&this.context.tagBag.forEach((function(e){var t=document.getElementById(e.id);t.parentNode.removeChild(t)})),this.context.tagBag=[]},e.prototype.tagsExist=function(){return this.context.tagBag.length>0},e}(),cZ=function(){return cZ=Object.assign||function(e){for(var t,i=1,r=arguments.length;i0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]0?JSON.stringify(r):"{}",';\n let bitbybitRunnerResult = {};\n const runContext = "runner";\n const mockBitbybitRunnerInputs = (inputs) => {\n }\n const getBitbybitRunnerInputs = () => {\n return bitbybitRunnerInputs;\n }\n const setBitbybitRunnerResult = (result) => {\n bitbybitRunnerResult = result;\n }\n const setBitbybitRunnerResultValue = (prop, value) => {\n bitbybitRunnerResult[prop] = value;\n }\n \n const bitbybit = this.bitbybit;\n const Bit = this.Bit;\n Bit.mockBitbybitRunnerInputs = mockBitbybitRunnerInputs;\n Bit.getBitbybitRunnerInputs = getBitbybitRunnerInputs;\n Bit.setBitbybitRunnerResult = setBitbybitRunnerResult;\n Bit.setBitbybitRunnerResultValue = setBitbybitRunnerResultValue;\n \n const BitByBit = this.BitByBit;\n const errorHandle = this.errorHandle;\n const BABYLON = this.BABYLON;\n BABYLON.GUI = this.GUI;\n const resolve = this.resolve;\n \n await ').concat(s.script,"\n if(bitbybitRunnerResult !== undefined){\n resolve(bitbybitRunnerResult);\n } else {\n resolve(undefined);\n }\n }\n \n bitbybitRunnerStart();\n "),a={HS:lZ,BitByBitContextHelperService:this.bitbybit.context},l={bitbybit:this.bitbybit,BABYLON:e,GUI:t,Bit:pZ,BitByBit:a,errorHandle:n},[2,new Promise((function(e){return l.resolve=e,new Function(o).apply(l)}))]}))}))},i.prototype.resetRunnerContext=function(){if(this.bitbybit.context.scene.dispose(),this.options.enablePhysics){var e=new fO(!0,this.havok);this.bitbybit.context.havokPlugin=e}var t=document.getElementById(this.options.canvasId),i=this.bitbybit.context.engine;this.initScene(i,t),this.tagService.removeTagsIfNeeded(),this.bitbybit.context.intervalBag.forEach((function(e){return clearInterval(e)})),this.bitbybit.context.timeoutBag.forEach((function(e){return clearTimeout(e)})),this.bitbybit.context.intervalBag.length=0,this.bitbybit.context.timeoutBag.length=0,this.bitbybit.context.renderLoopBag.length=0,this.bitbybit.context.keyPressBag.length=0,this.bitbybit.context.keyDownBag.length=0,this.bitbybit.context.keyUpBag.length=0},i.prototype.cleanOCCTCache=function(){return uZ(this,void 0,void 0,(function(){return dZ(this,(function(e){return[2,this.bitbybit.occtWorkerManager.cleanAllCache()]}))}))},i.prototype.cleanJSCADCache=function(){return uZ(this,void 0,void 0,(function(){return dZ(this,(function(e){return[2,this.bitbybit.jscadWorkerManager.cleanAllCache()]}))}))},i.prototype.cleanManifoldCache=function(){return uZ(this,void 0,void 0,(function(){return dZ(this,(function(e){return[2,this.bitbybit.manifoldWorkerManager.cleanAllCache()]}))}))},i}()})(),r})())); \ No newline at end of file diff --git a/workers/167.bitbybit-manifold-webworker.js b/workers/167.bitbybit-manifold-webworker.js deleted file mode 100644 index 594bd98..0000000 --- a/workers/167.bitbybit-manifold-webworker.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_bitbybit_dev_runner=self.webpackChunk_bitbybit_dev_runner||[]).push([[167],{167:()=>{}}]); \ No newline at end of file diff --git a/workers/167.bitbybit-occt-webworker.js b/workers/167.bitbybit-occt-webworker.js deleted file mode 100644 index 594bd98..0000000 --- a/workers/167.bitbybit-occt-webworker.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_bitbybit_dev_runner=self.webpackChunk_bitbybit_dev_runner||[]).push([[167],{167:()=>{}}]); \ No newline at end of file diff --git a/workers/903.bitbybit-occt-webworker.js b/workers/903.bitbybit-occt-webworker.js deleted file mode 100644 index dab947b..0000000 --- a/workers/903.bitbybit-occt-webworker.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk_bitbybit_dev_runner=self.webpackChunk_bitbybit_dev_runner||[]).push([[903],{903:(e,t,n)=>{let o;function r(){return o}n.r(t),n.d(t,{default:()=>r}),function e(t,n,o){function r(a,i){if(!n[a]){if(!t[a]){if(s)return s(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[a]={exports:{}};t[a][0].call(l.exports,(function(e){return r(t[a][1][e]||e)}),l,l.exports,e,t,n,o)}return n[a].exports}for(var s=void 0,a=0;a{let n=["basematerials",{id:"0"}];const o=[];return e.forEach(((e,n)=>{let r=a.rgbToHex(t.defaultcolor).toUpperCase();e.color&&(r=a.rgbToHex(e.color).toUpperCase()),o.push(["base",{name:`mat${n}`,displaycolor:r}])})),n=n.concat(o),n},f=(e,t)=>{const n=[];return e.forEach(((e,o)=>{i.geom3.isA(e)&&i.geom3.toPolygons(e).length>0&&(t.id=o,n.push(h(e,t)))})),n},h=(e,t)=>{const n=e.name?e.name:`Part ${t.id}`;return["object",{id:`${t.id+1}`,type:"model",pid:"0",pindex:`${t.id}`,name:n},m(e,t)]},m=(e,t)=>["mesh",{},g(e,t),y(e,t)],g=(e,t)=>{const n=[];return i.geom3.toPolygons(e).forEach((e=>{for(let o=0;o["vertex",{x:e[0],y:e[1],z:e[2]}],y=(e,t)=>{let n=0;const o=i.geom3.toPolygons(e);let r=["triangles",{}];return o.forEach((e=>{if(e.vertices.length<3)return;const t=v(e,n);r=r.concat(t),n+=e.vertices.length})),r},v=(e,t)=>{const n=[];for(let o=0;o{e=Object.assign({},{unit:"millimeter",metadata:!0,defaultcolor:[1,160/255,0,1],compress:!0},e);let n=(t=l(t)).filter((e=>i.geom3.isA(e)));if(0===n.length)throw new Error("only 3D geometries can be serialized to 3MF");t.length!==n.length&&console.warn("some objects could not be serialized to 3MF"),t=u(c.generalize({snap:!0,triangulate:!0},n));const a=["model",{unit:e.unit,"xml:lang":"und"},["metadata",{name:"Application"},"JSCAD"]];e.metadata&&a.push(["metadata",{name:"CreationDate"},(new Date).toISOString()]),a.push(((e,t)=>{let n=["resources",{},p(e,t)];return n=n.concat(f(e,t)),n})(t,e)),a.push(((e,t)=>{let n=["build",{}];const o=[];return e.forEach(((e,t)=>{o.push(["item",{objectid:`${t+1}`}])})),n=n.concat(o),n})(t));const h=`\n${s(a,2)}`;if(e.compress){const e={"3D":{"3dmodel.model":r(h)},_rels:{".rels":r('\n\n \n \n')},"[Content_Types].xml":r('\n\n \n \n \n \n')};return[o(e,{comment:"created by JSCAD"}).buffer]}return[h]},mimeType:"model/3mf",fileExtension:"3mf"}},{"@jscad/array-utils":6,"@jscad/modeling":511,fflate:827,"onml/lib/stringify":829}],3:[function(e,t,n){const o=e=>e.reduce(((e,t)=>Array.isArray(t)?e.concat(o(t)):e.concat(t)),[]);t.exports=o},{}],4:[function(e,t,n){t.exports=(e,t)=>e-t},{}],5:[function(e,t,n){t.exports=e=>{if(Array.isArray(e)&&0!==e.length)return e[0]}},{}],6:[function(e,t,n){t.exports={flatten:e("./flatten"),fnNumberSort:e("./fnNumberSort"),head:e("./head"),insertSorted:e("./insertSorted"),nth:e("./nth"),padToLength:e("./padToLength"),toArray:e("./toArray")}},{"./flatten":3,"./fnNumberSort":4,"./head":5,"./insertSorted":7,"./nth":8,"./padToLength":9,"./toArray":10}],7:[function(e,t,n){t.exports=(e,t,n)=>{let o=0,r=e.length;for(;r>o;){const s=Math.floor((o+r)/2);n(t,e[s])>0?o=s+1:r=s}return e.splice(o,0,t),e}},{}],8:[function(e,t,n){t.exports=(e,t)=>{if(Array.isArray(e)&&!(e.length{for(e=e.slice();e.lengthArray.isArray(e)?e:null==e?[]:[e]},{}],11:[function(e,t,n){t.exports={dxfHeaders:function(){return" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1027\n 9\n$ACADMAINTVER\n 70\n8\n 9\n$DWGCODEPAGE\n 3\nANSI_1252\n 9\n$LASTSAVEDBY\n 1\nunknown\n 9\n$REQUIREDVERSIONS\n160\n0\n 9\n$INSBASE\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$EXTMIN\n 10\n1e+20\n 20\n1e+20\n 30\n1e+20\n 9\n$EXTMAX\n 10\n-1e+20\n 20\n-1e+20\n 30\n-1e+20\n 9\n$LIMMIN\n 10\n0.0\n 20\n0.0\n 9\n$LIMMAX\n 10\n12.0\n 20\n9.0\n 9\n$ORTHOMODE\n 70\n0\n 9\n$REGENMODE\n 70\n1\n 9\n$FILLMODE\n 70\n1\n 9\n$QTEXTMODE\n 70\n0\n 9\n$MIRRTEXT\n 70\n0\n 9\n$LTSCALE\n 40\n1.0\n 9\n$ATTMODE\n 70\n1\n 9\n$TEXTSIZE\n 40\n0.2\n 9\n$TRACEWID\n 40\n0.05\n 9\n$TEXTSTYLE\n 7\nNotes\n 9\n$CLAYER\n 8\n0\n 9\n$CELTYPE\n 6\nByLayer\n 9\n$CECOLOR\n 62\n256\n 9\n$CELTSCALE\n 40\n1.0\n 9\n$DISPSILH\n 70\n0\n 9\n$DIMSCALE\n 40\n1.0\n 9\n$DIMASZ\n 40\n3.0\n 9\n$DIMEXO\n 40\n1.5\n 9\n$DIMDLI\n 40\n6.0\n 9\n$DIMRND\n 40\n0.0\n 9\n$DIMDLE\n 40\n0.0\n 9\n$DIMEXE\n 40\n3.0\n 9\n$DIMTP\n 40\n0.0\n 9\n$DIMTM\n 40\n0.0\n 9\n$DIMTXT\n 40\n3.0\n 9\n$DIMCEN\n 40\n3.0\n 9\n$DIMTSZ\n 40\n0.0\n 9\n$DIMTOL\n 70\n0\n 9\n$DIMLIM\n 70\n0\n 9\n$DIMTIH\n 70\n0\n 9\n$DIMTOH\n 70\n0\n 9\n$DIMSE1\n 70\n0\n 9\n$DIMSE2\n 70\n0\n 9\n$DIMTAD\n 70\n1\n 9\n$DIMZIN\n 70\n3\n 9\n$DIMBLK\n 1\n\n 9\n$DIMASO\n 70\n1\n 9\n$DIMSHO\n 70\n1\n 9\n$DIMPOST\n 1\n\n 9\n$DIMAPOST\n 1\n\n 9\n$DIMALT\n 70\n0\n 9\n$DIMALTD\n 70\n2\n 9\n$DIMALTF\n 40\n25.4\n 9\n$DIMLFAC\n 40\n1.0\n 9\n$DIMTOFL\n 70\n0\n 9\n$DIMTVP\n 40\n0.0\n 9\n$DIMTIX\n 70\n0\n 9\n$DIMSOXD\n 70\n0\n 9\n$DIMSAH\n 70\n0\n 9\n$DIMBLK1\n 1\n\n 9\n$DIMBLK2\n 1\n\n 9\n$DIMSTYLE\n 2\nCivil-Metric\n 9\n$DIMCLRD\n 70\n0\n 9\n$DIMCLRE\n 70\n0\n 9\n$DIMCLRT\n 70\n0\n 9\n$DIMTFAC\n 40\n1.0\n 9\n$DIMGAP\n 40\n2.0\n 9\n$DIMJUST\n 70\n0\n 9\n$DIMSD1\n 70\n0\n 9\n$DIMSD2\n 70\n0\n 9\n$DIMTOLJ\n 70\n1\n 9\n$DIMTZIN\n 70\n0\n 9\n$DIMALTZ\n 70\n0\n 9\n$DIMALTTZ\n 70\n0\n 9\n$DIMUPT\n 70\n0\n 9\n$DIMDEC\n 70\n2\n 9\n$DIMTDEC\n 70\n2\n 9\n$DIMALTU\n 70\n2\n 9\n$DIMALTTD\n 70\n2\n 9\n$DIMTXSTY\n 7\nStandard\n 9\n$DIMAUNIT\n 70\n0\n 9\n$DIMADEC\n 70\n2\n 9\n$DIMALTRND\n 40\n0.0\n 9\n$DIMAZIN\n 70\n2\n 9\n$DIMDSEP\n 70\n46\n 9\n$DIMATFIT\n 70\n3\n 9\n$DIMFRAC\n 70\n1\n 9\n$DIMLDRBLK\n 1\n\n 9\n$DIMLUNIT\n 70\n2\n 9\n$DIMLWD\n 70\n-2\n 9\n$DIMLWE\n 70\n-2\n 9\n$DIMTMOVE\n 70\n0\n 9\n$DIMFXL\n 40\n1.0\n 9\n$DIMFXLON\n 70\n0\n 9\n$DIMJOGANG\n 40\n0.785398163397\n 9\n$DIMTFILL\n 70\n0\n 9\n$DIMTFILLCLR\n 70\n0\n 9\n$DIMARCSYM\n 70\n0\n 9\n$DIMLTYPE\n 6\n\n 9\n$DIMLTEX1\n 6\n\n 9\n$DIMLTEX2\n 6\n\n 9\n$DIMTXTDIRECTION\n 70\n0\n 9\n$LUNITS\n 70\n2\n 9\n$LUPREC\n 70\n4\n 9\n$SKETCHINC\n 40\n0.1\n 9\n$FILLETRAD\n 40\n0.0\n 9\n$AUNITS\n 70\n4\n 9\n$AUPREC\n 70\n5\n 9\n$MENU\n 1\n.\n 9\n$ELEVATION\n 40\n0.0\n 9\n$PELEVATION\n 40\n0.0\n 9\n$THICKNESS\n 40\n0.0\n 9\n$LIMCHECK\n 70\n0\n 9\n$CHAMFERA\n 40\n0.0\n 9\n$CHAMFERB\n 40\n0.0\n 9\n$CHAMFERC\n 40\n0.0\n 9\n$CHAMFERD\n 40\n0.0\n 9\n$SKPOLY\n 70\n0\n 9\n$TDCREATE\n 40\n2457986.69756\n 9\n$TDUCREATE\n 40\n2455631.2632\n 9\n$TDUPDATE\n 40\n2457986.69756\n 9\n$TDUUPDATE\n 40\n2456436.43179\n 9\n$TDINDWG\n 40\n0.0003490741\n 9\n$TDUSRTIMER\n 40\n0.0003487153\n 9\n$USRTIMER\n 70\n1\n 9\n$ANGBASE\n 50\n0.0\n 9\n$ANGDIR\n 70\n0\n 9\n$PDMODE\n 70\n0\n 9\n$PDSIZE\n 40\n0.0\n 9\n$PLINEWID\n 40\n0.0\n 9\n$SPLFRAME\n 70\n0\n 9\n$SPLINETYPE\n 70\n6\n 9\n$SPLINESEGS\n 70\n8\n 9\n$HANDSEED\n 5\n5C7\n 9\n$SURFTAB1\n 70\n6\n 9\n$SURFTAB2\n 70\n6\n 9\n$SURFTYPE\n 70\n6\n 9\n$SURFU\n 70\n6\n 9\n$SURFV\n 70\n6\n 9\n$UCSBASE\n 2\n\n 9\n$UCSNAME\n 2\n\n 9\n$UCSORG\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSXDIR\n 10\n1.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSYDIR\n 10\n0.0\n 20\n1.0\n 30\n0.0\n 9\n$UCSORTHOREF\n 2\n\n 9\n$UCSORTHOVIEW\n 70\n0\n 9\n$UCSORGTOP\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGBOTTOM\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGLEFT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGRIGHT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGFRONT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGBACK\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSBASE\n 2\n\n 9\n$PUCSNAME\n 2\n\n 9\n$PUCSORG\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSXDIR\n 10\n1.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSYDIR\n 10\n0.0\n 20\n1.0\n 30\n0.0\n 9\n$PUCSORTHOREF\n 2\n\n 9\n$PUCSORTHOVIEW\n 70\n0\n 9\n$PUCSORGTOP\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGBOTTOM\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGLEFT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGRIGHT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGFRONT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGBACK\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$USERI1\n 70\n0\n 9\n$USERI2\n 70\n0\n 9\n$USERI3\n 70\n0\n 9\n$USERI4\n 70\n0\n 9\n$USERI5\n 70\n0\n 9\n$USERR1\n 40\n0.0\n 9\n$USERR2\n 40\n0.0\n 9\n$USERR3\n 40\n0.0\n 9\n$USERR4\n 40\n0.0\n 9\n$USERR5\n 40\n0.0\n 9\n$WORLDVIEW\n 70\n1\n 9\n$SHADEDGE\n 70\n3\n 9\n$SHADEDIF\n 70\n70\n 9\n$TILEMODE\n 70\n1\n 9\n$MAXACTVP\n 70\n64\n 9\n$PINSBASE\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PLIMCHECK\n 70\n0\n 9\n$PEXTMIN\n 10\n0.628866766397\n 20\n0.799999952316\n 30\n0.0\n 9\n$PEXTMAX\n 10\n9.02886638493\n 20\n7.19999957085\n 30\n0.0\n 9\n$PLIMMIN\n 10\n-0.700541819174\n 20\n-0.228100386192\n 9\n$PLIMMAX\n 10\n10.2994579405\n 20\n8.27189937351\n 9\n$UNITMODE\n 70\n0\n 9\n$VISRETAIN\n 70\n1\n 9\n$PLINEGEN\n 70\n0\n 9\n$PSLTSCALE\n 70\n1\n 9\n$TREEDEPTH\n 70\n3020\n 9\n$CMLSTYLE\n 2\nStandard\n 9\n$CMLJUST\n 70\n0\n 9\n$CMLSCALE\n 40\n1.0\n 9\n$PROXYGRAPHICS\n 70\n1\n 9\n$MEASUREMENT\n 70\n1\n 9\n$CELWEIGHT\n370\n-1\n 9\n$ENDCAPS\n280\n0\n 9\n$JOINSTYLE\n280\n0\n 9\n$LWDISPLAY\n290\n0\n 9\n$INSUNITS\n 70\n4\n 9\n$HYPERLINKBASE\n 1\n\n 9\n$STYLESHEET\n 1\n\n 9\n$XEDIT\n290\n1\n 9\n$CEPSNTYPE\n380\n0\n 9\n$PSTYLEMODE\n290\n1\n 9\n$FINGERPRINTGUID\n 2\n{39DB1BDD-BC6C-46D3-A333-DFCC0DC4782D}\n 9\n$VERSIONGUID\n 2\n{69EEBB2D-7039-498F-9366-3F994E4A07E7}\n 9\n$EXTNAMES\n290\n1\n 9\n$PSVPSCALE\n 40\n0.0\n 9\n$OLESTARTUP\n290\n0\n 9\n$SORTENTS\n280\n127\n 9\n$INDEXCTL\n280\n0\n 9\n$HIDETEXT\n280\n1\n 9\n$XCLIPFRAME\n280\n0\n 9\n$HALOGAP\n280\n0\n 9\n$OBSCOLOR\n 70\n257\n 9\n$OBSLTYPE\n280\n0\n 9\n$INTERSECTIONDISPLAY\n280\n0\n 9\n$INTERSECTIONCOLOR\n 70\n257\n 9\n$DIMASSOC\n280\n2\n 9\n$PROJECTNAME\n 1\n\n 9\n$CAMERADISPLAY\n290\n0\n 9\n$LENSLENGTH\n 40\n50.0\n 9\n$CAMERAHEIGHT\n 40\n0.0\n 9\n$STEPSPERSEC\n 40\n2.0\n 9\n$STEPSIZE\n 40\n6.0\n 9\n$3DDWFPREC\n 40\n2.0\n 9\n$PSOLWIDTH\n 40\n0.25\n 9\n$PSOLHEIGHT\n 40\n4.0\n 9\n$LOFTANG1\n 40\n1.57079632679\n 9\n$LOFTANG2\n 40\n1.57079632679\n 9\n$LOFTMAG1\n 40\n0.0\n 9\n$LOFTMAG2\n 40\n0.0\n 9\n$LOFTPARAM\n 70\n7\n 9\n$LOFTNORMALS\n280\n1\n 9\n$LATITUDE\n 40\n37.795\n 9\n$LONGITUDE\n 40\n-122.394\n 9\n$NORTHDIRECTION\n 40\n0.0\n 9\n$TIMEZONE\n 70\n-8000\n 9\n$LIGHTGLYPHDISPLAY\n280\n1\n 9\n$TILEMODELIGHTSYNCH\n280\n1\n 9\n$CMATERIAL\n347\n96\n 9\n$SOLIDHIST\n280\n1\n 9\n$SHOWHIST\n280\n1\n 9\n$DWFFRAME\n280\n2\n 9\n$DGNFRAME\n280\n0\n 9\n$REALWORLDSCALE\n290\n1\n 9\n$INTERFERECOLOR\n 62\n1\n 9\n$INTERFEREOBJVS\n345\nA3\n 9\n$INTERFEREVPVS\n346\nA0\n 9\n$CSHADOW\n280\n0\n 9\n$SHADOWPLANELOCATION\n 40\n0.0\n 0\nENDSEC"},dxfClasses:function(){return' 0\nSECTION\n 2\nCLASSES\n 0\nCLASS\n 1\nACDBDICTIONARYWDFLT\n 2\nAcDbDictionaryWithDefault\n 3\nObjectDBX Classes\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nDICTIONARYVAR\n 2\nAcDbDictionaryVar\n 3\nObjectDBX Classes\n 90\n0\n 91\n15\n280\n0\n281\n0\n 0\nCLASS\n 1\nTABLESTYLE\n 2\nAcDbTableStyle\n 3\nObjectDBX Classes\n 90\n4095\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nMATERIAL\n 2\nAcDbMaterial\n 3\nObjectDBX Classes\n 90\n1153\n 91\n3\n280\n0\n281\n0\n 0\nCLASS\n 1\nVISUALSTYLE\n 2\nAcDbVisualStyle\n 3\nObjectDBX Classes\n 90\n4095\n 91\n26\n280\n0\n281\n0\n 0\nCLASS\n 1\nSCALE\n 2\nAcDbScale\n 3\nObjectDBX Classes\n 90\n1153\n 91\n17\n280\n0\n281\n0\n 0\nCLASS\n 1\nMLEADERSTYLE\n 2\nAcDbMLeaderStyle\n 3\nACDB_MLEADERSTYLE_CLASS\n 90\n4095\n 91\n3\n280\n0\n281\n0\n 0\nCLASS\n 1\nCELLSTYLEMAP\n 2\nAcDbCellStyleMap\n 3\nObjectDBX Classes\n 90\n1152\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nEXACXREFPANELOBJECT\n 2\nExAcXREFPanelObject\n 3\nEXAC_ESW\n 90\n1025\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nNPOCOLLECTION\n 2\nAcDbImpNonPersistentObjectsCollection\n 3\nObjectDBX Classes\n 90\n1153\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nLAYER_INDEX\n 2\nAcDbLayerIndex\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nSPATIAL_INDEX\n 2\nAcDbSpatialIndex\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nIDBUFFER\n 2\nAcDbIdBuffer\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nDIMASSOC\n 2\nAcDbDimAssoc\n 3\n"AcDbDimAssoc|Product Desc: AcDim ARX App For Dimension|Company: Autodesk, Inc.|WEB Address: www.autodesk.com"\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nACDBSECTIONVIEWSTYLE\n 2\nAcDbSectionViewStyle\n 3\nObjectDBX Classes\n 90\n1025\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nACDBDETAILVIEWSTYLE\n 2\nAcDbDetailViewStyle\n 3\nObjectDBX Classes\n 90\n1025\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGEDEF\n 2\nAcDbRasterImageDef\n 3\nISM\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nRASTERVARIABLES\n 2\nAcDbRasterVariables\n 3\nISM\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGEDEF_REACTOR\n 2\nAcDbRasterImageDefReactor\n 3\nISM\n 90\n1\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGE\n 2\nAcDbRasterImage\n 3\nISM\n 90\n2175\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nPDFDEFINITION\n 2\nAcDbPdfDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nPDFUNDERLAY\n 2\nAcDbPdfReference\n 3\nObjectDBX Classes\n 90\n4095\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nDWFDEFINITION\n 2\nAcDbDwfDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nDWFUNDERLAY\n 2\nAcDbDwfReference\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nDGNDEFINITION\n 2\nAcDbDgnDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nDGNUNDERLAY\n 2\nAcDbDgnReference\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n1\n 0\nENDSEC'},dxfTables:function(){return" 0\nSECTION\n 2\nTABLES\n 0\nTABLE\n 2\nVPORT\n 5\n8\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nLTYPE\n 5\n5F\n330\n0\n100\nAcDbSymbolTable\n 70\n7\n 0\nLTYPE\n 5\n14\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nByBlock\n 70\n0\n 3\n\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n15\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nByLayer\n 70\n0\n 3\n\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n16\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nContinuous\n 70\n0\n 3\nSolid line\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n1B1\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nCENTER\n 70\n0\n 3\nCenter ____ _ ____ _ ____ _ ____ _ ____ _ ____\n 72\n65\n 73\n4\n 40\n2.0\n 49\n1.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n1B2\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nDASHED\n 70\n0\n 3\nDashed __ __ __ __ __ __ __ __ __ __ __ __ __ _\n 72\n65\n 73\n2\n 40\n0.75\n 49\n0.5\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n1B3\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nPHANTOM\n 70\n0\n 3\nPhantom ______ __ __ ______ __ __ ______\n 72\n65\n 73\n6\n 40\n2.5\n 49\n1.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n39E\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nHIDDEN\n 70\n0\n 3\nHidden __ __ __ __ __ __ __ __ __ __ __ __ __ __\n 72\n65\n 73\n2\n 40\n9.525\n 49\n6.35\n 74\n0\n 49\n-3.175\n 74\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nLAYER\n 5\n2\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n 0\nLAYER\n 5\n10\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\n0\n 70\n0\n 6\nContinuous\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nLAYER\n 5\n1B4\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\nView Port\n 70\n0\n 6\nContinuous\n290\n0\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nLAYER\n 5\n21D\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\nDefpoints\n 70\n0\n 6\nContinuous\n290\n0\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nSTYLE\n 5\n3\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n 0\nSTYLE\n 5\n11\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nStandard\n 70\n0\n 40\n0.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nSTYLE\n 5\nDC\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nAnnotative\n 70\n0\n 40\n0.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nSTYLE\n 5\n178\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nNotes\n 70\n0\n 40\n3.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nENDTAB\n 0\nTABLE\n 2\nVIEW\n 5\n6\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nUCS\n 5\n7\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nAPPID\n 5\n9\n330\n0\n100\nAcDbSymbolTable\n 70\n12\n 0\nAPPID\n 5\n12\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD\n 70\n0\n 0\nAPPID\n 5\nDD\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcadAnnoPO\n 70\n0\n 0\nAPPID\n 5\nDE\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcadAnnotative\n 70\n0\n 0\nAPPID\n 5\nDF\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMJAG\n 70\n0\n 0\nAPPID\n 5\nE0\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMTALN\n 70\n0\n 0\nAPPID\n 5\n107\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_MLEADERVER\n 70\n0\n 0\nAPPID\n 5\n1B5\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcAecLayerStandard\n 70\n0\n 0\nAPPID\n 5\n1BA\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_EXEMPT_FROM_CAD_STANDARDS\n 70\n0\n 0\nAPPID\n 5\n237\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMBREAK\n 70\n0\n 0\nAPPID\n 5\n28E\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_PSEXT\n 70\n0\n 0\nAPPID\n 5\n4B0\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_NAV_VCDISPLAY\n 70\n0\n 0\nAPPID\n 5\n4E3\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nHATCHBACKGROUNDCOLOR\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nDIMSTYLE\n 5\nA\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n100\nAcDbDimStyleTable\n 71\n3\n340\n242\n340\n27\n340\nE1\n 0\nDIMSTYLE\n105\n27\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nStandard\n 70\n0\n 41\n3.0\n 42\n2.0\n 43\n9.0\n 44\n5.0\n140\n3.0\n141\n2.0\n147\n2.0\n340\n11\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n90.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nDIMSTYLE\n105\nE1\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nAnnotative\n 70\n0\n 40\n0.0\n 41\n3.0\n 42\n2.5\n 43\n10.0\n 44\n5.0\n140\n3.0\n141\n2.0\n147\n2.0\n340\n11\n1001\nAcadAnnotative\n1000\nAnnotativeData\n1002\n{\n1070\n1\n1070\n1\n1002\n}\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n90.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nDIMSTYLE\n105\n242\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nCivil-Metric\n 70\n0\n 41\n3.0\n 42\n1.5\n 43\n6.0\n 44\n3.0\n 73\n0\n 74\n0\n 77\n1\n 78\n3\n 79\n2\n140\n3.0\n141\n3.0\n147\n2.0\n179\n2\n271\n2\n272\n2\n276\n1\n340\n11\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n3.0\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nBLOCK_RECORD\n 5\n1\n330\n0\n100\nAcDbSymbolTable\n 70\n4\n 0\nBLOCK_RECORD\n 5\n1F\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n*Model_Space\n340\n530\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n58\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n*Paper_Space\n340\n531\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n238\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n_ArchTick\n340\n0\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n23C\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n_Open30\n340\n0\n 70\n0\n280\n1\n281\n0\n 0\nENDTAB\n 0\nENDSEC"},dxfBlocks:function(){return" 0\nSECTION\n 2\nBLOCKS\n 0\nBLOCK\n 5\n23A\n330\n238\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n_ArchTick\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n_ArchTick\n 1\n\n 0\nENDBLK\n 5\n23B\n330\n238\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n20\n330\n1F\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n*Model_Space\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n*Model_Space\n 1\n\n 0\nENDBLK\n 5\n21\n330\n1F\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n5A\n330\n58\n100\nAcDbEntity\n 67\n1\n 8\n0\n100\nAcDbBlockBegin\n 2\n*Paper_Space\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n*Paper_Space\n 1\n\n 0\nENDBLK\n 5\n5B\n330\n58\n100\nAcDbEntity\n 67\n1\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n240\n330\n23C\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n_Open30\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n_Open30\n 1\n\n 0\nENDBLK\n 5\n241\n330\n23C\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nENDSEC"},dxfObjects:function(){return" 0\nSECTION\n 2\nOBJECTS\n 0\nDICTIONARY\n 5\nC\n330\n0\n100\nAcDbDictionary\n281\n1\n 3\nACAD_COLOR\n350\n524\n 3\nACAD_GROUP\n350\n525\n 3\nACAD_LAYOUT\n350\n526\n 3\nACAD_MATERIAL\n350\n527\n 3\nACAD_MLEADERSTYLE\n350\n528\n 3\nACAD_MLINESTYLE\n350\n529\n 3\nACAD_PLOTSETTINGS\n350\n52A\n 3\nACAD_PLOTSTYLENAME\n350\n52C\n 3\nACAD_SCALELIST\n350\n52D\n 3\nACAD_TABLESTYLE\n350\n52E\n 3\nACAD_VISUALSTYLE\n350\n52F\n 0\nDICTIONARY\n 5\n524\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n525\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n526\n330\nC\n100\nAcDbDictionary\n281\n1\n 3\nModel\n350\n530\n 3\nLayout1\n350\n531\n 0\nDICTIONARY\n 5\n527\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n528\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n529\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52A\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nACDBPLACEHOLDER\n 5\n52B\n330\n52C\n 0\nACDBDICTIONARYWDFLT\n 5\n52C\n330\nC\n100\nAcDbDictionary\n281\n1\n 3\nNormal\n350\n52B\n100\nAcDbDictionaryWithDefault\n340\n52B\n 0\nDICTIONARY\n 5\n52D\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52E\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52F\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nLAYOUT\n 5\n530\n330\n526\n100\nAcDbPlotSettings\n 1\n\n 2\nDWFx ePlot (XPS Compatible).pc3\n 4\nANSI_A_(8.50_x_11.00_Inches)\n 6\n\n 40\n5.8\n 41\n17.8\n 42\n5.8\n 43\n17.8\n 44\n215.9\n 45\n279.4\n 46\n0.0\n 47\n0.0\n 48\n0.0\n 49\n0.0\n140\n0.0\n141\n0.0\n142\n1.0\n143\n14.53\n 70\n11952\n 72\n0\n 73\n1\n 74\n0\n 7\n\n 75\n0\n147\n0.069\n148\n114.98\n149\n300.29\n100\nAcDbLayout\n 1\nModel\n 70\n1\n 71\n0\n 10\n0.0\n 20\n0.0\n 11\n12.0\n 21\n9.0\n 12\n0.0\n 22\n0.0\n 32\n0.0\n 14\n0.0\n 24\n0.0\n 34\n0.0\n 15\n0.0\n 25\n0.0\n 35\n0.0\n146\n0.0\n 13\n0.0\n 23\n0.0\n 33\n0.0\n 16\n1.0\n 26\n0.0\n 36\n0.0\n 17\n0.0\n 27\n1.0\n 37\n0.0\n 76\n0\n330\n1F\n 0\nLAYOUT\n 5\n531\n330\n526\n100\nAcDbPlotSettings\n 1\n\n 2\nDWFx ePlot (XPS Compatible).pc3\n 4\nANSI_A_(8.50_x_11.00_Inches)\n 6\n\n 40\n5.8\n 41\n17.8\n 42\n5.8\n 43\n17.8\n 44\n215.9\n 45\n279.4\n 46\n0.0\n 47\n0.0\n 48\n0.0\n 49\n0.0\n140\n0.0\n141\n0.0\n142\n1.0\n143\n1.0\n 70\n688\n 72\n0\n 73\n1\n 74\n5\n 7\nacad.ctb\n 75\n16\n147\n1.0\n148\n0.0\n149\n0.0\n100\nAcDbLayout\n 1\nLayout1\n 70\n1\n 71\n1\n 10\n-0.7\n 20\n-0.23\n 11\n10.3\n 21\n8.27\n 12\n0.0\n 22\n0.0\n 32\n0.0\n 14\n0.63\n 24\n0.8\n 34\n0.0\n 15\n9.0\n 25\n7.2\n 35\n0.0\n146\n0.0\n 13\n0.0\n 23\n0.0\n 33\n0.0\n 16\n1.0\n 26\n0.0\n 36\n0.0\n 17\n0.0\n 27\n1.0\n 37\n0.0\n 76\n0\n330\n58\n 0\nENDSEC"}}},{}],12:[function(e,t,n){t.exports=[[0,0,0,255],[255,0,0,255],[255,255,0,255],[0,255,0,255],[0,255,255,255],[0,0,255,255],[255,0,255,255],[255,255,255,255],[128,128,128,255],[192,192,192,255],[255,0,0,255],[255,127,127,255],[165,0,0,255],[165,82,82,255],[127,0,0,255],[127,63,63,255],[76,0,0,255],[76,38,38,255],[38,0,0,255],[38,19,19,255],[255,63,0,255],[255,159,127,255],[165,41,0,255],[165,103,82,255],[127,31,0,255],[127,79,63,255],[76,19,0,255],[76,47,38,255],[38,9,0,255],[38,28,19,255],[255,127,0,255],[255,191,127,255],[165,82,0,255],[165,124,82,255],[127,63,0,255],[127,95,63,255],[76,38,0,255],[76,57,38,255],[38,19,0,255],[38,28,19,255],[255,191,0,255],[255,223,127,255],[165,124,0,255],[165,145,82,255],[127,95,0,255],[127,111,63,255],[76,57,0,255],[76,66,38,255],[38,28,0,255],[38,33,19,255],[255,255,0,255],[255,255,127,255],[165,165,0,255],[165,165,82,255],[127,127,0,255],[127,127,63,255],[76,76,0,255],[76,76,38,255],[38,38,0,255],[38,38,19,255],[191,255,0,255],[223,255,127,255],[124,165,0,255],[145,165,82,255],[95,127,0,255],[111,127,63,255],[57,76,0,255],[66,76,38,255],[28,38,0,255],[33,38,19,255],[127,255,0,255],[191,255,127,255],[82,165,0,255],[124,165,82,255],[63,127,0,255],[95,127,63,255],[38,76,0,255],[57,76,38,255],[19,38,0,255],[28,38,19,255],[63,255,0,255],[159,255,127,255],[41,165,0,255],[103,165,82,255],[31,127,0,255],[79,127,63,255],[19,76,0,255],[47,76,38,255],[9,38,0,255],[23,38,19,255],[0,255,0,255],[125,255,127,255],[0,165,0,255],[82,165,82,255],[0,127,0,255],[63,127,63,255],[0,76,0,255],[38,76,38,255],[0,38,0,255],[19,38,19,255],[0,255,63,255],[127,255,159,255],[0,165,41,255],[82,165,103,255],[0,127,31,255],[63,127,79,255],[0,76,19,255],[38,76,47,255],[0,38,9,255],[19,88,23,255],[0,255,127,255],[127,255,191,255],[0,165,82,255],[82,165,124,255],[0,127,63,255],[63,127,95,255],[0,76,38,255],[38,76,57,255],[0,38,19,255],[19,88,28,255],[0,255,191,255],[127,255,223,255],[0,165,124,255],[82,165,145,255],[0,127,95,255],[63,127,111,255],[0,76,57,255],[38,76,66,255],[0,38,28,255],[19,88,88,255],[0,255,255,255],[127,255,255,255],[0,165,165,255],[82,165,165,255],[0,127,127,255],[63,127,127,255],[0,76,76,255],[38,76,76,255],[0,38,38,255],[19,88,88,255],[0,191,255,255],[127,223,255,255],[0,124,165,255],[82,145,165,255],[0,95,127,255],[63,111,217,255],[0,57,76,255],[38,66,126,255],[0,28,38,255],[19,88,88,255],[0,127,255,255],[127,191,255,255],[0,82,165,255],[82,124,165,255],[0,63,127,255],[63,95,127,255],[0,38,76,255],[38,57,126,255],[0,19,38,255],[19,28,88,255],[0,63,255,255],[127,159,255,255],[0,41,165,255],[82,103,165,255],[0,31,127,255],[63,79,127,255],[0,19,76,255],[38,47,126,255],[0,9,38,255],[19,23,88,255],[0,0,255,255],[127,127,255,255],[0,0,165,255],[82,82,165,255],[0,0,127,255],[63,63,127,255],[0,0,76,255],[38,38,126,255],[0,0,38,255],[19,19,88,255],[63,0,255,255],[159,127,255,255],[41,0,165,255],[103,82,165,255],[31,0,127,255],[79,63,127,255],[19,0,76,255],[47,38,126,255],[9,0,38,255],[23,19,88,255],[127,0,255,255],[191,127,255,255],[165,0,82,255],[124,82,165,255],[63,0,127,255],[95,63,127,255],[38,0,76,255],[57,38,126,255],[19,0,38,255],[28,19,88,255],[191,0,255,255],[223,127,255,255],[124,0,165,255],[142,82,165,255],[95,0,127,255],[111,63,127,255],[57,0,76,255],[66,38,76,255],[28,0,38,255],[88,19,88,255],[255,0,255,255],[255,127,255,255],[165,0,165,255],[165,82,165,255],[127,0,127,255],[127,63,127,255],[76,0,76,255],[76,38,76,255],[38,0,38,255],[88,19,88,255],[255,0,191,255],[255,127,223,255],[165,0,124,255],[165,82,145,255],[127,0,95,255],[127,63,111,255],[76,0,57,255],[76,38,66,255],[38,0,28,255],[88,19,88,255],[255,0,127,255],[255,127,191,255],[165,0,82,255],[165,82,124,255],[127,0,63,255],[127,63,95,255],[76,0,38,255],[76,38,57,255],[38,0,19,255],[88,19,28,255],[255,0,63,255],[255,127,159,255],[165,0,41,255],[165,82,103,255],[127,0,31,255],[127,63,79,255],[76,0,19,255],[76,38,47,255],[38,0,9,255],[88,19,23,255],[0,0,0,255],[101,101,101,255],[102,102,102,255],[153,153,153,255],[204,204,204,255],[255,255,255,255]]},{}],13:[function(e,t,n){const{geometries:o,modifiers:r}=e("@jscad/modeling"),{geom3:s,geom2:a,path2:i}=o,{flatten:c,toArray:l}=e("@jscad/array-utils"),{dxfHeaders:u,dxfClasses:p,dxfTables:f,dxfBlocks:h,dxfObjects:m}=e("./autocad_AC2017"),g=e("./colorindex2017"),d=(e,t)=>{const n=e.map(((e,n)=>{if(a.isA(e)){const n=e.color,o=e.name,r=a.toOutlines(e).map((e=>({closed:!0,points:e,color:n,name:o})));return"polyline"===t.geom2To?v(r,t):y(r,t)}if(s.isA(e))return"polyline"===t.geom3To?E(e,t):b(e,t);if(i.isA(e)){const n=e.color,o=e.name,r={closed:e.isClosed,points:i.toPoints(e),color:n,name:o};return y([r],t)}return""}));let o=" 0\nSECTION\n 2\nENTITIES\n";return n.forEach((e=>{e&&(o+=e)})),o+=" 0\nENDSEC",o},y=(e,t)=>{t.statusCallback&&t.statusCallback({progress:0});let n="";return e.forEach(((o,r)=>{if(o.points.length<1)return;const s=o.points.length+(o.closed?1:0);n+=` 0\nLWPOLYLINE\n 5\n${S(t)}\n 100\nAcDbEntity\n 3\n${T(o,t)}\n 8\n0\n 67\n0\n 62\n${P(o,t)}\n 100\nAcDbPolyline\n 90\n${s}\n 70\n${o.closed?1:0}\n`;for(let e=0;e=o.points.length&&(t-=o.points.length);const r=o.points[t];n+=` 10\n${r[0]}\n 20\n${r[1]}\n`}t.statusCallback&&t.statusCallback({progress:100*r/e.length})})),t.statusCallback&&t.statusCallback({progress:100}),[n]},v=(e,t)=>{t.statusCallback&&t.statusCallback({progress:0});let n="";return e.forEach(((o,r)=>{const s=o.points.length+(o.closed?1:0);n+=` 0\nPOLYLINE\n 5\n${S(t)}\n 100\nAcDbEntity\n 3\n${T(o,t)}\n 8\n0\n 62\n${P(o,t)}\n 100\nAcDb2dPolyline\n`;for(let e=0;e=o.points.length&&(r-=o.points.length);const s=o.points[r];n+=` 0\nVERTEX\n 5\n${S(t)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb2dVertex\n 10\n${s[0]}\n 20\n${s[1]}\n`}n+=` 0\nSEQEND\n 5\n${S(t)}\n 100\nAcDbEntity\n`,t.statusCallback&&t.statusCallback({progress:100*r/e.length})})),t.statusCallback&&t.statusCallback({progress:100}),[n]},b=(e,t)=>{t.statusCallback&&t.statusCallback({progress:0});let n="";const o=s.toPolygons(e),r=P(e,t);return o.forEach(((e,o)=>{const s=e.color?P(e,t):r;x(e).forEach(((e,o)=>{n+=A(e,t,s)}))})),t.statusCallback&&t.statusCallback({progress:100}),[n]},x=e=>{const t=e.vertices.length-2;if(t<1)return[];const n=e.vertices[0],o=[];for(let r=0;r{const o=e[0],r=e[1],s=e[2],a=e[2];return` 0\n3DFACE\n 5\n${S(t)}\n 100\nAcDbEntity\n 8\n0\n 62\n${n}\n 100\nAcDbFace\n 70\n0\n 10\n${o[0]}\n 20\n${o[1]}\n 30\n${o[2]}\n 11\n${r[0]}\n 21\n${r[1]}\n 31\n${r[2]}\n 12\n${s[0]}\n 22\n${s[1]}\n 32\n${s[2]}\n 13\n${a[0]}\n 23\n${a[1]}\n 33\n${a[2]}\n`},E=(e,t)=>{let n="";const o=w(s.toPolygons(e));return o.faces.length>0&&(n+=` 0\nPOLYLINE\n 5\n${S(t)}\n 100\nAcDbEntity\n 3\n${T(e,t)}\n 8\n0\n 62\n${P(e,t)}\n 100\nAcDb3dPolyline\n 70\n64\n 71\n${o.vertices.length}\n 72\n${o.faces.length}\n`,o.vertices.forEach((e=>{n+=` 0\nVERTEX\n 5\n${S(t)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb3dPolylineVertex\n 10\n${e[0]}\n 20\n${e[1]}\n 30\n${e[2]}\n 70\n192\n`})),o.faces.forEach((e=>{n+=` 0\nVERTEX\n 5\n${S(t)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb3dPolylineVertex\n 10\n0\n 20\n0\n 30\n0\n 70\n128\n 71\n${e[0]}\n 72\n${e[1]}\n 73\n${e[2]}\n 74\n${e[3]}\n`}))),[n]},w=e=>{const t=[],n=[];for(let o=0;o{e.entityId++;const t="00000"+e.entityId.toString(16).toUpperCase();return"CAD"+t.substr(t.length-5)},T=(e,t)=>{if(e.name)return e.name;const n="00000"+t.entityId.toString(16).toUpperCase();return"CAD"+n.substr(n.length-5)},P=(e,t)=>{let n=256;if(e.color){const o=Math.floor(255*e.color[0]),r=Math.floor(255*e.color[1]),s=Math.floor(255*e.color[2]),a=t.colorIndex;let i=765;for(let e=1;e{const n={geom2To:"lwpolyline",geom3To:"3dface",pathTo:"lwpolyline",statusCallback:null,colorIndex:g};if((e=Object.assign({},n,e)).entityId=0,0===(t=(t=c(t)).filter((e=>s.isA(e)||a.isA(e)||i.isA(e)))).length)throw new Error("only JSCAD geometries can be serialized to DXF");return t=l(r.generalize({snap:!0,triangulate:!0},t)),[`999\nCreated by JSCAD\n${u(e)}\n${p(e)}\n${f(e)}\n${h(e)}\n${d(t,e)}\n${m(e)}\n 0\nEOF\n`]},mimeType:"application/dxf"}},{"./autocad_AC2017":11,"./colorindex2017":12,"@jscad/array-utils":6,"@jscad/modeling":104}],14:[function(e,t,n){const o=e("./cssColors");t.exports=e=>o[e.toLowerCase()]},{"./cssColors":16}],15:[function(e,t,n){const o=e("../utils/flatten"),r=e("../geometries/geom2"),s=e("../geometries/geom3"),a=e("../geometries/path2"),i=e("../geometries/poly3");t.exports=(e,...t)=>{if(!Array.isArray(e))throw new Error("color must be an array");if(e.length<3)throw new Error("color must contain R, G and B values");if(3===e.length&&(e=[e[0],e[1],e[2],1]),0===(t=o(t)).length)throw new Error("wrong number of arguments");const n=t.map((t=>r.isA(t)?((e,t)=>{const n=r.clone(t);return n.color=e,n})(e,t):s.isA(t)?((e,t)=>{const n=s.clone(t);return n.color=e,n})(e,t):a.isA(t)?((e,t)=>{const n=a.clone(t);return n.color=e,n})(e,t):i.isA(t)?((e,t)=>{const n=i.clone(t);return n.color=e,n})(e,t):(t.color=e,t)));return 1===n.length?n[0]:n}},{"../geometries/geom2":38,"../geometries/geom3":53,"../geometries/path2":74,"../geometries/poly3":91,"../utils/flatten":408}],16:[function(e,t,n){t.exports={black:[0,0,0],silver:[192/255,192/255,192/255],gray:[128/255,128/255,128/255],white:[1,1,1],maroon:[128/255,0,0],red:[1,0,0],purple:[128/255,0,128/255],fuchsia:[1,0,1],green:[0,128/255,0],lime:[0,1,0],olive:[128/255,128/255,0],yellow:[1,1,0],navy:[0,0,128/255],blue:[0,0,1],teal:[0,128/255,128/255],aqua:[0,1,1],aliceblue:[240/255,248/255,1],antiquewhite:[250/255,235/255,215/255],aquamarine:[127/255,1,212/255],azure:[240/255,1,1],beige:[245/255,245/255,220/255],bisque:[1,228/255,196/255],blanchedalmond:[1,235/255,205/255],blueviolet:[138/255,43/255,226/255],brown:[165/255,42/255,42/255],burlywood:[222/255,184/255,135/255],cadetblue:[95/255,158/255,160/255],chartreuse:[127/255,1,0],chocolate:[210/255,105/255,30/255],coral:[1,127/255,80/255],cornflowerblue:[100/255,149/255,237/255],cornsilk:[1,248/255,220/255],crimson:[220/255,20/255,60/255],cyan:[0,1,1],darkblue:[0,0,139/255],darkcyan:[0,139/255,139/255],darkgoldenrod:[184/255,134/255,11/255],darkgray:[169/255,169/255,169/255],darkgreen:[0,100/255,0],darkgrey:[169/255,169/255,169/255],darkkhaki:[189/255,183/255,107/255],darkmagenta:[139/255,0,139/255],darkolivegreen:[85/255,107/255,47/255],darkorange:[1,140/255,0],darkorchid:[.6,50/255,.8],darkred:[139/255,0,0],darksalmon:[233/255,150/255,122/255],darkseagreen:[143/255,188/255,143/255],darkslateblue:[72/255,61/255,139/255],darkslategray:[47/255,79/255,79/255],darkslategrey:[47/255,79/255,79/255],darkturquoise:[0,206/255,209/255],darkviolet:[148/255,0,211/255],deeppink:[1,20/255,147/255],deepskyblue:[0,191/255,1],dimgray:[105/255,105/255,105/255],dimgrey:[105/255,105/255,105/255],dodgerblue:[30/255,144/255,1],firebrick:[178/255,34/255,34/255],floralwhite:[1,250/255,240/255],forestgreen:[34/255,139/255,34/255],gainsboro:[220/255,220/255,220/255],ghostwhite:[248/255,248/255,1],gold:[1,215/255,0],goldenrod:[218/255,165/255,32/255],greenyellow:[173/255,1,47/255],grey:[128/255,128/255,128/255],honeydew:[240/255,1,240/255],hotpink:[1,105/255,180/255],indianred:[205/255,92/255,92/255],indigo:[75/255,0,130/255],ivory:[1,1,240/255],khaki:[240/255,230/255,140/255],lavender:[230/255,230/255,250/255],lavenderblush:[1,240/255,245/255],lawngreen:[124/255,252/255,0],lemonchiffon:[1,250/255,205/255],lightblue:[173/255,216/255,230/255],lightcoral:[240/255,128/255,128/255],lightcyan:[224/255,1,1],lightgoldenrodyellow:[250/255,250/255,210/255],lightgray:[211/255,211/255,211/255],lightgreen:[144/255,238/255,144/255],lightgrey:[211/255,211/255,211/255],lightpink:[1,182/255,193/255],lightsalmon:[1,160/255,122/255],lightseagreen:[32/255,178/255,170/255],lightskyblue:[135/255,206/255,250/255],lightslategray:[119/255,136/255,.6],lightslategrey:[119/255,136/255,.6],lightsteelblue:[176/255,196/255,222/255],lightyellow:[1,1,224/255],limegreen:[50/255,205/255,50/255],linen:[250/255,240/255,230/255],magenta:[1,0,1],mediumaquamarine:[.4,205/255,170/255],mediumblue:[0,0,205/255],mediumorchid:[186/255,85/255,211/255],mediumpurple:[147/255,112/255,219/255],mediumseagreen:[60/255,179/255,113/255],mediumslateblue:[123/255,104/255,238/255],mediumspringgreen:[0,250/255,154/255],mediumturquoise:[72/255,209/255,.8],mediumvioletred:[199/255,21/255,133/255],midnightblue:[25/255,25/255,112/255],mintcream:[245/255,1,250/255],mistyrose:[1,228/255,225/255],moccasin:[1,228/255,181/255],navajowhite:[1,222/255,173/255],oldlace:[253/255,245/255,230/255],olivedrab:[107/255,142/255,35/255],orange:[1,165/255,0],orangered:[1,69/255,0],orchid:[218/255,112/255,214/255],palegoldenrod:[238/255,232/255,170/255],palegreen:[152/255,251/255,152/255],paleturquoise:[175/255,238/255,238/255],palevioletred:[219/255,112/255,147/255],papayawhip:[1,239/255,213/255],peachpuff:[1,218/255,185/255],peru:[205/255,133/255,63/255],pink:[1,192/255,203/255],plum:[221/255,160/255,221/255],powderblue:[176/255,224/255,230/255],rosybrown:[188/255,143/255,143/255],royalblue:[65/255,105/255,225/255],saddlebrown:[139/255,69/255,19/255],salmon:[250/255,128/255,114/255],sandybrown:[244/255,164/255,96/255],seagreen:[46/255,139/255,87/255],seashell:[1,245/255,238/255],sienna:[160/255,82/255,45/255],skyblue:[135/255,206/255,235/255],slateblue:[106/255,90/255,205/255],slategray:[112/255,128/255,144/255],slategrey:[112/255,128/255,144/255],snow:[1,250/255,250/255],springgreen:[0,1,127/255],steelblue:[70/255,130/255,180/255],tan:[210/255,180/255,140/255],thistle:[216/255,191/255,216/255],tomato:[1,99/255,71/255],turquoise:[64/255,224/255,208/255],violet:[238/255,130/255,238/255],wheat:[245/255,222/255,179/255],whitesmoke:[245/255,245/255,245/255],yellowgreen:[154/255,205/255,50/255]}},{}],17:[function(e,t,n){t.exports=e=>{if((e=e.replace("#","")).length<6)throw new Error("the given notation must contain 3 or more hex values");const t=parseInt(e.substring(0,2),16)/255,n=parseInt(e.substring(2,4),16)/255,o=parseInt(e.substring(4,6),16)/255;return e.length>=8?[t,n,o,parseInt(e.substring(6,8),16)/255]:[t,n,o]}},{}],18:[function(e,t,n){const o=e("../utils/flatten"),r=e("./hueToColorComponent");t.exports=(...e)=>{if((e=o(e)).length<3)throw new Error("values must contain H, S and L values");const t=e[0],n=e[1],s=e[2];let a=s,i=s,c=s;if(0!==n){const e=s<.5?s*(1+n):s+n-s*n,o=2*s-e;a=r(o,e,t+1/3),i=r(o,e,t),c=r(o,e,t-1/3)}return e.length>3?[a,i,c,e[3]]:[a,i,c]}},{"../utils/flatten":408,"./hueToColorComponent":20}],19:[function(e,t,n){const o=e("../utils/flatten");t.exports=(...e)=>{if((e=o(e)).length<3)throw new Error("values must contain H, S and V values");const t=e[0],n=e[1],r=e[2];let s=0,a=0,i=0;const c=Math.floor(6*t),l=6*t-c,u=r*(1-n),p=r*(1-l*n),f=r*(1-(1-l)*n);switch(c%6){case 0:s=r,a=f,i=u;break;case 1:s=p,a=r,i=u;break;case 2:s=u,a=r,i=f;break;case 3:s=u,a=p,i=r;break;case 4:s=f,a=u,i=r;break;case 5:s=r,a=u,i=p}return e.length>3?[s,a,i,e[3]]:[s,a,i]}},{"../utils/flatten":408}],20:[function(e,t,n){t.exports=(e,t,n)=>(n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e)},{}],21:[function(e,t,n){t.exports={colorize:e("./colorize"),colorNameToRgb:e("./colorNameToRgb"),cssColors:e("./cssColors"),hexToRgb:e("./hexToRgb"),hslToRgb:e("./hslToRgb"),hsvToRgb:e("./hsvToRgb"),hueToColorComponent:e("./hueToColorComponent"),rgbToHex:e("./rgbToHex"),rgbToHsl:e("./rgbToHsl"),rgbToHsv:e("./rgbToHsv")}},{"./colorNameToRgb":14,"./colorize":15,"./cssColors":16,"./hexToRgb":17,"./hslToRgb":18,"./hsvToRgb":19,"./hueToColorComponent":20,"./rgbToHex":22,"./rgbToHsl":23,"./rgbToHsv":24}],22:[function(e,t,n){const o=e("../utils/flatten");t.exports=(...e)=>{if((e=o(e)).length<3)throw new Error("values must contain R, G and B values");const t=255*e[0],n=255*e[1],r=255*e[2];let s=`#${Number(16777216+65536*t+256*n+r).toString(16).substring(1,7)}`;return e.length>3&&(s+=Number(255*e[3]).toString(16)),s}},{"../utils/flatten":408}],23:[function(e,t,n){const o=e("../utils/flatten");t.exports=(...e)=>{if((e=o(e)).length<3)throw new Error("values must contain R, G and B values");const t=e[0],n=e[1],r=e[2],s=Math.max(t,n,r),a=Math.min(t,n,r);let i,c;const l=(s+a)/2;if(s===a)i=c=0;else{const e=s-a;switch(c=l>.5?e/(2-s-a):e/(s+a),s){case t:i=(n-r)/e+(n3?[i,c,l,e[3]]:[i,c,l]}},{"../utils/flatten":408}],24:[function(e,t,n){const o=e("../utils/flatten");t.exports=(...e)=>{if((e=o(e)).length<3)throw new Error("values must contain R, G and B values");const t=e[0],n=e[1],r=e[2],s=Math.max(t,n,r),a=Math.min(t,n,r);let i;const c=s,l=s-a,u=0===s?0:l/s;if(s===a)i=0;else{switch(s){case t:i=(n-r)/l+(n3?[i,u,c,e[3]]:[i,u,c]}},{"../utils/flatten":408}],25:[function(e,t,n){const o=e("./lengths");t.exports=(e,t)=>{const{distance:n,segments:r}=Object.assign({},{distance:0,segments:100},e),s=o(r,t);let a=0,i=r;for(;a<=i;){const e=Math.floor(a+(i-a)/2),t=s[e]-n;if(t<0)a=e+1;else{if(!(t>0)){i=e;break}i=e-1}}const c=i;if(s[c]===n)return c/r;const l=s[c];return(c+(n-l)/(s[c+1]-l))/r}},{"./lengths":29}],26:[function(e,t,n){const o=function(e){const t=[];for(let n=0;n<=e;n++)t.push(r(e)/(r(n)*r(e-n)));return t},r=function(e){let t=1;for(let n=2;n<=e;n++)t*=n;return t};t.exports=e=>{if(!Array.isArray(e))throw new Error("Bezier points must be a valid array/");if(e.length<2)throw new Error("Bezier points must contain at least 2 values.");const t=function(e){let t=null;return e.forEach((e=>{let n="";if(Number.isFinite(e))n="float_single";else{if(!Array.isArray(e))throw new Error("Bezier points must all be numbers or arrays of number.");e.forEach((e=>{if(!Number.isFinite(e))throw new Error("Bezier point values must all be numbers.")})),n="float_"+e.length}if(null==t)t=n;else if(t!==n)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),t}(e);return{points:e,pointType:t,dimensions:"float_single"===t?0:e[0].length,permutations:o(e.length-1),tangentPermutations:o(e.length-2)}}},{}],27:[function(e,t,n){t.exports={create:e("./create"),valueAt:e("./valueAt"),tangentAt:e("./tangentAt"),lengths:e("./lengths"),length:e("./length"),arcLengthToT:e("./arcLengthToT")}},{"./arcLengthToT":25,"./create":26,"./length":28,"./lengths":29,"./tangentAt":30,"./valueAt":31}],28:[function(e,t,n){const o=e("./lengths");t.exports=(e,t)=>o(e,t)[e]},{"./lengths":29}],29:[function(e,t,n){const o=e("./valueAt"),r=(e,t)=>{if(Number.isFinite(e)&&Number.isFinite(t))return Math.abs(e-t);if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)throw new Error("The operands must have the same number of dimensions.");let n=0;for(let o=0;o{let n=0;const s=[0];let a=o(0,t);for(let i=1;i<=e;i++){const c=o(i/e,t);n+=r(c,a),s.push(n),a=c}return s}},{"./valueAt":31}],30:[function(e,t,n){const o=function(e,t,n){const o=t.length-1;let r=0;for(let s=0;s{if(e<0||e>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===t.pointType)return o(t,t.points,e);{const n=[];for(let r=0;r{if(e<0||e>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===t.pointType)return o(t,t.points,e);{const n=[];for(let r=0;r(o.isIdentity(e.transforms)||(e.sides=e.sides.map((t=>[r.transform(r.create(),t[0],e.transforms),r.transform(r.create(),t[1],e.transforms)])),e.transforms=o.create()),e)},{"../../maths/mat4":155,"../../maths/vec2":202}],34:[function(e,t,n){t.exports=e=>Object.assign({},e)},{}],35:[function(e,t,n){const o=e("../../maths/mat4");t.exports=e=>(void 0===e&&(e=[]),{sides:e,transforms:o.create()})},{"../../maths/mat4":155}],36:[function(e,t,n){const o=e("../../maths/mat4"),r=e("../../maths/vec2"),s=e("./create");t.exports=e=>{if(0!==e[0])throw new Error("invalid compact binary data");const t=s();t.transforms=o.clone(e.slice(1,17));for(let n=21;n=0&&(t.color=[e[17],e[18],e[19],e[20]]),t}},{"../../maths/mat4":155,"../../maths/vec2":202,"./create":35}],37:[function(e,t,n){const o=e("../../maths/vec2"),r=e("./create");t.exports=e=>{if(!Array.isArray(e))throw new Error("the given points must be an array");let t=e.length;if(t<3)throw new Error("the given points must define a closed geometry with three or more points");o.equals(e[0],e[t-1])&&--t;const n=[];let s=e[t-1];for(let r=0;r!!(e&&"object"==typeof e&&"sides"in e&&"transforms"in e&&Array.isArray(e.sides)&&"length"in e.transforms)},{}],40:[function(e,t,n){const o=e("./create"),r=e("./toSides");t.exports=e=>{const t=r(e).map((e=>[e[1],e[0]]));return t.reverse(),o(t)}},{"./create":35,"./toSides":44}],41:[function(e,t,n){t.exports=e=>{const t=e.sides,n=e.transforms;let o=[-1,-1,-1,-1];e.color&&(o=e.color);const r=new Float32Array(21+4*t.length);r[0]=0,r[1]=n[0],r[2]=n[1],r[3]=n[2],r[4]=n[3],r[5]=n[4],r[6]=n[5],r[7]=n[6],r[8]=n[7],r[9]=n[8],r[10]=n[9],r[11]=n[10],r[12]=n[11],r[13]=n[12],r[14]=n[13],r[15]=n[14],r[16]=n[15],r[17]=o[0],r[18]=o[1],r[19]=o[2],r[20]=o[3];for(let e=0;e{if(1===t.length)return t.pop();const n=o.create(),r=o.angleDegrees(o.subtract(n,e[1],e[0]));let s,a;t.forEach(((e,t)=>{let i=o.angleDegrees(o.subtract(n,e[1],e[0]))-r;i<-180&&(i+=360),i>=180&&(i-=360),(void 0===a||i>s)&&(a=t,s=i)}));const i=t[a];return t.splice(a,1),i};t.exports=e=>{const t=(e=>{const t=new Map;return(e=>{const t=new Map,n=e=>{const n=e.toString();return t.has(n)?t.get(n):(t.set(n,e),e)};return e.map((e=>e.map(n)))})(e).forEach((e=>{t.has(e[0])?t.get(e[0]).push(e):t.set(e[0],[e])})),t})(r(e)),n=[];for(;;){let e;for(const[n,o]of t){if(e=o.shift(),e)break;t.delete(n)}if(void 0===e)break;const o=[],r=e[0];for(;;){o.push(e[0]);const n=e[1];if(n===r)break;const a=t.get(n);if(!a)throw new Error(`geometry is not closed at vertex ${n}`);const i=s(e,a);0===a.length&&t.delete(n),e=i}o.length>0&&o.push(o.shift()),n.push(o)}return t.clear(),n}},{"../../maths/vec2":202,"./toSides":44}],43:[function(e,t,n){const o=e("./toSides");t.exports=e=>{const t=o(e).map((e=>e[0]));return t.length>0&&t.push(t.shift()),t}},{"./toSides":44}],44:[function(e,t,n){const o=e("./applyTransforms");t.exports=e=>o(e).sides},{"./applyTransforms":33}],45:[function(e,t,n){const o=e("../../maths/vec2"),r=e("./toSides");t.exports=e=>{const t=r(e);let n="geom2 ("+t.length+" sides):\n[\n";return t.forEach((e=>{n+=" ["+o.toString(e[0])+", "+o.toString(e[1])+"]\n"})),n+="]\n",n}},{"../../maths/vec2":202,"./toSides":44}],46:[function(e,t,n){const o=e("../../maths/mat4");t.exports=(e,t)=>{const n=o.multiply(o.create(),e,t.transforms);return Object.assign({},t,{transforms:n})}},{"../../maths/mat4":155}],47:[function(e,t,n){const o=e("../../maths/vec2"),r=e("./isA"),s=e("./toOutlines");t.exports=e=>{if(!r(e))throw new Error("invalid geom2 structure");if(s(e),e.sides.forEach((e=>{if(o.equals(e[0],e[1]))throw new Error(`geom2 self-edge ${e[0]}`)})),!e.transforms.every(Number.isFinite))throw new Error(`geom2 invalid transforms ${e.transforms}`)}},{"../../maths/vec2":202,"./isA":39,"./toOutlines":42}],48:[function(e,t,n){const o=e("../../maths/mat4"),r=e("../poly3");t.exports=e=>(o.isIdentity(e.transforms)||(e.polygons=e.polygons.map((t=>r.transform(e.transforms,t))),e.transforms=o.create()),e)},{"../../maths/mat4":155,"../poly3":91}],49:[function(e,t,n){t.exports=e=>Object.assign({},e)},{}],50:[function(e,t,n){const o=e("../../maths/mat4");t.exports=e=>(void 0===e&&(e=[]),{polygons:e,transforms:o.create()})},{"../../maths/mat4":155}],51:[function(e,t,n){const o=e("../../maths/vec3"),r=e("../../maths/mat4"),s=e("../poly3"),a=e("./create");t.exports=e=>{if(1!==e[0])throw new Error("invalid compact binary data");const t=a();t.transforms=r.clone(e.slice(1,17));const n=e[21];let i=22,c=e.length-3*n;for(;c=0&&(t.color=[e[17],e[18],e[19],e[20]]),t}},{"../../maths/mat4":155,"../../maths/vec3":233,"../poly3":91,"./create":50}],52:[function(e,t,n){const o=e("../poly3"),r=e("./create");t.exports=e=>{if(!Array.isArray(e))throw new Error("the given points must be an array");const t=e.map(((e,t)=>o.create(e)));return r(t)}},{"../poly3":91,"./create":50}],53:[function(e,t,n){t.exports={clone:e("./clone"),create:e("./create"),fromPoints:e("./fromPoints"),fromCompactBinary:e("./fromCompactBinary"),invert:e("./invert"),isA:e("./isA"),toPoints:e("./toPoints"),toPolygons:e("./toPolygons"),toString:e("./toString"),toCompactBinary:e("./toCompactBinary"),transform:e("./transform"),validate:e("./validate")}},{"./clone":49,"./create":50,"./fromCompactBinary":51,"./fromPoints":52,"./invert":54,"./isA":55,"./toCompactBinary":56,"./toPoints":57,"./toPolygons":58,"./toString":59,"./transform":60,"./validate":61}],54:[function(e,t,n){const o=e("../poly3"),r=e("./create"),s=e("./toPolygons");t.exports=e=>{const t=s(e).map((e=>o.invert(e)));return r(t)}},{"../poly3":91,"./create":50,"./toPolygons":58}],55:[function(e,t,n){t.exports=e=>!!(e&&"object"==typeof e&&"polygons"in e&&"transforms"in e&&Array.isArray(e.polygons)&&"length"in e.transforms)},{}],56:[function(e,t,n){const o=e("../poly3");t.exports=e=>{const t=e.polygons,n=e.transforms,r=t.length,s=t.reduce(((e,t)=>e+t.vertices.length),0);let a=[-1,-1,-1,-1];e.color&&(a=e.color);const i=new Float32Array(22+r+3*s);i[0]=1,i[1]=n[0],i[2]=n[1],i[3]=n[2],i[4]=n[3],i[5]=n[4],i[6]=n[5],i[7]=n[6],i[8]=n[7],i[9]=n[8],i[10]=n[9],i[11]=n[10],i[12]=n[11],i[13]=n[12],i[14]=n[13],i[15]=n[14],i[16]=n[15],i[17]=a[0],i[18]=a[1],i[19]=a[2],i[20]=a[3],i[21]=s;let c=22,l=c+r;return t.forEach((e=>{const t=o.toPoints(e);i[c]=t.length,c++;for(let e=0;er(e).map((e=>o.toPoints(e)))},{"../poly3":91,"./toPolygons":58}],58:[function(e,t,n){const o=e("./applyTransforms");t.exports=e=>o(e).polygons},{"./applyTransforms":48}],59:[function(e,t,n){const o=e("../poly3"),r=e("./toPolygons");t.exports=e=>{const t=r(e);let n="geom3 ("+t.length+" polygons):\n";return t.forEach((e=>{n+=" "+o.toString(e)+"\n"})),n}},{"../poly3":91,"./toPolygons":58}],60:[function(e,t,n){const o=e("../../maths/mat4");t.exports=(e,t)=>{const n=o.multiply(o.create(),e,t.transforms);return Object.assign({},t,{transforms:n})}},{"../../maths/mat4":155}],61:[function(e,t,n){const o=e("../poly3"),r=e("./isA");t.exports=e=>{if(!r(e))throw new Error("invalid geom3 structure");if(e.polygons.forEach(o.validate),(e=>{const t=new Map;e.polygons.forEach((({vertices:e})=>{e.forEach(((n,o)=>{const r=`${n}/${e[(o+1)%e.length]}`,s=t.has(r)?t.get(r):0;t.set(r,s+1)}))}));const n=[];if(t.forEach(((e,o)=>{const r=o.split("/").reverse().join("/");e!==t.get(r)&&n.push(o.replace("/"," -> "))})),n.length>0)throw new Error(`non-manifold edges ${n.length}\n${n.join("\n")}`)})(e),!e.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${e.transforms}`)}},{"../poly3":91,"./isA":55}],62:[function(e,t,n){t.exports={geom2:e("./geom2"),geom3:e("./geom3"),path2:e("./path2"),poly2:e("./poly2"),poly3:e("./poly3")}},{"./geom2":38,"./geom3":53,"./path2":74,"./poly2":85,"./poly3":91}],63:[function(e,t,n){const{TAU:o}=e("../../maths/constants"),r=e("../../maths/vec2"),s=e("./fromPoints"),a=e("./toPoints");t.exports=(e,t)=>{let{endpoint:n,radius:i,xaxisrotation:c,clockwise:l,large:u,segments:p}=Object.assign({},{radius:[0,0],xaxisrotation:0,clockwise:!1,large:!1,segments:16},e);if(!Array.isArray(n))throw new Error("endpoint must be an array of X and Y values");if(n.length<2)throw new Error("endpoint must contain X and Y values");if(n=r.clone(n),!Array.isArray(i))throw new Error("radius must be an array of X and Y values");if(i.length<2)throw new Error("radius must contain X and Y values");if(p<4)throw new Error("segments must be four or more");const f=1e5;if(t.isClosed)throw new Error("the given path cannot be closed");const h=a(t);if(h.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let m=i[0],g=i[1];const d=h[h.length-1];m=Math.round(m*f)/f,g=Math.round(g*f)/f,n=r.fromValues(Math.round(n[0]*f)/f,Math.round(n[1]*f)/f);const y=!l;let v=[];if(0===m||0===g)v.push(n);else{m=Math.abs(m),g=Math.abs(g);const t=c,s=Math.cos(t),a=Math.sin(t),i=r.subtract(r.create(),d,n);r.scale(i,i,.5);const l=Math.round((s*i[0]+a*i[1])*f)/f,h=Math.round((-a*i[0]+s*i[1])*f)/f,b=r.fromValues(l,h),x=b[0]*b[0]/(m*m)+b[1]*b[1]/(g*g);if(x>1){const e=Math.sqrt(x);m*=e,g*=e,m=Math.round(m*f)/f,g=Math.round(g*f)/f}let A=Math.sqrt((m*m*g*g-m*m*b[1]*b[1]-g*g*b[0]*b[0])/(m*m*b[1]*b[1]+g*g*b[0]*b[0]));y===u&&(A=-A);const E=r.fromValues(m*b[1]/g,-g*b[0]/m);r.scale(E,E,A);let w=r.fromValues(s*E[0]-a*E[1],a*E[0]+s*E[1]);w=r.add(w,w,r.scale(r.create(),r.add(r.create(),d,n),.5));const S=r.fromValues((b[0]-E[0])/m,(b[1]-E[1])/g),T=r.fromValues((-b[0]-E[0])/m,(-b[1]-E[1])/g),P=r.angleRadians(S);let D=r.angleRadians(T)-P;D%=o,!y&&D>0?D-=o:y&&D<0&&(D+=o);let C=Math.ceil(Math.abs(D)/o*p)+1;C<1&&(C=1);for(let e=1;e{let{controlPoints:n,segments:c}=Object.assign({},{segments:16},e);if(!Array.isArray(n))throw new Error("controlPoints must be an array of one or more points");if(n.length<1)throw new Error("controlPoints must be an array of one or more points");if(c<4)throw new Error("segments must be four or more");if(t.isClosed)throw new Error("the given geometry cannot be closed");const l=i(t);if(l.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(n=n.slice(),null===n[0]){if(n.length<2)throw new Error("a null control point must be passed with one more control points");let e=l[l.length-2];if("lastBezierControlPoint"in t&&(e=t.lastBezierControlPoint),!Array.isArray(e))throw new Error("the given path must contain TWO or more points if given a null control point");const o=r.scale(r.create(),l[l.length-1],2);r.subtract(o,o,e),n[0]=o}n.unshift(l[l.length-1]);const u=n.length-1,p=[];let f=1;for(let e=0;e<=u;++e)e>0&&(f*=e),p.push(f);const h=[];for(let e=0;e<=u;++e){const t=p[u]/(p[e]*p[u-e]);h.push(t)}const m=r.create(),g=r.create(),d=s.create(),y=e=>{let t=1,o=Math.pow(1-e,u);const s=1!==e?1/(1-e):1,a=r.create();for(let i=0;i<=u;++i){i===u&&(o=1);const c=h[i]*t*o,l=r.scale(m,n[i],c);r.add(a,a,l),t*=e,o*=s}return a},v=[],b=[],x=u+1;for(let e=0;ew){const e=b[A-1],t=b[A+1],n=e+1*(t-e)/3,o=e+2*(t-e)/3,r=y(n),s=y(o);v.splice(A,1,r,s),b.splice(A,1,n,o),A--,A<1&&(A=1)}else++A}v.shift();const S=a(v,t);return S.lastBezierControlPoint=n[n.length-2],S}},{"../../maths/constants":106,"../../maths/vec2":202,"./appendPoints":65,"./toPoints":78}],65:[function(e,t,n){const o=e("./concat"),r=e("./create");t.exports=(e,t)=>o(t,r(e))},{"./concat":69,"./create":70}],66:[function(e,t,n){const o=e("../../maths/mat4"),r=e("../../maths/vec2");t.exports=e=>(o.isIdentity(e.transforms)||(e.points=e.points.map((t=>r.transform(r.create(),t,e.transforms))),e.transforms=o.create()),e)},{"../../maths/mat4":155,"../../maths/vec2":202}],67:[function(e,t,n){t.exports=e=>Object.assign({},e)},{}],68:[function(e,t,n){const{EPS:o}=e("../../maths/constants"),r=e("../../maths/vec2"),s=e("./clone");t.exports=e=>{if(e.isClosed)return e;const t=s(e);if(t.isClosed=!0,t.points.length>1){const e=t.points,n=e[0];let s=e[e.length-1];for(;r.distance(n,s){let t=!1,n=[];return e.forEach(((e,o)=>{const a=r(e).slice();if(n.length>0&&a.length>0&&s(a[0],n[n.length-1])&&a.shift(),a.length>0&&t)throw new Error(`Cannot concatenate to a closed path; check the ${o}th path`);t=e.isClosed,n=n.concat(a)})),o({closed:t},n)}},{"../../maths/vec2":202,"./fromPoints":73,"./toPoints":78}],70:[function(e,t,n){const o=e("../../maths/mat4");t.exports=e=>(void 0===e&&(e=[]),{points:e,isClosed:!1,transforms:o.create()})},{"../../maths/mat4":155}],71:[function(e,t,n){const o=e("../../maths/vec2"),r=e("./toPoints");t.exports=(e,t)=>{if(e.isClosed!==t.isClosed)return!1;if(e.points.length!==t.points.length)return!1;const n=r(e),s=r(t),a=n.length;let i=0;do{let t=!1;for(let e=0;e{if(2!==e[0])throw new Error("invalid compact binary data");const t=s();t.transforms=o.clone(e.slice(1,17)),t.isClosed=!!e[17];for(let n=22;n=0&&(t.color=[e[18],e[19],e[20],e[21]]),t}},{"../../maths/mat4":155,"../../maths/vec2":202,"./create":70}],73:[function(e,t,n){const{EPS:o}=e("../../maths/constants"),r=e("../../maths/vec2"),s=e("./close"),a=e("./create");t.exports=(e,t)=>{let{closed:n}=Object.assign({},{closed:!1},e),i=a();if(i.points=t.map((e=>r.clone(e))),i.points.length>1){const e=i.points[0],t=i.points[i.points.length-1];r.distance(e,t)!!(e&&"object"==typeof e&&"points"in e&&"transforms"in e&&"isClosed"in e&&Array.isArray(e.points)&&"length"in e.transforms)},{}],76:[function(e,t,n){const o=e("./clone");t.exports=e=>{const t=o(e);return t.points=e.points.slice().reverse(),t}},{"./clone":67}],77:[function(e,t,n){t.exports=e=>{const t=e.points,n=e.transforms;let o=[-1,-1,-1,-1];e.color&&(o=e.color);const r=new Float32Array(22+2*t.length);r[0]=2,r[1]=n[0],r[2]=n[1],r[3]=n[2],r[4]=n[3],r[5]=n[4],r[6]=n[5],r[7]=n[6],r[8]=n[7],r[9]=n[8],r[10]=n[9],r[11]=n[10],r[12]=n[11],r[13]=n[12],r[14]=n[13],r[15]=n[14],r[16]=n[15],r[17]=e.isClosed?1:0,r[18]=o[0],r[19]=o[1],r[20]=o[2],r[21]=o[3];for(let e=0;eo(e).points},{"./applyTransforms":66}],79:[function(e,t,n){const o=e("../../maths/vec2"),r=e("./toPoints");t.exports=e=>{const t=r(e);let n="path ("+t.length+" points, "+e.isClosed+"):\n[\n";return t.forEach((e=>{n+=" "+o.toString(e)+",\n"})),n+="]\n",n}},{"../../maths/vec2":202,"./toPoints":78}],80:[function(e,t,n){const o=e("../../maths/mat4");t.exports=(e,t)=>{const n=o.multiply(o.create(),e,t.transforms);return Object.assign({},t,{transforms:n})}},{"../../maths/mat4":155}],81:[function(e,t,n){const o=e("../../maths/vec2"),r=e("./isA");t.exports=e=>{if(!r(e))throw new Error("invalid path2 structure");if(e.points.length>1)for(let t=0;t{if(!e.every(Number.isFinite))throw new Error(`path2 invalid point ${e}`)})),!e.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${e.transforms}`)}},{"../../maths/vec2":202,"./isA":75}],82:[function(e,t,n){const o=e("./measureArea"),r=e("./flip");t.exports=(e,t)=>{if(0===e.length)return 0;const n=t.vertices;return n.length<3?0:(o(t)<0&&(t=r(t)),e.reduce(((e,t)=>e+((e,t)=>{const n=t.length,o=e[0],r=e[1];let s=t[n-1],a=t[0],i=s[1]>r,c=0,l=0;for(let e=n+1;--e;){const e=a[1]>r;if(i!==e){const e=s[0]>o,t=a[0]>o;(e&&t||a[0]-(a[1]-r)*(s[0]-a[0])/(s[1]-a[1])>=o)&&(c=!c)}i=e,s=a,a=t[++l]}return c})(t,n)),0)===e.length?1:0)}},{"./flip":84,"./measureArea":86}],83:[function(e,t,n){t.exports=e=>((void 0===e||e.length<3)&&(e=[]),{vertices:e})},{}],84:[function(e,t,n){const o=e("./create");t.exports=e=>{const t=e.vertices.slice().reverse();return o(t)}},{"./create":83}],85:[function(e,t,n){t.exports={arePointsInside:e("./arePointsInside"),create:e("./create"),flip:e("./flip"),measureArea:e("./measureArea")}},{"./arePointsInside":82,"./create":83,"./flip":84,"./measureArea":86}],86:[function(e,t,n){const o=e("../../maths/utils/area");t.exports=e=>o(e.vertices)},{"../../maths/utils/area":179}],87:[function(e,t,n){const o=e("./create"),r=e("../../maths/vec3");t.exports=(...e)=>{let t,n;return 1===e.length?(t=o(),n=e[0]):(t=e[0],n=e[1]),t.vertices=n.vertices.map((e=>r.clone(e))),t}},{"../../maths/vec3":233,"./create":88}],88:[function(e,t,n){t.exports=e=>((void 0===e||e.length<3)&&(e=[]),{vertices:e})},{}],89:[function(e,t,n){const o=e("../../maths/vec3"),r=e("./create");t.exports=e=>{const t=e.map((e=>o.clone(e)));return r(t)}},{"../../maths/vec3":233,"./create":88}],90:[function(e,t,n){const o=e("./create");t.exports=(e,t)=>{const n=o(e);return n.plane=t,n}},{"./create":88}],91:[function(e,t,n){t.exports={clone:e("./clone"),create:e("./create"),fromPoints:e("./fromPoints"),fromPointsAndPlane:e("./fromPointsAndPlane"),invert:e("./invert"),isA:e("./isA"),isConvex:e("./isConvex"),measureArea:e("./measureArea"),measureBoundingBox:e("./measureBoundingBox"),measureBoundingSphere:e("./measureBoundingSphere"),measureSignedVolume:e("./measureSignedVolume"),plane:e("./plane"),toPoints:e("./toPoints"),toString:e("./toString"),transform:e("./transform"),validate:e("./validate")}},{"./clone":87,"./create":88,"./fromPoints":89,"./fromPointsAndPlane":90,"./invert":92,"./isA":93,"./isConvex":94,"./measureArea":95,"./measureBoundingBox":96,"./measureBoundingSphere":97,"./measureSignedVolume":98,"./plane":99,"./toPoints":100,"./toString":101,"./transform":102,"./validate":103}],92:[function(e,t,n){const o=e("../../maths/plane"),r=e("./create");t.exports=e=>{const t=e.vertices.slice().reverse(),n=r(t);return e.plane&&(n.plane=o.flip(o.create(),e.plane)),n}},{"../../maths/plane":174,"./create":88}],93:[function(e,t,n){t.exports=e=>!!(e&&"object"==typeof e&&"vertices"in e&&Array.isArray(e.vertices))},{}],94:[function(e,t,n){const o=e("../../maths/plane"),r=e("../../maths/vec3"),s=(e,t,n,o)=>{const s=r.cross(r.create(),r.subtract(r.create(),t,e),r.subtract(r.create(),n,t));return r.dot(s,o)>=0};t.exports=e=>(e=>{const t=e.length;if(t>2){const n=o.fromPoints(o.create(),...e);let r=e[t-2],a=e[t-1];for(let o=0;o{const t=e.vertices.length;if(t<3)return 0;const n=e.vertices,r=o(e),s=Math.abs(r[0]),a=Math.abs(r[1]),i=Math.abs(r[2]);if(s+a+i===0)return 0;let c=3;s>a&&s>i?c=1:a>i&&(c=2);let l=0,u=0,p=1,f=2;switch(c){case 1:for(p=1;p{const t=e.vertices,n=t.length,r=0===n?o.create():o.clone(t[0]),s=o.clone(r);for(let e=1;e{const t=r.get(e);if(t)return t;const n=e.vertices,s=o.create();if(0===n.length)return s[0]=0,s[1]=0,s[2]=0,s[3]=0,s;let a=n[0],i=a,c=a,l=a,u=a,p=a;n.forEach((e=>{a[0]>e[0]&&(a=e),i[1]>e[1]&&(i=e),c[2]>e[2]&&(c=e),l[0]{let t=0;const n=e.vertices,r=o.create();for(let e=0;e(e.plane||(e.plane=o.fromPoints(o.create(),...e.vertices)),e.plane)},{"../../maths/plane/":174}],100:[function(e,t,n){t.exports=e=>e.vertices},{}],101:[function(e,t,n){const o=e("../../maths/vec3/");t.exports=e=>{let t="poly3: vertices: [";return e.vertices.forEach((e=>{t+=`${o.toString(e)}, `})),t+="]",t}},{"../../maths/vec3/":233}],102:[function(e,t,n){const o=e("../../maths/mat4"),r=e("../../maths/vec3"),s=e("./create");t.exports=(e,t)=>{const n=t.vertices.map((t=>r.transform(r.create(),t,e)));return o.isMirroring(e)&&n.reverse(),s(n)}},{"../../maths/mat4":155,"../../maths/vec3":233,"./create":88}],103:[function(e,t,n){const o=e("../../maths/plane/signedDistanceToPoint"),{NEPS:r}=e("../../maths/constants"),s=e("../../maths/vec3"),a=e("./isA"),i=e("./isConvex"),c=e("./measureArea"),l=e("./plane");t.exports=e=>{if(!a(e))throw new Error("invalid poly3 structure");if(e.vertices.length<3)throw new Error(`poly3 not enough vertices ${e.vertices.length}`);if(c(e)<=0)throw new Error("poly3 area must be greater than zero");for(let t=0;t{if(!e.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${e}`)})),e.vertices.length>3){const t=l(e);e.vertices.forEach((e=>{const n=Math.abs(o(t,e));if(n>r)throw new Error(`poly3 must be coplanar: vertex ${e} distance ${n}`)}))}}},{"../../maths/constants":106,"../../maths/plane/signedDistanceToPoint":176,"../../maths/vec3":233,"./isA":93,"./isConvex":94,"./measureArea":95,"./plane":99}],104:[function(e,t,n){t.exports={colors:e("./colors"),curves:e("./curves"),geometries:e("./geometries"),maths:e("./maths"),measurements:e("./measurements"),primitives:e("./primitives"),text:e("./text"),utils:e("./utils"),booleans:e("./operations/booleans"),expansions:e("./operations/expansions"),extrusions:e("./operations/extrusions"),hulls:e("./operations/hulls"),modifiers:e("./operations/modifiers"),transforms:e("./operations/transforms")}},{"./colors":21,"./curves":32,"./geometries":62,"./maths":107,"./measurements":263,"./operations/booleans":277,"./operations/expansions":306,"./operations/extrusions":329,"./operations/hulls":351,"./operations/modifiers":362,"./operations/transforms":372,"./primitives":388,"./text":402,"./utils":410}],105:[function(e,t,n){const o=e("./mat4"),r=e("./vec2"),s=e("./vec3"),a=function(e,t){arguments.length<2&&(t=s.orthogonal(s.create(),e)),this.v=s.normalize(s.create(),s.cross(s.create(),e,t)),this.u=s.cross(s.create(),this.v,e),this.plane=e,this.planeorigin=s.scale(s.create(),e,e[3])};a.GetCartesian=function(e,t){const n=e+"/"+t;let o,r;if("X/Y"===n)o=[0,0,1],r=[1,0,0];else if("Y/-X"===n)o=[0,0,1],r=[0,1,0];else if("-X/-Y"===n)o=[0,0,1],r=[-1,0,0];else if("-Y/X"===n)o=[0,0,1],r=[0,-1,0];else if("-X/Y"===n)o=[0,0,-1],r=[-1,0,0];else if("-Y/-X"===n)o=[0,0,-1],r=[0,-1,0];else if("X/-Y"===n)o=[0,0,-1],r=[1,0,0];else if("Y/X"===n)o=[0,0,-1],r=[0,1,0];else if("X/Z"===n)o=[0,-1,0],r=[1,0,0];else if("Z/-X"===n)o=[0,-1,0],r=[0,0,1];else if("-X/-Z"===n)o=[0,-1,0],r=[-1,0,0];else if("-Z/X"===n)o=[0,-1,0],r=[0,0,-1];else if("-X/Z"===n)o=[0,1,0],r=[-1,0,0];else if("-Z/-X"===n)o=[0,1,0],r=[0,0,-1];else if("X/-Z"===n)o=[0,1,0],r=[1,0,0];else if("Z/X"===n)o=[0,1,0],r=[0,0,1];else if("Y/Z"===n)o=[1,0,0],r=[0,1,0];else if("Z/-Y"===n)o=[1,0,0],r=[0,0,1];else if("-Y/-Z"===n)o=[1,0,0],r=[0,-1,0];else if("-Z/Y"===n)o=[1,0,0],r=[0,0,-1];else if("-Y/Z"===n)o=[-1,0,0],r=[0,-1,0];else if("-Z/-Y"===n)o=[-1,0,0],r=[0,0,-1];else if("Y/-Z"===n)o=[-1,0,0],r=[0,1,0];else{if("Z/Y"!==n)throw new Error("OrthoNormalBasis.GetCartesian: invalid combination of axis identifiers. Should pass two string arguments from [X,Y,Z,-X,-Y,-Z], being two different axes.");o=[-1,0,0],r=[0,0,1]}return new a(new Plane(new Vector3D(o),0),new Vector3D(r))},a.Z0Plane=function(){const e=new Plane(new Vector3D([0,0,1]),0);return new a(e,new Vector3D([1,0,0]))},a.prototype={getProjectionMatrix:function(){return o.fromValues(this.u[0],this.v[0],this.plane[0],0,this.u[1],this.v[1],this.plane[1],0,this.u[2],this.v[2],this.plane[2],0,0,0,-this.plane[3],1)},getInverseProjectionMatrix:function(){const e=s.scale(s.create(),this.plane,this.plane[3]);return o.fromValues(this.u[0],this.u[1],this.u[2],0,this.v[0],this.v[1],this.v[2],0,this.plane[0],this.plane[1],this.plane[2],0,e[0],e[1],e[2],1)},to2D:function(e){return r.fromValues(s.dot(e,this.u),s.dot(e,this.v))},to3D:function(e){const t=s.scale(s.create(),this.u,e[0]),n=s.scale(s.create(),this.v,e[1]),o=s.add(t,t,this.planeorigin);return s.add(n,n,o)},line3Dto2D:function(e){const t=e.point,n=e.direction.plus(t),o=this.to2D(t),r=this.to2D(n);return Line2D.fromPoints(o,r)},line2Dto3D:function(e){const t=e.origin(),n=e.direction().plus(t),o=this.to3D(t),r=this.to3D(n);return Line3D.fromPoints(o,r)},transform:function(e){const t=this.plane.transform(e),n=this.u.transform(e),o=new Vector3D(0,0,0).transform(e),r=n.minus(o);return new a(t,r)}},t.exports=a},{"./mat4":155,"./vec2":202,"./vec3":233}],106:[function(e,t,n){const o=2*Math.PI;t.exports={EPS:1e-5,NEPS:1e-13,TAU:o,spatialResolution:1e5}},{}],107:[function(e,t,n){t.exports={constants:e("./constants"),line2:e("./line2"),line3:e("./line3"),mat4:e("./mat4"),plane:e("./plane"),utils:e("./utils"),vec2:e("./vec2"),vec3:e("./vec3"),vec4:e("./vec4")}},{"./constants":106,"./line2":117,"./line3":134,"./mat4":155,"./plane":174,"./utils":180,"./vec2":202,"./vec3":233,"./vec4":259}],108:[function(e,t,n){const o=e("./create");t.exports=e=>{const t=o();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}},{"./create":111}],109:[function(e,t,n){const o=e("../vec2"),r=e("./direction"),s=e("./origin");t.exports=(e,t)=>{const n=s(e),a=r(e),i=o.subtract(o.create(),t,n),c=o.dot(i,a);return o.scale(i,a,c),o.add(i,i,n),i}},{"../vec2":202,"./direction":112,"./origin":119}],110:[function(e,t,n){t.exports=(e,t)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],e)},{}],111:[function(e,t,n){t.exports=()=>[0,1,0]},{}],112:[function(e,t,n){const o=e("../vec2");t.exports=e=>{const t=o.normal(o.create(),e);return o.negate(t,t),t}},{"../vec2":202}],113:[function(e,t,n){const o=e("../vec2");t.exports=(e,t)=>{let n=o.dot(t,e);return n=Math.abs(n-e[2]),n}},{"../vec2":202}],114:[function(e,t,n){t.exports=(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]},{}],115:[function(e,t,n){const o=e("../vec2");t.exports=(e,t,n)=>{const r=o.subtract(o.create(),n,t);o.normal(r,r),o.normalize(r,r);const s=o.dot(t,r);return e[0]=r[0],e[1]=r[1],e[2]=s,e}},{"../vec2":202}],116:[function(e,t,n){const o=e("./create");t.exports=(e,t,n)=>{const r=o();return r[0]=e,r[1]=t,r[2]=n,r}},{"./create":111}],117:[function(e,t,n){t.exports={clone:e("./clone"),closestPoint:e("./closestPoint"),copy:e("./copy"),create:e("./create"),direction:e("./direction"),distanceToPoint:e("./distanceToPoint"),equals:e("./equals"),fromPoints:e("./fromPoints"),fromValues:e("./fromValues"),intersectPointOfLines:e("./intersectPointOfLines"),origin:e("./origin"),reverse:e("./reverse"),toString:e("./toString"),transform:e("./transform"),xAtY:e("./xAtY")}},{"./clone":108,"./closestPoint":109,"./copy":110,"./create":111,"./direction":112,"./distanceToPoint":113,"./equals":114,"./fromPoints":115,"./fromValues":116,"./intersectPointOfLines":118,"./origin":119,"./reverse":120,"./toString":121,"./transform":122,"./xAtY":123}],118:[function(e,t,n){const o=e("../vec2"),{solve2Linear:r}=e("../utils");t.exports=(e,t)=>{const n=r(e[0],e[1],t[0],t[1],e[2],t[2]);return o.clone(n)}},{"../utils":180,"../vec2":202}],119:[function(e,t,n){const o=e("../vec2");t.exports=e=>o.scale(o.create(),e,e[2])},{"../vec2":202}],120:[function(e,t,n){const o=e("../vec2"),r=e("./copy"),s=e("./fromValues");t.exports=(e,t)=>{const n=o.negate(o.create(),t),a=-t[2];return r(e,s(n[0],n[1],a))}},{"../vec2":202,"./copy":110,"./fromValues":116}],121:[function(e,t,n){t.exports=e=>`line2: (${e[0].toFixed(7)}, ${e[1].toFixed(7)}, ${e[2].toFixed(7)})`},{}],122:[function(e,t,n){const o=e("../vec2"),r=e("./fromPoints"),s=e("./origin"),a=e("./direction");t.exports=(e,t,n)=>{const i=s(t),c=a(t);return o.transform(i,i,n),o.transform(c,c,n),r(e,i,c)}},{"../vec2":202,"./direction":112,"./fromPoints":115,"./origin":119}],123:[function(e,t,n){const o=e("./origin");t.exports=(e,t)=>{let n=(e[2]-e[1]*t)/e[0];return Number.isNaN(n)&&(n=o(e)[0]),n}},{"./origin":119}],124:[function(e,t,n){const o=e("../vec3"),r=e("./create");t.exports=e=>{const t=r();return o.copy(t[0],e[0]),o.copy(t[1],e[1]),t}},{"../vec3":233,"./create":127}],125:[function(e,t,n){const o=e("../vec3");t.exports=(e,t)=>{const n=e[0],r=e[1],s=o.dot(o.subtract(o.create(),t,n),r)/o.dot(r,r),a=o.scale(o.create(),r,s);return o.add(a,a,n),a}},{"../vec3":233}],126:[function(e,t,n){const o=e("../vec3");t.exports=(e,t)=>(o.copy(e[0],t[0]),o.copy(e[1],t[1]),e)},{"../vec3":233}],127:[function(e,t,n){const o=e("../vec3");t.exports=()=>[o.fromValues(0,0,0),o.fromValues(0,0,1)]},{"../vec3":233}],128:[function(e,t,n){t.exports=e=>e[1]},{}],129:[function(e,t,n){const o=e("../vec3"),r=e("./closestPoint");t.exports=(e,t)=>{const n=r(e,t),s=o.subtract(o.create(),t,n);return o.length(s)}},{"../vec3":233,"./closestPoint":125}],130:[function(e,t,n){const o=e("../vec3");t.exports=(e,t)=>!!o.equals(e[1],t[1])&&!!o.equals(e[0],t[0])},{"../vec3":233}],131:[function(e,t,n){const o=e("../vec3"),{solve2Linear:r}=e("../utils"),{EPS:s}=e("../constants"),a=e("./fromPointAndDirection");t.exports=(e,t,n)=>{let i=o.cross(o.create(),t,n),c=o.length(i);if(c=u&&l>=p?(h=r(t[1],t[2],n[1],n[2],t[3],n[3]),f=o.fromValues(0,h[0],h[1])):u>=l&&u>=p?(h=r(t[0],t[2],n[0],n[2],t[3],n[3]),f=o.fromValues(h[0],0,h[1])):(h=r(t[0],t[1],n[0],n[1],t[3],n[3]),f=o.fromValues(h[0],h[1],0)),a(e,f,i)}},{"../constants":106,"../utils":180,"../vec3":233,"./fromPointAndDirection":132}],132:[function(e,t,n){const o=e("../vec3");t.exports=(e,t,n)=>{const r=o.normalize(o.create(),n);return o.copy(e[0],t),o.copy(e[1],r),e}},{"../vec3":233}],133:[function(e,t,n){const o=e("../vec3"),r=e("./fromPointAndDirection");t.exports=(e,t,n)=>{const s=o.subtract(o.create(),n,t);return r(e,t,s)}},{"../vec3":233,"./fromPointAndDirection":132}],134:[function(e,t,n){t.exports={clone:e("./clone"),closestPoint:e("./closestPoint"),copy:e("./copy"),create:e("./create"),direction:e("./direction"),distanceToPoint:e("./distanceToPoint"),equals:e("./equals"),fromPlanes:e("./fromPlanes"),fromPointAndDirection:e("./fromPointAndDirection"),fromPoints:e("./fromPoints"),intersectPointOfLineAndPlane:e("./intersectPointOfLineAndPlane"),origin:e("./origin"),reverse:e("./reverse"),toString:e("./toString"),transform:e("./transform")}},{"./clone":124,"./closestPoint":125,"./copy":126,"./create":127,"./direction":128,"./distanceToPoint":129,"./equals":130,"./fromPlanes":131,"./fromPointAndDirection":132,"./fromPoints":133,"./intersectPointOfLineAndPlane":135,"./origin":136,"./reverse":137,"./toString":138,"./transform":139}],135:[function(e,t,n){const o=e("../vec3");t.exports=(e,t)=>{const n=t,r=t[3],s=e[0],a=e[1],i=(r-o.dot(n,s))/o.dot(n,a);return o.add(o.create(),s,o.scale(o.create(),a,i))}},{"../vec3":233}],136:[function(e,t,n){t.exports=e=>e[0]},{}],137:[function(e,t,n){const o=e("../vec3"),r=e("./fromPointAndDirection");t.exports=(e,t)=>{const n=o.clone(t[0]),s=o.negate(o.create(),t[1]);return r(e,n,s)}},{"../vec3":233,"./fromPointAndDirection":132}],138:[function(e,t,n){t.exports=e=>{const t=e[0],n=e[1];return`line3: point: (${t[0].toFixed(7)}, ${t[1].toFixed(7)}, ${t[2].toFixed(7)}) direction: (${n[0].toFixed(7)}, ${n[1].toFixed(7)}, ${n[2].toFixed(7)})`}},{}],139:[function(e,t,n){const o=e("../vec3"),r=e("./fromPointAndDirection");t.exports=(e,t,n)=>{const s=t[0],a=t[1],i=o.add(o.create(),s,a),c=o.transform(o.create(),s,n),l=o.transform(i,i,n),u=o.subtract(l,l,c);return r(e,c,u)}},{"../vec3":233,"./fromPointAndDirection":132}],140:[function(e,t,n){t.exports=(e,t,n)=>(e[0]=t[0]+n[0],e[1]=t[1]+n[1],e[2]=t[2]+n[2],e[3]=t[3]+n[3],e[4]=t[4]+n[4],e[5]=t[5]+n[5],e[6]=t[6]+n[6],e[7]=t[7]+n[7],e[8]=t[8]+n[8],e[9]=t[9]+n[9],e[10]=t[10]+n[10],e[11]=t[11]+n[11],e[12]=t[12]+n[12],e[13]=t[13]+n[13],e[14]=t[14]+n[14],e[15]=t[15]+n[15],e)},{}],141:[function(e,t,n){const o=e("./create");t.exports=e=>{const t=o();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}},{"./create":143}],142:[function(e,t,n){t.exports=(e,t)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e)},{}],143:[function(e,t,n){t.exports=()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]},{}],144:[function(e,t,n){t.exports=(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15]},{}],145:[function(e,t,n){const{EPS:o}=e("../constants"),{sin:r,cos:s}=e("../utils/trigonometry"),a=e("./identity");t.exports=(e,t,n)=>{let[i,c,l]=n;const u=i*i+c*c+l*l;if(Math.abs(u)(e[0]=t[0],e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=t[1],e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=t[2],e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e)},{}],147:[function(e,t,n){const{sin:o,cos:r}=e("../utils/trigonometry");t.exports=(e,t,n,s)=>{const a=o(t),i=r(t),c=o(n),l=r(n),u=o(s),p=r(s);return e[0]=l*i,e[1]=l*a,e[2]=-c,e[3]=0,e[4]=u*c*i-p*a,e[5]=p*i+u*c*a,e[6]=u*l,e[7]=0,e[8]=u*a+p*c*i,e[9]=p*c*a-u*i,e[10]=p*l,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}},{"../utils/trigonometry":184}],148:[function(e,t,n){t.exports=(e,t)=>(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]=t[0],e[13]=t[1],e[14]=t[2],e[15]=1,e)},{}],149:[function(e,t,n){const o=e("./create");t.exports=(e,t,n,r,s,a,i,c,l,u,p,f,h,m,g,d)=>{const y=o();return y[0]=e,y[1]=t,y[2]=n,y[3]=r,y[4]=s,y[5]=a,y[6]=i,y[7]=c,y[8]=l,y[9]=u,y[10]=p,y[11]=f,y[12]=h,y[13]=m,y[14]=g,y[15]=d,y}},{"./create":143}],150:[function(e,t,n){const o=e("../vec3"),r=e("./fromRotation");t.exports=(e,t,n)=>{const s=o.normalize(o.create(),t),a=o.normalize(o.create(),n),i=o.cross(o.create(),a,s),c=o.dot(a,s);if(-1===c)return r(e,Math.PI,o.orthogonal(i,s));const l=1/(1+c);return e[0]=i[0]*i[0]*l+c,e[1]=i[1]*i[0]*l-i[2],e[2]=i[2]*i[0]*l+i[1],e[3]=0,e[4]=i[0]*i[1]*l+i[2],e[5]=i[1]*i[1]*l+c,e[6]=i[2]*i[1]*l-i[0],e[7]=0,e[8]=i[0]*i[2]*l-i[1],e[9]=i[1]*i[2]*l+i[0],e[10]=i[2]*i[2]*l+c,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}},{"../vec3":233,"./fromRotation":145}],151:[function(e,t,n){const{sin:o,cos:r}=e("../utils/trigonometry");t.exports=(e,t)=>{const n=o(t),s=r(t);return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=s,e[6]=n,e[7]=0,e[8]=0,e[9]=-n,e[10]=s,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}},{"../utils/trigonometry":184}],152:[function(e,t,n){const{sin:o,cos:r}=e("../utils/trigonometry");t.exports=(e,t)=>{const n=o(t),s=r(t);return e[0]=s,e[1]=0,e[2]=-n,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=n,e[9]=0,e[10]=s,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}},{"../utils/trigonometry":184}],153:[function(e,t,n){const{sin:o,cos:r}=e("../utils/trigonometry");t.exports=(e,t)=>{const n=o(t),s=r(t);return e[0]=s,e[1]=n,e[2]=0,e[3]=0,e[4]=-n,e[5]=s,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,e}},{"../utils/trigonometry":184}],154:[function(e,t,n){t.exports=e=>(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,e)},{}],155:[function(e,t,n){t.exports={add:e("./add"),clone:e("./clone"),copy:e("./copy"),create:e("./create"),invert:e("./invert"),equals:e("./equals"),fromRotation:e("./fromRotation"),fromScaling:e("./fromScaling"),fromTaitBryanRotation:e("./fromTaitBryanRotation"),fromTranslation:e("./fromTranslation"),fromValues:e("./fromValues"),fromVectorRotation:e("./fromVectorRotation"),fromXRotation:e("./fromXRotation"),fromYRotation:e("./fromYRotation"),fromZRotation:e("./fromZRotation"),identity:e("./identity"),isIdentity:e("./isIdentity"),isOnlyTransformScale:e("./isOnlyTransformScale"),isMirroring:e("./isMirroring"),mirrorByPlane:e("./mirrorByPlane"),multiply:e("./multiply"),rotate:e("./rotate"),rotateX:e("./rotateX"),rotateY:e("./rotateY"),rotateZ:e("./rotateZ"),scale:e("./scale"),subtract:e("./subtract"),toString:e("./toString"),translate:e("./translate")}},{"./add":140,"./clone":141,"./copy":142,"./create":143,"./equals":144,"./fromRotation":145,"./fromScaling":146,"./fromTaitBryanRotation":147,"./fromTranslation":148,"./fromValues":149,"./fromVectorRotation":150,"./fromXRotation":151,"./fromYRotation":152,"./fromZRotation":153,"./identity":154,"./invert":156,"./isIdentity":157,"./isMirroring":158,"./isOnlyTransformScale":159,"./mirrorByPlane":160,"./multiply":161,"./rotate":162,"./rotateX":163,"./rotateY":164,"./rotateZ":165,"./scale":166,"./subtract":167,"./toString":168,"./translate":169}],156:[function(e,t,n){t.exports=(e,t)=>{const n=t[0],o=t[1],r=t[2],s=t[3],a=t[4],i=t[5],c=t[6],l=t[7],u=t[8],p=t[9],f=t[10],h=t[11],m=t[12],g=t[13],d=t[14],y=t[15],v=n*i-o*a,b=n*c-r*a,x=n*l-s*a,A=o*c-r*i,E=o*l-s*i,w=r*l-s*c,S=u*g-p*m,T=u*d-f*m,P=u*y-h*m,D=p*d-f*g,C=p*y-h*g,M=f*y-h*d;let R=v*M-b*C+x*D+A*P-E*T+w*S;return R?(R=1/R,e[0]=(i*M-c*C+l*D)*R,e[1]=(r*C-o*M-s*D)*R,e[2]=(g*w-d*E+y*A)*R,e[3]=(f*E-p*w-h*A)*R,e[4]=(c*P-a*M-l*T)*R,e[5]=(n*M-r*P+s*T)*R,e[6]=(d*x-m*w-y*b)*R,e[7]=(u*w-f*x+h*b)*R,e[8]=(a*C-i*P+l*S)*R,e[9]=(o*P-n*C-s*S)*R,e[10]=(m*E-g*x+y*v)*R,e[11]=(p*x-u*E-h*v)*R,e[12]=(i*T-a*D-c*S)*R,e[13]=(n*D-o*T+r*S)*R,e[14]=(g*b-m*A-d*v)*R,e[15]=(u*A-p*b+f*v)*R,e):null}},{}],157:[function(e,t,n){t.exports=e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]},{}],158:[function(e,t,n){t.exports=e=>{const t=e[4]*e[9]-e[8]*e[5],n=e[8]*e[1]-e[0]*e[9],o=e[0]*e[5]-e[4]*e[1];return t*e[2]+n*e[6]+o*e[10]<0}},{}],159:[function(e,t,n){const o=e=>Math.abs(e)o(e[1])&&o(e[2])&&o(e[3])&&o(e[4])&&o(e[6])&&o(e[7])&&o(e[8])&&o(e[9])&&o(e[11])&&1===e[15]},{}],160:[function(e,t,n){t.exports=(e,t)=>{const[n,o,r,s]=t;return e[0]=1-2*n*n,e[1]=-2*o*n,e[2]=-2*r*n,e[3]=0,e[4]=-2*n*o,e[5]=1-2*o*o,e[6]=-2*r*o,e[7]=0,e[8]=-2*n*r,e[9]=-2*o*r,e[10]=1-2*r*r,e[11]=0,e[12]=2*n*s,e[13]=2*o*s,e[14]=2*r*s,e[15]=1,e}},{}],161:[function(e,t,n){t.exports=(e,t,n)=>{const o=t[0],r=t[1],s=t[2],a=t[3],i=t[4],c=t[5],l=t[6],u=t[7],p=t[8],f=t[9],h=t[10],m=t[11],g=t[12],d=t[13],y=t[14],v=t[15];let b=n[0],x=n[1],A=n[2],E=n[3];return e[0]=b*o+x*i+A*p+E*g,e[1]=b*r+x*c+A*f+E*d,e[2]=b*s+x*l+A*h+E*y,e[3]=b*a+x*u+A*m+E*v,b=n[4],x=n[5],A=n[6],E=n[7],e[4]=b*o+x*i+A*p+E*g,e[5]=b*r+x*c+A*f+E*d,e[6]=b*s+x*l+A*h+E*y,e[7]=b*a+x*u+A*m+E*v,b=n[8],x=n[9],A=n[10],E=n[11],e[8]=b*o+x*i+A*p+E*g,e[9]=b*r+x*c+A*f+E*d,e[10]=b*s+x*l+A*h+E*y,e[11]=b*a+x*u+A*m+E*v,b=n[12],x=n[13],A=n[14],E=n[15],e[12]=b*o+x*i+A*p+E*g,e[13]=b*r+x*c+A*f+E*d,e[14]=b*s+x*l+A*h+E*y,e[15]=b*a+x*u+A*m+E*v,e}},{}],162:[function(e,t,n){const{EPS:o}=e("../constants"),{sin:r,cos:s}=e("../utils/trigonometry"),a=e("./copy");t.exports=(e,t,n,i)=>{let[c,l,u]=i;const p=c*c+l*l+u*u;if(Math.abs(p){const s=o(n),a=r(n),i=t[4],c=t[5],l=t[6],u=t[7],p=t[8],f=t[9],h=t[10],m=t[11];return t!==e&&(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[4]=i*a+p*s,e[5]=c*a+f*s,e[6]=l*a+h*s,e[7]=u*a+m*s,e[8]=p*a-i*s,e[9]=f*a-c*s,e[10]=h*a-l*s,e[11]=m*a-u*s,e}},{"../utils/trigonometry":184}],164:[function(e,t,n){const{sin:o,cos:r}=e("../utils/trigonometry");t.exports=(e,t,n)=>{const s=o(n),a=r(n),i=t[0],c=t[1],l=t[2],u=t[3],p=t[8],f=t[9],h=t[10],m=t[11];return t!==e&&(e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[0]=i*a-p*s,e[1]=c*a-f*s,e[2]=l*a-h*s,e[3]=u*a-m*s,e[8]=i*s+p*a,e[9]=c*s+f*a,e[10]=l*s+h*a,e[11]=u*s+m*a,e}},{"../utils/trigonometry":184}],165:[function(e,t,n){const{sin:o,cos:r}=e("../utils/trigonometry");t.exports=(e,t,n)=>{const s=o(n),a=r(n),i=t[0],c=t[1],l=t[2],u=t[3],p=t[4],f=t[5],h=t[6],m=t[7];return t!==e&&(e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[0]=i*a+p*s,e[1]=c*a+f*s,e[2]=l*a+h*s,e[3]=u*a+m*s,e[4]=p*a-i*s,e[5]=f*a-c*s,e[6]=h*a-l*s,e[7]=m*a-u*s,e}},{"../utils/trigonometry":184}],166:[function(e,t,n){t.exports=(e,t,n)=>{const o=n[0],r=n[1],s=n[2];return e[0]=t[0]*o,e[1]=t[1]*o,e[2]=t[2]*o,e[3]=t[3]*o,e[4]=t[4]*r,e[5]=t[5]*r,e[6]=t[6]*r,e[7]=t[7]*r,e[8]=t[8]*s,e[9]=t[9]*s,e[10]=t[10]*s,e[11]=t[11]*s,e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}},{}],167:[function(e,t,n){t.exports=(e,t,n)=>(e[0]=t[0]-n[0],e[1]=t[1]-n[1],e[2]=t[2]-n[2],e[3]=t[3]-n[3],e[4]=t[4]-n[4],e[5]=t[5]-n[5],e[6]=t[6]-n[6],e[7]=t[7]-n[7],e[8]=t[8]-n[8],e[9]=t[9]-n[9],e[10]=t[10]-n[10],e[11]=t[11]-n[11],e[12]=t[12]-n[12],e[13]=t[13]-n[13],e[14]=t[14]-n[14],e[15]=t[15]-n[15],e)},{}],168:[function(e,t,n){t.exports=e=>e.map((e=>e.toFixed(7))).toString()},{}],169:[function(e,t,n){t.exports=(e,t,n)=>{const o=n[0],r=n[1],s=n[2];let a,i,c,l,u,p,f,h,m,g,d,y;return t===e?(e[12]=t[0]*o+t[4]*r+t[8]*s+t[12],e[13]=t[1]*o+t[5]*r+t[9]*s+t[13],e[14]=t[2]*o+t[6]*r+t[10]*s+t[14],e[15]=t[3]*o+t[7]*r+t[11]*s+t[15]):(a=t[0],i=t[1],c=t[2],l=t[3],u=t[4],p=t[5],f=t[6],h=t[7],m=t[8],g=t[9],d=t[10],y=t[11],e[0]=a,e[1]=i,e[2]=c,e[3]=l,e[4]=u,e[5]=p,e[6]=f,e[7]=h,e[8]=m,e[9]=g,e[10]=d,e[11]=y,e[12]=a*o+u*r+m*s+t[12],e[13]=i*o+p*r+g*s+t[13],e[14]=c*o+f*r+d*s+t[14],e[15]=l*o+h*r+y*s+t[15]),e}},{}],170:[function(e,t,n){t.exports=(e,t)=>(e[0]=-t[0],e[1]=-t[1],e[2]=-t[2],e[3]=-t[3],e)},{}],171:[function(e,t,n){const o=e("../vec3");t.exports=(e,t,n)=>{const r=o.normalize(o.create(),t),s=o.dot(n,r);return e[0]=r[0],e[1]=r[1],e[2]=r[2],e[3]=s,e}},{"../vec3":233}],172:[function(e,t,n){const o=e("../vec3");t.exports=(e,...t)=>{const n=t.length,r=o.create(),s=o.create(),a=e=>{const a=t[e],i=t[(e+1)%n],c=t[(e+2)%n];return o.subtract(r,i,a),o.subtract(s,c,a),o.cross(r,r,s),o.normalize(r,r),r};return e[0]=0,e[1]=0,e[2]=0,3===n?o.copy(e,a(0)):(t.forEach(((t,n)=>{o.add(e,e,a(n))})),o.normalize(e,e)),e[3]=o.dot(e,t[0]),e}},{"../vec3":233}],173:[function(e,t,n){const{EPS:o}=e("../constants"),r=e("../vec3");t.exports=(e,t,n,s)=>{let a=r.subtract(r.create(),n,t),i=r.subtract(r.create(),s,t);r.length(a){const n=t[0]*e[0]+t[1]*e[1]+t[2]*e[2]-e[3],r=t[0]-n*e[0],s=t[1]-n*e[1],a=t[2]-n*e[2];return o.fromValues(r,s,a)}},{"../vec3":233}],176:[function(e,t,n){const o=e("../vec3");t.exports=(e,t)=>o.dot(e,t)-e[3]},{"../vec3":233}],177:[function(e,t,n){const o=e("../mat4"),r=e("../vec3"),s=e("./fromPoints"),a=e("./flip");t.exports=(e,t,n)=>{const i=o.isMirroring(n),c=r.orthogonal(r.create(),t),l=r.cross(c,t,c),u=r.cross(r.create(),t,l);let p=r.fromScalar(r.create(),t[3]);r.multiply(p,p,t);let f=r.add(r.create(),p,l),h=r.add(r.create(),p,u);return p=r.transform(p,p,n),f=r.transform(f,f,n),h=r.transform(h,h,n),s(e,p,f,h),i&&a(e,e),e}},{"../mat4":155,"../vec3":233,"./flip":170,"./fromPoints":172}],178:[function(e,t,n){const{NEPS:o}=e("../constants");t.exports=(e,t)=>Math.abs(e[0]-t[0])<=o&&Math.abs(e[1]-t[1])<=o&&Math.abs(e[2]-t[2])<=o},{"../constants":106}],179:[function(e,t,n){t.exports=e=>{let t=0;for(let n=0;n{let o,r=n-e[1],s=t[1]-e[1];return s<0&&(r=-r,s=-s),o=r<=0?0:r>=s?1:s<1e-10?.5:r/s,e[0]+o*(t[0]-e[0])}},{}],182:[function(e,t,n){t.exports=(e,t,n,o)=>{if(e[0]===t[0]&&e[1]===t[1]||n[0]===o[0]&&n[1]===o[1])return;const r=(o[1]-n[1])*(t[0]-e[0])-(o[0]-n[0])*(t[1]-e[1]);if(Math.abs(r)1||a<0||a>1?void 0:[e[0]+s*(t[0]-e[0]),e[1]+s*(t[1]-e[1])]}},{}],183:[function(e,t,n){t.exports=(e,t,n,o,r,s)=>{const a=1/(e*o-t*n);let i=r*o-t*s,c=-r*n+e*s;return i*=a,c*=a,[i,c]}},{}],184:[function(e,t,n){const{NEPS:o}=e("../constants"),r=e=>Math.abs(e)r(Math.sin(e)),cos:e=>r(Math.cos(e))}},{"../constants":106}],185:[function(e,t,n){t.exports=(e,t)=>(e[0]=Math.abs(t[0]),e[1]=Math.abs(t[1]),e)},{}],186:[function(e,t,n){t.exports=(e,t,n)=>(e[0]=t[0]+n[0],e[1]=t[1]+n[1],e)},{}],187:[function(e,t,n){t.exports=e("./angleRadians")},{"./angleRadians":189}],188:[function(e,t,n){const o=e("./angleRadians");t.exports=e=>57.29577951308232*o(e)},{"./angleRadians":189}],189:[function(e,t,n){t.exports=e=>Math.atan2(e[1],e[0])},{}],190:[function(e,t,n){const o=e("./create");t.exports=e=>{const t=o();return t[0]=e[0],t[1]=e[1],t}},{"./create":192}],191:[function(e,t,n){t.exports=(e,t)=>(e[0]=t[0],e[1]=t[1],e)},{}],192:[function(e,t,n){t.exports=()=>[0,0]},{}],193:[function(e,t,n){t.exports=(e,t,n)=>(e[0]=0,e[1]=0,e[2]=t[0]*n[1]-t[1]*n[0],e)},{}],194:[function(e,t,n){t.exports=(e,t)=>{const n=t[0]-e[0],o=t[1]-e[1];return Math.sqrt(n*n+o*o)}},{}],195:[function(e,t,n){t.exports=(e,t,n)=>(e[0]=t[0]/n[0],e[1]=t[1]/n[1],e)},{}],196:[function(e,t,n){t.exports=(e,t)=>e[0]*t[0]+e[1]*t[1]},{}],197:[function(e,t,n){t.exports=(e,t)=>e[0]===t[0]&&e[1]===t[1]},{}],198:[function(e,t,n){const o=e("./fromAngleRadians");t.exports=(e,t)=>o(e,.017453292519943295*t)},{"./fromAngleRadians":199}],199:[function(e,t,n){const{sin:o,cos:r}=e("../utils/trigonometry");t.exports=(e,t)=>(e[0]=r(t),e[1]=o(t),e)},{"../utils/trigonometry":184}],200:[function(e,t,n){t.exports=(e,t)=>(e[0]=t,e[1]=t,e)},{}],201:[function(e,t,n){const o=e("./create");t.exports=(e,t)=>{const n=o();return n[0]=e,n[1]=t,n}},{"./create":192}],202:[function(e,t,n){t.exports={abs:e("./abs"),add:e("./add"),angle:e("./angle"),angleDegrees:e("./angleDegrees"),angleRadians:e("./angleRadians"),clone:e("./clone"),copy:e("./copy"),create:e("./create"),cross:e("./cross"),distance:e("./distance"),divide:e("./divide"),dot:e("./dot"),equals:e("./equals"),fromAngleDegrees:e("./fromAngleDegrees"),fromAngleRadians:e("./fromAngleRadians"),fromScalar:e("./fromScalar"),fromValues:e("./fromValues"),length:e("./length"),lerp:e("./lerp"),max:e("./max"),min:e("./min"),multiply:e("./multiply"),negate:e("./negate"),normal:e("./normal"),normalize:e("./normalize"),rotate:e("./rotate"),scale:e("./scale"),snap:e("./snap"),squaredDistance:e("./squaredDistance"),squaredLength:e("./squaredLength"),subtract:e("./subtract"),toString:e("./toString"),transform:e("./transform")}},{"./abs":185,"./add":186,"./angle":187,"./angleDegrees":188,"./angleRadians":189,"./clone":190,"./copy":191,"./create":192,"./cross":193,"./distance":194,"./divide":195,"./dot":196,"./equals":197,"./fromAngleDegrees":198,"./fromAngleRadians":199,"./fromScalar":200,"./fromValues":201,"./length":203,"./lerp":204,"./max":205,"./min":206,"./multiply":207,"./negate":208,"./normal":209,"./normalize":210,"./rotate":211,"./scale":212,"./snap":213,"./squaredDistance":214,"./squaredLength":215,"./subtract":216,"./toString":217,"./transform":218}],203:[function(e,t,n){t.exports=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1])},{}],204:[function(e,t,n){t.exports=(e,t,n,o)=>{const r=t[0],s=t[1];return e[0]=r+o*(n[0]-r),e[1]=s+o*(n[1]-s),e}},{}],205:[function(e,t,n){t.exports=(e,t,n)=>(e[0]=Math.max(t[0],n[0]),e[1]=Math.max(t[1],n[1]),e)},{}],206:[function(e,t,n){t.exports=(e,t,n)=>(e[0]=Math.min(t[0],n[0]),e[1]=Math.min(t[1],n[1]),e)},{}],207:[function(e,t,n){t.exports=(e,t,n)=>(e[0]=t[0]*n[0],e[1]=t[1]*n[1],e)},{}],208:[function(e,t,n){t.exports=(e,t)=>(e[0]=-t[0],e[1]=-t[1],e)},{}],209:[function(e,t,n){const{TAU:o}=e("../constants"),r=e("./create"),s=e("./rotate");t.exports=(e,t)=>s(e,t,r(),o/4)},{"../constants":106,"./create":192,"./rotate":211}],210:[function(e,t,n){t.exports=(e,t)=>{const n=t[0],o=t[1];let r=n*n+o*o;return r>0&&(r=1/Math.sqrt(r)),e[0]=n*r,e[1]=o*r,e}},{}],211:[function(e,t,n){t.exports=(e,t,n,o)=>{const r=t[0]-n[0],s=t[1]-n[1],a=Math.cos(o),i=Math.sin(o);return e[0]=r*a-s*i+n[0],e[1]=r*i+s*a+n[1],e}},{}],212:[function(e,t,n){t.exports=(e,t,n)=>(e[0]=t[0]*n,e[1]=t[1]*n,e)},{}],213:[function(e,t,n){t.exports=(e,t,n)=>(e[0]=Math.round(t[0]/n)*n+0,e[1]=Math.round(t[1]/n)*n+0,e)},{}],214:[function(e,t,n){t.exports=(e,t)=>{const n=t[0]-e[0],o=t[1]-e[1];return n*n+o*o}},{}],215:[function(e,t,n){t.exports=e=>{const t=e[0],n=e[1];return t*t+n*n}},{}],216:[function(e,t,n){t.exports=(e,t,n)=>(e[0]=t[0]-n[0],e[1]=t[1]-n[1],e)},{}],217:[function(e,t,n){t.exports=e=>`[${e[0].toFixed(7)}, ${e[1].toFixed(7)}]`},{}],218:[function(e,t,n){t.exports=(e,t,n)=>{const o=t[0],r=t[1];return e[0]=n[0]*o+n[4]*r+n[12],e[1]=n[1]*o+n[5]*r+n[13],e}},{}],219:[function(e,t,n){t.exports=(e,t)=>(e[0]=Math.abs(t[0]),e[1]=Math.abs(t[1]),e[2]=Math.abs(t[2]),e)},{}],220:[function(e,t,n){t.exports=(e,t,n)=>(e[0]=t[0]+n[0],e[1]=t[1]+n[1],e[2]=t[2]+n[2],e)},{}],221:[function(e,t,n){const o=e("./dot");t.exports=(e,t)=>{const n=e[0],r=e[1],s=e[2],a=t[0],i=t[1],c=t[2],l=Math.sqrt(n*n+r*r+s*s)*Math.sqrt(a*a+i*i+c*c),u=l&&o(e,t)/l;return Math.acos(Math.min(Math.max(u,-1),1))}},{"./dot":228}],222:[function(e,t,n){const o=e("./create");t.exports=e=>{const t=o();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}},{"./create":224}],223:[function(e,t,n){t.exports=(e,t)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],e)},{}],224:[function(e,t,n){t.exports=()=>[0,0,0]},{}],225:[function(e,t,n){t.exports=(e,t,n)=>{const o=t[0],r=t[1],s=t[2],a=n[0],i=n[1],c=n[2];return e[0]=r*c-s*i,e[1]=s*a-o*c,e[2]=o*i-r*a,e}},{}],226:[function(e,t,n){t.exports=(e,t)=>{const n=t[0]-e[0],o=t[1]-e[1],r=t[2]-e[2];return Math.sqrt(n*n+o*o+r*r)}},{}],227:[function(e,t,n){t.exports=(e,t,n)=>(e[0]=t[0]/n[0],e[1]=t[1]/n[1],e[2]=t[2]/n[2],e)},{}],228:[function(e,t,n){t.exports=(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]},{}],229:[function(e,t,n){t.exports=(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]},{}],230:[function(e,t,n){t.exports=(e,t)=>(e[0]=t,e[1]=t,e[2]=t,e)},{}],231:[function(e,t,n){const o=e("./create");t.exports=(e,t,n)=>{const r=o();return r[0]=e,r[1]=t,r[2]=n,r}},{"./create":224}],232:[function(e,t,n){t.exports=(e,t,n=0)=>(e[0]=t[0],e[1]=t[1],e[2]=n,e)},{}],233:[function(e,t,n){t.exports={abs:e("./abs"),add:e("./add"),angle:e("./angle"),clone:e("./clone"),copy:e("./copy"),create:e("./create"),cross:e("./cross"),distance:e("./distance"),divide:e("./divide"),dot:e("./dot"),equals:e("./equals"),fromScalar:e("./fromScalar"),fromValues:e("./fromValues"),fromVec2:e("./fromVec2"),length:e("./length"),lerp:e("./lerp"),max:e("./max"),min:e("./min"),multiply:e("./multiply"),negate:e("./negate"),normalize:e("./normalize"),orthogonal:e("./orthogonal"),rotateX:e("./rotateX"),rotateY:e("./rotateY"),rotateZ:e("./rotateZ"),scale:e("./scale"),snap:e("./snap"),squaredDistance:e("./squaredDistance"),squaredLength:e("./squaredLength"),subtract:e("./subtract"),toString:e("./toString"),transform:e("./transform")}},{"./abs":219,"./add":220,"./angle":221,"./clone":222,"./copy":223,"./create":224,"./cross":225,"./distance":226,"./divide":227,"./dot":228,"./equals":229,"./fromScalar":230,"./fromValues":231,"./fromVec2":232,"./length":234,"./lerp":235,"./max":236,"./min":237,"./multiply":238,"./negate":239,"./normalize":240,"./orthogonal":241,"./rotateX":242,"./rotateY":243,"./rotateZ":244,"./scale":245,"./snap":246,"./squaredDistance":247,"./squaredLength":248,"./subtract":249,"./toString":250,"./transform":251}],234:[function(e,t,n){t.exports=e=>{const t=e[0],n=e[1],o=e[2];return Math.sqrt(t*t+n*n+o*o)}},{}],235:[function(e,t,n){t.exports=(e,t,n,o)=>(e[0]=t[0]+o*(n[0]-t[0]),e[1]=t[1]+o*(n[1]-t[1]),e[2]=t[2]+o*(n[2]-t[2]),e)},{}],236:[function(e,t,n){t.exports=(e,t,n)=>(e[0]=Math.max(t[0],n[0]),e[1]=Math.max(t[1],n[1]),e[2]=Math.max(t[2],n[2]),e)},{}],237:[function(e,t,n){t.exports=(e,t,n)=>(e[0]=Math.min(t[0],n[0]),e[1]=Math.min(t[1],n[1]),e[2]=Math.min(t[2],n[2]),e)},{}],238:[function(e,t,n){t.exports=(e,t,n)=>(e[0]=t[0]*n[0],e[1]=t[1]*n[1],e[2]=t[2]*n[2],e)},{}],239:[function(e,t,n){t.exports=(e,t)=>(e[0]=-t[0],e[1]=-t[1],e[2]=-t[2],e)},{}],240:[function(e,t,n){t.exports=(e,t)=>{const n=t[0],o=t[1],r=t[2];let s=n*n+o*o+r*r;return s>0&&(s=1/Math.sqrt(s)),e[0]=n*s,e[1]=o*s,e[2]=r*s,e}},{}],241:[function(e,t,n){const o=e("./abs"),r=e("./create"),s=e("./cross");t.exports=(e,t)=>{const n=o(r(),t),a=0+(n[0]{const r=[],s=[];return r[0]=t[0]-n[0],r[1]=t[1]-n[1],r[2]=t[2]-n[2],s[0]=r[0],s[1]=r[1]*Math.cos(o)-r[2]*Math.sin(o),s[2]=r[1]*Math.sin(o)+r[2]*Math.cos(o),e[0]=s[0]+n[0],e[1]=s[1]+n[1],e[2]=s[2]+n[2],e}},{}],243:[function(e,t,n){t.exports=(e,t,n,o)=>{const r=[],s=[];return r[0]=t[0]-n[0],r[1]=t[1]-n[1],r[2]=t[2]-n[2],s[0]=r[2]*Math.sin(o)+r[0]*Math.cos(o),s[1]=r[1],s[2]=r[2]*Math.cos(o)-r[0]*Math.sin(o),e[0]=s[0]+n[0],e[1]=s[1]+n[1],e[2]=s[2]+n[2],e}},{}],244:[function(e,t,n){t.exports=(e,t,n,o)=>{const r=[],s=[];return r[0]=t[0]-n[0],r[1]=t[1]-n[1],s[0]=r[0]*Math.cos(o)-r[1]*Math.sin(o),s[1]=r[0]*Math.sin(o)+r[1]*Math.cos(o),e[0]=s[0]+n[0],e[1]=s[1]+n[1],e[2]=t[2],e}},{}],245:[function(e,t,n){t.exports=(e,t,n)=>(e[0]=t[0]*n,e[1]=t[1]*n,e[2]=t[2]*n,e)},{}],246:[function(e,t,n){t.exports=(e,t,n)=>(e[0]=Math.round(t[0]/n)*n+0,e[1]=Math.round(t[1]/n)*n+0,e[2]=Math.round(t[2]/n)*n+0,e)},{}],247:[function(e,t,n){t.exports=(e,t)=>{const n=t[0]-e[0],o=t[1]-e[1],r=t[2]-e[2];return n*n+o*o+r*r}},{}],248:[function(e,t,n){t.exports=e=>{const t=e[0],n=e[1],o=e[2];return t*t+n*n+o*o}},{}],249:[function(e,t,n){t.exports=(e,t,n)=>(e[0]=t[0]-n[0],e[1]=t[1]-n[1],e[2]=t[2]-n[2],e)},{}],250:[function(e,t,n){t.exports=e=>`[${e[0].toFixed(7)}, ${e[1].toFixed(7)}, ${e[2].toFixed(7)}]`},{}],251:[function(e,t,n){t.exports=(e,t,n)=>{const o=t[0],r=t[1],s=t[2];let a=n[3]*o+n[7]*r+n[11]*s+n[15];return a=a||1,e[0]=(n[0]*o+n[4]*r+n[8]*s+n[12])/a,e[1]=(n[1]*o+n[5]*r+n[9]*s+n[13])/a,e[2]=(n[2]*o+n[6]*r+n[10]*s+n[14])/a,e}},{}],252:[function(e,t,n){const o=e("./create");t.exports=e=>{const t=o();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t}},{"./create":254}],253:[function(e,t,n){t.exports=(e,t)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e)},{}],254:[function(e,t,n){t.exports=()=>[0,0,0,0]},{}],255:[function(e,t,n){t.exports=(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]},{}],256:[function(e,t,n){t.exports=(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]},{}],257:[function(e,t,n){t.exports=(e,t)=>(e[0]=t,e[1]=t,e[2]=t,e[3]=t,e)},{}],258:[function(e,t,n){const o=e("./create");t.exports=(e,t,n,r)=>{const s=o();return s[0]=e,s[1]=t,s[2]=n,s[3]=r,s}},{"./create":254}],259:[function(e,t,n){t.exports={clone:e("./clone"),copy:e("./copy"),create:e("./create"),dot:e("./dot"),equals:e("./equals"),fromScalar:e("./fromScalar"),fromValues:e("./fromValues"),toString:e("./toString"),transform:e("./transform")}},{"./clone":252,"./copy":253,"./create":254,"./dot":255,"./equals":256,"./fromScalar":257,"./fromValues":258,"./toString":260,"./transform":261}],260:[function(e,t,n){t.exports=e=>`(${e[0].toFixed(9)}, ${e[1].toFixed(9)}, ${e[2].toFixed(9)}, ${e[3].toFixed(9)})`},{}],261:[function(e,t,n){t.exports=(e,t,n)=>{const[o,r,s,a]=t;return e[0]=n[0]*o+n[4]*r+n[8]*s+n[12]*a,e[1]=n[1]*o+n[5]*r+n[9]*s+n[13]*a,e[2]=n[2]*o+n[6]*r+n[10]*s+n[14]*a,e[3]=n[3]*o+n[7]*r+n[11]*s+n[15]*a,e}},{}],262:[function(e,t,n){const{EPS:o}=e("../maths/constants");t.exports=(e,t)=>{let n=0;for(let o=0;o{if(0===(e=o(e)).length)throw new Error("measureAggregateArea: no geometries supplied");const t=r(e);return 1===e.length?t:t.reduce(((e,t)=>e+t),0)}},{"../utils/flatten":408,"./measureArea":268}],265:[function(e,t,n){const o=e("../utils/flatten"),r=e("../maths/vec3/min"),s=e("../maths/vec3/max"),a=e("./measureBoundingBox");t.exports=(...e)=>{if(0===(e=o(e)).length)throw new Error("measureAggregateBoundingBox: no geometries supplied");const t=a(e);if(1===e.length)return t;const n=[[Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE],[-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE]];return t.reduce(((e,t)=>[r(e[0],e[0],t[0]),s(e[1],e[1],t[1])]),n)}},{"../maths/vec3/max":236,"../maths/vec3/min":237,"../utils/flatten":408,"./measureBoundingBox":269}],266:[function(e,t,n){const o=e("../utils/flatten"),r=e("./measureAggregateBoundingBox"),s=e("./calculateEpsilonFromBounds"),{geom2:a,geom3:i,path2:c}=e("../geometries");t.exports=(...e)=>{if(0===(e=o(e)).length)throw new Error("measureAggregateEpsilon: no geometries supplied");const t=r(e);let n=0;return n=e.reduce(((e,t)=>c.isA(t)||a.isA(t)?Math.max(e,2):i.isA(t)?Math.max(e,3):0),n),s(t,n)}},{"../geometries":62,"../utils/flatten":408,"./calculateEpsilonFromBounds":262,"./measureAggregateBoundingBox":265}],267:[function(e,t,n){const o=e("../utils/flatten"),r=e("./measureVolume");t.exports=(...e)=>{if(0===(e=o(e)).length)throw new Error("measureAggregateVolume: no geometries supplied");const t=r(e);return 1===e.length?t:t.reduce(((e,t)=>e+t),0)}},{"../utils/flatten":408,"./measureVolume":275}],268:[function(e,t,n){const o=e("../utils/flatten"),r=e("../geometries/geom2"),s=e("../geometries/geom3"),a=e("../geometries/path2"),i=e("../geometries/poly3"),c=new WeakMap;t.exports=(...e)=>{if(0===(e=o(e)).length)throw new Error("wrong number of arguments");const t=e.map((e=>a.isA(e)?0:r.isA(e)?(e=>{let t=c.get(e);return t||(t=r.toSides(e).reduce(((e,t)=>e+(t[0][0]*t[1][1]-t[0][1]*t[1][0])),0),t*=.5,c.set(e,t),t)})(e):s.isA(e)?(e=>{let t=c.get(e);return t||(t=s.toPolygons(e).reduce(((e,t)=>e+i.measureArea(t)),0),c.set(e,t),t)})(e):0));return 1===t.length?t[0]:t}},{"../geometries/geom2":38,"../geometries/geom3":53,"../geometries/path2":74,"../geometries/poly3":91,"../utils/flatten":408}],269:[function(e,t,n){const o=e("../utils/flatten"),r=e("../maths/vec2"),s=e("../maths/vec3"),a=e("../geometries/geom2"),i=e("../geometries/geom3"),c=e("../geometries/path2"),l=e("../geometries/poly3"),u=new WeakMap;t.exports=(...e)=>{if(0===(e=o(e)).length)throw new Error("wrong number of arguments");const t=e.map((e=>c.isA(e)?(e=>{let t=u.get(e);if(t)return t;const n=c.toPoints(e);let o;o=0===n.length?r.create():r.clone(n[0]);let s=r.clone(o);return n.forEach((e=>{r.min(o,o,e),r.max(s,s,e)})),o=[o[0],o[1],0],s=[s[0],s[1],0],t=[o,s],u.set(e,t),t})(e):a.isA(e)?(e=>{let t=u.get(e);if(t)return t;const n=a.toPoints(e);let o;o=0===n.length?r.create():r.clone(n[0]);let s=r.clone(o);return n.forEach((e=>{r.min(o,o,e),r.max(s,s,e)})),o=[o[0],o[1],0],s=[s[0],s[1],0],t=[o,s],u.set(e,t),t})(e):i.isA(e)?(e=>{let t=u.get(e);if(t)return t;const n=i.toPolygons(e);let o=s.create();if(n.length>0){const e=l.toPoints(n[0]);s.copy(o,e[0])}let r=s.clone(o);return n.forEach((e=>{l.toPoints(e).forEach((e=>{s.min(o,o,e),s.max(r,r,e)}))})),o=[o[0],o[1],o[2]],r=[r[0],r[1],r[2]],t=[o,r],u.set(e,t),t})(e):[[0,0,0],[0,0,0]]));return 1===t.length?t[0]:t}},{"../geometries/geom2":38,"../geometries/geom3":53,"../geometries/path2":74,"../geometries/poly3":91,"../maths/vec2":202,"../maths/vec3":233,"../utils/flatten":408}],270:[function(e,t,n){const o=e("../utils/flatten"),r=e("../maths/vec2"),s=e("../maths/vec3"),a=e("../geometries/geom2"),i=e("../geometries/geom3"),c=e("../geometries/path2"),l=e("../geometries/poly3"),u=new WeakMap;t.exports=(...e)=>{const t=(e=o(e)).map((e=>c.isA(e)?(e=>{let t=u.get(e);if(void 0!==t)return t;const n=s.create();let o=0;const a=c.toPoints(e);if(a.length>0){let e=0;const t=s.create();a.forEach((o=>{s.add(n,n,s.fromVec2(t,o,0)),e++})),s.scale(n,n,1/e),a.forEach((e=>{o=Math.max(o,r.squaredDistance(n,e))})),o=Math.sqrt(o)}return t=[n,o],u.set(e,t),t})(e):a.isA(e)?(e=>{let t=u.get(e);if(void 0!==t)return t;const n=s.create();let o=0;const i=a.toSides(e);if(i.length>0){let e=0;const t=s.create();i.forEach((o=>{s.add(n,n,s.fromVec2(t,o[0],0)),e++})),s.scale(n,n,1/e),i.forEach((e=>{o=Math.max(o,r.squaredDistance(n,e[0]))})),o=Math.sqrt(o)}return t=[n,o],u.set(e,t),t})(e):i.isA(e)?(e=>{let t=u.get(e);if(void 0!==t)return t;const n=s.create();let o=0;const r=i.toPolygons(e);if(r.length>0){let e=0;r.forEach((t=>{l.toPoints(t).forEach((t=>{s.add(n,n,t),e++}))})),s.scale(n,n,1/e),r.forEach((e=>{l.toPoints(e).forEach((e=>{o=Math.max(o,s.squaredDistance(n,e))}))})),o=Math.sqrt(o)}return t=[n,o],u.set(e,t),t})(e):[[0,0,0],0]));return 1===t.length?t[0]:t}},{"../geometries/geom2":38,"../geometries/geom3":53,"../geometries/path2":74,"../geometries/poly3":91,"../maths/vec2":202,"../maths/vec3":233,"../utils/flatten":408}],271:[function(e,t,n){const o=e("../utils/flatten"),r=e("./measureBoundingBox");t.exports=(...e)=>{const t=(e=o(e)).map((e=>{const t=r(e);return[t[0][0]+(t[1][0]-t[0][0])/2,t[0][1]+(t[1][1]-t[0][1])/2,t[0][2]+(t[1][2]-t[0][2])/2]}));return 1===t.length?t[0]:t}},{"../utils/flatten":408,"./measureBoundingBox":269}],272:[function(e,t,n){const o=e("../utils/flatten"),r=e("../maths/vec3"),s=e("../geometries/geom2"),a=e("../geometries/geom3"),i=new WeakMap;t.exports=(...e)=>{const t=(e=o(e)).map((e=>s.isA(e)?(e=>{let t=i.get(e);if(void 0!==t)return t;const n=s.toSides(e);let o=0,a=0,c=0;if(n.length>0){for(let e=0;e{let t=i.get(e);if(void 0!==t)return t;t=r.create();const n=a.toPolygons(e);if(0===n.length)return t;let o=0;const s=r.create();return n.forEach((e=>{const n=e.vertices;for(let e=0;e{const t=(e=o(e)).map((e=>{const t=r(e);return[t[1][0]-t[0][0],t[1][1]-t[0][1],t[1][2]-t[0][2]]}));return 1===t.length?t[0]:t}},{"../utils/flatten":408,"./measureBoundingBox":269}],274:[function(e,t,n){const o=e("../utils/flatten"),{geom2:r,geom3:s,path2:a}=e("../geometries"),i=e("./calculateEpsilonFromBounds"),c=e("./measureBoundingBox");t.exports=(...e)=>{if(0===(e=o(e)).length)throw new Error("wrong number of arguments");const t=e.map((e=>a.isA(e)||r.isA(e)?(e=>i(c(e),2))(e):s.isA(e)?(e=>i(c(e),3))(e):0));return 1===t.length?t[0]:t}},{"../geometries":62,"../utils/flatten":408,"./calculateEpsilonFromBounds":262,"./measureBoundingBox":269}],275:[function(e,t,n){const o=e("../utils/flatten"),r=e("../geometries/geom2"),s=e("../geometries/geom3"),a=e("../geometries/path2"),i=e("../geometries/poly3"),c=new WeakMap;t.exports=(...e)=>{if(0===(e=o(e)).length)throw new Error("wrong number of arguments");const t=e.map((e=>a.isA(e)||r.isA(e)?0:s.isA(e)?(e=>{let t=c.get(e);return t||(t=s.toPolygons(e).reduce(((e,t)=>e+i.measureSignedVolume(t)),0),c.set(e,t),t)})(e):0));return 1===t.length?t[0]:t}},{"../geometries/geom2":38,"../geometries/geom3":53,"../geometries/path2":74,"../geometries/poly3":91,"../utils/flatten":408}],276:[function(e,t,n){const o=e("../../maths/vec2"),r=e("../../geometries/geom2");t.exports=(e,t)=>{const n=t.map((t=>((e,t)=>{if(t.vertices.length<4)return null;const n=[],r=t.vertices.filter(((e,t)=>e[2]>0&&(n.push(t),!0)));if(2!==r.length)throw new Error("Assertion failed: fromFakePolygon: not enough points found");const s=r.map((t=>{const n=Math.round(t[0]/e)*e+0,r=Math.round(t[1]/e)*e+0;return o.fromValues(n,r)}));if(o.equals(s[0],s[1]))return null;const a=n[1]-n[0];if(1!==a&&3!==a)throw new Error("Assertion failed: fromFakePolygon: unknown index ordering");return 1===a&&s.reverse(),s})(e,t))).filter((e=>null!==e));return r.create(n)}},{"../../geometries/geom2":38,"../../maths/vec2":202}],277:[function(e,t,n){t.exports={intersect:e("./intersect"),scission:e("./scission"),subtract:e("./subtract"),union:e("./union")}},{"./intersect":278,"./scission":283,"./subtract":285,"./union":296}],278:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../utils/areAllShapesTheSameType"),s=e("../../geometries/geom2"),a=e("../../geometries/geom3"),i=e("./intersectGeom2"),c=e("./intersectGeom3");t.exports=(...e)=>{if(0===(e=o(e)).length)throw new Error("wrong number of arguments");if(!r(e))throw new Error("only intersect of the types are supported");const t=e[0];return s.isA(t)?i(e):a.isA(t)?c(e):t}},{"../../geometries/geom2":38,"../../geometries/geom3":53,"../../utils/areAllShapesTheSameType":406,"../../utils/flatten":408,"./intersectGeom2":279,"./intersectGeom3":280}],279:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../geometries/geom3"),s=e("../../measurements/measureEpsilon"),a=e("./fromFakePolygons"),i=e("./to3DWalls"),c=e("./intersectGeom3");t.exports=(...e)=>{const t=(e=o(e)).map((e=>i({z0:-1,z1:1},e))),n=c(t),l=s(n);return a(l,r.toPolygons(n))}},{"../../geometries/geom3":53,"../../measurements/measureEpsilon":274,"../../utils/flatten":408,"./fromFakePolygons":276,"./intersectGeom3":280,"./to3DWalls":289}],280:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../modifiers/retessellate"),s=e("./intersectGeom3Sub");t.exports=(...e)=>{let t=(e=o(e)).shift();return e.forEach((e=>{t=s(t,e)})),t=r(t),t}},{"../../utils/flatten":408,"../modifiers/retessellate":366,"./intersectGeom3Sub":281}],281:[function(e,t,n){const o=e("../../geometries/geom3"),r=e("./mayOverlap"),{Tree:s}=e("./trees");t.exports=(e,t)=>{if(!r(e,t))return o.create();const n=new s(o.toPolygons(e)),a=new s(o.toPolygons(t));n.invert(),a.clipTo(n),a.invert(),n.clipTo(a),a.clipTo(n),n.addPolygons(a.allPolygons()),n.invert();const i=n.allPolygons();return o.create(i)}},{"../../geometries/geom3":53,"./mayOverlap":282,"./trees":293}],282:[function(e,t,n){const{EPS:o}=e("../../maths/constants"),r=e("../../measurements/measureBoundingBox");t.exports=(e,t)=>{if(0===e.polygons.length||0===t.polygons.length)return!1;const n=r(e),s=n[0],a=n[1],i=r(t),c=i[0],l=i[1];return!(c[0]-a[0]>o||s[0]-l[0]>o||c[1]-a[1]>o||s[1]-l[1]>o||c[2]-a[2]>o||s[2]-l[2]>o)}},{"../../maths/constants":106,"../../measurements/measureBoundingBox":269}],283:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../geometries/geom3"),s=e("./scissionGeom3");t.exports=(...e)=>{if(0===(e=o(e)).length)throw new Error("wrong number of arguments");const t=e.map((e=>r.isA(e)?s(e):e));return 1===t.length?t[0]:t}},{"../../geometries/geom3":53,"../../utils/flatten":408,"./scissionGeom3":284}],284:[function(e,t,n){const o=e("../../maths/vec3"),r=e("../../measurements/measureEpsilon"),s=e("../../geometries/geom3");t.exports=e=>{const t=r(e),n=s.toPolygons(e),a=n.length,i=new Map,c=o.create();n.forEach(((e,n)=>{e.vertices.forEach((e=>{((e,t,n)=>{const o=`${t}`,r=e.get(o);void 0===r?e.set(o,[n]):r.push(n)})(i,o.snap(c,e,t),n)}))}));const l=n.map((e=>{let n=[];return e.vertices.forEach((e=>{n=n.concat(((e,t)=>{const n=`${t}`;return e.get(n)})(i,o.snap(c,e,t)))})),{e:1,d:(r=n,r.sort(((e,t)=>e-t)).filter(((e,t,n)=>!t||e!==n[t-1])))};var r}));i.clear();let u=0;const p=l.length;for(let e=0;e0){const n=new Array(a);n[e]=!0;do{u=0,n.forEach(((e,t)=>{const o=l[t];if(o.e>0){o.e=-1;for(let e=0;e0);t.indexes=n}}const f=[];for(let e=0;et.push(n[o]))),f.push(s.create(t))}return f}},{"../../geometries/geom3":53,"../../maths/vec3":233,"../../measurements/measureEpsilon":274}],285:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../utils/areAllShapesTheSameType"),s=e("../../geometries/geom2"),a=e("../../geometries/geom3"),i=e("./subtractGeom2"),c=e("./subtractGeom3");t.exports=(...e)=>{if(0===(e=o(e)).length)throw new Error("wrong number of arguments");if(!r(e))throw new Error("only subtract of the types are supported");const t=e[0];return s.isA(t)?i(e):a.isA(t)?c(e):t}},{"../../geometries/geom2":38,"../../geometries/geom3":53,"../../utils/areAllShapesTheSameType":406,"../../utils/flatten":408,"./subtractGeom2":286,"./subtractGeom3":287}],286:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../geometries/geom3"),s=e("../../measurements/measureEpsilon"),a=e("./fromFakePolygons"),i=e("./to3DWalls"),c=e("./subtractGeom3");t.exports=(...e)=>{const t=(e=o(e)).map((e=>i({z0:-1,z1:1},e))),n=c(t),l=s(n);return a(l,r.toPolygons(n))}},{"../../geometries/geom3":53,"../../measurements/measureEpsilon":274,"../../utils/flatten":408,"./fromFakePolygons":276,"./subtractGeom3":287,"./to3DWalls":289}],287:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../modifiers/retessellate"),s=e("./subtractGeom3Sub");t.exports=(...e)=>{let t=(e=o(e)).shift();return e.forEach((e=>{t=s(t,e)})),t=r(t),t}},{"../../utils/flatten":408,"../modifiers/retessellate":366,"./subtractGeom3Sub":288}],288:[function(e,t,n){const o=e("../../geometries/geom3"),r=e("./mayOverlap"),{Tree:s}=e("./trees");t.exports=(e,t)=>{if(!r(e,t))return o.clone(e);const n=new s(o.toPolygons(e)),a=new s(o.toPolygons(t));n.invert(),n.clipTo(a),a.clipTo(n,!0),n.addPolygons(a.allPolygons()),n.invert();const i=n.allPolygons();return o.create(i)}},{"../../geometries/geom3":53,"./mayOverlap":282,"./trees":293}],289:[function(e,t,n){const o=e("../../maths/vec3"),r=e("../../geometries/geom2"),s=e("../../geometries/geom3"),a=e("../../geometries/poly3");t.exports=(e,t)=>{const n=r.toSides(t).map((t=>((e,t,n)=>{const r=[o.fromVec2(o.create(),n[0],e),o.fromVec2(o.create(),n[1],e),o.fromVec2(o.create(),n[1],t),o.fromVec2(o.create(),n[0],t)];return a.create(r)})(e.z0,e.z1,t)));return s.create(n)}},{"../../geometries/geom2":38,"../../geometries/geom3":53,"../../geometries/poly3":91,"../../maths/vec3":233}],290:[function(e,t,n){const o=e("../../../maths/plane"),r=e("../../../geometries/poly3");class s{constructor(e){this.plane=null,this.front=null,this.back=null,this.polygontreenodes=[],this.parent=e}invert(){const e=[this];let t;for(let n=0;n0&&r.push({node:n.front,polygontreenodes:a});const l=s.length;if(n.back&&l>0)r.push({node:n.back,polygontreenodes:s});else for(let e=0;e0&&e.rootnode.clipPolygons(n.polygontreenodes,t),n.front&&o.push(n.front),n.back&&o.push(n.back),n=o.pop()}while(void 0!==n)}addPolygonTreeNodes(e){let t={node:this,polygontreenodes:e};const n=[];do{const e=t.node,o=t.polygontreenodes;if(0===o.length){t=n.pop();continue}if(!e.plane){let t=0;t=Math.floor(o.length/2);const n=o[t].getPolygon();e.plane=r.plane(n)}const a=[],i=[],c=o.length;for(let t=0;t0&&(e.front||(e.front=new s(e)),c===a.length&&0===i.length?e.front.polygontreenodes=a:n.push({node:e.front,polygontreenodes:a})),i.length>0&&(e.back||(e.back=new s(e)),c===i.length&&0===a.length?e.back.polygontreenodes=i:n.push({node:e.back,polygontreenodes:i})),t=n.pop()}while(void 0!==t)}}t.exports=s},{"../../../geometries/poly3":91,"../../../maths/plane":174}],291:[function(e,t,n){const{EPS:o}=e("../../../maths/constants"),r=e("../../../maths/vec3"),s=e("../../../geometries/poly3"),a=e("./splitPolygonByPlane");class i{constructor(e,t){this.parent=e,this.children=[],this.polygon=t,this.removed=!1}addPolygons(e){if(!this.isRootNode())throw new Error("Assertion failed");const t=this;e.forEach((e=>{t.addChild(e)}))}remove(){if(!this.removed){this.removed=!0,this.polygon=null;const e=this.parent.children,t=e.indexOf(this);if(t<0)throw new Error("Assertion failed");e.splice(t,1),this.parent.recursivelyInvalidatePolygon()}}isRemoved(){return this.removed}isRootNode(){return!this.parent}invert(){if(!this.isRootNode())throw new Error("Assertion failed");this.invertSub()}getPolygon(){if(!this.polygon)throw new Error("Assertion failed");return this.polygon}getPolygons(e){let t=[this];const n=[t];let o,r,s,a;for(o=0;o0&&n.push(a.children)}splitByPlane(e,t,n,o,r){if(this.children.length){const s=[this.children];let a,i,c,l,u;for(a=0;a0?s.push(l.children):l._splitByPlane(e,t,n,o,r)}else this._splitByPlane(e,t,n,o,r)}_splitByPlane(e,t,n,i,c){const l=this.polygon;if(l){const u=s.measureBoundingSphere(l),p=u[3]+o,f=u,h=r.dot(e,f)-e[3];if(h>p)i.push(this);else if(h<-p)c.push(this);else{const o=a(e,l);switch(o.type){case 0:t.push(this);break;case 1:n.push(this);break;case 2:i.push(this);break;case 3:c.push(this);break;case 4:if(o.front){const e=this.addChild(o.front);i.push(e)}if(o.back){const e=this.addChild(o.back);c.push(e)}}}}}addChild(e){const t=new i(this,e);return this.children.push(t),t}invertSub(){let e=[this];const t=[e];let n,o,r,a;for(n=0;n0&&t.push(a.children)}recursivelyInvalidatePolygon(){this.polygon=null,this.parent&&this.parent.recursivelyInvalidatePolygon()}clear(){let e=[this];const t=[e];for(let n=0;n0&&t.push(o.children),o.children=[]}}}toString(){let e="",t=[this];const n=[t];let o,r,s,a;for(o=0;o0&&n.push(a.children)}return e}}t.exports=i},{"../../../geometries/poly3":91,"../../../maths/constants":106,"../../../maths/vec3":233,"./splitPolygonByPlane":295}],292:[function(e,t,n){const o=e("./Node"),r=e("./PolygonTreeNode");t.exports=class{constructor(e){this.polygonTree=new r,this.rootnode=new o(null),e&&this.addPolygons(e)}invert(){this.polygonTree.invert(),this.rootnode.invert()}clipTo(e,t=!1){this.rootnode.clipTo(e,t)}allPolygons(){const e=[];return this.polygonTree.getPolygons(e),e}addPolygons(e){const t=new Array(e.length);for(let n=0;n{const r=o.subtract(o.create(),n,t);let s=(e[3]-o.dot(e,t))/o.dot(e,r);return Number.isNaN(s)&&(s=0),s>1&&(s=1),s<0&&(s=0),o.scale(r,r,s),o.add(r,t,r),r}},{"../../../maths/vec3":233}],295:[function(e,t,n){const{EPS:o}=e("../../../maths/constants"),r=e("../../../maths/plane"),s=e("../../../maths/vec3"),a=e("../../../geometries/poly3"),i=e("./splitLineSegmentByPlane");t.exports=(e,t)=>{const n={type:null,front:null,back:null},c=t.vertices,l=c.length,u=a.plane(t);if(r.equals(u,e))n.type=0;else{let t=!1,r=!1;const p=[],f=-o;for(let n=0;no&&(t=!0),a=l&&(s=0);const a=p[s];if(f===a)f?r.push(o):t.push(o);else{const n=c[s],a=i(e,o,n);f?(r.push(o),r.push(a),t.push(a)):(t.push(o),t.push(a),r.push(a))}f=a}const h=o*o;if(r.length>=3){let e=r[r.length-1];for(let t=0;t=3){let e=t[t.length-1];for(let n=0;n=3&&(n.front=a.fromPointsAndPlane(t,u)),r.length>=3&&(n.back=a.fromPointsAndPlane(r,u))}else n.type=3;else n.type=2;else{const t=s.dot(e,u);n.type=t>=0?0:1}}return n}},{"../../../geometries/poly3":91,"../../../maths/constants":106,"../../../maths/plane":174,"../../../maths/vec3":233,"./splitLineSegmentByPlane":294}],296:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../utils/areAllShapesTheSameType"),s=e("../../geometries/geom2"),a=e("../../geometries/geom3"),i=e("./unionGeom2"),c=e("./unionGeom3");t.exports=(...e)=>{if(0===(e=o(e)).length)throw new Error("wrong number of arguments");if(!r(e))throw new Error("only unions of the same type are supported");const t=e[0];return s.isA(t)?i(e):a.isA(t)?c(e):t}},{"../../geometries/geom2":38,"../../geometries/geom3":53,"../../utils/areAllShapesTheSameType":406,"../../utils/flatten":408,"./unionGeom2":297,"./unionGeom3":298}],297:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../geometries/geom3"),s=e("../../measurements/measureEpsilon"),a=e("./fromFakePolygons"),i=e("./to3DWalls"),c=e("./unionGeom3");t.exports=(...e)=>{const t=(e=o(e)).map((e=>i({z0:-1,z1:1},e))),n=c(t),l=s(n);return a(l,r.toPolygons(n))}},{"../../geometries/geom3":53,"../../measurements/measureEpsilon":274,"../../utils/flatten":408,"./fromFakePolygons":276,"./to3DWalls":289,"./unionGeom3":298}],298:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../modifiers/retessellate"),s=e("./unionGeom3Sub");t.exports=(...e)=>{let t;for(e=o(e),t=1;t{if(!r(e,t))return((e,t)=>{let n=o.toPolygons(e);return n=n.concat(o.toPolygons(t)),o.create(n)})(e,t);const n=new s(o.toPolygons(e)),a=new s(o.toPolygons(t));n.clipTo(a,!1),a.clipTo(n),a.invert(),a.clipTo(n),a.invert();const i=n.allPolygons().concat(a.allPolygons());return o.create(i)}},{"../../geometries/geom3":53,"./mayOverlap":282,"./trees":293}],300:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../geometries/geom2"),s=e("../../geometries/geom3"),a=e("../../geometries/path2"),i=e("./expandGeom2"),c=e("./expandGeom3"),l=e("./expandPath2");t.exports=(e,...t)=>{if(0===(t=o(t)).length)throw new Error("wrong number of arguments");const n=t.map((t=>a.isA(t)?l(e,t):r.isA(t)?i(e,t):s.isA(t)?c(e,t):t));return 1===n.length?n[0]:n}},{"../../geometries/geom2":38,"../../geometries/geom3":53,"../../geometries/path2":74,"../../utils/flatten":408,"./expandGeom2":301,"./expandGeom3":302,"./expandPath2":303}],301:[function(e,t,n){const o=e("../../geometries/geom2"),r=e("./offsetFromPoints");t.exports=(e,t)=>{const{delta:n,corners:s,segments:a}=Object.assign({},{delta:1,corners:"edge",segments:16},e);if("edge"!==s&&"chamfer"!==s&&"round"!==s)throw new Error('corners must be "edge", "chamfer", or "round"');const i=o.toOutlines(t).map((t=>r(e={delta:n,corners:s,closed:!0,segments:a},t))).reduce(((e,t)=>e.concat(o.toSides(o.fromPoints(t)))),[]);return o.create(i)}},{"../../geometries/geom2":38,"./offsetFromPoints":308}],302:[function(e,t,n){const o=e("../../geometries/geom3"),r=e("../booleans/union"),s=e("./expandShell");t.exports=(e,t)=>{const{delta:n,corners:a,segments:i}=Object.assign({},{delta:1,corners:"round",segments:12},e);if("round"!==a)throw new Error('corners must be "round" for 3D geometries');if(0===o.toPolygons(t).length)throw new Error("the given geometry cannot be empty");const c=s(e={delta:n,corners:a,segments:i},t);return r(t,c)}},{"../../geometries/geom3":53,"../booleans/union":296,"./expandShell":304}],303:[function(e,t,n){const o=e("../../maths/utils/area"),r=e("../../maths/vec2"),s=e("../../geometries/geom2"),a=e("../../geometries/path2"),i=e("./offsetFromPoints");t.exports=(e,t)=>{e=Object.assign({},{delta:1,corners:"edge",segments:16},e);const{delta:n,corners:c,segments:l}=e;if(n<=0)throw new Error("the given delta must be positive for paths");if("edge"!==c&&"chamfer"!==c&&"round"!==c)throw new Error('corners must be "edge", "chamfer", or "round"');const u=t.isClosed,p=a.toPoints(t);if(0===p.length)throw new Error("the given geometry cannot be empty");const f={points:p,external:i({delta:n,corners:c,segments:l,closed:u},p),internal:i({delta:-n,corners:c,segments:l,closed:u},p)};return t.isClosed?(e=>{let{external:t,internal:n}=e;o(t)<0?t=t.reverse():n=n.reverse();const r=a.fromPoints({closed:!0},t),i=a.fromPoints({closed:!0},n),c=s.toSides(s.fromPoints(a.toPoints(r))),l=s.toSides(s.fromPoints(a.toPoints(i)));return c.push(...l),s.create(c)})(f):((e,t,n,o)=>{const{points:a,external:i,internal:c}=e,l=Math.floor(t/2),u=[],p=[];if("round"===n&&l>0){const e=Math.PI/l,t=a[a.length-1],n=r.angle(r.subtract(r.create(),i[i.length-1],t)),s=a[0],f=r.angle(r.subtract(r.create(),c[0],s));for(let a=1;a{const o=t.toString();if(e.has(o))e.get(o)[1].push(n);else{const r=[t,[n]];e.set(o,r)}},g=(e,t,n)=>{const o=t[0].toString(),r=t[1].toString(),s=o{e.findIndex((e=>e===t))<0&&e.push(t)};t.exports=(e,t)=>{const{delta:n,segments:y}=Object.assign({},{delta:1,segments:12},e);let v=c.create();const b=new Map,x=new Map,A=a.create(),E=a.create();return c.toPolygons(t).forEach(((e,t)=>{const o=a.scale(a.create(),l.plane(e),2*n),r=l.transform(s.fromTranslation(s.create(),a.scale(a.create(),o,-.5)),e),i=h(o,r);v=f(v,i);const c=e.vertices;for(let t=0;t{const t=e[0],s=e[1],u=t[0],p=t[1],h=a.subtract(a.create(),p,u);a.normalize(h,h);const m=s[0],g=a.cross(a.create(),m,h);let b=[];for(let e=0;e=0&&a.distance(i,w)=0){T.push(i),P.push(c);const e=[S,c,i,w],t=l.create(e);D.push(t)}w=i,S=c}}P.reverse(),D.push(l.create(T)),D.push(l.create(P));const C=c.create(D);v=f(v,C)})),b.forEach((e=>{const t=e[0],o=e[1],r=o[0];let s=null,i=0;for(let e=1;e.05&&c>i&&(i=c,s=t)}s||(s=a.orthogonal(A,r));const c=a.cross(A,r,s);a.normalize(c,c);const l=a.cross(E,c,r),p=u({center:[t[0],t[1],t[2]],radius:n,segments:y,axes:[r,c,l]});v=f(v,p)})),p(v)}},{"../../geometries/geom3":53,"../../geometries/poly3":91,"../../maths/constants":106,"../../maths/mat4":155,"../../maths/vec3":233,"../../primitives/sphere":396,"../../utils/fnNumberSort":409,"../booleans/unionGeom3Sub":299,"../modifiers/retessellate":366,"./extrudePolygon":305}],305:[function(e,t,n){const o=e("../../maths/mat4"),r=e("../../maths/vec3"),s=e("../../geometries/geom3"),a=e("../../geometries/poly3");t.exports=(e,t)=>{r.dot(a.plane(t),e)>0&&(t=a.invert(t));const n=[t],i=a.transform(o.fromTranslation(o.create(),e),t),c=t.vertices.length;for(let e=0;e{if(0===(t=o(t)).length)throw new Error("wrong number of arguments");const n=t.map((t=>s.isA(t)?i(e,t):r.isA(t)?a(e,t):t));return 1===n.length?n[0]:n}},{"../../geometries/geom2":38,"../../geometries/path2":74,"../../utils/flatten":408,"./offsetGeom2":309,"./offsetPath2":310}],308:[function(e,t,n){const{EPS:o,TAU:r}=e("../../maths/constants"),s=e("../../maths/utils/intersect"),a=e("../../maths/line2"),i=e("../../maths/vec2"),c=e("../../maths/utils/area");t.exports=(e,t)=>{let{delta:n,corners:l,closed:u,segments:p}=Object.assign({},{delta:1,corners:"edge",closed:!1,segments:16},e);if(Math.abs(n)0&&n>=0||f<0&&n<0;n=Math.abs(n);let m=null,g=[];const d=[],y=i.create(),v=t.length;for(let e=0;ee.set(t,n)));const t=a.create(),n=a.create();d.forEach((o=>{a.fromPoints(t,o.s0[0],o.s0[1]),a.fromPoints(n,o.s1[0],o.s1[1]);const r=a.intersectPointOfLines(t,n);if(Number.isFinite(r[0])&&Number.isFinite(r[1])){const t=o.s0[1],n=e.get(t);g[n]=r,g[(n+1)%g.length]=void 0}else{const t=o.s1[0],n=e.get(t);g[n]=void 0}})),g=g.filter((e=>void 0!==e))}if("round"===l){let e=Math.floor(p/4);const t=i.create();d.forEach((o=>{let s=i.angle(i.subtract(t,o.s1[0],o.c));if(s-=i.angle(i.subtract(t,o.s0[1],o.c)),h&&s<0&&(s+=Math.PI,s<0&&(s+=Math.PI)),!h&&s>0&&(s-=Math.PI,s>0&&(s-=Math.PI)),0!==s){e=Math.floor(p*(Math.abs(s)/r));const a=s/e,c=i.angle(i.subtract(t,o.s0[1],o.c)),l=[];for(let t=1;t0){const e=o.s0[1];let t=g.findIndex((t=>i.equals(e,t)));t=(t+1)%g.length,g.splice(t,0,...l)}}else{const e=o.s1[0],t=g.findIndex((t=>i.equals(e,t)));g.splice(t,1)}}))}return g}},{"../../maths/constants":106,"../../maths/line2":117,"../../maths/utils/area":179,"../../maths/utils/intersect":182,"../../maths/vec2":202}],309:[function(e,t,n){const o=e("../../geometries/geom2"),r=e("../../geometries/poly2"),s=e("./offsetFromPoints");t.exports=(e,t)=>{const{delta:n,corners:a,segments:i}=Object.assign({},{delta:1,corners:"edge",segments:0},e);if("edge"!==a&&"chamfer"!==a&&"round"!==a)throw new Error('corners must be "edge", "chamfer", or "round"');const c=o.toOutlines(t),l=c.map((t=>{const o=c.reduce(((e,n)=>e+r.arePointsInside(t,r.create(n))),0);return s(e={delta:o%2==0?n:-n,corners:a,closed:!0,segments:i},t)})).reduce(((e,t)=>e.concat(o.toSides(o.fromPoints(t)))),[]);return o.create(l)}},{"../../geometries/geom2":38,"../../geometries/poly2":85,"./offsetFromPoints":308}],310:[function(e,t,n){const o=e("../../geometries/path2"),r=e("./offsetFromPoints");t.exports=(e,t)=>{const n={delta:1,corners:"edge",closed:t.isClosed,segments:16},{delta:s,corners:a,closed:i,segments:c}=Object.assign({},n,e);if("edge"!==a&&"chamfer"!==a&&"round"!==a)throw new Error('corners must be "edge", "chamfer", or "round"');const l=r(e={delta:s,corners:a,closed:i,segments:c},o.toPoints(t));return o.fromPoints({closed:i},l)}},{"../../geometries/path2":74,"./offsetFromPoints":308}],311:[function(e,t,n){const{area:o}=e("../../../maths/utils"),{toOutlines:r}=e("../../../geometries/geom2"),{arePointsInside:s}=e("../../../geometries/poly2");t.exports=e=>{const t=r(e),n=[],a=[];t.forEach(((e,t)=>{const r=o(e);r<0?a.push(t):r>0&&n.push(t)}));const i=[],c=[];return n.forEach(((e,n)=>{const o=t[e];i[n]=[],a.forEach(((e,r)=>{const a=t[e];s([a[0]],{vertices:o})&&(i[n].push(e),c[r]||(c[r]=[]),c[r].push(n))}))})),a.forEach(((e,t)=>{if(c[t]&&c[t].length>1){const n=((e,t)=>{let n,o;return e.forEach(((e,r)=>{const s=t(e);(void 0===o||si[e].length));c[t].forEach(((t,o)=>{o!==n&&(i[t]=i[t].filter((t=>t!==e)))}))}})),i.map(((e,o)=>({solid:t[n[o]],holes:e.map((e=>t[e]))})))}},{"../../../geometries/geom2":38,"../../../geometries/poly2":85,"../../../maths/utils":180}],312:[function(e,t,n){const{filterPoints:o,linkedPolygon:r,locallyInside:s,splitPolygon:a}=e("./linkedPolygon"),{area:i,pointInTriangle:c}=e("./triangle"),l=(e,t)=>{const n=u(e,t);if(!n)return t;const r=a(n,e),s=o(n,n.next);return o(r,r.next),t===n?s:t},u=(e,t)=>{let n=t;const o=e.x,r=e.y;let a,i=-1/0;do{if(r<=n.y&&r>=n.next.y&&n.next.y!==n.y){const e=n.x+(r-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(e<=o&&e>i){if(i=e,e===o){if(r===n.y)return n;if(r===n.next.y)return n.next}a=n.x=n.x&&n.x>=u&&o!==n.x&&c(ra.x||n.x===a.x&&p(a,n)))&&(a=n,h=t)}n=n.next}while(n!==l);return a},p=(e,t)=>i(e.prev,e,t.prev)<0&&i(t.next,e,e.next)<0,f=e=>{let t=e,n=e;do{(t.x{const a=[];for(let n=0,o=t.length;ne.x-t.x));for(let e=0;e{if(!e)return;!l&&c&&y(e,o,s,c);let u,p,f=e;for(;e.prev!==e.next;)if(u=e.prev,p=e.next,c?g(e,o,s,c):m(e))t.push(u.i/n),t.push(e.i/n),t.push(p.i/n),r(e),e=p.next,f=p.next;else if((e=p)===f){l?1===l?(e=a(i(e),t,n),h(e,t,n,o,s,c,2)):2===l&&d(e,t,n,o,s,c):h(i(e),t,n,o,s,c,1);break}},m=e=>{const t=e.prev,n=e,o=e.next;if(p(t,n,o)>=0)return!1;let r=e.next.next;for(;r!==e.prev;){if(f(t.x,t.y,n.x,n.y,o.x,o.y,r.x,r.y)&&p(r.prev,r,r.next)>=0)return!1;r=r.next}return!0},g=(e,t,n,o)=>{const r=e.prev,s=e,a=e.next;if(p(r,s,a)>=0)return!1;const i=r.xs.x?r.x>a.x?r.x:a.x:s.x>a.x?s.x:a.x,u=r.y>s.y?r.y>a.y?r.y:a.y:s.y>a.y?s.y:a.y,h=v(i,c,t,n,o),m=v(l,u,t,n,o);let g=e.prevZ,d=e.nextZ;for(;g&&g.z>=h&&d&&d.z<=m;){if(g!==e.prev&&g!==e.next&&f(r.x,r.y,s.x,s.y,a.x,a.y,g.x,g.y)&&p(g.prev,g,g.next)>=0)return!1;if(g=g.prevZ,d!==e.prev&&d!==e.next&&f(r.x,r.y,s.x,s.y,a.x,a.y,d.x,d.y)&&p(d.prev,d,d.next)>=0)return!1;d=d.nextZ}for(;g&&g.z>=h;){if(g!==e.prev&&g!==e.next&&f(r.x,r.y,s.x,s.y,a.x,a.y,g.x,g.y)&&p(g.prev,g,g.next)>=0)return!1;g=g.prevZ}for(;d&&d.z<=m;){if(d!==e.prev&&d!==e.next&&f(r.x,r.y,s.x,s.y,a.x,a.y,d.x,d.y)&&p(d.prev,d,d.next)>=0)return!1;d=d.nextZ}return!0},d=(e,t,n,o,r,s)=>{let a=e;do{let e=a.next.next;for(;e!==a.prev;){if(a.i!==e.i&&c(a,e)){let c=u(a,e);return a=i(a,a.next),c=i(c,c.next),h(a,t,n,o,r,s),void h(c,t,n,o,r,s)}e=e.next}a=a.next}while(a!==e)},y=(e,t,n,o)=>{let r=e;do{null===r.z&&(r.z=v(r.x,r.y,t,n,o)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==e);r.prevZ.nextZ=null,r.prevZ=null,s(r,(e=>e.z))},v=(e,t,n,o,r)=>(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*r)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-o)*r)|t<<8))|t<<4))|t<<2))|t<<1))<<1;t.exports=(e,t,n=2)=>{const r=t&&t.length,s=r?t[0]*n:e.length;let a=l(e,0,s,n,!0);const i=[];if(!a||a.next===a.prev)return i;let c,u,p,f,m;if(r&&(a=o(e,t,a,n)),e.length>80*n){c=p=e[0],u=f=e[1];for(let t=n;tp&&(p=n),o>f&&(f=o)}m=Math.max(p-c,f-u),m=0!==m?1/m:0}return h(a,i,n,c,u,m),i}},{"./eliminateHoles":312,"./linkedList":314,"./linkedPolygon":316,"./triangle":318}],314:[function(e,t,n){const o=e("./linkedListSort");class r{constructor(e,t,n){this.i=e,this.x=t,this.y=n,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}t.exports={Node:r,insertNode:(e,t,n,o)=>{const s=new r(e,t,n);return o?(s.next=o.next,s.prev=o,o.next.prev=s,o.next=s):(s.prev=s,s.next=s),s},removeNode:e=>{e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)},sortLinked:o}},{"./linkedListSort":315}],315:[function(e,t,n){t.exports=(e,t)=>{let n,o,r,s,a,i=1;do{o=e,e=null;let c=null;for(a=0;o;){a++,r=o;let l=0;for(n=0;n0||u>0&&r;)0!==l&&(0===u||!r||t(o)<=t(r))?(s=o,o=o.nextZ,l--):(s=r,r=r.nextZ,u--),c?c.nextZ=s:e=s,s.prevZ=c,c=s;o=r}c.nextZ=null,i*=2}while(a>1);return e}},{}],316:[function(e,t,n){const{Node:o,insertNode:r,removeNode:s}=e("./linkedList"),{area:a}=e("./triangle"),i=(e,t)=>{if(!e)return e;t||(t=e);let n,o=e;do{if(n=!1,o.steiner||!p(o,o.next)&&0!==a(o.prev,o,o.next))o=o.next;else{if(s(o),o=t=o.prev,o===o.next)break;n=!0}}while(n||o!==t);return t},c=(e,t)=>a(e.prev,e,e.next)<0?a(e,t,e.next)>=0&&a(e,e.prev,t)>=0:a(e,t,e.prev)<0||a(e,e.next,t)<0,l=(e,t,n,o)=>{const r=Math.sign(a(e,t,n)),s=Math.sign(a(e,t,o)),i=Math.sign(a(n,o,e)),c=Math.sign(a(n,o,t));return r!==s&&i!==c||!(0!==r||!u(e,n,t))||!(0!==s||!u(e,o,t))||!(0!==i||!u(n,e,o))||!(0!==c||!u(n,t,o))},u=(e,t,n)=>t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y),p=(e,t)=>e.x===t.x&&e.y===t.y;t.exports={cureLocalIntersections:(e,t,n)=>{let o=e;do{const r=o.prev,a=o.next.next;!p(r,a)&&l(r,o,o.next,a)&&c(r,a)&&c(a,r)&&(t.push(r.i/n),t.push(o.i/n),t.push(a.i/n),s(o),s(o.next),o=e=a),o=o.next}while(o!==e);return i(o)},filterPoints:i,isValidDiagonal:(e,t)=>e.next.i!==t.i&&e.prev.i!==t.i&&!((e,t)=>{let n=e;do{if(n.i!==e.i&&n.next.i!==e.i&&n.i!==t.i&&n.next.i!==t.i&&l(n,n.next,e,t))return!0;n=n.next}while(n!==e);return!1})(e,t)&&(c(e,t)&&c(t,e)&&((e,t)=>{let n=e,o=!1;const r=(e.x+t.x)/2,s=(e.y+t.y)/2;do{n.y>s!=n.next.y>s&&n.next.y!==n.y&&r<(n.next.x-n.x)*(s-n.y)/(n.next.y-n.y)+n.x&&(o=!o),n=n.next}while(n!==e);return o})(e,t)&&(a(e.prev,e,t.prev)||a(e,t.prev,t))||p(e,t)&&a(e.prev,e,e.next)>0&&a(t.prev,t,t.next)>0),linkedPolygon:(e,t,n,o,a)=>{let i;if(a===((e,t,n,o)=>{let r=0;for(let s=t,a=n-o;s0)for(let s=t;s=t;s-=o)i=r(s,e[s],e[s+1],i);return i&&p(i,i.next)&&(s(i),i=i.next),i},locallyInside:c,splitPolygon:(e,t)=>{const n=new o(e.i,e.x,e.y),r=new o(t.i,t.x,t.y),s=e.next,a=t.prev;return e.next=t,t.prev=e,n.next=s,s.prev=n,r.next=n,n.prev=r,a.next=r,r.prev=a,r}}},{"./linkedList":314,"./triangle":318}],317:[function(e,t,n){const o=e("../../../geometries/geom2"),r=e("../../../maths/plane"),s=e("../../../maths/vec2"),a=e("../../../maths/vec3"),i=e("../slice/calculatePlane"),c=e("./assignHoles");t.exports=class{constructor(e){this.plane=i(e);const t=a.orthogonal(a.create(),this.plane),n=a.cross(a.create(),this.plane,t);this.v=a.normalize(n,n),this.u=a.cross(a.create(),this.v,this.plane),this.basisMap=new Map;const r=e.edges.map((e=>e.map((e=>this.to2D(e))))),s=o.create(r);this.roots=c(s)}to2D(e){const t=s.fromValues(a.dot(e,this.u),a.dot(e,this.v));return this.basisMap.set(t,e),t}to3D(e){const t=this.basisMap.get(e);if(t)return t;{console.log("Warning: point not in original slice");const t=a.scale(a.create(),this.u,e[0]),n=a.scale(a.create(),this.v,e[1]),o=a.scale(a.create(),r,r[3]),s=a.add(t,t,o);return a.add(n,n,s)}}}},{"../../../geometries/geom2":38,"../../../maths/plane":174,"../../../maths/vec2":202,"../../../maths/vec3":233,"../slice/calculatePlane":331,"./assignHoles":311}],318:[function(e,t,n){t.exports={area:(e,t,n)=>(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y),pointInTriangle:(e,t,n,o,r,s,a,i)=>(r-a)*(t-i)-(e-a)*(s-i)>=0&&(e-a)*(o-i)-(n-a)*(t-i)>=0&&(n-a)*(s-i)-(r-a)*(o-i)>=0}},{}],319:[function(e,t,n){const o=e("../../maths/mat4"),r=e("../../geometries/geom2"),s=e("../../geometries/geom3"),a=e("../../geometries/poly3"),i=e("./slice"),c=e("./slice/repair"),l=e("./extrudeWalls"),u=(e,t,n)=>{let s=null;return r.isA(n)&&(s=i.fromSides(r.toSides(n))),a.isA(n)&&(s=i.fromPoints(a.toPoints(n))),0===e||1===e?i.transform(o.fromTranslation(o.create(),[0,0,e]),s):null};t.exports=(e,t)=>{const n={numberOfSlices:2,capStart:!0,capEnd:!0,close:!1,repair:!0,callback:u},{numberOfSlices:o,capStart:r,capEnd:p,close:f,repair:h,callback:m}=Object.assign({},n,e);if(o<2)throw new Error("numberOfSlices must be 2 or more");h&&(t=c(t));const g=o-1;let d=null,y=null,v=null,b=[];for(let e=0;e{const n={angle:o,startAngle:0,pitch:10,endOffset:0,segmentsPerRotation:32},{angle:c,endOffset:l,segmentsPerRotation:u,startAngle:p}=Object.assign({},n,e);let f;if(f=!e.pitch&&e.height?e.height/(c/o):e.pitch?e.pitch:n.pitch,u<3)throw new Error("The number of segments per rotation needs to be at least 3.");const h=i.toSides(t);if(0===h.length)throw new Error("the given geometry cannot be empty");const m=h.filter((e=>e[0][0]>=0));let g=r.fromSides(h);0===m.length&&(g=r.reverse(g));const d=Math.round(u/o*Math.abs(c)),y=d>=2?d:2,v=s.create();let b;return a({numberOfSlices:y+1,callback:(e,t,n)=>{const a=p+c/y*t,i=l/y*t,u=(a-p)/o*f;return s.multiply(v,s.fromTranslation(s.create(),[i,0,u*Math.sign(c)]),s.fromXRotation(s.create(),-o/4*Math.sign(c))),b=s.create(),s.multiply(b,s.fromZRotation(s.create(),a),v),r.transform(b,n)}},g)}},{"../../geometries/geom2":38,"../../maths/constants":106,"../../maths/mat4":155,"./extrudeFromSlices":319,"./slice":337}],321:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../geometries/geom2"),s=e("../../geometries/path2"),a=e("./extrudeLinearGeom2"),i=e("./extrudeLinearPath2");t.exports=(e,...t)=>{const{height:n,twistAngle:c,twistSteps:l,repair:u}=Object.assign({},{height:1,twistAngle:0,twistSteps:1,repair:!0},e);if(0===(t=o(t)).length)throw new Error("wrong number of arguments");e={offset:[0,0,n],twistAngle:c,twistSteps:l,repair:u};const p=t.map((t=>s.isA(t)?i(e,t):r.isA(t)?a(e,t):t));return 1===p.length?p[0]:p}},{"../../geometries/geom2":38,"../../geometries/path2":74,"../../utils/flatten":408,"./extrudeLinearGeom2":322,"./extrudeLinearPath2":323}],322:[function(e,t,n){const o=e("../../maths/mat4"),r=e("../../maths/vec3"),s=e("../../geometries/geom2"),a=e("./slice"),i=e("./extrudeFromSlices");t.exports=(e,t)=>{let{offset:n,twistAngle:c,twistSteps:l,repair:u}=Object.assign({},{offset:[0,0,1],twistAngle:0,twistSteps:12,repair:!0},e);if(l<1)throw new Error("twistSteps must be 1 or more");0===c&&(l=1);const p=r.clone(n),f=s.toSides(t);if(0===f.length)throw new Error("the given geometry cannot be empty");const h=a.fromSides(f);p[2]<0&&a.reverse(h,h);const m=o.create();return i(e={numberOfSlices:l+1,capStart:!0,capEnd:!0,repair:u,callback:(e,t,n)=>{const s=t/l*c,i=r.scale(r.create(),p,t/l);return o.multiply(m,o.fromZRotation(m,s),o.fromTranslation(o.create(),i)),a.transform(m,n)}},h)}},{"../../geometries/geom2":38,"../../maths/mat4":155,"../../maths/vec3":233,"./extrudeFromSlices":319,"./slice":337}],323:[function(e,t,n){const o=e("../../geometries/geom2"),r=e("../../geometries/path2"),s=e("./extrudeLinearGeom2");t.exports=(e,t)=>{if(!t.isClosed)throw new Error("extruded path must be closed");const n=r.toPoints(t),a=o.fromPoints(n);return s(e,a)}},{"../../geometries/geom2":38,"../../geometries/path2":74,"./extrudeLinearGeom2":322}],324:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../geometries/geom2"),s=e("../../geometries/path2"),a=e("./extrudeRectangularPath2"),i=e("./extrudeRectangularGeom2");t.exports=(e,...t)=>{const{size:n,height:c}=Object.assign({},{size:1,height:1},e);if(0===(t=o(t)).length)throw new Error("wrong number of arguments");if(n<=0)throw new Error("size must be positive");if(c<=0)throw new Error("height must be positive");const l=t.map((t=>s.isA(t)?a(e,t):r.isA(t)?i(e,t):t));return 1===l.length?l[0]:l}},{"../../geometries/geom2":38,"../../geometries/path2":74,"../../utils/flatten":408,"./extrudeRectangularGeom2":325,"./extrudeRectangularPath2":326}],325:[function(e,t,n){const{area:o}=e("../../maths/utils"),r=e("../../geometries/geom2"),s=e("../../geometries/path2"),a=e("../expansions/expand"),i=e("./extrudeLinearGeom2");t.exports=(e,t)=>{const{size:n,height:c}=Object.assign({},{size:1,height:1},e);e.delta=n,e.offset=[0,0,c];const l=r.toOutlines(t);if(0===l.length)throw new Error("the given geometry cannot be empty");const u=l.map((t=>(o(t)<0&&t.reverse(),a(e,s.fromPoints({closed:!0},t))))).reduce(((e,t)=>e.concat(r.toSides(t))),[]),p=r.create(u);return i(e,p)}},{"../../geometries/geom2":38,"../../geometries/path2":74,"../../maths/utils":180,"../expansions/expand":300,"./extrudeLinearGeom2":322}],326:[function(e,t,n){const o=e("../../geometries/path2"),r=e("../expansions/expand"),s=e("./extrudeLinearGeom2");t.exports=(e,t)=>{const{size:n,height:a}=Object.assign({},{size:1,height:1},e);if(e.delta=n,e.offset=[0,0,a],0===o.toPoints(t).length)throw new Error("the given geometry cannot be empty");const i=r(e,t);return s(e,i)}},{"../../geometries/path2":74,"../expansions/expand":300,"./extrudeLinearGeom2":322}],327:[function(e,t,n){const{TAU:o}=e("../../maths/constants"),r=e("../../maths/mat4"),{mirrorX:s}=e("../transforms/mirror"),a=e("../../geometries/geom2"),i=e("./slice"),c=e("./extrudeFromSlices");t.exports=(e,t)=>{const n={segments:12,startAngle:0,angle:o,overflow:"cap"};let{segments:l,startAngle:u,angle:p,overflow:f}=Object.assign({},n,e);if(l<3)throw new Error("segments must be greater then 3");u=Math.abs(u)>o?u%o:u,p=Math.abs(p)>o?p%o:p;let h=u+p;if(h=Math.abs(h)>o?h%o:h,hl*e&&l++}let g=a.toSides(t);if(0===g.length)throw new Error("the given geometry cannot be empty");const d=g.filter((e=>e[0][0]<0)),y=g.filter((e=>e[0][0]>=0));d.length>0&&y.length>0&&"cap"===f&&(d.length>y.length?(g=g.map((e=>{let t=e[0],n=e[1];return t=[Math.min(t[0],0),t[1]],n=[Math.min(n[0],0),n[1]],[t,n]})),t=a.reverse(a.create(g)),t=s(t)):y.length>=d.length&&(g=g.map((e=>{let t=e[0],n=e[1];return t=[Math.max(t[0],0),t[1]],n=[Math.max(n[0],0),n[1]],[t,n]})),t=a.create(g)));const v=m/l,b=Math.abs(m){let s=v*t+u;return m===o&&t===l&&(s=u),r.multiply(A,r.fromZRotation(A,s),r.fromXRotation(r.create(),o/4)),i.transform(A,n)}},x)}},{"../../geometries/geom2":38,"../../maths/constants":106,"../../maths/mat4":155,"../transforms/mirror":373,"./extrudeFromSlices":319,"./slice":337}],328:[function(e,t,n){const{EPS:o}=e("../../maths/constants"),r=e("../../maths/vec3"),s=e("../../geometries/poly3"),a=e("./slice"),i=(e,t)=>e===t?e:e{const n=e/t.length;if(1===n)return t;const o=r.fromValues(n,n,n),s=[];return t.forEach((e=>{const t=r.subtract(r.create(),e[1],e[0]);r.divide(t,t,o);let a=e[0];for(let e=1;e<=n;++e){const e=r.add(r.create(),a,t);s.push([a,e]),a=e}})),s},l=o*o/2*Math.sin(Math.PI/3);t.exports=(e,t)=>{let n=a.toEdges(e),o=a.toEdges(t);if(n.length!==o.length){const e=(r=n.length)*(u=o.length)/i(r,u);e!==n.length&&(n=c(e,n)),e!==o.length&&(o=c(e,o))}var r,u;const p=[];return n.forEach(((e,t)=>{const n=o[t],r=s.create([e[0],e[1],n[1]]),a=s.measureArea(r);Number.isFinite(a)&&a>l&&p.push(r);const i=s.create([e[0],n[1],n[0]]),c=s.measureArea(i);Number.isFinite(c)&&c>l&&p.push(i)})),p}},{"../../geometries/poly3":91,"../../maths/constants":106,"../../maths/vec3":233,"./slice":337}],329:[function(e,t,n){t.exports={extrudeFromSlices:e("./extrudeFromSlices"),extrudeLinear:e("./extrudeLinear"),extrudeRectangular:e("./extrudeRectangular"),extrudeRotate:e("./extrudeRotate"),extrudeHelical:e("./extrudeHelical"),project:e("./project"),slice:e("./slice")}},{"./extrudeFromSlices":319,"./extrudeHelical":320,"./extrudeLinear":321,"./extrudeRectangular":324,"./extrudeRotate":327,"./project":330,"./slice":337}],330:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../maths/utils/aboutEqualNormals"),s=e("../../maths/plane"),a=e("../../maths/mat4"),i=e("../../geometries/geom2"),c=e("../../geometries/geom3"),l=e("../../geometries/poly3"),u=e("../../measurements/measureEpsilon"),p=e("../booleans/unionGeom2");t.exports=(e,...t)=>{const{axis:n,origin:f}=Object.assign({},{axis:[0,0,1],origin:[0,0,0]},e);if(0===(t=o(t)).length)throw new Error("wrong number of arguments");e={axis:n,origin:f};const h=t.map((t=>c.isA(t)?((e,t)=>{const n=s.fromNormalAndPoint(s.create(),e.axis,e.origin);if(Number.isNaN(n[0])||Number.isNaN(n[1])||Number.isNaN(n[2])||Number.isNaN(n[3]))throw new Error("project: invalid axis or origin");const o=u(t),f=o*o*Math.sqrt(3)/4;if(0===o)return i.create();const h=c.toPolygons(t);let m=[];for(let e=0;es.projectionOfPoint(n,e))),o=l.create(t),a=l.plane(o);r(n,a)&&(l.measureArea(o)l.transform(e,t)))}m=m.sort(((e,t)=>l.measureArea(t)-l.measureArea(e)));const g=m.map((e=>i.fromPoints(e.vertices)));return p(g)})(e,t):t));return 1===h.length?h[0]:h}},{"../../geometries/geom2":38,"../../geometries/geom3":53,"../../geometries/poly3":91,"../../maths/mat4":155,"../../maths/plane":174,"../../maths/utils/aboutEqualNormals":178,"../../measurements/measureEpsilon":274,"../../utils/flatten":408,"../booleans/unionGeom2":297}],331:[function(e,t,n){const o=e("../../../maths/plane"),r=e("../../../maths/vec3");t.exports=e=>{const t=e.edges;if(t.length<3)throw new Error("slices must have 3 or more edges to calculate a plane");const n=t.reduce(((e,t)=>r.add(r.create(),e,t[0])),r.create());let s;r.scale(n,n,1/t.length);let a=0;t.forEach((e=>{if(!r.equals(e[0],e[1])){const t=r.squaredDistance(n,e[0]);t>a&&(s=e,a=t)}}));const i=t.find((e=>r.equals(e[1],s[0])));return o.fromPoints(o.create(),i[0],s[0],s[1])}},{"../../../maths/plane":174,"../../../maths/vec3":233}],332:[function(e,t,n){const o=e("./create"),r=e("../../../maths/vec3");t.exports=(...e)=>{let t,n;return 1===e.length?(t=o(),n=e[0]):(t=e[0],n=e[1]),t.edges=n.edges.map((e=>[r.clone(e[0]),r.clone(e[1])])),t}},{"../../../maths/vec3":233,"./create":333}],333:[function(e,t,n){t.exports=e=>(e||(e=[]),{edges:e})},{}],334:[function(e,t,n){const o=e("../../../maths/vec3");t.exports=(e,t)=>{const n=e.edges,r=t.edges;return n.length===r.length&&n.reduce(((e,t,n)=>{const s=r[n],a=o.squaredDistance(t[0],s[0]);return e&&a{if(!Array.isArray(e))throw new Error("the given points must be an array");if(e.length<3)throw new Error("the given points must contain THREE or more points");const t=[];let n=e[e.length-1];return e.forEach((e=>{2===e.length&&t.push([o.fromVec2(o.create(),n),o.fromVec2(o.create(),e)]),3===e.length&&t.push([n,e]),n=e})),r(t)}},{"../../../maths/vec3":233,"./create":333}],336:[function(e,t,n){const o=e("../../../maths/vec3"),r=e("./create");t.exports=e=>{if(!Array.isArray(e))throw new Error("the given sides must be an array");const t=[];return e.forEach((e=>{t.push([o.fromVec2(o.create(),e[0]),o.fromVec2(o.create(),e[1])])})),r(t)}},{"../../../maths/vec3":233,"./create":333}],337:[function(e,t,n){t.exports={calculatePlane:e("./calculatePlane"),clone:e("./clone"),create:e("./create"),equals:e("./equals"),fromPoints:e("./fromPoints"),fromSides:e("./fromSides"),isA:e("./isA"),reverse:e("./reverse"),toEdges:e("./toEdges"),toPolygons:e("./toPolygons"),toString:e("./toString"),transform:e("./transform")}},{"./calculatePlane":331,"./clone":332,"./create":333,"./equals":334,"./fromPoints":335,"./fromSides":336,"./isA":338,"./reverse":340,"./toEdges":341,"./toPolygons":342,"./toString":343,"./transform":344}],338:[function(e,t,n){t.exports=e=>!!(e&&"object"==typeof e&&"edges"in e&&Array.isArray(e.edges))},{}],339:[function(e,t,n){const o=e("../../../maths/vec3"),r=e("./create");t.exports=e=>{if(!e.edges)return e;let t=e.edges;const n=new Map,s=new Map;t=t.filter((e=>!o.equals(e[0],e[1]))),t.forEach((e=>{const t=e[0].toString(),o=e[1].toString();n.set(t,e[0]),n.set(o,e[1]),s.set(t,(s.get(t)||0)+1),s.set(o,(s.get(o)||0)-1)}));const a=[],i=[];return s.forEach(((e,t)=>{e<0&&a.push(t),e>0&&i.push(t)})),a.forEach((e=>{const r=n.get(e);let s,a=1/0;i.forEach((e=>{const t=n.get(e),i=o.distance(r,t);it[0].toString()===e?[s,t[1]]:t[1].toString()===e?[t[0],s]:t))})),r(t)}},{"../../../maths/vec3":233,"./create":333}],340:[function(e,t,n){const o=e("./create");t.exports=(...e)=>{let t,n;return 1===e.length?(t=o(),n=e[0]):(t=e[0],n=e[1]),t.edges=n.edges.map((e=>[e[1],e[0]])),t}},{"./create":333}],341:[function(e,t,n){t.exports=e=>e.edges},{}],342:[function(e,t,n){const o=e("../../../geometries/poly3"),r=e("../earcut"),s=e("../earcut/polygonHierarchy");t.exports=e=>{const t=new s(e),n=[];return t.roots.forEach((({solid:e,holes:s})=>{let a=e.length;const i=[];s.forEach(((e,t)=>{i.push(a),a+=e.length}));const c=[e,...s].flat(),l=c.flat(),u=e=>t.to3D(c[e]),p=r(l,i);for(let e=0;e{return`[${t=e.edges,t.reduce(((e,t)=>e+`[${o.toString(t[0])}, ${o.toString(t[1])}], `),"")}]`;var t}},{"../../../maths/vec3":233}],344:[function(e,t,n){const o=e("../../../maths/vec3"),r=e("./create");t.exports=(e,t)=>{const n=t.edges.map((t=>[o.transform(o.create(),t[0],e),o.transform(o.create(),t[1],e)]));return r(n)}},{"../../../maths/vec3":233,"./create":333}],345:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../utils/areAllShapesTheSameType"),s=e("../../geometries/geom2"),a=e("../../geometries/geom3"),i=e("../../geometries/path2"),c=e("./hullPath2"),l=e("./hullGeom2"),u=e("./hullGeom3");t.exports=(...e)=>{if(0===(e=o(e)).length)throw new Error("wrong number of arguments");if(!r(e))throw new Error("only hulls of the same type are supported");const t=e[0];return i.isA(t)?c(e):s.isA(t)?l(e):a.isA(t)?u(e):t}},{"../../geometries/geom2":38,"../../geometries/geom3":53,"../../geometries/path2":74,"../../utils/areAllShapesTheSameType":406,"../../utils/flatten":408,"./hullGeom2":347,"./hullGeom3":348,"./hullPath2":349}],346:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../booleans/union"),s=e("./hull");t.exports=(...e)=>{if((e=o(e)).length<2)throw new Error("wrong number of arguments");const t=[];for(let n=1;n{e=o(e);const t=a(e),n=s(t);return n.length<3?r.create():r.fromPoints(n)}},{"../../geometries/geom2":38,"../../utils/flatten":408,"./hullPoints2":350,"./toUniquePoints":360}],348:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../geometries/geom3"),s=e("../../geometries/poly3"),a=e("./quickhull"),i=e("./toUniquePoints");t.exports=(...e)=>{if(1===(e=o(e)).length)return e[0];const t=i(e),n=a(t,{skipTriangulation:!0}).map((e=>{const n=e.map((e=>t[e]));return s.create(n)}));return r.create(n)}},{"../../geometries/geom3":53,"../../geometries/poly3":91,"../../utils/flatten":408,"./quickhull":358,"./toUniquePoints":360}],349:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../geometries/path2"),s=e("./hullPoints2"),a=e("./toUniquePoints");t.exports=(...e)=>{e=o(e);const t=a(e),n=s(t);return r.fromPoints({closed:!0},n)}},{"../../geometries/path2":74,"../../utils/flatten":408,"./hullPoints2":350,"./toUniquePoints":360}],350:[function(e,t,n){const o=e("../../maths/vec2");t.exports=e=>{let t=o.fromValues(1/0,1/0);e.forEach((e=>{(e[1]{const r=(a=e[1]-t[1],i=e[0]-t[0],0===a&&0===i?-1/0:-i/a),s=o.squaredDistance(e,t);var a,i;n.push({point:e,angle:r,distSq:s})})),n.sort(((e,t)=>e.angle!==t.angle?e.angle-t.angle:e.distSq-t.distSq));const r=[];return n.forEach((e=>{let t=r.length;for(;t>1&&(n=r[t-2],o=r[t-1],s=e.point,(o[0]-n[0])*(s[1]-n[1])-(o[1]-n[1])*(s[0]-n[0])<=Number.EPSILON);)r.pop(),t=r.length;var n,o,s;r.push(e.point)})),r}},{"../../maths/vec2":202}],351:[function(e,t,n){t.exports={hull:e("./hull"),hullChain:e("./hullChain")}},{"./hull":345,"./hullChain":346}],352:[function(e,t,n){const o=e("../../../maths/vec3/add"),r=e("../../../maths/vec3/copy"),s=e("../../../maths/vec3/cross"),a=e("../../../maths/vec3/dot"),i=e("../../../maths/vec3/length"),c=e("../../../maths/vec3/normalize"),l=e("../../../maths/vec3/scale"),u=e("../../../maths/vec3/subtract"),p=e("./HalfEdge");class f{constructor(){this.normal=[],this.centroid=[],this.offset=0,this.outside=null,this.mark=0,this.edge=null,this.nVertices=0}getEdge(e){if("number"!=typeof e)throw Error("requires a number");let t=this.edge;for(;e>0;)t=t.next,e-=1;for(;e<0;)t=t.prev,e+=1;return t}computeNormal(){const e=this.edge,t=e.next;let n=t.next;const a=u([],t.head().point,e.head().point),c=[],p=[];for(this.nVertices=2,this.normal=[0,0,0];n!==e;)r(p,a),u(a,n.head().point,e.head().point),o(this.normal,this.normal,s(c,p,a)),n=n.next,this.nVertices+=1;this.area=i(this.normal),this.normal=l(this.normal,this.normal,1/this.area)}computeNormalMinArea(e){if(this.computeNormal(),this.areat&&(e=n,t=o),n=n.next}while(n!==this.edge);const r=e.tail().point,s=e.head().point,i=u([],s,r),p=Math.sqrt(t);l(i,i,1/p);const f=a(this.normal,i);l(i,i,-f),o(this.normal,this.normal,i),c(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let e=this.edge;do{o(this.centroid,this.centroid,e.head().point),e=e.next}while(e!==this.edge);l(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(e){void 0!==e?this.computeNormalMinArea(e):this.computeNormal(),this.computeCentroid(),this.offset=a(this.normal,this.centroid)}distanceToPlane(e){return a(this.normal,e)-this.offset}connectHalfEdges(e,t){let n;if(e.opposite.face===t.opposite.face){const o=t.opposite.face;let r;e===this.edge&&(this.edge=t),3===o.nVertices?(r=t.opposite.prev.opposite,o.mark=2,n=o):(r=t.opposite.next,o.edge===r.prev&&(o.edge=r),r.prev=r.prev.prev,r.prev.next=r),t.prev=e.prev,t.prev.next=t,t.setOpposite(r),o.computeNormalAndCentroid()}else e.next=t,t.prev=e;return n}mergeAdjacentFaces(e,t){const n=e.opposite,o=n.face;t.push(o),o.mark=2;let r,s,a=e.prev,i=e.next,c=n.prev,l=n.next;for(;a.opposite.face===o;)a=a.prev,l=l.next;for(;i.opposite.face===o;)i=i.next,c=c.prev;for(r=l;r!==c.next;r=r.next)r.face=this;return this.edge=i,s=this.connectHalfEdges(c,i),s&&t.push(s),s=this.connectHalfEdges(a,l),s&&t.push(s),this.computeNormalAndCentroid(),t}collectIndices(){const e=[];let t=this.edge;do{e.push(t.head().index),t=t.next}while(t!==this.edge);return e}static createTriangle(e,t,n,o=0){const r=new f,s=new p(e,r),a=new p(t,r),i=new p(n,r);return s.next=i.prev=a,a.next=s.prev=i,i.next=a.prev=s,r.edge=s,r.computeNormalAndCentroid(o),r}}t.exports={VISIBLE:0,NON_CONVEX:1,DELETED:2,Face:f}},{"../../../maths/vec3/add":220,"../../../maths/vec3/copy":223,"../../../maths/vec3/cross":225,"../../../maths/vec3/dot":228,"../../../maths/vec3/length":234,"../../../maths/vec3/normalize":240,"../../../maths/vec3/scale":245,"../../../maths/vec3/subtract":249,"./HalfEdge":353}],353:[function(e,t,n){const o=e("../../../maths/vec3/distance"),r=e("../../../maths/vec3/squaredDistance");t.exports=class{constructor(e,t){this.vertex=e,this.face=t,this.next=null,this.prev=null,this.opposite=null}head(){return this.vertex}tail(){return this.prev?this.prev.vertex:null}length(){return this.tail()?o(this.tail().point,this.head().point):-1}lengthSquared(){return this.tail()?r(this.tail().point,this.head().point):-1}setOpposite(e){this.opposite=e,e.opposite=this}}},{"../../../maths/vec3/distance":226,"../../../maths/vec3/squaredDistance":247}],354:[function(e,t,n){const o=e("../../../maths/vec3/dot"),r=e("./point-line-distance"),s=e("./get-plane-normal"),a=e("./VertexList"),i=e("./Vertex"),{Face:c,VISIBLE:l,NON_CONVEX:u,DELETED:p}=e("./Face");t.exports=class{constructor(e){if(!Array.isArray(e))throw TypeError("input is not a valid array");if(e.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=e.length,this.faces=[],this.newFaces=[],this.claimed=new a,this.unclaimed=new a,this.vertices=[];for(let t=0;tthis.tolerance?this.addVertexToFace(o,t):this.unclaimed.add(o)}else this.unclaimed.addAll(n)}resolveUnclaimedPoints(e){let t=this.unclaimed.first();for(let n=t;n;n=t){t=n.next;let o,r=this.tolerance;for(let t=0;tr&&(r=e,o=s),r>1e3*this.tolerance)break}}o&&this.addVertexToFace(n,o)}}computeExtremes(){const e=[],t=[],n=[],o=[];let r,s;for(r=0;r<3;r+=1)n[r]=o[r]=this.vertices[0];for(r=0;r<3;r+=1)e[r]=t[r]=this.vertices[0].point[r];for(r=1;rt[s]&&(t[s]=i[s],o[s]=a)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(e[0]),Math.abs(t[0]))+Math.max(Math.abs(e[1]),Math.abs(t[1]))+Math.max(Math.abs(e[2]),Math.abs(t[2]))),[n,o]}createInitialSimplex(){const e=this.vertices,[t,n]=this.computeExtremes();let a,i,l,u,p=0,f=0;for(l=0;l<3;l+=1){const e=n[l].point[l]-t[l].point[l];e>p&&(p=e,f=l)}const h=t[f],m=n[f];for(p=0,l=0;lp&&(p=t,a=e)}}const g=s([],h.point,m.point,a.point),d=o(h.point,g);for(p=-1,l=0;lp&&(p=t,i=e)}}const y=[];if(o(i.point,g)-d<0)for(y.push(c.createTriangle(h,m,a),c.createTriangle(i,m,h),c.createTriangle(i,a,m),c.createTriangle(i,h,a)),l=0;l<3;l+=1){const e=(l+1)%3;y[l+1].getEdge(2).setOpposite(y[0].getEdge(e)),y[l+1].getEdge(1).setOpposite(y[e+1].getEdge(0))}else for(y.push(c.createTriangle(h,a,m),c.createTriangle(i,h,m),c.createTriangle(i,m,a),c.createTriangle(i,a,h)),l=0;l<3;l+=1){const e=(l+1)%3;y[l+1].getEdge(2).setOpposite(y[0].getEdge((3-l)%3)),y[l+1].getEdge(0).setOpposite(y[e+1].getEdge(1))}for(l=0;l<4;l+=1)this.faces.push(y[l]);for(l=0;lp&&(p=n,e=y[u])}e&&this.addVertexToFace(t,e)}}}reindexFaceAndVertices(){const e=[];for(let t=0;tn&&(n=r,e=t)}return e}}computeHorizon(e,t,n,o){let r;this.deleteFaceVertices(n),n.mark=p,r=t?t.next:t=n.getEdge(0);do{const t=r.opposite,n=t.face;n.mark===l&&(n.distanceToPlane(e)>this.tolerance?this.computeHorizon(e,t,n,o):o.push(r)),r=r.next}while(r!==t)}addAdjoiningFace(e,t){const n=c.createTriangle(e,t.tail(),t.head());return this.faces.push(n),n.getEdge(-1).setOpposite(t.opposite),n.getEdge(0)}addNewFaces(e,t){let n,o;this.newFaces=[];for(let r=0;r=e.nVertices)throw Error("merge recursion limit exceeded");const s=n.opposite.face;let a=!1;if(2===t?(this.oppositeFaceDistance(n)>-this.tolerance||this.oppositeFaceDistance(n.opposite)>-this.tolerance)&&(a=!0):e.area>s.area?this.oppositeFaceDistance(n)>-this.tolerance?a=!0:this.oppositeFaceDistance(n.opposite)>-this.tolerance&&(o=!1):this.oppositeFaceDistance(n.opposite)>-this.tolerance?a=!0:this.oppositeFaceDistance(n)>-this.tolerance&&(o=!1),a){const t=e.mergeAdjacentFaces(n,[]);for(let n=0;n{const i=[0,0,0];return s(e,t,n),s(i,n,a),o(e,e,i),r(e,e)}},{"../../../maths/vec3/cross":225,"../../../maths/vec3/normalize":240,"../../../maths/vec3/subtract":249}],358:[function(e,t,n){const o=e("./QuickHull");t.exports=(e,t={})=>{const n=new o(e);return n.build(),n.collectFaces(t.skipTriangulation)}},{"./QuickHull":354}],359:[function(e,t,n){const o=e("../../../maths/vec3/cross"),r=e("../../../maths/vec3/subtract"),s=e("../../../maths/vec3/squaredLength");t.exports=(e,t,n)=>Math.sqrt(((e,t,n)=>{const a=[],i=[];r(a,n,t),r(i,e,t);const c=s(o([],i,a)),l=s(a);if(0===l)throw Error("a and b are the same point");return c/l})(e,t,n))},{"../../../maths/vec3/cross":225,"../../../maths/vec3/squaredLength":248,"../../../maths/vec3/subtract":249}],360:[function(e,t,n){const o=e("../../geometries/geom2"),r=e("../../geometries/geom3"),s=e("../../geometries/path2");t.exports=e=>{const t=new Set,n=[],a=e=>{const o=e.toString();t.has(o)||(n.push(e),t.add(o))};return e.forEach((e=>{o.isA(e)?o.toPoints(e).forEach(a):r.isA(e)?r.toPoints(e).forEach((e=>e.forEach(a))):s.isA(e)&&s.toPoints(e).forEach(a)})),n}},{"../../geometries/geom2":38,"../../geometries/geom3":53,"../../geometries/path2":74}],361:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../measurements/measureEpsilon"),s=e("../../geometries/geom2"),a=e("../../geometries/geom3"),i=e("../../geometries/path2"),c=e("./snapPolygons"),l=e("./mergePolygons"),u=e("./insertTjunctions"),p=e("./triangulatePolygons");t.exports=(e,...t)=>{if(0===(t=o(t)).length)throw new Error("wrong number of arguments");const n=t.map((t=>{if(i.isA(t))return((e,t)=>t)(0,t);if(s.isA(t))return((e,t)=>t)(0,t);if(a.isA(t))return((e,t)=>{const{snap:n,simplify:o,triangulate:s}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},e),i=r(t);let f=a.toPolygons(t);n&&(f=c(i,f)),o&&(f=l(i,f)),s&&(f=u(f),f=p(i,f));const h=Object.assign({},t);return h.polygons=f,h})(e,t);throw new Error("invalid geometry")}));return 1===n.length?n[0]:n}},{"../../geometries/geom2":38,"../../geometries/geom3":53,"../../geometries/path2":74,"../../measurements/measureEpsilon":274,"../../utils/flatten":408,"./insertTjunctions":363,"./mergePolygons":364,"./snapPolygons":368,"./triangulatePolygons":369}],362:[function(e,t,n){t.exports={generalize:e("./generalize"),snap:e("./snap"),retessellate:e("./retessellate")}},{"./generalize":361,"./retessellate":366,"./snap":367}],363:[function(e,t,n){const o=e("../../maths/constants"),r=e("../../maths/vec3"),s=e("../../geometries/poly3"),a=e=>`${e}`,i=(e,t,n,o,r,s)=>{const i=a(o),l=a(r),u=`${i}/${l}`,p=`${l}/${i}`;if(e.has(p))return c(e,t,n,r,o,null),null;const f={vertex0:o,vertex1:r,polygonindex:s};return e.has(u)?e.get(u).push(f):e.set(u,[f]),t.has(i)?t.get(i).push(u):t.set(i,[u]),n.has(l)?n.get(l).push(u):n.set(l,[u]),u},c=(e,t,n,o,r,s)=>{const i=a(o),c=a(r),l=`${i}/${c}`;let u=-1;const p=e.get(l);for(let e=0;e{const t=new Map;for(let n=0;n=3){let e=o.vertices[0],s=a(e);for(let i=0;i0){const n=new Map,l=new Map,u=new Map;for(const[e,o]of t)u.set(e,!0),o.forEach((t=>{const o=a(t.vertex0),r=a(t.vertex1);n.has(o)?n.get(o).push(e):n.set(o,[e]),l.has(r)?l.get(r).push(e):l.set(r,[e])}));const p=e.slice(0);for(;0!==t.size;){for(const e of t.keys())u.set(e,!0);let e=!1;for(;;){const f=Array.from(u.keys());if(0===f.length)break;const h=f[0];let m=!0;if(t.has(h)){const f=t.get(h)[0];for(let h=0;h<2;h++){const g=0===h?f.vertex0:f.vertex1,d=0===h?f.vertex1:f.vertex0,y=a(g),v=a(d);let b=[];0===h?l.has(y)&&(b=l.get(y)):n.has(y)&&(b=n.get(y));for(let f=0;f0&&E<1){const g=r.scale(r.create(),b,E);if(r.add(g,g,f),r.squaredDistance(g,y){const t=s.toPoints(e),n=[];for(let e=0;e{const n=`${t.v1}:${t.v2}`;e.set(n,t)},c=(e,t)=>{const n=`${t.v1}:${t.v2}`;e.delete(n)},l=(e,t)=>{const n=`${t.v2}:${t.v1}`;return e.get(n)},u=(e,t,n)=>{let o=e.prev.v1,r=e.prev.v2,s=t.next.v2;const a=h(o,r,s,n);return o=t.prev.v1,r=t.prev.v2,s=e.next.v2,[a,h(o,r,s,n)]},p=r.create(),f=r.create(),h=(e,t,n,o)=>{const s=r.subtract(p,t,e),a=r.subtract(f,n,t);return r.cross(s,s,a),r.dot(s,o)};t.exports=(e,t)=>{const n=[];t.forEach((e=>{const t=n.find((t=>{return n=t[0],r=s.plane(e),Math.abs(n[3]-r[3])<15e-8&&o(n,r);var n,r}));t?t[1].push(e):n.push([s.plane(e),[e]])}));let r=[];return n.forEach((e=>{const t=(e=>{if(e.length<2)return e;const t=e[0].plane,n=e.slice(),o=new Map;for(;n.length>0;){const e=n.shift(),r=a(e);for(let e=0;e=0&&e[1]>=0){const t=s.next,r=n.next;n.prev.next=s.next,n.next.prev=s.prev,s.prev.next=n.next,s.next.prev=n.prev,n.v1=null,n.v2=null,n.next=null,n.prev=null,c(o,s),s.v1=null,s.v2=null,s.next=null,s.prev=null;const a=(e,t,n)=>{const o={v1:n.v1,v2:t.v2,next:t.next,prev:n.prev};n.prev.next=o,t.next.prev=o,c(e,t),t.v1=null,t.v2=null,t.next=null,t.prev=null,c(e,n),n.v1=null,n.v2=null,n.next=null,n.prev=null};0===e[0]&&a(o,t,t.prev),0===e[1]&&a(o,r,r.prev)}}else n.next&&i(o,n)}}const r=[];return o.forEach((e=>{const t=(e=>{let t;const n=[];for(;e.next;){const t=e.next;n.push(e.v1),e.v1=null,e.v2=null,e.next=null,e.prev=null,e=t}return n.length>0&&(t=s.create(n)),t})(e);t&&r.push(t)})),o.clear(),r})(e[1]);r=r.concat(t)})),r}},{"../../geometries/poly3":91,"../../maths/utils/aboutEqualNormals":178,"../../maths/vec3":233}],365:[function(e,t,n){const{EPS:o}=e("../../maths/constants"),r=e("../../maths/line2"),s=e("../../maths/vec2"),a=e("../../maths/OrthoNormalBasis"),i=e("../../maths/utils/interpolateBetween2DPointsForY"),{insertSorted:c,fnNumberSort:l}=e("../../utils"),u=e("../../geometries/poly3");t.exports=e=>{if(e.length<2)return e;const t=[],n=e.length,p=u.plane(e[0]),f=new a(p),h=[],m=[],g=new Map,d=new Map,y=new Map,v=10/o;for(let t=0;t0){let e,i;for(let c=0;ci)&&(i=p);let h=d.get(p);h||(h={},d.set(p,h)),h[t]=!0}if(e>=i)o=[],r=0,a=-1;else{let n=g.get(e);n||(n=[],g.set(e,n)),n.push(t)}}o.reverse(),a=r-a-1,h.push(o),m.push(a)}const b=[];d.forEach(((e,t)=>b.push(t))),b.sort(l);let x=[],A=[];for(let e=0;e=r&&(e=0),o[e][1]!==a)break;s=e}let c=i-1;if(c<0&&(c=r-1),o[c][1]===a&&(i=c),s!==t.leftvertexindex&&s===i)x.splice(e,1),--e;else{t.leftvertexindex=s,t.rightvertexindex=i,t.topleft=o[s],t.topright=o[i];let e=s+1;e>=r&&(e=0),t.bottomleft=o[e];let n=i-1;n<0&&(n=r-1),t.bottomright=o[n]}}}let y;if(e>=b.length-1)x=[],y=null;else{y=Number(b[e+1]);const t=.5*(a+y),n=g.get(a);for(const e in n){const o=n[e],r=h[o],s=r.length,l=m[o];let u=l;for(;;){let e=u+1;if(e>=s&&(e=0),r[e][1]!==a)break;if(e===l)break;u=e}let p=l;for(;;){let e=p-1;if(e<0&&(e=s-1),r[e][1]!==a)break;if(e===u)break;p=e}let f=u+1;f>=s&&(f=0);let g=p-1;g<0&&(g=s-1);const d={polygonindex:o,leftvertexindex:u,rightvertexindex:p,topleft:r[u],topright:r[p],bottomleft:r[f],bottomright:r[g]};c(x,d,((e,n)=>{const o=i(e.topleft,e.bottomleft,t),r=i(n.topleft,n.bottomleft,t);return o>r?1:o0){const e=n[n.length-1],t=s.distance(h.topleft,e.topright),r=s.distance(h.bottomleft,e.bottomright);t0){const e=new Set,a=new Set;for(let t=0;t=0)&&(m||f>=0)&&(i.outpolygon=n.outpolygon,i.leftlinecontinues=h,i.rightlinecontinues=m,e.add(t));break}}}for(let n=0;no&&e.outpolygon.leftpoints.push(e.bottomleft),e.outpolygon.leftpoints.reverse();const r=e.outpolygon.rightpoints.concat(e.outpolygon.leftpoints).map((e=>f.to3D(e))),a=u.fromPointsAndPlane(r,p);a.vertices.length&&t.push(a)}}for(let e=0;eo&&t.outpolygon.rightpoints.push(t.topright))}A=n}return t}},{"../../geometries/poly3":91,"../../maths/OrthoNormalBasis":105,"../../maths/constants":106,"../../maths/line2":117,"../../maths/utils/interpolateBetween2DPointsForY":181,"../../maths/vec2":202,"../../utils":410}],366:[function(e,t,n){const o=e("../../geometries/geom3"),r=e("../../geometries/poly3"),{NEPS:s}=e("../../maths/constants"),a=e("./reTesselateCoplanarPolygons"),i=(e,t)=>(n,o)=>n.plane[e]-o.plane[e]>t?1:o.plane[e]-n.plane[e]>t?-1:0;t.exports=e=>{if(e.isRetesselated)return e;const t=(e=>{let t=[e];const n=[];for(let e=3;e>=0;e--){const o=[],r=3===e?15e-9:s;t.forEach((t=>{t.sort(i(e,r));let s=0;for(let a=1;ar&&(a-s==1?n.push(t[s]):o.push(t.slice(s,a)),s=a);t.length-s==1?n.push(t[s]):o.push(t.slice(s))})),t=o}const o=[];return t.forEach((e=>{e[0]&&(o[e[0].index]=e)})),n.forEach((e=>{o[e.index]=e})),o})(o.toPolygons(e).map(((e,t)=>({vertices:e.vertices,plane:r.plane(e),index:t})))),n=[];t.forEach((e=>{if(Array.isArray(e)){const t=a(e);n.push(...t)}else n.push(e)}));const c=o.create(n);return c.isRetesselated=!0,c}},{"../../geometries/geom3":53,"../../geometries/poly3":91,"../../maths/constants":106,"./reTesselateCoplanarPolygons":365}],367:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../maths/vec2"),s=e("../../geometries/geom2"),a=e("../../geometries/geom3"),i=e("../../geometries/path2"),c=e("../../measurements/measureEpsilon"),l=e("./snapPolygons");t.exports=(...e)=>{if(0===(e=o(e)).length)throw new Error("wrong number of arguments");const t=e.map((e=>i.isA(e)?(e=>{const t=c(e),n=i.toPoints(e).map((e=>r.snap(r.create(),e,t)));return i.create(n)})(e):s.isA(e)?(e=>{const t=c(e);let n=s.toSides(e).map((e=>[r.snap(r.create(),e[0],t),r.snap(r.create(),e[1],t)]));return n=n.filter((e=>!r.equals(e[0],e[1]))),s.create(n)})(e):a.isA(e)?(e=>{const t=c(e),n=a.toPolygons(e),o=l(t,n);return a.create(o)})(e):e));return 1===t.length?t[0]:t}},{"../../geometries/geom2":38,"../../geometries/geom3":53,"../../geometries/path2":74,"../../maths/vec2":202,"../../measurements/measureEpsilon":274,"../../utils/flatten":408,"./snapPolygons":368}],368:[function(e,t,n){const o=e("../../maths/vec3"),r=e("../../geometries/poly3");t.exports=(e,t)=>{let n=t.map((t=>{const n=t.vertices.map((t=>o.snap(o.create(),t,e))),s=[];for(let e=0;e((e,t)=>{const n=Math.abs(r.measureArea(t));return Number.isFinite(n)&&n>e})(s,e))),n}},{"../../geometries/poly3":91,"../../maths/vec3":233}],369:[function(e,t,n){const o=e("../../maths/vec3"),r=e("../../geometries/poly3");t.exports=(e,t)=>{const n=[];return t.forEach((t=>{((e,t,n)=>{const s=t.vertices.length;if(s>3){if(s>4){const a=[0,0,0];t.vertices.forEach((e=>o.add(a,a,e))),o.snap(a,o.divide(a,a,[s,s,s]),e);for(let e=0;e{const o=s(e),r=[0,0,0];for(let e=0;e<3;e++)"center"===t[e]?r[e]=n[e]-(o[0][e]+o[1][e])/2:"max"===t[e]?r[e]=n[e]-o[1][e]:"min"===t[e]&&(r[e]=n[e]-o[0][e]);return a(r,e)};t.exports=(e,...t)=>{e=(e=>{if(!Array.isArray(e.modes)||e.modes.length>3)throw new Error("align(): modes must be an array of length <= 3");if(e.modes=r(e.modes,"none",3),3!==e.modes.filter((e=>["center","max","min","none"].includes(e))).length)throw new Error('align(): all modes must be one of "center", "max" or "min"');if(!Array.isArray(e.relativeTo)||e.relativeTo.length>3)throw new Error("align(): relativeTo must be an array of length <= 3");if(e.relativeTo=r(e.relativeTo,0,3),3!==e.relativeTo.filter((e=>Number.isFinite(e)||null==e)).length)throw new Error("align(): all relativeTo values must be a number, or null.");if("boolean"!=typeof e.grouped)throw new Error("align(): grouped must be a boolean value.");return e})(e=Object.assign({},{modes:["center","center","min"],relativeTo:[0,0,0],grouped:!1},e));let{modes:n,relativeTo:a,grouped:c}=e;if(0===(t=o(t)).length)throw new Error("align(): No geometries were provided to act upon");if(a.filter((e=>null==e)).length){const e=s(t);a=((e,t,n)=>{for(let o=0;o<3;o++)null==e[o]&&("center"===t[o]?e[o]=(n[0][o]+n[1][o])/2:"max"===t[o]?e[o]=n[1][o]:"min"===t[o]&&(e[o]=n[0][o]));return e})(a,n,e)}return 1===(t=c?i(t,n,a):t.map((e=>i(e,n,a)))).length?t[0]:t}},{"../../measurements/measureAggregateBoundingBox":265,"../../utils/flatten":408,"../../utils/padArrayToLength":412,"./translate":377}],371:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../geometries/geom2"),s=e("../../geometries/geom3"),a=e("../../geometries/path2"),i=e("../../measurements/measureBoundingBox"),{translate:c}=e("./translate"),l=(e,...t)=>{const{axes:n,relativeTo:l}=Object.assign({},{axes:[!0,!0,!0],relativeTo:[0,0,0]},e);if(0===(t=o(t)).length)throw new Error("wrong number of arguments");if(3!==l.length)throw new Error("relativeTo must be an array of length 3");e={axes:n,relativeTo:l};const u=t.map((t=>a.isA(t)||r.isA(t)||s.isA(t)?((e,t)=>{const{axes:n,relativeTo:o}=Object.assign({},{axes:[!0,!0,!0],relativeTo:[0,0,0]},e),r=i(t),s=[0,0,0];return n[0]&&(s[0]=o[0]-(r[0][0]+(r[1][0]-r[0][0])/2)),n[1]&&(s[1]=o[1]-(r[0][1]+(r[1][1]-r[0][1])/2)),n[2]&&(s[2]=o[2]-(r[0][2]+(r[1][2]-r[0][2])/2)),c(s,t)})(e,t):t));return 1===u.length?u[0]:u};t.exports={center:l,centerX:(...e)=>l({axes:[!0,!1,!1]},e),centerY:(...e)=>l({axes:[!1,!0,!1]},e),centerZ:(...e)=>l({axes:[!1,!1,!0]},e)}},{"../../geometries/geom2":38,"../../geometries/geom3":53,"../../geometries/path2":74,"../../measurements/measureBoundingBox":269,"../../utils/flatten":408,"./translate":377}],372:[function(e,t,n){t.exports={align:e("./align"),center:e("./center").center,centerX:e("./center").centerX,centerY:e("./center").centerY,centerZ:e("./center").centerZ,mirror:e("./mirror").mirror,mirrorX:e("./mirror").mirrorX,mirrorY:e("./mirror").mirrorY,mirrorZ:e("./mirror").mirrorZ,rotate:e("./rotate").rotate,rotateX:e("./rotate").rotateX,rotateY:e("./rotate").rotateY,rotateZ:e("./rotate").rotateZ,scale:e("./scale").scale,scaleX:e("./scale").scaleX,scaleY:e("./scale").scaleY,scaleZ:e("./scale").scaleZ,transform:e("./transform"),translate:e("./translate").translate,translateX:e("./translate").translateX,translateY:e("./translate").translateY,translateZ:e("./translate").translateZ}},{"./align":370,"./center":371,"./mirror":373,"./rotate":374,"./scale":375,"./transform":376,"./translate":377}],373:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../maths/mat4"),s=e("../../maths/plane"),a=e("../../geometries/geom2"),i=e("../../geometries/geom3"),c=e("../../geometries/path2"),l=(e,...t)=>{const{origin:n,normal:l}=Object.assign({},{origin:[0,0,0],normal:[0,0,1]},e);if(0===(t=o(t)).length)throw new Error("wrong number of arguments");const u=s.fromNormalAndPoint(s.create(),l,n);if(Number.isNaN(u[0]))throw new Error("the given origin and normal do not define a proper plane");const p=r.mirrorByPlane(r.create(),u),f=t.map((e=>c.isA(e)?c.transform(p,e):a.isA(e)?a.transform(p,e):i.isA(e)?i.transform(p,e):e));return 1===f.length?f[0]:f};t.exports={mirror:l,mirrorX:(...e)=>l({normal:[1,0,0]},e),mirrorY:(...e)=>l({normal:[0,1,0]},e),mirrorZ:(...e)=>l({normal:[0,0,1]},e)}},{"../../geometries/geom2":38,"../../geometries/geom3":53,"../../geometries/path2":74,"../../maths/mat4":155,"../../maths/plane":174,"../../utils/flatten":408}],374:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../maths/mat4"),s=e("../../geometries/geom2"),a=e("../../geometries/geom3"),i=e("../../geometries/path2"),c=(e,...t)=>{if(!Array.isArray(e))throw new Error("angles must be an array");if(0===(t=o(t)).length)throw new Error("wrong number of arguments");for(e=e.slice();e.length<3;)e.push(0);const n=e[2],c=e[1],l=e[0],u=r.fromTaitBryanRotation(r.create(),n,c,l),p=t.map((e=>i.isA(e)?i.transform(u,e):s.isA(e)?s.transform(u,e):a.isA(e)?a.transform(u,e):e));return 1===p.length?p[0]:p};t.exports={rotate:c,rotateX:(e,...t)=>c([e,0,0],t),rotateY:(e,...t)=>c([0,e,0],t),rotateZ:(e,...t)=>c([0,0,e],t)}},{"../../geometries/geom2":38,"../../geometries/geom3":53,"../../geometries/path2":74,"../../maths/mat4":155,"../../utils/flatten":408}],375:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../maths/mat4"),s=e("../../geometries/geom2"),a=e("../../geometries/geom3"),i=e("../../geometries/path2"),c=(e,...t)=>{if(!Array.isArray(e))throw new Error("factors must be an array");if(0===(t=o(t)).length)throw new Error("wrong number of arguments");for(e=e.slice();e.length<3;)e.push(1);if(e[0]<=0||e[1]<=0||e[2]<=0)throw new Error("factors must be positive");const n=r.fromScaling(r.create(),e),c=t.map((e=>i.isA(e)?i.transform(n,e):s.isA(e)?s.transform(n,e):a.isA(e)?a.transform(n,e):e));return 1===c.length?c[0]:c};t.exports={scale:c,scaleX:(e,...t)=>c([e,1,1],t),scaleY:(e,...t)=>c([1,e,1],t),scaleZ:(e,...t)=>c([1,1,e],t)}},{"../../geometries/geom2":38,"../../geometries/geom3":53,"../../geometries/path2":74,"../../maths/mat4":155,"../../utils/flatten":408}],376:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../geometries/geom2"),s=e("../../geometries/geom3"),a=e("../../geometries/path2");t.exports=(e,...t)=>{if(0===(t=o(t)).length)throw new Error("wrong number of arguments");const n=t.map((t=>a.isA(t)?a.transform(e,t):r.isA(t)?r.transform(e,t):s.isA(t)?s.transform(e,t):t));return 1===n.length?n[0]:n}},{"../../geometries/geom2":38,"../../geometries/geom3":53,"../../geometries/path2":74,"../../utils/flatten":408}],377:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../maths/mat4"),s=e("../../geometries/geom2"),a=e("../../geometries/geom3"),i=e("../../geometries/path2"),c=(e,...t)=>{if(!Array.isArray(e))throw new Error("offset must be an array");if(0===(t=o(t)).length)throw new Error("wrong number of arguments");for(e=e.slice();e.length<3;)e.push(0);const n=r.fromTranslation(r.create(),e),c=t.map((e=>i.isA(e)?i.transform(n,e):s.isA(e)?s.transform(n,e):a.isA(e)?a.transform(n,e):e));return 1===c.length?c[0]:c};t.exports={translate:c,translateX:(e,...t)=>c([e,0,0],t),translateY:(e,...t)=>c([0,e,0],t),translateZ:(e,...t)=>c([0,0,e],t)}},{"../../geometries/geom2":38,"../../geometries/geom3":53,"../../geometries/path2":74,"../../maths/mat4":155,"../../utils/flatten":408}],378:[function(e,t,n){const{EPS:o,TAU:r}=e("../maths/constants"),s=e("../maths/vec2"),a=e("../geometries/path2"),{isGT:i,isGTE:c,isNumberArray:l}=e("./commonChecks");t.exports=e=>{const t={center:[0,0],radius:1,startAngle:0,endAngle:r,makeTangent:!1,segments:32};let{center:n,radius:u,startAngle:p,endAngle:f,makeTangent:h,segments:m}=Object.assign({},t,e);if(!l(n,2))throw new Error("center must be an array of X and Y values");if(!i(u,0))throw new Error("radius must be greater than zero");if(!c(p,0))throw new Error("startAngle must be positive");if(!c(f,0))throw new Error("endAngle must be positive");if(!c(m,4))throw new Error("segments must be four or more");p%=r,f%=r;let g=r;pf&&(g=f+(r-p));const d=Math.acos((u*u+u*u-o*o)/(2*u*u)),y=s.clone(n);let v;const b=[];if(g.25&&(t=.25);const n=h?e+2:e;for(let o=0;o<=n;o++){let n=o;h&&(n=(o-1)*(e-2*t)/e+t,n<0&&(n=0),n>e&&(n=e));const r=p+n*(g/e);v=s.fromAngleRadians(s.create(),r),s.scale(v,v,u),s.add(v,v,y),b.push(v)}}return a.fromPoints({closed:!1},b)}},{"../geometries/path2":74,"../maths/constants":106,"../maths/vec2":202,"./commonChecks":380}],379:[function(e,t,n){const{TAU:o}=e("../maths/constants"),r=e("./ellipse"),{isGTE:s}=e("./commonChecks");t.exports=e=>{const t={center:[0,0],radius:1,startAngle:0,endAngle:o,segments:32};let{center:n,radius:a,startAngle:i,endAngle:c,segments:l}=Object.assign({},t,e);if(!s(a,0))throw new Error("radius must be positive");return a=[a,a],r({center:n,radius:a,startAngle:i,endAngle:c,segments:l})}},{"../maths/constants":106,"./commonChecks":380,"./ellipse":385}],380:[function(e,t,n){t.exports={isNumberArray:(e,t)=>!!(Array.isArray(e)&&e.length>=t)&&e.every((e=>Number.isFinite(e))),isGT:(e,t)=>Number.isFinite(e)&&e>t,isGTE:(e,t)=>Number.isFinite(e)&&e>=t}},{}],381:[function(e,t,n){const o=e("./cuboid"),{isGTE:r}=e("./commonChecks");t.exports=e=>{let{center:t,size:n}=Object.assign({},{center:[0,0,0],size:2},e);if(!r(n,0))throw new Error("size must be positive");return n=[n,n,n],o({center:t,size:n})}},{"./commonChecks":380,"./cuboid":382}],382:[function(e,t,n){const o=e("../geometries/geom3"),r=e("../geometries/poly3"),{isNumberArray:s}=e("./commonChecks");t.exports=e=>{const{center:t,size:n}=Object.assign({},{center:[0,0,0],size:[2,2,2]},e);if(!s(t,3))throw new Error("center must be an array of X, Y and Z values");if(!s(n,3))throw new Error("size must be an array of width, depth and height values");if(!n.every((e=>e>=0)))throw new Error("size values must be positive");return 0===n[0]||0===n[1]||0===n[2]?o.create():o.create([[[0,4,6,2],[-1,0,0]],[[1,3,7,5],[1,0,0]],[[0,1,5,4],[0,-1,0]],[[2,6,7,3],[0,1,0]],[[0,2,3,1],[0,0,-1]],[[4,5,7,6],[0,0,1]]].map((e=>{const o=e[0].map((e=>[t[0]+n[0]/2*(2*!!(1&e)-1),t[1]+n[1]/2*(2*!!(2&e)-1),t[2]+n[2]/2*(2*!!(4&e)-1)]));return r.create(o)})))}},{"../geometries/geom3":53,"../geometries/poly3":91,"./commonChecks":380}],383:[function(e,t,n){const o=e("../geometries/geom3"),r=e("./cylinderElliptic"),{isGTE:s}=e("./commonChecks");t.exports=e=>{const{center:t,height:n,radius:a,segments:i}=Object.assign({},{center:[0,0,0],height:2,radius:1,segments:32},e);if(!s(a,0))throw new Error("radius must be positive");return 0===n||0===a?o.create():r({center:t,height:n,startRadius:[a,a],endRadius:[a,a],segments:i})}},{"../geometries/geom3":53,"./commonChecks":380,"./cylinderElliptic":384}],384:[function(e,t,n){const{EPS:o,TAU:r}=e("../maths/constants"),s=e("../maths/vec3"),a=e("../geometries/geom3"),i=e("../geometries/poly3"),{sin:c,cos:l}=e("../maths/utils/trigonometry"),{isGT:u,isGTE:p,isNumberArray:f}=e("./commonChecks");t.exports=e=>{const t={center:[0,0,0],height:2,startRadius:[1,1],startAngle:0,endRadius:[1,1],endAngle:r,segments:32};let{center:n,height:h,startRadius:m,startAngle:g,endRadius:d,endAngle:y,segments:v}=Object.assign({},t,e);if(!f(n,3))throw new Error("center must be an array of X, Y and Z values");if(!u(h,0))throw new Error("height must be greater then zero");if(!f(m,2))throw new Error("startRadius must be an array of X and Y values");if(!m.every((e=>e>=0)))throw new Error("startRadius values must be positive");if(!f(d,2))throw new Error("endRadius must be an array of X and Y values");if(!d.every((e=>e>=0)))throw new Error("endRadius values must be positive");if(d.every((e=>0===e))&&m.every((e=>0===e)))throw new Error("at least one radius must be positive");if(!p(g,0))throw new Error("startAngle must be positive");if(!p(y,0))throw new Error("endAngle must be positive");if(!p(v,4))throw new Error("segments must be four or more");g%=r,y%=r;let b=r;gy&&(b=y+(r-g));const x=Math.min(m[0],m[1],d[0],d[1]),A=Math.acos((x*x+x*x-o*o)/(2*x*x));if(b{const o=t*b+g;return s.scale(C,P,n[0]*l(o)),s.scale(M,D,n[1]*c(o)),s.add(C,C,M),s.scale(R,T,e),s.add(R,R,w),s.add(s.create(),C,R)},L=(...e)=>{const t=e.map((e=>s.add(s.create(),e,n)));return i.create(t)},B=[];for(let e=0;e0&&m[1]>0&&B.push(L(w,I(0,n,m),I(0,t,m))),(m[0]>0||m[1]>0)&&B.push(L(I(0,t,m),I(0,n,m),I(1,t,d))),d[0]>0&&d[1]>0&&B.push(L(S,I(1,t,d),I(1,n,d))),(d[0]>0||d[1]>0)&&B.push(L(I(1,t,d),I(0,n,m),I(1,n,d))))}return b{const t={center:[0,0],radius:[1,1],startAngle:0,endAngle:r,segments:32};let{center:n,radius:p,startAngle:f,endAngle:h,segments:m}=Object.assign({},t,e);if(!u(n,2))throw new Error("center must be an array of X and Y values");if(!u(p,2))throw new Error("radius must be an array of X and Y values");if(!p.every((e=>e>=0)))throw new Error("radius values must be positive");if(!l(f,0))throw new Error("startAngle must be positive");if(!l(h,0))throw new Error("endAngle must be positive");if(!l(m,3))throw new Error("segments must be three or more");if(0===p[0]||0===p[1])return a.create();f%=r,h%=r;let g=r;fh&&(g=h+(r-f));const d=Math.min(p[0],p[1]);if(g{const{center:t,radius:n,segments:p,axes:f}=Object.assign({},{center:[0,0,0],radius:[1,1,1],segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},e);if(!u(t,3))throw new Error("center must be an array of X, Y and Z values");if(!u(n,3))throw new Error("radius must be an array of X, Y and Z values");if(!n.every((e=>e>=0)))throw new Error("radius values must be positive");if(!l(p,4))throw new Error("segments must be four or more");if(0===n[0]||0===n[1]||0===n[2])return s.create();const h=r.scale(r.create(),r.normalize(r.create(),f[0]),n[0]),m=r.scale(r.create(),r.normalize(r.create(),f[1]),n[1]),g=r.scale(r.create(),r.normalize(r.create(),f[2]),n[2]),d=Math.round(p/4);let y;const v=[],b=r.create(),x=r.create();for(let e=0;e<=p;e++){const n=o*e/p,s=r.add(r.create(),r.scale(b,h,c(n)),r.scale(x,m,i(n)));if(e>0){let e,n;for(let l=0;l<=d;l++){const u=o/4*l/d,p=c(u),f=i(u);if(l>0){let o,i=[];o=r.subtract(r.create(),r.scale(b,y,e),r.scale(x,g,n)),i.push(r.add(o,o,t)),o=r.subtract(r.create(),r.scale(b,s,e),r.scale(x,g,n)),i.push(r.add(o,o,t)),l{let{radius:t,frequency:n}=Object.assign({},{radius:1,frequency:6},e);if(!i(t,0))throw new Error("radius must be positive");if(!i(n,6))throw new Error("frequency must be six or more");if(0===t)return s.create();n=Math.floor(n/6);const c=[[.850651,0,-.525731],[.850651,-0,.525731],[-.850651,-0,.525731],[-.850651,0,-.525731],[0,-.525731,.850651],[0,.525731,.850651],[0,.525731,-.850651],[0,-.525731,-.850651],[-.525731,-.850651,-0],[.525731,-.850651,-0],[.525731,.850651,0],[-.525731,.850651,0]],l=[[0,9,1],[1,10,0],[6,7,0],[10,6,0],[7,9,0],[5,1,4],[4,1,9],[5,10,1],[2,8,3],[3,11,2],[2,5,4],[4,8,2],[2,11,5],[3,7,6],[6,11,3],[8,7,3],[9,8,4],[11,10,5],[10,11,6],[8,9,7]],u=(e,t,n)=>{const o=e[0],s=e[1],a=e[2];let i=n;const c=[],l=[];for(let e=0;e{const o=1-n,r=[];for(let s=0;s<3;s++)r[s]=e[s]*o+t[s]*n;return r};let f=[],h=[],m=0;for(let e=0;e{if(!Array.isArray(e))throw new Error("points must be an array");return o.fromPoints({},e)}},{"../geometries/path2":74}],390:[function(e,t,n){const o=e("../geometries/geom2");t.exports=e=>{const{points:t,paths:n}=Object.assign({},{points:[],paths:[]},e);if(!Array.isArray(t)||!Array.isArray(n))throw new Error("points and paths must be arrays");let r=t;Array.isArray(t[0])&&(Array.isArray(t[0][0])||(r=[t])),r.forEach(((e,t)=>{if(!Array.isArray(e))throw new Error("list of points "+t+" must be an array");if(e.length<3)throw new Error("list of points "+t+" must contain three or more points");e.forEach(((e,n)=>{if(!Array.isArray(e))throw new Error("list of points "+t+", point "+n+" must be an array");if(e.length<2)throw new Error("list of points "+t+", point "+n+" must contain by X and Y values")}))}));let s=n;if(0===n.length){let e=0;s=r.map((t=>t.map((t=>e++))))}const a=[];r.forEach((e=>e.forEach((e=>a.push(e)))));let i=[];return s.forEach((e=>{const t=e.map((e=>a[e])),n=o.fromPoints(t);i=i.concat(o.toSides(n))})),o.create(i)}},{"../geometries/geom2":38}],391:[function(e,t,n){const o=e("../geometries/geom3"),r=e("../geometries/poly3"),{isNumberArray:s}=e("./commonChecks");t.exports=e=>{const{points:t,faces:n,colors:a,orientation:i}=Object.assign({},{points:[],faces:[],colors:void 0,orientation:"outward"},e);if(!Array.isArray(t)||!Array.isArray(n))throw new Error("points and faces must be arrays");if(t.length<3)throw new Error("three or more points are required");if(n.length<1)throw new Error("one or more faces are required");if(a){if(!Array.isArray(a))throw new Error("colors must be an array");if(a.length!==n.length)throw new Error("faces and colors must have the same length")}t.forEach(((e,t)=>{if(!s(e,3))throw new Error(`point ${t} must be an array of X, Y, Z values`)})),n.forEach(((e,t)=>{if(e.length<3)throw new Error(`face ${t} must contain 3 or more indexes`);if(!s(e,e.length))throw new Error(`face ${t} must be an array of numbers`)})),"outward"!==i&&n.forEach((e=>e.reverse()));const c=n.map(((e,n)=>{const o=r.create(e.map((e=>t[e])));return a&&a[n]&&(o.color=a[n]),o}));return o.create(c)}},{"../geometries/geom3":53,"../geometries/poly3":91,"./commonChecks":380}],392:[function(e,t,n){const o=e("../maths/vec2"),r=e("../geometries/geom2"),{isNumberArray:s}=e("./commonChecks");t.exports=e=>{const{center:t,size:n}=Object.assign({},{center:[0,0],size:[2,2]},e);if(!s(t,2))throw new Error("center must be an array of X and Y values");if(!s(n,2))throw new Error("size must be an array of X and Y values");if(!n.every((e=>e>=0)))throw new Error("size values must be positive");if(0===n[0]||0===n[1])return r.create();const a=[n[0]/2,n[1]/2],i=[a[0],-a[1]],c=[o.subtract(o.create(),t,a),o.add(o.create(),t,i),o.add(o.create(),t,a),o.subtract(o.create(),t,i)];return r.fromPoints(c)}},{"../geometries/geom2":38,"../maths/vec2":202,"./commonChecks":380}],393:[function(e,t,n){const{EPS:o,TAU:r}=e("../maths/constants"),s=e("../maths/vec2"),a=e("../maths/vec3"),i=e("../geometries/geom3"),c=e("../geometries/poly3"),{sin:l,cos:u}=e("../maths/utils/trigonometry"),{isGTE:p,isNumberArray:f}=e("./commonChecks"),h=e("./cuboid"),m=(e,t,n,i,c,p)=>{const f=r/4*c/i,h=u(f),m=l(f),g=i-c;let d=n*h,y=t[2]-(n-n*m);p||(y=n-n*m-t[2]),d=d>o?d:0;const v=a.add(a.create(),e,[t[0]-n,t[1]-n,y]),b=a.add(a.create(),e,[n-t[0],t[1]-n,y]),x=a.add(a.create(),e,[n-t[0],n-t[1],y]),A=a.add(a.create(),e,[t[0]-n,n-t[1],y]),E=[],w=[],S=[],T=[];for(let e=0;e<=g;e++){const t=g>0?r/4*e/g:0,n=s.fromAngleRadians(s.create(),t);s.scale(n,n,d);const o=a.fromVec2(a.create(),n);E.push(a.add(a.create(),v,o)),a.rotateZ(o,o,[0,0,0],r/4),w.push(a.add(a.create(),b,o)),a.rotateZ(o,o,[0,0,0],r/4),S.push(a.add(a.create(),x,o)),a.rotateZ(o,o,[0,0,0],r/4),T.push(a.add(a.create(),A,o))}return p?[E,w,S,T]:(E.reverse(),w.reverse(),S.reverse(),T.reverse(),[T,S,w,E])},g=(e,t)=>{const n=[];for(let o=0;o{const n=[];for(let o=0;o{e=(e=[e[3],e[2],e[1],e[0]]).map((e=>e.slice().reverse()));const n=[];e.forEach((e=>{e.forEach((e=>n.push(e)))}));const o=[];t.forEach((e=>{e.forEach((e=>o.push(e)))}));const r=[];for(let e=0;e{let{center:t,size:n,roundRadius:r,segments:s}=Object.assign({},{center:[0,0,0],size:[2,2,2],roundRadius:.2,segments:32},e);if(!f(t,3))throw new Error("center must be an array of X, Y and Z values");if(!f(n,3))throw new Error("size must be an array of X, Y and Z values");if(!n.every((e=>e>=0)))throw new Error("size values must be positive");if(!p(r,0))throw new Error("roundRadius must be positive");if(!p(s,4))throw new Error("segments must be four or more");if(0===n[0]||0===n[1]||0===n[2])return i.create();if(0===r)return h({center:t,size:n});if(n=n.map((e=>e/2)),r>n[0]-o||r>n[1]-o||r>n[2]-o)throw new Error("roundRadius must be smaller then the radius of all dimensions");s=Math.floor(s/4);let a=null,l=null,u=[];for(let e=0;e<=s;e++){const o=m(t,n,r,s,e,!0),i=m(t,n,r,s,e,!1);if(0===e&&(u=u.concat(y(i,o))),a&&(u=u.concat(g(a,o),d(a,o))),l&&(u=u.concat(g(l,i),d(l,i))),e===s){let e=o.map((e=>e[0]));u.push(c.create(e)),e=i.map((e=>e[0])),u.push(c.create(e))}a=o,l=i}return i.create(u)}},{"../geometries/geom3":53,"../geometries/poly3":91,"../maths/constants":106,"../maths/utils/trigonometry":184,"../maths/vec2":202,"../maths/vec3":233,"./commonChecks":380,"./cuboid":382}],394:[function(e,t,n){const{EPS:o,TAU:r}=e("../maths/constants"),s=e("../maths/vec3"),a=e("../geometries/geom3"),i=e("../geometries/poly3"),{sin:c,cos:l}=e("../maths/utils/trigonometry"),{isGTE:u,isNumberArray:p}=e("./commonChecks"),f=e("./cylinder");t.exports=e=>{const{center:t,height:n,radius:h,roundRadius:m,segments:g}=Object.assign({},{center:[0,0,0],height:2,radius:1,roundRadius:.2,segments:32},e);if(!p(t,3))throw new Error("center must be an array of X, Y and Z values");if(!u(n,0))throw new Error("height must be positive");if(!u(h,0))throw new Error("radius must be positive");if(!u(m,0))throw new Error("roundRadius must be positive");if(m>h)throw new Error("roundRadius must be smaller then the radius");if(!u(g,4))throw new Error("segments must be four or more");if(0===n||0===h)return a.create();if(0===m)return f({center:t,height:n,radius:h});const d=[0,0,-n/2],y=[0,0,n/2],v=s.subtract(s.create(),y,d);if(2*m>s.length(v)-o)throw new Error("height must be larger than twice roundRadius");let b;b=Math.abs(v[0])>Math.abs(v[1])?s.fromValues(0,1,0):s.fromValues(1,0,0);const x=s.scale(s.create(),s.normalize(s.create(),v),m),A=s.scale(s.create(),s.normalize(s.create(),s.cross(s.create(),x,b)),h),E=s.scale(s.create(),s.normalize(s.create(),s.cross(s.create(),A,x)),h);s.add(d,d,x),s.subtract(y,y,x);const w=Math.floor(.25*g),S=e=>{const n=e.map((e=>s.add(e,e,t)));return i.create(n)},T=[],P=s.create(),D=s.create();let C;for(let e=0;e<=g;e++){const t=r*e/g,n=s.add(s.create(),s.scale(P,A,l(t)),s.scale(D,E,c(t)));if(e>0){let e,t,o=[];o.push(s.add(s.create(),d,n)),o.push(s.add(s.create(),d,C)),o.push(s.add(s.create(),y,C)),o.push(s.add(s.create(),y,n)),T.push(S(o));for(let a=0;a<=w;a++){const i=r/4*a/w,u=l(i),p=c(i);if(a>0){let r;o=[],r=s.add(s.create(),d,s.subtract(P,s.scale(P,C,e),s.scale(D,x,t))),o.push(r),r=s.add(s.create(),d,s.subtract(P,s.scale(P,n,e),s.scale(D,x,t))),o.push(r),a{let{center:t,size:n,roundRadius:u,segments:p}=Object.assign({},{center:[0,0],size:[2,2],roundRadius:.2,segments:32},e);if(!c(t,2))throw new Error("center must be an array of X and Y values");if(!c(n,2))throw new Error("size must be an array of X and Y values");if(!n.every((e=>e>=0)))throw new Error("size values must be positive");if(!i(u,0))throw new Error("roundRadius must be positive");if(!i(p,4))throw new Error("segments must be four or more");if(0===n[0]||0===n[1])return a.create();if(0===u)return l({center:t,size:n});if(n=n.map((e=>e/2)),u>n[0]-o||u>n[1]-o)throw new Error("roundRadius must be smaller then the radius of all dimensions");const f=Math.floor(p/4),h=s.add(s.create(),t,[n[0]-u,n[1]-u]),m=s.add(s.create(),t,[u-n[0],n[1]-u]),g=s.add(s.create(),t,[u-n[0],u-n[1]]),d=s.add(s.create(),t,[n[0]-u,u-n[1]]),y=[],v=[],b=[],x=[];for(let e=0;e<=f;e++){const t=r/4*e/f,n=s.fromAngleRadians(s.create(),t);s.scale(n,n,u),y.push(s.add(s.create(),h,n)),s.rotate(n,n,s.create(),r/4),v.push(s.add(s.create(),m,n)),s.rotate(n,n,s.create(),r/4),b.push(s.add(s.create(),g,n)),s.rotate(n,n,s.create(),r/4),x.push(s.add(s.create(),d,n))}return a.fromPoints(y.concat(v,b,x))}},{"../geometries/geom2":38,"../maths/constants":106,"../maths/vec2":202,"./commonChecks":380,"./rectangle":392}],396:[function(e,t,n){const o=e("./ellipsoid"),{isGTE:r}=e("./commonChecks");t.exports=e=>{let{center:t,radius:n,segments:s,axes:a}=Object.assign({},{center:[0,0,0],radius:1,segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},e);if(!r(n,0))throw new Error("radius must be positive");return n=[n,n,n],o({center:t,radius:n,segments:s,axes:a})}},{"./commonChecks":380,"./ellipsoid":386}],397:[function(e,t,n){const o=e("./rectangle"),{isGTE:r}=e("./commonChecks");t.exports=e=>{let{center:t,size:n}=Object.assign({},{center:[0,0],size:2},e);if(!r(n,0))throw new Error("size must be positive");return n=[n,n],o({center:t,size:n})}},{"./commonChecks":380,"./rectangle":392}],398:[function(e,t,n){const{TAU:o}=e("../maths/constants"),r=e("../maths/vec2"),s=e("../geometries/geom2"),{isGT:a,isGTE:i,isNumberArray:c}=e("./commonChecks"),l=(e,t,n,s)=>{const a=o/e,i=[];for(let o=0;o{let{center:t,vertices:n,outerRadius:u,innerRadius:p,density:f,startAngle:h}=Object.assign({},{center:[0,0],vertices:5,outerRadius:1,innerRadius:0,density:2,startAngle:0},e);if(!c(t,2))throw new Error("center must be an array of X and Y values");if(!i(n,2))throw new Error("vertices must be two or more");if(!a(u,0))throw new Error("outerRadius must be greater than zero");if(!i(p,0))throw new Error("innerRadius must be greater than zero");if(!i(h,0))throw new Error("startAngle must be greater than zero");if(n=Math.floor(n),f=Math.floor(f),h%=o,0===p){if(!i(f,2))throw new Error("density must be two or more");p=u*((e,t)=>e>0&&t>1&&t{const t={innerRadius:1,innerSegments:32,outerRadius:4,outerSegments:32,innerRotation:0,startAngle:0,outerRotation:o},{innerRadius:n,innerSegments:u,outerRadius:p,outerSegments:f,innerRotation:h,startAngle:m,outerRotation:g}=Object.assign({},t,e);if(!c(n,0))throw new Error("innerRadius must be greater than zero");if(!l(u,3))throw new Error("innerSegments must be three or more");if(!c(p,0))throw new Error("outerRadius must be greater than zero");if(!l(f,3))throw new Error("outerSegments must be three or more");if(!l(m,0))throw new Error("startAngle must be positive");if(!c(g,0))throw new Error("outerRotation must be greater than zero");if(n>=p)throw new Error("inner circle is two large to rotate about the outer circle");let d=i({radius:n,segments:u});return 0!==h&&(d=s([0,0,h],d)),d=a([p,0],d),r({startAngle:m,angle:g,segments:f},d)}},{"../maths/constants":106,"../operations/extrusions/extrudeRotate":327,"../operations/transforms/rotate":374,"../operations/transforms/translate":377,"./circle":379,"./commonChecks":380}],400:[function(e,t,n){const{NEPS:o}=e("../maths/constants"),r=e("../maths/vec2"),s=e("../geometries/geom2"),{isNumberArray:a}=e("./commonChecks"),i=(e,t,n)=>Math.acos((e*e+t*t-n*n)/(2*e*t)),c=(e,t,n,o,a,i)=>{const c=r.fromValues(0,0),l=r.fromValues(i,0),u=r.fromValues(o,0);return r.add(u,r.rotate(u,u,[0,0],Math.PI-t),l),s.fromPoints([c,l,u])};t.exports=e=>{let{type:t,values:n}=Object.assign({},{type:"SSS",values:[1,1,1]},e);if("string"!=typeof t)throw new Error("triangle type must be a string");if(t=t.toUpperCase(),"A"!==t[0]&&"S"!==t[0]||"A"!==t[1]&&"S"!==t[1]||"A"!==t[2]&&"S"!==t[2])throw new Error("triangle type must contain three letters; A or S");if(!a(n,3))throw new Error("triangle values must contain three values");if(!n.every((e=>e>0)))throw new Error("triangle values must be greater than zero");switch(t){case"AAA":return(e=>{if(Math.abs(e[0]+e[1]+e[2]-Math.PI)>o)throw new Error("AAA triangles require angles that sum to PI");const t=e[0],n=e[1],r=Math.PI-t-n,s=1/Math.sin(r)*Math.sin(t),a=1/Math.sin(r)*Math.sin(n);return c(t,n,r,s,a,1)})(n);case"AAS":return(e=>{const t=e[0],n=e[1],r=Math.PI+o-t-n;if(r{const t=e[0],n=e[2],r=Math.PI+o-t-n;if(r{const t=e[0],n=e[1],r=e[2],s=((e,t,n)=>t>o?Math.sqrt(e*e+n*n-2*e*n*Math.cos(t)):Math.sqrt((e-n)*(e-n)+e*n*t*t*(1-t*t/12)))(t,n,r),a=i(s,t,r),l=Math.PI-a-n;return c(a,n,l,r,s,t)})(n);case"SSA":return(e=>{const t=e[0],n=e[1],o=e[2],r=Math.asin(n*Math.sin(o)/t),s=Math.PI-r-o,a=t/Math.sin(o)*Math.sin(s);return c(r,s,o,n,a,t)})(n);case"SSS":return(e=>{const t=e[1],n=e[2],o=e[0];if(t+n<=o||n+o<=t||o+t<=n)throw new Error("SSS triangle is incorrect, as the longest side is longer than the sum of the other sides");const r=i(n,o,t),s=i(o,t,n),a=Math.PI-r-s;return c(r,s,a,t,n,o)})(n);default:throw new Error("invalid triangle type, try again")}}},{"../geometries/geom2":38,"../maths/constants":106,"../maths/vec2":202,"./commonChecks":380}],401:[function(e,t,n){t.exports={height:14,32:[16],33:[10,5,21,5,7,void 0,5,2,4,1,5,0,6,1,5,2],34:[16,4,21,4,14,void 0,12,21,12,14],35:[21,11,25,4,-7,void 0,17,25,10,-7,void 0,4,12,18,12,void 0,3,6,17,6],36:[20,8,25,8,-4,void 0,12,25,12,-4,void 0,17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3],37:[24,21,21,3,0,void 0,8,21,10,19,10,17,9,15,7,14,5,14,3,16,3,18,4,20,6,21,8,21,10,20,13,19,16,19,19,20,21,21,void 0,17,7,15,6,14,4,14,2,16,0,18,0,20,1,21,3,21,5,19,7,17,7],38:[26,23,12,23,13,22,14,21,14,20,13,19,11,17,6,15,3,13,1,11,0,7,0,5,1,4,2,3,4,3,6,4,8,5,9,12,13,13,14,14,16,14,18,13,20,11,21,9,20,8,18,8,16,9,13,11,10,16,3,18,1,20,0,22,0,23,1,23,2],39:[10,5,19,4,20,5,21,6,20,6,18,5,16,4,15],40:[14,11,25,9,23,7,20,5,16,4,11,4,7,5,2,7,-2,9,-5,11,-7],41:[14,3,25,5,23,7,20,9,16,10,11,10,7,9,2,7,-2,5,-5,3,-7],42:[16,8,21,8,9,void 0,3,18,13,12,void 0,13,18,3,12],43:[26,13,18,13,0,void 0,4,9,22,9],44:[10,6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4],45:[26,4,9,22,9],46:[10,5,2,4,1,5,0,6,1,5,2],47:[22,20,25,2,-7],48:[20,9,21,6,20,4,17,3,12,3,9,4,4,6,1,9,0,11,0,14,1,16,4,17,9,17,12,16,17,14,20,11,21,9,21],49:[20,6,17,8,18,11,21,11,0],50:[20,4,16,4,17,5,19,6,20,8,21,12,21,14,20,15,19,16,17,16,15,15,13,13,10,3,0,17,0],51:[20,5,21,16,21,10,13,13,13,15,12,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4],52:[20,13,21,3,7,18,7,void 0,13,21,13,0],53:[20,15,21,5,21,4,12,5,13,8,14,11,14,14,13,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4],54:[20,16,18,15,20,12,21,10,21,7,20,5,17,4,12,4,7,5,3,7,1,10,0,11,0,14,1,16,3,17,6,17,7,16,10,14,12,11,13,10,13,7,12,5,10,4,7],55:[20,17,21,7,0,void 0,3,21,17,21],56:[20,8,21,5,20,4,18,4,16,5,14,7,13,11,12,14,11,16,9,17,7,17,4,16,2,15,1,12,0,8,0,5,1,4,2,3,4,3,7,4,9,6,11,9,12,13,13,15,14,16,16,16,18,15,20,12,21,8,21],57:[20,16,14,15,11,13,9,10,8,9,8,6,9,4,11,3,14,3,15,4,18,6,20,9,21,10,21,13,20,15,18,16,14,16,9,15,4,13,1,10,0,8,0,5,1,4,3],58:[10,5,14,4,13,5,12,6,13,5,14,void 0,5,2,4,1,5,0,6,1,5,2],59:[10,5,14,4,13,5,12,6,13,5,14,void 0,6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4],60:[24,20,18,4,9,20,0],61:[26,4,12,22,12,void 0,4,6,22,6],62:[24,4,18,20,9,4,0],63:[18,3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13,12,9,10,9,7,void 0,9,2,8,1,9,0,10,1,9,2],64:[27,18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16,6,17,8,void 0,12,16,10,14,9,11,9,8,10,6,11,5,void 0,18,16,17,8,17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12,21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0,15,0,18,1,20,2,21,3,void 0,19,16,18,8,18,6,19,5],65:[18,9,21,1,0,void 0,9,21,17,0,void 0,4,7,14,7],66:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,void 0,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0],67:[21,18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5],68:[21,4,21,4,0,void 0,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16,3,14,1,11,0,4,0],69:[19,4,21,4,0,void 0,4,21,17,21,void 0,4,11,12,11,void 0,4,0,17,0],70:[18,4,21,4,0,void 0,4,21,17,21,void 0,4,11,12,11],71:[21,18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,void 0,13,8,18,8],72:[22,4,21,4,0,void 0,18,21,18,0,void 0,4,11,18,11],73:[8,4,21,4,0],74:[16,12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7],75:[21,4,21,4,0,void 0,18,21,4,7,void 0,9,12,18,0],76:[17,4,21,4,0,void 0,4,0,16,0],77:[24,4,21,4,0,void 0,4,21,12,0,void 0,20,21,12,0,void 0,20,21,20,0],78:[22,4,21,4,0,void 0,4,21,18,0,void 0,18,21,18,0],79:[22,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21],80:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13,10,4,10],81:[22,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,void 0,12,4,18,-2],82:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,4,11,void 0,11,11,18,0],83:[20,17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3],84:[16,8,21,8,0,void 0,1,21,15,21],85:[22,4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21],86:[18,1,21,9,0,void 0,17,21,9,0],87:[24,2,21,7,0,void 0,12,21,7,0,void 0,12,21,17,0,void 0,22,21,17,0],88:[20,3,21,17,0,void 0,17,21,3,0],89:[18,1,21,9,11,9,0,void 0,17,21,9,11],90:[20,17,21,3,0,void 0,3,21,17,21,void 0,3,0,17,0],91:[14,4,25,4,-7,void 0,5,25,5,-7,void 0,4,25,11,25,void 0,4,-7,11,-7],92:[14,0,21,14,-3],93:[14,9,25,9,-7,void 0,10,25,10,-7,void 0,3,25,10,25,void 0,3,-7,10,-7],94:[16,6,15,8,18,10,15,void 0,3,12,8,17,13,12,void 0,8,17,8,0],95:[16,0,-2,16,-2],96:[10,6,21,5,20,4,18,4,16,5,15,6,16,5,17],97:[19,15,14,15,0,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],98:[19,4,21,4,0,void 0,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3],99:[18,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],100:[19,15,21,15,0,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],101:[18,3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],102:[12,10,21,8,21,6,20,5,17,5,0,void 0,2,14,9,14],103:[19,15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],104:[19,4,21,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0],105:[8,3,21,4,20,5,21,4,22,3,21,void 0,4,14,4,0],106:[10,5,21,6,20,7,21,6,22,5,21,void 0,6,14,6,-3,5,-6,3,-7,1,-7],107:[17,4,21,4,0,void 0,14,14,4,4,void 0,8,8,15,0],108:[8,4,21,4,0],109:[30,4,14,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0,void 0,15,10,18,13,20,14,23,14,25,13,26,10,26,0],110:[19,4,14,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0],111:[19,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16,6,16,8,15,11,13,13,11,14,8,14],112:[19,4,14,4,-7,void 0,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3],113:[19,15,14,15,-7,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],114:[13,4,14,4,0,void 0,4,8,5,11,7,13,9,14,12,14],115:[17,14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14,3,13,1,10,0,7,0,4,1,3,3],116:[12,5,21,5,4,6,1,8,0,10,0,void 0,2,14,9,14],117:[19,4,14,4,4,5,1,7,0,10,0,12,1,15,4,void 0,15,14,15,0],118:[16,2,14,8,0,void 0,14,14,8,0],119:[22,3,14,7,0,void 0,11,14,7,0,void 0,11,14,15,0,void 0,19,14,15,0],120:[17,3,14,14,0,void 0,14,14,3,0],121:[16,2,14,8,0,void 0,14,14,8,0,6,-4,4,-6,2,-7,1,-7],122:[17,14,14,3,0,void 0,3,14,14,14,void 0,3,0,14,0],123:[14,9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,void 0,7,24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3,8,1,7,0,6,-2,6,-4,7,-6,void 0,6,8,8,6,8,4,7,2,6,1,5,-1,5,-3,6,-5,7,-6,9,-7],124:[8,4,25,4,-7],125:[14,5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,void 0,7,24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3,6,1,7,0,8,-2,8,-4,7,-6,void 0,8,8,6,6,6,4,7,2,8,1,9,-1,9,-3,8,-5,7,-6,5,-7],126:[24,3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,void 0,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12]}},{}],402:[function(e,t,n){t.exports={vectorChar:e("./vectorChar"),vectorText:e("./vectorText")}},{"./vectorChar":403,"./vectorText":405}],403:[function(e,t,n){const o=e("./vectorParams");t.exports=(e,t)=>{const{xOffset:n,yOffset:r,input:s,font:a,height:i,extrudeOffset:c}=o(e,t);let l=s.charCodeAt(0);l&&a[l]||(l=63);const u=[].concat(a[l]),p=(i-c)/a.height,f=c/2,h=u.shift()*p,m=[];let g=[];for(let e=0,t=u.length;e{t||"string"!=typeof e||(e={input:e}),e=e||{};const n=Object.assign({},o,e);return n.input=t||n.input,n}},{"./fonts/single-line/hershey/simplex.js":401}],405:[function(e,t,n){const o=e("./vectorChar"),r=e("./vectorParams"),s=(e,t)=>{const{x:n,y:o}=Object.assign({x:0,y:0},e||{}),r=t.segments;let s=null,a=null;for(let e=0,t=r.length;e{const{xOffset:n,yOffset:a,input:i,font:c,height:l,align:u,extrudeOffset:p,lineSpacing:f,letterSpacing:h}=r(e,t);let m,g,d,y,v,b,[x,A]=[n,a],E={width:0,segments:[]};const w=[];let S=[],T=0;const P=x,D=()=>{w.push(E),T=Math.max(T,E.width),E={width:0,segments:[]}};for(m=0,g=i.length;mE.width&&(b=T-E.width,"right"===u?E=s({x:b},E):"center"===u&&(E=s({x:b/2},E))),S=S.concat(E.segments);return S}},{"./vectorChar":403,"./vectorParams":404}],406:[function(e,t,n){const o=e("../geometries/geom2"),r=e("../geometries/geom3"),s=e("../geometries/path2");t.exports=e=>{let t;for(const n of e){let e=0;if(o.isA(n)&&(e=1),r.isA(n)&&(e=2),s.isA(n)&&(e=3),t&&e!==t)return!1;t=e}return!0}},{"../geometries/geom2":38,"../geometries/geom3":53,"../geometries/path2":74}],407:[function(e,t,n){t.exports=e=>.017453292519943295*e},{}],408:[function(e,t,n){const o=e=>e.reduce(((e,t)=>Array.isArray(t)?e.concat(o(t)):e.concat(t)),[]);t.exports=o},{}],409:[function(e,t,n){t.exports=(e,t)=>e-t},{}],410:[function(e,t,n){t.exports={areAllShapesTheSameType:e("./areAllShapesTheSameType"),degToRad:e("./degToRad"),flatten:e("./flatten"),fnNumberSort:e("./fnNumberSort"),insertSorted:e("./insertSorted"),radiusToSegments:e("./radiusToSegments"),radToDeg:e("./radToDeg")}},{"./areAllShapesTheSameType":406,"./degToRad":407,"./flatten":408,"./fnNumberSort":409,"./insertSorted":411,"./radToDeg":413,"./radiusToSegments":414}],411:[function(e,t,n){t.exports=(e,t,n)=>{let o=0,r=e.length;for(;r>o;){const s=Math.floor((o+r)/2);n(t,e[s])>0?o=s+1:r=s}e.splice(o,0,t)}},{}],412:[function(e,t,n){t.exports=(e,t,n)=>{for(e=e.slice();e.length57.29577951308232*e},{}],414:[function(e,t,n){const{TAU:o}=e("../maths/constants");t.exports=(e,t,n)=>{const r=t>0?e*o/t:0,s=n>0?o/n:0;return Math.ceil(Math.max(r,s,4))}},{"../maths/constants":106}],415:[function(e,t,n){t.exports=class{constructor(e){this._buffer=e,this._pos=0}readInt8(){return this._decodeInt(8,!0)}readUInt8(){return this._decodeInt(8,!1)}readInt16(){return this._decodeInt(16,!0)}readUInt16(){return this._decodeInt(16,!1)}readInt32(){return this._decodeInt(32,!0)}readUInt32(){return this._decodeInt(32,!1)}readFloat(){return this._decodeFloat(23,8)}readDouble(){return this._decodeFloat(52,11)}readChar(){return this.readString(1)}readString(e){this._checkSize(8*e);const t=this._buffer.substr(this._pos,e);return this._pos+=e,t}seek(e){this._pos=e,this._checkSize(0)}getPosition(){return this._pos}getSize(){return this._buffer.length}_decodeFloat(e,t){const n=e+t+1,o=n>>3;this._checkSize(n);const r=Math.pow(2,t-1)-1,s=this._readBits(e+t,1,o),a=this._readBits(e,t,o);let i=0,c=2,l=0,u=0;do{const t=this._readByte(++l,o);u=e%8||8;let n=1<>=1;)t&n&&(i+=1/c),c*=2}while(e-=u);return this._pos+=o,a===1+(r<<1)?i?NaN:s?-1/0:1/0:(1+-2*s)*(a||i?a?Math.pow(2,a-r)*(1+i):Math.pow(2,1-r)*i:0)}_decodeInt(e,t){const n=this._readBits(0,e,e/8),o=Math.pow(2,e),r=t&&n>=o/2?n-o:n;return this._pos+=e/8,r}_shl(e,t){for(++t;--t;e=1073741824&~(e%=2147483648)?2*(e-1073741824)+2147483647+1:2*e);return e}_readByte(e,t){return 255&this._buffer.charCodeAt(this._pos+t-e-1)}_readBits(e,t,n){const o=(e+t)%8,r=e%8,s=n-(e>>3)-1;let a=n+(-(e+t)>>3),i=s-a,c=this._readByte(s,n)>>r&(1<<(i?8-r:t))-1;for(i&&o&&(c+=(this._readByte(a++,n)&(1<{"string"==typeof e?this.length+=e.length:e instanceof ArrayBuffer&&(this.length+=e.byteLength)})),n.type&&(this.type=n.type.toLowerCase()),n.endings,n.encoding&&(this.encoding=n.encoding.toLowerCase()),n.length&&(this.length=n.length),this.buffer=e.allocUnsafe(this.length);for(let e=0;e{const{data:t,mimeType:n}=e;return new o(t,{type:n})}},{"./makeBlob":419}],418:[function(e,t,n){t.exports={convertToBlob:e("./convertToBlob"),makeBlob:e("./makeBlob"),BinaryReader:e("./BinaryReader"),Blob:e("./Blob")}},{"./BinaryReader":415,"./Blob":416,"./convertToBlob":417,"./makeBlob":419}],419:[function(e,t,n){const o=e("./Blob.js");t.exports=()=>"undefined"!=typeof window?window.Blob:o},{"./Blob.js":416}],420:[function(e,t,n){arguments[4][14][0].apply(n,arguments)},{"./cssColors":422,dup:14}],421:[function(e,t,n){arguments[4][15][0].apply(n,arguments)},{"../geometries/geom2":444,"../geometries/geom3":460,"../geometries/path2":481,"../geometries/poly3":498,"../utils/flatten":817,dup:15}],422:[function(e,t,n){arguments[4][16][0].apply(n,arguments)},{dup:16}],423:[function(e,t,n){arguments[4][17][0].apply(n,arguments)},{dup:17}],424:[function(e,t,n){arguments[4][18][0].apply(n,arguments)},{"../utils/flatten":817,"./hueToColorComponent":426,dup:18}],425:[function(e,t,n){arguments[4][19][0].apply(n,arguments)},{"../utils/flatten":817,dup:19}],426:[function(e,t,n){arguments[4][20][0].apply(n,arguments)},{dup:20}],427:[function(e,t,n){arguments[4][21][0].apply(n,arguments)},{"./colorNameToRgb":420,"./colorize":421,"./cssColors":422,"./hexToRgb":423,"./hslToRgb":424,"./hsvToRgb":425,"./hueToColorComponent":426,"./rgbToHex":428,"./rgbToHsl":429,"./rgbToHsv":430,dup:21}],428:[function(e,t,n){arguments[4][22][0].apply(n,arguments)},{"../utils/flatten":817,dup:22}],429:[function(e,t,n){arguments[4][23][0].apply(n,arguments)},{"../utils/flatten":817,dup:23}],430:[function(e,t,n){arguments[4][24][0].apply(n,arguments)},{"../utils/flatten":817,dup:24}],431:[function(e,t,n){arguments[4][25][0].apply(n,arguments)},{"./lengths":435,dup:25}],432:[function(e,t,n){arguments[4][26][0].apply(n,arguments)},{dup:26}],433:[function(e,t,n){arguments[4][27][0].apply(n,arguments)},{"./arcLengthToT":431,"./create":432,"./length":434,"./lengths":435,"./tangentAt":436,"./valueAt":437,dup:27}],434:[function(e,t,n){arguments[4][28][0].apply(n,arguments)},{"./lengths":435,dup:28}],435:[function(e,t,n){arguments[4][29][0].apply(n,arguments)},{"./valueAt":437,dup:29}],436:[function(e,t,n){arguments[4][30][0].apply(n,arguments)},{dup:30}],437:[function(e,t,n){arguments[4][31][0].apply(n,arguments)},{dup:31}],438:[function(e,t,n){arguments[4][32][0].apply(n,arguments)},{"./bezier":433,dup:32}],439:[function(e,t,n){arguments[4][33][0].apply(n,arguments)},{"../../maths/mat4":562,"../../maths/vec2":610,dup:33}],440:[function(e,t,n){arguments[4][34][0].apply(n,arguments)},{dup:34}],441:[function(e,t,n){arguments[4][35][0].apply(n,arguments)},{"../../maths/mat4":562,dup:35}],442:[function(e,t,n){arguments[4][36][0].apply(n,arguments)},{"../../maths/mat4":562,"../../maths/vec2":610,"./create":441,dup:36}],443:[function(e,t,n){arguments[4][37][0].apply(n,arguments)},{"../../maths/vec2":610,"./create":441,dup:37}],444:[function(e,t,n){arguments[4][38][0].apply(n,arguments)},{"./clone":440,"./create":441,"./fromCompactBinary":442,"./fromPoints":443,"./isA":445,"./reverse":446,"./toCompactBinary":447,"./toOutlines":448,"./toPoints":449,"./toSides":450,"./toString":451,"./transform":452,"./validate":453,dup:38}],445:[function(e,t,n){arguments[4][39][0].apply(n,arguments)},{dup:39}],446:[function(e,t,n){arguments[4][40][0].apply(n,arguments)},{"./create":441,"./toSides":450,dup:40}],447:[function(e,t,n){arguments[4][41][0].apply(n,arguments)},{dup:41}],448:[function(e,t,n){arguments[4][42][0].apply(n,arguments)},{"../../maths/vec2":610,"./toSides":450,dup:42}],449:[function(e,t,n){arguments[4][43][0].apply(n,arguments)},{"./toSides":450,dup:43}],450:[function(e,t,n){arguments[4][44][0].apply(n,arguments)},{"./applyTransforms":439,dup:44}],451:[function(e,t,n){arguments[4][45][0].apply(n,arguments)},{"../../maths/vec2":610,"./toSides":450,dup:45}],452:[function(e,t,n){const o=e("../../maths/mat4"),r=e("./reverse.js");t.exports=(e,t)=>{const n=o.multiply(o.create(),e,t.transforms),s=Object.assign({},t,{transforms:n});return e[0]*e[5]-e[4]*e[1]<0?r(s):s}},{"../../maths/mat4":562,"./reverse.js":446}],453:[function(e,t,n){arguments[4][47][0].apply(n,arguments)},{"../../maths/vec2":610,"./isA":445,"./toOutlines":448,dup:47}],454:[function(e,t,n){arguments[4][48][0].apply(n,arguments)},{"../../maths/mat4":562,"../poly3":498,dup:48}],455:[function(e,t,n){arguments[4][49][0].apply(n,arguments)},{dup:49}],456:[function(e,t,n){arguments[4][50][0].apply(n,arguments)},{"../../maths/mat4":562,dup:50}],457:[function(e,t,n){arguments[4][51][0].apply(n,arguments)},{"../../maths/mat4":562,"../../maths/vec3":641,"../poly3":498,"./create":456,dup:51}],458:[function(e,t,n){arguments[4][52][0].apply(n,arguments)},{"../poly3":498,"./create":456,dup:52}],459:[function(e,t,n){const o=e("../../operations/hulls/quickhull"),r=e("./create"),s=e("../poly3");t.exports=e=>{if(!Array.isArray(e))throw new Error("the given points must be an array");const t=o(e,{skipTriangulation:!0}).map((t=>{const n=t.map((t=>e[t]));return s.create(n)}));return r(t)}},{"../../operations/hulls/quickhull":767,"../poly3":498,"./create":456}],460:[function(e,t,n){t.exports={clone:e("./clone"),create:e("./create"),fromPointsConvex:e("./fromPointsConvex"),fromPoints:e("./fromPoints"),fromCompactBinary:e("./fromCompactBinary"),invert:e("./invert"),isA:e("./isA"),toPoints:e("./toPoints"),toPolygons:e("./toPolygons"),toString:e("./toString"),toCompactBinary:e("./toCompactBinary"),transform:e("./transform"),validate:e("./validate")}},{"./clone":455,"./create":456,"./fromCompactBinary":457,"./fromPoints":458,"./fromPointsConvex":459,"./invert":461,"./isA":462,"./toCompactBinary":463,"./toPoints":464,"./toPolygons":465,"./toString":466,"./transform":467,"./validate":468}],461:[function(e,t,n){arguments[4][54][0].apply(n,arguments)},{"../poly3":498,"./create":456,"./toPolygons":465,dup:54}],462:[function(e,t,n){arguments[4][55][0].apply(n,arguments)},{dup:55}],463:[function(e,t,n){arguments[4][56][0].apply(n,arguments)},{"../poly3":498,dup:56}],464:[function(e,t,n){arguments[4][57][0].apply(n,arguments)},{"../poly3":498,"./toPolygons":465,dup:57}],465:[function(e,t,n){arguments[4][58][0].apply(n,arguments)},{"./applyTransforms":454,dup:58}],466:[function(e,t,n){arguments[4][59][0].apply(n,arguments)},{"../poly3":498,"./toPolygons":465,dup:59}],467:[function(e,t,n){arguments[4][60][0].apply(n,arguments)},{"../../maths/mat4":562,dup:60}],468:[function(e,t,n){arguments[4][61][0].apply(n,arguments)},{"../poly3":498,"./isA":462,dup:61}],469:[function(e,t,n){arguments[4][62][0].apply(n,arguments)},{"./geom2":444,"./geom3":460,"./path2":481,"./poly2":492,"./poly3":498,dup:62}],470:[function(e,t,n){arguments[4][63][0].apply(n,arguments)},{"../../maths/constants":513,"../../maths/vec2":610,"./fromPoints":480,"./toPoints":485,dup:63}],471:[function(e,t,n){arguments[4][64][0].apply(n,arguments)},{"../../maths/constants":513,"../../maths/vec2":610,"./appendPoints":472,"./toPoints":485,dup:64}],472:[function(e,t,n){arguments[4][65][0].apply(n,arguments)},{"./concat":476,"./create":477,dup:65}],473:[function(e,t,n){arguments[4][66][0].apply(n,arguments)},{"../../maths/mat4":562,"../../maths/vec2":610,dup:66}],474:[function(e,t,n){arguments[4][67][0].apply(n,arguments)},{dup:67}],475:[function(e,t,n){arguments[4][68][0].apply(n,arguments)},{"../../maths/constants":513,"../../maths/vec2":610,"./clone":474,dup:68}],476:[function(e,t,n){arguments[4][69][0].apply(n,arguments)},{"../../maths/vec2":610,"./fromPoints":480,"./toPoints":485,dup:69}],477:[function(e,t,n){arguments[4][70][0].apply(n,arguments)},{"../../maths/mat4":562,dup:70}],478:[function(e,t,n){arguments[4][71][0].apply(n,arguments)},{"../../maths/vec2":610,"./toPoints":485,dup:71}],479:[function(e,t,n){arguments[4][72][0].apply(n,arguments)},{"../../maths/mat4":562,"../../maths/vec2":610,"./create":477,dup:72}],480:[function(e,t,n){arguments[4][73][0].apply(n,arguments)},{"../../maths/constants":513,"../../maths/vec2":610,"./close":475,"./create":477,dup:73}],481:[function(e,t,n){arguments[4][74][0].apply(n,arguments)},{"./appendArc":470,"./appendBezier":471,"./appendPoints":472,"./clone":474,"./close":475,"./concat":476,"./create":477,"./equals":478,"./fromCompactBinary":479,"./fromPoints":480,"./isA":482,"./reverse":483,"./toCompactBinary":484,"./toPoints":485,"./toString":486,"./transform":487,"./validate":488,dup:74}],482:[function(e,t,n){arguments[4][75][0].apply(n,arguments)},{dup:75}],483:[function(e,t,n){arguments[4][76][0].apply(n,arguments)},{"./clone":474,dup:76}],484:[function(e,t,n){arguments[4][77][0].apply(n,arguments)},{dup:77}],485:[function(e,t,n){arguments[4][78][0].apply(n,arguments)},{"./applyTransforms":473,dup:78}],486:[function(e,t,n){arguments[4][79][0].apply(n,arguments)},{"../../maths/vec2":610,"./toPoints":485,dup:79}],487:[function(e,t,n){arguments[4][80][0].apply(n,arguments)},{"../../maths/mat4":562,dup:80}],488:[function(e,t,n){arguments[4][81][0].apply(n,arguments)},{"../../maths/vec2":610,"./isA":482,dup:81}],489:[function(e,t,n){arguments[4][82][0].apply(n,arguments)},{"./flip":491,"./measureArea":493,dup:82}],490:[function(e,t,n){arguments[4][83][0].apply(n,arguments)},{dup:83}],491:[function(e,t,n){arguments[4][84][0].apply(n,arguments)},{"./create":490,dup:84}],492:[function(e,t,n){arguments[4][85][0].apply(n,arguments)},{"./arePointsInside":489,"./create":490,"./flip":491,"./measureArea":493,dup:85}],493:[function(e,t,n){arguments[4][86][0].apply(n,arguments)},{"../../maths/utils/area":587,dup:86}],494:[function(e,t,n){arguments[4][87][0].apply(n,arguments)},{"../../maths/vec3":641,"./create":495,dup:87}],495:[function(e,t,n){arguments[4][88][0].apply(n,arguments)},{dup:88}],496:[function(e,t,n){arguments[4][89][0].apply(n,arguments)},{"../../maths/vec3":641,"./create":495,dup:89}],497:[function(e,t,n){arguments[4][90][0].apply(n,arguments)},{"./create":495,dup:90}],498:[function(e,t,n){arguments[4][91][0].apply(n,arguments)},{"./clone":494,"./create":495,"./fromPoints":496,"./fromPointsAndPlane":497,"./invert":499,"./isA":500,"./isConvex":501,"./measureArea":502,"./measureBoundingBox":503,"./measureBoundingSphere":504,"./measureSignedVolume":505,"./plane":506,"./toPoints":507,"./toString":508,"./transform":509,"./validate":510,dup:91}],499:[function(e,t,n){arguments[4][92][0].apply(n,arguments)},{"../../maths/plane":582,"./create":495,dup:92}],500:[function(e,t,n){arguments[4][93][0].apply(n,arguments)},{dup:93}],501:[function(e,t,n){arguments[4][94][0].apply(n,arguments)},{"../../maths/plane":582,"../../maths/vec3":641,dup:94}],502:[function(e,t,n){arguments[4][95][0].apply(n,arguments)},{"./plane":506,dup:95}],503:[function(e,t,n){arguments[4][96][0].apply(n,arguments)},{"../../maths/vec3":641,dup:96}],504:[function(e,t,n){arguments[4][97][0].apply(n,arguments)},{"../../maths/vec4":667,dup:97}],505:[function(e,t,n){arguments[4][98][0].apply(n,arguments)},{"../../maths/vec3":641,dup:98}],506:[function(e,t,n){arguments[4][99][0].apply(n,arguments)},{"../../maths/plane/":582,dup:99}],507:[function(e,t,n){arguments[4][100][0].apply(n,arguments)},{dup:100}],508:[function(e,t,n){arguments[4][101][0].apply(n,arguments)},{"../../maths/vec3/":641,dup:101}],509:[function(e,t,n){arguments[4][102][0].apply(n,arguments)},{"../../maths/mat4":562,"../../maths/vec3":641,"./create":495,dup:102}],510:[function(e,t,n){arguments[4][103][0].apply(n,arguments)},{"../../maths/constants":513,"../../maths/plane/signedDistanceToPoint":584,"../../maths/vec3":641,"./isA":500,"./isConvex":501,"./measureArea":502,"./plane":506,dup:103}],511:[function(e,t,n){arguments[4][104][0].apply(n,arguments)},{"./colors":427,"./curves":438,"./geometries":469,"./maths":514,"./measurements":671,"./operations/booleans":685,"./operations/expansions":714,"./operations/extrusions":737,"./operations/hulls":760,"./operations/modifiers":771,"./operations/transforms":781,"./primitives":797,"./text":811,"./utils":819,dup:104}],512:[function(e,t,n){arguments[4][105][0].apply(n,arguments)},{"./mat4":562,"./vec2":610,"./vec3":641,dup:105}],513:[function(e,t,n){arguments[4][106][0].apply(n,arguments)},{dup:106}],514:[function(e,t,n){arguments[4][107][0].apply(n,arguments)},{"./constants":513,"./line2":524,"./line3":541,"./mat4":562,"./plane":582,"./utils":588,"./vec2":610,"./vec3":641,"./vec4":667,dup:107}],515:[function(e,t,n){arguments[4][108][0].apply(n,arguments)},{"./create":518,dup:108}],516:[function(e,t,n){arguments[4][109][0].apply(n,arguments)},{"../vec2":610,"./direction":519,"./origin":526,dup:109}],517:[function(e,t,n){arguments[4][110][0].apply(n,arguments)},{dup:110}],518:[function(e,t,n){arguments[4][111][0].apply(n,arguments)},{dup:111}],519:[function(e,t,n){arguments[4][112][0].apply(n,arguments)},{"../vec2":610,dup:112}],520:[function(e,t,n){arguments[4][113][0].apply(n,arguments)},{"../vec2":610,dup:113}],521:[function(e,t,n){arguments[4][114][0].apply(n,arguments)},{dup:114}],522:[function(e,t,n){arguments[4][115][0].apply(n,arguments)},{"../vec2":610,dup:115}],523:[function(e,t,n){arguments[4][116][0].apply(n,arguments)},{"./create":518,dup:116}],524:[function(e,t,n){arguments[4][117][0].apply(n,arguments)},{"./clone":515,"./closestPoint":516,"./copy":517,"./create":518,"./direction":519,"./distanceToPoint":520,"./equals":521,"./fromPoints":522,"./fromValues":523,"./intersectPointOfLines":525,"./origin":526,"./reverse":527,"./toString":528,"./transform":529,"./xAtY":530,dup:117}],525:[function(e,t,n){arguments[4][118][0].apply(n,arguments)},{"../utils":588,"../vec2":610,dup:118}],526:[function(e,t,n){arguments[4][119][0].apply(n,arguments)},{"../vec2":610,dup:119}],527:[function(e,t,n){arguments[4][120][0].apply(n,arguments)},{"../vec2":610,"./copy":517,"./fromValues":523,dup:120}],528:[function(e,t,n){arguments[4][121][0].apply(n,arguments)},{dup:121}],529:[function(e,t,n){arguments[4][122][0].apply(n,arguments)},{"../vec2":610,"./direction":519,"./fromPoints":522,"./origin":526,dup:122}],530:[function(e,t,n){arguments[4][123][0].apply(n,arguments)},{"./origin":526,dup:123}],531:[function(e,t,n){arguments[4][124][0].apply(n,arguments)},{"../vec3":641,"./create":534,dup:124}],532:[function(e,t,n){arguments[4][125][0].apply(n,arguments)},{"../vec3":641,dup:125}],533:[function(e,t,n){arguments[4][126][0].apply(n,arguments)},{"../vec3":641,dup:126}],534:[function(e,t,n){arguments[4][127][0].apply(n,arguments)},{"../vec3":641,dup:127}],535:[function(e,t,n){arguments[4][128][0].apply(n,arguments)},{dup:128}],536:[function(e,t,n){arguments[4][129][0].apply(n,arguments)},{"../vec3":641,"./closestPoint":532,dup:129}],537:[function(e,t,n){arguments[4][130][0].apply(n,arguments)},{"../vec3":641,dup:130}],538:[function(e,t,n){arguments[4][131][0].apply(n,arguments)},{"../constants":513,"../utils":588,"../vec3":641,"./fromPointAndDirection":539,dup:131}],539:[function(e,t,n){arguments[4][132][0].apply(n,arguments)},{"../vec3":641,dup:132}],540:[function(e,t,n){arguments[4][133][0].apply(n,arguments)},{"../vec3":641,"./fromPointAndDirection":539,dup:133}],541:[function(e,t,n){arguments[4][134][0].apply(n,arguments)},{"./clone":531,"./closestPoint":532,"./copy":533,"./create":534,"./direction":535,"./distanceToPoint":536,"./equals":537,"./fromPlanes":538,"./fromPointAndDirection":539,"./fromPoints":540,"./intersectPointOfLineAndPlane":542,"./origin":543,"./reverse":544,"./toString":545,"./transform":546,dup:134}],542:[function(e,t,n){arguments[4][135][0].apply(n,arguments)},{"../vec3":641,dup:135}],543:[function(e,t,n){arguments[4][136][0].apply(n,arguments)},{dup:136}],544:[function(e,t,n){arguments[4][137][0].apply(n,arguments)},{"../vec3":641,"./fromPointAndDirection":539,dup:137}],545:[function(e,t,n){arguments[4][138][0].apply(n,arguments)},{dup:138}],546:[function(e,t,n){arguments[4][139][0].apply(n,arguments)},{"../vec3":641,"./fromPointAndDirection":539,dup:139}],547:[function(e,t,n){arguments[4][140][0].apply(n,arguments)},{dup:140}],548:[function(e,t,n){arguments[4][141][0].apply(n,arguments)},{"./create":550,dup:141}],549:[function(e,t,n){arguments[4][142][0].apply(n,arguments)},{dup:142}],550:[function(e,t,n){arguments[4][143][0].apply(n,arguments)},{dup:143}],551:[function(e,t,n){arguments[4][144][0].apply(n,arguments)},{dup:144}],552:[function(e,t,n){arguments[4][145][0].apply(n,arguments)},{"../constants":513,"../utils/trigonometry":592,"./identity":561,dup:145}],553:[function(e,t,n){arguments[4][146][0].apply(n,arguments)},{dup:146}],554:[function(e,t,n){arguments[4][147][0].apply(n,arguments)},{"../utils/trigonometry":592,dup:147}],555:[function(e,t,n){arguments[4][148][0].apply(n,arguments)},{dup:148}],556:[function(e,t,n){arguments[4][149][0].apply(n,arguments)},{"./create":550,dup:149}],557:[function(e,t,n){arguments[4][150][0].apply(n,arguments)},{"../vec3":641,"./fromRotation":552,dup:150}],558:[function(e,t,n){arguments[4][151][0].apply(n,arguments)},{"../utils/trigonometry":592,dup:151}],559:[function(e,t,n){arguments[4][152][0].apply(n,arguments)},{"../utils/trigonometry":592,dup:152}],560:[function(e,t,n){arguments[4][153][0].apply(n,arguments)},{"../utils/trigonometry":592,dup:153}],561:[function(e,t,n){arguments[4][154][0].apply(n,arguments)},{dup:154}],562:[function(e,t,n){arguments[4][155][0].apply(n,arguments)},{"./add":547,"./clone":548,"./copy":549,"./create":550,"./equals":551,"./fromRotation":552,"./fromScaling":553,"./fromTaitBryanRotation":554,"./fromTranslation":555,"./fromValues":556,"./fromVectorRotation":557,"./fromXRotation":558,"./fromYRotation":559,"./fromZRotation":560,"./identity":561,"./invert":563,"./isIdentity":564,"./isMirroring":565,"./isOnlyTransformScale":566,"./mirrorByPlane":567,"./multiply":568,"./rotate":569,"./rotateX":570,"./rotateY":571,"./rotateZ":572,"./scale":573,"./subtract":574,"./toString":575,"./translate":576,dup:155}],563:[function(e,t,n){arguments[4][156][0].apply(n,arguments)},{dup:156}],564:[function(e,t,n){arguments[4][157][0].apply(n,arguments)},{dup:157}],565:[function(e,t,n){arguments[4][158][0].apply(n,arguments)},{dup:158}],566:[function(e,t,n){arguments[4][159][0].apply(n,arguments)},{dup:159}],567:[function(e,t,n){arguments[4][160][0].apply(n,arguments)},{dup:160}],568:[function(e,t,n){arguments[4][161][0].apply(n,arguments)},{dup:161}],569:[function(e,t,n){arguments[4][162][0].apply(n,arguments)},{"../constants":513,"../utils/trigonometry":592,"./copy":549,dup:162}],570:[function(e,t,n){arguments[4][163][0].apply(n,arguments)},{"../utils/trigonometry":592,dup:163}],571:[function(e,t,n){arguments[4][164][0].apply(n,arguments)},{"../utils/trigonometry":592,dup:164}],572:[function(e,t,n){arguments[4][165][0].apply(n,arguments)},{"../utils/trigonometry":592,dup:165}],573:[function(e,t,n){arguments[4][166][0].apply(n,arguments)},{dup:166}],574:[function(e,t,n){arguments[4][167][0].apply(n,arguments)},{dup:167}],575:[function(e,t,n){arguments[4][168][0].apply(n,arguments)},{dup:168}],576:[function(e,t,n){arguments[4][169][0].apply(n,arguments)},{dup:169}],577:[function(e,t,n){arguments[4][170][0].apply(n,arguments)},{dup:170}],578:[function(e,t,n){const o=e("../vec3"),r=e("./fromNormalAndPoint");t.exports=(e,...t)=>{e[0]=0,e[1]=0,e[2]=0,e[3]=0;const n=t.length;t.forEach((t=>{o.add(e,e,t)})),o.scale(e,e,1/n);let s=0,a=0,i=0,c=0,l=0,u=0;const p=o.create();t.forEach((t=>{o.subtract(p,t,e),s+=p[0]*p[0],a+=p[0]*p[1],i+=p[0]*p[2],c+=p[1]*p[1],l+=p[1]*p[2],u+=p[2]*p[2]})),s/=n,a/=n,i/=n,c/=n,l/=n,u/=n,p[0]=0,p[1]=0,p[2]=0;const f=o.create();let h=c*u-l*l;f[0]=h,f[1]=i*l-a*u,f[2]=a*l-i*c;let m=h*h;return o.add(p,p,o.scale(f,f,m)),h=s*u-i*i,f[0]=i*l-a*u,f[1]=h,f[2]=a*i-l*s,m=h*h,o.dot(p,f)<0&&(m=-m),o.add(p,p,o.scale(f,f,m)),h=s*c-a*a,f[0]=a*l-i*c,f[1]=a*i-l*s,f[2]=h,m=h*h,o.dot(p,f)<0&&(m=-m),o.add(p,p,o.scale(f,f,m)),r(e,p,e)}},{"../vec3":641,"./fromNormalAndPoint":579}],579:[function(e,t,n){arguments[4][171][0].apply(n,arguments)},{"../vec3":641,dup:171}],580:[function(e,t,n){arguments[4][172][0].apply(n,arguments)},{"../vec3":641,dup:172}],581:[function(e,t,n){arguments[4][173][0].apply(n,arguments)},{"../constants":513,"../vec3":641,dup:173}],582:[function(e,t,n){t.exports={clone:e("../vec4/clone"),copy:e("../vec4/copy"),create:e("../vec4/create"),equals:e("../vec4/equals"),flip:e("./flip"),fromNormalAndPoint:e("./fromNormalAndPoint"),fromValues:e("../vec4/fromValues"),fromNoisyPoints:e("./fromNoisyPoints"),fromPoints:e("./fromPoints"),fromPointsRandom:e("./fromPointsRandom"),projectionOfPoint:e("./projectionOfPoint"),signedDistanceToPoint:e("./signedDistanceToPoint"),toString:e("../vec4/toString"),transform:e("./transform")}},{"../vec4/clone":660,"../vec4/copy":661,"../vec4/create":662,"../vec4/equals":664,"../vec4/fromValues":666,"../vec4/toString":668,"./flip":577,"./fromNoisyPoints":578,"./fromNormalAndPoint":579,"./fromPoints":580,"./fromPointsRandom":581,"./projectionOfPoint":583,"./signedDistanceToPoint":584,"./transform":585}],583:[function(e,t,n){arguments[4][175][0].apply(n,arguments)},{"../vec3":641,dup:175}],584:[function(e,t,n){arguments[4][176][0].apply(n,arguments)},{"../vec3":641,dup:176}],585:[function(e,t,n){arguments[4][177][0].apply(n,arguments)},{"../mat4":562,"../vec3":641,"./flip":577,"./fromPoints":580,dup:177}],586:[function(e,t,n){arguments[4][178][0].apply(n,arguments)},{"../constants":513,dup:178}],587:[function(e,t,n){arguments[4][179][0].apply(n,arguments)},{dup:179}],588:[function(e,t,n){arguments[4][180][0].apply(n,arguments)},{"./aboutEqualNormals":586,"./area":587,"./interpolateBetween2DPointsForY":589,"./intersect":590,"./solve2Linear":591,"./trigonometry":592,dup:180}],589:[function(e,t,n){arguments[4][181][0].apply(n,arguments)},{dup:181}],590:[function(e,t,n){arguments[4][182][0].apply(n,arguments)},{dup:182}],591:[function(e,t,n){arguments[4][183][0].apply(n,arguments)},{dup:183}],592:[function(e,t,n){arguments[4][184][0].apply(n,arguments)},{"../constants":513,dup:184}],593:[function(e,t,n){arguments[4][185][0].apply(n,arguments)},{dup:185}],594:[function(e,t,n){arguments[4][186][0].apply(n,arguments)},{dup:186}],595:[function(e,t,n){arguments[4][187][0].apply(n,arguments)},{"./angleRadians":597,dup:187}],596:[function(e,t,n){arguments[4][188][0].apply(n,arguments)},{"./angleRadians":597,dup:188}],597:[function(e,t,n){arguments[4][189][0].apply(n,arguments)},{dup:189}],598:[function(e,t,n){arguments[4][190][0].apply(n,arguments)},{"./create":600,dup:190}],599:[function(e,t,n){arguments[4][191][0].apply(n,arguments)},{dup:191}],600:[function(e,t,n){arguments[4][192][0].apply(n,arguments)},{dup:192}],601:[function(e,t,n){arguments[4][193][0].apply(n,arguments)},{dup:193}],602:[function(e,t,n){arguments[4][194][0].apply(n,arguments)},{dup:194}],603:[function(e,t,n){arguments[4][195][0].apply(n,arguments)},{dup:195}],604:[function(e,t,n){arguments[4][196][0].apply(n,arguments)},{dup:196}],605:[function(e,t,n){arguments[4][197][0].apply(n,arguments)},{dup:197}],606:[function(e,t,n){arguments[4][198][0].apply(n,arguments)},{"./fromAngleRadians":607,dup:198}],607:[function(e,t,n){arguments[4][199][0].apply(n,arguments)},{"../utils/trigonometry":592,dup:199}],608:[function(e,t,n){arguments[4][200][0].apply(n,arguments)},{dup:200}],609:[function(e,t,n){arguments[4][201][0].apply(n,arguments)},{"./create":600,dup:201}],610:[function(e,t,n){arguments[4][202][0].apply(n,arguments)},{"./abs":593,"./add":594,"./angle":595,"./angleDegrees":596,"./angleRadians":597,"./clone":598,"./copy":599,"./create":600,"./cross":601,"./distance":602,"./divide":603,"./dot":604,"./equals":605,"./fromAngleDegrees":606,"./fromAngleRadians":607,"./fromScalar":608,"./fromValues":609,"./length":611,"./lerp":612,"./max":613,"./min":614,"./multiply":615,"./negate":616,"./normal":617,"./normalize":618,"./rotate":619,"./scale":620,"./snap":621,"./squaredDistance":622,"./squaredLength":623,"./subtract":624,"./toString":625,"./transform":626,dup:202}],611:[function(e,t,n){arguments[4][203][0].apply(n,arguments)},{dup:203}],612:[function(e,t,n){arguments[4][204][0].apply(n,arguments)},{dup:204}],613:[function(e,t,n){arguments[4][205][0].apply(n,arguments)},{dup:205}],614:[function(e,t,n){arguments[4][206][0].apply(n,arguments)},{dup:206}],615:[function(e,t,n){arguments[4][207][0].apply(n,arguments)},{dup:207}],616:[function(e,t,n){arguments[4][208][0].apply(n,arguments)},{dup:208}],617:[function(e,t,n){arguments[4][209][0].apply(n,arguments)},{"../constants":513,"./create":600,"./rotate":619,dup:209}],618:[function(e,t,n){arguments[4][210][0].apply(n,arguments)},{dup:210}],619:[function(e,t,n){arguments[4][211][0].apply(n,arguments)},{dup:211}],620:[function(e,t,n){arguments[4][212][0].apply(n,arguments)},{dup:212}],621:[function(e,t,n){arguments[4][213][0].apply(n,arguments)},{dup:213}],622:[function(e,t,n){arguments[4][214][0].apply(n,arguments)},{dup:214}],623:[function(e,t,n){arguments[4][215][0].apply(n,arguments)},{dup:215}],624:[function(e,t,n){arguments[4][216][0].apply(n,arguments)},{dup:216}],625:[function(e,t,n){arguments[4][217][0].apply(n,arguments)},{dup:217}],626:[function(e,t,n){arguments[4][218][0].apply(n,arguments)},{dup:218}],627:[function(e,t,n){arguments[4][219][0].apply(n,arguments)},{dup:219}],628:[function(e,t,n){arguments[4][220][0].apply(n,arguments)},{dup:220}],629:[function(e,t,n){arguments[4][221][0].apply(n,arguments)},{"./dot":636,dup:221}],630:[function(e,t,n){arguments[4][222][0].apply(n,arguments)},{"./create":632,dup:222}],631:[function(e,t,n){arguments[4][223][0].apply(n,arguments)},{dup:223}],632:[function(e,t,n){arguments[4][224][0].apply(n,arguments)},{dup:224}],633:[function(e,t,n){arguments[4][225][0].apply(n,arguments)},{dup:225}],634:[function(e,t,n){arguments[4][226][0].apply(n,arguments)},{dup:226}],635:[function(e,t,n){arguments[4][227][0].apply(n,arguments)},{dup:227}],636:[function(e,t,n){arguments[4][228][0].apply(n,arguments)},{dup:228}],637:[function(e,t,n){arguments[4][229][0].apply(n,arguments)},{dup:229}],638:[function(e,t,n){arguments[4][230][0].apply(n,arguments)},{dup:230}],639:[function(e,t,n){arguments[4][231][0].apply(n,arguments)},{"./create":632,dup:231}],640:[function(e,t,n){arguments[4][232][0].apply(n,arguments)},{dup:232}],641:[function(e,t,n){arguments[4][233][0].apply(n,arguments)},{"./abs":627,"./add":628,"./angle":629,"./clone":630,"./copy":631,"./create":632,"./cross":633,"./distance":634,"./divide":635,"./dot":636,"./equals":637,"./fromScalar":638,"./fromValues":639,"./fromVec2":640,"./length":642,"./lerp":643,"./max":644,"./min":645,"./multiply":646,"./negate":647,"./normalize":648,"./orthogonal":649,"./rotateX":650,"./rotateY":651,"./rotateZ":652,"./scale":653,"./snap":654,"./squaredDistance":655,"./squaredLength":656,"./subtract":657,"./toString":658,"./transform":659,dup:233}],642:[function(e,t,n){arguments[4][234][0].apply(n,arguments)},{dup:234}],643:[function(e,t,n){arguments[4][235][0].apply(n,arguments)},{dup:235}],644:[function(e,t,n){arguments[4][236][0].apply(n,arguments)},{dup:236}],645:[function(e,t,n){arguments[4][237][0].apply(n,arguments)},{dup:237}],646:[function(e,t,n){arguments[4][238][0].apply(n,arguments)},{dup:238}],647:[function(e,t,n){arguments[4][239][0].apply(n,arguments)},{dup:239}],648:[function(e,t,n){arguments[4][240][0].apply(n,arguments)},{dup:240}],649:[function(e,t,n){arguments[4][241][0].apply(n,arguments)},{"./abs":627,"./create":632,"./cross":633,dup:241}],650:[function(e,t,n){arguments[4][242][0].apply(n,arguments)},{dup:242}],651:[function(e,t,n){arguments[4][243][0].apply(n,arguments)},{dup:243}],652:[function(e,t,n){arguments[4][244][0].apply(n,arguments)},{dup:244}],653:[function(e,t,n){arguments[4][245][0].apply(n,arguments)},{dup:245}],654:[function(e,t,n){arguments[4][246][0].apply(n,arguments)},{dup:246}],655:[function(e,t,n){arguments[4][247][0].apply(n,arguments)},{dup:247}],656:[function(e,t,n){arguments[4][248][0].apply(n,arguments)},{dup:248}],657:[function(e,t,n){arguments[4][249][0].apply(n,arguments)},{dup:249}],658:[function(e,t,n){arguments[4][250][0].apply(n,arguments)},{dup:250}],659:[function(e,t,n){arguments[4][251][0].apply(n,arguments)},{dup:251}],660:[function(e,t,n){arguments[4][252][0].apply(n,arguments)},{"./create":662,dup:252}],661:[function(e,t,n){arguments[4][253][0].apply(n,arguments)},{dup:253}],662:[function(e,t,n){arguments[4][254][0].apply(n,arguments)},{dup:254}],663:[function(e,t,n){arguments[4][255][0].apply(n,arguments)},{dup:255}],664:[function(e,t,n){arguments[4][256][0].apply(n,arguments)},{dup:256}],665:[function(e,t,n){arguments[4][257][0].apply(n,arguments)},{dup:257}],666:[function(e,t,n){arguments[4][258][0].apply(n,arguments)},{"./create":662,dup:258}],667:[function(e,t,n){arguments[4][259][0].apply(n,arguments)},{"./clone":660,"./copy":661,"./create":662,"./dot":663,"./equals":664,"./fromScalar":665,"./fromValues":666,"./toString":668,"./transform":669,dup:259}],668:[function(e,t,n){arguments[4][260][0].apply(n,arguments)},{dup:260}],669:[function(e,t,n){arguments[4][261][0].apply(n,arguments)},{dup:261}],670:[function(e,t,n){arguments[4][262][0].apply(n,arguments)},{"../maths/constants":513,dup:262}],671:[function(e,t,n){arguments[4][263][0].apply(n,arguments)},{"./measureAggregateArea":672,"./measureAggregateBoundingBox":673,"./measureAggregateEpsilon":674,"./measureAggregateVolume":675,"./measureArea":676,"./measureBoundingBox":677,"./measureBoundingSphere":678,"./measureCenter":679,"./measureCenterOfMass":680,"./measureDimensions":681,"./measureEpsilon":682,"./measureVolume":683,dup:263}],672:[function(e,t,n){arguments[4][264][0].apply(n,arguments)},{"../utils/flatten":817,"./measureArea":676,dup:264}],673:[function(e,t,n){arguments[4][265][0].apply(n,arguments)},{"../maths/vec3/max":644,"../maths/vec3/min":645,"../utils/flatten":817,"./measureBoundingBox":677,dup:265}],674:[function(e,t,n){arguments[4][266][0].apply(n,arguments)},{"../geometries":469,"../utils/flatten":817,"./calculateEpsilonFromBounds":670,"./measureAggregateBoundingBox":673,dup:266}],675:[function(e,t,n){arguments[4][267][0].apply(n,arguments)},{"../utils/flatten":817,"./measureVolume":683,dup:267}],676:[function(e,t,n){arguments[4][268][0].apply(n,arguments)},{"../geometries/geom2":444,"../geometries/geom3":460,"../geometries/path2":481,"../geometries/poly3":498,"../utils/flatten":817,dup:268}],677:[function(e,t,n){arguments[4][269][0].apply(n,arguments)},{"../geometries/geom2":444,"../geometries/geom3":460,"../geometries/path2":481,"../geometries/poly3":498,"../maths/vec2":610,"../maths/vec3":641,"../utils/flatten":817,dup:269}],678:[function(e,t,n){arguments[4][270][0].apply(n,arguments)},{"../geometries/geom2":444,"../geometries/geom3":460,"../geometries/path2":481,"../geometries/poly3":498,"../maths/vec2":610,"../maths/vec3":641,"../utils/flatten":817,dup:270}],679:[function(e,t,n){arguments[4][271][0].apply(n,arguments)},{"../utils/flatten":817,"./measureBoundingBox":677,dup:271}],680:[function(e,t,n){arguments[4][272][0].apply(n,arguments)},{"../geometries/geom2":444,"../geometries/geom3":460,"../maths/vec3":641,"../utils/flatten":817,dup:272}],681:[function(e,t,n){arguments[4][273][0].apply(n,arguments)},{"../utils/flatten":817,"./measureBoundingBox":677,dup:273}],682:[function(e,t,n){arguments[4][274][0].apply(n,arguments)},{"../geometries":469,"../utils/flatten":817,"./calculateEpsilonFromBounds":670,"./measureBoundingBox":677,dup:274}],683:[function(e,t,n){arguments[4][275][0].apply(n,arguments)},{"../geometries/geom2":444,"../geometries/geom3":460,"../geometries/path2":481,"../geometries/poly3":498,"../utils/flatten":817,dup:275}],684:[function(e,t,n){arguments[4][276][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../maths/vec2":610,dup:276}],685:[function(e,t,n){arguments[4][277][0].apply(n,arguments)},{"./intersect":686,"./scission":691,"./subtract":693,"./union":704,dup:277}],686:[function(e,t,n){arguments[4][278][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/geom3":460,"../../utils/areAllShapesTheSameType":815,"../../utils/flatten":817,"./intersectGeom2":687,"./intersectGeom3":688,dup:278}],687:[function(e,t,n){arguments[4][279][0].apply(n,arguments)},{"../../geometries/geom3":460,"../../measurements/measureEpsilon":682,"../../utils/flatten":817,"./fromFakePolygons":684,"./intersectGeom3":688,"./to3DWalls":697,dup:279}],688:[function(e,t,n){arguments[4][280][0].apply(n,arguments)},{"../../utils/flatten":817,"../modifiers/retessellate":775,"./intersectGeom3Sub":689,dup:280}],689:[function(e,t,n){arguments[4][281][0].apply(n,arguments)},{"../../geometries/geom3":460,"./mayOverlap":690,"./trees":701,dup:281}],690:[function(e,t,n){arguments[4][282][0].apply(n,arguments)},{"../../maths/constants":513,"../../measurements/measureBoundingBox":677,dup:282}],691:[function(e,t,n){arguments[4][283][0].apply(n,arguments)},{"../../geometries/geom3":460,"../../utils/flatten":817,"./scissionGeom3":692,dup:283}],692:[function(e,t,n){arguments[4][284][0].apply(n,arguments)},{"../../geometries/geom3":460,"../../maths/vec3":641,"../../measurements/measureEpsilon":682,dup:284}],693:[function(e,t,n){arguments[4][285][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/geom3":460,"../../utils/areAllShapesTheSameType":815,"../../utils/flatten":817,"./subtractGeom2":694,"./subtractGeom3":695,dup:285}],694:[function(e,t,n){arguments[4][286][0].apply(n,arguments)},{"../../geometries/geom3":460,"../../measurements/measureEpsilon":682,"../../utils/flatten":817,"./fromFakePolygons":684,"./subtractGeom3":695,"./to3DWalls":697,dup:286}],695:[function(e,t,n){arguments[4][287][0].apply(n,arguments)},{"../../utils/flatten":817,"../modifiers/retessellate":775,"./subtractGeom3Sub":696,dup:287}],696:[function(e,t,n){arguments[4][288][0].apply(n,arguments)},{"../../geometries/geom3":460,"./mayOverlap":690,"./trees":701,dup:288}],697:[function(e,t,n){arguments[4][289][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/geom3":460,"../../geometries/poly3":498,"../../maths/vec3":641,dup:289}],698:[function(e,t,n){arguments[4][290][0].apply(n,arguments)},{"../../../geometries/poly3":498,"../../../maths/plane":582,dup:290}],699:[function(e,t,n){arguments[4][291][0].apply(n,arguments)},{"../../../geometries/poly3":498,"../../../maths/constants":513,"../../../maths/vec3":641,"./splitPolygonByPlane":703,dup:291}],700:[function(e,t,n){arguments[4][292][0].apply(n,arguments)},{"./Node":698,"./PolygonTreeNode":699,dup:292}],701:[function(e,t,n){arguments[4][293][0].apply(n,arguments)},{"./Tree":700,dup:293}],702:[function(e,t,n){arguments[4][294][0].apply(n,arguments)},{"../../../maths/vec3":641,dup:294}],703:[function(e,t,n){arguments[4][295][0].apply(n,arguments)},{"../../../geometries/poly3":498,"../../../maths/constants":513,"../../../maths/plane":582,"../../../maths/vec3":641,"./splitLineSegmentByPlane":702,dup:295}],704:[function(e,t,n){arguments[4][296][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/geom3":460,"../../utils/areAllShapesTheSameType":815,"../../utils/flatten":817,"./unionGeom2":705,"./unionGeom3":706,dup:296}],705:[function(e,t,n){arguments[4][297][0].apply(n,arguments)},{"../../geometries/geom3":460,"../../measurements/measureEpsilon":682,"../../utils/flatten":817,"./fromFakePolygons":684,"./to3DWalls":697,"./unionGeom3":706,dup:297}],706:[function(e,t,n){arguments[4][298][0].apply(n,arguments)},{"../../utils/flatten":817,"../modifiers/retessellate":775,"./unionGeom3Sub":707,dup:298}],707:[function(e,t,n){arguments[4][299][0].apply(n,arguments)},{"../../geometries/geom3":460,"./mayOverlap":690,"./trees":701,dup:299}],708:[function(e,t,n){arguments[4][300][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/geom3":460,"../../geometries/path2":481,"../../utils/flatten":817,"./expandGeom2":709,"./expandGeom3":710,"./expandPath2":711,dup:300}],709:[function(e,t,n){arguments[4][301][0].apply(n,arguments)},{"../../geometries/geom2":444,"./offsetFromPoints":716,dup:301}],710:[function(e,t,n){arguments[4][302][0].apply(n,arguments)},{"../../geometries/geom3":460,"../booleans/union":704,"./expandShell":712,dup:302}],711:[function(e,t,n){arguments[4][303][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/path2":481,"../../maths/utils/area":587,"../../maths/vec2":610,"./offsetFromPoints":716,dup:303}],712:[function(e,t,n){arguments[4][304][0].apply(n,arguments)},{"../../geometries/geom3":460,"../../geometries/poly3":498,"../../maths/constants":513,"../../maths/mat4":562,"../../maths/vec3":641,"../../primitives/sphere":805,"../../utils/fnNumberSort":818,"../booleans/unionGeom3Sub":707,"../modifiers/retessellate":775,"./extrudePolygon":713,dup:304}],713:[function(e,t,n){arguments[4][305][0].apply(n,arguments)},{"../../geometries/geom3":460,"../../geometries/poly3":498,"../../maths/mat4":562,"../../maths/vec3":641,dup:305}],714:[function(e,t,n){arguments[4][306][0].apply(n,arguments)},{"./expand":708,"./offset":715,dup:306}],715:[function(e,t,n){arguments[4][307][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/path2":481,"../../utils/flatten":817,"./offsetGeom2":717,"./offsetPath2":718,dup:307}],716:[function(e,t,n){arguments[4][308][0].apply(n,arguments)},{"../../maths/constants":513,"../../maths/line2":524,"../../maths/utils/area":587,"../../maths/utils/intersect":590,"../../maths/vec2":610,dup:308}],717:[function(e,t,n){arguments[4][309][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/poly2":492,"./offsetFromPoints":716,dup:309}],718:[function(e,t,n){arguments[4][310][0].apply(n,arguments)},{"../../geometries/path2":481,"./offsetFromPoints":716,dup:310}],719:[function(e,t,n){arguments[4][311][0].apply(n,arguments)},{"../../../geometries/geom2":444,"../../../geometries/poly2":492,"../../../maths/utils":588,dup:311}],720:[function(e,t,n){arguments[4][312][0].apply(n,arguments)},{"./linkedPolygon":724,"./triangle":726,dup:312}],721:[function(e,t,n){arguments[4][313][0].apply(n,arguments)},{"./eliminateHoles":720,"./linkedList":722,"./linkedPolygon":724,"./triangle":726,dup:313}],722:[function(e,t,n){arguments[4][314][0].apply(n,arguments)},{"./linkedListSort":723,dup:314}],723:[function(e,t,n){arguments[4][315][0].apply(n,arguments)},{dup:315}],724:[function(e,t,n){arguments[4][316][0].apply(n,arguments)},{"./linkedList":722,"./triangle":726,dup:316}],725:[function(e,t,n){arguments[4][317][0].apply(n,arguments)},{"../../../geometries/geom2":444,"../../../maths/plane":582,"../../../maths/vec2":610,"../../../maths/vec3":641,"../slice/calculatePlane":739,"./assignHoles":719,dup:317}],726:[function(e,t,n){arguments[4][318][0].apply(n,arguments)},{dup:318}],727:[function(e,t,n){arguments[4][319][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/geom3":460,"../../geometries/poly3":498,"../../maths/mat4":562,"./extrudeWalls":736,"./slice":745,"./slice/repair":747,dup:319}],728:[function(e,t,n){arguments[4][320][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../maths/constants":513,"../../maths/mat4":562,"./extrudeFromSlices":727,"./slice":745,dup:320}],729:[function(e,t,n){arguments[4][321][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/path2":481,"../../utils/flatten":817,"./extrudeLinearGeom2":730,"./extrudeLinearPath2":731,dup:321}],730:[function(e,t,n){arguments[4][322][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../maths/mat4":562,"../../maths/vec3":641,"./extrudeFromSlices":727,"./slice":745,dup:322}],731:[function(e,t,n){arguments[4][323][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/path2":481,"./extrudeLinearGeom2":730,dup:323}],732:[function(e,t,n){arguments[4][324][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/path2":481,"../../utils/flatten":817,"./extrudeRectangularGeom2":733,"./extrudeRectangularPath2":734,dup:324}],733:[function(e,t,n){arguments[4][325][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/path2":481,"../../maths/utils":588,"../expansions/expand":708,"./extrudeLinearGeom2":730,dup:325}],734:[function(e,t,n){arguments[4][326][0].apply(n,arguments)},{"../../geometries/path2":481,"../expansions/expand":708,"./extrudeLinearGeom2":730,dup:326}],735:[function(e,t,n){const{TAU:o}=e("../../maths/constants"),r=e("../../maths/mat4"),{mirrorX:s}=e("../transforms/mirror"),a=e("../../geometries/geom2"),i=e("./slice"),c=e("./extrudeFromSlices");t.exports=(e,t)=>{const n={segments:12,startAngle:0,angle:o,overflow:"cap"};let{segments:l,startAngle:u,angle:p,overflow:f}=Object.assign({},n,e);if(l<3)throw new Error("segments must be greater then 3");u=Math.abs(u)>o?u%o:u,p=Math.abs(p)>o?p%o:p;let h=u+p;if(h=Math.abs(h)>o?h%o:h,hl*e&&l++}let g=a.toSides(t);if(0===g.length)throw new Error("the given geometry cannot be empty");const d=g.filter((e=>e[0][0]<0)),y=g.filter((e=>e[0][0]>=0));d.length>0&&y.length>0&&"cap"===f&&(d.length>y.length?(g=g.map((e=>{let t=e[0],n=e[1];return t=[Math.min(t[0],0),t[1]],n=[Math.min(n[0],0),n[1]],[t,n]})),t=a.create(g),t=s(t)):y.length>=d.length&&(g=g.map((e=>{let t=e[0],n=e[1];return t=[Math.max(t[0],0),t[1]],n=[Math.max(n[0],0),n[1]],[t,n]})),t=a.create(g)));const v=m/l,b=Math.abs(m){let s=v*t+u;return m===o&&t===l&&(s=u),r.multiply(A,r.fromZRotation(A,s),r.fromXRotation(r.create(),o/4)),i.transform(A,n)}},x)}},{"../../geometries/geom2":444,"../../maths/constants":513,"../../maths/mat4":562,"../transforms/mirror":782,"./extrudeFromSlices":727,"./slice":745}],736:[function(e,t,n){arguments[4][328][0].apply(n,arguments)},{"../../geometries/poly3":498,"../../maths/constants":513,"../../maths/vec3":641,"./slice":745,dup:328}],737:[function(e,t,n){arguments[4][329][0].apply(n,arguments)},{"./extrudeFromSlices":727,"./extrudeHelical":728,"./extrudeLinear":729,"./extrudeRectangular":732,"./extrudeRotate":735,"./project":738,"./slice":745,dup:329}],738:[function(e,t,n){arguments[4][330][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/geom3":460,"../../geometries/poly3":498,"../../maths/mat4":562,"../../maths/plane":582,"../../maths/utils/aboutEqualNormals":586,"../../measurements/measureEpsilon":682,"../../utils/flatten":817,"../booleans/unionGeom2":705,dup:330}],739:[function(e,t,n){arguments[4][331][0].apply(n,arguments)},{"../../../maths/plane":582,"../../../maths/vec3":641,dup:331}],740:[function(e,t,n){arguments[4][332][0].apply(n,arguments)},{"../../../maths/vec3":641,"./create":741,dup:332}],741:[function(e,t,n){arguments[4][333][0].apply(n,arguments)},{dup:333}],742:[function(e,t,n){arguments[4][334][0].apply(n,arguments)},{"../../../maths/vec3":641,dup:334}],743:[function(e,t,n){arguments[4][335][0].apply(n,arguments)},{"../../../maths/vec3":641,"./create":741,dup:335}],744:[function(e,t,n){arguments[4][336][0].apply(n,arguments)},{"../../../maths/vec3":641,"./create":741,dup:336}],745:[function(e,t,n){arguments[4][337][0].apply(n,arguments)},{"./calculatePlane":739,"./clone":740,"./create":741,"./equals":742,"./fromPoints":743,"./fromSides":744,"./isA":746,"./reverse":748,"./toEdges":749,"./toPolygons":750,"./toString":751,"./transform":752,dup:337}],746:[function(e,t,n){arguments[4][338][0].apply(n,arguments)},{dup:338}],747:[function(e,t,n){arguments[4][339][0].apply(n,arguments)},{"../../../maths/vec3":641,"./create":741,dup:339}],748:[function(e,t,n){arguments[4][340][0].apply(n,arguments)},{"./create":741,dup:340}],749:[function(e,t,n){arguments[4][341][0].apply(n,arguments)},{dup:341}],750:[function(e,t,n){arguments[4][342][0].apply(n,arguments)},{"../../../geometries/poly3":498,"../earcut":721,"../earcut/polygonHierarchy":725,dup:342}],751:[function(e,t,n){arguments[4][343][0].apply(n,arguments)},{"../../../maths/vec3":641,dup:343}],752:[function(e,t,n){arguments[4][344][0].apply(n,arguments)},{"../../../maths/vec3":641,"./create":741,dup:344}],753:[function(e,t,n){arguments[4][345][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/geom3":460,"../../geometries/path2":481,"../../utils/areAllShapesTheSameType":815,"../../utils/flatten":817,"./hullGeom2":755,"./hullGeom3":756,"./hullPath2":757,dup:345}],754:[function(e,t,n){arguments[4][346][0].apply(n,arguments)},{"../../utils/flatten":817,"../booleans/union":704,"./hull":753,dup:346}],755:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../geometries/geom2"),s=e("./hullPoints2"),a=e("./toUniquePoints");t.exports=(...e)=>{e=o(e);const t=a(e),n=s(t);return n.length<3?r.create():r.fromPoints(n)}},{"../../geometries/geom2":444,"../../utils/flatten":817,"./hullPoints2":758,"./toUniquePoints":769}],756:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../geometries/geom3"),s=e("./toUniquePoints"),a=e("./hullPoints3");t.exports=(...e)=>{e=o(e);const t=s(e);return 0===t.length?r.create():r.create(a(t))}},{"../../geometries/geom3":460,"../../utils/flatten":817,"./hullPoints3":759,"./toUniquePoints":769}],757:[function(e,t,n){const o=e("../../utils/flatten"),r=e("../../geometries/path2"),s=e("./hullPoints2"),a=e("./toUniquePoints");t.exports=(...e)=>{e=o(e);const t=a(e),n=s(t);return r.fromPoints({closed:!0},n)}},{"../../geometries/path2":481,"../../utils/flatten":817,"./hullPoints2":758,"./toUniquePoints":769}],758:[function(e,t,n){const o=e("../../maths/vec2");t.exports=e=>{let t=o.fromValues(1/0,1/0);e.forEach((e=>{(e[1]{const r=(a=e[1]-t[1],i=e[0]-t[0],0===a&&0===i?-1/0:-i/a),s=o.squaredDistance(e,t);var a,i;n.push({point:e,angle:r,distSq:s})})),n.sort(((e,t)=>e.angle!==t.angle?e.angle-t.angle:e.distSq-t.distSq));const r=[];return n.forEach((e=>{let t=r.length;for(;t>1&&(n=r[t-2],o=r[t-1],s=e.point,(o[0]-n[0])*(s[1]-n[1])-(o[1]-n[1])*(s[0]-n[0])<=Number.EPSILON);)r.pop(),t=r.length;var n,o,s;r.push(e.point)})),r}},{"../../maths/vec2":610}],759:[function(e,t,n){const o=e("../../geometries/poly3"),r=e("./quickhull");t.exports=e=>r(e,{skipTriangulation:!0}).map((t=>{const n=t.map((t=>e[t]));return o.create(n)}))},{"../../geometries/poly3":498,"./quickhull":767}],760:[function(e,t,n){t.exports={hull:e("./hull"),hullChain:e("./hullChain"),hullPoints2:e("./hullPoints2"),hullPoints3:e("./hullPoints3")}},{"./hull":753,"./hullChain":754,"./hullPoints2":758,"./hullPoints3":759}],761:[function(e,t,n){arguments[4][352][0].apply(n,arguments)},{"../../../maths/vec3/add":628,"../../../maths/vec3/copy":631,"../../../maths/vec3/cross":633,"../../../maths/vec3/dot":636,"../../../maths/vec3/length":642,"../../../maths/vec3/normalize":648,"../../../maths/vec3/scale":653,"../../../maths/vec3/subtract":657,"./HalfEdge":762,dup:352}],762:[function(e,t,n){arguments[4][353][0].apply(n,arguments)},{"../../../maths/vec3/distance":634,"../../../maths/vec3/squaredDistance":655,dup:353}],763:[function(e,t,n){arguments[4][354][0].apply(n,arguments)},{"../../../maths/vec3/dot":636,"./Face":761,"./Vertex":764,"./VertexList":765,"./get-plane-normal":766,"./point-line-distance":768,dup:354}],764:[function(e,t,n){arguments[4][355][0].apply(n,arguments)},{dup:355}],765:[function(e,t,n){arguments[4][356][0].apply(n,arguments)},{dup:356}],766:[function(e,t,n){arguments[4][357][0].apply(n,arguments)},{"../../../maths/vec3/cross":633,"../../../maths/vec3/normalize":648,"../../../maths/vec3/subtract":657,dup:357}],767:[function(e,t,n){arguments[4][358][0].apply(n,arguments)},{"./QuickHull":763,dup:358}],768:[function(e,t,n){arguments[4][359][0].apply(n,arguments)},{"../../../maths/vec3/cross":633,"../../../maths/vec3/squaredLength":656,"../../../maths/vec3/subtract":657,dup:359}],769:[function(e,t,n){arguments[4][360][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/geom3":460,"../../geometries/path2":481,dup:360}],770:[function(e,t,n){arguments[4][361][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/geom3":460,"../../geometries/path2":481,"../../measurements/measureEpsilon":682,"../../utils/flatten":817,"./insertTjunctions":772,"./mergePolygons":773,"./snapPolygons":777,"./triangulatePolygons":778,dup:361}],771:[function(e,t,n){arguments[4][362][0].apply(n,arguments)},{"./generalize":770,"./retessellate":775,"./snap":776,dup:362}],772:[function(e,t,n){arguments[4][363][0].apply(n,arguments)},{"../../geometries/poly3":498,"../../maths/constants":513,"../../maths/vec3":641,dup:363}],773:[function(e,t,n){arguments[4][364][0].apply(n,arguments)},{"../../geometries/poly3":498,"../../maths/utils/aboutEqualNormals":586,"../../maths/vec3":641,dup:364}],774:[function(e,t,n){arguments[4][365][0].apply(n,arguments)},{"../../geometries/poly3":498,"../../maths/OrthoNormalBasis":512,"../../maths/constants":513,"../../maths/line2":524,"../../maths/utils/interpolateBetween2DPointsForY":589,"../../maths/vec2":610,"../../utils":819,dup:365}],775:[function(e,t,n){arguments[4][366][0].apply(n,arguments)},{"../../geometries/geom3":460,"../../geometries/poly3":498,"../../maths/constants":513,"./reTesselateCoplanarPolygons":774,dup:366}],776:[function(e,t,n){arguments[4][367][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/geom3":460,"../../geometries/path2":481,"../../maths/vec2":610,"../../measurements/measureEpsilon":682,"../../utils/flatten":817,"./snapPolygons":777,dup:367}],777:[function(e,t,n){arguments[4][368][0].apply(n,arguments)},{"../../geometries/poly3":498,"../../maths/vec3":641,dup:368}],778:[function(e,t,n){arguments[4][369][0].apply(n,arguments)},{"../../geometries/poly3":498,"../../maths/vec3":641,dup:369}],779:[function(e,t,n){arguments[4][370][0].apply(n,arguments)},{"../../measurements/measureAggregateBoundingBox":673,"../../utils/flatten":817,"../../utils/padArrayToLength":821,"./translate":786,dup:370}],780:[function(e,t,n){arguments[4][371][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/geom3":460,"../../geometries/path2":481,"../../measurements/measureBoundingBox":677,"../../utils/flatten":817,"./translate":786,dup:371}],781:[function(e,t,n){arguments[4][372][0].apply(n,arguments)},{"./align":779,"./center":780,"./mirror":782,"./rotate":783,"./scale":784,"./transform":785,"./translate":786,dup:372}],782:[function(e,t,n){arguments[4][373][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/geom3":460,"../../geometries/path2":481,"../../maths/mat4":562,"../../maths/plane":582,"../../utils/flatten":817,dup:373}],783:[function(e,t,n){arguments[4][374][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/geom3":460,"../../geometries/path2":481,"../../maths/mat4":562,"../../utils/flatten":817,dup:374}],784:[function(e,t,n){arguments[4][375][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/geom3":460,"../../geometries/path2":481,"../../maths/mat4":562,"../../utils/flatten":817,dup:375}],785:[function(e,t,n){arguments[4][376][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/geom3":460,"../../geometries/path2":481,"../../utils/flatten":817,dup:376}],786:[function(e,t,n){arguments[4][377][0].apply(n,arguments)},{"../../geometries/geom2":444,"../../geometries/geom3":460,"../../geometries/path2":481,"../../maths/mat4":562,"../../utils/flatten":817,dup:377}],787:[function(e,t,n){arguments[4][378][0].apply(n,arguments)},{"../geometries/path2":481,"../maths/constants":513,"../maths/vec2":610,"./commonChecks":789,dup:378}],788:[function(e,t,n){arguments[4][379][0].apply(n,arguments)},{"../maths/constants":513,"./commonChecks":789,"./ellipse":794,dup:379}],789:[function(e,t,n){arguments[4][380][0].apply(n,arguments)},{dup:380}],790:[function(e,t,n){arguments[4][381][0].apply(n,arguments)},{"./commonChecks":789,"./cuboid":791,dup:381}],791:[function(e,t,n){arguments[4][382][0].apply(n,arguments)},{"../geometries/geom3":460,"../geometries/poly3":498,"./commonChecks":789,dup:382}],792:[function(e,t,n){arguments[4][383][0].apply(n,arguments)},{"../geometries/geom3":460,"./commonChecks":789,"./cylinderElliptic":793,dup:383}],793:[function(e,t,n){arguments[4][384][0].apply(n,arguments)},{"../geometries/geom3":460,"../geometries/poly3":498,"../maths/constants":513,"../maths/utils/trigonometry":592,"../maths/vec3":641,"./commonChecks":789,dup:384}],794:[function(e,t,n){arguments[4][385][0].apply(n,arguments)},{"../geometries/geom2":444,"../maths/constants":513,"../maths/utils/trigonometry":592,"../maths/vec2":610,"./commonChecks":789,dup:385}],795:[function(e,t,n){arguments[4][386][0].apply(n,arguments)},{"../geometries/geom3":460,"../geometries/poly3":498,"../maths/constants":513,"../maths/utils/trigonometry":592,"../maths/vec3":641,"./commonChecks":789,dup:386}],796:[function(e,t,n){arguments[4][387][0].apply(n,arguments)},{"../geometries/geom3":460,"../maths/mat4":562,"../maths/vec3":641,"./commonChecks":789,"./polyhedron":800,dup:387}],797:[function(e,t,n){arguments[4][388][0].apply(n,arguments)},{"./arc":787,"./circle":788,"./cube":790,"./cuboid":791,"./cylinder":792,"./cylinderElliptic":793,"./ellipse":794,"./ellipsoid":795,"./geodesicSphere":796,"./line":798,"./polygon":799,"./polyhedron":800,"./rectangle":801,"./roundedCuboid":802,"./roundedCylinder":803,"./roundedRectangle":804,"./sphere":805,"./square":806,"./star":807,"./torus":808,"./triangle":809,dup:388}],798:[function(e,t,n){arguments[4][389][0].apply(n,arguments)},{"../geometries/path2":481,dup:389}],799:[function(e,t,n){const o=e("../geometries/geom2");t.exports=e=>{const{points:t,paths:n,orientation:r}=Object.assign({},{points:[],paths:[],orientation:"counterclockwise"},e);if(!Array.isArray(t)||!Array.isArray(n))throw new Error("points and paths must be arrays");let s=t;Array.isArray(t[0])&&(Array.isArray(t[0][0])||(s=[t])),s.forEach(((e,t)=>{if(!Array.isArray(e))throw new Error("list of points "+t+" must be an array");if(e.length<3)throw new Error("list of points "+t+" must contain three or more points");e.forEach(((e,n)=>{if(!Array.isArray(e))throw new Error("list of points "+t+", point "+n+" must be an array");if(e.length<2)throw new Error("list of points "+t+", point "+n+" must contain by X and Y values")}))}));let a=n;if(0===n.length){let e=0;a=s.map((t=>t.map((t=>e++))))}const i=[];s.forEach((e=>e.forEach((e=>i.push(e)))));let c=[];a.forEach((e=>{const t=e.map((e=>i[e])),n=o.fromPoints(t);c=c.concat(o.toSides(n))}));let l=o.create(c);return"clockwise"==r&&(l=o.reverse(l)),l}},{"../geometries/geom2":444}],800:[function(e,t,n){arguments[4][391][0].apply(n,arguments)},{"../geometries/geom3":460,"../geometries/poly3":498,"./commonChecks":789,dup:391}],801:[function(e,t,n){arguments[4][392][0].apply(n,arguments)},{"../geometries/geom2":444,"../maths/vec2":610,"./commonChecks":789,dup:392}],802:[function(e,t,n){const{EPS:o,TAU:r}=e("../maths/constants"),s=e("../maths/vec2"),a=e("../maths/vec3"),i=e("../geometries/geom3"),c=e("../geometries/poly3"),{sin:l,cos:u}=e("../maths/utils/trigonometry"),{isGTE:p,isNumberArray:f}=e("./commonChecks"),h=e("./cuboid"),m=(e,t,n,i,c,p)=>{const f=r/4*c/i,h=u(f),m=l(f),g=i-c;let d=n*h,y=t[2]-(n-n*m);p||(y=n-n*m-t[2]),d=d>o?d:0;const v=a.add(a.create(),e,[t[0]-n,t[1]-n,y]),b=a.add(a.create(),e,[n-t[0],t[1]-n,y]),x=a.add(a.create(),e,[n-t[0],n-t[1],y]),A=a.add(a.create(),e,[t[0]-n,n-t[1],y]),E=[],w=[],S=[],T=[];for(let e=0;e<=g;e++){const t=g>0?r/4*e/g:0,n=s.fromAngleRadians(s.create(),t);s.scale(n,n,d);const o=a.fromVec2(a.create(),n);E.push(a.add(a.create(),v,o)),a.rotateZ(o,o,[0,0,0],r/4),w.push(a.add(a.create(),b,o)),a.rotateZ(o,o,[0,0,0],r/4),S.push(a.add(a.create(),x,o)),a.rotateZ(o,o,[0,0,0],r/4),T.push(a.add(a.create(),A,o))}return p?[E,w,S,T]:(E.reverse(),w.reverse(),S.reverse(),T.reverse(),[T,S,w,E])},g=(e,t)=>{const n=[];for(let o=0;o{const n=[];for(let o=0;o{e=(e=[e[3],e[2],e[1],e[0]]).map((e=>e.slice().reverse()));const n=[];e.forEach((e=>{e.forEach((e=>n.push(e)))}));const o=[];t.forEach((e=>{e.forEach((e=>o.push(e)))}));const r=[];for(let e=0;e{let{center:t,size:n,roundRadius:r,segments:s}=Object.assign({},{center:[0,0,0],size:[2,2,2],roundRadius:.2,segments:32},e);if(!f(t,3))throw new Error("center must be an array of X, Y and Z values");if(!f(n,3))throw new Error("size must be an array of X, Y and Z values");if(!n.every((e=>e>=0)))throw new Error("size values must be positive");if(!p(r,0))throw new Error("roundRadius must be positive");if(!p(s,4))throw new Error("segments must be four or more");if(0===n[0]||0===n[1]||0===n[2])return i.create();if(0===r)return h({center:t,size:n});if(n=n.map((e=>e/2)),r>n[0]-o||r>n[1]-o||r>n[2]-o)throw new Error("roundRadius must be smaller than the radius of all dimensions");s=Math.floor(s/4);let a=null,l=null,u=[];for(let e=0;e<=s;e++){const o=m(t,n,r,s,e,!0),i=m(t,n,r,s,e,!1);if(0===e&&(u=u.concat(y(i,o))),a&&(u=u.concat(g(a,o),d(a,o))),l&&(u=u.concat(g(l,i),d(l,i))),e===s){let e=o.map((e=>e[0]));u.push(c.create(e)),e=i.map((e=>e[0])),u.push(c.create(e))}a=o,l=i}return i.create(u)}},{"../geometries/geom3":460,"../geometries/poly3":498,"../maths/constants":513,"../maths/utils/trigonometry":592,"../maths/vec2":610,"../maths/vec3":641,"./commonChecks":789,"./cuboid":791}],803:[function(e,t,n){const{EPS:o,TAU:r}=e("../maths/constants"),s=e("../maths/vec3"),a=e("../geometries/geom3"),i=e("../geometries/poly3"),{sin:c,cos:l}=e("../maths/utils/trigonometry"),{isGTE:u,isNumberArray:p}=e("./commonChecks"),f=e("./cylinder");t.exports=e=>{const{center:t,height:n,radius:h,roundRadius:m,segments:g}=Object.assign({},{center:[0,0,0],height:2,radius:1,roundRadius:.2,segments:32},e);if(!p(t,3))throw new Error("center must be an array of X, Y and Z values");if(!u(n,0))throw new Error("height must be positive");if(!u(h,0))throw new Error("radius must be positive");if(!u(m,0))throw new Error("roundRadius must be positive");if(m>h)throw new Error("roundRadius must be smaller than the radius");if(!u(g,4))throw new Error("segments must be four or more");if(0===n||0===h)return a.create();if(0===m)return f({center:t,height:n,radius:h});const d=[0,0,-n/2],y=[0,0,n/2],v=s.subtract(s.create(),y,d);if(2*m>s.length(v)-o)throw new Error("height must be larger than twice roundRadius");let b;b=Math.abs(v[0])>Math.abs(v[1])?s.fromValues(0,1,0):s.fromValues(1,0,0);const x=s.scale(s.create(),s.normalize(s.create(),v),m),A=s.scale(s.create(),s.normalize(s.create(),s.cross(s.create(),x,b)),h),E=s.scale(s.create(),s.normalize(s.create(),s.cross(s.create(),A,x)),h);s.add(d,d,x),s.subtract(y,y,x);const w=Math.floor(.25*g),S=e=>{const n=e.map((e=>s.add(e,e,t)));return i.create(n)},T=[],P=s.create(),D=s.create();let C;for(let e=0;e<=g;e++){const t=r*e/g,n=s.add(s.create(),s.scale(P,A,l(t)),s.scale(D,E,c(t)));if(e>0){let e,t,o=[];o.push(s.add(s.create(),d,n)),o.push(s.add(s.create(),d,C)),o.push(s.add(s.create(),y,C)),o.push(s.add(s.create(),y,n)),T.push(S(o));for(let a=0;a<=w;a++){const i=r/4*a/w,u=l(i),p=c(i);if(a>0){let r;o=[],r=s.add(s.create(),d,s.subtract(P,s.scale(P,C,e),s.scale(D,x,t))),o.push(r),r=s.add(s.create(),d,s.subtract(P,s.scale(P,n,e),s.scale(D,x,t))),o.push(r),a{let{center:t,size:n,roundRadius:u,segments:p}=Object.assign({},{center:[0,0],size:[2,2],roundRadius:.2,segments:32},e);if(!c(t,2))throw new Error("center must be an array of X and Y values");if(!c(n,2))throw new Error("size must be an array of X and Y values");if(!n.every((e=>e>=0)))throw new Error("size values must be positive");if(!i(u,0))throw new Error("roundRadius must be positive");if(!i(p,4))throw new Error("segments must be four or more");if(0===n[0]||0===n[1])return a.create();if(0===u)return l({center:t,size:n});if(n=n.map((e=>e/2)),u>n[0]-o||u>n[1]-o)throw new Error("roundRadius must be smaller than the radius of all dimensions");const f=Math.floor(p/4),h=s.add(s.create(),t,[n[0]-u,n[1]-u]),m=s.add(s.create(),t,[u-n[0],n[1]-u]),g=s.add(s.create(),t,[u-n[0],u-n[1]]),d=s.add(s.create(),t,[n[0]-u,u-n[1]]),y=[],v=[],b=[],x=[];for(let e=0;e<=f;e++){const t=r/4*e/f,n=s.fromAngleRadians(s.create(),t);s.scale(n,n,u),y.push(s.add(s.create(),h,n)),s.rotate(n,n,s.create(),r/4),v.push(s.add(s.create(),m,n)),s.rotate(n,n,s.create(),r/4),b.push(s.add(s.create(),g,n)),s.rotate(n,n,s.create(),r/4),x.push(s.add(s.create(),d,n))}return a.fromPoints(y.concat(v,b,x))}},{"../geometries/geom2":444,"../maths/constants":513,"../maths/vec2":610,"./commonChecks":789,"./rectangle":801}],805:[function(e,t,n){arguments[4][396][0].apply(n,arguments)},{"./commonChecks":789,"./ellipsoid":795,dup:396}],806:[function(e,t,n){arguments[4][397][0].apply(n,arguments)},{"./commonChecks":789,"./rectangle":801,dup:397}],807:[function(e,t,n){arguments[4][398][0].apply(n,arguments)},{"../geometries/geom2":444,"../maths/constants":513,"../maths/vec2":610,"./commonChecks":789,dup:398}],808:[function(e,t,n){arguments[4][399][0].apply(n,arguments)},{"../maths/constants":513,"../operations/extrusions/extrudeRotate":735,"../operations/transforms/rotate":783,"../operations/transforms/translate":786,"./circle":788,"./commonChecks":789,dup:399}],809:[function(e,t,n){arguments[4][400][0].apply(n,arguments)},{"../geometries/geom2":444,"../maths/constants":513,"../maths/vec2":610,"./commonChecks":789,dup:400}],810:[function(e,t,n){arguments[4][401][0].apply(n,arguments)},{dup:401}],811:[function(e,t,n){arguments[4][402][0].apply(n,arguments)},{"./vectorChar":812,"./vectorText":814,dup:402}],812:[function(e,t,n){arguments[4][403][0].apply(n,arguments)},{"./vectorParams":813,dup:403}],813:[function(e,t,n){arguments[4][404][0].apply(n,arguments)},{"./fonts/single-line/hershey/simplex.js":810,dup:404}],814:[function(e,t,n){arguments[4][405][0].apply(n,arguments)},{"./vectorChar":812,"./vectorParams":813,dup:405}],815:[function(e,t,n){arguments[4][406][0].apply(n,arguments)},{"../geometries/geom2":444,"../geometries/geom3":460,"../geometries/path2":481,dup:406}],816:[function(e,t,n){arguments[4][407][0].apply(n,arguments)},{dup:407}],817:[function(e,t,n){arguments[4][408][0].apply(n,arguments)},{dup:408}],818:[function(e,t,n){arguments[4][409][0].apply(n,arguments)},{dup:409}],819:[function(e,t,n){arguments[4][410][0].apply(n,arguments)},{"./areAllShapesTheSameType":815,"./degToRad":816,"./flatten":817,"./fnNumberSort":818,"./insertSorted":820,"./radToDeg":822,"./radiusToSegments":823,dup:410}],820:[function(e,t,n){arguments[4][411][0].apply(n,arguments)},{dup:411}],821:[function(e,t,n){arguments[4][412][0].apply(n,arguments)},{dup:412}],822:[function(e,t,n){arguments[4][413][0].apply(n,arguments)},{dup:413}],823:[function(e,t,n){arguments[4][414][0].apply(n,arguments)},{"../maths/constants":513,dup:414}],824:[function(e,t,n){const{geometries:o}=e("@jscad/modeling"),r=(e,t)=>{const n=[];return o.geom3.toPolygons(e).forEach(((e,t)=>{n.push(i(e))})),n.join("\n")},s=e=>`${e[0]} ${e[1]} ${e[2]}`,a=e=>`vertex ${s(e)}`,i=e=>{const t=[];if(e.vertices.length>=3){const n=a(e.vertices[0]);for(let r=0;r{t.statusCallback&&t.statusCallback({progress:0});const n=`solid JSCAD\n${((e,t)=>{const n=[];return e.forEach(((o,s)=>{n.push(r(o,t)),t.statusCallback&&t.statusCallback({progress:100*s/e.length})})),n.join("\n")})(e,t)}\nendsolid JSCAD\n`;return t.statusCallback&&t.statusCallback({progress:100}),[n]}}},{"@jscad/modeling":511}],825:[function(e,t,n){const{geometries:o}=e("@jscad/modeling");t.exports={serializeBinary:(e,t)=>{t.statusCallback&&t.statusCallback({progress:0});const n=new ArrayBuffer(4),r=new Int32Array(n,0,1),s=new Int8Array(n,0,4);if(r[0]=287454020,68!==s[0])throw new Error("Binary STL output is currently only supported on little-endian (Intel) processors");let a=0,i=0;e.forEach(((e,t)=>{o.geom3.toPolygons(e).forEach((e=>{const t=e.vertices.length;a+=t>=3?t-2:0,i+=1}))}));const c=new Uint8Array(80);for(let e=0;e<80;e++)c[e]=65;const l=new Uint32Array(1);l[0]=a;const u=new ArrayBuffer(50*a),p=new Int8Array(u),f=new ArrayBuffer(50),h=new Int8Array(f),m=new Float32Array(f,0,12),g=new Uint16Array(f,48,1);let d=0;return e.forEach((e=>{o.geom3.toPolygons(e).forEach(((e,n)=>{const r=e.vertices,s=r.length,a=o.poly3.plane(e);for(let e=0;e0?e:0)];m[t++]=o[0],m[t++]=o[1],m[t++]=o[2]}g[0]=0,p.set(h,d),d+=50}t.statusCallback&&t.statusCallback({progress:100*n/i})}))})),t.statusCallback&&t.statusCallback({progress:100}),[c.buffer,l.buffer,u]}}},{"@jscad/modeling":511}],826:[function(e,t,n){const{geometries:o,modifiers:r}=e("@jscad/modeling"),{flatten:s,toArray:a}=e("@jscad/array-utils"),{serializeBinary:i}=e("./CSGToStlb"),{serializeText:c}=e("./CSGToStla");t.exports={mimeType:"application/sla",serialize:(e,...t)=>{e=Object.assign({},{binary:!0,statusCallback:null},e);let n=(t=s(t)).filter((e=>o.geom3.isA(e)));if(0===n.length)throw new Error("only 3D geometries can be serialized to STL");return t.length!==n.length&&console.warn("some objects could not be serialized to STL"),n=a(r.generalize({snap:!0,triangulate:!0},n)),e.binary?i(n,e):c(n,e)}}},{"./CSGToStla":824,"./CSGToStlb":825,"@jscad/array-utils":6,"@jscad/modeling":511}],827:[function(e,t,n){var o=e("./node-worker.cjs"),r=Uint8Array,s=Uint16Array,a=Uint32Array,i=new r([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),c=new r([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),l=new r([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),u=function(e,t){for(var n=new s(31),o=0;o<31;++o)n[o]=t+=1<>>1|(21845&v)<<1;b=(61680&(b=(52428&b)>>>2|(13107&b)<<2))>>>4|(3855&b)<<4,y[v]=((65280&b)>>>8|(255&b)<<8)>>>1}var x=function(e,t,n){for(var o=e.length,r=0,a=new s(t);r>>l]=u}else for(i=new s(o),r=0;r>>15-e[r]);return i},A=new r(288);for(v=0;v<144;++v)A[v]=8;for(v=144;v<256;++v)A[v]=9;for(v=256;v<280;++v)A[v]=7;for(v=280;v<288;++v)A[v]=8;var E=new r(32);for(v=0;v<32;++v)E[v]=5;var w=x(A,9,0),S=x(A,9,1),T=x(E,5,0),P=x(E,5,1),D=function(e){for(var t=e[0],n=1;nt&&(t=e[n]);return t},C=function(e,t,n){var o=t/8|0;return(e[o]|e[o+1]<<8)>>(7&t)&n},M=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(7&t)},R=function(e){return(e+7)/8|0},I=function(e,t,n){(null==t||t<0)&&(t=0),(null==n||n>e.length)&&(n=e.length);var o=new(2==e.BYTES_PER_ELEMENT?s:4==e.BYTES_PER_ELEMENT?a:r)(n-t);return o.set(e.subarray(t,n)),o};n.FlateErrorCode={UnexpectedEOF:0,InvalidBlockType:1,InvalidLengthLiteral:2,InvalidDistance:3,StreamFinished:4,NoStreamHandler:5,InvalidHeader:6,NoCallback:7,InvalidUTF8:8,ExtraFieldTooLong:9,InvalidDate:10,FilenameTooLong:11,StreamFinishing:12,InvalidZipData:13,UnknownCompressionMethod:14};var L=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],B=function(e,t,n){var o=new Error(t||L[e]);if(o.code=e,Error.captureStackTrace&&Error.captureStackTrace(o,B),!n)throw o;return o},$=function(e,t,n){var o=e.length;if(!o||n&&n.f&&!n.l)return t||new r(0);var s=!t||n,a=!n||n.i;n||(n={}),t||(t=new r(3*o));var u=function(e){var n=t.length;if(e>n){var o=new r(Math.max(2*n,e));o.set(t),t=o}},p=n.f||0,h=n.p||0,m=n.b||0,d=n.l,y=n.d,v=n.m,b=n.n,A=8*o;do{if(!d){p=C(e,h,1);var E=C(e,h+1,3);if(h+=3,!E){var w=e[(V=R(h)+4)-4]|e[V-3]<<8,T=V+w;if(T>o){a&&B(0);break}s&&u(m+w),t.set(e.subarray(V,T),m),n.b=m+=w,n.p=h=8*T,n.f=p;continue}if(1==E)d=S,y=P,v=9,b=5;else if(2==E){var L=C(e,h,31)+257,$=C(e,h+10,15)+4,O=L+C(e,h+5,31)+1;h+=14;for(var k=new r(O),N=new r(19),_=0;_<$;++_)N[l[_]]=C(e,h+3*_,7);h+=3*$;var F=D(N),z=(1<>>4)<16)k[_++]=V;else{var Y=0,q=0;for(16==V?(q=3+C(e,h,3),h+=2,Y=k[_-1]):17==V?(q=3+C(e,h,7),h+=3):18==V&&(q=11+C(e,h,127),h+=7);q--;)k[_++]=Y}}var G=k.subarray(0,L),X=k.subarray(L);v=D(G),b=D(X),d=x(G,v,1),y=x(X,b,1)}else B(1);if(h>A){a&&B(0);break}}s&&u(m+131072);for(var Z=(1<>>4;if((h+=15&Y)>A){a&&B(0);break}if(Y||B(2),K<256)t[m++]=K;else{if(256==K){W=h,d=null;break}var J=K-254;if(K>264){var Q=i[_=K-257];J=C(e,h,(1<>>4;if(ee||B(3),h+=15&ee,X=g[te],te>3&&(Q=c[te],X+=M(e,h)&(1<A){a&&B(0);break}s&&u(m+131072);for(var ne=m+J;m>>8},k=function(e,t,n){n<<=7&t;var o=t/8|0;e[o]|=n,e[o+1]|=n>>>8,e[o+2]|=n>>>16},N=function(e,t){for(var n=[],o=0;om&&(m=i[o].s);var g=new s(m+1),d=_(n[f-1],g,0);if(d>t){o=0;var y=0,v=d-t,b=1<t))break;y+=b-(1<>>=v;y>0;){var A=i[o].s;g[A]=0&&y;--o){var E=i[o].s;g[E]==t&&(--g[E],++y)}d=t}return[new r(g),d]},_=function(e,t,n){return-1==e.s?Math.max(_(e.l,t,n+1),_(e.r,t,n+1)):t[e.s]=n},F=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new s(++t),o=0,r=e[0],a=1,i=function(e){n[o++]=e},c=1;c<=t;++c)if(e[c]==r&&c!=t)++a;else{if(!r&&a>2){for(;a>138;a-=138)i(32754);a>2&&(i(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(i(r),--a;a>6;a-=6)i(8304);a>2&&(i(a-3<<5|8208),a=0)}for(;a--;)i(r);a=1,r=e[c]}return[n.subarray(0,o),t]},z=function(e,t){for(var n=0,o=0;o>>8,e[r+2]=255^e[r],e[r+3]=255^e[r+1];for(var s=0;s4&&!_[l[j-1]];--j);var Y,q,G,X,Z=h+5<<3,H=z(r,A)+z(a,E)+u,W=z(r,d)+z(a,b)+u+14+3*j+z(L,_)+(2*L[16]+3*L[17]+7*L[18]);if(Z<=H&&Z<=W)return U(t,m,e.subarray(f,f+h));if(O(t,m,1+(W15&&(O(t,m,ee[B]>>>5&127),m+=ee[B]>>>12)}}}else Y=w,q=A,G=T,X=E;for(B=0;B255){te=o[B]>>>18&31,k(t,m,Y[te+257]),m+=q[te+257],te>7&&(O(t,m,o[B]>>>23&31),m+=i[te]);var ne=31&o[B];k(t,m,G[ne]),m+=X[ne],ne>3&&(k(t,m,o[B]>>>5&8191),m+=c[ne])}else k(t,m,Y[o[B]]),m+=q[o[B]];return k(t,m,Y[256]),m+q[256]},j=new a([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Y=new r(0),q=function(e,t,n,o,l,u){var p=e.length,f=new r(o+p+5*(1+Math.ceil(p/7e3))+l),m=f.subarray(o,f.length-l),g=0;if(!t||p<8)for(var y=0;y<=p;y+=65535){var v=y+65535;v>=p&&(m[g>>3]=u),g=U(m,g+1,e.subarray(y,v))}else{for(var b=j[t-1],x=b>>>13,A=8191&b,E=(1<7e3||O>24576)&&q>423){g=V(e,m,0,C,M,L,$,O,N,y-N,g),O=B=$=0,N=y;for(var G=0;G<286;++G)M[G]=0;for(G=0;G<30;++G)L[G]=0}var X=2,Z=0,H=A,W=F-z&32767;if(q>2&&_==D(y-W))for(var K=Math.min(x,q)-1,J=Math.min(32767,y),Q=Math.min(258,q);W<=J&&--H&&F!=z;){if(e[y+X]==e[y+X-W]){for(var ee=0;eeX){if(X=ee,Z=W,ee>K)break;var te=Math.min(W,ee-2),ne=0;for(G=0;Gne&&(ne=re,z=oe)}}}W+=(F=z)-(z=w[F])+32768&32767}if(Z){C[O++]=268435456|h[X]<<18|d[Z];var se=31&h[X],ae=31&d[Z];$+=i[se]+c[ae],++M[257+se],++L[ae],k=y+X,++B}else C[O++]=e[y],++M[e[y]]}}g=V(e,m,u,C,M,L,$,O,N,y-N,g),!u&&7&g&&(g=U(m,g+1,Y))}return I(f,0,o+R(g)+l)},G=function(){for(var e=new Int32Array(256),t=0;t<256;++t){for(var n=t,o=9;--o;)n=(1&n&&-306674912)^n>>>1;e[t]=n}return e}(),X=function(){var e=-1;return{p:function(t){for(var n=e,o=0;o>>8;e=n},d:function(){return~e}}},Z=function(){var e=1,t=0;return{p:function(n){for(var o=e,r=t,s=0|n.length,a=0;a!=s;){for(var i=Math.min(a+2655,s);a>16),r=(65535&r)+15*(r>>16)}e=o,t=r},d:function(){return(255&(e%=65521))<<24|e>>>8<<16|(255&(t%=65521))<<8|t>>>8}}},H=function(e,t,n,o,r){return q(e,null==t.level?6:t.level,null==t.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):12+t.mem,n,o,!r)},W=function(e,t){var n={};for(var o in e)n[o]=e[o];for(var o in t)n[o]=t[o];return n},K=function(e,t,n){for(var o=e(),r=e.toString(),s=r.slice(r.indexOf("[")+1,r.lastIndexOf("]")).replace(/\s+/g,"").split(","),a=0;a>>0},he=function(e,t){return fe(e,t)+4294967296*fe(e,t+4)},me=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8},ge=function(e,t){var n=t.filename;if(e[0]=31,e[1]=139,e[2]=8,e[8]=t.level<2?4:9==t.level?2:0,e[9]=3,0!=t.mtime&&me(e,4,Math.floor(new Date(t.mtime||Date.now())/1e3)),n){e[3]=8;for(var o=0;o<=n.length;++o)e[o+10]=n.charCodeAt(o)}},de=function(e){31==e[0]&&139==e[1]&&8==e[2]||B(6,"invalid gzip data");var t=e[3],n=10;4&t&&(n+=e[10]|2+(e[11]<<8));for(var o=(t>>3&1)+(t>>4&1);o>0;o-=!e[n++]);return n+(2&t)},ye=function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0},ve=function(e){return 10+(e.filename&&e.filename.length+1||0)},be=function(e,t){var n=t.level,o=0==n?0:n<6?1:9==n?3:2;e[0]=120,e[1]=o<<6|(o?32-2*o:1)},xe=function(e){(8!=(15&e[0])||e[0]>>>4>7||(e[0]<<8|e[1])%31)&&B(6,"invalid zlib data"),32&e[1]&&B(6,"invalid zlib data: preset dictionaries not supported")};function Ae(e,t){return t||"function"!=typeof e||(t=e,e={}),this.ondata=t,e}var Ee=function(){function e(e,t){t||"function"!=typeof e||(t=e,e={}),this.ondata=t,this.o=e||{}}return e.prototype.p=function(e,t){this.ondata(H(e,this.o,0,0,!t),t)},e.prototype.push=function(e,t){this.ondata||B(5),this.d&&B(4),this.d=t,this.p(e,t||!1)},e}();n.Deflate=Ee;var we=function(){return function(e,t){ue([te,function(){return[le,Ee]}],this,Ae.call(this,e,t),(function(e){var t=new Ee(e.data);onmessage=le(t)}),6)}}();function Se(e,t,n){return n||(n=t,t={}),"function"!=typeof n&&B(7),ce(e,t,[te],(function(e){return ae(Te(e.data[0],e.data[1]))}),0,n)}function Te(e,t){return H(e,t||{},0,0)}n.AsyncDeflate=we,n.deflate=Se,n.deflateSync=Te;var Pe=function(){function e(e){this.s={},this.p=new r(0),this.ondata=e}return e.prototype.e=function(e){this.ondata||B(5),this.d&&B(4);var t=this.p.length,n=new r(t+e.length);n.set(this.p),n.set(e,t),this.p=n},e.prototype.c=function(e){this.d=this.s.i=e||!1;var t=this.s.b,n=$(this.p,this.o,this.s);this.ondata(I(n,t,this.s.b),this.d),this.o=I(n,this.s.b-32768),this.s.b=this.o.length,this.p=I(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(e,t){this.e(e),this.c(t)},e}();n.Inflate=Pe;var De=function(){return function(e){this.ondata=e,ue([ee,function(){return[le,Pe]}],this,0,(function(){var e=new Pe;onmessage=le(e)}),7)}}();function Ce(e,t,n){return n||(n=t,t={}),"function"!=typeof n&&B(7),ce(e,t,[ee],(function(e){return ae(Me(e.data[0],ie(e.data[1])))}),1,n)}function Me(e,t){return $(e,t)}n.AsyncInflate=De,n.inflate=Ce,n.inflateSync=Me;var Re=function(){function e(e,t){this.c=X(),this.l=0,this.v=1,Ee.call(this,e,t)}return e.prototype.push=function(e,t){Ee.prototype.push.call(this,e,t)},e.prototype.p=function(e,t){this.c.p(e),this.l+=e.length;var n=H(e,this.o,this.v&&ve(this.o),t&&8,!t);this.v&&(ge(n,this.o),this.v=0),t&&(me(n,n.length-8,this.c.d()),me(n,n.length-4,this.l)),this.ondata(n,t)},e}();n.Gzip=Re,n.Compress=Re;var Ie=function(){return function(e,t){ue([te,ne,function(){return[le,Ee,Re]}],this,Ae.call(this,e,t),(function(e){var t=new Re(e.data);onmessage=le(t)}),8)}}();function Le(e,t,n){return n||(n=t,t={}),"function"!=typeof n&&B(7),ce(e,t,[te,ne,function(){return[Be]}],(function(e){return ae(Be(e.data[0],e.data[1]))}),2,n)}function Be(e,t){t||(t={});var n=X(),o=e.length;n.p(e);var r=H(e,t,ve(t),8),s=r.length;return ge(r,t),me(r,s-8,n.d()),me(r,s-4,o),r}n.AsyncGzip=Ie,n.AsyncCompress=Ie,n.gzip=Le,n.compress=Le,n.gzipSync=Be,n.compressSync=Be;var $e=function(){function e(e){this.v=1,Pe.call(this,e)}return e.prototype.push=function(e,t){if(Pe.prototype.e.call(this,e),this.v){var n=this.p.length>3?de(this.p):4;if(n>=this.p.length&&!t)return;this.p=this.p.subarray(n),this.v=0}t&&(this.p.length<8&&B(6,"invalid gzip data"),this.p=this.p.subarray(0,-8)),Pe.prototype.c.call(this,t)},e}();n.Gunzip=$e;var Oe=function(){return function(e){this.ondata=e,ue([ee,oe,function(){return[le,Pe,$e]}],this,0,(function(){var e=new $e;onmessage=le(e)}),9)}}();function ke(e,t,n){return n||(n=t,t={}),"function"!=typeof n&&B(7),ce(e,t,[ee,oe,function(){return[Ne]}],(function(e){return ae(Ne(e.data[0]))}),3,n)}function Ne(e,t){return $(e.subarray(de(e),-8),t||new r(ye(e)))}n.AsyncGunzip=Oe,n.gunzip=ke,n.gunzipSync=Ne;var _e=function(){function e(e,t){this.c=Z(),this.v=1,Ee.call(this,e,t)}return e.prototype.push=function(e,t){Ee.prototype.push.call(this,e,t)},e.prototype.p=function(e,t){this.c.p(e);var n=H(e,this.o,this.v&&2,t&&4,!t);this.v&&(be(n,this.o),this.v=0),t&&me(n,n.length-4,this.c.d()),this.ondata(n,t)},e}();n.Zlib=_e;var Fe=function(){return function(e,t){ue([te,re,function(){return[le,Ee,_e]}],this,Ae.call(this,e,t),(function(e){var t=new _e(e.data);onmessage=le(t)}),10)}}();function ze(e,t){t||(t={});var n=Z();n.p(e);var o=H(e,t,2,4);return be(o,t),me(o,o.length-4,n.d()),o}n.AsyncZlib=Fe,n.zlib=function(e,t,n){return n||(n=t,t={}),"function"!=typeof n&&B(7),ce(e,t,[te,re,function(){return[ze]}],(function(e){return ae(ze(e.data[0],e.data[1]))}),4,n)},n.zlibSync=ze;var Ue=function(){function e(e){this.v=1,Pe.call(this,e)}return e.prototype.push=function(e,t){if(Pe.prototype.e.call(this,e),this.v){if(this.p.length<2&&!t)return;this.p=this.p.subarray(2),this.v=0}t&&(this.p.length<4&&B(6,"invalid zlib data"),this.p=this.p.subarray(0,-4)),Pe.prototype.c.call(this,t)},e}();n.Unzlib=Ue;var Ve=function(){return function(e){this.ondata=e,ue([ee,se,function(){return[le,Pe,Ue]}],this,0,(function(){var e=new Ue;onmessage=le(e)}),11)}}();function je(e,t,n){return n||(n=t,t={}),"function"!=typeof n&&B(7),ce(e,t,[ee,se,function(){return[Ye]}],(function(e){return ae(Ye(e.data[0],ie(e.data[1])))}),5,n)}function Ye(e,t){return $((xe(e),e.subarray(2,-4)),t)}n.AsyncUnzlib=Ve,n.unzlib=je,n.unzlibSync=Ye;var qe=function(){function e(e){this.G=$e,this.I=Pe,this.Z=Ue,this.ondata=e}return e.prototype.push=function(e,t){if(this.ondata||B(5),this.s)this.s.push(e,t);else{if(this.p&&this.p.length){var n=new r(this.p.length+e.length);n.set(this.p),n.set(e,this.p.length)}else this.p=e;if(this.p.length>2){var o=this,s=function(){o.ondata.apply(o,arguments)};this.s=31==this.p[0]&&139==this.p[1]&&8==this.p[2]?new this.G(s):8!=(15&this.p[0])||this.p[0]>>4>7||(this.p[0]<<8|this.p[1])%31?new this.I(s):new this.Z(s),this.s.push(this.p,t),this.p=null}}},e}();n.Decompress=qe;var Ge=function(){function e(e){this.G=Oe,this.I=De,this.Z=Ve,this.ondata=e}return e.prototype.push=function(e,t){qe.prototype.push.call(this,e,t)},e}();n.AsyncDecompress=Ge,n.decompress=function(e,t,n){return n||(n=t,t={}),"function"!=typeof n&&B(7),31==e[0]&&139==e[1]&&8==e[2]?ke(e,t,n):8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31?Ce(e,t,n):je(e,t,n)},n.decompressSync=function(e,t){return 31==e[0]&&139==e[1]&&8==e[2]?Ne(e,t):8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31?Me(e,t):Ye(e,t)};var Xe=function(e,t,n,o){for(var s in e){var a=e[s],i=t+s,c=o;Array.isArray(a)&&(c=W(o,a[1]),a=a[0]),a instanceof r?n[i]=[a,c]:(n[i+="/"]=[new r(0),c],Xe(a,i,n,o))}},Ze="undefined"!=typeof TextEncoder&&new TextEncoder,He="undefined"!=typeof TextDecoder&&new TextDecoder,We=0;try{He.decode(Y,{stream:!0}),We=1}catch(e){}var Ke=function(e){for(var t="",n=0;;){var o=e[n++],r=(o>127)+(o>223)+(o>239);if(n+r>e.length)return[t,I(e,n-1)];r?3==r?(o=((15&o)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t+=String.fromCharCode(55296|o>>10,56320|1023&o)):t+=1&r?String.fromCharCode((31&o)<<6|63&e[n++]):String.fromCharCode((15&o)<<12|(63&e[n++])<<6|63&e[n++]):t+=String.fromCharCode(o)}},Je=function(){function e(e){this.ondata=e,We?this.t=new TextDecoder:this.p=Y}return e.prototype.push=function(e,t){if(this.ondata||B(5),t=!!t,this.t)return this.ondata(this.t.decode(e,{stream:!0}),t),void(t&&(this.t.decode().length&&B(8),this.t=null));this.p||B(4);var n=new r(this.p.length+e.length);n.set(this.p),n.set(e,this.p.length);var o=Ke(n),s=o[0],a=o[1];t?(a.length&&B(8),this.p=null):this.p=a,this.ondata(s,t)},e}();n.DecodeUTF8=Je;var Qe=function(){function e(e){this.ondata=e}return e.prototype.push=function(e,t){this.ondata||B(5),this.d&&B(4),this.ondata(et(e),this.d=t||!1)},e}();function et(e,t){if(t){for(var n=new r(e.length),o=0;o>1)),i=0,c=function(e){a[i++]=e};for(o=0;oa.length){var l=new r(i+8+(s-o<<1));l.set(a),a=l}var u=e.charCodeAt(o);u<128||t?c(u):u<2048?(c(192|u>>6),c(128|63&u)):u>55295&&u<57344?(c(240|(u=65536+(1047552&u)|1023&e.charCodeAt(++o))>>18),c(128|u>>12&63),c(128|u>>6&63),c(128|63&u)):(c(224|u>>12),c(128|u>>6&63),c(128|63&u))}return I(a,0,i)}function tt(e,t){if(t){for(var n="",o=0;o65535&&B(9),t+=o+4}return t},it=function(e,t,n,o,r,s,a,i){var c=o.length,l=n.extra,u=i&&i.length,p=at(l);me(e,t,null!=a?33639248:67324752),t+=4,null!=a&&(e[t++]=20,e[t++]=n.os),e[t]=20,t+=2,e[t++]=n.flag<<1|(null==s&&8),e[t++]=r&&8,e[t++]=255&n.compression,e[t++]=n.compression>>8;var f=new Date(null==n.mtime?Date.now():n.mtime),h=f.getFullYear()-1980;if((h<0||h>119)&&B(10),me(e,t,h<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>>1),t+=4,null!=s&&(me(e,t,n.crc),me(e,t+4,s),me(e,t+8,n.size)),me(e,t+12,c),me(e,t+14,p),t+=16,null!=a&&(me(e,t,u),me(e,t+6,n.attrs),me(e,t+10,a),t+=14),e.set(o,t),t+=c,p)for(var m in l){var g=l[m],d=g.length;me(e,t,+m),me(e,t+2,d),e.set(g,t+4),t+=4+d}return u&&(e.set(i,t),t+=u),t},ct=function(e,t,n,o,r){me(e,t,101010256),me(e,t+8,n),me(e,t+10,n),me(e,t+12,o),me(e,t+16,r)},lt=function(){function e(e){this.filename=e,this.c=X(),this.size=0,this.compression=0}return e.prototype.process=function(e,t){this.ondata(null,e,t)},e.prototype.push=function(e,t){this.ondata||B(5),this.c.p(e),this.size+=e.length,t&&(this.crc=this.c.d()),this.process(e,t||!1)},e}();n.ZipPassThrough=lt;var ut=function(){function e(e,t){var n=this;t||(t={}),lt.call(this,e),this.d=new Ee(t,(function(e,t){n.ondata(null,e,t)})),this.compression=8,this.flag=nt(t.level)}return e.prototype.process=function(e,t){try{this.d.push(e,t)}catch(e){this.ondata(e,null,t)}},e.prototype.push=function(e,t){lt.prototype.push.call(this,e,t)},e}();n.ZipDeflate=ut;var pt=function(){function e(e,t){var n=this;t||(t={}),lt.call(this,e),this.d=new we(t,(function(e,t,o){n.ondata(e,t,o)})),this.compression=8,this.flag=nt(t.level),this.terminate=this.d.terminate}return e.prototype.process=function(e,t){this.d.push(e,t)},e.prototype.push=function(e,t){lt.prototype.push.call(this,e,t)},e}();n.AsyncZipDeflate=pt;var ft=function(){function e(e){this.ondata=e,this.u=[],this.d=1}return e.prototype.add=function(e){var t=this;if(this.ondata||B(5),2&this.d)this.ondata(B(4+8*(1&this.d),0,1),null,!1);else{var n=et(e.filename),o=n.length,s=e.comment,a=s&&et(s),i=o!=e.filename.length||a&&s.length!=a.length,c=o+at(e.extra)+30;o>65535&&this.ondata(B(11,0,1),null,!1);var l=new r(c);it(l,0,e,n,i);var u=[l],p=function(){for(var e=0,n=u;e65535&&S(B(11,0,1),null),w)if(d<16e4)try{S(null,Te(r,l))}catch(e){S(e,null)}else p.push(Se(r,l,S));else S(null,r)},d=0;d65535&&B(11);var y=p?Te(l,u):l,v=y.length,b=X();b.p(l),o.push(W(u,{size:l.length,crc:b.d(),c:y,f:S,m,u:f!=i.length||m&&h.length!=g,o:s,compression:p})),s+=30+f+d+v,a+=76+2*(f+d)+(g||0)+v}for(var x=new r(a+22),A=s,E=a-s,w=0;w0){var o=Math.min(this.c,e.length),s=e.subarray(0,o);if(this.c-=o,this.d?this.d.push(s,!this.c):this.k[0].push(s),(e=e.subarray(o)).length)return this.push(e,t)}else{var a=0,i=0,c=void 0,l=void 0;this.p.length?e.length?((l=new r(this.p.length+e.length)).set(this.p),l.set(e,this.p.length)):l=this.p:l=e;for(var u=l.length,p=this.c,f=p&&this.d,h=function(){var e,t=fe(l,i);if(67324752==t){a=1,c=i,m.d=null,m.c=0;var o=pe(l,i+6),r=pe(l,i+8),s=2048&o,f=8&o,h=pe(l,i+26),g=pe(l,i+28);if(u>i+30+h+g){var d=[];m.k.unshift(d),a=2;var y,v=fe(l,i+18),b=fe(l,i+22),x=tt(l.subarray(i+30,i+=30+h),!s);4294967295==v?(e=f?[-2]:st(l,i),v=e[0],b=e[1]):f&&(v=-1),i+=g,m.c=v;var A={name:x,compression:r,start:function(){if(A.ondata||B(5),v){var e=n.o[r];e||A.ondata(B(14,"unknown compression type "+r,1),null,!1),(y=v<0?new e(x):new e(x,v,b)).ondata=function(e,t,n){A.ondata(e,t,n)};for(var t=0,o=d;t=0&&(A.size=v,A.originalSize=b),m.onfile(A)}return"break"}if(p){if(134695760==t)return c=i+=12+(-2==p&&8),a=3,m.c=0,"break";if(33639248==t)return c=i-=4,a=3,m.c=0,"break"}},m=this;i65558)return i(B(13,0,1),null),s;var l=pe(e,c+8);if(l){var u=l,p=fe(e,c+16),f=4294967295==p;if(f){if(c=fe(e,c-12),101075792!=fe(e,c))return i(B(13,0,1),null),s;u=l=fe(e,c+32),p=fe(e,c+48)}for(var h=t&&t.filter,m=function(t){var n=rt(e,p,f),c=n[0],u=n[1],m=n[2],g=n[3],d=n[4],y=n[5],v=ot(e,y);p=d;var b=function(e,t){e?(s(),i(e,null)):(t&&(a[g]=t),--l||i(null,a))};if(!h||h({name:g,size:u,originalSize:m,compression:c}))if(c)if(8==c){var x=e.subarray(v,v+u);if(u<32e4)try{b(null,Me(x,new r(m)))}catch(e){b(e,null)}else o.push(Ce(x,{size:m},b))}else b(B(14,"unknown compression type "+c,1),null);else b(null,I(e,v,v+u));else b(null,null)},g=0;g65558)&&B(13);var s=pe(e,o+8);if(!s)return{};var a=fe(e,o+16),i=4294967295==a;i&&(o=fe(e,o-12),101075792!=fe(e,o)&&B(13),s=fe(e,o+32),a=fe(e,o+48));for(var c=t&&t.filter,l=0;l0&&(n="\n",o=function(e){var t=" ".repeat(e);return function(e){var n,o=[];return"string"!=typeof e?e:1===(n=e.split("\n")).length?t+e:(n.forEach((function(e){""!==e.trim()?o.push(t+e):o.push(e)})),o.join("\n"))}}(t)),function e(t){var r,s,a;return s="",a=!0,t.some((function(t,o,i){if(0===o)return r="<"+t,1===i.length||void 0;if(1===o){if((c=t)&&"[object Object]"===Object.prototype.toString.call(c))return Object.keys(t).forEach((function(e){r+=" "+e+'="'+t[e]+'"'})),2===i.length||void(r+=">");r+=">"}var c;switch(typeof t){case"string":case"number":case"boolean":case"undefined":return void(s+=t+n)}a=!1,s+=e(t)}))?r+"/>"+n:a?r+function(e){var t=e.split("\n"),n=[];return t.forEach((function(e){""!==e.trim()&&n.push(e)})),n.join("\n")}(s)+""+n:r+n+o(s)+""+n}(e)}},{}],830:[function(e,t,n){n.byteLength=function(e){var t=c(e),n=t[0],o=t[1];return 3*(n+o)/4-o},n.toByteArray=function(e){var t,n,o=c(e),a=o[0],i=o[1],l=new s(function(e,t,n){return 3*(t+n)/4-n}(0,a,i)),u=0,p=i>0?a-4:a;for(n=0;n>16&255,l[u++]=t>>8&255,l[u++]=255&t;return 2===i&&(t=r[e.charCodeAt(n)]<<2|r[e.charCodeAt(n+1)]>>4,l[u++]=255&t),1===i&&(t=r[e.charCodeAt(n)]<<10|r[e.charCodeAt(n+1)]<<4|r[e.charCodeAt(n+2)]>>2,l[u++]=t>>8&255,l[u++]=255&t),l},n.fromByteArray=function(e){for(var t,n=e.length,r=n%3,s=[],a=16383,i=0,c=n-r;ic?c:i+a));return 1===r?(t=e[n-1],s.push(o[t>>2]+o[t<<4&63]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],s.push(o[t>>10]+o[t>>4&63]+o[t<<2&63]+"=")),s.join("")};for(var o=[],r=[],s="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0;i<64;++i)o[i]=a[i],r[a.charCodeAt(i)]=i;function c(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function l(e,t,n){for(var r,s,a=[],i=t;i>18&63]+o[s>>12&63]+o[s>>6&63]+o[63&s]);return a.join("")}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63},{}],831:[function(e,t,n){(function(t){var o=e("base64-js"),r=e("ieee754");n.Buffer=t,n.SlowBuffer=function(e){return+e!=e&&(e=0),t.alloc(+e)},n.INSPECT_MAX_BYTES=50;var s=2147483647;function a(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');var n=new Uint8Array(e);return n.__proto__=t.prototype,n}function t(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return l(e)}return i(e,t,n)}function i(e,n,o){if("string"==typeof e)return function(e,n){if("string"==typeof n&&""!==n||(n="utf8"),!t.isEncoding(n))throw new TypeError("Unknown encoding: "+n);var o=0|f(e,n),r=a(o),s=r.write(e,n);return s!==o&&(r=r.slice(0,s)),r}(e,n);if(ArrayBuffer.isView(e))return u(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(F(e,ArrayBuffer)||e&&F(e.buffer,ArrayBuffer))return function(e,n,o){if(n<0||e.byteLength=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function f(e,n){if(t.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||F(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var o=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===o)return 0;for(var s=!1;;)switch(n){case"ascii":case"latin1":case"binary":return o;case"utf8":case"utf-8":return k(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*o;case"hex":return o>>>1;case"base64":return N(e).length;default:if(s)return r?-1:k(e).length;n=(""+n).toLowerCase(),s=!0}}function h(e,t,n){var o=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return C(this,t,n);case"utf8":case"utf-8":return S(this,t,n);case"ascii":return P(this,t,n);case"latin1":case"binary":return D(this,t,n);case"base64":return w(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,t,n);default:if(o)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),o=!0}}function m(e,t,n){var o=e[t];e[t]=e[n],e[n]=o}function g(e,n,o,r,s){if(0===e.length)return-1;if("string"==typeof o?(r=o,o=0):o>2147483647?o=2147483647:o<-2147483648&&(o=-2147483648),z(o=+o)&&(o=s?0:e.length-1),o<0&&(o=e.length+o),o>=e.length){if(s)return-1;o=e.length-1}else if(o<0){if(!s)return-1;o=0}if("string"==typeof n&&(n=t.from(n,r)),t.isBuffer(n))return 0===n.length?-1:d(e,n,o,r,s);if("number"==typeof n)return n&=255,"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(e,n,o):Uint8Array.prototype.lastIndexOf.call(e,n,o):d(e,[n],o,r,s);throw new TypeError("val must be string, number or Buffer")}function d(e,t,n,o,r){var s,a=1,i=e.length,c=t.length;if(void 0!==o&&("ucs2"===(o=String(o).toLowerCase())||"ucs-2"===o||"utf16le"===o||"utf-16le"===o)){if(e.length<2||t.length<2)return-1;a=2,i/=2,c/=2,n/=2}function l(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(r){var u=-1;for(s=n;si&&(n=i-c),s=n;s>=0;s--){for(var p=!0,f=0;fr&&(o=r):o=r;var s=t.length;o>s/2&&(o=s/2);for(var a=0;a>8,r=n%256,s.push(r),s.push(o);return s}(t,e.length-n),e,n,o)}function w(e,t,n){return 0===t&&n===e.length?o.fromByteArray(e):o.fromByteArray(e.slice(t,n))}function S(e,t,n){n=Math.min(e.length,n);for(var o=[],r=t;r239?4:l>223?3:l>191?2:1;if(r+p<=n)switch(p){case 1:l<128&&(u=l);break;case 2:128==(192&(s=e[r+1]))&&(c=(31&l)<<6|63&s)>127&&(u=c);break;case 3:s=e[r+1],a=e[r+2],128==(192&s)&&128==(192&a)&&(c=(15&l)<<12|(63&s)<<6|63&a)>2047&&(c<55296||c>57343)&&(u=c);break;case 4:s=e[r+1],a=e[r+2],i=e[r+3],128==(192&s)&&128==(192&a)&&128==(192&i)&&(c=(15&l)<<18|(63&s)<<12|(63&a)<<6|63&i)>65535&&c<1114112&&(u=c)}null===u?(u=65533,p=1):u>65535&&(u-=65536,o.push(u>>>10&1023|55296),u=56320|1023&u),o.push(u),r+=p}return function(e){var t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);for(var n="",o=0;ot&&(e+=" ... "),""},t.prototype.compare=function(e,n,o,r,s){if(F(e,Uint8Array)&&(e=t.from(e,e.offset,e.byteLength)),!t.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===n&&(n=0),void 0===o&&(o=e?e.length:0),void 0===r&&(r=0),void 0===s&&(s=this.length),n<0||o>e.length||r<0||s>this.length)throw new RangeError("out of range index");if(r>=s&&n>=o)return 0;if(r>=s)return-1;if(n>=o)return 1;if(this===e)return 0;for(var a=(s>>>=0)-(r>>>=0),i=(o>>>=0)-(n>>>=0),c=Math.min(a,i),l=this.slice(r,s),u=e.slice(n,o),p=0;p>>=0,isFinite(n)?(n>>>=0,void 0===o&&(o="utf8")):(o=n,n=void 0)}var r=this.length-t;if((void 0===n||n>r)&&(n=r),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");o||(o="utf8");for(var s=!1;;)switch(o){case"hex":return y(this,e,t,n);case"utf8":case"utf-8":return v(this,e,t,n);case"ascii":return b(this,e,t,n);case"latin1":case"binary":return x(this,e,t,n);case"base64":return A(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+o);o=(""+o).toLowerCase(),s=!0}},t.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var T=4096;function P(e,t,n){var o="";n=Math.min(e.length,n);for(var r=t;rr)&&(n=r);for(var s="",a=t;an)throw new RangeError("Trying to access beyond buffer length")}function I(e,n,o,r,s,a){if(!t.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(n>s||ne.length)throw new RangeError("Index out of range")}function L(e,t,n,o,r,s){if(n+o>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function B(e,t,n,o,s){return t=+t,n>>>=0,s||L(e,0,n,4),r.write(e,t,n,o,23,4),n+4}function $(e,t,n,o,s){return t=+t,n>>>=0,s||L(e,0,n,8),r.write(e,t,n,o,52,8),n+8}t.prototype.slice=function(e,n){var o=this.length;(e=~~e)<0?(e+=o)<0&&(e=0):e>o&&(e=o),(n=void 0===n?o:~~n)<0?(n+=o)<0&&(n=0):n>o&&(n=o),n>>=0,t>>>=0,n||R(e,t,this.length);for(var o=this[e],r=1,s=0;++s>>=0,t>>>=0,n||R(e,t,this.length);for(var o=this[e+--t],r=1;t>0&&(r*=256);)o+=this[e+--t]*r;return o},t.prototype.readUInt8=function(e,t){return e>>>=0,t||R(e,1,this.length),this[e]},t.prototype.readUInt16LE=function(e,t){return e>>>=0,t||R(e,2,this.length),this[e]|this[e+1]<<8},t.prototype.readUInt16BE=function(e,t){return e>>>=0,t||R(e,2,this.length),this[e]<<8|this[e+1]},t.prototype.readUInt32LE=function(e,t){return e>>>=0,t||R(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},t.prototype.readUInt32BE=function(e,t){return e>>>=0,t||R(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},t.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||R(e,t,this.length);for(var o=this[e],r=1,s=0;++s=(r*=128)&&(o-=Math.pow(2,8*t)),o},t.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||R(e,t,this.length);for(var o=t,r=1,s=this[e+--o];o>0&&(r*=256);)s+=this[e+--o]*r;return s>=(r*=128)&&(s-=Math.pow(2,8*t)),s},t.prototype.readInt8=function(e,t){return e>>>=0,t||R(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},t.prototype.readInt16LE=function(e,t){e>>>=0,t||R(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},t.prototype.readInt16BE=function(e,t){e>>>=0,t||R(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},t.prototype.readInt32LE=function(e,t){return e>>>=0,t||R(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},t.prototype.readInt32BE=function(e,t){return e>>>=0,t||R(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},t.prototype.readFloatLE=function(e,t){return e>>>=0,t||R(e,4,this.length),r.read(this,e,!0,23,4)},t.prototype.readFloatBE=function(e,t){return e>>>=0,t||R(e,4,this.length),r.read(this,e,!1,23,4)},t.prototype.readDoubleLE=function(e,t){return e>>>=0,t||R(e,8,this.length),r.read(this,e,!0,52,8)},t.prototype.readDoubleBE=function(e,t){return e>>>=0,t||R(e,8,this.length),r.read(this,e,!1,52,8)},t.prototype.writeUIntLE=function(e,t,n,o){e=+e,t>>>=0,n>>>=0,o||I(this,e,t,n,Math.pow(2,8*n)-1,0);var r=1,s=0;for(this[t]=255&e;++s>>=0,n>>>=0,o||I(this,e,t,n,Math.pow(2,8*n)-1,0);var r=n-1,s=1;for(this[t+r]=255&e;--r>=0&&(s*=256);)this[t+r]=e/s&255;return t+n},t.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||I(this,e,t,1,255,0),this[t]=255&e,t+1},t.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||I(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},t.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||I(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},t.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||I(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},t.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||I(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},t.prototype.writeIntLE=function(e,t,n,o){if(e=+e,t>>>=0,!o){var r=Math.pow(2,8*n-1);I(this,e,t,n,r-1,-r)}var s=0,a=1,i=0;for(this[t]=255&e;++s>>=0,!o){var r=Math.pow(2,8*n-1);I(this,e,t,n,r-1,-r)}var s=n-1,a=1,i=0;for(this[t+s]=255&e;--s>=0&&(a*=256);)e<0&&0===i&&0!==this[t+s+1]&&(i=1),this[t+s]=(e/a|0)-i&255;return t+n},t.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||I(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},t.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||I(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},t.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||I(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},t.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||I(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},t.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||I(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},t.prototype.writeFloatLE=function(e,t,n){return B(this,e,t,!0,n)},t.prototype.writeFloatBE=function(e,t,n){return B(this,e,t,!1,n)},t.prototype.writeDoubleLE=function(e,t,n){return $(this,e,t,!0,n)},t.prototype.writeDoubleBE=function(e,t,n){return $(this,e,t,!1,n)},t.prototype.copy=function(e,n,o,r){if(!t.isBuffer(e))throw new TypeError("argument should be a Buffer");if(o||(o=0),r||0===r||(r=this.length),n>=e.length&&(n=e.length),n||(n=0),r>0&&r=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-n=0;--a)e[a+n]=this[a+o];else Uint8Array.prototype.set.call(e,this.subarray(o,r),n);return s},t.prototype.fill=function(e,n,o,r){if("string"==typeof e){if("string"==typeof n?(r=n,n=0,o=this.length):"string"==typeof o&&(r=o,o=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!t.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){var s=e.charCodeAt(0);("utf8"===r&&s<128||"latin1"===r)&&(e=s)}}else"number"==typeof e&&(e&=255);if(n<0||this.length>>=0,o=void 0===o?this.length:o>>>0,e||(e=0),"number"==typeof e)for(a=n;a55295&&n<57344){if(!r){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(a+1===o){(t-=3)>-1&&s.push(239,191,189);continue}r=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),r=n;continue}n=65536+(r-55296<<10|n-56320)}else r&&(t-=3)>-1&&s.push(239,191,189);if(r=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function N(e){return o.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(O,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function _(e,t,n,o){for(var r=0;r=t.length||r>=e.length);++r)t[r+n]=e[r];return r}function F(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function z(e){return e!=e}}).call(this,e("buffer").Buffer)},{"base64-js":830,buffer:831,ieee754:832}],832:[function(e,t,n){n.read=function(e,t,n,o,r){var s,a,i=8*r-o-1,c=(1<>1,u=-7,p=n?r-1:0,f=n?-1:1,h=e[t+p];for(p+=f,s=h&(1<<-u)-1,h>>=-u,u+=i;u>0;s=256*s+e[t+p],p+=f,u-=8);for(a=s&(1<<-u)-1,s>>=-u,u+=o;u>0;a=256*a+e[t+p],p+=f,u-=8);if(0===s)s=1-l;else{if(s===c)return a?NaN:1/0*(h?-1:1);a+=Math.pow(2,o),s-=l}return(h?-1:1)*a*Math.pow(2,s-o)},n.write=function(e,t,n,o,r,s){var a,i,c,l=8*s-r-1,u=(1<>1,f=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,h=o?0:s-1,m=o?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,a=u):(a=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-a))<1&&(a--,c*=2),(t+=a+p>=1?f/c:f*Math.pow(2,1-p))*c>=2&&(a++,c/=2),a+p>=u?(i=0,a=u):a+p>=1?(i=(t*c-1)*Math.pow(2,r),a+=p):(i=t*Math.pow(2,p-1)*Math.pow(2,r),a=0));r>=8;e[n+h]=255&i,h+=m,i/=256,r-=8);for(a=a<0;e[n+h]=255&a,h+=m,a/=256,l-=8);e[n+h-m]|=128*g}},{}]},{},[1])}}]); \ No newline at end of file diff --git a/workers/bitbybit-manifold-webworker.js b/workers/bitbybit-manifold-webworker.js index 15c73fb..66a6079 100644 --- a/workers/bitbybit-manifold-webworker.js +++ b/workers/bitbybit-manifold-webworker.js @@ -1 +1 @@ -(()=>{"use strict";var t,e,r,n,o={644:(t,e,r)=>{r.r(e),r.d(e,{default:()=>n});const n=r.p+"static/js/manifold.cc2ddd38.wasm"},581:(t,e,r)=>{var n;r.r(e),r.d(e,{default:()=>o});const o=(n="file:///Users/matasubarevicius/Documents/MyProjects/bitbybit-ui/node_modules/manifold-3d/manifold.js",async function(t={}){var e,o,s=t,i=new Promise(((t,r)=>{e=t,o=r})),a="object"==typeof window,c="function"==typeof importScripts,u="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(u){const{createRequire:t}=await r.e(167).then(r.t.bind(r,167,23));var l=t("file:///Users/matasubarevicius/Documents/MyProjects/bitbybit-ui/node_modules/manifold-3d/manifold.js")}var d=!1;s.setup=function(){if(d)return;function t(t,e,r=(t=>t)){if(e)for(let n of e)t.push_back(r(n));return t}function e(t,e=(t=>t)){const r=[],n=t.size();for(let o=0;ot(new s.Vector_vec2,e,(t=>t instanceof Array?{x:t[0],y:t[1]}:t))))}function n(t){for(let e=0;et.min[e])),max:["x","y"].map((e=>t.max[e]))}},s.CrossSection.prototype.offset=function(t,e="Square",r=2,n=0){return this._Offset(t,function(t){return"Round"==t?1:"Miter"==t?2:0}(e),r,n)},s.CrossSection.prototype.extrude=function(t,e=0,r=0,n=[1,1],i=!1){n=o([n]);const a=s._Extrude(this._ToPolygons(),t,e,r,n);return i?a.translate([0,0,-t/2]):a},s.CrossSection.prototype.revolve=function(t=0,e=360){return s._Revolve(this._ToPolygons(),t,e)},s.CrossSection.prototype.add=function(t){return this._add(u(t))},s.CrossSection.prototype.subtract=function(t){return this._subtract(u(t))},s.CrossSection.prototype.intersect=function(t){return this._intersect(u(t))},s.CrossSection.prototype.toPolygons=function(){const t=this._ToPolygons(),e=function(t,e=(t=>t)){const r=[],n=t.size();for(let o=0;o[t.x,t.y]));return t.delete(),e},s.Manifold.prototype.smoothOut=function(t=60,e=0){return this._SmoothOut(t,e)},s.Manifold.prototype.warp=function(t){const e=Ce((function(e){const r=[z(e,"double"),z(e+8,"double"),z(e+16,"double")];t(r),q(e,r[0],"double"),q(e+8,r[1],"double"),q(e+16,r[2],"double")}),"vi"),r=this._Warp(e);Se(e);const n=r.status();if(0!==n.value)throw new s.ManifoldError(n.value);return r},s.Manifold.prototype.calculateNormals=function(t,e=60){return this._CalculateNormals(t,e)},s.Manifold.prototype.setProperties=function(t,e){const r=this.numProp(),n=Ce((function(n,o,s){const i=[];for(let e=0;et.min[e])),max:["x","y","z"].map((e=>t.max[e]))}};class l{constructor({numProp:t=3,triVerts:e=new Uint32Array,vertProperties:r=new Float32Array,mergeFromVert:n,mergeToVert:o,runIndex:s,runOriginalID:i,faceID:a,halfedgeTangent:c,runTransform:u}={}){this.numProp=t,this.triVerts=e,this.vertProperties=r,this.mergeFromVert=n,this.mergeToVert=o,this.runIndex=s,this.runOriginalID=i,this.faceID=a,this.halfedgeTangent=c,this.runTransform=u}get numTri(){return this.triVerts.length/3}get numVert(){return this.vertProperties.length/this.numProp}get numRun(){return this.runOriginalID.length}merge(){const{changed:t,mesh:e}=s._Merge(this);return Object.assign(this,{...e}),t}verts(t){return this.triVerts.subarray(3*t,3*(t+1))}position(t){return this.vertProperties.subarray(this.numProp*t,this.numProp*t+3)}extras(t){return this.vertProperties.subarray(this.numProp*t+3,this.numProp*(t+1))}tangent(t){return this.halfedgeTangent.subarray(4*t,4*(t+1))}transform(t){const e=new Array(16);for(const r of[0,1,2,3])for(const n of[0,1,2])e[4*r+n]=this.runTransform[12*t+3*r+n];return e[15]=1,e}}function h(t){return function(...e){1==e.length&&(e=e[0]);const r=new s.Vector_crossSection;for(const t of e)r.push_back(u(t));const n=s["_crossSection"+t](r);return r.delete(),n}}s.Mesh=l,s.Manifold.prototype.getMesh=function(t=-1){return new l(this._GetMeshJS(t))},s.ManifoldError=function(t,...e){let r="Unknown error";switch(t){case s.status.NonFiniteVertex.value:r="Non-finite vertex";break;case s.status.NotManifold.value:r="Not manifold";break;case s.status.VertexOutOfBounds.value:r="Vertex index out of bounds";break;case s.status.PropertiesWrongLength.value:r="Properties have wrong length";break;case s.status.MissingPositionProperties.value:r="Less than three properties";break;case s.status.MergeVectorsDifferentLengths.value:r="Merge vectors have different lengths";break;case s.status.MergeIndexOutOfBounds.value:r="Merge index out of bounds";break;case s.status.TransformWrongLength.value:r="Transform vector has wrong length";break;case s.status.RunIndexWrongLength.value:r="Run index vector has wrong length";break;case s.status.FaceIDWrongLength.value:r="Face ID vector has wrong length";case s.status.InvalidConstruction.value:r="Manifold constructed with invalid parameters"}const n=Error.apply(this,[r,...e]);n.name=this.name="ManifoldError",this.message=n.message,this.stack=n.stack,this.code=t},s.ManifoldError.prototype=Object.create(Error.prototype,{constructor:{value:s.ManifoldError,writable:!0,configurable:!0}}),s.CrossSection=function(t,e="Positive"){const o=r(t),s=new c(o,a(e));return n(o),s},s.CrossSection.ofPolygons=function(t,e="Positive"){return new s.CrossSection(t,e)},s.CrossSection.square=function(...t){let e;e=0==t.length?{x:1,y:1}:"number"==typeof t[0]?{x:t[0],y:t[0]}:o(t);const r=t[1]||!1;return s._Square(e,r)},s.CrossSection.circle=function(t,e=0){return s._Circle(t,e)},s.CrossSection.compose=h("Compose"),s.CrossSection.union=h("UnionN"),s.CrossSection.difference=h("DifferenceN"),s.CrossSection.intersection=h("IntersectionN"),s.CrossSection.hull=function(...e){1==e.length&&(e=e[0]);let r=new s.Vector_vec2;for(const n of e)if(n instanceof c)s._crossSectionCollectVertices(r,n);else if(n instanceof Array&&2==n.length&&"number"==typeof n[0])r.push_back({x:n[0],y:n[1]});else if(n.x)r.push_back(n);else{const e=2==n[0].length&&"number"==typeof n[0][0]||n[0].x?[n]:n;for(const n of e)t(r,n,(t=>t instanceof Array?{x:t[0],y:t[1]}:t))}const n=s._crossSectionHullPoints(r);return r.delete(),n},s.CrossSection.prototype=Object.create(c.prototype),Object.defineProperty(s.CrossSection,Symbol.hasInstance,{get:()=>t=>t instanceof c});const f=s.Manifold;function p(t){return function(...e){1==e.length&&(e=e[0]);const r=new s.Vector_manifold;for(const t of e)r.push_back(t);const n=s["_manifold"+t+"N"](r);return r.delete(),n}}s.Manifold=function(t){const e=new f(t),r=e.status();if(0!==r.value)throw new s.ManifoldError(r.value);return e},s.Manifold.ofMesh=function(t){return new s.Manifold(t)},s.Manifold.tetrahedron=function(){return s._Tetrahedron()},s.Manifold.cube=function(...t){let e;e=0==t.length?{x:1,y:1,z:1}:"number"==typeof t[0]?{x:t[0],y:t[0],z:t[0]}:i(t);const r=t[1]||!1;return s._Cube(e,r)},s.Manifold.cylinder=function(t,e,r=-1,n=0,o=!1){return s._Cylinder(t,e,r,n,o)},s.Manifold.sphere=function(t,e=0){return s._Sphere(t,e)},s.Manifold.smooth=function(e,r=[]){const n=new s.Vector_smoothness;t(n,r);const o=s._Smooth(e,n);return n.delete(),o},s.Manifold.extrude=function(t,e,r=0,n=0,o=[1,1],i=!1){return(t instanceof c?t:s.CrossSection(t,"Positive")).extrude(e,r,n,o,i)},s.Manifold.revolve=function(t,e=0,r=360){return(t instanceof c?t:s.CrossSection(t,"Positive")).revolve(e,r)},s.Manifold.reserveIDs=function(t){return s._ReserveIDs(t)},s.Manifold.compose=function(e){const r=new s.Vector_manifold;t(r,e);const n=s._manifoldCompose(r);return r.delete(),n},s.Manifold.union=p("Union"),s.Manifold.difference=p("Difference"),s.Manifold.intersection=p("Intersection"),s.Manifold.levelSet=function(t,e,r,n=0,o=-1){const i={min:{x:e.min[0],y:e.min[1],z:e.min[2]},max:{x:e.max[0],y:e.max[1],z:e.max[2]}},a=Ce((function(e){const r=z(e,"double"),n=z(e+8,"double"),o=z(e+16,"double");return t([r,n,o])}),"di"),c=s._LevelSet(a,i,r,n,o);return Se(a),c},s.Manifold.hull=function(...e){1==e.length&&(e=e[0]);let r=new s.Vector_vec3;for(const n of e)n instanceof f?s._manifoldCollectVertices(r,n):n instanceof Array&&3==n.length&&"number"==typeof n[0]?r.push_back({x:n[0],y:n[1],z:n[2]}):n.x?r.push_back(n):t(r,n,(t=>t instanceof Array?{x:t[0],y:t[1],z:t[2]}:t));const n=s._manifoldHullPoints(r);return r.delete(),n},s.Manifold.prototype=Object.create(f.prototype),Object.defineProperty(s.Manifold,Symbol.hasInstance,{get:()=>t=>t instanceof f}),s.triangulate=function(t,o=-1){const i=r(t),a=e(s._Triangulate(i,o),(t=>[t[0],t[1],t[2]]));return n(i),a}};var h,f,p,m=Object.assign({},s),v="";if(u){var y=l("fs"),g=l("path");v=l("url").fileURLToPath(new URL(r(581),r.b)),h=(t,e)=>(t=H(t)?new URL(t):g.normalize(t),y.readFileSync(t,e?void 0:"utf8")),p=t=>{var e=h(t,!0);return e.buffer||(e=new Uint8Array(e)),e},f=(t,e,r,n=!0)=>{t=H(t)?new URL(t):g.normalize(t),y.readFile(t,n?void 0:"utf8",((t,o)=>{t?r(t):e(n?o.buffer:o)}))},!s.thisProgram&&process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2)}else(a||c)&&(c?v=self.location.href:"undefined"!=typeof document&&document.currentScript&&(v=document.currentScript.src),n&&(v=n),v=v.startsWith("blob:")?"":v.substr(0,v.replace(/[?#].*/,"").lastIndexOf("/")+1),h=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},c&&(p=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),f=(t,e,r)=>{if(H(t)){var n=new XMLHttpRequest;return n.open("GET",t,!0),n.responseType="arraybuffer",n.onload=()=>{200==n.status||0==n.status&&n.response?e(n.response):r()},n.onerror=r,void n.send(null)}fetch(t,{credentials:"same-origin"}).then((t=>t.ok?t.arrayBuffer():Promise.reject(new Error(t.status+" : "+t.url)))).then(e,r)});s.print||console.log.bind(console);var b,C,S=s.printErr||console.error.bind(console);Object.assign(s,m),m=null,s.arguments&&s.arguments,s.thisProgram&&s.thisProgram,s.quit&&s.quit,s.wasmBinary&&(b=s.wasmBinary);var w,T,$,P,M,O,x,_,D=!1;function A(){var t=C.buffer;s.HEAP8=w=new Int8Array(t),s.HEAP16=$=new Int16Array(t),s.HEAPU8=T=new Uint8Array(t),s.HEAPU16=P=new Uint16Array(t),s.HEAP32=M=new Int32Array(t),s.HEAPU32=O=new Uint32Array(t),s.HEAPF32=x=new Float32Array(t),s.HEAPF64=_=new Float64Array(t)}var k=[],E=[],j=[],I=0,R=null,W=null;function F(t){s.onAbort?.(t),S(t="Aborted("+t+")"),D=!0,t+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(t);throw o(e),e}var V,N=t=>t.startsWith("data:application/octet-stream;base64,"),H=t=>t.startsWith("file://");function B(t){if(t==V&&b)return new Uint8Array(b);if(p)return p(t);throw"both async and sync fetching of the wasm failed"}function L(t,e,r){return function(t){return b?Promise.resolve().then((()=>B(t))):new Promise(((e,r)=>{f(t,(t=>e(new Uint8Array(t))),(n=>{try{e(B(t))}catch(t){r(t)}}))}))}(t).then((t=>WebAssembly.instantiate(t,e))).then(r,(t=>{S(`failed to asynchronously prepare wasm: ${t}`),F(t)}))}var U=t=>{for(;t.length>0;)t.shift()(s)};function z(t,e="i8"){switch(e.endsWith("*")&&(e="*"),e){case"i1":case"i8":return w[t>>>0];case"i16":return $[t>>>1>>>0];case"i32":return M[t>>>2>>>0];case"i64":F("to do getValue(i64) use WASM_BIGINT");case"float":return x[t>>>2>>>0];case"double":return _[t>>>3>>>0];case"*":return O[t>>>2>>>0];default:F(`invalid type for getValue: ${e}`)}}function q(t,e,r="i8"){switch(r.endsWith("*")&&(r="*"),r){case"i1":case"i8":w[t>>>0]=e;break;case"i16":$[t>>>1>>>0]=e;break;case"i32":M[t>>>2>>>0]=e;break;case"i64":F("to do setValue(i64) use WASM_BIGINT");case"float":x[t>>>2>>>0]=e;break;case"double":_[t>>>3>>>0]=e;break;case"*":O[t>>>2>>>0]=e;break;default:F(`invalid type for setValue: ${r}`)}}s.noExitRuntime;class G{constructor(t){this.excPtr=t,this.ptr=t-24}set_type(t){O[this.ptr+4>>>2>>>0]=t}get_type(){return O[this.ptr+4>>>2>>>0]}set_destructor(t){O[this.ptr+8>>>2>>>0]=t}get_destructor(){return O[this.ptr+8>>>2>>>0]}set_caught(t){t=t?1:0,w[this.ptr+12>>>0]=t}get_caught(){return 0!=w[this.ptr+12>>>0]}set_rethrown(t){t=t?1:0,w[this.ptr+13>>>0]=t}get_rethrown(){return 0!=w[this.ptr+13>>>0]}init(t,e){this.set_adjusted_ptr(0),this.set_type(t),this.set_destructor(e)}set_adjusted_ptr(t){O[this.ptr+16>>>2>>>0]=t}get_adjusted_ptr(){return O[this.ptr+16>>>2>>>0]}get_exception_ptr(){if(xe(this.get_type()))return O[this.excPtr>>>2>>>0];var t=this.get_adjusted_ptr();return 0!==t?t:this.excPtr}}var X={},Y=t=>{for(;t.length;){var e=t.pop();t.pop()(e)}};function Z(t){return this.fromWireType(O[t>>>2>>>0])}var J,K,Q,tt={},et={},rt={},nt=t=>{throw new J(t)},ot=(t,e,r)=>{function n(e){var n=r(e);n.length!==t.length&&nt("Mismatched type converter count");for(var o=0;o{et.hasOwnProperty(t)?o[e]=et[t]:(s.push(t),tt.hasOwnProperty(t)||(tt[t]=[]),tt[t].push((()=>{o[e]=et[t],++i===s.length&&n(o)})))})),0===s.length&&n(o)},st=t=>{for(var e="",r=t;T[r>>>0];)e+=K[T[r++>>>0]];return e},it=t=>{throw new Q(t)};function at(t,e,r={}){if(!("argPackAdvance"in e))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(t,e,r={}){var n=e.name;if(t||it(`type "${n}" must have a positive integer typeid pointer`),et.hasOwnProperty(t)){if(r.ignoreDuplicateRegistrations)return;it(`Cannot register type '${n}' twice`)}if(et[t]=e,delete rt[t],tt.hasOwnProperty(t)){var o=tt[t];delete tt[t],o.forEach((t=>t()))}}(t,e,r)}var ct,ut=t=>{it(t.$$.ptrType.registeredClass.name+" instance already deleted")},lt=!1,dt=t=>{},ht=t=>{t.count.value-=1,0===t.count.value&&(t=>{t.smartPtr?t.smartPtrType.rawDestructor(t.smartPtr):t.ptrType.registeredClass.rawDestructor(t.ptr)})(t)},ft=(t,e,r)=>{if(e===r)return t;if(void 0===r.baseClass)return null;var n=ft(t,e,r.baseClass);return null===n?null:r.downcast(n)},pt={},mt=[],vt=()=>{for(;mt.length;){var t=mt.pop();t.$$.deleteScheduled=!1,t.delete()}},yt={},gt=(t,e)=>(e.ptrType&&e.ptr||nt("makeClassHandle requires ptr and ptrType"),!!e.smartPtrType!=!!e.smartPtr&&nt("Both smartPtrType and smartPtr must be specified"),e.count={value:1},bt(Object.create(t,{$$:{value:e,writable:!0}})));var bt=t=>"undefined"==typeof FinalizationRegistry?(bt=t=>t,t):(lt=new FinalizationRegistry((t=>{ht(t.$$)})),bt=t=>{var e=t.$$;if(e.smartPtr){var r={$$:e};lt.register(t,r,t)}return t},dt=t=>lt.unregister(t),bt(t));function Ct(){}var St=(t,e)=>Object.defineProperty(e,"name",{value:t}),wt=(t,e,r)=>{if(void 0===t[e].overloadTable){var n=t[e];t[e]=function(...n){return t[e].overloadTable.hasOwnProperty(n.length)||it(`Function '${r}' called with an invalid number of arguments (${n.length}) - expects one of (${t[e].overloadTable})!`),t[e].overloadTable[n.length].apply(this,n)},t[e].overloadTable=[],t[e].overloadTable[n.argCount]=n}},Tt=(t,e,r)=>{s.hasOwnProperty(t)?((void 0===r||void 0!==s[t].overloadTable&&void 0!==s[t].overloadTable[r])&&it(`Cannot register public name '${t}' twice`),wt(s,t,t),s.hasOwnProperty(r)&&it(`Cannot register multiple overloads of a function with the same number of arguments (${r})!`),s[t].overloadTable[r]=e):(s[t]=e,void 0!==r&&(s[t].numArguments=r))};function $t(t,e,r,n,o,s,i,a){this.name=t,this.constructor=e,this.instancePrototype=r,this.rawDestructor=n,this.baseClass=o,this.getActualType=s,this.upcast=i,this.downcast=a,this.pureVirtualFunctions=[]}var Pt=(t,e,r)=>{for(;e!==r;)e.upcast||it(`Expected null or instance of ${r.name}, got an instance of ${e.name}`),t=e.upcast(t),e=e.baseClass;return t};function Mt(t,e){if(null===e)return this.isReference&&it(`null is not a valid ${this.name}`),0;e.$$||it(`Cannot pass "${Kt(e)}" as a ${this.name}`),e.$$.ptr||it(`Cannot pass deleted object as a pointer of type ${this.name}`);var r=e.$$.ptrType.registeredClass;return Pt(e.$$.ptr,r,this.registeredClass)}function Ot(t,e){var r;if(null===e)return this.isReference&&it(`null is not a valid ${this.name}`),this.isSmartPointer?(r=this.rawConstructor(),null!==t&&t.push(this.rawDestructor,r),r):0;e&&e.$$||it(`Cannot pass "${Kt(e)}" as a ${this.name}`),e.$$.ptr||it(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&e.$$.ptrType.isConst&&it(`Cannot convert argument of type ${e.$$.smartPtrType?e.$$.smartPtrType.name:e.$$.ptrType.name} to parameter type ${this.name}`);var n=e.$$.ptrType.registeredClass;if(r=Pt(e.$$.ptr,n,this.registeredClass),this.isSmartPointer)switch(void 0===e.$$.smartPtr&&it("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:e.$$.smartPtrType===this?r=e.$$.smartPtr:it(`Cannot convert argument of type ${e.$$.smartPtrType?e.$$.smartPtrType.name:e.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:r=e.$$.smartPtr;break;case 2:if(e.$$.smartPtrType===this)r=e.$$.smartPtr;else{var o=e.clone();r=this.rawShare(r,Gt.toHandle((()=>o.delete()))),null!==t&&t.push(this.rawDestructor,r)}break;default:it("Unsupporting sharing policy")}return r}function xt(t,e){if(null===e)return this.isReference&&it(`null is not a valid ${this.name}`),0;e.$$||it(`Cannot pass "${Kt(e)}" as a ${this.name}`),e.$$.ptr||it(`Cannot pass deleted object as a pointer of type ${this.name}`),e.$$.ptrType.isConst&&it(`Cannot convert argument of type ${e.$$.ptrType.name} to parameter type ${this.name}`);var r=e.$$.ptrType.registeredClass;return Pt(e.$$.ptr,r,this.registeredClass)}function _t(t,e,r,n,o,s,i,a,c,u,l){this.name=t,this.registeredClass=e,this.isReference=r,this.isConst=n,this.isSmartPointer=o,this.pointeeType=s,this.sharingPolicy=i,this.rawGetPointee=a,this.rawConstructor=c,this.rawShare=u,this.rawDestructor=l,o||void 0!==e.baseClass?this.toWireType=Ot:n?(this.toWireType=Mt,this.destructorFunction=null):(this.toWireType=xt,this.destructorFunction=null)}var Dt,At,kt=(t,e,r)=>{s.hasOwnProperty(t)||nt("Replacing nonexistent public symbol"),void 0!==s[t].overloadTable&&void 0!==r?s[t].overloadTable[r]=e:(s[t]=e,s[t].argCount=r)},Et=[],jt=t=>{var e=Et[t];return e||(t>=Et.length&&(Et.length=t+1),Et[t]=e=Dt.get(t)),e},It=(t,e)=>(...r)=>((t,e,r=[])=>{if(t.includes("j"))return((t,e,r)=>(t=t.replace(/p/g,"i"),(0,s["dynCall_"+t])(e,...r)))(t,e,r);var n=jt(e)(...r);return"p"==t[0]?n>>>0:n})(t,e,r),Rt=(t,e)=>{var r=(t=st(t)).includes("j")||t.includes("p")?It(t,e):jt(e);return"function"!=typeof r&&it(`unknown function pointer with signature ${t}: ${e}`),r},Wt=t=>{var e=Pe(t),r=st(e);return Oe(e),r},Ft=(t,e)=>{var r=[],n={};throw e.forEach((function t(e){n[e]||et[e]||(rt[e]?rt[e].forEach(t):(r.push(e),n[e]=!0))})),new At(`${t}: `+r.map(Wt).join([", "]))},Vt=(t,e)=>{for(var r=[],n=0;n>>2>>>0]);return r};function Nt(t){for(var e=1;e0?", ":"")+a),u+=(r||n?"var rv = ":"")+"invoker(fn"+(a.length>0?", ":"")+a+");\n",o)u+="runDestructors(destructors);\n";else for(c=e?1:2;c{const e=(t=t.trim()).indexOf("(");return-1!==e?t.substr(0,e):t},Ut=[],zt=[];function qt(t){(t>>>=0)>9&&0==--zt[t+1]&&(zt[t]=void 0,Ut.push(t))}var Gt={toValue:t=>(t||it("Cannot use deleted val. handle = "+t),zt[t]),toHandle:t=>{switch(t){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:{const e=Ut.pop()||zt.length;return zt[e]=t,zt[e+1]=1,e}}}},Xt={name:"emscripten::val",fromWireType:t=>{var e=Gt.toValue(t);return qt(t),e},toWireType:(t,e)=>Gt.toHandle(e),argPackAdvance:8,readValueFromPointer:Z,destructorFunction:null};function Yt(t){return at(t>>>=0,Xt)}var Zt=(t,e,r)=>{switch(e){case 1:return r?function(t){return this.fromWireType(w[t>>>0])}:function(t){return this.fromWireType(T[t>>>0])};case 2:return r?function(t){return this.fromWireType($[t>>>1>>>0])}:function(t){return this.fromWireType(P[t>>>1>>>0])};case 4:return r?function(t){return this.fromWireType(M[t>>>2>>>0])}:function(t){return this.fromWireType(O[t>>>2>>>0])};default:throw new TypeError(`invalid integer width (${e}): ${t}`)}},Jt=(t,e)=>{var r=et[t];return void 0===r&&it(`${e} has unknown type ${Wt(t)}`),r},Kt=t=>{if(null===t)return"null";var e=typeof t;return"object"===e||"array"===e||"function"===e?t.toString():""+t},Qt=(t,e)=>{switch(e){case 4:return function(t){return this.fromWireType(x[t>>>2>>>0])};case 8:return function(t){return this.fromWireType(_[t>>>3>>>0])};default:throw new TypeError(`invalid float width (${e}): ${t}`)}},te=(t,e,r)=>{switch(e){case 1:return r?t=>w[t>>>0]:t=>T[t>>>0];case 2:return r?t=>$[t>>>1>>>0]:t=>P[t>>>1>>>0];case 4:return r?t=>M[t>>>2>>>0]:t=>O[t>>>2>>>0];default:throw new TypeError(`invalid integer width (${e}): ${t}`)}},ee="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,re="undefined"!=typeof TextDecoder?new TextDecoder("utf-16le"):void 0,ne=(t,e)=>{for(var r=t,n=r>>1,o=n+e/2;!(n>=o)&&P[n>>>0];)++n;if((r=n<<1)-t>32&&re)return re.decode(T.subarray(t>>>0,r>>>0));for(var s="",i=0;!(i>=e/2);++i){var a=$[t+2*i>>>1>>>0];if(0==a)break;s+=String.fromCharCode(a)}return s},oe=(t,e,r)=>{if(r??=2147483647,r<2)return 0;for(var n=e,o=(r-=2)<2*t.length?r/2:t.length,s=0;s>>1>>>0]=i,e+=2}return $[e>>>1>>>0]=0,e-n},se=t=>2*t.length,ie=(t,e)=>{for(var r=0,n="";!(r>=e/4);){var o=M[t+4*r>>>2>>>0];if(0==o)break;if(++r,o>=65536){var s=o-65536;n+=String.fromCharCode(55296|s>>10,56320|1023&s)}else n+=String.fromCharCode(o)}return n},ae=(t,e,r)=>{if(e>>>=0,r??=2147483647,r<4)return 0;for(var n=e,o=n+r-4,s=0;s=55296&&i<=57343&&(i=65536+((1023&i)<<10)|1023&t.charCodeAt(++s)),M[e>>>2>>>0]=i,(e+=4)+4>o)break}return M[e>>>2>>>0]=0,e-n},ce=t=>{for(var e=0,r=0;r=55296&&n<=57343&&++r,e+=4}return e},ue=(t,e,r)=>{var n=[],o=t.toWireType(n,r);return n.length&&(O[e>>>2>>>0]=Gt.toHandle(n)),o},le={},de=t=>{var e=le[t];return void 0===e?st(t):e},he=[];Reflect.construct;var fe,pe,me,ve=t=>{var e=(t-C.buffer.byteLength+65535)/65536;try{return C.grow(e),A(),1}catch(t){}},ye=(t,e)=>{t<128?e.push(t):e.push(t%128|128,t>>7)},ge=[],be=(t,e)=>{Dt.set(t,e),Et[t]=Dt.get(t)},Ce=(t,e)=>{var r=(t=>(fe||(fe=new WeakMap,((t,e)=>{if(fe)for(var r=0;r<0+e;r++){var n=jt(r);n&&fe.set(n,r)}})(0,Dt.length)),fe.get(t)||0))(t);if(r)return r;var n=(()=>{if(ge.length)return ge.pop();try{Dt.grow(1)}catch(t){if(!(t instanceof RangeError))throw t;throw"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."}return Dt.length-1})();try{be(n,t)}catch(r){if(!(r instanceof TypeError))throw r;var o=((t,e)=>{if("function"==typeof WebAssembly.Function)return new WebAssembly.Function((t=>{for(var e={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"},r={parameters:[],results:"v"==t[0]?[]:[e[t[0]]]},n=1;n{var r=t.slice(0,1),n=t.slice(1),o={i:127,p:127,j:126,f:125,d:124,e:111};e.push(96),ye(n.length,e);for(var s=0;s{fe.delete(jt(t)),be(t,null),ge.push(t)};J=s.InternalError=class extends Error{constructor(t){super(t),this.name="InternalError"}},(()=>{for(var t=new Array(256),e=0;e<256;++e)t[e]=String.fromCharCode(e);K=t})(),Q=s.BindingError=class extends Error{constructor(t){super(t),this.name="BindingError"}},Object.assign(Ct.prototype,{isAliasOf(t){if(!(this instanceof Ct))return!1;if(!(t instanceof Ct))return!1;var e=this.$$.ptrType.registeredClass,r=this.$$.ptr;t.$$=t.$$;for(var n=t.$$.ptrType.registeredClass,o=t.$$.ptr;e.baseClass;)r=e.upcast(r),e=e.baseClass;for(;n.baseClass;)o=n.upcast(o),n=n.baseClass;return e===n&&r===o},clone(){if(this.$$.ptr||ut(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var t,e=bt(Object.create(Object.getPrototypeOf(this),{$$:{value:(t=this.$$,{count:t.count,deleteScheduled:t.deleteScheduled,preservePointerOnDelete:t.preservePointerOnDelete,ptr:t.ptr,ptrType:t.ptrType,smartPtr:t.smartPtr,smartPtrType:t.smartPtrType})}}));return e.$$.count.value+=1,e.$$.deleteScheduled=!1,e},delete(){this.$$.ptr||ut(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&it("Object already scheduled for deletion"),dt(this),ht(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||ut(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&it("Object already scheduled for deletion"),mt.push(this),1===mt.length&&ct&&ct(vt),this.$$.deleteScheduled=!0,this}}),s.getInheritedInstanceCount=()=>Object.keys(yt).length,s.getLiveInheritedInstances=()=>{var t=[];for(var e in yt)yt.hasOwnProperty(e)&&t.push(yt[e]);return t},s.flushPendingDeletes=vt,s.setDelayFunction=t=>{ct=t,mt.length&&ct&&ct(vt)},Object.assign(_t.prototype,{getPointee(t){return this.rawGetPointee&&(t=this.rawGetPointee(t)),t},destructor(t){this.rawDestructor?.(t)},argPackAdvance:8,readValueFromPointer:Z,fromWireType:function(t){var e=this.getPointee(t);if(!e)return this.destructor(t),null;var r=((t,e)=>(e=((t,e)=>{for(void 0===e&&it("ptr should not be undefined");t.baseClass;)e=t.upcast(e),t=t.baseClass;return e})(t,e),yt[e]))(this.registeredClass,e);if(void 0!==r){if(0===r.$$.count.value)return r.$$.ptr=e,r.$$.smartPtr=t,r.clone();var n=r.clone();return this.destructor(t),n}function o(){return this.isSmartPointer?gt(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:e,smartPtrType:this,smartPtr:t}):gt(this.registeredClass.instancePrototype,{ptrType:this,ptr:t})}var s,i=this.registeredClass.getActualType(e),a=pt[i];if(!a)return o.call(this);s=this.isConst?a.constPointerType:a.pointerType;var c=ft(e,this.registeredClass,s.registeredClass);return null===c?o.call(this):this.isSmartPointer?gt(s.registeredClass.instancePrototype,{ptrType:s,ptr:c,smartPtrType:this,smartPtr:t}):gt(s.registeredClass.instancePrototype,{ptrType:s,ptr:c})}}),At=s.UnboundTypeError=(pe=Error,(me=St("UnboundTypeError",(function(t){this.name="UnboundTypeError",this.message=t;var e=new Error(t).stack;void 0!==e&&(this.stack=this.toString()+"\n"+e.replace(/^Error(:[^\n]*)?\n/,""))}))).prototype=Object.create(pe.prototype),me.prototype.constructor=me,me.prototype.toString=function(){return void 0===this.message?this.name:`${this.name}: ${this.message}`},me),zt.push(0,1,void 0,1,null,1,!0,1,!1,1),s.count_emval_handles=()=>zt.length/2-5-Ut.length;var we,Te={r:function(t,e,r){throw e>>>=0,r>>>=0,new G(t>>>=0).init(e,r),t},D:()=>{F("")},s:function(t){var e=X[t>>>=0];delete X[t];var r=e.rawConstructor,n=e.rawDestructor,o=e.fields,s=o.map((t=>t.getterReturnType)).concat(o.map((t=>t.setterArgumentType)));ot([t],s,(t=>{var s={};return o.forEach(((e,r)=>{var n=e.fieldName,i=t[r],a=e.getter,c=e.getterContext,u=t[r+o.length],l=e.setter,d=e.setterContext;s[n]={read:t=>i.fromWireType(a(c,t)),write:(t,e)=>{var r=[];l(d,t,u.toWireType(r,e)),Y(r)}}})),[{name:e.name,fromWireType:t=>{var e={};for(var r in s)e[r]=s[r].read(t);return n(t),e},toWireType:(t,e)=>{for(var o in s)if(!(o in e))throw new TypeError(`Missing field: "${o}"`);var i=r();for(o in s)s[o].write(i,e[o]);return null!==t&&t.push(n,i),i},argPackAdvance:8,readValueFromPointer:Z,destructorFunction:n}]}))},C:function(t,e,r,n,o){},H:function(t,e,r,n){at(t>>>=0,{name:e=st(e>>>=0),fromWireType:function(t){return!!t},toWireType:function(t,e){return e?r:n},argPackAdvance:8,readValueFromPointer:function(t){return this.fromWireType(T[t>>>0])},destructorFunction:null})},o:function(t,e,r,n,o,s,i,a,c,u,l,d,h){t>>>=0,e>>>=0,r>>>=0,n>>>=0,o>>>=0,s>>>=0,i>>>=0,a>>>=0,c>>>=0,u>>>=0,d>>>=0,h>>>=0,l=st(l>>>=0),s=Rt(o,s),a&&=Rt(i,a),u&&=Rt(c,u),h=Rt(d,h);var f=(t=>{if(void 0===t)return"_unknown";var e=(t=t.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return e>=48&&e<=57?`_${t}`:t})(l);Tt(f,(function(){Ft(`Cannot construct ${l} due to unbound types`,[n])})),ot([t,e,r],n?[n]:[],(e=>{var r,o;e=e[0],o=n?(r=e.registeredClass).instancePrototype:Ct.prototype;var i=St(l,(function(...t){if(Object.getPrototypeOf(this)!==c)throw new Q("Use 'new' to construct "+l);if(void 0===d.constructor_body)throw new Q(l+" has no accessible constructor");var e=d.constructor_body[t.length];if(void 0===e)throw new Q(`Tried to invoke ctor of ${l} with invalid number of parameters (${t.length}) - expected (${Object.keys(d.constructor_body).toString()}) parameters instead!`);return e.apply(this,t)})),c=Object.create(o,{constructor:{value:i}});i.prototype=c;var d=new $t(l,i,c,h,r,s,a,u);d.baseClass&&(d.baseClass.__derivedClasses??=[],d.baseClass.__derivedClasses.push(d));var p=new _t(l,d,!0,!1,!1),m=new _t(l+"*",d,!1,!1,!1),v=new _t(l+" const*",d,!1,!0,!1);return pt[t]={pointerType:m,constPointerType:v},kt(f,i),[p,m,v]}))},n:function(t,e,r,n,o,s){t>>>=0,n>>>=0,o>>>=0,s>>>=0;var i=Vt(e,r>>>=0);o=Rt(n,o),ot([],[t],(t=>{var r=`constructor ${(t=t[0]).name}`;if(void 0===t.registeredClass.constructor_body&&(t.registeredClass.constructor_body=[]),void 0!==t.registeredClass.constructor_body[e-1])throw new Q(`Cannot register multiple constructors with identical number of parameters (${e-1}) for class '${t.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return t.registeredClass.constructor_body[e-1]=()=>{Ft(`Cannot construct ${t.name} due to unbound types`,i)},ot([],i,(n=>(n.splice(1,0,null),t.registeredClass.constructor_body[e-1]=Bt(r,n,null,o,s),[]))),[]}))},a:function(t,e,r,n,o,s,i,a,c){t>>>=0,e>>>=0,o>>>=0,s>>>=0,i>>>=0;var u=Vt(r,n>>>=0);e=st(e),e=Lt(e),s=Rt(o,s),ot([],[t],(t=>{var n=`${(t=t[0]).name}.${e}`;function o(){Ft(`Cannot call ${n} due to unbound types`,u)}e.startsWith("@@")&&(e=Symbol[e.substring(2)]),a&&t.registeredClass.pureVirtualFunctions.push(e);var l=t.registeredClass.instancePrototype,d=l[e];return void 0===d||void 0===d.overloadTable&&d.className!==t.name&&d.argCount===r-2?(o.argCount=r-2,o.className=t.name,l[e]=o):(wt(l,e,n),l[e].overloadTable[r-2]=o),ot([],u,(o=>{var a=Bt(n,o,t,s,i,c);return void 0===l[e].overloadTable?(a.argCount=r-2,l[e]=a):l[e].overloadTable[r-2]=a,[]})),[]}))},G:Yt,y:function(t,e,r,n){function o(){}t>>>=0,r>>>=0,e=st(e>>>=0),o.values={},at(t,{name:e,constructor:o,fromWireType:function(t){return this.constructor.values[t]},toWireType:(t,e)=>e.value,argPackAdvance:8,readValueFromPointer:Zt(e,r,n),destructorFunction:null}),Tt(e,o)},h:function(t,e,r){e>>>=0;var n=Jt(t>>>=0,"enum");e=st(e);var o=n.constructor,s=Object.create(n.constructor.prototype,{value:{value:r},constructor:{value:St(`${n.name}_${e}`,(function(){}))}});o.values[r]=s,o[e]=s},A:function(t,e,r){r>>>=0,at(t>>>=0,{name:e=st(e>>>=0),fromWireType:t=>t,toWireType:(t,e)=>e,argPackAdvance:8,readValueFromPointer:Qt(e,r),destructorFunction:null})},d:function(t,e,r,n,o,s,i){t>>>=0,n>>>=0,o>>>=0,s>>>=0;var a=Vt(e,r>>>=0);t=st(t),t=Lt(t),o=Rt(n,o),Tt(t,(function(){Ft(`Cannot call ${t} due to unbound types`,a)}),e-1),ot([],a,(r=>{var n=[r[0],null].concat(r.slice(1));return kt(t,Bt(t,n,null,o,s,i),e-1),[]}))},p:function(t,e,r,n,o){t>>>=0,r>>>=0,e=st(e>>>=0),-1===o&&(o=4294967295);var s=t=>t;if(0===n){var i=32-8*r;s=t=>t<>>i}var a=e.includes("unsigned");at(t,{name:e,fromWireType:s,toWireType:a?function(t,e){return this.name,e>>>0}:function(t,e){return this.name,e},argPackAdvance:8,readValueFromPointer:te(e,r,0!==n),destructorFunction:null})},g:function(t,e,r){r>>>=0;var n=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][e];function o(t){var e=O[t>>>2>>>0],r=O[t+4>>>2>>>0];return new n(w.buffer,r,e)}at(t>>>=0,{name:r=st(r),fromWireType:o,argPackAdvance:8,readValueFromPointer:o},{ignoreDuplicateRegistrations:!0})},q:function(t,e){Yt(t>>>=0)},z:function(t,e){t>>>=0;var r="std::string"===(e=st(e>>>=0));at(t,{name:e,fromWireType(t){var e,n,o,s=O[t>>>2>>>0],i=t+4;if(r)for(var a=i,c=0;c<=s;++c){var u=i+c;if(c==s||0==T[u>>>0]){var l=(n=a,o=u-a,(n>>>=0)?((t,e,r)=>{for(var n=(e>>>=0)+r,o=e;t[o]&&!(o>=n);)++o;if(o-e>16&&t.buffer&&ee)return ee.decode(t.subarray(e,o));for(var s="";e>10,56320|1023&u)}}else s+=String.fromCharCode((31&i)<<6|a)}else s+=String.fromCharCode(i)}return s})(T,n,o):"");void 0===e?e=l:(e+=String.fromCharCode(0),e+=l),a=u+1}}else{var d=new Array(s);for(c=0;c>>0]);e=d.join("")}return Oe(t),e},toWireType(t,e){var n;e instanceof ArrayBuffer&&(e=new Uint8Array(e));var o="string"==typeof e;o||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int8Array||it("Cannot pass non-string to std::string"),n=r&&o?(t=>{for(var e=0,r=0;r=55296&&n<=57343?(e+=4,++r):e+=3}return e})(e):e.length;var s=Me(4+n+1),i=s+4;if(O[s>>>2>>>0]=n,r&&o)((t,e,r,n)=>{if(!(n>0))return 0;for(var o=(r>>>=0)+n-1,s=0;s=55296&&i<=57343&&(i=65536+((1023&i)<<10)|1023&t.charCodeAt(++s)),i<=127){if(r>=o)break;e[r++>>>0]=i}else if(i<=2047){if(r+1>=o)break;e[r++>>>0]=192|i>>6,e[r++>>>0]=128|63&i}else if(i<=65535){if(r+2>=o)break;e[r++>>>0]=224|i>>12,e[r++>>>0]=128|i>>6&63,e[r++>>>0]=128|63&i}else{if(r+3>=o)break;e[r++>>>0]=240|i>>18,e[r++>>>0]=128|i>>12&63,e[r++>>>0]=128|i>>6&63,e[r++>>>0]=128|63&i}}e[r>>>0]=0})(e,T,i,n+1);else if(o)for(var a=0;a255&&(Oe(i),it("String has UTF-16 code units that do not fit in 8 bits")),T[i+a>>>0]=c}else for(a=0;a>>0]=e[a];return null!==t&&t.push(Oe,s),s},argPackAdvance:8,readValueFromPointer:Z,destructorFunction(t){Oe(t)}})},x:function(t,e,r){var n,o,s,i;t>>>=0,e>>>=0,r=st(r>>>=0),2===e?(n=ne,o=oe,i=se,s=t=>P[t>>>1>>>0]):4===e&&(n=ie,o=ae,i=ce,s=t=>O[t>>>2>>>0]),at(t,{name:r,fromWireType:t=>{for(var r,o=O[t>>>2>>>0],i=t+4,a=0;a<=o;++a){var c=t+4+a*e;if(a==o||0==s(c)){var u=n(i,c-i);void 0===r?r=u:(r+=String.fromCharCode(0),r+=u),i=c+e}}return Oe(t),r},toWireType:(t,n)=>{"string"!=typeof n&&it(`Cannot pass non-string to C++ string type ${r}`);var s=i(n),a=Me(4+s+e);return O[a>>>2>>>0]=s/e,o(n,a+4,s+e),null!==t&&t.push(Oe,a),a},argPackAdvance:8,readValueFromPointer:Z,destructorFunction(t){Oe(t)}})},t:function(t,e,r,n,o,s){e>>>=0,r>>>=0,n>>>=0,o>>>=0,s>>>=0,X[t>>>=0]={name:st(e),rawConstructor:Rt(r,n),rawDestructor:Rt(o,s),fields:[]}},i:function(t,e,r,n,o,s,i,a,c,u){e>>>=0,r>>>=0,n>>>=0,o>>>=0,s>>>=0,i>>>=0,a>>>=0,c>>>=0,u>>>=0,X[t>>>=0].fields.push({fieldName:st(e),getterReturnType:r,getter:Rt(n,o),getterContext:s,setterArgumentType:i,setter:Rt(a,c),setterContext:u})},I:function(t,e){at(t>>>=0,{isVoid:!0,name:e=st(e>>>=0),argPackAdvance:0,fromWireType:()=>{},toWireType:(t,e)=>{}})},F:function(t,e,r){return t>>>=0,e>>>=0,r>>>=0,T.copyWithin(t>>>0,e>>>0,e+r>>>0)},v:function(t,e,r){return t>>>=0,e>>>=0,r>>>=0,t=Gt.toValue(t),e=Jt(e,"emval::as"),ue(e,r,t)},k:function(t,e,r,n,o){return e>>>=0,r>>>=0,n>>>=0,o>>>=0,(t=he[t>>>=0])(e=Gt.toValue(e),e[r=de(r)],n,o)},b:qt,u:function(t,e){return t>>>=0,e>>>=0,(t=Gt.toValue(t))==Gt.toValue(e)},l:function(t,e,r){var n=((t,e)=>{for(var r=new Array(t),n=0;n>>2>>>0],"parameter "+n);return r})(t,e>>>=0),o=n.shift();t--;var s="return function (obj, func, destructorsRef, args) {\n",i=0,a=[];0===r&&a.push("obj");for(var c=["retType"],u=[o],l=0;lt.name)).join(", ")}) => ${o.name}>`;return d=St(p,f),h=he.length,he.push(d),h},f:function(t,e){return t>>>=0,e>>>=0,t=Gt.toValue(t),e=Gt.toValue(e),Gt.toHandle(t[e])},w:function(t){(t>>>=0)>9&&(zt[t+1]+=1)},c:function(t){return t>>>=0,Gt.toHandle(de(t))},B:function(){return Gt.toHandle({})},j:function(t){t>>>=0;var e=Gt.toValue(t);Y(e),qt(t)},m:function(t,e,r){t>>>=0,e>>>=0,r>>>=0,t=Gt.toValue(t),e=Gt.toValue(e),r=Gt.toValue(r),t[e]=r},e:function(t,e){e>>>=0;var r=(t=Jt(t>>>=0,"_emval_take_value")).readValueFromPointer(e);return Gt.toHandle(r)},E:function(t){t>>>=0;var e=T.length,r=4294901760;if(t>r)return!1;for(var n,o=1;o<=4;o*=2){var s=e*(1+.2/o);s=Math.min(s,t+100663296);var i=Math.min(r,(n=Math.max(t,s))+(65536-n%65536)%65536);if(ve(i))return!0}return!1}},$e=function(){var t,e,n,i,a={a:Te};function c(t,e){var r;return $e=function(t){var e,r=t=>e=>t(e)>>>0;return(t=Object.assign({},t)).L=r(t.L),t.N=r(t.N),t._emscripten_stack_alloc=r(t._emscripten_stack_alloc),t.emscripten_stack_get_current=(e=t.emscripten_stack_get_current,()=>e()>>>0),t}($e=t.exports),C=$e.J,A(),Dt=$e.M,r=$e.K,E.unshift(r),function(t){if(I--,s.monitorRunDependencies?.(I),0==I&&(null!==R&&(clearInterval(R),R=null),W)){var e=W;W=null,e()}}(),$e}if(I++,s.monitorRunDependencies?.(I),s.instantiateWasm)try{return s.instantiateWasm(a,c)}catch(t){S(`Module.instantiateWasm callback failed with error: ${t}`),o(t)}return V||(V=function(){if(s.locateFile){var t="manifold.wasm";return N(t)?t:(e=t,s.locateFile?s.locateFile(e,v):v+e)}var e;return new URL(r(644),r.b).href}()),(t=b,e=V,n=a,i=function(t){c(t.instance)},t||"function"!=typeof WebAssembly.instantiateStreaming||N(e)||H(e)||u||"function"!=typeof fetch?L(e,n,i):fetch(e,{credentials:"same-origin"}).then((t=>WebAssembly.instantiateStreaming(t,n).then(i,(function(t){return S(`wasm streaming compile failed: ${t}`),S("falling back to ArrayBuffer instantiation"),L(e,n,i)}))))).catch(o),{}}(),Pe=t=>(Pe=$e.L)(t),Me=t=>(Me=$e.N)(t),Oe=t=>(Oe=$e.O)(t),xe=t=>(xe=$e.P)(t);function _e(){function t(){we||(we=!0,s.calledRun=!0,D||(U(E),e(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),function(){if(s.postRun)for("function"==typeof s.postRun&&(s.postRun=[s.postRun]);s.postRun.length;)t=s.postRun.shift(),j.unshift(t);var t;U(j)}()))}I>0||(function(){if(s.preRun)for("function"==typeof s.preRun&&(s.preRun=[s.preRun]);s.preRun.length;)t=s.preRun.shift(),k.unshift(t);var t;U(k)}(),I>0||(s.setStatus?(s.setStatus("Running..."),setTimeout((function(){setTimeout((function(){s.setStatus("")}),1),t()}),1)):t()))}if(s.addFunction=Ce,s.removeFunction=Se,W=function t(){we||_e(),we||(W=t)},s.preInit)for("function"==typeof s.preInit&&(s.preInit=[s.preInit]);s.preInit.length>0;)s.preInit.pop()();return _e(),i})}},s={};function i(t){var e=s[t];if(void 0!==e)return e.exports;var r=s[t]={exports:{}};return o[t](r,r.exports,i),r.exports}i.m=o,e=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,i.t=function(r,n){if(1&n&&(r=this(r)),8&n)return r;if("object"==typeof r&&r){if(4&n&&r.__esModule)return r;if(16&n&&"function"==typeof r.then)return r}var o=Object.create(null);i.r(o);var s={};t=t||[null,e({}),e([]),e(e)];for(var a=2&n&&r;"object"==typeof a&&!~t.indexOf(a);a=e(a))Object.getOwnPropertyNames(a).forEach((t=>s[t]=()=>r[t]));return s.default=()=>r,i.d(o,s),o},i.d=(t,e)=>{for(var r in e)i.o(e,r)&&!i.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},i.f={},i.e=t=>Promise.all(Object.keys(i.f).reduce(((e,r)=>(i.f[r](t,e),e)),[])),i.u=t=>t+".bitbybit-manifold-webworker.js",i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),i.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r={},n="@bitbybit-dev/runner:",i.l=(t,e,o,s)=>{if(r[t])r[t].push(e);else{var a,c;if(void 0!==o)for(var u=document.getElementsByTagName("script"),l=0;l{a.onerror=a.onload=null,clearTimeout(f);var o=r[t];if(delete r[t],a.parentNode&&a.parentNode.removeChild(a),o&&o.forEach((t=>t(n))),e)return e(n)},f=setTimeout(h.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=h.bind(null,a.onerror),a.onload=h.bind(null,a.onload),c&&document.head.appendChild(a)}},i.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},(()=>{var t;i.g.importScripts&&(t=i.g.location+"");var e=i.g.document;if(!t&&e&&(e.currentScript&&(t=e.currentScript.src),!t)){var r=e.getElementsByTagName("script");if(r.length)for(var n=r.length-1;n>-1&&(!t||!/^http(s?):/.test(t));)t=r[n--].src}if(!t)throw new Error("Automatic publicPath is not supported in this browser");t=t.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),i.p=t})(),(()=>{i.b=document.baseURI||self.location.href;var t={792:0};i.f.j=(e,r)=>{var n=i.o(t,e)?t[e]:void 0;if(0!==n)if(n)r.push(n[2]);else{var o=new Promise(((r,o)=>n=t[e]=[r,o]));r.push(n[2]=o);var s=i.p+i.u(e),a=new Error;i.l(s,(r=>{if(i.o(t,e)&&(0!==(n=t[e])&&(t[e]=void 0),n)){var o=r&&("load"===r.type?"missing":r.type),s=r&&r.target&&r.target.src;a.message="Loading chunk "+e+" failed.\n("+o+": "+s+")",a.name="ChunkLoadError",a.type=o,a.request=s,n[1](a)}}),"chunk-"+e,e)}};var e=(e,r)=>{var n,o,[s,a,c]=r,u=0;if(s.some((e=>0!==t[e]))){for(n in a)i.o(a,n)&&(i.m[n]=a[n]);c&&c(i)}for(e&&e(r);u{var t,e,r;(r=t||(t={}))[r.loading=0]="loading",r[r.loaded=1]="loaded",r[r.initialised=2]="initialised",r[r.computing=3]="computing";class n{constructor(){this.hashesFromPreviousRun={},this.usedHashes={},this.argCache={}}cleanAllCache(){Object.keys(this.usedHashes).forEach((t=>{if(this.argCache[t])try{this.argCache[t].delete()}catch(t){}})),this.argCache={},this.usedHashes={},this.hashesFromPreviousRun={}}cleanCacheForHash(t){if(this.argCache[t])try{this.argCache[t].delete()}catch(t){}delete this.argCache[t],delete this.usedHashes[t],delete this.hashesFromPreviousRun[t]}isManifoldObject(t){return null!=t&&!Array.isArray(t)&&void 0!==t.$$||Array.isArray(t)&&t.length>0&&void 0!==t[0].$$}cacheOp(t,e){let r=null;const n=this.computeHash(t);this.usedHashes[n]=n,this.hashesFromPreviousRun[n]=n;const o=this.checkCache(n);if(o)this.isManifoldObject(o)?(r=o,r.hash=o.hash):o.value&&(r=o.value);else if(r=e(),Array.isArray(r)&&this.isManifoldObject(r))r.forEach(((e,r)=>{const n=this.computeHash(Object.assign(Object.assign({},t),{index:r}));e.hash=n,this.addToCache(n,e)}));else if(this.isManifoldObject(r))this.addToCache(n,r);else if(r.compound&&r.data&&r.manifolds&&r.manifolds.length>0){const e=r,o=this.computeHash(Object.assign(Object.assign({},t),{index:"compound"}));e.compound.hash=o,this.addToCache(o,e.compound),e.manifolds.forEach(((e,r)=>{const n=this.computeHash(Object.assign(Object.assign({},t),{index:r}));e.manifold.hash=n,this.addToCache(n,e.manifold)})),this.addToCache(n,{value:e})}else this.addToCache(n,{value:r});return r}checkCache(t){return this.argCache[t]||null}addToCache(t,e){const r=e;return r.hash=t,this.argCache[t]=r,t}computeHash(t,e){let r=JSON.stringify(t);r=r.replace(/(\"ptr\"\:(-?[0-9]*?)\,)/g,""),r=r.replace(/(\"ptr\"\:(-?[0-9]*))/g,""),r.includes("ptr")&&console.error("YOU DONE MESSED UP YOUR REGEX.");const n=Math.random.toString()+r;return e?n:this.stringToHash(n)}stringToHash(t){let e=0;if(0===t.length)return e;for(let r=0;rt.hash!==e.hash||t.ptr!==e.ptr))}}!function(t){let e,r;!function(t){t.evenOdd="EvenOdd",t.nonZero="NonZero",t.positive="Positive",t.negative="Negative"}(e=t.fillRuleEnum||(t.fillRuleEnum={})),function(t){t.square="Square",t.round="Round",t.miter="Miter"}(r=t.manifoldJoinTypeEnum||(t.manifoldJoinTypeEnum={})),t.DecomposedManifoldMeshDto=class{},t.DrawManifoldOrCrossSectionDto=class{constructor(t,e,r,n,o,s,i,a){this.faceOpacity=1,this.faceColour="#ff0000",this.crossSectionColour="#ff00ff",this.crossSectionWidth=2,this.crossSectionOpacity=1,this.computeNormals=!1,void 0!==t&&(this.manifoldOrCrossSection=t),void 0!==e&&(this.faceOpacity=e),void 0!==r&&(this.faceMaterial=r),void 0!==n&&(this.faceColour=n),void 0!==o&&(this.crossSectionColour=o),void 0!==s&&(this.crossSectionWidth=s),void 0!==i&&(this.crossSectionOpacity=i),void 0!==a&&(this.computeNormals=a)}},t.DrawManifoldsOrCrossSectionsDto=class{constructor(t,e,r,n,o,s,i,a){this.faceColour="#ff0000",this.faceOpacity=1,this.crossSectionColour="#ff00ff",this.crossSectionWidth=2,this.crossSectionOpacity=1,this.computeNormals=!1,void 0!==t&&(this.manifoldsOrCrossSections=t),void 0!==e&&(this.faceOpacity=e),void 0!==r&&(this.faceMaterial=r),void 0!==n&&(this.faceColour=n),void 0!==o&&(this.crossSectionColour=o),void 0!==s&&(this.crossSectionWidth=s),void 0!==i&&(this.crossSectionOpacity=i),void 0!==a&&(this.computeNormals=a)}},t.CreateFromMeshDto=class{constructor(t){void 0!==t&&(this.mesh=t)}},t.CubeDto=class{constructor(t,e){this.center=!0,this.size=1,void 0!==t&&(this.center=t),void 0!==e&&(this.size=e)}},t.CreateContourSectionDto=class{constructor(t,r){this.fillRule=e.evenOdd,void 0!==t&&(this.polygons=t),void 0!==r&&(this.fillRule=r)}},t.SquareDto=class{constructor(t,e){this.center=!1,this.size=1,void 0!==t&&(this.center=t),void 0!==e&&(this.size=e)}},t.SphereDto=class{constructor(t,e){this.radius=1,void 0!==t&&(this.radius=t),void 0!==e&&(this.circularSegments=e)}},t.CylinderDto=class{constructor(t,e,r,n,o){this.height=1,this.radiusLow=1,this.radiusHigh=1,this.circularSegments=32,this.center=!0,void 0!==t&&(this.height=t),void 0!==e&&(this.radiusLow=e),void 0!==r&&(this.radiusHigh=r),void 0!==n&&(this.circularSegments=n),void 0!==o&&(this.center=o)}},t.CircleDto=class{constructor(t,e){this.radius=1,this.circularSegments=32,void 0!==t&&(this.radius=t),void 0!==e&&(this.circularSegments=e)}},t.RectangleDto=class{constructor(t,e,r){this.length=1,this.height=1,this.center=!1,void 0!==t&&(this.length=t),void 0!==e&&(this.height=e),void 0!==r&&(this.center=r)}},t.ManifoldDto=class{constructor(t){void 0!==t&&(this.manifold=t)}},t.CalculateNormalsDto=class{constructor(t,e,r){this.normalIdx=0,this.minSharpAngle=0,void 0!==t&&(this.manifold=t),void 0!==e&&(this.normalIdx=e),void 0!==r&&(this.minSharpAngle=r)}},t.CalculateCurvatureDto=class{constructor(t){void 0!==t&&(this.manifold=t)}},t.CountDto=class{constructor(t){void 0!==t&&(this.count=t)}},t.ManifoldsMinGapDto=class{constructor(t,e,r){this.searchLength=100,void 0!==t&&(this.manifold1=t),void 0!==e&&(this.manifold2=e),void 0!==r&&(this.searchLength=r)}},t.ManifoldRefineToleranceDto=class{constructor(t,e){this.tolerance=1e-6,void 0!==t&&(this.manifold=t),void 0!==e&&(this.tolerance=e)}},t.ManifoldRefineLengthDto=class{constructor(t,e){this.length=.1,void 0!==t&&(this.manifold=t),void 0!==e&&(this.length=e)}},t.ManifoldRefineDto=class{constructor(t,e){this.number=1,void 0!==t&&(this.manifold=t),void 0!==e&&(this.number=e)}},t.ManifoldSmoothByNormalsDto=class{constructor(t,e){this.normalIdx=0,void 0!==t&&(this.manifold=t),void 0!==e&&(this.normalIdx=e)}},t.ManifoldSmoothOutDto=class{constructor(t,e,r){this.minSharpAngle=60,this.minSmoothness=0,void 0!==t&&(this.manifold=t),void 0!==e&&(this.minSharpAngle=e),void 0!==r&&(this.minSmoothness=r)}},t.HullPointsDto=class{constructor(t){void 0!==t&&(this.points=t)}},t.SliceDto=class{constructor(t){this.height=.5,void 0!==t&&(this.manifold=t)}},t.MeshDto=class{constructor(t){void 0!==t&&(this.mesh=t)}},t.MeshVertexIndexDto=class{constructor(t,e){void 0!==t&&(this.mesh=t),void 0!==e&&(this.vertexIndex=e)}},t.MeshTriangleRunIndexDto=class{constructor(t,e){void 0!==t&&(this.mesh=t),void 0!==e&&(this.triangleRunIndex=e)}},t.MeshHalfEdgeIndexDto=class{constructor(t,e){void 0!==t&&(this.mesh=t),void 0!==e&&(this.halfEdgeIndex=e)}},t.MeshTriangleIndexDto=class{constructor(t,e){void 0!==t&&(this.mesh=t),void 0!==e&&(this.triangleIndex=e)}},t.CrossSectionDto=class{constructor(t){void 0!==t&&(this.crossSection=t)}},t.CrossSectionsDto=class{constructor(t){void 0!==t&&(this.crossSections=t)}},t.ExtrudeDto=class{constructor(t){this.height=1,this.nDivisions=1,this.twistDegrees=0,this.scaleTopX=1,this.scaleTopY=1,this.center=!0,void 0!==t&&(this.crossSection=t)}},t.RevolveDto=class{constructor(t,e,r,n){this.matchProfile=!0,this.circularSegments=32,void 0!==t&&(this.crossSection=t),void 0!==e&&(this.revolveDegrees=e),void 0!==r&&(this.matchProfile=r),void 0!==n&&(this.circularSegments=n)}},t.OffsetDto=class{constructor(t,e,n,o,s){this.joinType=r.round,this.miterLimit=2,this.circularSegments=32,void 0!==t&&(this.crossSection=t),void 0!==e&&(this.delta=e),void 0!==n&&(this.joinType=n),void 0!==o&&(this.miterLimit=o),void 0!==s&&(this.circularSegments=s)}},t.SimplifyDto=class{constructor(t,e){this.epsilon=1e-6,void 0!==t&&(this.crossSection=t),void 0!==e&&(this.epsilon=e)}},t.ComposeDto=class{constructor(t){void 0!==t&&(this.polygons=t)}},t.MirrorCrossSectionDto=class{constructor(t,e){this.normal=[1,0],void 0!==t&&(this.crossSection=t),void 0!==e&&(this.normal=e)}},t.Scale2DCrossSectionDto=class{constructor(t,e){this.vector=[2,2],void 0!==t&&(this.crossSection=t),void 0!==e&&(this.vector=e)}},t.TranslateCrossSectionDto=class{constructor(t,e){void 0!==t&&(this.crossSection=t),void 0!==e&&(this.vector=e)}},t.RotateCrossSectionDto=class{constructor(t,e){void 0!==t&&(this.crossSection=t),void 0!==e&&(this.degrees=e)}},t.ScaleCrossSectionDto=class{constructor(t,e){this.factor=2,void 0!==t&&(this.crossSection=t),void 0!==e&&(this.factor=e)}},t.TranslateXYCrossSectionDto=class{constructor(t,e,r){this.x=0,this.y=0,void 0!==t&&(this.crossSection=t),void 0!==e&&(this.x=e),void 0!==r&&(this.y=r)}},t.TransformCrossSectionDto=class{constructor(t,e){void 0!==t&&(this.crossSection=t),void 0!==e&&(this.transform=e)}},t.MirrorDto=class{constructor(t,e){this.normal=[1,0,0],void 0!==t&&(this.manifold=t),void 0!==e&&(this.normal=e)}},t.Scale3DDto=class{constructor(t,e){this.vector=[2,2,2],void 0!==t&&(this.manifold=t),void 0!==e&&(this.vector=e)}},t.TranslateDto=class{constructor(t,e){void 0!==t&&(this.manifold=t),void 0!==e&&(this.vector=e)}},t.TranslateByVectorsDto=class{constructor(t,e){void 0!==t&&(this.manifold=t),void 0!==e&&(this.vectors=e)}},t.RotateDto=class{constructor(t,e){void 0!==t&&(this.manifold=t),void 0!==e&&(this.vector=e)}},t.RotateXYZDto=class{constructor(t,e,r,n){this.x=0,this.y=0,this.z=0,void 0!==t&&(this.manifold=t),void 0!==e&&(this.x=e),void 0!==r&&(this.y=r),void 0!==n&&(this.z=n)}},t.ScaleDto=class{constructor(t,e){this.factor=2,void 0!==t&&(this.manifold=t),void 0!==e&&(this.factor=e)}},t.TranslateXYZDto=class{constructor(t,e,r,n){this.x=0,this.y=0,this.z=0,void 0!==t&&(this.manifold=t),void 0!==e&&(this.x=e),void 0!==r&&(this.y=r),void 0!==n&&(this.z=n)}},t.TransformDto=class{constructor(t,e){void 0!==t&&(this.manifold=t),void 0!==e&&(this.transform=e)}},t.TransformsDto=class{constructor(t,e){void 0!==t&&(this.manifold=t),void 0!==e&&(this.transforms=e)}},t.TwoCrossSectionsDto=class{constructor(t,e){void 0!==t&&(this.crossSection1=t),void 0!==e&&(this.crossSection2=e)}},t.TwoManifoldsDto=class{constructor(t,e){void 0!==t&&(this.manifold1=t),void 0!==e&&(this.manifold2=e)}},t.SplitManifoldsDto=class{constructor(t,e){void 0!==t&&(this.manifoldToSplit=t),void 0!==e&&(this.manifoldCutter=e)}},t.TrimByPlaneDto=class{constructor(t,e,r){this.normal=[1,0,0],this.originOffset=0,void 0!==t&&(this.manifold=t),void 0!==e&&(this.normal=e),void 0!==r&&(this.originOffset=r)}},t.SplitByPlaneDto=class{constructor(t,e,r){this.normal=[1,0,0],this.originOffset=0,void 0!==t&&(this.manifold=t),void 0!==e&&(this.normal=e),void 0!==r&&(this.originOffset=r)}},t.ManifoldsDto=class{constructor(t){void 0!==t&&(this.manifolds=t)}},t.ManifoldToMeshDto=class{constructor(t,e){void 0!==t&&(this.manifold=t),void 0!==e&&(this.normalIdx=e)}},t.ManifoldsToMeshesDto=class{constructor(t,e){void 0!==t&&(this.manifolds=t),void 0!==e&&(this.normalIdx=e)}},t.DecomposeManifoldOrCrossSectionDto=class{constructor(t,e){void 0!==t&&(this.manifoldOrCrossSection=t),void 0!==e&&(this.normalIdx=e)}},t.ManifoldOrCrossSectionDto=class{constructor(t){void 0!==t&&(this.manifoldOrCrossSection=t)}},t.ManifoldsOrCrossSectionsDto=class{constructor(t){void 0!==t&&(this.manifoldsOrCrossSections=t)}},t.DecomposeManifoldsOrCrossSectionsDto=class{constructor(t,e){void 0!==t&&(this.manifoldsOrCrossSections=t),void 0!==e&&(this.normalIdx=e)}}}(e||(e={}));class o{constructor(t){this.manifold=t}manifoldFromMesh(t){const{Manifold:e}=this.manifold;return new e(t.mesh)}cube(t){const{Manifold:e}=this.manifold,{cube:r}=e;return r(t.size,t.center)}sphere(t){const{Manifold:e}=this.manifold,{sphere:r}=e;return r(t.radius,t.circularSegments)}tetrahedron(){const{Manifold:t}=this.manifold,{tetrahedron:e}=t;return e()}cylinder(t){const{Manifold:e}=this.manifold,{cylinder:r}=e;return r(t.height,t.radiusLow,t.radiusHigh,t.circularSegments,t.center)}}class s{constructor(t){this.manifold=t}split(t){return t.manifoldToSplit.split(t.manifoldCutter)}splitByPlane(t){return t.manifold.splitByPlane(t.normal,t.originOffset)}trimByPlane(t){return t.manifold.asOriginal().trimByPlane(t.normal,t.originOffset)}subtract(t){return t.manifold1.subtract(t.manifold2)}add(t){return t.manifold1.add(t.manifold2)}intersect(t){return t.manifold1.intersect(t.manifold2)}differenceTwo(t){const{Manifold:e}=this.manifold,{difference:r}=e;return r(t.manifold1,t.manifold2)}difference(t){const{Manifold:e}=this.manifold,{difference:r}=e;return r(t.manifolds)}unionTwo(t){const{Manifold:e}=this.manifold,{union:r}=e;return r(t.manifold1,t.manifold2)}union(t){const{Manifold:e}=this.manifold,{union:r}=e;return r(t.manifolds)}intersectionTwo(t){const{Manifold:e}=this.manifold,{intersection:r}=e;return r(t.manifold1,t.manifold2)}intersection(t){const{Manifold:e}=this.manifold,{intersection:r}=e;return r(t.manifolds)}}class a{constructor(t){this.manifold=t}hull(t){return t.manifold.hull()}hullPoints(t){const{Manifold:e}=this.manifold,{hull:r}=e;return r(t.points)}slice(t){return t.manifold.slice(t.height)}project(t){return t.manifold.project()}setTolerance(t){return t.manifold.setTolerance(t.tolerance)}asOriginal(t){return t.manifold.asOriginal()}reserveIds(t){const{Manifold:e}=this.manifold,{reserveIDs:r}=e;return r(t.count)}compose(t){const{Manifold:e}=this.manifold,{compose:r}=e;return r(t.manifolds)}decompose(t){return t.manifold.decompose()}calculateNormals(t){return t.manifold.calculateNormals(t.normalIdx,t.minSharpAngle)}calculateCurvature(t){return t.manifold.calculateCurvature(t.gaussianIdx,t.meanIdx)}refineToTolerance(t){return t.manifold.refineToTolerance(t.tolerance)}refineToLength(t){return t.manifold.refineToLength(t.length)}refine(t){return t.manifold.refine(t.number)}smoothOut(t){return t.manifold.smoothOut(t.minSharpAngle,t.minSmoothness)}smoothByNormals(t){return t.manifold.smoothByNormals(t.normalIdx)}}class c{constructor(t){this.manifold=t}scale3D(t){return t.manifold.scale(t.vector)}scale(t){return t.manifold.scale(t.vector)}mirror(t){return t.manifold.mirror(t.normal)}translate(t){return t.manifold.translate(t.vector)}translateByVectors(t){return t.vectors.map((e=>t.manifold.translate(e)))}rotate(t){return t.manifold.rotate(t.vector)}rotateXYZ(t){return t.manifold.rotate(t.x,t.y,t.z)}translateXYZ(t){return t.manifold.translate(t.x,t.y,t.z)}transform(t){return t.manifold.transform(t.transform)}transforms(t){let e=t.manifold;const r=[];t.transforms.forEach((t=>{e=e.transform(t),r.push(e)}));const n=r.pop();return r.forEach((t=>{t.delete()})),n}}class u{constructor(t){this.manifold=t}volume(t){return t.manifold.volume()}surfaceArea(t){return t.manifold.surfaceArea()}isEmpty(t){return t.manifold.isEmpty()}numVert(t){return t.manifold.numVert()}numTri(t){return t.manifold.numTri()}numEdge(t){return t.manifold.numEdge()}numProp(t){return t.manifold.numProp()}numPropVert(t){return t.manifold.numPropVert()}boundingBox(t){const e=t.manifold.boundingBox();return[e.min,e.max]}tolerance(t){return t.manifold.tolerance()}genus(t){return t.manifold.genus()}minGap(t){return t.manifold1.minGap(t.manifold2,t.searchLength)}originalID(t){return t.manifold.originalID()}}class l{constructor(t){this.shapes=new o(t),this.booleans=new s(t),this.operations=new a(t),this.transforms=new c(t),this.evaluate=new u(t)}manifoldToMesh(t){return t.manifold.getMesh(t.normalIdx)}manifoldsToMeshes(t){return t.manifolds.map(((e,r)=>{const n=t.normalIdx?t.normalIdx[r]:void 0;return this.manifoldToMesh({manifold:e,normalIdx:n})}))}}class d{constructor(t){this.manifold=t}create(t){const{CrossSection:e}=this.manifold;return new e(t.polygons,t.fillRule)}square(t){const{CrossSection:e}=this.manifold,{square:r}=e;return r(t.size,t.center)}circle(t){const{CrossSection:e}=this.manifold,{circle:r}=e;return r(t.radius,t.circularSegments)}rectangle(t){const{CrossSection:e}=this.manifold,{square:r}=e;return r([t.length,t.height],t.center)}}class h{constructor(t){this.manifold=t}hull(t){return t.crossSection.hull()}extrude(t){return t.crossSection.extrude(t.height,t.nDivisions,t.twistDegrees,[t.scaleTopX,t.scaleTopY],t.center)}revolve(t){const e=t.crossSection.revolve(t.circularSegments,t.revolveDegrees);return t.matchProfile?e.rotate([90,0,0]):e}offset(t){return t.crossSection.offset(t.delta,t.joinType,t.miterLimit,t.circularSegments)}simplify(t){return t.crossSection.simplify(t.epsilon)}compose(t){const{CrossSection:e}=this.manifold,{compose:r}=e;return r(t.polygons)}decompose(t){return t.crossSection.decompose()}}class f{constructor(t){this.manifold=t}scale2D(t){return t.crossSection.scale(t.vector)}scale(t){return t.crossSection.scale(t.factor)}mirror(t){return t.crossSection.mirror(t.normal)}translate(t){return t.crossSection.translate(t.vector)}translateXY(t){return t.crossSection.translate([t.x,t.y])}rotate(t){return t.crossSection.rotate(t.degrees)}transform(t){return t.crossSection.transform(t.transform)}}class p{constructor(t){this.manifold=t}subtract(t){return t.crossSection1.subtract(t.crossSection2)}add(t){return t.crossSection1.add(t.crossSection2)}intersect(t){return t.crossSection1.intersect(t.crossSection2)}differenceTwo(t){const{CrossSection:e}=this.manifold,{difference:r}=e;return r(t.crossSection1,t.crossSection2)}difference(t){const{CrossSection:e}=this.manifold,{difference:r}=e;return r(t.crossSections)}unionTwo(t){const{CrossSection:e}=this.manifold,{union:r}=e;return r(t.crossSection1,t.crossSection2)}union(t){const{CrossSection:e}=this.manifold,{union:r}=e;return r(t.crossSections)}intersectionTwo(t){const{CrossSection:e}=this.manifold,{intersection:r}=e;return r(t.crossSection1,t.crossSection2)}intersection(t){const{CrossSection:e}=this.manifold,{intersection:r}=e;return r(t.crossSections)}}class m{constructor(t){this.manifold=t}area(t){return t.crossSection.area()}isEmpty(t){return t.crossSection.isEmpty()}numVert(t){return t.crossSection.numVert()}numContour(t){return t.crossSection.numContour()}bounds(t){const e=t.crossSection.bounds();return[e.min,e.max]}}class v{constructor(t){this.manifold=t,this.shapes=new d(t),this.operations=new h(t),this.transforms=new f(t),this.booleans=new p(t),this.evaluate=new m(t)}crossSectionToPolygons(t){return t.crossSection.toPolygons()}crossSectionsToPolygons(t){return t.crossSections.map((t=>this.crossSectionToPolygons({crossSection:t})))}deleteCrossSection(t){t.crossSection.delete()}deleteCrossSections(t){t.crossSections.forEach((t=>this.deleteCrossSection({crossSection:t})))}}class y{constructor(t){this.manifold=t}position(t){const e=t.mesh.position(t.vertexIndex);return[e[0],e[1],e[2]]}tangent(t){const e=t.mesh.tangent(t.halfEdgeIndex);return[e[0],e[1],e[2],e[4]]}verts(t){const e=t.mesh.verts(t.triangleIndex);return[e[0],e[1],e[2]]}extras(t){return[...t.mesh.extras(t.vertexIndex)]}transform(t){return[...t.mesh.transform(t.triangleRunIndex)]}numProp(t){return t.mesh.numProp}numVert(t){return t.mesh.numVert}numTri(t){return t.mesh.numTri}numRun(t){return t.mesh.numRun}}class g{constructor(t){this.manifold=t}merge(t){return t.mesh.merge()}}class b{constructor(t){this.operations=new g(t),this.evaluate=new y(t)}}class C{constructor(t){this.crossSection=new v(t),this.manifold=new l(t),this.mesh=new b(t)}decomposeManifoldOrCrossSection(t){return t.manifoldOrCrossSection.getMesh?t.manifoldOrCrossSection.getMesh(t.normalIdx):t.manifoldOrCrossSection.toPolygons()}decomposeManifoldsOrCrossSections(t){return t.manifoldsOrCrossSections.map(((e,r)=>{const n=t.normalIdx?t.normalIdx[r]:void 0;return this.decomposeManifoldOrCrossSection({manifoldOrCrossSection:e,normalIdx:n})}))}}let S,w,T;var $,P,M=i(581);P=function(){var t;return function(t,e){var r,n,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(i=0)),i;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,n=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]{let r;e("busy");try{if("manifoldToMesh"!==t.action.functionName&&"manifoldsToMeshes"!==t.action.functionName&&"deleteManifoldOrCrossSection"!==t.action.functionName&&"deleteManifoldsOrCrossSections"!==t.action.functionName&&"manifoldToMeshPointer"!==t.action.functionName&&"startedTheRun"!==t.action.functionName&&"cleanAllCache"!==t.action.functionName&&"addManifoldPluginDependency"!==t.action.functionName){Object.keys(t.action.inputs).forEach((e=>{const r=t.action.inputs[e];r&&r.type&&"manifold-shape"===r.type&&r.hash&&(t.action.inputs[e]=w.checkCache(t.action.inputs[e].hash)),r&&Array.isArray(r)&&r.length>0&&(r[0].type&&"manifold-shape"===r[0].type&&r[0].hash?t.action.inputs[e]=t.action.inputs[e].map((t=>w.checkCache(t.hash))):Array.isArray(r[0])&&r[0][0].type&&"manifold-shape"===r[0][0].type&&r[0][0].hash&&(t.action.inputs[e]=t.action.inputs[e].map((t=>t.map((t=>w.checkCache(t.hash)))))))}));const e=t.action.functionName.split(".");let n;if(n=3===e.length?w.cacheOp(t.action,(()=>S[e[0]][e[1]][e[2]](t.action.inputs))):2===e.length?w.cacheOp(t.action,(()=>S[e[0]][e[1]](t.action.inputs))):w.cacheOp(t.action,(()=>S[t.action.functionName](t.action.inputs))),w.isManifoldObject(n))r=Array.isArray(n)?n.map((t=>({hash:t.hash,type:"manifold-shape"}))):{hash:n.hash,type:"manifold-shape"};else if(n&&n.compound&&n.data&&n.manifolds&&n.manifolds.length>0){const t=n;t.manifolds=t.manifolds.map((t=>({id:t.id,manifold:{hash:t.manifold.hash,type:"manifold-shape"}}))),t.compound={hash:t.compound.hash,type:"manifold-shape"},r=t}else r=n}if("addManifoldPluginDependency"===t.action.functionName&&(S&&S.plugins?Object.keys(t.action.inputs).forEach((e=>{S.plugins.dependencies[e]=t.action.inputs[e]})):T=t.action.inputs),"manifoldToMesh"===t.action.functionName&&(t.action.inputs.manifold=w.checkCache(t.action.inputs.manifold.hash),r=S.decomposeManifoldOrCrossSection(t.action.inputs)),"manifoldToMeshPointer"===t.action.functionName){t.action.inputs.manifold=w.checkCache(t.action.inputs.manifold.hash);const e=S.manifold.manifoldToMesh(t.action.inputs),n=w.computeHash(t.action);w.addToCache(n,e),r={hash:n,type:"manifold-shape"}}if("manifoldsToMeshes"===t.action.functionName){if(!(t.action.inputs.manifolds&&t.action.inputs.manifolds.length>0))throw new Error("No manifolds detected");t.action.inputs.manifolds=t.action.inputs.manifolds.map((t=>w.checkCache(t.hash))),r=S.decomposeManifoldsOrCrossSections(t.action.inputs)}"deleteManifoldOrCrossSection"===t.action.functionName&&(w.cleanCacheForHash(t.action.inputs.manifoldOrCrossSection.hash),r={}),"deleteManifoldsOrCrossSections"===t.action.functionName&&(t.action.inputs.manifoldsOrCrossSections.forEach((t=>w.cleanCacheForHash(t.hash))),r={}),"startedTheRun"===t.action.functionName&&(w&&Object.keys(w.usedHashes).length>1e4&&w.cleanAllCache(),r={}),"cleanAllCache"===t.action.functionName&&(w.cleanAllCache(),r={}),e({uid:t.uid,result:r})}catch(r){let n,o;t&&t.action&&t.action.inputs&&(n=`Input values were: {${Object.keys(t.action.inputs).map((e=>`${e}: ${JSON.stringify(t.action.inputs[e])}`)).join(",")}}. `),t&&t.action&&t.action.functionName&&(o=`- ${t.action.functionName}`),e({uid:t.uid,result:void 0,error:`Manifold computation failed. ${r} While executing function ${o}. ${n}`})}})(t.data,postMessage)}))})()})(); \ No newline at end of file +(()=>{var t,e,r={644:(t,e,r)=>{"use strict";r.r(e),r.d(e,{default:()=>n});const n=r.p+"static/js/manifold.cc2ddd38.wasm"},448:(t,e,r)=>{"use strict";t.exports=r.p+"dae0f2142f7b35966b10.js"},167:()=>{}},n={};function o(t){var e=n[t];if(void 0!==e)return e.exports;var s=n[t]={exports:{}};return r[t](s,s.exports,o),s.exports}e=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,o.t=function(r,n){if(1&n&&(r=this(r)),8&n)return r;if("object"==typeof r&&r){if(4&n&&r.__esModule)return r;if(16&n&&"function"==typeof r.then)return r}var s=Object.create(null);o.r(s);var i={};t=t||[null,e({}),e([]),e(e)];for(var a=2&n&&r;"object"==typeof a&&!~t.indexOf(a);a=e(a))Object.getOwnPropertyNames(a).forEach((t=>i[t]=()=>r[t]));return i.default=()=>r,o.d(s,i),s},o.d=(t,e)=>{for(var r in e)o.o(e,r)&&!o.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},o.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),o.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),o.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},(()=>{var t;o.g.importScripts&&(t=o.g.location+"");var e=o.g.document;if(!t&&e&&(e.currentScript&&(t=e.currentScript.src),!t)){var r=e.getElementsByTagName("script");if(r.length)for(var n=r.length-1;n>-1&&(!t||!/^http(s?):/.test(t));)t=r[n--].src}if(!t)throw new Error("Automatic publicPath is not supported in this browser");t=t.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),o.p=t})(),o.b=void 0,(()=>{"use strict";var t,e,r;(r=t||(t={}))[r.loading=0]="loading",r[r.loaded=1]="loaded",r[r.initialised=2]="initialised",r[r.computing=3]="computing";class n{constructor(){this.hashesFromPreviousRun={},this.usedHashes={},this.argCache={}}cleanAllCache(){Object.keys(this.usedHashes).forEach((t=>{if(this.argCache[t])try{this.argCache[t].delete()}catch(t){}})),this.argCache={},this.usedHashes={},this.hashesFromPreviousRun={}}cleanCacheForHash(t){if(this.argCache[t])try{this.argCache[t].delete()}catch(t){}delete this.argCache[t],delete this.usedHashes[t],delete this.hashesFromPreviousRun[t]}isManifoldObject(t){return null!=t&&!Array.isArray(t)&&void 0!==t.$$||Array.isArray(t)&&t.length>0&&void 0!==t[0].$$}cacheOp(t,e){let r=null;const n=this.computeHash(t);this.usedHashes[n]=n,this.hashesFromPreviousRun[n]=n;const o=this.checkCache(n);if(o)this.isManifoldObject(o)?(r=o,r.hash=o.hash):o.value&&(r=o.value);else if(r=e(),Array.isArray(r)&&this.isManifoldObject(r))r.forEach(((e,r)=>{const n=this.computeHash(Object.assign(Object.assign({},t),{index:r}));e.hash=n,this.addToCache(n,e)}));else if(this.isManifoldObject(r))this.addToCache(n,r);else if(r.compound&&r.data&&r.manifolds&&r.manifolds.length>0){const e=r,o=this.computeHash(Object.assign(Object.assign({},t),{index:"compound"}));e.compound.hash=o,this.addToCache(o,e.compound),e.manifolds.forEach(((e,r)=>{const n=this.computeHash(Object.assign(Object.assign({},t),{index:r}));e.manifold.hash=n,this.addToCache(n,e.manifold)})),this.addToCache(n,{value:e})}else this.addToCache(n,{value:r});return r}checkCache(t){return this.argCache[t]||null}addToCache(t,e){const r=e;return r.hash=t,this.argCache[t]=r,t}computeHash(t,e){let r=JSON.stringify(t);r=r.replace(/(\"ptr\"\:(-?[0-9]*?)\,)/g,""),r=r.replace(/(\"ptr\"\:(-?[0-9]*))/g,""),r.includes("ptr")&&console.error("YOU DONE MESSED UP YOUR REGEX.");const n=Math.random.toString()+r;return e?n:this.stringToHash(n)}stringToHash(t){let e=0;if(0===t.length)return e;for(let r=0;rt.hash!==e.hash||t.ptr!==e.ptr))}}!function(t){let e,r;!function(t){t.evenOdd="EvenOdd",t.nonZero="NonZero",t.positive="Positive",t.negative="Negative"}(e=t.fillRuleEnum||(t.fillRuleEnum={})),function(t){t.square="Square",t.round="Round",t.miter="Miter"}(r=t.manifoldJoinTypeEnum||(t.manifoldJoinTypeEnum={})),t.DecomposedManifoldMeshDto=class{},t.DrawManifoldOrCrossSectionDto=class{constructor(t,e,r,n,o,s,i,a){this.faceOpacity=1,this.faceColour="#ff0000",this.crossSectionColour="#ff00ff",this.crossSectionWidth=2,this.crossSectionOpacity=1,this.computeNormals=!1,void 0!==t&&(this.manifoldOrCrossSection=t),void 0!==e&&(this.faceOpacity=e),void 0!==r&&(this.faceMaterial=r),void 0!==n&&(this.faceColour=n),void 0!==o&&(this.crossSectionColour=o),void 0!==s&&(this.crossSectionWidth=s),void 0!==i&&(this.crossSectionOpacity=i),void 0!==a&&(this.computeNormals=a)}},t.DrawManifoldsOrCrossSectionsDto=class{constructor(t,e,r,n,o,s,i,a){this.faceColour="#ff0000",this.faceOpacity=1,this.crossSectionColour="#ff00ff",this.crossSectionWidth=2,this.crossSectionOpacity=1,this.computeNormals=!1,void 0!==t&&(this.manifoldsOrCrossSections=t),void 0!==e&&(this.faceOpacity=e),void 0!==r&&(this.faceMaterial=r),void 0!==n&&(this.faceColour=n),void 0!==o&&(this.crossSectionColour=o),void 0!==s&&(this.crossSectionWidth=s),void 0!==i&&(this.crossSectionOpacity=i),void 0!==a&&(this.computeNormals=a)}},t.CreateFromMeshDto=class{constructor(t){void 0!==t&&(this.mesh=t)}},t.CubeDto=class{constructor(t,e){this.center=!0,this.size=1,void 0!==t&&(this.center=t),void 0!==e&&(this.size=e)}},t.CreateContourSectionDto=class{constructor(t,r){this.fillRule=e.evenOdd,void 0!==t&&(this.polygons=t),void 0!==r&&(this.fillRule=r)}},t.SquareDto=class{constructor(t,e){this.center=!1,this.size=1,void 0!==t&&(this.center=t),void 0!==e&&(this.size=e)}},t.SphereDto=class{constructor(t,e){this.radius=1,void 0!==t&&(this.radius=t),void 0!==e&&(this.circularSegments=e)}},t.CylinderDto=class{constructor(t,e,r,n,o){this.height=1,this.radiusLow=1,this.radiusHigh=1,this.circularSegments=32,this.center=!0,void 0!==t&&(this.height=t),void 0!==e&&(this.radiusLow=e),void 0!==r&&(this.radiusHigh=r),void 0!==n&&(this.circularSegments=n),void 0!==o&&(this.center=o)}},t.CircleDto=class{constructor(t,e){this.radius=1,this.circularSegments=32,void 0!==t&&(this.radius=t),void 0!==e&&(this.circularSegments=e)}},t.RectangleDto=class{constructor(t,e,r){this.length=1,this.height=1,this.center=!1,void 0!==t&&(this.length=t),void 0!==e&&(this.height=e),void 0!==r&&(this.center=r)}},t.ManifoldDto=class{constructor(t){void 0!==t&&(this.manifold=t)}},t.CalculateNormalsDto=class{constructor(t,e,r){this.normalIdx=0,this.minSharpAngle=0,void 0!==t&&(this.manifold=t),void 0!==e&&(this.normalIdx=e),void 0!==r&&(this.minSharpAngle=r)}},t.CalculateCurvatureDto=class{constructor(t){void 0!==t&&(this.manifold=t)}},t.CountDto=class{constructor(t){void 0!==t&&(this.count=t)}},t.ManifoldsMinGapDto=class{constructor(t,e,r){this.searchLength=100,void 0!==t&&(this.manifold1=t),void 0!==e&&(this.manifold2=e),void 0!==r&&(this.searchLength=r)}},t.ManifoldRefineToleranceDto=class{constructor(t,e){this.tolerance=1e-6,void 0!==t&&(this.manifold=t),void 0!==e&&(this.tolerance=e)}},t.ManifoldRefineLengthDto=class{constructor(t,e){this.length=.1,void 0!==t&&(this.manifold=t),void 0!==e&&(this.length=e)}},t.ManifoldRefineDto=class{constructor(t,e){this.number=1,void 0!==t&&(this.manifold=t),void 0!==e&&(this.number=e)}},t.ManifoldSmoothByNormalsDto=class{constructor(t,e){this.normalIdx=0,void 0!==t&&(this.manifold=t),void 0!==e&&(this.normalIdx=e)}},t.ManifoldSmoothOutDto=class{constructor(t,e,r){this.minSharpAngle=60,this.minSmoothness=0,void 0!==t&&(this.manifold=t),void 0!==e&&(this.minSharpAngle=e),void 0!==r&&(this.minSmoothness=r)}},t.HullPointsDto=class{constructor(t){void 0!==t&&(this.points=t)}},t.SliceDto=class{constructor(t){this.height=.5,void 0!==t&&(this.manifold=t)}},t.MeshDto=class{constructor(t){void 0!==t&&(this.mesh=t)}},t.MeshVertexIndexDto=class{constructor(t,e){void 0!==t&&(this.mesh=t),void 0!==e&&(this.vertexIndex=e)}},t.MeshTriangleRunIndexDto=class{constructor(t,e){void 0!==t&&(this.mesh=t),void 0!==e&&(this.triangleRunIndex=e)}},t.MeshHalfEdgeIndexDto=class{constructor(t,e){void 0!==t&&(this.mesh=t),void 0!==e&&(this.halfEdgeIndex=e)}},t.MeshTriangleIndexDto=class{constructor(t,e){void 0!==t&&(this.mesh=t),void 0!==e&&(this.triangleIndex=e)}},t.CrossSectionDto=class{constructor(t){void 0!==t&&(this.crossSection=t)}},t.CrossSectionsDto=class{constructor(t){void 0!==t&&(this.crossSections=t)}},t.ExtrudeDto=class{constructor(t){this.height=1,this.nDivisions=1,this.twistDegrees=0,this.scaleTopX=1,this.scaleTopY=1,this.center=!0,void 0!==t&&(this.crossSection=t)}},t.RevolveDto=class{constructor(t,e,r,n){this.matchProfile=!0,this.circularSegments=32,void 0!==t&&(this.crossSection=t),void 0!==e&&(this.revolveDegrees=e),void 0!==r&&(this.matchProfile=r),void 0!==n&&(this.circularSegments=n)}},t.OffsetDto=class{constructor(t,e,n,o,s){this.joinType=r.round,this.miterLimit=2,this.circularSegments=32,void 0!==t&&(this.crossSection=t),void 0!==e&&(this.delta=e),void 0!==n&&(this.joinType=n),void 0!==o&&(this.miterLimit=o),void 0!==s&&(this.circularSegments=s)}},t.SimplifyDto=class{constructor(t,e){this.epsilon=1e-6,void 0!==t&&(this.crossSection=t),void 0!==e&&(this.epsilon=e)}},t.ComposeDto=class{constructor(t){void 0!==t&&(this.polygons=t)}},t.MirrorCrossSectionDto=class{constructor(t,e){this.normal=[1,0],void 0!==t&&(this.crossSection=t),void 0!==e&&(this.normal=e)}},t.Scale2DCrossSectionDto=class{constructor(t,e){this.vector=[2,2],void 0!==t&&(this.crossSection=t),void 0!==e&&(this.vector=e)}},t.TranslateCrossSectionDto=class{constructor(t,e){void 0!==t&&(this.crossSection=t),void 0!==e&&(this.vector=e)}},t.RotateCrossSectionDto=class{constructor(t,e){void 0!==t&&(this.crossSection=t),void 0!==e&&(this.degrees=e)}},t.ScaleCrossSectionDto=class{constructor(t,e){this.factor=2,void 0!==t&&(this.crossSection=t),void 0!==e&&(this.factor=e)}},t.TranslateXYCrossSectionDto=class{constructor(t,e,r){this.x=0,this.y=0,void 0!==t&&(this.crossSection=t),void 0!==e&&(this.x=e),void 0!==r&&(this.y=r)}},t.TransformCrossSectionDto=class{constructor(t,e){void 0!==t&&(this.crossSection=t),void 0!==e&&(this.transform=e)}},t.MirrorDto=class{constructor(t,e){this.normal=[1,0,0],void 0!==t&&(this.manifold=t),void 0!==e&&(this.normal=e)}},t.Scale3DDto=class{constructor(t,e){this.vector=[2,2,2],void 0!==t&&(this.manifold=t),void 0!==e&&(this.vector=e)}},t.TranslateDto=class{constructor(t,e){void 0!==t&&(this.manifold=t),void 0!==e&&(this.vector=e)}},t.TranslateByVectorsDto=class{constructor(t,e){void 0!==t&&(this.manifold=t),void 0!==e&&(this.vectors=e)}},t.RotateDto=class{constructor(t,e){void 0!==t&&(this.manifold=t),void 0!==e&&(this.vector=e)}},t.RotateXYZDto=class{constructor(t,e,r,n){this.x=0,this.y=0,this.z=0,void 0!==t&&(this.manifold=t),void 0!==e&&(this.x=e),void 0!==r&&(this.y=r),void 0!==n&&(this.z=n)}},t.ScaleDto=class{constructor(t,e){this.factor=2,void 0!==t&&(this.manifold=t),void 0!==e&&(this.factor=e)}},t.TranslateXYZDto=class{constructor(t,e,r,n){this.x=0,this.y=0,this.z=0,void 0!==t&&(this.manifold=t),void 0!==e&&(this.x=e),void 0!==r&&(this.y=r),void 0!==n&&(this.z=n)}},t.TransformDto=class{constructor(t,e){void 0!==t&&(this.manifold=t),void 0!==e&&(this.transform=e)}},t.TransformsDto=class{constructor(t,e){void 0!==t&&(this.manifold=t),void 0!==e&&(this.transforms=e)}},t.TwoCrossSectionsDto=class{constructor(t,e){void 0!==t&&(this.crossSection1=t),void 0!==e&&(this.crossSection2=e)}},t.TwoManifoldsDto=class{constructor(t,e){void 0!==t&&(this.manifold1=t),void 0!==e&&(this.manifold2=e)}},t.SplitManifoldsDto=class{constructor(t,e){void 0!==t&&(this.manifoldToSplit=t),void 0!==e&&(this.manifoldCutter=e)}},t.TrimByPlaneDto=class{constructor(t,e,r){this.normal=[1,0,0],this.originOffset=0,void 0!==t&&(this.manifold=t),void 0!==e&&(this.normal=e),void 0!==r&&(this.originOffset=r)}},t.SplitByPlaneDto=class{constructor(t,e,r){this.normal=[1,0,0],this.originOffset=0,void 0!==t&&(this.manifold=t),void 0!==e&&(this.normal=e),void 0!==r&&(this.originOffset=r)}},t.ManifoldsDto=class{constructor(t){void 0!==t&&(this.manifolds=t)}},t.ManifoldToMeshDto=class{constructor(t,e){void 0!==t&&(this.manifold=t),void 0!==e&&(this.normalIdx=e)}},t.ManifoldsToMeshesDto=class{constructor(t,e){void 0!==t&&(this.manifolds=t),void 0!==e&&(this.normalIdx=e)}},t.DecomposeManifoldOrCrossSectionDto=class{constructor(t,e){void 0!==t&&(this.manifoldOrCrossSection=t),void 0!==e&&(this.normalIdx=e)}},t.ManifoldOrCrossSectionDto=class{constructor(t){void 0!==t&&(this.manifoldOrCrossSection=t)}},t.ManifoldsOrCrossSectionsDto=class{constructor(t){void 0!==t&&(this.manifoldsOrCrossSections=t)}},t.DecomposeManifoldsOrCrossSectionsDto=class{constructor(t,e){void 0!==t&&(this.manifoldsOrCrossSections=t),void 0!==e&&(this.normalIdx=e)}}}(e||(e={}));class s{constructor(t){this.manifold=t}manifoldFromMesh(t){const{Manifold:e}=this.manifold;return new e(t.mesh)}cube(t){const{Manifold:e}=this.manifold,{cube:r}=e;return r(t.size,t.center)}sphere(t){const{Manifold:e}=this.manifold,{sphere:r}=e;return r(t.radius,t.circularSegments)}tetrahedron(){const{Manifold:t}=this.manifold,{tetrahedron:e}=t;return e()}cylinder(t){const{Manifold:e}=this.manifold,{cylinder:r}=e;return r(t.height,t.radiusLow,t.radiusHigh,t.circularSegments,t.center)}}class i{constructor(t){this.manifold=t}split(t){return t.manifoldToSplit.split(t.manifoldCutter)}splitByPlane(t){return t.manifold.splitByPlane(t.normal,t.originOffset)}trimByPlane(t){return t.manifold.asOriginal().trimByPlane(t.normal,t.originOffset)}subtract(t){return t.manifold1.subtract(t.manifold2)}add(t){return t.manifold1.add(t.manifold2)}intersect(t){return t.manifold1.intersect(t.manifold2)}differenceTwo(t){const{Manifold:e}=this.manifold,{difference:r}=e;return r(t.manifold1,t.manifold2)}difference(t){const{Manifold:e}=this.manifold,{difference:r}=e;return r(t.manifolds)}unionTwo(t){const{Manifold:e}=this.manifold,{union:r}=e;return r(t.manifold1,t.manifold2)}union(t){const{Manifold:e}=this.manifold,{union:r}=e;return r(t.manifolds)}intersectionTwo(t){const{Manifold:e}=this.manifold,{intersection:r}=e;return r(t.manifold1,t.manifold2)}intersection(t){const{Manifold:e}=this.manifold,{intersection:r}=e;return r(t.manifolds)}}class a{constructor(t){this.manifold=t}hull(t){return t.manifold.hull()}hullPoints(t){const{Manifold:e}=this.manifold,{hull:r}=e;return r(t.points)}slice(t){return t.manifold.slice(t.height)}project(t){return t.manifold.project()}setTolerance(t){return t.manifold.setTolerance(t.tolerance)}asOriginal(t){return t.manifold.asOriginal()}reserveIds(t){const{Manifold:e}=this.manifold,{reserveIDs:r}=e;return r(t.count)}compose(t){const{Manifold:e}=this.manifold,{compose:r}=e;return r(t.manifolds)}decompose(t){return t.manifold.decompose()}calculateNormals(t){return t.manifold.calculateNormals(t.normalIdx,t.minSharpAngle)}calculateCurvature(t){return t.manifold.calculateCurvature(t.gaussianIdx,t.meanIdx)}refineToTolerance(t){return t.manifold.refineToTolerance(t.tolerance)}refineToLength(t){return t.manifold.refineToLength(t.length)}refine(t){return t.manifold.refine(t.number)}smoothOut(t){return t.manifold.smoothOut(t.minSharpAngle,t.minSmoothness)}smoothByNormals(t){return t.manifold.smoothByNormals(t.normalIdx)}}class c{constructor(t){this.manifold=t}scale3D(t){return t.manifold.scale(t.vector)}scale(t){return t.manifold.scale(t.vector)}mirror(t){return t.manifold.mirror(t.normal)}translate(t){return t.manifold.translate(t.vector)}translateByVectors(t){return t.vectors.map((e=>t.manifold.translate(e)))}rotate(t){return t.manifold.rotate(t.vector)}rotateXYZ(t){return t.manifold.rotate(t.x,t.y,t.z)}translateXYZ(t){return t.manifold.translate(t.x,t.y,t.z)}transform(t){return t.manifold.transform(t.transform)}transforms(t){let e=t.manifold;const r=[];t.transforms.forEach((t=>{e=e.transform(t),r.push(e)}));const n=r.pop();return r.forEach((t=>{t.delete()})),n}}class u{constructor(t){this.manifold=t}volume(t){return t.manifold.volume()}surfaceArea(t){return t.manifold.surfaceArea()}isEmpty(t){return t.manifold.isEmpty()}numVert(t){return t.manifold.numVert()}numTri(t){return t.manifold.numTri()}numEdge(t){return t.manifold.numEdge()}numProp(t){return t.manifold.numProp()}numPropVert(t){return t.manifold.numPropVert()}boundingBox(t){const e=t.manifold.boundingBox();return[e.min,e.max]}tolerance(t){return t.manifold.tolerance()}genus(t){return t.manifold.genus()}minGap(t){return t.manifold1.minGap(t.manifold2,t.searchLength)}originalID(t){return t.manifold.originalID()}}class l{constructor(t){this.shapes=new s(t),this.booleans=new i(t),this.operations=new a(t),this.transforms=new c(t),this.evaluate=new u(t)}manifoldToMesh(t){return t.manifold.getMesh(t.normalIdx)}manifoldsToMeshes(t){return t.manifolds.map(((e,r)=>{const n=t.normalIdx?t.normalIdx[r]:void 0;return this.manifoldToMesh({manifold:e,normalIdx:n})}))}}class h{constructor(t){this.manifold=t}create(t){const{CrossSection:e}=this.manifold;return new e(t.polygons,t.fillRule)}square(t){const{CrossSection:e}=this.manifold,{square:r}=e;return r(t.size,t.center)}circle(t){const{CrossSection:e}=this.manifold,{circle:r}=e;return r(t.radius,t.circularSegments)}rectangle(t){const{CrossSection:e}=this.manifold,{square:r}=e;return r([t.length,t.height],t.center)}}class d{constructor(t){this.manifold=t}hull(t){return t.crossSection.hull()}extrude(t){return t.crossSection.extrude(t.height,t.nDivisions,t.twistDegrees,[t.scaleTopX,t.scaleTopY],t.center)}revolve(t){const e=t.crossSection.revolve(t.circularSegments,t.revolveDegrees);return t.matchProfile?e.rotate([90,0,0]):e}offset(t){return t.crossSection.offset(t.delta,t.joinType,t.miterLimit,t.circularSegments)}simplify(t){return t.crossSection.simplify(t.epsilon)}compose(t){const{CrossSection:e}=this.manifold,{compose:r}=e;return r(t.polygons)}decompose(t){return t.crossSection.decompose()}}class f{constructor(t){this.manifold=t}scale2D(t){return t.crossSection.scale(t.vector)}scale(t){return t.crossSection.scale(t.factor)}mirror(t){return t.crossSection.mirror(t.normal)}translate(t){return t.crossSection.translate(t.vector)}translateXY(t){return t.crossSection.translate([t.x,t.y])}rotate(t){return t.crossSection.rotate(t.degrees)}transform(t){return t.crossSection.transform(t.transform)}}class p{constructor(t){this.manifold=t}subtract(t){return t.crossSection1.subtract(t.crossSection2)}add(t){return t.crossSection1.add(t.crossSection2)}intersect(t){return t.crossSection1.intersect(t.crossSection2)}differenceTwo(t){const{CrossSection:e}=this.manifold,{difference:r}=e;return r(t.crossSection1,t.crossSection2)}difference(t){const{CrossSection:e}=this.manifold,{difference:r}=e;return r(t.crossSections)}unionTwo(t){const{CrossSection:e}=this.manifold,{union:r}=e;return r(t.crossSection1,t.crossSection2)}union(t){const{CrossSection:e}=this.manifold,{union:r}=e;return r(t.crossSections)}intersectionTwo(t){const{CrossSection:e}=this.manifold,{intersection:r}=e;return r(t.crossSection1,t.crossSection2)}intersection(t){const{CrossSection:e}=this.manifold,{intersection:r}=e;return r(t.crossSections)}}class m{constructor(t){this.manifold=t}area(t){return t.crossSection.area()}isEmpty(t){return t.crossSection.isEmpty()}numVert(t){return t.crossSection.numVert()}numContour(t){return t.crossSection.numContour()}bounds(t){const e=t.crossSection.bounds();return[e.min,e.max]}}class v{constructor(t){this.manifold=t,this.shapes=new h(t),this.operations=new d(t),this.transforms=new f(t),this.booleans=new p(t),this.evaluate=new m(t)}crossSectionToPolygons(t){return t.crossSection.toPolygons()}crossSectionsToPolygons(t){return t.crossSections.map((t=>this.crossSectionToPolygons({crossSection:t})))}deleteCrossSection(t){t.crossSection.delete()}deleteCrossSections(t){t.crossSections.forEach((t=>this.deleteCrossSection({crossSection:t})))}}class g{constructor(t){this.manifold=t}position(t){const e=t.mesh.position(t.vertexIndex);return[e[0],e[1],e[2]]}tangent(t){const e=t.mesh.tangent(t.halfEdgeIndex);return[e[0],e[1],e[2],e[4]]}verts(t){const e=t.mesh.verts(t.triangleIndex);return[e[0],e[1],e[2]]}extras(t){return[...t.mesh.extras(t.vertexIndex)]}transform(t){return[...t.mesh.transform(t.triangleRunIndex)]}numProp(t){return t.mesh.numProp}numVert(t){return t.mesh.numVert}numTri(t){return t.mesh.numTri}numRun(t){return t.mesh.numRun}}class y{constructor(t){this.manifold=t}merge(t){return t.mesh.merge()}}class b{constructor(t){this.operations=new y(t),this.evaluate=new g(t)}}class S{constructor(t){this.crossSection=new v(t),this.manifold=new l(t),this.mesh=new b(t)}decomposeManifoldOrCrossSection(t){return t.manifoldOrCrossSection.getMesh?t.manifoldOrCrossSection.getMesh(t.normalIdx):t.manifoldOrCrossSection.toPolygons()}decomposeManifoldsOrCrossSections(t){return t.manifoldsOrCrossSections.map(((e,r)=>{const n=t.normalIdx?t.normalIdx[r]:void 0;return this.decomposeManifoldOrCrossSection({manifoldOrCrossSection:e,normalIdx:n})}))}}let C,w,T;var $,P=($="file:///Users/matasubarevicius/Documents/MyProjects/bitbybit-ui/node_modules/manifold-3d/manifold.js",async function(t={}){var e,r,n=t,s=new Promise(((t,n)=>{e=t,r=n})),i="object"==typeof window,a="function"==typeof importScripts,c="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(c){const{createRequire:t}=await Promise.resolve().then(o.t.bind(o,167,19));var u=t("file:///Users/matasubarevicius/Documents/MyProjects/bitbybit-ui/node_modules/manifold-3d/manifold.js")}var l=!1;n.setup=function(){if(l)return;function t(t,e,r=(t=>t)){if(e)for(let n of e)t.push_back(r(n));return t}function e(t,e=(t=>t)){const r=[],n=t.size();for(let o=0;ot(new n.Vector_vec2,e,(t=>t instanceof Array?{x:t[0],y:t[1]}:t))))}function o(t){for(let e=0;et.min[e])),max:["x","y"].map((e=>t.max[e]))}},n.CrossSection.prototype.offset=function(t,e="Square",r=2,n=0){return this._Offset(t,function(t){return"Round"==t?1:"Miter"==t?2:0}(e),r,n)},n.CrossSection.prototype.extrude=function(t,e=0,r=0,o=[1,1],i=!1){o=s([o]);const a=n._Extrude(this._ToPolygons(),t,e,r,o);return i?a.translate([0,0,-t/2]):a},n.CrossSection.prototype.revolve=function(t=0,e=360){return n._Revolve(this._ToPolygons(),t,e)},n.CrossSection.prototype.add=function(t){return this._add(u(t))},n.CrossSection.prototype.subtract=function(t){return this._subtract(u(t))},n.CrossSection.prototype.intersect=function(t){return this._intersect(u(t))},n.CrossSection.prototype.toPolygons=function(){const t=this._ToPolygons(),e=function(t,e=(t=>t)){const r=[],n=t.size();for(let o=0;o[t.x,t.y]));return t.delete(),e},n.Manifold.prototype.smoothOut=function(t=60,e=0){return this._SmoothOut(t,e)},n.Manifold.prototype.warp=function(t){const e=Se((function(e){const r=[z(e,"double"),z(e+8,"double"),z(e+16,"double")];t(r),q(e,r[0],"double"),q(e+8,r[1],"double"),q(e+16,r[2],"double")}),"vi"),r=this._Warp(e);Ce(e);const o=r.status();if(0!==o.value)throw new n.ManifoldError(o.value);return r},n.Manifold.prototype.calculateNormals=function(t,e=60){return this._CalculateNormals(t,e)},n.Manifold.prototype.setProperties=function(t,e){const r=this.numProp(),n=Se((function(n,o,s){const i=[];for(let e=0;et.min[e])),max:["x","y","z"].map((e=>t.max[e]))}};class h{constructor({numProp:t=3,triVerts:e=new Uint32Array,vertProperties:r=new Float32Array,mergeFromVert:n,mergeToVert:o,runIndex:s,runOriginalID:i,faceID:a,halfedgeTangent:c,runTransform:u}={}){this.numProp=t,this.triVerts=e,this.vertProperties=r,this.mergeFromVert=n,this.mergeToVert=o,this.runIndex=s,this.runOriginalID=i,this.faceID=a,this.halfedgeTangent=c,this.runTransform=u}get numTri(){return this.triVerts.length/3}get numVert(){return this.vertProperties.length/this.numProp}get numRun(){return this.runOriginalID.length}merge(){const{changed:t,mesh:e}=n._Merge(this);return Object.assign(this,{...e}),t}verts(t){return this.triVerts.subarray(3*t,3*(t+1))}position(t){return this.vertProperties.subarray(this.numProp*t,this.numProp*t+3)}extras(t){return this.vertProperties.subarray(this.numProp*t+3,this.numProp*(t+1))}tangent(t){return this.halfedgeTangent.subarray(4*t,4*(t+1))}transform(t){const e=new Array(16);for(const r of[0,1,2,3])for(const n of[0,1,2])e[4*r+n]=this.runTransform[12*t+3*r+n];return e[15]=1,e}}function d(t){return function(...e){1==e.length&&(e=e[0]);const r=new n.Vector_crossSection;for(const t of e)r.push_back(u(t));const o=n["_crossSection"+t](r);return r.delete(),o}}n.Mesh=h,n.Manifold.prototype.getMesh=function(t=-1){return new h(this._GetMeshJS(t))},n.ManifoldError=function(t,...e){let r="Unknown error";switch(t){case n.status.NonFiniteVertex.value:r="Non-finite vertex";break;case n.status.NotManifold.value:r="Not manifold";break;case n.status.VertexOutOfBounds.value:r="Vertex index out of bounds";break;case n.status.PropertiesWrongLength.value:r="Properties have wrong length";break;case n.status.MissingPositionProperties.value:r="Less than three properties";break;case n.status.MergeVectorsDifferentLengths.value:r="Merge vectors have different lengths";break;case n.status.MergeIndexOutOfBounds.value:r="Merge index out of bounds";break;case n.status.TransformWrongLength.value:r="Transform vector has wrong length";break;case n.status.RunIndexWrongLength.value:r="Run index vector has wrong length";break;case n.status.FaceIDWrongLength.value:r="Face ID vector has wrong length";case n.status.InvalidConstruction.value:r="Manifold constructed with invalid parameters"}const o=Error.apply(this,[r,...e]);o.name=this.name="ManifoldError",this.message=o.message,this.stack=o.stack,this.code=t},n.ManifoldError.prototype=Object.create(Error.prototype,{constructor:{value:n.ManifoldError,writable:!0,configurable:!0}}),n.CrossSection=function(t,e="Positive"){const n=r(t),s=new c(n,a(e));return o(n),s},n.CrossSection.ofPolygons=function(t,e="Positive"){return new n.CrossSection(t,e)},n.CrossSection.square=function(...t){let e;e=0==t.length?{x:1,y:1}:"number"==typeof t[0]?{x:t[0],y:t[0]}:s(t);const r=t[1]||!1;return n._Square(e,r)},n.CrossSection.circle=function(t,e=0){return n._Circle(t,e)},n.CrossSection.compose=d("Compose"),n.CrossSection.union=d("UnionN"),n.CrossSection.difference=d("DifferenceN"),n.CrossSection.intersection=d("IntersectionN"),n.CrossSection.hull=function(...e){1==e.length&&(e=e[0]);let r=new n.Vector_vec2;for(const o of e)if(o instanceof c)n._crossSectionCollectVertices(r,o);else if(o instanceof Array&&2==o.length&&"number"==typeof o[0])r.push_back({x:o[0],y:o[1]});else if(o.x)r.push_back(o);else{const e=2==o[0].length&&"number"==typeof o[0][0]||o[0].x?[o]:o;for(const n of e)t(r,n,(t=>t instanceof Array?{x:t[0],y:t[1]}:t))}const o=n._crossSectionHullPoints(r);return r.delete(),o},n.CrossSection.prototype=Object.create(c.prototype),Object.defineProperty(n.CrossSection,Symbol.hasInstance,{get:()=>t=>t instanceof c});const f=n.Manifold;function p(t){return function(...e){1==e.length&&(e=e[0]);const r=new n.Vector_manifold;for(const t of e)r.push_back(t);const o=n["_manifold"+t+"N"](r);return r.delete(),o}}n.Manifold=function(t){const e=new f(t),r=e.status();if(0!==r.value)throw new n.ManifoldError(r.value);return e},n.Manifold.ofMesh=function(t){return new n.Manifold(t)},n.Manifold.tetrahedron=function(){return n._Tetrahedron()},n.Manifold.cube=function(...t){let e;e=0==t.length?{x:1,y:1,z:1}:"number"==typeof t[0]?{x:t[0],y:t[0],z:t[0]}:i(t);const r=t[1]||!1;return n._Cube(e,r)},n.Manifold.cylinder=function(t,e,r=-1,o=0,s=!1){return n._Cylinder(t,e,r,o,s)},n.Manifold.sphere=function(t,e=0){return n._Sphere(t,e)},n.Manifold.smooth=function(e,r=[]){const o=new n.Vector_smoothness;t(o,r);const s=n._Smooth(e,o);return o.delete(),s},n.Manifold.extrude=function(t,e,r=0,o=0,s=[1,1],i=!1){return(t instanceof c?t:n.CrossSection(t,"Positive")).extrude(e,r,o,s,i)},n.Manifold.revolve=function(t,e=0,r=360){return(t instanceof c?t:n.CrossSection(t,"Positive")).revolve(e,r)},n.Manifold.reserveIDs=function(t){return n._ReserveIDs(t)},n.Manifold.compose=function(e){const r=new n.Vector_manifold;t(r,e);const o=n._manifoldCompose(r);return r.delete(),o},n.Manifold.union=p("Union"),n.Manifold.difference=p("Difference"),n.Manifold.intersection=p("Intersection"),n.Manifold.levelSet=function(t,e,r,o=0,s=-1){const i={min:{x:e.min[0],y:e.min[1],z:e.min[2]},max:{x:e.max[0],y:e.max[1],z:e.max[2]}},a=Se((function(e){const r=z(e,"double"),n=z(e+8,"double"),o=z(e+16,"double");return t([r,n,o])}),"di"),c=n._LevelSet(a,i,r,o,s);return Ce(a),c},n.Manifold.hull=function(...e){1==e.length&&(e=e[0]);let r=new n.Vector_vec3;for(const o of e)o instanceof f?n._manifoldCollectVertices(r,o):o instanceof Array&&3==o.length&&"number"==typeof o[0]?r.push_back({x:o[0],y:o[1],z:o[2]}):o.x?r.push_back(o):t(r,o,(t=>t instanceof Array?{x:t[0],y:t[1],z:t[2]}:t));const o=n._manifoldHullPoints(r);return r.delete(),o},n.Manifold.prototype=Object.create(f.prototype),Object.defineProperty(n.Manifold,Symbol.hasInstance,{get:()=>t=>t instanceof f}),n.triangulate=function(t,s=-1){const i=r(t),a=e(n._Triangulate(i,s),(t=>[t[0],t[1],t[2]]));return o(i),a}};var h,d,f,p=Object.assign({},n),m="";if(c){var v=u("fs"),g=u("path");m=u("url").fileURLToPath(new URL(o(448),o.b)),h=(t,e)=>(t=H(t)?new URL(t):g.normalize(t),v.readFileSync(t,e?void 0:"utf8")),f=t=>{var e=h(t,!0);return e.buffer||(e=new Uint8Array(e)),e},d=(t,e,r,n=!0)=>{t=H(t)?new URL(t):g.normalize(t),v.readFile(t,n?void 0:"utf8",((t,o)=>{t?r(t):e(n?o.buffer:o)}))},!n.thisProgram&&process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2)}else(i||a)&&(a?m=self.location.href:"undefined"!=typeof document&&document.currentScript&&(m=document.currentScript.src),$&&(m=$),m=m.startsWith("blob:")?"":m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1),h=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},a&&(f=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),d=(t,e,r)=>{if(H(t)){var n=new XMLHttpRequest;return n.open("GET",t,!0),n.responseType="arraybuffer",n.onload=()=>{200==n.status||0==n.status&&n.response?e(n.response):r()},n.onerror=r,void n.send(null)}fetch(t,{credentials:"same-origin"}).then((t=>t.ok?t.arrayBuffer():Promise.reject(new Error(t.status+" : "+t.url)))).then(e,r)});n.print||console.log.bind(console);var y,b,S=n.printErr||console.error.bind(console);Object.assign(n,p),p=null,n.arguments&&n.arguments,n.thisProgram&&n.thisProgram,n.quit&&n.quit,n.wasmBinary&&(y=n.wasmBinary);var C,w,T,P,M,O,x,_,D=!1;function A(){var t=b.buffer;n.HEAP8=C=new Int8Array(t),n.HEAP16=T=new Int16Array(t),n.HEAPU8=w=new Uint8Array(t),n.HEAPU16=P=new Uint16Array(t),n.HEAP32=M=new Int32Array(t),n.HEAPU32=O=new Uint32Array(t),n.HEAPF32=x=new Float32Array(t),n.HEAPF64=_=new Float64Array(t)}var E=[],j=[],I=[],k=0,R=null,W=null;function F(t){n.onAbort?.(t),S(t="Aborted("+t+")"),D=!0,t+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(t);throw r(e),e}var V,N=t=>t.startsWith("data:application/octet-stream;base64,"),H=t=>t.startsWith("file://");function B(t){if(t==V&&y)return new Uint8Array(y);if(f)return f(t);throw"both async and sync fetching of the wasm failed"}function U(t,e,r){return function(t){return y?Promise.resolve().then((()=>B(t))):new Promise(((e,r)=>{d(t,(t=>e(new Uint8Array(t))),(n=>{try{e(B(t))}catch(t){r(t)}}))}))}(t).then((t=>WebAssembly.instantiate(t,e))).then(r,(t=>{S(`failed to asynchronously prepare wasm: ${t}`),F(t)}))}var L=t=>{for(;t.length>0;)t.shift()(n)};function z(t,e="i8"){switch(e.endsWith("*")&&(e="*"),e){case"i1":case"i8":return C[t>>>0];case"i16":return T[t>>>1>>>0];case"i32":return M[t>>>2>>>0];case"i64":F("to do getValue(i64) use WASM_BIGINT");case"float":return x[t>>>2>>>0];case"double":return _[t>>>3>>>0];case"*":return O[t>>>2>>>0];default:F(`invalid type for getValue: ${e}`)}}function q(t,e,r="i8"){switch(r.endsWith("*")&&(r="*"),r){case"i1":case"i8":C[t>>>0]=e;break;case"i16":T[t>>>1>>>0]=e;break;case"i32":M[t>>>2>>>0]=e;break;case"i64":F("to do setValue(i64) use WASM_BIGINT");case"float":x[t>>>2>>>0]=e;break;case"double":_[t>>>3>>>0]=e;break;case"*":O[t>>>2>>>0]=e;break;default:F(`invalid type for setValue: ${r}`)}}n.noExitRuntime;class G{constructor(t){this.excPtr=t,this.ptr=t-24}set_type(t){O[this.ptr+4>>>2>>>0]=t}get_type(){return O[this.ptr+4>>>2>>>0]}set_destructor(t){O[this.ptr+8>>>2>>>0]=t}get_destructor(){return O[this.ptr+8>>>2>>>0]}set_caught(t){t=t?1:0,C[this.ptr+12>>>0]=t}get_caught(){return 0!=C[this.ptr+12>>>0]}set_rethrown(t){t=t?1:0,C[this.ptr+13>>>0]=t}get_rethrown(){return 0!=C[this.ptr+13>>>0]}init(t,e){this.set_adjusted_ptr(0),this.set_type(t),this.set_destructor(e)}set_adjusted_ptr(t){O[this.ptr+16>>>2>>>0]=t}get_adjusted_ptr(){return O[this.ptr+16>>>2>>>0]}get_exception_ptr(){if(xe(this.get_type()))return O[this.excPtr>>>2>>>0];var t=this.get_adjusted_ptr();return 0!==t?t:this.excPtr}}var X={},Y=t=>{for(;t.length;){var e=t.pop();t.pop()(e)}};function Z(t){return this.fromWireType(O[t>>>2>>>0])}var J,K,Q,tt={},et={},rt={},nt=t=>{throw new J(t)},ot=(t,e,r)=>{function n(e){var n=r(e);n.length!==t.length&&nt("Mismatched type converter count");for(var o=0;o{et.hasOwnProperty(t)?o[e]=et[t]:(s.push(t),tt.hasOwnProperty(t)||(tt[t]=[]),tt[t].push((()=>{o[e]=et[t],++i===s.length&&n(o)})))})),0===s.length&&n(o)},st=t=>{for(var e="",r=t;w[r>>>0];)e+=K[w[r++>>>0]];return e},it=t=>{throw new Q(t)};function at(t,e,r={}){if(!("argPackAdvance"in e))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(t,e,r={}){var n=e.name;if(t||it(`type "${n}" must have a positive integer typeid pointer`),et.hasOwnProperty(t)){if(r.ignoreDuplicateRegistrations)return;it(`Cannot register type '${n}' twice`)}if(et[t]=e,delete rt[t],tt.hasOwnProperty(t)){var o=tt[t];delete tt[t],o.forEach((t=>t()))}}(t,e,r)}var ct,ut=t=>{it(t.$$.ptrType.registeredClass.name+" instance already deleted")},lt=!1,ht=t=>{},dt=t=>{t.count.value-=1,0===t.count.value&&(t=>{t.smartPtr?t.smartPtrType.rawDestructor(t.smartPtr):t.ptrType.registeredClass.rawDestructor(t.ptr)})(t)},ft=(t,e,r)=>{if(e===r)return t;if(void 0===r.baseClass)return null;var n=ft(t,e,r.baseClass);return null===n?null:r.downcast(n)},pt={},mt=[],vt=()=>{for(;mt.length;){var t=mt.pop();t.$$.deleteScheduled=!1,t.delete()}},gt={},yt=(t,e)=>(e.ptrType&&e.ptr||nt("makeClassHandle requires ptr and ptrType"),!!e.smartPtrType!=!!e.smartPtr&&nt("Both smartPtrType and smartPtr must be specified"),e.count={value:1},bt(Object.create(t,{$$:{value:e,writable:!0}})));var bt=t=>"undefined"==typeof FinalizationRegistry?(bt=t=>t,t):(lt=new FinalizationRegistry((t=>{dt(t.$$)})),bt=t=>{var e=t.$$;if(e.smartPtr){var r={$$:e};lt.register(t,r,t)}return t},ht=t=>lt.unregister(t),bt(t));function St(){}var Ct=(t,e)=>Object.defineProperty(e,"name",{value:t}),wt=(t,e,r)=>{if(void 0===t[e].overloadTable){var n=t[e];t[e]=function(...n){return t[e].overloadTable.hasOwnProperty(n.length)||it(`Function '${r}' called with an invalid number of arguments (${n.length}) - expects one of (${t[e].overloadTable})!`),t[e].overloadTable[n.length].apply(this,n)},t[e].overloadTable=[],t[e].overloadTable[n.argCount]=n}},Tt=(t,e,r)=>{n.hasOwnProperty(t)?((void 0===r||void 0!==n[t].overloadTable&&void 0!==n[t].overloadTable[r])&&it(`Cannot register public name '${t}' twice`),wt(n,t,t),n.hasOwnProperty(r)&&it(`Cannot register multiple overloads of a function with the same number of arguments (${r})!`),n[t].overloadTable[r]=e):(n[t]=e,void 0!==r&&(n[t].numArguments=r))};function $t(t,e,r,n,o,s,i,a){this.name=t,this.constructor=e,this.instancePrototype=r,this.rawDestructor=n,this.baseClass=o,this.getActualType=s,this.upcast=i,this.downcast=a,this.pureVirtualFunctions=[]}var Pt=(t,e,r)=>{for(;e!==r;)e.upcast||it(`Expected null or instance of ${r.name}, got an instance of ${e.name}`),t=e.upcast(t),e=e.baseClass;return t};function Mt(t,e){if(null===e)return this.isReference&&it(`null is not a valid ${this.name}`),0;e.$$||it(`Cannot pass "${Kt(e)}" as a ${this.name}`),e.$$.ptr||it(`Cannot pass deleted object as a pointer of type ${this.name}`);var r=e.$$.ptrType.registeredClass;return Pt(e.$$.ptr,r,this.registeredClass)}function Ot(t,e){var r;if(null===e)return this.isReference&&it(`null is not a valid ${this.name}`),this.isSmartPointer?(r=this.rawConstructor(),null!==t&&t.push(this.rawDestructor,r),r):0;e&&e.$$||it(`Cannot pass "${Kt(e)}" as a ${this.name}`),e.$$.ptr||it(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&e.$$.ptrType.isConst&&it(`Cannot convert argument of type ${e.$$.smartPtrType?e.$$.smartPtrType.name:e.$$.ptrType.name} to parameter type ${this.name}`);var n=e.$$.ptrType.registeredClass;if(r=Pt(e.$$.ptr,n,this.registeredClass),this.isSmartPointer)switch(void 0===e.$$.smartPtr&&it("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:e.$$.smartPtrType===this?r=e.$$.smartPtr:it(`Cannot convert argument of type ${e.$$.smartPtrType?e.$$.smartPtrType.name:e.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:r=e.$$.smartPtr;break;case 2:if(e.$$.smartPtrType===this)r=e.$$.smartPtr;else{var o=e.clone();r=this.rawShare(r,Gt.toHandle((()=>o.delete()))),null!==t&&t.push(this.rawDestructor,r)}break;default:it("Unsupporting sharing policy")}return r}function xt(t,e){if(null===e)return this.isReference&&it(`null is not a valid ${this.name}`),0;e.$$||it(`Cannot pass "${Kt(e)}" as a ${this.name}`),e.$$.ptr||it(`Cannot pass deleted object as a pointer of type ${this.name}`),e.$$.ptrType.isConst&&it(`Cannot convert argument of type ${e.$$.ptrType.name} to parameter type ${this.name}`);var r=e.$$.ptrType.registeredClass;return Pt(e.$$.ptr,r,this.registeredClass)}function _t(t,e,r,n,o,s,i,a,c,u,l){this.name=t,this.registeredClass=e,this.isReference=r,this.isConst=n,this.isSmartPointer=o,this.pointeeType=s,this.sharingPolicy=i,this.rawGetPointee=a,this.rawConstructor=c,this.rawShare=u,this.rawDestructor=l,o||void 0!==e.baseClass?this.toWireType=Ot:n?(this.toWireType=Mt,this.destructorFunction=null):(this.toWireType=xt,this.destructorFunction=null)}var Dt,At,Et=(t,e,r)=>{n.hasOwnProperty(t)||nt("Replacing nonexistent public symbol"),void 0!==n[t].overloadTable&&void 0!==r?n[t].overloadTable[r]=e:(n[t]=e,n[t].argCount=r)},jt=[],It=t=>{var e=jt[t];return e||(t>=jt.length&&(jt.length=t+1),jt[t]=e=Dt.get(t)),e},kt=(t,e)=>(...r)=>((t,e,r=[])=>{if(t.includes("j"))return((t,e,r)=>(t=t.replace(/p/g,"i"),(0,n["dynCall_"+t])(e,...r)))(t,e,r);var o=It(e)(...r);return"p"==t[0]?o>>>0:o})(t,e,r),Rt=(t,e)=>{var r=(t=st(t)).includes("j")||t.includes("p")?kt(t,e):It(e);return"function"!=typeof r&&it(`unknown function pointer with signature ${t}: ${e}`),r},Wt=t=>{var e=Pe(t),r=st(e);return Oe(e),r},Ft=(t,e)=>{var r=[],n={};throw e.forEach((function t(e){n[e]||et[e]||(rt[e]?rt[e].forEach(t):(r.push(e),n[e]=!0))})),new At(`${t}: `+r.map(Wt).join([", "]))},Vt=(t,e)=>{for(var r=[],n=0;n>>2>>>0]);return r};function Nt(t){for(var e=1;e0?", ":"")+a),u+=(r||n?"var rv = ":"")+"invoker(fn"+(a.length>0?", ":"")+a+");\n",o)u+="runDestructors(destructors);\n";else for(c=e?1:2;c{const e=(t=t.trim()).indexOf("(");return-1!==e?t.substr(0,e):t},Lt=[],zt=[];function qt(t){(t>>>=0)>9&&0==--zt[t+1]&&(zt[t]=void 0,Lt.push(t))}var Gt={toValue:t=>(t||it("Cannot use deleted val. handle = "+t),zt[t]),toHandle:t=>{switch(t){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:{const e=Lt.pop()||zt.length;return zt[e]=t,zt[e+1]=1,e}}}},Xt={name:"emscripten::val",fromWireType:t=>{var e=Gt.toValue(t);return qt(t),e},toWireType:(t,e)=>Gt.toHandle(e),argPackAdvance:8,readValueFromPointer:Z,destructorFunction:null};function Yt(t){return at(t>>>=0,Xt)}var Zt=(t,e,r)=>{switch(e){case 1:return r?function(t){return this.fromWireType(C[t>>>0])}:function(t){return this.fromWireType(w[t>>>0])};case 2:return r?function(t){return this.fromWireType(T[t>>>1>>>0])}:function(t){return this.fromWireType(P[t>>>1>>>0])};case 4:return r?function(t){return this.fromWireType(M[t>>>2>>>0])}:function(t){return this.fromWireType(O[t>>>2>>>0])};default:throw new TypeError(`invalid integer width (${e}): ${t}`)}},Jt=(t,e)=>{var r=et[t];return void 0===r&&it(`${e} has unknown type ${Wt(t)}`),r},Kt=t=>{if(null===t)return"null";var e=typeof t;return"object"===e||"array"===e||"function"===e?t.toString():""+t},Qt=(t,e)=>{switch(e){case 4:return function(t){return this.fromWireType(x[t>>>2>>>0])};case 8:return function(t){return this.fromWireType(_[t>>>3>>>0])};default:throw new TypeError(`invalid float width (${e}): ${t}`)}},te=(t,e,r)=>{switch(e){case 1:return r?t=>C[t>>>0]:t=>w[t>>>0];case 2:return r?t=>T[t>>>1>>>0]:t=>P[t>>>1>>>0];case 4:return r?t=>M[t>>>2>>>0]:t=>O[t>>>2>>>0];default:throw new TypeError(`invalid integer width (${e}): ${t}`)}},ee="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,re="undefined"!=typeof TextDecoder?new TextDecoder("utf-16le"):void 0,ne=(t,e)=>{for(var r=t,n=r>>1,o=n+e/2;!(n>=o)&&P[n>>>0];)++n;if((r=n<<1)-t>32&&re)return re.decode(w.subarray(t>>>0,r>>>0));for(var s="",i=0;!(i>=e/2);++i){var a=T[t+2*i>>>1>>>0];if(0==a)break;s+=String.fromCharCode(a)}return s},oe=(t,e,r)=>{if(r??=2147483647,r<2)return 0;for(var n=e,o=(r-=2)<2*t.length?r/2:t.length,s=0;s>>1>>>0]=i,e+=2}return T[e>>>1>>>0]=0,e-n},se=t=>2*t.length,ie=(t,e)=>{for(var r=0,n="";!(r>=e/4);){var o=M[t+4*r>>>2>>>0];if(0==o)break;if(++r,o>=65536){var s=o-65536;n+=String.fromCharCode(55296|s>>10,56320|1023&s)}else n+=String.fromCharCode(o)}return n},ae=(t,e,r)=>{if(e>>>=0,r??=2147483647,r<4)return 0;for(var n=e,o=n+r-4,s=0;s=55296&&i<=57343&&(i=65536+((1023&i)<<10)|1023&t.charCodeAt(++s)),M[e>>>2>>>0]=i,(e+=4)+4>o)break}return M[e>>>2>>>0]=0,e-n},ce=t=>{for(var e=0,r=0;r=55296&&n<=57343&&++r,e+=4}return e},ue=(t,e,r)=>{var n=[],o=t.toWireType(n,r);return n.length&&(O[e>>>2>>>0]=Gt.toHandle(n)),o},le={},he=t=>{var e=le[t];return void 0===e?st(t):e},de=[];Reflect.construct;var fe,pe,me,ve=t=>{var e=(t-b.buffer.byteLength+65535)/65536;try{return b.grow(e),A(),1}catch(t){}},ge=(t,e)=>{t<128?e.push(t):e.push(t%128|128,t>>7)},ye=[],be=(t,e)=>{Dt.set(t,e),jt[t]=Dt.get(t)},Se=(t,e)=>{var r=(t=>(fe||(fe=new WeakMap,((t,e)=>{if(fe)for(var r=0;r<0+e;r++){var n=It(r);n&&fe.set(n,r)}})(0,Dt.length)),fe.get(t)||0))(t);if(r)return r;var n=(()=>{if(ye.length)return ye.pop();try{Dt.grow(1)}catch(t){if(!(t instanceof RangeError))throw t;throw"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."}return Dt.length-1})();try{be(n,t)}catch(r){if(!(r instanceof TypeError))throw r;var o=((t,e)=>{if("function"==typeof WebAssembly.Function)return new WebAssembly.Function((t=>{for(var e={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"},r={parameters:[],results:"v"==t[0]?[]:[e[t[0]]]},n=1;n{var r=t.slice(0,1),n=t.slice(1),o={i:127,p:127,j:126,f:125,d:124,e:111};e.push(96),ge(n.length,e);for(var s=0;s{fe.delete(It(t)),be(t,null),ye.push(t)};J=n.InternalError=class extends Error{constructor(t){super(t),this.name="InternalError"}},(()=>{for(var t=new Array(256),e=0;e<256;++e)t[e]=String.fromCharCode(e);K=t})(),Q=n.BindingError=class extends Error{constructor(t){super(t),this.name="BindingError"}},Object.assign(St.prototype,{isAliasOf(t){if(!(this instanceof St))return!1;if(!(t instanceof St))return!1;var e=this.$$.ptrType.registeredClass,r=this.$$.ptr;t.$$=t.$$;for(var n=t.$$.ptrType.registeredClass,o=t.$$.ptr;e.baseClass;)r=e.upcast(r),e=e.baseClass;for(;n.baseClass;)o=n.upcast(o),n=n.baseClass;return e===n&&r===o},clone(){if(this.$$.ptr||ut(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var t,e=bt(Object.create(Object.getPrototypeOf(this),{$$:{value:(t=this.$$,{count:t.count,deleteScheduled:t.deleteScheduled,preservePointerOnDelete:t.preservePointerOnDelete,ptr:t.ptr,ptrType:t.ptrType,smartPtr:t.smartPtr,smartPtrType:t.smartPtrType})}}));return e.$$.count.value+=1,e.$$.deleteScheduled=!1,e},delete(){this.$$.ptr||ut(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&it("Object already scheduled for deletion"),ht(this),dt(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||ut(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&it("Object already scheduled for deletion"),mt.push(this),1===mt.length&&ct&&ct(vt),this.$$.deleteScheduled=!0,this}}),n.getInheritedInstanceCount=()=>Object.keys(gt).length,n.getLiveInheritedInstances=()=>{var t=[];for(var e in gt)gt.hasOwnProperty(e)&&t.push(gt[e]);return t},n.flushPendingDeletes=vt,n.setDelayFunction=t=>{ct=t,mt.length&&ct&&ct(vt)},Object.assign(_t.prototype,{getPointee(t){return this.rawGetPointee&&(t=this.rawGetPointee(t)),t},destructor(t){this.rawDestructor?.(t)},argPackAdvance:8,readValueFromPointer:Z,fromWireType:function(t){var e=this.getPointee(t);if(!e)return this.destructor(t),null;var r=((t,e)=>(e=((t,e)=>{for(void 0===e&&it("ptr should not be undefined");t.baseClass;)e=t.upcast(e),t=t.baseClass;return e})(t,e),gt[e]))(this.registeredClass,e);if(void 0!==r){if(0===r.$$.count.value)return r.$$.ptr=e,r.$$.smartPtr=t,r.clone();var n=r.clone();return this.destructor(t),n}function o(){return this.isSmartPointer?yt(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:e,smartPtrType:this,smartPtr:t}):yt(this.registeredClass.instancePrototype,{ptrType:this,ptr:t})}var s,i=this.registeredClass.getActualType(e),a=pt[i];if(!a)return o.call(this);s=this.isConst?a.constPointerType:a.pointerType;var c=ft(e,this.registeredClass,s.registeredClass);return null===c?o.call(this):this.isSmartPointer?yt(s.registeredClass.instancePrototype,{ptrType:s,ptr:c,smartPtrType:this,smartPtr:t}):yt(s.registeredClass.instancePrototype,{ptrType:s,ptr:c})}}),At=n.UnboundTypeError=(pe=Error,(me=Ct("UnboundTypeError",(function(t){this.name="UnboundTypeError",this.message=t;var e=new Error(t).stack;void 0!==e&&(this.stack=this.toString()+"\n"+e.replace(/^Error(:[^\n]*)?\n/,""))}))).prototype=Object.create(pe.prototype),me.prototype.constructor=me,me.prototype.toString=function(){return void 0===this.message?this.name:`${this.name}: ${this.message}`},me),zt.push(0,1,void 0,1,null,1,!0,1,!1,1),n.count_emval_handles=()=>zt.length/2-5-Lt.length;var we,Te={r:function(t,e,r){throw e>>>=0,r>>>=0,new G(t>>>=0).init(e,r),t},D:()=>{F("")},s:function(t){var e=X[t>>>=0];delete X[t];var r=e.rawConstructor,n=e.rawDestructor,o=e.fields,s=o.map((t=>t.getterReturnType)).concat(o.map((t=>t.setterArgumentType)));ot([t],s,(t=>{var s={};return o.forEach(((e,r)=>{var n=e.fieldName,i=t[r],a=e.getter,c=e.getterContext,u=t[r+o.length],l=e.setter,h=e.setterContext;s[n]={read:t=>i.fromWireType(a(c,t)),write:(t,e)=>{var r=[];l(h,t,u.toWireType(r,e)),Y(r)}}})),[{name:e.name,fromWireType:t=>{var e={};for(var r in s)e[r]=s[r].read(t);return n(t),e},toWireType:(t,e)=>{for(var o in s)if(!(o in e))throw new TypeError(`Missing field: "${o}"`);var i=r();for(o in s)s[o].write(i,e[o]);return null!==t&&t.push(n,i),i},argPackAdvance:8,readValueFromPointer:Z,destructorFunction:n}]}))},C:function(t,e,r,n,o){},H:function(t,e,r,n){at(t>>>=0,{name:e=st(e>>>=0),fromWireType:function(t){return!!t},toWireType:function(t,e){return e?r:n},argPackAdvance:8,readValueFromPointer:function(t){return this.fromWireType(w[t>>>0])},destructorFunction:null})},o:function(t,e,r,n,o,s,i,a,c,u,l,h,d){t>>>=0,e>>>=0,r>>>=0,n>>>=0,o>>>=0,s>>>=0,i>>>=0,a>>>=0,c>>>=0,u>>>=0,h>>>=0,d>>>=0,l=st(l>>>=0),s=Rt(o,s),a&&=Rt(i,a),u&&=Rt(c,u),d=Rt(h,d);var f=(t=>{if(void 0===t)return"_unknown";var e=(t=t.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return e>=48&&e<=57?`_${t}`:t})(l);Tt(f,(function(){Ft(`Cannot construct ${l} due to unbound types`,[n])})),ot([t,e,r],n?[n]:[],(e=>{var r,o;e=e[0],o=n?(r=e.registeredClass).instancePrototype:St.prototype;var i=Ct(l,(function(...t){if(Object.getPrototypeOf(this)!==c)throw new Q("Use 'new' to construct "+l);if(void 0===h.constructor_body)throw new Q(l+" has no accessible constructor");var e=h.constructor_body[t.length];if(void 0===e)throw new Q(`Tried to invoke ctor of ${l} with invalid number of parameters (${t.length}) - expected (${Object.keys(h.constructor_body).toString()}) parameters instead!`);return e.apply(this,t)})),c=Object.create(o,{constructor:{value:i}});i.prototype=c;var h=new $t(l,i,c,d,r,s,a,u);h.baseClass&&(h.baseClass.__derivedClasses??=[],h.baseClass.__derivedClasses.push(h));var p=new _t(l,h,!0,!1,!1),m=new _t(l+"*",h,!1,!1,!1),v=new _t(l+" const*",h,!1,!0,!1);return pt[t]={pointerType:m,constPointerType:v},Et(f,i),[p,m,v]}))},n:function(t,e,r,n,o,s){t>>>=0,n>>>=0,o>>>=0,s>>>=0;var i=Vt(e,r>>>=0);o=Rt(n,o),ot([],[t],(t=>{var r=`constructor ${(t=t[0]).name}`;if(void 0===t.registeredClass.constructor_body&&(t.registeredClass.constructor_body=[]),void 0!==t.registeredClass.constructor_body[e-1])throw new Q(`Cannot register multiple constructors with identical number of parameters (${e-1}) for class '${t.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return t.registeredClass.constructor_body[e-1]=()=>{Ft(`Cannot construct ${t.name} due to unbound types`,i)},ot([],i,(n=>(n.splice(1,0,null),t.registeredClass.constructor_body[e-1]=Bt(r,n,null,o,s),[]))),[]}))},a:function(t,e,r,n,o,s,i,a,c){t>>>=0,e>>>=0,o>>>=0,s>>>=0,i>>>=0;var u=Vt(r,n>>>=0);e=st(e),e=Ut(e),s=Rt(o,s),ot([],[t],(t=>{var n=`${(t=t[0]).name}.${e}`;function o(){Ft(`Cannot call ${n} due to unbound types`,u)}e.startsWith("@@")&&(e=Symbol[e.substring(2)]),a&&t.registeredClass.pureVirtualFunctions.push(e);var l=t.registeredClass.instancePrototype,h=l[e];return void 0===h||void 0===h.overloadTable&&h.className!==t.name&&h.argCount===r-2?(o.argCount=r-2,o.className=t.name,l[e]=o):(wt(l,e,n),l[e].overloadTable[r-2]=o),ot([],u,(o=>{var a=Bt(n,o,t,s,i,c);return void 0===l[e].overloadTable?(a.argCount=r-2,l[e]=a):l[e].overloadTable[r-2]=a,[]})),[]}))},G:Yt,y:function(t,e,r,n){function o(){}t>>>=0,r>>>=0,e=st(e>>>=0),o.values={},at(t,{name:e,constructor:o,fromWireType:function(t){return this.constructor.values[t]},toWireType:(t,e)=>e.value,argPackAdvance:8,readValueFromPointer:Zt(e,r,n),destructorFunction:null}),Tt(e,o)},h:function(t,e,r){e>>>=0;var n=Jt(t>>>=0,"enum");e=st(e);var o=n.constructor,s=Object.create(n.constructor.prototype,{value:{value:r},constructor:{value:Ct(`${n.name}_${e}`,(function(){}))}});o.values[r]=s,o[e]=s},A:function(t,e,r){r>>>=0,at(t>>>=0,{name:e=st(e>>>=0),fromWireType:t=>t,toWireType:(t,e)=>e,argPackAdvance:8,readValueFromPointer:Qt(e,r),destructorFunction:null})},d:function(t,e,r,n,o,s,i){t>>>=0,n>>>=0,o>>>=0,s>>>=0;var a=Vt(e,r>>>=0);t=st(t),t=Ut(t),o=Rt(n,o),Tt(t,(function(){Ft(`Cannot call ${t} due to unbound types`,a)}),e-1),ot([],a,(r=>{var n=[r[0],null].concat(r.slice(1));return Et(t,Bt(t,n,null,o,s,i),e-1),[]}))},p:function(t,e,r,n,o){t>>>=0,r>>>=0,e=st(e>>>=0),-1===o&&(o=4294967295);var s=t=>t;if(0===n){var i=32-8*r;s=t=>t<>>i}var a=e.includes("unsigned");at(t,{name:e,fromWireType:s,toWireType:a?function(t,e){return this.name,e>>>0}:function(t,e){return this.name,e},argPackAdvance:8,readValueFromPointer:te(e,r,0!==n),destructorFunction:null})},g:function(t,e,r){r>>>=0;var n=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][e];function o(t){var e=O[t>>>2>>>0],r=O[t+4>>>2>>>0];return new n(C.buffer,r,e)}at(t>>>=0,{name:r=st(r),fromWireType:o,argPackAdvance:8,readValueFromPointer:o},{ignoreDuplicateRegistrations:!0})},q:function(t,e){Yt(t>>>=0)},z:function(t,e){t>>>=0;var r="std::string"===(e=st(e>>>=0));at(t,{name:e,fromWireType(t){var e,n,o,s=O[t>>>2>>>0],i=t+4;if(r)for(var a=i,c=0;c<=s;++c){var u=i+c;if(c==s||0==w[u>>>0]){var l=(n=a,o=u-a,(n>>>=0)?((t,e,r)=>{for(var n=(e>>>=0)+r,o=e;t[o]&&!(o>=n);)++o;if(o-e>16&&t.buffer&&ee)return ee.decode(t.subarray(e,o));for(var s="";e>10,56320|1023&u)}}else s+=String.fromCharCode((31&i)<<6|a)}else s+=String.fromCharCode(i)}return s})(w,n,o):"");void 0===e?e=l:(e+=String.fromCharCode(0),e+=l),a=u+1}}else{var h=new Array(s);for(c=0;c>>0]);e=h.join("")}return Oe(t),e},toWireType(t,e){var n;e instanceof ArrayBuffer&&(e=new Uint8Array(e));var o="string"==typeof e;o||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int8Array||it("Cannot pass non-string to std::string"),n=r&&o?(t=>{for(var e=0,r=0;r=55296&&n<=57343?(e+=4,++r):e+=3}return e})(e):e.length;var s=Me(4+n+1),i=s+4;if(O[s>>>2>>>0]=n,r&&o)((t,e,r,n)=>{if(!(n>0))return 0;for(var o=(r>>>=0)+n-1,s=0;s=55296&&i<=57343&&(i=65536+((1023&i)<<10)|1023&t.charCodeAt(++s)),i<=127){if(r>=o)break;e[r++>>>0]=i}else if(i<=2047){if(r+1>=o)break;e[r++>>>0]=192|i>>6,e[r++>>>0]=128|63&i}else if(i<=65535){if(r+2>=o)break;e[r++>>>0]=224|i>>12,e[r++>>>0]=128|i>>6&63,e[r++>>>0]=128|63&i}else{if(r+3>=o)break;e[r++>>>0]=240|i>>18,e[r++>>>0]=128|i>>12&63,e[r++>>>0]=128|i>>6&63,e[r++>>>0]=128|63&i}}e[r>>>0]=0})(e,w,i,n+1);else if(o)for(var a=0;a255&&(Oe(i),it("String has UTF-16 code units that do not fit in 8 bits")),w[i+a>>>0]=c}else for(a=0;a>>0]=e[a];return null!==t&&t.push(Oe,s),s},argPackAdvance:8,readValueFromPointer:Z,destructorFunction(t){Oe(t)}})},x:function(t,e,r){var n,o,s,i;t>>>=0,e>>>=0,r=st(r>>>=0),2===e?(n=ne,o=oe,i=se,s=t=>P[t>>>1>>>0]):4===e&&(n=ie,o=ae,i=ce,s=t=>O[t>>>2>>>0]),at(t,{name:r,fromWireType:t=>{for(var r,o=O[t>>>2>>>0],i=t+4,a=0;a<=o;++a){var c=t+4+a*e;if(a==o||0==s(c)){var u=n(i,c-i);void 0===r?r=u:(r+=String.fromCharCode(0),r+=u),i=c+e}}return Oe(t),r},toWireType:(t,n)=>{"string"!=typeof n&&it(`Cannot pass non-string to C++ string type ${r}`);var s=i(n),a=Me(4+s+e);return O[a>>>2>>>0]=s/e,o(n,a+4,s+e),null!==t&&t.push(Oe,a),a},argPackAdvance:8,readValueFromPointer:Z,destructorFunction(t){Oe(t)}})},t:function(t,e,r,n,o,s){e>>>=0,r>>>=0,n>>>=0,o>>>=0,s>>>=0,X[t>>>=0]={name:st(e),rawConstructor:Rt(r,n),rawDestructor:Rt(o,s),fields:[]}},i:function(t,e,r,n,o,s,i,a,c,u){e>>>=0,r>>>=0,n>>>=0,o>>>=0,s>>>=0,i>>>=0,a>>>=0,c>>>=0,u>>>=0,X[t>>>=0].fields.push({fieldName:st(e),getterReturnType:r,getter:Rt(n,o),getterContext:s,setterArgumentType:i,setter:Rt(a,c),setterContext:u})},I:function(t,e){at(t>>>=0,{isVoid:!0,name:e=st(e>>>=0),argPackAdvance:0,fromWireType:()=>{},toWireType:(t,e)=>{}})},F:function(t,e,r){return t>>>=0,e>>>=0,r>>>=0,w.copyWithin(t>>>0,e>>>0,e+r>>>0)},v:function(t,e,r){return t>>>=0,e>>>=0,r>>>=0,t=Gt.toValue(t),e=Jt(e,"emval::as"),ue(e,r,t)},k:function(t,e,r,n,o){return e>>>=0,r>>>=0,n>>>=0,o>>>=0,(t=de[t>>>=0])(e=Gt.toValue(e),e[r=he(r)],n,o)},b:qt,u:function(t,e){return t>>>=0,e>>>=0,(t=Gt.toValue(t))==Gt.toValue(e)},l:function(t,e,r){var n=((t,e)=>{for(var r=new Array(t),n=0;n>>2>>>0],"parameter "+n);return r})(t,e>>>=0),o=n.shift();t--;var s="return function (obj, func, destructorsRef, args) {\n",i=0,a=[];0===r&&a.push("obj");for(var c=["retType"],u=[o],l=0;lt.name)).join(", ")}) => ${o.name}>`;return h=Ct(p,f),d=de.length,de.push(h),d},f:function(t,e){return t>>>=0,e>>>=0,t=Gt.toValue(t),e=Gt.toValue(e),Gt.toHandle(t[e])},w:function(t){(t>>>=0)>9&&(zt[t+1]+=1)},c:function(t){return t>>>=0,Gt.toHandle(he(t))},B:function(){return Gt.toHandle({})},j:function(t){t>>>=0;var e=Gt.toValue(t);Y(e),qt(t)},m:function(t,e,r){t>>>=0,e>>>=0,r>>>=0,t=Gt.toValue(t),e=Gt.toValue(e),r=Gt.toValue(r),t[e]=r},e:function(t,e){e>>>=0;var r=(t=Jt(t>>>=0,"_emval_take_value")).readValueFromPointer(e);return Gt.toHandle(r)},E:function(t){t>>>=0;var e=w.length,r=4294901760;if(t>r)return!1;for(var n,o=1;o<=4;o*=2){var s=e*(1+.2/o);s=Math.min(s,t+100663296);var i=Math.min(r,(n=Math.max(t,s))+(65536-n%65536)%65536);if(ve(i))return!0}return!1}},$e=function(){var t,e,s,i,a={a:Te};function u(t,e){var r;return $e=function(t){var e,r=t=>e=>t(e)>>>0;return(t=Object.assign({},t)).L=r(t.L),t.N=r(t.N),t._emscripten_stack_alloc=r(t._emscripten_stack_alloc),t.emscripten_stack_get_current=(e=t.emscripten_stack_get_current,()=>e()>>>0),t}($e=t.exports),b=$e.J,A(),Dt=$e.M,r=$e.K,j.unshift(r),function(t){if(k--,n.monitorRunDependencies?.(k),0==k&&(null!==R&&(clearInterval(R),R=null),W)){var e=W;W=null,e()}}(),$e}if(k++,n.monitorRunDependencies?.(k),n.instantiateWasm)try{return n.instantiateWasm(a,u)}catch(t){S(`Module.instantiateWasm callback failed with error: ${t}`),r(t)}return V||(V=function(){if(n.locateFile){var t="manifold.wasm";return N(t)?t:(e=t,n.locateFile?n.locateFile(e,m):m+e)}var e;return new URL(o(644),o.b).href}()),(t=y,e=V,s=a,i=function(t){u(t.instance)},t||"function"!=typeof WebAssembly.instantiateStreaming||N(e)||H(e)||c||"function"!=typeof fetch?U(e,s,i):fetch(e,{credentials:"same-origin"}).then((t=>WebAssembly.instantiateStreaming(t,s).then(i,(function(t){return S(`wasm streaming compile failed: ${t}`),S("falling back to ArrayBuffer instantiation"),U(e,s,i)}))))).catch(r),{}}(),Pe=t=>(Pe=$e.L)(t),Me=t=>(Me=$e.N)(t),Oe=t=>(Oe=$e.O)(t),xe=t=>(xe=$e.P)(t);function _e(){function t(){we||(we=!0,n.calledRun=!0,D||(L(j),e(n),n.onRuntimeInitialized&&n.onRuntimeInitialized(),function(){if(n.postRun)for("function"==typeof n.postRun&&(n.postRun=[n.postRun]);n.postRun.length;)t=n.postRun.shift(),I.unshift(t);var t;L(I)}()))}k>0||(function(){if(n.preRun)for("function"==typeof n.preRun&&(n.preRun=[n.preRun]);n.preRun.length;)t=n.preRun.shift(),E.unshift(t);var t;L(E)}(),k>0||(n.setStatus?(n.setStatus("Running..."),setTimeout((function(){setTimeout((function(){n.setStatus("")}),1),t()}),1)):t()))}if(n.addFunction=Se,n.removeFunction=Ce,W=function t(){we||_e(),we||(W=t)},n.preInit)for("function"==typeof n.preInit&&(n.preInit=[n.preInit]);n.preInit.length>0;)n.preInit.pop()();return _e(),s});const M=P;(async()=>{const t=await M({locateFile:()=>"https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.19.0-alpha.0.2/wasm/manifold.cc2ddd38.wasm"});var e;t.setup(),e=t,w=new n,C=new S(e),postMessage("manifold-initialised"),postMessage("manifold-initialised")})(),addEventListener("message",(({data:t})=>{((t,e)=>{let r;e("busy");try{if("manifoldToMesh"!==t.action.functionName&&"manifoldsToMeshes"!==t.action.functionName&&"deleteManifoldOrCrossSection"!==t.action.functionName&&"deleteManifoldsOrCrossSections"!==t.action.functionName&&"manifoldToMeshPointer"!==t.action.functionName&&"startedTheRun"!==t.action.functionName&&"cleanAllCache"!==t.action.functionName&&"addManifoldPluginDependency"!==t.action.functionName){Object.keys(t.action.inputs).forEach((e=>{const r=t.action.inputs[e];r&&r.type&&"manifold-shape"===r.type&&r.hash&&(t.action.inputs[e]=w.checkCache(t.action.inputs[e].hash)),r&&Array.isArray(r)&&r.length>0&&(r[0].type&&"manifold-shape"===r[0].type&&r[0].hash?t.action.inputs[e]=t.action.inputs[e].map((t=>w.checkCache(t.hash))):Array.isArray(r[0])&&r[0][0].type&&"manifold-shape"===r[0][0].type&&r[0][0].hash&&(t.action.inputs[e]=t.action.inputs[e].map((t=>t.map((t=>w.checkCache(t.hash)))))))}));const e=t.action.functionName.split(".");let n;if(n=3===e.length?w.cacheOp(t.action,(()=>C[e[0]][e[1]][e[2]](t.action.inputs))):2===e.length?w.cacheOp(t.action,(()=>C[e[0]][e[1]](t.action.inputs))):w.cacheOp(t.action,(()=>C[t.action.functionName](t.action.inputs))),w.isManifoldObject(n))r=Array.isArray(n)?n.map((t=>({hash:t.hash,type:"manifold-shape"}))):{hash:n.hash,type:"manifold-shape"};else if(n&&n.compound&&n.data&&n.manifolds&&n.manifolds.length>0){const t=n;t.manifolds=t.manifolds.map((t=>({id:t.id,manifold:{hash:t.manifold.hash,type:"manifold-shape"}}))),t.compound={hash:t.compound.hash,type:"manifold-shape"},r=t}else r=n}if("addManifoldPluginDependency"===t.action.functionName&&(C&&C.plugins?Object.keys(t.action.inputs).forEach((e=>{C.plugins.dependencies[e]=t.action.inputs[e]})):T=t.action.inputs),"manifoldToMesh"===t.action.functionName&&(t.action.inputs.manifold=w.checkCache(t.action.inputs.manifold.hash),r=C.decomposeManifoldOrCrossSection(t.action.inputs)),"manifoldToMeshPointer"===t.action.functionName){t.action.inputs.manifold=w.checkCache(t.action.inputs.manifold.hash);const e=C.manifold.manifoldToMesh(t.action.inputs),n=w.computeHash(t.action);w.addToCache(n,e),r={hash:n,type:"manifold-shape"}}if("manifoldsToMeshes"===t.action.functionName){if(!(t.action.inputs.manifolds&&t.action.inputs.manifolds.length>0))throw new Error("No manifolds detected");t.action.inputs.manifolds=t.action.inputs.manifolds.map((t=>w.checkCache(t.hash))),r=C.decomposeManifoldsOrCrossSections(t.action.inputs)}"deleteManifoldOrCrossSection"===t.action.functionName&&(w.cleanCacheForHash(t.action.inputs.manifoldOrCrossSection.hash),r={}),"deleteManifoldsOrCrossSections"===t.action.functionName&&(t.action.inputs.manifoldsOrCrossSections.forEach((t=>w.cleanCacheForHash(t.hash))),r={}),"startedTheRun"===t.action.functionName&&(w&&Object.keys(w.usedHashes).length>1e4&&w.cleanAllCache(),r={}),"cleanAllCache"===t.action.functionName&&(w.cleanAllCache(),r={}),e({uid:t.uid,result:r})}catch(r){let n,o;t&&t.action&&t.action.inputs&&(n=`Input values were: {${Object.keys(t.action.inputs).map((e=>`${e}: ${JSON.stringify(t.action.inputs[e])}`)).join(",")}}. `),t&&t.action&&t.action.functionName&&(o=`- ${t.action.functionName}`),e({uid:t.uid,result:void 0,error:`Manifold computation failed. ${r} While executing function ${o}. ${n}`})}})(t,postMessage)}))})()})(); \ No newline at end of file